Search Results

Search found 108 results on 5 pages for 'enumerator'.

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

  • SSIS ForEachLoop Container

    - by Leonard Mwangi
    I recently had a client request to create an SSIS package that would loop through a set of data in SQL tables to allow them to complete their data transformation processes. Knowing that Integration Services does have ForEachLoop Container, I knew the task would be easy but the moment I jumped into it I figured there was no straight forward way to accomplish the task since for each didn’t really have a loop through the table enumerator. With the capabilities of integration Services, I was still confident that it was possible it was just a matter of creativity to get it done. I set out to discover what different ForEach Loop Editor Enumerators did and settled with Variable Enumerator.  Here is how I accomplished the task. 1.       Drop your ForEach Loop Container in your WorkArea. 2.       Create a few SSIS Variable that will contain the data. Notice I have assigned MyID_ID variable a value of “TEST’ which is not evaluated either. This variable will be assigned data from the database hence allowing us to loop. 3.       In the ForEach Loop Editor’s Collection select Variable Enumerator 4.       Once this is all set, we need a mechanism to grab the data from the SQL Table and assigning it to the variable. Fig: Select Top 1 record Fig: Assign Top 1 record to the variable 5.       Now all that’s required is a house cleaning process that will update the table that you are looping so that you can be able to grab the next record   A look of the complete package

    Read the article

  • Help me understand the code snippet in c#

    - by Benny
    I am reading this blog: Pipes and filters pattern I am confused by this code snippet: public class Pipeline<T> { private readonly List<IOperation<T>> operations = new List<IOperation<T>>(); public Pipeline<T> Register(IOperation<T> operation) { operations.Add(operation); return this; } public void Execute() { IEnumerable<T> current = new List<T>(); foreach (IOperation<T> operation in operations) { current = operation.Execute(current); } IEnumerator<T> enumerator = current.GetEnumerator(); while (enumerator.MoveNext()); } } what is the purpose of this statement: while (enumerator.MoveNext());? seems this code is a noop.

    Read the article

  • When is NSEnumerator finished?

    - by samfu_1
    How do we know when enumeration is finished? The docs say: the return value of nextObject is nil when all objects have been enumerated. I was hoping to implement some "delegate-like" behavior whereby ... if (nextObject == nil) { do something because we're done! } But I see there is no such thing as: enumerationDidFinish: where in the following block could I check for the enumerator to be complete? NSArray *anArray = // ... ; NSEnumerator *enumerator = [anArray objectEnumerator]; id object; while ((object = [enumerator nextObject])) { // do something with object... }

    Read the article

  • Scripting Part 1

    - by rbishop
    Dynamic Scripting is a large topic, so let me get a couple of things out of the way first. If you aren't familiar with JavaScript, I can suggest CodeAcademy's JavaScript series. There are also many other websites and books that cover JavaScript from every possible angle.The second thing we need to deal with is JavaScript as a programming language versus a JavaScript environment running in a web browser. Many books, tutorials, and websites completely blur these two together but they are in fact completely separate. What does this really mean in relation to DRM? Since DRM isn't a web browser, there are no document, window, history, screen, or location objects. There are no events like mousedown or click. Trying to call alert('hello!') in DRM will just cause an error. Those concepts are all related to an HTML document (web page) and are part of the Browser Object Model or Document Object Model. DRM has its own object model that exposes DRM-related objects. In practice, feel free to use those sorts of tutorials or practice within your browser; Many of the concepts are directly translatable to writing scripts in DRM. Just don't try to call document.getElementById in your property definition!I think learning by example tends to work the best, so let's try getting a list of all the unique property values for a given node and its children. var uniqueValues = {}; var childEnumerator = node.GetChildEnumerator(); while(childEnumerator.MoveNext()) { var propValue = childEnumerator.GetCurrent().PropValue("Custom.testpropstr1"); print(propValue); if(propValue != null && propValue != '' && !uniqueValues[propValue]) uniqueValues[propValue] = true; } var result = ''; for(var value in uniqueValues){ result += "Found value " + value + ","; } return result;  Now lets break this down piece by piece. var uniqueValues = {}; This declares a variable and initializes it as a new empty Object. You could also have written var uniqueValues = new Object(); Why use an object here? JavaScript objects can also function as a list of keys and we'll use that later to store each property value as a key on the object. var childEnumerator = node.GetChildEnumerator(); while(childEnumerator.MoveNext()) { This gets an enumerator for the node's children. The enumerator allows us to loop through the children one by one. If we wanted to get a filtered list of children, we would instead use ChildrenWith(). When we reach the end of the child list, the enumerator will return false for MoveNext() and that will stop the loop. var propValue = childEnumerator.GetCurrent().PropValue("Custom.testpropstr1"); print(propValue); if(propValue != null && propValue != '' && !uniqueValues[propValue]) uniqueValues[propValue] = true; } This gets the node the enumerator is currently pointing at, then calls PropValue() on it to get the value of a property. We then make sure the prop value isn't null or the empty string, then we make sure the value doesn't already exist as a key. Assuming it doesn't we add it as a key with a value (true in this case because it makes checking for an existing value faster when the value exists). A quick word on the print() function. When viewing the prop grid, running an export, or performing normal DRM operations it does nothing. If you have a lot of print() calls with complicated arguments it can slow your script down slightly, but otherwise has no effect. But when using the script editor, all the output of print() will be shown in the Warnings area. This gives you an extremely useful debugging tool to see what exactly a script is doing. var result = ''; for(var value in uniqueValues){ result += "Found value " + value + ","; } return result; Now we build a string by looping through all the keys in uniqueValues and adding that value to our string. The last step is to simply return the result. Hopefully this small example demonstrates some of the core Dynamic Scripting concepts. Next time, we can try checking for node references in other hierarchies to see if they are using duplicate property values.

    Read the article

  • iPhone JSON Object

    - by Cosizzle
    Hello, I'm trying to create a application that will retrieve JSON data from an HTTP request, send it to a the application main controller as a JSON object then from there do further processing with it. Where I'm stick is actually creating a class that will serve as a JSON class in which will take a URL, grab the data, and return that object. Alone, im able to make this class work, however I can not get the class to store the object for my main controller to retrieve it. Because im fairly new to Objective-C itself, my thoughts are that im messing up within my init call: -initWithURL:(NSString *) value { responseData = [[NSMutableData data] retain]; NSString *theURL = value; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:theURL]]; [[NSURLConnection alloc] initWithRequest:request delegate:self]; return self; } The processing of the JSON object takes place here: - (void)connectionDidFinishLoading:(NSURLConnection *)connection { [connection release]; NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; [responseData release]; NSError *jsonError; SBJSON *json = [[SBJSON new] autorelease]; NSDictionary *parsedJSON = [json objectWithString:responseString error:&jsonError]; // NSArray object. listings = [parsedJSON objectForKey:@"posts"]; NSEnumerator *enumerator = [listings objectEnumerator]; NSDictionary* item; // to prove that it does work. while (item = (NSDictionary*)[enumerator nextObject]) { NSLog(@"posts:id = %@", [item objectForKey:@"id"]); NSLog(@"posts:address = %@", [item objectForKey:@"address"]); NSLog(@"posts:lat = %@", [item objectForKey:@"lat"]); NSLog(@"posts:lng = %@", [item objectForKey:@"lng"]); } [responseString release]; } Now when calling the object within the main controller I have this bit of code in the viewDidLoad method call: - (void)viewDidLoad { [super viewDidLoad]; JSON_model *jsonObj = [[JSON_model alloc] initWithURL:@"http://localhost/json/faith_json.php?user=1&format=json"]; NSEnumerator *enumerator = [[jsonObj listings] objectEnumerator]; NSDictionary* item; // while (item = (NSDictionary*)[enumerator nextObject]) { NSLog(@"posts:id = %@", [item objectForKey:@"id"]); NSLog(@"posts:address = %@", [item objectForKey:@"address"]); NSLog(@"posts:lat = %@", [item objectForKey:@"lat"]); NSLog(@"posts:lng = %@", [item objectForKey:@"lng"]); } }

    Read the article

  • Should enumerators be placed in a separate file or within another class?

    - by Icono123
    I currently have a class file with the following enumerator: using System; namespace Helper { public enum ProcessType { Word = 0, Adobe = 1, } } Or should I include the enumerator in the class where it's being used? I noticed Microsoft creates a new class file for DockStyle: using System; using System.ComponentModel; using System.Drawing.Design; namespace System.Windows.Forms { public enum DockStyle { None = 0, Top = 1, Bottom = 2, Left = 3, Right = 4,. Fill = 5, } }

    Read the article

  • We've completed the first iteration

    - by CliveT
    There are a lot of features in C# that are implemented by the compiler and not by the underlying platform. One such feature is a lambda expression. Since local variables cannot be accessed once the current method activation finishes, the compiler has to go out of its way to generate a new class which acts as a home for any variable whose lifetime needs to be extended past the activation of the procedure. Take the following example:     Random generator = new Random();     Func func = () = generator.Next(10); In this case, the compiler generates a new class called c_DisplayClass1 which is marked with the CompilerGenerated attribute. [CompilerGenerated] private sealed class c__DisplayClass1 {     // Fields     public Random generator;     // Methods     public int b__0()     {         return this.generator.Next(10);     } } Two quick comments on this: (i)    A display was the means that compilers for languages like Algol recorded the various lexical contours of the nested procedure activations on the stack. I imagine that this is what has led to the name. (ii)    It is a shame that the same attribute is used to mark all compiler generated classes as it makes it hard to figure out what they are being used for. Indeed, you could imagine optimisations that the runtime could perform if it knew that classes corresponded to certain high level concepts. We can see that the local variable generator has been turned into a field in the class, and the body of the lambda expression has been turned into a method of the new class. The code that builds the Func object simply constructs an instance of this class and initialises the fields to their initial values.     c__DisplayClass1 class2 = new c__DisplayClass1();     class2.generator = new Random();     Func func = new Func(class2.b__0); Reflector already contains code to spot this pattern of code and reproduce the form containing the lambda expression, so this is example is correctly decompiled. The use of compiler generated code is even more spectacular in the case of iterators. C# introduced the idea of a method that could automatically store its state between calls, so that it can pick up where it left off. The code can express the logical flow with yield return and yield break denoting places where the method should return a particular value and be prepared to resume.         {             yield return 1;             yield return 2;             yield return 3;         } Of course, there was already a .NET pattern for expressing the idea of returning a sequence of values with the computation proceeding lazily (in the sense that the work for the next value is executed on demand). This is expressed by the IEnumerable interface with its Current property for fetching the current value and the MoveNext method for forcing the computation of the next value. The sequence is terminated when this method returns false. The C# compiler links these two ideas together so that an IEnumerator returning method using the yield keyword causes the compiler to produce the implementation of an Iterator. Take the following piece of code.         IEnumerable GetItems()         {             yield return 1;             yield return 2;             yield return 3;         } The compiler implements this by defining a new class that implements a state machine. This has an integer state that records which yield point we should go to if we are resumed. It also has a field that records the Current value of the enumerator and a field for recording the thread. This latter value is used for optimising the creation of iterator instances. [CompilerGenerated] private sealed class d__0 : IEnumerable, IEnumerable, IEnumerator, IEnumerator, IDisposable {     // Fields     private int 1__state;     private int 2__current;     public Program 4__this;     private int l__initialThreadId; The body gets converted into the code to construct and initialize this new class. private IEnumerable GetItems() {     d__0 d__ = new d__0(-2);     d__.4__this = this;     return d__; } When the class is constructed we set the state, which was passed through as -2 and the current thread. public d__0(int 1__state) {     this.1__state = 1__state;     this.l__initialThreadId = Thread.CurrentThread.ManagedThreadId; } The state needs to be set to 0 to represent a valid enumerator and this is done in the GetEnumerator method which optimises for the usual case where the returned enumerator is only used once. IEnumerator IEnumerable.GetEnumerator() {     if ((Thread.CurrentThread.ManagedThreadId == this.l__initialThreadId)               && (this.1__state == -2))     {         this.1__state = 0;         return this;     } The state machine itself is implemented inside the MoveNext method. private bool MoveNext() {     switch (this.1__state)     {         case 0:             this.1__state = -1;             this.2__current = 1;             this.1__state = 1;             return true;         case 1:             this.1__state = -1;             this.2__current = 2;             this.1__state = 2;             return true;         case 2:             this.1__state = -1;             this.2__current = 3;             this.1__state = 3;             return true;         case 3:             this.1__state = -1;             break;     }     return false; } At each stage, the current value of the state is used to determine how far we got, and then we generate the next value which we return after recording the next state. Finally we return false from the MoveNext to signify the end of the sequence. Of course, that example was really simple. The original method body didn't have any local variables. Any local variables need to live between the calls to MoveNext and so they need to be transformed into fields in much the same way that we did in the case of the lambda expression. More complicated MoveNext methods are required to deal with resources that need to be disposed when the iterator finishes, and sometimes the compiler uses a temporary variable to hold the return value. Why all of this explanation? We've implemented the de-compilation of iterators in the current EAP version of Reflector (7). This contrasts with previous version where all you could do was look at the MoveNext method and try to figure out the control flow. There's a fair amount of things we have to do. We have to spot the use of a CompilerGenerated class which implements the Enumerator pattern. We need to go to the class and figure out the fields corresponding to the local variables. We then need to go to the MoveNext method and try to break it into the various possible states and spot the state transitions. We can then take these pieces and put them back together into an object model that uses yield return to show the transition points. After that Reflector can carry on optimising using its usual optimisations. The pattern matching is currently a little too sensitive to changes in the code generation, and we only do a limited analysis of the MoveNext method to determine use of the compiler generated fields. In some ways, it is a pity that iterators are compiled away and there is no metadata that reflects the original intent. Without it, we are always going to dependent on our knowledge of the compiler's implementation. For example, we have noticed that the Async CTP changes the way that iterators are code generated, so we'll have to do some more work to support that. However, with that warning in place, we seem to do a reasonable job of decompiling the iterators that are built into the framework. Hopefully, the EAP will give us a chance to find examples where we don't spot the pattern correctly or regenerate the wrong code, and we can improve things. Please give it a go, and report any problems.

    Read the article

  • condition in recursion - best practise

    - by mo
    hi there! what's the best practise to break a loop? my ideas were: Child Find(Parent parent, object criteria) { Child child = null; foreach(Child wannabe in parent.Childs) { if (wannabe.Match(criteria)) { child = wannabe; break; } else { child = Find(wannabe, criteria); } } return child; } or Child Find(Parent parent, object criteria) { Child child = null; var conditionator = from c parent.Childs where child != null select c; foreach(Child wannabe in conditionator) { if (wannabe.Match(criteria)) { child = wannabe; } else { child = Find(wannabe, criteria); } } return child; } or Child Find(Parent parent, object criteria) { Child child = null; var enumerator = parent.Childs.GetEnumerator(); while(child != null && enumerator.MoveNext()) { if (enumerator.Current.Match(criteria)) { child = wannabe; } else { child = Find(wannabe, criteria); } } return child; } what do u think, any better ideas? i'm looking for the niciest solution :D mo

    Read the article

  • Objective-C: fetchManagedObjectsForEntity problem

    - by Meko
    Hi.I am trying to get value from CoreData entity name Person with predicate and then comparing with new data in dictionary.But it it returns every time 0 .And it creates about 5 person with same name. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userName == %@",[flickr usernameForUserID:@"owner"]]; peopleList = (NSMutableArray *)[flickr fetchManagedObjectsForEntity:@"Person" withPredicate:predicate]; NSEnumerator *enumerator = [peopleList objectEnumerator]; Person *person; BOOL exists = FALSE; while (person = [enumerator nextObject]) { NSLog(@" Person is: %@ ", person.userName); NSLog(@"Person ID IS %@",person.userID); NSLog(@"Dict ID is %@",[dict objectForKey:@"owner"]); if([person.userID isEqualToString:[dict objectForKey:@"owner"]]) { exists = TRUE; NSLog(@"-- Person Exists : %@--", person.userName); [newPhoto setPerson:person]; } } Here peopleList returns 0 and the enumerator also 0 and it does not use if and not comparing.In my entity I have Person and Photo entities.In Person I have userName and userID attributes and also one-to many relationship with Photo entity. I think problem in predicate but i cant figure out it .

    Read the article

  • How to stop OpenGL from applying blending to certain content? (cocos2d/iPhone/OpenGL)

    - by RexOnRoids
    Supporting Info: I use cocos2d to draw a sprite (graph background) on the screen (z:-1). I then use cocos2d to draw lines/points (z:0) on top of the background -- and make some calls to OpenGL blending functions before the drawing to SMOOTH out the lines. Problem: The problem is that: aside from producing smooth lines/points, calling these OpenGL blending functions seems to degrade the underlying sprite (graph background). So there is a tradeoff: I can either have (Case 1) a nice background and choppy lines/points, or I can have (Case 2) nice smooth lines/points and a degraded background. But obviously I need both. The Code: I have included code of the draw() method of the CCLayer for both cases explained above. As you can see, the code producing the difference between Case 1 and Case 2 seems to be 1 or 2 lines involving OpenGL Blending. Case 1 -- MainScene.h (CCLayer): -(void)draw{ int lastPointX = 0; int lastPointY = 0; GLfloat colorMAX = 255.0f; GLfloat valR; GLfloat valG; GLfloat valB; if([self.myGraphManager ready]){ valR = (255.0f/colorMAX)*1.0f; valG = (255.0f/colorMAX)*1.0f; valB = (255.0f/colorMAX)*1.0f; NSEnumerator *enumerator = [[self.myGraphManager.currentCanvas graphPoints] objectEnumerator]; GraphPoint* object; while ((object = [enumerator nextObject])) { if(object.filled){ /*Commenting out the following two lines induces a problem of making it impossible to have smooth lines/points, but has merit in that it does not degrade the background sprite.*/ //glEnable (GL_BLEND); //glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint (GL_LINE_SMOOTH_HINT, GL_DONT_CARE); glEnable (GL_LINE_SMOOTH); glLineWidth(1.5f); glColor4f(valR, valG, valB, 1.0); ccDrawLine(ccp(lastPointX, lastPointY), ccp(object.position.x, object.position.y)); lastPointX = object.position.x; lastPointY = object.position.y; glPointSize(3.0f); glEnable(GL_POINT_SMOOTH); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); ccDrawPoint(ccp(lastPointX, lastPointY)); } } } } Case 2 -- MainScene.h (CCLayer): -(void)draw{ int lastPointX = 0; int lastPointY = 0; GLfloat colorMAX = 255.0f; GLfloat valR; GLfloat valG; GLfloat valB; if([self.myGraphManager ready]){ valR = (255.0f/colorMAX)*1.0f; valG = (255.0f/colorMAX)*1.0f; valB = (255.0f/colorMAX)*1.0f; NSEnumerator *enumerator = [[self.myGraphManager.currentCanvas graphPoints] objectEnumerator]; GraphPoint* object; while ((object = [enumerator nextObject])) { if(object.filled){ /*Enabling the following two lines gives nice smooth lines/points, but has a problem in that it degrades the background sprite.*/ glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint (GL_LINE_SMOOTH_HINT, GL_DONT_CARE); glEnable (GL_LINE_SMOOTH); glLineWidth(1.5f); glColor4f(valR, valG, valB, 1.0); ccDrawLine(ccp(lastPointX, lastPointY), ccp(object.position.x, object.position.y)); lastPointX = object.position.x; lastPointY = object.position.y; glPointSize(3.0f); glEnable(GL_POINT_SMOOTH); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); ccDrawPoint(ccp(lastPointX, lastPointY)); } } } }

    Read the article

  • How to stop OpenGL from applying blending to certain content? (see pics)

    - by RexOnRoids
    Supporting Info: I use cocos2d to draw a sprite (graph background) on the screen (z:-1). I then use cocos2d to draw lines/points (z:0) on top of the background -- and make some calls to OpenGL blending functions before the drawing to SMOOTH out the lines. Problem: The problem is that: aside from producing smooth lines/points, calling these OpenGL blending functions seems to "degrade" the underlying sprite (graph background). As you can see from the images below, the "degraded" background seems to be made darker and less sharp in Case 2. So there is a tradeoff: I can either have (Case 1) a nice background and choppy lines/points, or I can have (Case 2) nice smooth lines/points and a degraded background. But obviously I need both. THE QUESTION: How do I set OpenGL so as to only apply the blending to the layer with the Lines/Points in it and thus leave the background alone? The Code: I have included code of the draw() method of the CCLayer for both cases explained above. As you can see, the code producing the difference between Case 1 and Case 2 seems to be 1 or 2 lines involving OpenGL Blending. Case 1 -- MainScene.h (CCLayer): -(void)draw{ int lastPointX = 0; int lastPointY = 0; GLfloat colorMAX = 255.0f; GLfloat valR; GLfloat valG; GLfloat valB; if([self.myGraphManager ready]){ valR = (255.0f/colorMAX)*1.0f; valG = (255.0f/colorMAX)*1.0f; valB = (255.0f/colorMAX)*1.0f; NSEnumerator *enumerator = [[self.myGraphManager.currentCanvas graphPoints] objectEnumerator]; GraphPoint* object; while ((object = [enumerator nextObject])) { if(object.filled){ /*Commenting out the following two lines induces a problem of making it impossible to have smooth lines/points, but has merit in that it does not degrade the background sprite.*/ //glEnable (GL_BLEND); //glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint (GL_LINE_SMOOTH_HINT, GL_DONT_CARE); glEnable (GL_LINE_SMOOTH); glLineWidth(1.5f); glColor4f(valR, valG, valB, 1.0); ccDrawLine(ccp(lastPointX, lastPointY), ccp(object.position.x, object.position.y)); lastPointX = object.position.x; lastPointY = object.position.y; glPointSize(3.0f); glEnable(GL_POINT_SMOOTH); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); ccDrawPoint(ccp(lastPointX, lastPointY)); } } } } Case 2 -- MainScene.h (CCLayer): -(void)draw{ int lastPointX = 0; int lastPointY = 0; GLfloat colorMAX = 255.0f; GLfloat valR; GLfloat valG; GLfloat valB; if([self.myGraphManager ready]){ valR = (255.0f/colorMAX)*1.0f; valG = (255.0f/colorMAX)*1.0f; valB = (255.0f/colorMAX)*1.0f; NSEnumerator *enumerator = [[self.myGraphManager.currentCanvas graphPoints] objectEnumerator]; GraphPoint* object; while ((object = [enumerator nextObject])) { if(object.filled){ /*Enabling the following two lines gives nice smooth lines/points, but has a problem in that it degrades the background sprite.*/ glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint (GL_LINE_SMOOTH_HINT, GL_DONT_CARE); glEnable (GL_LINE_SMOOTH); glLineWidth(1.5f); glColor4f(valR, valG, valB, 1.0); ccDrawLine(ccp(lastPointX, lastPointY), ccp(object.position.x, object.position.y)); lastPointX = object.position.x; lastPointY = object.position.y; glPointSize(3.0f); glEnable(GL_POINT_SMOOTH); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); ccDrawPoint(ccp(lastPointX, lastPointY)); } } } }

    Read the article

  • Some non-generic collections

    - by Simon Cooper
    Although the collections classes introduced in .NET 2, 3.5 and 4 cover most scenarios, there are still some .NET 1 collections that don't have generic counterparts. In this post, I'll be examining what they do, why you might use them, and some things you'll need to bear in mind when doing so. BitArray System.Collections.BitArray is conceptually the same as a List<bool>, but whereas List<bool> stores each boolean in a single byte (as that's what the backing bool[] does), BitArray uses a single bit to store each value, and uses various bitmasks to access each bit individually. This means that BitArray is eight times smaller than a List<bool>. Furthermore, BitArray has some useful functions for bitmasks, like And, Xor and Not, and it's not limited to 32 or 64 bits; a BitArray can hold as many bits as you need. However, it's not all roses and kittens. There are some fundamental limitations you have to bear in mind when using BitArray: It's a non-generic collection. The enumerator returns object (a boxed boolean), rather than an unboxed bool. This means that if you do this: foreach (bool b in bitArray) { ... } Every single boolean value will be boxed, then unboxed. And if you do this: foreach (var b in bitArray) { ... } you'll have to manually unbox b on every iteration, as it'll come out of the enumerator an object. Instead, you should manually iterate over the collection using a for loop: for (int i=0; i<bitArray.Length; i++) { bool b = bitArray[i]; ... } Following on from that, if you want to use BitArray in the context of an IEnumerable<bool>, ICollection<bool> or IList<bool>, you'll need to write a wrapper class, or use the Enumerable.Cast<bool> extension method (although Cast would box and unbox every value you get out of it). There is no Add or Remove method. You specify the number of bits you need in the constructor, and that's what you get. You can change the length yourself using the Length property setter though. It doesn't implement IList. Although not really important if you're writing a generic wrapper around it, it is something to bear in mind if you're using it with pre-generic code. However, if you use BitArray carefully, it can provide significant gains over a List<bool> for functionality and efficiency of space. OrderedDictionary System.Collections.Specialized.OrderedDictionary does exactly what you would expect - it's an IDictionary that maintains items in the order they are added. It does this by storing key/value pairs in a Hashtable (to get O(1) key lookup) and an ArrayList (to maintain the order). You can access values by key or index, and insert or remove items at a particular index. The enumerator returns items in index order. However, the Keys and Values properties return ICollection, not IList, as you might expect; CopyTo doesn't maintain the same ordering, as it copies from the backing Hashtable, not ArrayList; and any operations that insert or remove items from the middle of the collection are O(n), just like a normal list. In short; don't use this class. If you need some sort of ordered dictionary, it would be better to write your own generic dictionary combining a Dictionary<TKey, TValue> and List<KeyValuePair<TKey, TValue>> or List<TKey> for your specific situation. ListDictionary and HybridDictionary To look at why you might want to use ListDictionary or HybridDictionary, we need to examine the performance of these dictionaries compared to Hashtable and Dictionary<object, object>. For this test, I added n items to each collection, then randomly accessed n/2 items: So, what's going on here? Well, ListDictionary is implemented as a linked list of key/value pairs; all operations on the dictionary require an O(n) search through the list. However, for small n, the constant factor that big-o notation doesn't measure is much lower than the hashing overhead of Hashtable or Dictionary. HybridDictionary combines a Hashtable and ListDictionary; for small n, it uses a backing ListDictionary, but switches to a Hashtable when it gets to 9 items (you can see the point it switches from a ListDictionary to Hashtable in the graph). Apart from that, it's got very similar performance to Hashtable. So why would you want to use either of these? In short, you wouldn't. Any gain in performance by using ListDictionary over Dictionary<TKey, TValue> would be offset by the generic dictionary not having to cast or box the items you store, something the graphs above don't measure. Only if the performance of the dictionary is vital, the dictionary will hold less than 30 items, and you don't need type safety, would you use ListDictionary over the generic Dictionary. And even then, there's probably more useful performance gains you can make elsewhere.

    Read the article

  • HOM with Objective C

    - by Coxer
    Hey, i am new to objective C, but i tried to use HOM in order to iterate over an NSArray and append a string to each element. here is my code: void print( NSArray *array ) { NSEnumerator *enumerator = [array objectEnumerator]; id obj; while ( nil!=(obj = [enumerator nextObject]) ) { printf( "%s\n", [[obj description] cString] ); } } int main( int argc, const char *argv[] ) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSArray *names = [[NSArray alloc] init]; NSArray *names_concat = [[NSArray alloc] init]; names = [NSArray arrayWithObjects:@"John",@"Mary",@"Bob",nil]; names_concat = [[names collect] stringByAppendingString: @" Doe"]; print(names_concat); [pool release]; } What is wrong with this code? My compiler (gcc) says NSArray may not respond to "-collect"

    Read the article

  • IEnumerable<T> ToArray usage, is it a copy or a pointer?

    - by Daniel
    I am parsing an arbitrary length byte array that is going to be passed around to a few different layers of parsing. Each parser creates a Header and a Packet payload just like any ordinary encapsulation. And my problem lies in how the encapsulation holds its packet byte array payload. Say i have a 100 byte array, and it has 3 levels of encapsulation. 3 packet objects will be created and i want to set the payload of these packets to the corresponding position in the byte array of the packet. For example lets say the payload size is 20 for all levels, then imagine it has a public byte[] Payload on each object. However the problem is that this byte[] Payload is a copy of the original 100 bytes. So i'm going to end up with 160 bytes in memory instead of 100. If it were in c++ i could just easily use a pointer however i'm writing this in c#. So i created the following class: public class PayloadSegment<T> : IEnumerable<T> { public readonly T[] Array; public readonly int Offset; public readonly int Count; public PayloadSegment(T[] array, int offset, int count) { this.Array = array; this.Offset = offset; this.Count = count; } public T this[int index] { get { if (index < 0 || index >= this.Count) throw new IndexOutOfRangeException(); else return Array[Offset + index]; } set { if (index < 0 || index >= this.Count) throw new IndexOutOfRangeException(); else Array[Offset + index] = value; } } public IEnumerator<T> GetEnumerator() { for (int i = Offset; i < Offset + Count; i++) yield return Array[i]; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { IEnumerator<T> enumerator = this.GetEnumerator(); while (enumerator.MoveNext()) { yield return enumerator.Current; } } } This way i can simply reference a position inside the original byte array but use positional indexing. However if i do something like: PayloadSegment<byte> something = new PayloadSegment<byte>(someArray, 5, 10); byte[] somethingArray = something.ToArray(); Will the somethingArray be a copy of the bytes, or a reference to the original PayloadSegment which in turn is a reference to the original byte array? Sorry it was hard to word this lol _<

    Read the article

  • Can Parallel.ForEach be used safely with CloudTableQuery

    - by knightpfhor
    I have a reasonable number of records in an Azure Table that I'm attempting to do some one time data encryption on. I thought that I could speed things up by using a Parallel.ForEach. Also because there are more than 1K records and I don't want to mess around with continuation tokens myself I'm using a CloudTableQuery to get my enumerator. My problem is that some of my records have been double encrypted and I realised that I'm not sure how thread safe the enumerator returned by CloudTableQuery.Execute() is. Has anyone else out there had any experience with this combination?

    Read the article

  • Function in xcode

    - by Joy
    I have a function which have two global variable 1.temp-a nsmutable array 2.j-a int type variable. But i cant access any global variable inside this function. I'm giving the code sample. void print( NSArray *array) { NSEnumerator *enumerator = [array objectEnumerator]; id obj; while ( nil!=(obj = [enumerator nextObject]) ) { NSString *tem=[[obj description] cString]; [temp insertObject:tem atIndex:j]; j=j+1; printf( "%s\n", [[obj description] cString]); } } Looking forward to your response. Thanks in advance..

    Read the article

  • Strings in .NET are Enumerable

    - by Scott Dorman
    It seems like there is always some confusion concerning strings in .NET. This is both from developers who are new to the Framework and those that have been working with it for quite some time. Strings in the .NET Framework are represented by the System.String class, which encapsulates the data manipulation, sorting, and searching methods you most commonly perform on string data. In the .NET Framework, you can use System.String (which is the actual type name or the language alias (for C#, string). They are equivalent so use whichever naming convention you prefer but be consistent. Common usage (and my preference) is to use the language alias (string) when referring to the data type and String (the actual type name) when accessing the static members of the class. Many mainstream programming languages (like C and C++) treat strings as a null terminated array of characters. The .NET Framework, however, treats strings as an immutable sequence of Unicode characters which cannot be modified after it has been created. Because strings are immutable, all operations which modify the string contents are actually creating new string instances and returning those. They never modify the original string data. There is one important word in the preceding paragraph which many people tend to miss: sequence. In .NET, strings are treated as a sequence…in fact, they are treated as an enumerable sequence. This can be verified if you look at the class declaration for System.String, as seen below: // Summary:// Represents text as a series of Unicode characters.public sealed class String : IEnumerable, IComparable, IComparable<string>, IEquatable<string> The first interface that String implements is IEnumerable, which has the following definition: // Summary:// Exposes the enumerator, which supports a simple iteration over a non-generic// collection.public interface IEnumerable{ // Summary: // Returns an enumerator that iterates through a collection. // // Returns: // An System.Collections.IEnumerator object that can be used to iterate through // the collection. IEnumerator GetEnumerator();} As a side note, System.Array also implements IEnumerable. Why is that important to know? Simply put, it means that any operation you can perform on an array can also be performed on a string. This allows you to write code such as the following: string s = "The quick brown fox";foreach (var c in s){ System.Diagnostics.Debug.WriteLine(c);}for (int i = 0; i < s.Length; i++){ System.Diagnostics.Debug.WriteLine(s[i]);} If you executed those lines of code in a running application, you would see the following output in the Visual Studio Output window: In the case of a string, these enumerable or array operations return a char (System.Char) rather than a string. That might lead you to believe that you can get around the string immutability restriction by simply treating strings as an array and assigning a new character to a specific index location inside the string, like this: string s = "The quick brown fox";s[2] = 'a';   However, if you were to write such code, the compiler will promptly tell you that you can’t do it: This preserves the notion that strings are immutable and cannot be changed once they are created. (Incidentally, there is no built in way to replace a single character like this. It can be done but it would require converting the string to a character array, changing the appropriate indexed location, and then creating a new string.)

    Read the article

  • NSFILEMANAGER CRASHING IN APP DELEGATE

    - by theiphoneguy
    I have this code in a method called from applicationDidFinishLaunching. It works in the simulator, but crashes on the iPhone. There are about 1,600 2KB mp3 files being copied in this operation. If I try to instantiate the app multiple times, it will eventually copy more each time until the app eventually will start without crashing. I am releasing everything I allocate. I have about 20GB disk space free on the iPhone. If I progressively comment out code and run it on the iPhone, the copyItemAtPath seems to be the suspect. (void)createCopyOfAudioFiles:(BOOL)force { @try { NSError *error; NSString *component; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSFileManager *fileManager = [[NSFileManager alloc] init]; NSEnumerator *enumerator = [[[NSBundle mainBundle]pathsForResourcesOfType:@"mp3" inDirectory:nil] objectEnumerator]; while ((component = [enumerator nextObject]) != nil) { NSArray *temp = [component componentsSeparatedByString:@".app/"]; NSString *file = [NSString stringWithFormat:@"%@", [temp objectAtIndex:1]]; NSString *writableAudioPath = [documentsDirectory stringByAppendingPathComponent:file]; BOOL success = [fileManager fileExistsAtPath:writableAudioPath]; if (success &amp;&amp; !force) { continue; } else if (success &amp;&amp; force) { success = [fileManager removeItemAtPath:writableAudioPath error:&amp;error]; } success = [fileManager copyItemAtPath:component toPath:writableAudioPath error:&amp;error]; if (!success) { @throw [NSException exceptionWithName:[error localizedDescription] reason:[error localizedFailureReason] userInfo:nil]; } } [fileManager release]; } @catch (NSException *exception) { NSLog(@"%@", exception); @throw [NSException exceptionWithName:exception.name reason:exception.reason userInfo:nil]; } @finally { } }

    Read the article

  • Maintain denormalized data with NHibernate EventListener

    - by Michael Valenty
    I have one bit of denormalized data used for performance reasons and I'm trying to maintain the data with an NHibernate event listener rather than a trigger. I'm not convinced this is the best approach, but I'm neck deep into it and I want to figure this out before moving on. I'm getting following error: System.InvalidOperationException : Collection was modified; enumeration operation may not execute. System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource) System.Collections.Generic.List`1.Enumerator.MoveNextRare() System.Collections.Generic.List`1.Enumerator.MoveNext() NHibernate.Engine.ActionQueue.ExecuteActions(IList list) NHibernate.Engine.ActionQueue.ExecuteActions() NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions (IEventSource session) NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent event) NHibernate.Impl.SessionImpl.Flush() NHibernate.Transaction.AdoTransaction.Commit() Here's the code to make happen: using (var tx = session.BeginTransaction()) { var business = session .Get<Business>(1234) .ChangeZipCodeTo("92011"); session.Update(business); tx.Commit(); // error happens here } and the event listener: public void OnPostUpdate(PostUpdateEvent @event) { var business = @event.Entity as Business; if (business != null) { var links = @event.Session .CreateQuery("select l from BusinessCategoryLink as l where l.Business.BusinessId = :businessId") .SetParameter("businessId", business.BusinessId) .List<BusinessCategoryLink>(); foreach (var link in links) { link.Location = business.Location; @event.Session.Update(link); } } }

    Read the article

  • Properly maintain sorted state of Array/Set

    - by Jeff
    I'm trying to get data out of my MOC and then create some new objects based on those objects, and put it all back together, while keeping my sort state. The securities come out of the MOC in proper order. And everything seems to be fine until I do the assignment to the game at the bottom from setWithArray. The documentation says that setWithArray removed the duplicate objects, if there are any. I'm wonder if that's messing up my data, but I don't see a good alternative. The data is ultimately being pulled out into a UITableView. When I add items to the game manually, then they stay sorted, so I don't think the breaking of the sort is beyond the scope of what I've included here. NSError *error; NSArray *allTheSecurities = [managedObjectContext executeFetchRequest:request error:&error]; if (allTheSecurities == nil) { // Handle the error. } [request release]; /**/ NSLog( @"Enumerate..." ); NSEnumerator *enumerator = [allTheSecurities objectEnumerator]; id anObject; NSMutableArray *portfolioStocks = [[NSMutableArray alloc] init]; while (anObject = [enumerator nextObject]) { NSLog( @"Iteration... %@", [anObject name] ); NSLog( @"Build a stock..." ); PortfolioStocks *this_stock = (PortfolioStocks *)[NSEntityDescription insertNewObjectForEntityForName:@"PortfolioStocks" inManagedObjectContext:context]; NSLog( @"Set a value..." ); [this_stock setSecurity:(Security *)anObject]; [this_stock setQuantity:[NSNumber numberWithInt:0]]; NSLog( @"Add to portfolioStocks..." ); [portfolioStocks addObject:this_stock]; } //Sorted properly up to here! NSLog( @"Add to portfolio..." ); [game setPortfolio:[NSSet setWithArray:portfolioStocks]]; // <-- This is where it's not sorted anymore.

    Read the article

  • Objective C Enumerate Sentences in a paragraph

    - by Faz Ya
    I would like to write an enumerator that would go through a paragraph of text and gives me one sentence at a time. I tried using stringEnumerate with the NSStringEnumerationBySentences but that simply looks at the periods and fails. For example, lets say I have the following text Block: "Senator John A. Boehner decided not to move forward. He also decided not to call the congress. The news reporter said though...." I would like my function to break down the above paragraph in the following sentences: Senator John A. Boehner decided not to move forward He also decided not to call the congress (No third sentence because it's a half a sentence) The String Enumerator with the sentence optionjust looks at the periods and breaks down that way which is wrong: Senator John A. Boehner decided not to move forward He also decided not to call the congress The news reporter said though.... Is there any library or function that I can call that does a better job at this? Thanks - (NSMutableString *) getOnlyFullSentencesFromTextBlock:(NSMutableString *) textBlock{ [textBlock enumerateSubstringsInRange:NSMakeRange(0, [textBlock length]) options:NSStringEnumerationBySentences | NSStringEnumerationLocalized usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { NSLog(@"Sentence Frag:%@", substring); }]; return textBlock; }

    Read the article

  • How to enumerate word document using office interop API?

    - by Shekhar
    Hello everyone, I want to traverse through all the elements of an word document one by one and according to type of element (header, sentence, table,image,textbox, shape, etc.) I want to process that element. I tried to search any enumerator or object which can represent elements of document in office interop API but failed to find any. API offers sentences, paragraphs, shapes collections but doesnt provide generic object which can point to next element. For example : <header of document> <plain text sentences> <table with many rows,columns> <text box> <image> <footer> (Please imagine it as a word document) So, now I want some enumerator which will first give me <header of document>, then on next iteration give me <plain text sentences>, then <table with many rows,columns> and so on. Does anyone knows how we can achieve this? Is it possible? I am using C#, visual studio 2005 and Word 2003. Thanks a lot

    Read the article

  • SQL server 2008 R2 installation error

    - by Sonia
    I have a windows 7,32 bit laptop. I am the administrator with all permissions. when I click on the SQL server 2008R2 set up file,it says : "SQL server set up has encountered the following error:Failed to retreive data for this request" click on OK. I have uninstalled all the components of SQL from control panel. I used Windows installer clean up to remove the files(which I must have not done ),but still no go. The summary.txt log says: Overall summary: Final result: Failed: see details below Exit code (Decimal): 847168662 Exit facility code: 638 Exit error code: 50326 Exit message: Failed to retrieve data for this request. Start time: 2012-05-25 14:59:15 End time: 2012-05-25 15:00:09 Requested action: RunRules Log with failure: C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20120525_145905\Detail.txt Exception help link: http%3a%2f%2fgo.microsoft.com%2ffwlink%3fLinkId%3d20476%26ProdName%3dMicrosoft%2bSQL%2bServer%26EvtSrc%3dsetup.rll%26EvtID%3d50000%26ProdVer%3d10.0.5500.0%26EvtType%3d0xEF814B06%400x92D13C14 Machine Properties: Machine name: EWAN-PC Machine processor count: 4 OS version: Windows Vista OS service pack: Service Pack 1 OS region: Australia OS language: English (United States) OS architecture: x86 Process architecture: 32 Bit OS clustered: No Package properties: Description: SQL Server Database Services 2008 SQLProductFamilyCode: {628F8F38-600E-493D-9946-F4178F20A8A9} ProductName: SQL2008 Type: RTM Version: 10 SPLevel: 0 Installation location: c:\385030d65c6ff61fb9\x86\setup\ Installation edition: EXPRESS User Input Settings: ACTION: RunRules CONFIGURATIONFILE: FEATURES: HELP: False INDICATEPROGRESS: False INSTANCENAME: QUIET: False QUIETSIMPLE: False RULES: GLOBALRULES,SqlUnsupportedProductBlocker,PerfMonCounterNotCorruptedCheck,Bids2005InstalledCheck,BlockInstallSxS,AclPermissionsFacet,FacetDomainControllerCheck,SSMS_IsInternetConnected,FacetWOW64PlatformCheck,FacetPowerShellCheck X86: False Configuration file: C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20120525_145905\ConfigurationFile.ini Detailed results: Rules with failures: Global rules: There are no scenario-specific rules. Rules report file: The rule result report file is not available. Exception summary: The following is an exception stack listing the exceptions in outermost to innermost order Inner exceptions are being indented Exception type: Microsoft.SqlServer.Management.Sdk.Sfc.EnumeratorException Message: Failed to retrieve data for this request. Data: HelpLink.ProdName = Microsoft SQL Server HelpLink.BaseHelpUrl = http://go.microsoft.com/fwlink HelpLink.LinkId = 20476 DisableWatson = true Stack: at Microsoft.SqlServer.Setup.Chainer.Workflow.PendingActions.InvokeActions(WorkflowObject metaDb, TextWriter loggingStream) at Microsoft.SqlServer.Setup.Chainer.Workflow.ActionEngine.RunActionQueue() at Microsoft.SqlServer.Setup.Chainer.Workflow.Workflow.RunWorkflow(HandleInternalException exceptionHandler) at Microsoft.SqlServer.Chainer.Setup.Setup.RunRequestedWorkflow() at Microsoft.SqlServer.Chainer.Setup.Setup.Run() at Microsoft.SqlServer.Chainer.Setup.Setup.Start() at Microsoft.SqlServer.Chainer.Setup.Setup.Main() Inner exception type: Microsoft.SqlServer.Configuration.Sco.ScoException Message: Attempted to perform an unauthorized operation. Data: WatsonData = HKEY_LOCAL_MACHINE@SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft SQL Server 10 Stack: at Microsoft.SqlServer.Configuration.Sco.InternalRegistryKey.OpenSubKey(String subkey, RegistryAccess requestedAccess) at Microsoft.SqlServer.Configuration.Sco.SqlRegistryKey.OpenSubKey(String subkey, RegistryAccess requestedAccess) at Microsoft.SqlServer.Discovery.RegistryKeyExistsPropertyValueProvider.GetPropertyValue(Object[] context) at Microsoft.SqlServer.Discovery.DiscoveryEnumObject.GetPropertyValueFromProvider(IPropertyValueProvider propertyValueProvider, String machineName, Object[] context) at Microsoft.SqlServer.Discovery.ObjectInstanceSettings.IsObjectFound(String machineName, String idFilter) at Microsoft.SqlServer.Discovery.Product.FilterObjectSet(ArrayList objects, String idFilter) at Microsoft.SqlServer.Discovery.Product.GetData(EnumResult erParent) at Microsoft.SqlServer.Management.Sdk.Sfc.Environment.GetData() at Microsoft.SqlServer.Management.Sdk.Sfc.Environment.GetData(Request req, Object ci) at Microsoft.SqlServer.Management.Sdk.Sfc.Enumerator.GetData(Object connectionInfo, Request request) at Microsoft.SqlServer.Management.Sdk.Sfc.Enumerator.Process(Object connectionInfo, Request request) Inner exception type: System.UnauthorizedAccessException Message: Attempted to perform an unauthorized operation. Stack: at Microsoft.SqlServer.Configuration.Sco.InternalRegistryKey.OpenSubKey(String subkey, RegistryAccess requestedAccess) Ineed to install SQL server 2008 R2 for one of the company softwares to work. Any immediate help will be greatly appreciated. Thanks Sonia

    Read the article

  • LINQ und ArcObjects

    - by Marko Apfel
    LINQ und ArcObjects Motivation LINQ1 (language integrated query) ist eine Komponente des Microsoft .NET Frameworks seit der Version 3.5. Es erlaubt eine SQL-ähnliche Abfrage zu verschiedenen Datenquellen wie SQL, XML u.v.m. Wie SQL auch, bietet LINQ dazu eine deklarative Notation der Problemlösung - d.h. man muss nicht im Detail beschreiben wie eine Aufgabe, sondern was überhaupt zu lösen ist. Das befreit den Entwickler abfrageseitig von fehleranfälligen Iterator-Konstrukten. Ideal wäre es natürlich auf diese Möglichkeiten auch in der ArcObjects-Programmierung mit Features zugreifen zu können. Denkbar wäre dann folgendes Konstrukt: var largeFeatures = from feature in features where (feature.GetValue("SHAPE_Area").ToDouble() > 3000) select feature; bzw. dessen Äquivalent als Lambda-Expression: var largeFeatures = features.Where(feature => (feature.GetValue("SHAPE_Area").ToDouble() > 3000)); Dazu muss ein entsprechender Provider zu Verfügung stehen, der die entsprechende Iterator-Logik managt. Dies ist leichter als man auf den ersten Blick denkt - man muss nur die gewünschten Entitäten als IEnumerable<IFeature> liefern. (Anm.: nicht wundern - die Methoden GetValue() und ToDouble() habe ich nebenbei als Erweiterungsmethoden deklariert.) Im Hintergrund baut LINQ selbständig eine Zustandsmaschine (state machine)2 auf deren Ausführung verzögert ist (deferred execution)3 - d.h. dass erst beim tatsächlichen Anfordern von Entitäten (foreach, Count(), ToList(), ..) eine Instanziierung und Verarbeitung stattfindet, obwohl die Zuweisung schon an ganz anderer Stelle erfolgte. Insbesondere bei mehrfacher Iteration durch die Entitäten reibt man sich bei den ersten Debuggings verwundert die Augen wenn der Ausführungszeiger wie von Geisterhand wieder in die Iterator-Logik springt. Realisierung Eine ganz knappe Logik zum Konstruieren von IEnumerable<IFeature> lässt sich mittels Durchlaufen eines IFeatureCursor realisieren. Dazu werden die einzelnen Feature mit yield ausgegeben. Der einfachen Verwendung wegen, habe ich die Logik in eine Erweiterungsmethode GetFeatures() für IFeatureClass aufgenommen: public static IEnumerable GetFeatures(this IFeatureClass featureClass, IQueryFilter queryFilter, RecyclingPolicy policy) { IFeatureCursor featureCursor = featureClass.Search(queryFilter, RecyclingPolicy.Recycle == policy); IFeature feature; while (null != (feature = featureCursor.NextFeature())) { yield return feature; } //this is skipped in unit tests with cursor-mock if (Marshal.IsComObject(featureCursor)) { Marshal.ReleaseComObject(featureCursor); } } Damit kann man sich nun ganz einfach die IEnumerable<IFeature> erzeugen lassen: IEnumerable features = _featureClass.GetFeatures(RecyclingPolicy.DoNotRecycle); Etwas aufpassen muss man bei der Verwendung des "Recycling-Cursors". Nach einer verzögerten Ausführung darf im selben Kontext nicht erneut über die Features iteriert werden. In diesem Fall wird nämlich nur noch der Inhalt des letzten (recycelten) Features geliefert und alle Features sind innerhalb der Menge gleich. Kritisch würde daher das Konstrukt largeFeatures.ToList(). ForEach(feature => Debug.WriteLine(feature.OID)); weil ToList() schon einmal durch die Liste iteriert und der Cursor somit einmal durch die Features bewegt wurde. Die Erweiterungsmethode ForEach liefert dann immer dasselbe Feature. In derartigen Situationen darf also kein Cursor mit Recycling verwendet werden. Ein mehrfaches Ausführen von foreach ist hingegen kein Problem weil dafür jedes Mal die Zustandsmaschine neu instanziiert wird und somit der Cursor neu durchlaufen wird – das ist die oben schon erwähnte Magie. Ausblick Nun kann man auch einen Schritt weiter gehen und ganz eigene Implementierungen für die Schnittstelle IEnumerable<IFeature> in Angriff nehmen. Dazu müssen nur die Methode und das Property zum Zugriff auf den Enumerator ausprogrammiert werden. Im Enumerator selbst veranlasst man in der Reset()-Methode das erneute Ausführen der Suche – dazu übergibt man beispielsweise ein entsprechendes Delegate in den Konstruktur: new FeatureEnumerator( _featureClass, featureClass => featureClass.Search(_filter, isRecyclingCursor)); und ruft dieses beim Reset auf: public void Reset() {     _featureCursor = _resetCursor(_t); } Auf diese Art und Weise können Enumeratoren für völlig verschiedene Szenarien implementiert werden, die clientseitig restlos identisch nach obigen Schema verwendet werden. Damit verschmelzen Cursors, SelectionSets u.s.w. zu einer einzigen Materie und die Wiederverwendbarkeit von Code steigt immens. Obendrein lässt sich ein IEnumerable in automatisierten Unit-Tests sehr einfach mocken - ein großer Schritt in Richtung höherer Software-Qualität.4 Fazit Nichtsdestotrotz ist Vorsicht mit diesen Konstrukten in performance-relevante Abfragen geboten. Dadurch dass im Hintergrund eine Zustandsmaschine verwalten wird, entsteht einiges an Overhead dessen Verarbeitung zusätzliche Zeit kostet - ca. 20 bis 100 Prozent. Darüber hinaus ist auch das Arbeiten ohne Recycling schnell ein Performance-Gap. Allerdings ist deklarativer LINQ-Code viel eleganter, fehlerfreier und wartungsfreundlicher als das manuelle Iterieren, Vergleichen und Aufbauen einer Ergebnisliste. Der Code-Umfang verringert sich erfahrungsgemäß im Schnitt um 75 bis 90 Prozent! Dafür warte ich gerne ein paar Millisekunden länger. Wie so oft muss abgewogen werden zwischen Wartbarkeit und Performance - wobei für mich Wartbarkeit zunehmend an Priorität gewinnt. Zumeist ist sowieso nicht der Code sondern der Anwender die Bremse im Prozess. Demo-Quellcode support.esri.de   [1] Wikipedia: LINQ http://de.wikipedia.org/wiki/LINQ [2] Wikipedia: Zustandsmaschine http://de.wikipedia.org/wiki/Endlicher_Automat [3] Charlie Calverts Blog: LINQ and Deferred Execution http://blogs.msdn.com/b/charlie/archive/2007/12/09/deferred-execution.aspx [4] Clean Code Developer - gelber Grad/Automatisierte Unit Tests http://www.clean-code-developer.de/Gelber-Grad.ashx#Automatisierte_Unit_Tests_8

    Read the article

  • How to break out of if statement

    - by TheBroodian
    I'm not sure if the title is exactly an accurate representation of what I'm actually trying to ask, but that was the best I could think of. I am experiencing an issue with my character class. I have developed a system so that he can perform chain attacks, and something that was important to me was that 1)button presses during the process of an attack wouldn't interrupt the character, and 2) at the same time, button presses should be stored so that the player can smoothly queue up chain attacks in the middle of one so that gameplay doesn't feel rigid or unresponsive. This all begins when the player presses the punch button. Upon pressing the punch button, the game checks the state of the dpad at the moment of the button press, and then translates the resulting combined buttons into an int which I use as an enumerator relating to a punch method for the character. The enumerator is placed into a List so that the next time the character's Update() method is called, it will execute the next punch in the list. It only executes the next punch if my character is flagged with acceptInput as true. All attacks flag acceptInput as false, to prevent the interruption of attacks, and then at the end of an attack, acceptInput is set back to true. While accepting input, all other actions are polled for, i.e. jumping, running, etc. In runtime, if I attack, and then queue up another attack behind it (by pressing forward+punch) I can see the second attack visibly execute, which should flag acceptInput as false, yet it gets interrupted and my character will stop punching and start running if I am still holding down the dpad. Included is some code for context. This is the input region for my character. //Placed this outside the if (acceptInput) tree because I want it //to be taken into account whether we are accepting input or not. //This will queue up attacks, which will only be executed if we are accepting input. //This creates a desired effect that helps control the character in a // smoother fashion for the player. if (Input.justPressed(buttonManager.Punch)) { int dpadPressed = Input.DpadState(0); if (attackBuffer.Count() < 1) { attackBuffer.Add(CheckPunch(dpadPressed)); } else { attackBuffer.Clear(); attackBuffer.Add(CheckPunch(dpadPressed)); } } if (acceptInput) { if (attackBuffer.Count() > 0) { ExecutePunch(attackBuffer[0]); attackBuffer.RemoveAt(0); } //If D-Pad left is being held down. if (Input.DpadDirectionHeld(0, buttonManager.Left)) { flipped = false; if (onGround) { newAnimation = "run"; } velocity = new Vector2(velocity.X - acceleration, velocity.Y); if (walking == true && velocity.X <= -walkSpeed) { velocity.X = -walkSpeed; } else if (walking == false && velocity.X <= -maxSpeed) { velocity.X = -maxSpeed; } } //If D-Pad right is being held down. if (Input.DpadDirectionHeld(0, buttonManager.Right)) { flipped = true; if (onGround) { newAnimation = "run"; } velocity = new Vector2(velocity.X + acceleration, velocity.Y); if (walking == true && velocity.X >= walkSpeed) { velocity.X = walkSpeed; } else if (walking == false && velocity.X >= maxSpeed) { velocity.X = maxSpeed; } } //If jump/accept button is pressed. if (Input.justPressed(buttonManager.JumpAccept)) { if (onGround) { Jump(); } } //If toggle element next button is pressed. if (Input.justPressed(buttonManager.ToggleElementNext)) { if (elements.Count != 0) { elementInUse++; if (elementInUse >= elements.Count) { elementInUse = 0; } } } //If toggle element last button is pressed. if (Input.justPressed(buttonManager.ToggleElementLast)) { if (elements.Count != 0) { elementInUse--; if (elementInUse < 0) { elementInUse = Convert.ToSByte(elements.Count() - 1); } } } //If character is in the process of jumping. if (jumping == true) { if (Input.heldDown(buttonManager.JumpAccept)) { velocity.Y -= fallSpeed.Y; maxJumpTime -= elapsed; } if (Input.justReleased(buttonManager.JumpAccept) || maxJumpTime <= 0) { jumping = false; maxJumpTime = 0; } } //Won't execute abilities if input isn't being accepted. foreach (PlayerAbility ability in playerAbilities) { if (buffer.Matches(ability)) { if (onGround) { ability.Activate(); } if (!onGround && ability.UsableInAir) { ability.Activate(); } else if (!onGround && !ability.UsableInAir) { buffer.Clear(); } } } } When the attackBuffer calls ExecutePunch(int) method, ExecutePunch() will call one of the following methods: private void NeutralPunch1() //0 { acceptInput = false; busy = true; newAnimation = "punch1"; numberOfAttacks++; timeSinceLastAttack = 0; } private void ForwardPunch2(bool toLeft) //true == 7, false == 4 { forwardPunch2Timer = 0f; acceptInput = false; busy = true; newAnimation = "punch2begin"; numberOfAttacks++; timeSinceLastAttack = 0; if (toLeft) { velocity.X -= 800; } if (!toLeft) { velocity.X += 800; } } I assume the attack is being interrupted due to the fact that ExecutePunch() is in the same if statement as running, but I haven't been able to find a suitable way to stop this happening. Thank you ahead of time for reading this, I apologize for it having become so long winded.

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >