Modifying variables from another file - node.js

i've got this in a file called voting_Request.js:
else
{
count1 = 0;
count2 = 0;
boolCheck = true;
module.exports.count1 = count1;
module.exports.count2 = count2;
}
and i've got this as well in a file called vote.js:
var request = require('./voting_Request.js');
async run(message,args){
var c1 = request.count1;
var c2 = request.count2;
if(!request.boolCheck){
message.reply('No ongoing votings please try again when a voting is available');
}
else{
if(request.voted.indexOf(message.author.tag) > -1){
message.reply("You have already voted!");
}
else{
request.noVote = false;
switch (args) {
case '1':
c1++;
message.reply('Thanks for voting!');
request.voted.push(message.author.tag);
break;
case '2':
c2++;
message.reply('Thanks for voting!');
request.voted.push(message.author.tag);
break;
default:
message.reply(args + ' is not an available option');
}
module.exports.c1 = c1;
module.exports.c2 = c2;
}
}
}
and basicallyinstead of taking the VALUE of count1 and count2 from the request file and only copying it into new variables in vote.js, i want to modify them from vote.js but the value in count1 and count2 will change depending on vote.js.
Thanks for the help!

Related

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;
}

Ticket channel name with numbers

I have a support ticket system but I would like my channel to be named as: USERNAME-001.
Even if the old one is deleted, it's still USERNAME-002.
And at 300 it's 001.
I don't know if I was understood.
I would like to be a bit like the public discord bot: Tickety: http://prntscr.com/mwiqp5
Because right now it's like: USERNAME-USERNAMEDISCRIMINATOR : http://prntscr.com/mwit8q
Ask me if you want more details on a part of the code or the request...
My code that creates the current channel:
message.guild.createChannel(message.author.username + " - " + message.author.discriminator, "text").then((channel) => {
Sincerely.
const counter = 0; // This has to defined in previous code. If I were you, I would use a database for this.
As I wrote in the comment, I would use a database for this where you countup with every ticket which is created on a Discord server.
Then you can use the following code:
var reached300 = false;
if (reached300 === true && counter !== 0) {
counter -= 1;
} else {
counter += 1;
}
if (counter === 300) {
reached300 = true;
} else if (counter === 0) {
reached300 = false;
}
var counterName;
if (counter <= 10) {
counterName = `#000${counter}`
} else if (counter <= 100) {
counterName = `#00${counter}`
} else if (counter <= 1000) {
counterName = `#0${counter}`
} else {
counterName = `#${counter}`
}
message.guild.createChannel(`ticket-${counterName}`, "text").then((channel) => {
// CODE HERE
});

Using Epplus to import data from an Excel file to SQL Server database table

I've tried implementing thishttps://www.paragon-inc.com/resources/blogs-posts/easy_excel_interaction_pt6 on an ASP.NET MVC 5 Application.
//SEE CODE BELOW
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
var regPIN = DB.AspNetUsers.Where(i => i.Id == user.Id).Select(i => i.registrationPIN).FirstOrDefault();
if (file != null && file.ContentLength > 0)
{
var extension = Path.GetExtension(file.FileName);
var excelFile = Path.Combine(Server.MapPath("~/App_Data/BulkImports"),regPIN + extension);
if (System.IO.File.Exists(excelFile))
{
System.IO.File.Delete(excelFile);
}
else if (file.ContentType == "application/vnd.ms-excel" || file.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
file.SaveAs(excelFile);//WORKS FINE
//BEGINING OF IMPORT
FileInfo eFile = new FileInfo(excelFile);
using (var excelPackage = new ExcelPackage(eFile))
{
if (!eFile.Name.EndsWith("xlsx"))//Return ModelState.AddModelError()
{ ModelState.AddModelError("", "Incompartible Excel Document. Please use MSExcel 2007 and Above!"); }
else
{
var worksheet = excelPackage.Workbook.Worksheets[1];
if (worksheet == null) { ModelState.AddModelError("", "Wrong Excel Format!"); }// return ImportResults.WrongFormat;
else
{
var lastRow = worksheet.Dimension.End.Row;
while (lastRow >= 1)
{
var range = worksheet.Cells[lastRow, 1, lastRow, 3];
if (range.Any(c => c.Value != null))
{ break; }
lastRow--;
}
using (var db = new BlackBox_FinaleEntities())// var db = new BlackBox_FinaleEntities())
{
for (var row = 2; row <= lastRow; row++)
{
var newPerson = new personalDetails
{
identificationType = worksheet.Cells[row, 1].Value.ToString(),
idNumber = worksheet.Cells[row, 2].Value.ToString(),
idSerial = worksheet.Cells[row, 3].Value.ToString(),
fullName = worksheet.Cells[row, 4].Value.ToString(),
dob = DateTime.Parse(worksheet.Cells[row, 5].Value.ToString()),
gender = worksheet.Cells[row, 6].Value.ToString()
};
DB.personalDetails.Add(newPerson);
try { db.SaveChanges(); }
catch (Exception) { }
}
}
}
}
}//END OF IMPORT
ViewBag.Message = "Your file was successfully uploaded.";
return RedirectToAction("Index");
}
ViewBag.Message = "Error: Your file was not uploaded. Ensure you upload an excel workbook file.";
return View();
}
else
{
ViewBag.Message = "Error: Your file was not uploaded. Ensure you upload an excel workbook file.";
return View();
}
}
See Picture Error
Any help would be greatly appreciated mates.
you can do like this:
public bool readXLS(string FilePath)
{
FileInfo existingFile = new FileInfo(FilePath);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
//get the first worksheet in the workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int colCount = worksheet.Dimension.End.Column; //get Column Count
int rowCount = worksheet.Dimension.End.Row; //get row count
string queryString = "INSERT INTO tableName VALUES"; //Here I am using "blind insert". You can specify the column names Blient inset is strongly not recommanded
string eachVal = "";
bool status;
for (int row = 1; row <= rowCount; row++)
{
queryString += "(";
for (int col = 1; col <= colCount; col++)
{
eachVal = worksheet.Cells[row, col].Value.ToString().Trim();
queryString += "'" + eachVal + "',";
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
if (row % 1000 == 0) //On every 1000 query will execute, as maximum of 1000 will be executed at a time.
{
queryString += ")";
status = this.runQuery(queryString); //executing query
if (status == false)
return status;
queryString = "INSERT INTO tableName VALUES";
}
else
{
queryString += "),";
}
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
status = this.runQuery(queryString); //executing query
return status;
}
}
Details: http://sforsuresh.in/read-data-excel-sheet-insert-database-table-c/

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.

Why is parallel.Invoke not working in this case

I have an array of files like this..
string[] unZippedFiles;
the idea is that I want to parse these files in paralle. As they are parsed a record gets placed on a concurrentbag. As record is getting placed I want to kick of the update function.
Here is what I am doing in my Main():
foreach(var file in unZippedFiles)
{ Parallel.Invoke
(
() => ImportFiles(file),
() => UpdateTest()
);
}
this is what the code of Update loooks like.
static void UpdateTest( )
{
Console.WriteLine("Updating/Inserting merchant information.");
while (!merchCollection.IsEmpty || producingRecords )
{
merchant x;
if (merchCollection.TryTake(out x))
{
UPDATE_MERCHANT(x.m_id, x.mInfo, x.month, x.year);
}
}
}
This is what the import code looks like. It's pretty much a giant string parser.
System.IO.StreamReader SR = new System.IO.StreamReader(fileName);
long COUNTER = 0;
StringBuilder contents = new StringBuilder( );
string M_ID = "";
string BOF_DELIMITER = "%%MS_SKEY_0000_000_PDF:";
string EOF_DELIMITER = "%%EOF";
try
{
record_count = 0;
producingRecords = true;
for (COUNTER = 0; COUNTER <= SR.BaseStream.Length - 1; COUNTER++)
{
if (SR.EndOfStream)
{
break;
}
contents.AppendLine(Strings.Trim(SR.ReadLine()));
contents.AppendLine(System.Environment.NewLine);
//contents += Strings.Trim(SR.ReadLine());
//contents += Strings.Chr(10);
if (contents.ToString().IndexOf((EOF_DELIMITER)) > -1)
{
if (contents.ToString().StartsWith(BOF_DELIMITER) & contents.ToString().IndexOf(EOF_DELIMITER) > -1)
{
string data = contents.ToString();
M_ID = data.Substring(data.IndexOf("_M") + 2, data.Substring(data.IndexOf("_M") + 2).IndexOf("_"));
Console.WriteLine("Merchant: " + M_ID);
merchant newmerch;
newmerch.m_id = M_ID;
newmerch.mInfo = data.Substring(0, (data.IndexOf(EOF_DELIMITER) + 5));
newmerch.month = DateTime.Now.AddMonths(-1).Month;
newmerch.year = DateTime.Now.AddMonths(-1).Year;
//Update(newmerch);
merchCollection.Add(newmerch);
}
contents.Clear();
//GC.Collect();
}
}
SR.Close();
// UpdateTest();
}
catch (Exception ex)
{
producingRecords = false;
}
finally
{
producingRecords = false;
}
}
the problem i am having is that the Update runs once and then the importfile function just takes over and does not yield to the update function. Any ideas on what am I doing wrong would be of great help.
Here's my stab at fixing your thread synchronisation. Note that I haven't changed any of the code from the functional standpoint (with the exception of taking out the catch - it's generally a bad idea; exceptions need to be propagated).
Forgive if something doesn't compile - I'm writing this based on incomplete snippets.
Main
foreach(var file in unZippedFiles)
{
using (var merchCollection = new BlockingCollection<merchant>())
{
Parallel.Invoke
(
() => ImportFiles(file, merchCollection),
() => UpdateTest(merchCollection)
);
}
}
Update
private void UpdateTest(BlockingCollection<merchant> merchCollection)
{
Console.WriteLine("Updating/Inserting merchant information.");
foreach (merchant x in merchCollection.GetConsumingEnumerable())
{
UPDATE_MERCHANT(x.m_id, x.mInfo, x.month, x.year);
}
}
Import
Don't forget to pass in merchCollection as a parameter - it should not be static.
System.IO.StreamReader SR = new System.IO.StreamReader(fileName);
long COUNTER = 0;
StringBuilder contents = new StringBuilder( );
string M_ID = "";
string BOF_DELIMITER = "%%MS_SKEY_0000_000_PDF:";
string EOF_DELIMITER = "%%EOF";
try
{
record_count = 0;
for (COUNTER = 0; COUNTER <= SR.BaseStream.Length - 1; COUNTER++)
{
if (SR.EndOfStream)
{
break;
}
contents.AppendLine(Strings.Trim(SR.ReadLine()));
contents.AppendLine(System.Environment.NewLine);
//contents += Strings.Trim(SR.ReadLine());
//contents += Strings.Chr(10);
if (contents.ToString().IndexOf((EOF_DELIMITER)) > -1)
{
if (contents.ToString().StartsWith(BOF_DELIMITER) & contents.ToString().IndexOf(EOF_DELIMITER) > -1)
{
string data = contents.ToString();
M_ID = data.Substring(data.IndexOf("_M") + 2, data.Substring(data.IndexOf("_M") + 2).IndexOf("_"));
Console.WriteLine("Merchant: " + M_ID);
merchant newmerch;
newmerch.m_id = M_ID;
newmerch.mInfo = data.Substring(0, (data.IndexOf(EOF_DELIMITER) + 5));
newmerch.month = DateTime.Now.AddMonths(-1).Month;
newmerch.year = DateTime.Now.AddMonths(-1).Year;
//Update(newmerch);
merchCollection.Add(newmerch);
}
contents.Clear();
//GC.Collect();
}
}
SR.Close();
// UpdateTest();
}
finally
{
merchCollection.CompleteAdding();
}
}

Resources