w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Basic pointer/reference issue in Objective-C - accessor methods in one instance affect all instances at class level
XYPoint *origin; is a global variable, which means it is shared throughout whole program. You need to declare it as a property, just like you did with x, y, width and height.

Categories : Objective C

KVO or custom accessor methods?
You could do this as such: @implementation Company // ... - (void) didChangeValueForKey: (NSString *) key { [super didChangeValueForKey: key]; if (! [key isEqualToString: @"has_changed"]) self.has_changed = YES; } // ... @end and similar for Person though the company property. You'd also want to implement didChangeValueForKey:withSetMutation:usingObjects: Note that this suggestion does not address the common need of having a controller know about a change. There are other ways to do that.

Categories : IOS

java conditional statement using accessor methods
Apart from using equals you should also use an if else instead of two distinct ifs : if (_holder.getColor() != super.getColor()) { ... _holder.setColor(super.getColor()); } if (_holder.getColor() == super.getColor()) { ... } Note that the second if condition will always evaluate to true - if the holder's color is not equal to super's color, it will be set in the first if condition. if (_holder.getColor().equals(super.getColor())) { ... do sth } else { ... do sth else } Also make sure that either the holder and super do not return null as color or check it explicitly.

Categories : Java

Accessor methods for specific values of a hash in Ruby
This is what I ended up doing. It uses some of Ruby's metaprogramming methods to loop through the element texts, and create methods for each of them. The two things I didn't know that really helped out were these. First, looping through the array with each_with_index lets me have the index of the item in the array, which was necessary for creating the accessor methods. Second, I learned how to pass a value to a proc; see the setter methods. class OmekaItem attr_accessor :data # Parse the data we got from the API into handy methods. All of the data # from the JSON returned by the API is available as RecursiveOpenStructs # through @data. The Dublin Core and Item Type Metadata fields are also # available though special methods of the form dc_title and itm_field. #

Categories : Ruby

Multiple accessor views on c++ class
Choosing from the two options I'd choose the "friend" one, because it doesn't need several additional lines of code, the logic is compacted (not split in two separate classes) and because it fulfills your need. A polymorphic solution could be however implemented to "hide" from the plugin user the unneeded code. So my solution could be a mixture from those two: class A_base { friend class GlobalList; public: A_base(int v) : val(v) {} int get() { return val; } private: int v; void set(int v) { val = v; } }; class A : public A_base { public: A(int v) : A_base(v) { GlobalList::register(this); } }; and GlobalList must have a list of A * (or similar). GlobalList have direct access of every A and A_base methods and fields, public, protected and private ones

Categories : C++

Base class methods calling derived class methods, any possible solution?
if you have a base class with derived classes, the these derived classes override the function, lets call it func(), then that override of func() will be called. as far as i could find, the only solution to what you want is relaying on the good behavior of the derived classes or put func() as a static function, put it into friend class, or put it into a static inner class.

Categories : C++

How to approach implenting a class's methods when these methods depend on another class?
Rework to inherited as MrLister commented, otherwise Method 1 has object ownership issues. If that's not possible, then use Method 2, but modified as method(A &a) (or method(const A &a) if that's the intention) to clarify the object is required.

Categories : C++

Appending the input of my methods to an array-list (methods passed as parameter to the constructor of my class)
A few observations about your program: All you have to do is add the box object to the list: boxList.add(box); Once there, you can access the array list entries to get all the properties of each box in it. Please check the Java API for ArrayList. Now, I have to tell you: You are mixing in your Box class everithing: Object attributes and User interface. I recommend you take out the scanner of the Box class, and use your main method to deal with the user input. You can write setXXX() methods in your Box class to set the attribute values from an external piece of code: public class Box { private String type; private String model; private String serialNum; public Box() { // A simple constructor that does nothing } public void setType(String type) {

Categories : Java

why has_and_belongs_to_many adds class methods rather than instance methods?
When creating a new object (let's say Product), you can use the .build method to fill out those associations and call save! EDIT: here is a good read

Categories : Ruby On Rails

Initializing With Instance Methods versus Class Methods
The difference between a class method and an instance method is that an instance method requires an instance of the class on which it will (generally) operate. The message to invoke an instance method must be sent to an instance of a class. For example In Cocoa the NSString class has several class methods named stringWithSomethingOrOther: that will create a new NSString object and hand it back to you. On the other hand, NSString also has many instance methods - operations which really have no meaning without an actual instance to work with. A commonly-used one might be the length method, which tells you how many characters are in the specific NSString instance to which the message is sent. Suppose for another example- @interface DeepsClass : NSObject + (void)myClassMethod; - (void)

Categories : IOS

req.user is undefined when trying to get it from api methods
You must include the passport's session middleware before all your routes so it can set req.user. app.use(express.session({ secret: 'secret' })); app.use(passport.initialize()); app.use(passport.session()); app.use(app.router); app.use(myRoutes);

Categories : Javascript

Error saying that my methods are undefined
spelling mistake use addWater instead of addwater I think you should check the java naming convention here specially naming a variable says Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed. Variable names should be short yet meaningful. The choice of a variable name should be mnemonic- that is, designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided except for temporary "throwaway" variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters.

Categories : Java

Meteor.methods returns undefined
This is a perfectly normal behavior: server method calls in Meteor are documented to be asynchronous : On the client, if you do not pass a callback and you are not inside a stub, call will return undefined, and you will have no way to get the return value of the method. It means that when you ask for a Meteor.call method to execute remotely on the server, the local method call is non blocking and returns undefined immediately. When the method has been called on the server it will send the result asynchronously to the client, so you should retrieve it using the callback pattern : Meteor.call("myMethod", arguments..., function(error, result){ if(error){ console.log(error.reason); return; } // do something with result }); The anonymous callback function will be called o

Categories : Meteor

Rebinding immutable class attribute in the base class from a derived class
Use the __bases__ attribute: In [68]: class Base(object): ...: # class attribute: ...: class_attr = 0 ...: In [69]: class Derived(Base): ...: @classmethod ...: def inc(cls): ...: p, = cls.__bases__ ...: p.class_attr += 1 ...: In [70]: Base.class_attr Out[70]: 0 In [71]: Derived.inc() In [72]: Derived.inc() In [73]: Base.class_attr Out[73]: 2 If you have multiple inheritance: In [88]: class DifferentInherited(object): ...: class2_attr = 0 ...: In [90]: class Der2(Base, DifferentInherited): ...: @classmethod ...: def inc(cls): ...: print cls.__bases__ ...: a, b, = cls.__bases__ ...: print a.class_attr ...: print b.class2_attr

Categories : Python

Add methods to a class generated from other methods
Do not get the other method from the __dict__; use getattr() instead so the descriptor protocol can kick in. And don't wrap the method function in a MethodType() object as that'd neutralize the descriptor you put on method. You need to bind k to the function you generate; a closured k would change with the loop: @class_or_instance def method(self, verbose=False, _async_method_name=k, *args, **kwargs): response = getattr(self, _async_method_name)(*args,**kwargs) result = self._parse_result(response, verbose=verbose) return result cls.__dict__[methodname] = method Don't forget to return cls at the end; I've changed this to use a separate function to create a new scope to provide a new local name _async_method_name instead of a keyword parameter; this avoids difficulties wit

Categories : Python

MEF not importing methods that has attribute which allows multiple
Not sure if it will work for your particular case since I don't know your entire design and ultimate goal, but since you're creating a meta attrib and so on, you could wrap a flag enum (see Enumeration Types as Bit Flags) in your BusinessLogicMetaDataAttribute, that is, instead of using strings, use a flags enum, then you could do like below [BusinessLogicMetaData(MyFlagEnum.myplugin | MyFlagEnum.myplugin1)] public void Test(object sender, EventArgs e) { //.... } Update: To do multiple exports without using flag enums, inherit from Attribute instead of ExportAttribute, there are a few discussions about this problem around the web [MetadataAttribute] [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class BusinessLogicMetaDataAttribute : Attribute, IBusinessLog

Categories : C#

Image SRC attribute "undefined"
You should look after src if its an image, not href. Try this: var image_href = $(this).attr("src"); You can use .prop instead of .attr, you can read here why. If you are looking for the href of the parent of the img you can use: var image_href = $(event.target).parent().attr("href"); Check this demo were you get first the image src, and then the href.

Categories : Jquery

Nan/Undefined number attribute
for(var turn in turns){ newLine.push(Number(turn.x)); newLine.push(Number(turn.y)); } In JavaScript, a for ... in loop iterates through the property names of an object, not the property values. for (var i = 0; i < turns.length; ++i) { newLine.push(Number(turns[i].x)); newLine.push(Number(turns[i].y)); } You really should not use for ... in on arrays unless you really know that you need to do that.

Categories : Javascript

In AngularJS, how can I see errors from templates, such as calls to undefined methods?
AngularJS expressions are not evaluated with eval(). http://docs.angularjs.org/guide/expression This is actually a huge advantage of Angular, as it leads to less buggy user experiences. Forgiving: expression evaluation is forgiving to undefined and null, unlike in JavaScript, where trying to evaluate undefined properties can generate ReferenceError or TypeError. As far as I know, there is no way to change this ^

Categories : Angularjs

Find model returns undefined when trying to get the attribute of a model by first finding the model by another attribute?
Someone on irc gave me this answer. Then I modified it to make it work completely. Basically I should have used filtered. App.Office.filter( function(e){return e.get('unique_attribute_a') == 'foo'}).objectAt(0) Then I can get the attribute like: App.Office.filter( function(e){return e.get('unique_attribute_a') == 'foo'}).objectAt(0).get('attribute_b') See the code in jsbin. Does anyone know WHY filter works but find doesn't? They both return RecordArrays.

Categories : Ember Js

NDepend Discard methods for types with an attribute
The query for that is: // <Name>Not my code, methods tagged with GeneratedCodeAttribute</Name> notmycode from t in Application.Types where t.HasAttribute ("System.CodeDom.Compiler.GeneratedCodeAttribute".AllowNoMatch()) select t Notice that the default notmycode query for types already takes account of methods tagged with GeneratedCodeAttribute. // <Name>Discard generated Types from JustMyCode</Name> // --- Make sure to make this query richer to discard generated types from NDepend rules results --- notmycode from t in Application.Types where // Resources, Settings, or typed DataSet generated types for example, are tagged with this attribute t.HasAttribute ("System.CodeDom.Compiler.GeneratedCodeAttribute".AllowNoMatch()) || // This attributes identifies

Categories : Dotnet

Symfony2 - Doctrine ArrayCollection methods coming back as undefined
Odd. I was able to work around it by checking its underlying type: public function getThing() { if (get_type($this->things) === 'ArrayCollection') { return $this->things->current(); } else { return $this->things; } } The form now appears, correctly, with no exceptions. Maybe it lazy-assigns an ArrayCollection if there's more than one related entity, and leaves it as just the related entity if there's only one? :shrug:

Categories : Symfony2

undefined attribute name data-placeholder
<form id="selectCountry" name="selectCountry"> <p> <label for="selectCountry">Select a Country:</label> <select data-placeholder="Select a Country.." class="chzn-select" style="width:350px;" tabindex="2"> <option value="" selected="selected"></option> <option value="Australia">Australia</option> <option value="USA">USA</option> <option value="Canada">Canada</option> <option value="England">England</option> </select> </p> </form> Your form was invaild since he was in p / pre tag. About data-placeholder, have you tried Placeholder only?

Categories : PHP

Why `this` can't access the derived class members from base class methods when called for derived class object
Class Base doesn't know that you're only going to use it as part of a Derived object; in general, there might be many different derived classes, only one or some of which may have put(). How could Base be compiled then? When you have a Base pointer to a Derived object, you can cast it to obtain a pointer to Derived, and call the method that way: Base* b = new Derived; dynamic_cast<Derived*>(b)-> put(); A class could actually cast this to a derived instance ponter, if needed: dynamic_cast<Derived*>(this)-> put();

Categories : C++

ObjectiveC passing class Pointer to static library and then calling methods from class
Declare a protocol like this in your static library: @protocol AppDelegateRequiredMethods @required ... methods here ... @end Then, import the header that declares that protocol into your various AppDelegate implementations and declare your app delegate as implementing said protocol: @interface MyAppDelegate:NSObject <AppDelegateRequiredMethods> ... @end

Categories : Iphone

I have define a class and instantiate it and after that I am calling methods of this class but it is not giving any output?
Just remove $var from $obj. Call it as just $obj <?php class user{ public $name; public $age; public function __construct($name, $age){ $this->name=$name; $this->age=$age; } public function sayHello(){ echo("hiiiii".$this->name."!!!"); } public function sayAge(){ $a=time()-strtotime($this->age); echo " hello Your age is".floor($a/(365*30*60*60)); } } $obj = new user('xyz','16 july 1980'); $obj->sayHello(); $obj->sayAge(); ?>

Categories : PHP

How can you access public methods from private class from a different class in java?
Yes there is. You don't actually return an direct reference to your private class, since other classes can't use it. Instead, you extend some public class, and return your private class as an instance of that public class. Then any methods it inherited can be called. public interface Printable { void print(); } public class Test { public Printable getPrintable() { return new PrintTest(); } private class PrintTest implements Printable { public void print() { } } } Test test = new Test(); test.getPrintable().print();

Categories : Java

Abstract class methods implementation with subclasses of an other base class
No, it wouldn't make sense. Think about the following scenario - you have a container (vector/set w/e) of Algorithm* type objects and a function that takes this container and a InputData* in as an input and then iterate over them and call insertData(in) on each of the objects in the container, this of course should work properly, but if one of the objects in your container is of type Algorithm1 what will happen then?

Categories : C++

Class inheritance - Calling properties and/or methods not in the parent class
I'm trying to find out how many levels deep inheritance will go. infinetely, if you want. no limits Is there a term for calling a property or method that does not exist in the current object instance, but this property or method exists in a parent or ancestor class? For class variables: no. For class methods: yes. declare them as private: class A { private function test() { echo 'test'; } } class B extends A { public function __construct() { $this->test(); } } $b = new B(); Output: Fatal error: Call to private method A::test() from context 'B' in /home/thorsten/a.php on line 14

Categories : PHP

Are the methods of derived class facets called from the base class?
No, it will be a reference to a std::ctype<char> facet that will be returned. The methods of a std::ctype facet (that was not default-constructed on construction of the its locale) will operate based on the locale to which it was installed. Using a byname facet means that you want a specific cultural convention on which to apply its methods that could possibly differ from its locale. It fills the same slot as a base class facet, so use_facet won't return a byname facet.

Categories : C++

Do I have to create an object to call on class methods, or can I just type in the class name?
You can use a static method if you don't want to instantiate an object. However, the advantages of having an object instance means you can create more than one instance of the same class with different data. #include <iostream> #include <string> using namespace std; class Sayings{ public: static void coolSaying(){ cout << "Preachin to the choir" << endl; } }; int main() { Sayings::coolSaying(); } And as an sample of the usefulness of class instances: #include <iostream> using namespace std; class Sayings{ public: Sayings(const std::string & saying) : saying_(saying) { } void coolSaying(){ cout << saying_ << endl; } private: std::stri

Categories : C++

Which Membership and Role Provider methods should I override for Authorize attribute?
You need to override the following methods in order for MembershipProvider and RoleProvider to work. public class CustomMembershipProvider : MembershipProvider { public override bool ValidateUser(string username, string password) { } public override MembershipUser GetUser(string username, bool userIsOnline) { } } public class CustomRoleProvider : RoleProvider { public override bool IsUserInRole(string username, string roleName) { } public override string[] GetRolesForUser(string username) { } } OR if you just want the Authorize filter to work, you can simply create Principal object by yourself.

Categories : Asp Net Mvc

Getting access to class properties from within class methods - Java
myDataSource is not static private MyDataSource myDataSource = new MyDataSource(); But CreateUser is static public static User CreateUser( int id, String firstName, String lastName ) So make myDataSource static or remove CreateUser's static modifier. Oh, or a new UserRepository().

Categories : Java

OCMock stub class methods of the class that is being tested
This works fine for me: +(NSString *) classMethod:(id)someDataObject { NSString *returnStr = @"prefix-"; returnStr = [NSString stringWithFormat:@"%@%@", returnStr,[self getCurrentTimestamp]]; return returnStr; } + (NSString *)getCurrentTimestamp { NSNumber *t = [NSNumber numberWithLong:[[NSDate date] timeIntervalSince1970]]; return [t stringValue]; } - (void)testClass { id mock = [OCMockObject mockForClass:[Bar class]]; [[[mock stub] andReturn:@"1378468455"] getCurrentTimestamp]; NSString *str = [Bar classMethod:nil]; NSLog(@"Str: %@", str); } // Result: // Str: prefix-1378468455 Can you confirm your OCMock version, change the number to a string, and / or explain how it is not working for you?

Categories : Misc

Add rails route helpers to a class as class methods
URL routes shouldn't generally need to be accessed from a model. Typically you should only need to access them from your controller when handling a request, or when rendering a view (if you're e.g. formatting a link URL). So instead of asking your model object for the root path, you would simply call root_path from within your controller or a view. Edit If you're just interested in the reason why you're unable to include the module's method as class methods in your class, I would not expect a simple include to work, since that would include the module's methods as as instance methods in your class. extend would normally work, but in this case it does not due to how the url_helpers method is implemented. From actionpack/lib/action_dispatch/routing/route_set.rb source def url_helpers

Categories : Ruby On Rails

Can we use class methods (which start with + sign) with instances of that class
No You cant invoke a static method with the instance. Static method can only invoked by using class name. You cant access instance variables from static methods. Only static variables can be access.

Categories : Objective C

how to invoke customview class methods into GLSurfaceview Class
You cannot add these methods to GLSurfaceView class easily. GLSurfaceView is actually a hole punching view. It has a transparent view to show the underneath surface that display the image. If you scroll this view, only transparent pixels are moved. You should implement these features by using OpenGL ES1/2.

Categories : Android

Creating class extension for a Class's private methods
Your createNewGameAgainst method is a class method (see the + in front of the method declaration). Your checkIfGameAlreadyExistsAgainst method is a instance method (see the - in front of the method declaration). To call checkIfGameAlreadyExistsAgainst from createNewGameAgainst you need to get an instance of MESGameModel. self inside of createNewGameAgainst references the class itself, not an instance of it.

Categories : IOS

c++ using the child class methods of a class that inherits an interface
You want dynamic cast. ChildClass * child = dynamic_cast<ChildClass*>(aClient); if(child){ //cast sucess child->anotherMethod(); }else{ //cast failed, wrong type }

Categories : C++

The attribute lookup is undefined for the annotation type Resource
Try using the mappedName attribute as: @Resource(mappedName="jms/ConnectionFactory") Also if you still want to use lookup, then take a look at the javax.annotation.jar you are using. Lookup attribute was introduced in JavaEE 6. Probably you have an older version.

Categories : Eclipse



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.