w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Finding matching objects in array: array or object
My guess is you're a Java or C++ programmer because your thinking is class-centric. The Ruby way is duck typing. For classification pairing to work, you need only know if the items in a list respond_to? a type method and a pairedby=. It would be pretty standard Ruby to implement this operation as a mix-in on arrays. You should probably not split such simple functionality across two classes unless there is a need to access the inner function, i.e. pair_with_next. One reason: By splitting the function you pretty much doom yourself to O(n^2) performance when O(n) is trivial to obtain. Make one pass. Keep a queue of A indexes. When you see a B, remove the head index from the queue. That's the A that matches the current B. Continue until complete. If the queue is empty, assign nil

Categories : Ruby

Using JQuery/JavaScript how would I group values in an array of objects and create a new array of objects from the groups
If you're willing to use Underscore.js, this becomes pretty trivial. Assuming data is your original list of json objects, this will achieve what you're after: var groups = []; var by_grade = _.groupBy(data, function(obj) { return obj['grade'] }); _.each(by_grade, function(objs, grade) { var group = {}; group['grade'] = grade; group['ids'] = _.pluck(objs, 'id'); group['versions'] = _.pluck(objs, 'version'); // Use the following if the value is known to be // the same for all grouped objects group['platform'] = objs[0]['platform']; // And the rest... groups.push(group); }); _.groupBy() will group your objects by grade, resulting in two objects with the keys X and A, whose values are lists of objects with the corresponding grades. You can then loop ove

Categories : Javascript

java method accepts array of objects and a double then returns an array of objects
You need to create the array before you write to it. House[] lowPriceHouses = null; should be something like House[] lowPriceHouses = new House[houses.length]; you actually want a smaller array since, you might not need all houses.. It would be easier to make this a ArrayList and then convert it toArray before returning. for (int i = 0; i <= houses.length; i++) You want to do only < This is because when you have an array of size 10, the elements are indexed from 0 - 9. Thus accessing the element arr[10] will lead to issues.

Categories : Java

In a Javascript array of objects, how can I target a specific array element by name/ID if that element is an array of objects itself?
First off, comments should be an array and you have an object. Then proceed like this: reviews[someIndex].comments.push( { commenter: 'john', comment: 'hello!!'}); I.e. if you need to add a comment to the first post do: reviews[0].comments.push( { /* your comment */ } ); EDIT : I always used get() to retrieve an index but I seem to not be able to find much documentation about it, so I'm assuming (though I'm not sure) that [i] is a more standard way of doing things, hence why I changed the example. However the concept of pushing into comments doesn't change. EDIT 2: OP wants to target a particular element in an array. I would use Array.prototype.indexOf as described here where you can find a solution for browsers that do not support indexOf as well.

Categories : Javascript

Finding objects nearby
What should I do? Get the output of the produced query (django-debug-toolbar will work for this). Run manual queries against your database server until you get it working. Then come back and modify your extra.

Categories : Python

Finding an object in NSSet of different objects
If you create your predicate using + (NSPredicate *)predicateWithBlock:(BOOL (^)(id evaluatedObject, NSDictionary *bindings))block then you can perform a check in the block to ensure that the evaluatedObject has the key and then perform the appropriate check.

Categories : Objective C

Flattening an array of objects into another array of objects using javascript
The following should work for you: function combine(arr) { var newObj = {}; // combine the comments for (var i=0; i < arr.length; i++) { if (newObj[arr[i].itemId]) { newObj[arr[i].itemId].push(arr[i].comments); } else { newObj[arr[i].itemId] = [arr[i].comments]; } } // make the list var keys = Object.keys(newObj); return keys.map(function(key){return {itemId: key, comments: newObj[key]} }) }

Categories : Javascript

accessing a method in an array of objects that are in an array of objects
I think you accidentally left out the index into polygons (e.g. polygons[i]). Also, currently you have intersect being assigned the value of intersect() which means it is overwriting any other values given to the boolean intersect in previous loop iterations. I have added an if statement that will break out of the function immediately if that case if found instead. However, you could instead do something like intersect = intersect || ... .intersect() if you want to keep that variable. Try this: private boolean intersect(Polygon[] polygons, Line[] the_path, int i, int j) { int k = 0; for (i = 0; i < polygons.length; i++) { for (j = 0; j < polygons[i]._lines.length; j++) { for (k = 0; k < the_path.length; k++) { if (polygons[i]._lines[j].intersect(the_path[k

Categories : Java

what is the difference between a mul-dim array of mul-dim objects and an array of one higher dim that contains only one-dim objects
In C and C++, a multidimensional array is simply an array of arrays. On the other hand, there are a lot of data structures that emulate multidimensional arrays using pointers to rows or pointers to elements. Depending on how the data structure is defined, you can use the same arr[x][y] syntax to access the elements. Array indexing is defined in terms of pointer arithmetic, and in the common case where the prefix is the name of an array object, the name is implicitly converted to a pointer; if the prefix is already a pointer no conversion is done. Recommended reading: Section 6 of the comp.lang.c FAQ. (In C++, it's generally easier to use container classes rather than C-style arrays.)

Categories : C++

finding UI objects in xcode UI object library
May be that was Mac OS controls. Sometimes it show up. Me too don't know when exactly it comes up. but if you are creating iOS app then you don't need that. it can't be used in iOS app. so its good that you leave that. Cheers!!

Categories : IOS

Finding "Missing" objects in image using openCV
Well, this is also a kind of motion detection, since you can think the Mat has move out of the scene. If your images are aligned (i.e. if the camera is placed at the same position), image subtraction is a good way to begin with. With this you can have a clue of what objects have appeared or disappeared. Note that this technique is not suitable if you allow your Mat to appear in the image but at a different position. On the other hand, if you are watching that certain Mat, you can go with object detection, so that if you are not able to detect the object in the image, you can suppose the object has been stolen. You can achieve this by extracting features from an image of the object (e.g. SURF) and matching these later with features extracted from your webcam image. If that black Mat must b

Categories : C++

Finding which code allocated large objects in Sun JVM
I'm not sure there is a way to do this with just command lines to the JVM, but you should be able to use hprof to dump the heap, and then analyze the dump using jhat to find the large objects and where they were allocated (assuming they are still in the heap when hprof dumps it). You can use hprof to dump the heap like so: java -agentlib:hprof=heap=dump This will give you a file .hprof, then you can run jhat: jhat <pid>.hprof jhat will run a webserver at: http://localhost:7000. So point your browser there and take al ook.

Categories : Misc

Effective algorithm for finding value objects in collection
If by collection you mean ArrayCollection, I would recommend to use Vector instead. Vectors are around 50 times faster then ArrayCollections. If you need databinding, you could have a look at VectorCollection, but I can't imagine the performance to be anywhere close to Vector. Also if you are not extending class SomeObjectType anywhere, you could gain some performance (especially on iOS) by making it final class SomeObjectType.

Categories : Actionscript

Algorithm for finding shortest path between 2 objects
This problem is known as finding shortest path between two points with polygonal obstacle, and studied a lot in literature. See here for one example. All algorithms for this is by converting problem to the graph theory problem then running Dijkstra. To doing this: Each vertex in any polygon is vertex in your graph. Start point and end points are also vertices in the graph. Between two vertex there is an edge, if they are visible to each other, to achieve this we can use triangulation algorithms. Weight of each edge is the distance between its two endpoints in Euclidean space. Now we are ready to run any shortest path algorithm. The hard part is triangulation, I think triangle library fits for your requirements. Also easier way is searching the web by the keywords that I said in the fir

Categories : Algorithm

What's a good algorithm for finding if two objects are connected in a 2D grid?
This is a simple 'flood-fill' approach to what you want Add point A to a set called scanning Also create a set called checked (leave it empty at the beginning) while point B is not found and the set scanning is not empty: for each point in the scanning set do the following: if it is point B, then stop. remove the point from the scanning set and add to checked for each neighbor, if it is not added to checked or scanning then add the neighbor to scanning

Categories : Algorithm

How can I add objects to an array list using the equals method to exclude similar objects?
There is a lot to discover in the Java Collection. You are using the wrong data structure, you can add two different objects in a List because the purpose of the list is to be : An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. So you have the elements in a given order which is kept when adding objects and you can access objects at any given index in this order. Now it seems that's not what you want, you'd rather have no duplicate elements rather than an order, right ? If so you need to use a class that implements the Set interface which purpose is to be : A collection that

Categories : Java

Build immutable NSDictionary from array with custom objects where each key could have multiple objects
There's no built-in concept of a one-to-many dictionary so I don't think there's a neater way to achieve exactly what you write — there's certainly no single line of syntax like there is for a whole bunch of other common manipulations. That said, minor suggestions would be: Use key-value coding to read the keyed property. So replace your references to obj.key with a single call to [obj valueForKeyPath:keyPath] and take keyPath as a parameter. Then you've got to write this code only once. For safety you should check that obj.key isn't nil. If it is then you'll end up doing [tmpMutableDic setObject:... forKey:nil], which raises an exception because dictionaries can't store values against a nil key. copy will return an immutable dictionary but the values in it will still be mutable arra

Categories : IOS

Remove objects with duplicate values in array of stdClass objects
You can do something like this: $newArray = array(); foreach ($array as $value) { $newArray[$value->name] = $value; } By the end of that cycle you will have an array, where every name meets only once (and you will keep the latest occurrence of that name).

Categories : PHP

Parsing an array of json objects to scala objects with pickling
"Collections of non-primitive types are not supported" (yet) https://github.com/scala/pickling/issues/6 From what I can see, scala.pickling is still very rough around the edges. Furthermore, the default pickling format JSONPickleFormat requires some meta-data (the tpe field) and I'm guessing won't be parsing arbitrary JSON objects.

Categories : Java

ECMA5 array methods - Finding the first object of a kind in an array
There isn't a built-in method for that in ES5. ES6 is adding Array.prototype.find for this http://people.mozilla.org/~jorendorff/es6-draft.html#sec-22.1.3.8 console.log(things.find(getBob)); Here's a polyfill adapted from https://gist.github.com/dcherman/5167353 (function() { function polyfill(fnName) { if (!Array.prototype[fnName]) { Object.defineProperty(Array.prototype, fnName, { value: function( predicate /*, thisArg */ ) { var i, len, test, thisArg = arguments[ 1 ]; if ( typeof predicate !== "function" ) { throw new TypeError(); } test = !thisArg ? predicate : function() { return predicate.apply( thisArg, arg

Categories : Javascript

how to access variables in objects in an array of objects in java
Here is your problem: public Droid droid_array; Has type Droid. This is your class level property. Inside the MainGamePanel constructor you hide the class level property with this variable: Droid[] droid_array Once you leave the MainGamePanel constructor the Droid[] droid_array variable goes out of scope. The Update method references the public Droid droid_array class property, which is not an array.

Categories : Java

Find where array of objects does not contain objects with param with specific value
Use the $ne operator and dot notation to do this: UserModel.find({'registrations.fieldA': {$ne: 'specific value'}}, cb); When used with an array field like this, $ne will only match docs where no array element contains the specific value.

Categories : Javascript

Finding a way to create a list of array from another complex array
use array_merge_recursive for example $ar1=array('color'=>"green"); $ar2=array('color'=>"blue"); $result = array_merge_recursive($ar1, $ar2); output : Array ( [color] => Array ( [0] => green [1] => blue ) )

Categories : PHP

Initializing objects in array of pointer to objects
The only problem I see is that you are trying to initialize lists with with an array of List objects instead of an array of pointers to List objects. change lists = new List[listCount]; to lists = new List*[listCount];

Categories : C++

Loading objects into an array of pointer to objects
Use a std::vector<Competitor> to store your competitors, and add them with push_back().

Categories : C++

Counting associated objects from an array of parent objects
Asuming there are household_id in Neighbor model @household_ids = [31, 15, 30, 38, 1, 5, 32, 25, 10, 26, 14,29] total_number_of_neighbors = Neighbor.where('household_id IN (?)', @household_ids).count

Categories : Ruby On Rails

Finding missing array in array of arrays
I hope that this helps you, function findDeselectedItem(CurrentArray, PreviousArray) { var CurrentArrSize = CurrentArray.length; var PreviousArrSize = PreviousArray.length; var deselectedItem = []; // loop through previous array for(var j = 0; j < PreviousArrSize; j++) { var checkArray = PreviousArrSize[j]; // loop through 2nd array to match both array for(var i = 0; i < CurrentArrSize; i++) { // look for same thing in new array if (CurrentArray[i].indexOf(checkArray) == -1) deselectedItem.push(CurrentArray[i]); } } return deselectedItem; }

Categories : Javascript

finding if the strings in an array is exists in another array
Do : for (int y = 0; y < question.length; y++) { } instead of <=. The problem outcomes from the fact you don't have a question[question.length] element. Also, I don't see where you declare the y variable. Update: Here's a complete sample: String[] questions = {"adorable", "able", "adventurous"}; String u = "able adorable asd"; String[] t = u.split(" "); for (int y = 0; y < questions.length; y++) { for (int w = 0; w < t.length; w++) { if (t[w].equals(questions[y])) { System.out.print(t[w] + " "); break; } } } This prints: adorable able

Categories : Java

Java Array objects returns array's type instead of Array
The class of what the reference is pointing to is a String array. if you want to test to see if that reference is part of an array, then there is a special method for that, isArray. System.out.println(stt.getClass().isArray()); As some other have noted, with a closer look you can see the difference in the output just using class [Ljava.lang.String; // Array of String class java.lang.String // String

Categories : Java

Finding sub-array sum in an integer array
When S is not too large, we can count the distinct sums with one (fast) polynomial multiplication. When S is larger, N is hopefully small enough to use a quadratic algorithm. Let x_1, x_2, ..., x_n be the array elements. Let y_0 = 0 and y_i = x_1 + x_2 + ... + x_i. Let P(z) = z^{y_0} + z^{y_1} + ... + z^{y_n}. Compute the product of polynomials P(z) * P(z^{-1}); the coefficient of z^k with k > 0 is nonzero if and only if k is a sub-array sum, so we just have to read off the number of nonzero coefficients of positive powers. The powers of z, moreover, range from -S to S, so the multiplication takes time on the order of S log S.

Categories : Algorithm

Web worker crashes Chrome tab when passing large array of objects which have array buffers
Have you tried passing data to Worker thread using Transfer of Ownership. That is particularly useful when you are passing large Array Buffers, that will require you to change postMessage call with one extra argument postMessage(ObjectToTransfer,[ObjectToTransfer.buffer,.....]); This way you can clone entire object but transfer Array Buffers in that object. Checkout Using transferable objects from a Web Worker

Categories : Javascript

Jackson parsing JSON containing an array of objects and array of maps w/ dynamic keys
You could probably get around this by writing your own custom deserializer and register it with the object mapper that you are using. This should work as you will have complete control of how each object is deserialized into a User object. See this jackson documentation on how to roll your own deserializer. Would also like to say, if you have control over the json structure - I would change the key value (which I am guessing is an ID for the user) to be a part of the actual json object as opposed to being the key. This will help you avoid the issue all together. For example: "users":{ { "id":"1234", "firstname":"Joe", "lastname":"Smith" }, { "id":"9876", "firstname":"Bob", "lastname":"A

Categories : Java

How to most efficiently generate an array based on collapsed values in an array of objects?
Edit: Sorry, misread your question. This doesn't really do what you want -- It doesn't take the names into account. But it is still not fully clear to me what the problem exactly is. The trick with this kind of problem usually is to keep a map (or nested maps) of the information you have collected so far, and to update it as needed. The map key usually should be the information you need to merge, so the lookup is efficient. I haven't tested the code, it should just collapse the objects into rows. Depending on what your problem really is, it may or may not be a reasonable starting point. The code puts labels into row 0 of the result, but it should be easy to add support for a predefined list as a starting point... function collapse (array) { var labels = []; var result = [labels

Categories : Javascript

Array of objects of array, how to access the invidual element without using property names?
Try this function avg(i) { for(j in data[i]) { sum=0; for(k=0;k<data[i][j].length;k++) { sum+=data[i][j][k]; } average=sum/3; document.write("value "+i+":"+average); } } Call it like this <script> avg(0); // Index </script> Working Fiddle DEMO

Categories : Javascript

Initializing an array of subclass objects creates a heterogeneous superclass array
I've never tried this myself, but I believe that matlab.mixin.Heterogeneous has a method getDefaultScalarElement that you can implement/override yourself, which will define how to backfill the initial elements of an array when you assign a later element. See about halfway down this documentation page for more information.

Categories : Matlab

Create an array of integers from an array of objects (id) and send to a web service
Can't you create a NSString with the list of integers and separate them by , and send that instead? NSMutableString *mutableList = [[NSMutableString alloc ]initWithString:@"<q14:ArrayOfint>"]; //I'll say like this because i don't know if you added them as NSNumber or NSString for(int i = 0 ;i < idProdotti.count;i++) { NSInteger value = [[idProdotti objectAtIndex:i]integerValue]; [mutableList appendFormat:@"<arr:int>%d</arr:int>",value]; } [mutableList appendFormat:@"</q14:ArrayOfint>"]; and send mutableList then release it; //second one for qtaProdotti NSMutableString *mutableList1 = [[NSMutableString alloc ]initWithString:@"<q15:ArrayOfint>"]; //I'll say like this because i don't know if you added them as NSNumber or NSString for(int i = 0 ;i <

Categories : Iphone

How to query for objects that are not already in an array (refreshing for an array) using parse.com service?
When you use whereKey:notContainedIn:, the key should be a field on your Employee. If you're following naming conventions, what you've actually supplied is the object name itself. And it looks like you supply an array of objects. You should have an identity field (or something similar) and and you should be supplying an array of identities to whereKey:notContainedIn:. You can get the array of identities with: NSArray *identities = [currentEmployees valueForKey:@"identity"]; (substitute the appropriate filed name in place of identity)

Categories : IOS

Function to turn an array of objects into an array of primitives, by key
Iterating over an array of objects and getting one key of each object is typically called as "plucking", though there are other names. In modern Javascript versions this can be trivially implemented with a map: var arr = [{ foo : 'bar', baz : 42 }, { foo : ... }, ...], foos = arr.map(function (obj) { return obj.foo; }); If you really want to abstract this into a function: function pluck(arr, key) { return arr.map(function (obj) { return obj[key]; }); } pluck(arr, 'foo'); If hasOwnProperty is a concern, your function is about as optimal as it gets already.

Categories : Javascript

JavaScript - identify a property within an array of objects as an array
pagesArray[0].pages instanceof Array works fine, though you have an extra curly brace causing a syntax error. http://jsfiddle.net/vVPCA/

Categories : Javascript

Array referencing: adding an object to array of objects
Objects in JS are always references (unlike strings or numbers). Whenever you push you're referring to the same object that is already inside the array, you need to clone: ar2.push(ar1.slice(0)); // clone ar1

Categories : Javascript



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