dygraph - how to change series names for bar chart - javascript

I have a bar chart with 3 series, but I cant change their names, I have only y1 y2 y2, not my own names from the code. As per example bar chartI see, that I should use Multi-columnBarChart, but how can I do that?
here is comment from example Multi-columnBarChart:
function multiColumnBarPlotter(e) {
// We need to handle all the series simultaneously.
if (e.seriesIndex !== 0) return;
var g = e.dygraph;
var ctx = e.drawingContext;
var sets = e.allSeriesPoints;
var y_bottom = e.dygraph.toDomYCoord(0);
// Find the minimum separation between x-values.
// This determines the bar width.
var min_sep = Infinity;
for (var j = 0; j < sets.length; j++) {
var points = sets[j];
for (var i = 1; i < points.length; i++) {
var sep = points[i].canvasx - points[i - 1].canvasx;
if (sep < min_sep) min_sep = sep;
}
}
var bar_width = Math.floor(2.0 / 3 * min_sep);
here is my code:
function barChartPlotter(e) {
var ctx = e.drawingContext;
var points = e.points;
var y_bottom = e.dygraph.toDomYCoord(0);
// The RGBColorParser class is provided by rgbcolor.js, which is
// packed in with dygraphs.
var color = new RGBColorParser(e.color);
color.r = Math.floor((255 + color.r) / 2);
color.g = Math.floor((255 + color.g) / 2);
color.b = Math.floor((255 + color.b) / 2);
ctx.fillStyle = color.toRGB();
// Find the minimum separation between x-values.
// This determines the bar width.
var min_sep = Infinity;
for (var i = 1; i < points.length; i++) {
var sep = points[i].canvasx - points[i - 1].canvasx;
if (sep < min_sep) min_sep = sep;
}
var bar_width = Math.floor(2.0 / 3 * min_sep);
// Do the actual plotting.
for (var i = 0; i < points.length; i++) {
var p = points[i];
var center_x = p.canvasx;
ctx.fillRect(center_x - bar_width / 2, p.canvasy,
bar_width, y_bottom - p.canvasy);
ctx.strokeRect(center_x - bar_width / 2, p.canvasy,
bar_width, y_bottom - p.canvasy);
}
}
data = [];
var x = js_array.length;
// CONVERTATION
pass = [];
fail = [];
tree = [];
for (var i=0; i<x; i++){
if (js_array[i] == 1) {
pass.push(js_array[i]);
fail.push(NaN);
tree.push(NaN);
}
else if (js_array[i] == 2) {
pass.push(NaN);
fail.push(js_array[i]);
tree.push(NaN);
}
else if (js_array[i] == 3) {
pass.push(NaN);
fail.push(NaN);
tree.push(js_array[i]);
}
}
// DATA
for (var i=0; i<x; i++){
var y = x - i - 1;
data.push([new Date(js_array_time[y]), pass[y], fail[y], tree[y]]);
}
seriesName = ['x','PASS', 'FAIL', 'TREE']
// OPTIONS
var start = new Date(js_array_time[9]);
var stop = new Date(js_array_time[0]);
start.setMinutes(start.getMinutes() - 10);
stop.setMinutes(stop.getMinutes() + 10);
s = document.getElementById("s");
g = new Dygraph(
document.getElementById("graphdiv"),
data,
{
width: 580,
includeZero: true,
animatedZooms: true,
plotter: barChartPlotter,
axisLineWidth: 0.001,
//labels: seriesName,
legend: 'always',
title: 'Test results',
drawYAxis:false,
valueRange: [0.5, 3.5],
dateWindow: [Date.parse(start), Date.parse(stop)],
pointClickCallback: function(e, p) {
//s.innerHTML += "<b>Point Click</b> " + p.name + ": " + p.xval + "<br/>";
window.open('../RUNNER/_VLOGS/launch' + p.xval + '.html','_blank');
window.open('../RUNNER/_LOGS/launch_log' + p.xval + '.txt','_blank');
},
//drawPoints: true,
//drawXGrid: false,
//drawYGrid: false,
//fillGraph: true
}
);
g.ready(function() {
g.setAnnotations([
{
}]);
});

For multiple series, you need to get allSeriesPoints instead of just points. Here is an example I put together for another SO question:
Here is a working DEMO at jsFiddle.com
The plotter code looks like this:
function multiColumnBarPlotter(e) {
// We need to handle all the series simultaneously.
if (e.seriesIndex !== 0) return;
var g = e.dygraph;
var ctx = e.drawingContext;
var sets = e.allSeriesPoints;
var y_bottom = e.dygraph.toDomYCoord(0);
// Find the minimum separation between x-values.
// This determines the bar width.
var min_sep = Infinity;
for (var j = 0; j < sets.length; j++) {
var points = sets[j];
for (var i = 1; i < points.length; i++) {
var sep = points[i].canvasx - points[i - 1].canvasx;
if (sep < min_sep) min_sep = sep;
}
}
var bar_width = Math.floor(2.0 / 3 * min_sep);
var fillColors = [];
var strokeColors = g.getColors();
for (var i = 0; i < strokeColors.length; i++) {
var color = new RGBColorParser(strokeColors[i]);
color.r = Math.floor((255 + color.r) / 2);
color.g = Math.floor((255 + color.g) / 2);
color.b = Math.floor((255 + color.b) / 2);
fillColors.push(color.toRGB());
}
for (var j = 0; j < sets.length; j++) {
ctx.fillStyle = fillColors[j];
ctx.strokeStyle = strokeColors[j];
for (var i = 0; i < sets[j].length; i++) {
var p = sets[j][i];
var center_x = p.canvasx;
var x_left = center_x - (bar_width / 1.3) * (1 - j/(sets.length-1));
ctx.fillRect(x_left, p.canvasy,
bar_width/sets.length, y_bottom - p.canvasy);
ctx.strokeRect(x_left, p.canvasy,
bar_width/sets.length, y_bottom - p.canvasy);
}
}
}
I then create 2 charts of the same data, one using CSV and the other an array. The CSV provides labels directly in the data, for the array, you can change labels with the labels property:
labels: ['x', 'series1', 'series2', 'series3'],
The whole chart code would then be
g2 = new Dygraph(document.getElementById("g_div2"),
theData,
{
// options go here. See http://dygraphs.com/options.html
legend: 'always',
labels: ['x', 'series1', 'series2', 'series3'],
animatedZooms: true,
plotter: multiColumnBarPlotter,
colors: ["#00A0B0", "#6A4A3C", "#CC333F", ],
dateWindow: [0, 8]
});

Related

Why wont my function draw multiple bricks?

So I have this simple function that should show multiple bricks, but it only shows one. Anyone knows why? I doesn't show any errors.
function drawbricks() {
for (var r = 0; r < 12; r++) {
for (var c = 0; c < 6; c++) {
var posix = r + 20;
var posiy = c + 20;
ctx.fillRect(posix, posiy, 50, 50);
}
}
}
I've added some constants so you can configure your bricks.
const c = document.getElementsByTagName('canvas')[0];
const ctx = c.getContext('2d');
ctx.fillStyle = 'orange';
drawbricks(ctx);
function drawbricks(ctx) {
const brickCountRows = 10;
const brickCountColumns = 15;
const brickWidth = 20;
const brickHeight = 10;
const brickSpacingX = 2;
const brickSpacingY = 2;
for (var r = 0; r < brickCountRows; r++) {
for (var c = -1; c < brickCountColumns; c++) { // start at -1 to fill gap caused by offset (see below)
var posix = c * (brickWidth + brickSpacingX); // switched r by c (column is x component)
var posiy = r * (brickHeight + brickSpacingY); // switched c by r (row is y component)
// offset every other row by half brickWidth + brickSpacing
if (r%2 == 1) {
posix += Math.floor((brickWidth + brickSpacingX)/2)
}
ctx.fillRect(posix, posiy, brickWidth, brickHeight);
}
}
}
<canvas/>
I believe you ment to multiply the coordinates instead of adding.
var posix = r * 20;
var posiy = c * 20;
But still, the "bricks" will overlay each other.

Many bouncing balls in javascript

I've been trying to get this to work for a while and I've hit a block and can't get these balls to bounce off of each other and the walls. I'm trying to make essentially a virus simulator, with different balls having different properties determining infection chances whenever they contact each other. Here's the code I'm working with:
Molecule.js:
class Molecule {
constructor(_i, _max_rad){
this.moleculeIndex = _i;
this.rad = random(min_rad, _max_rad);
this.position = createVector(random(this.rad,width-this.rad),random(this.rad, height-this.rad));
this.velocity = createVector(random(-2,5),random(-2,5));
this.bounce = false;
}
render() {
noStroke();
if (this.bounce) {
let dx = this.position.x - molecules[moleculeIndex].position.x;
let dy = this.position.y - molecules[moleculeIndex].position.y;
let dist = Math.sqrt(dx * dx + dy * dy);
let normalX = dx / dist;
let normalY = dy / dist;
let midpointX = (this.position.x.x + molecules[moleculeIndexmoleculeIndex].position.x) / 2;
let midpointY = (this.position.x.y + molecules[moleculeIndex].position.y) / 2;
let dVector = (this.velocity.x - molecules[moleculeIndex].velocity.x) * normalX;
dVector += (this.velocity.y - molecules[moleculeIndex].velocity.y) * normalY;
let dvx = dVector * normalX;
let dvy = dVector * normalY;
this.velocity.x -= dvx;
this.velocity.y -= dvy;
molecules[moleculeIndex].velocity.x += dvx;
molecules[moleculeIndex].velocity.y += dvy;
}
push();
translate(this.position.x,this.position.y)
ellipse(0,0,this.rad*2,this.rad*2);
pop();
}
step() {
this.position.add(this.velocity);
}
checkEdges(){
if(this.position.x < this.rad || this.position.x > width-this.rad){
this.velocity.x = this.velocity.x * -1;
}
if(this.position.y < this.rad || this.position.y > height-this.rad){
this.velocity.y = this.velocity.y * -1;
}
}
}
Sketch.js:
let molecules = [];
let numOfMolecules = 100;
let min_rad = 10;
let max_rad = 50;
let row = 5;
let col = 5;
let gridHeight;
let gridWidth;
let moleculeKey;
let tempArray;
let intersectCount;
let numchecks;
let displayMolecules = true;
let draw_grid = true;
let display_info = true;
function setup() {
createCanvas(window.innerWidth, window.innerHeight); //create canvas size of screen
background(150, 178, 164);
createMolecules();
}
function createMolecules() {
molecules = [];
for (let i = 0; i < numOfMolecules; i++) {
molecules.push(new Molecule(i, max_rad));
}
}
function draw() {
background(150, 178, 164);
gridWidth = window.innerWidth / col;
gridHeight = window.innerHeight / row;
splitIntoGrids();
checkIntersections();
drawGrid();
renderGrid();
resetBalls();
}
function splitIntoGrids() {
moleculeKey = [];
for (let i = 0; i < row; i++) {
moleculeKey.push([]);
for (let j = 0; j < col; j++) {
moleculeKey[i].push([]);
molecules.forEach(molecule => {
if ((molecule.position.x + molecule.rad > j * gridWidth) &&
(molecule.position.x - molecule.rad < j * gridWidth + gridWidth) &&
(molecule.position.y + molecule.rad > i * gridHeight) &&
(molecule.position.y - molecule.rad < i * gridHeight + gridHeight)) {
moleculeKey[i][j].push(molecule.moleculeIndex);
}
});
}
}
}
/* Splits into grids and counts the molecules in each grid.
* Also checks molecules when overlapping between two cells
* Stores molecules in an array, to track the location of each molecule
*/
function checkIntersections() {
intersectCount = 0;
numchecks = 0;
for (let i = 0; i < moleculeKey.length; i++) {
for (let j = 0; j < moleculeKey[i].length; j++) {
// if a cell contains more than one molecule, store the molecules into temporary array
if (moleculeKey[i][j].length > 1) {
tempArray = moleculeKey[i][j];
// loops through each molecule in the temporary array
for (let k = 0; k < tempArray.length; k++) {
for (let l = k + 1; l < tempArray.length; l++) {
// calculate distance of the molecules between each other
let distanceMolecules = p5.Vector.sub(molecules[tempArray[k]].position, molecules[tempArray[l]].position);
let vectorLength = distanceMolecules.mag();
numchecks++;
//checks if molecules are intersecting
if (vectorLength < molecules[tempArray[k]].rad + molecules[tempArray[l]].rad) {
molecules[tempArray[k]].bounce = true;
molecules[tempArray[l]].bounce = true;
intersectCount++;
}
}
}
}
}
}
}
function drawGrid() {
if (draw_grid) {
for (let i = 0; i < row; i++) {
for (let j = 0; j < col; j++) {
stroke(255);
noFill();
rect(j * gridWidth, i * gridHeight, gridWidth, gridHeight);
fill(255);
textSize(12);
text(moleculeKey[i][j].length, j * gridWidth + 10, i * gridHeight + gridHeight - 10);
}
}
}
}
function resetBalls() {
for (let i = 0; i < moleculeKey.length; i++) {
for (let j = 0; j < moleculeKey[i].length; j++) {
if (moleculeKey[i][j].length > 1) {
tempArray = moleculeKey[i][j];
//console.log(tempArray);
for (let k = 0; k < tempArray.length; k++) {
for (let l = k + 1; l < tempArray.length; l++) {
let distanceMolecules = p5.Vector.sub(molecules[tempArray[k]].position, molecules[tempArray[l]].position);
let vectorLength = distanceMolecules.mag(); //get the length of vector
//checks if molecules are not intersecting
if (!vectorLength < molecules[tempArray[k]].rad + molecules[tempArray[l]].rad) {
//change back color
molecules[tempArray[k]].bounce = false;
molecules[tempArray[l]].bounce = false;
}
}
}
}
}
}
}
function renderGrid() {
molecules.forEach(molecule => {
if (displayMolecules) {
molecule.render();
}
molecule.checkEdges();
molecule.step();
});
}
With this code I get an error 'Uncaught ReferenceError: moleculeIndex is not defined' on the first line of the if(bounce), I've tried replacing moleculeIndex with some other things but really it was just hoping. Does anyone know why I'm having this problem?
Thanks.
Try replacing the: moleculeIndex with this.moleculeIndex

Python and Javascript Pseudo Random Number Generator PRNG

I am looking for a way to generate the same sequence of pseudo random integer numbers from both python and javascript.
When I seed in python like this I get the below results:
random.seed(3909461935)
random.randint(0, 2147483647) = 162048056
random.randint(0, 2147483647) = 489743869
random.randint(0, 2147483647) = 1561110296
I need the same sequence in javascript.
Note: I used 2147483647 as the range in the randint method because I am assuming javascript can only handle 32 bit INTs.
Are there any libraries on both sides I can use to generate the same set of pseudo random numbers given the same seed?
I have found two implementations of Mersenne Twister that generate the same 32 bit integer values given the same seed.
This way you can generate a server side sequence in Python, and have the browser independently generate the same sequence in javascript.
Python:
from mt_random import *
r = mersenne_rng(seed = 12345)
r.get_random_number() # Prints 3992670690
r.get_random_number() # Prints 3823185381
r.get_random_number() # Prints 1358822685
Javascript:
r = new MersenneTwister();
r.init_genrand(12345);
r = mersenne_rng(seed = 12345)
r.genrand_int32(); # Prints 3992670690
r.genrand_int32(); # Prints 3823185381
r.genrand_int32(); # Prints 1358822685
The JS is here:
/*
* 疑似乱数生成機 移植
*
* Mersenne Twister with improved initialization (2002)
* http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/mt.html
* http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/mt19937ar.html
*/
// = 移植元ラインセンス =======================================================
// ======================================================================
/*
A C-program for MT19937, with initialization improved 2002/2/10.
Coded by Takuji Nishimura and Makoto Matsumoto.
This is a faster version by taking Shawn Cokus's optimization,
Matthe Bellew's simplification, Isaku Wada's real version.
Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or another materials provided with the distribution.
3. The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Any feedback is very welcome.
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat # math.sci.hiroshima-u.ac.jp (remove space)
*/
// ======================================================================
function MersenneTwister() {
// 整数を扱うクラス
function Int32(value) {
var bits = new Array(0, 0, 0, 0);
var i;
var v = value;
if (v != 0) {
for (i = 0; i < 4; ++i) {
bits[i] = v & 0xff;
v = v >> 8;
}
}
this.getValue = function () {
return (bits[0] | (bits[1] << 8) | (bits[2] << 16)) + ((bits[3] << 16) * 0x100);
};
this.getBits = function (i) { return bits[i & 3]; };
this.setBits = function (i, val) { return (bits[i & 3] = val & 0xff); };
this.add = function (another) {
var tmp = new Int32(0);
var i, fl = 0, b;
for (i = 0; i < 4; ++i) {
b = bits[i] + another.getBits(i) + fl;
tmp.setBits(i, b);
fl = b >> 8;
}
return tmp;
};
this.sub = function (another) {
var tmp = new Int32(0);
var bb = new Array(0, 0, 0, 0);
var i;
for (i = 0; i < 4; ++i) {
bb[i] = bits[i] - another.getBits(i);
if ((i > 0) && (bb[i - 1] < 0)) {
--bb[i];
}
}
for (i = 0; i < 4; ++i) {
tmp.setBits(i, bb[i]);
}
return tmp;
};
this.mul = function (another) {
var tmp = new Int32(0);
var bb = new Array(0, 0, 0, 0, 0);
var i, j;
for (i = 0; i < 4; ++i) {
for (j = 0; i + j < 4; ++j) {
bb[i + j] += bits[i] * another.getBits(j);
}
tmp.setBits(i, bb[i]);
bb[i + 1] += bb[i] >> 8;
}
return tmp;
};
this.and = function (another) {
var tmp = new Int32(0);
var i;
for (i = 0; i < 4; ++i) {
tmp.setBits(i, bits[i] & another.getBits(i));
}
return tmp;
};
this.or = function (another) {
var tmp = new Int32(0);
var i;
for (i = 0; i < 4; ++i) {
tmp.setBits(i, bits[i] | another.getBits(i));
}
return tmp;
};
this.xor = function (another) {
var tmp = new Int32(0);
var i;
for (i = 0; i < 4; ++i) {
tmp.setBits(i, bits[i] ^ another.getBits(i));
}
return tmp;
};
this.rshifta = function (s) {
var tmp = new Int32(0);
var bb = new Array(0, 0, 0, 0, 0);
var p = s >> 3;
var i, sg = 0;
if ((bits[3] & 0x80) > 0) {
bb[4] = sg = 0xff;
}
for (i = 0; i + p < 4; ++i) {
bb[i] = bits[i + p];
}
for (; i < 4; ++i) {
bb[i] = sg;
}
p = s & 0x7;
for (i = 0; i < 4; ++i) {
tmp.setBits(i, ((bb[i] | (bb[i + 1] << 8)) >> p) & 0xff);
}
return tmp;
};
this.rshiftl = function (s) {
var tmp = new Int32(0);
var bb = new Array(0, 0, 0, 0, 0);
var p = s >> 3;
var i;
for (i = 0; i + p < 4; ++i) {
bb[i] = bits[i + p];
}
p = s & 0x7;
for (i = 0; i < 4; ++i) {
tmp.setBits(i, ((bb[i] | (bb[i + 1] << 8)) >> p) & 0xff);
}
return tmp;
};
this.lshift = function (s) {
var tmp = new Int32(0);
var bb = new Array(0, 0, 0, 0, 0);
var p = s >> 3;
var i;
for (i = 0; i + p < 4; ++i) {
bb[i + p + 1] = bits[i];
}
p = s & 0x7;
for (i = 0; i < 4; ++i) {
tmp.setBits(i, (((bb[i] | (bb[i + 1] << 8)) << p) >> 8) & 0xff);
}
return tmp;
};
this.equals = function (another) {
var i;
for (i = 0; i < 4; ++i) {
if (bits[i] != another.getBits(i)) {
return false;
}
}
return true;
};
this.compare = function (another) {
var i;
for (i = 3; i >= 0; --i) {
if (bits[i] > another.getBits(i)) {
return 1;
} else if (bits[i] < another.getBits(i)) {
return -1;
}
}
return 0;
};
}
// End of Int32
/* Period parameters */
var N = 624;
var M = 397;
var MATRIX_A = new Int32(0x9908b0df); /* constant vector a */
var UMASK = new Int32(0x80000000); /* most significant w-r bits */
var LMASK = new Int32(0x7fffffff); /* least significant r bits */
var INT32_ZERO = new Int32(0);
var INT32_ONE = new Int32(1);
var MIXBITS = function (u, v) {
return (u.and(UMASK)).or(v.and(LMASK));
};
var TWIST = function (u, v) {
return ((MIXBITS(u, v).rshiftl(1)).xor((v.and(INT32_ONE)).equals(INT32_ZERO) ? INT32_ZERO : MATRIX_A));
};
var state = new Array(); /* the array for the state vector */
var left = 1;
var initf = 0;
var next = 0;
var i;
for (i = 0; i < N; ++i) {
state[i] = INT32_ZERO;
}
/* initializes state[N] with a seed */
var _init_genrand = function (s) {
var lt1812433253 = new Int32(1812433253);
var j;
state[0]= new Int32(s);
for (j = 1; j < N; ++j) {
state[j] = ((lt1812433253.mul(state[j - 1].xor(state[j - 1].rshiftl(30)))).add(new Int32(j)));
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array state[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
//state[j] &= 0xffffffff; /* for >32 bit machines */
}
left = 1; initf = 1;
};
this.init_genrand = _init_genrand;
/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
/* slight change for C++, 2004/2/26 */
this.init_by_array = function (init_key, key_length) {
var lt1664525 = new Int32(1664525);
var lt1566083941 = new Int32(1566083941);
var i, j, k;
_init_genrand(19650218);
i = 1; j = 0;
k = (N > key_length ? N : key_length);
for (; k; --k) {
state[i] = ((state[i].xor((state[i - 1].xor(state[i - 1].rshiftl(30))).mul(lt1664525))).add(
new Int32(init_key[j]))).add(new Int32(j)); /* non linear */
//state[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */
i++; j++;
if (i >= N) {
state[0] = state[N - 1];
i = 1;
}
if (j >= key_length) {
j = 0;
}
}
for (k = N - 1; k; --k) {
state[i] = (state[i].xor((state[i-1].xor(state[i - 1].rshiftl(30))).mul(lt1566083941))).sub(
new Int32(i)); /* non linear */
//state[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */
i++;
if (i >= N) {
state[0] = state[N - 1];
i = 1;
}
}
state[0] = new Int32(0x80000000); /* MSB is 1; assuring non-zero initial array */
left = 1; initf = 1;
};
var next_state = function () {
var p = 0;
var j;
/* if init_genrand() has not been called, */
/* a default initial seed is used */
if (initf == 0) {
_init_genrand(5489);
}
left = N;
next = 0;
for (j = N - M + 1; --j; ++p) {
state[p] = state[p + M].xor(TWIST(state[p], state[p + 1]));
}
for (j = M; --j; ++p) {
state[p] = state[p + M - N].xor(TWIST(state[p], state[p + 1]));
}
state[p] = state[p + M - N].xor(TWIST(state[p], state[0]));
};
var lt0x9d2c5680 = new Int32(0x9d2c5680);
var lt0xefc60000 = new Int32(0xefc60000);
/* generates a random number on [0,0xffffffff]-interval */
var _genrand_int32 = function () {
var y;
if (--left == 0) {
next_state();
}
y = state[next];
++next;
/* Tempering */
y = y.xor(y.rshiftl(11));
y = y.xor((y.lshift(7)).and(lt0x9d2c5680));
y = y.xor((y.lshift(15)).and(lt0xefc60000));
y = y.xor(y.rshiftl(18));
return y.getValue();
};
this.genrand_int32 = _genrand_int32;
/* generates a random number on [0,0x7fffffff]-interval */
this.genrand_int31 = function () {
var y;
if (--left == 0) {
next_state();
}
y = state[next];
++next;
/* Tempering */
y = y.xor(y.rshiftl(11));
y = y.xor((y.lshift(7)).and(lt0x9d2c5680));
y = y.xor((y.lshift(15)).and(lt0xefc60000));
y = y.xor(y.rshiftl(18));
return (y.rshiftl(1)).getValue();
};
/* generates a random number on [0,1]-real-interval */
this.genrand_real1 = function () {
var y;
if (--left == 0) {
next_state();
}
y = state[next];
++next;
/* Tempering */
y = y.xor(y.rshiftl(11));
y = y.xor((y.lshift(7)).and(lt0x9d2c5680));
y = y.xor((y.lshift(15)).and(lt0xefc60000));
y = y.xor(y.rshiftl(18));
return y.getValue() * (1.0/4294967295.0);
/* divided by 2^32-1 */
};
/* generates a random number on [0,1)-real-interval */
this.genrand_real2 = function () {
var y;
if (--left == 0) {
next_state();
}
y = state[next];
++next;
/* Tempering */
y = y.xor(y.rshiftl(11));
y = y.xor((y.lshift(7)).and(lt0x9d2c5680));
y = y.xor((y.lshift(15)).and(lt0xefc60000));
y = y.xor(y.rshiftl(18));
return y.getValue() * (1.0 / 4294967296.0);
/* divided by 2^32 */
};
/* generates a random number on (0,1)-real-interval */
this.genrand_real3 = function () {
var y;
if (--left == 0) {
next_state();
}
y = state[next];
++next;
/* Tempering */
y = y.xor(y.rshiftl(11));
y = y.xor((y.lshift(7)).and(lt0x9d2c5680));
y = y.xor((y.lshift(15)).and(lt0xefc60000));
y = y.xor(y.rshiftl(18));
return (y.getValue() + 0.5) * (1.0 / 4294967296.0);
/* divided by 2^32 */
};
/* generates a random number on [0,1) with 53-bit resolution*/
this.genrand_res53 = function () {
var a = ((new Int32(_genrand_int32())).rshiftl(5)).getValue();
var b = ((new Int32(_genrand_int32())).rshiftl(6)).getValue();
return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0);
};
/* These real versions are due to Isaku Wada, 2002/01/09 added */
}
The corresponding Python implementation is here:
class mersenne_rng(object):
def __init__(self, seed = 5489):
self.state = [0]*624
self.f = 1812433253
self.m = 397
self.u = 11
self.s = 7
self.b = 0x9D2C5680
self.t = 15
self.c = 0xEFC60000
self.l = 18
self.index = 624
self.lower_mask = (1<<31)-1
self.upper_mask = 1<<31
# update state
self.state[0] = seed
for i in range(1,624):
self.state[i] = self.int_32(self.f*(self.state[i-1]^(self.state[i-1]>>30)) + i)
def twist(self):
for i in range(624):
temp = self.int_32((self.state[i]&self.upper_mask)+(self.state[(i+1)%624]&self.lower_mask))
temp_shift = temp>>1
if temp%2 != 0:
temp_shift = temp_shift^0x9908b0df
self.state[i] = self.state[(i+self.m)%624]^temp_shift
self.index = 0
def get_random_number(self):
if self.index >= 624:
self.twist()
y = self.state[self.index]
y = y^(y>>self.u)
y = y^((y<<self.s)&self.b)
y = y^((y<<self.t)&self.c)
y = y^(y>>self.l)
self.index+=1
return self.int_32(y)
def int_32(self, number):
return int(0xFFFFFFFF & number)
if __name__ == "__main__":
rng = mersenne_rng(1131464071)
for i in range(10):
print rng.get_random_number()

How to write multidimensional array in JS in a loop?

I have the following code:
var marketReturns = [1];
var marketReturnsVol = [1];
var marketVolatility = [1];
var yearlyReturns = [];
var yearlyReturns2 = [];
for (y = 0; y < 50000; y++) {
for (x = 1; x <= 251; x++) {
do {
var rand1 = Math.random();
var rand2 = Math.random();
var x1 = 2.0 * rand1 - 1.0;
var x2 = 2.0 * rand2 - 1.0;
var w = Math.pow(x1, 2) + Math.pow(x2, 2);
} while (w === 0 || w > 1);
multiplier = Math.sqrt((-2 * Math.log(w)) / w);
var volVol = 1 + (((x2 * multiplier) / 100) * 5.98); // real ^VIX is 5.98.
marketVolatility[x] = volVol * marketVolatility[x - 1];
var y1 = 1 + (((x1 * multiplier) / 100) * 1.07); // 1.07 is the daily vol of ^GSPC
var y12 = 1 + (((x1 * multiplier) / 100) * 1.07 * marketVolatility[x]) + 0.00038; // 1.07 is the daily vol of ^GSPC
marketReturns[x] = y1 * marketReturns[x - 1];
marketReturnsVol[x] = y12 * marketReturnsVol[x - 1];
}
yearlyReturns[y] = marketReturns[251];
yearlyReturns2[y] = marketReturnsVol[251];
}
yearlyReturns.sort(function (a, b) {
return (a - b);
})
yearlyReturns2.sort(function (a, b) {
return (a - b);
})
for (x = 0; x < yearlyReturns.length; x++) {
document.write(yearlyReturns2[x] + ", ");
}
So essentially I am calculating marketReturns, which is marketReturns[x-1] * daily change. I want however to make this into subarrays where I can preserve all the individual marketReturns for each iteration of y instead of just preserving the last day like I am in yearlyReturns[y].
I thought I could do it as such:
marketReturns[y][x] = y1 * marketReturns[y][x - 1];
marketReturnsVol[y][x] = y12 * marketReturnsVol[y][x - 1];
But this doesn't work. Is there any way for me to start writing the marketReturns figures into subarrays? Thanks.
You can mimic the multidimensional array using nested array/nested object in javascript:
e.g.
var arr = [];
//Initialize a 10x10 "multidimensional" array
for(var i = 0; i < 10; i++) {
arr[i] = [];
for(var j = 0; j < 10; j++) {
arr[i][j] = 0;
}
}
//Store
arr[5][5] = 10;

Phonegap Camera API and Barcode Reader Relation

I try the add barcode reader in my application on Sencha Touch. I have used phonegap camera api . My capture code is here :
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI,saveToPhotoAlbum : true
});
function onSuccess(imageData) {
try
{
var barcode =getBarcodeFromImage(imageData);
alert('The scanned barcode is: ' + barcode);
}
catch(error)
{
alert(error);
}
}
function onFail(message) {
alert('Failed because: ' + message);
}
I could open camera and take picture.Its working.But I want the reading barcode in this photo.
Its my barcode reader code:
(function(){
var UPC_SET = {
"3211": '0',
"2221": '1',
"2122": '2',
"1411": '3',
"1132": '4',
"1231": '5',
"1114": '6',
"1312": '7',
"1213": '8',
"3112": '9'
};
getBarcodeFromImage = function(imgOrId){
alert('girdi');
var doc = document,
img = "object" == typeof imgOrId ? imgOrId : doc.getElementById(imgOrId),
canvas = doc.createElement("canvas"),
ctx = canvas.getContext("2d"),
width = img.width,
height = img.height,
spoints = [1, 9, 2, 8, 3, 7, 4, 6, 5],
numLines = spoints.length,
slineStep = height / (numLines + 1);
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0);
while(numLines--){
console.log(spoints[numLines]);
var pxLine = ctx.getImageData(0, slineStep * spoints[numLines], width, 2).data,
sum = [],
min = 0,
max = 0;
for(var row = 0; row < 2; row++){
for(var col = 0; col < width; col++){
var i = ((row * width) + col) * 4,
g = ((pxLine[i] * 3) + (pxLine[i + 1] * 4) + (pxLine[i + 2] * 2)) / 9,
s = sum[col];
pxLine[i] = pxLine[i + 1] = pxLine[i + 2] = g;
sum[col] = g + (undefined == s ? 0 : s);
}
}
for(var i = 0; i < width; i++){
var s = sum[i] = sum[i] / 2;
if(s < min){ min = s; }
if(s > max){ max = s; }
}
var pivot = min + ((max - min) / 2),
bmp = [];
for(var col = 0; col < width; col++){
var matches = 0;
for(var row = 0; row < 2; row++){
if(pxLine[((row * width) + col) * 4] > pivot){ matches++; }
}
bmp.push(matches > 1);
}
var curr = bmp[0],
count = 1,
lines = [];
for(var col = 0; col < width; col++){
if(bmp[col] == curr){ count++; }
else{
lines.push(count);
count = 1;
curr = bmp[col];
}
}
var code = '',
bar = ~~((lines[1] + lines[2] + lines[3]) / 3),
u = UPC_SET;
for(var i = 1, l = lines.length; i < l; i++){
if(code.length < 6){ var group = lines.slice(i * 4, (i * 4) + 4); }
else{ var group = lines.slice((i * 4 ) + 5, (i * 4) + 9); }
var digits = [
Math.round(group[0] / bar),
Math.round(group[1] / bar),
Math.round(group[2] / bar),
Math.round(group[3] / bar)
];
code += u[digits.join('')] || u[digits.reverse().join('')] || 'X';
if(12 == code.length){ return code; break; }
}
if(-1 == code.indexOf('X')){ return code || false; }
}
return false;
}
})();
when the camera captured returns image uri. In the Barcode function throwing "cannot read property 'width' of null.
So function not reading my captured photo. How to fix this ?
I used phonegap barcode api and resolved problem

Categories

Resources