Search Results

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

Page 19/195 | < Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >

  • C# to find JobId, Owner, TotalPages from Printer

    - by tanthiamhuat
    My below code works when the Form loads and I can get a list of Network Printers in listBox1. I am also able to see a specific printer's property name and value in listBox2. private void Form1_Load(object sender, EventArgs e) { foreach (String printer in PrinterSettings.InstalledPrinters) { listBox1.Items.Add(printer.ToString()); } } private void button1_Click(object sender, EventArgs e) { string printerName = "Ricoh-L4-1"; string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printerName); ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); ManagementObjectCollection coll = searcher.Get(); foreach (ManagementObject printer in coll) { foreach (PropertyData property in printer.Properties) { listBox2.Items.Add(string.Format("{0}: {1}", property.Name, property.Value)); } } } But when I try to find JobId, Owner, TotalPages for a particular printer (when I actually send jobs to print to that printer), those values do not display at all. private void button2_Click(object sender, EventArgs e) { listBox2.Items.Clear(); string printerName = "Ricoh-L4-1"; string query = string.Format("SELECT * from Win32_PrintJob WHERE Name LIKE '%{0}'", printerName); ManagementObjectSearcher SearchPrintJobs = new ManagementObjectSearcher(query); ManagementObjectCollection PrntJobCollection = SearchPrintJobs.Get(); foreach (ManagementObject PrntJob in PrntJobCollection) { string m_JobID = PrntJob.Properties["JobId"].Value.ToString(); string m_Owner = PrntJob.Properties["Owner"].Value.ToString(); string m_TotalPages = PrntJob.Properties["TotalPages"].Value.ToString(); listBox2.Items.Add(string.Format("{0}:{1}:{2}", m_JobID,m_Owner,m_TotalPages)); } } Do you have any idea how to get above to work? thanks in advance.

    Read the article

  • Getting the CVE ID Property of an update from WSUS API via Powershell

    - by thebitsandthebytes
    I am writing a script in Powershell to get the update information from each computer and correlate the information with another System which identifies updates by CVE ID. I have discovered that there is a "CVEIDs" property for an update in WSUS, which is documented in MSDN, but I have no idea how to access the property. Retrieving the CVE ID from WSUS is the key to this script, so I am hoping someone out there can help! Here is the property that I am having difficulty accessing: IUpdate2::CveIDs Property - http://msdn.microsoft.com/en-us/library/aa386102(VS.85).aspx According to this, the IUnknown::QueryInterface method is needed to interface IUpdate2 -  "http://msdn.microsoft.com/en-us/library/ee917057(PROT.10).aspx" "An IUpdate instance can be retrieved by calling the IUpdateCollection::Item (opnum 8) (section 3.22.4.1) method.  The client can use the IUnknown::QueryInterface method to then obtain an IUpdate2, IUpdate3, IUpdate4, or IUpdate5 interface. Additionally, if the update is a driver, the client can use the IUnknown::QueryInterface method to obtain an IWindowsDriverUpdate, IWindowsDriverUpdate2, IWindowsDriverUpdate3, IWindowsDriverUpdate4, or IWindowsDriverUpdate5 interface. " Here is a skeleton of my code: [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration") | Out-Null  if (!$wsus)  {  Returns an object that implements IUpdateServer  $wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::GetUpdateServer($server, $false, $port)  }  $computerScope = New-Object Microsoft.UpdateServices.Administration.ComputerTargetScope  $updateScope = New-Object Microsoft.UpdateServices.Administration.UpdateScope  $updateScope.UpdateSources = [Microsoft.UpdateServices.Administration.UpdateSources]::MicrosoftUpdate  $wsusMachines = $wsus.GetComputerTargets($computerScope)  foreach machine in QSUS, write the full domain name $wsusMachines | ForEach-Object {  Write-host $.FullDomainName  $updates = $.GetUpdateInstallationInfoPerUpdate($updateScope)  foreach update for each machine, write the update title, installation state and securitybulletin $updates | ForEach-Object {  $update = $wsus.GetUpdate($.UpdateId) # Returns an object that implements Microsoft.UpdateServices.Administration.IUpdate $updateTitle = $update.Title | Write-Host $updateInstallationState = $.UpdateInstallationState | Write-Host $updateSecurityBulletin = $update.SecurityBulletins | Write-Host  $updateCveIds = $update.CveIDs # ERROR: Property 'CveIDs' belongs to IUpdate2, not IUpdate  }  }

    Read the article

  • Populating JavaScript Array from JSP List

    - by tkeE2036
    Ok so perhaps someone can help me with a problem I'm trying to solve. Essentially I have a JSP page which gets a list of Country objects (from the method referenceData() from a Spring Portlet SimpleFormController, not entirely relevant but just mentioning in case it is). Each Country object has a Set of province objects and each province and country have a name field: public class Country { private String name; private Set<Province> provinces; //Getters and setters } public class Province { private String name; //Getters and setters } Now I have two drop down menus in my JSP for countries and provinces and I want to filter the provinces by country. I've been following this tutorial/guide to make a chain select in JavaScript. Now I need a dynamic way to create the JavaScript array from my content. And before anyone mentions AJAX this is out of the question since our project uses portlets and we'd like to stay away from using frameworks like DWR or creating a servlet. Here is the JavaScript/JSP I have so far but it is not populating the Array with anything: var countries = new Array(); <c:forEach items="${countryList}" var="country" varStatus="status"> countries[status.index] = new Array(); countries[status.index]['country'] = ${country.name}; countries[status.index]['provinces'] = [ <c:forEach items="${country.provinces}" var="province" varStatus="provinceStatus"> '${province.name}' <c:if test="${!provinceStatus.last}"> , </c:if> </c:forEach> ]; </c:forEach> Does anyone know how to create an JavaScript array in JSP in the case above or what the 'best-practice' would be considered in this case? Thanks in advance!

    Read the article

  • Creating nodes porgramatically in Drupal 6

    - by John
    Hey, I have been searching for how to create nodes in Drupal 6. I found some entries here on stackoverflow, but the questions seemed to either be for older versions or the solutions did not work for me. Ok, so here is my current process for trying to create $node = new stdClass(); $node->title = "test title"; $node->body = "test body"; $node->type= "story"; $node->created = time(); $node->changed = $node->created; $node->status = 1; $node->promote = 1; $node->sticky = 0; $node->format = 1; $node->uid = 1; node_save( $node ); When I execute this code, the node is created, but when I got the administration page, it throws the following errors: warning: Invalid argument supplied for foreach() in C:\wamp\www\steelylib\includes\menu.inc on line 258. warning: Invalid argument supplied for foreach() in C:\wamp\www\steelylib\includes\menu.inc on line 258. user warning: Duplicate entry '36' for key 1 query: INSERT INTO node_comment_statistics (nid, last_comment_timestamp, last_comment_name, last_comment_uid, comment_count) VALUES (36, 1269980590, NULL, 1, 0) in C:\wamp\www\steelylib\sites\all\modules\nodecomment\nodecomment.module on line 409. warning: Invalid argument supplied for foreach() in C:\wamp\www\steelylib\includes\menu.inc on line 258. warning: Invalid argument supplied for foreach() in C:\wamp\www\steelylib\includes\menu.inc on line 258. I've looked at different tutorials, and all seem to follow the same process. I'm not sure what I am doing wrong. I am using Drupal 6.15. When I roll back the database (to right before I made the changes) the errors are gone. Any help is appreciated!

    Read the article

  • XML Comparison?

    - by CrazyNick
    I got a books.xml file from http://msdn.microsoft.com/en-us/library/ms762271(VS.85).aspx and just saved it with two different names, removed few lines from the second file and tried to compare the files using the below powershell code: clear-host $xml = New-Object XML $xml = [xml](Get-Content D:\SharePoint\Powershell\Comparator\Comparator_Config.xml) $xml.config.compare | ForEach-Object { $strFile1 = get-Content $.source; $strFile2 = get-Content $.destination; $diff  = Compare-Object $strFile1 $strFile2; $result1 = $diff | where {$.SideIndicator -eq "<=" } | select InputObject; $result2 = $diff | where {$.SideIndicator -eq "=" } | select InputObject; Write-host "nEntries are differ in First web.config filen"; $result1 | ForEach-Object {write-host $.InputObject}; Write-host "nEntries are differ in Second web.config filen" ;$result2 | ForEach-Object {write-host $.InputObject}; $.parameters | ForEach-Object { write-host $.parameter } } and it is working perfectly and giving me the below results: Entries are differ in First web.config file < price36.95< /price < descriptionMicrosoft Visual Studio 7 is explored in depth, looking at how Visual Basic, Visual C++, C#, and ASP+ are integrated into a comprehensive development environment.< /description Entries are differ in Second web.config file < price< /price < description< /description however I wan to know the root node of the above mentioned nodes, is that possible to find? if so, how?

    Read the article

  • Invalid Cast Exception in ASP.NET but not in WinForms

    - by Shadow Scorpion
    I have a problem in this code: public static T[] GetExtras <T>(Type[] Types) { List<T> Res = new List<T>(); foreach (object Current in GetExtras(typeof(T), Types)) { Res.Add((T)Current);//this is the error } return Res.ToArray(); } public static object[] GetExtras(Type ExtraType, Type[] Types) { lock (ExtraType) { if (!ExtraType.IsInterface) return new object[] { }; List<object> Res = new List<object>(); bool found = false; found = (ExtraType == typeof(IExtra)); foreach (Type CurInterFace in ExtraType.GetInterfaces()) { if (found = (CurInterFace == typeof(IExtra))) break; } if (!found) return new object[] { }; foreach (Type CurType in Types) { found = false; if (!CurType.IsClass) continue; foreach (Type CurInterface in CurType.GetInterfaces()) { try { if (found = (CurInterface.FullName == ExtraType.FullName)) break; } catch { } } try { if (found) Res.Add(Activator.CreateInstance(CurType)); } catch { } } return Res.ToArray(); } } When I'm using this code in windows application it works! But I cant use it on ASP page. Why?

    Read the article

  • Which LINQ expression is faster

    - by Vlad Bezden
    Hi All In following code public class Person { public string Name { get; set; } public uint Age { get; set; } public Person(string name, uint age) { Name = name; Age = age; } } void Main() { var data = new List<Person>{ new Person("Bill Gates", 55), new Person("Steve Ballmer", 54), new Person("Steve Jobs", 55), new Person("Scott Gu", 35)}; // 1st approach data.Where (x => x.Age > 40).ToList().ForEach(x => x.Age++); // 2nd approach data.ForEach(x => { if (x.Age > 40) x.Age++; }); data.ForEach(x => Console.WriteLine(x)); } in my understanding 2nd approach should be faster since it iterates through each item once and first approach is running 2 times: Where clause ForEach on subset of items from where clause. However internally it might be that compiler translates 1st approach to the 2nd approach anyway and they will have the same performance. Any suggestions or ideas? I could do profiling like suggested, but I want to understand what is going on compiler level if those to lines of code are the same to the compiler, or compiler will treat it literally. Thanks in advance for your help.

    Read the article

  • Auditing in Entity Framework.

    - by Gabriel Susai
    After going through Entity Framework I have a couple of questions on implementing auditing in Entity Framework. I want to store each column values that is created or updated to a different audit table. Rightnow I am calling SaveChanges(false) to save the records in the DB(still the changes in context is not reset). Then get the added | modified records and loop through the GetObjectStateEntries. But don't know how to get the values of the columns where their values are filled by stored proc. ie, createdate, modifieddate etc. Below is the sample code I am working on it. //Get the changed entires( ie, records) IEnumerable<ObjectStateEntry> changes = context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified); //Iterate each ObjectStateEntry( for each record in the update/modified collection) foreach (ObjectStateEntry entry in changes) { //Iterate the columns in each record and get thier old and new value respectively foreach (var columnName in entry.GetModifiedProperties()) { string oldValue = entry.OriginalValues[columnName].ToString(); string newValue = entry.CurrentValues[columnName].ToString(); //Do Some Auditing by sending entityname, columnname, oldvalue, newvalue } } changes = context.ObjectStateManager.GetObjectStateEntries(EntityState.Added); foreach (ObjectStateEntry entry in changes) { if (entry.IsRelationship) continue; var columnNames = (from p in entry.EntitySet.ElementType.Members select p.Name).ToList(); foreach (var columnName in columnNames) { string newValue = entry.CurrentValues[columnName].ToString(); //Do Some Auditing by sending entityname, columnname, value } }

    Read the article

  • C# iterator is executed twice when composing two IEnumerable methods

    - by achristoph
    I just started learning about C# iterator but got confused with the flow of the program after reading the output of the program. The foreach with uniqueVals seems to be executed twice. My understanding is that the first few lines up to the line before "Nums in Square: 3" should not be there. Can anyone help to explain why this happens? The output is: Unique: 1 Adding to uniqueVals: 1 Unique: 2 Adding to uniqueVals: 2 Unique: 2 Unique: 3 Adding to uniqueVals: 3 Nums in Square: 3 Unique: 1 Adding to uniqueVals: 1 Square: 1 Number returned from Unique: 1 Unique: 2 Adding to uniqueVals: 2 Square: 2 Number returned from Unique: 4 Unique: 2 Unique: 3 Adding to uniqueVals: 3 Square: 3 Number returned from Unique: 9 static class Program { public static IEnumerable<T> Unique<T>(IEnumerable<T> sequence) { Dictionary<T, T> uniqueVals = new Dictionary<T, T>(); foreach (T item in sequence) { Console.WriteLine("Unique: {0}", item); if (!uniqueVals.ContainsKey(item)) { Console.WriteLine("Adding to uniqueVals: {0}", item); uniqueVals.Add(item, item); yield return item; Console.WriteLine("After Unique yield: {0}", item); } } } public static IEnumerable<int> Square(IEnumerable<int> nums) { Console.WriteLine("Nums in Square: {0}", nums.Count()); foreach (int num in nums) { Console.WriteLine("Square: {0}", num); yield return num * num; Console.WriteLine("After Square yield: {0}", num); } } static void Main(string[] args) { var nums = new int[] { 1, 2, 2, 3 }; foreach (int num in Square(Unique(nums))) Console.WriteLine("Number returned from Unique: {0}", num); Console.Read(); } }

    Read the article

  • JSP: Refresh ComboBox options

    - by framara
    Hi, There's a class 'Car' with brand and model as properties. I have a list of items of this class List<Car> myCars. I need to represent in a JSP website 2 ComboBox, one for brand and another for model, that when you select the brand, in the model list only appear the ones from that brand. I don't know how to do this in a dynamic way. Any suggestion where to start? Thanks Update Ok, what I do now is send in the request a list with all the brand names, and a list of the items. The JSP code is like: <select name="manufacturer" id="id_manufacturer" onchange="return getManufacturer();"> <option value=""></option> <c:forEach items="${manufacturers}" var="man"> <option value="${man}" >${man}</option> </c:forEach> </select> <select name="model" id="id_model"> <c:forEach items="${mycars}" var="car"> <c:if test="${car.manufacturer eq man_selected}"> <option value="${car.id}">${car.model}</option> </c:if> </c:forEach> </select> <script> function getManufacturer() { man_selected = document.getElementById('id_manufacturer').value; } </script> How do I do to refresh the 'model' select options according to the selected 'man_selected' ?

    Read the article

  • Set ContentTemplate in CodeBehind: XamlParseException 2260 Error

    - by user362215
    Hi, I'd like to change the ContentTemplate of a ContentPresenter in the CodeBehind file. But if I run the Silverlight 4 application a XamlParseException with the error code 2260 occures. foreach (ContentPresenter item in Headers) { item.ContentTemplate = Parent.UnselectedHeaderTemplate; } if ((index >= 0) && (index < Headers.Count)) { ContentPresenter item0 = (ContentPresenter)Headers[index]; item0.ContentTemplate = Parent.SelectedHeaderTemplate; } If I do only the foreach code without the code in the "if", it works. And if I only do the code in the "if" without the foreach it works too. But togheter (the "if"-code and the foreach-code) it doesn't work. I have no idea why it doesn't work. The two templates look like this: <Setter Property="UnselectedHeaderTemplate"> <Setter.Value> <DataTemplate> <ContentControl Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}" Margin="10,-10" FontSize="72" Foreground="#FF999999" CacheMode="BitmapCache"/> </DataTemplate> </Setter.Value> </Setter> <!-- SelectedHeader template --> <Setter Property="SelectedHeaderTemplate"> <Setter.Value> <DataTemplate> <ContentControl Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}" Margin="10,-10" FontSize="72" Foreground="{TemplateBinding Foreground}" CacheMode="BitmapCache"/> </DataTemplate> </Setter.Value> </Setter> If you have an idea what problem is please tell me.

    Read the article

  • Getting method arguments with Roslyn

    - by Kevin Burton
    I can get a list from the solution of all calls to a particuliar method using the following code: var createCommandList = new List<MethodSymbol>(); INamedTypeSymbol interfaceSymbol = (from p in solution.Projects select p.GetCompilation().GetTypeByMetadataName("BuySeasons.BsiServices.DataResource.IBsiDataConnection")).FirstOrDefault(); foreach (ISymbol symbol in interfaceSymbol.GetMembers("CreateCommand")) { if (symbol.Kind == CommonSymbolKind.Method && symbol is MethodSymbol) { createCommandList.Add(symbol as MethodSymbol); } } foreach (MethodSymbol methodSymbol in createCommandList) { foreach (ReferencedSymbol referenceSymbol in methodSymbol.FindReferences(solution)) { foreach (ReferenceLocation referenceLocation in from l in referenceSymbol.Locations orderby l.Document.FilePath select l) { if (referenceLocation.Location.GetLineSpan(false).StartLinePosition.Line == referenceLocation.Location.GetLineSpan(false).EndLinePosition.Line) { Debug.WriteLine(string.Format("{0} {1} at {2} {3}/{4} - {5}", methodSymbol.Name, "(" + string.Join(",", (from p in methodSymbol.Parameters select p.Type.Name + " " + p.Name).ToArray()) + ")", Path.GetFileName(referenceLocation.Location.GetLineSpan(false).Path), referenceLocation.Location.GetLineSpan(false).StartLinePosition.Line, referenceLocation.Location.GetLineSpan(false).StartLinePosition.Character, referenceLocation.Location.GetLineSpan(false).EndLinePosition.Character)); } else { throw new ApplicationException("Call spans multiple lines"); } } } } But this gives me a list of ReferencedSymbol's. Although this gives me the file and line number that the method is called from I would also like to get the specific arguments that the method is called with. How can I either convert what I have or get the same information with Roslyn? (notice the I first load the solution with the Solution.Load method and then loop through to find out where the method is defined/declared (createCommandList)). Thank you.

    Read the article

  • PHP: SimpleXML and Arrays

    - by acemasta
    When I run this code: foreach($xml->movie as $movie) { if(isset($movie->photos)) { foreach ($movie->photos as $photo) { echo $photo."&nbsp;"; } echo "<hr/>"; } } I get nice output of the actual data, e.g. a row looks like 06397001.jpg 06397002.jpg 06397003.jpg 06397004.jpg 06397005.jpg But when I throw it in an array, it includes all the SimpleXML wrapper tags and the jpgs are not at the root of the array. code: foreach($xml->movie as $movie) { if(isset($movie->photos)) { $photos = array(); foreach ($movie->photos as $photo) { $photos[] = $photo; } } else $photos = ""; var_dump($photos); echo "<hr />"; } e.g. same row looks like array(5) { [0]= object(SimpleXMLElement)#11 (1) { [0]= string(12) "06397001.jpg" } [1]= object(SimpleXMLElement)#12 (1) { [0]= string(12) "06397002.jpg" } [2]= object(SimpleXMLElement)#13 (1) { [0]= string(12) "06397003.jpg" } [3]= object(SimpleXMLElement)#14 (1) { [0]= string(12) "06397004.jpg" } [4]= object(SimpleXMLElement)#15 (1) { [0]= string(12) "06397005.jpg" } } Why is this happening/how can I remove this so I just get an array of the photos at root level like when I echo it? Thanks, sorry for the single line code formatting; was messing up when I tried to paste directly with line breaks.

    Read the article

  • Using PHP as template language

    - by Kunal
    I wrote up this quick class to do templating via PHP -- I was wondering if this is easily exploitable if I were ever to open up templating to users (not the immediate plan, but thinking down the road). class Template { private $allowed_methods = array( 'if', 'switch', 'foreach', 'for', 'while' ); private function secure_code($template_code) { $php_section_pattern = '/\<\?(.*?)\?\>/'; $php_method_pattern = '/([a-zA-Z0-9_]+)[\s]*\(/'; preg_match_all($php_section_pattern, $template_code, $matches); foreach (array_unique($matches[1]) as $index => $code_chunk) { preg_match_all($php_method_pattern, $code_chunk, $sub_matches); $code_allowed = true; foreach ($sub_matches[1] as $method_name) { if (!in_array($method_name, $this->allowed_methods)) { $code_allowed = false; break; } } if (!$code_allowed) { $template_code = str_replace($matches[0][$index], '', $template_code); } } return $template_code; } public function render($template_code, $params) { extract($params); ob_start(); eval('?>'.$this->secure_code($template_code).'<?php '); $result = ob_get_contents(); ob_end_clean(); return $result; } } Example usage: $template_code = '<?= $title ?><? foreach ($photos as $photo): ?><img src="<?= $photo ?>"><? endforeach ?>'; $params = array('title' => 'My Title', 'photos' => array('img1.jpg', 'img2.jpg')); $template = new Template; echo $template->render($template_code, $params); The idea here is that I'd store the templates (PHP code) in the database, and then run it through the class which uses regular expressions to only allow permitted methods (if, for, etc.). Anyone see an obvious way to exploit this and run arbitrary PHP? If so, I'll probably go the more standard route of a templating language such as Smarty...

    Read the article

  • does entity framework or mysql provider swallows timeout exceptions on enumeration of result?!

    - by Freddy Rios
    I'm trying to make sense of a situation I have using entity framework on .net 3.5 sp1 + MySQL 6.1.2.0 as the provider. It involves the following code: Response.Write("Products: " + plist.Count() + "<br />"); var total = 0; foreach (var p in plist) { //... some actions total++; //... other actions } Response.Write("Total Products Checked: " + total + "<br />"); Basically the total products is varying on each run, and it isn't matching the full total in plist. Its varies widely, from ~ 1/5th to half. There isn't any control flow code inside the foreach i.e. no break, continue, try/catch, conditions around total++, anything that could affect the count. As confirmation, there are other totals captured inside the loop related to the actions, and those match the lower and higher total runs. I don't find any reason to the above, other than something in entity framework or the mysql provider that causes it to end the foreach when retrieving an item. The body of the foreach can have some good variation in time, as the actions involve file & network access, my best shot at the time is that when it takes beyond certain threshold there is some type of timeout in the underlying framework/provider and instead of causing an exception it is silently reporting no more items for enumeration. Can anyone give some light in the above scenario and/or confirm if the entity framework/mysql provider has the above behavior?

    Read the article

  • Drupal theme preprocess function - primary links and suckerfish menus

    - by slimcady
    I have a preprocess function that works fine when the menu is single level list. However I would like it to work w/ suckerfish menus. I want to add a class to the top level menu item so that I can style it. This is the code I used for the single level menu: function cti_flex_preprocess_page(&$vars, $hook) { // Make a shortcut for the primary links variables $primary_links = $vars['primary_links']; // Loop thru the menu, adding a new class for CSS selectors $i = 1; foreach ($primary_links as $link => $attributes){ // Append the new class to existing classes for each menu item $class = $attributes['attributes']['class'] . " item-$i"; // Add revised classes back to the primary links temp variable $primary_links[$link]['attributes']['class'] = $class; $link['title'] = '<span class="hide">' . check_plain($link['title']) . '</span>'; $i++; } // end the foreach loop // reset the variable to contain the new markup $vars['primary_links'] = $primary_links; } I've been trying to use the menu_tree() function to no avail, for example: function cti_flex_preprocess_page(&$vars, $hook) { // Make a shortcut for the primary links variables $primary_links = $vars['primary_links']; // Loop thru the menu, adding a new class for CSS selectors $i = 1; foreach ($primary_links as $link => $attributes){ // Append the new class to existing classes for each menu item $class = $attributes['attributes']['class'] . " item-$i"; // Add revised classes back to the primary links temp variable $primary_links[$link]['attributes']['class'] = $class; $link['title'] = '<span class="hide">' . check_plain($link['title']) . '</span>'; $i++; } // end the foreach loop // reset the variable to contain the new markup $vars['primary_links_tree'] = menu_tree(variable_get('menu_primary_links_source', '$primary_links')); } Any ideas would be greatly appreciated.

    Read the article

  • Visitor Pattern can be replaced with Callback functions?

    - by getit
    Is there any significant benefit to using either technique? In case there are variations, the Visitor Pattern I mean is this: http://en.wikipedia.org/wiki/Visitor_pattern And below is an example of using a delegate to achieve the same effect (at least I think it is the same) Say there is a collection of nested elements: Schools contain Departments which contain Students Instead of using the Visitor pattern to perform something on each collection item, why not use a simple callback (Action delegate in C#) Say something like this class Department { List Students; } class School { List Departments; VisitStudents(Action<Student> actionDelegate) { foreach(var dep in this.Departments) { foreach(var stu in dep.Students) { actionDelegate(stu); } } } } School A = new School(); ...//populate collections A.Visit((student)=> { ...Do Something with student... }); *EDIT Example with delegate accepting multiple params Say I wanted to pass both the student and department, I could modify the Action definition like so: Action class School { List Departments; VisitStudents(Action<Student, Department> actionDelegate, Action<Department> d2) { foreach(var dep in this.Departments) { d2(dep); //This performs a different process. //Using Visitor pattern would avoid having to keep adding new delegates. //This looks like the main benefit so far foreach(var stu in dep.Students) { actionDelegate(stu, dep); } } } }

    Read the article

  • How to create a generic method in C# that's all applicable to many types - ints, strings, doubles et

    - by satyajit
    Let's I have a method to remove duplicates in an integer Array public int[] RemoveDuplicates(int[] elems) { HashSet<int> uniques = new HashSet<int>(); foreach (int item in elems) uniques.Add(item); elems = new int[uniques.Count]; int cnt = 0; foreach (var item in uniques) elems[cnt++] = item; return elems; } How can I make this generic such that now it accepts a string array and remove duplicates in it? How about a double array? I know I am probably mixing things here in between primitive and value types. For your reference the following code won't compile public List<T> RemoveDuplicates(List<T> elems) { HashSet<T> uniques = new HashSet<T>(); foreach (var item in elems) uniques.Add(item); elems = new List<T>(); int cnt = 0; foreach (var item in uniques) elems[cnt++] = item; return elems; } The reason is that all generic types should be closed at run time. Thanks for you comments

    Read the article

  • Display two array's in the same table

    - by Naeem Ahmed
    $row = $query->fetchAll(PDO::FETCH_ASSOC); $num_rows = count($row); for ($i = 0; $i < $num_rows; $i++) { $title = htmlspecialchars($row[$i]['title']); $author =htmlspecialchars($row[$i]['author']); $school =htmlspecialchars($row[$i]['school']); $solution = $row[$i]['solution']; $notes = $row[$i]['notes']; $ad = array($title, $price, $author, $school, $contact, $content, $date); $inlcude = array($solutions, $notes); $field = 0; echo "<table border='1'>"; // foreach($inlcude as $in) This failled miserably foreach ($ad as $post) { if ($field < 3) //The first three values are placed in the first row { echo "<td>$post</td>"; } if ($field >= 3) { echo "<tr><td>$post</td><td>$in</td></tr>"; } $field++; } echo '</table>'; } I have two arrays and I would like to display them in different columns in my table. $ad displays perfectly fine but I'm having trouble displaying the contents in $inlcude in the second column. I've tried putting another foreach loop to iterate through contents of the second array but that really screws up my table by placing random values in different places on the table. Besides the foreach loop, I don't know of any other way to iterate through the array. Any suggestions would be appreciated.Thanks!

    Read the article

  • Is there a better loop I could write to reduce database queries?

    - by dmanexe
    Below is some code I've written that is effective, but makes too many database queries. Is there a way I could optimize and reduce the number of queries but have conditional statements still be as effective as below? I pasted the code repeated a few times just for good measure. echo "<h3>Pool Packages</h3>"; echo "<ul>"; foreach ($items as $item): $this->db->where('id', $item['id']); $query = $this->db->get('items')->row(); if ($item['quantity'] > 1 && $item['quantity'] == TRUE && $query->category == "Pool Packages") { $newprice = $item['quantity'] * $query->price; $totals[] = $newprice; } else { $newprice = $query->price; $totals[] = $newprice; } if ($query->category == "Pool Packages") { echo "<li>" . $query->name . " (QTY: " . $item['quantity'] . " x = " . str_ireplace(" ", "", money_format('%(#10n', $newprice)) . ")</li>"; } else { } endforeach; echo "</ul>"; echo "<h3>Water Features</h3>"; echo "<ul>"; foreach ($items as $item): $this->db->where('id', $item['id']); $query = $this->db->get('items')->row(); if ($item['quantity'] > 1 && $item['quantity'] == TRUE && $query->category == "Water Features") { $newprice = $item['quantity'] * $query->price; $totals[] = $newprice; } else { $newprice = $query->price; $totals[] = $newprice; } if ($query->category == "Water Features") { echo "<li>" . $query->name . " (QTY: " . $item['quantity'] . " x = " . str_ireplace(" ", "", money_format('%(#10n', $newprice)) . ")</li>"; } else { } endforeach; echo "</ul>"; echo "<h3>Waterfall Rock Work</h3>"; echo "<ul>"; foreach ($items as $item): $this->db->where('id', $item['id']); $query = $this->db->get('items')->row(); if ($item['quantity'] > 1 && $item['quantity'] == TRUE) { $newprice = $item['quantity'] * $query->price; $totals[] = $newprice; } else { $newprice = $query->price; $totals[] = $newprice; } if ($query->category == "Waterfall Rock Work") { echo "<li>" . $query->name . " (QTY: " . $item['quantity'] . " x = " . str_ireplace(" ", "", money_format('%(#10n', $newprice)) . ")</li>"; } else { } endforeach; echo "</ul>"; echo "<h3>Sheer Descents</h3>"; echo "<ul>"; foreach ($items as $item): $this->db->where('id', $item['id']); $query = $this->db->get('items')->row(); if ($item['quantity'] > 1 && $item['quantity'] == TRUE && $query->category == "Sheer Descents") { $newprice = $item['quantity'] * $query->price; $totals[] = $newprice; } else { $newprice = $query->price; $totals[] = $newprice; } if ($query->category == "Sheer Descents") { echo "<li>" . $query->name . " (QTY: " . $item['quantity'] . " x = " . str_ireplace(" ", "", money_format('%(#10n', $newprice)) . ")</li>"; } else { } endforeach; echo "</ul>"; echo "<h3>Booster Pump</h3>"; echo "<ul>"; foreach ($items as $item): $this->db->where('id', $item['id']); $query = $this->db->get('items')->row(); if ($item['quantity'] > 1 && $item['quantity'] == TRUE && $query->category == "Booster Pump") { $newprice = $item['quantity'] * $query->price; $totals[] = $newprice; } else { $newprice = $query->price; $totals[] = $newprice; } if ($query->category == "Booster Pump") { echo "<li>" . $query->name . " (QTY: " . $item['quantity'] . " x = " . str_ireplace(" ", "", money_format('%(#10n', $newprice)) . ")</li>"; } else { } endforeach; echo "</ul>"; echo "<h3>Pool Concrete Decking</h3>"; echo "<ul>"; foreach ($items as $item): $this->db->where('id', $item['id']); $query = $this->db->get('items')->row(); if ($item['quantity'] > 1 && $item['quantity'] == TRUE && $query->category == "Pool Concrete Decking") { $newprice = $item['quantity'] * $query->price; $totals[] = $newprice; } else { $newprice = $query->price; $totals[] = $newprice; } if ($query->category == "Pool Concrete Decking") { echo "<li>" . $query->name . " (QTY: " . $item['quantity'] . " x = " . str_ireplace(" ", "", money_format('%(#10n', $newprice)) . ")</li>"; } else { } endforeach; echo "</ul>"; echo "<h3>Solar Heating</h3>"; echo "<ul>"; foreach ($items as $item): $this->db->where('id', $item['id']); $query = $this->db->get('items')->row(); if ($item['quantity'] > 1 && $item['quantity'] == TRUE && $query->category == "Solar Heating") { $newprice = $item['quantity'] * $query->price; $totals[] = $newprice; } else { $newprice = $query->price; $totals[] = $newprice; } if ($query->category == "Solar Heating") { echo "<li>" . $query->name . " (QTY: " . $item['quantity'] . " x = " . str_ireplace(" ", "", money_format('%(#10n', $newprice)) . ")</li>"; } else { } endforeach; echo "</ul>"; echo "<h3>Raised Bond Beam</h3>"; echo "<ul>"; foreach ($items as $item): $this->db->where('id', $item['id']); $query = $this->db->get('items')->row(); if ($item['quantity'] > 1 && $item['quantity'] == TRUE && $query->category == "Raised Bond Beam") { $newprice = $item['quantity'] * $query->price; $totals[] = $newprice; } else { $newprice = $query->price; $totals[] = $newprice; } if ($query->category == "Raised Bond Beam") { echo "<li>" . $query->name . " (QTY: " . $item['quantity'] . " x = " . str_ireplace(" ", "", money_format('%(#10n', $newprice)) . ")</li>"; } else { echo "<li>None</li>"; } endforeach; echo "</ul>"; It goes on beyond this to several more categories, but I don't know how to handle looping through this best. Thanks!

    Read the article

  • Enlist a table's columns in other component

    - by bungrudi
    The main goal is to have a dropdown menu where each of its menuItems represents one column of a <rich:extendedDataTable />. Above the table I have this: <rich:dropDownMenu value="Column visibility" submitMode="none" direction="bottom-right"> <c:forEach var="columnConfigVO" items="#{gridConfigurationManager.getColumnConfigs(listId)}"> <rich:menuItem value="columnConfigVO.columnId" /> </c:forEach> </rich:dropDownMenu> And then bellow that I have the usual <rich:extendedDataTable /> with its columns. I register the table columns to gridConfigurationManager component by overriding beforeRenderResponse() in ExtendedDataTable class. The problem is that <c:forEach /> is executing before renderResponse phase, thus gridConfigurationManager.getColumnConfigs(listId) return empty. The question is, how do I register the columns in gridConfigurationManager component before <c:forEach /> start executing? Or, anyone know a different approach to accomplish this? Thanks.

    Read the article

  • Recursive Iterators

    - by soandos
    I am having some trouble making an iterator that can traverse the following type of data structure. I have a class called Expression, which has one data member, a List<object>. This list can have any number of children, and some of those children might be other Expression objects. I want to traverse this structure, and print out every non-list object (but I do want to print out the elements of the list of course), but before entering a list, I want to return "begin nest" and after I just exited a list, I want to return "end nest". I was able to do this if I ignored the class wherever possible, and just had List<object> objects with List<object> items if I wanted a subExpression, but I would rather do away with this, and instead have an Expressions as the sublists (it would make it easier to do operations on the object. I am aware that I could use extension methods on the List<object> but it would not be appropriate (who wants an Evaluate method on their list that takes no arguments?). The code that I used to generate the origonal iterator (that works) is: public IEnumerator GetEnumerator(){ return theIterator(expr).GetEnumerator(); } private IEnumerable theIterator(object root) { if ((root is List<object>)){ yield return " begin nest "; foreach (var item in (List<object>)root){ foreach (var item2 in theIterator(item)){ yield return item2; } } yield return " end nest "; } else yield return root; } A type swap of List<object> for expression did not work, and lead to a stackOverflow error. How should the iterator be implemented? Update: Here is the swapped code: public IEnumerator GetEnumerator() { return this.GetEnumerator(); } private IEnumerable theIterator(object root) { if ((root is Expression)) { yield return " begin nest "; foreach (var item in (Expression)root) { foreach (var item2 in theIterator(item)) yield return item2; } yield return " end nest "; } else yield return root; }

    Read the article

  • html/js: Refresh 'Select' options

    - by framara
    Hi, There's a class 'Car' with brand and model as properties. I have a list of items of this class List<Car> myCars. I need to represent in a JSP website 2 ComboBox, one for brand and another for model, that when you select the brand, in the model list only appear the ones from that brand. I don't know how to do this in a dynamic way. Any suggestion where to start? Thanks Update Ok, what I do now is send in the request a list with all the brand names, and a list of the items. The JSP code is like: <select name="manufacturer" id="id_manufacturer" onchange="return getManufacturer();"> <option value=""></option> <c:forEach items="${manufacturers}" var="man"> <option value="${man}" >${man}</option> </c:forEach> </select> <select name="model" id="id_model"> <c:forEach items="${mycars}" var="car"> <c:if test="${car.manufacturer eq man_selected}"> <option value="${car.id}">${car.model}</option> </c:if> </c:forEach> </select> <script> function getManufacturer() { man_selected = document.getElementById('id_manufacturer').value; } </script> How do I do to refresh the 'model' select options according to the selected 'man_selected' ?

    Read the article

  • Make an abstract class or use a processor?

    - by Tim Murphy
    I'm developing a class to compare two directories and run an action when a directory/file in the source directory does not exist in destination directory. Here is a prototype of the class: public abstract class IdenticalDirectories { private DirectoryInfo _sourceDirectory; private DirectoryInfo _destinationDirectory; protected abstract void DirectoryExists(DirectoryInfo sourceDirectory, DirectoryInfo destinationDirectory); protected abstract void DirectoryDoesNotExist(DirectoryInfo sourceDirectory, DirectoryInfo destinationDirectory); protected abstract void FileExists(DirectoryInfo sourceDirectory, DirectoryInfo destinationDirectory); protected abstract void FileDoesNotExist(DirectoryInfo sourceDirectory, DirectoryInfo destinationDirectory); public IdenticalDirectories(DirectoryInfo sourceDirectory, DirectoryInfo destinationDirectory) { ... } public void Run() { foreach (DirectoryInfo sourceSubDirectory in _sourceDirectory.GetDirectories()) { DirectoryInfo destinationSubDirectory = this.GetDestinationDirectoryInfo(subDirectory); if (destinationSubDirectory.Exists()) { this.DirectoryExists(sourceSubDirectory, destinationSubDirectory); } else { this.DirectoryDoesNotExist(sourceSubDirectory, destinationSubDirectory); } foreach (FileInfo sourceFile in sourceSubDirectory.GetFiles()) { FileInfo destinationFile = this.GetDestinationFileInfo(sourceFile); if (destinationFile.Exists()) { this.FileExists(sourceFile, destinationFile); } else { this.FileDoesNotExist(sourceFile, destinationFile); } } } } } The above prototype is an abstract class. I'm wondering if it would be better to make the class non-abstract and have the Run method receiver a processor? eg. public void Run(IIdenticalDirectoriesProcessor processor) { foreach (DirectoryInfo sourceSubDirectory in _sourceDirectory.GetDirectories()) { DirectoryInfo destinationSubDirectory = this.GetDestinationDirectoryInfo(subDirectory); if (destinationSubDirectory.Exists()) { processor.DirectoryExists(sourceSubDirectory, destinationSubDirectory); } else { processor.DirectoryDoesNotExist(sourceSubDirectory, destinationSubDirectory); } foreach (FileInfo sourceFile in sourceSubDirectory.GetFiles()) { FileInfo destinationFile = this.GetDestinationFileInfo(sourceFile); if (destinationFile.Exists()) { processor.FileExists(sourceFile, destinationFile); } else { processor.FileDoesNotExist(sourceFile, destinationFile); } } } } What do you see as the pros and cons of each implementation?

    Read the article

  • Smarty/PHP loop not being passed to IE(Pc) or Chrome/FF(Mac)

    - by Kyle Sevenoaks
    Hi, I've been working on a site that has a lot of PHP/Smarty involved, I've been asked to re-skin a webstore checkout process, but during this we've discovered this issue. This particular quirk is one part of a tax calculation that doesn't get sent to the browser in IE for PC and Chrome/FF for the Mac. It's NOT in the output source in the browsers, but is in FF, Chrome and Opera on the PC. Here is the code that doesn't "work:" {foreach $cart.taxes.$currency as $tax} <div id="subTotalCaption2"><p style="width:100px;">{$tax.name_lang}:</p></div> <div id="taxAmount2"><p>{$tax.formattedAmount}</p></div> {/foreach} It's not a CSS issue as if you go all the way through the checkout process and then back to the order page (Not using the back button, using the on-site links) it works. There is another calculation on the last page of the process that does the same thing: {foreach from=$order.taxes.$currency item="tax"} <tr> <td colspan="{$colspan}" class="tax">{$tax.name_lang}:</td> <td>{$tax.formattedAmount}</td> </tr> {/foreach} I guess my question is what could cause this to not be read (Parsed?) in IE and the mac but other browsers do it fine on the PC. Thanks.

    Read the article

< Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >