w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Creating a new nested list element that is a combination of two existing nested list elements (in R)
Here are your for loops using replicate (Note that the expression value for each replicate is the same expression you have in the assignment portion of your for loop) ## This is your inner for-loop, using replicate inds <- seq(begin, end, 10) datas <- replicate(length(inds), list('mean'=vector(mode='list',length=12),'sd'=vector(mode='list',length=12)) , simplify=FALSE) names(datas) <- inds # This is your outer loop tardis2 <- replicate(length(dataLayers), list('longName'='timeLord','units'='theDr','data'=datas) , simplify=FALSE) names(tardis2) <- dataLayers # Compare Results identical(tardis2, tardis) # [1] TRUE However, I'm not sure if lists are relaly the best structure for this. Have you considered data.frames?

Categories : R

How can I bind data from nested List<> objects to nested ListView controls?
You can bind the datasource of your inner list view to a property of the items bound to your outer listview. However, to do that the inner listview as to be in the itemtemplate of the outer listview. See the code below and note the DataSource='<%# Eval("Labels_color") %>' attribute for the inner list view. <asp:ListView ID="ListView_Orp_Results" runat="server" ItemPlaceholderID="itemPlaceholder"> <LayoutTemplate> <div id="outer_result_container"> <div id="itemPlaceholder" /> </div> </LayoutTemplate> <ItemTemplate> <div id="result_photo">...</div> <div id="result_category">...</div> <div id="result_detector">...</div> <div id="inner_result_container" runat="server"

Categories : Asp Net

nested json with jQuery: create List of nested item
Your problem is that institut is an array containing a single object, so you can reference that single object using institut[0]. This will work: $.each(data.fakultaeten, function (key, value) { var mother = "<li id='first'>" + value.name + "<ul>"; $.each(value.institut[0], function (key1, value1) { alert(key1); }); }); Here is a working example

Categories : Jquery

Sum a nested list of a nested list of a nested list of integers
Assuming that you are only using lists, this should do the trick: def sum_nested(l): s = 0 for item in l: if type(item) is list: s += sum_nested(item) else: s += item return s

Categories : Python

Initialize a List with values that are not null
Use the Enumerable.Range LINQ method to specify the number of iterations. List<MyObject> NewNames = Enumerable.Range(1,5).Select(i => new MyObject()).ToList(); The number 1 here is arbitrary, as the indexer is not used in any way.

Categories : C#

How do I initialize a list of integer arrays in C#?
When you add the temp array to the List, it is just a pointer to the array created on the heap. You need to create a new temp array for every array you add to the list. List<int[]> MyListOfArrays = new List<int[]>(); range = xlApp.get_Range("NamedRange"); values = (object[,])range.Value2; for (int i = 0; i < values.GetLength(0); i++) { int[] temp = new int[30]; // moved inside the loop for (int j = 0; j < values.GetLength(1); j++) { temp[j] = Convert.ToInt32(values[i + 1, j + 1]); } MyListOfArrays.Add(temp); }

Categories : C#

EmberJS: initialize nested model with parent model loaded by ajax
When your App.TourdatesRoute is loaded, all data from the json, will be rendered. And when you click to edit one of these loaded objects, using a link-to for example, ember is smart enough to get the already referenced object, instead of send a new request. So your url will change to: yourhost.com/tourdate/id. When you direct call this url, it will call the App.TourdateRoute model method. Because doesn't have any pre loaded data. But in your case you have a: tourdates.findBy('id', params.tourdate_id); And I can't see in any place the declaration of tourdates. I recommed you to change your TourdateRoute to TourdateIndexRoute so when transitioning to tourdates the ajax call is performed once: App.TourdatesIndexRoute = Ember.Route.extend({ model: function() { return $.getJ

Categories : Javascript

Is there a way to initialize a list of variables using an array in Java?
Nope, there is no way to do that in Java, other than the answer you already gave, which is to initialize each variable separately. However, you could also do something like: String[] array = { "hello", "world" }; final int HELLO = 0, WORLD = 1; and then use array[HELLO] or array[WORLD] wherever you would have used the variables. It's not a great solution, but, then again, Java usually is verbose.

Categories : Java

Initialize a std::ofstream in a class using initializer list
Take a look at cppreference basic_ofstream( const basic_ofstream& rhs) = delete; (5) (since C++11) It is not possible to copy construct a basic_ofstream. Possibly you are using pre-c++11 compiler and it is marked as private in the library.

Categories : C++

Initialize String List property on User Control
You can do it by other way. Add other property of type string, you can name it is as ListData. This will be in usercontrol public string ListData { get; set; } Assign string with comma separator to this property <uc1:MyListControl ID="MyListControl1" runat="server" ListData="ABC,XYZ" /> You can parse this string to List in page_load of usercontrol. protected void Page_Load(object sender, EventArgs e) { if (!string.IsNullOrEmpty(ListData)) { MyList = ListData.Split(new char[] { ',' }).ToList(); } } Now you can use this MyList as list populated with data

Categories : Asp Net

Initialize all the classes in a module into nameless objects in a list
There are at least two approaches you can take. You can get all of the subclasses of a class by calling a class's __subclasses__() method. So if your parent class is called Rule, you could call: rule_list = [cls() for cls in Rule.__subclasses__()] This will give you all subclasses of Rule, and will not limit them to the ones found in a particular module. If you have a handle to your module, you can iterate over its content. Like so: import rule rule_list = [] for name in dir(rule): value = getattr(rule, name) if isinstance(value, type) and issubclass(value, Rule): rule_list.append(value()) Unfortunately, issubclass throws TypeError if you give it an object that is not a class as its first argument. So you have to handle that somehow. EDIT: dealing with the issub

Categories : Python

Is there a way to initialize multiple variables from array or List in Scala?
How about this: scala> val numbers = List(1, 2, 3) numbers: List[Int] = List(1, 2, 3) scala> val List(hours, minutes, seconds) = numbers hours: Int = 1 minutes: Int = 2 seconds: Int = 3

Categories : Scala

Python: Split a list into nested list at points where item matches criteria
Something like this: li = [1,2,3,4000,5,6,7,8,9000,10,11,12,1300] r = [[]] # start with a list containing an empty sub-list for i in li: if i >= 2000: # start a new sub-list when we see a big value r.append([i]) else: # append to the last sub-list of r r[-1].append(i)

Categories : Python

Python: compare and find matches in a list of tuples and a nested list
Create an inverse mapping of data1 first: inverse_data1 = {v['code'][0]: k for k, v in data1} Now the rest is much simpler; you can look codes against that inverse mapping and find the corresponding name in O(1) time: data3 = [[inverse_data1[d[0]]] + d[1:] for d in data2 if d[0] in inverse_data1] Demo: >>> inverse_data1 = {v['code'][0]: k for k, v in data1} >>> [[inverse_data1[d[0]]] + d[1:] for d in data2 if d[0] in inverse_data1] [['Name1', '123456', 'name1'], ['Name2', '789012', 'name2']] Generally speaking, do not loop over range(len(somelist)) when you can just loop directly over that list. You can use the enumerate() function to add an index if you need one for other purposes. Your data1 and data2 lists are not of equal length, so you cannot just use indice

Categories : Python

How should i create datacontract for a List of class which contain nested list of classes as properties
What you have in your example is fine and will automatically serialize correctly. I recommend attributing your classes with [DataContract] and your properties with [DataMember] for explicitness.

Categories : Wcf

Get list of values from a nested Python data-structure using a list comprehension?
Try following: >>> from collections import namedtuple >>> >>> class P(namedtuple('_P', 'val back')): ... def __iter__(self): ... while self: ... yield self.val, self.back ... self = self.back ... >>> q = P(val=15, back=P(val=11, back=P(val=9, back=P(val=6, back=P(val=2, back=P(val=0, back=None)))))) >>> [val for val, back in q] [15, 11, 9, 6, 2, 0]

Categories : Python

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

Filtering out items from a list using nested list comprehensions in Python
You got the order mixed up: [sentence for sentence in sentences for word in words if banned_word not in sentence] Not that that'll work as that'll list the sentence every time a banned word does show up in the sentence. Take a look at the fully expanded nested loops version: for sentence in sentences: for word in words: if banned_word not in sentence: result.append(sentence) Use the any() function to test for banned words instead: [sentence for sentence in sentences if not any(banned_word in sentence for banned_word in words)] any() loops over the generator expression only until a True value is found; it'll stop doing work the moment a banned word is found in the sentence. This is more efficient at least.

Categories : Python

python: determine if all entries of a list are within entry of a nested list
I think One Should remember that both bool([False]) == True and bool([True]) == True so when construction [any(...)]: is used Any one can tells for sure that this statement will be True

Categories : Python

Hibernate 4 + Spring Data CrudRepository, CLI application: failed to lazily initialize a collection: could not initialize proxy - no Session
Run this code: User user = userService.findByLogin(login); categoryService.deleteByUser(user); within a single transaction like so: @Transactional public void deleteCategoriesByUser(String login) { User user = userService.findByLogin(login); categoryService.deleteByUser(user); } which will make sure the same Hibernate session is used for both operations.

Categories : Java

Why nested list indexing gets swapped with list comprehensions?
You have your loops inverted in the first version. You are creating inner tuples looping over range(len(avail)) and outer tuples with a loop over range(len(avail[i])). Your code is the equivalent (with lists instead of tuples) of this instead: outer = [] for j in range(len(avail[i])): inner = [] for i in range(len(avail)): inner.append(False if (i,j) in neighborhood else avail[i][j]) outer.append(inner) and relied on i still being assigned as a global. You can see this too when you indent your expression based on the parenthesis: return tuple( tuple( False if (i,j) in neighborhood else avail[i][j] for i in range(len(avail)) ) for j in range(len(avail[i])) ) Reverse the loops (indented differently to communicate the grouping better

Categories : Python

How to convert a nested list into a one-dimensional list in Python?
You need to recursively loop over the list and check if an item is iterable(strings are iterable too, but skip them) or not. itertools.chain will not work for [1,[2,2,2],4] because it requires all of it's items to be iterable, but 1 and 4 (integers) are not iterable. That's why it worked for the second one because it's a list of lists. >>> from collections import Iterable def flatten(lis): for item in lis: if isinstance(item, Iterable) and not isinstance(item, basestring): for x in flatten(item): yield x else: yield item >>> lis = [1,[2,2,2],4] >>> list(flatten(lis)) [1, 2, 2, 2, 4] >>> list(flatten([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) [1, 2, 3, 4, 5, 6, 7, 8, 9] Works for any

Categories : Python

Grouping a list into a nested list under a condition - Python
May be there is a prettier solution, but this works: >>> A = [1.10,1.11,1.12,1.21,1.22,1.48] >>> [A[i:i+3] for i in range(len(A) - 2)] [[1.1, 1.11, 1.12], [1.11, 1.12, 1.21], [1.12, 1.21, 1.22], [1.21, 1.22, 1.48]]

Categories : Python

Backbone render after initialize - initialize get's triggered to early?
Rather than having the div#all render and append the view to itself, you can pass it as a parent to the View: this.gameView = new Game({parent: this}); Then in your Game view: initialize: function (options) this.parent = options.parent { this.model.on('getGame', function() { this.$el.appendTo(this.parent); }); this.model.getGame(); } Alternatively you could use a global Backbone event object like this: window.vent = $.extend({}, Backbone.Events); Now you have a global object (which you can name and put in any namespace as you like, don't just do it as in the code above), that you can use like this: MAIN VIEW: initialize: function () { vent.on("GameReady", function () { // fade in game view }); } GAME VIEW: initialize: function (options

Categories : Backbone Js

Group a list of list by nested size in R
To get all nested list of length equal to 1 you can do the following: P3[lapply(P3,length) ==1] ## get all elements with size equal to 1 $`2` [1] "a" $`3` [1] "b" $`5` [1] "c" Now, We can use this to group the nested lists by their lengths. We loop(lapply) over all unique lengths, and we perform the above statement for each length : lapply(unique(unlist(lapply(P3,length))), function(x) P3[lapply(P3,length) ==x] )

Categories : R

best way to iterate list and nested list
Try using a HashTable instead of the second list. In that way, you will have a direct access to the category items, without searching for them. That makes it 2 loops, which is actually 1 over all of the items in both containers If you develop OOP, I would suggest using an object with a category and a list of items. And just creating a list of these objects instead - one loop.

Categories : List

List operation for nested list
Use a nested list comprehension: otherlist = [[(L[0], t) for t in L[1]] for L in lst] so for each element L in lst, we create a new list with tuples containing (L[0], elements of L[1]). Demo: >>> lst = [(1, [('a1', 'b1', 'c1'), ("a1'", "b1'", "c1'"), ('a1"', 'b1"', 'c1"')]), (2, [('a3', 'b3', 'c3'), ("a3'", "b3'", "c3'"), ('a3"', 'b3"', 'c3"')]), (3, [('a3', 'b3', 'c3'), ("a3'", "b3'", "c3'"), ('a3"', 'b3"', 'c3"')])] >>> [[(L[0], t) for t in L[1]] for L in lst] [[(1, ('a1', 'b1', 'c1')), (1, ("a1'", "b1'", "c1'")), (1, ('a1"', 'b1"', 'c1"'))], [(2, ('a3', 'b3', 'c3')), (2, ("a3'", "b3'", "c3'")), (2, ('a3"', 'b3"', 'c3"'))], [(3, ('a3', 'b3', 'c3')), (3, ("a3'", "b3'", "c3'")), (3, ('a3"', 'b3"', 'c3"'))]]

Categories : Python

LINQ on List with lot of nested List
LINQ expressions can have multiple nested from clauses: // nested from clauses var names = from c1 in myClass1List from c2 in c1.Class2List where c2.Name == "something" from c3 in c2.Class3List select c3.Name; For completeness, here are two variants using method syntax: var names = myClass1List .SelectMany(c1 => c1.Class2List.Where(c2 => c2.Name == "something")) .SelectMany(c2 => c2.Class3List.Select(c3 => c3.Name)); var names = myClass1List .SelectMany(c1 => c1.Class2List .Where(c2 => c2.Name == "something") .SelectMany(c2 => c2.Class3List .Select(c3 => c3.Name)));

Categories : C#

C# Nested List not adding a new list
I have the same placement for each list creation You do NOT have the same placement of creation, the AStore is created outside of the for loop, and the APages one is.

Categories : C#

how can i initialize my array when i cant initialize as null?
In Java everything is a pointer behind the scenes. So when you do mynums[]=null, you are pointing to a null. So what is null[i]? That is where your NPE comes from. Alternatively when you point it to an array, then you are actually accessing the i'th element of the array.

Categories : Java

Get to nested dictionary in list
Use a list comprehension: only_last_and_first = [d for d in L if 'firstname' in d and 'lastname' in d] Now you have a list of dictionaries that have those two keys. Demo: >>> L = [{'color':'yellow','fruit':'banana'},{'firstname':'Jack','lastname':'Black'}] >>> [d for d in L if 'firstname' in d and 'lastname' in d] [{'lastname': 'Black', 'firstname': 'Jack'}] If you only wanted the first such a dictionary, use next() and a generator expression: first = next((d for d in L if 'firstname' in d and 'lastname' in d), None) Here first will be set to either the first dictionary with the two keys, or None if there is no such dictionary. If such syntax is a little daunting, here is a version with a for loop instead: first = None for d in L: if 'firstname' in d and '

Categories : Python

Indexing a nested list
Don't bother. This is almost certainly not your bottleneck, and it's not worth the headache of managing the indexing calculations and the row length variable. Timing data: >>> timeit("a[1][2]", setup="a = [[0]*5 for _ in xrange(4)]") 0.09207810811146055 >>> timeit("a[1*5+2]", setup="a = [0]*5*4") 0.06518904043262097 >>> timeit("a[1*row_length+2]", setup="a = [0]*5*4; row_length=5") 0.11411290029380439 The flattened list won when the row length was an inlined constant, but it lost when the row length was a global variable. If you try to gain an advantage by flattening your list, you will waste a ton of time managing the indexes, and unless you do it very carefully, it may even run slower. Don't bother.

Categories : Python

get deepest nested list
Here's my solution. Your get_deepest() call was not returning anything back, so there is a logical error, and it keeps going deeper. Lst = ['o', ([], [(1, 'V'), (-1, 'C')]), ['o', ['o', (['prefers'], [(1, 'D'), (1, 'D'), (-1, 'V')]), ['o', (['the'], [(1, 'N'), (-1, 'D')]), (['beer'], [(-1, 'N')])]], ['o', (['the'], [(1, 'N'), (-1, 'D')]), (['king'], [(-1, 'N')])]]] def get_dpst(L, maxdepth): deepest_tup = (L, maxdepth) for e in L: is_list = any(isinstance(e,list) for e in L) if is_list: tup = get_dpst(e, maxdepth+1) if tup[1] > deepest_tup[1]: deepest_tup = tup return deepest_tup def get_deepest(L): tup = get_dpst(L, 0) return tup[0] def printlist(lst): print '[%s]' % ', '.join(map(str, lst)) printlist(

Categories : Python

How to index nested list?
I would suggest to do the following: Implement the IComparable interface to the type of which the objects in the lists are. This way you can store the comparison logic inside the type itself. Create a list of this type (just like the lists in posCheckOptions). Lets call it bigList iterarte over all lists in posCheckOptions iterate over each item in the contained list and check if the item is contained in bigList. If it is, delete it from the current inner list. If not add it to bigList

Categories : C#

jquery get last li of each nested list
Simply use :last-child as in CSS : $('#test ul li:last-child')

Categories : Jquery

Targeting ol li ol li ol li, nested list with css
Your html is bad, you need to put the ol in the <li> <ol> <li>Ordered List Style</li> <li>Here’s another, they shouldn’t be too terribly long, but might wrap a line or three <ol> <li>nested</li> <li>nested <ol> <li>nested</li> <li>nested</li> </ol> </li> </ol> </li> <li>Let’s talk about the benefits of this here product!</li> <li>More feature talk! This thing is super useful, you should totally buy it!</li> </ol>

Categories : HTML

Javascript nested list css
You need to stopPropagation() to prevent the event from bubbling up the listener tree: document.getElements('li').addEvents({ mouseover: function(e){ this.addClass('css_class'); e.stopPropagation(); }, mouseout: function(){ this.removeClass('css_class'); e.stopPropagation(); } });

Categories : Javascript

nested list css problems
Here: http://jsfiddle.net/eAJjs/ $('#question > li > a').click(function () { if (!$(this).hasClass('active')) { $('#question>li>ul').slideUp(); $(this).next().slideToggle(); $('#question>li>a').removeClass('active'); $(this).addClass('active'); } else { $('#question>li>ul').slideUp(); $('#question>li>a').removeClass('active'); } }); <ul id="question"> <li><a href="#">QUESTION goes here</a> <ul> <li><a href="#">ANSWER goes here></a> </li> </ul> </li> <li><a href="#">QUESTION 2 goes here</a> <ul> <li><a href="#">ANSWER 2 g

Categories : Javascript

Printing items within a list within a list, etc. (Printing nested lists)
The function has no argument called C therefore you cannot pass it a keyword argument called C. Either use directory=... instead or pass it the object as a normal argument. C = ... tree_traverse(C)

Categories : Python

How to creat a nested list from an array PHP
$array = [your existing array]; $n = array(); foreach($array as $a) { $year = $a['Award']['year']; if(!isset($n[$year])) { $n[$year] = array(); } $n[$year][] = $a['Award']; } // now you have a new array $n looking like this print_r($n); ksort($n); // sort array by key // and you can walk through it foreach($n as $year => $awards) { echo $year."<br>"; foreach($awards as $aw) { echo $aw['title']."<br>"; } }

Categories : PHP



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