w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
dictionary/tree fast key based lookup
You may want to create a dictionary of dictionaries of hashmaps. The first dictionary can contain all the TLD entries paired with a dictionary of all the second-level domains that have that TLD. Then each second-level domain can contain a hashmap of all the lower level domains it contains. Each entry will also have a flag to indicate if that entry is actually in the database or just a placeholder for lower level entries. Like with the short list you used, .com is not actually in the list, but would still be an entry in the TLD so give access to stackoverflow.com and wikipedia.com (which itself would be a placeholder for ru.wikipedia.com). A lookup would then just start with the URLs TLD, then second and finally lower level if it needs to go that deep. I hope I understood your dilemma

Categories : C#

Linq type conversion delegate for .First method
You need to call Select before First(): return _session.Query<Data.Model.User>() .Where(x => x.Username == username) .Select(_userMapper.CreateUser) .First(); Or: return _session.Query<Data.Model.User>() .Select(_userMapper.CreateUser) .First(x => x.Username == username);

Categories : C#

How to create Dictionary to store the type of a child class
I think you just want to use Dictionary<string, Type> then when you add something you should do; dict.Add("key1", typeof(Child1)); EDIT: As noted in Aiv's answer you can use the GetType() method on an instance if you want to add a Type at runtime. If you're doing it at compile time, you generally will use typeof on the class.

Categories : C#

Delegate types and covariance with a generic delegate type
The problem is the two delegate types simply aren't compatible. In order to make this work you are going to need to add an indirection layer which converts the arguments between ICommand and TCommand. public void RegisterHandler<TCommand>(CommandHandler<TCommand> handler) where TCommand : ICommand { mCommandHandlers.Add( typeof(TCommand), (command) => handler((TCommand)command); ); }

Categories : C#

Convert members of interface based dictionary to concrete based dictionary
You can do below. But if your code requires some casting from abstract type to its concrete implementation then you may have some other problems with your design. Dictionary<KeyType, IList<ValueType>> newDict = myDict.ToDictionary( k => k.Key as KeyType, v => v.Value.OfType<ValueType>() as IList<ValueType>);

Categories : C#

Type.InvokeMember when method has a Dictionary parameter
Reflection can not find the method because the method expects a hash table not a dictinary, dictionary doesn't inherit from hashtable so you can not use dictionary instead of hashtable. Method signiture should match before reflection can invoke a method.

Categories : C#

How to build a new defaultdict(list) in place based on an existing dictionary of the same type and use the original name
Try this: other_dictionary = defaultdict(list, ((k, v) for k, v in other_dictionary.iteritems() if k not in some_dictionary)) Notice that a defaultdict must receive a callable as its first argument, for determining what's the default value. In your code, the list argument was missing. Other than that, your algorithm was essentially correct - but it can be written a bit more concisely using iteritems(), as shown above.

Categories : Python

Issue with Dictionary type, If gived a specific text then get the equivalent dictionary key or dictionary value?
If this were my application, I would change the UI element to a datagridview so that I could bind a collection containing a custom class and just hide or show the appropriate columns as needed. This approach will allow you to easily add additional property columns in the future without worrying about the problems you are currently facing. It would also allow you to extend the UI to other platforms (mobile, web) without a lot of hard-coded information in the UI. For example, I would create the following class and collection to hold info about the files: Public Class FileDetails Public Property Index As Integer Public Property Description As String = String.Empty Public Property FullFileName As String = String.Empty Public ReadOnly Property FileName As String Get

Categories : Dotnet

Is there a use for a delegate type that returns a delegate of the same type as itself?
I have an example of some similar code that isn't exactly a recursive delegate, but it comes close. A "Y-Combinator" comes close - and quite frankly I have no idea how it works in practice, but it is used to define recursive functions. Here's the funky code you need to define: public delegate T S<T>(S<T> s); public static T U<T>(S<T> s) { return s(s); } public static Func<A, Z> Y<A, Z>(Func<Func<A, Z>, Func<A, Z>> f) { return U<Func<A, Z>>(r => a => f(U(r))(a)); } Now you can define recursive functions in one line. Factorial: var fact = Y<int, int>(_ => x => x == 0 ? 1 : x * _(x - 1)); var fact5 = fact(5); // == 120 var fact6 = fact(6); // == 720 var fact7 = fact(7); // == 5040 Fibonacci:

Categories : C#

Can I use use Hashcode to directly lookup a value in a C# Dictionary
I doubt it would make much difference, but you could do some timing tests to find out. You could write a simple immutable wrapper class for String that caches the hash code, and use that as the key type, for example: public sealed class StringKey: IEquatable<StringKey> { public StringKey(string key) { Contract.Requires(key != null); _key = key; _hashCode = key.GetHashCode(); } public override int GetHashCode() { return _hashCode; } public bool Equals(StringKey other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return (_hashCode == other._hashCode) && string.Equals(_key, other._key); } public overri

Categories : C#

Dictionary of string array lookup
Hopefully someone will correct me if I'm wrong, but it's my understanding that when you call ContainsKey, the Dictionary has a private method (exploring in dotPeek), which runs to decide wether the objects you're comparing are equal or not. Depending on what type you're using for the key, a different equality comparison will occur, based on various implementations of IEqualityComparer, this way the most appropriate comparison can be run, based on the types you wish to compare. You're using string arrays as the keys, so you're essentially checking the equality of the array objects themselves, not their contents. So it's entirely correct that your ContainsKey is returning false, you aren't asking your Dictionary if it contains the same array as a key, you're asking it if it contains a diff

Categories : C#

How to replace elements in a list using dictionary lookup
If all values are unique then you should reverse the dict first to get an efficient solution: >>> subs = { ... "Houston": "HOU", ... "L.A. Clippers": "LAC", ... ... } >>> rev_subs = { v:k for k,v in subs.iteritems()} >>> [rev_subs.get(item,item) for item in my_lst] ['L.A. Clippers', 'Houston', '03/03 06:11 PM', '2.13', '1.80', '03/03 03:42 PM'] If you're only trying to updated selected indexes, then try: indexes = [0, 1] for ind in indexes: val = my_lst[ind] my_lst[ind] = rev_subs.get(val, val)

Categories : Python

Using Lookup or Dictionary to represent a hand of cards in C#
To be clear, I didn't read your novel. TL;DR SPARKNOTES VERSION: How can I add more values to the keys inside of a Lookup? Usually, when I need a "dictionary" with a key that has multiple values, I use a List<KeyValuePair<string, int>>. You could use LINQ to Objects to select all the values. For example: static void StackOverflowExample() { var cardList = new List<KeyValuePair<string,int>> () { new KeyValuePair<string, int>("Club", 8), new KeyValuePair<string, int>("Spade", 9), new KeyValuePair<string, int>("Heart", 10) }; var results = cardList.Where(p => p.Key == "Heart"); } var results is an IEnumerable<KeyValuePair<string,int>>. Hopeful

Categories : C#

How can I pass parameters into these functions called via dictionary lookup
In make_choice scope, kwargs is a dictionary containing your paramX vaules and keys. So in this function scope, kwargs is nothing more than a dictionary. Just remove the ** before the kwargs in the arguments of your doXXX functions, and it will work.

Categories : Python

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[X]', but this dictionary requires a model item of type 'X'
Take this at face value - yours is not unique. Your problem is you are passing an array of user to a controller action that expects a user. You need to post your HTML but it is probably something like @model List user or something instead of a single user. If your model represents a single user then pass that to the controller. If opposite, do opposite, If you want to pass a list to the controller use list users edit make your razor syntax @model Mike.Models.User

Categories : Asp Net Mvc

Error while adding delegate to Action Dictionary using an out reference
Your example can be simplified (dictionary excluded): void Foo() { Console.WriteLine("Foo"); } void Bar() { Console.WriteLine("Bar"); } ... Action x = Foo; Action y = x; if (Object.ReferenceEquals(x, y)) Console.WriteLine("x was equal to y"); // creates new delegate instance: // x = x + Bar; // that is equal to // x = Action.Combine(x, Bar); // so x is not equal to y any longer: // x is a combined delegate (Foo + Bar) // y is a delegate to Foo (an old version of x) // such a behavior is typical for operators (+, +=, etc.): // when we declare "public static MyType operator + (MyType a, MyType b)" // it means that a new object "c" will be created that'll equal to sum of a and b x += Bar; if (Object.ReferenceEquals(x,

Categories : C#

Filter a list of dictionaries to always return a single dictionary, given a default key value to lookup
next() is the most pythonic function to achieve just that: def get_with_default(colour, colours, default): search = (d for d in colours if d['color'] in (colour, default)) match_or_default = next(search) if match_or_default['color'] != default or default == colour: return match_or_default return next(search, match_or_default) next() loops over the first argument until that produces a result, then returns that. If the first argument is exhausted, StopIteration is raised instead, unless a second argument is given, a default, in which case that value is returned instead of raising the exception. By giving it a generator expression that embodies the search, you efficiently scan the colours list for the first match. If that turns out to be the default, then we contin

Categories : Python

Webgrid: Cannot convert lambda expression to type 'object' because it is not a delegate type
You can't use embedded razor strings within the lambda expression, as @Alessandro D'Andra suggests you have to use x => "<img src='" + someString + "'></img>"; instead. You might also have to wrap it all in an MvcHtmlString to prevent Razor from escaping the string once it is used by the formatter, but I don't know exactly how the formatter works - you have to try it. I made a small test file to find out exactly what the Razor compiler would do with your code. This is the razor file: @{ string someString = "somestring"; Func<object, object> a = x => "<text><img src='" + someString + "'></img></text>"; Func<object, object> b = x => @<text><img src="@someString"></img></text>); } The ASP.NET

Categories : C#

WPF: Cannot convert lambda expression to type 'string' because it is not a delegate type
Your NotifyPropertyChanged expects a string, and you're passing it a delegate. Try: public string SelectedTransactionName { set { if (_selectedTransactionWsName == value) return; this._selectedTransactionWsName = value; // InitializaMessageElement(value.WsMethodName, transactionTypes); InitializaMessageElement(); this.NotifyPropertyChanged("SelectedTransactionName"); this.NotifyPropertyChanged("IsTransactionNameSelected"); } get { return this._selectedTransactionWsName; } }

Categories : Wpf

Calling Correct Method Based on Instance Type
C2 doesn't implement your equals method directly. If you want to use the C2 Equals method when you pass an instance of C2 as the interface, you need to Cast it to the type C2 and then you'll be able to use the C2 implementation of Equals. //psudocode void myMethod(I param1) { var obj = param1 as C2; if(obj != null) //use obj.Equals method which will use the C2 implementation. if(obj == null) //this is a C1 type and will use C1 equals method via param1.Equals }

Categories : C#

Django template unable to access a dictionary lookup variable. What mistake am I doing in code?
headers is a dictionary, you should iterate over it using items (docs): {% for key, value in headers.items %} <tr><td> {{ key }} </td><td>{{ value }}</td></tr> {% endfor %} You mistake is in using {{ headers.k }}, which is basically headers['k'] - request.META don't have k key - that's why you are seeing nothing. Hope that helps.

Categories : Python

How can I cast a subset of a dictionary to a type derived from Dictionary<>
You get an invalid cast exception because the result of ToDictionary is not MyDict. In order to fix this problem, add a constructor to MyDict that takes an IDictionary<string,A>, and return the result of calling that constructor from your GetSubSet method: public class MyDict : Dictionary<string, A> { public MyDict() { // Perform the default initialization here ... } public MyDict(IDictionary<string,A> dict) { // Initialize with data from the dict ... } } ... public MyDict GetSubSet(int testVal) { var ret = dict.Where(e => e.Value.aValue == testVal). ToDictionary(k => k.Key, k => k.Value); return new MyDict(ret); }

Categories : C#

Dynamic selection of method based on runtime parameter type
Maybe you want something very close to visitor patter. If you just want to pick a method (Foo) of an object (FooBar) by argument type you can use reflection to get all methods with given name (Foo) and do manual match of argument based on type of object (ObjectTypeX) and choices of the argument. Don't forget to handle derived classes properly. To avoid paying cost of reflection on every call - cache results (i.e. by building/compiling en Expression tree). Note that Dictionary (actions for given method name indexed by type) approach will probably easier to support/debug to start with. Later if you find it slow for you needs you may replace it with something more complicated like reflection.

Categories : C#

How much data can I store in a lookup table on App Engine without running into performance problems?
Holding all static data in memory is a great idea to improve performance. Non surprisingly, how much data you can you in memory depends on how much memory you have. App Engine allows you to choose how much memory to put on your instances, so the limit will depend on your choice. For now the default is 128MB, configurable up to 1024MB. https://developers.google.com/appengine/docs/adminconsole/performancesettings

Categories : Python

Lookup from HashMap based on expression
There is a reason there is no implementation of such a data-structure. Lets reverse engineer it: Requirements: keyA = Expression.getInstance("00*"); keyB = Expression.getInstance("0011"); map.get(keyA) == map.get(keyB) Now how does hashmap() work? First, key's hash value is calculated, which is used to locate the hash bucket. Now with that bucket key's equals() is used to find the Entry object and then Entry.value() is returned. Anaysis So that means, keyA and keyB should have same hashCode and should be equal as well. so keyA.equals(keyB) == true What about, keyC = Expression.getInstance("0010"); According to your logic keyC.equals(keyA) = true. But because equals is transitive that means keyB.equals(keyC) == true. That means in your map, 0010 and 0011 map to the same value

Categories : Java

Is loosely coupling more reliable (based on lookup API from netbeans)?
Striving for the loose-coupling (and programming to interface rather to implementation) is one of the fundamental principles you should adhere to. This way you can change the implementation later (when you change your mind or specifications change) without affecting the dependent code which use the to-be-changed class. Its like you are in business and have a contractor which is bound by the contract to do certain thing with agreed upon input. When you decide that you want another contractor (doing the SAME stuff with the SAME input but for the less money or faster) you just change him without effect on your business. Because you are not tightly coupled. This principle of not being to reliant on some entity and 'connect to it' via interface only (set of predefined methods with fixed

Categories : Java

jquery lookup adjacent span in table based on value
If you change your code to generate spans like this instead: <span id="Rate30">45</span> Then you can simply do this: $("#Rate" + $ddl.val()).text(); Where $ddl is your dropdown list.

Categories : Jquery

How to unmarshall incoming request payload as method/function arguments based on content type in Python flask or bottle frameworks
There are some caveats in doing so for code readability but a possible solution is as follow. Define the serialization method. If you need to work with different clients I suggest JSON. Create a decorator and put it between your function and the route @route(...) @expandargs def foo(id, bar, baz): ... In the decorator use request.json() (automatically decodes the payload if it's JSON) to expand the args and then you'll call the wrapped function with original args and the new, say, **expandedargs (note the double asterisks to explode the keywords). Problems arise when mixing positional and keyword args.

Categories : Python

Delegate of type 'required'
In this particular case, "locationManagerDidPauseLocationUpdates" is called on iOS 6 (and newer) OS'es to inform your app that the location isn't changing and that it's shutting down to save power. On iOS 5, this delegate method won't get called but if you implement it, it will get called in iOS 6. If you target iOS 6 (instead of iOS 5), you'll get a compiler warning if you didn't implement any "required" delegate methods.

Categories : IOS

SSIS - Extract multiple databases based on lookup table
As a rough idea, you could work with SSIS Package Configurations and executing packages from within packages, and then use the Transfer SQL Server Objects Task: Make a "Main package" that iterates over the column in your lookup table. For each entry, it should UPDATE the Package Config entry of your second SSIS package accordingly. Use the "SQL Server" configuration for that second package. The Main package should then execute the second package - there is a also a task for this. The second package looks at its config to find out which server to get databases from and uses the Transfer SQL Server Objects Task to do so. then the Main package continues with the next entry from your lookup table. Ideally you would want to have your "second SSIS package" inside SQL Server's MSDB rather tha

Categories : SQL

In Solr, is it possible to add values for document during indexing, based on a certain field value and a lookup?
Nope. but you can try for options Create a New Filter/Analyzer and use it with copyfield with source as product id. Load the file, if a match found add special as the token in the copyfield dest. Use synonyms text with id=special mapping so that field match if found would have special as the contents. If using DIH check for ScriptTransformer which will allow you to check value and add a new field

Categories : Solr

Annotations for Hibernate lookup table/type?
For your base class you would add the following annotation: @MappedSuperclass public class BaseLookup implements Serializable { @Id @Column (name="ID") private Long id; @Column (name="NAME") private String name; @Column private String tag; // ...getters, setters and ctors, etc. } And for your children classes you would do the following: @Table(name = "CREDITCARDTYPES") public class CreditCardTypes extends BaseLookup { // .. perhaps a few other fields, methods, etc... @Coulmn (name="FIELD1_COLUMN_NAME") private String field1; } And you could do the second class in the same manner: @Table(name = "PAYMENTTYPES") public class PaymentTypes extends BaseLookup { // .. perhaps a few other fields, methods, etc... @Coulmn (name="FIELD2_COLU

Categories : Java

LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression
Since LINQ to Entities does not support Convert.ToInt32, you need to parse to int outside LINQ first: TaxiEntities db = new TaxiEntities(); int password = int.Parse(txtPassWord.Text); bool IsUserPassCorrected = db.tblOperators .Any(item => item.UserName.ToLower() == txtUserName.Text.ToLower() && item.Password == password);

Categories : C#

What does equating an EventHandler type var to a delegate mean in C#?
I have not seen enywhere that an EventHandler is equal to a delegate ? EventHandler is a delegate type. public delegate void EventHandler( Object sender, EventArgs e ) (Attributes removed for simplicity.) In this case what you're seeing is an anonymous method - a way of creating a delegate from an "inline" block of code. Lambda expressions are a more common way of achieving that these days though. (Anonymous methods were introduced in C# 2; lambda expressions were introduced in C# 3.) Both lambda expressions and anonymous methods can be converted to delegate instances; some lambda expressions can also be converted into expression trees for code which needs to analyze the logic within the expression. If you're reasonably new to delegates in general, you might also want t

Categories : C#

"expected type" while implementing delegate
Add the following at the top. Since the protocol TopBarDelegate is defined above the class TopBarViewController, at the point you define the protocol, the compiler doesn't know there is a class called TopBarViewController. This line tells it there really is a class with that name defined somewhere. @class TopBarViewController;

Categories : IOS

Where to store my Dictionary
You could use LINQ2XML to create two methods for writing and reading the Dictionary object. Storing the Dictionary (extend / change for your types) to a file: private void storeXml(string location, Dictionary<int, string> data) { var xml = new XElement("storage", data.Select(kv => new XElement("entry", new XElement("key", kv.Key), new XElement("value", kv.Value)))); xml.Save(location); } Read data from a file and fill the dictionary object: private Dictionary<int, string> readXml(string location) { var data = new Dictionary<int, string>(); var xml = XDocument.Load(location); foreach(var element in xml.Descendants("entry").ToList()) { var key = i

Categories : C#

The attribute lookup is undefined for the annotation type Resource
Try using the mappedName attribute as: @Resource(mappedName="jms/ConnectionFactory") Also if you still want to use lookup, then take a look at the javax.annotation.jar you are using. Lookup attribute was introduced in JavaEE 6. Probably you have an older version.

Categories : Eclipse

Delegate method not being sent
I think that you mix up the location services of CLLocationManager and of MapView. mapView:didUpdateUserLocation: is a delegate method of MKMapView. If you just need this method to update the user's location, you don't have to instantiate a CLLocationManager. Instead you simply say, as you did, [worldView setShowsUserLocation:YES]; But of course, your object that implements mapView:didUpdateUserLocation: has to be the delegate of you MKMapView object, here of worldView, not of a CLLocationManager object! So my suggestion is to set your TrackViewController object as the delegate of your MKMapView object, i.e. of worldView, and delete the code related to the CLLocationManager.

Categories : IOS

What is this delegate method doing?
The delegate keyword indicates that what follows is essentially a function signature, so therefore, Refresh becomes kind of like a pointer to a function that takes no arguments. However, to assign something to the Refresh pointer, you have to give it a function to point to. In this case, it's the Reset function. And further, the Reset function must take no arguments. In addition, the syntax: Refresh = Reset; is also valid, and is just syntactic sugar for the more formal syntax: Refresh = new NoArguments(Reset); in both cases, you could then execute the Reset function by calling Refresh: Refresh(); Note, however, that if you execute Refresh() without it having been assigned, then you could generate an exception. The way to prevent this would be to check it against null: if (R

Categories : C#

MVC Cannot convert lambda expression to type because it is not a delegate
Found what happens. The asp.net tags are not allowed in the SetContent() that way. The correct way to do it is: CBsettings.SetContent(() => { ViewContext.Writer.Write("<h1>Hello World</h1>"); ... }); So sad the intellisense doesn't give a clue about what is wrong.

Categories : C#



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