FAQ Database Discussion Community


NSMutableArray adds same NSDictionary multiple times

ios,objective-c,for-loop,nsarray,nsdictionary
I am looping through an array, getting two items and putting them in a dictionary, and then add them to an array, but it keeps adding the last item of the array for the number objects in the array, even though when I log the dictionary inside the loop it...

How to create an item list to use multiple times on a Jinja2 template page?

python,python-3.x,for-loop,flask,jinja2
I want to create an HTML option list and display it multiple times on the template page. I tried to iterate through the list passed on to the template but this seems only to work once on the page: {% for item in points %} <option value="{{ item }}">{{ item...

For-loop does not go over all objects

python,list,for-loop
Why does this for-loop not go through all items: temp = 0 for br in my_list : temp +=1 #other code here #my list is not used at all, only br is used inside here my_list.remove(br) print temp assert len(my_list) == 0 , "list should be empty" So, assertion fires....

Matlab: Looping through an array

matlab,loops,for-loop,while-loop,do-while
This is my one dimensional array A. containing 10 numbers A = [-8.92100000000000 10.6100000000000 1.33300000000000 ... -2.57400000000000 -4.52700000000000 9.63300000000000 ... 4.26200000000000 16.9580000000000 8.16900000000000 4.75100000000000]; I want the loop to go through like this; (calculating mean interval wise) - Interval length of 2,4,8 (a(1)+a(2))/2 - value stored in one block of...

R Creating a Character Column from a Numeric Column w/o using For Loop

r,for-loop,mapping,character,lookup
I am trying to create a column of characters based on an existing column of numbers, preferably without using a for loop. I have come up with a variety of ways to do this, but I keep feeling like I'm making this far more complicated than it needs to be....

Create an object that contains an array of objects with a for loop

javascript,for-loop
I would like to create on JavaScript an object of one array (line_items_object) that contains objects with a for loop like this structure: var data = { line_items_object: [ { id: 8111696 }, { id: 8111688 } ] }; How can I do that? ...

iterating over a table passed as an argument to a function in lua

for-loop,lua,iterator,lua-table
I am trying using the for _ in pairs() notation to iterate over a table within a function, but if I type anything, even gibberish like print('asdgfafs'), nested inside the for loop, it never gets printed. Code: record = {bid1,bid2,bid3} bid1 = {bidTime = 0.05,bidType = 'native'} bid2 = {bidTime...

For loop not only passing once

for-loop,selenium-webdriver
String[] expected = new String[10]; //{"Acapulco","Frankfurt","London","New York","Paris","Portland","San Francisco","Seattle","Sydney","Zurich"}; expected[0] = "Acapulco"; expected[1] = "Frankfurt"; expected[2] = "London"; expected[3] = "New York"; expected[4] = "Paris"; expected[5] = "Portland"; expected[6] = "San Francisco"; expected[7] = "Seattle"; expected[8] = "Sydney"; expected[9] = "Zurich"; List<WebElement> allOptions = driver.findElements(By.name("fromPort")); // match the fromPort list...

Can not figure out how to print second dimension in three dimension List

c#,list,for-loop,dimensions
I am making lists in three dimensions. If I run my code it shows the following strings: list5 + list3 + list1. Now this is in three dimensions, so each dimension adds a word. If you look to the code there will be displayed: 4*4*4 = 64 possiblities. Now I...

How to get get max value in java? [closed]

java,for-loop,max
I am writing a program that finds the taxes based on a person's income. So far the problem I am running into is some numbers that come out don't round up two decimal places and keep on going and I don't know how to get the max out of all...

bash - for loop for IP range excluding certain IPs

bash,for-loop,ip,ip-address,exclude
I have the below for loop for ip in 10.11.{32..47}.{0..255} do echo "<ip>${ip}</ip>" done I want to exclude this iprange: 10.11.{32..35}.{39..61} from the above for loop. This ip range is a subset of the above one. Is there a way to do that? I tried this, this doesn't work: abc=10.11.{34..37}.{39..61}...

matlab Create growing matrix with for loop that grows by 3 per loop

matlab,loops,for-loop,matrix
So I have written this: HSRXdistpR = squeeze(comDatape_m1(2,7,1,:,isubj)); HSRXdistpL = squeeze(comDatape_m1(2,4,1,:,isubj)); TocomXdistp = squeeze(comDatape_m1(2,10,1,:,isubj)); for i = 1:2; HSRXp = NaN(8,3*i); HSRXp(:,i*3) = [HSRXdistpR(:,i) HSRXdistpL(:,i) TocomXdistp(:,i)]; end In the first part I am just selecting data from a 5-D matrix, nothing special. All that's important here is that it creates...

Matlab Reintroduction of AR and GARCH processes

matlab,for-loop,return,time-series,volatility
I am trying reintroduce autocorrelation and heteroskedasticity to my simulated residuals. My simulated (standardized) residuals have the dimension (horizon, nTrials, nIndices). In order to calculate today's mean / variance (i.e. t), I need to use the last periods mean /variance (i.e. t-1) as an input. This is where I am...

How to remove all Objects in For Loop?

actionscript-3,for-loop,flash-cs6
Hey Everyone So I know this has to be really Simple I am over complicating it and can't figure out how to do it. So I have these stars moving in the background in my startScreen and I want to remove them when the Game starts. Here is How I...

Matlab loop not working properly

matlab,loops,for-loop
largest = 0; num = 0; temp = 0; num_flip = 0; for x = 100 : 999 for y = x : 999 num = x*y; temp = num2str(num); num_flip = str2double(fliplr(temp)); if num/num_flip == 1 largest = num; one = x; two = y; end end end I'm...

swift iterate on array

json,swift,for-loop
i would like to ask a little help. I have a method which call a webservice and get a json object from it. it's look like this way: func wsServiceFeedTst() { println("WS called...") println("tstFrames count: " + tstFrames.count.description) let json = JSON(url:"http://79.172.249.175:7001/RestWebServiceApp/webresources/entity.bkkkallerfeedtst") println(json) for (k, v) in json["bkkKallerFeedTst"] { let...

For loop - 2 arrays

javascript,arrays,for-loop,sum
I'm a beginner and I've been stuck for hours. I have problems with a simple for loop. I want an alert box that gives me the sum of the bars controlled by the player (it's part of the code for a simple boardgame) This is my code: var districts =...

looping variable in swift

swift,for-loop,uiimage
i want to change this variable become looping in swift: var image1 = UIImage(named: "image1") var image2 = UIImage(named: "image2") var image3 = UIImage(named: "image3") var image4 = UIImage(named: "image4") var image5 = UIImage(named: "image5") var image6 = UIImage(named: "image6") var image7 = UIImage(named: "image7") images.append(image1!) images.append(image2!) images.append(image3!) images.append(image4!) images.append(image5!)...

Filling PHP array with “for” loop

php,arrays,for-loop,population
I'm trying to populate an array in PHP as following : <?php $maxPages = 20; for ($i = 0; $i <= $maxPages; $i++) { $url = 'http://127.0.0.1/?page='.$i; $targets = array( $url => array( CURLOPT_TIMEOUT => 10 ), ); } print_r($targets); ?> However it only seems to display the last populated...

Continuous to discrete cut quartile in R from for loop

r,loops,for-loop,cut,quartile
I am trying to create a bunch of columns that are quartile cuts based on multiple columns. For example, dataset[,412:422] <- NA for( i in 50:60){ for(j in 412:422){ dataset[,j] <- cut(dataset[,i], breaks=unique(quantile(dataset[,i],probs=seq(.1,1,by=.1),na.rm=T)), include.lowest=TRUE) } } I want to create new columns 412 to 422 based on the binning of...

How to build a 'for' loop with input$i in R Shiny

r,loops,for-loop,shiny
In my shiny app, I build a a number of checkboxes using a for loop, like this: landelist <- c("Danmark", "Tjekkiet", "Østrig", "Belgien", "Tyskland", "Sverige", "USA", "Norge", "Island") landecheckbox <- c() for (land in landelist){ landechek <- paste0("<label class=\"checkbox inline\"><input id=\"", land, "\" type=\"checkbox\" checked><span>", land, "</span></label>") landecheckbox <- c(landechek,...

Change a Script to a For Do Done Loop

linux,bash,for-loop,awk
I have a script that I need to turn into a loop, the script works exactly as I need it to (My Awk-fu is extremely weak, so be nice) when I put in the file name like the example below. #!/bin/bash awk -v FS='(<LastName>|<\/LastName>)' '{print $2}' 17822624.xml >> test.csv awk...

Item not being properly indexed in PHP array inside of for loop

php,arrays,for-loop,attachment,binaryfiles
I have a for loop that is pulling attachments from email using PHP's IMAP functions. This works fine for one attachment, but it is unable to pull more than one attachment from a single mail. See code below - for ($i = 0; $i < $count; $i++) { $attachments[$i] =...

Java print result every 10th iteration of a for loop

java,for-loop
I'm trying to write simple function to print a message every 5th or 10th iteration of for loop. for example: In this code I want to print i each tenth iteration: private void calc() { int broadcast_by_percent = 100 / 10; int calculate = 0; for (int i = 0;...

Iteratively adding new columns to a list of data frames

r,list,for-loop,data.frame
I am trying to write some code that iterates through a list of data frames, adding to each a new column that contains the same values as an older column but shifted by 1. The first value in this column will be NA. Below is my code: for(dataframe in 1:length(listOfDataFrames)){...

php for loop of an array

php,html,arrays,for-loop
I have an html form that passes an array into php and then does a for loop to print out values. This is the code that I have $payloads = $_POST['topay']; $loadNum = $_POST['loadnum']; $unit = $_POST['unit']; $driver = $_POST['driver']; for($i=0;$i<count($payloads);$i++) { echo $payloads[$i]; echo "<br>"; echo '<td width="50" valign="top">'.$loadNum[$i].'</td>';...

Cancel last line iteration on a file

python,python-3.x,for-loop,file-io
I need to iterate on a file, stop iteration on a condition and then continue parse the file at the same line with another function (That may change so I can't just add content in the previous function). An example file (file.txt) : 1 2 3 4 5 6 7...

Combine or merge 2 array with loop or function

c,arrays,for-loop,merge
I'm new to the C world. I'm using Visual 2010. I need to create an array from 2 other arrays, or a function to merge them; I come from PHP so I'm sorry if this is stupid. I tested some loop without success.. a real example could be helpful: int...

Printing off the content of Array or Set using for loop

arrays,swift,for-loop,set,println
When trying to print off the content of Set or Array using for loop I don't receive values but number of them. For example: var favouriteSports: Set = ["Snowboarding", "Skateboarding", "Surfing"] for genre in favouriteSports { print("\(genre)") } What I wanted to receive in console is "Snowboarding, Skateboarding, Surfing" but...

Combining multiple for loops into one using the OR operator

c++,if-statement,for-loop
This is probably a simple question, but I can't get it to work. I've searched and have tried all the suggestions people gave for the OR operator ||, but my code just won't properly use it. So here's what I've got: This part of my code looks at a vector...

How to use list comprehensions to make a dict having list of list as values

python,list,for-loop
I Have a list as following and I want to convert that as output shown below using List comprehensions. Any help is appreciated. a = [{'type': 'abc', 'values': 1}, {'type': 'abc', 'values': 2}, {'type': 'abc', 'values': 3}, {'type': 'xyz', 'values': 4}, {'type': 'xyz', 'values': 5}, {'type': 'pqr', 'values': 6}, {'type':...

concurrent modification on arraylist

java,for-loop,arraylist,concurrentmodification
There are a lot of concurrent mod exception questions, but I'm unable to find an answer that has helped me resolve my issue. If you find an answer that does, please supply a link instead of just down voting. So I originally got a concurrent mod error when attempting to...

Parallel for loop with reduction and manipulating arrays

c,for-loop,openmp,pragma
I'm new to openMP and I try to optimize for loop. The result is not as expected, the for loops are not working correctly (due to dependency). I don't understand how to get a perfect parallel loop with the examples below : #pragma omp parallel for default(shared) reduction(+...) for(i =...

Add XElement dynamically using loop in MVC 4?

c#,xml,asp.net-mvc-4,for-loop
i will like to add the Xelement in Xdocument but how can i add in dynamically using loop? I need to capture the user multiple answer and generate the Xelement dynamically. Please guide me or provide any hint. Thanks alot! [HttpPost] public ActionResult SURV_Answer_Submit(List<AnswerQuestionViewModel> viewmodel, int Survey_ID, string Language) {...

What's the fastest way to compare point elements with each other?I have used Nested for loop to do that, but it's very slow

c++,opencv,for-loop,dictionary,vector
I want to find the points which the distant between points less than 3.For example, some points as follow, (220,221)(220,119)(220,220)(20,90)(220,222). I use (220,221) to find points.Then i can get (220,221)(220,119)(220,220)(220,222) I use (220,119) to find points.Then i can get (220,221)(220,119)(220,220) I have used Nested for loop to do that, but...

How to dynamically name my object params in this lodash loop?

javascript,loops,for-loop,lodash
https://lodash.com/docs#find var params = {}; _.forEach(n.tags, function(n, index) { console.log(index); index++ // For each tag, create new param.term1, term2, term3 etc... params.term[index] = _.result(_.find(n.tags, function(term_id) { return term_id; }), 'term_id'); }); The _.forEach will loop over n.tags (which contains up to 3 tags). I iterate the index++ by 1 so...

How can I set OptionButton font using VBA For Loop?

excel,vba,excel-vba,loops,for-loop
I am trying to manually set every OptionButton's font on a sheet to be a uniform size and type using a For Loop. I can do them manually by writing out each specific button's information but I have hundreds of buttons. I can even get VBA to write the correct...

Javascript For Loop with Iterator In the Middle and Decrement Operator to the Left of i?

javascript,for-loop,syntax,decrement
For a non-recursive example of a factorial function I found this example and am having a little difficulty tracing through the code: function fact(x) { if(x == 0) { return 1; } if(x < 0 ) { return undefined; } for(var i = x; --i; ) { x *= i;...

Can javascript for loop starts from negative number? [closed]

javascript,jquery,loops,for-loop
Here is a standard for loop: for (i=0; i<=5; i++) { el.append('<span>' + i + '</span>'); } This should append 11 spans with text from -5 up to 5, but this doesn't work at all... for (i=-5; i<=5; i++) { el.append('<span>' + i + '</span>'); } Is it possible to...

Matlab: Writing to a file

arrays,matlab,loops,math,for-loop
I want to store mean_2....mean_8, std_2....std_8, and coVariance as separate columns in a file. Help Please? This Code calculates IntervalFeatures of Erp signal with 256 time frames and plots them Datapoints are store in A ___________HowTheCodeWorks________________________________________________ each 1x4 sliding sub-matrix is made a column for eg:- if A is...

How to sort multidimentional array

c++,c,sorting,for-loop
New to coding ! After many attempts to use sort without success, here my actual code : #include <algorithm> #define N 5 int a[N] = { 3, 6, 2, 4, 1 }; int b[N] = { 6, 3, 1, 2, 9 }; int c[N][3]; for ( size_t i = 0;...

System.ArgumentOutOfRangeException in For loop due to entry deleted from database. Help fix it

database,vb.net,for-loop,indexing
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim TimeNow As DateTime TimeNow = DateTime.Now With ReservationTableDataGridView For i As Integer = 0 To (.Rows.Count - 1) ListView1.BackColor = Color.Black Dim ToBeTested As DateTime ToBeTested = (.Rows(i).Cells(1).Value) # Console.WriteLine(ToBeTested) If ToBeTested > TimeNow.AddMinutes(45) Then Me.ReservationTableTableAdapter.Delete((.Rows(i).Cells(4).Value), (.Rows(i).Cells(1).Value), (.Rows(i).Cells(2).Value), (.Rows(i).Cells(3).Value))...

Error using range-based for loop - Eclipse CDT Luna

templates,c++11,for-loop,mingw,eclipse-luna
I am a beginner at C++ programming. I tried to write a very simple program that combines the use of templates, passing arrays as arguments to a function and a range-based for loop. This is the program that I wrote and compiled using the Eclipse Luna CDT software. #include <iostream>...

R vector looping confusion [closed]

r,for-loop,vector
I'm learning R and I have tracked down a problem in my code to an expectation of what looping over a vector would do. Here's what I'm confused by--say I've got a numeric vector with two nonconsecutive elements in it. x <- c(1, 3) If I loop through the vector...

consistent matched pairs in R

r,for-loop,matching
So using the Matching Package (Link to package here) We can work through a modified GenMatch example. library(Matching) data(lalonde) #introduce an id vaiable lalonde$ID <- 1:length(lalonde$age) X = cbind(lalonde$age, lalonde$educ, lalonde$black, lalonde$hisp, lalonde$married, lalonde$nodegr, lalonde$u74, lalonde$u75, lalonde$re75, lalonde$re74) BalanceMat <- cbind(lalonde$age, lalonde$educ, lalonde$black, lalonde$hisp, lalonde$married, lalonde$nodegr, lalonde$u74, lalonde$u75, lalonde$re75, lalonde$re74,...

Display text once within for loop on the first loop

php,for-loop
I have SQL query inside a for loop and I want to echo something of success of these query only once. Here is part of my code <?php for($i=0;$i<sizeof($assigned_project_id);$i++){ $sql2="SELECT * FROM assign_task INNER JOIN branch ON assign_task.branch_ID=branch.branch_ID WHERE project_ID=".$assigned_project_id[$i]." AND USER_ID=1"; $query2=mysqli_query($con,$sql2); if(mysqli_num_rows($query2)>0){ echo" You have Assigned following Reports";...

Create a new loop without quotation marks

python,string,for-loop
I wrote a function on python that should print the sentences below. def write_to_file(matrix, path): f = open(path, "w") f.write('\r\n') for i in range (2,5): item = (bestQuarterRate(matrix, i)) item = (str(item)) print item f.write(item) f.close() The problem is that I get this: ('Highest quarter rate is between', '1/1/15', 'and',...

Retrieve index of newly added row - for loop in R

r,for-loop,indexing
I am trying to retrieve the index of a newly-added row, added via a for loop. Starting from the beginning, I have a list of matrices of p-values, each with a variable number of rows and columns. This is because not all groups have an adequate number of treated individuals...

TIme complexity of various nested for loops

loops,for-loop,big-o,time-complexity,asymptotic-complexity
Time Complexity of a loop is considered as O(Logn) if the loop variables is divided / multiplied by a constant amount. loop 1 ---- for (int i = 1; i <=n; i *= c) { // some O(1) expressions } loop 2 ----- for (int i = n; i >...

Javascript: Forloop Difference between i++ and (i+1)

javascript,loops,for-loop
I was building a javascript for loop and I want to compare the value of an array to the next value in the array. If both values are not equal, I want to return true, otherwise I want to return false. In the code below I pass the string "aba",...

Converting Object Names to Strings in AS2

string,object,for-loop,actionscript-2,movieclip
So i've made an object called "potato", then started a loop to check if something in "_level0" has the name of "_level0.potato". What i think is that since the the things in _level0 are objects instead of strings, the object name can't be recognized as a string, so im guessing...

Time complexity of if-else statements in a for loop

if-statement,for-loop,time-complexity,asymptotic-complexity
Let A[1, …, n] be an array storing a bit (1 or 0) at each location, and f(m) is a function whose time complexity is θ(m). Consider the following program fragment written in a C like language: Case 1 :- counter = 0; for (i = 1; i < =...

Jekyll and Liquid for-loop

html5,for-loop,navigation,jekyll,liquid
I want to create a little side navigation vor on-page navigation. The site contains multiple images one above the other, the navigation is inside every single image and is linking to the individual id's. I am using jekyll with the liquid templating engine. To not hard code every single element...

How to retrieve filtered data from json with double for loop

javascript,json,loops,for-loop,filter
So i have build up this json file (http://www.smartbustracking.be/json/data.json) and now i am able to retrieve data. but what i would like to achieve is to filter data based on id with a for loop. i am able to show one item of a specific id but not all the...

iteration (for-loop) ms Access with past value

vba,for-loop,access-vba,iteration,recordset
I tried to translate a code from VBA excel to access. My data is a column of prices and I want to compute the returns. This is the original VBA code in excel: DerCol = Cells(T.Row, Columns.Count).End(xlToLeft).Column Cells(T.Row, DerCol + 1) = "Returns" For i = T.Row + 2 To...

How are the results for count different in all these three cases?

python,for-loop,while-loop,break
Code 1: iteration = 0 count = 0 while iteration < 5: for letter in "hello, world": count += 1 print "Iteration " + str(iteration) + "; count is: " + str(count) iteration += 1 Code 2: iteration = 0 while iteration < 5: count = 0 for letter in...

Making var 's in a for-loop

c#,for-loop,var
It is hard to explain but I will show an example of what I want in my code: At the moment I do it this way: var something1 = new (Microsoft.Office.Interop.Excel.Worksheet)appExcel.Worksheets.Add(Type.Missing, appExcel.Worksheets[appExcel.Worksheets.Count], 1, XlSheetType.xlWorksheet); var something2 = new (Microsoft.Office.Interop.Excel.Worksheet)appExcel.Worksheets.Add(Type.Missing, appExcel.Worksheets[appExcel.Worksheets.Count], 1, XlSheetType.xlWorksheet); var something3 = new...

Doubts with for loop in Unix

bash,shell,unix,for-loop
Sorry if its sounds dumb but I'm currently studying for an exam to apply for a job (administrative one) and I learnt about java, php, python but not much about unix scripts. I can see it's very similar to php in structure and I have many questions about it ....

Using for loop indices in variable generation SAS

for-loop,sas
I would like to set up a for loop in SAS where I would like to create time dependent tables. The idea is rather simple. I have multiple tables where I would like to left join them and i would like to this operation for every month. I dont have...

Java - allocation in enhanced for loop

java,for-loop,memory
I have small problem in java with allocation of my object in "enhanced for loop". I tried something like this, which gives me later nullPointerException: SomeClass tab[] = new SomeClass[100]; for( SomeClass x : tab){ x = new SomeClass(); } So... Earlier I code in C++ and It was possible...

Why does my nested for-if loops load much slonger when I dont nest this? And can I possibly fix this?

c#,excel,if-statement,for-loop,nested
Sorry if the question if a bit vague, but the code is very complicated and I hope you will have the right eye to see and understand it :) I will show 2 sort codes. The codes just read an excel sheet and depending on the text it contains, it...

Objective C for loop delay

objective-c,for-loop,cocos2d-iphone,delay,grand-central-dispatch
I have a for loop that I want to add a delay between iterations. I have changed waitUntilDone to YES and get the same results. My array only has two numbers in it and both are called after the five seconds instead of: 0s - nothing 5s - Block called...

Using function “cat” with “replicate” in R

r,for-loop,cat,replicate
Is there a way how to combine function "cat" with function "replicate" in R? I want to see number of "loops" R has already made at a particular moment. However, instead of using "for" loop, I prefer to use "replicate". See the simple example below: Data <- rnorm(20,20,3) # with...

Using a for loop to search array

java,arrays,for-loop
I am working on an assignment and am stuck on one part. Searching my array to see if it contains the number 4. I am also having the problem of that answer repeating 10 times. I know why that is happening I just don't know how to fix it. I...

Why cant I refer to a random index in my 4D list, while I know it exists?

c#,list,for-loop,dimensions
I got a 4D list, and I want where I want to display only the [k][3][j][z], but this isnt working. I checked all the counts and they are all 5+, so 3[4] should work... for (int k = 0; k < lijst4D.Count; k++) { for (int i = 0; i...

Understanding the for loop in java

java,for-loop
I'm new to java as you can see. I can't seem to understand why these two codes have different output. Please explain it to me. What is the difference of y<=x; and y<=5;. As you can see the x is = 5 too, I don't get why I get different...

An easier way of referring to the index of a desired dictionary (Python)?

python,for-loop
Question feels like it's phrased poorly, feel free to adjust it if you agree and know how better to phrase it. I have the following code: def owned_calendars(cal_items): """Returns only the calendars in which the user is marked as "owner" """ owner_cals = [] for entry in cal_items: if entry['accessRole']...

Matlab Calculating mean of distribution quantile in a for-loop

matlab,loops,for-loop,distribution,quantile
I am trying to calculate portfolio cVaR (conditional value at risk) levels from my simulated data for various portfolios. I am able to do that for one single portfolio using the following code: % Without a for-loop for series 1 test2 = test(:,1) VaR_Calib_EVT = 100 * quantile(test2, VarLevel_Calib); help1...

for of loop querySelectorAll

javascript,google-chrome,for-loop,mozilla,queryselectorall
Mozilla states that "for of loops will loop over NodeList objects correctly". (source: https://developer.mozilla.org/en-US/docs/Web/API/NodeList) However, this doesn't work in Chrome 43. Is this incorrect documentation or a browser bug? The copied example code used on a page with checkboxes: var list = document.querySelectorAll( 'input[type=checkbox]' ); for (var item of list)...

Why is my C code printing out an extra line of rows?

c,loops,for-loop,macros,printf
#include <stdio.h> #define rows 500 //can define rows as any number int main() { int i,j; for(i=0;i<=rows;++i) { for(j=0;j<(2*i+1);++j) { printf("* "); } printf("\n"); } return 0; } So here is my code, what it does is it prints the number of rows set by #define and creates a right...

for loop vs for loop in reverse: performance

javascript,performance,for-loop
According to What's the Fastest Way to Code a Loop in JavaScript? and Why is to decrement the iterator toward 0 faster than incrementing , a basic for loop is slower than a for - loop with simplified test condition, i.e.: console.log("+++++++"); var until = 100000000; function func1() { console.time("basic")...

for-loop add columns using SQL in MS Access

sql,ms-access,table,for-loop,iteration
I am trying to add n columns to a table, like in this example of code where n = 10: Sub toto() Dim db As Database, i As Integer Set db = CurrentDb() For i = 1 To i = 10 db.Execute " ALTER TABLE time_series " _ & "ADD...

Why does this loop return a value that's O(n log log n) and not O(n log n)?

loops,for-loop,time-complexity,nested-loops,asymptotic-complexity
Consider the following C function: int fun1 (int n) { int i, j, k, p, q = 0; for (i = 1; i<n; ++i) { p = 0; for (j=n; j>1; j=j/2) ++p; for (k=1; k<p; k=k*2) ++q; } return q; } The question is to decide which of the...

GET request inside of a loop in JavaScript

javascript,jquery,for-loop,get
So, my code looks something like for(int n = 0; n < object.length; n++){ /*Other code */ $.get(...,function(data){ //do stuff });} Now, the other code executes multiple times like it should. However, when the get command is ran, it is only ran once and that is when n reaches the...

How to push row of two-dimensional array to object

javascript,arrays,for-loop
I have the following array: var myArray = [ [47,22,11], [28,5,1], [22,11,11] ] And I need the following structure: var myStructure = [ { Pass: 47, Warning: 22, Fail: 11}, { Pass: 28, Warning:5, Fail: 1}, { Pass: 22, Warning:11, Fail: 11;}, ]; How can I do that...

Run 3 variables at once in a python for loop.

python,loops,variables,csv,for-loop
For loop with multiple variables in python 2.7. Hello, I am not certain how to go about this, I have a function that goes to a site and downloads a .csv file. It saves the .csv file in a particular format: name_uniqueID_dataType.csv. here is the code import requests name =...

How to stop handler.postDelayed in for-loop?

java,android,for-loop,handler,runnable
I saw no real answer for this type of using "handler.posDelayed". So, I execute "handler.posDelayed" multiple times with a for-loop. The problem is, when I leave the activity and restart it, the new objects AND the old ones from the handler are executed too. I don't know, how to stop...

printing an string in cross manner using c program

c,arrays,loops,for-loop,multidimensional-array
I'am trying to write a program for converting the given string in cross manner(i.e Diagonal from left-right and from right-left). If the string length is even it returns a message else arrange it in a cross form. The code is: #include<stdio.h> #include<string.h> int main() { char str[50]; char str2[50][50]; int...

How to fill array with random values 1-110

java,arrays,for-loop,random
I want to fill tab[110] array with random bits (so 1 and 0). Don't know how to fill with values 1-110, but not 0-109. My for-loop: for (int i = 0; i<tab.length; i++) { Random r = new Random(); tab[i] = r.nextInt(2); if (i%25==0) { System.out.println(""); } System.out.print(tab[i]+"("+i+")"+", "); }...

Count neighboring cells

java,function,for-loop
I don't understand what is wrong with this loop, it normaly would check the surrounding cells of (x,y). When calling this function, there is only 4 passages in the loop and not 8 This is probably a stupid mistake but I cant see it ! private int countAliveNeighbors(int x, int...

Tallying incorrect answers for Javascript game

javascript,for-loop
So I am trying to make a javascript game for my geography class but I have run into some trouble, I can ask the questions and tell you if you're wrong or not but I would like to be able to keep track of the wrongs answers. I want to...

python compare items in 2 list of different length - order is important

python,list,loops,for-loop,indexing
list_1 = ['a', 'a', 'a', 'b'] list_2 = ['a', 'b', 'b', 'b', 'c'] so in the list above, only items in index 0 is the same while index 1 to 4 in both list are different. also, list_2 has an extra item 'c'. I want to count the number of...

C++ Same name local variables keeping values between loops [closed]

c++,loops,for-loop,local-variables
I have the following 2 loops in my C++ code: for (int hcount = 0; hcount < height; hcount++) { for (count = 0; count < width; count++) { cout << character; } cout << endl; } cout << endl; for (int hcount = 0; hcount < height; hcount++); {...

VHDL average of Array through for loop

arrays,for-loop,vhdl,moving-average
I have an Array of X Integer values in VHDL declared as a variable inside a process. I would like to calculate the average of all Values in a for loop. If I write it out for 3 Values manually everything works fine (tested on hardware): entity MyEntity is Port(...

How to stop a decreasing iteration after xth element?

php,for-loop,iteration
So I have a for loop that is decreasing... for ($i=count($array); i>0; $i--;) { if(condition) {DO SOMETHING like print the element in a decreasing manner} if(enter ending iteration condition here after xth element) break; } that pretty much sums up my question. How do I formulate the ending iteration -...

Set up a for loop to fill image src's

javascript,html,xml,for-loop
So I'm sending a request to NASA's APOD API and receiving back an array of info, part of which is an image url. I need to perform this action multiple times, and am wondering how to set this up as a for loop, or maybe just a function(?). The HTML...

c# nested if/else in a for loop

c#,if-statement,for-loop
I have a nested if/else statement in a for loop to determine whether or a a value is valid with an array value. It returns all values just fine, however if the IF is correct, it still does the else an additional three times. I thought once it was equal...

Matlab: For loop with window array

arrays,matlab,math,for-loop,while-loop
This is my one dimensional array A, containing 10 numbers: A = [-8.92100000000000 10.6100000000000 1.33300000000000 ... -2.57400000000000 -4.52700000000000 9.63300000000000 ... 4.26200000000000 16.9580000000000 8.16900000000000 4.75100000000000]; I want the loop to go through like this; (calculating mean interval wise) - Interval length of 2,4,8 (a(1)+a(2))/2 - value stored in one block of...

Python For Loop Using Math Operators

python,for-loop
Ok, I'm in the process of learning Python, and had a quick question about for loops. I was wondering if you could use math operators in them, like JavaScript. For example, could I do: for i = 0, i < 5, i++: #code here Now, I'm quite aware that Python...

Refering to Integer inside String? Python

python,for-loop
How do you refer to an integer inside a string, using python? I am completely new to coding and I am trying to do this bug collection exercise where the user will input the number of bugs collected each day for a week and be presented the total number of...

For Loops Not Always Updating C# [duplicate]

c#,for-loop
This question already has an answer here: Random number generator only generating one random number 7 answers I've run into a strange issue. When I run the following code, each of my text boxes get's filled with the same randomly generated number. public void diceAdd() { int[] die =...

Loop throught list in R [on hold]

r,for-loop
I am new to R. Get stuck in my homework: Create a list with length 10: for the first component list[[1]], the dimension is 1, the second is 1*2, the third is 3*3, the fourth is 4*4, and so on. The values should be selected randomly from 1:100. For each...

Batch For Do Test if exist rename url link on desktop

batch-file,for-loop
Why does this not work? I want to test each users desktop for a file and then if it is there, rename it. FOR /F "tokens=*" %%G IN ('DIR c:\users /B') DO if exist "C:\Users\%%G\Desktop\My Link With Spaces.url" ( rename "C:\Users\%%G\Desktop\My Link With Spaces.url" "My NEW Link With Spaces.url" )...

Create a Triangular Matrix from a Vector performing sequential operations

r,for-loop,matrix,vector,conditional
I have been trying to solve the following problem. Suppose I have the following vector: aux1<-c(0,0,0,4,5,0,7,0,0,10,11,12) where the numbers represent the number of the row. I want to calculate the distance between the differents elements of this vector fixing the first component, then the second and so on. If the...

How to iterate through a table in its exact order?

loops,for-loop,lua,order
If i try to output this table, they are looped through in the false order: local letters = {DIN1="hi", AIN1= "my", AIN2 ="name", DIN2="is"} for name, value in pairs(letters) do print(name,value) end Expected Output: DIN1 hi AIN1 my AIN2 name DIN2 is Output: AIN1 my DIN2 is DIN1 hi AIN2...

Switching between date format in a for loop; Python

python,date,if-statement,for-loop
The date in my data is stored in two different formats: Dienstag 31. Dezember 2013 and 30. Juni 2007 I wrote scripts to extract Year/Month/Day from both formats and store them in a list: for row in reader: line_count = line_count + 1 if row[1] == "DATE": pass else: date...

GPA Calculator in C

loops,for-loop,do-while
I'm trying to get this code to calculate a class's average GPA. The problem I'm having is that I seem to have made a mistake in my do...while code, because, when I run it, it constantly loops back to asking me to input another GPA, rather than asking if I...

Array stored in array gets overwritten to the contents of the last one added

java,arrays,for-loop
Maybe it's something simple I'm missing, but I can't seem to figure out why my array of arrays is being overwritten with the last value in that is put into the array. This is my code: import java.util.Arrays; import class.ArgsProcessor; public class Dice { public static void main(String[] args) {...

I have an Array of 2 objects, when I use a for loop, both of the object gets the change that only one of them should have

java,arrays,for-loop,libgdx,box2d
Basically I have this code : for(int i = 0; i < tnt.size; i++){ TNT t = tnt.get(i); if(cl.isVänster()){ t.getBody().setLinearVelocity(6,0); } if(cl.isHöger()){t.getBody().setLinearVelocity(-6,0); } if(t.getBody().getPosition().x > 1888/PPM){t.getBody().setLinearVelocity(-6,0); } if(t.getBody().getPosition().x < 31/PPM){t.getBody().setLinearVelocity(6,0);} } What happens is if I have 2 objects in this Array, when something happens to object #1 it gets...

Java for loop only executing once

java,for-loop
Sorry to ask such a basic question but other questions on here don't seem to fix the problem and I've been staring at it for quite a while now. I'm writing some code to find the smallest common multiple for the numbers from 1 to 20. From debugging, the outer...