w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Java generics converting Future of list of concrete class to future of list of interface?
Yes, you should do it. Suppose you have: public void doStuffWithInterface(Future<List<InterfaceClass>> f) { List<InterfaceClass> list = f.get(); list.add(new AnotherConcreteClassWhichImplementsTheInterface());// it will fail if you use "? extends" } So, it makes the list of only ConcreteClasses to contain incompatible type. Simple example: public void addStuff(List<Number> l) {l.add(1.5);} List<Integer> l = new ArrayList<>(); addStuff(l); for(Integer i : l) {}// class cast exception!

Categories : Java

Can List.Distinct() apply to the list type of List>?
That's because List<T> has no Equals and GetHashCode implemented, so standard reference comparison is being performed. And it returns false, because you have two separated lists. You can write your own IEqualityComparer<List<string>> implementation and provide it as Distinct method parameter. Within the comparer you can use Enumerable.SequenceEqual) method to check if lists has the same content.

Categories : C#

Python: given a list of lists, create a list ordered by the number of occurrences in inner list
You can use collections.Counter to keep a counter for each element inside each sublist. Something like this, >>> from collections import Counter >>> lst = [['a','b','c'], ['a'], ['a','b']] >>> counts = Counter() >>> for sublst in lst: ... for ele in sublst: ... counts[ele] += 1 ... >>> [ele for ele, _ in counts.most_common()] ['a', 'b', 'c']

Categories : Python

In a responsive site design, how do i put a list below other list that contains a sub-list without overlap the main lists
Pretty simple : remove the fixed height of your li.menulinks, add a "header" (green rounded rectangle with 35px height) div as first child of the li and...you're set ! Look at this fiddle : http://jsfiddle.net/32pga/ <div class="sitemap"> <div class="row-fluid"> <ul> <li class="menulinks"> <div class="menulinks-header"></div> <ul> <li class="submenulinks"> <div>Test 1</div> </li> <li class="submenulinks"> <div>Test 2</div> </li> <li class="submenulinks"> <div>Test

Categories : HTML

iterating list of array-list and assigning each list to single dynamically created div in jsp
Try this, <c:forEach var="user" items="${userList}" varStatus="count"> <div id="col${count}"> <c:out value="${user.name}"/> </div> </c:forEach>

Categories : Java

Why does Haskell let me return an empty list where a list inside a list is expected?
Because [] is of type [[a]] in this case: it is a list containing exactly 0 alpha lists. In general, the empty list can match any list type because every element (all zero of them) is of the correct type.

Categories : Haskell

How to modify the style in list(ordered list and unordered list) in HTML?
Here you go. WORKING DEMO The HTML: <ul style="list-style-type:decimal;"> <li>First</li> <li>Second</li> <li>Third</li> </ul> The CSS: li{ position: relative; } li:before{ position: absolute; left: -13px; content: ')'; background:white;} Hope this helps.

Categories : HTML

Unmarshall xml list of objects to java list without class list
You could use JAXB with StAX to do the following: import java.util.*; import javax.xml.bind.*; import javax.xml.stream.*; import javax.xml.transform.stream.StreamSource; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(User.class); XMLInputFactory xif = XMLInputFactory.newFactory(); StreamSource xml = new StreamSource("src/forum17047306/input.xml"); XMLStreamReader xsr = xif.createXMLStreamReader(xml); List<User> users = new ArrayList<User>(); Unmarshaller unmarshaller = jc.createUnmarshaller(); while(xsr.getEventType() != XMLStreamReader.END_DOCUMENT) { if(xsr.isStartElement() && "User".equals(xsr.getLocalName())) {

Categories : Java

Appending to create a list instead of creating a list inside a list
Use extend: for item in items: forename = re.findall(pattern2, item) surname = re.findall(pattern3, item) mainlist.extend(surname) myList.extend(L) adds the individual elements of L onto myList. It's similar to: for element in L: myList.append(element)

Categories : Python

Getting a list of values from a list of dict in python: Without using list comprehension
You could use map() here. map() applies the lambda to every item of testList and returns it as a list. >>> testList = [{'id': 1L, 'name': u'Library'}, {'id': 2L, 'name': u'Arts'}, {'id': 3L, 'name': u'Sports'}] >>> map(lambda x: x['name'], testList) [u'Library', u'Arts', u'Sports']

Categories : Python

Why does adding a list to another list, using add range, remove the elements from the first list?
It's because of the IEnumerable. When you set groupsToAdd to the result of groups1.Where(g => false == groups2.Contains(g)) there is deferred execution, which means that the query is not run until AddRange() and then again at Dump(). Because the list, groups2, now contains the elements they no longer are a result of the original query.

Categories : C#

create a list from another list and remove elements from copied list
Yes your understanding is correct. List newList = new ArrayList(collection); will do a shallow copy. You can modify the newList without affecting the original collection, but they will each reference the same elements so if you modify an element in one list, the other list's element will also get the change. This is called a Shallow Copy. Here's a visual representation of what I've described: The things at the bottom are the objects in your array.

Categories : Java

Create larger list from an existing list using a list comprehension or map()
How about: >>> atom_indices = [0, 4, 5, 8] >>> coords = [3*a+k for a in atom_indices for k in range(3)] >>> coords [0, 1, 2, 12, 13, 14, 15, 16, 17, 24, 25, 26] We can nest loops in list comprehensions in the same order we'd write the loops, i.e. this is basically coords = [] for a in atom_indices: for k in range(3): coords.append(3*a+k) Don't be afraid of for loops, though, if they're clearer in the situation. For reasons I've never fully understood, some people feel like they're being more clever when they write code horizontally instead of vertically, even though it makes it harder to debug.

Categories : Python

How to assign List or List to List
I don't think there's an easy way to do that using only strongly typed collections1, since there is no covariant collection interface that exposes a Remove method... I see 2 possible solutions: use the non-generic ICollection interface, that is implemented by List<T>: var collection = (ICollection) CouldBeBearsOrGoats; collection.Remove(whatever); The drawback is that a collection that implements ICollection<T> might not implement ICollection... use dynamic: dynamic collection = CouldBeBearsOrGoats collection.Remove(whatever); But it's probably slower than the previous approach. 1 assuming you don't want to change the actual type of the collections by casting items to IAnimal

Categories : C#

What kind of List is List list = Database.getAllData();?
You don't have to know; that's the point. The interface is what matters to you, not the implementation. You can't know without looking at the source of that method. But even if you do, it's immaterial to your client. All you call are List methods.

Categories : Java

In python, what happens, will the length of a list decrease if I add part of the list to another list?
The string "hi" will be split into chars and assigned to example when you do example+=python[0] So example in this case will contain ['h','i']. Also, the list python will not lose an element.

Categories : Python

when appending a list with math using another list, how do i make the second list the same length as the first ?
You need to iterate over each elements in start_list: for item in start_list: # for each element in `start_list` square_list.append(item ** 2) # add square of `item` in `square_list` square_list.sort(); # finally sort the list or you can use sorted() function over generator expression: >>> sorted(item ** 2 for item in start_list)

Categories : Python

List within a List - How to put new line with LinQ after List within List is over?
Console.Write( String.Join(Environment.NewLine, f.Select(flight => { var segments = flight.Segments.Where(x => x.DepartureDate > DateTime.Now); return String.Join(" ", segments.Select(segment => { return String.Format("Departure: {0}, Arrival: {1};", segment.DepartureDate, segment.ArrivalDate)); }); }); ); I personally prefer to have a Joined extension method on IEnumerable<T> which wraps String.Join (taking a delimiter and an optional transformation delegate), and a Formatted extension method on String which wraps String.Format: var output = f.Joined(Environment.NewLine, flight => flight.Segments .Where(s => s.DepartureDate > DateTime.Now) .Joined(" ", s => "Departure:

Categories : C#

ASP.NET/C#: Get nearest future date based from list of days
Like this ? public DateTime GetNextPossibleDay(DateTime DT, DayOfWeek[] PossibleDays) { if (PossibleDays.Length == 0) throw new Exception("No possible day."); do { DT = DT.AddDays(1); } while (!PossibleDays.Contains(DT.DayOfWeek)); return DT; }

Categories : C#

TSQL - Faster to use IN (list) or use NOT IN (list) for a small list?
NOT IN ('val4') is basically equivalent to WHERE NOT (column = 'val4') /* or column <> 'val4' */ whereas IN ('val1', 'val2', 'val3') is basically equivalent to WHERE ( column = 'val1' OR column = 'val2' OR column = 'val3' ) I would hope that the first option is faster, if only negligibly. The SQL engine might optimize IN differently depending on how many values you specify in the IN function and what indexes are available on your table. What behavior are you seeing that you're questioning the method to use?

Categories : SQL

Using a list as "list of indexes" to address elements of another list
You could use reduce(operator.getitem, index, mylist) Here is a complete example: import operator mylist = [[1,2,3],[4,5,6],[7,8,9]] index = [1,2] val = reduce(operator.getitem, index, mylist) print(val) For NumPy arrays, there is a simpler method: import numpy as np ... myarr = np.array(mylist) val = myarr[tuple(index)] print(val)

Categories : Python

How to get the list elements using list inside another list in java
You can try this ,Let say you have variables like double dtime; Timestamp tp; And listofresults is coming from query results. listofresults = results.getResultList(); If list is coming from query then put it in the loop this way in the condition of for loop for(int i=0;i< listofresults.size() ;i=i+2) { dtime=(double) listofresults.get(i); //cast because the value is of object type tp=(TimeStamp) listofresults.get(i+1); //cast because the value is of object type //do something with these variables }

Categories : Java

Parsing List of Strings from Scala future JSON response
This will work: response.json "data" \ "id" From the documentation of the \ operator: Lookup for fieldName in the current object and all descendants.

Categories : Json

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

Write list of list to file and then retrieve it from the file as a list of list
>>> import pickle >>> banana, beans = ['Banana' , .54 , 'No' , 'Food'], ['Beans' , 1.39, 'Yes', 'Food'] >>> food = [banana, beans] >>> with open('data', 'wb') as f: pickle.dump(food, f) >>> with open('data', 'rb') as f: print pickle.load(f) [['Banana', 0.54, 'No', 'Food'], ['Beans', 1.39, 'Yes', 'Food']]

Categories : Python

Shortest list in list of list (Haskell)
First what you have already: shortest [] = [] I actually don't like this very much because this means there is no difference between shortest [] and shortest [[]] But, if you like this behavior then Data.List has minimumBy which has the type (a -> a -> Ordering) -> [a] -> a So we first need that (a -> a -> Ordering) which we can get with compare and a useful little function called on from Data.Function. on acts like a "nozzle" of sorts and applies a function to 2 arguments before feeding them into another function. cmp = compare `on` length Which just gives us shortest = minimumBy cmp But this breaks when given an empty list so shortest [] = [] shortest ls = minimumBy cmp ls shortest [] = Nothing shortest ls = Just $ minimumBy cmp ls

Categories : List

flatten list of list through list comprehension
You're trying to iterate through a number, which you can't do (hence the error). If you're using python 2.7: >>> from compiler.ast import flatten >>> flatten(l) [1, 2, 3, 4, 5, 6, 7, 8] But do note that the module is now deprecated, and no longer exists in Python 3

Categories : Python

c# List.Contain(List) not returning true for containing list
To compare the lists, use SequenceEqual (MSDN) In your case, you can combine it with Any: var containsListToFind = parentList.Any(x => x.SequenceEqual(listToFind)); Contains won't work because it uses the default .Equals method of the objects in the list. For List<T>, that is a reference comparison, not a value comparision. Since listToFind is a different object than the one in parentList, the references are different and Contains won't find anything.

Categories : List

Python: filter list of list with another list
Use a list comprehension: result = [x for x in list_a if x[0] in list_b] For improved performance convert list_b to a set first. As @kevin noted in comments something like list(5,8)(unless it's not a pseudo-code) is invalid and you'll get an error. list() accepts only one item and that item should be iterable/iterator

Categories : Python

Make a list distinct list of a list
Try LINQ .... To be more specific... Given that your list is actually string[] you could do this... string[] list = {"a","b","a","f","a",null,"a","e","a","e"}; var distinctList = list.Distinct(); foreach (var str in distinctList)//Distinct list of values { Console.Write(str); }

Categories : C#

How to create an unordered list inside an unordered list in a list menu?
The key to getting the sub-menu working is to use the child combinator (>) to target direct descendants. A child combinator describes a childhood relationship between two elements. A child combinator is made of the "greater-than sign" (U+003E, >) character and separates two sequences of simple selectors. (http://www.w3.org/TR/css3-selectors/#child-combinators) The following changes are required: Add the .menu li ul ul setting left: 100%; and top: 0;. This will tell all sub-menus to be positioned against the right edge of its parent menu. Change .menu li:hover ul to .menu li:hover > ul. This will ensure that only the direct child ul is shown when the user hovers over the parent li. Change .menu li ul a:hover, .menu li ul li:hover a to .menu li ul li:hover > a. This will e

Categories : HTML

Java Collection: what to convert Collection> to ArrayList> or List>?
You can use the appropriate constructor: List<List<String>> yourList = new ArrayList<>(yourCollection); The order of the elements in the list is the order of the iterator of the collection.

Categories : Java

R: Test condition on column of dataframe elements within list; return smaller list
You can use this: myList <- myList[sapply(myList, function(d) max(d$values) != 0)] instead of the for() loop. This will let pass dataframes with zero rows, with a warning. To ensure empty dataframes are removed, use this: myList <- myList[sapply(myList, function(d) if(nrow(d)==0) FALSE else max(d$values)!=0)]

Categories : R

How to make a jQuery UI droppable list where elements added to the list are also drop targets
I think what you really want is a sortable for the users list and then all the draggable for the "eligible items" jQuery(function($) { $('#list2 li').draggable({ cursor: 'move', helper: 'clone', connectToSortable: "#list1", }); $('#list1').sortable({ revert: true, }); }); http://jsfiddle.net/petersendidit/gKtXa/5/

Categories : Javascript

Trying to input data from a txt file in a list, then make a list, then assign values to the lines
[] implies a list. '' implies a string. allt = ['mw91 42.927 -72.84 2.8'] allt is a list that contains a string: allt[0] --> 'mw91 42.927 -72.84 2.8' allt[0][2] --> '9' allt.split() --> ['mw91', '42.927', '-72.84', '2.8'] allt.split()[2] --> '-72.84' #This is still a string. float(allt.split()[2]) --> -72.84 #This is now a float.

Categories : Python

get a list of comma separated values in python and use that list to perform a command as many times as necessary with each value
You can use a for loop to loop over a dict object and create multiple pages. Here is a little snippet to get you started. import gdata.sites.client client = gdata.sites.client.SitesClient( source=SOURCE_APP_NAME, site=site_name, domain=site_domain) pages = {"page_1":'<b>Your html content</b>', "page_2":'<b>Your other html content</b>'} for title, content in pages.items(): feed = client.GetContentFeed() parent = None if selection is not None: parent = feed.entry[selection - 1] client.CreatePage('webpage', page_title, content, parent=parent) as for feeding your script from an external source I would recommend something like a csv file ##if you have a csv file called pages.csv with the following lines ##page_1,<b>

Categories : Python

suppose output python list as javascript list in html, but the char "'" is printed
From the docs on Filtering it would appear that $:categoriesPython might do the trick By default, Templetor uses web.websafe filter to do HTML-encoding. render.hello("1 < 2") "Hello 1 < 2" To turnoff filter use : after $. For example: The following will not be html escaped. $:form.render()

Categories : Javascript

Show SQLite data by clicking list item in a list populated by the Database
You need to change focusable mode of your TextView to false update TextView in XML android:focusable="false" lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View view, int position, long id) { data.moveToPosition(position); Toast.makeText(getApplicationContext(), c.getString(c.getColumnIndex("notes")), Toast.LENGTH_LONG).show(); speakOut(c.getString(c.getColumnIndex(BaseColumns._ID))); } });

Categories : Android

Linq expression to filter an a list of entity's collection, and maintain list of entities
var r = Foos.Select(x => new Foo() { Id = x.Id, Name = x.Name, Bars = x.Bars.Where(y => y.Age <= 25 && y.Age >= 5).ToList() });

Categories : C#

Is there a way to print out an object from a script as it would appear in the REPL? (e.g. myList: List[String] = List(Hello there, World!)
The Scala equivalent of this would be the getClass method (from Java) on java.lang.Object. For instance: scala> 1.getClass res0: Class[Int] = int scala> Nil.getClass res1: Class[_ <: scala.collection.immutable.Nil.type] = class scala.collection.immutable.Nil$ scala> "hello".getClass res2: Class[_ <: String] = class java.lang.String

Categories : Scala



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