w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Subscripting an Array of Integers in Python?
You're going to need to get clarification on this, because there's no such thing as "an array of integers subscripted by the letters 'A' through 'Z'" in Python. Possible interpretations that I can think of: It's supposed to be a dictionary rather than an array. Python dictionaries are similar to lists (the Python datatype that is roughly equivalent to "arrays" in other languages), but they can be subscripted by strings, whereas lists can be subscripted only by integers. This way, you can store an integer to be associated with each letter. This is how most Python programmers would generally do something like this. You're supposed to use parallel lists. You can do this by making two lists of 26 elements each, one containing the letters 'A' through 'Z' and one containing integers. For each

Categories : Python

Subscripting text in matplotlib labels
Try to change this line plt.plot(x,y, label='H2O') for this: plt.plot(x,y, label='$H_2O$') It shows with the font math. Or also you can use the unicode character for that: ₂ (0xE2 / ₂) plt.plot(x,y, label=u'H₂O') or instead: plt.plot(x,y, label=u"Hu2082O") Please, note that unicode strings are noted as u"" instead than "".

Categories : Python

Objective-C object subscripting, iOS5, and GCC
According to the "Objective-C Feature Availability Index", NSArray subscripting requires at least LLVM Compiler 4.0. Starting with iOS 6, NSArray has a objectAtIndexedSubscript: method. For iOS 5, this method is supplied by the static Arclite library that is linked into the application (see e.g. How to enable the new Objective-C object literals on iOS? and the links given in the answer). But that is a Clang only feature, GCC does not support ARC. So I do not see how you could use array subscripting if the main application is compiled and linked with GCC.

Categories : Objective C

Creating a 3-dimensional OrderedDict with natural subscripting
All you need is to subclass OrderedDict and add a __missing__ function: from collections import OrderedDict class DefaultOrderedDict(OrderedDict): def __missing__(self, key): self[key] = type(self)() return self[key] The default dict type will call a __missing__ method if present before raising a KeyError, which is what the defaultdict type makes use of. See the dict documentation (scroll down to the d[key] description): New in version 2.5: If a subclass of dict defines a method __missing__(), if the key key is not present, the d[key] operation calls that method with the key key as argument. The d[key] operation then returns or raises whatever is returned or raised by the __missing__(key) call if the key is not present. No other operations or methods invoke __m

Categories : Python

How do I find elements in array with another indexes array?
Try this as below using Array#values_at a = ["mo", "tu", "we", "th", "fr", "sa", "su"] b= [1, 5] c = a.values_at(*b) # => ["tu", "sa"]

Categories : Ruby

What about 2D-array indexes in C?
What is wrong? What is wrong is your assumption about the compiler and/or the language. C has no bounds checking. The compiler won't warn you if you are accessing an array out of bounds. What happens instead: your code is now invalid, it is said to invoke undefined behavior, and it's free to do anything it wants (including crashing or seemingly "working fine").

Categories : C

javascript object literal, combining values of objects within same literal
I'm a little unclear on the exact math you're trying to achieve, but I think I can help with the looping. You don't need two loops, just one to iterate through the array of data objects. Then, build yourself a new array of your new objects. Like: var newData = []; for (var i=0; i<data.length; i++) { var currentDataObject = data[i]; // don't really need this but just to make it clear newData.push({ repId: currentDataObject.repId, profit: your math here, expense: your math }); } For the record though, if you did need to iterate through the properties of an object, you'd need to use the "for (var key in data)" syntax.

Categories : Javascript

JavaScript string literal in object literal syntax error
You have an unclosed string literal. JavaScript strings are not multi line by default. var modalcontent = { description1 : '<div id = "description"><div class = "tbc"> '+ '<label class = "tbc" for = "tbc">Description</label>'+ '</div>'+ '<div class = "tbc">'+ '<input type = "text" class = "tbc" name = "description" id = "tbc" placeholder = "Enter description">'+ '</div>'+ '</div>'+ '<!--end description div-->' } (fiddle) Alternatively, you can create multi line string by using the character, those only work in newer implementations. See this related question or the language specification. Note: It's usually not the best idea to store HTML in strings, it makes it harder to debug and work with. You can usually

Categories : Javascript

Indexing mongodb collection with 2dsphere indexes and IP address indexes
This should work: db.position.ensureIndex({"geoField.coordinates":"2dsphere","ipaddress":1}) Take a look at this article I hope it helps

Categories : Mongodb

After using array get, how to remove the indexes in TCL
The simplest and most basic way I think would be to use a foreach loop: % set list {0 a 1 b 2 c 3 d} % set entrylist {} % foreach {id entry} $list { % lappend entrylist $entry % } % puts $entrylist a b c d

Categories : Arrays

Using resources as array indexes in PHP
I use this function with multi_curl, very effective for sorting to make sure text doesn't line up randomly: function get_resource_id($resource) { if (!is_resource($resource)) return false; return array_pop(explode('#', (string)$resource)); }

Categories : PHP

Combining array indexes
You should make a class to store the date rather than the use two separate arrays. public class Employee { private int sales; private String name; public Employee(String name, int sales){ this.name = name; this.sales = sales; } public String getName(){ return this.name; } public int getSales(){ return this.sales; } } Now store the name and sales as local variables when you read in from your Scanner and pass them to the Employee constructor. You can then create an Employee array[] or ArrayList<Employee> and sort this array/arraylist on Employee.getSales() Like so: import java.util.Scanner; import java.util.Arrays; public class EmpArray { public static void main(String[] args){ employee();

Categories : Java

read array from 1 to 3 indexes
You can accomplish this by using implode and array_slice: $start = 1; $end = 3; $str = implode("/", array_slice($arr, $start, $end - $start + 1));

Categories : PHP

Calculating the sum of all odd array indexes
String id = "9506265088085"; int[] intArray = new int[strArray.length]; int sum = 0; for (int i = 1; i < id.length(); i+=2) { sum += Integer.parseInt(String.valueOf(id.charAt(i))); } System.out.println(sum);

Categories : Java

How to append regex literal with string literal in javascript
Don't use a literal. Use the RegExp constructor : var reg = new RegExp("(\d+\s" + query + ")");

Categories : Javascript

Remove array of indexes from array
How about Array.prototype.remove = function (indexes) { if(indexes.prototype.constructor.name == "Array") { // your code to support indexes } else { // the regular code to remove single or multiple indexes } };

Categories : Javascript

Difference between paired indexes and single column indexes?
You wasn't using the paired index. You are restricting your data based on one of the columns at a time. Not both at once. In fact you are just using the TIME index because of your WHERE clause. The paired index would have speed your query up if your WHERE clause restricts the SENSOR_ID additionally. To see which indexes are really used you should have a look at the execution plan of the query.

Categories : Mysql

Retrieve property value from array literal
obj is not a object as you expect, it's an array of objects. You'll need to iterate the array and then iterate the keys in each array item. var i, key; for (i = 0; i < obj.length; i++) { for (key in obj[i]) { if (obj[i].hasOwnProperty(key) { console.log(key + " -> " + obj[i][key]); } } }

Categories : Javascript

Literal array notation in Objective-C
This is an exact equivalent of: [[cellsArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]; cellsArray is an array of arrays, a 2-dimensional array. its count is number of sections in table view. every array represents a section and contains cells for this section. so you can access each cell by its row

Categories : IOS

I can't compare associative array indexes to a var
Use this syntax: foreach ($array as $key => $value) foreach ($list_array as $index => $key) { if($index == 'second' ) { echo $key['one']. ' - '. $key['two']; } } One suggestion though: Rename $key to an appropriate and meaningful name in your context! If you do not find any or if your function works with arrays in general, use $value since this term is very well-known among developers: foreach ($list_array as $index => $value) { if($index == 'second') { echo $value['one'] . ' - ' . $value['two']; } } Consider u_mulder's answer below if you just want to directly access the key. As far as I can see in your code, a loop is unnecessary.

Categories : PHP

explicit indexes in C array literals?
It's part of standard C (C99 and newer), called "designated initialization". From 6.7.9 Initialization, paragraph 6: If a designator has the form [ constant-expression ] then the current object ... shall have array type and the expression shall be an integer constant expression. If the array is of unknown size, any nonnegative value is valid. And paragraph 33: EXAMPLE 9 Arrays can be initialized to correspond to the elements of an enumeration by using designators: enum { member_one, member_two }; const char *nm[] = { [member_two] = "member two", [member_one] = "member one", }; According to answers at this question, C++ doesn't support the same behaviour. Your compiler may provide extensions. Perhaps more helpful to you (and a direct answer to your questi

Categories : C++

PHP - Certain array indexes not accepting variables
I figured out my problem, and it would not have been determinable from what I posted. I tested $tags[intval($links[1][1])] and it worked.The $links array is being generated by exploding a string (1, 2). I was axploding on "," not ", " so the value of the second entry was " 2" instead of "2", hence the intval. The string needs to be adjusted to "1,2" or the explode needs to be adjusted to ", ". Either way fixes the problem.

Categories : PHP

change indexes after array sorting
Use the key order with caution: when transferring JSON, Chrome will re-sort your indices, whereas Firefox will keep them intact. You can't be sure if the order is kept or not. The only way to solve this is to use $array = array_values($ret) or in your code change the last loop to foreach ($sorter as $ii => $va) $ret[]=$array[$ii]; after your sort to create a clean ascending order. If you need the old index you have to store it within your data for each node.

Categories : PHP

Passing np.array indexes into functions
Note: I do not know Django. I am assuming you can only pass a string to the Django model. You could eval the string "slice(...)": In [101]: arr = np.random.random((100,)) In [102]: arr[eval("slice(6,10)")] Out[102]: array([ 0.60968632, 0.17116998, 0.24861622, 0.37071511]) or, if you have a 2D-array, you could even pass a stringified tuple of slices: In [105]: arr = arr.reshape(10,10) In [107]: arr[eval("slice(6,10), slice(2,5)")] Out[107]: array([[ 0.23903737, 0.07691556, 0.08544998], [ 0.79273288, 0.73710837, 0.11193991], [ 0.65617212, 0.53528755, 0.53514291], [ 0.01626145, 0.59864093, 0.71240672]]) Note, however, that eval is inherently unsafe if the string comes from user input. Here is a safer way: Pass a stringified list of tuples. E

Categories : Python

JavaScript Array of Key/Value Pairs Uses Literal Variable Name for Key
Bracket notation is the correct way to use a dynamic key name: books[bookTitle] = author However, you need to use an intermediate object: var books = []; var bookTitle = "Tom Sawyer"; var author = "Mark Twain"; var foo = {}; foo[bookTitle] = author; books.push(foo); console.log("books: %s", JSON.stringify(books))

Categories : Javascript

returning a std::array from a user defined literal in c++11
You need a template literal operator. Function parameters are never valid constant expressions; even if normal usage makes sense your operator still has to support an explicit call of the form operator "" _a1 ( "hello", 5 ); For integer and floating user-defined literals, there is a templated form that can return an array: template< char ... c > constexpr std::array< char, sizeof ... (c) > operator "" _a1 () { return { c ... }; } This is not (yet?) supported for string literals, perhaps because of issues with multibyte encoding. So, you're out of luck in this particular approach. You can take another tack, though, and take the string as an array. template< std::size_t size > constexpr std::array< char, size > string_to_array( char const (&str)[ size

Categories : C++

Pass array literal to PostgreSQL function
SQL NOT IN works with sets. Since you are passing in an array, use <> ALL. You have to be extra careful not to involve any NULL values with such an expression, because NULL <> anything never evaluates to TRUE and therefore never qualifies in a WHERE clause. Your function could look like this: CREATE OR REPLACE FUNCTION get_questions(vcode text[]) RETURNS TABLE(id int, title text, code text) AS $func$ SELECT q.id, q.title, q.code FROM questions q WHERE q.code <> ALL ($1); $func$ LANGUAGE sql; Call: SELECT * FROM get_questions('{qcode2, qcode2}'); Or (alternative syntax with an array constructor): SELECT * FROM get_questions(ARRAY['qcode2', 'qcode2']); Major points: Using a simple SQL function since there is nothing in your question that would require th

Categories : PHP

C - Comparing string literal with character array
I think this is a perfect starting point for you: http://www.wikihow.com/Compare-Two-Strings-in-C-Programming It's probably written at the right level for you. Good luck and welcome to stackoverflow!

Categories : C

Reindex array by increasing and decreasing all of top indexes
The easiest way would probably to use foreach and make a new array... like this: $new = array(); foreach($arr as $k=>$v) { $new[$k+1] = $v; // either increase $new[$k-1] = $v; // or decrease } You can also perform the operation by passing the original array by reference.

Categories : PHP

Why array indexes are zero based in most programming languages?
I guess it has mostly historical reasons, new languages just try to use the existing convention which programmers are familiar with. Older languages from which this rule originated were close to the metal, and an index is really the distance from the starting element, hence 0 makes sense for the first element.

Categories : Arrays

Is a character literal ('A') exactly equivalent to a hex literal (0x41)
Is there any situation in which changing 'A' to 0x41 could change the behaviour of my program? Yes, in EBCDIC character set 'A' value is not 0x41 but 0xC1. C does not require ASCII character set. (C99, 5.2.1p1) "The values of the members of the execution character set are implementation-defined."

Categories : C

Parse a large string literal in JS with regex into object array
Description This regex will parse the text into a roman numeral and body. The body can then be split on the new line . ^s+([CDMLXVI]{1,12})(?: | |$).*?(?:^.*?)(^.*?)(?=^s+([MLXVI]{1,12})(?: | |$)|) Capture Groups Group 0 get the entire matching section gets the roman numeral gets the body of the section, not including the roman numeral Javascript Code Example: Sample text pulled from your link VII Lo! in the orient when the gracious light Lifts up his burning head, each under eye Doth homage to his new-appearing sight, VIII Music to hear, why hear'st thou music sadly? Sweets with sweets war not, joy delights in joy: Why lov'st thou that which thou receiv'st not gladly, Or else receiv'st with pleasure thine annoy? IX Is it for fear to wet a wid

Categories : Javascript

Setting object property to Array Literal throwing error
new is used to instantiate an object using a constructor (which is a function, hence your error message). In your case simply use var a = { aa: [] } Some references : Values, variables and literals types

Categories : Javascript

How to deal with cycling through an unknown number of indexes in an array or list
My solutions was to take the name and check if it matched the regex formula provided by another user of stackoverflow. The following code should be credited to Lib. def getEntryName(var_string) : # From LIB @ Stackoverflow.com result = re.search(r'(.*?)((?:[d*])*)$', var_string) var_name = result.group(1) numbers = re.findall(r'[(d+)]', result.group(2)) return var_name, numbers This returns the base name of a variable and a list called "numbers" which contains all of the indexes of all of the arrays. Now I used a recurvise call to find iterate through any number of indexes! def BracketHandler( PassedRange, var_name, var_Length, var_startA, numbers ) for i in range( 0, int( PassedRange ) - 1 ) : # We cycle through it! if numbers : # If there ar

Categories : Python

Checking if value in slave array exists in master array Quickly without loop via PHP
The only other way to do this is to use an associative array with your values as keys (well, you could custom-implement another storage container specifically for this, but that'd be overkill imo). Then, you can check with isset. For example: $masterArray = array(....); // same thing, but with values as keys instead of values foreach($_POST as $key => $value) { if(isset($masterArray[$value])) { // do stuff } else { // do stuff } } I'm kind of curious what the point of doing this is anyway, especially given the statement printed by your echo call. There may be an even better way to accomplish your goal than this. EDIT: Another method suggested by grossvogel: loop over $masterArray instead of $_POST. If you expect $_POST to be a large set of data consisten

Categories : PHP

Why does SoapClient using WSDL in document/literal style return array with extra key element?
Are you totally sure that it's not specified in the WSDL definition somewhere? I'm sure that the extra element is not added by the server for fun :) Or perhaps it's a consequence of the encoding style of the document. The item element is very common in SAP Webservices (which I use regularly) when returning content of an array type but, like I wrote above, it's clearly specified in the WSDL. You may also find that when the array has only one element item will not be an array so take care of that in your code using if(!is_array($messages->item)) { $messages->item = array($messages->item); }

Categories : PHP

Effecient Javascript Object filtering using multiple array indexes. How much data before using Node?
Basically you want var arrays = { "Country": […], … }; var result = my50000items.filter(function(item) { for (var prop in arrays) if (arrays[prop].indexOf(item[prop]) == -1) return false; return true; }); You can optimise this by replacing the indexOf call with a faster property lookup. To do so, make: var lookups = {}; for (var prop in arrays) { var obj = lookups[prop] = {}; for (var i=0; i<arrays[prop].length; i++) obj[arrays[prop][i]] = true; } Then you can use var result = my50000items.filter(function(item) { for (var prop in lookups) if (!lookups[prop][item[prop]]) return false; return true; });

Categories : Javascript

Selection Indexes are not same to getText indexes
See Text and New Lines for more information and a solution. The basics of this link is to use: int length = textPane.getDocument().getLength(); String text = textPane.getDocument().getText(0, length); The above will only return " " as the EOL string so the offsets will match when you do a search and then select the text.

Categories : Java

Is it inefficient to use implicit array creation (a.k.a. shorthand or literal notation) in loops or function parameters?
Performance wise, the difference will be negligible, but implicit creation is usually slightly slower but implicit is far more readable which is more important long term unless you're dealing with some sort of massive scaling problem. Edit: Wrote a quick test script, and I get completely different results. I'd say both are so close, it shouldn't matter, but run the test on your system. I'm running this on a Macbook Pro with CF10, it may vary with your specific implementation. Maybe the resulting java byte output might reveal any structural differences between the two methods. <cfset iterations = 1000000> <cfset start = getTickCount()> <cfloop from="1" to="#iterations#" index="x"> <cfset a[x] = arrayNew(1)> <cfset a[x][1] = x> <cfset a[x][2]

Categories : Arrays

Do we need to delete the collection named system.indexes to make new indexes apply on the collection
Thew system.profile collection is not there however, no you do not. The profile collection is the output of the profiler, nothing more. Indexes will still apply. Edit Since your question says two things, no you do not need to drop system.indexes either, MongoDB will handle updating the records in there for you. Dropping it might actually damage your database.

Categories : Mongodb



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