Search Results

Search found 2166 results on 87 pages for 'obj'.

Page 9/87 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Java synchronized seems ignored

    - by viraptor
    Hi, I've got the following code, which I expected to deadlock after printing out "Main: pre-sync". But it looks like synchronized doesn't do what I expect it to. What happens here? import java.util.*; public class deadtest { public static class waiter implements Runnable { Object obj; public waiter(Object obj) { this.obj = obj; } public void run() { System.err.println("Thead: pre-sync"); synchronized(obj) { System.err.println("Thead: pre-wait"); try { obj.wait(); } catch (Exception e) { } System.err.println("Thead: post-wait"); } System.err.println("Thead: post-sync"); } } public static void main(String args[]) { Object obj = new Object(); System.err.println("Main: pre-spawn"); Thread waiterThread = new Thread(new waiter(obj)); waiterThread.start(); try { Thread.sleep(1000); } catch (Exception e) { } System.err.println("Main: pre-sync"); synchronized(obj) { System.err.println("Main: pre-notify"); obj.notify(); System.err.println("Main: post-notify"); } System.err.println("Main: post-sync"); try { waiterThread.join(); } catch (Exception e) { } } } Since both threads synchronize on the created object, I expected the threads to actually block each other. Currently, the code happily notifies the other thread, joins and exits.

    Read the article

  • What is the best practice for ouputting data from a collection on an ASP.net Page?

    - by bshacklett
    I've ported a page from classic ASP to ASP.net. Part of what happens in this page is that a collection of custom types is generated and then displayed via Response.Write() commands. I'd like to get the business logic separated out into a code behind file (and maybe move this all into a user control), but I can't seem to figure out how I'd actually display the collection once it's been generated. I want to specify a master page here, too, so the code can't stay inline. Here's a very stripped down version of the current code: <% Dim objs as ArrayList = New ArrayList() For i = 0 To 2 Dim obj as Obj = New Obj() obj.setProp1("ASDF") obj.setProp2("FDSA") objs.Add(obj) Next i %> <table> <thead> <tr> <th scope="col">Property 1</th> <th scope="col">Property 2</th> </tr> </thead> <tbody> <% For Each obj As Obj In objs Dim objProp1 As String = obj.getProp1 Dim objProp2 As String = obj.getProp2 %> <tr> <td><% Response.Write(objProp1)%></td> <td><% Response.Write(objProp2)%></td> </tr> <% Next %> </tbody> </table> What is the ".net" way of doing this?

    Read the article

  • overload Equals, is this wrong?

    - by Zka
    Reading some piece of code and I keep seeing this : public override bool Equals (object obj) { if (obj == null || this.GetType ().Equals (obj.GetType())) return false; //compare code... } Shouldn't it be like this (note the !): public override bool Equals (object obj) { if (obj == null || !this.GetType ().Equals (obj.GetType())) return false; //compare code... } Or does the equals perform differently in this case?

    Read the article

  • Skip makefile dependency generation for certain targets (e.g. `clean`)

    - by Shtééf
    I have several C and C++ projects that all follow a basic structure I've been using for a while now. My source files go in src/*.c, intermediate files in obj/*.[do], and the actual executable in the top level directory. My makefiles follow roughly this template: # The final executable TARGET := something # Source files (without src/) INPUTS := foo.c bar.c baz.c # OBJECTS will contain: obj/foo.o obj/bar.o obj/baz.o OBJECTS := $(INPUTS:%.cpp=obj/%.o) # DEPFILES will contain: obj/foo.d obj/bar.d obj/baz.d DEPFILES := $(OBJECTS:%.o=%.d) all: $(TARGET) obj/%.o: src/%.cpp $(CC) $(CFLAGS) -c -o $@ $< obj/%.d: src/%.cpp $(CC) $(CFLAGS) -M -MF $@ -MT $(@:%.d=%.o) $< $(TARGET): $(OBJECTS) $(LD) $(LDFLAGS) -o $@ $(OBJECTS) .PHONY: clean clean: -rm -f $(OBJECTS) $(DEPFILES) $(RPOFILES) $(TARGET) -include $(DEPFILES) Now I'm at the point where I'm packaging this for a Debian system. I'm using debuild to build the Debian source package, and pbuilder to build the binary package. The debuild step only has to execute the clean target, but even this causes the dependency files to be generated and included. In short, my question is really: Can I somehow prevent make from generating dependencies when all I want is to run the clean target?

    Read the article

  • C++0x Overload on reference, versus sole pass-by-value + std::move?

    - by dean
    It seems the main advice concerning C++0x's rvalues is to add move constructors and move operators to your classes, until compilers default-implement them. But waiting is a losing strategy if you use VC10, because automatic generation probably won't be here until VC10 SP1, or in worst case, VC11. Likely, the wait for this will be measured in years. Here lies my problem. Writing all this duplicate code is not fun. And it's unpleasant to look at. But this is a burden well received, for those classes deemed slow. Not so for the hundreds, if not thousands, of smaller classes. ::sighs:: C++0x was supposed to let me write less code, not more! And then I had a thought. Shared by many, I would guess. Why not just pass everything by value? Won't std::move + copy elision make this nearly optimal? Example 1 - Typical Pre-0x constructor OurClass::OurClass(const SomeClass& obj) : obj(obj) {} SomeClass o; OurClass(o); // single copy OurClass(std::move(o)); // single copy OurClass(SomeClass()); // single copy Cons: A wasted copy for rvalues. Example 2 - Recommended C++0x? OurClass::OurClass(const SomeClass& obj) : obj(obj) {} OurClass::OurClass(SomeClass&& obj) : obj(std::move(obj)) {} SomeClass o; OurClass(o); // single copy OurClass(std::move(o)); // zero copies, one move OurClass(SomeClass()); // zero copies, one move Pros: Presumably the fastest. Cons: Lots of code! Example 3 - Pass-by-value + std::move OurClass::OurClass(SomeClass obj) : obj(std::move(obj)) {} SomeClass o; OurClass(o); // single copy, one move OurClass(std::move(o)); // zero copies, two moves OurClass(SomeClass()); // zero copies, one move Pros: No additional code. Cons: A wasted move in cases 1 & 2. Performance will suffer greatly if SomeClass has no move constructor. What do you think? Is this correct? Is the incurred move a generally acceptable loss when compared to the benefit of code reduction?

    Read the article

  • Is this a good decorator pattern for javascript?

    - by Kucebe
    I need some simple objects that could become more complex later, with many different properties, so i thought to decorator pattern. I made this looking at Crockford's power constructor and object augmentation: //add property to object Object.prototype.addProperty = function(name, func){ for(propertyName in this){ if(propertyName == name){ throw new Error(propertyName + " is already defined"); } } this[name] = func; }; //constructor of base object var BaseConstructor = function(param){ var _privateVar = param; return{ getPrivateVar: function(){ return _privateVar; } }; }; //a simple decorator, adds one private attribute and one privileged method var simpleDecorator = function(obj, param){ var _privateVar = param; var privilegedMethod1 = function(){ return "privateVar of decorator is: " + _privateVar; }; obj.addProperty("privilegedMethod1", privilegedMethod1); return obj; } //a more complex decorator, adds public and private properties var complexDecorator = function(obj, param1, param2){ //private properties var _privateVar = param1; var _privateMethod = function(x){ for(var i=0; i<x; i++){ _privateVar += x; } return _privateVar; }; //public properties var publicVar = "I'm public"; obj.addProperty("publicVar", publicVar); var privilegedMethod2 = function(){ return _privateMethod(param2); }; obj.addProperty("privilegedMethod2", privilegedMethod2); var publicMethod = function(){ var temp = this.privilegedMethod2(); return "do something: " + temp + " - publicVar is: " + this.publicVar; }; obj.addProperty("publicMethod", publicMethod); return obj; } //new basic object var myObj = BaseConstructor("obj1"); //the basic object will be decorated var myObj = simpleDecorator(obj, "aParam"); //the basic object will be decorated with other properties var myObj = complexDecorator(obj, 2, 3); Is this a good way to have Decorator Pattern in javascript? Are there other better ways to do this?

    Read the article

  • In Javascript, is it true that function aliasing works as long as the function being aliased doesn't

    - by Jian Lin
    In Javascript, if we are aliasing a function, such as in: f = g; f = obj.display; obj.f = foo; all the 3 lines above, they will work as long as the function / method on the right hand side doesn't touch this? Since we are passing in all the arguments, the only way it can mess up is when the function / method on the right uses this? Actually, line 1 is probably ok if g is also a property of window? If g is referencing obj.display, then the same problem is there. In line 2, when obj.display touches this, it is to mean the obj, but when f() is invoked, the this is window, so they are different. In line 3, it is the same: when f() is invoked inside of obj's code, then the this is obj, while foo might be using this to refer to window if it were a property of window. (global function). So line 2 can be written as f = function() { obj.display.apply(obj, arguments) } and line 3: obj.f = function() { foo.apply(window, arguments) } Is this the correct method, and are there there other methods besides this?

    Read the article

  • Iterate over a dict or list in Python

    - by Chris Dutrow
    Just wrote some nasty code that iterates over a dict or a list in Python. I have a feeling this was not the best way to go about it. The problem is that in order to iterate over a dict, this is the convention: for key in dict_object: dict_object[key] = 1 But modifying the object properties by key does not work if the same thing is done on a list: # Throws an error because the value of key is the property value, not # the list index: for key in list_object: list_object[key] = 1 The way I solved this problem was to write this nasty code: if isinstance(obj, dict): for key in obj: do_loop_contents(obj, key) elif isinstance(obj, list): for i in xrange(0, len(obj)): do_loop_contents(obj, i) def do_loop_contents(obj, key): obj[key] = 1 Is there a better way to do this? Thanks!

    Read the article

  • Cant insert a object into a silverlight databound combo box

    - by Steve
    Hi Until recently I had a combo box that was bound to a Linq queried IEnumerable of a DataService.Obj type in the bind method, and all worked fine private IEnumerable<DataService.Obj> _GeneralList; private IEnumerable<DataService.Obj> _QueriedList; private void Bind() { _GeneralList = SharedLists.GeneralList; _QueriedList = _GeneralList.Where(q =>q.ID >1000); cmbobox.ItemsSource = _QueriedList; } Then I had to change the method to insert a new obj and set that object as the default obj and now I get a "System.NullReferenceException: Object reference not set to an instance of an object" exception. I know this has to do with inserting into a linq queried ienumerable but I cant fix it. Any help will be gratefully received. private IEnumerable<DataService.Obj> _GeneralList; private IEnumerable<DataService.Obj> _QueriedList; private void Bind() { _GeneralList = SharedLists.GeneralList; _QueriedList = _GeneralList.Where(q =>q.ID >1000); cmbobox.ItemsSource = _QueriedList; DataService.Obj info = new DataService.Obj(); info.ID = "0"; (cmbobox.ItemsSource as ObservableCollection<DataService.Obj>).Insert(0,info); cmbobox.SelectedIndex = 0; } Thanks in advance

    Read the article

  • new operator overwriting an existing object

    - by dvpdiner2
    I have a custom FastStack class, implemented as a fixed size array and an index into that array. In my copy constructor, I allocate the array and then assign each object from the copy's array into the new array. There's some refcounting in the objects on the stack, hence assignment is used rather than a simple copy. The problem is that when allocating the array, it sometimes overwrites part of the other stack's array. As can be expected, this leads to eventual segmentation faults when that data is dereferenced. class FastStack { private: int m_size, m_ptr; ObjectRef* m_stack; public: FastStack(int size) : m_size(size), m_ptr(-1) { m_stack = new ObjectRef[m_size]; } FastStack(const FastStack& copy) : m_size(copy.m_size), m_ptr(copy.m_ptr) { long a = (long)copy.m_stack[0]; m_stack = new ObjectRef[m_size]; if ((long)copy.m_stack[0] != a) fprintf(stderr, "\nWe have a serious problem!\n\n"); for (int i = 0; i <= m_ptr; i++) m_stack[i] = copy.m_stack[i]; } ~FastStack() { delete[] m_stack; } }; class ObjectRef { private: DataObj* m_obj; public: ObjectRef() : m_obj(0) { } ObjectRef(DataObj* obj) : m_obj(obj) { if (m_obj) m_obj->addRef(); } ObjectRef(const ObjectRef& obj) : m_obj(obj.m_obj) { if (m_obj) m_obj->addRef(); } ~ObjectRef() { if (m_obj) m_obj->delRef(); } ObjectRef& operator=(DataObj* obj) { if (obj) obj->addRef(); if (m_obj) m_obj->delRef(); m_obj = obj; return *this; } ObjectRef& operator=(const ObjectRef& obj) { if (obj.m_obj) obj.m_obj->addRef(); if (m_obj) m_obj->delRef(); m_obj = obj.m_obj; return *this; } }; I see that "We have a serious problem!" line shortly before a segfault, and stepping through it with gdb I can see that one of the ObjectRefs created by new has the same address as the other stack's array. My first instinct is to say that new should never be allocating memory that is already in use, but that clearly seems to be the case here and I am at a complete loss as to what can be done. Added: At the time that I see this happen, m_size = 2 and m_ptr = 0.

    Read the article

  • Why does my player stop when stepping onto a new tile?

    - by user220631
    Me and my friend are creating a game from scratch. He is in charge of art design and I am in charge of coding. I have done well so far with the code, but I have a collision detection problem when the character moves right: Once the player moves right, whenever a new block is encountered, the player stops. I don't know if this is a problem with collision or the player but I can't work around it. Here is the collision code: this.IsColliding = function(obj) { if(this.X > obj.X + obj.Width) return false; else if(this.X + this.Width < obj.X) return false; else if(this.Y > obj.Y + obj.Height) return false; else if(this.Y + this.Height < obj.Y) return false; else return true; } I also wanted to see if there as a way to make the player collide with the bottom of the block and the right side of the block instead of running through it.

    Read the article

  • How do I call an Obj-C method from Javascript?

    - by gnfti
    Hi all, I'm developing a native iPhone app using Phonegap, so everything is done in HTML and JS. I am using the Flurry SDK for analytics and want to use the [FlurryAPI logEvent:@"EVENT_NAME"]; method to track events. Is there a way to do this in Javascript? So when tracking a link I would imagine using something like <a onClick="flurryTrackEvent("Click_Rainbows")" href="#Rainbows">Rainbows</a> <a onClick="flurryTrackEvent("Click_Unicorns")" href="#Unicorns">Unicorns</a> "FlurryAPI.h" has the following: @interface FlurryAPI : NSObject { } + (void)startSession:(NSString *)apiKey; + (void)logEvent:(NSString *)eventName; + (void)logEvent:(NSString *)eventName withParameters:(NSDictionary *)parameters; + (void)logError:(NSString *)errorID message:(NSString *)message exception:(NSException *)exception; + (void)setUserID:(NSString *)userID; + (void)setEventLoggingEnabled:(BOOL)value; + (void)setServerURL:(NSString *)url; + (void)setSessionReportsOnCloseEnabled:(BOOL)sendSessionReportsOnClose; @end I'm only interested in the logEvent method(s). If it's not clear by now, I'm comfortable with JS but a recovering Obj-C noob. I've read the Apple docs but the examples described there are all for newly declared methods and I imagine this could be simpler to implement because the Obj-C method(s) are already defined. Thank you in advance for any input.

    Read the article

  • C++ linker unresolved external symbol (again;) from other source file *.obj file. (VC++ express)

    - by bua
    Hi there, I'm back to C/C++ after some break. I've a following problem: I've a solution where I've several projects (compilable and linkable). Now I need to add another project to this solution which depends on some sources from other projects. My new project compiles without any problems (I've added "existing sources" to my project). the error: 1>Linking... 1>LicenceManager.obj : error LNK2019: unresolved external symbol "int __cdecl saveLic(char *,struct Auth *)" (?saveLic@@YAHPADPAUAuth@@@Z) referenced in function "public: void __thiscall LicenceManager::generateLicence(int,char *)" (?generateLicence@LicenceManager@@QAEXHPAD@Z) 1>LicenceManager.obj : error LNK2019: unresolved external symbol "void __cdecl getSysInfo(struct Auth *)" (?getSysInfo@@YAXPAUAuth@@@Z) referenced in function "public: void __thiscall LicenceManager::generateLicence(int,char *)" (?generateLicence@LicenceManager@@QAEXHPAD@Z) Functions saveLic, and getSysInfo are defined in files which I've added to my new project from existing ones. There is object file created during compilation with those functions in target dir, but my LicenceManager class doesn't want to link. I use some extern "C" , and #pragma pack somewhere, but no more fancy stuff. I think every directory, lib and other necessary dependencies are visible in settings for this project. Thanks for any advice.

    Read the article

  • Opengl-es picking object

    - by lacas
    I saw a lot of picking code opengl-es, but nothing worked. Can someone give me what am I missing? My code is (from tutorials/forums) Vec3 far = Camera.getPosition(); Vec3 near = Shared.opengl().getPickingRay(ev.getX(), ev.getY(), 0); Vec3 direction = far.sub(near); direction.normalize(); Log.e("direction", direction.x+" "+direction.y+" "+direction.z); Ray mouseRay = new Ray(near, direction); for (int n=0; n<ObjectFactory.objects.size(); n++) { if (ObjectFactory.objects.get(n)!=null) { IObject obj = ObjectFactory.objects.get(n); float discriminant, b; float radius=0.1f; b = -mouseRay.getOrigin().dot(mouseRay.getDirection()); discriminant = b * b - mouseRay.getOrigin().dot(mouseRay.getOrigin()) + radius*radius; discriminant = FloatMath.sqrt(discriminant); double x1 = b - discriminant; double x2 = b + discriminant; Log.e("asd", obj.getName() + " "+discriminant+" "+x1+" "+x2); } } my camera vectors: //cam Vec3 position =new Vec3(-obj.getPosX()+x, obj.getPosZ()-0.3f, obj.getPosY()+z); Vec3 direction =new Vec3(-obj.getPosX(), obj.getPosZ(), obj.getPosY()); Vec3 up =new Vec3(0.0f, -1.0f, 0.0f); Camera.set(position, direction, up); and my picking code: public Vec3 getPickingRay(float mouseX, float mouseY, float mouseZ) { int[] viewport = getViewport(); float[] modelview = getModelView(); float[] projection = getProjection(); float winX, winY; float[] position = new float[4]; winX = (float)mouseX; winY = (float)Shared.screen.width - (float)mouseY; GLU.gluUnProject(winX, winY, mouseZ, modelview, 0, projection, 0, viewport, 0, position, 0); return new Vec3(position[0], position[1], position[2]); } My camera moving all the time in 3d space. and my actors/modells moving too. my camera is following one actor/modell and the user can move the camera on a circle on this model. How can I change the above code to working?

    Read the article

  • Creating classed in JavaScript

    - by Renso
    Goal:Creating class instances in JavaScript is not available since you define "classes" in js with object literals. In order to create classical classes like you would in c#, ruby, java, etc, with inheritance and instances.Rather than typical class definitions using object literals, js has a constructor function and the NEW operator that will allow you to new-up a class and optionally provide initial properties to initialize the new object with.The new operator changes the function's context and behavior of the return statement.var Person = function(name) {   this.name = name;};   //Init the personvar dude= new Person("renso");//Validate the instanceassert(dude instanceof Person);When a constructor function is called with the new keyword, the context changes from global window to a new and empty context specific to the instance; "this" will refer in this case to the "dude" context.Here is class pattern that you will need to define your own CLASS emulation library:var Class = function() {   var _class = function() {      this.init.apply(this, arguments);   };   _class.prototype.init = function(){};   return _class;}var Person a new Class();Person.prototype.init = function() {};var person = new Person;In order for the class emulator to support adding functions and properties to static classes as well as object instances of People, change the emulator:var Class = function() {   var _class = function() {      this.init.apply(this, arguments);   };   _class.prototype.init = function(){};   _class.fn = _class.prototype;   _class.fn.parent = _class;   //adding class properties   _class.extend = function(obj) {      var extended = obj.extended;      for(var i in obj) {         _class[i] = obj[i];      };      if(extended) extended(_class);   };   //adding new instances   _class.include = function(obj) {      var included = obj.included;      for(var i in obj) {         _class.fn[i] = obj[i];      };      if(included) included(_class);   };   return _class;}Now you can use it to create and extend your own object instances://adding static functions to the class Personvar Person = new Class();Person.extend({   find: function(name) {/*....*/},      delete: function(id) {/*....*/},});//calling static function findvar person = Person.find('renso');   //adding properties and functions to the class' prototype so that they are available on instances of the class Personvar Person = new Class;Person.extend({   save: function(name) {/*....*/},   delete: function(id) {/*....*/}});var dude = new Person;//calling instance functiondude.save('renso');

    Read the article

  • JPA behaviour...

    - by Marcel
    Hi I have some trouble understanding a JPA behaviour. Mabye someone could give me a hint. Situation: Product entity: @Entity public class Product implements Serializable { ... @OneToMany(mappedBy="product", fetch=FetchType.EAGER) private List<ProductResource> productResources = new ArrayList<ProductResource>(); .... public List<ProductResource> getProductResources() { return productResources; } public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; if (!(obj instanceof Product)) return false; Product p = (Product) obj; return p.productId == productId; } } Resource entity: @Entity public class Resource implements Serializable { ... @OneToMany(mappedBy="resource", fetch=FetchType.EAGER) private List<ProductResource> productResources = new ArrayList<ProductResource>(); ... public void setProductResource(List<ProductResource> productResource) { this.productResources = productResource; } public List<ProductResource> getProductResources() { return productResources; } public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; if (!(obj instanceof Resource)) return false; Resource r = (Resource) obj; return (long)resourceId==(long)r.resourceId; } } ProductResource Entity: This is a JoinTable (association class) with additional properties (amount). It maps Product and Resources. @Entity public class ProductResource implements Serializable { ... @JoinColumn(nullable=false, updatable=false) @ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST) private Product product; @JoinColumn(nullable=false, updatable=false) @ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST) private Resource resource; private int amount; public void setProduct(Product product) { this.product = product; if(!product.getProductResources().contains((this))){ product.getProductResources().add(this); } } public Product getProduct() { return product; } public void setResource(Resource resource) { this.resource = resource; if(!resource.getProductResources().contains((this))){ resource.getProductResources().add(this); } } public Resource getResource() { return resource; } ... public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; if (!(obj instanceof ProductResource)) return false; ProductResource pr = (ProductResource) obj; return (long)pr.productResourceId == (long)productResourceId; } } This is the Session Bean (running on glassfish). @Stateless(mappedName="PersistenceManager") public class PersistenceManagerBean implements PersistenceManager { @PersistenceContext(unitName = "local_mysql") private EntityManager em; public Object create(Object entity) { em.persist(entity); return entity; } public void delete(Object entity) { em.remove(em.merge(entity)); } public Object retrieve(Class entityClass, Long id) { Object entity = em.find(entityClass, id); return entity; } public void update(Object entity) { em.merge(entity); } } I call the session Bean from a java client: public class Start { public static void main(String[] args) throws NamingException { PersistenceManager pm = (PersistenceManager) new InitialContext().lookup("java:global/BackITServer/PersistenceManagerBean"); ProductResource pr = new ProductResource(); Product p = new Product(); Resource r = new Resource(); pr.setProduct(p); pr.setResource(r); ProductResource pr_stored = (ProductResource) pm.create(pr); pm.delete(pr_stored); Product p_ret = (Product) pm.retrieve(Product.class, pr_stored.getProduct().getProductId()); // prints out true ???????????????????????????????????? System.out.println(p_ret.getProductResources().contains(pr_stored)); } } So here comes my problem. Why is the ProductResource entity still in the List productResources(see code above). The productResource tuple in the db is gone after the deletion and I do newly retrieve the Product entity. If I understood right every method call of the client happens in a new persistence context, but here i obviously get back the non-refreshed product object!? Any help is appreciated Thanks Marcel

    Read the article

  • Javascript game with css position

    - by newb125505
    I am trying to make a very simple helicopter game in javascript and I'm currently using css positions to move the objects. but I wanted to know if there was a better/other method for moving objects (divs) when a user is pressing a button here's a code i've got so far.. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Game 2 helicopter</title> <script type="text/javascript"> function num(x){ return parseInt(x.replace(/([^0-9]+)/g,'')); } function getPos(x, y){ var inum=Math.floor(Math.random()*(y+1-x)) + x; inum=inum; return inum; } function setTop(x,y){ x.style.top = y+'px'; } function setBot(x,y){ x.style.bottom = y+'px'; } function setLeft(x,y){ x.style.left = y+'px'; } function setRight(x,y){ x.style.right = y+'px'; } function getTop(x){ return num(x.style.top); } function getBot(x){ return num(x.style.bottom); } function getLeft(x){ return num(x.style.left); } function getRight(x){ return num(x.style.right); } function moveLeft(x,y){ var heli = document.getElementById('heli'); var obj = document.getElementById('obj'); var poss = [20,120,350,400]; var r_pos = getPos(1,4); var rand_pos = poss[r_pos]; xleft = getLeft(x)-y; if(xleft>0){ xleft=xleft; } else{ xleft=800; setTop(x,rand_pos); } setLeft(x,xleft); setTimeout(function(){moveLeft(x,y)},10); checkGame(heli,obj); } var heli; var obj; function checkGame(x,y){ var obj_right = getLeft(x) + 100; var yt = getTop(y); var yb = (getTop(y)+100); if(getTop(x) >= yt && getTop(x) <= yb && obj_right==getLeft(y)){ endGame(); } } function func(){ var x = document.getElementById('heli'); var y = document.getElementById('obj'); alert(getTop(x)+' '+getTop(y)+' '+(getTop(y)+200)); } function startGame(e){ document.getElementById('park').style.display='block'; document.getElementById('newgame').style.display='none'; heli = document.getElementById('heli'); obj = document.getElementById('obj'); hp = heli.style.top; op = obj.style.top; setTop(heli,20); setLeft(heli,20); setLeft(obj,800); setTop(obj,20); moveLeft(obj,5); } function newGameLoad(){ document.getElementById('park').style.display='none'; document.getElementById('newgame').style.display='block'; } function gamePos(e){ heli = document.getElementById('heli'); obj = document.getElementById('obj'); var keynum; var keychar; var numcheck; if(window.event){ // IE keynum = e.keyCode; } else if(e.which){ // Netscape/Firefox/Opera keynum = e.which; } keychar = String.fromCharCode(keynum); // up=38 down=40 left=37 right=39 /*if(keynum==37){ //left tl=tl-20; db.style.left = tl + 'px'; } if(keynum==39){ //right //stopPos(); tl=tl+20; db.style.left = tl + 'px'; }*/ curb = getTop(heli); if(keynum==38){ //top setTop(heli,curb-10); //alert(curb+10); } if(keynum==40){ //bottom setTop(heli,curb+10); //alert(curb-10); } } function endGame(){ clearTimeout(); newGameLoad(); } </script> <style type="text/css"> .play{position:absolute;color:#fff;} #heli{background:url(http://classroomclipart.com/images/gallery/Clipart/Transportation/Helicopter/TN_00-helicopter2.jpg);width:150px;height:59px;} #obj{background:red;width:20px;height:200px;} .park{height:550px;border:5px solid brown;border-left:none;border-right:none;} #newgame{display:none;} </style> </head> <body onload="startGame();" onkeydown="gamePos(event);"> <div class="park" id="park"> <div id="heli" class="play"></div> <div id="obj" class="play"></div> </div> <input type="button" id="newgame" style="position:absolute;top:25%;left:25%;" onclick="startGame();" value="New Game" /> </body> </html>

    Read the article

  • Difficulties getting GraphViz working as a library in C++

    - by DistortedLojik
    Am working on a program that will allow a graph of nodes to be displayed and then updated visually as the nodes themselves are updated. I am fairly new to Visual Studio 2010 and am following the GraphViz guide located at http://www.graphviz.org/pdf/libguide.pdf in order to get GraphViz working as a library. I have the following code which is taken straight from the pdf linked above. #include <graphviz\gvc.h> #include <graphviz\cdt.h> #include <graphviz\graph.h> #include <graphviz\pathplan.h> using namespace std; int main(int argc, char **argv) { Agraph_t *g; Agnode_t *n, *m; Agedge_t *e; Agsym_t *a; GVC_t *gvc; /* set up a graphviz context */ gvc = gvContext(); /* parse command line args - minimally argv[0] sets layout engine */ gvParseArgs(gvc, argc, argv); /* Create a simple digraph */ g = agopen("g", AGDIGRAPH); n = agnode(g, "n"); m = agnode(g, "m"); e = agedge(g, n, m); /* Set an attribute - in this case one that affects the visible rendering */ agsafeset(n, "color", "red", ""); /* Compute a layout using layout engine from command line args */ gvLayoutJobs(gvc, g); /* Write the graph according to -T and -o options */ gvRenderJobs(gvc, g); /* Free layout data */ gvFreeLayout(gvc, g); /* Free graph structures */ agclose(g); /* close output file, free context, and return number of errors */ return (gvFreeContext(gvc)); } After compiling I get the following errors which indicate that I do not have it correctly linked. 1>main.obj : error LNK2019: unresolved external symbol _gvFreeContext referenced in function _main 1>main.obj : error LNK2019: unresolved external symbol _agclose referenced in function _main 1>main.obj : error LNK2019: unresolved external symbol _gvFreeLayout referenced in function _main 1>main.obj : error LNK2019: unresolved external symbol _gvRenderJobs referenced in function _main 1>main.obj : error LNK2019: unresolved external symbol _gvLayoutJobs referenced in function _main 1>main.obj : error LNK2019: unresolved external symbol _agsafeset referenced in function _main 1>main.obj : error LNK2019: unresolved external symbol _agedge referenced in function _main 1>main.obj : error LNK2019: unresolved external symbol _agnode referenced in function _main 1>main.obj : error LNK2019: unresolved external symbol _agopen referenced in function _main 1>main.obj : error LNK2019: unresolved external symbol _gvParseArgs referenced in function _main 1>main.obj : error LNK2019: unresolved external symbol _gvContext referenced in function _main Within the VC++ Directories I have C:\Program Files (x86)\Graphviz2.26.3\include in the Include Directories and C:\Program Files (x86)\Graphviz2.26.3\lib\release\lib in the Library Directories Any help would be greatly appreciated to help get this working. Thank you.

    Read the article

  • How to create constant NSString by concatenating strings in Obj-C ?

    - by eric-morand
    Hi guys, I'm trying to instanciate a constant NSString by concatanating other NSString instances. Here is what I'm doing in my implementation file : static NSString *const MY_CONST = @"TEST"; static NSString *const MY_CONCATENATE_CONST = [NSString stringWithFormat:@"STRING %@", MY_CONST]; It leads to the following compilation error : Initializer element is not constant I suppose this is because stringWithFormat doesn't return a constant NSString, but since there is no other way to concatenate strings in Obj-C, what am I supposed to do ? Thanks for your help, Eric.

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >