Get all date based on given requirement - node.js

My requirement.EX: date(2019-07-01) in that month 4th week i wanna particular dates based on like["1","6","7"] . ex Result like: [2019-07-28,2019-,2019-08-02,2019-08-03]

var data = {"2020-07-01",
"2020-07-02",
"2020-07-03",
"2020-07-04",
"2020-07-05",
"2020-07-06",
"2020-07-07",
"2020-07-08",
"2020-07-09",
"2020-07-10",
"2020-07-11",
"2020-07-12",
"2020-07-13",
"2020-07-14",
"2020-07-15",
"2020-07-16",
"2020-07-17",
"2020-07-18",
"2020-07-19",
"2020-07-20",
"2020-07-21",
"2020-07-22",
"2020-07-23",
"2020-07-24",
"2020-07-25",
"2020-07-26",
"2020-07-27",
"2020-07-28",
"2020-07-29",
"2020-07-30",
"2020-07-31",}
for(var n = 0; n < data.on.order.length; n++){
for(var m = 0; m < data.on.days.length; m++){
//****
if(data.on.order[n] === '1'){
firstdayMonth = moment(endOfMonth).date(0);
}else{
firstdayMonth = moment(endOfMonth).date(1);
}
// console.log('------------1',firstdayMonth)
var firstdayWeek = moment(firstdayMonth).isoWeekday(parseInt(data.on.days[m],10));
console.log('------------2 ',firstdayWeek)
// if(data.on.order[n] === "1"){
nWeeks = parseInt(data.on.order[n],10);
// }else{
// nWeeks = parseInt(data.on.order[n],10);
// }
var nextEvent = moment(firstdayWeek).add(nWeeks,'w');
// = moment(firstdayWeek).add(nWeeks,'w');
console.log('------------3',nextEvent,'---- ',nWeeks)
//****
if(nextEvent.isAfter(eventDate)){
eventDate = nextEvent;
// console.log("### eventDate: ", eventDate)
// console.log('Total dates in month ',eventDate.format("YYYY-MM-DD"))
meetings.push(eventDate.format("YYYY-MM-DD"));
}
}
}

Related

Discover exact POST parameters

I'm trying to get data from a website that does not have an API documentation. I used selenium to login and navigate. Today I found the data I need, it appears after a post request.
There's any way I can get the exact post parameters to do it in my node program?
Data I need
edit 1:
the code that works from console browser scrap the data from the page and save a csv file:
const timeElapsed = Date.now();
const today = new Date(timeElapsed);
let updateTime;
let dataStudents = "";
let anoSerie;
let turma;
let prova;
let disciplina;
class AlunoProva {
constructor(nome, Status, anoSerie, turma, prova, disciplina, modalidadeEnsino, data) {
this.nome = nome;
this.Status = Status;
this.anoSerie = anoSerie;
this.turma = turma;
this.prova = prova;
this.disciplina = disciplina;
this.modalidadeEnsino = modalidadeEnsino;
this.data = data;
}
}
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
blob = new Blob([data], { type: "ext/csv;charset=utf-8;" }),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
const atualState = "Finalizado - Digital, Não iniciado, Em progresso - Digital"
function getTurma() {
let Turma = prompt("Informe a letra da turma atual", "A");
while (Turma == null || Turma == "") {
alert("Truma inválida! Por favor, informe uma turma válida.");
Turma = prompt("Informe a letra da turma atual", "A");
}
return Turma;
}
turma = getTurma().toUpperCase();
function getCombo(id) {
let combo = document.getElementById(id);
let dataComboSelected = combo.options[combo.selectedIndex].text;
return dataComboSelected;
}
String.prototype.hashCode = function () {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
let aluno = new AlunoProva()
function dataMount(data) {
if (data !== "ESTUDANTE" && data !== "PARTICIPAÇÃO")
if (!atualState.includes(data)) {
aluno.nome = data;
dataStudents += data + ",";
}
else {
aluno.Status = data;
dataStudents += data + ",";
aluno.anoSerie = anoSerie;
dataStudents += anoSerie + ","
aluno.turma = turma;
dataStudents += turma + ","
aluno.prova = prova;
dataStudents += prova + ","
aluno.disciplina = disciplina;
dataStudents += disciplina + ","
if (anoSerie.includes("EF")) {
aluno.modalidadeEnsino = "Fundamental";
dataStudents += "Fundamental,"
}
else {
aluno.modalidadeEnsino = "Médio";
dataStudents += "Médio,"
}
aluno.data = today.toLocaleDateString();
dataStudents += today.toLocaleDateString() + "\n"
}
}
prova = getCombo('selectnn74f9d641c4DADOS.VL_FILTRO_AVALIACAO')
disciplina = getCombo('select3lw7fc885326DADOS.VL_FILTRO_DISCIPLINA')
anoSerie = getCombo('selecty0fuc3bed07cDADOS.VL_FILTRO_ETAPA')
Array.from($$("body table tr *")).forEach((el) => {
el = String(el.innerHTML)
if (el.indexOf('Atualizado') === 0) {
updateTime = el;
} else if (el.length != 0 && el != undefined) {
dataMount(el);
}
});
let hashname = (anoSerie + turma + prova + disciplina + JSON.stringify(today.toLocaleDateString())).toString();
fileName = `${anoSerie} - ${turma} - ${prova} - ${disciplina}"${hashname.hashCode()}".csv`
saveData(dataStudents, fileName);
I'm having a problem with selectors on node, just rebember that I'm not conected with the site, I'm simulating a navigation with selenium. All the frameworks I checked to help me with selectors needed that I provide an url, but I can't, the only way I found to enter the system is from selenium navigation to simulating a real user.

How to get quantity of duplicates in array nodejs

I'm trying to get the quantity of for example: DragonBall, it would return x3 or Featured it would return x2 etc, however I have tried this method with just the spammed response of 2
let data = mockdata.forEach(function (i) {
count[i] = (count[i] || 0) + 1;
console.log(count[i] = (count[i] || 0) + 1)
});
[
'Daily',
'DragonBall1B',
'DragonBall2B',
'DragonBall3B',
'Featured',
'Featured2',
'SquadOrigins',
'SquadOrigins2'
]
API used to retrieve the above information:
https://fortnitecontent-website-prod07.ol.epicgames.com/content/api/pages/fortnite-game/shop-sections
A regular expression can remove the first instance of digits (along with whatever follows) to get you to the key you're interested in grouping on.
const mockdata = [
'Daily',
'DragonBall1B',
'DragonBall2B',
'DragonBall3B',
'Featured',
'Featured2',
'SquadOrigins',
'SquadOrigins2'
]
const count = {};
mockdata.forEach((str) => {
const key = str.replace(/\d+.*/, '');
count[key] = (count[key] || 0) + 1;
});
console.log(count.DragonBall);
const arr = [
'Daily',
'DragonBall1B',
'DragonBall2B',
'DragonBall3B',
'Featured',
'Featured2',
'SquadOrigins',
'SquadOrigins2'
]
const count = {};
arr.forEach((str) => {
const key = str.replace(/\d+.*/, "");
count[key] = (count[key] || 0) + 1;
});
let val = Object.entries(count);
let itemName;
let itemNum;
let result = [];
for (var i in val) {
itemName = val[i][0];
itemNum = val[i][1];
result += `${itemName} (x${itemNum})\n`;
}
console.log(result);

How to calculate the working hours in flutter using mongodb

I want to calculate the working hours, my scenario is, when user login to the app and clicks on time in button that time will be stored in the database (I am using mongodb) and if user logout and then login again and then time in button should display the time at which user did last time, and then if user clicks on time out button then it should calculate the working hours, for example, if user time in at 9:10:35 AM and time out at 5:50:47 PM then the total working hours should be 9:40:13 , but from my logic of calculating total working hours it give me this 4:40:12.
Here is my code:
totalWorkingHours() {
print("working hours");
var totalWorkingMin;
var totalWorkingSec;
var totalWorkingHour;
var timeInHoursSplit;
var timeOutHoursSplit;
var timeInHours0;
var timeOutHours0;
List timeInHours;
List timeOutHours;
var inHour;
var outHour;
var inMin;
var outMin;
var inSec;
var outSec;
var flagMin = false;
var flagSec = false;
var defaultIn = " 00:00:00 PM";
var defaultOut = " 00:00:00 PM";
var data = {};
//here i am getting the time in and time out values and using api if in case user logout, and spliting it to get the hours, min and sec
if(workinghours=="0" && getapitimeout==""){
print("11");
timeInHoursSplit = defaultIn.split(' '); //18:35:00 PM
timeOutHoursSplit = defaultOut.split(' ');
}
else if (workinghours == "0" && getTimeInStatus == true) {
print("12");
timeInHoursSplit = gettimeinvalue.split(' '); //18:35:00 PM
timeOutHoursSplit = getapitimeout.split(' ');
}
//if logged in , did timein and timeout at once.
else if(gettimeinworkinghours=="0" && getapitimeout!=""){
print("13");
print(getapitimein);
print(getapitimeout);
timeInHoursSplit = getapitimein.split(' ');
timeOutHoursSplit = getapitimeout.split(' ');
}
//if not time in and time out yet
else {
print("14");
print(getapitimeout);
timeInHoursSplit = defaultIn.split(' ');
timeOutHoursSplit = defaultOut.split(' ');
}
print("1");
print(timeInHoursSplit); //[18:35:00, PM]
timeInHours0 = timeInHoursSplit[1]; //18:35:00
print("2");
print(timeInHours0);
timeOutHours0 = timeOutHoursSplit[1];
timeInHours = timeInHours0.split(':'); //[18, 35, 00]
print(timeInHours);
timeOutHours = timeOutHours0.split(':');
inHour = timeInHours[0];
outHour = timeOutHours[0];
inMin = timeInHours[1];
outMin = timeOutHours[1];
inSec=timeInHours[2];
outSec=timeOutHours[2];
// here i am calculating the hours
if (int.parse(inHour) > int.parse(outHour)) {
totalWorkingHour = int.parse(inHour) - int.parse(outHour);
print(totalWorkingHours);
} else {
totalWorkingHour = int.parse(outHour) - int.parse(outHour);
print(totalWorkingHours);
}
// here i am calculating the min
if (inMin != outMin) {
if (int.parse(outMin) > int.parse(inMin)) {
totalWorkingMin = int.parse(outMin) - int.parse(inMin);
flagMin = true;
} else if (int.parse(inMin) > int.parse(outMin)) {
totalWorkingMin = int.parse(inMin) - int.parse(outMin);
flagMin = true;
}
} else if (inMin == outMin) {
totalWorkingMin = int.parse(outMin) - int.parse(inMin);
flagMin = true;
}
// here i am calculating the sec
if (inSec != outSec) {
if (int.parse(outSec) > int.parse(inSec)) {
totalWorkingSec = int.parse(outSec) - int.parse(inSec);
flagSec = true;
} else if (int.parse(inSec) > int.parse(outSec)) {
totalWorkingSec = int.parse(inSec) - int.parse(outSec);
flagSec = true;
}
} else if (inSec == outSec) {
totalWorkingSec = int.parse(outSec) - int.parse(inSec);
flagSec = true;
}
//// here i am getting the totalworkinghours by concatenating the hours, min and sec
if (flagMin == true && flagSec==true) {
print("1 output");
totalTime = totalWorkingHour.toString() +":" +totalWorkingMin.toString() +":"+totalWorkingSec.toString();
print(totalTime);
return totalTime;
}
//cond 2
else if (flagMin == false && flagSec==false){
print("2 output");
totalTime = totalWorkingHour.toString() +":" +inMin.toString() + ":" +inSec.toString();
return totalTime;
}
//cond 3
else if (flagMin == false && flagSec == true) {
print("3 output");
totalTime = totalWorkingHour.toString() +":" +inMin.toString() ;
return totalTime;
}
//cond 4
else if (flagMin == true && flagSec == false) {
print("4 output");
totalTime = totalWorkingHour.toString() +":" +totalWorkingMin.toString() +":" +inSec.toString();
return totalTime;
}
}
Kindly please help how I can do this.

How to verify a document from QLDB in Node.js?

I'm trying to verify a document from QLDB using nodejs. I have been following the Java verification example as much as I can, but I'm unable to calculate the same digest as stored on the ledger.
This is the code I have come up with. I query the proof and block hash from QLDB and then try to calculate digest in the same way as in Java example. But after concatinating the two hashes and calculating the new hash from the result I get the wrong output from crypto.createHash('sha256').update(c).digest("base64"). I have also tried using "base64" instead of "hex" with different, but also wrong result.
const rBlock = makeReader(res.Revision.IonText);
var block = [];
rBlock.next();
rBlock.stepIn();
rBlock.next();
while (rBlock.next() != null) {
if (rBlock.fieldName() == 'hash') {
block.push(Buffer.from(rBlock.byteValue()).toString('hex'));
}
}
console.log(block);
var proof = [];
const rProof = makeReader(res.Proof.IonText);
rProof.next();
rProof.stepIn();
while (rProof.next() != null) {
proof.push(Buffer.from(rProof.byteValue()).toString('hex'));
}
var ph = block[0];
var c;
for (var i = 0; i < proof.length; i++) {
console.log(proof[i])
for (var j = 0; j < ph.length; j++) {
if (parseInt(ph[j]) > parseInt(proof[i][j])){
c = ph + proof[i];
break;
}
if (parseInt(ph[j]) < parseInt(proof[i][j])){
c = proof[i] + ph;
break;
}
}
ph = crypto.createHash('sha256').update(c).digest("hex");
console.log(ph);
console.log();
}
I have figure it out. The problem was that I was converting the blobs to hex strings and hash them instead of the raw values. For anyone wanting to verify data in node, here is the bare solution:
ledgerInfo.getRevision(params).then(res => {
console.log(res);
const rBlock = makeReader(res.Revision.IonText);
var ph;
rBlock.next();
rBlock.stepIn();
rBlock.next();
while (rBlock.next() != null) {
if (rBlock.fieldName() == 'hash') {
ph = rBlock.byteValue()
}
}
var proof = [];
const rProof = makeReader(res.Proof.IonText);
rProof.next();
rProof.stepIn();
while (rProof.next() != null) {
proof.push(rProof.byteValue());
}
for (var i = 0; i < proof.length; i++) {
var c;
if (hashComparator(ph, proof[i]) < 0) {
c = concatTypedArrays(ph, proof[i]);
}
else {
c = concatTypedArrays(proof[i], ph);
}
var buff = crypto.createHash('sha256').update(c).digest("hex");
ph = Uint8Array.from(Buffer.from(buff, 'hex'));
}
console.log(Buffer.from(ph).toString('base64'));
}).catch(err => {
console.log(err, err.stack)
});
function concatTypedArrays(a, b) {
var c = new (a.constructor)(a.length + b.length);
c.set(a, 0);
c.set(b, a.length);
return c;
}
function hashComparator(h1, h2) {
for (var i = h1.length - 1; i >= 0; i--) {
var diff = (h1[i]<<24>>24) - (h2[i]<<24>>24);
if (diff != 0)
return diff;
}
return 0;
}

Node xlsx module get headers of the excel file

How to get the headers of the given Excel file in node xlsx (https://www.npmjs.com/package/xlsx) module?
Did the following in xlsx v0.16.9
const workbookHeaders = xlsx.readFile(filePath, { sheetRows: 1 });
const columnsArray = xlsx.utils.sheet_to_json(workbookHeaders.Sheets[sheetName], { header: 1 })[0];
As I could find, there's no exposed method to get headers of the Excel file from the module. So I copied few functions (With all respect to author. https://github.com/SheetJS/js-xlsx) from their source code and make that work with few changes.
function getHeaders(sheet){
var header=0, offset = 1;
var hdr=[];
var o = {};
if (sheet == null || sheet["!ref"] == null) return [];
var range = o.range !== undefined ? o.range : sheet["!ref"];
var r;
if (o.header === 1) header = 1;
else if (o.header === "A") header = 2;
else if (Array.isArray(o.header)) header = 3;
switch (typeof range) {
case 'string':
r = safe_decode_range(range);
break;
case 'number':
r = safe_decode_range(sheet["!ref"]);
r.s.r = range;
break;
default:
r = range;
}
if (header > 0) offset = 0;
var rr = XLSX.utils.encode_row(r.s.r);
var cols = new Array(r.e.c - r.s.c + 1);
for (var C = r.s.c; C <= r.e.c; ++C) {
cols[C] = XLSX.utils.encode_col(C);
var val = sheet[cols[C] + rr];
switch (header) {
case 1:
hdr.push(C);
break;
case 2:
hdr.push(cols[C]);
break;
case 3:
hdr.push(o.header[C - r.s.c]);
break;
default:
if (val === undefined) continue;
hdr.push(XLSX.utils.format_cell(val));
}
}
return hdr;
}
function safe_decode_range(range) {
var o = {s:{c:0,r:0},e:{c:0,r:0}};
var idx = 0, i = 0, cc = 0;
var len = range.length;
for(idx = 0; i < len; ++i) {
if((cc=range.charCodeAt(i)-64) < 1 || cc > 26) break;
idx = 26*idx + cc;
}
o.s.c = --idx;
for(idx = 0; i < len; ++i) {
if((cc=range.charCodeAt(i)-48) < 0 || cc > 9) break;
idx = 10*idx + cc;
}
o.s.r = --idx;
if(i === len || range.charCodeAt(++i) === 58) { o.e.c=o.s.c; o.e.r=o.s.r; return o; }
for(idx = 0; i != len; ++i) {
if((cc=range.charCodeAt(i)-64) < 1 || cc > 26) break;
idx = 26*idx + cc;
}
o.e.c = --idx;
for(idx = 0; i != len; ++i) {
if((cc=range.charCodeAt(i)-48) < 0 || cc > 9) break;
idx = 10*idx + cc;
}
o.e.r = --idx;
return o;
}
Call getHeaders function by passing the Work Sheet will return the headers array of the excel sheet.
Have a look here:
https://www.npmjs.com/package/xlsx if we go through the documentation. It says that we need to pass options By default, sheet_to_json scans the first row and uses the values as headers. With the header: 1 option, the function exports an array of arrays of values.
So the whole code goes like this:
const data = e.target.result;
const workbook = XLSX.read(data, { type: "array" });
console.log(workbook);
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
const options = { header: 1 };
const sheetData2 = XLSX.utils.sheet_to_json(worksheet, options);
const header = sheetData2.shift();
console.log(header); //you should get your header right here
Where e.target comes from your input.

Resources