Search Results

Search found 581 results on 24 pages for 'iterating'.

Page 11/24 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • canvas tile grid, hover effects, single tilesheet, etc

    - by user121730
    I'm currently in the process of building both the client and server side of an html5, canvas, and WebSocket game. This is what I have thus far for the client: http://jsfiddle.net/dDmTf/7/ Current obstacles The hover effect has no idea what to put back after the mouse leaves. Currently it's just drawing a "void" tile, but I can't figure out how to redraw a single tile without redrawing the whole map. How would I go about storing multiple layers within the map variable? I was considering just using a multi-dimensional array for each layer (similar to what you see as the current array), and just iterating through it, but is that really an efficient way of doing it? Side note The tile sheet being used for the jsfiddle display is only for development. I'll be replacing it as things progress in the engine. I hope you can help! Hopefully you guys can help me, I've been struggling to get through things, since I'm learning how things kind of stuff works as I go. If you guys have any pointers for my JavaScript, feel free. As I'm more or less learning advanced usage as I go, I'm sure I'm doing plenty of things wrong. Note: I will continue to update this post as the engine improves, but updating the jsfiddle link and updating the obstacles list by striking things that have been solved, or adding additions. Thanks!

    Read the article

  • clear contents from matched column of data in another sheet

    - by Peta
    I have a column of email addresses on sheet 2 col A (but I could put them on sheet 1 if it would make it easier / faster) that I want to remove from sheet 1 col D if matched (there may be 2 or more occurences of the same email to be removed/cleared). (1000s of rows in each sheet). After all day searching forums I’m getting more confused & can't find what I'm looking for. Not sure whether to use .match or .find & .ClearContents & the syntax for iterating through. Thanks very much in anticipation Peta

    Read the article

  • find files their name is smaller or greater than a given parameter

    - by Tzury Bar Yochay
    Say that in a given directory I got tzury@x200:~/Desktop/sandbox$ ls -l total 20 drwxr-xr-x 2 tzury tzury 4096 2011-03-09 10:19 N00.P000 drwxr-xr-x 2 tzury tzury 4096 2011-03-09 10:19 N00.P001 drwxr-xr-x 2 tzury tzury 4096 2011-03-09 10:19 N00.P002 drwxr-xr-x 2 tzury tzury 4096 2011-03-09 10:19 N00.P003 drwxr-xr-x 2 tzury tzury 4096 2011-03-09 10:19 N00.P004 drwxr-xr-x 2 tzury tzury 4096 2011-03-09 10:19 N01.P000 drwxr-xr-x 2 tzury tzury 4096 2011-03-09 10:19 N01.P001 drwxr-xr-x 2 tzury tzury 4096 2011-03-09 10:19 N01.P002 I seek for a bash way to grab the list of files which their name is either grater or smaller than a given parameter, for instance: $ my_finder lt N00.P003 shall return N00.P000, N00.P001 and N00.P002 $ my_finder gt N00.P003 shall return N00.P004, N01.P000, N01.P001 and N01.P002 I was thinking of iterating over for name in $(ls) and while $name != $2 but believe there are more elegant way of doing so

    Read the article

  • How to increase the disk cache of Windows 7

    - by Mark Christiaens
    Under Windows 7 (64 bit), I'm reading through 9000 moderately sized files. In total, there is more than 200 MB of data. Using Java (JDK 1.6.21) I'm iterating over the files. The first 1400 or so go at full speed but then speed drops off to 4ms per file. It turns out that the main cost is incurred simply by opening the files. I'm opening the files using new FileInputStream (and of course closing them in time to avoid file leaks). After some investigating, I see that Windows' disk cache is using only 100 MB or so of RAM although I have 8 GiB available. I've tried increasing the cache size using the CacheSet tool but any values I provide are considered out of range. I've also tried enabling the LargeSystemCache registry key but (after rebooting) the CacheSet tool still indicates I'm using 100 MB of cache (and doesn't increase during the test run). Does anybody have any suggestions to "encourage" Windows 7 to cache my 9000 files?

    Read the article

  • What is involved with writing a lobby server?

    - by Kira
    So I'm writing a Chess matchmaking system based on a Lobby view with gaming rooms, general chat etc. So far I have a working prototype but I have big doubts regarding some things I did with the server. Writing a gaming lobby server is a new programming experience to me and so I don't have a clear nor precise programming model for it. I also couldn't find a paper that describes how it should work. I ordered "Java Network Programming 3rd edition" from Amazon and still waiting for shipment, hopefully I'll find some useful examples/information in this book. Meanwhile, I'd like to gather your opinions and see how you would handle some things so I can learn how to write a server correctly. Here are a few questions off the top of my head: (may be more will come) First, let's define what a server does. It's primary functionality is to hold TCP connections with clients, listen to the events they generate and dispatch them to the other players. But is there more to it than that? Should I use one thread per client? If so, 300 clients = 300 threads. Isn't that too much? What hardware is needed to support that? And how much bandwidth does a lobby consume then approx? What kind of data structure should be used to hold the clients' sockets? How do you protect it from concurrent modification (eg. a player enters or exists the lobby) when iterating through it to dispatch an event without hurting throughput? Is ConcurrentHashMap the correct answer here, or are there some techniques I should know? When a user enters the lobby, what mechanism would you use to transfer the state of the lobby to him? And while this is happening, where do the other events bubble up? Screenshot : http://imageshack.us/photo/my-images/695/sansrewyh.png/

    Read the article

  • Should Starting a Quick Game via Google Game Services be Iterated?

    - by user46727
    I have been following this tutorial for Google Play Game Services. I am a little unclear as to if the room matching algorithm should be looped or not. Can I just initialize this process once and let it time out? Or by iterating through it is it somehow rechecking it? If anyone had the approximate timeout that would be great as well. The problem stems from the fact that even when both phones are signing into the Game Services (at virtually the same time, my friend and I logged in), the room is not registering multiple people. One time my friend's phone even entered the game map, showing that he somehow was able to progress from the room initialization process. Relevant screen update methods which I am starting this matchmaking process: @Override public void update(float deltaTime) { game.options.updateTiles(); if(!isInitiated) { startQuickGame(); } } private void startQuickGame() { // auto-match criteria to invite one random automatch opponent. // You can also specify more opponents (up to 3). if(game.mGoogleClient.isConnected() && !isInitiated) { Bundle am = RoomConfig.createAutoMatchCriteria(1, 3, 0); // build the room config: RoomConfig.Builder roomConfigBuilder = RoomConfig.builder(Network.getInstance()); roomConfigBuilder.setMessageReceivedListener(Network.getInstance()); roomConfigBuilder.setRoomStatusUpdateListener(Network.getInstance()); roomConfigBuilder.setAutoMatchCriteria(am); RoomConfig roomConfig = roomConfigBuilder.build(); // create room: Games.RealTimeMultiplayer.create(game.mGoogleClient, roomConfig); // go to game screen this.mRoom = Network.getInstance().getRoom(); if(this.mRoom != null && this.mRoom.getParticipants().size() >= 2) { game.setScreen(new MultiGameScreen(game, this.mRoom)); isInitiated = true; } } else { game.mGoogleClient.connect(); } }

    Read the article

  • Implementing Explosions

    - by Xkynar
    I want to add explosions to my 2D game, but im having a hard time with the architecture. Several game elements might be responsible for explosions, like, lets say, explosive barrels and bullets (and there might be chain reactions with close barrels). The only options i can come up with are: 1 - Having an array of explosions and treat them as a game element as important as any other Pros: Having a single array which is updated and drawn with all the other game element arrays makes it more organized and simple to update, and the explosive barrels at a first glance would be easy to create, simply by passing the explosion array as a pointer to each explosive barrel constructor Cons: It might be hard for the bullets to add an explosion to the vector, since bullets are shot by a Weapon class which is located in every mob, so lets say, if i create a new enemy and add it to the enemy array, that enemy will have a weapon and functions to be able to use it, and if i want the weapon (rocket launcher in this case) to have access to the explosions array to be able to add a new one, id have to pass the explosion array as a pointer to the enemy, which would then pass it to the weapon, which would pass it to the bullets (ugly chain). Another problem I can think of is a little more weird: If im checking the collisions between explosions and barrels (so i create a chain reaction) and i detect an explosion colliding with a barrel, if i add a new explosion while im iterating the explosions java will trow an exception. So this is kinda annoying, i cant iterate through the explosions and add a new explosion, i must do it in another way... The other way which isnt really well thought yet is to just add an explosive component to every element that might explode so that when it dies, it explodes or something, but i dont have good ways on implementing this theory either Honestly i dont like either the solutions so id like to know how is it usually done by actual game developers, sorry if my problem seems trivial and dumb.

    Read the article

  • Running an allocation simulation repeatedly breaks after the first run.

    - by Az
    Background I have a bunch of students, their desired projects and the supervisors for the respective projects. I'm running a battery of simulations to see which projects the students end up with, which will allow me to get some useful statistics required for feedback. So, this is essentially a Monte-Carlo simulation where I'm randomising the list of students and then iterating through it, allocating projects until I hit the end of the list. Then the process is repeated again. Note that, within a single session, after each successful allocation of a project the following take place: + the project is set to allocated and cannot be given to another student + the supervisor has a fixed quota of students he can supervise. This is decremented by 1 + Once the quota hits 0, all the projects from that supervisor become blocked and this has the same effect as a project being allocated Code def resetData(): for student in students.itervalues(): student.allocated_project = None for supervisor in supervisors.itervalues(): supervisor.quota = 0 for project in projects.itervalues(): project.allocated = False project.blocked = False The role of resetData() is to "reset" certain bits of the data. For example, when a project is successfully allocated, project.allocated for that project is flipped to True. While that's useful for a single run, for the next run I need to be deallocated. Above I'm iterating through thee three dictionaries - one each for students, projects and supervisors - where the information is stored. The next bit is the "Monte-Carlo" simulation for the allocation algorithm. sesh_id = 1 for trial in range(50): for id in randomiseStudents(1): stud_id = id student = students[id] if not student.preferences: # Ignoring the students who've not entered any preferences for rank in ranks: temp_proj = random.choice(list(student.preferences[rank])) if not (temp_proj.allocated or temp_proj.blocked): alloc_proj = student.allocated_proj_ref = temp_proj.proj_id alloc_proj_rank = student.allocated_rank = rank successActions(temp_proj) temp_alloc = Allocated(sesh_id, stud_id, alloc_proj, alloc_proj_rank) print temp_alloc # Explained break sesh_id += 1 resetData() # Refer to def resetData() above All randomiseStudents(1) does is randomise the order of students. Allocated is a class defined as such: class Allocated(object): def __init__(self, sesh_id, stud_id, alloc_proj, alloc_proj_rank): self.sesh_id = sesh_id self.stud_id = stud_id self.alloc_proj = alloc_proj self.alloc_proj_rank = alloc_proj_rank def __repr__(self): return str(self) def __str__(self): return "%s - Student: %s (Project: %s - Rank: %s)" %(self.sesh_id, self.stud_id, self.alloc_proj, self.alloc_proj_rank) Output and problem Now if I run this I get an output such as this (truncated): 1 - Student: 7720 (Project: 1100241 - Rank: 1) 1 - Student: 7832 (Project: 1100339 - Rank: 1) 1 - Student: 7743 (Project: 1100359 - Rank: 1) 1 - Student: 7820 (Project: 1100261 - Rank: 2) 1 - Student: 7829 (Project: 1100270 - Rank: 1) . . . 1 - Student: 7822 (Project: 1100280 - Rank: 1) 1 - Student: 7792 (Project: 1100141 - Rank: 7) 2 - Student: 7739 (Project: 1100267 - Rank: 1) 3 - Student: 7806 (Project: 1100272 - Rank: 1) . . . 45 - Student: 7806 (Project: 1100272 - Rank: 1) 46 - Student: 7714 (Project: 1100317 - Rank: 1) 47 - Student: 7930 (Project: 1100343 - Rank: 1) 48 - Student: 7757 (Project: 1100358 - Rank: 1) 49 - Student: 7759 (Project: 1100269 - Rank: 1) 50 - Student: 7778 (Project: 1100301 - Rank: 1) Basically, it works perfectly for the first run, but on subsequent runs leading upto the nth run, in this case 50, only a single student-project allocation pair is returned. Thus, the main issue I'm having trouble with is figuring out what is causing this anomalous behaviour especially since the first run works smoothly. Thanks in advance, Az

    Read the article

  • Return NSArray from NSDictionary

    - by Jon
    I have a fetch that returns an array with dictionary in it of an attribute of a core data object. Here is my previous question: Create Array From Attribute of NSObject From NSFetchResultsController This is the fetch: NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:entity]; [request setResultType:NSDictionaryResultType]; [request setReturnsDistinctResults:NO]; //set to YES if you only want unique values of the property [request setPropertiesToFetch :[NSArray arrayWithObject:@"timeStamp"]]; //name(s) of properties you want to fetch // Execute the fetch. NSError *error; NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error]; When I log the NSArray data, I get this: The content of data is( { timeStamp = "2011-06-14 21:30:03 +0000"; }, { timeStamp = "2011-06-16 21:00:18 +0000"; }, { timeStamp = "2011-06-11 21:00:18 +0000"; }, { timeStamp = "2011-06-23 19:53:35 +0000"; }, { timeStamp = "2011-06-21 19:53:35 +0000"; } ) What I want is an array with this format: [NSArray arrayWithObjects: @"2011-11-01 00:00:00 +0000", @"2011-12-01 00:00:00 +0000", nil];' Edit: This is the method for which I want to replace the data array with my new data array: - (NSArray*)calendarMonthView:(TKCalendarMonthView *)monthView marksFromDate:(NSDate *)startDate toDate:(NSDate *)lastDate { NSLog(@"calendarMonthView marksFromDate toDate"); NSLog(@"Make sure to update 'data' variable to pull from CoreData, website, User Defaults, or some other source."); // When testing initially you will have to update the dates in this array so they are visible at the // time frame you are testing the code. NSArray *data = [NSArray arrayWithObjects: @"2011-01-01 00:00:00 +0000", @"2011-12-01 00:00:00 +0000", nil]; // Initialise empty marks array, this will be populated with TRUE/FALSE in order for each day a marker should be placed on. NSMutableArray *marks = [NSMutableArray array]; // Initialise calendar to current type and set the timezone to never have daylight saving NSCalendar *cal = [NSCalendar currentCalendar]; [cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; // Construct DateComponents based on startDate so the iterating date can be created. // Its massively important to do this assigning via the NSCalendar and NSDateComponents because of daylight saving has been removed // with the timezone that was set above. If you just used "startDate" directly (ie, NSDate *date = startDate;) as the first // iterating date then times would go up and down based on daylight savings. NSDateComponents *comp = [cal components:(NSMonthCalendarUnit | NSMinuteCalendarUnit | NSYearCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSSecondCalendarUnit) fromDate:startDate]; NSDate *d = [cal dateFromComponents:comp]; // Init offset components to increment days in the loop by one each time NSDateComponents *offsetComponents = [[NSDateComponents alloc] init]; [offsetComponents setDay:1]; // for each date between start date and end date check if they exist in the data array while (YES) { // Is the date beyond the last date? If so, exit the loop. // NSOrderedDescending = the left value is greater than the right if ([d compare:lastDate] == NSOrderedDescending) { break; } // If the date is in the data array, add it to the marks array, else don't if ([data containsObject:[d description]]) { [marks addObject:[NSNumber numberWithBool:YES]]; } else { [marks addObject:[NSNumber numberWithBool:NO]]; } // Increment day using offset components (ie, 1 day in this instance) d = [cal dateByAddingComponents:offsetComponents toDate:d options:0]; } [offsetComponents release]; return [NSArray arrayWithArray:marks]; }

    Read the article

  • C#/.NET Little Wonders: The Useful But Overlooked Sets

    - by James Michael Hare
    Once again we consider some of the lesser known classes and keywords of C#.  Today we will be looking at two set implementations in the System.Collections.Generic namespace: HashSet<T> and SortedSet<T>.  Even though most people think of sets as mathematical constructs, they are actually very useful classes that can be used to help make your application more performant if used appropriately. A Background From Math In mathematical terms, a set is an unordered collection of unique items.  In other words, the set {2,3,5} is identical to the set {3,5,2}.  In addition, the set {2, 2, 4, 1} would be invalid because it would have a duplicate item (2).  In addition, you can perform set arithmetic on sets such as: Intersections: The intersection of two sets is the collection of elements common to both.  Example: The intersection of {1,2,5} and {2,4,9} is the set {2}. Unions: The union of two sets is the collection of unique items present in either or both set.  Example: The union of {1,2,5} and {2,4,9} is {1,2,4,5,9}. Differences: The difference of two sets is the removal of all items from the first set that are common between the sets.  Example: The difference of {1,2,5} and {2,4,9} is {1,5}. Supersets: One set is a superset of a second set if it contains all elements that are in the second set. Example: The set {1,2,5} is a superset of {1,5}. Subsets: One set is a subset of a second set if all the elements of that set are contained in the first set. Example: The set {1,5} is a subset of {1,2,5}. If We’re Not Doing Math, Why Do We Care? Now, you may be thinking: why bother with the set classes in C# if you have no need for mathematical set manipulation?  The answer is simple: they are extremely efficient ways to determine ownership in a collection. For example, let’s say you are designing an order system that tracks the price of a particular equity, and once it reaches a certain point will trigger an order.  Now, since there’s tens of thousands of equities on the markets, you don’t want to track market data for every ticker as that would be a waste of time and processing power for symbols you don’t have orders for.  Thus, we just want to subscribe to the stock symbol for an equity order only if it is a symbol we are not already subscribed to. Every time a new order comes in, we will check the list of subscriptions to see if the new order’s stock symbol is in that list.  If it is, great, we already have that market data feed!  If not, then and only then should we subscribe to the feed for that symbol. So far so good, we have a collection of symbols and we want to see if a symbol is present in that collection and if not, add it.  This really is the essence of set processing, but for the sake of comparison, let’s say you do a list instead: 1: // class that handles are order processing service 2: public sealed class OrderProcessor 3: { 4: // contains list of all symbols we are currently subscribed to 5: private readonly List<string> _subscriptions = new List<string>(); 6:  7: ... 8: } Now whenever you are adding a new order, it would look something like: 1: public PlaceOrderResponse PlaceOrder(Order newOrder) 2: { 3: // do some validation, of course... 4:  5: // check to see if already subscribed, if not add a subscription 6: if (!_subscriptions.Contains(newOrder.Symbol)) 7: { 8: // add the symbol to the list 9: _subscriptions.Add(newOrder.Symbol); 10: 11: // do whatever magic is needed to start a subscription for the symbol 12: } 13:  14: // place the order logic! 15: } What’s wrong with this?  In short: performance!  Finding an item inside a List<T> is a linear - O(n) – operation, which is not a very performant way to find if an item exists in a collection. (I used to teach algorithms and data structures in my spare time at a local university, and when you began talking about big-O notation you could immediately begin to see eyes glossing over as if it was pure, useless theory that would not apply in the real world, but I did and still do believe it is something worth understanding well to make the best choices in computer science). Let’s think about this: a linear operation means that as the number of items increases, the time that it takes to perform the operation tends to increase in a linear fashion.  Put crudely, this means if you double the collection size, you might expect the operation to take something like the order of twice as long.  Linear operations tend to be bad for performance because they mean that to perform some operation on a collection, you must potentially “visit” every item in the collection.  Consider finding an item in a List<T>: if you want to see if the list has an item, you must potentially check every item in the list before you find it or determine it’s not found. Now, we could of course sort our list and then perform a binary search on it, but sorting is typically a linear-logarithmic complexity – O(n * log n) - and could involve temporary storage.  So performing a sort after each add would probably add more time.  As an alternative, we could use a SortedList<TKey, TValue> which sorts the list on every Add(), but this has a similar level of complexity to move the items and also requires a key and value, and in our case the key is the value. This is why sets tend to be the best choice for this type of processing: they don’t rely on separate keys and values for ordering – so they save space – and they typically don’t care about ordering – so they tend to be extremely performant.  The .NET BCL (Base Class Library) has had the HashSet<T> since .NET 3.5, but at that time it did not implement the ISet<T> interface.  As of .NET 4.0, HashSet<T> implements ISet<T> and a new set, the SortedSet<T> was added that gives you a set with ordering. HashSet<T> – For Unordered Storage of Sets When used right, HashSet<T> is a beautiful collection, you can think of it as a simplified Dictionary<T,T>.  That is, a Dictionary where the TKey and TValue refer to the same object.  This is really an oversimplification, but logically it makes sense.  I’ve actually seen people code a Dictionary<T,T> where they store the same thing in the key and the value, and that’s just inefficient because of the extra storage to hold both the key and the value. As it’s name implies, the HashSet<T> uses a hashing algorithm to find the items in the set, which means it does take up some additional space, but it has lightning fast lookups!  Compare the times below between HashSet<T> and List<T>: Operation HashSet<T> List<T> Add() O(1) O(1) at end O(n) in middle Remove() O(1) O(n) Contains() O(1) O(n)   Now, these times are amortized and represent the typical case.  In the very worst case, the operations could be linear if they involve a resizing of the collection – but this is true for both the List and HashSet so that’s a less of an issue when comparing the two. The key thing to note is that in the general case, HashSet is constant time for adds, removes, and contains!  This means that no matter how large the collection is, it takes roughly the exact same amount of time to find an item or determine if it’s not in the collection.  Compare this to the List where almost any add or remove must rearrange potentially all the elements!  And to find an item in the list (if unsorted) you must search every item in the List. So as you can see, if you want to create an unordered collection and have very fast lookup and manipulation, the HashSet is a great collection. And since HashSet<T> implements ICollection<T> and IEnumerable<T>, it supports nearly all the same basic operations as the List<T> and can use the System.Linq extension methods as well. All we have to do to switch from a List<T> to a HashSet<T>  is change our declaration.  Since List and HashSet support many of the same members, chances are we won’t need to change much else. 1: public sealed class OrderProcessor 2: { 3: private readonly HashSet<string> _subscriptions = new HashSet<string>(); 4:  5: // ... 6:  7: public PlaceOrderResponse PlaceOrder(Order newOrder) 8: { 9: // do some validation, of course... 10: 11: // check to see if already subscribed, if not add a subscription 12: if (!_subscriptions.Contains(newOrder.Symbol)) 13: { 14: // add the symbol to the list 15: _subscriptions.Add(newOrder.Symbol); 16: 17: // do whatever magic is needed to start a subscription for the symbol 18: } 19: 20: // place the order logic! 21: } 22:  23: // ... 24: } 25: Notice, we didn’t change any code other than the declaration for _subscriptions to be a HashSet<T>.  Thus, we can pick up the performance improvements in this case with minimal code changes. SortedSet<T> – Ordered Storage of Sets Just like HashSet<T> is logically similar to Dictionary<T,T>, the SortedSet<T> is logically similar to the SortedDictionary<T,T>. The SortedSet can be used when you want to do set operations on a collection, but you want to maintain that collection in sorted order.  Now, this is not necessarily mathematically relevant, but if your collection needs do include order, this is the set to use. So the SortedSet seems to be implemented as a binary tree (possibly a red-black tree) internally.  Since binary trees are dynamic structures and non-contiguous (unlike List and SortedList) this means that inserts and deletes do not involve rearranging elements, or changing the linking of the nodes.  There is some overhead in keeping the nodes in order, but it is much smaller than a contiguous storage collection like a List<T>.  Let’s compare the three: Operation HashSet<T> SortedSet<T> List<T> Add() O(1) O(log n) O(1) at end O(n) in middle Remove() O(1) O(log n) O(n) Contains() O(1) O(log n) O(n)   The MSDN documentation seems to indicate that operations on SortedSet are O(1), but this seems to be inconsistent with its implementation and seems to be a documentation error.  There’s actually a separate MSDN document (here) on SortedSet that indicates that it is, in fact, logarithmic in complexity.  Let’s put it in layman’s terms: logarithmic means you can double the collection size and typically you only add a single extra “visit” to an item in the collection.  Take that in contrast to List<T>’s linear operation where if you double the size of the collection you double the “visits” to items in the collection.  This is very good performance!  It’s still not as performant as HashSet<T> where it always just visits one item (amortized), but for the addition of sorting this is a good thing. Consider the following table, now this is just illustrative data of the relative complexities, but it’s enough to get the point: Collection Size O(1) Visits O(log n) Visits O(n) Visits 1 1 1 1 10 1 4 10 100 1 7 100 1000 1 10 1000   Notice that the logarithmic – O(log n) – visit count goes up very slowly compare to the linear – O(n) – visit count.  This is because since the list is sorted, it can do one check in the middle of the list, determine which half of the collection the data is in, and discard the other half (binary search).  So, if you need your set to be sorted, you can use the SortedSet<T> just like the HashSet<T> and gain sorting for a small performance hit, but it’s still faster than a List<T>. Unique Set Operations Now, if you do want to perform more set-like operations, both implementations of ISet<T> support the following, which play back towards the mathematical set operations described before: IntersectWith() – Performs the set intersection of two sets.  Modifies the current set so that it only contains elements also in the second set. UnionWith() – Performs a set union of two sets.  Modifies the current set so it contains all elements present both in the current set and the second set. ExceptWith() – Performs a set difference of two sets.  Modifies the current set so that it removes all elements present in the second set. IsSupersetOf() – Checks if the current set is a superset of the second set. IsSubsetOf() – Checks if the current set is a subset of the second set. For more information on the set operations themselves, see the MSDN description of ISet<T> (here). What Sets Don’t Do Don’t get me wrong, sets are not silver bullets.  You don’t really want to use a set when you want separate key to value lookups, that’s what the IDictionary implementations are best for. Also sets don’t store temporal add-order.  That is, if you are adding items to the end of a list all the time, your list is ordered in terms of when items were added to it.  This is something the sets don’t do naturally (though you could use a SortedSet with an IComparer with a DateTime but that’s overkill) but List<T> can. Also, List<T> allows indexing which is a blazingly fast way to iterate through items in the collection.  Iterating over all the items in a List<T> is generally much, much faster than iterating over a set. Summary Sets are an excellent tool for maintaining a lookup table where the item is both the key and the value.  In addition, if you have need for the mathematical set operations, the C# sets support those as well.  The HashSet<T> is the set of choice if you want the fastest possible lookups but don’t care about order.  In contrast the SortedSet<T> will give you a sorted collection at a slight reduction in performance.   Technorati Tags: C#,.Net,Little Wonders,BlackRabbitCoder,ISet,HashSet,SortedSet

    Read the article

  • How to merge two php Doctrine 2 ArrayCollection()

    - by Throoze
    Is there any convenience method that allows me to concatenate two Doctrine ArrayCollection()? something like: $collection1 = new ArrayCollection(); $collection2 = new ArrayCollection(); $collection1->add($obj1); $collection1->add($obj2); $collection1->add($obj3); $collection2->add($obj4); $collection2->add($obj5); $collection2->add($obj6); $collection1->concat($collection2); // $collection1 now contains {$obj1, $obj2, $obj3, $obj4, $obj5, $obj6 } I just want to know if I can save me iterating over the 2nd collection and adding each element one by one to the 1st collection. Thanks!

    Read the article

  • Accessing Instance Attributes from Secondary Thread (iPhone-SDK)

    - by Travis
    I have a class with an NSDictionary attribute. Inside this class I dispatch another thread to handle NSXMLParser handling. Inside my -didStartElement, I access the dictionary in the class (to compare an element found in the XML to one in the dictionary). At this point I get undefined results. Using NSLog (I'm not advanced in XCode debugging), I see that it bombs around access of the NSDictionary. I tried just iterating the dictionary and dumping the key/values inside the didStartElement and this bombs at different keys each time. The only thing I can conclude is that something is not kosher that I'm doing with regards to accessing main thread attributes from the secondary thread. I'm somewhat new to multithreading and am not sure what the best protocol is safely access attributes from additional threads. Thanks all.

    Read the article

  • xsd validation againts xsd generated class level validation

    - by Miral
    In my project I have very big XSD file which i use to validate some XML request and response to a 3rd party. For the above scenario I can have 2 approaches 1) Create XML and then validate against give XSD 2) Create classes from XSD with the help of XSD gen tool, add xtra bit of attirbutes and use them for validation. Validation in the second way will work somewhat in this manner, a) convert xml request/response into object with XML Serialization b) validate the object with custom attributes set on each property, i.e. Pass the object to a method which will validate the object by iterating through properties and its custom attributes set on the each property, and this will return a boolean value if the object validates and that determines whether the xml request is valid or not? Now the concern which approach is good in terms of performance and anything else???

    Read the article

  • using BOOST_FOREACH with std::map

    - by kmote
    I'd like to iterate over a std::map using BOOST_FOREACH and edit the values. I can't quite get it. typedef std::pair<int, int> IdSizePair_t; std::map<int,int> mmap; mmap[1] = 1; mmap[2] = 2; mmap[3] = 3; BOOST_FOREACH( IdSizePair_t i, mmap ) i.second++; // mmap should contain {2,3,4} here Of course this doesn't change anything because I'm not iterating by reference. So I substitute this line instead (as per the example in the Boost docs): BOOST_FOREACH( IdSizePair_t &i, mmap ) and I get the compiler error: error C2440: 'initializing' : cannot convert from 'std::pair<_Ty1,_Ty2>' to 'IdSizePair_t &' with [ _Ty1=const int, _Ty2=int ] Any suggestions?

    Read the article

  • Populate Android Database From CSV file?

    - by MoMo
    Is it possible to take a csv file stored in the res/raw resource directory and use it to populate a table in the sqlite3 database? My thought was that, if there was a way to do a bulk import for the entire file into the table then that would be cleaner and faster than iterating over each line in the file and executing individual insert statements... I've found that there is a sqlite import command that allows this: http://stackoverflow.com/questions/1045910/how-can-i-import-load-a-sql-or-csv-file-into-sqlite ...but I'm having trouble applying those statements in my Android application. My first thought was to try something like the following...but no luck: db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, name TEXT)"); db.execSQL(".mode csv"); db.execSQL(".import res/raw/MyFile.csv " + TABLE_NAME); Is this possible? Should I be trying a different approach to populate my database? Thanks for you answers!

    Read the article

  • Updating onclick's string value with Greasemonkey

    - by Devin McCabe
    I'm trying to write a Greasemonkey script to update the onclick value of a bunch of links on a page. The HTML looks like this: <a onclick="OpenGenericPopup('url-99.asp','popup',500,500,false)" href="javascript:void(0)">text</a> I need to update the url-99.asp part of the Javascript into something like urlB-99.asp. In my script, I'm collecting all the links with an XPath expression and iterating through them: var allEl = document.evaluate( 'td[@class="my-class"]/a', document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null); for (var i = 0; i < allEl.snapshotLength; i++) { var el = allEl.snapshotItem(i); //something here; } If I try to alert(el.onclick), I get an error in the console: Component is not available I've read up on unsafeWindow and other Greasemonkey features, and I understand how to set an event handler for that link with a new onClick event, but how do I read the current onclick value into a string so I can manipulate it and update the element?

    Read the article

  • django deleting models and overriding delete method

    - by Mike
    I have 2 models class Vhost(models.Model): dns = models.ForeignKey(DNS) user = models.ForeignKey(User) extra = models.TextField() class ApplicationInstalled(models.Model): user = models.ForeignKey(User) added = models.DateTimeField(auto_now_add=True) app = models.ForeignKey(Application) ver = models.ForeignKey(ApplicationVersion) vhost = models.ForeignKey(Vhost) path = models.CharField(max_length=100, default="/") def delete(self): # # remove the files # print "need to remove some files" super(ApplicationInstalled, self).delete() If I do the following >>> vhost = Vhost.objects.get(id=10) >>> vhost.id 10L >>> ApplicationInstalled.objects.filter(vhost=vhost) [<ApplicationInstalled: http://wiki.jy.com/>] >>> vhost.delete() >>> ApplicationInstalled.objects.filter(vhost=vhost) [] As you can see there is an applicationinstalled object linked to vhost but when I delete the vhost, the applicationinstalled object is gone but the print never gets called. Any easy way to do this without iterating through the objects in the vhost delete?

    Read the article

  • MVVM Good Design. DataSet or a RowViewModel

    - by LnDCobra
    I have just started learning MVVM and having a dilemna. If I have a a main ViewModel and inside this model I have a number of datasets. Now should I be creating a new ViewModel for each row inside the dataset? Or expose the DataSet itself as a DependencyProperty? For now the dataset has about 20 rows inside it, and the thought of iterating through each row to create a ViewModel binding to each row.... might not be the best option for performance reasons and memory reasons in the future, like when there are 1000+ rows. Should I still go ahead and create a RowViewModel and iterate through the dataset? And have an ObservableCollection of it or just expose the dataset? Any help would be greatly appreciated.

    Read the article

  • Can I split an IEnumerable into two by a boolean criteria without two queries?

    - by SFun28
    Folks, Is it possible to split an IEnumerable into two IEnumerables using LINQ and only a single query/linq statement? In this way, I would avoid iterating through the IEnumerable twice. For example, is it possible to combine the last two statements below so allValues is only traversed once? IEnumerable<MyObj> allValues = ... List<MyObj> trues = allValues.Where( val => val.SomeProp ).ToList(); List<MyObj> falses = allValues.Where( val => !val.SomeProp ).ToList();

    Read the article

  • What's an efficient way of calculating the nearest point?

    - by Griffo
    I have objects with location data stored in Core Data, I would like to be able to fetch and display just the nearest point to the current location. I'm aware there are formulas which will calculate the distance from current lat/long to a stored lat/long, but I'm curious about the best way to perform this for a set of 1000+ points stored in Core Data. I know I could just return the points from Core Data to an array and then loop through that looking for the min value for distance between the points but I'd imagine there's a more efficient method, possibly leveraging Core Data in some way. Any insight would be appreciated. EDIT: I don't know how I missed this on my initial search but this SO question suggests just iterating through an array of Core Data objects but limiting the array size with a bounding box based on the current location. Is this the best I can do?

    Read the article

  • "Collection was modified..." Issue

    - by Tyler Murry
    Hey guys, I've got a function that checks a list of objects to see if they've been clicked and fires the OnClick events accordingly. I believe the function is working correctly, however I'm having an issue: When I hook onto one of the OnClick events and remove and insert the element into a different position in the list (typical functionality for this program), I get the "Collection was modified..." error. I believe I understand what is going on: The function cycles through each object firing OnClick events where necessary An event is fired and the object changes places in the list per the hooked function An exception is thrown for modifying the collection while iterating through it My question is, how to do I allow the function to iterate through all the objects, fire the necessary events at the proper time and still give the user the option of manipulating the object's position in the list? Thanks, Tyler

    Read the article

  • Switching Timezones in Perl's Template::Toolkit plugin Template::Plugin::Date

    - by aidan
    I have a calendar on my website, generated in Perl using Template::Toolkit and Template::Plugin::Date. It highlights the current day. I achieve this by iterating through all the dates (as I print the calendar) and comparing against the current date. Something like this: [% IF cur_date == date.format(format = '%Y-%m-%d') %] ... [% END %] It all works well until someone in Australia looks at it. (They are in a different timezone to me and my server in the UK). What's the best way to get Template::Plugin::Date to use a different time zone? It accepts a 'locale' parameter, but AFAIK this is only used for formatting.

    Read the article

  • Removing an Entity from an EntitySet during Iteration...

    - by Gregorius
    I've got this code... seems nice and elegant, but apparently the framework don't like it when i mess with a collection while iterating through it: foreach (KitGroup kg in ProductToTransfer.KitGroups) { // Remove kit groups that have been excluded by the user if (inKitGroupExclusions != null && inKitGroupExclusions.Contains(kg.KitGroupID)) ProductToTransfer.KitGroups.Remove(kg); else { // Loop through the kit items and do other stuff //... } } The error it throws when it iterates to the 2nd object in the collection is: "EntitySet was modified during enumeration" I know i could create a new collection of KitGroup objects (or even just IDs) that i want to remove, and then another loop afterwards to loop through these, and remove them from the collection, but this just seems like unnecessary extra code... can anybody suggest a more elegant way of achieving the same thing? Cheers Greg

    Read the article

  • Base class for windows service

    - by user187020
    My new project has a design in which there are number windows services for performing different tasks. I have been given a task to create base class from which all of the windows service will inherit. This base class will perform common functions like creating instances of other windows services by iterating through the config file (may be like Activator.CreateInstance), do event logging on onStart, onStop etc. and may contain some more functionality. Before I start developing stuff, wondering if there is any pattern already in place or someone has good understanding of how to implement this kind of functionality. Any help appreciated.

    Read the article

  • How to remove objects from an Enumerable collection in a loop

    - by johnc
    Duplicate Modifying A Collection While Iterating Through It Has anyone a nice pattern to allow me to get around the inability to remove objects while I loop through an enumerable collection (eg, an IList or KeyValuePairs in a dictionary) For example, the following fails, as it modifies the List being enumerated over during the foreach foreach (MyObject myObject in MyListOfMyObjects) { if (condition) MyListOfMyObjects.Remove(myObject); } In the past I have used two methods. I have replaced the foreach with a reversed for loop (so as not to change the any indexes I am looping over if I remove an object). I have also tried storing a new collection of objects to remove within to loop, then looping through that collection and removed the objects from the original collection. These work fine, but neither feels nice, and I was wondering if anyone has come up with a more elegant solution to the issue

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >