Search Results

Search found 4616 results on 185 pages for 'lists'.

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

  • Behavior of <- NULL on lists versus data.frames for removing data

    - by Ananda Mahto
    Many R users eventually figure out lots of ways to remove elements from their data. One way is to use NULL, particularly when you want to do something like drop a column from a data.frame or drop an element from a list. Eventually, a user comes across a situation where they want to drop several columns from a data.frame at once, and they hit upon <- list(NULL) as the solution (since using <- NULL will result in an error). A data.frame is a special type of list, so it wouldn't be too tough to imagine that the approaches for removing items from a list should be the same as removing columns from a data.frame. However, they produce different results, as can be seen in the example below. ## Make some small data--two data.frames and two lists cars1 <- cars2 <- head(mtcars)[1:4] cars3 <- cars4 <- as.list(cars2) ## Demonstration that the `list(NULL)` approach works cars1[c("mpg", "cyl")] <- list(NULL) cars1 # disp hp # Mazda RX4 160 110 # Mazda RX4 Wag 160 110 # Datsun 710 108 93 # Hornet 4 Drive 258 110 # Hornet Sportabout 360 175 # Valiant 225 105 ## Demonstration that simply using `NULL` does not work cars2[c("mpg", "cyl")] <- NULL # Error in `[<-.data.frame`(`*tmp*`, c("mpg", "cyl"), value = NULL) : # replacement has 0 items, need 12 Switch to applying the same concept to a list, and compare the difference in behavior. ## Does not fully drop the items, but sets them to `NULL` cars3[c("mpg", "cyl")] <- list(NULL) # $mpg # NULL # # $cyl # NULL # # $disp # [1] 160 160 108 258 360 225 # # $hp # [1] 110 110 93 110 175 105 ## *Does* drop the `list` items while this would ## have produced an error with a `data.frame` cars4[c("mpg", "cyl")] <- NULL # $disp # [1] 160 160 108 258 360 225 # # $hp # [1] 110 110 93 110 175 105 The main questions I have are, if a data.frame is a list, why does it behave so differently in this scenario? Is there a foolproof way of knowing when an element will be dropped, when it will produce an error, and when it will simply be given a NULL value? Or do we depend on trial-and-error for this?

    Read the article

  • lists searches in SYB or uniplate haskell

    - by Chris
    I have been using uniplate and SYB and I am trying to transform a list For instance type Tree = [DataA] data DataA = DataA1 [DataB] | DataA2 String | DataA3 String [DataA] deriving Show data DataB = DataB1 [DataA] | DataB2 String | DataB3 String [DataB] deriving Show For instance, I would like to traverse my tree and append a value to all [DataB] So my first thought was to do this: changeDataB:: Tree -> Tree changeDataB = everywhere(mkT changeDataB') chanegDataB'::[DataB] -> [DataB] changeDataB' <add changes here> or if I was using uniplate changeDataB:: Tree -> Tree changeDataB = transformBi changeDataB' chanegDataB'::[DataB] -> [DataB] changeDataB' <add changes here> The problem is that I only want to search on the full list. Doing either of these searches will cause a search on the full list and all of the sub-lists (including the empty list) The other problem is that a value in [DataB] may generate a [DataB], so I don't know if this is the same kind of solution as not searching chars in a string. I could pattern match on DataA1 and DataB3, but in my real application there are a bunch of [DataB]. Pattern matching on the parents would be extensive. The other thought that I had was to create a data DataBs = [DataB] and use that to transform on. That seems kind of lame, there must be a better solution.

    Read the article

  • SharePoint Lists.asmx's UpdateListItems() returns too much data

    - by Philipp Schmid
    Is there a way to prevent the UpdateListItems() web service call in SharePoint's Lists.asmx endpoint from returning all of the fields of the newly created or updated list item? In our case an event handler attached to our custom list is adding some rather large field values which are turned to the client unnecessarily. Is there a way to tell it to only return the ID of the newly created (or updated) list item? For example, currently the web service returns something like this: <Results xmlns="http://schemas.microsoft.com/sharepoint/soap/"> <Result ID="1,Update"> <ErrorCode>0x00000000</ErrorCode> <z:row ows_ID="4" ows_Title="Title" ows_Modified="2003-06-19 20:31:21" ows_Created="2003-06-18 10:15:58" ows_Author="3;#User1_Display_Name" ows_Editor="7;#User2_Display_Name" ows_owshiddenversion="3" ows_Attachments="-1" ows__ModerationStatus="0" ows_LinkTitleNoMenu="Title" ows_LinkTitle="Title" ows_SelectTitle="4" ows_Order="400.000000000000" ows_GUID="{4962F024-BBA5-4A0B-9EC1-641B731ABFED}" ows_DateColumn="2003-09-04 00:00:00" ows_NumberColumn="791.00000000000000" xmlns:z="#RowsetSchema" /> </Result> ... </Results> where as I am looking for a trimmed response only containing for example the ows_ID attribute: <Results xmlns="http://schemas.microsoft.com/sharepoint/soap/"> <Result ID="1,Update"> <ErrorCode>0x00000000</ErrorCode> <z:row ows_ID="4" /> </Result> ... </Results> I have unsuccessfully looked for a resource that documents all of the valid attributes for both the <Batch> and <Method> tags in he updates XmlNode parameter of UpdateListItems() in the hope that I will find a way to specify the fields to return. A solution for WSS 3.0 would be preferable over an SP 2010-only solution.

    Read the article

  • Unable to cast lists with Reflection in C#

    - by DrLazer
    I am having a lot of trouble with Reflection in C# at the moment. The app I am writing allows the user to modify the attributes of certain objects using a config file. I want to be able to save the object model (users project) to XML. The function below is called in the middle of a foreach loop, looping through a list of objects that contain all the other objects in the project within them. The idea is, that it works recursively to translate the object model into XML. Dont worry about the call to "Unreal" that just modifes the name of the objects slightly if they contain certain words. private void ReflectToXML(object anObject, XmlElement parentElement) { Type aType = anObject.GetType(); XmlElement anXmlElement = m_xml.CreateElement(Unreal(aType.Name)); parentElement.AppendChild(anXmlElement); PropertyInfo[] pinfos = aType.GetProperties(); //loop through this objects public attributes foreach (PropertyInfo aInfo in pinfos) { //if the attribute is a list Type propertyType = aInfo.PropertyType; if ((propertyType.IsGenericType)&&(propertyType.GetGenericTypeDefinition() == typeof(List<>))) { List<object> listObjects = (aInfo.GetValue(anObject,null) as List<object>); foreach (object aListObject in listObjects) { ReflectToXML(aListObject, anXmlElement); } } //attribute is not a list else anXmlElement.SetAttribute(aInfo.Name, ""); } } If an object attributes are just strings then it should be writing them out as string attributes in the XML. If an objects attributes are lists, then it should recursively call "ReflectToXML" passing itself in as a parameter, thereby creating the nested structure I require that nicely reflect the object model in memory. The problem I have is with the line List<object> listObjects = (aInfo.GetValue(anObject,null) as List<object>); The cast doesn't work and it just returns null. While debugging I changed the line to object temp = aInfo.GetValue(anObject,null); slapped a breakpoint on it to see what "GetValue" was returning. It returns a "Generic list of objects" Surely I should be able to cast that? The annoying thing is that temp becomes a generic list of objects but because i declared temp as a singular object, I can't loop through it because it has no Enumerator. How can I loop through a list of objects when I only have it as a propertyInfo of a class? I know at this point I will only be saving a list of empty strings out anyway, but thats fine. I would be happy to see the structure save out for now. Thanks in advance

    Read the article

  • C# - How to override GetHashCode with Lists in object

    - by Christian
    Hi, I am trying to create a "KeySet" to modify UIElement behaviour. The idea is to create a special function if, eg. the user clicks on an element while holding a. Or ctrl+a. My approach so far, first lets create a container for all possible modifiers. If I would simply allow a single key, it would be no problem. I could use a simple Dictionary, with Dictionary<Keys, Action> _specialActionList If the dictionary is empty, use the default action. If there are entries, check what action to use depending on current pressed keys And if I wasn't greedy, that would be it... Now of course, I want more. I want to allow multiple keys or modifiers. So I created a wrapper class, wich can be used as Key to my dictionary. There is an obvious problem when using a more complex class. Currently two different instances would create two different key, and thereby he would never find my function (see code to understand, really obvious) Now I checked this post: http://stackoverflow.com/questions/638761/c-gethashcode-override-of-object-containing-generic-array which helped a little. But my question is, is my basic design for the class ok. Should I use a hashset to store the modifier and normal keyboardkeys (instead of Lists). And If so, how would the GetHashCode function look like? I know, its a lot of code to write (boring hash functions), some tips would be sufficient to get me started. Will post tryouts here... And here comes the code so far, the Test obviously fails... public class KeyModifierSet { private readonly List<Key> _keys = new List<Key>(); private readonly List<ModifierKeys> _modifierKeys = new List<ModifierKeys>(); private static readonly Dictionary<KeyModifierSet, Action> _testDict = new Dictionary<KeyModifierSet, Action>(); public static void Test() { _testDict.Add(new KeyModifierSet(Key.A), () => Debug.WriteLine("nothing")); if (!_testDict.ContainsKey(new KeyModifierSet(Key.A))) throw new Exception("Not done yet, help :-)"); } public KeyModifierSet(IEnumerable<Key> keys, IEnumerable<ModifierKeys> modifierKeys) { foreach (var key in keys) _keys.Add(key); foreach (var key in modifierKeys) _modifierKeys.Add(key); } public KeyModifierSet(Key key, ModifierKeys modifierKey) { _keys.Add(key); _modifierKeys.Add(modifierKey); } public KeyModifierSet(Key key) { _keys.Add(key); } }

    Read the article

  • Move options between multiple dropdown lists

    - by Martha
    We currently have a form with the standard multi-select functionality of "here are the available options, here are the selected options, here are some buttons to move stuff back and forth." However, the client now wants the ability to not just select certain items, but to also categorize them. For example, given a list of books, they want to not just select the ones they own, but also the ones they've read, the ones they would like to read, and the ones they've heard about. (All examples fictional.) Thankfully, a selected item can only be in one category at a time. I can find many examples of moving items between listboxes, but not a single one for moving items between multiple listboxes. To add to the complication, the form needs to have two sets of list+categories, e.g. a list of movies that need to be categorized in addition to the aforementioned books. An additional problem is that sorting between lists is all well and good in the javascript-enabled world, but I can't really think of a good fallback interface for, say, mobile browsers. Maybe a pseudo-listbox with radio buttons next to each item? The master list of items will in general be very long - over 100 items, certainly, possibly many more. Any given category will most likely contain one or two selected items, but the possibility exists for a category to have dozens of selected items, or zero selected items. As far as OS and stuff, the site is in classic asp (quit snickering!), the server-side code is VBScript, and so far we've avoided the various Javascript libraries by the simple expedient of almost never using client-side scripting. This one form for this one client is currently the big exception. Give 'em an inch and they want a mile... Oh, and I have to add: I suck at Javascript, or really at any C-descendant language. Curly braces give me hives. I'd really, really like something I can just copy & paste into my page, maybe tweak some variable names, and never look at it again. A girl can dream, can't she? :)

    Read the article

  • Linked lists in Java - help with assignment

    - by user368241
    Representation of a string in linked lists In every intersection in the list there will be 3 fields : The letter itself. The number of times it appears consecutively. A pointer to the next intersection in the list. The following class CharNode represents a intersection in the list : public class CharNode { private char _data; private int _value; private charNode _next; public CharNode (char c, int val, charNode n) { _data = c; _value = val; _next = n; } public charNode getNext() { return _next; } public void setNext (charNode node) { _next = node; } public int getValue() { return _value; } public void setValue (int v) { value = v; } public char getData() { return _data; } public void setData (char c) { _data = c; } } The class StringList represents the whole list : public class StringList { private charNode _head; public StringList() { _head = null; } public StringList (CharNode node) { _head = node; } } Add methods to the class StringList according to the details : (I will add methods gradually according to my specific questions) (Pay attention, these are methods from the class String and we want to fulfill them by the representation of a string by a list as explained above) public int indexOf (int ch) - returns the index in the string it is operated on of the first appeareance of the char "ch". If the char "ch" doesn't appear in the string, returns -1. If the value of fromIndex isn't in the range, returns -1. Pay attention to all the possible error cases. Write what is the time complexity and space complexity of every method that you wrote. Make sure the methods you wrote are effective. It is NOT allowed to use ready classes of Java. It is NOT allowed to move to string and use string operations. Here is my try to write the method indexOf (int ch). Kindly assist me with fixing the bugs so I can move on. public int indexOf (int ch) { int count = 0; charNode pose = _head; if (pose == null ) { return -1; } for (pose = _head; pose!=null && pose.getNext()!='ch'; pose = pose.getNext()) { count++; } if (pose!=null) return count; else return -1; }

    Read the article

  • Trying to implement a method that can compare any two lists but it always returns false

    - by Tyler Pfaff
    Hello like the title says I'm trying to make a method that can compare any two lists for equality. I'm trying to compare them in a way that validates that every element of one list has the same value as every element of another list. My Equals method below always returns false, can anyone see why that is? Thank you! using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class IEnumerableComparer<T> : IEqualityComparer<IEnumerable<T>> { public bool Equals(IEnumerable<T> x, IEnumerable<T> y) { for(int i = 0; i<x.Count();i++){ if(!Object.Equals(x.ElementAt(i), y.ElementAt(i))){ return false; } } return true; } public int GetHashCode(IEnumerable<T> obj) { if (obj == null) return 0; return unchecked(obj.Select(e => e.GetHashCode()).Aggregate(0, (a, b) => a + b)); } } Here is my data I'm using to test this Equals method. static void Main(string[] args) { Car car1 = new Car(); car1.make = "Toyota"; car1.model = "xB"; Car car2 = new Car(); car2.make = "Toyota"; car2.model = "xB"; List<Car> l1 = new List<Car>(); List<Car> l2 = new List<Car>(); l1.Add(car1); l2.Add(car2); IEnumerableComparer<Car> seq = new IEnumerableComparer<Car>(); bool b = seq.Equals(l1, l2); Console.Write(b); //always says false Console.Read(); } } Car class class Car { public String make { get; set; } public String model { get; set; } }

    Read the article

  • Iterating multple lists consecutively (C++)

    - by Graham Rogers
    I have 3 classes, 2 inheriting from the other like so: class A { public: virtual void foo() {cout << "I am A!" << endl;} }; class B : public A { public: void foo() {cout << "B pretending to be A." << endl} void onlyBFoo() {cout << "I am B!" << endl} }; class C : public A { public: void foo() {cout << "C pretending to be A." << endl} void onlyCFoo() {cout << "I am C!" << endl} }; What I want to do is something like this: list<A> list_of_A; list<B> list_of_B; list<C> list_of_C; //put three of each class in their respective list for (list<B>::iterator it = list_of_B.begin(); it != list_of_B.end(); ++it) { (*it).onlyBFoo(); } for (list<C>::iterator it = list_of_C.begin(); it != list_of_C.end(); ++it) { (*it).foo(); } //This part I am not sure about for (list<A>::iterator it = list_of_all.begin(); it != list_of_all.end(); ++it) { (*it).foo(); } To output: I am B! I am B! I am B! I am C! I am C! I am C! I am A! I am A! I am A! B pretending to be A. B pretending to be A. B pretending to be A. C pretending to be A. C pretending to be A. C pretending to be A. Basically, sometimes I want to only loop the Bs and Cs so that I can use their methods, but sometimes I want to loop all of them so that I can use the same method from each i.e. iterate the As, then the Bs, then the Cs all in one loop. I thought of creating a separate list (like the code above) containing everything, but it would create lots of unnecessary maintenance, as I will be adding and removing every object from 2 lists instead of one.

    Read the article

  • Validation Summary for Lists using Data Annotations with MVC

    - by David Liddle
    I currently use a custom method to display validation error messages for lists but would like to replace this system for using with Data Annotations. In summary on validation of my form, I want to display "*" next to each input that is incorrect and also provide a Validation Summary at the bottom that relates each error message to the particular item in the list. e.g. say if validation failed on the 2nd list item on a Name input box and the 4th item on an Address input box the validation summary would display [2] Name is invalid [4] Address is invalid Please ignore if there are mistakes in the code below. I'm just writing this as an example. The code below shows how I was able to do it using my custom version of adding model errors but was wondering how to do this using Data Annotations? //Domain Object public class MyObject { public int ID { get; set; } public string Name { get; set; } public string Address { get; set; } public bool IsValid { get { return (GetRuleViolations().Count() == 0); } } public void IEnumerable<RuleViolation> GetRuleViolations() { if (String.IsNullOrEmpty(Name)) yield return new RuleViolation(ID, "Name", "Name is invalid"); if (String.IsNullOrEmpty(Address)) yield return new RuleViolation(ID, "Address", "Address is invalid"); yield break; } } //Rule Violation public class RuleViolation { public int ID { get; private set; } public string PropertyName { get; private set; } public string ErrorMessage { get; private set; } } //View <% for (int i = 0; i < 5; i++) { %> <p> <%= Html.Hidden("myObjects[" + i + "].ID", i) %> Name: <%= Html.TextBox("myObjects[" + i + "].Name") %> <br /> <%= Html.ValidationMessage("myObjects[" + i + "].Name", "*")<br /> Address: <%= Html.TextBox("myObjects[" + i + "].Address") %> <%= Html.ValidationMessage("myObjects[" + i + "].Address", "*")<br /> </p> <% } %> <p><%= Html.ValidationSummary() %> //Controller public ActionResult MyAction(IList<MyObject> myObjects) { foreach (MyObject o in myObjects) { if (!o.IsValid) ModelState.AddModelErrors(o.GetRuleViolations(), o.GetType().Name); } if (!Model.IsValid) { return View(); } } public static class ModelStateExtensions { public static void AddModelError(this ModelStateDictionary modelState, RuleViolation issue, string name) { string key = String.Format("{0}[{1}].{2}", name, issue.ID, issue.PropertyName); string error = String.Format("[{0}] {1}", (issue.ID + 1), issue.ErrorMessage); //above line determines the [ID] ErrorMessage to be //displayed in the Validation Summary modelState.AddModelError(key, error); }

    Read the article

  • Passing integer lists in a sql query, best practices

    - by Artiom Chilaru
    I'm currently looking at ways to pass lists of integers in a SQL query, and try to decide which of them is best in which situation, what are the benefots of each, and what are the pitfalls, what should be avoided :) Right now I know of 3 ways that we currently use in our application. 1) Table valued parameter: Create a new Table Valued Parameter in sql server: CREATE TYPE [dbo].[TVP_INT] AS TABLE( [ID] [int] NOT NULL ) Then run the query against it: using (var conn = new SqlConnection(DataContext.GetDefaultConnectionString)) { var comm = conn.CreateCommand(); comm.CommandType = CommandType.Text; comm.CommandText = @" UPDATE DA SET [tsLastImportAttempt] = CURRENT_TIMESTAMP FROM [Account] DA JOIN @values IDs ON DA.ID = IDs.ID"; comm.Parameters.Add(new SqlParameter("values", downloadResults.Select(d => d.ID).ToDataTable()) { TypeName = "TVP_INT" }); conn.Open(); comm.ExecuteScalar(); } The major disadvantages of this method is the fact that Linq doesn't support table valued params (if you create an SP with a TVP param, linq won't be able to run it) :( 2) Convert the list to Binary and use it in Linq! This is a bit better.. Create an SP, and you can run it within linq :) To do this, the SP will have an IMAGE parameter, and we'll be using a user defined function (udf) to convert this to a table.. We currently have implementations of this function written in C++ and in assembly, both have pretty much the same performance :) Basically, each integer is represented by 4 bytes, and passed to the SP. In .NET we have an extension method that convers an IEnumerable to a byte array The extension method: public static Byte[] ToBinary(this IEnumerable intList) { return ToBinaryEnum(intList).ToArray(); } private static IEnumerable<Byte> ToBinaryEnum(IEnumerable<Int32> intList) { IEnumerator<Int32> marker = intList.GetEnumerator(); while (marker.MoveNext()) { Byte[] result = BitConverter.GetBytes(marker.Current); Array.Reverse(result); foreach (byte b in result) yield return b; } } The SP: CREATE PROCEDURE [Accounts-UpdateImportAttempts] @values IMAGE AS BEGIN UPDATE DA SET [tsLastImportAttempt] = CURRENT_TIMESTAMP FROM [Account] DA JOIN dbo.udfIntegerArray(@values, 4) IDs ON DA.ID = IDs.Value4 END And we can use it by running the SP directly, or in any linq query we need using (var db = new DataContext()) { db.Accounts_UpdateImportAttempts(downloadResults.Select(d => d.ID).ToBinary()); // or var accounts = db.Accounts .Where(a => db.udfIntegerArray(downloadResults.Select(d => d.ID).ToBinary(), 4) .Select(i => i.Value4) .Contains(a.ID)); } This method has the benefit of using compiled queries in linq (which will have the same sql definition, and query plan, so will also be cached), and can be used in SPs as well. Both these methods are theoretically unlimited, so you can pass millions of ints at a time :) 3) The simple linq .Contains() It's a more simple approach, and is perfect in simple scenarios. But is of course limited by this. using (var db = new DataContext()) { var accounts = db.Accounts .Where(a => downloadResults.Select(d => d.ID).Contains(a.ID)); } The biggest drawback of this method is that each integer in the downloadResults variable will be passed as a separate int.. In this case, the query is limited by sql (max allowed parameters in a sql query, which is a couple of thousand, if I remember right). So I'd like to ask.. What do you think is the best of these, and what other methods and approaches have I missed?

    Read the article

  • Linked Lists in Java - Help with assignment

    - by doron2010
    I have been trying to solve this assignment all day, please help me. I'm completely lost. Representation of a string in linked lists In every intersection in the list there will be 3 fields : The letter itself. The number of times it appears consecutively. A pointer to the next intersection in the list. The following class CharNode represents a intersection in the list : public class CharNode { private char _data; private int _value; private charNode _next; public CharNode (char c, int val, charNode n) { _data = c; _value = val; _next = n; } public charNode getNext() { return _next; } public void setNext (charNode node) { _next = node; } public int getValue() { return _value; } public void setValue (int v) { value = v; } public char getData() { return _data; } public void setData (char c) { _data = c; } } The class StringList represents the whole list : public class StringList { private charNode _head; public StringList() { _head = null; } public StringList (CharNode node) { _head = node; } } Add methods to the class StringList according to the details : (Pay attention, these are methods from the class String and we want to fulfill them by the representation of a string by a list as explained above) public char charAt (int i) - returns the char in the place i in the string. Assume that the value of i is in the right range. public StringList concat (String str) - returns a string that consists of the string that it is operated on and in its end the string "str" is concatenated. public int indexOf (int ch) - returns the index in the string it is operated on of the first appeareance of the char "ch". If the char "ch" doesn't appear in the string, returns -1. If the value of fromIndex isn't in the range, returns -1. public int indexOf (int ch, int fromIndex) - returns the index in the string it is operated on of the first appeareance of the char "ch", as the search begins in the index "fromIndex". If the char "ch" doesn't appear in the string, returns -1. public boolean equals (String str) - returns true if the string that it is operated on is equal to the string str. Otherwise returns false. This method must be written in recursion, without using loops at all. public int compareTo (String str) - compares between the string that the method is operated on to the string "str" that is in the parameter. The method returns 0 if the strings are equal. If the string in the object is smaller lexicographic from the string "str" in the paramater, a negative number will be returned. And if the string in the object is bigger lexicographic from the string "str", a positive number will be returned. public StringList substring (int i) - returns the list of the substring that starts in the place i in the string on which it operates. Meaning, the sub-string from the place i until the end of the string. Assume the value of i is in the right range. public StringList substring (int i, int j) - returns the list of the substring that begins in the place i and ends in the place j (not included) in the string it operates on. Assume the values of i, j are in the right range. public int length() - will return the length of the string on which it operates. Pay attention to all the possible error cases. Write what is the time complexity and space complexity of every method that you wrote. Make sure the methods you wrote are effective. It is NOT allowed to use ready classes of Java. It is NOT allowed to move to string and use string operations.

    Read the article

  • Reconciling a new BindingList into a master BindingList using LINQ

    - by Neo
    I have a seemingly simple problem whereby I wish to reconcile two lists so that an 'old' master list is updated by a 'new' list containing updated elements. Elements are denoted by a key property. These are my requirements: All elements in either list that have the same key results in an assignment of that element from the 'new' list over the original element in the 'old' list only if any properties have changed. Any elements in the 'new' list that have keys not in the 'old' list will be added to the 'old' list. Any elements in the 'old' list that have keys not in the 'new' list will be removed from the 'old' list. I found an equivalent problem here - http://stackoverflow.com/questions/161432/ - but it hasn't really been answered properly. So, I came up with an algorithm to iterate through the old and new lists and perform the reconciliation as per the above. Before anyone asks why I'm not just replacing the old list object with the new list object in its entirety, it's for presentation purposes - this is a BindingList bound to a grid on a GUI and I need to prevent refresh artifacts such as blinking, scrollbars moving, etc. So the list object must remain the same, only its updated elements changed. Another thing to note is that the objects in the 'new' list, even if the key is the same and all the properties are the same, are completely different instances to the equivalent objects in the 'old' list, so copying references is not an option. Below is what I've come up with so far - it's a generic extension method for a BindingList. I've put comments in to demonstrate what I'm trying to do. public static class BindingListExtension { public static void Reconcile<T>(this BindingList<T> left, BindingList<T> right, string key) { PropertyInfo piKey = typeof(T).GetProperty(key); // Go through each item in the new list in order to find all updated and new elements foreach (T newObj in right) { // First, find an object in the new list that shares its key with an object in the old list T oldObj = left.First(call => piKey.GetValue(call, null).Equals(piKey.GetValue(newObj, null))); if (oldObj != null) { // An object in each list was found with the same key, so now check to see if any properties have changed and // if any have, then assign the object from the new list over the top of the equivalent element in the old list foreach (PropertyInfo pi in typeof(T).GetProperties()) { if (!pi.GetValue(oldObj, null).Equals(pi.GetValue(newObj, null))) { left[left.IndexOf(oldObj)] = newObj; break; } } } else { // The object in the new list is brand new (has a new key), so add it to the old list left.Add(newObj); } } // Now, go through each item in the old list to find all elements with keys no longer in the new list foreach (T oldObj in left) { // Look for an element in the new list with a key matching an element in the old list if (right.First(call => piKey.GetValue(call, null).Equals(piKey.GetValue(oldObj, null))) == null) { // A matching element cannot be found in the new list, so remove the item from the old list left.Remove(oldObj); } } } } It can be called like this: _oldBindingList.Reconcile(newBindingList, "MyKey") However, I'm looking for perhaps a method of doing the same using LINQ type methods such as GroupJoin<, Join<, Select<, SelectMany<, Intersect<, etc. So far, the problem I've had is that each of these LINQ type methods result in brand new intermediary lists (as a return value) and really, I only want to modify the existing list for all the above reasons. If anyone can help with this, would be most appreciated. If not, no worries, the above method (as it were) will suffice for now. Thanks, Jason

    Read the article

  • Silverlight 4 Twitter Client &ndash; Part 6

    - by Max
    In this post, we are going to look into implementing lists into our twitter application and also about enhancing the data grid to display the status messages in a pleasing way with the profile images. Twitter lists are really cool feature that they recently added, I love them and I’ve quite a few lists setup one for DOTNET gurus, SQL Server gurus and one for a few celebrities. You can follow them here. Now let us move onto our tutorial. 1) Lists can be subscribed to in two ways, one can be user’s own lists, which he has created and another one is the lists that the user is following. Like for example, I’ve created 3 lists myself and I am following 1 other lists created by another user. Both of them cannot be fetched in the same api call, its a two step process. 2) In the TwitterCredentialsSubmit method we’ve in Home.xaml.cs, let us do the first api call to get the lists that the user has created. For this the call has to be made to https://twitter.com/<TwitterUsername>/lists.xml. The API reference is available here. myService1.AllowReadStreamBuffering = true; myService1.UseDefaultCredentials = false; myService1.Credentials = new NetworkCredential(GlobalVariable.getUserName(), GlobalVariable.getPassword()); myService1.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ListsRequestCompleted); myService1.DownloadStringAsync(new Uri("https://twitter.com/" + GlobalVariable.getUserName() + "/lists.xml")); 3) Now let us look at implementing the event handler – ListRequestCompleted for this. public void ListsRequestCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e) { if (e.Error != null) { StatusMessage.Text = "This application must be installed first."; parseXML(""); } else { //MessageBox.Show(e.Result.ToString()); parseXMLLists(e.Result.ToString()); } } 4) Now let us look at the parseXMLLists in detail xdoc = XDocument.Parse(text); var answer = (from status in xdoc.Descendants("list") select status.Element("name").Value); foreach (var p in answer) { Border bord = new Border(); bord.CornerRadius = new CornerRadius(10, 10, 10, 10); Button b = new Button(); b.MinWidth = 70; b.Background = new SolidColorBrush(Colors.Black); b.Foreground = new SolidColorBrush(Colors.Black); //b.Width = 70; b.Height = 25; b.Click += new RoutedEventHandler(b_Click); b.Content = p.ToString(); bord.Child = b; TwitterListStack.Children.Add(bord); } So here what am I doing, I am just dynamically creating a button for each of the lists and put them within a StackPanel and for each of these buttons, I am creating a event handler b_Click which will be fired on button click. We will look into this method in detail soon. For now let us get the buttons displayed. 5) Now the user might have some lists to which he has subscribed to. We need to create a button for these as well. In the end of TwitterCredentialsSubmit method, we need to make a call to http://api.twitter.com/1/<TwitterUsername>/lists/subscriptions.xml. Reference is available here. The code will look like this below. myService2.AllowReadStreamBuffering = true; myService2.UseDefaultCredentials = false; myService2.Credentials = new NetworkCredential(GlobalVariable.getUserName(), GlobalVariable.getPassword()); myService2.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ListsSubsRequestCompleted); myService2.DownloadStringAsync(new Uri("http://api.twitter.com/1/" + GlobalVariable.getUserName() + "/lists/subscriptions.xml")); 6) In the event handler – ListsSubsRequestCompleted, we need to parse through the xml string and create a button for each of the lists subscribed, let us see how. I’ve taken only the “full_name”, you can choose what you want, refer the documentation here. Note the point that the full_name will have @<UserName>/<ListName> format – this will be useful very soon. xdoc = XDocument.Parse(text); var answer = (from status in xdoc.Descendants("list") select status.Element("full_name").Value); foreach (var p in answer) { Border bord = new Border(); bord.CornerRadius = new CornerRadius(10, 10, 10, 10); Button b = new Button(); b.Background = new SolidColorBrush(Colors.Black); b.Foreground = new SolidColorBrush(Colors.Black); //b.Width = 70; b.MinWidth = 70; b.Height = 25; b.Click += new RoutedEventHandler(b_Click); b.Content = p.ToString(); bord.Child = b; TwitterListStack.Children.Add(bord); } Please note, I am setting the button width to be auto based on the content and also giving it a midwidth value. I wanted to create a rounded corner buttons, but for some reason its not working. Also add this StackPanel – TwitterListStack of the Home.xaml <StackPanel HorizontalAlignment="Center" Orientation="Horizontal" Name="TwitterListStack"></StackPanel> After doing this, you would get a series of buttons in the top of the home page. 7) Now the button click event handler – b_Click, in this method, once the button is clicked, I call another method with the content string of the button which is clicked as the parameter. Button b = (Button)e.OriginalSource; getListStatuses(b.Content.ToString()); 8) Now the getListsStatuses method: toggleProgressBar(true); WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp); WebClient myService = new WebClient(); myService.AllowReadStreamBuffering = true; myService.UseDefaultCredentials = false; myService.DownloadStringCompleted += new DownloadStringCompletedEventHandler(TimelineRequestCompleted); if (listName.IndexOf("@") > -1 && listName.IndexOf("/") > -1) { string[] arrays = null; arrays = listName.Split('/'); arrays[0] = arrays[0].Replace("@", " ").Trim(); //MessageBox.Show(arrays[0]); //MessageBox.Show(arrays[1]); string url = "http://api.twitter.com/1/" + arrays[0] + "/lists/" + arrays[1] + "/statuses.xml"; //MessageBox.Show(url); myService.DownloadStringAsync(new Uri(url)); } else myService.DownloadStringAsync(new Uri("http://api.twitter.com/1/" + GlobalVariable.getUserName() + "/lists/" + listName + "/statuses.xml")); Please note that the url to look at will be different based on the list clicked – if its user created, the url format will be http://api.twitter.com/1/<CurentUser>/lists/<ListName>/statuses.xml But if it is some lists subscribed, it will be http://api.twitter.com/1/<ListOwnerUserName>/lists/<ListName>/statuses.xml The first one is pretty straight forward to implement, but if its a list subscribed, we need to split the listName string to get the list owner and list name and user them to form the string. So that is what I’ve done in this method, if the listName has got “@” and “/” I build the url differently. 9) Until now, we’ve been using only a few nodes of the status message xml string, now we will look to fetch a new field - “profile_image_url”. Images in datagrid – COOL. So for that, we need to modify our Status.cs file to include two more fields one string another BitmapImage with get and set. public string profile_image_url { get; set; } public BitmapImage profileImage { get; set; } 10) Now let us change the generic parseXML method which is used for binding to the datagrid. public void parseXML(string text) { XDocument xdoc; xdoc = XDocument.Parse(text); statusList = new List<Status>(); statusList = (from status in xdoc.Descendants("status") select new Status { ID = status.Element("id").Value, Text = status.Element("text").Value, Source = status.Element("source").Value, UserID = status.Element("user").Element("id").Value, UserName = status.Element("user").Element("screen_name").Value, profile_image_url = status.Element("user").Element("profile_image_url").Value, profileImage = new BitmapImage(new Uri(status.Element("user").Element("profile_image_url").Value)) }).ToList(); DataGridStatus.ItemsSource = statusList; StatusMessage.Text = "Datagrid refreshed."; toggleProgressBar(false); } We are here creating a new bitmap image from the image url and creating a new Status object for every status and binding them to the data grid. Refer to the Twitter API documentation here. You can choose any column you want. 11) Until now, we’ve been using the auto generate columns for the data grid, but if you want it to be really cool, you need to define the columns with templates, etc… <data:DataGrid AutoGenerateColumns="False" Name="DataGridStatus" Height="Auto" MinWidth="400"> <data:DataGrid.Columns> <data:DataGridTemplateColumn Width="50" Header=""> <data:DataGridTemplateColumn.CellTemplate> <DataTemplate> <Image Source="{Binding profileImage}" Width="50" Height="50" Margin="1"/> </DataTemplate> </data:DataGridTemplateColumn.CellTemplate> </data:DataGridTemplateColumn> <data:DataGridTextColumn Width="Auto" Header="User Name" Binding="{Binding UserName}" /> <data:DataGridTemplateColumn MinWidth="300" Width="Auto" Header="Status"> <data:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock TextWrapping="Wrap" Text="{Binding Text}"/> </DataTemplate> </data:DataGridTemplateColumn.CellTemplate> </data:DataGridTemplateColumn> </data:DataGrid.Columns> </data:DataGrid> I’ve used only three columns – Profile image, Username, Status text. Now our Datagrid will look super cool like this. Coincidentally,  Tim Heuer is on the screenshot , who is a Silverlight Guru and works on SL team in Microsoft. His blog is really super. Here is the zipped file for all the xaml, xaml.cs & class files pages. Ok let us stop here for now, will look into implementing few more features in the next few posts and then I am going to look into developing a ASP.NET MVC 2 application. Hope you all liked this post. If you have any queries / suggestions feel free to comment below or contact me. Cheers! Technorati Tags: Silverlight,LINQ,Twitter API,Twitter,Silverlight 4

    Read the article

  • css problem with unordered lists (as usual with IE)

    - by Emin
    I am using un-ordered lists that nests some divs to show the desired output on screen. I am using css to style them and they seem to look perfect on chrome and firefox. But in IE(8) it looks there is a problem which I was unable to locate. I am using the below CSS <style type="text/css"> .ur_container {width:980px; padding: 0; margin: 0;} .ur_container ul.bx_grp {list-style-type: none; padding: 0px; margin: 0px; } .ur_container ul.bx_lnx {list-style-type: none; padding: 5px; margin: 0px; } .bx_grp {border:1px solid #c5c5c5; background-color: yellow; margin:0; padding:0;} .bx_grp_header {background-color: #d6d6d6; border-bottom:1px solid #acacac;} .bx_grp_title {float: left; font: bold 11px Arial; padding:5px;} .bx_grp_options {float: right; font: 10px Arial; padding: 5px;} .bx_grp_options a{color: #125B93; text-decoration: none; } .bx_lnx {padding:0px; background-color: red;} .bx_lnx_header {font:11px Arial; color:#333;} .bx_lnx_title {float: left;} .bx_lnx_refno {background-color:#333; color: fff; padding: 1px; margin-right: 5px; } .bx_lnx_options {float: right;} .bx_lnx_options a {color: #258CF4; text-decoration: none;} .bx_lnx_url {font: 9px Arial; color: #999; margin-top: 4px; } .bx_lnx_notes {} .bx_lnx_notes span {background-color: #FDFFCC; color: #666; font: 9px Arial; padding:2px;} .bx_lnx_tags {} .bx_lnx_tags span {background-color: #efefef; border-bottom: 1px solid #ccc; color: #666; font: 9px Arial; padding: 1px 2px 1px 2px; margin-right: 5px;} </style> Against the following HTML <div class="ur_container"> <ul class="bx_grp" id="grp_1"> <li> <div class="bx_grp_header"> <span class="bx_grp_title">Personal File</span> <span class="bx_grp_options"><a href="#">rename</a> &bull; <a href="#">make private</a> &bull; <a href="#">hide</a href="#"> &bull; <a href="#">delete</a></span> <div style="clear: both;"></div> </div> </li> <li> <ul class="bx_lnx" id="lnx_1"> <li> <div class="bx_lnx_header"> <span class="bx_linx_title"><span class="bx_lnx_refno">#3103</span>How to file personal files</span> <span class="bx_lnx_options"><a href="#">edit</a> &bull; <a href="#">move</a> &bull; <a href="#">delete</a></span> </div> </li> <li class="bx_lnx_url">http://www.google.com</li> <li class="bx_lnx_notes"><span>search google for this</span></li> <li class="bx_lnx_tags"><span>personal</span><span>file</span><span>google</span></li> </ul> </li> </ul> </div> Which produces this output in Chrome and Fireworks and the following in IE The yellow and red colors was used in order to show that is being going wrong. The yellow part is the undesired one. Can anyone point me in the right direction please ? Regards

    Read the article

  • Linked lists in Java - Help with writing methods

    - by user368241
    Representation of a string in linked lists In every intersection in the list there will be 3 fields : The letter itself. The number of times it appears consecutively. A pointer to the next intersection in the list. The following class CharNode represents a intersection in the list : public class CharNode { private char _data; private int _value; private charNode _next; public CharNode (char c, int val, charNode n) { _data = c; _value = val; _next = n; } public charNode getNext() { return _next; } public void setNext (charNode node) { _next = node; } public int getValue() { return _value; } public void setValue (int v) { value = v; } public char getData() { return _data; } public void setData (char c) { _data = c; } } The class StringList represents the whole list : public class StringList { private charNode _head; public StringList() { _head = null; } public StringList (CharNode node) { _head = node; } } Add methods to the class StringList according to the details : (I will add methods gradually according to my specific questions) (Pay attention, these are methods from the class String and we want to fulfill them by the representation of a string by a list as explained above) Pay attention to all the possible error cases. Write what is the time complexity and space complexity of every method that you wrote. Make sure the methods you wrote are effective. It is NOT allowed to use ready classes of Java. It is NOT allowed to move to string and use string operations. 1) public int indexOf (int ch) - returns the index in the string it is operated on of the first appeareance of the char "ch". If the char "ch" doesn't appear in the string, returns -1. If the value of fromIndex isn't in the range, returns -1. Here is my try : public int indexOf (int ch) { int count = 0; charNode pos = _head; if (pos == null ) { return -1; } for (pos = _head; pos!=null && pos.getData()!=ch; pos = pos.getNext()) { count = count + pos.getValue(); } if (pos==null) return -1; return count; } Time complexity = O(N) Space complexity = O(1) EDIT : I have a problem. I tested it in BlueJ and if the char ch doesn't appear it returns -1 but if it does, it always returns 0 and I don't understand why... I am confused. How can the compiler know that the value is the number of times the letter appears consecutively? Can I assume this because its given on the question or what? If it's true and I can assume this, then my code should be correct right? Ok I just spoke with my instructor and she said it isn't required to write it in the exercise but in order for me to test that it indeed works, I need to open a new class and write a code for making a list so that the the value of every node is the number of times the letter appears consecutively. Can someone please assist me? So I will copy+paste to BlueJ and this way I will be able to test all the methods. Meanwhile I am moving on to the next methods. 2) public int indexOf (int ch, int fromIndex) - returns the index in the string it is operated on of the first appeareance of the char "ch", as the search begins in the index "fromIndex". If the char "ch" doesn't appear in the string, returns -1. If the value of fromIndex doesn't appear in the range, returns -1. Here is my try: public int indexOf (int ch, int fromIndex) { int count = 0, len=0, i; charNode pos = _head; CharNode cur = _head; for (pos = _head; pos!=null; pos = pos.getNext()) { len = len+1; } if (fromIndex<0 || fromIndex>=len) return -1; for (i=0; i<fromIndex; i++) { cur = cur.getNext(); } if (cur == null ) { return -1; } for (cur = _head; cur!=null && cur.getData()!=ch; cur = cur.getNext()) { count = count + cur.getValue(); } if (cur==null) return -1; return count; } Time complexity = O(N) ? Space complexity = O(1) 3) public StringList concat (String str) - returns a string that consists of the string that it is operated on and in its end the string "str" is concatenated. Here is my try : public StringList concat (String str) { String str = ""; charNode pos = _head; if (str == null) return -1; for (pos = _head; pos!=null; pos = pos.getNext()) { str = str + pos.getData(); } str = str + "str"; return str; } Time complexity = O(N) Space complexity = O(1)

    Read the article

  • CSS Hover on parent list Item only

    - by Daniel O'Connor
    Hey Everyone, So I have some nested lists (only one level deep) and I'm running into trouble with the CSS :hover feature. I only want the hover to apply to the parent class, but I can't figure that one out. Here's my CSS <style type="text/css" media="screen"> .listblock li img { visibility: hidden; } .listblock li:hover img { visibility: visible; } </style> And here is a sample of one of the lists. <ul> <li>One <a href="#"><img src="img/basket.png" height="16" width="16" alt="Buy" class="buy" onClick="pageTracker._trackEvent('Outbound Links', 'Amazon');"/></a></li> <li>Two <a href="#"><img src="img/basket.png" height="16" width="16" class="buy" /></a> <ul> <li>Uno<a href="#"><img src="img/basket.png" height="16" width="16" class="buy" /></a></li> <li>Dos <a href="#"><img src="img/basket.png" height="16" width="16" class="buy" /></a></li> </ul> </li> <li>Three <a href="#"><img src="img/basket.png" height="16" width="16" alt="Buy" class="buy" onClick="pageTracker._trackEvent('Outbound Links', 'Amazon');"/></a></li> </ul> The problem is that the image in the Uno and Dos list items also hovers. :( Help please! Thanks a lot

    Read the article

  • Need help with copy constructor for very basic implementation of singly linked lists

    - by Jesus
    Last week, we created a program that manages sets of strings, using classes and vectors. I was able to complete this 100%. This week, we have to replace the vector we used to store strings in our class with simple singly linked lists. The function basically allows users to declare sets of strings that are empty, and sets with only one element. In the main file, there is a vector whose elements are a struct that contain setName and strSet (class). HERE IS MY PROBLEM: It deals with the copy constructor of the class. When I remove/comment out the copy constructor, I can declare as many empty or single sets as I want, and output their values without a problem. But I know I will obviously need the copy constructor for when I implement the rest of the program. When I leave the copy constructor in, I can declare one set, either single or empty, and output its value. But if I declare a 2nd set, and i try to output either of the first two sets, i get a Segmentation Fault. Moreover, if i try to declare more then 2 sets, I get a Segmentation Fault. Any help would be appreciated!! Here is my code for a very basic implementation of everything: Here is the setcalc.cpp: (main file) #include <iostream> #include <cctype> #include <cstring> #include <string> #include "help.h" #include "strset2.h" using namespace std; // Declares of structure to hold all the sets defined struct setsOfStr { string nameOfSet; strSet stringSet; }; // Checks if the set name inputted is unique bool isSetNameUnique( vector<setsOfStr> strSetArr, string setName) { for(unsigned int i = 0; i < strSetArr.size(); i++) { if( strSetArr[i].nameOfSet == setName ) { return false; } } return true; } int main(int argc, char *argv[]) { char commandChoice; // Declares a vector with our declared structure as the type vector<setsOfStr> strSetVec; string setName; string singleEle; // Sets a loop that will constantly ask for a command until 'q' is typed while (1) { // declaring a set to be empty if(commandChoice == 'd') { cin >> setName; // Check that the set name inputted is unique if (isSetNameUnique(strSetVec, setName) == true) { strSet emptyStrSet; setsOfStr set1; set1.nameOfSet = setName; set1.stringSet = emptyStrSet; strSetVec.push_back(set1); } else { cerr << "ERROR: Re-declaration of set '" << setName << "'\n"; } } // declaring a set to be a singleton else if(commandChoice == 's') { cin >> setName; cin >> singleEle; // Check that the set name inputted is unique if (isSetNameUnique(strSetVec, setName) == true) { strSet singleStrSet(singleEle); setsOfStr set2; set2.nameOfSet = setName; set2.stringSet = singleStrSet; strSetVec.push_back(set2); } else { cerr << "ERROR: Re-declaration of set '" << setName << "'\n"; } } // using the output function else if(commandChoice == 'o') { cin >> setName; if(isSetNameUnique(strSetVec, setName) == false) { // loop through until the set name is matched and call output on its strSet for(unsigned int k = 0; k < strSetVec.size(); k++) { if( strSetVec[k].nameOfSet == setName ) { (strSetVec[k].stringSet).output(); } } } else { cerr << "ERROR: No such set '" << setName << "'\n"; } } // quitting else if(commandChoice == 'q') { break; } else { cerr << "ERROR: Ignoring bad command: '" << commandChoice << "'\n"; } } return 0; } Here is the strSet2.h: #ifndef _STRSET_ #define _STRSET_ #include <iostream> #include <vector> #include <string> struct node { std::string s1; node * next; }; class strSet { private: node * first; public: strSet (); // Create empty set strSet (std::string s); // Create singleton set strSet (const strSet &copy); // Copy constructor // will implement destructor later void output() const; strSet& operator = (const strSet& rtSide); // Assignment }; // End of strSet class #endif // _STRSET_ And here is the strSet2.cpp (implementation of class) #include <iostream> #include <vector> #include <string> #include "strset2.h" using namespace std; strSet::strSet() { first = NULL; } strSet::strSet(string s) { node *temp; temp = new node; temp->s1 = s; temp->next = NULL; first = temp; } strSet::strSet(const strSet& copy) { cout << "copy-cst\n"; node *n = copy.first; node *prev = NULL; while (n) { node *newNode = new node; newNode->s1 = n->s1; newNode->next = NULL; if (prev) { prev->next = newNode; } else { first = newNode; } prev = newNode; n = n->next; } } void strSet::output() const { if(first == NULL) { cout << "Empty set\n"; } else { node *temp; temp = first; while(1) { cout << temp->s1 << endl; if(temp->next == NULL) break; temp = temp->next; } } } strSet& strSet::operator = (const strSet& rtSide) { first = rtSide.first; return *this; }

    Read the article

  • How do you create a mailing list with Lotus Notes?

    - by Richard Cotton
    I have a list of users of an application stored in an SQL database. I'd like to be able to email these people with useful information. Two parts to the question. How do I send queries to an SQL database from Lotus Notes (v6.5.5), in order to retrieve the email addresses? (I'm okay with what the contents of the query should be, I just need to know how to get Notes talking to the database.) How do I programmatically store these addresses as a group contact?

    Read the article

  • Mailing List Solution

    - by Shoaibi
    I have more than 1M users and i need to send newsletters to. I have tried PHPList but it has failed as it gets stalled every 30K emails. I need a faster and more reliable solution.

    Read the article

  • User cannot Add or Remove people from a distribution list using outlook.

    - by Matt
    Recently we moved across a user and a distribution list from Exchange 2003 to 2010. The user used to be able to add and remove from a distribution list within Outlook. I have added them to the Managed by list in Exchange in the distribution list, but to no avail. They are getting an error message saying You do not have the sufficient permissions to perform this operation on this object. I cannot seem to find the setting to allow the user permissions.

    Read the article

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