Javascript multi-nested Objects losing deeper-level Object's variables - javascript

I have what is basically an object that nests an object that nests a third.
What I have found is the last object's constructor information suddenly disappears.
Ex: A PlayerPos object that contains two Triangle objects, which each in turn contain three Point objects.
Here is what I have done to debug:
// Points to be used
var one = new Point(1, 2);
var two = new Point(2, 3);
var three = new Point(3, 4);
// Creation of the triangle
var tri = new Triangle(one, two, three);
// Check the console to see what it outputs.
console.log(tri);
At this point the console tells me this:
Triangle {front: Point, oneBack: Point, twoBack: Point}
Which, is exactly what I want. Everything is going well so far.
I then decided to make the PlayerPos.
// Create player position
var player = new PlayerPos(tri, tri);
// Check the log to make sure it can still find the triangles.
// (next) is one of PlayerPos's constructor names.
console.log(player.next);
This outputs:
Triangle {front: undefined, oneBack: undefined, twoBack: undefined}
Wait. What?
Why does the Triangle in PlayerPos suddenly decides to dump what it knows? And how to fix this.

Related

Tensorflow Error: Constructing tensor of shape (120800) should match the length of values (121881)

I am new to machine and new to tensorflow. As a method of learning, I have been following along with Dan Shiffman of the Coding Train as he shows how to create a color classifier.
I, however, wanted to do something different, so I collected data of hand-drawn shapes. Each shape has a label (square, circle, or triangle) and also has an array of 400 pixels (each picture was draw in a 20x20 grid). The data is stored in an object, which is contained within a JSON file.
Using p5.js's 'loadJSON' function, I can access the JSON file, iterate the entries, and create two arrays: 'shapes,' which is a an array of an array of pixels, and 'labels,' which is an array of the corresponding labels.
Below is the code, which utilizes p5's 'preload' and 'setup' functions.
let data;
let model;
// list of labels from which you can get the oneHot index
let labelList = [
"square",
"circle",
"triangle"
];
// function that is ran before setup
function preload() {
data = loadJSON('shapeData.json'); // loads the json file
}
// called after preload
function setup() {
let shapes = []; // an array of the pixels of hand-drawn shapes
let labels = []; // the corresponding label of each hand-drawn shape
// iterates over all of the entries in data
for (let record of data.entries) {
let pixels = record.pixels;
shapes.push(pixels);
labels.push(labelList.indexOf(record.label));
}
// ---------------- ERROR ------------------------
let xs = tf.tensor2d(shapes);
// these tensors work great
let labelsTensor = tf.tensor1d(labels, 'int32');
let ys = tf.oneHot(labelsTensor, 3);
}
The problem arises when I try to create the 'xs' as a tensor2d.
I get the error:
Error: Constructing tensor of shape (120800) should match the length of values (121881)
at assert (tfjs#0.11.7:2)
at new e (tfjs#0.11.7:2)
at Function.e.make (tfjs#0.11.7:2)
at Function.e.tensor (tfjs#0.11.7:2)
at Object.e.tensor2d (tfjs#0.11.7:2)
at setup (sketch.js:27)
at p5.<anonymous> (p5.js:46551)
at _runIfPreloadsAreDone (p5.js:46499)
at p5._decrementPreload (p5.js:46509)
at p5.js:59586
I have a total of 302 data points, each of which is an array of 400 binary numbers. Therefore the shape of the tensor should be [302, 400], and when I change the shape to something that is wrong (like [303, 401]) it gives an error saying that it should be [302, 400].
I am new to this whole process, so any help will be appreciated.
Thanks
I have found the fix! The separate script which downloads the data had an error. This created data of different lengths...
For instance, one shape had 400 pixels and another had 410 pixels. This difference created a problem within tensorflow. After removing the data points that did not have 400 pixels, the program worked just fine!

Run a command many times in Javascript

I have a scenario in Javascript which runs and it gives me a result in Console. In this scenario, I need to insert 5 times a pair of different coordinates (for each time). If I copy-paste the same code 5 times, with different coordinates (which they are inserted in different variables each time), it doesn't run. Below, I put the same code twice with different coordinates as I try the same thing in Jsfiddle.
//first pair of coordinates:
let x= 38.041242 ,y= 23.679595
let myString = `https://maps.googleapis.com/maps/api/streetview?location=${x},${y}&size=300x300&pitch=90`
getBase64FromImageUrl(myString);
console.log(x,y);
//second pair of coordinates:
let z= 38.041310 ,f= 23.679684
let myString = `https://maps.googleapis.com/maps/api/streetview?location=${z},${f}&size=300x300&pitch=90`
getBase64FromImageUrl(myString);
console.log(z,f);
I suspect as #ThatBrianDude and #Archer have already stated that you are getting an error because you are defining the variable myString more than once. I would also recommend you create an array of objects instead of copy pasting the code over and over.
// Array of coordinates to run through.
let coordinates = [{x: 38.041242, y: 23.679595, {x: 38.041310, y: 23.679684}];
// List of images.
let images = coordinates.map((coordinate) => {
// URL based on coordinates.
return getBase64FromImageUrl(`https://maps.googleapis.com/maps/api/streetview?location=${coordinate.x},${coordinate.y}&size=300x300&pitch=90`);
});

Don't understand train data from convnetjs

I'm trying to predict some data using a neural network in javascript. For that I found convnetjs that seems easy to use.
In the example, they use one thing that they call MagicNet, so you don't need to know about NN to work with it. This is the example of use:
// toy data: two data points, one of class 0 and other of class 1
var train_data = [new convnetjs.Vol([1.3, 0.5]), new convnetjs.Vol([0.1, 0.7])];
var train_labels = [0, 1];
// create a magic net
var magicNet = new convnetjs.MagicNet(train_data, train_labels);
magicNet.onFinishBatch(finishedBatch); // set a callback a finished evaluation of a batch of networks
// start training MagicNet. Every call trains all candidates in current batch on one example
setInterval(function(){ magicNet.step() }, 0});
// once at least one batch of candidates is evaluated on all folds we can do prediction!
function finishedBatch() {
// prediction example. xout is Vol of scores
// there is also predict_soft(), which returns the full score volume for all labels
var some_test_vol = new convnetjs.Vol([0.1, 0.2]);
var predicted_label = magicNet.predict(some_test_vol);
}
What I don't understand is this:
They create train data like [new convnetjs.Vol([1.3, 0.5]), new convnetjs.Vol([0.1, 0.7])] and then use 2 labels. Those labels, are one for each position of array or for each element of subarray in those positions??
Here is a visual example:
It's like [new 0, new 1] or like [new convnetjs.Vol([0, 1]), new convnetjs.Vol([0, 1])]?
The sample new convnetjs.Vol([1.3, 0.5]) has label 0.
The sample new convnetjs.Vol([0.1, 0.7]) has label 1.
In general, in machine learning, you'd usually have samples which can be quite high-dimensional (here they are only two-dimensional), but you'd have a single label per sample which tells you which "class" it belongs in. What the classes actually mean depends on the problem you are trying to solve; for instance, they could be the digits that are represented by images of hand-written digits.

Box2dWeb call function when objects collide

I'm fairly new to javascript and box2d, i was wondering if someone knows how i can call a custom function when two objects collide. I tried using some examples that uses the b2ContactListener without any succes. I've placed an object above another and let the standard Box2d physics do it's thing.
I recieve two console outputs, the first is null and the second is Ball with the following code:
var listener = new Box2D.Dynamics.b2ContactListener;
listener.BeginContact = function(contact) {
console.log(contact.GetFixtureA().GetBody().GetUserData());
console.log(contact.GetFixtureB().GetBody().GetUserData());
};.
The two objects that need to collide are a b2_dynamicbody (ball) and a b2PolygonShape. (rectangle). Using bodyDef.userData = "Ball"; in my Ball.js and bodyDef.userData = "Mouse"; in my Mouse.js i try to identify if they are hit. Instead only the ball is displayed.
Next to that i'm sure this is not the correct way for detecting collision :P I hope i've explained it well enough, could somebody steer me in the right direction?
Ok I solved it myself, apparently I had to add my custom event to the world I create with box2d. So, the issue was solved by me reading big chunks of box2d documentation/manual which can be found here:
I started with adding a String as UserData() to every object which can collide and has to do something else next to just colliding. Using the following code:
bodyDef.userData = "Car";
note: every object has to have it's own unique string.
Then I created a new contact listener (formulated in my question above) and listened for fixtures colliding with each other. When that happens, I 'save' the fixtures UserData() in variables which I can then use to look what objects collide with each other.
var contactListener = new Box2D.Dynamics.b2ContactListener;
contactListener.BeginContact = function(contact) {
var fixA = contact.GetFixtureA().GetBody().GetUserData();
var fixB = contact.GetFixtureB().GetBody().GetUserData();
// if else statement here...
};
world.SetContactListener(contactListener);
Finally, I added the last statement world.SetContactListener(contactListener); to add the event to the world, making it possible for it to listen to collisions, which I forgot to add and thus was my problem.
Hope someone finds this usefull!

How to handle collisions with tile id javascript

Ive written a small game in JavaScript with the html5 canvas and am at the point of collision detection and getting rather confused.
I build my levels in tiled and then import the saved JSON file into the game.
In my level draw function i have a check to see if there are any layer properties and if the layer properties are collisions. If it does, that layer is returned and the loop carries on. When finished, the layer that was returned with collisions gets put through another loop so that the the tile values can be put into an array.
So in this array i have i have a series of arrays depending on how many rows of tiles there are in the layer, and these rows hold the data for that row for each tile.
What i would like to do is when the player x/y is in one of the tiles which doesn't equal 0, then collide.
How would i do this if all i have is the value that is in that tile space?
Here is a link to the live version of the game so you can see for yourself how the tiles are stored, i have put in some console.logs so you might want to use firebug or equivalent to look at that. To log in use
Username - guest
password - guest
TO clarify my question is: How do i create collisions between my player x/y and a tile value??
Thanks very much
UPDATE
Ok so i think im nearly there, my problem at the moment is how do i read the objects x and y out of the array and then check the collision, at the moment the collision detection on works with the last tile in the array (the bottom right of the screen), here is the code i implemented to go through the array:
this.check_coll = function(array,posX, posY){
var collided = false,
block_x,
block_y,
block_cx,
block_cy,
combined_hw = 32,
combined_hh = 32,
player_cx = posX+(32/2),
player_cy = posY+(32/2);
array.forEach(function(value,i){
//get obj x
block_x = value[1];
//get obj y
block_y = value[2];
block_cx = block_x+(32/2);
block_cy = block_y+(32/2);
collided = Math.abs(player_cx - block_cx)< combined_hw
&& Math.abs(player_cy - block_cy)< combined_hh;
});
return collided;
}
Any ideas guys??

Categories