Search Results

Search found 15634 results on 626 pages for 'foreach loop container'.

Page 3/626 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Changing a Container while using Visitor

    - by Florian
    Hi everyone, I implemented the Visitor pattern in C++ using a STL-like iterator for storing the Visitor's current position in the container. Now I would like to change the container while I iterate over it, and I'm especially interested in deleting items from the container, even the one I'm currently visiting. Now obviously this will invalidate the Visitors internal iterator, because it was pointing to exactly this item. Currently, I store a list of all iterators in the container and update them, as soon as anything is added to or removed from the list. So in a way this is similar to the Observer pattern applied to the iterator (as Observer) and the list (as Observable). Alternatively I considered having the visitor() methods return some hint to the Visitor about what happend to the current item and how to proceed iterating, but that doesn't sound like such a good idea either, because the visit() implementation shouldn't really care about finding the next item. So, my question is: What's the best way to keep a visitor working, even when items are added to the container or removed from it. Regards, Florian

    Read the article

  • [Android] For-Loop Performance Oddity

    - by Jack Holt
    I just noticed something concerning for-loop performance that seems to fly in the face of the recommendations given by the Google Android team. Look at the following code: package com.jackcholt; import android.app.Activity; import android.os.Bundle; import android.util.Log; public class Main extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); loopTest(); finish(); } private void loopTest() { final long loopCount = 1228800; final int[] image = new int[8 * 320 * 480]; long start = System.currentTimeMillis(); for (int i = 0; i < (8 * 320 * 480); i++) { image[i] = i; } for (int i = 0; i < (8 * 320 * 480); i++) { image[i] = i; } Log.i("loopTest", "Elapsed time (recompute loop limit): " + (System.currentTimeMillis() - start)); start = System.currentTimeMillis(); for (int i = 0; i < 1228800; i++) { image[i] = i; } for (int i = 0; i < 1228800; i++) { image[i] = i; } Log.i("loopTest", "Elapsed time (literal loop limit): " + (System.currentTimeMillis() - start)); start = System.currentTimeMillis(); for (int i = 0; i < loopCount; i++) { image[i] = i; } for (int i = 0; i < loopCount; i++) { image[i] = i; } Log.i("loopTest", "Elapsed time (precompute loop limit): " + (System.currentTimeMillis() - start)); } } When I run this code I get the following output in logcat: I/loopTest( 726): Elapsed time (recompute loop limit): 759 I/loopTest( 726): Elapsed time (literal loop limit): 755 I/loopTest( 726): Elapsed time (precompute loop limit): 1317 As you can see the code that seems to recompute the loop limit value on every iteration of the loop compares very well to the code that uses a literal value for the loop limit. However, the code that uses a variable which contains the precomputed value for the loop limit is significantly slower than either of the others. I'm not surprised that accessing a variable should be slower that using a literal but why does code that looks like it should be using two multiply instructions on every iteration of the loop so comparable in performance to a literal? Could it be that because literals are the only thing being multiplied, the Java compiler is optimizing out the multiplication and using a precomputed literal?

    Read the article

  • How do I create a loop based off this array?

    - by dmanexe
    I'm trying to process this array, first testing for the presence of a check, then extrapolating the data from quantity to return a valid price. Here's the input for fixed amounts of items, with no variable quantity. <input type="checkbox" name="measure[<?=$item->id?>][checked]" value="<?=$item->id?>"> <input type="hidden" name="measure[<?=$item->id?>][quantity]" value="1" /> Here's the inputs for variable amounts of items. <input type="checkbox" name="measure[<?=$item->id?>][checked]" value="<?=$item->id?>"> <input class="item_mult" value="0" type="text" name="measure[<?=$item->id?>][quantity]" /> So, the resulting array is multidimensional. Here's an output: Array ( [1] => Array ( [quantity] => 1 ) [2] => Array ( [quantity] => 1 ) [3] => Array ( [quantity] => 1 ) ... [14] => Array ( [checked] => 14 [quantity] => 999 ) ) Here's the loop I'm using to take this array and process items checked off the form in the first place. I guess the question essentially boils down to how do I structure my conditional statement to incorporate the multi-dimensional array? foreach($field as $value): if ($value['checked'] == TRUE) { $query = $this->db->get_where('items', array('id' => $value['checked']))->row(); #Test to see if quantity input is present if ($value['quantity'] == TRUE) { $newprice = $value['quantity'] * $query->price; $totals[] = $newprice; } #Just return the base value if not else { $newprice = $query->price; $totals[] = $newprice; } } else { } ?> <p><?=$query->name?> - <?=money_format('%(#10n', $newprice)?></p> <? endforeach; ?>

    Read the article

  • php foreach loop help

    - by sico87
    I am working with a PHP foreach loop and I am needing it to out some specific HTML depening on which array value it is spitting out. Everytime that the foreach loop hits a $content['contentTitle'] i need it to insert a new table and then from there carry on essentially what I am what is for the loop to spit out a new table every a new contentTitle is found, but then add the rest of the data in the array as tr and td's

    Read the article

  • php if clause inside foreach not retrieving data correctly

    - by Mike
    Here's my issue: In my controller, I want to grab user input from a form. I then parse the input, and compare it to database values to ensure I'm grabbing the correct input. I simply want to match the user's answers to the question, grab the user ID, the question ID, and then determine if the answer applies to a multiple choice or checkbox question, or something else. I take those values and insert them into the answer table. Ignore the waiver stuff. I'll test that once I get the answers input correctly. // add answers and waiver consent records try { $answerArray = array(); $waiverArray = array(); // retrieve answers, waiver consents, and the question ID's from form object foreach ($formData as $key => $value) { $parts = explode("_", $key); if ($parts[0] == 'question') { array_push($answerArray, $value); } if ($parts[0] == 'waiverTitle') { array_push($waiverArray, $value); } } $questions = new Model_DbTable_Questions(); $questionResults = $questions->getQuestionResults($session->idEvent); foreach ( $questionResults as $qr ) { if ($qr ['questionType'] == 'multipleChoice' || $qr ['questionType'] == 'checkBox') { foreach ( $answerArray as $aa ) { $answerData = $answers->addAnswer ( $lastUserID, $qr ['idQuestion'], null, $aa ); echo count ( $answerData ) . ', ' . $qr ['questionType'] . ', ' . $aa . '<br />'; } } else { foreach ( $answerArray as $aa ) { $answerData = $answers->addAnswer ( $lastUserID, $qr ['idQuestion'], $aa, null ); echo count ( $answerData ) . ', ' . $qr ['questionType'] . ', ' . $aa . '<br />'; } } } } catch (Zend_Db_Statement_Exception $e) { $e->getMessage(); throw $e; } From my test data, I expect to get 2 records that match the multiple choice and checkbox criteria, and 1 record for text in the ELSE clause like this: 3, checkbox, 1 3, multipleChoice, 1 3, text, question_2 What I get is a 3x3 Cartesian product, 3 question elements each with the 3 possible answers like this output from the echo statements: 4, checkBox, 1 4, checkBox, 1 4, checkBox, question_2 4, multipleChoice, 1 4, multipleChoice, 1 4, multipleChoice, question_2 4, text, 1 4, text, 1 4, text, question_2 I've tried placing the IF clause inside the inner foreach, but I get the same results. I've been staring at this problem for way too long and cannot see what I'm doing wrong. Your kind assistance would be greatly appreciated. Please let me know if my request requires more clarification.

    Read the article

  • zend_form display group inside foreach

    - by Mike
    I want to create a display group generated from foreach() clause output. I can't seem to get the syntax correct. Here's the business logic: for each category row find the associated fees output the category description as a label and the fees as radio buttons then create a display group with the fees as the group elements and the category description as the legend. I then have a style sheet format the elements on the page. and here's the code: foreach ($categoryData as $categoryRow) { $fees[$i] = new Zend_Form_Element_Radio("fees[$i]"); $fees[$i]->setDescription(strval($categoryRow['description'])); foreach ($feeData as $feeRow) { if ($feeRow['categories_idCategory'] == $categoryRow['idCategory']){ $fees[$i] ->addMultiOption($feeRow['idFees'] . '-' . $feeRow['categories_idCategory'], $feeRow['amount'] . '-' . $feeRow['name']); } } $fees[$i]->setRequired(TRUE); $this->addElements(array($fees[$i])); $this->addDisplayGroup($feeRow['name'], 'feeGroup',array('legend' => strval($feeRow['description']))); $i++; } I tried placing the addDisplayGroup() code within the foreach(), but I get the error: Message: No valid elements specified for display group So, my guess is that I'm making some kind of novice mistake that you experts will spot right away. I appreciate your time and attention to this matter.

    Read the article

  • How to iterate over an array of objects without foreach and ArrayAccess

    - by kenny99
    Hi, I'm having to develop a site on PHP 5.1.6 and I've just come across a bug in my site which isn't happening on 5.2+. When using foreach() to iterate over an object, I get the following error: "Fatal error: Objects used as arrays in post/pre increment/decrement must return values by reference..." Does anyone know how to convert the following foreach loop to a construct which will work with 5.1.6? Thanks in advance! foreach ($post['commercial_brands'] as $brand) { $comm_food = new Commercial_food_Model; $comm_food->brand = $brand; $comm_food->feeding_type_id = $f_type->id; $comm_food->save(); }

    Read the article

  • Passing in a value to a usercontrol through a foreach loop

    - by LooDaFunk
    in my asp.net mark up I have a foreach loop that iterates through a simple list. In this foreach loop I am adding a new user control and attempting to pass in the value from the loop. However, this value just wont budge and get inside that damn control! Anyone have any suggestions? <%foreach (userInfo i in this.items) { %> <uc1:ItemControl ID="ItemControl" runat="server" UserID='<%#Eval("userID") %>'/> <%} %> userID is a public property in the control, when it goes to set, the value is just literally : <%#Eval("userID") %. I've tried #Bind and =Value but nothing seems to work. Any help would be appreciated!

    Read the article

  • h:graphicimage not working in c:foreach

    - by Muneeswaran Balasubramanian
    I have used c:forEach loop for display the list of images using h:graphicImage. But I can't display the images. I have the h:commandLink also in my page. The image have to be displayed at the time of form inititalization. But its not working. But after click the h:commandlink, the images are displayed properly. Before that it shows the image not found text (alt message). I have used h:graphicImage tag like below <c:forEach items="#{Sample.imageList}" var="images" varstatus="imageStatus"> <h:graphicimage id="image" url="#{images}" alt="Image Not Found"/> </c:forEach> What I do wrong in that and how can I achieve that?

    Read the article

  • Two foreach loops, ideea for my code please

    - by webmasters
    Please give me an ideea for my code, its a simple links script. TY I need two foreach loops, one which loops my sites and one which loops my anchors. So i'll have <li>link to site1 and anchor to site1</li> <li>link to site2 and anchor to site2</li> <li>link to site3 and anchor to site3</li> $currentsite = ''.bloginfo('wpurl').''; $mysites = array('http://site1.com', 'http://site2.com', 'http://site3.com'); $myanchors = array('anchor1','anchor2','anchor3'); foreach($mysites as $mysite) ****** i need a foreach loop for the anchors array ******* { if ( $mysite !== $currentsite ){echo '<li><a href="'.$mysite.'" title="'.$myanchor.'">'.$myanchor.'</a></li>';} }

    Read the article

  • vertical accordion from horizontal

    - by Sify Juhy
    //# jQuery - Horizontal Accordion //# Version 2.00.00 Alpha 1 //# //# portalZINE(R) - New Media Network //# http://www.portalzine.de //# //# Alexander Graef //# [email protected] //# //# Copyright 2007-2009 (function($) { $.hrzAccordion = { setOnEvent: function(i, container, finalWidth, settings){ $("#"+container+"Handle"+i).bind(settings.eventTrigger,function() { var status = $('[rel='+container+'ContainerSelected]').data('status'); if(status ==1 && settings.eventWaitForAnim === true){ return false; } if( $("#"+container+"Handle"+i).attr("rel") != container+"HandleSelected"){ settings.eventAction; $('[id*='+container+'Handle]').attr("rel",""); $('[id*='+container+'Handle]').attr("class",settings.handleClass); $("#"+container+"Handle"+i).addClass(settings.handleClassSelected); $("."+settings.contentWrapper).css({width: finalWidth+"px" }); switch(settings.closeOpenAnimation) { case 1: if($('[rel='+container+'ContainerSelected]').get(0) ){ $('[rel='+container+'ContainerSelected]').data('status',1); //current_width = $('[rel='+container+'ContainerSelected]').width(); $('[rel='+container+'ContainerSelected]').animate({width: "0px",opacity:"0"}, { queue:true, duration:settings.closeSpeed ,easing:settings.closeEaseAction,complete: function(){ $('[rel='+container+'ContainerSelected]').data('status',0); } ,step: function(now){ width = $(this).width(); //new_width = finalWidth- (finalWidth * (width/current_width)); new_width = finalWidth - width; $('#'+container+'Content'+i).width(Math.ceil(new_width)).css("opacity","1"); }}); }else{ $('[rel='+container+'ContainerSelected]').data('status',1); $('#'+container+'Content'+i).animate({width: finalWidth,opacity:"1"}, { queue:false, duration:settings.closeSpeed ,easing:settings.closeEaseAction,complete: function(){ $('[rel='+container+'ContainerSelected]').data('status',0); }}); } break; case 2: $('[id*='+container+'Content]').css({width: "0px"}); $('#'+container+'Content'+i).animate({width: finalWidth+"px",opacity:"1"}, { queue:false, duration:settings.openSpeed ,easing:settings.openEaseAction, complete: settings.completeAction }); break; } $('[id*='+container+'Content]').attr("rel",""); $("#"+container+"Handle"+i).attr("rel",container+"HandleSelected"); $("#"+container+"Content"+i).attr("rel",container+"ContainerSelected"); } }); } }; $.fn.extend({ hrzAccordionLoop: function(options) { return this.each(function(a){ var container = $(this).attr("id") || $(this).attr("class"); var elementCount = $('#'+container+' > li, .'+container+' > li').size(); var settings = $(this).data('settings'); variable_holder="interval"+container ; var i =0; var loopStatus = "start"; variable_holder = window.setInterval(function(){ $("#"+container+"Handle"+i).trigger(settings.eventTrigger); if(loopStatus =="start"){ i = i + 1; }else{ i = i-1; } if(i==elementCount && loopStatus == "start"){ loopStatus = "end"; i=elementCount-1; } if(i==0 && loopStatus == "end"){ loopStatus = "start"; i=0; } },settings.cycleInterval); }); }, hrzAccordion: function(options) { this.settings = { eventTrigger : "click", containerClass : "container", listItemClass : "listItem", contentContainerClass : "contentContainer", contentWrapper : "contentWrapper", contentInnerWrapper : "contentInnerWrapper", handleClass : "handle", handleClassOver : "handleOver", handleClassSelected : "handleSelected", handlePosition : "right", handlePositionArray : "", // left,left,right,right,right closeEaseAction : "swing", closeSpeed : 500, openEaseAction : "swing", openSpeed : 500, openOnLoad : 2, hashPrefix : "tab", eventAction : function(){ //add your own extra clickAction function here }, completeAction : function(){ //add your own onComplete function here }, closeOpenAnimation : 1,// 1 - open and close at the same time / 2- close all and than open next cycle : false, // not integrated yet, will allow to cycle through tabs by interval cycleInterval : 10000, fixedWidth : "", eventWaitForAnim : true }; if(options){ $.extend(this.settings, options); } var settings = this.settings; return this.each(function(a){ var container = $(this).attr("id") || $(this).attr("class"); $(this).data('settings', settings); $(this).wrap("<div class='"+settings.containerClass+"'></div>"); var elementCount = $('#'+container+' > li, .'+container+' > li').size(); var containerWidth = $("."+settings.containerClass).width(); var handleWidth = $("."+settings.handleClass).css("width"); handleWidth = handleWidth.replace(/px/,""); var finalWidth; var handle; if(settings.fixedWidth){ finalWidth = settings.fixedWidth; }else{ finalWidth = containerWidth-(elementCount*handleWidth)-handleWidth; } $('#'+container+' > li, .'+container+' > li').each(function(i) { $(this).attr('id', container+"ListItem"+i); $(this).attr('class',settings.listItemClass); $(this).html("<div class='"+settings.contentContainerClass+"' id='"+container+"Content"+i+"'>" +"<div class=\""+settings.contentWrapper+"\">" +"<div class=\""+settings.contentInnerWrapper+"\">" +$(this).html() +"</div></div></div>"); if($("div",this).hasClass(settings.handleClass)){ var html = $("div."+settings.handleClass,this).attr("id",""+container+"Handle"+i+"").html(); $("div."+settings.handleClass,this).remove(); handle = "<div class=\""+settings.handleClass+"\" id='"+container+"Handle"+i+"'>"+html+"</div>"; }else{ handle = "<div class=\""+settings.handleClass+"\" id='"+container+"Handle"+i+"'></div>"; } if(settings.handlePositionArray){ splitthis = settings.handlePositionArray.split(","); settings.handlePosition = splitthis[i]; } switch(settings.handlePosition ){ case "left": $(this).prepend( handle ); break; case "right": $(this).append( handle ); break; case "top": $("."+container+"Top").append( handle ); break; case "bottom": $("."+container+"Bottom").append( handle ); break; } $("#"+container+"Handle"+i).bind("mouseover", function(){ $("#"+container+"Handle"+i).addClass(settings.handleClassOver); }); $("#"+container+"Handle"+i).bind("mouseout", function(){ if( $("#"+container+"Handle"+i).attr("rel") != "selected"){ $("#"+container+"Handle"+i).removeClass(settings.handleClassOver); } }); $.hrzAccordion.setOnEvent(i, container, finalWidth, settings); if(i == elementCount-1){ $('#'+container+",."+container).show(); } if(settings.openOnLoad !== false && i == elementCount-1){ var location_hash = location.hash; location_hash = location_hash.replace("#", ""); if(location_hash.search(settings.hashPrefix) != '-1' ){ var tab = 1; location_hash = location_hash.replace(settings.hashPrefix, ""); } if(location_hash && tab ==1){ $("#"+container+"Handle"+(location_hash)).attr("rel",container+"HandleSelected"); $("#"+container+"Content"+(location_hash)).attr("rel",container+"ContainerSelected"); $("#"+container+"Handle"+(location_hash-1)).trigger(settings.eventTrigger); }else{ $("#"+container+"Handle"+(settings.openOnLoad)).attr("rel",container+"HandleSelected"); $("#"+container+"Content"+(settings.openOnLoad)).attr("rel",container+"ContainerSelected"); $("#"+container+"Handle"+(settings.openOnLoad-1)).trigger(settings.eventTrigger); } } }); if(settings.cycle === true){ $(this).hrzAccordionLoop(); } }); } }); })(jQuery); **Given is the code used for the accordion...please check out this Accordion Link. in the link there are four examples of accordions. i want the last accordion i.e example 4 to be vertical ...kindly help me.

    Read the article

  • How to get child container reference in View Model

    - by niels-verkaart
    Hello, I´m trying to share a Data Service (Entity Manager) wrapped in a Repository from a ViewModel (called 'AVM') in Module A to a ViewModel (called 'BVM') in Module B, and I can't get this working. We use PRISM/Unity 2.0 This is my scenario: A user may open multiple Customer screens (composite view as mini shell) each with another customer (unit of work). We realize this using child containers. Each child container resolves it's own repository with its own Entity manager (the repository is a singleton within the child container). This is done in module A. The main shell has a main region manager, and each Customer screen with its childcontainer creates a scoped region. In each customer screen there is a View 'AV' (connected to ViewModel 'AVM') with a SubRegion (tab control) registered as 'SubRegion'. We create this with a 'Screen Factory' In Module B we have a Customer Orders in View 'BV' and ViewModel 'BVM'. In the constructor of Module B we get the main container by injection. In the initialize method we resolve the (main) region manager and register View 'BV' with it. In the constructor of View 'BV' a ViewModel 'BVM' is injected/created. Now this works, but the ViewModel 'BVM' cannot get the child container. It only get the main container. Is this doable, or do I have to do this another way? Thanks, Niels

    Read the article

  • Moving inserted container element if possible

    - by doublep
    I'm trying to achieve the following optimization in my container library: when inserting an lvalue-referenced element, copy it to internal storage; but when inserting rvalue-referenced element, move it if supported. The optimization is supposed to be useful e.g. if contained element type is something like std::vector, where moving if possible would give substantial speedup. However, so far I was unable to devise any working scheme for this. My container is quite complicated, so I can't just duplicate insert() code several times: it is large. I want to keep all "real" code in some inner helper, say do_insert() (may be templated) and various insert()-like functions would just call that with different arguments. My best bet code for this (a prototype, of course, without doing anything real): #include <iostream> #include <utility> struct element { element () { }; element (element&&) { std::cerr << "moving\n"; } }; struct container { void insert (const element& value) { do_insert (value); } void insert (element&& value) { do_insert (std::move (value)); } private: template <typename Arg> void do_insert (Arg arg) { element x (arg); } }; int main () { { // Shouldn't move. container c; element x; c.insert (x); } { // Should move. container c; c.insert (element ()); } } However, this doesn't work at least with GCC 4.4 and 4.5: it never prints "moving" on stderr. Or is what I want impossible to achieve and that's why emplace()-like functions exist in the first place?

    Read the article

  • WPF TreeView MouseDown

    - by imekon
    I've got something like this in a TreeView: <DataTemplate x:Key="myTemplate"> <StackPanel MouseDown="OnItemMouseDown"> ... </StackPanel> </DataTemplate> Using this I get the mouse down events if I click on items in the stack panel. However... there seems to be another item behind the stack panel that is the TreeViewItem - it's very hard to hit, but not impossible, and that's when the problems start to occur. I had a go at handling PreviewMouseDown on TreeViewItem, however that seems to require e.Handled = false otherwise standard tree view behaviour stops working. Ok, Here's the source code... MainWindow.xaml <Window x:Class="WPFMultiSelectTree.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WPFMultiSelectTree" Title="Multiple Selection Tree" Height="300" Width="300"> <Window.Resources> <!-- Declare the classes that convert bool to Visibility --> <local:VisibilityConverter x:Key="visibilityConverter"/> <local:VisibilityInverter x:Key="visibilityInverter"/> <!-- Set the style for any tree view item --> <Style TargetType="TreeViewItem"> <Style.Triggers> <DataTrigger Binding="{Binding Selected}" Value="True"> <Setter Property="Background" Value="DarkBlue"/> <Setter Property="Foreground" Value="White"/> </DataTrigger> </Style.Triggers> <EventSetter Event="PreviewMouseDown" Handler="OnTreePreviewMouseDown"/> </Style> <!-- Declare a hierarchical data template for the tree view items --> <HierarchicalDataTemplate x:Key="RecursiveTemplate" ItemsSource="{Binding Children}"> <StackPanel Margin="2" Orientation="Horizontal" MouseDown="OnTreeMouseDown"> <Ellipse Width="12" Height="12" Fill="Green"/> <TextBlock Margin="2" Text="{Binding Name}" Visibility="{Binding Editing, Converter={StaticResource visibilityInverter}}"/> <TextBox Margin="2" Text="{Binding Name}" KeyDown="OnTextBoxKeyDown" IsVisibleChanged="OnTextBoxIsVisibleChanged" Visibility="{Binding Editing, Converter={StaticResource visibilityConverter}}"/> <TextBlock Margin="2" Text="{Binding Index, StringFormat=({0})}"/> </StackPanel> </HierarchicalDataTemplate> <!-- Declare a simple template for a list box --> <DataTemplate x:Key="ListTemplate"> <TextBlock Text="{Binding Name}"/> </DataTemplate> </Window.Resources> <Grid> <!-- Declare the rows in this grid --> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition/> <RowDefinition Height="Auto"/> <RowDefinition/> </Grid.RowDefinitions> <!-- The first header --> <TextBlock Grid.Row="0" Margin="5" Background="PowderBlue">Multiple selection tree view</TextBlock> <!-- The tree view --> <TreeView Name="m_tree" Margin="2" Grid.Row="1" ItemsSource="{Binding Children}" ItemTemplate="{StaticResource RecursiveTemplate}"/> <!-- The second header --> <TextBlock Grid.Row="2" Margin="5" Background="PowderBlue">The currently selected items in the tree</TextBlock> <!-- The list box --> <ListBox Name="m_list" Margin="2" Grid.Row="3" ItemsSource="{Binding .}" ItemTemplate="{StaticResource ListTemplate}"/> </Grid> </Window> MainWindow.xaml.cs /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private Container m_root; private Container m_first; private ObservableCollection<Container> m_selection; private string m_current; /// <summary> /// Constructor /// </summary> public MainWindow() { InitializeComponent(); m_selection = new ObservableCollection<Container>(); m_root = new Container("root"); for (int parents = 0; parents < 50; parents++) { Container parent = new Container(String.Format("parent{0}", parents + 1)); for (int children = 0; children < 1000; children++) { parent.Add(new Container(String.Format("child{0}", children + 1))); } m_root.Add(parent); } m_tree.DataContext = m_root; m_list.DataContext = m_selection; m_first = null; } /// <summary> /// Has the shift key been pressed? /// </summary> private bool ShiftPressed { get { return Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift); } } /// <summary> /// Has the control key been pressed? /// </summary> private bool CtrlPressed { get { return Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl); } } /// <summary> /// Clear down the selection list /// </summary> private void DeselectAndClear() { foreach(Container container in m_selection) { container.Selected = false; } m_selection.Clear(); } /// <summary> /// Add the container to the list (if not already present), /// mark as selected /// </summary> /// <param name="container"></param> private void AddToSelection(Container container) { if (container == null) { return; } foreach (Container child in m_selection) { if (child == container) { return; } } container.Selected = true; m_selection.Add(container); } /// <summary> /// Remove container from list, mark as not selected /// </summary> /// <param name="container"></param> private void RemoveFromSelection(Container container) { m_selection.Remove(container); container.Selected = false; } /// <summary> /// Process single click on a tree item /// /// Normally just select an item /// /// SHIFT-Click extends selection /// CTRL-Click toggles a selection /// </summary> /// <param name="sender"></param> private void OnTreeSingleClick(object sender) { FrameworkElement element = sender as FrameworkElement; if (element != null) { Container container = element.DataContext as Container; if (container != null) { if (CtrlPressed) { if (container.Selected) { RemoveFromSelection(container); } else { AddToSelection(container); } } else if (ShiftPressed) { if (container.Parent == m_first.Parent) { if (container.Index < m_first.Index) { Container item = container; for (int i = container.Index; i < m_first.Index; i++) { AddToSelection(item); item = item.Next; if (item == null) { break; } } } else if (container.Index > m_first.Index) { Container item = m_first; for (int i = m_first.Index; i <= container.Index; i++) { AddToSelection(item); item = item.Next; if (item == null) { break; } } } } } else { DeselectAndClear(); m_first = container; AddToSelection(container); } } } } /// <summary> /// Process double click on tree item /// </summary> /// <param name="sender"></param> private void OnTreeDoubleClick(object sender) { FrameworkElement element = sender as FrameworkElement; if (element != null) { Container container = element.DataContext as Container; if (container != null) { container.Editing = true; m_current = container.Name; } } } /// <summary> /// Clicked on the stack panel in the tree view /// /// Double left click: /// /// Switch to editing mode (flips visibility of textblock and textbox) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnTreeMouseDown(object sender, MouseButtonEventArgs e) { Debug.WriteLine("StackPanel mouse down"); switch(e.ChangedButton) { case MouseButton.Left: switch (e.ClickCount) { case 2: OnTreeDoubleClick(sender); e.Handled = true; break; } break; } } /// <summary> /// Clicked on tree view item in tree /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnTreePreviewMouseDown(object sender, MouseButtonEventArgs e) { Debug.WriteLine("TreeViewItem preview mouse down"); switch (e.ChangedButton) { case MouseButton.Left: switch (e.ClickCount) { case 1: { // We've had a single click on a tree view item // Unfortunately this is the WHOLE tree item, including the +/- // symbol to the left. The tree doesn't do a selection, so we // have to filter this out... MouseDevice device = e.Device as MouseDevice; Debug.WriteLine(String.Format("Tree item clicked on: {0}", device.DirectlyOver.GetType().ToString())); // This is bad. The whole point of WPF is for the code // not to know what the UI has - yet here we are testing for // it as a workaround. Sigh... if (device.DirectlyOver.GetType() != typeof(Path)) { OnTreeSingleClick(sender); } // Cannot say handled - if we do it stops the tree working! //e.Handled = true; } break; } break; } } /// <summary> /// Key press in text box /// /// Return key finishes editing /// Escape key finishes editing, restores original value (this doesn't work!) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnTextBoxKeyDown(object sender, KeyEventArgs e) { switch(e.Key) { case Key.Return: { TextBox box = sender as TextBox; if (box != null) { Container container = box.DataContext as Container; if (container != null) { container.Editing = false; e.Handled = true; } } } break; case Key.Escape: { TextBox box = sender as TextBox; if (box != null) { Container container = box.DataContext as Container; if (container != null) { container.Editing = false; container.Name = m_current; e.Handled = true; } } } break; } } /// <summary> /// When text box becomes visible, grab focus and select all text in it. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnTextBoxIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { bool visible = (bool)e.NewValue; if (visible) { TextBox box = sender as TextBox; if (box != null) { box.Focus(); box.SelectAll(); } } } } Here's the Container class public class Container : INotifyPropertyChanged { private string m_name; private ObservableCollection<Container> m_children; private Container m_parent; private bool m_selected; private bool m_editing; /// <summary> /// Constructor /// </summary> /// <param name="name">name of object</param> public Container(string name) { m_name = name; m_children = new ObservableCollection<Container>(); m_parent = null; m_selected = false; m_editing = false; } /// <summary> /// Name of object /// </summary> public string Name { get { return m_name; } set { if (m_name != value) { m_name = value; OnPropertyChanged("Name"); } } } /// <summary> /// Index of object in parent's children /// /// If there's no parent, the index is -1 /// </summary> public int Index { get { if (m_parent != null) { return m_parent.Children.IndexOf(this); } return -1; } } /// <summary> /// Get the next item, assuming this is parented /// /// Returns null if end of list reached, or no parent /// </summary> public Container Next { get { if (m_parent != null) { int index = Index + 1; if (index < m_parent.Children.Count) { return m_parent.Children[index]; } } return null; } } /// <summary> /// List of children /// </summary> public ObservableCollection<Container> Children { get { return m_children; } } /// <summary> /// Selected status /// </summary> public bool Selected { get { return m_selected; } set { if (m_selected != value) { m_selected = value; OnPropertyChanged("Selected"); } } } /// <summary> /// Editing status /// </summary> public bool Editing { get { return m_editing; } set { if (m_editing != value) { m_editing = value; OnPropertyChanged("Editing"); } } } /// <summary> /// Parent of this object /// </summary> public Container Parent { get { return m_parent; } set { m_parent = value; } } /// <summary> /// WPF Property Changed event /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Handler to inform WPF that a property has changed /// </summary> /// <param name="name"></param> private void OnPropertyChanged(string name) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(name)); } } /// <summary> /// Add a child to this container /// </summary> /// <param name="child"></param> public void Add(Container child) { m_children.Add(child); child.m_parent = this; } /// <summary> /// Remove a child from this container /// </summary> /// <param name="child"></param> public void Remove(Container child) { m_children.Remove(child); child.m_parent = null; } } The two classes VisibilityConverter and VisibilityInverter are implementations of IValueConverter that translates bool to Visibility. They make sure the TextBlock is displayed when not editing, and the TextBox is displayed when editing.

    Read the article

  • Computer still in boot loop

    - by user2856410
    My computer is in a boot loop and despite all my efforts, I haven't been able to load windows XP with it. When the computer loads, I see some white loading bar at the bottom, then the windows XP loading screen, then the DELL boot screen, then windows XP loading screen, and it just keeps looping. The blue screen error is: UNMOUNTABLE_BOOT_VOLUME Stop: 0x000000ED (0x823D6C08, 0xC000009C, 0x000000000, 0x000000000) I have booted using Hiren's mini XP, and ran CHKDSK /f /r, but it didn't affect the boot loop. Is there anything else I can try to get my computer to start up? I don't have my windows XP disc, but I have a dvd burner on another computer, and can burn a downloaded ISO if it could help me get out of this loop. Thanks!

    Read the article

  • LINQ/C#: Where & Foreach using index in a list/array

    - by Andrew White
    Hi, I have a list/array and need to process certain elements, but also need the index of the element in the processing. Example: List Names = john, mary, john, bob, simon Names.Where(s = s != "mary").Foreach(MyObject.setInfo(s.index, "blah") But cannot use the "index" property with lists, inversely if the names were in an Array I cannot use Foreach... Any suggestions?

    Read the article

  • need to store values from foreach loop into array

    - by Brad
    Need to store values from foreach loop into an array, need help doing that. Code below does not work, only stores the last value, tried $items .= ..., but that is not doing the trick either, any help will be appreciated. <?php foreach($group_membership as $i => $username) { $items = array($username); } print_r($items); ?>

    Read the article

  • c# string.replace in foreach loop

    - by paradox
    Somehow I can't seem to get string replacement within a foreach loop in C# to work. My code is as follows : foreach (string s in names) { s.Replace("pdf", "txt"); } Am still quite new to LINQ so pardon me if this sounds amateurish ;)

    Read the article

  • How to loop 3 dimension array using foreach PHP

    - by vzhen
    Below is foreach and the 3 dimension arrays, no problem with the looping but i cannot sepcify which array to echo, they must me the whole arrays like echo $subvalue, any better solutions with looping 3 dimension array? i actually feel weird with this looping. Thanks in adv foreach ($stories as $key => $story){ //echo "<br />"; foreach($story as $subkey => $subvalue){ echo $subvalue."<br />"; foreach($subvalue as $key => $subsubvalue){ echo $subsubvalue."<br />"; } } } Array ( [270] => Array ( [uid] => 36 [user_email] => [email protected] [sid] => 270 [story_name] => Story C [photo_url] => Array ( [0] => story_photos/2012/0322/361332381418153311.jpg [1] => story_photos/2012/0322/361332393792911587.jpg ) [photo_added_date] => Array ( [0] => 1332381418 [1] => 1332393792 ) ) [269] => Array ( [uid] => 36 [user_email] => [email protected] [sid] => 269 [story_name] => Story B [photo_url] => Array ( [0] => story_photos/2012/0322/361332381406580761.jpg ) [photo_added_date] => Array ( [0] => 1332381406 ) ) [268] => Array ( [uid] => 36 [user_email] => [email protected] [sid] => 268 [story_name] => Story A [photo_url] => Array ( [0] => story_photos/2012/0322/361332381393552719.jpg ) [photo_added_date] => Array ( [0] => 1332381393 ) ) )

    Read the article

  • Perl, foreach order

    - by Mike
    Does Perl's foreach loop operator require that the list items be presented in order? For example my @a=(1,2,3); foreach my $item (@a) { print $item; } will always print 1 2 3? I suspect so, but I can't find it documented.

    Read the article

  • PHP Casting as Object type in foreach Loop

    - by Coulton
    Within the following code, $quiz_object->personalities contains an array of Personality() objects. // Loop through each personality that exists for the quiz foreach($quiz_object->personalities AS $existing_personality) { // Show all of the existing personalities echo $existing_personality->GetQuizMakerPersonalityHTML(); } How do I "cast" (I think that's the right word) my variable $existing_personality within the foreach loop as the object type? I wish to do this so that when I type $existing_personality->, I get the list of public functions available for that object type. At the moment, Zend doesn't know that it refers to a Personality object within the loop.

    Read the article

  • Looping through a method without for/foreach/while

    - by RichK
    Is there a way of calling a method/lines of code multiple times not using a for/foreach/while loop? For example, if I were to use to for loop: int numberOfIterations = 6; for(int i = 0; i < numberOfIterations; i++) { DoSomething(); SomeProperty = true; } The lines of code I'm calling don't use 'i' and in my opinion the whole loop declaration hides what I'm trying to do. This is the same for a foreach. I was wondering if there's a looping statement I can use that looks something like: do(6) { DoSomething(); SomeProperty = true; } It's really clear that I just want to execute that code 6 times and there's no noise involving index instantiating and adding 1 to some arbitrary variable. As a learning exercise I have written a static class and method: Do.Multiple(int iterations, Action action) Which works but scores very highly on the pretentious scale and I'm sure my peers wouldn't approve. I'm probably just being picky and a for loop is certainly the most recognisable, but as a learning point I was just wondering if there (cleaner) alternatives. Thanks. (I've had a look at this thread, but it's not quite the same) http://stackoverflow.com/questions/2248985/using-ienumerable-without-foreach-loop

    Read the article

  • need help passing multiple variables from foreach loop to test in switch case statement

    - by Brad
    $list_of_groups = array("FACULTY","STAFF"); foreach ($list_of_groups as $i => $group) { $user_in_group = $adldap->user_ingroup($username,$group); print "<h2>Group: ".$group." user in group? ".$user_in_group."</h2>"; // if 1, means yes } Need to print run the appropriate function based on what returns true. There are user's that are members of both FACULTY and STAFF groups, so I want to check for those users and display the appropriate content for them. So if the user is both faculty and staff, then display this, if they are only of staff, display that, same for faculty, might not make sense, but I will write out some code "in theory" that will help you understand what I am trying to do switch(Get group membership of user) { case "FACULTY": print "Faculty group member"; break; case "STAFF": print "Staff group member"; break; case "FACULTY and STAFF": print "Member of both faculty and staff"; break; } I am unsure on how it will check if they are members of both groups and run that thru the case statement to display the appropriate message. The foreach look currently runs thru every group the user belongs to, prints out the ones from the $list_of_groups and the number 1 to the right of it, signifying they belong to it. The problem I have is trying to use that information to run thru the case statement, I am unsure of how to go about that. This is what it prints out for the user currently passed thru the foreach loop: Group: FACULTY user in group? 1 Group: STAFF user in group? 1 Any help is appreciated.

    Read the article

  • Invalid argument supplied for foreach() using adldap

    - by Brad
    I am using adldap http://adldap.sourceforge.net/ And I am passing the session from page to page, and checking to make sure the username within the session is a member of a certain member group, for this example, it is the STAFF group. <?php ini_set('display_errors',1); error_reporting(E_ALL); require_once('/web/ee_web/include/adLDAP.php'); $adldap = new adLDAP(); session_start(); $group = "STAFF"; //$authUser = $adldap->authenticate($username, $password); $result=$adldap->user_groups($_SESSION['user_session']); foreach($result as $key=>$value) { switch($value) { case $group: print '<h3>'.$group.'</h3>'; break; default: print '<h3>Did not find specific value: '.$value.'</h3>'; } if($value == $group) { print 'for loop broke'; break; } } ?> It gives me the error: Warning: Invalid argument supplied for foreach() on line 15, which is this line of code: foreach($result as $key=$value) { When I uncomment the code $authUser = $adldap-authenticate($username, $password); and enter in the appropriate username and password, it works fine, but I shouldn't have to, since the session is valid, I just want to see if the username stored within the valid_session is apart of the STAFF group. Why would it be giving me that problem?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >