w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Deserializing List of objects yields empty list
Ok, I've reimplemented your solution in C#, and what makes the difference is the fact that you didn't provide the namespace for TaskRequests in MobileRequest class. To summarize: 1) You mix attributes for DataContractSerializer and XmlSerializer which makes this code hard to manage, I've used only XmlSerializer related attributes. 2) The XML you've provided cannot be the result of serializing the classes you've presented. It contains "MyNameSpace" on TaskReqests field, whereas in your code there are no namespaces for XmlSerializer (only for DataContractSerializer which is not relevant here). 3) The minimal fix of your code to make XML you've given deserialize correctly (see edit below) is: [Serializable] public class MobileRequest { [XmlArray(Namespace="MyNameSpace")] //note the n

Categories : Xml

Passing whole object instance (that contains an empty List) from View -> Controller results in List.Count==1 in Controller
Use explicit for loop instead of a foreach loop, and reference your elements by their index Have a look at this: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx It's a bit old but still applies.

Categories : Asp Net Mvc

Deserialize an empty list in Web Services
This blog posting gives examples of how the JAXB XmlElementWrapper is supposed to work. According to it, what you have written should give you an empty collection; see "Mapping #3". So I think that the real problem is somewhere else. Maybe the schema does not allow the list to be empty. Maybe the input XML is not what you think it should be.

Categories : Java

When I access a list on an object it incorrectly returns as empty list
You replace the neighbours parameter with an empty list def __init__(self, (x,y,z), n, radius, neighbours): neighbours = [] # <- HERE self.neighbours = neighbours Remove that line, and you should be able to access the neighbour list.

Categories : Python

How to use a case class to deserialize an array of json objects to List[Map[String,String]]
As I replied to you on the Salat mailing list, Salat doesn't support deserializing nested collections right now. https://github.com/novus/salat/wiki/Collections

Categories : Scala

Failed to deserialize an object with List using Gson
I tried your example with this: public static void main(String[] args) { String s = "{"avgEngLength":[{"time":1378905300000,"total":0},{"time":1378906200000,"total":2,"sum":130000,"avgLen":65000.0}]}"; Gson gson = new GsonBuilder().create(); Api a = gson.fromJson(s, Api.class); System.out.println(a); } and it worked (pay attention that your string in example has no escaped quotes). Api [avgEngLength=[ApiData [time=1378905300000, total=0, sum=null, avgLen=null], ApiData [time=1378906200000, total=2, sum=130000, avgLen=65000.0]]] So my best guess it that your team is working with different versions of the library. I'm using Gson 2.2.4 and I checked the source code: that error string is not present in the library.

Categories : Java

Deserialize JSON string - list/array
This JSON looks badly designed. If you can have multiple children, it should be an array, such as: { "id":"123", "result": [ { "children_id": "0", "name": "some name" }, { "children_id": "1", "name": "some other name" } ] } If you have control over the JSON generation, change that (your current C# code would work in deserialization). If you don't, you are better off deserializing that to a dictionary, which would make your RootObject look like this: public class RootObject { public string id { get; set; } public Dictionary<int, Data> result { get; set; } }

Categories : C#

Jackson deserialize JSON object field into single list property
Jackson does not contains any XPath feature but you can define converter for each property. This converter will be used by Jackson to convert input type to output type which you need. In your example input type is Map<String, Object> and output type is List<String>. Probably, this is not the simplest and the best solution which we can use but it allows us to define converter for only one property without defining deserializer for entire entity. Your POJO class: class MyProfileDto { @JsonDeserialize(converter = SkillConverter.class) private List<String> skills; public List<String> getSkills() { return skills; } public void setSkills(List<String> skills) { this.skills = skills; } } Converter for List<String> s

Categories : Java

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

Using C# LINQ to concat a filtered List to List
If names is empty, what you're meant to do is this: var names = businessNames.Select(item => item.Name).ToList(); Another option is to use the List<T>'s ConvertAll method, like so: var names = buisnessNames.ConvertAll(item => item.Name); However, if it may be not empty, you'd need to use an if statement too: var names = new List<string>(); //some code if (names.Any()) names.AddRange(/*your selected method*/); else names = //your selected method;

Categories : C#

How to parse String List into List using Gson
Your getGenericClass() won't work, you need to retrieve the class of T. You can provide it : Class<T> type; public Class<T> getType() { return this.type; } or get it at runtime (unsafe, you can find many post on this subjet I think) public Class<T> getType() { return (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; } Then to build the list token you can use this code : static TypeToken<?> getGenToken(final Class<?> raw, final Class<?> gen) throws Exception { Constructor<ParameterizedTypeImpl> constr = ParameterizedTypeImpl.class.getDeclaredConstructor(Class.class, Type[].class, Type.class); constr.setAccessible(true); ParameterizedTypeImpl paramType = cons

Categories : List

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

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#

Object Attribute as List
You must have a bug elsewhere in your script. The attrgetter works just fine for both strings and lists: >>> from operator import attrgetter >>> class Book: def __init__(self, author): self.author_split = author.split() self.author_first = self.author_split[0] self.author_last = self.author_split[1] def __repr__(self): return 'Book(%r)' % ' '.join(self.author_split) >>> books = Book('Stephen King'), Book('Dean Koontz') >>> sorted(books, key=attrgetter('author_first')) [Book('Dean Koontz'), Book('Stephen King')] >>> sorted(books, key=attrgetter('author_last')) [Book('Stephen King'), Book('Dean Koontz')] >>> sorted(books, key=attrgetter('author_split')) [Book('Dean Koontz'), Book('Stephen King')

Categories : Python

How do I convert a Map of > into a Map of >?
It sounds like you want to group a List to a Map. You haven't provided enough detail to solve your particular problem. Here's a generic utility method: public interface GroupingExpression<T, U> { T groupBy(U item); } public static <T, U> Map<T, List<U>> group(List<U> list, GroupingExpression<T, U> groupingExpression) { Map<T, List<U>> groupedMap = new LinkedHashMap<T, List<U>>(); for(U item : list) { T key = groupingExpression.groupBy(item); List<U> keyedList = groupedMap.get(key); if(keyedList == null) { keyedList = new ArrayList<U>(); groupedMap.put(key, keyedList); } keyedList.add(item); } return groupedMap; }

Categories : Java

Bind an empty object list
Why not check that selectedItems is not null? @if (Model.selectedItems != null && Model.selectedItems.Count() > 0) { @Html.TextBoxFor(m => m.selectedItems[0].id) }

Categories : C#

Trying to fill a List> with reflection is always empty
Try to add BindingFlags.Instance to the binding flags filter: BindingFlags.Public | BindingFlags.Instance. More on binding flags can be found here.

Categories : C#

C# DataContractSerializer - Deserialize list of list
If you drop this part of the code everything works as expected: [OnDeserialized] internal void OnSerializingMethod(StreamingContext context) ListOfTwo = new List<Two>(); } If you wish to make sure you always have an empty ListOfTwo change it to: [OnDeserialized] internal void OnSerializingMethod(StreamingContext context) { if(ListOfTwo == null) { ListOfTwo = new List<Two>(); } } I ran the code with a small modification (not reading from file) string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?> <RootLevel> <!--Container--> <ListOfOne> <!--List of One --> <One> <ListOfTwo> <!--List of Two --> &

Categories : C#

'list' object has no attribute 'colliderect'
I believe in your update function you need to construct a pygame.Rectout of self.rect because map returns a list type. Right now, you are trying to call a method of a pygame.Rect on a list object, which certainly will not work. I don't know what your alg.w_avg function returns, so you may have to do something more complicated than a simple cast, but I believe that is the source of your problem. A potential solution is (if alg.w_avg returns something 'nice' enough to be easily allow a Rect to be constructed from it) : self.rect = Rect(map(alg.w_avg, zip(self.rect, self.dest_vector))) Edit: Seeing your w_avg method, I believe what you are going to want to do is self.rect.topleft = map(alg.w_avg, zip(self.rect, self.dest_vector)) or some other location (center, etc.) on self.re

Categories : Python

Why can't pickle a list that is an attribute of an object?
It is definitely possible to pickle List objects within Python. It is possible that the custom class you are using may have overridden the __getstate__ and __setstate__ methods, where-in the developer has decided not to pickle the widget list by deleting it from the set of attributes to be pickled/un-pickled for that class. Refer here for more information. It would be good if you can observe the source code for this custom class and check if this indeed the case

Categories : Python

Get the object with the max attribute's value in a list of objects
max() takes a key parameter, a function that when passed one of the objects returns the value by which to compare them. Use operator.attrgetter() to get that value: from operator import attrgetter max(self.allPartners, key=attrgetter('attrOne')) This returns the matching object for which that attribute is the maximum. If you wanted to store just that maximum value itself, you have two options: Take the attribute from the returned object: max(self.allPartners, key=attrgetter('attrOne')).attrOne Pass just the attributes instead to max() with a generator expression: max(p.attrOne for p in self.allPartners) If you find that you need to order the One classes in various directions by the same attribute again and again (to find the minimum, maximum, sort them, etc.) you may want to m

Categories : Python

Deserializing string list with " " results in empty string
You'll need to use the XmlReader and XmlWriter classes or the DataContractSerializer. See: How to keep XmlSerializer from killing NewLines in Strings? public static string XmlSerialize<T>(T objectToSerialize) { XmlSerializer s = new XmlSerializer(typeof(T)); var settings = new XmlWriterSettings { NewLineHandling = NewLineHandling.Entitize }; using(var stream = new StringWriter()) using(var writer = XmlWriter.Create(stream, settings)) { s.Serialize(writer, objectToSerialize); return stream.ToString(); } } public static T XmlDeserialize<T>(string serializedObject) { XmlSerializer s = new XmlSerializer(typeof(T)); using(var stream = new StringReader(seria

Categories : C#

Python print string just above empty string in a list
Is this considered a list of lists, or strings within a list? This is a list of list. [ [element], [element], [element], [element], ] A list of strings would be this: [ 'element', 'element', 'element', 'element', ] I have tried a for loop but that seems to just bypass the empty strings and only lists the zip files present in the folder. Please post what you have tried so far, and the output it gives. I'll edit this answer with any corrections I can suggest.

Categories : Python

how to get or set object's attribute from a list in maya python?
Unless there is a Maya specific issue that I don't know about, there are a couple of ways to do this in Python: for myObject in myList: # directly getting and setting attribute myObject.translateY = 30.0 # set a = myObject.translateY # get # alternatively, via setattr and getattr built-in functions. setattr(myObject, "translateY", 40.0) # getter which Raises exception if myObject has no "translateY" attr: a = getattr(myObject, "translateY") # getter which supplies defaultVal if myObject has no "translateY" attr a = getattr(myObject, "translateY", defaultVal) As an aside, it is bad form to call your variable "list", as this name will shadow Python's built-in list function. Better to use something like "myList" instead.

Categories : Python

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

Python 2: AttributeError: 'list' object has no attribute 'strip'
strip() is a method for strings, you are calling it on a list, hence the error. >>> 'strip' in dir(str) True >>> 'strip' in dir(list) False To do what you want, just do >>> l = ['Facebook;Google+;MySpace', 'Apple;Android'] >>> l1 = [elem.strip().split(';') for elem in l] >>> print l1 [['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']] Since, you want the elements to be in a single list (and not a list of lists), you have two options. Create an empty list and append elements to it. Flatten the list. To do the first, follow the code: >>> l1 = [] >>> for elem in l: l1.extend(elem.strip().split(';')) >>> l1 ['Facebook', 'Google+', 'MySpace', 'Apple', 'Android'] To do the second, use itertools.

Categories : Python

A xs:attribute accept a predefined list and any other string value
There's no point in having a specific list of values if you also accept any other value as valid too. Let's imagine you are a schema validator, trying to validate whether a value correctly matches this type. You could go through the predefined list looking for a match, but what happens when the value isn't in that list? You accept it anyway, because the schema considers any other string value to be valid too. So there was really no point in checking the list. Just make the type xs:string or xs:token and leave it at that. Now Michael Kay had made the argument that a more complex data type (a union of your enumeration with a string) might still be of some use if you're using the schema for data typing. Such a schema might look something like this (just showing the contents of the xs:list

Categories : Xml

String List doesnt save values and keeps being empty
I would rather call the dbSet.add method when the object is new and the dbSet.attach method when the object already exists. Like this _dbset.Add(entity); //object is new (create) _context.SaveChanges(); Or _dbset.Attach(entity); //object already exists in the dbset (update/modify) _context.Entry(entity).State = EntityState.Modified; _context.SaveChanges(); I suppose you are using EF. Btw, why are you using 'virtual List Tag'. How is this saved to the database? In a separate table? Did you already check if the date was added to the table? Kr

Categories : Asp Net Mvc

Add empty string to Parameter List for Insertion into AccessDB
change this public int InsertValues(Customer customer) { this.dbConn.Open(); //System.Data.OleDb.OleDbConnection this.query = "INSERT INTO someTable (ContactFirstName, ContactLastName, Email, Phone) VALUES (@ContactFirstName,@ContactLastName,@Email,@Phone)"; this.dbComm = new OleDbCommand(this.query, this.dbConn); //System.Data.OleDb.OleDbCommand //Add parameters this.dbComm.Parameters.AddWithValue("@ContactFirstName", customer.ContactFirstName); this.dbComm.Parameters.AddWithValue("@ContactLastName", customer.ContactLastName); this.dbComm.Parameters.AddWithValue("@Email", customer.Email); this.dbComm.Parameters.AddWithValue("@Phone", customer.Phone); this.dbComm.ExecuteNonQuery(); //--Snip-- }

Categories : C#

Removing empty list elements from a sql coalesce string
YOU got the result because [tb_groups].[f_member_id_creator], maybe, the empty instead of null. Try this: coalesce(NULLIF(LTRIM(RTRIM(cast([tb_groups].[f_member_id_creator] as varchar))), '') + ',', '') + ... If you agree that you haven't trailing and/or leading spaces you can omit LTRIM/RTRIM.

Categories : Sql Server

How to deserialize JSON data which sometimes is an empty array and sometimes a string value
Writing a custom JsonConverter for a primitive type is pretty straghtforward: using System; using Newtonsoft.Json; namespace So17171737_ArrayOrString { class StringOrArrayConverter : JsonConverter { public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { switch (reader.TokenType) { case JsonToken.String: case JsonToken.Null: return reader.Value; case JsonToken.StartArray: reader.Read(); if (reader.TokenType != JsonToken.EndArray) throw new JsonReaderException("Empty array expected."); return ""; } throw new JsonReade

Categories : C#

Attribute that returns a single object from a List inside the same class
You can OrderByDescending then get the first item: return CourseStatusList.OrderByDescending(s => s.InsertDate) .FirstOrDefault();

Categories : C#

Will ifndef always work on an object-like macro defined with an empty replacement-list
No, it doesn't. The replacement list may well be empty. #define FOO means that defined FOO is true, but FOO is replaced with nothing. Example: #define FOO #define BAR 1 #if defined FOO && defined BAR int a = FOO + BAR ; #endif Result of preprocessing: int a = + 1 ;

Categories : C

Why is first text view in list empty when populating the list from SQLite Database?
Try this: Cursor data = database.query("notes", fields, null, null, null, null,null); data.moveToNext(); dataSource = new SimpleCursorAdapter(this, R.layout.highscores, data, fields, new int[] { R.id.first }, 0); Does it works? Remember to add 0 as last parameter to use the non deprecated method.

Categories : Android

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

why list slices in right-to-left direction returns empty list?
Remember that indexes start at 0: sample_list = [1,2,3,4,5,6,7] # 0 1 2 3 4 5 6 When you do sample_list[-2:2], you're trying to get the second last element to the third element. But you can't just go from negative to positive (unless you add in a negative step). If you wish to obtain a reversed list, then add a step: >>> print sample_list[2:-2][::-1] [5, 4, 3] This is the same problem with your second example. You're trying to go backwards with negative indicies, but you can't... unless... you add in a negative step!: >>> print sample_list[-3:-7:-1] [5, 4, 3, 2]

Categories : Python

python dictionary error AttributeError: 'list' object has no attribute 'item'
result = sorted(result.iteritems(), key=operator.itemgetter(1)) result is not a dictionary anymore. If I am not mistaken, your problem can be solved this way (assuming lines comes from somewhere): result = sorted({(calculate_score(line), line) for line in lines}) print(result[:20]) Take a look at OrderedDict for making an ordered dictionary.

Categories : Python

Sort a list of queryset objects from different models by the date_created attribute of object
I think you should replace this code object_list.append(model.objects.order_by('-date_created').all()) with this code : object_list.append(model.objects.all().order_by('-date_created')) And I think you don't need to use this code object_list = sorted(object_list, key=attrgetter('date_created')) Because you've sorted already using "order by"

Categories : Django

How to ignore a list mapping when the list is empty but not null?
I wrote this extension, hope it helps! public static void MapListIfNotEmpty<TSource, TMapFrom>(this IMemberConfigurationExpression<TSource> map, Func<TSource, IEnumerable<TMapFrom>> mapFrom) { map.Condition(src => !mapFrom(src).IsNullOrEmpty()); map.MapFrom(mapFrom); } and you can use it like this: Mapper.CreateMap<Model.Event, DataContracts.Event>() .ForMember(des => des.Divisions, e => e.MapListIfNotEmpty(source => source.Geographies));

Categories : C#

Take parameter, determine if its an object or list<>; if list<> then loop and treat each item as object
You could do something like this: public static Dictionary<string, object> Pick(object obj, Array Picklist) { Dictionary<string, object> dic = new Dictionary<string, object> (); IEnumerable items = obj as IEnumerable ?? new[] { obj }; foreach(string key in Picklist) { foreach(object item in items) { dic.Add(key, item.GetType().GetProperty(key).GetValue(item, null)); } } return dic; } Note however, this will fail if you actually try to provide two or more items, since it will attempt to add the same key to the dictionary twice. It will also fail if you try to pass an object which doesn't have one of the specified properties. It's unclear exactly what you want this method to do in these cases, but this code s

Categories : C#



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