w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Find duplicate items in list based on particular member value
How can I find duplicate items in list based on particular value and group the duplicated items together? Sounds like GroupBy to me. You've already done that grouping in the code in the question - you just need to use the results. The result of GroupBy is a sequence of groups where each group is a key and a sequence of values sharing that key. For example: foreach (var group in Customers.GroupBy(x => x.emailaddress)) { Console.WriteLine("Customers with email address {0}", group.Key); foreach (var customer in group) { Console.WriteLine(" {0}", customer.Name); // Or whatever } }

Categories : C#

Dynamic drop down list - SelectedValue which is invalid because it does not exist in the list of items
You have set the SelectedValue to -1 which must exist. Don't confuse it with the SelectedIndex where -1 indicates that nothing should be selected. So i assume that you actually want: ' ... modelDD.Items.Clear() modelDD.SelectedIndex = -1 ' instead of SelectedValue = -1 ' ...

Categories : Asp Net

Removing class of nested list elements based off click on outer list element?
You need this on click of A- $(this).closest('ul').find('li.active').removeClass('active'); $(this).closest('li').addClass('active') Demo -------> http://jsfiddle.net/NrGGz/

Categories : Javascript

Linq how to query a list of items for a combined list of a child collection based on a property of the parent item
You may just want to group the invoice headers by the group: var groups = invoiceHeader.GroupBy(ih => ih.Group); Then you can access the lines of the groups: foreach(var group in groups) { Console.WriteLine("Group " + group.Group); Console.WriteLine("Lines:"); Console.WriteLine(string.Join(", ", group.SelectMany(h => h.InvoiceHeader.InvoiceLines))); } Output would be something like Group A Lines: invoice1, invoice2, invoice3, invoice4 Group B Lines: invoice5, invoice6, invoice7, invoice8

Categories : C#

Removing list items in C# / XNA
Removing an item from the iterating list decrement the count therefore: for(int i=rocketPosition.Count; i > 0 ; i--) { rocketPosition[i] = new Vector2(rocketPosition[i].X, rocketPosition[i].Y - rocketSpeed); Vector2 smokePosition = rocketPosition[i]; smokePosition.X += Rocket.Width / 2 + smokeTexture.Width / 2 + randomizer.Next(10) - 5; smokePosition.Y += Rocket.Height + randomizer.Next(10) - 5; smokeList.Add(new Particle(smokePosition, gameTime.TotalGameTime.Milliseconds)); if (rocketPosition[i].Y < 0 - Rocket.Height) { rocketPosition.RemoveAt(i); } } for(int i = smokeList.Count; i > 0 ; i--) { if (smokeList[i].Time < gameTime.TotalGameTime.Milliseconds - smokeDuration) { smokeList.RemoveAt(i); } }

Categories : C#

Removing matching items from a list?
You will need to iterate over that player's cards: if any(card[1] == target_card for card in pHands[target_player]): Or pick a better data structure for the cards, like a named tuple.

Categories : Python

Removing items from a list when a condition is met
Iterate backwards in a For loop instead of a Foreach loop for(int i = download.Count; i >= 0; i--) { if (download[i].queryComplete()) { // if download is no longer in progress it is removed from the list. download.RemoveAt(i); } }

Categories : C#

Removing sequential repeating items from List using linq
check if last of new list and current item is not same then add to new list: List<string> results = new List<string>(); results.Add(array.First()); foreach (var element in array) { if(results[results.Length - 1] != element) results.Add(element); } or using LINQ: List<int> arr=new List<int>(){1, 2, 3, 4, 4, 4, 1, 1, 2, 3, 4, 4 }; List<int> result = new List<int>() { arr.First() }; arr.Select(x => { if (result[result.Length - 1] != x) result.Add(x); return x; }).ToList(); Do have proper validation for null object.

Categories : C#

How do I append list items
  • from an Unordered list
  • var lists = { numbers: [], AH: [], IP: [], QZ: [] }; $('.brand').each(function () { var letter = $.text(this).substr(0, 1); if ( /d/.test(letter) ) { lists.numbers.push(this); } else if ( /[a-h]/i.test(letter) ) { lists.AH.push(this); } else if ( /[i-p]/i.test(letter) ) { lists.IP.push(this); } else if ( /[q-z]/i.test(letter) ) { lists.QZ.push(this); } }); $('.brand-directory-list-num').append( lists.numbers ); $('.brand-directory-list-ah').append( lists.AH ); $('.brand-directory-list-ip').append( lists.IP ); $('.brand-directory-list-qz').append( lists.QZ ); Here's the fiddle: http://jsfiddle.net/q697n/ If you want to make the code a little DRYer, you can store the regular expressions in a map objec

    Categories : Javascript

    Knockout mapping from multiple sources into a single list without removing unlisted items
    What's stopping you from using a Computed Observable to produce this behavior? ko.mapping.fromJS(listA,mapping,vm.listA); ko.mapping.fromJS(listB,mapping,vm.listB); vm.mergedList= ko.computed(function(){ return listA().concat(listB()); });

    Categories : Javascript

    Iterating through a list of elements and removing the cursor style on them based on inner text
    The line: var planLinks = $('.status-progress, .plan-name a'); ...will select all such anchor elements, not just the ones related to the current iteration of the .each() loop. One way to get just the related ones is: var planLinks = $(this).closest("div").find("a"); That is, use DOM traversal methods to find the containing div and then select the anchors within it. Or you could go based on siblings, etc., but that is more fragile since a change to the html structure is then more likely to require a change to the JS. But you don't really need the .each() loop if you do something like this instead: $("a.status-progress:contains('in progress')") // find the 'in progress' anchors .closest("div") // get their containing divs .find("a")

    Categories : Javascript

    jQuery replacing list items with different list items with specific classes
    You don't have to use .load there, If, classes are already there, you don't have to do anything - Simply remove this Line $(this).load("li a.add-this-list-on-click-instead > *").fadeIn("slow"); and if .add-this-list-on-click-instead are hidden initially - then just make it visible with this - $("#dynamic").click(function() { $this = $(this); var refreshId = setInterval(function() { $('.remove-this-list-on-click').fadeOut("slow", function () { $this.find("a.add-this-list-on-click-instead").fadeIn("slow"); }); }); });

    Categories : Jquery

    Adding Sharepoint 2010 List Items to a List with external Items
    One option is to create an SQL server trigger. This trigger would fire whenever a new sales order is created in your source database. You could make it a CLR trigger, and in the function make use of the SharePoint client interface. After you provided a clearer description of the problem: I believe that you're looking for something like the list event handler. This will run on the events you care about, and you can pull from the database at the appropriate time. Essentially, you need to make a Visual Studio SharePoint project (from my past experience this method requires you to use VS right on the SharePoint server, or else you have to copy a lot of DLLs manually from the server); and make an event receiver.

    Categories : SQL

    Find list index of list items within other list items
    Maybe something like?: my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456'] things_to_find = ['abc', 'def'] for n, e in enumerate(my_list): for m in things_to_find: if m in e: print '%s is in %s at %s' % (m, e, n) Output: abc is in abc-123 at 0 def is in def-456 at 1 abc is in abc-456 at 3

    Categories : Python

    select items from a list based on length of the item
    You want to take an iterative approach, really. Your code can be replaced with a list comprehension: invalidLengthNumbers = [num for num in returnNumbers if len(num) < 7 or len(num) > 24] or, shorter and only taking one len() call by taking advantage of comparison chaining: invalidLengthNumbers = [num for num in returnNumbers if not 7 <= len(num) <= 24] but that'll only be marginally faster. If you need to loop over invalidLengthNumbers later, don't use an intermediary list. Loop and filter over returnNumbers directly. Perhaps even returnNumbers itself can be replaced by a generator, and filtering that generator can be done iteratively too. def produceReturnNumbers(): for somevalue in someprocess: yield some_other_value_based_on_somevalue from itertools im

    Categories : Python

    Selecting items from sharepoint list based on IDs using rest
    This article is excellent regarding how to use filters: Basically you want to perform an OR-Query, like this: /_vti_bin/listdata.svc/Absences?$select=AbsenceDate,AbsenceTime&$filter=(Id%20eq%20'67')%20OR%20(Id%20eq%20'68')

    Categories : Rest

    Merge nested list items based on a repeating value
    Quick stab at it... use itertools.groupby to do the grouping for you, but do it over a generator that converts the 2 element list into a 3 element. from itertools import groupby from operator import itemgetter marker_array = [['hard','2','soft'],['heavy','2','light'],['rock','2','feather'],['fast','3'], ['turtle','4','wet']] def my_group(iterable): temp = ((el + [''])[:3] for el in marker_array) for k, g in groupby(temp, key=itemgetter(1)): fst, snd = map(' '.join, zip(*map(itemgetter(0, 2), g))) yield filter(None, [fst, k, snd]) print list(my_group(marker_array))

    Categories : Python

    iterate through ListView and delete list items based on their content
    I'm not sure you understand how ListView works. A ListView is the visual representation of the data in your adapter, so you should never try to edit, add or delete views of a ListView directly, but instead edit the data and then call notifyDataSetChanged() on your adapter. The ListView will then check for changes in your adapter's data and refresh the views accordingly. For your specific problem, it means that you should work directly with mPendingItemList, find the items that have a specific content, remove them and then call notifyDataSetChanged().

    Categories : Android

    How to loop over the items of multiple list simultaneously based on the indices
    You're looking for itertools.product: >>> from itertools import product >>> animal = ['dog','cat'] >>> number = [5,45,8,9] >>> color = ['yellow','blue','black'] for i,p in enumerate(product(animal, number, color),1): print "{}. {}".format(i,str(list(p))) ... 1. ['dog', 5, 'yellow'] 2. ['dog', 5, 'blue'] 3. ['dog', 5, 'black'] 4. ['dog', 45, 'yellow'] 5. ['dog', 45, 'blue'] 6. ['dog', 45, 'black'] 7. ['dog', 8, 'yellow'] 8. ['dog', 8, 'blue'] 9. ['dog', 8, 'black'] 10. ['dog', 9, 'yellow'] 11. ['dog', 9, 'blue'] 12. ['dog', 9, 'black'] 13. ['cat', 5, 'yellow'] 14. ['cat', 5, 'blue'] 15. ['cat', 5, 'black'] 16. ['cat', 45, 'yellow'] 17. ['cat', 45, 'blue'] 18. ['cat', 45, 'black'] 19. ['cat', 8, 'yellow'] 20. ['cat', 8, 'blue'] 21. ['cat', 8, 'bl

    Categories : Python

    Adding items to a list based on a reference to parent item
    I think you're overcomplicating things a bit. You can do a simple loop through the original posts collection, and add in what you need easily by using: foreach(var a in aposts.OrderByDescending(p => p.CreatedOn)) { parcels.Add(a); parcels.Add(bposts.Where(b => a.ID == b.RecipientID).OrderByDescending(p => p.CreatedOn)); } UPDATE Taking into account the fact that you want to loop through each bpost reply to get any other replies to it, I've written an iteration method that will loop until all parent -> children -> grandchildren -> etc. are resolved. This should get everything you want based upon created on field. foreach(var a in aposts.OrderByDescending(p => p.CreatedOn)) { parcels.Add(a); foreach(var b in bposts.Where(bpost => bpost.RecipientID == a.ID

    Categories : C#

    Select items from a List where the children contain the items from another List using LINQ
    If you want to return all the products which has all the provided categories in its Categories which means it selects product where it has category1 AND category2. Then you need to use the All with the combination of Contains: public List<Product> FilterProducts(List<Category> categories) { return products.Where(p => categories.All(c => p.Categories.Contains(c)) .ToList(); } If you want to return all the product where it has it least one cetegory from the provided categories which means it selects product where it has category1 OR category2. Then you need to use Any public List<Product> FilterProducts(List<Category> categories) { return products.Where(p => categories.Any(c => p.Categories.Contains(c)

    Categories : C#

    Print search term that does not exist in list comprehension of a list comprension
    You could try this, which is a bit more of a pythonic version of your loop and conditional: import re resourceProperties = 'test test token test' rpAttrs = [['ajgagag', 'knkagga'], ['token', 'knkagga'], ['ajgagag', 'knkagga']] print(' '.join(value[0] for value in rpAttrs if not list(re.finditer(value[0], resourceProperties)))) This outputs: ajgagag ajgagag

    Categories : Python

    Sort list of dictionary items based on custom comparator in python
    Erm... byfirst = sort(somedict.values(), key=operator.itemgetter(0)) bysecond = sort(somedict.values(), key=operator.itemgetter(1)) Binary comparators are deprecated in 2.x, and removed in 3.x.

    Categories : Python

    Dynamically change the row height in a listview based on number of list items
    To set your ListView to fill the entire space allotted, you can set the listView attribute in XML: android:fillViewport=”true” Or in code: myListView.setFillViewport(true); If you want to change the size of a cell, you can calculate the ViewParams to set. For example, for a single cell, you can use: AbsListView.LayoutParams params = new AbsListView.LayoutParams(AbsListView.LayoutParams.FILL_PARENT, AbsListView.LayoutParams.FILL_PARENT); v.setLayoutParams(params); For n cells, you can calculate the vertical size based on the size of your ListView: int n = /* number of cells */ 3; int height = (myListView.getBottom() - myListView.getTop()); AbsListView.LayoutParams params = new AbsListView.LayoutParams(AbsListView.LayoutParams.FILL_PARENT, height/n); v.setLayoutParams(params);

    Categories : Android

    Create an algorithm to alternate list items based on item type
    I don't know how much can this be performing, but should be functional: Create an array of array in which you put the element of group I in array[i][j], so you should have something like array[0]: Group1, Group3, Group4, Group5 array[1]: Group2, Group2 array[2]: Group3 then save for each array an index that points to the element just added Finally, cycle between your row of array and the "columns", making an index restart from 0 when you reach the end of a sub-array. It's not beautiful but should work fine. Sorry for my english, I hope you'll understand :)

    Categories : C#

    How to create a new list out of an existing list by removing duplicates and shifting values?
    the simplest way i can see is the following: >>> from collections import OrderedDict >>> d = OrderedDict() >>> for (k, v) in [(12, "AB"), (12, "AB"), (12, "CD"), (13, None), (13, "DE"), (13, "DE")]: ... if k not in d: d[k] = set() ... d[k].add(v) >>> d OrderedDict([(12, {'AB', 'CD'}), (13, {'DE', None})]) or, if you want lists (which will also keep the value order) and don't mind being a little less efficient (because the v not in ... test has to scan the list): >>> d = OrderedDict() >>> for (k, v) in [(12, "AB"), (12, "AB"), (12, "CD"), (13, None), (13, "DE"), (13, "DE")]: ... if k not in d: d[k] = [] ... if v not in d[k]: d[k].append(v) >>> d OrderedDict([(12, ['AB', 'CD']), (13, [None, 'DE'])]) and f

    Categories : Python

    How to split a list into a list of lists by removing a specific separation(Haskell)
    I will try to help you develop the understanding of how to develop functions that work on lists via recursion. It is helpful to learn how to do it first in a 'low-level' way so you can understand better what's happening in the 'high-level' ways that are more common in real code. First, you must think about the nature of the type of data that you want to work with. The list is in some sense the canonical example of a recursively-defined type in Haskell: a list is either the empty list [] or it is some list element a combined with a list via a : list. Those are the only two possibilities. We call the empty list the base case because it is the one that does not refer to itself in its definition. If there were no base case, recursion would never "bottom out" and would continue indefinitely!

    Categories : List

    Remove duplicate items from list if certain properties match and get the top item based on some ordering
    The simplest way to group on multiple properties is to use an anonymous type: var groups = users.GroupBy(user => new { Name, Type, SubType, }); This works because the implementation of anonymous types is such that they override the Equals method to compare the values of each member of the type, and also overrides the GetHashCode method to make it a composite hash of the hashes of all of the values of the object. If you just created a new named type you would need to handle all of that yourself, which is simply tedious.

    Categories : C#

    Member list omit Admin Account from List
    Just update your query: $q = "SELECT username,userlevel,email,timestamp " ."FROM ".TBL_USERS." where userlevel<>'Admin' ORDER BY userlevel DESC,username"; If you use PDO library: ... $adminLevel = 'Admin'; $q = "SELECT username,userlevel,email,timestamp " ."FROM ".TBL_USERS." where userlevel <> ? ORDER BY userlevel DESC,username"; $statement = $database->prepare($q); $result = $statement->execute(array($adminLevel)); ... // Go on with the rest of your code

    Categories : PHP

    How to show inner content in list item outside of that list item without being covered up by descending list items
    You must set the z-index of the clicked 'li' higher and in return the former clicked 'li' back. Here is the example: fiddle And here the script: var oldli; $('li').click( function(){ $(oldli).toggleClass('displayNone displayBlock'); $(oldli).css("z-index","1"); $(this).toggleClass('displayBlock displayNone'); $(this).css("z-index","5"); oldli=$(this); } );

    Categories : Javascript

    Linq - How to select items from a list that contains only items of another list?
    This returns the items which all states are in stateList, I think that that's what you need: Items.Where(x => x.TestList.All(s => stateList.Contains(s.State)));

    Categories : C#

    Why do the members of my list get overwritten with the last member of said list?
    You're creating a single TblInfo object, and then changing the properties on each iteration. Your list contains lots of references to the same object. Just move this line: TblInfo CurrentTableInfo = new TblInfo(); to the inside of the first loop, and this line: ClmnInfo CurrentColumnInfo = new ClmnInfo(); inside the nested foreach loop, so that you're creating new instances on each iteration. Next: Important Make sure you understand why it was failing before. Read my article on references if you're not sure how objects and references (and value types) work in C# Use camelCased names instead of CamelCased ones for local variables Consider using an object initializer for the ClmnInfo Change your type names to avoid unnecessary abbreviation (TableInfo, ColumnInfo) Change your propert

    Categories : C#

    Counting visible list items and then applying class to nth item of that list in jQuery?
    Use $.each to iterate over the elements and then apply the logic. var $elems = $('.row-fluid ul.thumbnails li:visible'); $elems.each(function() { var $this = $(this); if($this.hasClass('span3')) { $this.filter(':nth-child(4n + 5)').addClass('span-left'); } else if($this.hasClass('span4')) { $this.filter(':nth-child(3n + 4)').addClass('span-left'); } else if($this.hasClass('span6')) { $this.filter(':nth-child(2n + 3)').addClass('span-left'); } });

    Categories : Jquery

    conditionally adding multiple items to a list of lists via python list comprehension
    The line html = BeautifulSoup(urllib2.urlopen('http://domain.com').read(), 'lxml') implies you have lxml installed, so you could use an XPath using | to pull out text or attribute values: import urllib2 import lxml.html as LH html = LH.parse(urllib2.urlopen('http://domain.com')) clean_data = [[elt for elt in tr.xpath('td/a/text() | td/a/@href | td/text()')] for tr in html.xpath('//table[@id="targeted_table"]/tr')] print(clean_data) yields [['http://domain.com', 'data 01', 'data 02', 'data 03', 'data 04'], ['http://domain.com', 'data 11', 'data 12', 'data 13', 'data 14'], ['http://domain.com', 'data 01', 'data 22', 'data 23', 'data 24'], ['http://domain.com', 'data 01', 'data 32', 'data 33', 'data 34']] You could also do it with a single call to the xpath met

    Categories : Python

    Adding checked items in a custom list view to array list in android
    initialize the "ArrayList" ArrayList<List> selectedItems; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home_page); selectedItems = new ArrayList<List>(); }

    Categories : Android

    Adding specific items from a list to a new list, index out of range error
    The simple fix is to wrap your append in a try catch statement. for item in stock_data: try: closing_prices.append(stock_data[count]) except IndexError: break print (closing_prices) count = count + 6 the reason you are getting to the error is that when you get to the 5th to the last item in the list then add 6 to it you are now out of range of the lists maximum index so to speak. Another possible solution is to use a while loop. closing_prices = [] count = 10 while count < len(stock_data): closing_prices.append(stock_data[count]) count += 6 print closing_prices

    Categories : Python

    Selenium adding items from a Web element list to a string array list
    Please try using following sample code, change xpath/data accordingly List<WebElement> resultList = _driver.findElements(By.xpath("//img[contains(@src,'tab-close.png')]/preceding-sibling::span[@class='tab-name ng-binding']")); for (WebElement resultItem : resultList){ String tabname=resultItem.getText(); if(resultItem.getText().equalsIgnoreCase("Dashboard")){ GlobalFunctions.clickOnButtonCustomised(false, _driver, By.xpath("//span[@class='tab-name ng-binding' and contains(text(),'"+tabname+"')]/following-sibling::img[contains(@src,'tab-close.png')]"), ""); } }

    Categories : Java

    Generate unique list item id for all list items in site collection
    There is no comparable feature to the documentID service for Items in general out of the box. You would have to build it using Custom code. You can create a custom ID which appends the list GUID and the OOTB item ID which is unique to every item in the site collection.

    Categories : Sharepoint

    knockoutjs - How to Create a List style app in with entry before adding list items
    You are in fact very close to making it work. The problem was that you did not define the donationAmount observable property in the main view model, which resulted in KnockoutJS failing when binding this unavailable property to the input tag. Here is the part of the code that had to be changed so that it works now: function DonationsViewModel() { var self = this; self.donationAmount = ko.observable(); // .... } and here's some little change to your HTML: <div> <select data-bind="options: availableDonations, optionsCaption: 'Please select...', value: selectedDonation, optionsText: 'label'"></select> <input data-bind="value: donationAmount"/> <button typ="button" data-bind="click: addDonation">Add Donation<

    Categories : Knockout Js

    Make check box items indent like an unorderded list inside a list?
    Without more info it's difficult to figure out what you want, but I think this may come very close. Just give the labels for the checkboxes display:block. And some cosmetics to make it look right. li label {display:inline-block; max-width:80%; vertical-align:top} See http://jsfiddle.net/MrLister/6VyL6/1 If that's not what you're after, you may have to show some code of your own.

    Categories : HTML



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