w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
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

Oracle 11g: shuffling VARCHAR2 column to get random mapping
You could use row_number to create a random pair: with names1 as ( select row_number() over (order by dbms_random.value) as rn , name from Company ) , names2 as ( select row_number() over (order by dbms_random.value) as rn , name from Company ) select n1.name as name1 , n2.name as name2 from names1 n1 join names2 n2 on n1.rn = n2.rn

Categories : SQL

Math.random and splice to randomly delete array elements
You should be using c.splice(num, 1);, because you want to remove one element from the array at a time, not num elements. This updated fiddle logs the length after each removal, and always outputs 9,8,7,6,5.

Categories : Javascript

shuffling array javascript
you are getting a random value, not a random index into the deck for (r=0;r<deck.length;r++){ var randomindex = Math.floor(Math.random()*deck.length); new_deck.push(deck[randomindex]); }

Categories : Javascript

Very non-random factor of Math.random when filling an array with random numbers
If the length is even, you add all the numbers once and subtract all of them once – of course, the result is 0. Example with length==6: /*i==0*/ sum += rand[0] + rand[5]; /*i==1*/ sum -= rand[1] + rand[4]; /*i==2*/ sum += rand[2] + rand[3]; /*i==3*/ sum -= rand[3] + rand[2]; /*i==4*/ sum += rand[4] + rand[1]; /*i==5*/ sum -= rand[5] + rand[0]; Did you try any uneven lengths?

Categories : Java

How do I take a JS array that has some elements that are also arrays and make ALL array elements top level elements
You don't need the second step to have an array of arrays, just join then split it by the comma: var array = ["item1", "item2", "item3, item4", "item5", "item6"] console.log(array.join(',').split(',')); Example fiddle

Categories : Javascript

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

How do I choose a random element from a random array?
your code is correct, but array initialization is not. Here's what you have to do: animals = ['dog', 'cat', 'mouse'] planets = ['jupiter', 'mars'] fruits = ['apple', 'orange', 'mango'] categories = [animals, planets, fruits] In your code, animals is array, planets and fruits are arrays of arrays, and categories is array of three arrays, inside of each one is one of you variables

Categories : Ruby

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

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

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

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

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

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

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

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

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++

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

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

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

Efficient way to check if elements of an array is a substring of elements in another array
die if @array1 != @array2; for (0..$#array1) { die if $array2[$_] ne qq{Name: creating "$array1[$_]"}; } or if the Name part is variable, die if @array1 != @array2; for (0..$#array1) { die if $array2[$_] !~ /: creating "Q$array1[$_]E"$/; }

Categories : Arrays

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

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

Random groups of elements of a dictionary
You could use a generator to produce random values: import random def random_group(d, size=10): keys = list(d.keys()) random.shuffle(keys) for i in range(0, len(keys), size): yield [(key, d[key]) for key in keys[i:i + size]] This produces groups of 10 (key, value) pairs at a time: for group in random_group(your_dictionary): print group You can adjust the function to produce just keys, just values or dictionaries instead: yield keys[i:i + size] # list of keys yield [d[key] for key in keys[i:i + size]] # list of values yield {key: d[key] for key in keys[i:i + size]} # dictionary

Categories : Python

Draw n random elements (w/o replacment) from an stl container
I assume by 'random elements' you mean elements distributed evenly. Since you have no knowledge of the sequence's length, and you can't calculate it beforehand, you have to build your random sequence gradually. So let's do that, and hope the probabilities we use all add up nicely so we end up with what we wanted in the first place. We'll do this in two steps. First, decide which of the sequence numbers are drawn, and then we can choose a random order for them, if we need to (it wasn't clear from the question). And I'll call your N 'K', because it's easier for me. First we create a K element array, to hold the K drawn elements. We go over the first K elements of the sequence and copy them to the array. If the sequence doesn't have K elements, we say "No can do". Now we know we have K ra

Categories : C++

IE sets :focus on lots of random elements
you might give this a try :focus[tabindex] { box-shadow: 2px 2px 2px red; } you can even set different index results: :focus[tabindex='1'] { box-shadow: 2px 2px 2px red; }

Categories : CSS

Given a list of length n select k random elements using C#
Take a look at this extension method http://extensionmethod.net/csharp/ienumerable-t/shuffle. You could add Skip() Take() type to page the values out the final list.

Categories : C#

NumberFormatException while selecting random elements from a big file
Any unparsable String if you pass to parseInt method then it will raise NumberFormatException. Like empty String and also Integer can hold the maximum & minimum value an int can have, 2147483647 or -2147483648. And if value goes beyond of that then it raise NumberFormatException If the string does not contain a parsable integer. ([Documentation][1])

Categories : Java

Is there a more idiomatic way to get N random elements of a collection in Clojure?
An easy solution but not optimal for big collections could be: (take n (shuffle coll)) Has the "advantage" of not repeating elements. Also you could implement a lazy-shuffle but it will involve more code.

Categories : Clojure

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

Associate Array / Key Pair Array In Javascript arranged in with random order of keys.
Looks to me as if your using an object. The sorting of an object's properties is never guaranteed. I don't think internet explorer (at least the old versions) sorts the properties but chrome does by default. Your code is invalid, it should have the properties as strings if they are not numbers. And you would have to use an object a = {}; a["T1001"] ="B" a["T1005"] = "A" a["T1003"] ="C" You can either use two arrays to store your properties and the value if you want to preserve the ordering, or you cannot guarantee the ordering if you insist on using an object. Two arrays a1 = []; a2 = [] a1[0] = "T1001"; a2[0] = "B"; a1[1] = "T1005"; a2[1] = "A"; a1[2] = "T1003"; a2[2] = "C"; EDIT: Unless I guessed at what you meant wrong and that T1001, etc are variables containing numbers.

Categories : Javascript

Why does inserting sequential elements in a tree require more time than inserting random elements into a tree?
Inserting sequential items( 1,2,3,4...) to a binary tree will cause it to always add the nodes to the same side( left for example ) . When you insert random items you will add nodes randomly left and right. Adding sequentially will cause the list to behave as a ordinary linked list ( for the sequential items) because new items will have to visit every previously added item and that will take O(n) steps , when adding randomly it will take O( log N) steps on average.

Categories : C++

How do you store random parts of an array within an array and then print as a list?
I don't know if I get what you need, but I found your code really chaotic, so I created my own function from your description, here's whole with repaired arrays and everything $mars = array ('How big is Mars?', 'How many moons does Mars have?', 'How far away is Mars?', 'What is the highest point on Mars?'); $jupiter = array ('How big is Jupiter?', 'How many moons does Jupiter have?', 'How far away is Jupiter?', 'What is the highest point on Jupiter?'); $earth = array ('How big is Earth?', 'How many moons does Earth have?', 'How far away is Earth?', 'What is the highest point on Earth?'); $all = array($mars, $jupiter, $earth); function createList($a) { echo "<ul>"; foreach ($a as $array) { $questions = count($array); $idquestion = rand(0, $questions-1); echo "&

Categories : PHP

CUDA - Array Generating random array on gpu and its modification using kernel
This is wrong: cudaMalloc((void**)&randomArray_gpu, size*size*sizeof(float)); We don't use cudaMalloc with __device__ variables. If you do proper cuda error checking I'm pretty sure that line will throw an error. If you really want to use a __device__ pointer this way, you need to create a separate normal pointer, cudaMalloc that, then copy the pointer value to the device pointer using cudaMemcpyToSymbol: float *my_dev_pointer; cudaMalloc((void**)&my_dev_pointer, size*size*sizeof(float)); cudaMemcpyToSymbol(randomArray_gpu, &my_dev_pointer, sizeof(float *)); Whenever you are having trouble with your CUDA programs, you should do proper cuda error checking. It will likely focus your attention on what is wrong. And, yes, kernels can access __device__ variables without th

Categories : Visual C++

How to get two (pseudo)random but distinct from each other container iterators/elements?
•Is this the best way to get two different values from a container? This would generate different values, but you could possibly get an index that is out of range because you increment and decrement. I would suggest just re-generating one of the mission locations while it equals the other instead of incrementing, as that will also remove some bias that incrementing causes. Also, I don't know why you have the if(!mission_start_location) block, what are you trying to achieve with this? EDIT I saw that you were worried about infinite loops. You shouldn't be. This is the most standard C++ way to generate non-equal random numbers, and your chances of entering an infinite loop are extremely unlikely, even if your vector has size 2 (in which case, it will take on average 2 iterations to g

Categories : C++

filling numpy array with random element from another array
I had to do something similar a while ago. def getRandomList(n, source): ''' Returns a list of n elements randomly selected from source. Selection is done without replacement. ''' list = source indices = range(len(source)) randIndices = [] for i in range(n): randIndex = indices.pop(np.random.randint(0, high=len(indices))) randIndices += [randIndex] return [source[index] for index in randIndices] data = [1,2,3,4,5,6,7,8,9] randomData = getRandomList(4, data) print randomData

Categories : Python



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