Menu
  • HOME
  • TAGS

Iterate through a specific directory tree and store all the .ttf files into an array in PHP

php,loops,iterator,directory,iteration

SPL's recursive iterators are particularly useful for this type of functionality: abstract class FilesystemRegexFilter extends RecursiveRegexIterator { protected $regex; public function __construct(RecursiveIterator $it, $regex) { $this->regex = $regex; parent::__construct($it, $regex); } } class FilenameFilter extends FilesystemRegexFilter { // Filter files against the regex public function accept() { return ( !...

Query With CONCAT and LOOP using SELECT

mysql,loops,concat

There is LPAD. SELECT LPAD(reference_number, 10, '0') FROM example ...

how to find a specific objet in a liste of object (other way than a loop)

php,loops,object

If you want set "Yes" to one of picture from pictures array, you should use code like this; $bestscorelike = 0; $bestPictureObject = null; foreach($pictures as $picture) { $scorelike = $picture->getScorelike(); if($scorelike > $bestscorelike) { /** * Now in the $bestPictureObject exists picture with scorelike less then current $picture */...

javascript manipulating html elements in a php foreach

javascript,php,html,html5,loops

To give to each button a different id you can do this way: <?php $i = 1; foreach($queryResult as $res) { ?> // output all table columns <form onsubmit="return javascriptFunction(); " method="post"> <button id="element-<?= $i ?>">edit</button> </form> <?php $i++; } ?> For the second question: if you want to pass...

Php counting with $i++

php,loops

<?php for($i = 0; $i < count($collection); $i++){ echo '<div id="'.$i.'">' . 'Anchor' . '</div>'; echo '<a href="#'.$i.'">' . 'Link-A ' . '</a>'; echo '<a href="#'.$i.'">' . 'Link-B ' . '</a>'; } ?> It is a basic for loop....

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

c,loops,for-loop,macros,printf

There is no issue with the #define, there is one issue with the conditional statement in the for loop. I believe, you'er overlooking the <= operator. You need to have only < operator. Change for(i=0;i<=rows;++i) to for(i=0;i<rows;++i) That said, the recommended signature of main() is int main(void)....

Get next item in array using iterator using flags

javascript,jquery,loops,iterator,iteration

$.each(playlist,function(index, value){ if( !value.played ){ if( stop ){ song = index; return false; } else { if ( !value.playing ) { playlist[index].playing = false; stop = true; } } } }); outputs (index):87 hash2 (index):87 hash3 (index):87 hash4 (index):87 hash5 (index):87 hash1 ...

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

javascript,loops,for-loop

The i++ is using post increment, so the value of the expression i++ is what the value was in the variable i before the increment. This code: if(sortedLetters[i] !== sortedLetters[i++]) return true; does the same thing as: if(sortedLetters[i] !== sortedLetters[i]) return true; i = i + 1; As x !==...

How to innerHTML a function with array as parameter?

javascript,arrays,loops,foreach,innerhtml

Just take a variable for the occurrence of even or odd numbers. var myArray = function (nums) { var average = 0; var totalSum = 0; var hasEven = false; // flag if at least one value is even => true, otherwise false nums.forEach(function (value) { totalSum = totalSum +...

Linq implementation of for and if loop

c#,linq,loops

This is effectively the same as the answer from Stephen Kennedy, but I sometimes like this syntax. Usually for more complicated things, but still: foreach (var item in from l in list1 where l == eCode select l) { // Do something with each item } ...

Check for new files in a loop - java

java,loops

Rather than comparing old and new files, why not write a method to just return Last Modified Files. public static ArrayList<File> listLastModifiedFiles(File folder, long sleepDuration) throws Exception { ArrayList<File> newFileList = new ArrayList<File>(); for (File fileEntry : folder.listFiles()) if ((System.currentTimeMillis() - fileEntry.lastModified()) <= sleepDuration) newFileList.add(fileEntry); return newFileList; } //Sample usage:...

for loop - checking if numbers in array move more up or down

java,arrays,loops

A small semantic correction - the compiler isn't throwing any exception - your code compiles just fine. The runtime execution of this code causes an exception. And more to the point, an array a has elements from 0 to a.length - 1. Your code attempts to access element number a.length...

How do I write a loop to read text file and insert it to the database

sql-server,loops,powershell

To add a simple loop, you can use your existing AutoImportFlatFiles function like this: $Folder= $(read-host "Folder Location ('C:\Test\' okay)") foreach ($file in (get-childitem $Folder)) { $location = split-path $file.FullName -Parent $filename = (split-path $file.FullName -Leaf).split(".")[0] $extension = (split-path $file.FullName -Leaf).split(".")[1] AutoImportFlatFiles -location $location -file $filename -extension $extension -server "WIN123"...

Python: TypeError: list indices must be integers, not list

python,list,loops,indices

You are indexing your lists with a non-int type index: for count in list_kp2_ok: for count1 in list_kp2_2_ok: if list_kp2_ok[count]==list_kp2_2_ok[count1]: So a quick fix for that is to do it this way: for coord1 in list_kp2_ok: for coord2 in list_kp2_2_ok: if coord1==coord2: You can even do the whole coding in...

Index out of Range exception in arrays

c#,loops

This line: public static string [] starGenerated = new string[numberOfForbiddenWords]; ... is executed when the class is initialized. That will happen while numberOfForbiddenWords is still 0, i.e. long before this line is executed: numberOfForbiddenWords = int.Parse(Console.ReadLine()); So when you call StarGenerator, unless numberOfForbiddenWords is still 0, you're going to be...

performance issues executing list of stored procedures

c#,multithreading,performance,loops

What I would do is something like this: int openThread = 0; ConcurrentQueue<Type> queue = new ConcurrentQueue<Type>(); foreach (var sp in lstSps) { Thread worker = new Thread(() => { Interlocked.Increment(ref openThread); if(sp.TimeToRun() && sp.HasResult) { queue.add(sp); } Interlocked.Decrement(ref openThread); }) {Priority = ThreadPriority.AboveNormal, IsBackground = false}; worker.Start(); } //...

Calling function and passing arguments multiple times

python,function,loops

a,b,c = 1,2,3 while i<n: a,b,c = myfunction(a,b,c) i +=1 ...

How to create series of pandas dataframe by iteration

python,loops,pandas

To create variables by string, you can use - globals() function , which returns the dictionary of global namespace, and then create a new element in that dictionary for your variable and set the value to the value you want. Also , you can directly call - pandas.DataFrame(Series) - and...

Why this while loop cannot print 1,000 times per seconds?

java,loops,time,while-loop

Try System.nanoTime() since you are not measuring time since the epoch. System.currentTimeMillis vs System.nanoTime

Grep for beginning of line while searching for a certain string

bash,loops

If the columns are delimited with tabs then you can do: role='Role A' number=$(awk -v role="$role" -F '\t' '$2==role {print $1}' role_info.txt) If it's just spaces, try instead: role='Role A' number=$(grep "$role" role_info.txt | cut -d' ' -f1) Either way, you can then check if a match was found with:...

An error while looping a linear regression

r,loops,data.frame,regression

The problem arises from you mixture of subsetting types here: df$target[which(df$snakes=='a'),] Once you use $ the output is no longer a data.frame, and the two parameter [ subsetting is no longer valid. You are better off compacting it to: sum(df[df$snakes=="a","target"]) [1] 23 As for your model, you can just create...

Comparing two values in the same row and change if needed

php,mysql,loops

Below query will work, unless you need to do query optimization and reduce the locking period UPDATE Product SET Voorraad = Minvoorraad WHERE Minvoorraad > Voorraad ...

How to iterate multi dimensional array and calculate sum for each row in php?

php,arrays,loops,foreach,dimensional

When you do this loop: foreach($array as $cases) { if($cases['allergies'] == $_POST['allergies']){ $count = 1; } if($cases['vege'] == $_POST['vege']){ $count1 = 1; } if($cases['bmi'] == $bmi2) $count2 = 1; if($cases['age'] == $age2) $count3 = 1; $sum = $count + $count1 + $count2 + $count3; echo $sum; } You are not...

How can I reset my program? (without using goto) [closed]

c++,loops,reset,goto

Use a do while loop to enclose your code and set the condition to what you want. #include <iostream> #include <string> #include <fstream> using namespace std; int main() { int flag=1; do { //your code that needs to be repeated //when you need to exit set flag=0 } while(flag); }...

while loop is not breaking even if the condition is satisfied

c,loops,while-loop,iteration

You are using same variable (i) for both loops, and in the inner loop the condition of exit is i being 0 or negative, but the only change in this variable in the inner loop is i=i/10 which usually gives unexpected results when using with int. Also, the i will...

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

javascript,jquery,loops,for-loop

Yes, it's possible, and it works fine. for (i=-5; i<=5; i++) { ... } is the same thing as i=-5; while (i<=5) { ... } continue { i++ } The point is that any expression is allowed inside the for's first part....

Difference between two similar functions, why is one working and the other not

javascript,jquery,loops,vue.js

Simple answer, you don't. Because your function is called through timeout, it's not in the same context anymore and 'this' will not refer to the same object anymore. You can do this: loopThroughSplittedTextNotWorking: function() { // delete this var locationInString = 0; var that = this; function delayedOutput() { document.getElementById('output').innerHTML...

Matching key/value pairs in two dictionaries and creating a third one

python,loops,dictionary

The problem is this line matched = {i: data1[i]} It is overwriting the previous values of the dictionary. It should be matched[i] = data1[i] Or you can use update matched.update({i: data1[i]}) ...

How can i make a jQuery animation loop on infinite, after it finish?

jquery,loops,animation

You can achieve this in CSS alone through the use of @keyframes. Try this: @-moz-keyframes rotating { 0% { -moz-transform: rotate(-20deg); } 50% { -moz-transform: rotate(20deg); } 100% { -moz-transform: rotate(-20deg); } } @-webkit-keyframes rotating { 0% { -webkit-transform: rotate(-20deg); } 50% { -webkit-transform: rotate(20deg); } 100% { -webkit-transform: rotate(-20deg);...

Jquery Loop appending image element just appends once

jquery,loops,dom

You should create the image object within the for loop because if it is not then it is using the same object multiple times See demo Change you jQuery to this, $(document).ready(function () { for (i = 0; i < 12; i++) { var myImage = new Image(); myImage.src =...

IllegalStateException: Iterator already obtained [duplicate]

java,file,loops,path

You have to call DirectoryStream<Path> files = Files.newDirectoryStream(dir); each time you iterate over the files. Pls check this question... java.lang.IllegalStateException: Iterator already obtained...

How to retrieve filtered data from json with double for loop

javascript,json,loops,for-loop,filter

If i understood you correctly, you need to add additional for loop for all bussen for (var i=0;i<bushalte2.length;i++) { $("#bussen").append(bushalte2[i].name + "<br/>"); for (var j=0; j <bushalte2[i].bussen.length; j++) { $("#bussen").append(bushalte2[i].bussen[j].busnummer + "<br/>"); } } here is updated jsfiddle https://jsfiddle.net/or4e8t3u/...

How to use _lodash to retrieve value from Objects in Array?

javascript,arrays,loops,lodash

You can use _.pluck: https://lodash.com/docs#pluck console.log(_.pluck(_.pluck(list, 'ticker'), 'ticker')); http://jsfiddle.net/kevinle/vj7e66zy/...

Escape out of 2 Javascript loops (or stop script)

javascript,loops

To stop setInterval you have to use this clearInterval(n); And put var n = setInterval(function () {.... ...

Excel 2013 vba refresh chart content after each iteration of For Loop

excel,vba,loops,iteration,refresh

Add a DoEvents to your code after each iteration step. It works for me.

JQuery loop on multiple items of the same CSS class

jquery,loops,each,keyup,word-count

I'd wrap each textarea + word count (eg. in a div), and in the keyup event find the other child tag based on the shared parent element. This example just grabs the immediate parent but you could do it based on a common ancestor or its class name. eg. http://jsfiddle.net/mzqo2ruk/...

Add mouseListener to Labels in Array Loop

java,loops,mouselistener

the problem is when mouse-event fire value of i have value 6 or last value of for-loop for (i = 0; i < 6; i++){} you can create a jlable class and give a instance variable like lableindex so when mouse-event occurs you first get the lable index and then...

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

matlab,loops,for-loop,matrix

Here is your problem: HSRXp(:,i*3) = [HSRXdistpR(:,i) HSRXdistpL(:,i) TocomXdistp(:,i)]; You're trying to assign an n x 3 matrix (RHS) into an n x 1 vector (LHS). It would be easier to simply use horizontal concatenation: HSRXp = [HSRXp, [HSRXdistpR(:,i) HSRXdistpL(:,i) TocomXdistp(:,i)]]; But that would mean reallocation at each step, which...

How to repeat this statement in R probably using apply()

r,loops

Here's a recommended way to ask a question, focusing on the fact that your actual data is too big, too complicated, or too private to share. Question: how to apply a function on each row of a data.frame? My data: # make up some data s <- "Lorem ipsum dolor...

C++ - back to start of loop without checking the condition

c++,perl,loops,redo

There is no redo keyword for going back to the start of a loop, but there's no reason you couldn't do it with goto. (Oh I feel so dirty recommending goto...) int tries = 0; for(int i=0; i<10; ++i) { loop_start: bool ok = ((i+tries)%3==0); if(ok) { ++tries; goto loop_start;...

Loops to minimize function of arrays in python

python,arrays,loops,minimization

There is already a handy formula for least squares fitting. I came up with two different ways to solve your problem. For the first one, consider the matrix K: L = len(X) K = np.identity(L) - np.ones((L, L)) / L In your case, A and B are defined as: A...

GPA Calculator in C

loops,for-loop,do-while

There are two issues here. First, you need to discard new lines on your scanf. See here for details. Second the || operator is going to cause the whole statement to evaluate to true no matter if the user has entered Y or y. Try switching to an && operator...

How to iterate through a table in its exact order?

loops,for-loop,lua,order

You may utilize integer part of the table to store keys in order: function add(t, k, v, ...) if k ~= nil then t[k] = v t[#t+1] = k return add(t, ...) end return t end t = add({ }, "A", "hi", "B", "my", "C", "name", "D", "is") for i,k...

How can I iterate through nested HTML lists without returning the “youngest” children?

javascript,jquery,html,list,loops

You could just check the nesting level by counting parents $("ul li").each(function() { if ( $(this).parents('ul').length < 3 ) { // do stuff } }); FIDDLE To make it more dynamic one could simply find the deepest nesting level and filter based on that var lis = $("ul li"); var...

How do I use the Find function with a variable term, for example Run1, Run2, RunX

vba,excel-vba,loops,variables

Yes, you need a variable, and just concatenate it. Use something like this: Dim counter as long counter = 1 Cells.Find(What:="Run:" & counter, After:=Cells(1, 1), _ ...yaddayadda Or use it in a loop: For i=1 to 100 Cells.Find(What:="Run:" & i, After:=Cells(1, 1), _ ...yaddayadda Next i ...

Callback in a double loop

loops,callback

As a native recursion alternative, here's a way to do it var marker = [[43.000,-79.321],[44.000,-79],[45.000,-78],[46.000,-77]]; var result = []; var i=0, j=0; function test(){ if(j >= marker.length){ j=0; i++; } // j is done one lap, reset to 0, i++ for next lap if(i >= marker.length){ return false; } //...

Using Yahoo! database without quantmod functions

r,loops,yahoo-finance

x<-c('AAIT', 'AAL', 'AAME') kk<-lapply(x,function(i) download.file(paste0("http://ichart.finance.yahoo.com/table.csv?s=",i),paste0(i,".csv"))) if you want to directly read the file: jj<- lapply(x,function(i) read.csv(paste0("http://ichart.finance.yahoo.com/table.csv?s=",i))) ...

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

javascript,loops,for-loop,lodash

You're referring to params.term as an existing array, which is why you're getting an error. Try this instead... params["term" + index] = .... That will create a property for each index instead. You can either access it with params["term1"] or... params.term1 ...

Appending a data frame with for if and else statements or how do put print in dataframe

r,loops,data.frame,append

It's generally not a good idea to try to add rows one-at-a-time to a data.frame. it's better to generate all the column data at once and then throw it into a data.frame. For your specific example, the ifelse() function can help list<-c(10,20,5) data.frame(x=list, y=ifelse(list<8, "Greater","Less")) ...

How to make function in loop run synchronously?

javascript,jquery,loops,google-chrome-extension,synchronization

One option would be to make your function(response) recursive. When it runs, call this same method again. Pass in some of your "looping" variables, and just do an if check at the beginning. function AnotherGoRound(i,data) { if (i<data[i2].data.length) { console.log("SENDING: i=" + i + "; i2=" + i2); // Send...

How to make sure to draw two different random cards [closed]

python,loops,random,while-loop

There are three different options you have to choose from here, I will explain each one: Option 1 - break while first_draw == second_draw: first_draw = random.choice(card_values) + random.choice(card_classes) second_draw = random.choice(card_values) + random.choice(card_classes) break break will end the innermost loop. In this case, the loop will only run once....

Incrementing an integer and initialisation placement having a weird effect?

c,loops,int

You are causing undefined behavior in scanf("%s", &c); because "%s" specifier adds a terminating nul byte to the target which is a single char. Instead you can try if (scanf(" %c", &c) != 1) handleErrorPlease(); the space before the "%c" is intentional, it will eat any white space character left...

Run external R script n times, with different input paramters, and save outputs in a data frame

r,loops

Wrap the script into a function by putting: my_function <- function(latitude) { at the top and } at the bottom. That way, you could source it once then then use ldply from the plyr package: results <- ldply(10 * 5:8, myFunction) If you wanted a column to identify which latitude...

call function after “loop” function for multiple elements is finished in jQuery

jquery,function,loops,animation

I didn't want to rewrite it all but you have some necessary stuff. It illustrates the use of the fadeIn callback. https://jsfiddle.net/c633f5w8/4/ var v = $(".box"); var cur = 0; var len = v.length; console.log(len); var first = function () { function fadeInNextLI() { if(cur+1 == len){ v.eq(cur++).fadeIn(200,'swing',finish); } else...

How can I make my own timer without standard library?

c++,loops,timer

I am posting this answer to my own question, as per the comments received. It is not possible to make a timer because: The time that an iteration will take is unpredictable, this depends not only on the CPU used, but you need to take into account power management, the...

Javascript how to start script on exact time

javascript,loops,time,setinterval

I'd use the getTime object in JS I believe I have the time set right in this JSFiddle var d = new Date(); var year = d.getFullYear(); // Month 0 = January | Month 11 = December | so I changed vallues by +one var month = d.getMonth() +...

Creating an auto incrementing loop within a function in python

python,loops,tkinter,increment

You can use itertools.count() for that. It creates a generator, that just returns one number after the other, when you call it's next() method: from itertools import count counter = count(1) for row in rows: row_id = counter.next() In this example on every iteration through the rows you will get...

Creating a number list with nested For loops in Python

python,loops,nested

For the first instance, try this: print('', end = '') For the second instance, the mistake is that you are adding 0 to the second for loop. Change it to: for j in range(0, 1+i): The thing with range is that it goes until one number lower. Have a look...

How do I format the logic for 3 conditions and use a previous condition as well?

java,loops,if-statement,while-loop,logic

The second condition should be changed, otherwise the third if won't be reached. Also the third condition should be changed to check if the daysLate variable is greater or equal to zero: if (daysLate > 90) { costDue = bookPrice + 10; } else if (daysLate >= 7) { costDue...

Counter not working after jumps - assembly language

loops,assembly,counter,increment

The fault is caused because the mouse interrupt 33h function AX=0003h returns the mouse position in CX and DX. This overwrites your "counter" in register CX. It is always a dangerous game to keep values in registers throughout a program. Better to have a memory variable location. You could also...

Matlab Calculating mean of distribution quantile in a for-loop

matlab,loops,for-loop,distribution,quantile

Your test variable is a three-dimensional variable, so when you do test2 = test(:,1); and then test2(:) <VaR_Calib_EVT/100 it's not the same as in your second example when you do test(:,i)<(VaR_Calib_EVT(:,i)/100) To replicate the results of your first example you could explicitly do the test2 assignment inside the loop, which...

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

r,loops,for-loop,shiny

Use [[ or [ if you want to subset by string names, not $. From Hadley's Advanced R, "x$y is equivalent to x[["y", exact = FALSE]]." ## Create input input <- `names<-`(lapply(landelist, function(x) sample(0:1, 1)), landelist) filterland <- c() for (landeselect in landelist) if (input[[landeselect]] == TRUE) # use `[[`...

Python - Using a created list as a parameter

python,list,loops,if-statement,compare

I believe you are incorrectly referencing to num instead of line which is the counter variable in your for loops, you either need to use num as the counter variable, or use line in the if condition. def countGasGuzzlers(list1, list2): total = 0 CCount = 0 HCount = 0 for...

c++ mathematical calculations [closed]

c++,loops,math

simply iterate from 1 to the maximum number of offices n and add number of required plates to total. for 1 to 9 you need 1 plate, for 10 to 99 you need 2 and so on. we implement this by using limit and step. limit indicates when we need...

Matlab: Looping through an array

matlab,loops,for-loop,while-loop,do-while

You could do this using conv without loops avg_2 = mean([A(1:end-1);A(2:end)]) avg_4 = conv(A,ones(1,4)/4,'valid') avg_8 = conv(A,ones(1,8)/8,'valid') Output for the sample Input: avg_2 = 0.8445 5.9715 -0.6205 -3.5505 2.5530 6.9475 10.6100 12.5635 6.4600 avg_4 = 0.1120 1.2105 0.9662 1.6985 6.5815 9.7555 8.5350 avg_8 = 3.3467 5.4830 4.7506 Finding Standard Deviation...

Matlab: Writing to a file

arrays,matlab,loops,math,for-loop

If you want to get the matrices to be displayed in each column, that's going to be ugly. If I'm interpreting your request correctly, you are concatenating row vectors so that they appear as a single row. That's gonna look pretty bad. What I would suggest you do is split...

Infinite loop with fread

c,arrays,loops,malloc,fread

If you're "trying to allocate an array 64 bytes in size", you may consider uint8_t Buffer[64]; instead of uint8_t *Buffer[64]; (the latter is an array of 64 pointers to byte) After doing this, you will have no need in malloc as your structure with a 64 bytes array inside is...

Methods within my while Loop not working

python,loops

Calling open(output.txt) returns a file object, not the the text within the file. Calling str on the file object just gives a description of the object, not the text. To get that you need to something like output = open('output.txt') past_results = output.read() Also, it looks like you're calling str...

R - Check different matrices with a possible lag

r,loops,matrix,lag

Here's a simple way to do it: lag <- 3 # or whatever lag you want nr <- nrow(mat1) nc <- ncol(mat1) mat3 <- matrix(0, ncol=nc, nrow=nr) for (r in 1:nr) { for (c in 1:nc) { if (mat1[r,c] == 1 && any(mat2[r,c:min(c+lag,nc)] == 1)) mat3[r,c] <- 1 } }...

Object Variable or With Block Variable Not set in loop using find function

vba,excel-vba,loops,object,find

If the Cells.Find(What:="Run:" & i,... fails to find a match, the Select part of the statement will then cause the error. You should always store the result of a Find in a range variable and then test that for Nothing. Add this declaration to your code: Dim cellsFound As Range...

wrong results from simple java method [duplicate]

java,arrays,loops

Change double average = sum/numbers; to double average = (double)sum/numbers; to force floating point division. Otherwise, int division (which is the operation that takes place when dividing two variables of int type) will give you 2 when dividing 8/3 (as you do in your example)....

How does a while loop inside a for loop work?

java,loops

It will enter the for loop first when i = 0. Immediately after it will enter the while loop and continue running indefinitely as i will always be 0 and therefore < 3. You perhaps need to deal with j in the break condition of inner loop for avoiding an...

printing an string in cross manner using c program

c,arrays,loops,for-loop,multidimensional-array

In your code, you need to change the for loop condition checking expressions, like i == lenstr and later i==0. They are not entering the loop, essentially. Instead, you can replace the whole block for(i = 0;i == lenstr;i++) { str2[i][j] = str[i]; j = j + 1; } for(i...

Trying to output a list of lists from a loop in r

r,loops

James, the following should work. I've just tested it. pair1 <- c(2,4) pair2 <- c(1,3) pair3 <- c(5,6) pairedList <- c(pair1, pair2, pair3) botList <- c(1:(length(pairedList)/2) library(gtools) test <- function(pairedList, botList) { #initialising empty list output <- list() for (i in botList) { x <- rep(0, length(pairedList)) ind <- pairedList[i:(i+1)]...

for each loop: how to step out of conditions

loops,vbscript,condition

Use else as follows: for each file in folder.files if (filename = "foo.bar") then log.writeline("found foo.bar -> delete!") fs.deletefile (folder & file.name), true 'exit for else if (isNumeric(firstPosition)) then if (isNumeric(secondPosition)) then log.writeline("2 numbers seen -> alright!") else log.writeline("Filename is corrupt!") fs.copyFile file, errorFolder, true fs.deleteFile file, true 'exit for...

How do I count the total number of iterations within a loop?

ruby-on-rails,ruby,loops

User has many photos @user.photos.count #as user has_many photos From loop with index of each photo object @user.photos.map.with_index.to_a #[[photo1, 0], [photo2, 1]] To get total count/ or total iteration of photos @user.photos.map.with_index(1).to_a.last.last You can find enumerator#with_index...

PHP: How to push Select results to multi-dimensional array (partially working)

php,arrays,loops,select,multidimensional-array

You are getting this output because you are overwriting the keys in your array. You would need to save to another array (aka not 2-dimensional): <?php $tbl = "TranslationsMain"; $conn = new mysqli($servername, $username, $password, $dbname); if($conn->connect_error){ die("Connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM " ....

How to create bootstrap html structure in php loop?

php,html,loops,bootstrap

You can do some thing like this. You can modify according to your need. I just mentioned logic <div class="row"> <?php $i = 0; foreach(....../*your code*/){ if($i == 4){ $i = 0; ?> </div><div class="row"> <?php } ?> <div class="col-sm-3"> <!--content--> </div> <?php $i++; } ?> </div> ...

how to make a loop and if statement that loops through a different groups of radio buttons (javascript)

html,loops,twitter-bootstrap-3,radio-button

Here, take a look at this demo boootply. Since you're using Bootstrap, jQuery should already be part of your page. Here's the relevent code: $(document).ready(function(){ $('#submitBtn').click(function(e){ e.preventDefault(); if($('li.option :radio:checked').length == $('li.option').length){ // enter code here to submit your form alert('submitted'); }else{ alert('Please answer all questions'); } }); }); And the...

Array values are not being read correctly inside gameloop

javascript,arrays,loops

So it turns out I was wrong in my other comment. The non-detection of edges was causing you to index into unset parts of your array causing those weird messages and was all of your problems I scaled it back a bit to look at it see https://jsfiddle.net/goujdwog/2/ the important...

PHP foreach and continue [closed]

php,loops,foreach

If you made the if statements equivalent, I'd say the top version is more generic and better for more complex statements due to the following: If you had multiple if - continue statements, the first approach would allow you to list them in order without nested indentation which could keep...

R - loop and break after value found for each Rows

r,loops,matrix,break

You seem to be fond of for loops and those seem like a natural choice here. Just change your code to this: for(i in 1:nrow(matSolo)){ for(j in 1:ncol(matSolo)){ if(SoloNight[i,j] == 1) { matSolo [i,j] <- 1 break } } } However, this will be quite slow for big matrices. Fortunately,...

Lua in pairs with same order as it's written

loops,lua,order,lua-table

In Lua, the order that pairs iterates through the keys is unspecified. However you can save the order in which items are added in an array-style table and use ipairs (which has a defined order for iterating keys in an array). To help with that you can create your own...

Run 3 variables at once in a python for loop.

python,loops,variables,csv,for-loop

zip the lists and use a for loop: def downloadData(n,i,d): for name, id, data in zip(n,i,d): URL = "http://www.website.com/data/{}".format(name) #downloads the file from the website. The last part of the URL is the name r = requests.get(URL) with open("data/{}_{}_{}.csv".format(name, id, data), "wb") as code: #create the file in the format...

echo both users

php,mysql,sql,database,loops

Why don't you just do it in one single query? Just replace the necessary table and column name, and variables/values/parameters to be bind in your query: $query = mysqli_query($conn, "SELECT first_name, last_name, description, role FROM `wp_usermeta` WHERE `first_name` = '$first_name' OR `last_name` = '$last_name' OR `description` = '$description' OR `role`...

How to print iterations per second?

python,performance,loops,cmd,progress

You can get a total average number of events per second like this: #!/usr/bin/env python3 import time import datetime as dt start_time = dt.datetime.today().timestamp() i = 0 while(True): time.sleep(0.1) time_diff = dt.datetime.today().timestamp() - start_time i += 1 print(i / time_diff) Which in this example would print approximately 10. Please note...

2 Foreach Loop Inside A Table

php,loops,laravel-4,foreach,blade

You create new TD for each member. The nested foreach has to be: <td> @foreach($user as $mem) {{ $mem->name }}<br> @endforeach </td> The result will be: <td> Name 1<br> Name 2<br> Name 3<br> </td> I don't know the template engine you used, add inside a loop condition and don't put...

Nested foreach loop in a While loop can make the condition for the while loop go over?

php,loops,foreach,while-loop

Glad you found an answer. Here is something I was working on while you found it. // SET START DATE $startDate = new DateTime($dateStart); $nextBill = new DateTime(); for($i=1;$i<$countDays;$i++){ switch(true){ case ($startDate->format('j') > $days[2]): // go to next month $nextBill->setDate( $startDate->format('Y'), $startDate->format('m')+1, $days[0]; ); break; case ($startDate->format('j') > $days[1]): //...

Interface Controls for DoEvent in Excel

excel,vba,excel-vba,loops,doevents

How about changing your 'do until' loop to a 'for next' loop? Something like?... Sub rowinput() Dim lngInputStartRow As Long Dim lngInputEndRow As Long Dim row_number As Long lngInputStartRow = Range("A1").Value 'specify your input cell here lngInputEndRow = Range("A2").Value For row_number = lngInputStartRow To lngInputEndRow DoEvents Next row_number 'Then a...

How to match words in 2 list against another string of words without sub-string matching in Python?

python,regex,string,loops,twitter

Store slangNames and riskNames as sets, split the strings and check if any of the words appear in both sets slangNames = set(["Vikes", "Demmies", "D", "MS", "Contin"]) riskNames = set(["enough", "pop", "final", "stress", "trade"]) d = {1: "Vikes is not enough for me", 2:"Demmies is okay", 3:"pop a D"} for...