Search Results

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

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

  • JPA: what is the proper pattern for iterating over large result sets?

    - by Caffeine Coma
    Let's say I have a table with millions of rows. Using JPA, what's the proper way to iterate over a query against that table, such that I don't have all an in-memory List with millions of objects? I suspect that the following will blow up if the table is large: List<Model> models = entityManager().createQuery("from Model m", Model.class).getResultList(); for (Model model : models) { // do something with model } Is pagination (looping and manually updating setFirstResult()/setMaxResult()) really the best solution?

    Read the article

  • Is there any method in Cocoa that helps iterating through all NSColor values(R,G,B only, alpha not t

    - by krasnyk
    You may ask why do I need it? I have to detect all white objects at the B/W image. I'm coloring each object and taking its rect. In order fill each object with different color I would be very happy to use a function that can for a given color gimme a next one or so. In Qt there is a nice one that is called nextColor or so, returns the integer representing the next color(which can be easily translated to RGB). Does Cocoa have sth like that?

    Read the article

  • How do you find the last element of an array while iterating using a foreach loop in php ?

    - by Vaibhav Kamble
    I am writing a sql query creator using some parameters. While doing that ,I came across this problem. In java , Its very easy to detect the last element of an array from inside the for loop by just checking the current array position with the array length. for(int i=0; i< arr.length;i++){ boolean isLastElem = i== (arr.length -1) ? true : false; } php has some different fashion. They have non integer indexes to access arrays. So you must iterate over an array using foreach loop. But it becomes very problematic when you need to take some decision (in my case to append or/and parameter while building query). I am sure there must be some standard way of doing this. How do you solve this problem normally in php ?

    Read the article

  • Ruby on Rails: how to sort data in an array of active record objects right before iterating?

    - by DerNalia
    What is the best way to sort an array of active record objects by by a field? This array is a field of an object, link_pages, and I want it sorted by the field "sequence" <% @menu_bar.link_pages.each do |lp| %> <li id="page_<%= lp.id%>" class="ui-state-default"> <span class="ui-icon ui-icon-arrowthick-2-n-s"></span> <font size=5><%= lp.name %></font> | <%= link_to "remove", :controller => "admin/menu_bars", :action => :remove_page_from_menu, :page => lp.id, :id => @menu_bar.id %> </li> <% end %> maybe there is a way to do @menu_bar.link_pages.sort_by_sequence.each do .... that would be slick... but I just don't know.

    Read the article

  • Using MSBuild, how to construct a dynamic string from iterating over files in an ItemGroup?

    - by RyBolt
    I need to create multiple /testcontainer: parameters to feed into a task that exec's MsTest. I have the following : <ItemGroup> <TestFiles Include="$(ProjectPath)\**\UnitTest.*.dll" /> </ItemGroup> for each match in TestFiles I would like to build a string like so: "/testcontainer:UnitTest.SomeLibrary1.dll" "/testcontainer:UnitTest.SomeLibrary2.dll" "/testcontainer:UnitTest.SomeLibrary3.dll" I am trying to use the internals of MSBuild without having to create a custom task, is this possible ? TIA

    Read the article

  • When iterating over values, why does typeof(value) return "string" when value is a number? Javascrip

    - by Mark
    I'm using Google Chrome for this test: Contrary to intuition, the first loop alerts "string" 3 times, while the second loop alerts "number" 3 times. numarray = [1, 2, 3]; //for-each loop for(num in numarray) alert(typeof(num)); //standard loop for(i=0; i<numarray.length; i++) alert(typeof(numarray[i])); I was expecting both loops to alert "number" 3 times. How is the first loop implemented in Javascript? In other words, if the for-each is syntactic sugar, what is its equivalent using a standard loop? Also, is there some way to iterate over an object's namespace using a standard loop? I'm looking to touch every one of some object's methods and attributes using a loop of the second kind. I'm new to Javascript and any help is highly appreciated, thanks.

    Read the article

  • Can't access a property with <html:checkbox property="..."> when iterating a list

    - by Bernhard V
    Hi. In my Struts form I've got a list. In a JSP I iterate over it like this: <c:forEach items="${MyForm.auspraegungen}" var="auspraegung"> <tr> <td>${auspraegung.name}</td> <td>${auspraegung.forced}</td> <td>${auspraegung.cbx_uebernehmen}</td> <html:checkbox property="auspraegung.cbx_uebernehmen" /> </tr> </c:forEach> Now the <html:checkbox isn't working. I'm always getting the following error: Caused by: javax.servlet.jsp.JspException: No getter method for property auspraegung.cbx_uebernehmen of bean org.apache.struts.taglib.html.BEAN But actually there is a getter for this property in my form class. It's written like this: public Boolean getCbx_uebernehmen() { return cbx_uebernehmen; } When I remove the checkbox it's also possible to display the property as in the <td>-tag above so I don't know where the problem is. Maybe I'm accessing it in the wrong way?

    Read the article

  • Safe way of iterating over an array or dictionary and deleting entries?

    - by mystify
    I've heard that it is a bad idea to do something like this. But I am sure there is some rule of thumb which can help to get that right. When I iterate over an NSMutableDictionary or NSMutableArray often I need to get rid of entries. Typical case: You iterate over it, and compare the entry against something. Sometimes the result is "don't need anymore" and you have to remove it. But doing so affects the index of all the rows, doesn't it? So how could I safely iterate over it without accidently exceeding bounds or jumping over an element that hasn't been checked?

    Read the article

  • Why does the order of the loops affect performance when iterating over a 2D array? [closed]

    - by Mark
    Possible Duplicate: Which of these two for loops is more efficient in terms of time and cache performance Below are two programs that are almost identical except that I switched the i and j variables around. They both run in different amounts of time. Could someone explain why this happens? Version 1 #include <stdio.h> #include <stdlib.h> main () { int i,j; static int x[4000][4000]; for (i = 0; i < 4000; i++) { for (j = 0; j < 4000; j++) { x[j][i] = i + j; } } } Version 2 #include <stdio.h> #include <stdlib.h> main () { int i,j; static int x[4000][4000]; for (j = 0; j < 4000; j++) { for (i = 0; i < 4000; i++) { x[j][i] = i + j; } } }

    Read the article

  • Iterating over a String to check for a number and printing out the String value if it doesn't have a number

    - by wheelerlc64
    I have set up my function for checking for a number in a String, and printing out that String if it has no numbers, and putting up an error message if it does. Here is my code: public class NumberFunction { public boolean containsNbr(String str) { boolean containsNbr = false; if(str != null && !str.isEmpty()) { for(char c : str.toCharArray()) { if(containsNbr = Character.isDigit(c)) { System.out.println("Can't contain numbers in the word."); break; } else { System.out.println(str); } } } return containsNbr; } } import com.imports.validationexample.function.NumberFunction; public class Main { public static void main(String[] args) { NumberFunction nf = new NumberFunction(); System.out.println(nf.containsNbr("bill4")); } } I am trying to get it to print out the result to the console, but the result keeps printing multiple times and prints the boolean value, which I do not want, something like this: bill4 bill4 bill4 bill4 Can't contain numbers in the word. true Why is this happening? I've tried casting but that hasn't worked out either. Any help would be much appreciated.

    Read the article

  • [PHP] Does unsetting array values during iterating save on memory?

    - by saturn_rising
    Hello fellow code warriors, This is a simple programming question, coming from my lack of knowledge of how PHP handles array copying and unsetting during a foreach loop. It's like this, I have an array that comes to me from an outside source formatted in a way I want to change. A simple example would be: $myData = array('Key1' => array('value1', 'value2')); But what I want would be something like: $myData = array([0] => array('MyKey' => array('Key1' => array('value1', 'value2')))); So I take the first $myData and format it like the second $myData. I'm totally fine with my formatting algorithm. My question lies in finding a way to conserve memory since these arrays might get a little unwieldy. So, during my foreach loop I copy the current array value(s) into the new format, then I unset the value I'm working with from the original array. E.g.: $formattedData = array(); foreach ($myData as $key => $val) { // do some formatting here, copy to $reformattedVal $formattedData[] = $reformattedVal; unset($myData[$key]); } Is the call to unset() a good idea here? I.e., does it conserve memory since I have copied the data and no longer need the original value? Or, does PHP automatically garbage collect the data since I don't reference it in any subsequent code? The code runs fine, and so far my datasets have been too negligible in size to test for performance differences. I just don't know if I'm setting myself up for some weird bugs or CPU hits later on. Thanks for any insights. -sR

    Read the article

  • Enumerating all combinations of lists of different types

    - by jball
    Given two IEnumberables of different types, what is the best practice (considering readability and maintainability) for iterating over both lists to perform an action on all possible combinations? My initial solution was to use nested foreach loops, iterating over the first IEnumerable, and then within that loop, iterating over the second IEnumerable and passing the value from the outer and the current loop into the target method. Eg.: enum ParamOne { First, Second, Etc } List<int> paramTwo = new List<int>() { 1, 2, 3 }; void LoopExample() { foreach (ParamOne alpha in Enum.GetValues(typeof(ParamOne))) { foreach (int beta in paramTwo) { DoSomething(alpha, beta); } } } I tried to restructure it with LINQ, but ended up with something that had no obvious advantages and seemed less intuitive. A search here shows lots of questions about nesting foreachs to iterate over child properties, but I couldn't find anything about iterating over two distinct lists.

    Read the article

  • An observation on .NET loops – foreach, for, while, do-while

    It’s very common that .NET programmers use “foreach” loop for iterating through collections. Following is my observation whilst I was testing simple scenario on loops. “for” loop is 30% faster than “foreach” and “while” loop is 50% faster than “foreach”. “do-while” is bit faster than “while”. Someone may feel that how does it make difference if I’m iterating only 1000 times in a loop. This test case is only for simple iteration. According to the "Data structure" concepts, best and worst cases are completely based on the data we provide to the algorithm. so we can not conclude that a "foreach" algorithm is not good. All I want to tell that we need to be little cautious even choosing the loops. Example:- You might want to chose quick sort when you want to sort more numbers. At the same time bubble sort may be effective than quick sort when you want to sort less numbers. Take a simple scenario, a request of a simple web application fetches the data of 10000 (10K) rows and iterating them for some business logic. Think, this application is being accessed by 1000 (1K) people simultaneously. In this simple scenario you are ending up with 10000000 (10Million or 1 Crore) iterations. below is the test scenario with simple console application to test 100 Million records. using System;using System.Collections.Generic;using System.Diagnostics;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { var sw = new Stopwatch(); var numbers = GetSomeNumbers(); sw.Start(); foreach (var item in numbers) { } sw.Stop(); Console.WriteLine( String.Format("\"foreach\" took {0} milliseconds", sw.ElapsedMilliseconds)); sw.Reset(); sw.Start(); for (int i = 0; i < numbers.Count; i++) { } sw.Stop(); Console.WriteLine( String.Format("\"for\" loop took {0} milliseconds", sw.ElapsedMilliseconds)); sw.Reset(); sw.Start(); var it = 0; while (it++ < numbers.Count) { } sw.Stop(); Console.WriteLine( String.Format("\"while\" loop took {0} milliseconds", sw.ElapsedMilliseconds)); sw.Reset(); sw.Start(); var it2 = 0; do { } while (it2++ < numbers.Count); sw.Stop(); Console.WriteLine( String.Format("\"do-while\" loop took {0} milliseconds", sw.ElapsedMilliseconds)); } #region Get me 10Crore (100 Million) numbers private static List<int> GetSomeNumbers() { var lstNumbers = new List<int>(); var count = 100000000; for (var i = 1; i <= count; i++) { lstNumbers.Add(i); } return lstNumbers; } #endregion Get me some numbers }} In above example, I was just iterating through 100 Million numbers. You can see the time to execute various  loops provided in .NET Output "foreach" took 1108 milliseconds "for" loop took 727 milliseconds "while" loop took 596 milliseconds "do-while" loop took 594 milliseconds   Press any key to continue . . . So I feel we need to be careful while choosing the looping strategy. Please comment your thoughts. span.fullpost {display:none;}

    Read the article

  • Removing elements from C++ std::vector

    - by user219847
    What is the proper way to remove elements from a C++ vector while iterating through it? I am iterating over an array and want to remove some elements that match a certain condition. I've been told that it's a bad thing to modify it during traversal.

    Read the article

  • What's the new way to iterate over a Java Map in Scala 2.8.0?

    - by Alex R
    How does scala.collection.JavaConversions supercede the answers given here: http://stackoverflow.com/questions/495741/iterating-over-java-collections-in-scala (doesn't work because the "jcl" package is gone) and here http://www.eishay.com/2009/05/iterating-over-map-with-scala.html (doesn't work me in a complicated test which I'll try to boil down and post here later) The latter is actually a Scala Map question but I think I need to know both answers in order to iterate over a java.util.Map. Thanks

    Read the article

  • C++ dictionary/map with added order

    - by Gopalakrishnan Subramani
    I want to have something similar to map but while iterating I want them to be in the same order as it is added. Example map.insert("one", 1); map.insert("two", 2); map.insert("three", 3); While iterating I want the items to be like "one", ""two", "three"..By default, map doesn't provide this added order. How to get the map elements the way I have added? Anything with STL is fine or other alternative suggestions also fine

    Read the article

  • 45 minutes to talk about C# [closed]

    - by Philip
    I have the opportunity to give a 45 minute talk on C# in the theory of programming languages class I'm taking. The college teaches Java almost exclusively, so that's what all the students are most familiar with. (There's a little C, assembly, Prolog and LISP as well.) I decide what to talk about. It seems to me the best approach is to focus on a few of the big, obvious differences between C# and Java. I don't intend it to be a recommendation to use C# -- there are reasons to use each, mostly because of their ecosystems. So I want to focus on C# as a language. I don't want to go too fast and end up listing a whole bunch of features without showing their usefulness. My current plan is this: Functions as first class objects. This is, in my opinion, one of the biggest differences between C# and Java. The professor briefly mentioned this notion and showed a LISP example, but many of the students have probably never used it. I can show real world examples where it's made my code more readable. Lambda expressions as concise syntax for anonymous functions. Obviously with examples to show how this is useful. The real hit-home examples will be at the end when it's combined with the rest. I don't see an advantage to first showing the old delegate syntax and then replacing it with lambdas -- most of us won't have ever seen delegates anyway so it would just be confusing. The yield keyword and how it's different from returning an array. I have the impression that a lot of C# developers aren't familiar with how to use this. It will likely be very foreign to Java developers. I have some examples from my own work where it was really useful, such as iterating over a tree traversal, or iterating over neighbors in a graph where the neighbors aren't stored in memory. In both cases, doing it in Java would likely mean returning a complete list -- with yield I can stop iterating if I find what I want early on, without using memory for superfluous lists or arrays. Extension methods as a way to write implementation on interfaces. We'll all be familiar with how interfaces don't allow method implementation, and how this leads to code duplication. I'll show a specific example of this and how the extension method can solve the problem. Demonstrate how the above can be combined by implementing some simple Linq methods and using them. Where, Select, First, maybe more depending on how much time is left. Ideas on which ones might 'hit home' the best? There are other things I could talk about such as generics, value types, properties and more. I haven't yet though of good ways to incorporate these. In the case of generics and value types, the advantages might not be obvious or as relevant. Properties are obviously useful, particularly since we're taught strict JavaBeans here, but I don't know if I could integrate it with the "path to Linq" discussion above without it feeling tacked on. So I'm looking for thoughts on how to talk about C#, and what to talk about. Even minor details. I'm sure there are more experienced C# developers than me here who have good insight about what's really important in the language, and what would miss the point.

    Read the article

  • Why won't this loop normalize my Vector2 list?

    - by ssb
    See the following code: List<Vector2> axes = new List<Vector2>(); axes.Add(TopRight() - TopLeft()); axes.Add(BottomLeft() - TopLeft()); axes.Add(otherRectangle.TopRight() - otherRectangle.TopLeft()); axes.Add(otherRectangle.BottomLeft() - otherRectangle.TopLeft()); // Try normalizing vectors? foreach (Vector2 axis in axes) { axis.Normalize(); } the Vector2.Normalize() method is a void method that normalizes the vector it's called on. Yet for some reason when I do this loop it doesn't normalize the vectors. Am I just unable to modify a list this way? Some oddities: Iterating with a for loop, i.e. axis[i].Normalize() doesn't work. Iterating with the built-in List<T>.ForEach iterator does not work. Creating a normalizing the vector before adding it to the list rather than iterating over the list does work. Why does iteration not work?

    Read the article

  • Most efficient Implementation a Tree in C++

    - by Topo
    I need to write a tree where each element may have any number of child elements, and because of this each branch of the tree may have any length. The tree is only going to receive elements at first and then it is going to use exclusively for iterating though it's branches in no specific order. The tree will have several million elements and must be fast but also memory efficient. My plan makes a node class to store the elements and the pointers to its children. When the tree is fully constructed, it would be transformed it to an array or something faster and if possible, loaded to the processor's cache. Construction and the search on the tree are two different problems. Can I focus on how to solve each problem on the best way individually? The construction of has to be as fast as possible but it can use memory as it pleases. Then the transformation into a format that give us speed when iterating the tree's branches. This should preferably be an array to avoid going back and forth from RAM to cache in each element of the tree. So the real question is which is the structure to implement a tree to maximize insert speed, how can I transform it to a structure that gives me the best speed and memory?

    Read the article

  • How to recursively display folders and sub folders with specific file types only using PHP5 Recursiv

    - by Jared
    Hi I am trying to get RecursiveDirectoryIterator class using a extension on the FilterIterator to work but for some reason it is iterating on the root directory only. my code is this. class fileTypeFilter extends FilterIterator { public function __construct($path) { parent::__construct(new RecursiveDirectoryIterator($path)); } public function accept() { $file = $this->getInnerIterator()->current(); return preg_match('/\.php/i', $file->getFilename()); } } $it = new RecursiveDirectoryIterator('./'); $it = new fileTypeFilter($it); foreach ($it as $file) { echo $file; } my directory structure is something like this. -Dir1 --file1.php --file2.php -Dir2 --file1.php etc etc But as I said before the class is not recursively iterating over the entire directory structure and is only looking at the root. Question is, how do use a basic RescursiveDirectoryIterator to display folders and then run the FilterIterator to only show the php files in those directorys? Cheers

    Read the article

  • List<T>.RemoveAll Doesn't Exist in Silverlight?

    - by ashes999
    I'm working on a Silverlight 2/3 application. I would like to use List.RemoveAll (or maybe it's IList.RemoveAll?) and specify a predicate so that I can remove a bunch of elements from a list in one sweep. It seems like this function doesn't exist in Silverlight, though. Am I missing something here? Is there an alternative approach that's equally easy? Right now, I'm manually iterating over my elements in a foreach and keeping a second list (because you can't delete while iterating), and it's quite ... cumbersome.

    Read the article

  • Why are listener lists Lists?

    - by Joonas Pulakka
    Why are listener lists (e.g. in Java those that use addXxxListener() and removeXxxListener() to register and unregister listeners) called lists, and usually implemented as Lists? Wouldn't a Set be a better fit, since in the case of listeners there's No matter in which order they get called (although there may well be such needs, but they're special cases; ordinary listener mechanisms make no such guarantees), and No need to register the same listener more than once (whether doing that should result in calling the same listener 1 times or N times, or be an error, is another question) Is it just a matter of tradition? Sets are some kind of lists under the hood anyway. Are there performance differences? Is iterating through a List faster or slower than iterating through a Set? Does either take more or less memory? The differences are certainly almost negligible.

    Read the article

  • C# 4.0 'dynamic' and foreach statement

    - by ControlFlow
    Not long time before I've discovered, that new dynamic keyword doesn't work well with the C#'s foreach statement: using System; sealed class Foo { public struct FooEnumerator { int value; public bool MoveNext() { return true; } public int Current { get { return value++; } } } public FooEnumerator GetEnumerator() { return new FooEnumerator(); } static void Main() { foreach (int x in new Foo()) { Console.WriteLine(x); if (x >= 100) break; } foreach (int x in (dynamic)new Foo()) { // :) Console.WriteLine(x); if (x >= 100) break; } } } I've expected that iterating over the dynamic variable should work completely as if the type of collection variable is known at compile time. I've discovered that the second loop actually is looked like this when is compiled: foreach (object x in (IEnumerable) /* dynamic cast */ (object) new Foo()) { ... } and every access to the x variable results with the dynamic lookup/cast so C# ignores that I've specify the correct x's type in the foreach statement - that was a bit surprising for me... And also, C# compiler completely ignores that collection from dynamically typed variable may implements IEnumerable<T> interface! The full foreach statement behavior is described in the C# 4.0 specification 8.8.4 The foreach statement article. But... It's perfectly possible to implement the same behavior at runtime! It's possible to add an extra CSharpBinderFlags.ForEachCast flag, correct the emmited code to looks like: foreach (int x in (IEnumerable<int>) /* dynamic cast with the CSharpBinderFlags.ForEachCast flag */ (object) new Foo()) { ... } And add some extra logic to CSharpConvertBinder: Wrap IEnumerable collections and IEnumerator's to IEnumerable<T>/IEnumerator<T>. Wrap collections doesn't implementing Ienumerable<T>/IEnumerator<T> to implement this interfaces. So today foreach statement iterates over dynamic completely different from iterating over statically known collection variable and completely ignores the type information, specified by user. All that results with the different iteration behavior (IEnumarble<T>-implementing collections is being iterated as only IEnumerable-implementing) and more than 150x slowdown when iterating over dynamic. Simple fix will results a much better performance: foreach (int x in (IEnumerable<int>) dynamicVariable) { But why I should write code like this? It's very nicely to see that sometimes C# 4.0 dynamic works completely the same if the type will be known at compile-time, but it's very sadly to see that dynamic works completely different where IT CAN works the same as statically typed code. So my question is: why foreach over dynamic works different from foreach over anything else?

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >