Why array registers only the last object multiple times Nodejs - node.js

Im trying to fill an array with n objects but it just register the last object n times this is my code :
async function show(carId,debut,fin){
let score = {}
let array = [];
res = await ScoreData(carId);
for(i = 0; i < res.entries.length ; i++){
date = res.entries[i].Timestamp._.toISOString().slice(0, 10);
if (date >= debut && date <= fin){
score.roadSpeed_1 = (res.entries[i].speed_1._)/((res.entries[i].speed_1._)+ (res.entries[i].speed_2._) + (res.entries[i].speed_3._))*10000;
score.roadSpeed_2 = (res.entries[i].speed_2._)/((res.entries[i].speed_1._)+ (res.entries[i].speed_2._) + (res.entries[i].speed_3._))*10000;
score.roadSpeed_3 = (res.entries[i].speed_3._)/((res.entries[i].speed_1._)+ (res.entries[i].speed_2._) + (res.entries[i].speed_3._))*10000;
score.Acceleration = Math.round(res.entries[i].millage._ / res.entries[i].Vehicle_speed._)
console.log(res.entries[i].millage._ / res.entries[i].Vehicle_speed._)
array.push(score);
}
}
console.log(array)
}
This is the result :
[
{ roadSpeed_1: 100, roadSpeed_2: 0, roadSpeed_3: 0, Acceleration: 4 },
{ roadSpeed_1: 100, roadSpeed_2: 0, roadSpeed_3: 0, Acceleration: 4 },
{ roadSpeed_1: 100, roadSpeed_2: 0, roadSpeed_3: 0, Acceleration: 4 },
{ roadSpeed_1: 100, roadSpeed_2: 0, roadSpeed_3: 0, Acceleration: 4 },
{ roadSpeed_1: 100, roadSpeed_2: 0, roadSpeed_3: 0, Acceleration: 4 },
{ roadSpeed_1: 100, roadSpeed_2: 0, roadSpeed_3: 0, Acceleration: 4 },
{ roadSpeed_1: 100, roadSpeed_2: 0, roadSpeed_3: 0, Acceleration: 4 },
{ roadSpeed_1: 100, roadSpeed_2: 0, roadSpeed_3: 0, Acceleration: 4 },
{ roadSpeed_1: 100, roadSpeed_2: 0, roadSpeed_3: 0, Acceleration: 4 }
]

Objects in JavaScript are passed by reference. When more than one variable is set to store either an object , array or function , those variables will point to the same allocated space in the memory. Passed by reference. Source : Link
Better solution i guess :
array.push({roadspeed_1: operation 1, roadspeed_2: operation 2 ,roadspeed_3: operation 3 });

Related

How to mirror front camera [duplicate]

Can I horizontally flip/reflect a shape item in QML. For example; I have the below shape:
Can I flip/reflect it horizontally to produce:
I know I could edit my QML code to draw the lines differently but it would be much simpler to just use a QML animation or something to flip it if thats possible.
Shape {
id: annotationHLine;
anchors.left: annotationShp.right;
anchors.top: annotationShp.top;
anchors.topMargin: annotationShp.height * 0.5;
ShapePath {
strokeWidth: 2;
strokeColor: "Green";
fillColor: "transparent";
startX: -slant; startY: 0;
PathLine { x: relativeTargetX*0.5; y: 0 }
PathLine { x: relativeTargetX; y: relativeTargetY }
}
}
you can use transform and Scale
transform: Scale{ xScale: -1 }
Yes you can, by simply setting a horizontal mirror transformation matrix to the shape:
transform: Matrix4x4 {
matrix: Qt.matrix4x4(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)
}
Edit:
The x position doesn't really change, it is still the same, it is just that the object is now rendered with the transformation. You can compensate for that by stacking a translate on top of the matrix:
transform: [
Matrix4x4 {
matrix: Qt.matrix4x4(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)
},
Translate {
x: annotationHLine.width
}
]
Edit 2:
Actually, you can incorporate the translation in the original matrix to simplify things a bit:
transform: Matrix4x4 {
matrix: Qt.matrix4x4( -1, 0, 0, but.width, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)}
}

Highcharts Scrollbar up arrow throws error on click

When clicking the up arrow on a highcharts xrange graph with a scrollbar on the yAxis (there is also one on the xAxis but it doesn't throw an error when i use it's arrow button)
the error returned is
Uncaught TypeError: Cannot read property 'call' of undefined
at SVGGElement.<anonymous> (highcharts.src.js:5182)
I haven't found anything specific on the internet about this error so far but if i do i will update this ticket
Might this have something to do with having an X and Y scrollbar ?
I don't plan on using the button at all since we have implemented a listener for the trackpad/wheel - is there a way of removing the arrow button entirely (rather than make it transparent which i currently have implemented which includes an unsightly hover i can't get rid of)
If you can help me A) Remove/hide the button entirely B) listen for the click and throw away the event to avoid this error or C) fix whatever the underlying cause of this error is ... i'd greatly appreciate it
{
'chart': {
'renderTo': graphId,
'type': 'xrange',
'zoomType': 'xy',
'panning': true,
'panKey': 'shift',
'marginRight': 40,
'marginLeft': 150,
'resetZoomButton': {
'position': {
'x': -150,
'y': -10
}
}
},
'exporting': {
'enabled': true,
'buttons': {
'enabled': true,
'contextButton': {
'enabled': false
},
'resetScopeButton': {
'y': -10,
'x': -25,
'symbolX': 20,
'symbolY': 20,
'enabled': true,
'onclick': context['LiAnalytics']['resetScopeButton'],
'symbol': 'url(../images/refresh.png)'
},
'hourButton': {
'enabled': true,
'text': 'H',
'y': -10,
'x': -50,
'onclick': context['LiAnalytics']['hourButton']
},
'dayButton': {
'text': 'D',
'y': -10,
'x': -75,
'enabled': endTS - startTS > 86400000,
'onclick': context['LiAnalytics']['dayButton']
},
'weekButton': {
'text': 'W',
'y': -10,
'x': -100,
'enabled': endTS - startTS >= 604800000,
'onclick': context['LiAnalytics']['weekButton']
},
'monthButton': {
'text': 'M',
'y': -10,
'x': -125,
'enabled': endTS - startTS >= 2419000000,
'onclick': context['LiAnalytics']['monthButton']
}
}
},
'legend': {
'enabled': false
},
'xAxis': {
'type': 'datetime',
'dateTimeLabelFormats': {
...
},
'events': {
'setExtremes': new js.JsFunction.withThis(_handleRedraw)
},
'min': (endTS - startTS) > initialZoom ? endTS - initialZoom : startTS,
'max': endTS,
'scrollbar': {
'enabled': true,
'showFull': false,
'barBackgroundColor': '#ccc',
'barBorderRadius': 7,
'barBorderWidth': 0,
'buttonBorderWidth': 0,
'buttonArrowColor': 'transparent',
'buttonBackgroundColor': 'transparent',
'rifleColor': 'transparent',
'trackBackgroundColor': '#F3F3F3',
'trackBorderColor': 'transparent',
'height': 10,
'minWidth': 25
}
},
'yAxis': {
'categories': agents,
'min': 0,
'max': agents.length < maxY ? agents.length - 1 : maxY,
'scrollbar': { /* Why you throw err on click ? */
'enabled': true,
'showFull': false,
'barBackgroundColor': '#ccc',
'barBorderRadius': 7,
'barBorderWidth': 0,
'buttonBorderWidth': 0,
'buttonArrowColor': 'transparent', /* Remove entirely ? */
'buttonBackgroundColor': 'transparent',
'rifleColor': 'transparent',
'trackBackgroundColor': '#F3F3F3',
'trackBorderColor': 'transparent',
'height': 10,
'minWidth': 25
},
'reversed': true,
'tickmarkPlacement': 'on',
'gridLineColor': 'transparent'
},
'plotOptions': {
'series': {
'animation': {
'duration': 2000
},
'point': {
'events': { /* can i do something similar for scrollbar? */
'mouseOver': new js.JsFunction.withThis(_mouseOver),
'mouseOut': new js.JsFunction.withThis(_mouseOut)
}
},
'pointWidth': 20,
'pointPlacement': 0,
'minPointLength': 10,
'borderRadius': 0
}
},
'series': series,
'tooltip': {
...
}
}
(C) Current code block
(function() {
//internal functions
function stopEvent(e) {
if (e) {
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
e.cancelBubble = true;
}
}
/* Wrap allows us to override the behavior of render while not interrupting the normal rendering procedure */
Highcharts.wrap(Highcharts.Chart.prototype, 'render', function(proceed) {
var chart = this;
proceed.call(chart);
/* When a chart has a scrollbar and is xrange our PM/UX has requested the touchpad be abled to control the scrollbar */
if (chart.options['chart']['type'] === "xrange" && chart.options['yAxis'][0]['scrollbar']['enabled']) {
// Add the mousewheel event
Highcharts.addEvent(chart.container, document.onmousewheel === undefined ? 'DOMMouseScroll' : 'mousewheel', function (event) {
var delta, diff, extr, newMax, newMin, step, axis = chart.yAxis[0];
e = chart.pointer.normalize(event);
// Firefox uses e.detail, WebKit and IE uses wheelDelta
delta = e.detail || -(e.wheelDelta / 120);
delta = delta < 0 ? 1 : -1;
/* Up or Down */
if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
extr = axis.getExtremes();
if (extr.dataMax !== extr.dataMin) {
diff = extr.max - extr.min;
step = diff / 5;
/* move by fifths */
step = step > 1 ? Math.ceil(step) : 1;
/* Min step is 1, Move by whole numbers */
step = step * delta;
/* Up/Down */
if (step > 0) {
/* UP */
if (extr.max + step > extr.dataMax) {
newMax = extr.dataMax;
newMin = extr.dataMax - diff;
/* Enforce window not getting too small */
} else {
newMin = extr.min + step;
newMax = extr.max + step;
}
} else {
/* DOWN */
if (extr.min + step < 0) {
newMin = 0;
newMax = diff;
} else {
newMin = extr.min + step;
newMax = extr.max + step;
}
}
axis.setExtremes(newMin, newMax, true, false);
}
}
stopEvent(event);
return false;
});
}
});
Highcharts.Scrollbar.prototype.addEvents = function() {
var chart = this;
var buttonsOrder = chart.options.inverted ? [1, 0] : [0, 1],
buttons = chart.scrollbarButtons,
bar = chart.scrollbarGroup.element,
track = chart.track.element,
mouseDownHandler = chart.mouseDownHandler,
mouseMoveHandler = chart.mouseMoveHandler,
mouseUpHandler = chart.mouseUpHandler,
_events;
// Mouse events
_events = [
/* [buttons[buttonsOrder[0]].element, 'click', this.buttonToMinClick],
[buttons[buttonsOrder[1]].element, 'click', this.buttonToMaxClick], */
[track, 'click', this.trackClick],
[bar, 'mousedown', mouseDownHandler],
[bar.ownerDocument, 'mousemove', mouseMoveHandler],
[bar.ownerDocument, 'mouseup', mouseUpHandler]
];
// Touch events
if (Highcharts.hasTouch) {
_events.push(
[bar, 'touchstart', mouseDownHandler], [bar.ownerDocument, 'touchmove', mouseMoveHandler], [bar.ownerDocument, 'touchend', mouseUpHandler]
);
}
// Add them all
_events.forEach(function(args) {
Highcharts.addEvent.apply(null, args);
});
chart._events = _events;
};
}());
EDIT: removed old details
This was caused by trying to singularly disable the context button while including other custom buttons. The context button hung around as a phantom button that was overladed over the scrollbar up arrow causing the misdiagnosis during debugging.
Solution i ended up going up with was repurposing the context button by overriding the symbol/symbolX symoblY(to center symbol in button area)/onclick behavior
routed onclick to the resetScope behavior i was working toward
overrode the burger symbol with the png saved / decided on by UX

What optimization is making my rust program so much faster?

Frustrated that I could not solve a Sudoku puzzle, I quickly hacked together a simple recursive backtracking solver:
fn is_allowed(board: &[[u8; 9]; 9], row: usize, col: usize, x: u8) -> bool {
for i in 0..9 {
if board[row][i] == x {
return false;
}
if board[i][col] == x {
return false;
}
}
let r = row - (row % 3);
let c = col - (col % 3);
for i in r..(r + 3) {
for j in c..(c + 3) {
if board[i][j] == x {
return false;
}
}
}
true
}
fn solve(board: &mut [[u8; 9]; 9]) -> bool {
for i in 0..9 {
for j in 0..9 {
if board[i][j] == 0 {
for x in 1..=9 {
if is_allowed(board, i, j, x) {
board[i][j] = x;
if solve(board) {
return true
}
board[i][j] = 0;
}
}
return false;
}
}
}
true
}
fn main() {
let mut board = [
[ 0, 0, 8, 0, 0, 4, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 7 ],
[ 0, 0, 6, 0, 0, 0, 0, 1, 0 ],
[ 0, 0, 0, 0, 0, 0, 5, 0, 9 ],
[ 0, 0, 0, 6, 0, 0, 0, 0, 0 ],
[ 0, 2, 0, 8, 1, 0, 0, 0, 0 ],
[ 9, 4, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 1, 8, 0 ],
[ 0, 0, 7, 0, 0, 5, 0, 0, 0 ],
];
if solve(&mut board) {
for i in 0..9 {
println!("{:?}", board[i]);
}
} else {
println!("no solution");
}
}
When running without optimizations (cargo run), it takes more than 6 minutes to run.
When running with optimizations (cargo run --release), it takes about 7 seconds to run.
What optimization is leading to such a difference?
It is difficult to be sure without analyzing the generated assembly, but I think that it is related to the combination of these optimizations:
Loop unrolling: the compiler knows that each loop runs 8 times, so instead of a loop it compiles the loop body 8 times with the index as a constant. This is why the godbold link by #MatthieuM in the comments above is so long.
Range checking: since i, j and k are now constants (in the unrolled loops) and the arrays are of known size, the compiler will omit all range checks.
Function inlining.
In fact, each time you write board[i][j]:
In debug mode, you are calling two library functions that do checkings and computations.
In release mode each instance of such code is just a read or write to fixed offset in the stack.

how to set color with leaflet glify

I'm using the glify plugin for Leaflet, and can't for the life of me figure out how to set the color of my points to a function.
This works fine:
L.glify.points({
data: data,
map: map,
opacity: 1,
size: 10,
color: 'red',
However this returns all black points:
L.glify.points({
data: data,
map: map,
opacity: 1,
size: 10,
color: function(){
if ( 1 > 0 ){ return 'red';}else{return 'blue';}
},
Does anyone have any idea what I need to do here?
figured it out, needs to be formatted like this:
color: function(){
if (1 > 0){
return {
r: 0,
g: .51,
b: .1
};
}else{
return {
r: 30,
g: 1,
b: 2
};
}
},
You need to convert your hex color code into rgb form using below function
function fromHex(hex) {
if (hex.length < 6) return null;
hex = hex.toLowerCase();
if (hex[0] === '#') {
hex = hex.substring(1, hex.length);
}
var r = parseInt(hex[0] + hex[1], 16),
g = parseInt(hex[2] + hex[3], 16),
b = parseInt(hex[4] + hex[5], 16);
return {
r: r / 255,
g: g / 255,
b: b / 255
};
}
and then return it like this :
L.glify.points({
data: data,
map: map,
opacity: 1,
size: 10,
color: function(){
if ( 1 > 0 ){
return fromHex("#FF0000");
}else{
return fromHex("#0000FF");
}
}
});

react - setState find object item then assign

i have object in state -
this.state = {
states: {
na: 0, s1a: 0, s2a: 0, s3a: 0, s4a: 0, l1a: 0, l2a: 0, l3a: 0, t1a: 0, t2a: 0, t3a: 0,
nb: 0, s1b: 0, s2b: 0, s3b: 0, s4b: 0, l1b: 0, l2b: 0, l3b: 0, t1b: 0, t2b: 0, t3b: 0
},
and i want to change value of some key i my function -
onInputUpdated(id){
var array = {};
let char = id.slice(-1);
switch(char){
case 'a':
array[id] = this.getY(ReactDOM.findDOMNode(this.refs[id].refs.inp).value);
break;
case 'b':
array[id] = this.getX(ReactDOM.findDOMNode(this.refs[id].refs.inp).value);
break;
}
this.setState({
states: { id : array[id]}
});
but there is no id, id represents string 'na' or others... so how i can do it? any tips pls? btw onIputUpdated(id) is callBack from children..
Firstly, you cant update nested states directly. You will to have to update the whole "states" object. Something like this
let oldStates = this.state.states;
oldStates[id] = array[id];
this.setState({
states: {
...oldStates
}
});

Resources