Search Results

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

Page 1/24 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Iterating Over Params Hash

    - by Joe Clark
    I'm having an extremely frustrating time getting some images to upload. They are obviously being uploaded as rack/multipart but the way that I'm iterating over my params hash must be causing the problem. I could REALLY use some help, so I can stop pulling out my hair. So I've got a params hash that looks like this: Parameters: {"commit"=>"Submit", "sighting_report"=>[{"number_seen"=>"1", "picture"=>#<File:/var/folders/IX/IXXrbzpCHkq68OuyY-yoI++++TI/-Tmp-/RackMultipart.85991.5>, "species_id"=>"2"}], "authenticity_token"=>"u0eN5MAfvGWtfEzrqBt4qfrL54VJ9SGX0jFLZCJ8iRM=", "sighting"=>{"sighting_date(2i)"=>"6", "name"=>"", "sighting_date(3i)"=>"5", "county"=>"0", "notes"=>"", "location"=>"", "sighting_date(1i)"=>"2010", "email"=>""}} My form can have multiple sighting reports with multiple pictures in each sighting report. Here's my controller code: def create_multiple @report = Report.new @report.name = params[:sighting]["name"] @report.sighting_date = Date.civil(params[:sighting][:"sighting_date(1i)"].to_i, params[:sighting][:"sighting_date(2i)"].to_i, params[:sighting][:"sighting_date(3i)"].to_i) @report.county_id = params[:sighting][:county] @report.location = params[:sighting][:location] @report.notes = params[:sighting][:notes] @report.email = params[:sighting][:email] @report.save! @report.reload for sr in params[:sighting_report] do sighting = SightingReport.new sighting.report_id = @report.id sighting.species_id = sr[:species_id] sighting.number_seen = sr[:number_seen] sighting.save if sr[:picture] sighting.reload for pic in sr[:picture] do p = SpeciesPic.new p.uploaded_picture = pic p.species_id = sighting.species_id p.report_id = @report.id p.save! end end end redirect_to :action => 'new_multiple' end

    Read the article

  • Iterating through a JSON object.

    - by user327508
    [ { "title": "Baby (Feat. Ludacris) - Justin Bieber", "description": "Baby (Feat. Ludacris) by Justin Bieber on Grooveshark", "link": "http://listen.grooveshark.com/s/Baby+Feat+Ludacris+/2Bqvdq", "pubDate": "Wed, 28 Apr 2010 02:37:53 -0400", "pubTime": 1272436673, "TinyLink": "http://tinysong.com/d3wI", "SongID": "24447862", "SongName": "Baby (Feat. Ludacris)", "ArtistID": "1118876", "ArtistName": "Justin Bieber", "AlbumID": "4104002", "AlbumName": "My World (Part II);\nhttp://tinysong.com/gQsw", "LongLink": "11578982", "GroovesharkLink": "11578982", "Link": "http://tinysong.com/d3wI" }, { "title": "Feel Good Inc - Gorillaz", "description": "Feel Good Inc by Gorillaz on Grooveshark", "link": "http://listen.grooveshark.com/s/Feel+Good+Inc/1UksmI", "pubDate": "Wed, 28 Apr 2010 02:25:30 -0400", "pubTime": 1272435930 } ] That is the current JSON object I have. I am now trying to iterate through it to get the import stuff like title and link. This is where I am having trouble I cant seem to get to the content that is past the ":" i tried doing dictionary way couldn't get it. def getLastSong(user,limit): base_url = 'http://gsuser.com/lastSong/' user_url = base_url + str(user) + '/' + str(limit) + "/" raw = urllib.urlopen(user_url) json_raw= raw.readlines() json_object = json.loads(json_raw[0]) #filtering and making it look good. gsongs = [] print json_object for song in json_object[0]: print song This code prints all the information before ":" Please help. ignore the Justin Bieber track :)

    Read the article

  • Randomly and uniquely iterating over a range

    - by Synetech
    Say you have a range of values (or anything else) and you want to iterate over the range and stop at some indeterminate point. Because the stopping value could be anywhere in the range, iterating sequentially is no good because it causes the early values to be accessed more often than later values (which is bad for things that wear out), and also because it reduces performance since it must traverse extra values. Randomly iterating is better because it will (on average) increase the hit-rate so that fewer values have to be accessed before finding the right one, and also distribute the accesses more evenly (again, on average). The problem is that the standard method of randomly jumping around will result in values being accessed multiple times, and has no automatic way of determining when each value has been checked and thus the whole range has been exhausted. One simplified and contrived solution could be to make a list of each value, pick one at random, then remove it. Each time through the loop, you pick one fromt he set of remaining items. Unfortunately this only works for small lists. As a (forced) example, say you are creating a game where the program tries to guess what number you picked and shows how many guess it took. The range is between 0-255 and instead of asking Is it 0? Is it 1? Is it 2?…, you have it guess randomly. You could create a list of 255 numbers, pick randomly and remove it. But what if the range was between 0-232? You can’t really create a 4-billion item list. I’ve seen a couple of implementations RNGs that are supposed to provide a uniform distribution, but none that area also supposed to be unique, i.e., no repeated values. So is there a practical way to randomly, and uniquely iterate over a range?

    Read the article

  • Iterating selected rows in an ADF Faces table

    - by Frank Nimphius
    In OTN Harvest May 2012; http://www.oracle.com/technetwork/developer-tools/adf/learnmore/may2012-otn-harvest-1652358.pdf I wrote about "Common mistake when iterating <af:table> rows". In this entry I showed code to access the row associated with a selected table row from the binding layer to avoid the problem of having to programmatically change the selected table row. As it turns out, my solution only worked fro selected table rows that are in the current iterator query range. So here's a solution that works for all ranges public String onButtonPress() { RowKeySet rks = table.getSelectedRowKeys(); Iterator it = rks.iterator(); while (it.hasNext()) { List selectedRowKeyPath = (List)it.next(); //table is the JSF component reference created using the table's binding //property Row row = ((JUCtrlHierNodeBinding)table.getRowData(selectedRowKeyPath)).getRow(); System.out.println("Print Test: " + row.getAttribute(1)); } return null; }

    Read the article

  • Segfault when iterating over a map<string, string> and drawing its contents using SDL_TTF

    - by Michael Stahre
    I'm not entirely sure this question belongs on gamedev.stackexchange, but I'm technically working on a game and working with SDL, so it might not be entirely offtopic. I've written a class called DebugText. The point of the class is to have a nice way of printing values of variables to the game screen. The idea is to call SetDebugText() with the variables in question every time they change or, as is currently the case, every time the game's Update() is called. The issue is that when iterating over the map that contains my variables and their latest updated values, I get segfaults. See the comments in DrawDebugText() below, it specifies where the error happens. I've tried splitting the calls to it-first and it-second into separate lines and found that the problem doesn't always happen when calling it-first. It alters between it-first and it-second. I can't find a pattern. It doesn't fail on every call to DrawDebugText() either. It might fail on the third time DrawDebugText() is called, or it might fail on the fourth. Class header: #ifndef CLIENT_DEBUGTEXT_H #define CLIENT_DEBUGTEXT_H #include <Map> #include <Math.h> #include <sstream> #include <SDL.h> #include <SDL_ttf.h> #include "vector2.h" using std::string; using std::stringstream; using std::map; using std::pair; using game::Vector2; namespace game { class DebugText { private: TTF_Font* debug_text_font; map<string, string>* debug_text_list; public: void SetDebugText(string var, bool value); void SetDebugText(string var, float value); void SetDebugText(string var, int value); void SetDebugText(string var, Vector2 value); void SetDebugText(string var, string value); int DrawDebugText(SDL_Surface*, SDL_Rect*); void InitDebugText(); void Clear(); }; } #endif Class source file: #include "debugtext.h" namespace game { // Copypasta function for handling the toString conversion template <class T> inline string to_string (const T& t) { stringstream ss (stringstream::in | stringstream::out); ss << t; return ss.str(); } // Initializes SDL_TTF and sets its font void DebugText::InitDebugText() { if(TTF_WasInit()) TTF_Quit(); TTF_Init(); debug_text_font = TTF_OpenFont("LiberationSans-Regular.ttf", 16); TTF_SetFontStyle(debug_text_font, TTF_STYLE_NORMAL); } // Iterates over the current debug_text_list and draws every element on the screen. // After drawing with SDL you need to get a rect specifying the area on the screen that was changed and tell SDL that this part of the screen needs to be updated. this is done in the game's Draw() function // This function sets rects_to_update to the new list of rects provided by all of the surfaces and returns the number of rects in the list. These two parameters are used in Draw() when calling on SDL_UpdateRects(), which takes an SDL_Rect* and a list length int DebugText::DrawDebugText(SDL_Surface* screen, SDL_Rect* rects_to_update) { if(debug_text_list == NULL) return 0; if(!TTF_WasInit()) InitDebugText(); rects_to_update = NULL; // Specifying the font color SDL_Color font_color = {0xff, 0x00, 0x00, 0x00}; // r, g, b, unused int row_count = 0; string line; // The iterator variable map<string, string>::iterator it; // Gets the iterator and iterates over it for(it = debug_text_list->begin(); it != debug_text_list->end(); it++) { // Takes the first value (the name of the variable) and the second value (the value of the parameter in string form) //---------THIS LINE GIVES ME SEGFAULTS----- line = it->first + ": " + it->second; //------------------------------------------ // Creates a surface with the text on it that in turn can be rendered to the screen itself later SDL_Surface* debug_surface = TTF_RenderText_Solid(debug_text_font, line.c_str(), font_color); if(debug_surface == NULL) { // A standard check for errors fprintf(stderr, "Error: %s", TTF_GetError()); return NULL; } else { // If SDL_TTF did its job right, then we now set a destination rect row_count++; SDL_Rect dstrect = {5, 5, 0, 0}; // x, y, w, h dstrect.x = 20; dstrect.y = 20*row_count; // Draws the surface with the text on it to the screen int res = SDL_BlitSurface(debug_surface,NULL,screen,&dstrect); if(res != 0) { //Just an error check fprintf(stderr, "Error: %s", SDL_GetError()); return NULL; } // Creates a new rect to specify the area that needs to be updated with SDL_Rect* new_rect_to_update = (SDL_Rect*) malloc(sizeof(SDL_Rect)); new_rect_to_update->h = debug_surface->h; new_rect_to_update->w = debug_surface->w; new_rect_to_update->x = dstrect.x; new_rect_to_update->y = dstrect.y; // Just freeing the surface since it isn't necessary anymore SDL_FreeSurface(debug_surface); // Creates a new list of rects with room for the new rect SDL_Rect* newtemp = (SDL_Rect*) malloc(row_count*sizeof(SDL_Rect)); // Copies the data from the old list of rects to the new one memcpy(newtemp, rects_to_update, (row_count-1)*sizeof(SDL_Rect)); // Adds the new rect to the new list newtemp[row_count-1] = *new_rect_to_update; // Frees the memory used by the old list free(rects_to_update); // And finally redirects the pointer to the old list to the new list rects_to_update = newtemp; newtemp = NULL; } } // When the entire map has been iterated over, return the number of lines that were drawn, ie. the number of rects in the returned rect list return row_count; } // The SetDebugText used by all the SetDebugText overloads // Takes two strings, inserts them into the map as a pair void DebugText::SetDebugText(string var, string value) { if (debug_text_list == NULL) { debug_text_list = new map<string, string>(); } debug_text_list->erase(var); debug_text_list->insert(pair<string, string>(var, value)); } // Writes the bool to a string and calls SetDebugText(string, string) void DebugText::SetDebugText(string var, bool value) { string result; if (value) result = "True"; else result = "False"; SetDebugText(var, result); } // Does the same thing, but uses to_string() to convert the float void DebugText::SetDebugText(string var, float value) { SetDebugText(var, to_string(value)); } // Same as above, but int void DebugText::SetDebugText(string var, int value) { SetDebugText(var, to_string(value)); } // Vector2 is a struct of my own making. It contains the two float vars x and y void DebugText::SetDebugText(string var, Vector2 value) { SetDebugText(var + ".x", to_string(value.x)); SetDebugText(var + ".y", to_string(value.y)); } // Empties the list. I don't actually use this in my code. Shame on me for writing something I don't use. void DebugText::Clear() { if(debug_text_list != NULL) debug_text_list->clear(); } }

    Read the article

  • Iterating XML nodes using VBA

    - by ydobonmai
    Note:- It just might be a iterating XML nodes using VBA question. Please look at the bottom of this question. It would be good If we can iterate without using MSXML2.DOMDocument I see the this question which answers part of my question on how to retrieve the CustomXMLPart. However, I am not able to iterate through the Xml. That way, this might not be specific to CustomXmlPart, It just might be a iterating XML using VBA question. Following is the XML I have in my CustomXMLPart. <Items> <Item1>Item1</Item1> <Item2>Item2</Item2> <Item3>Item3</Item3> </Items> This is how I add the above XML as CustomXmlPart:- static void AddCustomTableXmlPart(WordprocessingDocument document) { MainDocumentPart mainDocumentPart = document.MainDocumentPart; XDocument itemXml = GetItemsAsCustomXML(); if (mainDocumentPart.GetPartsCountOfType<CustomXmlPart>() > 0) mainDocumentPart.DeleteParts<CustomXmlPart>(mainDocumentPart.CustomXmlParts); //Add a new customXML part and then add content var customXmlPart = mainDocumentPart.AddCustomXmlPart(CustomXmlPartType.CustomXml); //copy the XML into the new part... using (var ts = new StreamWriter(customXmlPart.GetStream())) { ts.Write(itemXml.ToString()); ts.Flush(); } } and this is how I am accessing it in the macro:- Dim itemNode As xmlNode Dim itemChildren As XMLNodes ' The below line throws a run-time error 'Run-time error '13' - 'type mismatch ' not sure why. **Set itemChildren= ActiveDocument.CustomXMLParts(ActiveDocument.CustomXMLParts.Count).SelectSingleNode("//Items").ChildNodes** Interestingly, when I quick watch ActiveDocument.CustomXMLParts(ActiveDocument.CustomXMLParts.Count).SelectSingleNode("//Items").ChildNodes, I see child items in the quick watch window. Is the assignment to the itemChildren variable incorrect? I want to iterate through all the items and get get text for all of them. Could anybody help?

    Read the article

  • Iterating through Event Log Entry Collection, IndexOutOutOfBoundsException

    - by fjdumont
    Hello, in a service application I am iterating through the Windows application event log to parse Events in order react depanding on the entry message. In the case that the event log is full (Windows usually makes sure there is enough space by deleting old entries - this is configurable in the eventvwr.exe settings), the service always runs into an IndexOutOfBoundsException while iterating through the EventLog.Entries collection. No matter how I iterate (for-loop, using the collections enumerator, copying the collection into an array, ...), I can't seem to get rid of this ´bug´. Currently, I ensure that the log is not full in order to keep the service running by regularly deleting the last few item by parsing the event log file and deleting the last few nodes (Don't beat me up, I couldn't find a better alternative...). How can I iterate through the collection without trying to access already deleted entries? Is there probably a more elegant method? I am only trying to acces the logs written during the last x seconds (even LINQ failed to select those when the log is full - same exception), could this help? Thanks for any advice and hints Frank Edit: I forgot to mention that my assumption is the loops are accessing entries which are being deleted during iteration by Windows. Basically that is why I tried to clone the collection. Is there perhaps a way to lock the collection for a small amount of time for just my application?

    Read the article

  • Iterating through folders and files in batch file?

    - by Will Marcouiller
    Here's my situation. A project has as objective to migrate some attachments to another system. These attachments will be located to a parent folder, let's say "Folder 0" (see this question's diagram for better understanding), and they will be zipped/compressed. I want my batch script to be called like so: BatchScript.bat "c:\temp\usd\Folder 0" I'm using 7za.exe as the command line extraction tool. What I want my batch script to do is to iterate through the "Folder 0"'s subfolders, and extract all of the containing ZIP files into their respective folder. It is obligatory that the files extracted are in the same folder as their respective ZIP files. So, files contained in "File 1.zip" are needed in "Folder 1" and so forth. I have read about the FOR...DO command on Windows XP Professional Product Documentation - Using Batch Files. Here's my script: @ECHO OFF FOR /D %folder IN (%%rootFolderCmdLnParam) DO FOR %zippedFile IN (*.zip) DO 7za.exe e %zippedFile I guess that I would also need to change the actual directory before calling 7za.exe e %zippedFile for file extraction, but I can't figure out how in this batch file (through I know how in command line, and even if I know it is the same instruction "cd"). Anyone's help is gratefully appreciated.

    Read the article

  • Shell Script, iterating over a folder

    - by Martin
    I have very basic shell scripting knowledge. I have photos under original folder on many different folder like this folder + folder1 + original + folder2 + original + folder3 + original + folder4 + original Using mogrify I'm trying to create thumbs under a thumb folder following a structure to this. folder + folder1 + original + thumb + folder2 + original + thumb + folder3 + original + thumb + folder4 + original + thumb I'm a little lost in how to write the shell script that may iterate through it. I'm ok giving mogrify its settings but I don't complete understand how to tell the script to go iterate each folder to run the mogrify command.

    Read the article

  • Iterating over resources in puppet templates

    - by daveg
    So I've got a puppet manifest, with multiple resources class foo { Custom::Resource {'resource1': attr1 => 'val1', attr2 => 'val2', } Custom::Resource {'resource2': attr1 => 'val3', attr2 => 'val4', } Custom::Resource {'resource3': attr1 => 'val5', attr2 => 'val6', } } If I wanted to loop over the Custom::Resource resource names in an .erb template that are defined in class foo, how do I access them? So if I wanted to write out a template that looked like this: ThisLine = resource1 ThisLine = resource2 ThisLine = resource3

    Read the article

  • Amazon S3 Iterating Through Multi-Page Results. (withMarker)

    - by Jitu
    Trying to iterate through AmazonS3 that has around 5000+ keys stored in the bucket, used sample code based on provided link on Amazon Developer Guide http://docs.amazonwebservices.com/AmazonS3/latest/dev/ListingObjectKeysUsingNetSDK.html Issue is iteration fails when NexMarker is passed which has length of more than 128 string characters, which seems unusal as withMarker accepts string as parameter and there is no documentation on limit to withMarker. request.Marker = response.NextMarker; Has anyone faced similar issue. Thanks in advance.

    Read the article

  • Iterating over two dimension array and knowing current position

    - by Nuno Furtado
    I am trying to iterate a multidimension array created with the following line To iterate i'm using the following code visiblematrix= Array.new (10) {Array.new(10){0}} But this doesn't allow me to know the current x,y position while iterating. how can i find it out without resorting to temporary variables visiblematrix.each do |x| x.each do |y| puts y end end

    Read the article

  • Fastest way to iterate through an NSArray with objects and keys

    - by AppGolfer
    Hello, I have an NSArray called 'objects' below with arrayCount = 1000. It takes about 10 secs to iterate through this array. Does anyone have a faster method of iterating through this array? Thanks! for (int i = 0; i <= arrayCount; i++) { event.latitude = [[[objects valueForKey:@"CLatitude"] objectAtIndex:i] floatValue]; event.longitude = [[[objects valueForKey:@"CLongitude"] objectAtIndex:i] floatValue]; }

    Read the article

  • Peek ahead when iterating an array in PHP 5.2

    - by pako
    Is it possible to "peek ahead" while iterating an array in PHP 5.2? For example, I often use foreach to manipulate data from an array: foreach($array as $object) { // do something } But I often need to peek at the next element while going through the array. I know I could use a for loop and reference the next item by it's index ($array[$i+1]), but it wouldn't work for associative arrays. Is there any elegant solution for my problem, perhaps involving SPL?

    Read the article

  • Fast iterating over first n items of an iterable in python

    - by martinthenext
    Hello! I'm looking for a pythonic way of iterating over first n items of a list, and it's quite important to do this as fast as possible. This is how I do it now: count = 0 for item in iterable: do_somethin(item) count += 1 if count >= n: break Doesn't seem neat to me. Another way of doing this is: for item in itertools.islice(iterable, n): do_something(item) This looks good, the question is it fast enough to use with some generator(s)? For example: pair_generator = lambda iterable: itertools.izip(*[iter(iterable)]*2) for item in itertools.islice(pair_generator(iterable), n): so_something(item) Will it run fast enough as compared to the first method? Is there some easier way to do it?

    Read the article

  • Iterating Oracle collections of objects with out exploding them

    - by Scott Bailey
    I'm using Oracle object data types to represent a timespan or period. And I've got to do a bunch of operations that involve working with collections of periods. Iterating over collections in SQL is significantly faster than in PL/SQL. CREATE TYPE PERIOD AS OBJECT ( beginning DATE, ending DATE, ... some member functions...); CREATE TYPE PERIOD_TABLE AS TABLE OF PERIOD; -- sample usage SELECT <<period object>>.contains(period2) FROM TABLE(period_table1) t The problem is that the TABLE() function explodes the objects into scalar values, and I really need the objects instead. I could use the scalar values to recreate the objects but this would incur the overhead of re-instantiating the objects. And the period is designed to be subclassed so there would be additional difficulty trying to figure out what to initialize it as. Is there another way to do this that doesn't destroy my objects?

    Read the article

  • Python: Remove items from a list while iterating in Python

    - by xApple
    My problem is simple: I have a long list of elements that I want to iterate through and check every element against a condition. Depending on the outcome of the condition I would like to delete the current element of the list, and continue iterating over it as usual. I have read a few other threads on this matter. Two solutions seam to be proposed. Either make a dictionary out of the list (which implies making a copy of all the data that is already filling all the RAM in my case). Either walk the list in reverse (which breaks the concept of the alogrithm I want to implement). Is there any better or more elegant way than this to do it ? def walk_list(list_of_g): g_index = 0 while g_index < len(list_of_g): g_current = list_of_g[g_index] if subtle_condition(g_current): list_of_g.pop(g_index) else: g_index = g_index + 1

    Read the article

  • Fast iterating over first n items of an iterable (not a list) in python

    - by martinthenext
    Hello! I'm looking for a pythonic way of iterating over first n items of an iterable (upd: not a list in a common case, as for lists things are trivial), and it's quite important to do this as fast as possible. This is how I do it now: count = 0 for item in iterable: do_something(item) count += 1 if count >= n: break Doesn't seem neat to me. Another way of doing this is: for item in itertools.islice(iterable, n): do_something(item) This looks good, the question is it fast enough to use with some generator(s)? For example: pair_generator = lambda iterable: itertools.izip(*[iter(iterable)]*2) for item in itertools.islice(pair_generator(iterable), n): so_something(item) Will it run fast enough as compared to the first method? Is there some easier way to do it?

    Read the article

  • iterating through an array

    - by Farstucker
    Iterating though an array isn’t a problem but what if I only wanted to incremented only when the method is called? Im not even sure if this would work but is there an easier way of doing this int counter; string[] myArray = {"foo", "bar", "something", "else", "here"}; private string GetNext() { string myValue = string.Empty; if (counter < myArray.Length) { myValue = myArray [counter]; } else { counter = 0; } counter++; return myValue; }

    Read the article

  • How to print element values when iterating through XML document in PHP

    - by pharma_joe
    I am iterating through the results of a service call to yahoo news thus: //Send service request if (!$yahooResults = file_get_contents($yahooRequest)) { echo 'Error processing service request'; } //Read result into xml document $yahooResultXml = new DOMDocument('1.0', 'UTF-8'); $yahooResultXml-loadXML($yahooResults); //Build page include_once('components/pageHeader.php'); echo 'Search Results'; //echo $yahooResultXml-saveHTML(); //Iterate over each Result node $stories = $yahooResultXml-getElementsByTagName('Result'); foreach ($stories as $story) { //Title //Summary //Url //Source //Language //Publish Date //Modification Date } include_once('components/pageFooter.php'); Each Title is in a Title node within a Result Node. I cannot figure out how to simply echo the content of the Title node!

    Read the article

  • Iterating through std queue

    - by Ockonal
    Hi, I'm trying to use BOOST_FOREACH for iterating through the std::queue. But there isn't iterators in that class cause I have an error: std::queue<std::string> someList; BOOST_FOREACH(std::string temp, someList) { std::cout << temp; } >no matching function for call to begin(...) >no type named ‘iterator’ in ‘class std::queue<std::basic_string<char> >’ I need in structure like: the first comes, the first goes away.

    Read the article

  • Iterating Through a jQuery Object Array

    - by DeltaFox
    I know this has been asked and answered a couple times already, but I'm still confused about how to reference the current object when iterating over a jQuery array. For example, the following code gives me the error "TypeError: genH3Array[i].next is not a function". What is the right way to reference the current array object? var genH3Array = $('#Generation_II').parent(); genH3Array.push($('#Generation_III').parent());; genH3Array.push($('#Generation_IV').parent()) $.each(genH3Array, function(i, value) { if(genH3Array[i].next().attr("align") == "center") { genH3Array[i].next().next().next().insertBefore(heading.next()) } genH3Array[i].next().next().insertBefore(heading.next()) genH3Array[i].next().insertBefore(heading.next()) })

    Read the article

  • Manually iterating over a selection of XML elements (C#, XDocument)

    - by user316117
    What is the “best practice” way of manually iterating (i.e., one at a time with a “next” button) over a set of XElements in my XDocument? Say I select the set of elements I want thusly: var elems = from XElement el in m_xDoc.Descendants() where (el.Name.LocalName.ToString() == "q_a") select el; I can use an IEnumerator to iterate over them, i.e., IEnumerator m_iter; But when I get to the end and I want to wrap around to the beginning if I call Reset() on it, it throws a NotSupportedException. That’s because, as the Microsoft C# 2.0 Specification under chapter 22 "Iterators" says "Note that enumerator objects do not support the IEnumerator.Reset method. Invoking this method causes a System.NotSupportedException to be thrown ." So what IS the right way of doing this? And what if I also want to have bidirectional iteration, i.e., a “back” button, too? Someone on a Microsoft discussion forum said I shouldn’t be using IEnumerable directly anyway. He said there was a way to do what I want with LINQ but I didn’t understand what. Someone else suggested dumping the XElements into a List with ToList(), which I think would work, but I wasn’t sure it was “best practice”. Thanks in advance for any suggestions!

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >