w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
"'System.Dynamic.ExpandoObject' does not contain a definition for "PropertyName"
I gather this is expected behavior when using an ExpandoObject. I took a look at the IntelliTrace log for this code and the entries for the exceptions you are seeing are paired up: Exception:Thrown: "'System.Dynamic.ExpandoObject' does not contain a definition for 'clients'" (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) Exception:Caught: "'System.Dynamic.ExpandoObject' does not contain a definition for 'clients'" (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) i.e. The exception is being thrown and then caught. If you look at the Call Stack Window you will see that the throws and catches are within the .NET Framework. BTW, I did have to make a small change to your code to make it run: I changed: root.clients.client.Count to root.clients.Count in the for loop.

Categories : C#

Java ArrayList class cast exception when trying to set an member variable for an instance of a class
I'm not strong in JSP but what clear for me , you try to show students in JSP file like single String. But students is defined as List. please, run in loop in JSP file on your Students. Something like: <% ArrayList<String> students = teacherAccount .getStudents(); Iterator<String> iterator = students .iterator(); while (iterator.hasNext()) { String student = (String)iterator.next(); String pId = String.getId(); ... %> Suppose your problem is here: <div>Test for jsp vars <%=currentUsername%> PASS: <%=currentPassword%> STUDENTS: <%=students%></div> ^^^^ Use forEach instead to show it

Categories : Java

How to get ServiceStack to serialize a dynamic (ExpandoObject) property on request
You may have seen this announcement: The next major v4.0 will also be a "breaking-release", with new features protected under an "AGPL/FOSS License Exception" and include a number of breaking changes that have built up over time, including upgrading all projects (to .NET 4+), major code and NuGet package re-factoring, clean-up and removal of deprecated code, better consistency / simplification of some concepts and implementation of some roadmap features I've been wanting to add but never had time for. Fixes and releases will continue to v3.x and be maintained in a separate v3 branch until v4.0 comes out of beta. As there's no reason to fix dynamic object support in the current 3.x branch, which doesn't support .Net4.0, the answer is 'No, ServiceStack can't serialize the JSON request

Categories : Json

Member with same type as class instance
One solution that should work is to use "Recursive generics" (See this post). We change the definition of Node<T> to Node<N, T> where N has to implement Node<N, T>... abstract class Node<N, T> where N : Node<N, T> // Here is the recursive definition where T : IComparable<T> { T value; public N NextNode; public N GetLastNode() { N current = (N)this; while (this.NextNode != null) { current = current.NextNode; } return current; } // etc. } Then, you just have to change the base class of AdvancedNode<T> to Node<AdvancedNode<T>, T>. class AdvancedNode<T> : Node<AdvancedNode<T>, T> where T : IComparable<T> { int Height;

Categories : C#

Member function called only on initialization of first instance of a class (C++)
Simple solution: class C { private: static bool runOnce; public: C() { if (!C::runOnce) { C::runOnce = true; RunSth(); } } }; bool C::runOnce = false;

Categories : C++

C++ derived template class: Access protected member of an instance
Why having virtual? In your example derived::assign() does the same as base::assign(). class base { ... public: ... void assign(const base<T>& other) ... } derived<int> b(6); b.assign(a); //calls base<int>::assign(..) If derived should do some more work in assign(..), use base<T>::assign(other); as proposed by Igor Tandetnik. No need to use friend.

Categories : C++

Calling the public instance methods of a composed private class member without passthrough functions in Javascript
I suppose you could write something like: for (var methodName in ProgressBar.prototype) { if (typeof ProgressBar.prototype[methodName] === 'function' && ProgressBar.prototype[methodName] !== ComposedProgressBar.prototype[methodName]) { ComposedProgressBar.prototype[methodName] = (function (methodName) { return function () { return this.progressBar[methodName] .apply(this.progressBar, arguments); }; })(methodName); } } (Naturally this would only create delegates for methods that already exist in ProgressBar.prototype: it wouldn't detect any methods added later, and wouldn't support the ad-hoc method-ing of apply.)

Categories : Javascript

How can I use member function without creating instance of class, using std::function?
You cannot execute a non-static method without an instance (neither std::function nor anything else would allow to do this). Usually non-static methods access some instance data. You have to provide these data (i.e. the instance). In your case I suppose that a Renderer must know something about window it renders. But why do you want to call getRenderer without an instance? You have an instance: const Window& is an instance. So just use the second argument: void Texture::Init(const char* path, const Window& wnd) { loadTexture(path, wnd.getRenderer()); }

Categories : C++

call a class member to get default parameters for another member function of same class
listGraph getPlanarGraph(const vector<int> &nodeSe=this->getLabels()); ... isn't possible because when a method is being called, this refers to whichever class instance is calling the method, not to an instance of the class to which the method belongs. this only refers to the instance of the class to which the method belongs once the method is being executed. As to why it isn't possible, the line above is somewhat similar to calling the method like this: x xinstance; const vector<int> nodeSe labels = this->getLabels(); listGraph lg = xinstance.getPlanarGraph(labels); This code would work, but you can see clearly that this refers to the instance of whatever class contains the lines of code above, not to xinstance. As @Ivan Aucamp pointed out in the commen

Categories : C++

In python ,how to add class member function pointer in class member?
UPDATE: There's no way to get the syntax you want, since there's no way for self.__class__.functionMap[itemName] to know which instance it should operate on. However, if you pass self explicitly, you can get very close: class MyClass: def __detectWhichItemClicked(self): itemName = getItemName() if itemName in self.functionMap: # Pass self into the call self.functionMap[itemName](self, arg) ... # This goes after the __handle methods are defined. functionMap = { "ITEM1": __handleRightClickItem1, ... } # Equivalent. getattr(obj, "foo")(arg) getattr(MyClass, "foo")(obj, arg) obj.foo(arg) MyClass.foo(obj, arg) # Also equivalent bound_method = obj.foo # or getattr(obj, "foo") bound_method(arg) # Still equivalent u

Categories : Python

Can one call an instance's method inside a class without recreating the instance within class' scope?
You have to import the global $errorhandler variable into your local scope: class AnotherClass { function __construct() { global $errorhandler; try { $not_possible = 1/0; } catch (Exception $e) { $errorhandler->log($e); # Doesn't work } } } P.S. 1/0 is not an exception, it's a runtime error. You can't catch those with a try/catch block.

Categories : PHP

Can a child instance access dynamic parent instance attributes and attribute values?
You're misusing inheritance. Rule doesn't need to inherit from Map to access a Map's attributes, and attaching a Rule to a Map won't make it see the Map's attribute values as its own. Inheriting from Map means a Rule is a Map, not that it's linked to or managed by a Map. If you want a Rule to know about its Map, have it record which Map it's associated with: class Rule(object): def __init__(self, number, map): super(Rule, self).__init__() self.number = number self.map = map def __str__(self): # __str__, not __repr__, because __repr__ should be unambiguous, # have a clear beginning and ending, and obviously indicate the type. return "Map {} rule number {}".format(self.map.mapName, self.number) Rule(1, map) # makes a rule associated

Categories : Python

How Does Getting the Address of a Class Member Through a Scope Resolution Operator Work When Using a Pointer-to-Member?
When you declare a pointer to member data, it isn't bounded to any particular instance. If you want to know the address of a data member for a given instance you need to take the address of the result after doing .* or ->*. For instance: #include <stdio.h> struct A { int n; }; int main() { A a = {42}; A aa = {55}; int A::*ptm = &A::n; printf("a.*ptm: %p ", (void *)&(a.*ptm)); printf("aa.*ptm: %p ", (void *)&(aa.*ptm)); } prints as one possible output: a.*ptm: 0xbfbe268c aa.*ptm: 0xbfbe2688

Categories : C++

Strange behavior with volatile write on class member vs struct member
The time difference is most likely a consequence of the var volatileLong = new VolatileLongClass(); within the loop; that statement causes the compiler to--once--allocate space to hold a VolatileLongClass reference, and then on each pass through the loop create a new object and store a reference into that location. By contrast, the statement var volatileLong = new VolatileLongStruct(); causes the compiler to--once--allocate space to hold a VolatileLongStruct instance, and then on each pass through the loop mutate that pre-existing instance by zeroing out all its data (using normal, rather than volatile, writes). Note that if code will require structs fields to have particular multi-thread semantics, such fields should often be made public, and the struct should be regarded as being a gro

Categories : C#

Can a class instance created by another class instance access the creator's members?
You can do this, and you've almost done it, with one minor problem: class Created(): def __init__(self, creator): self.parameter = self.creator.parameter There is no self.creator. If you never need to access it again after this __init__ call, just use the creator parameter directly: class Created(): def __init__(self, creator): self.parameter = creator.parameter If you need it later, store it as self.creator, and then of course you can access it there: class Created(): def __init__(self, creator): self.creator = creator self.parameter = self.creator.parameter … although you probably don't even need to copy over parameter in that case, because you can always get to it as self.creator.parameter. This is a very common pattern. The only

Categories : Python

Make derived class instance given base class instance in Java
Make Parent instances immutable and you can just delegate to an instance of Parent. See Effective Java, Item 16: Favor composition over inheritance.

Categories : Java

Non-member operator as private member of foreign class
It is not possible to make a version of operator == the way you want. It can't be made static. If it is a member, then it must take one argument. If you are willing to "duplicate code", then you can play tricks with namespaces. Your generic interpreter could be a template that takes a language specific derived class as a template parameter. It in turn calls a templated operator== based on a language specific token. template <typename TOKEN> bool operator == (const std::string &l, const TOKEN token) { return token == l; } // Language specific interpreters inherit from this template template <typename LANG> class Interpreter { public: void interpret () { std::string s("hi"); if (s == LANG::KEYWORD_ELSE) {} } }; Each language specific subclass

Categories : C++

Python: Child instance class of an instance of Parent Class
You are not calling __init__ in B. Using the name of the function just gives you that function object. The brackets after __init__() actually execute the function. super(B, self) returns a class, not an object (which makes sense - a class doesn't have a superinstance, it has a superclass), so you then call __class__ on that class, which results in the unexpected result. You use __class__ on self because self is an instance of the class. class B(A): def __init__(self): super(B, self).__init__() print type(self).__name__ print super(B, self).__name__ Note my use of type() over accessing __class__ - using the built-in functions is better than accessing the magic values directly. It's more readable and allows for special functionality.

Categories : Python

Python: Trying to set attributes of a class instance from output of another class instance
The following is incorrect: class photoGallery: def __init__(self, *args): self.output = 'Output from photoGallery class instance' return self.output "_init_" is the constructor for photoGallery which has the responsibility of initialising the photoGallery object. As such it doesn't make sense for it to to return anything. Get rid of return self.output and try again

Categories : Python

accessing private member of member class
public class A { private int myMember; public int getMyMember() { return myMember; } public void setMyMember(int myMember) { this.myMember = myMember; } } public class B{ private A myA; public B() { myA = new A(); myA.setMyMember(0); int a = myA.getMyMember(); } }

Categories : Java

initialize member variable of base class inside child class and use in other class
There are two instances of BaseClass in the example you posted. One is the one instantiated with new ChildClass() and the other one is instantiated by the main() method (TestClass). Each one of them, being a subclass of BaseClass, has its own test member (they are different variables with different values). Remember that the this keyword always references the instance in which it is used. In this case, System.out.println(this.test); is accessing the test property of the TestClass instance created in the main method. You need to access the test property of the other instance. You could do so by keeping a reference to the ChildClass instance and accessing the test property afterwards: ChildClass instance = new ChildClass().initialize(); System.out.println(instance.test); You

Categories : Java

Web dynamic project, Instance the same instance
The problem I assume is, that HTTP is a stateless protocol. That means by default the server does not know anything about the client. That is where Sessionscome in place. On your initial request you have to initialize a session for the client who made the request. From then you are able to "recognize" the client on requests (e.g. to restore the clients state). You also have to save the "connection" inside the session context. You may want to consider using so called "Connection Pools" because it could be very complicated to handle all established connection and close them properly (e.g. session timeout etc.) I suggest you read basics about the HTTP protocol, Sessions and (e.g. Database)Connetion-Handling.

Categories : Java

When I make a second instance of a class in Ruby it changes the first instance of that class
Array.new does not create a deep copy, so your boards are shared, since EMPTY_BOARD is two levels deep. In addition, keeping EMPTY_BOARD outside of your CatanBoard class probably isn't a good idea anyway from a cohesion point of view. If you introduce a private method def empty_board Array.new(19) {Array.new(0) {[]}} end private :empty_board then you can just reference this method during initialization: @board = empty_board

Categories : Ruby

Is there a way to reset a class instance's initialized attribute to the value entered when the instance was created?
There's nothing in Ruby that saves the initial value passed on, so nothing in Ruby that will let you automatically reset it. However, you can certainly save the value in an another instance variable and reset it as you wish, as in: def initialize(..., meat_quality) ... @original_meat_quality = @meat_quality = meat_quality end def reset_meat_quality @meat_quality = @original_meat_quality end

Categories : Ruby

Are object of my classes being created everytime there is a request or does it only create one instance of a class per instance server
Instances of resource classes are created "per-request" by default. You can mark them as singletons however and then one instance would be used for all requests. To do this you can use the following annotations: @com.sun.jersey.spi.resource.Singleton for Jersey 1.x (JAX-RS 1.1) @javax.inject.Singleton for Jersey 2.x (JAX-RS 2.0)

Categories : Java

How do I examine the member configurations of an EntityTypeConfiguration instance?
I received a reply from Arthur Vickers in the Entity Framework Codeplex Discussions. Essentially, he told me I'm barking up the wrong tree, because, by design, they didn't want the configuration classes to be inspected from the normal public surface - the idea being that it would pollute the API and trying to find something like the max length of a string would often tell you the story, but not the whole story (the ultimate max length restriction may have come from several conventions, including a default setting), which might not always give you the answer you are really after. He recommended getting the metadata from the model after being built, through the MetadataWorkspace which can be accessed like this: ((IObjectContextAdapter)myDbContext).ObjectContext.MetadataWorkspace I haven

Categories : C#

Callback method cannot access member variables or instance
You need to pass a pointer to method, but the uvarupdate is pointer to function, these are different types. Pointer to a method contains implicit pointer to this of an instance, it doesn't fit into function-pointer. You need to pass this in some another way. If you do not change signature of the callback, you have to calculate an instance (this) somehow. If it can be determined from name parameter, well, it's easy. Another way is to create a trampoline for each instance you have. If there are only few instances, you can write a separate trampoline function for each instance. Creating trampolines dynamically (in run-time) is tricky and non-portable: in fact, you need to write some machine instructions into RAM so that they call your method with the correct this parameter. But that's also

Categories : C++

FormCollection to expandoObject
Well, not the most elegant code (probably better ways to do it), but one way could be something like this: [HttpPost] public ActionResult Test(FormCollection collection) { dynamic expando = new ExpandoObject(); var dictionary = (IDictionary<string, object>) expando; foreach (var item in collection.AllKeys.ToDictionary(key => key, value => collection[value])) { dictionary.Add(item.Key, item.Value); } // your expando will be populated here ... // do awesomeness } I hope this helps (at least it might give you an idea).

Categories : C#

Java Homework Help (Accessing Static Member via Instance Reference)
You should actually not use the string temp. You should call it as String.format. To answer your question, it is confusing, since the call actually doesn't look at temp.

Categories : Java

Is it possible to query list of ExpandoObject?
Your suggestion is right, you would be able to query a collection of dynamic objects using the dot notation. var ids = generatedItems.Cast<dynamic>().Select(x => x.Id); However, keep in mind that there's no type safety here and, as you stated, IntelliSense is of no use, since you're using dynamic objects. If your code depends on whether one of those objects have an optional property (e.g., some have "Title", others don't), then it will require a little more manual labor. if((generatedItems as IDictionary<String, object>).ContainsKey("Title")) { }

Categories : C#

Should name lookup be deferred for a dependent class/namespace-name in a class-member-access expression?
1 Here is how I think your first case, t.Dependent::f works. First, I believe (means, I am not totally sure) that 14.6.2.1p5 should say "unqualified-id" instead of "id-expression". But independent of that, your name Dependent::f is actually composed out of two names (in the Standard, each nested nested-name-specifier followed by a member name is called "qualified-id", even if grammatically, these are not qualified-id productions. So a name foo::bar::baz is a qualified-id but also contains 1 other "qualified-id" aswell). Dependent and Dependent::f. The former is not "An id-expression denoting the member in a class member access expression", so you can't simply apply the rule that applies to Dependent::f to apply also to Dependent. Dependent is therefor non-dependent and albeit it will

Categories : C++

initializing derived class member variables using base class reference object
Those are too many questions in a single post. What is the correct way to initialize der_e ? For initializing der_e you will have to have Reference of Derived class as it knows about the der_e property and not Base class. What is the advantages of having a reference of base class and using an object derived class for _ref ? Yes that's called Polymorphism which is the essence of Object Oriented Programming. It allows us to hold various concrete implementations without knowing about the actual implementation. If that's the case, should all the member variables of derived class be initialized during construction itself (like this: _ref = new Derived (a,b,c,d) ) There is no such rule. It depends on your scenario. If the values are not meant to be changed after the creat

Categories : C#

Error when using in-class initialization of non-static data member and nested class constructor
Maybe this is the problem: §12.1 5. A default constructor that is defaulted and not defined as deleted is implicitly defined when it is odr- used (3.2) to create an object of its class type (1.8) or when it is explicitly defaulted after its first declaration So, the default constructor is generated when first looked up, but the lookup will fail because A is not completely defined and B inside A will therefore not be found.

Categories : C++

Java: Accessing member of a derived class when an object is declared as a base class
the equals method must be defined as public Object equals(Object obj) in all classes in order for them to override correctly (hint, listen to the @Override annotation compilation error).

Categories : Java

Confused about self in derived class and relation to base class member variables
Unless you do something in a subclass that would eliminate it, then yes. Attributes assigned to Python objects are just added to the object's __dict__ (except for the relatively rare cases where slots is used or __setattr__ is overridden to do something non-standard), and the implicit first argument to a bound member method is going to be the same for methods originating from the child or the parent class. Vanilla instance attributes (though not methods or class attributes) are not bound in any way to a specific class definition, only to the object instance to which they belong. The one caveat to that statement is attributes with names beginning with double underscores. They'll still be added to the __dict__ and accessible, but they will have been name mangled, so will only be accessib

Categories : Python

Error: "Function" is not a Non static data member or base class of "Class"
When you define your methods inside your class declaration, you can't use the :: scope resolution operator. Also your methods should probably in public. And finally you have to be sure that your mChildren member is correctly define. class Container { // ... public: Container() // ^^ : mChildren() , mSelectedChild(-1) { } void pack(Component::Ptr component) // ^^ { // ... } bool isSelectable() const // ^^ { // ... } private: std::vector<Component::Ptr> mChildren; // Example of a definition of mChildren // ^^^^^^^^^^^^^^ replace with the good type };

Categories : C++

Initialize a base class member variable in derived class with some conditions
IMHO, You could do this way: Option 1 : a) Override the Set() in Derived1; b) In Derived1::Set, -- assign the pVal desired value. -- Call Base::Set Sample code: void Derived::Set(){ pVal = /*some value*/; Base::Set(); } Option 2: As pointed by Angew class Derived1: public Base { public: Derived() { pVal = /*some value*/; } }; The SuperBase *s = new Derived1; will invoke the above constructor and pVal would be set.

Categories : C++

how to compile and run a class in apackage that inherits protected member from another class in another package
You'll want to compile Child.java at the root (should be src in many cases) and use a path to compile, something like this assuming from your package name: javac other/Child.java

Categories : Java

Why are private members accessible from derived class (unsing member fxns of base class)
"sINCE WE KNOW THAT PRIVATE MEMBERS ARE NOT INHERITED" That's not true at all. Private members are inherited, but they are not accessible to the derived class. So their storage is still present--otherwise the base class wouldn't have the ability to use its own members either (recall that a derived class object "is a" base class object, just with more stuff added).

Categories : C++

LINQ - Select a list of a class as fields of the class member
You could use something like: string ReportPerson(Person person) { return string.Format("{0}, {1}, {2}", person.name, person.surname, string.Join(", ", person.aspect.SelectMany(a => new[] {a.key, a.value}))); } Edit in response to your edit: This is not directly possible, as anonymous types are defined at compile time. A LINQ query which built out a series of properties like this would require knowing how many keys and values existed at compile time, in order to project your data into the appropriate type. On alternative might be to place your data into a Dictionary<string,string> instead, which would allow you to have an entry for each option: Dictionary<string,string> ProjectPerson(Person person) { var results = Dictionary<string,string>();

Categories : C#



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