Create multiple XML files in Node Js - node.js

I am new to Node Js. I can't find a solution for this problem: I have to use a for loop to change the XML and to create a new one. It already gives me one new XML file but I want ten new XML files in the end. I hope my explanation wasn't too bad.
for (t = 0; t < 10; t++) {
for (let i = 0; i < homeTeamStarting11.length; i++) {
homeTeamStarting11[i] = homeTeamStarting11[i];
let roleHome = homeTeamStarting11[i].role['$t']; //string
let roleAway = awayTeamStarting11[i].role['$t'];
let currentPosition = homeTeamStarting11[i].position;
let currentPositiontwo = awayTeamStarting11[i].position;
if (roleHome === 'GOALKEEPER' || roleAway === 'GOALKEEPER') {
} else if (roleHome === 'DEFENSE' || roleAway === 'DEFENSE') {
currentPosition['y']['$t'] = Math.floor(Math.random() * 80) + 3;
currentPositiontwo['y']['$t'] = Math.floor(Math.random() * 80) + 3;
currentPosition['x']['$t'] = Math.floor(Math.random() * 80) + 3;
currentPositiontwo['x']['$t'] = Math.floor(Math.random() * 80) + 3;
} else {
currentPosition['y']['$t'] = Math.random() * (90 - 1) + 1;
currentPositiontwo['y']['$t'] = Math.random() * (90 - 1) + 1;
currentPosition['x']['$t'] = Math.random() * (90 - 1) + 1;
currentPositiontwo['x']['$t'] = Math.random() * (90 - 1) + 1;
}
homeTeamStarting11[i].position = currentPosition;
//awayTeamStarting11[i].position = currentPositiontwo;
//const TeamTogether = homeTeamStarting11.concat(awayTeamStarting11);
json['lineup']['away']['startingEleven']['persons']['player'] = awayTeamStarting11;
json['lineup']['home']['startingEleven']['persons']['player'] = homeTeamStarting11;
}
const Name = JSON.stringify(json);
const xml = parser.toXml(Name);
let xjz = getFilename(2);
fs.writeFile('xmls/' + xjz + '.xml', xml, function(err, data) {
});
function getFilename(anyNumber) {
let filename = 'xmlfilename' + anyNumber;
return filename;
}
}

You call your getFilename() function with a constant 2. So each run through your for (t = 0; t < 10; t++) { ... } loop overwrites the same file.
Try using let xjz = getFilename(t); to get a different filename each time.

Related

How to generate the array of time durations

I'm trying to create an array of time durations in a day with 15 minute intervals with moment.js and ES6.
Example: let time_duration= ["15 Min", "30 Min",..., "1 hr 15 min", "1 hr 30 min"]
I think it supposed to work:
generateTimeDurations(minutesGap: number, length: number): string[] {
const result = Array(length).fill(null);
let acc = 0;
return result.map(_ => {
acc += minutesGap;
if (acc >= 60) {
return `${Math.floor(acc / 60)} hr ${acc % 60} min`;
} else {
return `${acc} min`;
}
});
}
If you only need static time levels like "15 Min", "30 Min" and so on you could try to do it in plain JS with Array#fill and Array#map.
const hours = 24;
const minutes = 24 * 60;
function minsToHM(totalMins) {
let padZero = value => String(value).padStart(2, "0");
totalMins = Number(totalMins);
const h = Math.floor(totalMins / 60);
const m = Math.floor(totalMins % 60);
const hDisplay = h > 0 ? padZero(h) + (h == 1 ? " Hour" : " Hours") : "";
const mDisplay = m > 0 ? padZero(m) + (m == 1 ? " Min" : " Mins") : "";
return `${hDisplay}${h > 0 && m > 0 ? ", ": ""}${mDisplay}`;
}
function splitHours(hours, difference) {
const mins = hours * 60;
return Array(Math.floor(mins / difference))
.fill(1)
.map((_, idx) => (idx+1) * difference)
}
const output = splitHours(1.5, 15).map(i => minsToHM(i))
console.log(output)
.as-console-wrapper { max-height: 100% !important; top: 0px }
console.clear();
function digitToMinute(digit) {
return digit * 60 / 100;
}
function minutesToDigit(minute) {
return minute * 100 / 60;
}
function digitsToHourAndMinutes(digit) {
return [Math.floor(digit / 60), digitToMinute(getFraction(digit / 60))];
}
function getFraction(f) {
return Math.ceil(((f < 1.0) ? f : (f % Math.floor(f))) * 100)
}
function getIntervals(max) {
var intervals = [];
var span = 15;
var i = 0;
while (i <= max) {
if (i > 0) {
let [hour, minute] = digitsToHourAndMinutes((i));
let string = [];
if (hour > 0) {
string.push(hour + ' hour');
}
if (minute > 0) {
string.push(minute + ' minutes');
}
intervals.push(string.join(' '));
}
i = i + span;
}
return intervals;
}
console.log(getIntervals(60 * 5));

Instagram Auto-Like JavaScript BOT

This code brings back an error of
Uncaught TypeError: Cannot read property 'innerHTML' of null
at doLike (<anonymous>:20:21)
at <anonymous>:35:1
doLike # VM1269:20
(anonymous) # VM1269:35
It has worked in the past, I got it from this website : https://blog.joeldare.com/simple-instagram-like-bot/
function getHeartElement() {
var knownHeartElementNames = ["coreSpriteHeartOpen", "coreSpriteLikeHeartOpen"];
var i = 0;
// Loop through the known heart elements until one works
for (i = 0; i < knownHeartElementNames.length; i++) {
var heartElement = document.querySelector("." + knownHeartElementNames[i]);
if (heartElement != undefined) {
break;
}
}
return heartElement;
}
function doLike() {
var likeMax = 100;
var likeElement = getHeartElement();
var nextElement = document.querySelector(".coreSpriteRightPaginationArrow");
likeCount++;
var nextTime = Math.random() * (14000 - 4000) + 4000;
if (likeElement.innerHTML.match("Unlike") == null) {
likeElement.click();
console.log(likeCount + " - liked");
} else {
console.log(likeCount + " - skipped");
}
setTimeout(function() {nextElement.click();}, 1000);
if (likeCount < likeMax) {
setTimeout(doLike, nextTime);
} else {
console.log("Nice! Time for a break.");
}
}
var likeCount = 0;
doLike();
You may want to use a tool such a Keygram - https://www.thekeygram.com
It works really well for me to gain followers

How do I reverse a scanline using the jpeg-js module/node JS buffer?

I've been fiddling around with the jpeg-js module and Node JS Buffer, and attempting to create a small command line program that modifies the decoded JPEG buffer data and creates a pattern of X number of reversed scanlines and X number of normal scanlines before saving a new JPEG. In other words, I'm looking to flip portions of the image, but not the entire image itself (plenty of modules that do such a thing, of course, but not the specific use case I have).
To create the reversed/normal line patterns, I've been reading/writing line by line, and saving a slice of that line to a variable, then starting at the end of scanline and incrementally going down by slices of 4 bytes (the alloc for an RGBA value) until I'm at the beginning of the line. Code for the program:
'use strict';
const fs = require('fs');
const jpeg = require('jpeg-js');
const getPixels = require('get-pixels');
let a = fs.readFileSync('./IMG_0006_2.jpg');
let d = Buffer.allocUnsafe(a.width * a.height * 4);
let c = jpeg.decode(a);
let val = false; // track whether normal or reversed scanlines
let lineWidth = b.width * 4;
let lineCount = 0;
let track = 0;
let track2 = 0;
let track3 = 0;
let curr, currLine; // storage for writing/reading scnalines, respectively
let limit = {
one: Math.floor(Math.random() * 141),
two: Math.floor(Math.random() * 151),
three: Math.floor(Math.random() * 121)
};
if (limit.one < 30) {
limit.one = 30;
}
if (limit.two < 40) {
limit.two = 40;
}
if (limit.two < 20) {
limit.two = 20;
}
let calc = {};
calc.floor = 0;
calc.ceil = 0 + lineWidth;
d.forEach(function(item, i) {
if (i % lineWidth === 0) {
lineCount++;
/* // alternate scanline type, currently disabled to figure out how to succesfully reverse image
if (lineCount > 1 && lineCount % limit.one === 0) {
// val = !val;
}
*/
if (lineCount === 1) {
val = !val; // setting alt scanline check to true initially
} else if (calc.floor + lineWidth < b.data.length - 1) {
calc.floor += lineWidth;
calc.ceil += lineWidth;
}
currLine = c.data.slice(calc.floor, calc.ceil); // current line
track = val ? lineWidth : 0; // tracking variable for reading from scanline
track2 = val ? 4 : 0; // tracking variable for writing from scanline
}
//check if reversed and writing variable has written 4 bytes for RGBA
//if so, set writing source to 4 bytes at end of line and read from there incrementally
if (val && track2 === 4) {
track2 = 0; // reset writing count
curr = currLine.slice(track - 4, track); // store 4 previous bytes as writing source
if (lineCount === 1 && lineWidth - track < 30) console.log(curr); //debug
} else {
curr = currLine; //set normal scanline
}
d[i] = curr[track2];
// check if there is no match between data source and decoded image
if (d[i] !== curr[track2]) {
if (track3 < 50) {
console.log(i);
}
track3++;
}
track2++; //update tracking variable
track = val ? track - 1 : track + 1; //update tracking variable
});
var rawImageData = {
data: d,
width: b.width,
height: b.height
};
console.log(b.data.length);
console.log('errors\t', track3);
var jpegImageData = jpeg.encode(rawImageData, 100);
fs.writeFile('foo2223.jpg', jpegImageData.data);
Alas, the reversed scanline code I've written does not properly. Unfortunately, I've only been able successfully reverse the red channel of my test image (see below left), with the blue and green channels just turning into vague blurs. The color scheme should look something like the right image.
What am I doing wrong here?
For reversed lines, you stored slices of 4 bytes(4 bytes = 1 pixel), then write the first value of the pixel(red) correctly.
But in the next iteration, you overwrite the slice curr with currLine, rest of channels gets wrong values.
if (val && track2 === 4) {
track2 = 0; // reset writing count
curr = currLine.slice(track - 4, track); // store 4 previous bytes as writing source
if (lineCount === 1 && lineWidth - track < 30) console.log(curr); //debug
} else {
curr = currLine; //set normal scanline
}
Iteration 0: val == true, track2 == 4, set curr to next pixel, write red channel.
Iteration 1: val == true, track2 == 1, (val && track2 === 4) == false, set curr to currLine, write green channel.
You can move track2 === 4 branch to avoid this:
if (val) {
if (track2 === 4) {
track2 = 0; // reset writing count
curr = currLine.slice(track - 4, track); // store 4 previous bytes as writing source
if (lineCount === 1 && lineWidth - track < 30) console.log(curr); //debug
}
} else {
curr = currLine; //set normal scanline
}
Fixed code should look like this:
function flipAlt(input, output) {
const fs = require('fs');
const jpeg = require('jpeg-js');
let a = fs.readFileSync(input);
let b = jpeg.decode(a);
let d = Buffer.allocUnsafe(b.width * b.height * 4);
let val = false; // track whether normal or reversed scanlines
let lineWidth = b.width * 4;
let lineCount = 0;
let track = 0;
let track2 = 0;
let track3 = 0;
let curr, currLine; // storage for writing/reading scnalines, respectively
let limit = {
one: Math.floor(Math.random() * 141),
two: Math.floor(Math.random() * 151),
three: Math.floor(Math.random() * 121)
};
if (limit.one < 30) {
limit.one = 30;
}
if (limit.two < 40) {
limit.two = 40;
}
if (limit.two < 20) {
limit.two = 20;
}
let calc = {};
calc.floor = 0;
calc.ceil = 0 + lineWidth;
d.forEach(function(item, i) {
if (i % lineWidth === 0) {
lineCount++;
if (lineCount > 1) {
val = !val;
}
if (lineCount === 1) {
val = !val; // setting alt scanline check to true initially
} else if (calc.floor + lineWidth < b.data.length - 1) {
calc.floor += lineWidth;
calc.ceil += lineWidth;
}
currLine = b.data.slice(calc.floor, calc.ceil); // current line
track = val ? lineWidth : 0; // tracking variable for reading from scanline
track2 = val ? 4 : 0; // tracking variable for writing from scanline
}
//check if reversed and writing variable has written 4 bytes for RGBA
//if so, set writing source to 4 bytes at end of line and read from there incrementally
if (val) {
if (track2 === 4) {
track2 = 0; // reset writing count
curr = currLine.slice(track - 4, track); // store 4 previous bytes as writing source
if (lineCount === 1 && lineWidth - track < 30) console.log(curr); //debug
}
} else {
curr = currLine; //set normal scanline
}
d[i] = curr[track2];
// check if there is no match between data source and decoded image
if (d[i] !== curr[track2]) {
if (track3 < 50) {
console.log(i);
}
track3++;
}
track2++; //update tracking variable
track = val ? track - 1 : track + 1; //update tracking variable
});
var rawImageData = {
data: d,
width: b.width,
height: b.height
};
console.log(b.data.length);
console.log('errors\t', track3);
var jpegImageData = jpeg.encode(rawImageData, 100);
fs.writeFile(output, jpegImageData.data);
}
flipAlt('input.jpg', 'output.jpg');
Instead of tracking array indices, you can use utility library like lodash, it should make things easier:
function flipAlt(input, output) {
const fs = require('fs');
const jpeg = require('jpeg-js');
const _ = require('lodash');
const image = jpeg.decode(fs.readFileSync(input));
const lines = _.chunk(image.data, image.width*4);
const flipped = _.flatten(lines.map((line, index) => {
if (index % 2 != 0) {
return line;
}
const pixels = _.chunk(line, 4);
return _.flatten(pixels.reverse());
}));
const imageData = jpeg.encode({
width: image.width,
height: image.height,
data: new Buffer(flipped)
}, 100).data;
fs.writeFile(output, imageData);
}
flipAlt('input.jpg', 'output.jpg');

nodejs split image into chunks

Is there a nodeJS-way to split an image into single chunks?
Probably with different dimensions?
Like the photos on image below
I've done something like this using jimp, however it can probably be much more concise...
var Jimp = require("jimp");
/**
* #param filename - input file
* #param numSlices - how many slices
* #param attenuation - how quickly slices get smaller
*/
function sliceImage(filename, numSlices, attenuation) {
Jimp.read(filename).then(image => {
let w = image.bitmap.width;
let h = image.bitmap.height;
let sliceWidth = w / numSlices;
let midlane = w / 2;
let slack = 0.001;
let slices = [];
function slicePair(left, right) {
if (left < (0 - slack) || (right - sliceWidth) > (w + slack)) {
return;
}
let leftSlice = image.clone();
let rightSlice = image.clone();
leftSlice.crop(left, 0, sliceWidth, h);
rightSlice.crop(right - sliceWidth, 0, sliceWidth, h);
slices.push(leftSlice);
slices.push(rightSlice);
slicePair(left - sliceWidth, right + sliceWidth);
}
function doSlice() {
if (numSlices % 2 == 0) {
slicePair(midlane - sliceWidth, midlane + sliceWidth);
} else {
let middle = image.clone();
middle.crop(midlane - (sliceWidth / 2), 0, sliceWidth, h);
slices.push(middle);
slicePair(midlane - (1.5 * sliceWidth), midlane + (1.5 * sliceWidth));
}
}
function overlay() {
let canvas = image.clone().brightness(1);
let odd = !(slices.length % 2 === 0);
let adjust = odd ? (sliceWidth / 2) : 0;
slices.reverse();
if (odd) {
let middle = slices.pop();
canvas.composite(middle, (midlane - (sliceWidth / 2)), 0);
}
for (let i = 0; i < (slices.length + 2); i++) {
let k = odd ? (i + 1) : i;
let left = slices.pop().crop(0, attenuation * k, sliceWidth, (h - (attenuation * k) * 2));
let right = slices.pop().crop(0, attenuation * k, sliceWidth, (h - (attenuation * k) * 2));
canvas.composite(left, (midlane - ((i + 1) * sliceWidth)) - adjust, (attenuation * k));
canvas.composite(right, (midlane + (i * sliceWidth)) + adjust, (attenuation * k));
}
canvas.write("result.jpg");
return canvas;
}
doSlice();
return overlay();
});
}
const Jimp = require('jimp') ;
const forloop=require('async-for-loop');
const width=1000, height=716,h=7,v=7;
async function crop(source,filename,offSetX, offSetY, width,height,cb) {
// Reading Image
const image = await Jimp.read
(source);
image.crop(offSetX, offSetY, width,height)
.write(filename);
}
//
forloop(h,(hi,nextH)=>{
forloop(v,async (vi,nextV)=>{
await crop('/Users/you/Projects/sliceit/imgs/image.jpg',`/Users/you/Projects/sliceit/out/slice_${hi}_${vi}.jpg`,
hi*width,vi*height,width,height,nextV
);
nextV();
},()=>{
nextH();
})
},()=>{
console.log("Image is processed successfully");
})

Calculate the bounding box of STL file with JavaScript

So I am using this npm package: node-stl
And its working great. However the regexp syntax, mathematics and geometrical calculations are somewhat confusing to me. Especially all at the same time.
Basically what I want to achieve is to extend the script to calculate the bounding box of the STL.
Here is the main file that calculates the volume and weight of the STL being parsed/read.
var fs = require('fs');
// Vertex
function Vertex (v1,v2,v3) {
this.v1 = Number(v1);
this.v2 = Number(v2);
this.v3 = Number(v3);
}
// Vertex Holder
function VertexHolder (vertex1,vertex2,vertex3) {
this.vert1 = vertex1;
this.vert2 = vertex2;
this.vert3 = vertex3;
}
// transforming a Node.js Buffer into a V8 array buffer
function _toArrayBuffer (buffer) {
var
ab = new ArrayBuffer(buffer.length),
view = new Uint8Array(ab);
for (var i = 0; i < buffer.length; ++i) {
view[i] = buffer[i];
}
return ab;
}
// calculation of the triangle volume
// source: http://stackoverflow.com/questions/6518404/how-do-i-calculate-the-volume-of-an-object-stored-in-stl-files
function _triangleVolume (vertexHolder) {
var
v321 = Number(vertexHolder.vert3.v1 * vertexHolder.vert2.v2 * vertexHolder.vert1.v3),
v231 = Number(vertexHolder.vert2.v1 * vertexHolder.vert3.v2 * vertexHolder.vert1.v3),
v312 = Number(vertexHolder.vert3.v1 * vertexHolder.vert1.v2 * vertexHolder.vert2.v3),
v132 = Number(vertexHolder.vert1.v1 * vertexHolder.vert3.v2 * vertexHolder.vert2.v3),
v213 = Number(vertexHolder.vert2.v1 * vertexHolder.vert1.v2 * vertexHolder.vert3.v3),
v123 = Number(vertexHolder.vert1.v1 * vertexHolder.vert2.v2 * vertexHolder.vert3.v3);
return Number(1.0/6.0)*(-v321 + v231 + v312 - v132 - v213 + v123);
}
// parsing an STL ASCII string
function _parseSTLString (stl) {
var totalVol = 0;
// yes, this is the regular expression, matching the vertexes
// it was kind of tricky but it is fast and does the job
var vertexes = stl.match(/facet\s+normal\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+outer\s+loop\s+vertex\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+vertex\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+vertex\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+endloop\s+endfacet/g);
vertexes.forEach(function (vert) {
var preVertexHolder = new VertexHolder();
vert.match(/vertex\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s/g).forEach(function (vertex, i) {
var tempVertex = vertex.replace('vertex', '').match(/[-+]?[0-9]*\.?[0-9]+/g);
var preVertex = new Vertex(tempVertex[0],tempVertex[1],tempVertex[2]);
preVertexHolder['vert'+(i+1)] = preVertex;
});
var partVolume = _triangleVolume(preVertexHolder);
totalVol += Number(partVolume);
})
var volumeTotal = Math.abs(totalVol)/1000;
return {
volume: volumeTotal, // cubic cm
weight: volumeTotal * 1.04 // gm
}
}
// parsing an STL Binary File
// (borrowed some code from here: https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/STLLoader.js)
function _parseSTLBinary (buf) {
buf = _toArrayBuffer(buf);
var
headerLength = 80,
dataOffset = 84,
faceLength = 12*4 + 2,
le = true; // is little-endian
var
dvTriangleCount = new DataView(buf, headerLength, 4),
numTriangles = dvTriangleCount.getUint32(0, le),
totalVol = 0;
for (var i = 0; i < numTriangles; i++) {
var
dv = new DataView(buf, dataOffset + i*faceLength, faceLength),
normal = new Vertex(dv.getFloat32(0, le), dv.getFloat32(4, le), dv.getFloat32(8, le)),
vertHolder = new VertexHolder();
for(var v = 3; v < 12; v+=3) {
var vert = new Vertex(dv.getFloat32(v*4, le), dv.getFloat32((v+1)*4, le), dv.getFloat32( (v+2)*4, le ) );
vertHolder['vert'+(v/3)] = vert;
}
totalVol += _triangleVolume(vertHolder);
}
var volumeTotal = Math.abs(totalVol)/1000;
return {
volume: volumeTotal, // cubic cm
weight: volumeTotal * 1.04 // gm
}
}
// NodeStl
// =======
// > var stl = NodeStl(__dirname + '/myCool.stl');
// > console.log(stl.volume + 'cm^3');
// > console.log(stl.weight + 'gm');
function NodeStl (stlPath) {
var
buf = fs.readFileSync(stlPath),
isAscii = true;
for (var i=0, len=buf.length; i<len; i++) {
if (buf[i] > 127) { isAscii=false; break; }
}
if (isAscii)
return _parseSTLString(buf.toString());
else
return _parseSTLBinary(buf);
}
module.exports = NodeStl;
If anyone could help me with this it would be great. I know and it feels like it simple. That I just need to know max/min of the different directions(x,y,z) and could then calculate the bounding box.
But I do not understand what the max/min for x,y and z is here. Please answer if you have an idea.
I've made a new branch https://github.com/johannesboyne/node-stl/tree/boundingbox could you please verify whether the applied algorithm works?
Best,
Johannes
Edit: If the branch is stable -> works I'll push it into v.0.1.0 (don't know why it is still 0.0.1)

Resources