Search Results

Search found 1698 results on 68 pages for 'loops'.

Page 20/68 | < Previous Page | 16 17 18 19 20 21 22 23 24 25 26 27  | Next Page >

  • C input loop for shell

    - by AustinM
    So I'm working on creating a very simple C program that just preforms shell commands. This is what I have so far: #include <stdio.h> int main() { char input[30]; fputs("$ ", stdout); fflush(stdout); fgets(input, sizeof input, stdin); system(input); } It works, but only for one command. For example if I compile and type ./cmd I get the $ prompt. If I type ls I get what I'm supposed to get. But then it exits and goes back to the regular system shell. How can I make it so after the user types a command it goes back to the "$" input.

    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

  • How to use an adjacency matrix to determine which rows to 'pass' to a function in r?

    - by dubhousing
    New to R, and I have a long-ish question: I have a shapefile/map, and I'm aiming to calculate a certain index for every polygon in that map, based on attributes of that polygon and each polygon that neighbors it. I have an adjacency matrix -- which I think is the same as a "1st-order queen contiguity weights matrix", although I'm not sure -- that describes which polygons border which other polygons, e.g., POLYID A B C D E A 0 0 1 0 1 B 0 0 1 0 0 C 1 1 0 1 0 D 0 0 1 0 1 E 1 0 0 1 0 The above indicates, for instance, that polygons 'C' and 'E' adjoin polygon 'A'; polygon 'B' adjoins only polygon 'C', etc. The attribute table I have has one polygon per row: POLYID TOT L10K 10_15K 15_20K ... A 500 24 30 77 ... Where TOT, L10K, etc. are the variables I use to calculate an index. There are 525 polygons/rows in my data, so I'd like to use the adjacency matrix to determine which rows' attributes to incorporate into the calculation of the index of interest. For now, I can calculate the index when I subset the rows that correspond to one 'bundle' of neighboring polygons, and then use a loop (if it's of interest, I'm calculating the Centile Gap Index, a measure of local income segregation). E.g., subsetting the 'neighborhood' of the Detroit City Schools: Detroit <- UNSD00[c(142,150,164,221,226,236,295,327,157,177,178,364,233,373,418,424,449,451,487),] Then record the marginal column proportions and a running total: catprops <- vector() for(i in 4:19) { catprops[(i-3)]<-sum(Detroit[,i])/sum(Detroit[,3]) } catprops <- as.data.frame(catprops) catprops[,2]<-cumsum(catprops[,1]) Columns 4:19 are the necessary ones in the attribute table. Then I use the following code to calculate the index -- note that the loop has "i in 1:19" because the Detroit subset has 19 polygons. cgidistsum <- 0 for(i in 1:19) { pranks <- vector() for(j in 4:19) { if (Detroit[i,j]==0) pranks <- append(pranks,0) else if (j == 4) pranks <- append(pranks,seq(0,catprops[1,2],by=catprops[1,2]/Detroit[i,j])) else pranks <- append(pranks,seq(catprops[j-4,2],catprops[j-3,2],by=catprops[j-3,1]/Detroit[i,j])) } distpranks <- vector() distpranks<-abs(pranks-median(pranks)) cgidistsum <- cgidistsum + sum(distpranks) } cgi <- (.25-(cgidistsum/sum(Detroit[,3])))/.25 My apologies if I've provided more information than is necessary. I would really like to exploit the adjacency matrix in order to calculate the CGI for each 'bundle' of these rows. If you happen to know how I could started with this, that would be great. and my apologies for any novice mistakes, I'm new to R!

    Read the article

  • while loop / string input not working java

    - by Mikeecb
    I have looked online and all of the tutorials / questions have pointed me to this. I can't see why this isn't working. Any help would be much appreciated. Thanks import java.util.*; public class test { static Scanner userInput = new Scanner(System.in); public static void main(String[] args) { String textEntered = userInput.next(); if (textEntered == "hello") { System.out.println("Hello to you too!"); } } } I enter "hello" but nothing is printed. Also I have tried next() and nextLine();

    Read the article

  • why is there different syntax same outcome?

    - by Lizard
    Why is there different syntax same outcome? For example # Example 1 if($myCondition == true) : #my code here endif; if($myCondition == true) { #my code here } # Example 2 foreach($films as $film) : #my code here endforeach; foreach($films as $film) { #my code here } Also I have been using <?= for ages now and i now understand that is deprecated and I should be using <?php echo Is this the case and why? Its alot more annoying to have to write that out each time. What are your thoughts?

    Read the article

  • PHP while(variable=mysql_fetch_assoc) - explanation

    - by Petr
    Hi, I have been working with C# so this is quite strange for me: while($variable=mysql_fetch_assoc) I have not been able to look up in PHP manual how it works. I guess that in each loop it advances to next element of assoc.array. But what is this generally called in PHP? I am just not used to see '=' in loop condition.

    Read the article

  • [Java]Queue in while loop, cannot modify the value?

    - by javaLearner.java
    This is my code: Iterator it = queue.iterator(); while(it.hasNext()){ random = randNumber(1,2); if(random == 1){ queue.poll(); } else { queue.add("new"); queue.poll(); } } It gives me: Exception in thread "test" java.util.ConcurrentModificationException at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:761) at java.util.LinkedList$ListItr.next(LinkedList.java:696) Edit @Jon Skeet: What I want to do is: I have a queue list in, let say the size is 10, lets say: a,b,c,d ... j Generate a number between 1 and 2. if 1, pull (remove the top element) else if 2 add new element I will stop the loop until I added 3 new elements

    Read the article

  • Strings, regexp and files

    - by A Moose
    <?php $iprange = array( "^12\.34\.", "^12\.35\.", ); foreach($iprange as $var) { if (preg_match($var, $_SERVER['REMOTE_ADDR'])) { I'm looking to have a list that will constitute each of the values inside the array. Let's call it iprange.txt, from which I would extract the variable $iprange. I would also be updating the file with new ranges, but I also want to convert those strings to regexp if that's something that's needed in php, as it is in the above example. If you could help me with the two following issues: I understand that somehow I would be using an array include, but I'm not sure how to implement it. I would like to run a cron that would update the text file and turn it into a regexp acceptable for use in the above example, if you think regexp is a good idea and there isn't another option. I know how to apply a cron in a directadmin gui, but I don't know what the cronned file would look like.

    Read the article

  • If Key Value pair exists in multidimensional array.. How to?

    - by Daniel White
    I have a codeigniter shopping cart going and its "cart" array is the following: Array ( [a87ff679a2f3e71d9181a67b7542122c] => Array ( [rowid] => a87ff679a2f3e71d9181a67b7542122c [id] => 4 [qty] => 1 [price] => 12.95 [name] => Maroon Choir Stole [image] => 2353463627maroon_3.jpg [custprod] => 0 [subtotal] => 12.95 ) [8f14e45fceea167a5a36dedd4bea2543] => Array ( [rowid] => 8f14e45fceea167a5a36dedd4bea2543 [id] => 7 [qty] => 1 [price] => 12.95 [name] => Shiny Red Choir Stole [image] => 2899638984red_vstole_1.jpg [custprod] => 0 [subtotal] => 12.95 ) [eccbc87e4b5ce2fe28308fd9f2a7baf3] => Array ( [rowid] => eccbc87e4b5ce2fe28308fd9f2a7baf3 [id] => 3 [qty] => 1 [price] => 14.95 [name] => Royal Blue Choir Stole [image] => 1270984005royal_vstole.jpg [custprod] => 1 [subtotal] => 14.95 ) ) My goal is to loop through this multidimensional array some how and if ANY product with the key value pair "custprod == 1" exists, then my checkout page will display one thing, and if no custom products are in the cart it displays another thing. Any help is appreciated. Thanks.

    Read the article

  • Javascript looping only through defined properties of array. How?

    - by Beck
    For example if i'm keeping array of references via id like that: if(typeof channel_boards[misc.channel_id] == 'undefined') { channel_boards[misc.channel_id] = $('<div class="channel" channel_id="'+misc.channel_id+'"></div>').appendTo('#board'); } And then i'm looping through array to find required reference. I'm looping through undefined properties as well. Is it possible to loop only through defined properties? for(i=0;i<channel_boards.length;i++) { if(channel_boards[i] != undefined) { if(channel_boards[i].attr('channel_id') != visible) {channel_boards[i].addClass('hidden_board');} else {channel_boards[i].removeClass('hidden_board');} } } Maybe i should change the way i'm storing references? Via object for example, but how i'll be able to find proper reference via id number.

    Read the article

  • Scala Unit type

    - by portoalet
    I use opencsv to parse csv files, and my code is while( (line = reader.readNext()) != null ) { .... } I got a compiler warning saying: comparing values of types Unit and Null using `!=' will always yield true [warn] while( (aLine = reader.readNext()) != null ) { How should I do the while loop?

    Read the article

  • How to output multiple rows from an SQL query using the mysqli object

    - by Jonathan
    Assuming that the mysqli object is already instantiatied (and connected) with the global variable $mysql, here is the code I am trying to work with. class Listing { private $mysql; function getListingInfo($l_id = "", $category = "", $subcategory = "", $username = "", $status = "active") { $condition = "`status` = '$status'"; if (!empty($l_id)) $condition .= "AND `L_ID` = '$l_id'"; if (!empty($category)) $condition .= "AND `category` = '$category'"; if (!empty($subcategory)) $condition .= "AND `subcategory` = '$subcategory'"; if (!empty($username)) $condition .= "AND `username` = '$username'"; $result = $this->mysql->query("SELECT * FROM listing WHERE $condition") or die('Error fetching values'); $this->listing = $result->fetch_array() or die('could not create object'); foreach ($this->listing as $key => $value) : $info[$key] = stripslashes(html_entity_decode($value)); endforeach; return $info; } } there are several hundred listings in the db and when I call $result-fetch_array() it places in an array the first row in the db. however when I try to call the object, I can't seem to access more than the first row. for instance: $listing_row = new Listing; while ($listing = $listing_row-getListingInfo()) { echo $listing[0]; } this outputs an infinite loop of the same row in the db. Why does it not advance to the next row? if I move the code: $this->listing = $result->fetch_array() or die('could not create object'); foreach ($this->listing as $key => $value) : $info[$key] = stripslashes(html_entity_decode($value)); endforeach; if I move this outside the class, it works exactly as expected outputting a row at a time while looping through the while statement. Is there a way to write this so that I can keep the fetch_array() call in the class and still loop through the records?

    Read the article

  • How to import datarow from one dataset to another?

    - by Disciple
    Hi, I want to copy the row to the new dataset if the previous value in second column isn't the same as the current one (i.e this dataset should have rows with unique values): DataTable tbl = new DataTable(); DataTable tmpTable = ds.Tables[0]; for( var rowIndex = 0; rowIndex < ds.Tables[0].Rows.Count; rowIndex++ ) { object value = null; foreach (DataRow x in tbl.Rows) { if (ds.Tables[0].Rows[rowIndex][1] == x[1]) { value = ds.Tables[0].Rows[rowIndex][1]; break; } } // value already exists if (value == null) { tbl.ImportRow(ds.Tables[0].Rows[rowIndex]); } } How to do this correctly? Maybe one loop instead 2?

    Read the article

  • Need help specifying a ending while condition

    - by johnthexiii
    I have written a Python script to download all of the xkcd comic images. The only problem is I can't tell it to stop when it gets to the last one... Here is what I have so far. import re, mechanize from urllib import urlretrieve from BeautifulSoup import BeautifulSoup as bs baseUrl = "http://xkcd.com/1/" #Specify the first comic page br = mechanize.Browser() #Create a browser response = br.open(baseUrl) #Create an initial response x = 1 #Assign an initial file name while (SomeCondition): soup = bs(response.get_data()) #Create an instance of bs that contains the response data img = soup.findAll('img')[1] #Get the online file path of the image localFile = "C:\\Comics\\xkcd\\" + str(x) + ".jpg" #Come up with a local file name urlretrieve(img["src"], localFile) #Download the image file response = br.follow_link(text = "Next >") #Store the response of the next button x += 1 #Increase x by 1 print "All xkcd comics downloaded" #Let the user know the images have been downloaded Initially what I had was something like while br.follow_link(text = "Next >") != br.follow_link(text = ">|"): but by doing this I actually send skip to the last page before the script has a chance to perform the intended purpose.

    Read the article

  • My MYSQL & PHP while code is out of memory, when there is only one row

    - by Sam
    Hey all, why is this code throwing an out of memory error, when there is only 1 row in the database.. $request_db = mysql_query("SELECT * FROM requests WHERE haveplayed='0'") or die(mysql_error()); $request = mysql_fetch_array( $request_db ); echo "<table border=\"1\" align=\"center\">"; while ( $request['haveplayed'] == "0" ) { echo "<tr><td>"; echo $request['SongName']; echo "</td><td>"; echo "<tr><td>"; echo $request['Artist']; echo "</td><td>"; echo "<tr><td>"; echo $request['DedicatedTo']; echo "</td><td>"; } echo "</table>"; Thanks.

    Read the article

  • loop prematurely quitting

    - by Nick Gibson
    This loop works fine but prematurely quits at times. I set a piece of code in it so that I can view the random number. It only closes prematurely when the random number is equal to the highest numbered question the user inputs (Example...a user wants 10 questions, if the random number is 10 the program quits.) I have no idea why since i have it set to if(random number <= the number of questions) for ( int loop = 1; loop < loopCount; loop++ ) { aa = r.nextInt ( 10 + 1 ); abc = ( int ) aa; String[] userAnswer = new String[x]; JOptionPane.showMessageDialog ( null, abc ); if ( abc <= x ) { for ( overValue = 1; overValue < forLoop; overValue++ ); { userAnswer[j] = JOptionPane.showInputDialog ( null, "Question " + quesNum + "\n" + questions[abc] + "\n\nA: " + a[abc] + "\nB: " + b[abc] + "\nC: " + c[abc] + "\nD: " + d[abc] ); if ( userAnswer[j].equals ( answers[j] ) ) { JOptionPane.showMessageDialog ( null, "Correct. \nThe Correct Answer is " + answers[abc] ); } else { JOptionPane.showMessageDialog ( null, "Wrong. \n The Correct Answer is " + answers[abc] ); }//else }//for }//if }//for

    Read the article

  • How to do elif statments more elegantly if appending to array in python

    - by user1741339
    I am trying to do a more elegant version of this code. This just basically appends a string to categorynumber depending on the number. Would appreciate any help. number = [100,150,200,500] categoryNumber = [] for i in range (0,len(number)): if (number [i] >=1000): categoryNumber.append('number > 1000') elif (number [i] >=200): categoryNumber.append('200 < number < 300') elif (number [i] >=100): categoryNumber.append('100 < number < 200') elif (number [i] >=50): categoryNumber.append('50 < number < 100') elif (number [i] < 50): categoryNumber.append('number < 50') for i in range(0,len(categoryNumber)): print i

    Read the article

  • How do you chain functions dynamically in jQuery?

    - by clarke78
    I want to loop through an object that contains functions which will execute one after another. My most ideal approach would be to have these chain somehow (ie. func2 waits for func1 and func3 waits for func2) but this needs to happen dynamically and the functions will all have different durations. I'm using jQuery so I thought that perhaps "queue()" may help but I haven't worked with it much. A main concern is to not add any scope/callbacks to the functions within the object. I'd rather somehow enclose them within a parent function to execute within the loop in order to create the callback/chaining. Here's an example of what I've got now, but dumbed down. Thanks for any help! var obj = [ {'name':'func1','callback':function(){ alert(1); }}, {'name':'func2','callback':function(){ alert(2); }}, {'name':'func3','callback':function(){ alert(3); }} ]; $.each(obj, function(x, el) { el.callback(); });

    Read the article

  • Calling multiple functions simultaneously with jquery.

    - by clarke78
    I want to loop through an object that contains functions which will execute one after another. My most ideal approach would be to have these chain somehow (ie. func2 waits for func1 and func3 waits for func2) but this needs to happen dynamically and the functions will all have different durations. I'm using jQuery so I thought that perhaps "queue()" may help but I haven't worked with it much. A main concern is to not add any scope/callbacks to the functions within the object. I'd rather somehow enclose them within a parent function to execute within the loop in order to create the callback/chaining. Here's an example of what I've got now, but dumbed down. Thanks for any help! var obj = [ {'name':'func1','callback':function(){ alert(1); }}, {'name':'func2','callback':function(){ alert(2); }}, {'name':'func3','callback':function(){ alert(3); }} ]; $.each(obj, function(x, el) { el.callback(); });

    Read the article

  • Loop on enumeration values

    - by Rachel
    How awful is it - or is it perfectly acceptable - to index a loop on an enumeration? I have an enumeration defined. The values of the literals are default values. The assigned values do not have any significance, will not have any significance, and the values of any literals added in the future will also not have any significance. It's just defined to limit the allowed values and to make things easier to follow. Therefore the values will always start at 0 and increase by 1. Can I set up a loop like so: enum MyEnum { value1, value2, value3, maxValue } for(MyEnum i = value1; i < maxValue; i = static_cast<MyEnum>(i+1)){}

    Read the article

  • [java] How to get ALL the information from a socket

    - by raven
    Hello, I'll begin this question with the claim that I have read the java networking guide before asking you. I do not understand how to READ the socket and get all the info summed up into a string. the socket might contains more than 1 line [trying to make a chat]. Please do no refer me to any other site unless it clearly states "this exact line does this.." because I failed to understand what this code part does BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); } Please, I just want to make a loop that will receive information from a socket, get all the content together into one string [I also want it to know where to add another line]. Thanks allot for anyone who helps, I have been trying to get an answer from tuts for hours and just failed to understand!

    Read the article

  • form_for called in a loop overloads IDs and associates fields and labels incorrectly

    - by Katy Levinson
    Rails likes giving all of my fields the same IDs when they are generated in a loop, and this causes trouble. <% current_user.subscriptions.each do |s| %> <div class="subscription_listing"> <%= link_to_function s.product.name, "toggle_delay(this)"%> in <%= s.calc_time_to_next_arrival %> days. <div class="modify_subscription"> <%= form_for s, :url => change_subscription_path(s) do |f| %> <%= label_tag(:q, "Days to delay:") %> <%= text_field_tag(:query) %> <%= check_box_tag(:always) %> <%= label_tag(:always, "Apply delay to all future orders") %> <%= submit_tag("Change") %> <% end %> <%= link_to 'Destroy', s, :confirm => 'Are you sure?', :method => :delete %> </div> </div> <% end %> Produces <div class="subscription_listing"> <a href="#" onclick="toggle_delay(this); return false;">Pasta</a> in 57 days. <div class="modify_subscription"> <form accept-charset="UTF-8" action="/subscriptions/7/change" class="edit_subscription" id="edit_subscription_7" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /><input name="_method" type="hidden" value="put" /><input name="authenticity_token" type="hidden" value="s5LJffuzmbEMkSrez8b3KLVmDWN/PGmDryXhp25+qc4=" /></div> <label for="q">Days to delay:</label> <input id="query" name="query" type="text" /> <input id="always" name="always" type="checkbox" value="1" /> <label for="always">Apply delay to all future orders</label> <input name="commit" type="submit" value="Change" /> </form> <a href="/subscriptions/7" data-confirm="Are you sure?" data-method="delete" rel="nofollow">Destroy</a> </div> </div> <div class="subscription_listing"> <a href="#" onclick="toggle_delay(this); return false;">Gummy Bears</a> in 57 days. <div class="modify_subscription"> <form accept-charset="UTF-8" action="/subscriptions/8/change" class="edit_subscription" id="edit_subscription_8" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /><input name="_method" type="hidden" value="put" /><input name="authenticity_token" type="hidden" value="s5LJffuzmbEMkSrez8b3KLVmDWN/PGmDryXhp25+qc4=" /></div> <label for="q">Days to delay:</label> <input id="query" name="query" type="text" /> <input id="always" name="always" type="checkbox" value="1" /> <label for="always">Apply delay to all future orders</label> <input name="commit" type="submit" value="Change" /> </form> <a href="/subscriptions/8" data-confirm="Are you sure?" data-method="delete" rel="nofollow">Destroy</a> </div> </div> And that's a problem because now no matter which "Apply delay to all future orders" I select it always very helpfully checks the first box for me. How can I override the ID without doing something ugly and un-rails-like?

    Read the article

< Previous Page | 16 17 18 19 20 21 22 23 24 25 26 27  | Next Page >