w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
vba to search a list and colour code matches based on a contents list.
I hate to encourage you, because you did not follow the site rules that say to research and attempt a solution before asking a quesiton, and share what you have already tried. That is probably why others have given your question a negative rating. However, you did enough thinking about the parameters of your problem, that I suspect you may have tried something before composing this question, and I'm granting you the benefit of the doubt. Here is a possible solution, if by "pre colour coded data" you mean the interior of the cell. Change the Constants at the top to match the column and header row of your data. If the pre colour coding of your data is something other than the interior settings I've used, you can take Marty McVry's advice of using the macro recorder to determine which set

Categories : Excel

Parallel version of code to accumulate values from list>
Personally, I would use: double sum = yourListOfList.AsParallel().SelectMany(list => list).Average(); In order to fix your method, you need to property use your loop state in the local final lambda. (You're not using x at all currently.) double sum = 0; var syncObj = new object(); Parallel.For<double>(0, this.Count, () => 0, (i, loop, sub) => { var innerList = this[i]; for (int j = 0; j < innerList.Count; j++) { sub += innerList[j]; } return sub; }, (x) => { lock(syncObj) sum += x; }); return sum / ((this.Count * this[0].Count)); Note that your version (and my "correction") has many drawbacks. It's assuming that each sub list is the same length as this[0]

Categories : C#

Python change list to set in code
Use dict.setdefault: def makeInverseIndex(s): dic={} for index, line in enumerate(s): #use enumerate() for getting index as well as item words = line.split() for palabra in words: dic.setdefault(palabra,set()).add(index) Don't use set as a variable name, as it hides the built-in function set().

Categories : Python

Why does the following Ember.js code not update the given list?
You have a scoping issue, fixed at link: http://jsbin.com/izunik/1/edit You were referring to "this" inside of set interval which is not the same as "this" in the view.

Categories : Javascript

What can I do to list activities instead of package name in my code?
Actually in your system apps are stored with their unique package name that's why you are listing them with them. If you want only the last section of that name (supposing you have no duplicates) you can do some trick: String s = "com.example.MyApp"; String appName = s.substring(s.lastIndexOf(".")+1); // appName <- MyApp

Categories : Android

Can I vectorize code when data is in a list?
My 'low hanging fruit' (scan; pre-allocate and fill) seem to be not relevant, so... The operations in the distance calculation sort of look vectorized enough to me. Probably you can squeeze some extra speed out of doing a single distance calculation over all your matrices, but this probably makes the code less understandable. The weightedMatrix calculation looks like there is room for improvement. Let's calculate w <- d^(-2) / cumsum(d^(-2)) For a weighted matrix m I think the relationship between successive matrices is just m' = m * (1 - w[i]) + l[[i]] * w[i], so res <- vector("list", length(l)) for (i in seq_along(l)) if (i == 1L) { res[[i]] = l[[i]] * w[[i]] } else { res[[i]] = res[[i - 1]] * (1 - w[[i]]) + l[[i]] * w[[i]] } This changes the c

Categories : R

Why does this code hang during an insert of stl list
getlist returns a list by value so list1.insert is using iterators into different lists for its start and end points. You should change getlist to return a reference to its list rather than a copy of it list<string>& getlist()

Categories : C++

LLDB: List source code
In Xcode 4.6, lldb's l alias is a simple shortcut for source list. In the top of tree sources, this has been improved to behave more like gdb. If you look at source/Interpreter/CommandInterpreter.cpp over at http://lldb.llvm.org/ you'll see that l is now a regular expression command alias with these cases: if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "source list --line %1") && list_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "source list --file '%1' --line %2") && list_regex_cmd_ap->AddRegexCommand("^\*?(0x[[:xdigit:]]+)[[:space:]]*$", "source list --address %1") && list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$", "source list --reverse") &

Categories : C++

adding nested ul list from code behind
In the inner loop, you need to create a sub <ul> tag. foreach (TreeNode childNode in node.ChildNodes) { HtmlGenericControl child_li = new HtmlGenericControl("li"); navMenu.Controls.Add(child_li); becomes if(node.ChildNodes.Count > 0) { HtmlGenericControl child_ul = new HtmlGenericControl("ul"); li.Controls.Add(child_ul); foreach (TreeNode childNode in node.ChildNodes) { HtmlGenericControl child_li = new HtmlGenericControl("li"); child_ul.Controls.Add(child_li); etc...

Categories : HTML

Trying to put drop down list on a code using Tkinter
I modified your aceptar_piezas function to do what I think you want: def aceptar_piezas(self): num_piezas = self.entrypiezas.get() print num_piezas self.piezastext.grid_remove() self.entrypiezas.grid_remove() self.aceptarnumpiezas.grid_remove() # Create a list of tuples to hold the dynamically created Optionmenus # The first item in the tuple is the menu, the second is its variable self.optionmenus = list() n = 1 while n <= int(num_piezas): self.textopieza = Label(self.frameOne, text = "Pieza", justify="left") self.textopieza.grid(row=n, column=0) # Variable for the Optionmenu var = StringVar() # The menu menu = OptionMenu(self.frameOne, var, "a","b","c") menu.grid(row=n, column=1)

Categories : Python

How to ImageIcon Array List resize in following code
To resize an Image you can use Image.getScaledInstance() List<ImageIcon> images = new ArrayList<ImageIcon>();// Array list for (int fileInList = 0; fileInList < files.length; fileInList++) { if (files[fileInList].isFile()) { Image baseImage = ImageIO.read(files[fileInList]); Image scaledImage = baseImage.getScaledInstance(85, 100, java.awt.Image.SCALE_SMOOTH); images.add(0, new ImageIcon(scaledImage)); } } Or you could use the Graphics.drawImage(). List<ImageIcon> images = new ArrayList<ImageIcon>();// Array list for (int fileInList = 0; fileInList < files.length; fileInList++) { if (files[fileInList].isFile()) { Image baseImage = ImageIO.read(files[fileInList]); BufferedImage scaledImage = new BufferedImage(85, 100, BufferedIma

Categories : Java

Search through code for list of unique controls
I'm using NDepend when it comes to dependencies analysis and changes analysis. If you don't have licence trial version should allow you to use all features without restrictions. Start from creation of the new project and add compiled assembly of your web application. It will automatically load all dependencies which you can browse with Class Browser. This will give you the basic understanding of what types (controls) are used by your web app. Also you can narrow or extend your findings with Queries and Rules Edit (Ctrl+Alt+R). Run following query to get a list of used controls from System.Web.UI.WebControls: from type in Assemblies.WithNameNotIn("WebApplication2").ChildTypes() // depth is needed th find all controls that are used directly or indirectly let depth = type.DepthOfIsUsedB

Categories : Asp Net

EF Code First Generic Add Method From List of Objects
When inferring generic arguments the compiler uses the declared type of the variables passed, not what that variable contains at runtime. If you want to do things this way, you could use reflection to call the method with the correct generic argument: var addMethod = typeof(PreApplicationInit) .GetMethod("Add", BindingFlags.Static | BindingFlags.NonPublic) .MakeGenericMethod(o.GetType()); addMethod.Invoke(null, new[] { entity }); If it's going to be called many times, I would create a Dictionary<Type, MethodInfo>() to store the MethodInfo objects in as you create them, as creation is slow. You could also make the Add() method non-generic, and use reflection on context.Set<T>() within Add().

Categories : C#

find group within Mailchimp List C# code
I researched a lot on the web, however I was not been able to find suitable example for finding group associated with mailchimp list using C#. finally, I do it myself which you may find helpful. Furthermore, I am using MCAPI.NET wrapper library for this code. string apikey = System.Configuration.ConfigurationManager.AppSettings["mailchimpapikey"]; string listId = System.Configuration.ConfigurationManager.AppSettings["ListID"]; var input = new listInterestGroupingsInput(apikey, listId); var lig = new listInterestGroupings(input); var success = lig.Execute(input);

Categories : C#

Get the selected item of dropdown list from code behind
Your Select input which you add some options with JQuery to it, it is a Client side object and in no circumstances you can have access to it using code behind To access this object you have to add to property to your select input ID and runat=server thsese to property let you access your object from the code behind, you final select should be something like this <select id="select1" runat="server"> <option value="val1">dfgbfbff</option> </select> then in your code behind you can check its values with checking the select1

Categories : Asp Net

Having a big list of static data into code instead of a database?
I've embedded data that would otherwise be in a database inside of an application many times. No XML file, no plain text file, no database. I usually only do that for small amounts of data that I think will never change. The reason for that is always laziness. I don't want to make a database, a schema, write the data access code, etc. In those cases even making an XML file is too much work for small amounts of data. If all the data is read only, I think it's a fun idea to deploy assemblies instead of an actual database. As you said it removes a very and potentially problematic dependency. The only downside I can think of is that when you're doing queries, the assembly potentially has to load a very large amount of data into memory. As long as you have some sort of lazy loading functi

Categories : Dotnet

Drop Down List - Unreachable Code Detected
Well, first of all warnings are not errors. Back to the warning which is quite descriptive. You have some code that will never execute (i.e. unreachable code). To detect what's preventing it from execution always look at the statement before the underlined statement (statement warning is referring to, in a case you use IDE that does not underline warnings). In this case, you'll see the problem is that you use return without any condition, that means nothing after return will be executed. Thank you Daniel and Pawel. It now works as required. Don't know how I missed that. If you always keep return at the end of the method you'll almost never make this mistake. And you can and should be keeping return at the end unless it's necessary to return because of some condition.

Categories : C#

Is an empty initializer list valid C code?
No, an empty initializer list is not allowed. This can also be shown by GCC when compiling with -std=c99 -pedantic: a.c:4: warning: ISO C forbids empty initializer braces The reason is the way the grammar is defined in 6.7.8: initializer: assignment-expression { initializer-list } { initializer-list , } initializer-list: designation(opt) initializer initializer-list , designation(opt) initializer According to that definition, an initializer-list must contain at least one initializer.

Categories : C

Android: Code not working when getting list of all images
Here is code that worked. public ArrayList<String> getCameraImages(Context context) { // Set up an array of the Thumbnail Image ID column we want String[] projection = {MediaStore.Images.Media.DATA}; final Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, null); ArrayList<String> result = new ArrayList<String>(cursor.getCount()); Log.i("cursor.getCount()) :", cursor.getCount() + ""); if (cursor.moveToFirst()) { final int dataColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); do { final String data = cursor.getString(dataColumn); Log.i ("data :",data ); res

Categories : Android

PHP code for adding incrementing css ID's to generated list
Change: echo "<li id:"S-$i"><img class="zuper" src="$file" /></li>", $i++; to echo "<li id:"S-$i"><img class="zuper" src="$file" /></li>"; $i++; Note how I changed , to ;. See Instruction Separation.

Categories : PHP

PHP + AJAX code - Display data on selecting a value from a list
Variable str22 is not being assigned when you call showBlock2() on changing year. So replace the line showB(); with showB(document.getElementsByName("h")[0].value); This would work when you select health and then year, no need to call showB() on changing health list. EDITED (Optimized Code): The following code has been altered from your source. Mainpage <html> <head> <script type="text/javascript"> function showBlock2() { var str11=document.getElementsByName("h")[0].value; var str22=document.getElementsByName("yr")[0].value; document.getElementById("txtHint").innerHTML=""; var xmlhttp; if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }

Categories : PHP

Code to find count in list generates error
How about using a dictionary: word_counter = {} if word in word_counter: word_counter[word] += 1 else: word_counter[word] = 1 The if/else is used to check if the dictionary already contains the word. If it does, it will increment its associated value, if it doesn't, it initializes the value to 1. Python dictionaries. And, to find out more about why your code wasn't working, here's more on lists. As mentioned by Ashwini Chaudhary you can also use collections.Counter whose purpose is to do this kind of thing: >>> # Tally occurrences of words in a list >>> cnt = Counter() >>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']: ... cnt[word] += 1 >>> cnt Counter({'blue': 3, 'red': 2, 'green': 1}) and here's an example of how to

Categories : Python

Code Optimization to check some items of checkbox list
I think you need to eliminate the nested iteration. As you state, both lists have a large set of items. If they both have 5,000 items, then you're looking at 25,000,000 iterations in the worst case. There's no need to continually re-iterate orderList for every single ListItem. Instead create an ID lookup so you have fast O(1) lookups for each ID. Not sure what work is involved hitting scopeComputer.SelectedBox, but that may as well be resolved once outside the loop as well. bool selectedState = scopeComputer.SelectedBox; HashSet<int> orderIDs = new HashSet<int>(orders.Select(o => o.id)); foreach (System.Web.UI.WebControls.ListItem item in OrdersChoiceList.Items) { if (orderIDs.Contains(item.id)) item.Selected = selectedState; } Using a HashSet lookup, you're

Categories : C#

Reverse singly linked list - Code improvement
A better implementation should be as below: public Node reverse(Node current) { if (current== null || current.next==null) return current; Node nextItem = current.next; current.next = null; Node reverseRest = reverse(nextItem); nextItem.next = current; return reverseRest; }

Categories : Java

R code: Modifying Built in Function on lapply list
For stepwise using 'forward' or 'both', you need to include a scope argument. For you, the scope would be something like the full potential equation. For example on X1: scope='X1~X2+X3'. However, after step 1 of models, you have a list of 3 equations, where each equation uses all the possible variables. Therefore, stepwise cannot possibly add any new variables. Instead, try "backward". This does not require a scope argument, and it shows that the syntax is correct. I've corrected your code below: models <- lapply(varlist, function(x) { lm(substitute(i~., list(i = as.name(x))), data = test) }) And then run stepwise, but backward. lapply(models, function(x){step(x,direction="backward")})

Categories : R

Access a stopword list from a Solr component code
You need to make your component ResourceLoaderAware. ResourceLoaderAware would provide you inform method with an instance of ResourceLoader and you can use this to load and read the files. The files should be hosted in the conf directory, probably. e.g. code from SynonymFilterFactory.java synonyms is the attribute defined in the schema.xml protected Iterable<String> loadRules( String synonyms, ResourceLoader loader ) { List<String> wlist=null; try { File synonymFile = new File(synonyms); if (synonymFile.exists()) { wlist = loader.getLines(synonyms); } else { List<String> files = StrUtils.splitFileNames(synonyms); wlist = new ArrayList<String>(); for (String file : files) { List<String> l

Categories : Java

Dump an Python list to file as code text
print repr(arr). Of course, pickle isn't especially slow. And, as zhangyangyu notes, while this works for a list, it won't work for objects whose repr cannot be eval'd.

Categories : Python

How to pass a generic list to a dynamically compiled C# code?
There are several options. Change the type of your Parameters object to List<string>[]. This is the way to go if you always know you are passing in a List<string>. Cast in your dynamically generated code: ((List<string)Parameters[0]).Count; It is a little bit clunky, but will get rid of the error. Change the type of your Parameters object to dynamic. Since your are compiling the code at runtime, compile time type checking may not be a priority for you.

Categories : C#

c# code in asp.net for displaying database values in dropdown list
Dont write the code in dropdowns selected index changed event write it in a function and call it in pageload event you have to set the DataTextField and DatavalueField objc.ClientName = Convert.ToString(Session["ClientName"]); DataSet ClientN = obj.GetClientList(); DataView Projview = new DataView(); Projview.Table = ClientN.Tables[0]; DrpClientName.DataSource = Projview; DrpClientName.DataTextField="Description"; DrpClientName.DataValueField="ID"; DrpClientName.DataBind();

Categories : C#

What more does the code need to delete a node from a linked list successfully?
Why are you allocating two nodes in the delete function, then leaking their memory? It seems they should be initialized to start or one of its successors. You also need to update the next pointer in the previous element and potentially also the start (head) of the list if the removed element was the first (ie. index_no == 1). You also have an off-by-one error where the final node can never be deleted, because only a node with a ->next pointer will be considered for deletion. Suggested reading: A Tutorial on Pointers and Arrays in C.

Categories : C

How to specify hosts list or roledefs in text file (instead of code)?
if I understand you correctly, you need separate file for list of hosts. You need to add this lines to your fabfile: env.roledefs = { #static roles } # add dynamic role from file "hosts" with open("./hosts") as f: env.roledefs['tmp'] = f.readlines() Create hosts file with list of hosts in current directory: example1.com example2.com try it: $ fab -R tmp -- uname -a

Categories : Python

List of bytes in MVC model not generated in database by EF code first
I don't think EF knows how to map List<byte>. I would try just byte[]. [Required] [Display(Name = "List of items included into product name")] public byte[] ProductsNameCompositionList { get; set; }

Categories : C#

Custom HTML Code creates emtpy list in IE 9
Probably, because you're not closing your List Items with </li> Before the dawn <ul><li><b>Blah blah blah !!</b></li> <li><b>Do not combine capital letters Blah blah</b></li></ul> You should also use just one Unordered List <ul></ul> instead of having one for every list item. And, although it may work otherwise, display tags like bold <b> should ideally go inside the structure tags like list item <li>.

Categories : Java

PHP randomise file list array from existing code?
You are over complicating things by building the JS yourself. Try json_encode: <?php function returnimages($dirname=".") { $images = array(); $pattern="(.jpg$)|(.png$)|(.jpeg$)|(.gif$)"; //valid image extensions if($handle = opendir($dirname)) { while(false !== ($file = readdir($handle))){ if(eregi($pattern, $file)){ //if this file is a valid image $images[] = $file; } } closedir($handle); } return $images; } $images = returnimages(); shuffle($images); Header("content-type: application/x-javascript"); echo 'var galleryarray = ' . json_encode( $images ) . ';'; ?> shuffle does not return the shuffled array, but the status of the operation (TRUE/FALSE).

Categories : PHP

How To Add Two List<> at run time ? Index out of range error My code Attached (ASP.net C#)
You may need something like this (assuming that first and second are List): List<double> Result = new List<double>(); for (int i = 0; i < 30; i++) { double firstVal = 0; double secondVal = 0; if (first.Count > i) { firstVal = first[i]; } if (second.Count > i) { secondVal = second[i]; } Result.Add(firstVal + secondVal); }

Categories : C#

error in my PHP code drop down list to select item from MYSQL
The error you are seeing is a database error. It has nothing to do with the drop down. The syntax you are following is incorrect. Change $sql = 'SELECT `id`, `name`, `mime`, `size`, `created` FROM $table'; to $sql = "SELECT id, name, mime, size, created FROM '$table'";

Categories : PHP

Does code exist, for shifting List elements to left or right by specified amount, in C#?
Something like this for shift left... public static void ShiftLeft<T>(List<T> lst, int shifts) { for (int i = shifts; i < lst.Count; i++) { lst[i - shifts] = lst[i]; } for (int i = lst.Count - shifts; i < lst.Count; i++) { lst[i] = default(T); } } For shift right it's a little more tricky, because we must copy in reverse public static void ShiftRight<T>(List<T> lst, int shifts) { for (int i = lst.Count - shifts - 1; i >= 0; i--) { lst[i + shifts] = lst[i]; } for (int i = 0; i < shifts; i++) { lst[i] = default(T); } } With arrays it's a lot more simple, because Array has very powerful methods: public static void ShiftLeft<T>(T[] arr, int shifts) { Array.Copy

Categories : C#

Python-Turtle: Turning list of Strings into a working code
Things like "hello" are called string "literals" in python. They represent an immutable sequence of characters. You can't assign values to a string literal. If you're trying to store the commands in such a way that they can be referenced and called by their string representation, try this: commands = {} commands['lift pen'] = pu commands['lower pen'] = pd commands['thin lines'] = lambda:pensize(1) commands['thick lines'] = lambda:pensize(5) commands['black pen'] = lambda:color('black') commands['coloured pen'] = lambda:color('green') commands['go to'] = lambda x, y:goto(x,y) commands['draw dot'] = lambda s:dot(s) Then you could access the commands with something like this: commandList = [("lift pen", []), ("go to", [10, 20]), ("lower pen", [])] for command, args in commandList: #

Categories : Python

Code throws TypeError: unsupported operand type(s) for -: 'int' and 'list'
This is a speculative improvement on your code. Like so many others, I don't see what you are trying to do. Also, the setting of index inside move needs elaboration. Presumably it is some value from u. from pprint import pprint colors = [ ['red', 'green', 'green', 'red' , 'red'], ['red', 'red', 'green', 'red', 'red'], ['red', 'red', 'green', 'green', 'red'], ['red', 'red', 'red', 'red', 'red'] ] motions = [[0,0],[0,1],[1,0],[1,0],[0,1]] p_move = 0.8 def move(lst, u): q = [] if u[0] != 0: index = u[0] for i, elem in enumerate(lst): q.append([lst[j-index][i] * p_move] for j in range(len(elem))) elif u[1] != 0: index = u[1] for i, elem in enumerate(lst): q.append([lst[i][j-index] * p_move] for j in range(

Categories : Python

How to pass multi value of checkbox list to stored procedure in code behind?
The problem is that the IN clause where UserBrDiv in(@ParmUserBrDiv) isn't going to work like that so no records are actually selected. You use this in two different places, getting the @maxcnt, which will always be zero because of it, and then trying to update the actual table, which will never select any rows because of it. What you need to do is build this UDF in your database: IF OBJECT_ID('dbo.CSVToTable') IS NOT NULL DROP FUNCTION dbo.CSVToTable GO CREATE FUNCTION [dbo].[CSVToTable] ( @KeyValue VARCHAR(8000), @StringInput VARCHAR(8000) ) RETURNS @OutputTable TABLE ( [KeyValue] VARCHAR(8000), [String] VARCHAR(8000) ) AS BEGIN DECLARE @String VARCHAR(10) WHILE LEN(@StringInput) > 0 BEGIN SET @String = LEFT(@StringInput, ISNUL

Categories : C#



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