Search Results

Search found 376 results on 16 pages for 'enumerate'.

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

  • Is this GetEnumAsStrings<T>() method reinventing the wheel?

    - by Edward Tanguay
    I have a number of enums and need to get them as List<string> objects in order to enumerate through them and hence made the GetEnumAsStrings<T>() method. But it seems to me there would be an easier way. Is there not a built-in method to get an enum like this into a List<string>? using System; using System.Collections.Generic; namespace TestEnumForeach2312 { class Program { static void Main(string[] args) { List<string> testModes = StringHelpers.GetEnumAsStrings<TestModes>(); testModes.ForEach(s => Console.WriteLine(s)); Console.ReadLine(); } } public static class StringHelpers { public static List<string> GetEnumAsStrings<T>() { List<string> enumNames = new List<string>(); foreach (T item in Enum.GetValues(typeof(TestModes))) { enumNames.Add(item.ToString()); } return enumNames; } } public enum TestModes { Test, Show, Wait, Stop } }

    Read the article

  • Save PyML.classifiers.multi.OneAgainstRest(SVM()) object?

    - by Michael Aaron Safyan
    I'm using PYML to construct a multiclass linear support vector machine (SVM). After training the SVM, I would like to be able to save the classifier, so that on subsequent runs I can use the classifier right away without retraining. Unfortunately, the .save() function is not implemented for that classifier, and attempting to pickle it (both with standard pickle and cPickle) yield the following error message: pickle.PicklingError: Can't pickle : it's not found as __builtin__.PySwigObject Does anyone know of a way around this or of an alternative library without this problem? Thanks. Edit/Update I am now training and attempting to save the classifier with the following code: mc = multi.OneAgainstRest(SVM()); mc.train(dataset_pyml,saveSpace=False); for i, classifier in enumerate(mc.classifiers): filename=os.path.join(prefix,labels[i]+".svm"); classifier.save(filename); Notice that I am now saving with the PyML save mechanism rather than with pickling, and that I have passed "saveSpace=False" to the training function. However, I am still gettting an error: ValueError: in order to save a dataset you need to train as: s.train(data, saveSpace = False) However, I am passing saveSpace=False... so, how do I save the classifier(s)? P.S. The project I am using this in is pyimgattr, in case you would like a complete testable example... the program is run with "./pyimgattr.py train"... that will get you this error. Also, a note on version information: [michaelsafyan@codemage /Volumes/Storage/classes/cse559/pyimgattr]$ python Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. import PyML print PyML.__version__ 0.7.0

    Read the article

  • Python line file iteration and strange characters

    - by muckabout
    I have a huge gzipped text file which I need to read, line by line. I go with the following: for i, line in enumerate(codecs.getreader('utf-8')(gzip.open('file.gz'))): print i, line At some point late in the file, the python output diverges from the file. This is because lines are getting broken due to weird special characters that python thinks are newlines. When I open the file in 'vim', they are correct, but the suspect characters are formatted weirdly. Is there something I can do to fix this? I've tried other codecs including utf-16, latin-1. I've also tried with no codec. I looked at the file using 'od'. Sure enough, there are \n characters where they shouldn't be. But, the "wrong" ones are prepended by a weird character. I think there's some encoding here with some characters being 2-bytes, but the trailing byte being a \n if not viewed properly. If I replace: gzip.open('file.gz') With: os.popen('zcat file.gz') It works fine (and actually, quite faster). But, I'd like to know where I'm going wrong.

    Read the article

  • How do tools like Hiphop for PHP deal with heterogenous arrays?

    - by Derek Thurn
    I think HipHop for PHP is an interesting tool. It essentially converts PHP code into C++ code. Cross compiling in this manner seems like a great idea, but I have to wonder, how do they overcome the fundamental differences between the two type systems? One specific example of my general question is heterogeneous data structures. Statically typed languages don't tend to let you put arbitrary types into an array or other container because they need to be able to figure out the types on the other end. If I have a PHP array like this: $mixedBag = array("cat", 42, 8.5, false); How can this be represented in C++ code? One option would be to use void pointers (or the superior version, boost::any), but then you need to cast when you take stuff back out of the array... and I'm not at all convinced that the type inferencer can always figure out what to cast to at the other end. A better option, perhaps, would be something more like a union (or boost::variant), but then you need to enumerate all possible types at compile time... maybe possible, but certainly messy since arrays can contain arbitrarily complex entities. Does anyone know how HipHop and similar tools which go from a dynamic typing discipline to a static discipline handle these types of problems?

    Read the article

  • Comparison operators not supported for type IList when Paging data in Linq to Sql

    - by Dan
    I can understand what the error is saying - it can't compare a list. Not a problem, other than the fact that I don't know how to not have it compare a list when I want to page through a model with a list as a property. My Model: Event : IEvent int Id string Title // Other stuff.. LazyList<EventDate> Dates // The "problem" property Method which pages the data (truncated): public JsonResult JsonEventList(int skip, int take) { var query = _eventService.GetEvents(); // Do some filtering, then page data.. query = query.Skip(skip).Take(take); return Json(query.ToArray()); } As I said, the above is truncated quite a bit, leaving only the main point of the function: filter, page and return JSON'd data. The exception occurs when I enumerate (.ToArray()). The Event object is really only used to list the common objects of all the event types (Meetings, Birthdays, etc - for example). It still implements IEvent like the other types, so I can't just remove the LazyList<EventDate> Dates' property unless I no longer implementIEvent` Anyway, is there a way to avoid this? I don't really want to compare a LazyList when I page, but I do not know how to resolve this issue. Thank you in advance! :)

    Read the article

  • HTML file: add annotations through IHTMLDocument

    - by peterchen
    I need to add "annotations" to existing HTML documents - best in the form of string property values I can read & write by name. Apparently (to me), meta elements in the header seem to be the common way - i.e. adding/modifying elements like <head> <meta name="unique-id_property-name" content="property-value"/> ... </head> Question 1: Ist that "acceptable" / ok, or is there a better way to add meta data? I have a little previous experience with getting/mut(il)ating HTML contents through the document in an web browser control. For this task, I've already loaded the HTML document into a HTMLDocument object, but I'm not sure how to go on: // what I have IHTMLDocument2Ptr doc; doc.CreateInstance(__uuidof(HTMLDocument)); IPersistFile pf = doc; pf->Load(fileName, STGM_READ); // everything ok until here Questions 2: Should I be using anything else than HTMLDocument? Questions 3..N: How do I get the head element? How do I get the value of a meta element with a given name? How do I set the value of a meta element (adding the item if and only if it doesn't exist yet)? doc->all returns a collection of all tags, which I can enumerate even though count returns 0. I could scan that for head, then scan that for all meta where the name starts with a certain string, etc. - but this feels very clumsy.

    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

  • Thread Safety of C# List<T> for readers

    - by ILIA BROUDNO
    I am planning to create the list once in a static constructor and then have multiple instances of that class read it (and enumerate through it) concurrently without doing any locking. In this article http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx MS describes the issue of thread safety as follows: Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe. A List can support multiple readers concurrently, as long as the collection is not modified. Enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with one or more write accesses, the only way to ensure thread safety is to lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization. The "Enumerating through a collection is intrinsically not a thread-safe procedure." Statement is what worries me. Does this mean that it is thread safe for readers only scenario, but as long as you do not use enumeration? Or is it safe for my scenario?

    Read the article

  • BeautifulSoup: just get inside of a tag, no matter how many enclosing tags there are

    - by AP257
    I'm trying to scrape all the inner html from the <p> elements in a web page using BeautifulSoup. There are internal tags, but I don't care, I just want to get the internal text. For example, for: <p>Red</p> <p><i>Blue</i></p> <p>Yellow</p> <p>Light <b>green</b></p> How can I extract: Red Blue Yellow Light green Neither .string nor .contents[0] does what I need. Nor does .extract(), because I don't want to have to specify the internal tags in advance - I want to deal with any that may occur. Is there a 'just get the visible HTML' type of method in BeautifulSoup? ----UPDATE------ On advice, trying: p_tags = page.findAll('p',text=True) for i, p_tag in enumerate(p_tags): print str(p_tag) But that doesn't help - it just prints out: Red <i>Blue</i> Yellow Light <b>green</b>

    Read the article

  • TicTacToe strategic reduction

    - by NickLarsen
    I decided to write a small program that solves TicTacToe in order to try out the effect of some pruning techniques on a trivial game. The full game tree using minimax to solve it only ends up with 549,946 possible games. With alpha-beta pruning, the number of states required to evaluate was reduced to 18,297. Then I applied a transposition table that brings the number down to 2,592. Now I want to see how low that number can go. The next enhancement I want to apply is a strategic reduction. The basic idea is to combine states that have equivalent strategic value. For instance, on the first move, if X plays first, there is nothing strategically different (assuming your opponent plays optimally) about choosing one corner instead of another. In the same situation, the same is true of the center of the walls of the board, and the center is also significant. By reducing to significant states only, you end up with only 3 states for evaluation on the first move instead of 9. This technique should be very useful since it prunes states near the top of the game tree. This idea came from the GameShrink method created by a group at CMU, only I am trying to avoid writing the general form, and just doing what is needed to apply the technique to TicTacToe. In order to achieve this, I modified my hash function (for the transposition table) to enumerate all strategically equivalent positions (using rotation and flipping functions), and to only return the lowest of the values for each board. Unfortunately now my program thinks X can force a win in 5 moves from an empty board when going first. After a long debugging session, it became apparent to me the program was always returning the move for the lowest strategically significant move (I store the last move in the transposition table as part of my state). Is there a better way I can go about adding this feature, or a simple method for determining the correct move applicable to the current situation with what I have already done?

    Read the article

  • Enumerating computers in NT4 domain using WNetEnumResourceW (C++) or DirectoryEntry (C#)

    - by Kevin Davis
    I'm trying to enumerate computers in NT4 domains (not Active Directory) and support Unicode NetBIOS names. According to MSDN, WNetEnumResourceW is the Unicode counterpart of WNetEnumResource which to me would imply that using this would do the trick. However, I have not been able to get Unicode NetBIOS names properly using WNetEnumResourceW. I've also tried the C# rough equivalent DirectoryEntry using the WinNT: provider with no luck on Unicode names either. If I use DirectoryEntry on Active Directory (using the LDAP: provider) I do get Unicode names back. I noticed that during some debugging my code using DirectoryEntry and the WinNT: provider, the exceptions I saw were of type System.Runtime.InteropServices.COMException which tends to make me believe that this is just calling WNetEnumResourceW via COM. This web page implies that for some Net APIs the MS documentation is incomplete and possibly inaccurate which further confuses things. Additionally I've found that using the C# method which certainly results in cleaner, more understandable code also yields incomplete results in enumerating computers in domains\workgroups. Does anyone have any insight on this? Is it possible that computer acting as the WINS server is mangling the name? How would I determine this? Thanks

    Read the article

  • Trusted Folder/Drive Picker in the Browser

    - by kylepfritz
    I'd like to write a Folder/Drive picker the runs in the browser and allows a user to select files to upload to a webservice. The primary usage would be selecting folders or a whole CD and uploading them to the web with their directory structure in tact. I'm imagining something akin to Jumploader but which automatically enumerates external drives and CDs. I remember a version of Facebook's picture uploader that could do this sort of enumeration and was java-based but it has since been replaced by a much slicker plugin-based architecture. Because the application needs to run at very high trust, I think I'm limited to old-school java applets. Is there another alternative? I'm hesitant to start down the plugin route because of the necessity of writing one for both IE and Mozilla at a minimum. Are there good places to get started there? On the applet front, I built a clunky prototype to demonstrate that I can enumerate devices and list files. It runs fine in the applet viewer but I don't think I have the security settings configured correctly for it to run in the browser at full trust. Currently I don't get any drives back when I run it in the browser. Applet Prototype: public class Loader extends javax.swing.JApplet { ... private void EnumerateDrives(java.awt.event.ActionEvent evt) { File[] roots = File.listRoots(); StringBuilder b = new StringBuilder(); for (File root : roots) { b.append(root.getAbsolutePath() + ", "); } jLabel.setText(b.toString()); } } Embed Html: <p>Loader:</p> <script src="http://www.java.com/js/deployJava.js" type="text/javascript" ></script> <script> var attributes = {code:'org.exampl.Loader.Loader.class', archive:'Loader/dist/Loader.jar', width:600, height:400} ; var parameters = {}; deployJava.runApplet(attributes, parameters, '1.6');

    Read the article

  • Communicating with all network computers regardless of IP address

    - by Stephen Jennings
    I'm interested in finding a way to enumerate all accessible devices on the local network, regardless of their IP address. For example, in a 192.168.1.X network, if there is a computer with a 10.0.0.X IP address plugged into the network, I want to be able to detect that rogue computer and preferrably communicate with it as well. Both computers will be running this custom software. I realize that's a vague description, and a full solution to the problem would be lengthy, so I'm really looking for help finding the right direction to go in ("Look into using class XYZ and ABC in this manner") rather than a full implementation. The reason I want this is that our company ships imaged computers to thousands of customers, each of which have different network settings (most use the same IP scheme, but a large percentage do not, and most do not have DHCP enabled on their networks). Once the hardware arrives, we have a hard time getting it up on the network, especially if the IP scheme doesn't match, since there is no one technically oriented on-site. Ideally, I want to design some kind of console to be used from their main workstation which looks out on the network, finds all computers running our software, displays their current IP address, and allows you to change the IP. I know it's possible to do this because we sell a couple pieces of custom hardware which have exactly this capability (plug the hardware in anywhere and view it from another computer regardless of IP), but I'm hoping it's possible to do in .NET 2.0, but I'm open to using .NET 3.5 or P/Invoke if I have to.

    Read the article

  • Speed of QHash lookups using QStrings as keys.

    - by Ryan R.
    I need to draw a dynamic overlay on a QImage. The component parts of the overlay are defined in XML and parsed out to a QHash<QString, QPicture> where the QString is the name (such as "crosshairs") and the QPicture is the resolution independent drawing. I then draw components of the overlay as they are needed at a position determined during runtime. Example: I have 10 pictures in my QHash composing every possible element in a HUD. During a particular frame of video I need to draw 6 of them at different positions on the image. During the next frame something has changed and now I only need to draw 4 of them but 2 of those positions have changed. Now to my question: If I am trying to do this quickly, should I redefine my QHash as QHash<int, QPicture> and enumerate the keys to counteract the overhead caused by string comparisons; or are the comparisons not going to make a very big impact on performance? I can easily make the conversion to integer keys as the XML parser and overlay composer are completely separate classes; but I would like to use a consistent data structure across the application. Should I overcome my desire for consistency and re-usability in order to increase performance? Will it even matter very much if I do?

    Read the article

  • Most elegant way to break CSV columns into separate data structures using Python?

    - by Nick L
    I'm trying to pick up Python. As part of the learning process I'm porting a project I wrote in Java to Python. I'm at a section now where I have a list of CSV headers of the form: headers = [a, b, c, d, e, .....] and separate lists of groups that these headers should be broken up into, e.g.: headers_for_list_a = [b, c, e, ...] headers_for_list_b = [a, d, k, ...] . . . I want to take the CSV data and turn it into dict's based on these groups, e.g.: list_a = [ {b:val_1b, c:val_1c, e:val_1e, ... }, {b:val_2b, c:val_2c, e:val_2e, ... }, {b:val_3b, c:val_3c, e:val_3e, ... }, . . . ] where for example, val_1b is the first row of the 'b' column, val_3c is the third row of the 'c' column, etc. My first "Java instinct" is to do something like: for row in data: for col_num, val in enumerate(row): col_name = headers[col_num] if col_name in group_a: dict_a[col_name] = val elif headers[col_cum] in group_b: dict_b[col_name] = val ... list_a.append(dict_a) list_b.append(dict_b) ... However, this method seems inefficient/unwieldy and doesn't posses the elegance that Python programmers are constantly talking about. Is there a more "Zen-like" way I should try- keeping with the philosophy of Python?

    Read the article

  • iPhone: Low memory crash...

    - by MacTouch
    Once again I'm hunting memory leaks and other crazy mistakes in my code. :) I have a cache with frequently used files (images, data records etc. with a TTL of about one week and a size limited cache (100MB)). There are sometimes more then 15000 files in a directory. On application exit the cache writes an control file with the current cache size along with other useful information. If the applications crashes for some reason (sh.. happens sometimes) I have in such case to calculate the size of all files on application start to make sure I know the cache size. My app crashes at this point because of low memory and I have no clue why. Memory leak detector does not show any leaks at all. I do not see any too. What's wrong with the code below? Is there any other fast way to calculate the total size of all files within a directory on iPhone? Maybe without to enumerate the whole contents of the directory? The code is executed on the main thread. NSUInteger result = 0; NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSDirectoryEnumerator *dirEnum = [[[NSFileManager defaultManager] enumeratorAtPath:path] retain]; int i = 0; while ([dirEnum nextObject]) { NSDictionary *attributes = [dirEnum fileAttributes]; NSNumber* fileSize = [attributes objectForKey:NSFileSize]; result += [fileSize unsignedIntValue]; if (++i % 500 == 0) { // I tried lower values too [pool drain]; } } [dirEnum release]; dirEnum = nil; [pool release]; pool = nil; Thanks, MacTouch

    Read the article

  • Copy folder contents using VBScript

    - by LukeR
    I am trying to copy the contents of certain folders to another folder using VBScript. The goal is to enumerate a user's AD groups and then copy specific folder content based on those groups. I have code, which is currently not working. Dim Group,User,objFSO,objFolder,source,target,StrDomain StrDomain = "domain.local" FolderBase = "\\domain.local\netlogon\workgrps\icons" Set net = CreateObject("wscript.network") Struser = net.username target = "\\fs1\users\"&net.username&"\Desktop\AppIcons\" DispUserInWhichGroup() Function DispUserInWhichGroup() On Error Resume Next Set objFSO=CreateObject("Scripting.FileSystemObject") Set User = GetObject("WinNT://" & strDomain & "/" & strUser & ",user") For Each Group In User.Groups source = FolderBase & Group.name Set objFolder = GetFolder(source) For Each file in objFolder.Files objFSO.CopyFile source &"\"& file.name, target&"\"&file.name Next Next End Function This has been cobbled together from various sources, and I'm sure most of it is right, I just can't get it working completely. Any assistance would be great. Cheers.

    Read the article

  • Quickly or concisely determine the longest string per column in a row-based data collection

    - by ccornet
    Judging from the failure of my last inquiry, I need to calculate and preset the widths of a set of columns in a table that is being made into an Excel file. Unfortunately, the string data is stored in a row-based format, but the widths must be calculated in a column-based format. The data for the spreadsheets are generated from the following two collections: var dictFiles = l.Items.Cast<SPListItem>().GroupBy(foo => foo.GetSafeSPValue("Category")).ToDictionary(bar => bar.Key); StringDictionary dictCols = GetColumnsForItem(l.Title); Where l is an SPList whose title determines which columns are used. Each SPListItem corresponds to a row of data, which are sorted into separate worksheets based on Category (hence the dictionary). The second line is just a simple StringDictionary that has the column name (A, B, C, etc.) as a key and the corresponding SPListItme field display name as the corresponding value. So for each Category, I enumerate through dictFiles[somekey] to get all the rows in that sheet, and get the particular cell data using SPListItem.Fields[dictCols[colName]]. What I am asking is, is there a quick or concise method, for any one dictFiles[somekey], to retrieve a readout of the longest string in each column provided by dictCols? If it is impossible to get both quickness and conciseness, I can settle for either (since I always have the O(n*m) route of just enumerating the collection and updating an array whenever strCurrent.Length strLongest.Length). For example, if the goal table was the following... Item# Field1 Field2 Field3 1 Oarfish Atmosphere Pretty 2 Raven Radiation Adorable 3 Sunflower Flowers Cute I'd like a function which could cleanly take the collection of items 1, 2, and 3 and output in the correct order... Sunflower, Atmosphere, Adorable Using .NET 3.5 and C# 3.0.

    Read the article

  • How to alter Postgres table data based on its contents?

    - by williamjones
    This is probably a super simple question, but I'm struggling to come up with the right keywords to find it on Google. I have a Postgres table that has among its contents a column of type text named content_type. That stores what type of entry is stored in that row. There are only about 5 different types, and I decided I want to change one of them to display as something else in my application (I had been directly displaying these). It struck me that it's funny that my view is being dictated by my database model, and I decided I would convert the types being stored in my database as strings into integers, and enumerate the possible types in my application with constants that convert them into their display names. That way, if I ever got the urge to change any category names again, I could just change it with one alteration of a constant. I also have the hunch that storing integers might be somewhat more efficient than storing text in the database. First, a quick threshold question of, is this a good idea? Any feedback or anything I missed? Second, and my main question, what's the Postgres command I could enter to make an alteration like this? I'm thinking I could start by renaming the old content_type column to old_content_type and then creating a new integer column content_type. However, what command would look at a row's old_content_type and fill in the new content_type column based off of that?

    Read the article

  • Draggable cards (touch enumeration) issue

    - by glitch
    I'm trying to let a player tap, drag and release a card from a fanned stack on the screen to a 4x4 field on the board. My cards are instantiated from a custom class that inherits from the UIImageView class. I started with the Touches sample app, and I modified the event handlers for touches to iterate over my player's card hand instead of the 3 squares the sample app allows you to move on screen. Everything works, until that is, I move the card I'm dragging near another card. I'm really drawing a blank here for the logic to get the cards to behave properly. Here's my code: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { NSUInteger numTaps = [[touches anyObject] tapCount]; if(numTaps = 1) { for (UITouch *touch in touches) { [self dispatchFirstTouchAtPoint:[touch locationInView: self.boardCardView] forEvent:nil]; } } } -(void) dispatchFirstTouchAtPoint:(CGPoint)touchPoint forEvent:(UIEvent *)event { for (int i = 0; i<5; i++) { UIImageView *touchedCard = boardBuffer[i]; if (CGRectContainsPoint([touchedCard frame], touchPoint)) { [self animateFirstTouchAtPoint:touchPoint forView:touchedCard]; } } } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { NSUInteger touchCount = 0; for (UITouch *touch in touches){ [self dispatchTouchEvent:[touch view] toPosition:[touch locationInView:self.boardCardView]]; touchCount++; } } My questions are: How do I get the touch logic to disallow other cards from being picked up by a dragging finger? Is there anyway I can only enumerate the objects that are directly below a player's finger and explicitly disable other objects from responding? Thanks!

    Read the article

  • Faster or more memory-efficient solution in Python for this Codejam problem.

    - by jeroen.vangoey
    I tried my hand at this Google Codejam Africa problem (the contest is already finished, I just did it to improve my programming skills). The Problem: You are hosting a party with G guests and notice that there is an odd number of guests! When planning the party you deliberately invited only couples and gave each couple a unique number C on their invitation. You would like to single out whoever came alone by asking all of the guests for their invitation numbers. The Input: The first line of input gives the number of cases, N. N test cases follow. For each test case there will be: One line containing the value G the number of guests. One line containing a space-separated list of G integers. Each integer C indicates the invitation code of a guest. Output For each test case, output one line containing "Case #x: " followed by the number C of the guest who is alone. The Limits: 1 = N = 50 0 < C = 2147483647 Small dataset 3 = G < 100 Large dataset 3 = G < 1000 Sample Input: 3 3 1 2147483647 2147483647 5 3 4 7 4 3 5 2 10 2 10 5 Sample Output: Case #1: 1 Case #2: 7 Case #3: 5 This is the solution that I came up with: with open('A-large-practice.in') as f: lines = f.readlines() with open('A-large-practice.out', 'w') as output: N = int(lines[0]) for testcase, i in enumerate(range(1,2*N,2)): G = int(lines[i]) for guest in range(G): codes = map(int, lines[i+1].split(' ')) alone = (c for c in codes if codes.count(c)==1) output.write("Case #%d: %d\n" % (testcase+1, alone.next())) It runs in 12 seconds on my machine with the large input. Now, my question is, can this solution be improved in Python to run in a shorter time or use less memory? The analysis of the problem gives some pointers on how to do this in Java and C++ but I can't translate those solutions back to Python.

    Read the article

  • How can I generate a list of #define values from C code?

    - by djs
    I have code that has a lot of complicated #define error codes that are not easy to decode since they are nested through several levels. Is there any elegant way I can get a list of #defines with their final numerical values (or whatever else they may be)? As an example: <header1.h> #define CREATE_ERROR_CODE(class, sc, code) ((class << 16) & (sc << 8) & code)) #define EMI_MAX 16 <header2.h> #define MI_1 EMI_MAX <header3.h> #define MODULE_ERROR_CLASS MI_1 #define MODULE_ERROR_SUBCLASS 1 #define ERROR_FOO CREATE_ERROR_CODE(MODULE_ERROR_CLASS, MODULE_ERROR_SUBCLASS, 1) I would have a large number of similar #defines matching ERROR_[\w_]+ that I'd like to enumerate so that I always have a current list of error codes that the program can output. I need the numerical value because that's all the program will print out (and no, it's not an option to print out a string instead). Suggestions for gcc or any other compiler would be helpful.

    Read the article

  • How to efficiently get all instances from deeper level in Cocoa model?

    - by Johan Kool
    In my Cocoa Mac app I have an instance A which contains an unordered set of instances B which in turn has an ordered set of instances C. An instance of C can only be in one instance B and B only in one A.   I would like to have an unordered set of all instances C available on instance A. I could enumerate over all instances B each time, but that seems expensive for something I need to do often. However, I am a bit worried that keeping track of instances C in A could become cumbersome and be the cause of  inconsistencies, for example if an instance C gets removed from B but not from A.  Solution 1 Use a NSMutableSet in A and add or remove C instances whenever I do the same operation in B.  Solution 2 Use a weak referenced NSHashTable in A. When deleting a C from B, it should disappear for A as well.  Solution 3 Use key value observing in A to keep track of changes in B, and update a NSMutableSet in A accordingly.  Solution 4 Simply iterate over all instances B to create the set whenever I need it.   Which way is best? Are there any other approaches that I missed?  NB I don't and won't use CoreData for this app.

    Read the article

  • Retrieve nested list from XDocument with LINQ

    - by twreid
    Ok I want my link query to return a list of users. Below is the XML <section type="Users"> <User type="WorkerProcessUser"> <default property="UserName" value="Main"/> <default property="Password" value=""/> <default property="Description" value=""/> <default property="Group" value=""/> </User> <User type="AnonymousUser"> <default property="UserName" value="Second"/> <default property="Password" value=""/> <default property="Description" value=""/> <default property="Group" value=""/> </User> </section> And my current LINQ Query that doesn't work. doc is an XDocument var users = (from iis in doc.Descendants("section") where iis.Attribute("type").Value == "Users" from user in iis.Elements("User") from prop in user.Descendants("default") select new { Type = user.Attribute("type").Value, UserName = prop.Attribute("UserName").Value }); This does not work can anyone tell me what I need to fix? Here is my second attempt after fixing for the wrong property name. However this one does not seem to enumerate the UserName value for me when I try to use it or at least when I try to write it to the console. Also this returns 8 total results I should only have 2 results as I only have 2 users. (from iis in doc.Descendants("section") where iis.Attribute("type").Value == "Users" from user in iis.Elements("User") from prop in user.Descendants("default") select new { Type = user.Attribute("type").Value, UserName = (from name in prop.Attributes("property") where name.Value == "UserName" select name.NextAttribute.Value).ToString() });

    Read the article

  • What is the best way to properly test object equality against an array of objects?

    - by radesix
    My objective is to abort the NSXMLParser when I parse an item that already exists in cache. The basic flow of the program works like this: 1) Program starts and downloads an XML feed. Each item in the feed is represented by a custom object (FeedItem). Each FeedItem gets added to an array. 2) When the parsing is complete the contents of the array (all FeedItem objects) are archived to the disk. The next time the program is executed or the feed is refreshed by the user I begin parsing again; however, since a cache (array) now exists as each item is parsed I want to see if the object exists in the cache. If it does then I know I have downloaded all the new items and no longer need to continue parsing. What I am learning, I think, is that I can't use indexOfObject or indexOfObjectIDenticalTo: because these really seem to be checking to see that the objects are using the same memory address (thus identical). What I want to do is see if the contents of the object are equal (or at least some of the contents). I've done some research and found that I can override the IsEqual method; however, I really don't want to iterate/enumerate through the entire cache contents table for every newly parsed XML FeedItem. Is iterating through the collection and testing each one for equality the only way to do this or is there a better technique I am not aware of? Currently I am using the following code though I know it needs to change: NSUInteger index = [self.feedListCache.feedList indexOfObject:self.currentFeedItem]; if (index == NSNotFound) { }

    Read the article

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