Search Results

Search found 4036 results on 162 pages for 'nested loops'.

Page 31/162 | < Previous Page | 27 28 29 30 31 32 33 34 35 36 37 38  | Next Page >

  • How to copy a variable in JavaScript?

    - by Michael Stum
    I have this JavaScript code: for (var idx in data) { var row = $("<tr></tr>"); row.click(function() { alert(idx); }); table.append(row); } So I'm looking through an array, dynamically creating rows (the part where I create the cells is omitted as it's not important). Important is that I create a new function which encloses the idx variable. However, idx is only a reference, so at the end of the loop, all rows have the same function and all alert the same value. One way I solve this at the moment is by doing this: function GetRowClickFunction(idx){ return function() { alert(idx); } } and in the calling code I call row.click(GetRowClickFunction(idx)); This works, but is somewhat ugly. I wonder if there is a better way to just copy the current value of idx inside the loop? While the problem itself is not jQuery specific (it's related to JavaScript closures/scope), I use jQuery and hence a jQuery-only solution is okay if it works.

    Read the article

  • PHP loop hanging/interspersed/threaded through HTML

    - by sandyv
    I can't figure out how to say what I'm talking about which is a big part of why I'm stuck. In PHP I often see code like this html <?php language construct that uses brackets { some code; ?> more html <?php some more code; } ?> rest of html Is there any name for this? Having seen this lead me to try it out so here is a concrete example whose behavior doesn't make sense to me <div id="content"> <ul id="nav"> <?php $path = 'content'; $dir = dir($path); while(false !== ($file = $dir->read())) { if(preg_match('/.+\.txt/i', $file)) { echo "<li>$file</li>"; ?> </ul> <?php echo file_get_contents($path . '/' . $file); } } ?> </div> Which outputs roughly <div><ul><li></li></ul><li></li>...</div> instead of <div><ul><li></li>...</ul></div> which is what I thought would happen and what I want to happen.

    Read the article

  • JQUERY - Find all Elements with Class="X" and then POST all those elements to the server to INS into

    - by nobosh
    Given a large text block from a WYSIWYG like: Lorem ipsum dolor sit amet, <span class="X" id="12">consectetur adipiscing elit</span>. Donec interdum, neque at posuere scelerisque, justo tortor tempus diam, eu hendrerit libero velit sed magna. Morbi laoreet <span class="X" id="13">tincidunt quam in facilisis.</span> Cras lacinia turpis viverra lacus <span class="X" id="14">egestas elementum. Curabitur sed diam ipsum.</span> How can I use JQUERY to find the following: <span class="X" id="12">consectetur adipiscing elit</span> <span class="X" id="13">tincidunt quam in facilisis.</span> <span class="X" id="14">egestas elementum. Curabitur sed diam ipsum.</span> And post it to the server as follows 12, consectetur adipiscing 13, tincidunt quam in facilisis. 14, egestas elementum. Curabitur sed diam ipsum. In a way where in Coldfusion it can loop through the results and make 3 inserts into the DB? Thanks

    Read the article

  • PHP: Loop through text file and isolate lines which a specific "starting point"

    - by Mestika
    Hi everyone, I’m trying to reduce some editing time within some textfiles where there approximately are 10.000 lines of text, but I only need around 200 or some. The text file relies on a almost specific pattern but it deviates from time to time but my “focus” in order to select the right line to keep is, that the line always starts with: z3455 and then have a variable afterwards, e.g.: z3455 http://url.com/data1/data1.1/data1.3/ (342kb) I have an algorithm to capture the URL and its content but now I need some way to loop through the text file, deleting all lines except does that starts with z3455 and then “push” them together so they are listed underneath each other. I’ve tried different approaches for this in PHP but can’t seem to find a correct function. I can “isolate” a specific line number but when it deviates I can’t use this approach fully. I hope that someone can help me, either by providing the code or knocking me in the right direction to how I’ll solve this problem. Thanks in advance Sincerely - Mestika

    Read the article

  • Write the longest possible loop.

    - by Abhay
    Hello Group, Recently I was asked this question in a technical discussion. What is the longest possible loop that can be written in a programming language? This loop has to be as long as possible and yet not an infinite loop and should not end-up crashing the program (Recursion etc...) I honestly did not know how to attack this problem, so I asked him if is it practically possible. He said using some computer science concepts, you can arrive at a hypothetical number which may not be practical but nevertheless it will still not be infinite. Anyone here; knows how to analyse / attack this problem. P.S. Choosing some highest limit for a type that can store the highest numerical value is apparently not an answer. Thanks in advance,

    Read the article

  • How can I optimize this loop?

    - by Moshe
    I've got a piece of code that returns a super-long string that represents "search results". Each result is represented by a double HTML break symbol. For example: Result1<br><br>Result 2<br><br>Result3 I've got the following loop that takes each result and puts it into an array, stripping out the break indicator, "kBreakIndicator" (<br><br>). The problem is that this lopp takes way too long to execute. With a few results it's fine, but once you hit a hundred results, it's about 20-30 seconds slower. It's unacceptable performance. What can I do to improve performance? Here's my code: content is the original NSString. NSMutableArray *results = [[NSMutableArray alloc] init]; //Loop through the string of results and take each result and put it into an array while(![content isEqualToString:@""]){ NSRange rangeOfResult = [content rangeOfString:kBreakIndicator]; NSString *temp = (rangeOfResult.location != NSNotFound) ? [content substringToIndex:rangeOfResult.location] : nil; if (temp) { [results addObject:temp]; content = [[[content stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@%@", temp, kBreakIndicator] withString:@""] mutableCopy] autorelease]; }else{ [results addObject:[content description]]; content = [[@"" mutableCopy] autorelease]; } } //Do something with the results array. [results release];

    Read the article

  • Should try...catch go inside or outside a loop?

    - by mmyers
    I have a loop that looks something like this: for(int i = 0; i < max; i++) { String myString = ...; float myNum = Float.parseFloat(myString); myFloats[i] = myNum; } This is the main content of a method whose sole purpose is to return the array of floats. I want this method to return null if there is an error, so I put the loop inside a try...catch block, like this: try { for(int i = 0; i < max; i++) { String myString = ...; float myNum = Float.parseFloat(myString); myFloats[i] = myNum; } } catch (NumberFormatException ex) { return null; } But then I also thought of putting the try...catch block inside the loop, like this: for(int i = 0; i < max; i++) { String myString = ...; try { float myNum = Float.parseFloat(myString); } catch (NumberFormatException ex) { return null; } myFloats[i] = myNum; } So my question is: is there any reason, performance or otherwise, to prefer one over the other? EDIT: The consensus seems to be that it is cleaner to put the loop inside the try/catch, possibly inside its own method. However, there is still debate on which is faster. Can someone test this and come back with a unified answer? (EDIT: did it myself, but voted up Jeffrey and Ray's answers)

    Read the article

  • How to store multiple variables from a File Input of unknown size in Java?

    - by AlphaOmegaStrife
    I'm a total beginner with my first programming assignment in Java. For our programming assignment, we will be given a .txt file of students like so: 3 345 Lisa Miller 890238 Y 2 <-(Number of classes) Mathematics MTH345 4 A Physics PHY357 3 B Bill Wilton 798324 N 2 English ENG378 3 B Philosophy PHL534 3 A Dandy Goat 746333 Y 1 History HIS101 3 A" The teacher will give us a .txt file on the day of turning it in with a list of unknown students. My problem is: I have a specific class for turning the data from the file into variables to be used for a different class in printing it to the screen. However, I do not know of a good way to get the variables from the input file for the course numbers, since that number is not predetermined. The only way I can think of to iterate over that unknown amount is using a loop, but that would just overwrite my variables every time. Also, the teacher has requested that we not use any JCL classes (I don't really know what this means.) Sorry if I have done a poor job of explaining this, but I can't think of a better way to conceptualize it. Let me know if I can clarify. Edit: public static void analyzeData() { Scanner inputStream = null; try { inputStream = new Scanner(new FileInputStream("Programming Assignment 1 Data.txt")); } catch (FileNotFoundException e) { System.out.println("File Programming Assignment 1 Data.txt could not be found or opened."); System.exit(0); } int numberOfStudents = inputStream.nextInt(); int tuitionPerHour = inputStream.nextInt(); String firstName = inputStream.next(); String lastname = inputStream.next(); String isTuitionPaid = inputStream.next(); int numberOfCourses = inputStream.nextInt(); String courseName = inputStream.next(); String courseNumber = inputStream.next(); int creditHours = inputStream.nextInt(); String grade = inputStream.next(); To show the methods I am using now, I am just using a Scanner to read from the file and for Scanner inputStream, I am using nextInt() or next() to get variables from the file. Obviously this will not work when I do not know exactly how many classes each student will have.

    Read the article

  • Skipping a line and reading another line in shell script while loop

    - by parameswar
    i have a code which reads a file line by line using a while loop. Inside the while loop, i have certain conditions. Is there a way using which i can skip the current line and read the next line based upon the condition ? Let me be precise: while read Line do //some sample conditions a=$Line if [ "a" == "b" ] //i want to go to the next line from this point. done < **inputfile** Any help would be appreciated.

    Read the article

  • add limited product to cart in android

    - by user1859172
    I have to develop one shopping cart app. Here i have to add the product only 5.otherwise have to display the message on alert dialog like 5 products only allowed. How can i develop this.please help me This is my code: ImageButton mImgAddCart = (ImageButton) findViewById(R.id.img_add); mImgAddCart.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub mTitle = txttitle.getText().toString(); mCost = text_cost_code.getText().toString(); mCost = mCost.replace("From ", ""); mTotal = txt_total.getText().toString(); mTotal = mTotal.replace("From ", ""); mQty = edit_qty_code.getText().toString(); if (Constants.mItem_Detail.size() <= 0) { HashMap<String, String> mTempObj = new HashMap<String, String>(); mTempObj.put(KEY_TITLE, mTitle); mTempObj.put(KEY_QTY, mQty); mTempObj.put(KEY_COST, mCost); mTempObj.put(KEY_TOTAL, mTotal); Constants.mItem_Detail.add(mTempObj); } else { for (int i = 0; i < Constants.mItem_Detail.size(); i++) { if (Constants.mItem_Detail.get(i).get(KEY_TITLE) .equals(mTitle)) { Constants.mItem_Detail.remove(i); break; } else { } } HashMap<String, String> mTempObj = new HashMap<String, String>(); mTempObj.put(KEY_TITLE, mTitle); mTempObj.put(KEY_QTY, mQty); mTempObj.put(KEY_COST, mCost); mTempObj.put(KEY_TOTAL, mTotal); Constants.mItem_Detail.add(mTempObj); } AlertDialog.Builder alertdialog = new AlertDialog.Builder( Small.this); alertdialog.setTitle(getResources() .getString(R.string.app_name)); alertdialog.setMessage("Add in ViewCart"); alertdialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub finish(); } }); alertdialog.show(); } }); How can i set the condition for this.please give me one idea.

    Read the article

  • merging and manupulating files in matlab

    - by Paul
    Is there a way to run a loop through a folder and process like 30 files for a month and give the average,max of each columns and write in one excel sheet or so?? I have 30 files of size [43200 x 30] I ran a different matlab scrip to generate them so the names are easy File_2010_04_01.xls , File_2010_04_02.xls ..... and so on I cannot merge them as each are 20mbs and matlab would crash. Any ideas? Thanks

    Read the article

  • Update Params in Python During Infinite Loop

    - by python Dude
    Hello, I was hoping to get some help on a question. I have an infinite loop that I need run and I need to update a set of variables (x in this case) at random times from the command-line. Is there any way to do this? For example: x = 0 while True: x = x + 1 if x < 30: do something and I need to update x's value from the command-line periodically

    Read the article

  • Basic Python While loop compound conditional evaluation

    - by dbjohn
    In Python IDLE Shell it seems I cannot use a compound conditional expression and a while loop. I tried it within brackets too. k=0 m=0 while k<10 & m<10: print k k +=1 m+=1 If I write while k<10: print k k+=1 This does work. Is there a way I could achieve the first block of code with the "and" operator. I have done it in Java. Do I just need to put together "if" statements to achieve the same functionality in Python?

    Read the article

  • Fatal error: Cannot use string offset as an array

    - by learner
    Array ( [0] = Array ( [auth_id] = 1 [auth_section] = Client Data Base [auth_parent_id] = 0 [auth_admin] = 1 [sub] = Array ( [0] = Array ( [auth_id] = 2 [auth_section] = Client Contact [auth_parent_id] = 1 [auth_admin] = 1 ) ) ) [1] => Array ( [auth_id] => 6 [auth_section] => All Back Grounds [auth_parent_id] => 0 [auth_admin] => ,4 [sub] => Array ( [0] => Array ( [auth_id] => 7 [auth_section] => Edit Custom [auth_parent_id] => 6 [auth_admin] => 1 ) ) ) [2] => Array ( [auth_id] => 20 [auth_section] => Order Mail [auth_parent_id] => 0 [auth_admin] => 1 [sub] => ) } When I process the sub inner array it shows this error how can I avoid that :)

    Read the article

  • Help me refactor my World Cup Challenge Script

    - by kylemac
    I am setting up a World Cup Challenge between some friends, and decided to practice my Ruby and write a small script to automate the process. The Problem: 32 World Cup qualifiers split into 4 tiers by their Fifa ranking 8 entries Each entry is assigned 1 random team per tier Winner takes all :-) I wrote something that suffices yet is admittedly brute force. But, in my attempt to improve my Ruby, I acknowlege that this code isn't the most elegant solution around - So I turn to you, the experts, to show me the way. It may be more clear to check out this gist - https://gist.github.com/91e1f1c392bed8074531 My Current (poor) solution: require 'yaml' @teams = YAML::load(File.open('teams.yaml')) @players = %w[Player1 Player2 Player3 Player4 Player5 Player6 Player7 Player8] results = Hash.new players = @players.sort_by{rand} players.each_with_index do |p, i| results[p] = Array[@teams['teir_one'][i]] end second = @players.sort_by{rand} second.each_with_index do |p, i| results[p] << @teams['teir_two'][i] end third = @players.sort_by{rand} third.each_with_index do |p, i| results[p] << @teams['teir_three'][i] end fourth = @players.sort_by{rand} fourth.each_with_index do |p, i| results[p] << @teams['teir_four'][i] end p results I am sure there is a better way to iterate through the tiers, and duplicating the @players object ( dup() or clone() maybe?) So from one Cup Fan to another, help me out.

    Read the article

  • Is "}while(0);" always equal to "break;}while(1);" ?

    - by Hernán Eche
    I have compared gcc assembler output of do{ //some code }while(0); with do{ //some code break; }while(1); The output is equal, with or without optimization but.. It's always that way? No experiment can prove theories, they can only show they are wrong And because (I hope) programming is not an experimental science, and results can be predicted (at least simple things) I want to be sure next time I reeplace a break;}while(1); for the clearer (and less risky) while(0); Thank you for reading

    Read the article

  • Check the cumulative status of onLoadInit in a for statement

    - by jonobr1
    In a setup like this is it possible to check the cumulative status of all onLoadInit? for(var i:Number = 0; i < limit; i++) { var mcLoader:MovieClipLoader = new MovieClipLoader(); var mclListener:Object = new Object(); mclListener.onLoadInit = function(mc:MovieClip) { trace(i + " is finished loading!"); } mcLoader.addListener(mclListener); mcLoader.loadClip(some_image_path, someMovieClip); } Initially I was thinking that I could pass an array of Boolean's, but I'm not really sure where to add that checkpoint, because a flash frame doesn't keep looping. Would I have to add it to an onEnterFrame()?

    Read the article

  • Pulling $_GET data and creating multidimensional array using loop

    - by Chris J
    I'm creating a checkout for customers and the data about what's in their cart is being sent to a page (for just now) via $_GET. I want to extract that data and then populate a multidimensional array with it using a loop. Here's how I'm naming the data: $itemCount = $_GET['itemCount']; $i = 1; while ($i <= $itemCount) { ${'item_name_'.$i} = $_GET["item_name_{$i}"]; ${'item_quantity_'.$i} = $_GET["item_quantity_{$i}"]; ${'item_price_'.$i} = $_GET["item_price_{$i}"]; //echo "<br />Name: " .${'item_name_'.$i}. " - Quantity: " .${'item_quantity_'.$i}. " - Price: ".${'item_price_'.$i}; $i++; } From here I'd like to create a multidimensional array like such: Array ( [Item_1] => Array ( [item_name] => Shoe [item_quantity] => 2 [item_price] => 40.00 ) [Item_2] => Array ( [item_name] => Bag [item_quantity] => 1 [item_price] => 60.00 ) [Item_3] => Array ( [item_name] => Parrot [item_quantity] => 4 [item_price] => 90.00 ) . . . ) What I'd like to know is if there is a way I can create this array in the existing while loop? I'm aware of being able to add data to an array like $data = [] after delacring an empty array but the actual syntax eludes me. Maybe I'm completely off the right track and there is a better way of doing it? Thanks

    Read the article

  • Is it faster to count down than it is to count up?

    - by Bob
    Our computer science teacher once said that for some reason it is more efficient to count down that count up. For example if you need to use a FOR loop and the loop index is not used somewhere (like printing a line of N * to the screen) I mean that code like this : for (i=N; i>=0; i--) putchar('*'); is better than: for (i=0; i<N; i++) putchar('*'); Is it really true? and if so does anyone know why?

    Read the article

  • SASS color array

    - by Eric Holmes
    I am trying to write a loop that will cycle through colors and condense the amount of code in my scss file. Here is a simple example of what I have: $color1: blue; $color2: red; $color3: white; $color4: black; .color1-bg { background-color: $color1; } .color2-bg { background-color: $color2; } .color1-border { border-color: $color1; } .color2-border { border-color: $color2; } And so on. I am looking for a way to make the equivalent of a foreach loop, and cycle through an 'array' of colours by index. Something like this: @each $color in $color1, $color2, $color3, $color4 { .{$color}-bg { background-color: $color; .{$color}-border { border-color: $color; } I know the syntax is wrong, but that is my thinking process. Thanks for the help!

    Read the article

  • How can I loop through each of the days of a given week in Ruby?

    - by Angela
    I am defining monday and friday using the following: @monday = Date.today.at_beginning_of_week @friday = 5.days.since(@monday) But I actually need, for any given day, to loop through Monday, Tuesday, Wednesday and take that date and put the output into a column. <th>Monday</th> <th>Tuesday</th> etcetera A given row, for example, would be: <tr><td>value(monday)</td><td>value(tuesday)</td><td>value(wednesday)</td></tr> This is where value is a method that takes args date. What's the cleanest way to do this? Thanks.

    Read the article

< Previous Page | 27 28 29 30 31 32 33 34 35 36 37 38  | Next Page >