Search Results

Search found 4868 results on 195 pages for 'foreach'.

Page 14/195 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • How to get user inputs of trinidad componant which are placed in tr:foreach tag?

    - by Navnath
    Hi There, Can any one tell me how do I get user inputs from jsf component which are placed inside tr:foreach tag? I am trying to show multiple table where there are some fields which user can be input for it. I don't know how many table are going to display on page, because that decide at run time. So I put that table tag inside foreach tag. Now I want to reat each tables each record. But I am not able to do that because, there is no any binding attribute for foreach tag. Just sample code..... Thank You, Navnath Kumbhar.

    Read the article

  • Powershell Foreach-Object with if statement not working - help!

    - by Dmart
    I have a batch file that takes a computer name as its argument and will install Java JRE on it remotely. Now, Im trying to run this Powershell script to repeatedly call the batch file and install Java on any system that it finds without the latest version. It seems to run error-free, but the statements inside the if code block never seem to run - even when the if conditional test evaluates to true. Can anyone look at this script and point out what I'm possibly missing? I'm using the Quest AD cmdlets, and BSOnPosh module. Thank you. get-qadcomputer -sizelimit 0 -name mypc* -searchroot 'OU=MyComputers,DC=MyDomain,DC=lcl'| test-host -property name |ForEach-Object -process { $targnm = $_.name $tststr=reg query "\\$targnm\HKLM\SOFTWARE\JavaSoft\Java Runtime Environment" /v Java6FamilyVersion if(-not ($tststr | select-string -SimpleMatch '1.6.0_20')) { $mssg="Updating to JRE 6u20 on $targnm" Out-Host $mssg Out-File -filepath c:\install_jre_log.txt -inputobject $mssg -Append cmd /c \\server\apps\java\installjreremote.cmd $targnm } else { $mssg ="JRE 6u20 found on $targnm" Out-Host $mssg Out-File -filepath c:\install_jre_log.txt -inputobject $mssg -Append } }

    Read the article

  • How to convert this foreach loop into Linq code?

    - by a-galkin
    I am new one with Linq and I would like to modify my old c# code to use Linq. The idea of this code to select all tables where it's not set and reference’s field PrimaryTable equal "myTable" foreach (Table table in dbServer.Tables) { if (!table.IsSet) { foreach (Reference refer in table.References) { if (refer.PrimaryTable == "myTable") { tables.Add(table); } } } } After digging in internet I have got this code var q = from table in dbServer.Tables let refers = from refer in table.References where refer.PrimaryTable == "myTable" select refer.ForeignTable where refers.Contains(table.Name) select table; But it does not work at all and I need your help to make it works. Thanks in advance.

    Read the article

  • Smarty iteration: is there a similar function when not in a foreach loop?

    - by Kyle Sevenoaks
    Hi, I'm trying to add a JS fly to basket plugin to the site I'm working on, but the plugin needs unique productID numbers, is there a way to iterate this in Smarty when not in a foreach loop? Something like: {$smarty.foreach.foo.iteration} Here's the code I need to itrate: <span id="slidingProd57404045"> <a href="{link controller=order action=addToCart id=$product.ID returnPath=true}" rel="nofollow" class="addToCart" title="Bestill" onclick="addToBasket(57404045); return false;" id="fly_to_basket">&nbsp;</a> </span> The 57404045 needs to be iterated. Thanks.

    Read the article

  • Gathering buslogic SCSI hardware and virtual machine operating system

    - by Julian
    I'm trying to use Powershell to get SCSI hardware from several virtual servers and get the operating system of each specific server. I've managed to get the specific SCSI hardware that I want to find with my code, however I'm unable to figure out how to properly get the operating system of each of the servers. Also, I'm trying to send all the data that I find into a csv log file, however I'm unsure of how you can make a powershell script create multiple columns. Here is my code (almost works but something's wrong): $log = "C:\Users\me\Documents\Scripts\ScsiLog.csv" Get-VM | Foreach-Object { $vm = $_ Get-ScsiController -VM $vm | Where-Object { $_.Type -eq "VirtualBusLogic" } | Foreach-Object { get-VMGuest -VM $vm } | Foreach-Object{ Write-output $vm.Guest.VmName >> $log } } I don't receive any errors when I run this code however whenever I run it I'm only getting the name of the servers and not the OS. Also I'm not sure what I need to do to make the OS appear in a different column from the name of the server in the csv log that I'm creating. What do I need to change in my code to get the OS version of each virtual machine and output it in a different column in my csv log file? EDIT: Here's a more in depth look at things I've tried that have all failed: Get-VM | Foreach-Object { $vm = $_ $svm = Get-ScsiController -VM $vm | Where-Object { $_.Type -eq "VirtualBusLogic" } Foreach-Object {get-VMGuest -VM $svm } | Foreach-Object{Write-output $svm >> $log} } #Get-VM | Foreach-Object { # $vm = $_ # Get-ScsiController -VM $vm | Where-Object { $_.Type -eq "VirtualBusLogic"} #| write-host $vm # | Foreach-Object { # # #get-VMGuest -VM $_ | # #write-host $vm # #get-VMGuest -VM $vm } | Foreach-Object{ # #write-output $vm.VmName >> $log # #write-output $vm.guest.VmName, get-VmGuest -VM $vm >> $log NO GOOD # # Write-host $vm.Guest.VmName #+ get-vmGuest -vm $VM >> $log # # # } # } I'm not sure why get-VmGuest fails though. I'm getting the scsi hardware, filtering the hardware to only get buslogic, and then wanting to get the operating system of just the filtered VMs. I don't see where my code fails though.

    Read the article

  • Why is my element variable always null in this foreach loop?

    - by ZeroDivide
    Here is the code: public IEnumerable<UserSummary> getUserSummaryList() { var db = new entityContext(); List<UserSummary> model = new List<UserSummary>(); List<aspnet_Users> users = (from user in db.aspnet_Users select user).ToList<aspnet_Users>(); foreach (aspnet_Users u in users) //u is always null while users is a list that contains 4 objects { model.Add(new UserSummary() { UserName = u.UserName, Email = u.aspnet_Membership.Email, Role = Roles.GetRolesForUser(u.UserName).First(), AdCompany = u.AD_COMPANIES.ad_company_name != null ? u.AD_COMPANIES.ad_company_name : "Not an Advertiser", EmployeeName = u.EMPLOYEE.emp_name != null ? u.EMPLOYEE.emp_name : "Not an Employee" }); } return model; } For some reason the u variable in the foreach loop is always null. I've stepped through the code and the users collection is always populated. The table entity for db.aspnet_Users is the users table that comes with asp.net membership services. I've only added a couple associations to it. edit : image of debugger

    Read the article

  • Tooltips problem, making this javascript work with my smarty foreach loop, help pelase!

    - by Kyle Sevenoaks
    I am using an example of tooltips from http://www.dynamicdrive.com/dynamicindex5/stickytooltip.htm on www.euroworker.no/order I have this code here to work with, but it just doesn't seem to work correctly, I've tried everything I can think of (not a lot of things) Here's the code. {foreach from=$cart.cartItems item="item" name="cart"} <div class="{zebra loop="cart"}"> <div id="sgproductview"> <div id="cart2Varekode"> <p> {if $product.sku} <span class="param">{$item.product.sku}</span> {else} <span>{img src=$item.Product.DefaultImage.paths.1 alt=$item.Product.name_lang|escape}</span> {/if} </p> </div> <div id="cart2Produkt"> <p>{if $item.Product.ID} <a href="{productUrl product=$item.Product}" data-tooltip="sticky{$smarty.foreach.cart.iteration}" target="_blank">{$item.Product.name_lang|truncate:20}</a> {else} <span>{$item.Product.name_lang|truncate:20}</span> </a> {/if} </p> <p> {include file="order/itemVariations.tpl"} {include file="order/block/itemOptions.tpl"} {if $multi} {include file="order/selectItemAddress.tpl" item=$item} {/if} </p> </div> {if $item.Product.DefaultImage.paths.3} <div id="mystickytooltip" class="stickytooltip"> <div style="padding:5px;"> <div id="sticky1" class="atip" style="width:200px;"> <img src="{$item.Product.DefaultImage.paths.3}" alt="{$item.Product.name_lang|escape}"><br> {$item.Product.name_lang} </div> <div id="sticky2" class="atip" style="width:200px;"> <img src={$item.Product.DefaultImage.paths.3} alt="{$item.Product.name_lang|escape}"><br> {$item.formattedPrice} </div> <div id="sticky3" class="atip" style="width:200px;"> <img src="{$item.Product.DefaultImage.paths.3}" alt="{$item.Product.name_lang|escape}"><br> {$item.Product.name_lang}PRODUCT 3 </div> <div id="sticky4" class="atip" style="width:200px;"> <img src="{$item.Product.DefaultImage.paths.3}" alt="{$item.Product.name_lang|escape}"><br> {$item.Product.name_lang} </div> </div> </div> {/if} <div id="cart2Price"> <p class="actualPrice"> {$item.formattedPrice} </p> </div> <div id="salg"></div> <div id="cart2Salg"> <p></p> </div> <div id="antallbox"> <p class="cartQuant"> {textfield name="item_`$item.ID`" class="text"} </p> </div> <div id="cart2Total"> <p> {if $item.count == 1} <span class="basePrice">{$item.formattedBasePrice}</span><span class="actualPrice">{$item.formattedPrice}</span> {else} {$item.formattedDisplaySubTotal} <div class="subTotalCalc"> {$item.count} x <span class="basePrice">{$item.formattedBasePrice}</span><span class="actualPrice">{$item.formattedPrice}</span> </div> {/if} </p> </div> <div id="delete"> {if 'ENABLE_WISHLISTS'|config} <a href="{link controller=order action=moveToWishList id=$item.ID query="return=`$return`"}">{t _move_to_wishlist}</a> {/if} <a id="slett" href="{link controller=order action=delete id=$item.ID query="return=`$return`"}" title="Slett"><!--{t _remove}--></a> </div> </div> </div> {/foreach} Anyone can help? {html_image} doesn't work, by the way and all the extensions are present and correct.

    Read the article

  • "Simple" sort a nested array using array_multisort or native PHP functions instead of my own foreach loop

    - by Ana Ban
    I have the following array of days of the week, with each day having hours of the day (the whole array represents the schedule of a part-time employee): Array ( [7] => Array ( [0] => 15 [1] => 14 [2] => 13 [3] => 11 [4] => 12 [5] => 10 ) [1] => Array ( [0] => 10 [1] => 13 [2] => 12 ) [6] => Array ( [0] => 14 ) [3] => Array ( [0] => 4 [1] => 5 [2] => 6 ) ) and I simply need to: sort asc each sub-array (2nd dimension) - no need to maintain the numeric keys, values are integers sort asc the 1st dimension and maintain the numeric, integer keys ie: Array ( [1] => Array ( [0] => 10 [1] => 12 [2] => 13 ) [3] => Array ( [0] => 4 [1] => 5 [2] => 6 ) [6] => Array ( [0] => 14 ) [7] => Array ( [0] => 10 [1] => 11 [2] => 12 [3] => 13 [4] => 14 [5] => 15 ) ) Additional info: only the keys of the 1st dimension and the values of the 2nd dimension (and of course their association) are meaningful to my use-case the 1st dimension can have at most 7 values, ranging from 1-7 (days of the week), and will have at least 1 value (1 day) the 2nd dimension can have at most 24 values, ranging from 0-23 (hours of each day), and will have at least 1 value (1 hour per day) I know I can do this with a foreach on the whole ksorted array and sort each 2nd dimension array: ksort($sched); foreach ($sched as &$array) sort($array); unset($array); but I was hoping I could achieve this with native php array function(s) instead. My search led me to try array_multisort(array_values($array), array_keys($array), $array) but I just can't make it work.

    Read the article

  • Spring mvc: controller returns [][], usable in jsp with foreach, but how to bind?

    - by Joe
    I'm building a spring mvc application. Now the problem I have is the following. I have a controller which adds a DayInfo[][] to my ModelMap. (DayInfo has an id, a title (String) and Text(also String). Now the problem I have is that I have no problem displaying this DayInfo[][] with foreach tags in my jsp. However I'm outputting the Title property as an input box(type text), and I'd like to be able to update this value (and thus saving it to be a database but that shouldn't be a problem). However I'm having trouble with binding this value to the input box so that it is actually returned to the controller. If anyone has some advice it would be welcome.

    Read the article

  • How do you find the last element of an array while iterating using a foreach loop in php ?

    - by Vaibhav Kamble
    I am writing a sql query creator using some parameters. While doing that ,I came across this problem. In java , Its very easy to detect the last element of an array from inside the for loop by just checking the current array position with the array length. for(int i=0; i< arr.length;i++){ boolean isLastElem = i== (arr.length -1) ? true : false; } php has some different fashion. They have non integer indexes to access arrays. So you must iterate over an array using foreach loop. But it becomes very problematic when you need to take some decision (in my case to append or/and parameter while building query). I am sure there must be some standard way of doing this. How do you solve this problem normally in php ?

    Read the article

  • is there an index to be accessed in the CI foreach with {}-Notation?

    - by helle
    Hello Guys, i'm new with Codeigniter,and whish to know if i can access any kind of iterator for the foreach with {}-Notation in my views. The thing is, i'm having a list which should be devided after each x items. example (what i would like to do: <ul> {list} <li>{items}</li> <? if ($iterator % 15 == 0) echo "</ul><ul>"; ?> {/list} </ul> thanks in advice ;-)

    Read the article

  • How does Array.ForEach() compare to standard for loop in C#?

    - by DaveN59
    I pine for the days when, as a C programmer, I could type: memset( byte_array, '0xFF' ); and get a byte array filled with 'FF' characters. So, I have been looking for a replacement for this: for (int i=0; i < byteArray.Length; i++) { byteArray[i] = 0xFF; } Lately, I have been using some of the new C# features and have been using this approach instead: Array.ForEach<byte>(byteArray, b => b = 0xFF); Granted, the second approach seems cleaner and is easier on the eye, but how does the performance compare to using the first approach? Am I introducing needless overhead by using Linq and generics? Thanks, Dave

    Read the article

  • Writing functions of tuples conveniently in Scala

    - by Alexey Romanov
    Quite a few functions on Map take a function on a key-value tuple as the argument. E.g. def foreach(f: ((A, B)) ? Unit): Unit. So I looked for a short way to write an argument to foreach: > val map = Map(1 -> 2, 3 -> 4) map: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 3 -> 4) > map.foreach((k, v) => println(k)) error: wrong number of parameters; expected = 1 map.foreach((k, v) => println(k)) ^ > map.foreach({(k, v) => println(k)}) error: wrong number of parameters; expected = 1 map.foreach({(k, v) => println(k)}) ^ > map.foreach(case (k, v) => println(k)) error: illegal start of simple expression map.foreach(case (k, v) => println(k)) ^ I can do > map.foreach(_ match {case (k, v) => println(k)}) 1 3 Any better alternatives?

    Read the article

  • making query from different related tables using codeigniter

    - by fatemeh karam
    I'm using codeigniter as i mentioned this is a part of my view code foreach($projects_query as $row)// $row indicates the projects { ?> <tr><td><h3><button type="submit" class="button red-gradient glossy" name = "project_click" > <?php echo $row->txtTaskName; ?></button></h3></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr> <?php foreach($tasks_query as $row2) { // if( $row->txtTaskName == "TestProject") if($row->intTaskID == $row2->intInside)// intInside indicades that the current task($row2) is the subset of which task (system , subsystem or project) { if($row2->intSummary == 0)//if the task(the system) is an executable task & doesn't have any subtask: { $query_team_user_id = $this->admin_in_out_model->get_user_team_task_query($row2->intTaskID);//runs the function and generates a query from tbl_userteamtask where intTaskID equals to the selected row's intTaskID foreach($query_team_user_id as $row_teamid) { $query_teamname = $this->admin_in_out_model->get_team_name($row_teamid->intTeamID); $query_fn_ln = $this->admin_in_out_model->get_fn_ln_from_userid($row_teamid->intUserID); foreach($query_teamname as $row_teamname) {?> <tr><td></td><td></td><td><h4> <?php echo $row2->txtTaskName;?></h4></td> <td><b><font color='#F33558'><?php echo $row_teamname->txtTeamName;?></font></b></td> <?php } foreach($query_fn_ln as $row_f_l_name) {?> <td> <?php echo $row_f_l_name->txtFirstname." ".$row_f_l_name->txtLastname;?></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td> <?php }?> </tr> <?php } } else{ ?> <tr><td></td><td></td><td><h4> <?php echo $row2->txtTaskName;?></h4></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr><?php } foreach($tasks_query as $row_subsystems) { if($row_subsystems->intInside == $row2->intTaskID )//if the task is the subtask of a system(it means the task is a subsystem) { if($row_subsystems->intSummary == 0)//if the task is an executable task & doesn't have any subtask: { $query_team_user_id = $this->admin_in_out_model->get_user_team_task_query($row_subsystems->intTaskID); foreach($query_team_user_id as $row_teamid) {?> <tr><?php $query_teamname = $this->admin_in_out_model->get_team_name($row_teamid->intTeamID); $query_fn_ln = $this->admin_in_out_model->get_fn_ln_from_userid($row_teamid->intUserID); foreach($query_teamname as $row_teamname) {?> <td></td><td></td><td><h5><?php echo $row_subsystems->txtTaskName?></h5><br/></td> <td><b><font color='#F33558'><?php echo $row_teamname->txtTeamName;?></font></b></td><?php } foreach($query_fn_ln as $row_f_l_name) {?> <td><?php echo $row_f_l_name->txtFirstname." ".$row_f_l_name->txtLastname;?></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><?php }?> </tr><?php } } else{ ?><tr><td></td><td></td><td><h5><?php echo $row_subsystems->txtTaskName?></h5></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr><?php } foreach($tasks_query as $row_tasks) { if($row_tasks->intInside == $row_subsystems->intTaskID )//if the task is the subtask of a subsystem { if($row_tasks->intSummary == 0)//if the task is an executable task & doesn't have any subtask: { $query_team_user_id = $this->admin_in_out_model->get_user_team_task_query($row_tasks->intTaskID); foreach($query_team_user_id as $row_teamid) {?> <tr><?php $query_teamname = $this->admin_in_out_model->get_team_name($row_teamid->intTeamID); $query_fn_ln = $this->admin_in_out_model->get_fn_ln_from_userid($row_teamid->intUserID); foreach($query_teamname as $row_teamname) {?> <td></td><td></td><td><b><?php echo $row_tasks->txtTaskName;?></b></td> <td><b><font color='#F33558'><?php echo $row_teamname->txtTeamName;?></font></b></td><?php } foreach($query_fn_ln as $row_f_l_name) {?> <td><?php echo $row_f_l_name->txtFirstname." ".$row_f_l_name->txtLastname;?></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><?php }?> </tr><?php } } } } } } } } }?> and in controller i have $projects_query = $this->admin_in_out_model->get_projects(); $tasks_query = $this->admin_in_out_model->get_systems(); $userteamtask = $this->admin_in_out_model->get_user_team_task(); $data['tasks_query'] = $tasks_query; $data['projects_query'] = $projects_query; $this->load->view('project_view',$data); but as you see I'm calling my model functions within the view how can i do something else to do this i mean not calling my model function in my view I have to add that, my model function have parameters these are the model functions: function get_projects() { $this -> db -> select('*'); $this -> db -> from('tbl_task'); $this -> db -> where('intInside','0'); $query = $this->db->get(); return $query->result(); } function get_systems() { $this -> db -> select('*'); $this -> db -> from('tbl_task '); $this -> db -> where('intInside <> ','0'); $query = $this->db->get(); return $query->result(); } function get_user_team_task_query($task_id)//gets information from tbl_userteamtask where the field intTaskID is equal to $task_id { $this -> db -> select('*'); $this -> db -> from('tbl_userteamtask'); $this -> db -> where('intTaskID',$task_id); $query_teamid = $this->db->get(); return $query_teamid->result(); } function get_user_team_task()//gets information from tbl_userteamtask where the field intTaskID is equal to $task_id { $this -> db -> select('*'); $this -> db -> from('tbl_userteamtask'); // $this -> db -> where('intTaskID',$task_id); $query_teamid = $this->db->get(); return $query_teamid->result(); } function get_team_name($query_teamid) { $this -> db -> select('*'); $this -> db -> from('tbl_team'); $this -> db -> where('intTeamID',$query_teamid); $query_teamname = $this->db->get(); return $query_teamname->result(); } function get_user_name($query_userid) { $this -> db -> select('*'); $this -> db -> from('tbl_user'); $this -> db -> where('intUserID',$query_userid); $query_username = $this->db->get(); return $query_username->result(); } function get_fn_ln_from_userid($selected_id) { $this -> db -> select('tbl_user.intUserID, tbl_user.intPersonID,tbl_person.intPersonID,tbl_person.txtFirstname, tbl_person.txtLastname'); $this -> db -> from('tbl_user , tbl_person'); $where = "tbl_user.intPersonID = tbl_person.intPersonID "; $this -> db -> where($where); $this -> db -> where('tbl_user.intUserID', $selected_id); $query = $this -> db -> get();//makes query from DB return $query->result(); } do I have to use subquery ? is this true? i mean can i do this? foreach( $data as $key => $each ) { $data[$key]['team_id'] = $this->get_user_team_task_query( $each['intTaskID'] ); foreach($data[$key]['team_id'] as $key_teamname => $each) { $data[$key_teamname]['team_name'] = $this->get_team_name( $each['intTeamID'] ); } } the model code: foreach( $data as $key => $each ) { $data[$key]['intTaskID'] = $each['intTaskID']; $data[$key]['team_id'] = $this->get_user_team_task_query( $each['intTaskID'] ); foreach($data[$key]['team_id'] as $key => $each) { $data[$key]['team_name'] = $this->get_team_name( $each['intTeamID'] ); #fetching of the teamname and saving in the array $data[$key]['user_name'] = $this->get_fn_ln_from_userid( $each['intUserID'] ); foreach($data[$key]['user_name'] as $key => $each) { $data[$key]['first_name'] = $each['txtFirstname'] ; $data[$key]['last_name'] = $each['txtLastname'] ; } $data[$key]['first_name'] = $data[$key]['first_name']; $data[$key]['last_name'] = $data[$key]['last_name']; } }

    Read the article

  • Parallelism in .NET – Part 8, PLINQ’s ForAll Method

    - by Reed
    Parallel LINQ extends LINQ to Objects, and is typically very similar.  However, as I previously discussed, there are some differences.  Although the standard way to handle simple Data Parellelism is via Parallel.ForEach, it’s possible to do the same thing via PLINQ. PLINQ adds a new method unavailable in standard LINQ which provides new functionality… LINQ is designed to provide a much simpler way of handling querying, including filtering, ordering, grouping, and many other benefits.  Reading the description in LINQ to Objects on MSDN, it becomes clear that the thinking behind LINQ deals with retrieval of data.  LINQ works by adding a functional programming style on top of .NET, allowing us to express filters in terms of predicate functions, for example. PLINQ is, generally, very similar.  Typically, when using PLINQ, we write declarative statements to filter a dataset or perform an aggregation.  However, PLINQ adds one new method, which provides a very different purpose: ForAll. The ForAll method is defined on ParallelEnumerable, and will work upon any ParallelQuery<T>.  Unlike the sequence operators in LINQ and PLINQ, ForAll is intended to cause side effects.  It does not filter a collection, but rather invokes an action on each element of the collection. At first glance, this seems like a bad idea.  For example, Eric Lippert clearly explained two philosophical objections to providing an IEnumerable<T>.ForEach extension method, one of which still applies when parallelized.  The sole purpose of this method is to cause side effects, and as such, I agree that the ForAll method “violates the functional programming principles that all the other sequence operators are based upon”, in exactly the same manner an IEnumerable<T>.ForEach extension method would violate these principles.  Eric Lippert’s second reason for disliking a ForEach extension method does not necessarily apply to ForAll – replacing ForAll with a call to Parallel.ForEach has the same closure semantics, so there is no loss there. Although ForAll may have philosophical issues, there is a pragmatic reason to include this method.  Without ForAll, we would take a fairly serious performance hit in many situations.  Often, we need to perform some filtering or grouping, then perform an action using the results of our filter.  Using a standard foreach statement to perform our action would avoid this philosophical issue: // Filter our collection var filteredItems = collection.AsParallel().Where( i => i.SomePredicate() ); // Now perform an action foreach (var item in filteredItems) { // These will now run serially item.DoSomething(); } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } This would cause a loss in performance, since we lose any parallelism in place, and cause all of our actions to be run serially. We could easily use a Parallel.ForEach instead, which adds parallelism to the actions: // Filter our collection var filteredItems = collection.AsParallel().Where( i => i.SomePredicate() ); // Now perform an action once the filter completes Parallel.ForEach(filteredItems, item => { // These will now run in parallel item.DoSomething(); }); This is a noticeable improvement, since both our filtering and our actions run parallelized.  However, there is still a large bottleneck in place here.  The problem lies with my comment “perform an action once the filter completes”.  Here, we’re parallelizing the filter, then collecting all of the results, blocking until the filter completes.  Once the filtering of every element is completed, we then repartition the results of the filter, reschedule into multiple threads, and perform the action on each element.  By moving this into two separate statements, we potentially double our parallelization overhead, since we’re forcing the work to be partitioned and scheduled twice as many times. This is where the pragmatism comes into play.  By violating our functional principles, we gain the ability to avoid the overhead and cost of rescheduling the work: // Perform an action on the results of our filter collection .AsParallel() .Where( i => i.SomePredicate() ) .ForAll( i => i.DoSomething() ); The ability to avoid the scheduling overhead is a compelling reason to use ForAll.  This really goes back to one of the key points I discussed in data parallelism: Partition your problem in a way to place the most work possible into each task.  Here, this means leaving the statement attached to the expression, even though it causes side effects and is not standard usage for LINQ. This leads to my one guideline for using ForAll: The ForAll extension method should only be used to process the results of a parallel query, as returned by a PLINQ expression. Any other usage scenario should use Parallel.ForEach, instead.

    Read the article

  • How would i stop this foreach loop after 3 iterations?

    - by Tapha
    Here is the loop. foreach($results->results as $result){ echo '<div id="twitter_status">'; echo '<img src="'.$result->profile_image_url.'" class="twitter_image">'; $text_n = $result->text; echo "<div id='text_twit'>".$text_n."</div>"; echo '<div id="twitter_small">'; echo "<span id='link_user'".'<a href="http://www.twitter.com/'.$result->from_user.'">'.$result->from_user.'</a></span>'; $date = $result->created_at; $dateFormat = new DateIntervalFormat(); $time = strtotime($result->created_at); echo "<div class='time'>"; print sprintf('Submitted %s ago', $dateFormat->getInterval($time)); echo '</div>'; echo "</div>"; echo "</div>"; Thanks!!!! alot.

    Read the article

  • How can I use multi-threading with a "for" or "foreach" loop?

    - by saafh
    I am trying to run the for loop in a separate thread so that the UI should be responsive and the progress bar is visible. The problem is that I don't know how to do that :). In this code, the process starts in a separate thread, but the next part of the code is executed at the same time. The messageBox is displayed and the results are never returned (e.g. the listbox's selected index property is never set). It doesn't work even if I use, "taskEx.delay()". TaskEx.Run(() => { for (int i = 0; i < sResults.Count(); i++) { if (sResults.ElementAt(i).DisplayIndexForSearchListBox.Trim().Contains(ayaStr)) { lstGoto.SelectedIndex = i; lstGoto_SelectionChanged(lstReadingSearchResults, null); IsIndexMatched = true; break; } } }); //TaskEx.delay(1000); if (IsIndexMatched == true) stkPanelGoto.Visibility = Visibility.Collapsed; else //the index didn't match { MessagePrompt.ShowMessage("The test'" + ayaStr + "' does not exist.", "Warning!"); } Could anyone please tell me how can I use multi-threading with a "for" or "foreach" loop?

    Read the article

  • Deleted array value still showing up on foreach loop in AS3 (bug in flash?)

    - by nexus
    It took me many hours to narrow down a problem in some code to this reproducible error, which seems to me like a bug in AVM2. Can anyone shed light on why this is occurring or how to fix it? When the value at index 1 is deleted and a value is subsequently set at index 0, the non-existent (undefined) value at index 1 will now show up in a foreach loop. I have only been able to produce this outcome with index 1 and 0 (not any other n and n-1). Run this code: package { import flash.display.Sprite; public class Main extends Sprite { public function Main():void { var bar : Array = new Array(6); out(bar); //proper behavior trace("bar[1] = 1", bar[1] = 1); out(bar); //proper behavior trace("delete bar[1]", delete bar[1]); out(bar); //proper behavior trace("bar[4] = 4", bar[4] = 4); out(bar); //for each loop will now iterate over the undefined position at index 1 trace("bar[0] = 0", bar[0] = 0); out(bar); trace("bar[3] = 3", bar[3] = 3); out(bar); } private function out(bar:Array):void { trace(bar); for each(var i : * in bar) { trace(i); } } } } It will give this output: ,,,,, bar[1] = 1 1 ,1,,,, 1 delete bar[1] true ,,,,, bar[4] = 4 4 ,,,,4, 4 bar[0] = 0 0 0,,,,4, 0 undefined 4 bar[3] = 3 3 0,,,3,4, 0 undefined 4 3

    Read the article

  • Performance due to entity update

    - by Rizzo
    I always think about 2 ways to code the global Step() function, both with pros and cons. Please note that AIStep is just to provide another more step for whoever who wants it. // Approach 1 step foreach( entity in entities ) { entity.DeltaStep( delta_time ); if( time_for_fixed_step ) entity.FixedStep(); if( time_for_AI_step ) entity.AIStep(); ... // all kind of updates you want } PRO: you just have to iterate once over all entities. CON: fidelity could be lower at some scenarios, since the entity.FixedStep() isn't going all at a time. // Approach 2 step foreach( entity in entities ) entity.DeltaStep( delta_time ); if( time_for_fixed_step ) foreach( entity in entities ) entity.FixedStep(); if( time_for_AI_step ) foreach( entity in entities ) entity.FixedStep(); // all kind of updates you want SEPARATED PRO: fidelity on FixedStep is higher, shouldn't be much time between all entities update, rather than Approach 1 where you may have to wait other updates until FixedStep() comes. CON: you iterate once for each kind of update. Also, a third approach could be a hybrid between both of them, something in the way of foreach( entity in entities ) { entity.DeltaStep( delta_time ); if( time_for_AI_step ) entity.AIStep(); // all kind of updates you want BUT FixedStep() } if( time_for_fixed_step ) { foreach( entity in entities ) { entity.FixedStep(); } } Just two loops, don't caring about time fidelity in nothing other than at FixedStep(). Any thoughts on this matter? Should it really matters to make all steps at once or am I thinking on problems that don't exist?

    Read the article

  • Determinism in multiplayer simulation with Box2D, and single computer

    - by Jake
    I wrote a small test car driving multiplayer game with Box2D using TCP server-client communcations. I ran 1 instance of server.exe and 2 instance of client.exe on the same machine that I code and compile the executables. I type inputs (WASD for a simple car movement) into one of the 2 clients and I can get both clients to update the simulation. There are 2 cars in the simulation. As long as the cars do not collide, I get the same identical output on both client.exe. I can run the car(s) around for as long as I could they still update the same. However, if I start to collide the cars, very quickly they go out of sync. My tools: Windows 7, C++, MSVS 2010, Box2D, freeGlut. My Psuedocode: // client.exe void timer(int value) { tcpServer.send(my_inputs); foreach(i = player including myself) inputs[i] = tcpServer.receive(); foreach(i = player including myself) players[i].process(inputs[i]); myb2World.step(33, 8, 6); // Box2D world step simulation foreach(i = player including myself) renderer.render(player[i]); glutTimerFunc(33, timer, 0); } // server.exe void serviceloop { while(all clients alive) { foreach(c = clients) tcpClients[c].receive(&inputs[c]); // send input of each client to all clients foreach(source = clients) { foreach(dest = clients) { tcpClients[dest].send(inputs[source]); } } } } I have read all over the internet and SE the following claims (paraphrased): Box2D is deterministic as long as floating point architecture/implementation is the same. (For any deterministic engine) Determinism is gauranteed if playback of recorded inputs is on the same machine with exe compiled using same compiler and machine. Additionally my server.exe and client.exe gameloop is single thread with blocking socket calls and fixed time step. Question: Can anyone explain what I did wrong to get different Box2D output?

    Read the article

  • Template syntax for users - is there a right way to do it?

    - by RickM
    Ok, I'm in the middle of building a saas system, and as part of that, the hosted clients need to be able to edit certain layout templates, baqsically just html, css and javascript files. I'm obviously going to be wanting to use a template syntax here as it would be dumb to let people execute PHP code, so in this instance template syntax does need to be used. I know that in the grand scale of things, this is a very minor thing, but what template syntax do you use, and why? Is there one that's considered better than others? I've seen all sorts being used with no real consistency, for example: Smarty Style: {$someVar} {foreach from="foo" item="bar"} {$bar.food} {/foreach} ASP Style: {% someVar %} {% foreach foo as bar %} {% bar.food %} {% endforeach %} HTML Style: <someVar> <foreach from="foo" item="bar"> <bar:food> </foreach> PyroCMS/FuelPHP "LEX" Style: {{ someVar }} {{ foreach from="foo" item="bar" }} {{ bar:food }} {{ endforeach }} Obviously these arent 100% accurate (for example, LEX is used alongside PHP for loops), and are only to give you an example of what I mean. What, in your opinion would be the best one (if any) to go with. I ask this bearing in mind that people using this are likely to be novice users. I did look around at a bunch of hosted CMS and E-Commerce systems as these seem to make use of user-editable templates, and most seem to be using some form of their own syntax. I should note that whatever style I end up going with, it will be with a custom template handler due to the complexity of the system and how template files are stored. Plus I'd not want to touch the likes of Smarty with a barge pole!

    Read the article

  • Writing xml with powershell

    - by alex
    i have a script that get all the info i need about my SharePoint farm : [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null $farm = [Microsoft.SharePoint.Administration.SPFarm]::Local $websvcs = $farm.Services | where -FilterScript {$_.GetType() -eq [Microsoft.SharePoint.Administration.SPWebService]} $webapps = @() foreach ($websvc in $websvcs) { write-output "Web Applications" write-output "" foreach ($webapp in $websvc.WebApplications) { write-output "Webapp Name -->"$webapp.Name write-output "" write-output "Site Collections" write-output "" foreach ($site in $webapp.Sites) { write-output "Site URL --> -->" $site.URL write-output "" write-output "Websites" write-output "" foreach ($web in $site.AllWebs) { write-output "Web URL --> --> -->" $web.URL write-output "" write-output "Lists" write-output "" foreach ($list in $web.Lists) { write-output "List Title --> --> --> -->" $list.Title write-output "" } foreach ($group in $web.Groups) { write-output "Group Name --> --> --> -->" $group.Name write-output "" foreach ($user in $group.Users) { write-output "User Name --> --> --> -->" $user.Name write-output "" } } } } } } i want to make the output to an XML file and then connect the xml file to HTML and make a site of it for manager use how can i do it ? thanks for the help !

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >