w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Return list of interface type
The feature that makes the code break by its absence is called generic type covariance. C# does support variance in generics, but only in interfaces (not concrete classes). The foreach snippet works because it treats Fruitlist as an IEnumerable<Fruit>, and since that's a generic interface with an out (covariant) type parameter the compiler can view it as an IEnumerable<Resource>. If it's acceptable for getListOf to return an IEnumerable<Resource> then changing the function signature will make the code compile. Otherwise the compiler would not be able to guarantee type safety, because you could write this code: List<Resource> apples = this.getListOf("apple"); apples.Add(new Orange()); // adding a Resource to a List<Resource>, right? Another option would be

Categories : C#

How to sort list of locale objects in list interface using comparator in java
You are using an unmodifiable list. If you put the elements in a modifiable list it can be sorted. Otherwise you could your own sorting algorithm that put the elements in a new list. This approach could be faster. Try this instead: List<Locale> localeList = new ArrayList<Locale>(list); Collections.sort(localeList, comparator);

Categories : Java

Why does List interface extend Collection interface?
They're re-written so that they can be documented, in order to specify how the List refines the contract of these methods compared to the contract specified in the Collection interface. For example, the add() method in List is documented to specify that the element is added to the end of the list. This can't be specified in Collection, since a Collection doesn't have a beginning and an end.

Categories : Java

WCF Return list of baseclass objects containing derived class
Try adding a KnownTypeAttribute to your Animal class for each subclass you'd like to have serialized: [DataContract] [KnownType(typeof(Snake))] [KnownType(typeof(Pig))] public class Animal { }

Categories : C#

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

Cannot convert from List to List
The behavior you're describing is called covariance – if A is B, then List<A> is List<B>. However, for mutable types like List<T>, that is fundamentally unsafe. Had this been possible, the method would be able to add a new OtherDerivedClass() to a list that can actually only hold DerivedClass. Covariance is safe on immutable types, although .Net only supports it in interfaces and delegates. If you change the List<T> parameter to IEnumerable<T>, that will work

Categories : C#

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#

Inherit extended generic type from an interface
I think you want public interface ICard<T> extends Comparable<T>{ public abstract String toString(); public abstract int compareTo(T o) throws WrongCardTypeException; } (note the ICard<T>) and then PlayingCard implements ICard<PlayingCard>. That said, this interface gets you exactly nothing over the Comparable interface, since toString() is already available for all Java objects, and trying to require it will have no effect.

Categories : Java

Interface for a modifiable list
You cannot assure because the return type is Collection.What you can do is a proper doc. In terms of API design, you should just make your javadoc clear ! People who use a method without reading its doc deserve the surprise. Is it acceptable to return unmodifiableList or should I return array?

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

IList in interface, List in implementation
AddRange is not a method on IList, however Add is, so you can easily make an extension method: public static void AddRange<T>(this IList<T> list, IEnumerable<T> values) { foreach(var value in values) list.Add(value); } You could also in your extension method check if list is actually an instance of List in which case you can call AddRange directly

Categories : C#

Send List to Controller using interface?
You need to add getData logic to your repository like this(check Context Products, im not sure about it) : public class MyRepository : IProduct { public IQueryable<Product> Products { get { return MYcontext.pList; } } public IQueryable<Product> GetProducts() { return (from obj in Products select obj).FirstOrDefault(); } } And your interface namespace Uppgift_1.Models { public interface IProduct { IQueryable<Product> GetProducts(); } } And in Controller you could use it like this: public MyController:Controller { IProduct<Product> service = new MyRepository(); public ActionResult Index() { var prods = service.GetProducts(); return View(prods) ; } }

Categories : C#

How to find duplicates in a std::vector and return a std::list of them sorted alphabetically without duplicates in that resulting list
Edit In response to comment: Remove duplicates function name is misleading, it is actually trying to return a list of words that are repeating in the sequence, but that result list only has one copy of each duplicate – user2624236 10 hours ago I hinted std::sort + std::adjacent_find(... std::equal_to<>). Here's the realization of that: template <typename C, typename T = typename C::value_type> std::list<T> adjacent_search(C input) { std::sort(begin(input), end(input)); static const auto eq = std::equal_to<T>{}; static const auto neq= std::not2(eq); std::list<T> dupes; auto end_streak = begin(input); auto dupe_at = std::adjacent_find(end_streak, end(input), eq); for(auto end_streak=begin(input); (dupe_at = st

Categories : C++

Spring @RequestBody containing a list of different types (but same interface)
You should use the Jackson annotations @JsonTypeInfo and @JsonSubTypes to achieve polymorphic json. The annotations go on the Animal base class. @JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "type") @JsonSubTypes({@JsonSubTypes.Type(value = Dog.class, name = "Dog"), @JsonSubTypes.Type(value = Cat.class, name = "Cat")}) public abstract class Animal { }

Categories : Java

Get list of property names using interface method
public static List<string> GetPropertyNames(this Object o) { List<string> names = new List<string> foreach (PropertyInfo prop in o.GetType().GetProperties()) names.Add(prop.Name); return names; } Now you can implement ITablefy in terms of any object.GetPropertyNames() using the extension method above. There are a few questions that comes to my mind: If It's so easy to do generically, why are you even using the interface? Shouldn't you be checking properties for public accessors? Shouldn't your interface be returning a more general type like IEnumerable<string> or ICollection<string>? Wouldn't the interface be better designed to filter out property names that you don't want? That way you could assume all public properties are part of

Categories : C#

Can you list interface methods in the service registry OSGI
If a service implements an interface then any method on that interface is implemented by that service, by definition in Java. So any other bundle that knows about the service (and thus the interface) is fully aware of these methods. If you want to advertise to bundles that do not know the interface, then you could register properties. However, by definition accessing those methods would require reflection. In general this is not the way to go in Java, it is much nicer to stay type safe and use the interface as the anchor.

Categories : Java

Exposing a List via an IList
Suppose you could do something like this: // NOT REAL CODE public interface IMyInterface { } public class MyRealClass : IMyInterface { } ... public class Domain { private List<MyRealClass> myList; public IList<IMyInterface> Interfaces { get { return (IList<IMyInterface>)this.myList; } } } What's to stop a user of this Domain class from doing this? public class MyFakeClass : IMyInterface { } ... domain.Interfaces.Add(new MyFakeClass()); Obviously this would be problematic because myList is in reality a List<MyRealClass>, but the compiler cannot ensure that only instances of MyRealClass are added to the list (it would require a run-time check). In other words, this kind of behavior is not type-safe, so the compiler won't allow it. You can expose

Categories : C#

C# list of interface objects - casting single elements
for(int i = 0; i < fooBarObjects.Count; i++) { if(fooBarObjects[i] is bar1) { ((bar1)fooBarObjects[i]).anotherMethodBar1(); } else if (fooBarObjects[i] is bar2) { ((bar2)fooBarObjects[i]).anotherMethodBar2(); } } The key is the keyword is which checks if the object is of type bar1 (or any type derived from bar1) and the (type)object syntax which casts the object to your specified type. An alternative option is to use as keyword which does the cast and returns null if the cast cannot be done. for(int i = 0; i < fooBarObjects.Count; i++) { var b1 = fooBarObjects[i] as bar1; if (b1 != null) {

Categories : C#

Create list of interface types from JavaScript array
The problem is that the de-serializer has to instantiate classes to populate your list, not interfaces. But it has no way of knowing which class. So your question boils down to: how to hint the deserializer which class to create for each JSON object? There is no standard way of including a 'class' description in JSON (at least for now). You have to come up with your own rule (include a 'type' property, or probe the existing properties like you suggest). Of course the JSON framework has no way of knowing the rule, so it won't happen 'magically'. Assuming you use Newtonsoft's JSON.net for serialization (if you don't -- you should). This exact question was asked and answered here: How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects It basically c

Categories : C#

asp.net json web service sending array error Cannot convert object of type 'System.String' to type 'System.Collections.Generic.List`1[System.String]'
You need to make your data parameter of the $.ajax call like this: JSON.stringify({'a': variables}) The JSON variable is not available in < IE8 so you'll want to include a JSON implementation like the one mentioned in the answer here Also, you had an extra } in the success function. So, in the future, if you want to add extra parameters to your data object passed to the web service, you'd construct it like so: var someArr = ['el1', 'el2']; JSON.stringify({ 'param1': 1, 'param2': 'two' 'param3': someArr // etc }); JavaScript: var variables = Array(); var i = 0; $('#Div_AdSubmition').find('.selectBox').each(function () { variables[i] = $(this).find('.selected').find(".text").html(); i++; }); $.ajax({ type: 'post', data: JSON.stringify({'a': variables}),

Categories : C#

Compiler error on Java generic interface with a List<> method
The error seems to lie here: Task task = new MyTask(); You have forgotten to add generics after Task. It should work if you change it to one of these: Task<Boolean> task = new MyTask(); Task<?> task = new MyTask();

Categories : Java

How to customize the list data view in Django admin interface?
You have to build your own view and add it to admin. Maybe the admin list_view is a good starting point. If this sounds too much of work, I could imagine three work arounds: Make a new column for each task and each deadline and add the tasks and dealines there like "task_taskname" etc. Of course, this will be too much information if you are haveing mor then two or three tasks in each project. Reverse your logic! Don't make a list_view for projects, but for tasks! You can still add the project name to this list. In fact, this is your current TaskAdmin. Generate the entrys for Task Name and Deadline using model functions. Additionally, give a short description like get_all_tasks.short_description = 'Task Name'. That should do the trick! Funny enough, your question might have triggerd s

Categories : Django

"TypeError: 'list' does not support the buffer interface" when writing bytes to file
After you've read the file, data is a bytes object, which can behave like a list of numbers, but isn't one, while new is an actual list of numbers. Binary files support writing only bytes, so that's what you need to give it. One solution is to replace file.write(new) with file.write(bytes(new)). And here is a shorter rewrite of the code: with open(filename+'.bmp', 'rb') as in_file: data = in_file.read() new_data = bytes(byte//2*2 for byte in data) with open(filename+'.bmp', 'wb') as out_file: out_file.write(new_data) Note that the BMP format contains some headers, not just pixel data, so it will probably become corrupt after such modification.

Categories : Python

Override Property in Subclass from Baseclass Interface
You're doing it wrong. Do following: declare base class property using virtual keyword add override keyword next to subclass property declaration public class BaseClass : Inf { public virtual string Info { get { return "Something"; } } } public class SubClass : BaseClass { public override string Info { get { return "Something else"; } } } With that the result is as you expect. Read more about overriding and polymorphism here: Polymorphism (C# Programming Guide)

Categories : C#

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

Using Java's built-in Set classes to count EACH(keyword) unique element in List values from a list
You are looking for Map<String, Integer> data structure, not Set Something like for(iterating over something){ Integer count =map.get(value); if( count == null){ map.put(value, 1); } else{ count++; map.put(value, count); } } Map is the data structure that maps unique to value

Categories : Java

How to get a list of active network interfaces in c. Can i choose manually among these interface while sending data in socket programming?
You can show all the active network interfaces with ioctl() and its different flags. You can find an exemple here. You will be able to bind your socket to a specific interface, with setsockopt(). An example can be found here.

Categories : C

How can I cast a worksheet that implements and interface into an object of the type of the interface reliably?
I can't answer the first part of your question (the "why") but after struggling with this myself, I've found a way around it. I've built a Connect function in each of the worksheet modules that I use to implement an interface (in your example, ITest). Then I use it to set to an instance of ITest later. The Connect function is very easy: ' Place in the worksheet that implements the ITest interface Public Function Connect() As ITest Set Connect = Me End Function In your IsRangeInSheetImplementingTest replace Set oWks = rngIn.Worksheet with Set oWks = rngIn.Worksheet.Parent.Sheets(rngIn.Worksheet.Name).Connect It is UGLY, but it works every time.

Categories : Excel

When initialzing a variable of an interface type, what happens to the non-interface methods belonging to the class in the initialization statement?
Interfaces are a great feature. Think about it -- lets say you want to implement an algorithm that uses a hashMap. Previously in the code, the user chose a hash map implementation that was optimized in algorithms ran earlier. If you didn't have an interface,(rather, if the concept of interfaces didn't exist at all...or a set of function pointers didn't exist at all ), you would have to create the new algorithm that you want to implement for each implementation of the hash map. That's a lot of redundant code, and it's not very readable. You don't really lose access to the underlying methods. However, if you want to access the underlying TreeMap and its methods...you will have to cast it to a tree map from a map. @suppressedwarnings TreeMap treeMap = null; if(myMap instanceof TreeMap){

Categories : Java

ASP.net Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Web.UI.WebControls.DropDownList'
Set the Property .DataSource of the UI Control DropDownMenu or dropdownList.Items.AddRange(myList.ToArray()); if it has Items Collection.

Categories : C#

How to find out the type of list items and then create a list of that type of items?
You can do this using Reflection, for example: var listType = typeof(List<>); listType.MakeGenericType(typeof(MyType)) return Activator.CreateInstance(listType); Another example, if all you have is an instance of "MyType" but don't know what it is until runtime: public IEnumerable GetGenericListFor(object myObject){ var listType = typeof(List<>); listType.MakeGenericType(myObject.GetType()) return Activator.CreateInstance(listType); }

Categories : C#

Why is a class implementing an interface not compatible with the interface type when used in generics?
It's not a bug, it's a reflection you made that is wrong. Using a compatible type as a generic type argument does not make the generic type compatible as well. This has to do with covariance and contravariance.

Categories : Delphi

List passed in ViewBag gets spoiled with "System.Collections.Generic.List`1[System.String]"
Your problem is due to the fact that you're trying to pass a List of strings but have assigned it to a string property in the ActionLink(). You'll need to create a small helper to explode this List out to a single formatted string of your choice. This will then be passed to the url as a (for example) comma separated string. You'd then do some magic in the controller action to rehydrate this as required back to the List.

Categories : C#

Cannot convert from 'System.Type' to myself defined interface
typeof(T) returns a Type object that has meta information about the class that is represented by T. SomeMethod is looking for an object that extends IExportable, so you probably want to create an object that is a T which extends IExportable. You have a few options to do this. The most straight forward option may be to add the new constraint on your generic paramter and use T's default constructor. //Notice that I've added the generic paramters A and T. It looks like you may //have missed adding those parameters or you have specified too many types. public static A SomeAction<A, B, T>(IList<T> data) where T : IExportable, new() { T tType = new T(); IList<B> BLists = SomeMethod(tType); //... } I've explicitly stated the type of tType to better illustrat

Categories : C#

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

Finding case sensitive string in a cell from a specific list and return a value from the list
Assuming the following: Sheet 1, column a = Sheet1!A:A Sheet 1, column b = Sheet1!B:B Sheet 2, column a = Sheet2!A:A Sheet 2, column b = Sheet2!B:B You can simply insert an INDEX MATCH into Sheet1!B1 =INDEX(Sheet2!B:B,MATCH(Sheet1!A1,Sheet2!A:A,0))

Categories : Excel

Can I retrieve the interface type within an interface method?
public class MyClass : ITest, IDecoy { void ITest.DoSomething() { //called with ITest } void IDecoy.DoSomething() { //called with IDecoy } }

Categories : C#

I want my parser to return a list of strings, but it returns a blank list
I hope I got you right. You got a hex-string which contains various interface definition. Inside each interface definition the second octet describes the length of the name of the interface. Lets say the string contains the interfaces eth0 and eth01 and looks like this (length 4 for eth0 and length 5 for eth01): 01046574683001000001056574683031010000 Then you can split it like this: def splitIt (s): tokens = [] while s: length = int (s [2:4], 16) * 2 + 10 #name length * 2 + 10 digits for rest tokens.append (s [:length] ) s = s [length:] return tokens This yields: ['010465746830010000', '01056574683031010000']

Categories : Python

Return list of models passing in a List of ids using repository pattern
Use List's Contains method which will is translated to sql's in operator. I Suggest that you try to get a list of Homes with their CityBlock and City property included, then you can use linq to get all cities: var repository = new GenericRepository<Home>(); var homes = repository.Get(home => homeIdList.Contains(home.Id), includeProperties: "CityBlock, CityBlock.City") .ToList(); var cities = homes.Select(h => h.CityBlock.City).Distinct().ToList(); Hope this helps.

Categories : C#

Python: How to return a list without modifying the original list using a while loop only?
If you need to do this with a while loop, you could do it by appending each element to a list rather than printing it, and then returning that list: def everythird(l): i = 0 ret = [] while i < len(l): ret.append(l[i]) i += 3 return ret Though as you note, it would certainly be preferably to do def everythird(l): return l[0::3] Or if you were allowed to use a for loop: def everythird(l): ret = [] for i in range(0, len(l), 3): ret.append(l[i]) return ret Finally, if you were allowed to use a list comprehension: def everythird(l): return [l[i] for i in range(0, len(l), 3)] The slice indexing is certainly the best, but in any case a while loop might be the worst way to do it.

Categories : Python



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