Search Results

Search found 2441 results on 98 pages for 'delegate'.

Page 14/98 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • CreateDelegate with unknown types

    - by Giorgi
    Hello, I am trying to create Delegate for reading/writing properties of unknown type of class at runtime. I have a generic class Main<T> and a method which looks like this: Delegate.CreateDelegate(typeof(Func<T, object>), get) where get is a MethodInfo of the property that should be read. The problem is that when the property returns int (I guess this happens for value types) the above code throws ArgumentException because the method cannot be bound. In case of string it works well. To solve the problem I changed the code so that corresponding Delegate type is generated by using MakeGenericType. So now the code is: Type func = typeof(Func<,>); Type generic = func.MakeGenericType(typeof(T), get.ReturnType); var result = Delegate.CreateDelegate(generic, get) The problem now is that the created delegate instance of generic so I have to use DynamicInvoke which would be as slow as using pure reflection to read the field. So my question is why is that the first snippet of code fails with value types. According to MSDN it should work as it says that The return type of a delegate is compatible with the return type of a method if the return type of the method is more restrictive than the return type of the delegate and how to execute the delegate in the second snippet so that it is faster than reflection. Thanks.

    Read the article

  • How to goup EC2 instances in order to delegate administrations to differents teams?

    - by Olivier
    Is it possible (using ARN) to make severals groups of instances. Then using differents policy to grant some access to a group of instance only and not the other instances? For example : { "Statement": [ { "Action": "ec2:*", "Effect": "Allow", "Resource": "*" }, { "Effect": "Allow", "Action": "elasticloadbalancing:*", "Resource": "*" }, { "Effect": "Allow", "Action": "cloudwatch:*", "Resource": "*" }, { "Effect": "Allow", "Action": "autoscaling:*", "Resource": "*" } ] } Instead of "*" could we use a group or something like that? like a specific subnet? a Tag? or whatever... Thanks for your help

    Read the article

  • Why not systematically attach event in WPF instead of using delegate ?

    - by user310291
    For a button to handle event, we can add a delegate to the click property of the button: this.button1.Click += new System.EventHandler(this.button1_Click); But in WPF contrary to Winform, you can also attach a handler http://msdn.microsoft.com/en-us/magazine/cc785480.aspx So why not do so for the button ? Is performance better in first case maybe ? Update: I mean this Attached Events In order to enable elements to handle events that are declared in a different element, WPF supports something called attached events. Attached events are routed events that support a hookup in XAML on elements other than the type on which the event is declared. For example, if you want the Grid element to listen for a Button.Click event to bubble past, you would simply hook it up like the following: <Grid Button.Click="myButton_Click"> <Button Name="myButton" >Click Me</Button> </Grid> The resulting code in the compile-time-generated partial class now looks like this: #line 5 "..\..\Window1.xaml" ((System.Windows.Controls.Grid)(target)).AddHandler( System.Windows.Controls.Primitives.ButtonBase.ClickEvent, new System.Windows.RoutedEventHandler(this.myButton_Click));

    Read the article

  • Where do I attach the StoreKit delegate and observer in a Cocos2d App?

    - by Jeff B
    I have figured out how all of the StoreKit stuff works and have actually tested working code... however, I have a problem. I made my "store" layer/scene the SKProductsRequestDelegate. Is this the correct thing to do? I get the initial product info like so: SKProductsRequest *productRequest = [[SKProductsRequest alloc] initWithProductIdentifiers: productIDs]; [productRequest setDelegate: self]; [productRequest start]; The problem is that if I transition to a new scene when a request is in progress, the current layer is retained by the productRequest. This means that touches on my new scene/layer are handled by both the new layer and the old layer. I could cancel the productRequest when leaving the scene, but: I do not know if it is in progress at that point. I cannot release it because it may or may not have been released by the request delegates. There has got to be a better way to do this. I could make the delegate a class external to the current layer, but then I do not know how to easily update the layer with the product information when the handler is called.

    Read the article

  • Custom Gesture in cocos2d

    - by Lewis
    I've found a little tutorial that would be useful for my game: http://blog.mellenthin.de/archives/2012/02/13/an-one-finger-rotation-gesture-recognizer/ But I can't work out how to convert that gesture to work with cocos2d, I have found examples of pre made gestures in cocos2d, but no custom ones, is it possible? EDIT STILL HAVING PROBLEMS WITH THIS: I've added the code from Sentinel below (from SO), the Gesture and RotateGesture have both been added to my solution and are compiling. Although In the rotation class now I only see selectors, how do I set those up? As the custom gesture found in that project above looks like: header file for custom gesture: #import <Foundation/Foundation.h> #import <UIKit/UIGestureRecognizerSubclass.h> @protocol OneFingerRotationGestureRecognizerDelegate <NSObject> @optional - (void) rotation: (CGFloat) angle; - (void) finalAngle: (CGFloat) angle; @end @interface OneFingerRotationGestureRecognizer : UIGestureRecognizer { CGPoint midPoint; CGFloat innerRadius; CGFloat outerRadius; CGFloat cumulatedAngle; id <OneFingerRotationGestureRecognizerDelegate> target; } - (id) initWithMidPoint: (CGPoint) midPoint innerRadius: (CGFloat) innerRadius outerRadius: (CGFloat) outerRadius target: (id) target; - (void)reset; - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event; - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event; - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event; @end .m for custom gesture file: #include <math.h> #import "OneFingerRotationGestureRecognizer.h" @implementation OneFingerRotationGestureRecognizer // private helper functions CGFloat distanceBetweenPoints(CGPoint point1, CGPoint point2); CGFloat angleBetweenLinesInDegrees(CGPoint beginLineA, CGPoint endLineA, CGPoint beginLineB, CGPoint endLineB); - (id) initWithMidPoint: (CGPoint) _midPoint innerRadius: (CGFloat) _innerRadius outerRadius: (CGFloat) _outerRadius target: (id <OneFingerRotationGestureRecognizerDelegate>) _target { if ((self = [super initWithTarget: _target action: nil])) { midPoint = _midPoint; innerRadius = _innerRadius; outerRadius = _outerRadius; target = _target; } return self; } /** Calculates the distance between point1 and point 2. */ CGFloat distanceBetweenPoints(CGPoint point1, CGPoint point2) { CGFloat dx = point1.x - point2.x; CGFloat dy = point1.y - point2.y; return sqrt(dx*dx + dy*dy); } CGFloat angleBetweenLinesInDegrees(CGPoint beginLineA, CGPoint endLineA, CGPoint beginLineB, CGPoint endLineB) { CGFloat a = endLineA.x - beginLineA.x; CGFloat b = endLineA.y - beginLineA.y; CGFloat c = endLineB.x - beginLineB.x; CGFloat d = endLineB.y - beginLineB.y; CGFloat atanA = atan2(a, b); CGFloat atanB = atan2(c, d); // convert radiants to degrees return (atanA - atanB) * 180 / M_PI; } #pragma mark - UIGestureRecognizer implementation - (void)reset { [super reset]; cumulatedAngle = 0; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesBegan:touches withEvent:event]; if ([touches count] != 1) { self.state = UIGestureRecognizerStateFailed; return; } } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesMoved:touches withEvent:event]; if (self.state == UIGestureRecognizerStateFailed) return; CGPoint nowPoint = [[touches anyObject] locationInView: self.view]; CGPoint prevPoint = [[touches anyObject] previousLocationInView: self.view]; // make sure the new point is within the area CGFloat distance = distanceBetweenPoints(midPoint, nowPoint); if ( innerRadius <= distance && distance <= outerRadius) { // calculate rotation angle between two points CGFloat angle = angleBetweenLinesInDegrees(midPoint, prevPoint, midPoint, nowPoint); // fix value, if the 12 o'clock position is between prevPoint and nowPoint if (angle > 180) { angle -= 360; } else if (angle < -180) { angle += 360; } // sum up single steps cumulatedAngle += angle; // call delegate if ([target respondsToSelector: @selector(rotation:)]) { [target rotation:angle]; } } else { // finger moved outside the area self.state = UIGestureRecognizerStateFailed; } } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesEnded:touches withEvent:event]; if (self.state == UIGestureRecognizerStatePossible) { self.state = UIGestureRecognizerStateRecognized; if ([target respondsToSelector: @selector(finalAngle:)]) { [target finalAngle:cumulatedAngle]; } } else { self.state = UIGestureRecognizerStateFailed; } cumulatedAngle = 0; } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesCancelled:touches withEvent:event]; self.state = UIGestureRecognizerStateFailed; cumulatedAngle = 0; } @end Then its initialised like this: // calculate center and radius of the control CGPoint midPoint = CGPointMake(image.frame.origin.x + image.frame.size.width / 2, image.frame.origin.y + image.frame.size.height / 2); CGFloat outRadius = image.frame.size.width / 2; // outRadius / 3 is arbitrary, just choose something >> 0 to avoid strange // effects when touching the control near of it's center gestureRecognizer = [[OneFingerRotationGestureRecognizer alloc] initWithMidPoint: midPoint innerRadius: outRadius / 3 outerRadius: outRadius target: self]; [self.view addGestureRecognizer: gestureRecognizer]; The selector below is also in the same file where the initialisation of the gestureRecogonizer: - (void) rotation: (CGFloat) angle { // calculate rotation angle imageAngle += angle; if (imageAngle > 360) imageAngle -= 360; else if (imageAngle < -360) imageAngle += 360; // rotate image and update text field image.transform = CGAffineTransformMakeRotation(imageAngle * M_PI / 180); [self updateTextDisplay]; } I can't seem to get this working in the RotateGesture class can anyone help me please I've been stuck on this for days now. SECOND EDIT: Here is the users code from SO that was suggested to me: Here is projec on GitHub: SFGestureRecognizers It uses builded in iOS UIGestureRecognizer, and don't needs to be integrated into cocos2d sources. Using it, You can make any gestures, just like you could, if you whould work with UIGestureRecognizer. For example: I made a base class Gesture, and subclassed it for any new gesture: //Gesture.h @interface Gesture : NSObject <UIGestureRecognizerDelegate> { UIGestureRecognizer *gestureRecognizer; id delegate; SEL preSolveSelector; SEL possibleSelector; SEL beganSelector; SEL changedSelector; SEL endedSelector; SEL cancelledSelector; SEL failedSelector; BOOL preSolveAvailable; CCNode *owner; } - (id)init; - (void)addGestureRecognizerToNode:(CCNode*)node; - (void)removeGestureRecognizerFromNode:(CCNode*)node; -(void)recognizer:(UIGestureRecognizer*)recognizer; @end //Gesture.m #import "Gesture.h" @implementation Gesture - (id)init { if (!(self = [super init])) return self; preSolveAvailable = YES; return self; } - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { return YES; } - (BOOL)gestureRecognizer:(UIGestureRecognizer *)recognizer shouldReceiveTouch:(UITouch *)touch { //! For swipe gesture recognizer we want it to be executed only if it occurs on the main layer, not any of the subnodes ( main layer is higher in hierarchy than children so it will be receiving touch by default ) if ([recognizer class] == [UISwipeGestureRecognizer class]) { CGPoint pt = [touch locationInView:touch.view]; pt = [[CCDirector sharedDirector] convertToGL:pt]; for (CCNode *child in owner.children) { if ([child isNodeInTreeTouched:pt]) { return NO; } } } return YES; } - (void)addGestureRecognizerToNode:(CCNode*)node { [node addGestureRecognizer:gestureRecognizer]; owner = node; } - (void)removeGestureRecognizerFromNode:(CCNode*)node { [node removeGestureRecognizer:gestureRecognizer]; } #pragma mark - Private methods -(void)recognizer:(UIGestureRecognizer*)recognizer { CCNode *node = recognizer.node; if (preSolveSelector && preSolveAvailable) { preSolveAvailable = NO; [delegate performSelector:preSolveSelector withObject:recognizer withObject:node]; } UIGestureRecognizerState state = [recognizer state]; if (state == UIGestureRecognizerStatePossible && possibleSelector) { [delegate performSelector:possibleSelector withObject:recognizer withObject:node]; } else if (state == UIGestureRecognizerStateBegan && beganSelector) [delegate performSelector:beganSelector withObject:recognizer withObject:node]; else if (state == UIGestureRecognizerStateChanged && changedSelector) [delegate performSelector:changedSelector withObject:recognizer withObject:node]; else if (state == UIGestureRecognizerStateEnded && endedSelector) { preSolveAvailable = YES; [delegate performSelector:endedSelector withObject:recognizer withObject:node]; } else if (state == UIGestureRecognizerStateCancelled && cancelledSelector) { preSolveAvailable = YES; [delegate performSelector:cancelledSelector withObject:recognizer withObject:node]; } else if (state == UIGestureRecognizerStateFailed && failedSelector) { preSolveAvailable = YES; [delegate performSelector:failedSelector withObject:recognizer withObject:node]; } } @end Subclass example: //RotateGesture.h #import "Gesture.h" @interface RotateGesture : Gesture - (id)initWithTarget:(id)target preSolveSelector:(SEL)preSolve possibleSelector:(SEL)possible beganSelector:(SEL)began changedSelector:(SEL)changed endedSelector:(SEL)ended cancelledSelector:(SEL)cancelled failedSelector:(SEL)failed; @end //RotateGesture.m #import "RotateGesture.h" @implementation RotateGesture - (id)initWithTarget:(id)target preSolveSelector:(SEL)preSolve possibleSelector:(SEL)possible beganSelector:(SEL)began changedSelector:(SEL)changed endedSelector:(SEL)ended cancelledSelector:(SEL)cancelled failedSelector:(SEL)failed { if (!(self = [super init])) return self; preSolveSelector = preSolve; delegate = target; possibleSelector = possible; beganSelector = began; changedSelector = changed; endedSelector = ended; cancelledSelector = cancelled; failedSelector = failed; gestureRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(recognizer:)]; gestureRecognizer.delegate = self; return self; } @end Use example: - (void)addRotateGesture { RotateGesture *rotateRecognizer = [[RotateGesture alloc] initWithTarget:self preSolveSelector:@selector(rotateGesturePreSolveWithRecognizer:node:) possibleSelector:nil beganSelector:@selector(rotateGestureStateBeganWithRecognizer:node:) changedSelector:@selector(rotateGestureStateChangedWithRecognizer:node:) endedSelector:@selector(rotateGestureStateEndedWithRecognizer:node:) cancelledSelector:@selector(rotateGestureStateCancelledWithRecognizer:node:) failedSelector:@selector(rotateGestureStateFailedWithRecognizer:node:)]; [rotateRecognizer addGestureRecognizerToNode:movableAreaSprite]; } I dont understand how to implement the custom gesture code at the start of this post into the rotateGesture class which is a subclass of the gesture class written by the SO user. Any ideas please? When I get 6 more rep I'll add a bounty to this.

    Read the article

  • Problems extracting information from RSS feed description field

    - by Graeme
    Hi, I've built an iPhone application using the parsing code from the TopSongs sample iPhone application. I've hit a problem though - the feed I'm trying to parse data from doesn't have a separate field for every piece of information (i.e. if it was for a feed about dogs, all the information such as dog type, dog age and dog price is contained in the feed. However, the TopSongs app relies on information having its own tags, so instead of using it uses and . So my question is this. How do I extract this information from the description field so that it can be parsed using the TopSongs parser? Can you somehow extract the dog age, price and type information using Yahoo Pipes and use that RSS feed for the feed? Or is there code that I can add to do it in application? Update: To view the code of my application parser (based on the TopSongs Core Data Apple provided application, see below. Here's a sample of one item from the the actual RSS feed I'm using (the description is longer, and has status,size, and a couple of other fields, but they're all formatted the same.: <item> <title>MOE, MARGRET STREET</title> <description> <b>District/Region:</b>&nbsp;REGION 09</br><b>Location:</b>&nbsp;MOE</br><b>Name:</b>&nbsp;MARGRET STREET</br></description> <pubDate>Thu,11 Mar 2010 05:43:03 GMT</pubDate> <guid>1266148</guid> </item> /* File: iTunesRSSImporter.m Abstract: Downloads, parses, and imports the iTunes top songs RSS feed into Core Data. Version: 1.1 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2009 Apple Inc. All Rights Reserved. */ #import "iTunesRSSImporter.h" #import "Song.h" #import "Category.h" #import "CategoryCache.h" #import <libxml/tree.h> // Function prototypes for SAX callbacks. This sample implements a minimal subset of SAX callbacks. // Depending on your application's needs, you might want to implement more callbacks. static void startElementSAX(void *context, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI, int nb_namespaces, const xmlChar **namespaces, int nb_attributes, int nb_defaulted, const xmlChar **attributes); static void endElementSAX(void *context, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI); static void charactersFoundSAX(void *context, const xmlChar *characters, int length); static void errorEncounteredSAX(void *context, const char *errorMessage, ...); // Forward reference. The structure is defined in full at the end of the file. static xmlSAXHandler simpleSAXHandlerStruct; // Class extension for private properties and methods. @interface iTunesRSSImporter () @property BOOL storingCharacters; @property (nonatomic, retain) NSMutableData *characterBuffer; @property BOOL done; @property BOOL parsingASong; @property NSUInteger countForCurrentBatch; @property (nonatomic, retain) Song *currentSong; @property (nonatomic, retain) NSURLConnection *rssConnection; @property (nonatomic, retain) NSDateFormatter *dateFormatter; // The autorelease pool property is assign because autorelease pools cannot be retained. @property (nonatomic, assign) NSAutoreleasePool *importPool; @end static double lookuptime = 0; @implementation iTunesRSSImporter @synthesize iTunesURL, delegate, persistentStoreCoordinator; @synthesize rssConnection, done, parsingASong, storingCharacters, currentSong, countForCurrentBatch, characterBuffer, dateFormatter, importPool; - (void)dealloc { [iTunesURL release]; [characterBuffer release]; [currentSong release]; [rssConnection release]; [dateFormatter release]; [persistentStoreCoordinator release]; [insertionContext release]; [songEntityDescription release]; [theCache release]; [super dealloc]; } - (void)main { self.importPool = [[NSAutoreleasePool alloc] init]; if (delegate && [delegate respondsToSelector:@selector(importerDidSave:)]) { [[NSNotificationCenter defaultCenter] addObserver:delegate selector:@selector(importerDidSave:) name:NSManagedObjectContextDidSaveNotification object:self.insertionContext]; } done = NO; self.dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; [dateFormatter setDateStyle:NSDateFormatterLongStyle]; [dateFormatter setTimeStyle:NSDateFormatterNoStyle]; // necessary because iTunes RSS feed is not localized, so if the device region has been set to other than US // the date formatter must be set to US locale in order to parse the dates [dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"US"] autorelease]]; self.characterBuffer = [NSMutableData data]; NSURLRequest *theRequest = [NSURLRequest requestWithURL:iTunesURL]; // create the connection with the request and start loading the data rssConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; // This creates a context for "push" parsing in which chunks of data that are not "well balanced" can be passed // to the context for streaming parsing. The handler structure defined above will be used for all the parsing. // The second argument, self, will be passed as user data to each of the SAX handlers. The last three arguments // are left blank to avoid creating a tree in memory. context = xmlCreatePushParserCtxt(&simpleSAXHandlerStruct, self, NULL, 0, NULL); if (rssConnection != nil) { do { [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; } while (!done); } // Display the total time spent finding a specific object for a relationship NSLog(@"lookup time %f", lookuptime); // Release resources used only in this thread. xmlFreeParserCtxt(context); self.characterBuffer = nil; self.dateFormatter = nil; self.rssConnection = nil; self.currentSong = nil; [theCache release]; theCache = nil; NSError *saveError = nil; NSAssert1([insertionContext save:&saveError], @"Unhandled error saving managed object context in import thread: %@", [saveError localizedDescription]); if (delegate && [delegate respondsToSelector:@selector(importerDidSave:)]) { [[NSNotificationCenter defaultCenter] removeObserver:delegate name:NSManagedObjectContextDidSaveNotification object:self.insertionContext]; } if (self.delegate != nil && [self.delegate respondsToSelector:@selector(importerDidFinishParsingData:)]) { [self.delegate importerDidFinishParsingData:self]; } [importPool release]; self.importPool = nil; } - (NSManagedObjectContext *)insertionContext { if (insertionContext == nil) { insertionContext = [[NSManagedObjectContext alloc] init]; [insertionContext setPersistentStoreCoordinator:self.persistentStoreCoordinator]; } return insertionContext; } - (void)forwardError:(NSError *)error { if (self.delegate != nil && [self.delegate respondsToSelector:@selector(importer:didFailWithError:)]) { [self.delegate importer:self didFailWithError:error]; } } - (NSEntityDescription *)songEntityDescription { if (songEntityDescription == nil) { songEntityDescription = [[NSEntityDescription entityForName:@"Song" inManagedObjectContext:self.insertionContext] retain]; } return songEntityDescription; } - (CategoryCache *)theCache { if (theCache == nil) { theCache = [[CategoryCache alloc] init]; theCache.managedObjectContext = self.insertionContext; } return theCache; } - (Song *)currentSong { if (currentSong == nil) { currentSong = [[Song alloc] initWithEntity:self.songEntityDescription insertIntoManagedObjectContext:self.insertionContext]; } return currentSong; } #pragma mark NSURLConnection Delegate methods // Forward errors to the delegate. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [self performSelectorOnMainThread:@selector(forwardError:) withObject:error waitUntilDone:NO]; // Set the condition which ends the run loop. done = YES; } // Called when a chunk of data has been downloaded. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { // Process the downloaded chunk of data. xmlParseChunk(context, (const char *)[data bytes], [data length], 0); } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // Signal the context that parsing is complete by passing "1" as the last parameter. xmlParseChunk(context, NULL, 0, 1); context = NULL; // Set the condition which ends the run loop. done = YES; } #pragma mark Parsing support methods static const NSUInteger kImportBatchSize = 20; - (void)finishedCurrentSong { parsingASong = NO; self.currentSong = nil; countForCurrentBatch++; // Periodically purge the autorelease pool and save the context. The frequency of this action may need to be tuned according to the // size of the objects being parsed. The goal is to keep the autorelease pool from growing too large, but // taking this action too frequently would be wasteful and reduce performance. if (countForCurrentBatch == kImportBatchSize) { [importPool release]; self.importPool = [[NSAutoreleasePool alloc] init]; NSError *saveError = nil; NSAssert1([insertionContext save:&saveError], @"Unhandled error saving managed object context in import thread: %@", [saveError localizedDescription]); countForCurrentBatch = 0; } } /* Character data is appended to a buffer until the current element ends. */ - (void)appendCharacters:(const char *)charactersFound length:(NSInteger)length { [characterBuffer appendBytes:charactersFound length:length]; } - (NSString *)currentString { // Create a string with the character data using UTF-8 encoding. UTF-8 is the default XML data encoding. NSString *currentString = [[[NSString alloc] initWithData:characterBuffer encoding:NSUTF8StringEncoding] autorelease]; [characterBuffer setLength:0]; return currentString; } @end #pragma mark SAX Parsing Callbacks // The following constants are the XML element names and their string lengths for parsing comparison. // The lengths include the null terminator, to ensure exact matches. static const char *kName_Item = "item"; static const NSUInteger kLength_Item = 5; static const char *kName_Title = "title"; static const NSUInteger kLength_Title = 6; static const char *kName_Category = "category"; static const NSUInteger kLength_Category = 9; static const char *kName_Itms = "itms"; static const NSUInteger kLength_Itms = 5; static const char *kName_Artist = "description"; static const NSUInteger kLength_Artist = 7; static const char *kName_Album = "description"; static const NSUInteger kLength_Album = 6; static const char *kName_ReleaseDate = "releasedate"; static const NSUInteger kLength_ReleaseDate = 12; /* This callback is invoked when the importer finds the beginning of a node in the XML. For this application, out parsing needs are relatively modest - we need only match the node name. An "item" node is a record of data about a song. In that case we create a new Song object. The other nodes of interest are several of the child nodes of the Song currently being parsed. For those nodes we want to accumulate the character data in a buffer. Some of the child nodes use a namespace prefix. */ static void startElementSAX(void *parsingContext, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI, int nb_namespaces, const xmlChar **namespaces, int nb_attributes, int nb_defaulted, const xmlChar **attributes) { iTunesRSSImporter *importer = (iTunesRSSImporter *)parsingContext; // The second parameter to strncmp is the name of the element, which we known from the XML schema of the feed. // The third parameter to strncmp is the number of characters in the element name, plus 1 for the null terminator. if (prefix == NULL && !strncmp((const char *)localname, kName_Item, kLength_Item)) { importer.parsingASong = YES; } else if (importer.parsingASong && ( (prefix == NULL && (!strncmp((const char *)localname, kName_Title, kLength_Title) || !strncmp((const char *)localname, kName_Category, kLength_Category))) || ((prefix != NULL && !strncmp((const char *)prefix, kName_Itms, kLength_Itms)) && (!strncmp((const char *)localname, kName_Artist, kLength_Artist) || !strncmp((const char *)localname, kName_Album, kLength_Album) || !strncmp((const char *)localname, kName_ReleaseDate, kLength_ReleaseDate))) )) { importer.storingCharacters = YES; } } /* This callback is invoked when the parse reaches the end of a node. At that point we finish processing that node, if it is of interest to us. For "item" nodes, that means we have completed parsing a Song object. We pass the song to a method in the superclass which will eventually deliver it to the delegate. For the other nodes we care about, this means we have all the character data. The next step is to create an NSString using the buffer contents and store that with the current Song object. */ static void endElementSAX(void *parsingContext, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI) { iTunesRSSImporter *importer = (iTunesRSSImporter *)parsingContext; if (importer.parsingASong == NO) return; if (prefix == NULL) { if (!strncmp((const char *)localname, kName_Item, kLength_Item)) { [importer finishedCurrentSong]; } else if (!strncmp((const char *)localname, kName_Title, kLength_Title)) { importer.currentSong.title = importer.currentString; } else if (!strncmp((const char *)localname, kName_Category, kLength_Category)) { double before = [NSDate timeIntervalSinceReferenceDate]; Category *category = [importer.theCache categoryWithName:importer.currentString]; double delta = [NSDate timeIntervalSinceReferenceDate] - before; lookuptime += delta; importer.currentSong.category = category; } } else if (!strncmp((const char *)prefix, kName_Itms, kLength_Itms)) { if (!strncmp((const char *)localname, kName_Artist, kLength_Artist)) { NSString *string = importer.currentSong.artist; NSArray *strings = [string componentsSeparatedByString: @", "]; //importer.currentSong.artist = importer.currentString; } else if (!strncmp((const char *)localname, kName_Album, kLength_Album)) { importer.currentSong.album = importer.currentString; } else if (!strncmp((const char *)localname, kName_ReleaseDate, kLength_ReleaseDate)) { NSString *dateString = importer.currentString; importer.currentSong.releaseDate = [importer.dateFormatter dateFromString:dateString]; } } importer.storingCharacters = NO; } /* This callback is invoked when the parser encounters character data inside a node. The importer class determines how to use the character data. */ static void charactersFoundSAX(void *parsingContext, const xmlChar *characterArray, int numberOfCharacters) { iTunesRSSImporter *importer = (iTunesRSSImporter *)parsingContext; // A state variable, "storingCharacters", is set when nodes of interest begin and end. // This determines whether character data is handled or ignored. if (importer.storingCharacters == NO) return; [importer appendCharacters:(const char *)characterArray length:numberOfCharacters]; } /* A production application should include robust error handling as part of its parsing implementation. The specifics of how errors are handled depends on the application. */ static void errorEncounteredSAX(void *parsingContext, const char *errorMessage, ...) { // Handle errors as appropriate for your application. NSCAssert(NO, @"Unhandled error encountered during SAX parse."); } // The handler struct has positions for a large number of callback functions. If NULL is supplied at a given position, // that callback functionality won't be used. Refer to libxml documentation at http://www.xmlsoft.org for more information // about the SAX callbacks. static xmlSAXHandler simpleSAXHandlerStruct = { NULL, /* internalSubset */ NULL, /* isStandalone */ NULL, /* hasInternalSubset */ NULL, /* hasExternalSubset */ NULL, /* resolveEntity */ NULL, /* getEntity */ NULL, /* entityDecl */ NULL, /* notationDecl */ NULL, /* attributeDecl */ NULL, /* elementDecl */ NULL, /* unparsedEntityDecl */ NULL, /* setDocumentLocator */ NULL, /* startDocument */ NULL, /* endDocument */ NULL, /* startElement*/ NULL, /* endElement */ NULL, /* reference */ charactersFoundSAX, /* characters */ NULL, /* ignorableWhitespace */ NULL, /* processingInstruction */ NULL, /* comment */ NULL, /* warning */ errorEncounteredSAX, /* error */ NULL, /* fatalError //: unused error() get all the errors */ NULL, /* getParameterEntity */ NULL, /* cdataBlock */ NULL, /* externalSubset */ XML_SAX2_MAGIC, // NULL, startElementSAX, /* startElementNs */ endElementSAX, /* endElementNs */ NULL, /* serror */ }; Thanks.

    Read the article

  • Issue with translating a delegate function from c# to vb.net for use with Google OAuth 2

    - by Jeremy
    I've been trying to translate a Google OAuth 2 example from C# to Vb.net for a co-worker's project. I'm having on end of issues translating the following methods: private OAuth2Authenticator<WebServerClient> CreateAuthenticator() { // Register the authenticator. var provider = new WebServerClient(GoogleAuthenticationServer.Description); provider.ClientIdentifier = ClientCredentials.ClientID; provider.ClientSecret = ClientCredentials.ClientSecret; var authenticator = new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization) { NoCaching = true }; return authenticator; } private IAuthorizationState GetAuthorization(WebServerClient client) { // If this user is already authenticated, then just return the auth state. IAuthorizationState state = AuthState; if (state != null) { return state; } // Check if an authorization request already is in progress. state = client.ProcessUserAuthorization(new HttpRequestInfo(HttpContext.Current.Request)); if (state != null && (!string.IsNullOrEmpty(state.AccessToken) || !string.IsNullOrEmpty(state.RefreshToken))) { // Store and return the credentials. HttpContext.Current.Session["AUTH_STATE"] = _state = state; return state; } // Otherwise do a new authorization request. string scope = TasksService.Scopes.TasksReadonly.GetStringValue(); OutgoingWebResponse response = client.PrepareRequestUserAuthorization(new[] { scope }); response.Send(); // Will throw a ThreadAbortException to prevent sending another response. return null; } The main issue being this line: var authenticator = new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization) { NoCaching = true }; The Method signature reads as for this particular line reads as follows: Public Sub New(tokenProvider As TClient, authProvider As System.Func(Of TClient, DotNetOpenAuth.OAuth2.IAuthorizationState)) My understanding of Delegate functions in VB.net isn't the greatest. However I have read over all of the MSDN documentation and other relevant resources on the web, but I'm still stuck as to how to translate this particular line. So far all of my attempts have resulted in either the a cast error (see below) or no call to GetAuthorization. The Code (vb.net on .net 3.5) Private Function CreateAuthenticator() As OAuth2Authenticator(Of WebServerClient) ' Register the authenticator. Dim client As New WebServerClient(GoogleAuthenticationServer.Description, oauth.ClientID, oauth.ClientSecret) Dim authDelegate As Func(Of WebServerClient, IAuthorizationState) = AddressOf GetAuthorization Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(client, authDelegate) With {.NoCaching = True} 'Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(client, GetAuthorization(client)) With {.NoCaching = True} 'Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(client, New Func(Of WebServerClient, IAuthorizationState)(Function(c) GetAuthorization(c))) With {.NoCaching = True} 'Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(client, New Func(Of WebServerClient, IAuthorizationState)(AddressOf GetAuthorization)) With {.NoCaching = True} Return authenticator End Function Private Function GetAuthorization(arg As WebServerClient) As IAuthorizationState ' If this user is already authenticated, then just return the auth state. Dim state As IAuthorizationState = AuthState If (Not state Is Nothing) Then Return state End If ' Check if an authorization request already is in progress. state = arg.ProcessUserAuthorization(New HttpRequestInfo(HttpContext.Current.Request)) If (state IsNot Nothing) Then If ((String.IsNullOrEmpty(state.AccessToken) = False Or String.IsNullOrEmpty(state.RefreshToken) = False)) Then ' Store Credentials HttpContext.Current.Session("AUTH_STATE") = state _state = state Return state End If End If ' Otherwise do a new authorization request. Dim scope As String = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue() Dim _response As OutgoingWebResponse = arg.PrepareRequestUserAuthorization(New String() {scope}) ' Add Offline Access and forced Approval _response.Headers("location") += "&access_type=offline&approval_prompt=force" _response.Send() ' Will throw a ThreadAbortException to prevent sending another response. Return Nothing End Function The Cast Error Server Error in '/' Application. Unable to cast object of type 'DotNetOpenAuth.OAuth2.AuthorizationState' to type 'System.Func`2[DotNetOpenAuth.OAuth2.WebServerClient,DotNetOpenAuth.OAuth2.IAuthorizationState]'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidCastException: Unable to cast object of type 'DotNetOpenAuth.OAuth2.AuthorizationState' to type 'System.Func`2[DotNetOpenAuth.OAuth2.WebServerClient,DotNetOpenAuth.OAuth2.IAuthorizationState]'. I've spent the better part of a day on this, and it's starting to drive me nuts. Help is much appreciated.

    Read the article

  • Tableview reload data problem iphone sdk

    - by neha
    Hi all, I have a class A which is a subclass of uitableviewcontroller and one more class B which actually displays my tableview with its content is a subclass of A. There's an xml parser which parses my xml and stores the content in an nsmutablearray of application delegate. Now, I fetch this delegate array into a local nsmutablearray in class B to minimise the communication between the two classes i.e. delegate and class B and display that. After certain condition is met in class A, I'm calling xml parser to refill the delegate array and I'm calling class B's tableview reload method. The problem is when I call the tableview's reload data, class B's delegate methods are called. But before that I need to grab this delegate array in local array in class B. How shall I do that? Can anybody please help? Thanx in advance.

    Read the article

  • In c++ is there any Events/delegates/interfaces/notifications! anything?

    - by Bach
    Say i have these classes ViewA and ViewB In objective C using the delegate pattern I could do @protocol ViewBDelegate{ - (void) doSomething(); } then in ViewB interface: id<ViewBDelegate> delegate; then in ViewA implementation i set the delegate: viewB.delegate = self; and now I can call in doSomething from viewB onto any that unknown type delegate. [delegate doSomething]; "C++ How to Program" has been the worse read an can't find simple examples that demonstrates basic design patterns. What i'm looking for in C++ is: events ActionScript and java either delegates or notifications in Objective C anything that allows class A, Class B and Class C to know that ClassX didSomething()!!! thanks

    Read the article

  • Yet another UITableView Question

    - by barbgal
    Hi, I have a strange issue in my iPhone application. I have created a UITableView with 4 Sections and 3 Rows so totally 12 Rows. But - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath The above method only gets called for 9 times instead of 12 times.why this happenning. My 4th section is not getting constructed but my 1st section gets duplicated as 4th section. Thanks for your time and help. Plese refer my code below @interface MainViewController : UITableViewController<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource> { } @end // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { CGRect frameRect = CGRectMake(0,0,320,460); UITableView *tableView = [[UITableView alloc] initWithFrame:frameRect style:UITableViewStyleGrouped]; tableView.delegate = self; tableView.dataSource = self; tableView.backgroundColor = [UIColor purpleColor]; tableView.scrollEnabled = YES; self.view = tableView; [tableView release]; [super viewDidLoad]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return 3; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 4; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"CELL IS NIL %i", indexPath.section); static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; if (indexPath.section == 0) { if(indexPath.row == 0) { cell.text = @"Tmail"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } else if ( indexPath.row == 1 ) { cell.text = @"English"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } else { cell.text = @"Hindi"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } } else if (indexPath.section == 1) { if(indexPath.row == 0) { cell.text = @"Street"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } else if ( indexPath.row == 1 ) { cell.text = @"City"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } else { cell.text = @"State"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } } else if (indexPath.section == 2) { if(indexPath.row == 0) { cell.text = @"Salem"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } else if ( indexPath.row == 1 ) { cell.text = @"Samalpatti"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } else { cell.text = @"Chennai"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } } else if (indexPath.section == 3) { if(indexPath.row == 0) { cell.text = @"NOKIA"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } else if ( indexPath.row == 1) { cell.text = @"SAMSUNG"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } else { cell.text = @"SONY"; UITextField *aField = [[UITextField alloc]initWithFrame:CGRectMake(100,10,200,40)]; aField.placeholder = @"Mandatory"; aField.delegate = self; aField.textColor = [UIColor blackColor]; [cell addSubview:aField]; [aField release]; } } } return cell; }

    Read the article

  • Parallelism in .NET – Part 14, The Different Forms of Task

    - by Reed
    Before discussing Task creation and actual usage in concurrent environments, I will briefly expand upon my introduction of the Task class and provide a short explanation of the distinct forms of Task.  The Task Parallel Library includes four distinct, though related, variations on the Task class. In my introduction to the Task class, I focused on the most basic version of Task.  This version of Task, the standard Task class, is most often used with an Action delegate.  This allows you to implement for each task within the task decomposition as a single delegate. Typically, when using the new threading constructs in .NET 4 and the Task Parallel Library, we use lambda expressions to define anonymous methods.  The advantage of using a lambda expression is that it allows the Action delegate to directly use variables in the calling scope.  This eliminates the need to make separate Task classes for Action<T>, Action<T1,T2>, and all of the other Action<…> delegate types.  As an example, suppose we wanted to make a Task to handle the ”Show Splash” task from our earlier decomposition.  Even if this task required parameters, such as a message to display, we could still use an Action delegate specified via a lambda: // Store this as a local variable string messageForSplashScreen = GetSplashScreenMessage(); // Create our task Task showSplashTask = new Task( () => { // We can use variables in our outer scope, // as well as methods scoped to our class! this.DisplaySplashScreen(messageForSplashScreen); }); .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } This provides a huge amount of flexibility.  We can use this single form of task for any task which performs an operation, provided the only information we need to track is whether the task has completed successfully or not.  This leads to my first observation: Use a Task with a System.Action delegate for any task for which no result is generated. This observation leads to an obvious corollary: we also need a way to define a task which generates a result.  The Task Parallel Library provides this via the Task<TResult> class. Task<TResult> subclasses the standard Task class, providing one additional feature – the ability to return a value back to the user of the task.  This is done by switching from providing an Action delegate to providing a Func<TResult> delegate.  If we decompose our problem, and we realize we have one task where its result is required by a future operation, this can be handled via Task<TResult>.  For example, suppose we want to make a task for our “Check for Update” task, we could do: Task<bool> checkForUpdateTask = new Task<bool>( () => { return this.CheckWebsiteForUpdate(); }); Later, we would start this task, and perform some other work.  At any point in the future, we could get the value from the Task<TResult>.Result property, which will cause our thread to block until the task has finished processing: // This uses Task<bool> checkForUpdateTask generated above... // Start the task, typically on a background thread checkForUpdateTask.Start(); // Do some other work on our current thread this.DoSomeWork(); // Discover, from our background task, whether an update is available // This will block until our task completes bool updateAvailable = checkForUpdateTask.Result; This leads me to my second observation: Use a Task<TResult> with a System.Func<TResult> delegate for any task which generates a result. Task and Task<TResult> provide a much cleaner alternative to the previous Asynchronous Programming design patterns in the .NET framework.  Instead of trying to implement IAsyncResult, and providing BeginXXX() and EndXXX() methods, implementing an asynchronous programming API can be as simple as creating a method that returns a Task or Task<TResult>.  The client side of the pattern also is dramatically simplified – the client can call a method, then either choose to call task.Wait() or use task.Result when it needs to wait for the operation’s completion. While this provides a much cleaner model for future APIs, there is quite a bit of infrastructure built around the current Asynchronous Programming design patterns.  In order to provide a model to work with existing APIs, two other forms of Task exist.  There is a constructor for Task which takes an Action<Object> and a state parameter.  In addition, there is a constructor for creating a Task<TResult> which takes a Func<Object, TResult> as well as a state parameter.  When using these constructors, the state parameter is stored in the Task.AsyncState property. While these two overloads exist, and are usable directly, I strongly recommend avoiding this for new development.  The two forms of Task which take an object state parameter exist primarily for interoperability with traditional .NET Asynchronous Programming methodologies.  Using lambda expressions to capture variables from the scope of the creator is a much cleaner approach than using the untyped state parameters, since lambda expressions provide full type safety without introducing new variables.

    Read the article

  • Parallelism in .NET – Part 4, Imperative Data Parallelism: Aggregation

    - by Reed
    In the article on simple data parallelism, I described how to perform an operation on an entire collection of elements in parallel.  Often, this is not adequate, as the parallel operation is going to be performing some form of aggregation. Simple examples of this might include taking the sum of the results of processing a function on each element in the collection, or finding the minimum of the collection given some criteria.  This can be done using the techniques described in simple data parallelism, however, special care needs to be taken into account to synchronize the shared data appropriately.  The Task Parallel Library has tools to assist in this synchronization. The main issue with aggregation when parallelizing a routine is that you need to handle synchronization of data.  Since multiple threads will need to write to a shared portion of data.  Suppose, for example, that we wanted to parallelize a simple loop that looked for the minimum value within a dataset: double min = double.MaxValue; foreach(var item in collection) { double value = item.PerformComputation(); min = System.Math.Min(min, value); } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } This seems like a good candidate for parallelization, but there is a problem here.  If we just wrap this into a call to Parallel.ForEach, we’ll introduce a critical race condition, and get the wrong answer.  Let’s look at what happens here: // Buggy code! Do not use! double min = double.MaxValue; Parallel.ForEach(collection, item => { double value = item.PerformComputation(); min = System.Math.Min(min, value); }); This code has a fatal flaw: min will be checked, then set, by multiple threads simultaneously.  Two threads may perform the check at the same time, and set the wrong value for min.  Say we get a value of 1 in thread 1, and a value of 2 in thread 2, and these two elements are the first two to run.  If both hit the min check line at the same time, both will determine that min should change, to 1 and 2 respectively.  If element 1 happens to set the variable first, then element 2 sets the min variable, we’ll detect a min value of 2 instead of 1.  This can lead to wrong answers. Unfortunately, fixing this, with the Parallel.ForEach call we’re using, would require adding locking.  We would need to rewrite this like: // Safe, but slow double min = double.MaxValue; // Make a "lock" object object syncObject = new object(); Parallel.ForEach(collection, item => { double value = item.PerformComputation(); lock(syncObject) min = System.Math.Min(min, value); }); This will potentially add a huge amount of overhead to our calculation.  Since we can potentially block while waiting on the lock for every single iteration, we will most likely slow this down to where it is actually quite a bit slower than our serial implementation.  The problem is the lock statement – any time you use lock(object), you’re almost assuring reduced performance in a parallel situation.  This leads to two observations I’ll make: When parallelizing a routine, try to avoid locks. That being said: Always add any and all required synchronization to avoid race conditions. These two observations tend to be opposing forces – we often need to synchronize our algorithms, but we also want to avoid the synchronization when possible.  Looking at our routine, there is no way to directly avoid this lock, since each element is potentially being run on a separate thread, and this lock is necessary in order for our routine to function correctly every time. However, this isn’t the only way to design this routine to implement this algorithm.  Realize that, although our collection may have thousands or even millions of elements, we have a limited number of Processing Elements (PE).  Processing Element is the standard term for a hardware element which can process and execute instructions.  This typically is a core in your processor, but many modern systems have multiple hardware execution threads per core.  The Task Parallel Library will not execute the work for each item in the collection as a separate work item. Instead, when Parallel.ForEach executes, it will partition the collection into larger “chunks” which get processed on different threads via the ThreadPool.  This helps reduce the threading overhead, and help the overall speed.  In general, the Parallel class will only use one thread per PE in the system. Given the fact that there are typically fewer threads than work items, we can rethink our algorithm design.  We can parallelize our algorithm more effectively by approaching it differently.  Because the basic aggregation we are doing here (Min) is communitive, we do not need to perform this in a given order.  We knew this to be true already – otherwise, we wouldn’t have been able to parallelize this routine in the first place.  With this in mind, we can treat each thread’s work independently, allowing each thread to serially process many elements with no locking, then, after all the threads are complete, “merge” together the results. This can be accomplished via a different set of overloads in the Parallel class: Parallel.ForEach<TSource,TLocal>.  The idea behind these overloads is to allow each thread to begin by initializing some local state (TLocal).  The thread will then process an entire set of items in the source collection, providing that state to the delegate which processes an individual item.  Finally, at the end, a separate delegate is run which allows you to handle merging that local state into your final results. To rewriting our routine using Parallel.ForEach<TSource,TLocal>, we need to provide three delegates instead of one.  The most basic version of this function is declared as: public static ParallelLoopResult ForEach<TSource, TLocal>( IEnumerable<TSource> source, Func<TLocal> localInit, Func<TSource, ParallelLoopState, TLocal, TLocal> body, Action<TLocal> localFinally ) The first delegate (the localInit argument) is defined as Func<TLocal>.  This delegate initializes our local state.  It should return some object we can use to track the results of a single thread’s operations. The second delegate (the body argument) is where our main processing occurs, although now, instead of being an Action<T>, we actually provide a Func<TSource, ParallelLoopState, TLocal, TLocal> delegate.  This delegate will receive three arguments: our original element from the collection (TSource), a ParallelLoopState which we can use for early termination, and the instance of our local state we created (TLocal).  It should do whatever processing you wish to occur per element, then return the value of the local state after processing is completed. The third delegate (the localFinally argument) is defined as Action<TLocal>.  This delegate is passed our local state after it’s been processed by all of the elements this thread will handle.  This is where you can merge your final results together.  This may require synchronization, but now, instead of synchronizing once per element (potentially millions of times), you’ll only have to synchronize once per thread, which is an ideal situation. Now that I’ve explained how this works, lets look at the code: // Safe, and fast! double min = double.MaxValue; // Make a "lock" object object syncObject = new object(); Parallel.ForEach( collection, // First, we provide a local state initialization delegate. () => double.MaxValue, // Next, we supply the body, which takes the original item, loop state, // and local state, and returns a new local state (item, loopState, localState) => { double value = item.PerformComputation(); return System.Math.Min(localState, value); }, // Finally, we provide an Action<TLocal>, to "merge" results together localState => { // This requires locking, but it's only once per used thread lock(syncObj) min = System.Math.Min(min, localState); } ); Although this is a bit more complicated than the previous version, it is now both thread-safe, and has minimal locking.  This same approach can be used by Parallel.For, although now, it’s Parallel.For<TLocal>.  When working with Parallel.For<TLocal>, you use the same triplet of delegates, with the same purpose and results. Also, many times, you can completely avoid locking by using a method of the Interlocked class to perform the final aggregation in an atomic operation.  The MSDN example demonstrating this same technique using Parallel.For uses the Interlocked class instead of a lock, since they are doing a sum operation on a long variable, which is possible via Interlocked.Add. By taking advantage of local state, we can use the Parallel class methods to parallelize algorithms such as aggregation, which, at first, may seem like poor candidates for parallelization.  Doing so requires careful consideration, and often requires a slight redesign of the algorithm, but the performance gains can be significant if handled in a way to avoid excessive synchronization.

    Read the article

  • Get Func-y v2.0

    - by PhubarBaz
    In my last post I talked about using funcs in C# to do async calls in WinForms to free up the main thread for the UI. In that post I demonstrated calling a method and then waiting until the value came back. Today I want to talk about calling a method and then continuing on and handling the results of the async call in a callback.The difference is that in the previous example although the UI would not lock up the user couldn't really do anything while the other thread was working because it was waiting for it to finish. This time I want to allow the user to continue to do other stuff while waiting for the thread to finish.Like before I have a service call I want to make that takes a long time to finish defined in a method called MyServiceCall. We need to define a callback method takes an IAsyncResult parameter.public ServiceCallResult MyServiceCall(int param1)...public int MyCallbackMethod(IAsyncResult ar)...We start the same way by defining a delegate to the service call method using a Func. We need to pass an AsyncCallback object into the BeginInvoke method. This will tell it to call our callback method when MyServiceCall finishes. The second parameter to BeginInvoke is the Func delegate. This will give us access to it in our callback.Func<int, ServiceCallResult> f = MyServiceCall;AsyncCallback callback =   new AsyncCallback(MyCallbackMethod);IAsyncResult async = f.BeginInvoke(23, callback, f); Now let's expand the callback method. The IAsyncResult parameter contains the Func delegate in its AsyncState property. We call EndInvoke on that Func to get the return value.public int MyCallbackMethod(IAsyncResult ar){    Func<int, ServiceCallResult> delegate =        (Func<int, ServiceCallResult>)ar.AsyncState;    ServiceCallResult result = delegate.EndInvoke(ar);}There you have it. Now you don't have to make the user wait for something that isn't critical to the loading of the page.

    Read the article

  • MVC and delegation

    - by timjver
    I am a beginning iOS programmer and use the Model-View-Controller model as a design pattern: my model doesn't know anything about my view (in order to make it compatible with any view), my view doesn't know anything about my model so they interact via my controller. A very usual way for a view to interact with the controller is through delegation: when the user interacts with the app, my view will notify my controller, which can call some methods of my model and update my view, if necessary. However, would it make sense to also make my controller the delegate of my model? I'm not convinced this is the way to go. It could be handy for my model to notify my controller of some process being finished, for example, or to ask for extra input of the user if it doesn't have enough information to complete the task. The downside of this, though, is that my controller would be the delegate for both my controller and my model, so there wouldn't be really a proper way to notify my model of changes in my view, and vice versa. (correct me if I'm wrong.) Conclusion: I don't really think it's a good idea to to have my controller to be the delegate of my model, but just being the delegate of my view would be fine. Is this the way most MVC models handle? Or is there a way to have the controller be the delegate of both the controller and the model, with proper communication between them? Like I said, I'm a beginner, so I want to do such stuff the right way immediately, rather than spending loads of hours on models that won't work anyway. :)

    Read the article

  • UITableView crashes when trying to scroll

    - by Ondrej
    Hi, I have a problem with data in UITableView. I have UIViewController, that contains UITableView outlet and few more things I am using and ... It works :) ... it works lovely, but ... I've created an RSS reader class that is using delegates to deploy the data to the table ... and once again, If I'll just create dummy data in the main controller everything works! problem is with this line: rss.delegate = self; Preview looks a little bit broken than here are those RSS reader files on Google code: (Link to the header file on GoogleCode) (Link to the implementation file on Google code) viewDidLoad function of my controller: IGDataRss20 *rss = [[[IGDataRss20 alloc] init] autorelease]; rss.delegate = self; [rss initWithContentsOfUrl:@"http://rss.cnn.com/rss/cnn_topstories.rss"]; and my delegate methods: - (void)parsingEnded:(NSArray *)result { super.data = [[NSMutableArray alloc] initWithArray:result]; NSLog(@"My Items: %d", [super.data count]); [super.table reloadData]; NSLog(@"Parsing ended"); } (void)parsingError:(NSString *)message { NSLog(@"MyMessage: %@", message); } (void)parsingStarted:(NSXMLParser *)parser { NSLog(@"Parsing started"); } Just to clarify, NSLog(@"Parsing ended"); is being executed and I have 10 items in the array. Ok, here's my RSS reader header file: @class IGDataRss20; @protocol IGDataRss20Delegate @optional (void)parsingStarted:(NSXMLParser *)parser; (void)parsingError:(NSString *)message; (void)parsingEnded:(NSArray *)result; @end @interface IGDataRss20 : NSObject { NSXMLParser *rssParser; NSMutableArray *data; NSMutableDictionary *currentItem; NSString *currentElement; id <IGDataRss20Delegate> delegate; } @property (nonatomic, retain) NSMutableArray *data; @property (nonatomic, assign) id delegate; (void)initWithContentsOfUrl:(NSString *)rssUrl; (void)initWithContentsOfData:(NSData *)inputData; @end And this RSS reader implementation file: #import "IGDataRss20.h" @implementation IGDataRss20 @synthesize data, delegate; (void)initWithContentsOfUrl:(NSString *)rssUrl { self.data = [[NSMutableArray alloc] init]; NSURL *xmlURL = [NSURL URLWithString:rssUrl]; rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL]; [rssParser setDelegate:self]; [rssParser setShouldProcessNamespaces:NO]; [rssParser setShouldReportNamespacePrefixes:NO]; [rssParser setShouldResolveExternalEntities:NO]; [rssParser parse]; } (void)initWithContentsOfData:(NSData *)inputData { self.data = [[NSMutableArray alloc] init]; rssParser = [[NSXMLParser alloc] initWithData:inputData]; [rssParser setDelegate:self]; [rssParser setShouldProcessNamespaces:NO]; [rssParser setShouldReportNamespacePrefixes:NO]; [rssParser setShouldResolveExternalEntities:NO]; [rssParser parse]; } (void)parserDidStartDocument:(NSXMLParser *)parser { [[self delegate] parsingStarted:parser]; } (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { NSString * errorString = [NSString stringWithFormat:@"Unable to parse RSS feed (Error code %i )", [parseError code]]; NSLog(@"Error parsing XML: %@", errorString); if ([parseError code] == 31) NSLog(@"Error code 31 is usually caused by encoding problem."); [[self delegate] parsingError:errorString]; } (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { currentElement = [elementName copy]; if ([elementName isEqualToString:@"item"]) currentItem = [[NSMutableDictionary alloc] init]; } (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ([elementName isEqualToString:@"item"]) { [data addObject:(NSDictionary *)[currentItem copy]]; } } (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if (![currentItem objectForKey:currentElement]) [currentItem setObject:[[[NSMutableString alloc] init] autorelease] forKey:currentElement]; [[currentItem objectForKey:currentElement] appendString:string]; } (void)parserDidEndDocument:(NSXMLParser *)parser { //NSLog(@"RSS array has %d items: %@", [data count], data); [[self delegate] parsingEnded:(NSArray *)self.data]; } (void)dealloc { [data, delegate release]; [super dealloc]; } @end Hope someone will be able to help me as I am becoming to be quite desperate, and I thought I am not already such a greenhorn :) Thanks, Ondrej

    Read the article

  • Why can't c# use inline anonymous lambdas or delegates?

    - by Samuel Meacham
    I hope I worded the title of my question appropriately. In c# I can use lambdas (as delegates), or the older delegate syntax to do this: Func<string> fnHello = () => "hello"; Console.WriteLine(fnHello()); Func<string> fnHello2 = delegate() { return "hello 2"; }; Console.WriteLine(fnHello2()); So why can't I "inline" the lambda or the delegate body, and avoid capturing it in a named variable (making it anonymous)? // Inline anonymous lambda not allowed Console.WriteLine( (() => "hello inline lambda")() ); // Inline anonymous delegate not allowed Console.WriteLine( (delegate() { return "hello inline delegate"; })() ); An example that works in javascript (just for comparison) is: alert( (function(){ return "hello inline anonymous function from javascript"; })() ); Which produces the expected alert box. UPDATE: It seems you can have an inline anonymous lambda in C#, if you cast appropriately, but the amount of ()'s starts to make it unruly. // Inline anonymous lambda with appropriate cast IS allowed Console.WriteLine( ((Func<string>)(() => "hello inline anonymous lambda"))() ); Perhaps the compiler can't infer the sig of the anonymous delegate to know which Console.WriteLine() you're trying to call? Does anyone know why this specific cast is required?

    Read the article

  • Properly declare delegation in Objective C (iPhone)

    - by Gordon Fontenot
    Ok, This has been explained a few times (I got most of the way there using this post on SO), but I am missing something. I am able to compile cleanly, and able to set the delegate as well as call methods from the delegate, but I'm getting a warning on build: No definition of protocol 'DetailViewControllerDelegate' is found I have a DetailViewController and a RootViewController only. I am calling a method in RootViewController from DetailViewController. I have the delegate set up as so: In RootViewController.h: #import "DetailViewController.h" @interface RootViewController : UITableViewController <NSFetchedResultsControllerDelegate, DetailViewControllerDelegate> //Error shows up here { //Some Stuff Here } //Some other stuff here @end In RootViewController.m I define the delegate when I create the view using detailViewController.delegate = self In DetailViewController.h: @protocol DetailViewControllerDelegate; #import "RootViewController.h" @interface DetailViewController : UITableViewController <UITextFieldDelegate> { id <DetailViewControllerDelegate> delegate; } @property (nonatomic, assign) id <DetailViewControllerDelegate> delegate; @end @protocol DetailViewControllerDelegate //some methods that reside in RootViewController.m @end I feel weird about declaring the protocol above the import in DetailViewController.h, but if I don't it doesn't build. Like I said, the methods are called fine, and there are no other errors going on. What am I missing here?

    Read the article

  • Getting around IBActions limited scope

    - by Septih
    Hello, I have an NSCollectionView and the view is an NSBox with a label and an NSButton. I want a double click or a click of the NSButton to tell the controller to perform an action with the represented object of the NSCollectionViewItem. The Item View is has been subclassed, the code is as follows: #import <Cocoa/Cocoa.h> #import "WizardItem.h" @interface WizardItemView : NSBox { id delegate; IBOutlet NSCollectionViewItem * viewItem; WizardItem * wizardItem; } @property(readwrite,retain) WizardItem * wizardItem; @property(readwrite,retain) id delegate; -(IBAction)start:(id)sender; @end #import "WizardItemView.h" @implementation WizardItemView @synthesize wizardItem, delegate; -(void)awakeFromNib { [self bind:@"wizardItem" toObject:viewItem withKeyPath:@"representedObject" options:nil]; } -(void)mouseDown:(NSEvent *)event { [super mouseDown:event]; if([event clickCount] > 1) { [delegate performAction:[wizardItem action]]; } } -(IBAction)start:(id)sender { [delegate performAction:[wizardItem action]]; } @end The problem I've run into is that as an IBAction, the only things in the scope of -start are the things that have been bound in IB, so delegate and viewItem. This means that I cannot get at the represented object to send it to the delegate. Is there a way around this limited scope or a better way or getting hold of the represented object? Thanks.

    Read the article

  • What is the delegate method that is called when an MKPinAnnotationView is touched?

    - by Jake Schwartz
    I have been searching for this all night and I have just so frustrated. When a MKPinAnnotationView is clicked, the name and the subtitle comes up. I also want to center that point on the view. I figured there was some method I had to override because the information that pops up happened without me having to code it. Hopefully this was clear enough for you all. And in the mean time, I feel like there is some hidden guide on this use of MKMaps and other classes. Either that or it is terribly documented because I am having a lot of trouble finding information. Thanks.

    Read the article

  • pushing view controller inside a tab bar from app delegate, after a notification.

    - by shani
    hi i have an app with tab bar and a navigation controller inside every tab. i have set a notification that when it lunches the user can get lunch the app by pressing the action on the alert. i want to redirect the user to one of the views inside one of the controllers. i have tried this: (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notif { NSArray *data = [notif.userInfo objectForKey:@"todoDate"]; NSInteger ind = [[data objectAtIndex:2] integerValue]; QuickViewController *detailViewController ; detailViewController = [[QuickViewController alloc] initWithNibName:@"QuickViewController" bundle:nil]; detailViewController.title = @"Edit"; detailViewController.personName = [data objectAtIndex:0]; detailViewController.DelitionDate=[data objectAtIndex:1]; detailViewController.personCategory=@"NO Category"; detailViewController.personID = ind r ; rootControler.selectedIndex = 1; [rootControler.tabBarController.selectedViewController.navigationController pushViewController:detailViewController animated:YES]; } but nothing is happening (no crashing) except of the :rootControler.selectedIndex = 1; when i tried : presentModalViewController i got the view perfectly but without the navigation controller. thanks shani

    Read the article

  • Can you have too many Delegate.BeginInvoke calls at once?

    - by stewsha
    I am cleaning up some old code converting it to work asynchronously. psDelegate.GetStops decStops = psLoadRetrieve.GetLoadStopsByLoadID; var arStops = decStops.BeginInvoke(loadID, null, null); WaitHandle.WaitAll(new WaitHandle[] { arStops.AsyncWaitHandle }); var stops = decStops.EndInvoke(arStops); Above is a single example of what I am doing for asynchronous work. My plan is to have close to 20 different delegates running. All will call BeginInvoke and wait until they are all complete before calling EndInvoke. My question is will having so many delegates running cause problems? I understand that BeginInvoke uses the ThreadPool to do work and that has a limit of 25 threads. 20 is under that limit but it is very likely that other parts of the system could be using any number of threads from the ThreadPool as well. Thanks!

    Read the article

  • Is there a way to determine the Variance of an Interface / Delegate in C# 4.0?

    - by BFree
    So now that we have generic Covariance and Contravariance on interfaces and delegates in C#, I was just curious if given a Type, you can figure out the covariance/contravariance of its generic arguments. I started trying to write my own implementation, which would look through all of the methods on a given type and see if the return types and or arguments match the types in the generic arguments. The problem is that even if I have this: public interface IFoo<T> { void DoSomething(T item); } using my logic, it LOOKS like it should be contravariant, but since we didn't actually specify: public interface IFoo<in T> { void DoSomething(T item); } (the in parameter) it isn't actually contravariant. Which leads to my question: Is there a way to determine the variance of generic parameters?

    Read the article

  • Reason for getting error in Reverse Geocoder Delegate method in the morning times.

    - by Srilakshmi
    - (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error { NSLog(@"reverseGeocoder:%@ didFailWithError:%@", geocoder, error); } This method is getting called in morning times and it is not showing the placemark while running the application in simulator. From Afternoon it is showing the placemark as "Cupertino". Will you give me the reason for not getting the placeMark at morning times?

    Read the article

  • How do I combine similar method calls into a delegate pattern?

    - by Daniel T.
    I have three methods: public void Save<T>(T entity) { using (new Transaction()) { Session.Save(entity); } } public void Create<T>(T entity) { using (new Transaction()) { Session.Create(entity); } } public void Delete<T>(T entity) { using (new Transaction()) { Session.Delete(entity); } } As you can see, the only thing that differs is the method call inside the using block. How can I rewrite this so it's something like this instead: public void Save<T>(T entity) { TransactionWrapper(Session.Save(entity)); } public void Create<T>(T entity) { TransactionWrapper(Session.Create(entity)); } public void Save<T>(T entity) { TransactionWrapper(Session.Save(entity)); } So in other words, I pass a method call as a parameter, and the TransactionWrapper method wraps a transaction around the method call.

    Read the article

  • iOS6: do we have to set rootViewController in App delegate in order to support different orientations?

    - by Centurion
    The app was perfectly fine working in iOS5 in landscape orientation. However in iOS6, it started to use portrait orientation in all view controllers. The methods shouldAutorotateToInterfaceOrientation are not called anymore. I read the new stuff about changed rotation mechanism in iOS6 and I was able to fix that by adding a line in my AppDelegate: self.window.rootViewController = _viewController _viewControler is the starting screen (Home-menu). All other view controllers implement shouldAutorotateToInterfaceOrientation method and returns YES for landscape orientations only. So, it's perfectly working solution for the app that needs to support only one orientation. However, the problem is I need one view controller (lets call it phone-VC) to be presented in portrait orientation. Now, if I want this view controller would be rotated then I need to return YES in Home-menu controller that is assigned to rootViewControler in appDelegate. However, I can't do that because this rootViewController is starting window that need to presented in landscape only, otherwise the layout with graphics in this window will break. But if I don't return YES from its shouldAutorotateToInterfaceOrientation (Home-menu) then the same method is not called in my view phone-VC that needs to be presented in portrait. Any ideas? Does the assignation of rootViewController is mandatory in AppDelegate? UPDATE: the problem exists on device (at least on iPhone4).

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >