node.js require() weird behavior - node.js

UPDATE - I added more information. The issue seems to be dependant on the order of the require statements. Unfortunately, fixing one breaks the other, please help!!!
I cannot figure out what is going on here. I have 5 files shown below, and am using index.js simply to demonstrate the issue. If HDate is required first then HDate.make fails within the HDateTime class. If HDateTime is required first, then HDateTime.make fails within the HDate class. Appears it is possibly a circular reference issue, but I have not been able to figure out how to correct the problem.
index.js - fails on DATETIME
var HDate = require('./HDate');
var HDateTime = require('./HDateTime');
var HTimeZone = require('./HTimeZone');
var utc = HTimeZone.UTC;
console.log('DATE: ' + HDate.make(2011, 1, 2));
console.log('MIDNIGHT: ' + HDate.make(2011, 1, 2).midnight(utc));
console.log('DATETIME: ' + HDateTime.make(2011, 1, 2, 3, 4, 5, utc, 0));
ERROR OUTPUT:
C:\Users\Shawn\nodehaystack>node index.js
DATE: 2011-01-02
MIDNIGHT: 2011-01-02T00:00:00Z UTC
C:\Users\Shawn\nodehaystack\HDateTime.js:95
return HDateTime.make(HDate.make(arg1, arg2, arg3), HTime.make(arg4, arg5,
^
TypeError: undefined is not a function
at Function.HDateTime.make (C:\Users\Shawn\nodehaystack\HDateTime.js:95:33)
at Object.<anonymous> (C:\Users\Shawn\nodehaystack\index.js:8:38)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
index.js - fails on MIDNIGHT
var HDateTime = require('./HDateTime');
var HDate = require('./HDate');
var HTimeZone = require('./HTimeZone');
var utc = HTimeZone.UTC;
console.log('DATE: ' + HDate.make(2011, 1, 2));
console.log('DATETIME: ' + HDateTime.make(2011, 1, 2, 3, 4, 5, utc, 0));
console.log('MIDNIGHT: ' + HDate.make(2011, 1, 2).midnight(utc));
ERROR OUTPUT:
C:\Users\Shawn\nodehaystack>node index.js
DATE: 2011-01-02
DATETIME: 2011-01-02T03:04:05Z UTC
C:\Users\Shawn\nodehaystack\HDate.js:46
HDate.prototype.midnight = function(tz) { return HDateTime.make(this, HTime.MI
^
TypeError: undefined is not a function
at HVal.HDate.midnight (C:\Users\Shawn\nodehaystack\HDate.js:46:60)
at Object.<anonymous> (C:\Users\Shawn\nodehaystack\index.js:8:51)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
HDate.js
var HVal = require('./HVal');
var HDateTime = require('./HDateTime');
var HTime = require('./HTime');
/** Private constructor */
function HDate(year, month, day) {
/** Four digit year such as 2011 */
this.year = year;
/** Month as 1-12 (Jan is 1, Dec is 12) */
this.month = month;
/** Day of month as 1-31 */
this.day = day;
};
HDate.prototype = Object.create(HVal.prototype);
/** int - Hash is based on year, month, day */
HDate.prototype.hashCode = function() { return (this.year << 16) ^ (this.month << 8) ^ this.day; };
/** String - Encode as "YYYY-MM-DD" */
HDate.prototype.toZinc = function() {
var s = this.year + "-";
if (this.month < 10) s += "0"; s += this.month + "-";
if (this.day < 10) s += "0"; s += this.day;
return s;
};
/** boolean - Equals is based on year, month, day */
HDate.prototype.equals = function(that) { return that instanceof HDate && this.year === that.year && this.month === that.month && this.day === that.day; };
/** int - Return sort order as negative, 0, or positive */
HDate.prototype.compareTo = function(that) {
if (this.year < that.year) return -1; else if (this.year > that.year) return 1;
if (this.month < that.month) return -1; else if (this.month > that.month) return 1;
if (this.day < that.day) return -1; else if (this.day > that.day) return 1;
return 0;
};
/** Convert this date into HDateTime for midnight in given timezone. */
HDate.prototype.midnight = function(tz) { return HDateTime.make(this, HTime.MIDNIGHT, tz); };
/** Return date in future given number of days */
HDate.prototype.plusDays = function(numDays) {
if (numDays == 0) return this;
if (numDays < 0) return this.minusDays(-numDays);
var year = this.year;
var month = this.month;
var day = this.day;
for (; numDays > 0; --numDays) {
day++;
if (day > HDate.daysInMonth(year, month)) {
day = 1;
month++;
if (month > 12) { month = 1; year++; }
}
}
return HDate.make(year, month, day);
};
/** Return date in past given number of days */
HDate.prototype.minusDays = function(numDays) {
if (numDays == 0) return this;
if (numDays < 0) return this.plusDays(-numDays);
var year = this.year;
var month = this.month;
var day = this.day;
for (; numDays > 0; --numDays) {
day--;
if (day <= 0) {
month--;
if (month < 1) { month = 12; year--; }
day = HDate.daysInMonth(year, month);
}
}
return HDate.make(year, month, day);
};
/** Return day of week: Sunday is 1, Saturday is 7 */
HDate.prototype.weekday = function() { return new Date(this.year, this.month-1, this.day).getDay() + 1; };
/** Export for use in testing */
module.exports = HDate;
/** Construct from basic fields, javascript Date instance, or String in format "YYYY-MM-DD" */
HDate.make = function(arg, month, day) {
if (arg instanceof Date) {
return new HDate(arg.getFullYear(), arg.getMonth() + 1, arg.getDate());
} else if (HVal.typeis(arg, 'string', String)) {
try {
var s = arg.split('-');
return new HDate(parseInt(s[0]), parseInt(s[1]), parseInt(s[2]));
} catch(err) {
throw err;
}
} else {
if (arg < 1900) throw new Error("Invalid year");
if (month < 1 || month > 12) throw new Error("Invalid month");
if (day < 1 || day > 31) throw new Error("Invalid day");
return new HDate(arg, month, day);
}
};
/** Get HDate for current time in default timezone */
HDate.today = function() { return HDateTime.now().date; };
/** Return if given year a leap year */
HDate.isLeapYear = function(year) {
if ((year & 3) != 0) return false;
return (year % 100 != 0) || (year % 400 == 0);
};
/** Return number of days in given year (xxxx) and month (1-12) */
var daysInMon = [ -1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
var daysInMonLeap = [ -1, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
HDate.daysInMonth = function(year, mon) { return HDate.isLeapYear(year) ? daysInMonLeap[mon] : daysInMon[mon]; };
HDateTime.js
var moment = require('moment-timezone');
var HVal = require('./HVal');
var HDate = require('./HDate');
var HTime = require('./HTime');
var HTimeZone = require('./HTimeZone');
// require('./io/HZincReader');
/** Private constructor */
function HDateTime(date, time, tz, tzOffset) {
/** HDate - Date component of the timestamp */
this.date = date;
/** HTime - Time component of the timestamp */
this.time = time;
/** int - Offset in seconds from UTC including DST offset */
this.tz = tz;
/** HTimeZone - Timezone as Olson database city name */
this.tzOffset = (typeof(tzOffset) == 'undefined' ? 0 : tzOffset);
/** long - millis since Epoch */
this.millis;
}
HDateTime.prototype = Object.create(HVal.prototype);
/** long - Get this date time as Java milliseconds since epoch */
HDateTime.prototype.millis = function() {
if (this.millis <= 0) {
var d = new Date(this.date.year, this.date.month-1, this.date.day, this.time.hour, this.time.min, this.time.sec, this.time.ms);
//TODO: implement UTC timezone
this.millis = d.getTime();
}
return this.millis;
};
/** int - Hash code is based on date, time, tzOffset, and tz */
HDateTime.prototype.hashCode = function() { return this.date.hashCode() ^ this.time.hashCode() ^ tzOffset ^ this.tz.hashCode(); };
/** String - Encode as "YYYY-MM-DD'T'hh:mm:ss.FFFz zzzz" */
HDateTime.prototype.toZinc = function() {
var s = this.date.toZinc() + "T" + this.time.toZinc();
if (this.tzOffset == 0) s += "Z";
else {
var offset = this.tzOffset;
if (offset < 0) { s += "-"; offset = -offset; }
else { s += "+"; }
var zh = offset / 3600;
var zm = (offset % 3600) / 60;
if (zh < 10) s += "0"; s += zh + ":";
if (zm < 10) s += "0"; s += zm;
}
s += " " + this.tz;
return s;
};
/** boolean - Equals is based on date, time, tzOffset, and tz */
HDateTime.prototype.equals = function(that) {
return that instanceof HDateTime && this.date === that.date
&& this.time === that.time && this.tzOffset === that.tzOffset && this.tz === that.tz;
};
/** int - Comparison based on millis. */
HDateTime.prototype.compareTo = function(that) {
var thisMillis = this.millis();
var thatMillis = that.millis();
if (thisMillis < thatMillis) return -1;
else if (thisMillis > thatMillis) return 1;
return 0;
};
/** Export for use in testing */
module.exports = HDateTime;
function utcDate(year, month, day, hour, min, sec, ms) {
var d = new Date();
d.setUTCFullYear(year);
d.setUTCMonth(month-1);
d.setUTCDate(day);
d.setUTCHours(hour);
d.setUTCMinutes(min);
d.setUTCSeconds(sec);
d.setUTCMilliseconds(ms);
return d;
}
/** Construct from various values */
HDateTime.make = function(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) {
if (arg7 instanceof HTimeZone) {
return HDateTime.make(HDate.make(arg1, arg2, arg3), HTime.make(arg4, arg5, arg6), arg7, arg8);
} else if (arg6 instanceof HTimeZone) {
return HDateTime.make(HDate.make(arg1, arg2, arg3), HTime.make(arg4, arg5, 0), arg6, arg7);
} else if (arg3 instanceof HTimeZone) {
// use Date to decode millis to fields
var d = utcDate(arg1.year, arg1.month, arg1.day, arg2.hour, arg2.min, arg2.sec, arg2.ms);
var tzOffset = arg4;
if (typeof(tzOffset) == 'undefined') {
// convert to designated timezone
d = moment(d).tz(arg3.js.name);
tzOffset = d.utcOffset() * 60;
}
var ts = new HDateTime(arg1, arg2, arg3, tzOffset);
ts.millis = d.valueOf() + (tzOffset * -1000);
return ts;
} else if (this.typeis(arg1, 'string', String)) {
// TODO: Implemet parsing
// var val = new HZincReader(arg1).readScalar();
// if (typeof(val) == HDateTime) return val;
// throw new Error("Parse Error: " + arg1);
} else {
var tz = arg2;
if (typeof(tz) == 'undefined') tz = HTimeZone.DEFAULT;
var d = new Date(arg1);
// convert to designated timezone
d = moment(d).tz(tz.js.name);
tzOffset = d.utcOffset() * 60;
var ts = new HDateTime(HDate.make(d), HTime.make(d), tz, tz.getOffset());
ts.millis = arg1;
}
};
/** HDateTime - Get HDateTime for given timezone */
HDateTime.now = function(tz) { return make(new Date().getTime(), tz); };
HTime.js
var HVal = require('./HVal');
// require('./io/HZincReader');
/** Private constructor */
function HTime(hour, min, sec, ms) {
/** int - Hour of day as 0-23 */
this.hour = hour;
/** int - Minute of hour as 0-59 */
this.min = min;
/** int - Second of minute as 0-59 */
this.sec = (typeof(sec) == 'undefined' ? 0 : sec);
/** int - Fractional seconds in milliseconds 0-999 */
this.ms = (typeof(ms) == 'undefined' ? 0 : ms);
};
HTime.prototype = Object.create(HVal.prototype);
/** int - Hash code is based on hour, min, sec, ms */
HTime.prototype.hashCode = function() { return (this.hour << 24) ^ (this.min << 20) ^ (this.sec << 16) ^ this.ms; };
/** boolean - Equals is based on hour, min, sec, ms */
HTime.prototype.equals = function(that) {
return that instanceof HTime && this.hour === that.hour &&
this.min === that.min && this.sec === that.sec && this.ms === that.ms;
};
/** int - Return sort order as negative, 0, or positive */
HTime.prototype.compareTo = function(that) {
if (this.hour < that.hour) return -1; else if (this.hour > that.hour) return 1;
if (this.min < that.min) return -1; else if (this.min > that.min) return 1;
if (this.sec < that.sec) return -1; else if (this.sec > that.sec) return 1;
if (this.ms < that.ms) return -1; else if (this.ms > that.ms) return 1;
return 0;
};
/** String - Encode as "hh:mm:ss.FFF" */
HTime.prototype.toZinc = function() {
var s = "";
if (this.hour < 10) s += "0"; s += this.hour + ":";
if (this.min < 10) s += "0"; s += this.min + ":";
if (this.sec < 10) s += "0"; s += this.sec;
if (this.ms != 0) {
s += ".";
if (this.ms < 10) s += "0";
if (this.ms < 100) s += "0";
s += this.ms;
}
return s;
};
/** Export for use in testing */
module.exports = HTime;
/** Singleton for midnight 00:00 */
HTime.MIDNIGHT = new HTime(0, 0, 0, 0);
/** Construct with all fields, with Javascript Date object, or Parse from string fomat "hh:mm:ss.FF" */
HTime.make = function(arg1, min, sec, ms) {
if (HVal.typeis(arg1, 'string', String)) {
// TODO: Implemet parsing
// var val = new HZincReader(arg1).readScalar();
// if (val instanceof HTime) return val;
// throw new Error("Parse Error: " + arg1);
} else if (arg1 instanceof Date) {
return new HTime(arg1.getHours(), arg1.getMinutes(), arg1.getSeconds(), arg1.getMilliseconds());
} else {
return new HTime(arg1, min, sec, ms);
}
};
HTimeZone.js
var moment = require('moment-timezone');
var HVal = require('./HVal');
/** Package private constructor */
function HTimeZone(name, js) {
/** Haystack timezone name */
this.name = name;
/** Javascript (moment) representation of this timezone. */
this.js = js;
};
/** String - Return Haystack timezone name */
HTimeZone.prototype.toString = function() { return this.name; };
module.exports = HTimeZone;
HTimeZone.make = function(arg1, checked) {
if (typeof(checked) == 'undefined') return HTimeZone.make(arg1, true);
if (HVal.typeis(arg1, 'string', String)) {
/**
* Construct with Haystack timezone name, raise exception or
* return null on error based on check flag.
*/
// lookup in cache
var tz = cache[arg1];
if (typeof(tz) != 'undefined') return tz;
// map haystack id to Javascript full id
var jsId = toJS[arg1];
if (typeof(jsId) == 'undefined') {
if (checked) throw new Error("Unknown tz: " + arg1);
return undefined;
}
// resolve full id to HTimeZone and cache
var js = moment.tz.zone(jsId)
tz = new HTimeZone(arg1, js);
cache[arg1] = tz;
return tz;
} else {
/**
* Construct from Javascript timezone. Throw exception or return
* null based on checked flag.
*/
var jsId = arg1.name;
if (jsId.startsWith("GMT")) fixGMT(jsId);
var name = fromJS[jsId];
if (typeof(name) != 'undefined') return HTimeZone.make(name);
if (checked) throw new Error("Invalid Java timezone: " + arg1.name);
return;
}
};
function fixGMT(jsId) {
// Javscript (moment) IDs can be in the form "GMT[+,-]h" as well as
// "GMT", and "GMT0". In that case, convert the ID to "Etc/GMT[+,-]h".
// V8 uses the format "GMT[+,-]hh00 (used for default timezone), this also
// needs converted.
if (jsId.indexOf("+")<0 && jsId.indexOf("-")<0) return "Etc/" + jsId; // must be "GMT" or "GMT0" which are fine
// get the prefix
var pre = jsId.substring(0, 4);
var num = parseInt(jsId.substring(4, 6));
// ensure we have a valid value
if ((pre.substring(3)=="+" && num<13) || (pre.substring(3)=="-" & num<15)) return "Etc/" + pre + num;
// nothing we could do, return what was passed
return jsId;
}
var cache = {};
var toJS = {};
var fromJS = {};
{
try {
// only time zones which start with these
// regions are considered valid timezones
var regions = {};
regions["Africa"] = "ok";
regions["America"] = "ok";
regions["Antarctica"] = "ok";
regions["Asia"] = "ok";
regions["Atlantic"] = "ok";
regions["Australia"] = "ok";
regions["Etc"] = "ok";
regions["Europe"] = "ok";
regions["Indian"] = "ok";
regions["Pacific"] = "ok";
// iterate Javascript timezone IDs available
var ids = moment.tz.names();
for (var i=0; i<ids.length; ++i) {
var js = ids[i];
// skip ids not formatted as Region/City
var slash = js.indexOf('/');
if (slash < 0) continue;
var region = js.substring(0, slash);
if (typeof(regions[region]) == 'undefined') continue;
// get city name as haystack id
slash = js.lastIndexOf('/');
var haystack = js.substring(slash+1);
// store mapping b/w Javascript <-> Haystack
toJS[haystack] = js;
fromJS[js] = haystack;
}
} catch (err) {
console.log(err.stack);
}
var utc;
try {
utc = HTimeZone.make(moment.tz.zone("Etc/UTC"));
} catch (err) {
console.log(err.stack);
}
var def;
try {
// check if configured with system property
var defName = process.env["haystack.tz"];
if (defName != null) {
def = make(defName, false);
if (typeof(def) == 'undefined') console.log("WARN: invalid haystack.tz system property: " + defName);
}
// if we still don't have a default, try to use Javascript's
if (typeof(def) == 'undefined') {
var date = new Date().toString();
var gmtStart = date.indexOf("GMT");
var gmtEnd = date.indexOf(" ", gmtStart);
def = fromJS[fixGMT(date.substring(gmtStart, gmtEnd))];
}
} catch (err) {
console.log(err.stack);
def = utc;
}
/** UTC timezone */
HTimeZone.UTC = utc;
/** Default timezone for VM */
HTimeZone.DEFAULT = def;
}

The problem is how you export functions.
you say
module.exports = HDate which is fine
but then you do
module.exports.make = function(){} which is fine too.
But both together won't work reliable as you just experienced.
To fix that export the class either as something like module.exports.hdate OR add the make function to HDate:
Hdate.make = myFunction() {}
This goes obviously for all methods you export like this.
Let me know if that solves your problem :)

I have found that the best solution to this issue is to move all the require statements that could cause a cyclical dependency to ensure they are after the constructor for my class and after the module.exports statement. For example...
var HVal = require('./HVal');
/**
* HDate models a date (day in year) tag value.
* #see {#link http://project-haystack.org/doc/TagModel#tagKinds|Project Haystack}
*
* #constructor
* #private
* #extends {HVal}
* #param {int} year - Four digit year such as 2011
* #param {int} month - Month as 1-12 (Jan is 1, Dec is 12)
* #param {int} day - Day of month as 1-31
*/
function HDate(year, month, day) {
this.year = year;
this.month = month;
this.day = day;
}
HDate.prototype = Object.create(HVal.prototype);
module.exports = HDate;
var HDateTime = require('./HDateTime'),
HTime = require('./HTime');
Doing this method consistently in all of my classes prevents any cyclical issues.

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

BIP32 derivePath different privatekey in nodejs and dart(flutter) (same mnemonic)

Hello i'm have some problem with BIP32
i use BIP32 library in nodejs and dart(flutter)
in dart(flutter) BIP32 derivePath show different privatekey but not of all mnemonic is just incorrect some mnemonic
in 1000 mnemonic different privatekey 1-2 mnemonic
below is dart derivePath,,
what is inccorect in this code:
Help me pls.
BIP32 derivePath(String path) {
final regex = new RegExp(r"^(m\/)?(\d+'?\/)*\d+'?$");
if (!regex.hasMatch(path)) throw new ArgumentError("Expected BIP32 Path");
List<String> splitPath = path.split("/");
if (splitPath[0] == "m") {
if (parentFingerprint != 0) throw new ArgumentError("Expected master, got child");
splitPath = splitPath.sublist(1);
print("splitPath: "+ splitPath);
}
print("splitPath: "+ splitPath);
return splitPath.fold(this, (BIP32 prevHd,String indexStr) {
int index;
if (indexStr.substring(indexStr.length - 1) == "'") {
index = int.parse(indexStr.substring(0, indexStr.length - 1));
return prevHd.deriveHardened(index);
} else {
index = int.parse(indexStr);
return prevHd.derive(index);
}
});
}
BIP32 derive(int index) {
if (index > UINT32_MAX || index < 0) throw new ArgumentError("Expected UInt32");
final isHardened = index >= HIGHEST_BIT;
Uint8List data = new Uint8List(37);
if (isHardened) {
if (isNeutered()) {
throw new ArgumentError("Missing private key for hardened child key");
}
data[0] = 0x00;
data.setRange(1, 33, privateKey);
data.buffer.asByteData().setUint32(33, index);
} else {
data.setRange(0, 33, publicKey);
data.buffer.asByteData().setUint32(33, index);
}
final I = hmacSHA512(chainCode, data);
final IL = I.sublist(0, 32);
final IR = I.sublist(32);
if (!ecc.isPrivate(IL)) {
return derive(index + 1);
}
BIP32 hd;
if (!isNeutered()) {
final ki = ecc.privateAdd(privateKey, IL);
if (ki == null) return derive(index + 1);
hd = BIP32.fromPrivateKey(ki, IR, network);
} else {
final ki = ecc.pointAddScalar(publicKey, IL, true);
if (ki == null) return derive(index + 1);
hd = BIP32.fromPublicKey(ki, IR, network);
}
hd.depth = depth + 1;
hd.index = index;
hd.parentFingerprint = fingerprint.buffer.asByteData().getUint32(0);
return hd;
}
BIP32 deriveHardened(int index) {
if (index > UINT31_MAX || index < 0) throw new ArgumentError("Expected UInt31");
return this.derive(index + HIGHEST_BIT);
}
OK can solved this problem problem occur in the ecuve function bytes is less than 32 bytes just padding 0 in the left equal 32 bytes just solved it !

Get all date based on given requirement

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

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

Function failing to return a value

So I'm making a simple steganography tool (encrypting messages within images) and exposing it as a web service via Node.js. I am very new to Javascript and Node.js in particular. The app first converts a text string into a binary string by changing each character into an 8-bit ASCII encoding, resulting in one large binary string. I then encrypt the message within the pixels. Even values of pixels represent 0s from the binary, and odd values represent 1s. The end of the string is marked as 3 pixels of value 100 in a row (this is temporary, until I figure out a better way to mark the end). I'm using a node.js library called 'pngjs' that gives me pixel-level access to png images.
So I have a problem with the decodeMessage function. It builds up the string message, and is then meant to return it, however the return call at the end results in undefined.
How can I fix it?
Thanks in advance for the help!
function encodeMessage(image, mes) {
var message = mes;
var fs = require('fs'),
PNG = require('pngjs').PNG;
fs.createReadStream(image)
.pipe(new PNG({
filterType: 4
}))
.on('parsed', function() {
for (var y = 0; y < this.height; y++) {
for (var x = 0; x < this.width; x++) {
var idx = (this.width * y + x);// << 2;
//console.log(idx);
if (idx < message.length) {
var item = message.charAt(idx);
/* if the character in the encoded string is 0 */
if (item == 0) {
/* if the pixel is odd, we want it to be even */
if (this.data[idx] % 2 == 1) {
/* if the pixel is 0, add 1 to it */
if (this.data[idx] == 0) {
this.data[idx] = this.data[idx] + 1;
} else {
/* else substract 1 */
this.data[idx] = this.data[idx] - 1;
}
}
} else {
/* if the character in the encoded string is 1 */
if (this.data[idx] % 2 == 0) {
if (this.data[idx] == 0) {
this.data[idx] = this.data[idx] + 1;
} else {
this.data[idx] = this.data[idx] - 1;
}
}
}
//console.log(this.data[idx]);
} else if (idx === message.length) {
/* do something to the first pixel following the end of the string */
this.data[idx] = 100;
this.data[idx+1] = 100;
this.data[idx+2] = 100;
//console.log(this.data[idx]);
} else {
/* do something to the remaining pixels */
}
}
}
this.pack().pipe(fs.createWriteStream('encoded_' + image));
});
}
function decodeMessage(image) {
var message = "";
var fs = require('fs'),
PNG = require('pngjs').PNG;
fs.createReadStream(image)
.pipe(new PNG({
filterType: 4
}))
.on('parsed', function() {
dance:
for (var y = 0; y < this.height; y++) {
for (var x = 0; x < this.width; x++) {
var idx = (this.width * y + x);// << 2;
if (this.data[idx] == 100 && this.data[idx+1] == 100 && this.data[idx+2] == 100) {
break dance;
} else {
if (this.data[idx] % 2 == 0) {
message += "0";
} else {
message += "1";
}
}
}
}
/* the message outputs correctly over here */
console.log(message);
//return message;
});
/* but the return of the variable here doesn't work */
return message;
}
exports.encodeMessage = encodeMessage;
exports.decodeMessage = decodeMessage;
The parsed event is fired asynchronously, so you cannot return a value from decodeMessage.
function decodeMessage(image, cb) {
// Code
.on('parsed', function() {
// Code
console.log(message);
cb(message);
});
}
Then you must pass a callback to your decodeMessage function.
decodeMessage(image, function(decoded){
// Here is the decoded data.
});
The same is true for your encodeMessage function. The function will return before encoding has finished. If you want to know when it is done, you need to pass a callback the same way.

Resources