Search Results

Search found 195 results on 8 pages for 'accessor'.

Page 3/8 | < Previous Page | 1 2 3 4 5 6 7 8  | Next Page >

  • OAuth + Twitter on Android: Callback fails

    - by Samuh
    My Android application uses Java OAuth library, found here for authorization on Twitter. I am able to get a request token, authorize the token and get an acknowlegement but when the browser tries the call back url to reconnect with my application, it does not use the URL I provide in code, but uses the one I supplied while registering with Twitter. Note: 1. When registering my application with twitter, I provided a hypothetical call back url:http://abz.xyc.com and set the application type as browser. 2. I provided a callback url in my code "myapp" and have added an intent filter for my activity with Browsable category and data scheme as "myapp". 3. URL called when authorizing does contain te callback url, I specified in code. Any idea what I am doing wrong here? Relevant Code: public class FirstActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); OAuthAccessor client = defaultClient(); Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(client.consumer.serviceProvider.userAuthorizationURL + "?oauth_token=" + client.requestToken + "&oauth_callback=" + client.consumer.callbackURL)); startActivity(i); } OAuthServiceProvider defaultProvider() { return new OAuthServiceProvider(GeneralRuntimeConstants.request_token_URL, GeneralRuntimeConstants.authorize_url, GeneralRuntimeConstants.access_token_url); } OAuthAccessor defaultClient() { String callbackUrl = "myapp:///"; OAuthServiceProvider provider = defaultProvider(); OAuthConsumer consumer = new OAuthConsumer(callbackUrl, GeneralRuntimeConstants.consumer_key, GeneralRuntimeConstants.consumer_secret, provider); OAuthAccessor accessor = new OAuthAccessor(consumer); OAuthClient client = new OAuthClient(new HttpClient4()); try { client.getRequestToken(accessor); } catch (Exception e) { e.printStackTrace(); } return accessor; } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); Uri uri = this.getIntent().getData(); if (uri != null) { String access_token = uri.getQueryParameter("oauth_token"); } } } // Manifest file <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".FirstActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="myapp"/> </intent-filter> </activity> </application>

    Read the article

  • PLT Scheme Extracting field ids from structures

    - by Steve Knight
    I want to see if I can map PLT Scheme structure fields to columns in a DB. I've figured out how to extract accessor functions from structures in PLT scheme using the fourth return value of: (struct-type-info) However the returned procedure indexes into the struct using an integer. Is there some way that I can find out what the field names were at point of definition? Looking at the documentation it seems like this information is "forgotten" after the structure is defined and exists only via the generated-accessor functions: (<id>-<field-id> s). So I can think of two possible solutions: Search the namespace symbols for ones that start with my struct name (yuk); Define a custom define-struct macro that captures the ordered sequence of field-names inside some hash that is keyed by struct name (eek).

    Read the article

  • ASP.net MVC - OneToOne relationship with pluralized nomenclature

    - by ludicco
    Hi, I have an OneToOne relationship between my models Account and Company the table names are Accounts and Companies respectively. Here is a brief screenshot of the structure: http://cl.ly/1AEU Everything works well, but mysteriously when I use the OneToOne associations I have accessors like: var db = new DB(); var account = db.Accounts.First(); var company = account.Companies; // note the plural not the singular accessor So, what's happing is that even if using OneToOne association, I still get the plural accessor with "companies" and not "company", if it this is a pure object representation and not an EntitySet generated in case when it s an oneToMany relationship. Is there a way to get this nomenclature to be applied properly? Thanks a lot

    Read the article

  • OAuth java implementation, oauth_callback missing

    - by l245c4l
    Hey, My problem is I get error while trying to get request token from Yahoo. The error says Im missing oauth_callback parameter and yes I miss it because I dont need it. Ive read I need to set it to "oob" value if I dont want to use it(desktop app). And I did that but to no avail. If I set it to null the same happens. Im using OAuth for java: http://oauth.googlecode.com/svn/code/java/core/ OAuthServiceProvider serviceProvider = new OAuthServiceProvider("https://api.login.yahoo.com/oauth/v2/get_request_token", "https://api.login.yahoo.com/oauth/v2/request_auth", "https://api.login.yahoo.com/oauth/v2/get_token"); OAuthConsumer consumer = new OAuthConsumer("oob", consumerKey, consumerSecret, serviceProvider); OAuthAccessor accessor = new OAuthAccessor(consumer); OAuthClient client = new OAuthClient(new HttpClient4()); OAuthMessage response = client.getRequestTokenResponse(accessor, OAuthMessage.POST, null); System.out.println(response.getBodyAsStream());

    Read the article

  • Does different iVar name change retain count when used with property

    - by russell
    Here is 2 code snapshot- Class A:NSObject { NSMutableArray *a; } @property (retain) NSMutableArray *a; @implementation @synthesize a; -(id)init { if(self=[super init]) { a=[[NSMutableArray alloc] init]; } } @end Class A:NSObject { NSMutableArray *_a; } @property (retain) NSMutableArray *a; @implementation @synthesize a=_a; -(id)init { if(self=[super init]) { _a=[[NSMutableArray alloc] init]; } } @end Now what i need to know, is in both code instance variable assigned value directly rather than using accessor and retain count is 1? Or there is difference between them. Thanks. And one more things, apple recommended not to use accessor in init/dealloc, but at the same time ask not to directly set iVar. So what is the best way to assign value of ivar in init()??

    Read the article

  • Speeding up templates in GAE-Py by aggregating RPC calls

    - by Sudhir Jonathan
    Here's my problem: class City(Model): name = StringProperty() class Author(Model): name = StringProperty() city = ReferenceProperty(City) class Post(Model): author = ReferenceProperty(Author) content = StringProperty() The code isn't important... its this django template: {% for post in posts %} <div>{{post.content}}</div> <div>by {{post.author.name}} from {{post.author.city.name}}</div> {% endfor %} Now lets say I get the first 100 posts using Post.all().fetch(limit=100), and pass this list to the template - what happens? It makes 200 more datastore gets - 100 to get each author, 100 to get each author's city. This is perfectly understandable, actually, since the post only has a reference to the author, and the author only has a reference to the city. The __get__ accessor on the post.author and author.city objects transparently do a get and pull the data back (See this question). Some ways around this are Use Post.author.get_value_for_datastore(post) to collect the author keys (see the link above), and then do a batch get to get them all - the trouble here is that we need to re-construct a template data object... something which needs extra code and maintenance for each model and handler. Write an accessor, say cached_author, that checks memcache for the author first and returns that - the problem here is that post.cached_author is going to be called 100 times, which could probably mean 100 memcache calls. Hold a static key to object map (and refresh it maybe once in five minutes) if the data doesn't have to be very up to date. The cached_author accessor can then just refer to this map. All these ideas need extra code and maintenance, and they're not very transparent. What if we could do @prefetch def render_template(path, data) template.render(path, data) Turns out we can... hooks and Guido's instrumentation module both prove it. If the @prefetch method wraps a template render by capturing which keys are requested we can (atleast to one level of depth) capture which keys are being requested, return mock objects, and do a batch get on them. This could be repeated for all depth levels, till no new keys are being requested. The final render could intercept the gets and return the objects from a map. This would change a total of 200 gets into 3, transparently and without any extra code. Not to mention greatly cut down the need for memcache and help in situations where memcache can't be used. Trouble is I don't know how to do it (yet). Before I start trying, has anyone else done this? Or does anyone want to help? Or do you see a massive flaw in the plan?

    Read the article

  • Returning a C++ reference in a const member functionasses

    - by Chris Kaminski
    A have a class hierarchy that looks somethign like this: class AbstractDataType { public: virtual int getInfo() = 0; }; class DataType: public AbstractDataType { public: virtual int getInfo() { }; } class Accessor { DataType data; public: const AbstractDataType& getData() const { return(data); } } Well, GCC 4.4 reports: In member function ‘const AbstractDataType& Accessor::getData() const’: error: invalid initialization of reference of type ‘const AbstractDataType&’ from expression of type ‘const DataType’ Where am I going wrong - is this a case where I MUST use a pointer?

    Read the article

  • django related_name for field clashes.

    - by Absolute0
    I am getting a field clash in my models: class Visit(models.Model): user = models.ForeignKey(User) visitor = models.ForeignKey(User) Error: One or more models did not validate: profiles.visit: Accessor for field 'user' clashes with related field 'User.visit_set'. Add a related_name argument to the definition for 'user'. profiles.visit: Accessor for field 'visitor' clashes with related field 'User.visit_set'. Add a related_name argument to the definition for 'visitor'. what would be a sensible 'related_field' to use on visitor field? This model basically represents the visits that take place to a particular user's profile. Also should I replace any of the ForeignKey's with a ManyToManyField? The logic is a bit confusing. Edit: This seems to fix it, but I am unsure if its what I want. :) class Visit(models.Model): user = models.ForeignKey(User) visitor = models.ForeignKey(User, related_name='visitors')

    Read the article

  • View Link inConsistency

    - by Abhishek Dwivedi
    What is View Link Consistency? When multiple instances (say VO1, VO2, VO3 etc) of an EO-based VO are based on the same underlying EO, a new row created in one of these VO instances (say VO1)can be automatically added (without re-query) to the row sets of the others (VO2, VO3 etc ). This capability is known as the view link consistency. This feature works for any VO for which it is enabled, regardless of whether they are involved in a view link or not. What causes View Link inConsistency? Unless jbo.viewlink.consistent  is disabled for this VO (or globally), or setAssociationConsistent(false) is applied, any of the following can cause View Link inConsistency.  1. setWhereClause 2. Unreferenced secondary EO 3. findByViewCriteria() 4. Using view link accessor row set Why does this happen - View Link inConsistency? Well, there can be one of the following reasons. a. In case of 1 & 2, the view link consistency flag is disabled on that view object. b. As far as 3 is concerned, findByViewCriteria is used to retrieve a new row set to process programmatically without changing the contents of the default row set. In this case, unlike previous cases, the view link consistency flag is not disabled, meaning that the changes in the default row set would be reflected in the new row set.  However, the opposite doesn't hold true. For instance, if a row is deleted from this new row set, the corresponding row in the default row set does not get deleted. In one of my features, which involved deletion of row(s), I resolved the view link inconsistency issue by replacing findByViewCriteria by applyViewCriteria. b. For 4, it's similar to 3 - whenever a view link accessor row set is retrieved, a new row set is created. Now, creating new row set does not mean re-executing the query each time, only creating a new instance of a RowSet object with its default iterator reset to the "slot" before the first row. Also, please note that this new row set always originates from an internally created view object instance, not one you that added to the data model. This internal view object instance is created as needed and added with a system-defined name to the root application module. Anyway, the very reason a distinct, internally-created view object instance is used is to guarantee that it remains unaffected by developer-related changes to their own view objects instances in the data model.

    Read the article

  • Cocoa equivalent of the Carbon method getPtrSize

    - by Michael Minerva
    I need to translate the a carbon method into cocoa into and I am having trouble finding any documentation about what the carbon method getPtrSize really does. From the code I am translating it seems that it returns the byte representation of an image but that doesn't really match up with the name. Could someone give me a good explanation of this method or link me to some documentation that describes it. The code I am translating is in a common lisp implementation called MCL that has a bridge to carbon (I am translating into CCL which is a common lisp implementation with a Cocoa bridge). Here is the MCL code (#_before a method call means that it is a carbon method): (defmethod COPY-CONTENT-INTO ((Source inflatable-icon) (Destination inflatable-icon)) ;; check for size compatibility to avoid disaster (unless (and (= (rows Source) (rows Destination)) (= (columns Source) (columns Destination)) (= (#_getPtrSize (image Source)) (#_getPtrSize (image Destination)))) (error "cannot copy content of source into destination inflatable icon: incompatible sizes")) ;; given that they are the same size only copy content (setf (is-upright Destination) (is-upright Source)) (setf (height Destination) (height Source)) (setf (dz Destination) (dz Source)) (setf (surfaces Destination) (surfaces Source)) (setf (distance Destination) (distance Source)) ;; arrays (noise-map Source) ;; accessor makes array if needed (noise-map Destination) ;; ;; accessor makes array if needed (dotimes (Row (rows Source)) (dotimes (Column (columns Source)) (setf (aref (noise-map Destination) Row Column) (aref (noise-map Source) Row Column)) (setf (aref (altitudes Destination) Row Column) (aref (altitudes Source) Row Column)))) (setf (connectors Destination) (mapcar #'copy-instance (connectors Source))) (setf (visible-alpha-threshold Destination) (visible-alpha-threshold Source)) ;; copy Image: slow byte copy (dotimes (I (#_getPtrSize (image Source))) (%put-byte (image Destination) (%get-byte (image Source) i) i)) ;; flat texture optimization: do not copy texture-id -> destination should get its own texture id from OpenGL (setf (is-flat Destination) (is-flat Source)) ;; do not compile flat textures: the display list overhead slows things down by about 2x (setf (auto-compile Destination) (not (is-flat Source))) ;; to make change visible we have to reset the compiled flag (setf (is-compiled Destination) nil))

    Read the article

  • Replacing instructions in a method's MethodBody

    - by Alix
    Hi, (First of all, this is a very lengthy post, but don't worry: I've already implemented all of it, I'm just asking your opinion.) I'm having trouble implementing the following; I'd appreciate some help: I get a Type as parameter. I define a subclass using reflection. Notice that I don't intend to modify the original type, but create a new one. I create a property per field of the original class, like so: public class OriginalClass { private int x; } public class Subclass : OriginalClass { private int x; public int X { get { return x; } set { x = value; } } } For every method of the superclass, I create an analogous method in the subclass. The method's body must be the same except that I replace the instructions ldfld x with callvirt this.get_X, that is, instead of reading from the field directly I call the get accessor. I'm having trouble with step 4. I know you're not supposed to manipulate code like this, but I really need to. Here's what I've tried: Attempt #1: Use Mono.Cecil. This would allow me to parse the body of the method into human-readable Instructions, and easily replace instructions. However, the original type isn't in a .dll file, so I can't find a way to load it with Mono.Cecil. Writing the type to a .dll, then load it, then modify it and write the new type to disk (which I think is the way you create a type with Mono.Cecil), and then load it seems like a huge overhead. Attempt #2: Use Mono.Reflection. This would also allow me to parse the body into Instructions, but then I have no support for replacing instructions. I've implemented a very ugly and inefficient solution using Mono.Reflection, but it doesn't yet support methods that contain try-catch statements (although I guess I can implement this) and I'm concerned that there may be other scenarios in which it won't work, since I'm using the ILGenerator in a somewhat unusual way. Also, it's very ugly ;). Here's what I've done: private void TransformMethod(MethodInfo methodInfo) { // Create a method with the same signature. ParameterInfo[] paramList = methodInfo.GetParameters(); Type[] args = new Type[paramList.Length]; for (int i = 0; i < args.Length; i++) { args[i] = paramList[i].ParameterType; } MethodBuilder methodBuilder = typeBuilder.DefineMethod( methodInfo.Name, methodInfo.Attributes, methodInfo.ReturnType, args); ILGenerator ilGen = methodBuilder.GetILGenerator(); // Declare the same local variables as in the original method. IList<LocalVariableInfo> locals = methodInfo.GetMethodBody().LocalVariables; foreach (LocalVariableInfo local in locals) { ilGen.DeclareLocal(local.LocalType); } // Get readable instructions. IList<Instruction> instructions = methodInfo.GetInstructions(); // I first need to define labels for every instruction in case I // later find a jump to that instruction. Once the instruction has // been emitted I cannot label it, so I'll need to do it in advance. // Since I'm doing a first pass on the method's body anyway, I could // instead just create labels where they are truly needed, but for // now I'm using this quick fix. Dictionary<int, Label> labels = new Dictionary<int, Label>(); foreach (Instruction instr in instructions) { labels[instr.Offset] = ilGen.DefineLabel(); } foreach (Instruction instr in instructions) { // Mark this instruction with a label, in case there's a branch // instruction that jumps here. ilGen.MarkLabel(labels[instr.Offset]); // If this is the instruction that I want to replace (ldfld x)... if (instr.OpCode == OpCodes.Ldfld) { // ...get the get accessor for the accessed field (get_X()) // (I have the accessors in a dictionary; this isn't relevant), MethodInfo safeReadAccessor = dataMembersSafeAccessors[((FieldInfo) instr.Operand).Name][0]; // ...instead of emitting the original instruction (ldfld x), // emit a call to the get accessor, ilGen.Emit(OpCodes.Callvirt, safeReadAccessor); // Else (it's any other instruction), reemit the instruction, unaltered. } else { Reemit(instr, ilGen, labels); } } } And here comes the horrible, horrible Reemit method: private void Reemit(Instruction instr, ILGenerator ilGen, Dictionary<int, Label> labels) { // If the instruction doesn't have an operand, emit the opcode and return. if (instr.Operand == null) { ilGen.Emit(instr.OpCode); return; } // Else (it has an operand)... // If it's a branch instruction, retrieve the corresponding label (to // which we want to jump), emit the instruction and return. if (instr.OpCode.FlowControl == FlowControl.Branch) { ilGen.Emit(instr.OpCode, labels[Int32.Parse(instr.Operand.ToString())]); return; } // Otherwise, simply emit the instruction. I need to use the right // Emit call, so I need to cast the operand to its type. Type operandType = instr.Operand.GetType(); if (typeof(byte).IsAssignableFrom(operandType)) ilGen.Emit(instr.OpCode, (byte) instr.Operand); else if (typeof(double).IsAssignableFrom(operandType)) ilGen.Emit(instr.OpCode, (double) instr.Operand); else if (typeof(float).IsAssignableFrom(operandType)) ilGen.Emit(instr.OpCode, (float) instr.Operand); else if (typeof(int).IsAssignableFrom(operandType)) ilGen.Emit(instr.OpCode, (int) instr.Operand); ... // you get the idea. This is a pretty long method, all like this. } Branch instructions are a special case because instr.Operand is SByte, but Emit expects an operand of type Label. Hence the need for the Dictionary labels. As you can see, this is pretty horrible. What's more, it doesn't work in all cases, for instance with methods that contain try-catch statements, since I haven't emitted them using methods BeginExceptionBlock, BeginCatchBlock, etc, of ILGenerator. This is getting complicated. I guess I can do it: MethodBody has a list of ExceptionHandlingClause that should contain the necessary information to do this. But I don't like this solution anyway, so I'll save this as a last-resort solution. Attempt #3: Go bare-back and just copy the byte array returned by MethodBody.GetILAsByteArray(), since I only want to replace a single instruction for another single instruction of the same size that produces the exact same result: it loads the same type of object on the stack, etc. So there won't be any labels shifting and everything should work exactly the same. I've done this, replacing specific bytes of the array and then calling MethodBuilder.CreateMethodBody(byte[], int), but I still get the same error with exceptions, and I still need to declare the local variables or I'll get an error... even when I simply copy the method's body and don't change anything. So this is more efficient but I still have to take care of the exceptions, etc. Sigh. Here's the implementation of attempt #3, in case anyone is interested: private void TransformMethod(MethodInfo methodInfo, Dictionary<string, MethodInfo[]> dataMembersSafeAccessors, ModuleBuilder moduleBuilder) { ParameterInfo[] paramList = methodInfo.GetParameters(); Type[] args = new Type[paramList.Length]; for (int i = 0; i < args.Length; i++) { args[i] = paramList[i].ParameterType; } MethodBuilder methodBuilder = typeBuilder.DefineMethod( methodInfo.Name, methodInfo.Attributes, methodInfo.ReturnType, args); ILGenerator ilGen = methodBuilder.GetILGenerator(); IList<LocalVariableInfo> locals = methodInfo.GetMethodBody().LocalVariables; foreach (LocalVariableInfo local in locals) { ilGen.DeclareLocal(local.LocalType); } byte[] rawInstructions = methodInfo.GetMethodBody().GetILAsByteArray(); IList<Instruction> instructions = methodInfo.GetInstructions(); int k = 0; foreach (Instruction instr in instructions) { if (instr.OpCode == OpCodes.Ldfld) { MethodInfo safeReadAccessor = dataMembersSafeAccessors[((FieldInfo) instr.Operand).Name][0]; // Copy the opcode: Callvirt. byte[] bytes = toByteArray(OpCodes.Callvirt.Value); for (int m = 0; m < OpCodes.Callvirt.Size; m++) { rawInstructions[k++] = bytes[put.Length - 1 - m]; } // Copy the operand: the accessor's metadata token. bytes = toByteArray(moduleBuilder.GetMethodToken(safeReadAccessor).Token); for (int m = instr.Size - OpCodes.Ldfld.Size - 1; m >= 0; m--) { rawInstructions[k++] = bytes[m]; } // Skip this instruction (do not replace it). } else { k += instr.Size; } } methodBuilder.CreateMethodBody(rawInstructions, rawInstructions.Length); } private static byte[] toByteArray(int intValue) { byte[] intBytes = BitConverter.GetBytes(intValue); if (BitConverter.IsLittleEndian) Array.Reverse(intBytes); return intBytes; } private static byte[] toByteArray(short shortValue) { byte[] intBytes = BitConverter.GetBytes(shortValue); if (BitConverter.IsLittleEndian) Array.Reverse(intBytes); return intBytes; } (I know it isn't pretty. Sorry. I put it quickly together to see if it would work.) I don't have much hope, but can anyone suggest anything better than this? Sorry about the extremely lengthy post, and thanks.

    Read the article

  • InvalidOperationException (Lambda parameter not in scope) when trying to Compile a Lambda Expression

    - by Moshe Levi
    Hello, I'm writing an Expression Parser to make my API more refactor friendly and less error prone. basicaly, I want the user to write code like that: repository.Get(entity => entity.Id == 10); instead of: repository.Get<Entity>("Id", 10); Extracting the member name from the left side of the binary expression was straight forward. The problems began when I tried to extract the value from the right side of the expression. The above snippet demonstrates the simplest possible case which involves a constant value but it can be much more complex involving closures and what not. After playing with that for some time I gave up on trying to cover all the possible cases myself and decided to use the framework to do all the heavy lifting for me by compiling and executing the right side of the expression. the relevant part of the code looks like that: public static KeyValuePair<string, object> Parse<T>(Expression<Func<T, bool>> expression) { var binaryExpression = (BinaryExpression)expression.Body; string memberName = ParseMemberName(binaryExpression.Left); object value = ParseValue(binaryExpression.Right); return new KeyValuePair<string, object>(memberName, value); } private static object ParseValue(Expression expression) { Expression conversionExpression = Expression.Convert(expression, typeof(object)); var lambdaExpression = Expression.Lambda<Func<object>>(conversionExpression); Func<object> accessor = lambdaExpression.Compile(); return accessor(); } Now, I get an InvalidOperationException (Lambda parameter not in scope) in the Compile line. when I googled for the solution I came up with similar questions that involved building an expression by hand and not supplying all the pieces, or trying to rely on parameters having the same name and not the same reference. I don't think that this is the case here because I'm reusing the given expression. I would appreciate if someone will give me some pointers on this. Thank you.

    Read the article

  • Django User M2M relationship

    - by Antonio
    When trying to syncdb with the following models: class Contact(models.Model): user_from = models.ForeignKey(User,related_name='from_user') user_to = models.ForeignKey(User, related_name='to_user') class Meta: unique_together = (('user_from', 'user_to'),) User.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)) I get the following error: Error: One or more models did not validate: auth.user: Accessor for m2m field 'following' clashes with related m2m field 'User.followers'. Add a related_name argument to the definition for 'following'. auth.user: Reverse query name for m2m field 'following' clashes with related m2m field 'User.followers'. Add a related_name argument to the definition for 'following'. auth.user: The model User has two manually-defined m2m relations through the model Contact, which is not permitted. Please consider using an extra field on your intermediary model instead. auth.user: Accessor for m2m field 'following' clashes with related m2m field 'User.followers'. Add a related_name argument to the definition for 'following'. auth.user: Reverse query name for m2m field 'following' clashes with related m2m field 'User.followers'. Add a related_name argument to the definition for 'following'.

    Read the article

  • NSPredicate case-insensitive matching on to-many relationship

    - by Brian Webster
    I am implementing a search field where the user can type in a string to filter the items displayed in a view. Each object being displayed has a keywords to-many relationship, and I would like to be able to filter the objects based on their keywords. Each keyword object has a name property, so I've set up an NSPredicate to do the filtering that looks like this: NSPredicate* predicate = [NSPredicate predicateWithFormat:@"keywords.name CONTAINS %@", self.searchString]; This works, but the problem is that the search is case-sensitive, so if the keyword has a capital letter but the user types in all lowercase, no matches are found. I've tried the following modification: NSPredicate* predicate = [NSPredicate predicateWithFormat:@"keywords.name CONTAINS[c] %@", self.searchString]; But that doesn't make any difference in the case sensitivity of the matching. Is there a way to do this case-insensitive matching using just a plain predicate? Or will I need to implement some sort of custom accessor on the keyword class, e.g. write a lowercaseName method and match against a lowercased version of the search string instead? Addendum: After further exploration, the workaround of adding a custom accessor works OK for manual use of NSPredicate, but does not work at all when using NSFetchRequest with Core Data, which only works when querying attributes defined in the Core Data model.

    Read the article

  • When is it better to use a method versus a property for a class definition?

    - by ccomet
    Partially related to an earlier question of mine, I have a system in which I have to store complex data as a string. Instead of parsing these strings as all kinds of separate objects, I just created one class that contains all of those objects, and it has some parser logic that will encode all properties into strings, or decode a string to get those objects. That's all fine and good. This question is not about the parser itself, but about where I should house the logic for the parser. Is it a better choice to put it as a property, or as a method? In the case of a property, say public string DataAsString, the get accessor would house the logic to encode all of the data into a string, while the set accessor would decode the input value and set all of the data in the class instance. It seems convenient because the input/output is indeed a string. In the case of a method, one method would be Encode(), which returns the encoded string. Then, either the constructor itself would house the logic for the decoding a string and require the string argument, or I write a Decode(string str) method which is called separately. In either case, it would be using a method instead of a property. So, is there a functional difference between these paths, in terms of the actual running of the code? Or are they basically equivalent and it then boils down to a choice of personal preference or which one looks better? And in that kind of question... which would look cleaner anyway?

    Read the article

  • qtruby, QUiLoader and respond_to?

    - by Tim Sylvester
    I'm writing a simple Qt4 application in Ruby (using qtruby) to teach myself both. Mostly it has gone well, but in trying to use Ruby's "duck typing" I've run into a snag; respond_to? doesn't seem to reflect reality. irb(main):001:0> require 'rubygems' => true irb(main):002:0> require 'Qt4' => true irb(main):003:0> require 'qtuitools' => true irb(main):004:0> Qt::Application.new(ARGV) => #<Qt::Application:0xc3c9a08 objectName="ruby"> irb(main):005:0> file = Qt::File.new("dlg.ui") { open(Qt::File::ReadOnly) } => #<Qt::File:0xc2e1748 objectName=""> irb(main):006:0> obj = Qt::UiLoader.new().load(file, nil) => #<Qt::Dialog:0xc2bf650 objectName="dlg", x=0, y=0, width=283, height=244> irb(main):007:0> obj.respond_to?('children') => false irb(main):008:0> obj.respond_to?(:children) => false irb(main):009:0> obj.children => [#<Qt::FormInternal::TranslationWatcher:0xc2a1980 objectName="">, ... As you can see, when I check to ensure that the object I get back from loading the UI file has a children accessor I get false. If call that accessor, however, I get an array rather than a NoMethodError. So, is this a bug or have I incorrectly understood respond_to?? This looks like the problem described here, but I thought I would get an expert opinion before filing a bug against the project.

    Read the article

  • How do I interact with a Perl object that has a hash attribute?

    - by brydgesk
    I have a class with several variables, one of which is a hash (_runs): sub new { my ($class, $name) = @_; my $self = { _name => $name, ... _runs => (), _times => [], ... }; bless ($self, $class); return $self; } Now, all I'm trying to do is create an accessor/mutator, as well as another subroutine that pushes new data into the hash. But I'm having a hell of a time getting all the referencing/dereferencing/$self calls working together. I've about burned my eyes out with "Can't use string ("blah") as a HASH ref etc etc" errors. For the accessor, what is 'best practice' for returning hashes? Which one of these options should I be using (if any)?: return $self->{_runs}; return %{ $self->{_runs} }; return \$self->{_runs}; Further, when I'm using the hash within other subroutines in the class, what syntax do I use to copy it? my @runs = $self->{_runs}; my @runs = %{ $self->{_runs} }; my @runs = $%{ $self->{_runs} }; my @runs = $$self->{_runs}; Same goes for iterating over the keys: foreach my $dt (keys $self->{_runs}) foreach my $dt (keys %{ $self->{_runs} }) And how about actually adding the data? $self->{_runs}{$dt} = $duration; %{ $self->{_runs} }{$dt} = $duration; $$self->{_runs}{$dt} = $duration; You get the point. I've been reading articles about using classes, and articles about referencing and dereferencing, but I can't seem to get my brain to combine the knowledge and use both at the same time. I got my _times array working finally, but mimicking my array syntax over to hashes didn't work.

    Read the article

  • Perl - Using hashes in classes

    - by brydgesk
    I have a class with several variables, one of which is a hash (_runs): sub new { my ($class, $name) = @_; my $self = { _name => $name, ... _runs => (), _times => [], ... }; bless ($self, $class); return $self; } Now, all I'm trying to do is create an accessor/mutator, as well as another subroutine that pushes new data into the hash. But I'm having a hell of a time getting all the referencing/dereferencing/$self calls working together. I've about burned my eyes out with "Can't use string ("blah") as a HASH ref etc etc" errors. For the accessor, what is 'best practice' for returning hashes? Which one of these options should I be using (if any)?: return $self->{_runs}; return %{ $self->{_runs} }; return \$self->{_runs}; Further, when I'm using the hash within other subroutines in the class, what syntax do I use to copy it? my @runs = $self->{_runs}; my @runs = %{ $self->{_runs} }; my @runs = $%{ $self->{_runs} }; my @runs = $$self->{_runs}; Same goes for iterating over the keys: foreach my $dt (keys $self->{_runs}) foreach my $dt (keys %{ $self->{_runs} }) And how about actually adding the data? $self->{_runs}{$dt} = $duration; %{ $self->{_runs} }{$dt} = $duration; $$self->{_runs}{$dt} = $duration; You get the point. I've been reading articles about using classes, and articles about referencing and dereferencing, but I can't seem to get my brain to combine the knowledge and use both at the same time. I got my _times array working finally, but mimicking my array syntax over to hashes didn't work.

    Read the article

  • Doesn't this defeat the whole purpose of having read-only properties?

    - by flockofcode
    I know how to use properties and I understand that they implicitly call underlying get and set accessors, depending on whether we are writing to or reading from a property. static void Main(string[] args) { A a = new A(); (a.b).i = 100; } class A { private B _b = new B(); public B b { get { return _b; } } } class B { public int i; } What code (a.b).i = 100; essentially does is that first property’s get accessor returns a reference to an object _b, and once we have this reference, we are able to access _b’s members and change their values. Thus, in our example, having read only property only prevents outside code from changing the value of a reference variable _b, but it doesn’t prevent outside code from accessing _b’s members. So it seems that property can only detect whether we are trying to read from or write to a variable ( in our case variable _b ) located on the stack, while it’s not able to detect whether we’re trying to also write to members of an object to which the variable on the stack ( assuming this variable is of reference type ) points to. a) But doesn’t that defeat the whole purpose of having read-only properties? Wouldn’t it be more effective if properties had the ability to also detect whether we’re trying to access members of an object returned by get accessor( assuming backing field is of a reference type )? thank you

    Read the article

  • How to maintain encapsulation with composition in C++?

    - by iFreilicht
    I am designing a class Master that is composed from multiple other classes, A, Base, C and D. These four classes have absolutely no use outside of Master and are meant to split up its functionality into manageable and logically divided packages. They also provide extensible functionality as in the case of Base, which can be inherited from by clients. But, how do I maintain encapsulation of Master with this design? So far, I've got two approaches, which are both far from perfect: 1. Replicate all accessors: Just write accessor-methods for all accessor-methods of all classes that Master is composed of. This leads to perfect encapsulation, because no implementation detail of Master is visible, but is extremely tedious and makes the class definition monstrous, which is exactly what the composition should prevent. Also, adding functionality to one of the composees (is that even a word?) would require to re-write all those methods in Master. An additional problem is that inheritors of Base could only alter, but not add functionality. 2. Use non-assignable, non-copyable member-accessors: Having a class accessor<T> that can not be copied, moved or assigned to, but overrides the operator-> to access an underlying shared_ptr, so that calls like Master->A()->niceFunction(); are made possible. My problem with this is that it kind of breaks encapsulation as I would now be unable to change my implementation of Master to use a different class for the functionality of niceFunction(). Still, it is the closest I've gotten without using the ugly first approach. It also fixes the inheritance issue quite nicely. A small side question would be if such a class already existed in std or boost. EDIT: Wall of code I will now post the code of the header files of the classes discussed. It may be a bit hard to understand, but I'll give my best in explaining all of it. 1. GameTree.h The foundation of it all. This basically is a doubly-linked tree, holding GameObject-instances, which we'll later get to. It also has it's own custom iterator GTIterator, but I left that out for brevity. WResult is an enum with the values SUCCESS and FAILED, but it's not really important. class GameTree { public: //Static methods for the root. Only one root is allowed to exist at a time! static void ConstructRoot(seed_type seed, unsigned int depth); inline static bool rootExists(){ return static_cast<bool>(rootObject_); } inline static weak_ptr<GameTree> root(){ return rootObject_; } //delta is in ms, this is used for velocity, collision and such void tick(unsigned int delta); //Interaction with the tree inline weak_ptr<GameTree> parent() const { return parent_; } inline unsigned int numChildren() const{ return static_cast<unsigned int>(children_.size()); } weak_ptr<GameTree> getChild(unsigned int index) const; template<typename GOType> weak_ptr<GameTree> addChild(seed_type seed, unsigned int depth = 9001){ GOType object{ new GOType(seed) }; return addChildObject(unique_ptr<GameTree>(new GameTree(std::move(object), depth))); } WResult moveTo(weak_ptr<GameTree> newParent); WResult erase(); //Iterators for for( : ) loop GTIterator& begin(){ return *(beginIter_ = std::move(make_unique<GTIterator>(children_.begin()))); } GTIterator& end(){ return *(endIter_ = std::move(make_unique<GTIterator>(children_.end()))); } //unloading should be used when objects are far away WResult unloadChildren(unsigned int newDepth = 0); WResult loadChildren(unsigned int newDepth = 1); inline const RenderObject& renderObject() const{ return gameObject_->renderObject(); } //Getter for the underlying GameObject (I have not tested the template version) weak_ptr<GameObject> gameObject(){ return gameObject_; } template<typename GOType> weak_ptr<GOType> gameObject(){ return dynamic_cast<weak_ptr<GOType>>(gameObject_); } weak_ptr<PhysicsObject> physicsObject() { return gameObject_->physicsObject(); } private: GameTree(const GameTree&); //copying is only allowed internally GameTree(shared_ptr<GameObject> object, unsigned int depth = 9001); //pointer to root static shared_ptr<GameTree> rootObject_; //internal management of a child weak_ptr<GameTree> addChildObject(shared_ptr<GameTree>); WResult removeChild(unsigned int index); //private members shared_ptr<GameObject> gameObject_; shared_ptr<GTIterator> beginIter_; shared_ptr<GTIterator> endIter_; //tree stuff vector<shared_ptr<GameTree>> children_; weak_ptr<GameTree> parent_; unsigned int selfIndex_; //used for deletion, this isn't necessary void initChildren(unsigned int depth); //constructs children }; 2. GameObject.h This is a bit hard to grasp, but GameObject basically works like this: When constructing a GameObject, you construct its basic attributes and a CResult-instance, which contains a vector<unique_ptr<Construction>>. The Construction-struct contains all information that is needed to construct a GameObject, which is a seed and a function-object that is applied at construction by a factory. This enables dynamic loading and unloading of GameObjects as done by GameTree. It also means that you have to define that factory if you inherit GameObject. This inheritance is also the reason why GameTree has a template-function gameObject<GOType>. GameObject can contain a RenderObject and a PhysicsObject, which we'll later get to. Anyway, here's the code. class GameObject; typedef unsigned long seed_type; //this declaration magic means that all GameObjectFactorys inherit from GameObjectFactory<GameObject> template<typename GOType> struct GameObjectFactory; template<> struct GameObjectFactory<GameObject>{ virtual unique_ptr<GameObject> construct(seed_type seed) const = 0; }; template<typename GOType> struct GameObjectFactory : GameObjectFactory<GameObject>{ GameObjectFactory() : GameObjectFactory<GameObject>(){} unique_ptr<GameObject> construct(seed_type seed) const{ return unique_ptr<GOType>(new GOType(seed)); } }; //same as with the factories. this is important for storing them in vectors template<typename GOType> struct Construction; template<> struct Construction<GameObject>{ virtual unique_ptr<GameObject> construct() const = 0; }; template<typename GOType> struct Construction : Construction<GameObject>{ Construction(seed_type seed, function<void(GOType*)> func = [](GOType* null){}) : Construction<GameObject>(), seed_(seed), func_(func) {} unique_ptr<GameObject> construct() const{ unique_ptr<GameObject> gameObject{ GOType::factory.construct(seed_) }; func_(dynamic_cast<GOType*>(gameObject.get())); return std::move(gameObject); } seed_type seed_; function<void(GOType*)> func_; }; typedef struct CResult { CResult() : constructions{} {} CResult(CResult && o) : constructions(std::move(o.constructions)) {} CResult& operator= (CResult& other){ if (this != &other){ for (unique_ptr<Construction<GameObject>>& child : other.constructions){ constructions.push_back(std::move(child)); } } return *this; } template<typename GOType> void push_back(seed_type seed, function<void(GOType*)> func = [](GOType* null){}){ constructions.push_back(make_unique<Construction<GOType>>(seed, func)); } vector<unique_ptr<Construction<GameObject>>> constructions; } CResult; //finally, the GameObject class GameObject { public: GameObject(seed_type seed); GameObject(const GameObject&); virtual void tick(unsigned int delta); inline Matrix4f trafoMatrix(){ return physicsObject_->transformationMatrix(); } //getter inline seed_type seed() const{ return seed_; } inline CResult& properties(){ return properties_; } inline const RenderObject& renderObject() const{ return *renderObject_; } inline weak_ptr<PhysicsObject> physicsObject() { return physicsObject_; } protected: virtual CResult construct_(seed_type seed) = 0; CResult properties_; shared_ptr<RenderObject> renderObject_; shared_ptr<PhysicsObject> physicsObject_; seed_type seed_; }; 3. PhysicsObject That's a bit easier. It is responsible for position, velocity and acceleration. It will also handle collisions in the future. It contains three Transformation objects, two of which are optional. I'm not going to include the accessors on the PhysicsObject class because I tried my first approach on it and it's just pure madness (way over 30 functions). Also missing: the named constructors that construct PhysicsObjects with different behaviour. class Transformation{ Vector3f translation_; Vector3f rotation_; Vector3f scaling_; public: Transformation() : translation_{ 0, 0, 0 }, rotation_{ 0, 0, 0 }, scaling_{ 1, 1, 1 } {}; Transformation(Vector3f translation, Vector3f rotation, Vector3f scaling); inline Vector3f translation(){ return translation_; } inline void translation(float x, float y, float z){ translation(Vector3f(x, y, z)); } inline void translation(Vector3f newTranslation){ translation_ = newTranslation; } inline void translate(float x, float y, float z){ translate(Vector3f(x, y, z)); } inline void translate(Vector3f summand){ translation_ += summand; } inline Vector3f rotation(){ return rotation_; } inline void rotation(float pitch, float yaw, float roll){ rotation(Vector3f(pitch, yaw, roll)); } inline void rotation(Vector3f newRotation){ rotation_ = newRotation; } inline void rotate(float pitch, float yaw, float roll){ rotate(Vector3f(pitch, yaw, roll)); } inline void rotate(Vector3f summand){ rotation_ += summand; } inline Vector3f scaling(){ return scaling_; } inline void scaling(float x, float y, float z){ scaling(Vector3f(x, y, z)); } inline void scaling(Vector3f newScaling){ scaling_ = newScaling; } inline void scale(float x, float y, float z){ scale(Vector3f(x, y, z)); } void scale(Vector3f factor){ scaling_(0) *= factor(0); scaling_(1) *= factor(1); scaling_(2) *= factor(2); } Matrix4f matrix(){ return WMatrix::Translation(translation_) * WMatrix::Rotation(rotation_) * WMatrix::Scale(scaling_); } }; class PhysicsObject; typedef void tickFunction(PhysicsObject& self, unsigned int delta); class PhysicsObject{ PhysicsObject(const Transformation& trafo) : transformation_(trafo), transformationVelocity_(nullptr), transformationAcceleration_(nullptr), tick_(nullptr) {} PhysicsObject(PhysicsObject&& other) : transformation_(other.transformation_), transformationVelocity_(std::move(other.transformationVelocity_)), transformationAcceleration_(std::move(other.transformationAcceleration_)), tick_(other.tick_) {} Transformation transformation_; unique_ptr<Transformation> transformationVelocity_; unique_ptr<Transformation> transformationAcceleration_; tickFunction* tick_; public: void tick(unsigned int delta){ tick_ ? tick_(*this, delta) : 0; } inline Matrix4f transformationMatrix(){ return transformation_.matrix(); } } 4. RenderObject RenderObject is a base class for different types of things that could be rendered, i.e. Meshes, Light Sources or Sprites. DISCLAIMER: I did not write this code, I'm working on this project with someone else. class RenderObject { public: RenderObject(float renderDistance); virtual ~RenderObject(); float renderDistance() const { return renderDistance_; } void setRenderDistance(float rD) { renderDistance_ = rD; } protected: float renderDistance_; }; struct NullRenderObject : public RenderObject{ NullRenderObject() : RenderObject(0.f){}; }; class Light : public RenderObject{ public: Light() : RenderObject(30.f){}; }; class Mesh : public RenderObject{ public: Mesh(unsigned int seed) : RenderObject(20.f) { meshID_ = 0; textureID_ = 0; if (seed == 1) meshID_ = Model::getMeshID("EM-208_heavy"); else meshID_ = Model::getMeshID("cube"); }; unsigned int getMeshID() const { return meshID_; } unsigned int getTextureID() const { return textureID_; } private: unsigned int meshID_; unsigned int textureID_; }; I guess this shows my issue quite nicely: You see a few accessors in GameObject which return weak_ptrs to access members of members, but that is not really what I want. Also please keep in mind that this is NOT, by any means, finished or production code! It is merely a prototype and there may be inconsistencies, unnecessary public parts of classes and such.

    Read the article

  • Get and Set property accessors are ‘actually’ methods

    - by nmarun
    Well, they are ‘special’ methods, but they indeed are methods. See the class below: 1: public class Person 2: { 3: private string _name; 4:  5: public string Name 6: { 7: get 8: { 9: return _name; 10: } 11: set 12: { 13: if (value == "aaa") 14: { 15: throw new ArgumentException("Invalid Name"); 16: } 17: _name = value; 18: } 19: } 20:  21: public void Save() 22: { 23: Console.WriteLine("Saving..."); 24: } 25: } Ok, so a class with a field, a property with the get and set accessors and a method. Now my calling code says: 1: static void Main() 2: { 3: try 4: { 5: Person person1 = new Person 6: { 7: Name = "aaa", 8: }; 9:  10: } 11: catch (Exception ex) 12: { 13: Console.WriteLine(ex.Message); 14: Console.WriteLine(ex.StackTrace); 15: Console.WriteLine("--------------------"); 16: } 17: } When the code is run, you’ll get the following exception message displayed: Now, you see the first line of the stack trace where it says that the exception was thrown in the method set_Name(String value). Wait a minute, we have not declared any method with that name in our Person class. Oh no, we actually have. When you create a property, this is what happens behind the screen. The CLR creates two methods for each get and set property accessor. Let’s look at the signature once again: set_Name(String value) This also tells you where the ‘value’ keyword comes from in our set property accessor. You’re actually wiring up a method parameter to a field. 1: set 2: { 3: if (value == "aaa") 4: { 5: throw new ArgumentException("Invalid Name"); 6: } 7: _name = value; 8: } Digging deeper on this, I ran the ILDasm tool and this is what I see: We see the ‘free’ constructor (named .ctor) that the compiler gives us, the _name field, the Name property and the Save method. We also see the get_Name and set_Name methods. In order to compare the Save and the set_Name methods, I double-clicked on the two methods and this is what I see: The ‘.method’ keyword tells that both Save and set_Name are both methods (no guessing there!). Seeing the set_Name method as a public method did kinda surprise me. So I said, why can’t I do a person1.set_Name(“abc”) since it is declared as public. This cannot be done because the get_Name and set_Name methods have an extra attribute called ‘specialname’. This attribute is used to identify an IL (Intermediate Language) token that can be treated with special care by the .net language. So the thumb-rule is that any method with the ‘specialname’ attribute cannot be generally called / invoked by the user (a simple test using intellisense proves this). Their functionality is exposed through other ways. In our case, this is done through the property itself. The same concept gets extended to constructors as well making them special methods too. These so-called ‘special’ methods can be identified through reflection. 1: static void ReflectOnPerson() 2: { 3: Type personType = typeof(Person); 4:  5: MethodInfo[] methods = personType.GetMethods(); 6:  7: for (int i = 0; i < methods.Length; i++) 8: { 9: Console.Write("Method: {0}", methods[i].Name); 10: // Determine whether or not each method is a special name. 11: if (methods[i].IsSpecialName) 12: { 13: Console.Write(" has 'SpecialName' attribute"); 14: } 15: Console.WriteLine(); 16: } 17: } Line 11 shows the ‘IsSpecialName’ boolean property. So a method with a ‘specialname’ attribute gets mapped to the IsSpecialName property. The output is displayed as: Wuhuuu! There they are.. our special guests / methods. Verdict: Getting to know the internals… helps!

    Read the article

  • How to structure my java packages

    - by MightyPork
    I have a Java library, quite a huge one. I'm asking regarding Best Practices of structuring the source. For example, the logging sybsystem: Option 1: All in one package, named to sort nicely Log - static accessor LogMonitor - interface for log minotor LogMonitorBase - abstract class LogMonitorStdout - print log to console LogWriter - interface for file logger LogWriterSimple - log writer with just one log file LogWriterArchiving - log writer that handles old log files Option 2: Subpackages for Monitors and Writers, with better names Log monitors/LogMonitor monitors/BaseMonitor monitors/StdoutMonitor writers/LogWriter writers/SimpleLog writers/ArchivingLog The second maybe looks better, but perhaps it's not so practical from the java point of view (two extra packages). What do you suggest as the best practice here? A lot in one package, grouped by naming prefixes, or a lot of subpackages with better names?

    Read the article

  • Moq how to correctly mock read-only properties or set only properies

    - by Chris Marisic
    What is the correct way for dealing with interfaces the expose only read-only or set-only properties with Moq? Previously I've added the other accessor but this has bleed into my domain too far with random throw new NotImplementedException() statements throughout. I just want to do something simple like mock.VerifySet(view => view.SetOnlyValue, Times.Never()); But this is a compile error of The property 'SetOnlyValue' has no getter

    Read the article

  • OO design - car rental

    - by gkid123
    AnHow would you implement the following car hierarchy along with the accessor functions and a CarRental class which contains the container to store them? A car rental company wants to keep track of its cars. Each vehicle has a license plate and a brand. Currently the company has SUV and Sedans. SUV have an optional third row seat, sedan’s have an optional sport package. Each car can be queried to inquire the number of passengers it can carry.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8  | Next Page >