Hi I am learning web worker and I believe that I have managed to make it work but still, I am struggling to figure out how to make it parallel.
for (let m = 0; m < keyCountMap.length; m += 2) {
fetchWorker.postMessage([keyCountMap[m], keyCountMap[m + 1]]);
}
I have this for loop inside which there was another for loop and i transferred all the code into the fetchWorker.
import Worker from "./worker/fetcher.worker.js";
const fetchWorker = new Worker();
I want to parallelize this at least with 5/10 thread so can i just add fetchWorker.postMessage with different parameter one after another inside the loop and increment the variable "m" of likewise
for (let m = 0; m < keyCountMap.length; m += 2) {
fetchWorker.postMessage([keyCountMap[m], keyCountMap[m + 1]]);
fetchWorker.postMessage([keyCountMap[m+2], keyCountMap[m + 3]]);
}
Does this act as two threads per loop?
This is my fetcher code:
import { Copc, Key } from "copc";
import * as THREE from "three";
const color = new THREE.Color();
const colors = [];
var nodePages, pages, receivedData, copc;
let x_min, y_min, z_min, x_max, y_max, z_max, width;
let positions = [];
let filename = "https://s3.amazonaws.com/data.entwine.io/millsite.copc.laz";
const readPoints = (id, getters) => {
let returnPoint = getXyzi(id, getters);
positions.push(
returnPoint[0] - x_min - 0.5 * width,
returnPoint[1] - y_min - 0.5 * width,
returnPoint[2] - z_min - 0.5 * width
);
const vx = (returnPoint[3] / 65535) * 255;
color.setRGB(vx, vx, vx);
colors.push(color.r, color.g, color.b);
};
function getXyzi(index, getters) {
return getters.map((get) => get(index));
}
async function load() {
copc = await Copc.create(filename);
let scale = copc.header.scale[0];
[x_min, y_min, z_min, x_max, y_max, z_max] = copc.info.cube;
width = Math.abs(x_max - x_min);
receivedData = await Copc.loadHierarchyPage(
filename,
copc.info.rootHierarchyPage
);
nodePages = receivedData.nodes;
pages = receivedData.pages;
postMessage(200);
}
async function loadData(myRoot, pointCount) {
const view = await Copc.loadPointDataView(filename, copc, myRoot);
let getters = ["X", "Y", "Z", "Intensity"].map(view.getter);
for (let j = 0; j < pointCount; j += 1) {
readPoints(j, getters);
}
postMessage([positions, colors]);
}
load();
onmessage = function (message) {
let mapIndex = message.data[0];
let pointCount = message.data[1];
console.log(mapIndex);
let myRoot = nodePages[mapIndex];
loadData(myRoot, pointCount);
};
Can anyone help me please !!
Related
I'm trying to calculate the normalized cpu percentage for my node process. My goal is to get it to match the output that I have in my htop for the pid but I'm unable to do so. My code is below along with my htop output.
import { cpuUsage } from "node:process";
import { cpus } from "os";
function basicCpuUsage() {
const startTime = process.hrtime();
const startUsage = cpuUsage();
const numCpus = cpus().length;
const add = 1 + 1; // make cpu do work?
const usageDiff = cpuUsage(startUsage); // get diff time from start
const endTime = process.hrtime(startTime); // total amount of time that has elapsed
const usageMS = (usageDiff.user + usageDiff.system) / 1e3;
const totalMS = endTime[0] * 1e3 + endTime[1] / 1e6;
const cpuPercent = (usageMS / totalMS) * 100;
const normTotal = usageMS / numCpus; // average usage time per cpu
const normPercent = (normTotal / totalMS) * 100;
console.log({
cpuPercent: cpuPercent.toFixed(2),
normPercent: normPercent.toFixed(2),
});
}
process.title = "CPU Test";
const { pid } = process;
console.log({ pid });
const title = setInterval(() => {
basicCpuUsage();
}, 1000);
Here is my output, as you can see my code cpu output does no match my htop cpu output. Which part of my calculation is incorrect? I was thinking this might have to do with my setInterval function call, but not sure. I am attempting to create a long running process where I can view the cpu usage.
Turns out I was making an incorrect calculation. I was dividing my totalTimeMS twice when I should have done it once. Additionally I moved the currentUsage and currentTime to the outside of the function.
Below is the correct calculation:
import { cpus } from "os";
let currentUsage = process.cpuUsage();
let currentTime = process.hrtime();
function basicCpuUsage() {
const numCpus = cpus().length;
const usageDiff = process.cpuUsage(currentUsage); // get diff time from start
const endTime = process.hrtime(currentTime); // total amount of time that has elapsed
currentUsage = process.cpuUsage()
currentTime = process.hrtime();
const usageMS = (usageDiff.user + usageDiff.system) / 1e3;
const totalMS = endTime[0] * 1e3 + endTime[1] / 1e6;
const cpuPercent = (usageMS / totalMS) * 100;
const normPercent = (usageMS / totalMS / numCpus) * 100; // average usage time per cpu
console.log({
cpuPercent: cpuPercent.toFixed(2),
normPercent: normPercent.toFixed(2),
});
}
process.title = "CPU Test";
setInterval(() => {
for (let i = 0; i < 25; i++) {
const add = 1 + 1;
}
basicCpuUsage();
}, 5000);
My goal is to repeatedly call a function to generate a random key as fast as possible. I've tried the following script and it takes around ~30ms to execute the function which seems slow.
const cluster = require("node:cluster");
const { cpus } = require("node:os");
const process = require("node:process");
const ethers = require("ethers");
const numCPUs = cpus().length;
// Get number of leading zeros from ethereum address
const getLeadingZeros = (address) => {
const leadingZeros = address.slice(2, address.length).match(/^0+/);
return leadingZeros ? leadingZeros[0].length : 0;
};
if (cluster.isPrimary) {
console.log(`Primary ${process.pid}: starting workers...`);
// Fork workers.
for (let i = 0; i < numCPUs / 2; i++) {
cluster.fork();
}
} else {
console.log(`Worker ${process.pid} started`);
let num = 5;
while (true) {
let wallet = ethers.Wallet.createRandom();
let address = wallet.address;
if (getLeadingZeros(address) > num) {
console.log(
`Found ${num} zeros in ${address}`
);
}
}
}
My Code:
const crypto = require('crypto');
const crashHash = '';
// Hash from bitcoin block #610546. Public seed event: https://twitter.com/Roobet/status/1211800855223123968
const salt = '0000000000000000000fa3b65e43e4240d71762a5bf397d5304b2596d116859c';
function saltHash(hash) {
return crypto
.createHmac('sha256', hash)
.update(salt)
.digest('hex');
}
function generateHash(seed) {
return crypto
.createHash('sha256')
.update(seed)
.digest('hex');
}
function divisible(hash, mod) {
// We will read in 4 hex at a time, but the first chunk might be a bit smaller
// So ABCDEFGHIJ should be chunked like AB CDEF GHIJ
var val = 0;
var o = hash.length % 4;
for (var i = o > 0 ? o - 4 : 0; i < hash.length; i += 4) {
val = ((val << 16) + parseInt(hash.substring(i, i + 4), 16)) % mod;
}
return val === 0;
}
function crashPointFromHash(serverSeed) {
const hash = crypto
.createHmac('sha256', serverSeed)
.update(salt)
.digest('hex');
const hs = parseInt(100 / 4);
if (divisible(hash, hs)) {
return 1;
}
const h = parseInt(hash.slice(0, 52 / 4), 16);
const e = Math.pow(2, 52);
return Math.floor((100 * e - h) / (e - h)) / 100.0;
}
function getPreviousGames() {
const previousGames = [];
let gameHash = generateHash(crashHash);
for (let i = 0; i < 100; i++) {
const gameResult = crashPointFromHash(gameHash);
previousGames.push({ gameHash, gameResult });
gameHash = generateHash(gameHash);
}
return previousGames;
}
function verifyCrash() {
const gameResult = crashPointFromHash(crashHash);
const previousHundredGames = getPreviousGames();
return { gameResult, previousHundredGames };
}
console.log(verifyCrash());
Code Sandbox
I'm trying to make this code show the results it already shows, but I want it to add something to the end of each gameResult data so it would look like this: gameResult: 4.39 "maybe"
I've tried to add something like this to the code with no luck. I had it working to the point where it would only return the very first gameResult but not the ones after. If someone could help that would be great, or if you have another way other than this code below that I was trying to use, that works too.
function gameResult
const result =
if (gameResult === 1) {
return "no";
};
if (gameResult <= 3) {
return "maybe";
};
if (gameResult <= 10) {
return "yes";
};
So, if I understand correctly the expected output should be like this,
{
"gameResult": "4.39 "yes"",
"previousHundredGames": [...]
}
I am able to do this by modifying the verifyCrash function to this,
function verifyCrash() {
let gameResult = crashPointFromHash(crashHash);
const previousHundredGames = getPreviousGames();
if (gameResult === 1) {
gameResult=+' "no"';
}
if (gameResult <= 3) {
gameResult=+' "maybe"';
}
if (gameResult <= 10) {
gameResult+= ' "yes"';
}
return { gameResult, previousHundredGames };
}
Check this link to see it in action,
https://codesandbox.io/s/crash-forked-f7fb7
How to add a calculation function to the loan calculator. When I add
another block (else) function does not work and other functions too. How do I add a function correctly? That the data below could work correctly.
// global variables
var min, max, creditBody, oneTimeCommission, monthlyCommission, rate, grace, smsCost, monthlyFee;
// calculating function
function calc(type, summ, term) {
min = 3, max = 36;
if (type == "standart") {
$("#month-slider").slider('option', {min: 3});
$("#min").text('3');
oneTimeCommission = 0.0199;
monthlyCommission = 0.0199;
rate = 0.0001;
smsCost = 20;
creditBody = summ / (1 - monthlyCommission);
monthlyFee = ((creditBody + (creditBody * term * monthlyCommission)) / term) + smsCost;
}
else {
min = 4, max = 36;
$("#month-slider").slider('option',{min: min});
$("#min").text('4');
if (term < min) {
term = min;
}
oneTimeCommission = 0;
monthlyCommission = 0.035;
grace = 4;
smsCost = 20;
creditBody = summ / (1 - 0);
monthlyFee = ((creditBody + (creditBody * (term - grace) * monthlyCommission)) / term) + smsCost;
}
// my add block - not work :(
else {
min = 8, max = 36;
$("#month-slider").slider('option',{min: min});
$("#min").text('8');
if (term < min) {
term = min;
}
oneTimeCommission = 0;
monthlyCommission = 0.035;
grace = 8;
smsCost = 20;
creditBody = summ / (1 - 0);
monthlyFee = ((creditBody + (creditBody * (term - grace) * monthlyCommission)) / term) + smsCost;
}
//
var result = {type:type,summ:summ,term:term};
$("#monthlyFee").text(parseInt(monthlyFee) + " грн");
$("#total-sum").text(parseInt($("#product-sum").val()) + " грн");
$("#total-month").text(parseInt($("#credit-month").val()) + " мic");
return result
}
Maybe this can be a better way to handle your case, avoiding if/else conditions and make it more pure.
calc = ( type, params ) => {
const typesFn = {
'standart': () => {
// do something here
},
'test': ( params ) => {
console.log( params );
}
}
typesFn[type](params); // call && exec
}
calc( 'test', {summ: null, term:null, test: true});
I hope that helps you :)
i was trying to implement the A* algorithm and followed the wikipedia pseudo code to make this.
when i pass a predefined object pixel to the a funtion getG() it says that the object is null. I'm sorry if i am not pointing to a specific problem but i am not even sure how to really specify the problem by name. i have tried commenting out the code to increase readability.
git repository link of the whole project - https://github.com/NirobNabil/WhirlWind
(things are a little messy here because i didn't use github at first and i uploaded it just a little ago for posting the problem)
[ i'm actually making this to use a* to find path for my bot which is powered by arduino. thats why i'm using involt. ]
here goes the code,
$(function() {
// define the height, width and bot size in centemeter
total_width = 200;
total_height = 200;
bot_size = 20;
total_box = (total_height / bot_size) * (total_width / bot_size);
box_in_x = total_width / bot_size;
box_in_y = total_height / bot_size;
//populating the pixels array
populate(total_width / bot_size, total_height / bot_size, "UND");
pathfind(pixels, pixels[13], pixels[pixels.length - 1]);
})
var pixels = []; //an array to hold all the objects(the grid)
var obstacles = []; //array to hold the obstacles
function pixel(X, Y, obs) {
this.X_co_ordinate = X;
this.Y_co_ordinate = Y;
this.state = obs; //availale states OPN, UND, OBS, DIS, NULL
this.g = 0;
this.h = 0;
this.f = 0;
this.last = null;
} //every block in the grid is a pixel
//01719372596
function populate(height, width, obs_val = "UND") {
pixels[0] = new pixel(0, 10, obs_val);
for (h = height, i = 0; h >= 0; h--) {
for (w = 0; w < width; w++, i++) {
var temp_obs = new pixel(w, h, obs_val);
temp_obs.last = pixels[0];
pixels[i] = temp_obs; //saving temp_pixel object to pixels array
}
}
} //populating the grid AKA pixels with pixel objects or blocks
// this funtion is where the problem shows up
function getG(current, start) {
let g = 1;
while (current != start && current.last != start && current) {
current = current.last;
g++;
}
return g;
} //get the g val(cost to come to this pixel from the start) of the current pixel
function getH(current, end) {
let I = Math.abs(current.X_co_ordinate - end.X_co_ordinate) + Math.abs(current.Y_co_ordinate - end.Y_co_ordinate);
return I;
} //get the h val(heuristic) of the current pixel
function getF(start, current, end) {
let G = getG(current, start);
let H = getH(current, end);
return G + H;
} //get the f val(total) of the current pixel
function lowFinArray(arr, start, end) {
// here arr is the grid/pixel
let current_low = arr[0];
for (let i = 0; i < arr.length; i++) {
let getF1 = getF(start, current_low, end);
let getF2 = getF(start, arr[i], end);
if (getF1 < getF2) {
current_low = arr[i];
}
}
console.log("current low");
console.log(current_low);
return current_low;
}
function getneighbours(grid, current) {
let neightbours = [];
neightbours.push(grid[getIndex(current.X_co_ordinate - 1, current.Y_co_ordinate)]);
neightbours.push(grid[getIndex(current.X_co_ordinate + 1, current.Y_co_ordinate)]);
neightbours.push(grid[getIndex(current.X_co_ordinate, current.Y_co_ordinate - 1)]);
neightbours.push(grid[getIndex(current.X_co_ordinate, current.Y_co_ordinate + 1)]);
/*
for(i=0; i<neightbours.length; i++){
neightbours[i].last = current;
}*/
console.log("neightbours");
console.log(neightbours);
return neightbours;
} //get the neighbour pixels of the current pixel
//main algo
function pathfind(grid, start, end) {
let closedSet = [];
let openSet = [];
openSet.push(start);
let current = start;
//trying to debug
console.log("low F in arr");
console.log(lowFinArray(grid, start, end));
console.log(start);
console.log(current);
console.log(end);
console.log(grid);
let x = 0;
while (openSet.length > 0) {
//trying to debug
console.log("executed " + (x++));
console.log("openset");
console.log(openSet);
current = lowFinArray(grid, start, end); //assigning the pixel with lowest f val to current
console.log("current");
console.log(current);
if (current == end) {
console.log(getPath(current));
}
let neighbours = getneighbours(grid, current);
for (let i = 0; i < neighbours.length; i++) {
let neighbour = neighbours[i];
if (closedSet.includes(neighbour)) {
continue;
}
if (!openSet.includes(neighbours)) {
openSet.push(neighbours);
}
//console.log(current);
let getg = getG(current, start);
let geth = getH(current, end);
//console.log(getg);
let tGscore = getg + geth; //here getH is being used as a distance funtion
if (tGscore >= getg) {
continue;
}
neighbour.last = current;
neighbour.g = tGscore;
neighbour.f = getF(neighbour);
}
if (x > 10) {
return 0;
}; //the loop was running forever so i tried this to stop the loop after 10 iterations
}
}
function getPath(current) {
let path = [current];
while (current.last != null) {
path.push(current.last);
}
return path;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
and here is what the console says,
Uncaught TypeError: Cannot read property 'last' of null
at getG (app.js:226)
at getF (app.js:241)
at lowFinArray (app.js:249)
at pathfind (app.js:292)
at HTMLDocument.<anonymous> (app.js:92)
at mightThrow (jquery-3.1.1.js:3570)
at process (jquery-3.1.1.js:3638)
You're doing your checks in the wrong order:
while (current != start && current.last != start && current) {
There's no point in using && current after you've already used current.last.
Perhaps changing the order would solve the problem. It will at least get rid of your current error:
while (current && current != start && current.last != start) {
Regarding the title of this question:
In javascript, after i pass a non null object to a funtion it says the object is null
It may very well be non-null 100% of the time you pass it into the function, but you are repeatedly overwriting its parameter within the function, so all bets are off.