w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Possibilities and nested foreach loops C#
Try a recursive method. A small example : public List<Table> assignToTable(List<Person> invited, List<Table> tables) { if(!tables.HasRoom) return tables; else { assign(tables,invited) //code to add a person to a table assignToTable(invited, tables); } } If I were you I'll create a object taht represent you tables with a propertie to know if there is still some room avaiblable. This will assign to every people a table without any foreach. Then in you main you could have a method that will rearrange the tables in all the way possible : Table 1 Table 2 Table 3 Then Table 1 Table 3 Table 2 ... Table 3 Table 2 Table 1 and call the recursive method on those lists and you will have all the possibility where poeple can sit...

Categories : C#

Nested foreach loops - anything more efficient?
You can squeeze a bit more performance from your loops by using the values by reference: foreach ($arraykey as $columnname => &$value) { Hence the &$value, but beware, every time you do something to $value after that, it will affect the original $arraykey[$columnname] value. Also, not sure you're nesting the foreach correctly. I would move the ending bracket for the nested foreach down: // $value passed by reference foreach ($arraykey as $columnname => &$value) { // Pass $field_entity_id by reference foreach ($records as &$field_entity_id) { $fieldinsertloop = "('registration', 'reg_type', 0,".$field_entity_id.",".$field_entity_id.", 'und', 0,'".$value."','".$value."')"; $sql = "INSERT INTO " .str_replace("multi_reg", "field_data", $colu

Categories : PHP

nested for loops in python with lists
Use the zip function, like this: list1=['a','b'] list2=['y','z'] for i, j in zip(list1, list2): print(i, j) Output: ('a', 'y') ('b', 'z')

Categories : Python

Nested foreach loops, PHP, how do I manipulate the values?
You need to use the reference syntax (& prefix): foreach ($final_array as &$final_array_val) { } unset($final_array_val); Note that the unset is required to break the reference to the last value. Read more here.

Categories : PHP

Why does not the data-binding work? (using nested foreach loops)
This can't work : self.pc_listOfExpenses()[claimID] = JSON.parse(data); Because you are modifying the internal array of the observableArray(). I am not sure, but you could try this : var items = self.pc_listOfExpenses(); items[claimID] = JSON.parse(data); self.pc_listOfExpenses(items); I hope it helps.

Categories : Javascript

nested foreach loops in R to update common array
foreach loops are used for their return value, like lapply. In this way they are very different from for loops which are used for their side effects. By using the appropriate .combine functions, the inner foreach loop can return vectors which are combined row-wise into a matrix by the outer foreach loop: x <- foreach(i=1:8, .combine='rbind') %dopar% { foreach(j=1:2, .combine='c') %do% { l <- runif(1, i, 100) i + j + l } } You can also use the nesting operator: %:%: x <- foreach(i=1:8, .combine='rbind') %:% foreach(j=1:2, .combine='c') %dopar% { l <- runif(1, i, 100) i + j + l } Note that set.seed probably won't do what you want, since it is being performed on the local machine, while the random numbers are generated in different R ses

Categories : R

Write nested XML file with powershell in foreach loops
using $xmlWriter.WriteEndElement() instead of $xmlWriter.WriteEndElement should fix your problem same problem in this post

Categories : Xml

Avoiding nested each loops when handling nested JSON data
JSON is "just" javascript object literals. You can skip the jQuery call, and just reference the objects and arrays directly after you parse it. obj.custom_sql_rule[0].something_else[0]; of course, your JSON is a bit oddly-formed. If at all possible, don't arbitrarily mix objects {} and arrays [] . Use the latter when you have lists of identical objects or primitive data, and the former when you have named properties. And once you have a valid javascript object, you can just iterate through its properties. for(var sqlProp in jsonObj) { if(jsonObj[sqlProp].error) { errorsContainer.append("<div>" + jsonObj[sqlProp].error + "</div>"); } }

Categories : Javascript

How to insert nested lists (or nested block elements) into RichTextBlock?
Ok Ill start with silverlight. There was a TreeView Control in silverlight that would have exactly solved your problem. Link to tree view example But since we already know that winRt is a subset of API's these controls have been removed for metro app. More over microsofts design policy regarding the Type Of scenario you are mentioning has changed to : Semantic Zoom For Metro Apps So i advise if your app requirement is like that Either go with the richtextbox or use Grids with Rows and columns Which ever suits your coding best. One more way is to use third party library for tree structure . Syncfusion tree control Syncfusion has a tree control you can try out in the Demo. Even there are more third party tool but none are free not even he above one. Please Let me know if any more co

Categories : HTML

PHP: Pull values foreach() nested array, run function, return a 2nd level nested array
foreach ($array as $key => $value){ $array[$key]['restaurants'] = work($value['id'],$value['name']); } function work($id,$name){ $results = array(); ///process data return $results; }

Categories : PHP

Struts 1.1 nested and in combination
Use <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> and the code will look like <c:choose> <c:when test="${element.method1 == true}"> <c:choose> <c:when test="${element.method2 == true}"> <span style="color:green;"><c:out value="${element.prop1}/></span> </c:when> <c:otherwise> <span style="color:red;"><c:out value="${element.prop1}/></span> </c:otherwise> </c:choose> </c:when> <c:otherwise> <span style="color:black;"><c:out value="${element.prop1}/></span> </c:otherwise> </c:choose>

Categories : Java

Nested for loops in OMP C
I can confirm, you have some data-race error. Without OpenMP: First number : 123456 Second number : 654321 Result :  08563613376 Calculation time = 0.005543371655221563 With OpenMP: First number : 123456 Second number : 654321 Result :  00000000825 Calculation time = 0.007188999978097854 And I don't solve the whole problem, but based on i saw, i have some remark. First i would say that you should specify the for variable in the for construct #pragma omp for schedule(dynamic) nowait for(int i=0;i<=aLength;i++) { a[i] = a[i] - 48; } And an example of the main error you made (every time) ... when you enter a parallel region you MUST take care of your variable. what is shared, what is private to each thread ? In your end loop, you don't use

Categories : C

Nested for loops, is there a better way?
To create a copy of an array, just do this: var newArray = oldArray.slice(0); That aside, I can't really think of any simpler way to filter out empty values, other than just not having them there in the first place.

Categories : Javascript

Nested "for" loops c++
You should initialize max to 0. int max = 0; Additionally there are two more bugs. int max ; should be declared before the for loop for i. (Otherwise max is defined to be 0 always) In the inner loop print i, not j.

Categories : C++

SQL nested loops
UPDATE QUESTIONNAIRE_QUESTIONS SET QUESTION_CODE = (QUESTION_NUMBER * 100) WHERE QUESTIONNAIRE_QUESTIONS.ID IN (SELECT DISTINCT QUESTIONNAIRE.ID FROM QUESTIONNAIRE, QUESTIONNAIRE_QUESTIONS WHERE QUESTIONNAIRE_QUESTIONS.ID = PARENT_QUESTION_ID) Not so sure about the 2nd question. Is that a typo?QUESTION_CODE.QUESTION_NUMBER*100

Categories : SQL

How to use nested for loops?
This needs to be done every time the outer loop is accessed: system.out.println(); this allows the *'s to be on different lines, also this code only does the top half of the triangle. In order to do the bottom half, you have to count down from tri.

Categories : Java

Is there a better way to implement those nested loops?
first you need to merge all arrays char[] one = {'a', 'b', 'c'}; char[] two = {'1', '2', '3'}; char[] three = {'x', 'y', 'z'}; char[] four = {'m', 'n', 'o'}; char[][] a = new char[4][]; a[0] = one; a[1] = two; a[2] = three; a[3] = four; then you can print what you want with 2 for like this int[] index = new int[4]; for (int i = 0; i < Math.pow(3, 4); i++) { int current = i; for (int j = 0; j < 2; j++) { index[j] = current % 3; current /= 3; } int k=0; for (int j=index.length-1;j>=0;j--) { System.out.print(a[k][index[j]]+" "); k++; } System.out.println(); }

Categories : Java

Complicated nested loops
I think google have a lot of APIs to create charts... i found this one:Populating Data Using Server-Side Code PS:Im not a PHP programmer...i know a little only. I think it will help you ...

Categories : PHP

Nested for each loops in Objective-C
The way you do it, for each single iteration of the first loop the second loop iterates completely. I think it won't work with a for-in loop. But you said the number of items in the two arrays is the same - so you can easily do: for (i=0; i< feedsArray.count; i++) { NSDictionary subscription = feedsArray[i]; NSDictionary unreadCount = unreadCountsArray[i]; [RDInsertObjects insertFeedsWithSubscription: subscription unreadCount: unreadCount]; } This will only work, if the number of items in the array are always ever the same - if sometime they aren't, you need a modification to prevent an out-of-bounds error or it will crash!

Categories : IOS

How do I create nested loops with LESS CSS?
Hm, nevermind—Found it myself. I’m leaving the answer here for posterity’s sake: @maxi: 8; .i-loop (@i) when (@i > 0) { @maxj: 8; .j-loop (@j) when (@j > 0) { .my-class-@{i}-@{j} { width: (100% / @i); height: (100% / @j); } .j-loop(@j - 1); } .j-loop (0) {} .j-loop(@maxj); .i-loop(@i - 1); } .i-loop (0) {} .i-loop(@maxi);

Categories : CSS

how to exit nested loops
Don't cook spaghetti and extract your loops into the function: void foo(...) { while (...) { /* some code... */ while (...) { if ( /* this loop should stop */ ) break; if ( /* both loops should stop */ ) return; } /* more code... */ } } this decomposition will also yield cleaner code since instead of hundreds of lines of ugly procedural code, you will have neat functions at different levels of abstraction.

Categories : C++

jQuery : nested loops
I don't know how the ajax returns the countries/cities objects but here is an example how you can create that select options var countries = ["United Kingdom", "France", "Spain"]; var cities = [["London", "Birmingham", "Bristol", "Leeds"], ["Paris", "Lille", "Calais"], ["Barcelona", "Real Madrid"] ]; $(countries).each(function(key, val){ $("#result").append('<optgroup label="'+val+'">'); $(cities[key]).each(function(k, v){ $("#result").append('<option>'+v+'</option>'); }); $("#result").append('</optgroup>'); }); EXAMPLE: http://jsfiddle.net/kC75w/

Categories : Jquery

Nested loops in php mysql
It's a little confusing to understand without a printscreen of your page or something, but it sounds like you have a page that allows multiple checkboxes to be selected at the same time, yet you're only keeping the reference for a single checbox in your $_POST. If that's the case, you should be sending the questions' ID's through an array. Please take a look at this accepted answer to see how that can be done: PHP $_POST get data array

Categories : PHP

Vectorising Nested For Loops
So you want to vectorise this code: for k = 1:10 for l = 1:num L_Mid(k,l) = sum(LMat(k,1+in_point(l):out_point(l))); L_Sides(k,l) = sum(LMat(k,:))-L_Mid(k,l); end end First step, removing the outer loop: for l=1:num L_Mid(:,l)=sum(LMat(:,1+in_point(l):out_point(l)),2); % Using the dim input to sum L_Sides(:,l) = bsxfun(@minus,sum(LMat,2),L_Mid(:,l)); % Using bsxfun to subtract end Next step, L_Sides can be created with a single operation: for l=1:num L_Mid(:,l)=sum(LMat(:,1+in_point(l):out_point(l)),2); % Using the dim input to sum end L_Sides = bsxfun(@minus,sum(LMat,2),L_Mid); Since the length of in_point(l):out_point(l) is variable, there is no tidy way to vectorize this (that I know of; anyone got a good way I'd love to know!), and you c

Categories : Matlab

how to browse nested for loops
Alright, I think it is a bit hard to understand what is wrong in your code. I can't see anything obvious (maybe someone else will) but here are a couple points to help you find out what is going on: Have you tried to comment out all your functions in your last loop (with iterator p)? Is it working when you do so? You probably don't want to do any display in this big loop, you should build or draw everything then display only when finished. Refactoring this code would be a good idea, you may know what you're doing now but how about in 6 months? I'm not even mentioning the fact that someone else seeing this code will probably either give up understanding it or rewrite the whole thing himself even if the bug fix would have been one character.

Categories : C++

Is there a way I can avoid these nested loops?
Unless the trackslopes/trackconvolve procedures can be reduced to something simple, then there is no way to (non-trivially) remove the nested loops. The best way to see this is that each sub-loop depends on the values of at least one of its super-loops, so that unless the inner-most computation is such that the entire process can be simplified mathematically, it is already in its simplest form. If you just don't like looking at that many levels of nesting, you can try to flatten the 5-D space by using an array of indices instead of 5 distinct indices, and then you have to write a fairly ugly 1-D loop which checks the bounds of each of the 5 indices and then advances the index array appropriately.

Categories : Performance

Nested Loops Ruby
For make the problem simple, I think it is better calculate all round multiples before update the pebble. pebbles = Array.new(10) 10.times do |i| # calculate all multiples for each index multiples = Array(1..10).select {|j| j % (i + 1) == 0} # observer that we must have to sub 1 since Ruby use 0 indexed arrays multiples.map! {|j| j - 1} # update each pebble multiples.each do |j| pebbles[j] = pebbles[j] == 'b' ? 'w' : 'b' end end puts "Black pebbles: #{pebbles.select {|p| p == 'b'}.size}"

Categories : Ruby

Generalized nested for loops
I'm not 100% certain about what you want to achieve, but I believe what you would want here is polymorphism, namely inheritance and virtual functions (I dunno which language you are using but C++, for example, supports this). Basically, you would make Global government the base class, and all your other classes the derived classes which would inherit Global government (or each other). Through inheritance you can establish the hierarchy you want (for example, by making classes lower in the hierarchy inherit from classes higher up in the hierarchy). This page covers inheritance: http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Now for the iterative part: first, you declare functions/methods virtual (using the keyword virtual) in the base class (e.g. global governme

Categories : Java

Nested Parallel While Loops
Have you tried using a single loop with && ? while (toc(t_start) < trial_duration) && (check ~= 1) % Data Collection count = count +1; end

Categories : Multithreading

Javascript get Div info from nested Div
You could use document.querySelectorAll('div#countdowndiv div#time') but you should note that it isn't completely cross-browswer compatible. More information here.

Categories : Javascript

How/should I use nested for loops inside of if statements?
It is difficult to tell the precise situation here, but this is how it sounds to me: defaults is almost certainly meant to be an instance of NSUserDefaults. The bolded "for" in your instructions is not suggesting a for-loop; it's giving you a hint at the method you need to use. Take a look at the NSUserDefaults reference there and see if you can find a method that might be useful for looking up a BOOL value for a named key.

Categories : Objective C

Single Line Nested For Loops
The best source of information is the official Python tutorial on list comprehensions. List comprehensions are nearly the same as for loops (certainly any list comprehension can be written as a for-loop) but they are often faster than using a for loop. Look at this longer list comprehension from the tutorial (the if part filters the comprehension, only parts that pass the if statement are passed into the final part of the list comprehension (here (x,y)): >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] It's exactly the same as this nested for loop (and, as the tutorial says, note how the order of for and if are the same). >>> combs = [] >>> for x in [1,2,3]: ... for y in [3,1,4]: ...

Categories : Python

nested loops, how to make a calendar
Seems like this is a homework problem, so I'm not going to give you the code, but you're heading in the right direction. First, I'd change System.out.print("x"); to System.out.print(" x"); //Add two spaces in front of the x so you have space between the numbers. Next, to generate actual numbers instead of x's, put int dayOfMonth = 1; above the for loop. You'll then want to print out dayOfMonth instead of x's. The problem I leave to you is how to make the value of dayOfMonth increase each time.

Categories : Java

How can I simplify my nested for-loops with ReactiveCocoa?
You basically would like to create the cartesian product of the dictionaries and make a selection on it. There is no default operator in ReactiveCocoa that I know of that would do this for you. (In LINQ there are operators for this.) In RAC the simplest solution is to use the scanWithStart:combine: method to implement this operation. Once the cartesian is ready, the filter: and take:1 operations will produce the sequence of your choice. NSDictionary *adic = @{@"aa":@"vb", @"ab": @"va"}; NSDictionary *bdic = @{@"ba": @"va", @"bb":@"vb"};; RACSequence *aseq = adic.rac_keySequence; RACSequence *bseq = bdic.rac_keySequence; RACSequence *cartesian = [[aseq scanWithStart:nil combine:^id(id running, id next_a) { return [bseq scanWithStart:nil combine:^id(id running, id next_b) { re

Categories : Objective C

Nested loops for large datasets
Hmm. Well, first of all,this code is probably so heavily I/O bound that optimizing anything but disk access is probably inconsequential. You might try throwing a pointless loop to 1000 before every if-test just to see how much difference that makes. It doesn't appear like indexing would help you here, since you must access all the data when a value isn't specified, but if you are computing aggregates then caching those might help. Intersystem's DeepSee product is designed for that. But it sounds like maybe you are just running a big report printing all the data, and want to optimize what you can. In that case, I think your solution does that. As far as elegance, well, it usually isn't found in conjunction with heavy optimization. The problem with generalizing a solution is that it'

Categories : Misc

Storing output from nested for loops in r
Similar to how you create a ctr variable outside the scope of your for loop, if you want to retain the results of these loops you should create some sort of storage variable for the output you're trying to capture. If you can provide a reproducible example we can help you more. Here's a simple example: p=10 q=20 M=matrix(seq(1,p*q), p, q) output=matrix(NA, p,q) # storage matrix for(i in 1:p){ for(j in 1:q){ # do something output[i,j] = 2*i + j^2 } } As others have stated, it's likely that what you are trying to accomplish would be simplified by using the apply functions.

Categories : R

How to simplify nested loops and conditions?
You could do this: for (i = 0; i < data.length; i++) { if (chars.indexOf(data[i].item) != -1) { // Do something } else { // Do something else } } However, if chars is large, I would create an object whose keys are the elements of chars and use if (chars_obj[data[i].item]). This is more efficient than searching an array every time.

Categories : Javascript

issue with two nested loops in bash
In the script there is a mistake which echoes a value of $mica_header which will be substituted only for make calls in the next outer loop run. This is caused by the second sed being run only after make. It should have been called before the inner loop. Could not this cause the confusion? Also instead of replacing one value of a parameter for another it is better to create a template of r.src file with placeholders for the parameters to be changed. This way we can be sure that for some values of the parameters there could not be conflicts with the search patterns and that a typo will not prevent substitution. Below is an improved script with considerably simpler code. The part inside if test "$Test" = 1 is just a testing code activated by Test=1. For this script just create a template fo

Categories : Bash

More efficient nested loops calculation
The best solution would be to represent the date in SQLITE in a sortable format; # of seconds since epoch is typical. Then you can use an ORDER BY as @bengoesboom suggested. If you can't do that, then you can collapse those two loops into a single call to sortedArrayUsingComparator: where the comparator does the conversion. That, of course, is going to be really slow because you'll be repeatedly parsing the dates. You really need to represent the dates in the objects as NSDates, probably by doing the conversion when fetched from the database. And, of course, I hope you are at least using something like FMDB and not the raw SQLite APIs. As well, if you don't need data format portability, consider using Core Data.

Categories : Objective C

Update database with nested for loops?
Don't use $x in for($x = 0; $x < sizeof($answer); $x++){ **$x** = sprintf("UPDATE exam_answers SET answer_description = '%s' WHERE answer_question_set_id = '%s'", mysql_real_escape_string($answer[$x]), mysql_real_escape_string($answerid[$x])); mysql_query($x)or die(mysql_error()); } Instead use another variable of your choice. this will complicate to your loop.

Categories : PHP



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.