language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function expectsError(fn, settings, exact) {
if (typeof fn !== 'function') {
exact = settings;
settings = fn;
fn = undefined;
}
function innerFn(error) {
if (arguments.length !== 1) {
// Do not use `assert.strictEqual()` to prevent `util.inspect` from
// always being called.
assert.fail('Expected one argument, got ' + util.inspect(arguments));
}
var descriptor = Object.getOwnPropertyDescriptor(error, 'message');
// The error message should be non-enumerable
assert.strictEqual(descriptor.enumerable, false);
var innerSettings = settings;
if ('type' in settings) {
var type = settings.type;
if (type !== Error && !Error.isPrototypeOf(type)) {
throw new TypeError('`settings.type` must inherit from `Error`');
}
var _constructor = error.constructor;
if (_constructor.name === 'NodeError' && type.name !== 'NodeError') {
_constructor = Object.getPrototypeOf(error.constructor);
}
// Add the `type` to the error to properly compare and visualize it.
if (!('type' in error)) error.type = _constructor;
}
if ('message' in settings && typeof settings.message === 'object' && settings.message.test(error.message)) {
// Make a copy so we are able to modify the settings.
innerSettings = Object.create(settings, Object.getOwnPropertyDescriptors(settings));
// Visualize the message as identical in case of other errors.
innerSettings.message = error.message;
}
// Check all error properties.
var keys = objectKeys(settings);
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = keys[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var key = _step2.value;
if (!require('deep-strict-equal')(error[key], innerSettings[key])) {
// Create placeholder objects to create a nice output.
var a = new Comparison(error, keys);
var b = new Comparison(innerSettings, keys);
var tmpLimit = Error.stackTraceLimit;
Error.stackTraceLimit = 0;
var err = new assert.AssertionError({
actual: a,
expected: b,
operator: 'strictEqual',
stackStartFn: assert.throws
});
Error.stackTraceLimit = tmpLimit;
throw new assert.AssertionError({
actual: error,
expected: settings,
operator: 'common.expectsError',
message: err.message
});
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
return true;
}
if (fn) {
assert.throws(fn, innerFn);
return;
}
return mustCall(innerFn, exact);
} | function expectsError(fn, settings, exact) {
if (typeof fn !== 'function') {
exact = settings;
settings = fn;
fn = undefined;
}
function innerFn(error) {
if (arguments.length !== 1) {
// Do not use `assert.strictEqual()` to prevent `util.inspect` from
// always being called.
assert.fail('Expected one argument, got ' + util.inspect(arguments));
}
var descriptor = Object.getOwnPropertyDescriptor(error, 'message');
// The error message should be non-enumerable
assert.strictEqual(descriptor.enumerable, false);
var innerSettings = settings;
if ('type' in settings) {
var type = settings.type;
if (type !== Error && !Error.isPrototypeOf(type)) {
throw new TypeError('`settings.type` must inherit from `Error`');
}
var _constructor = error.constructor;
if (_constructor.name === 'NodeError' && type.name !== 'NodeError') {
_constructor = Object.getPrototypeOf(error.constructor);
}
// Add the `type` to the error to properly compare and visualize it.
if (!('type' in error)) error.type = _constructor;
}
if ('message' in settings && typeof settings.message === 'object' && settings.message.test(error.message)) {
// Make a copy so we are able to modify the settings.
innerSettings = Object.create(settings, Object.getOwnPropertyDescriptors(settings));
// Visualize the message as identical in case of other errors.
innerSettings.message = error.message;
}
// Check all error properties.
var keys = objectKeys(settings);
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = keys[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var key = _step2.value;
if (!require('deep-strict-equal')(error[key], innerSettings[key])) {
// Create placeholder objects to create a nice output.
var a = new Comparison(error, keys);
var b = new Comparison(innerSettings, keys);
var tmpLimit = Error.stackTraceLimit;
Error.stackTraceLimit = 0;
var err = new assert.AssertionError({
actual: a,
expected: b,
operator: 'strictEqual',
stackStartFn: assert.throws
});
Error.stackTraceLimit = tmpLimit;
throw new assert.AssertionError({
actual: error,
expected: settings,
operator: 'common.expectsError',
message: err.message
});
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
return true;
}
if (fn) {
assert.throws(fn, innerFn);
return;
}
return mustCall(innerFn, exact);
} |
JavaScript | get opensslCli() {
if (opensslCli !== null) return opensslCli;
if (process.config.variables.node_shared_openssl) {
// use external command
opensslCli = 'openssl';
} else {
// use command built from sources included in Node.js repository
opensslCli = path.join(path.dirname(process.execPath), 'openssl-cli');
}
if (exports.isWindows) opensslCli += '.exe';
var opensslCmd = spawnSync(opensslCli, ['version']);
if (opensslCmd.status !== 0 || opensslCmd.error !== undefined) {
// openssl command cannot be executed
opensslCli = false;
}
return opensslCli;
} | get opensslCli() {
if (opensslCli !== null) return opensslCli;
if (process.config.variables.node_shared_openssl) {
// use external command
opensslCli = 'openssl';
} else {
// use command built from sources included in Node.js repository
opensslCli = path.join(path.dirname(process.execPath), 'openssl-cli');
}
if (exports.isWindows) opensslCli += '.exe';
var opensslCmd = spawnSync(opensslCli, ['version']);
if (opensslCmd.status !== 0 || opensslCmd.error !== undefined) {
// openssl command cannot be executed
opensslCli = false;
}
return opensslCli;
} |
JavaScript | async updateDB(tableName, obj) {
if (tableName !== 'Product') return;
let productInDB = null;
productInDB = await this.find(tableName, {productName: obj.productName}).catch(err => {
console.log('error when finding product in DB' + err);
});
if (!productInDB) await this.addNew(tableName, obj).catch(err => {
console.log('error when creating new product ' + err);
});
else await this.update(tableName, {productName: obj.productName}, obj).catch(err => {
console.log('error when updating product ' + err);
});
console.log('success ' + obj.productName);
} | async updateDB(tableName, obj) {
if (tableName !== 'Product') return;
let productInDB = null;
productInDB = await this.find(tableName, {productName: obj.productName}).catch(err => {
console.log('error when finding product in DB' + err);
});
if (!productInDB) await this.addNew(tableName, obj).catch(err => {
console.log('error when creating new product ' + err);
});
else await this.update(tableName, {productName: obj.productName}, obj).catch(err => {
console.log('error when updating product ' + err);
});
console.log('success ' + obj.productName);
} |
JavaScript | function validateDayEntry(){
if(_day < 1 || _day >31){
return false;
} else {
return true;
}
} | function validateDayEntry(){
if(_day < 1 || _day >31){
return false;
} else {
return true;
}
} |
JavaScript | function validateMonthEntry(){
if(_month < 1 || _month > 12){
return false;
}else {
return true;
}
} | function validateMonthEntry(){
if(_month < 1 || _month > 12){
return false;
}else {
return true;
}
} |
JavaScript | _startSpan (name, fields) {
const references = getReferences(fields.references)
const parent = getParent(references)
const tags = {
'service.name': this._service
}
if (this._env) {
tags.env = this._env
}
const span = new Span(this, this._recorder, this._sampler, this._prioritySampler, {
operationName: fields.operationName || name,
parent: parent && parent.referencedContext(),
tags: Object.assign(tags, this._tags, fields.tags),
startTime: fields.startTime
})
if (parent && parent.type() === opentracing.REFERENCE_CHILD_OF) {
parent.referencedContext().children.push(span)
}
return span
} | _startSpan (name, fields) {
const references = getReferences(fields.references)
const parent = getParent(references)
const tags = {
'service.name': this._service
}
if (this._env) {
tags.env = this._env
}
const span = new Span(this, this._recorder, this._sampler, this._prioritySampler, {
operationName: fields.operationName || name,
parent: parent && parent.referencedContext(),
tags: Object.assign(tags, this._tags, fields.tags),
startTime: fields.startTime
})
if (parent && parent.type() === opentracing.REFERENCE_CHILD_OF) {
parent.referencedContext().children.push(span)
}
return span
} |
JavaScript | function storeToken(token) {
console.log('token from google', token);
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFileSync(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
} | function storeToken(token) {
console.log('token from google', token);
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFileSync(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
} |
JavaScript | function randomFact() {
const facts =
['Sometimes I get my age wrong.', 'I\'m learning Chinese calligraphy.',
'I could speak 5 languages/dialects (technically).', 'I\'m a huge sports fan'];
// Pick a random greeting.
const displayFact = facts[Math.floor(Math.random() * facts.length)];
// Add it to the page.
const factContainer = document.getElementById('fact-container');
factContainer.innerText = displayFact;
} | function randomFact() {
const facts =
['Sometimes I get my age wrong.', 'I\'m learning Chinese calligraphy.',
'I could speak 5 languages/dialects (technically).', 'I\'m a huge sports fan'];
// Pick a random greeting.
const displayFact = facts[Math.floor(Math.random() * facts.length)];
// Add it to the page.
const factContainer = document.getElementById('fact-container');
factContainer.innerText = displayFact;
} |
JavaScript | function myFunction() {
var x = document.getElementById("mynav");
if (x.className == "nav") {
x.className += " responsive";
} else {
x.className = "nav";
}
} | function myFunction() {
var x = document.getElementById("mynav");
if (x.className == "nav") {
x.className += " responsive";
} else {
x.className = "nav";
}
} |
JavaScript | function questionThree(){
var ready = prompt("Alright the next question is a yes/no question. Please answer with Yes or No. Are you ready?" ).toUpperCase();
console.log('Ready', ready);
if (ready === 'YES' || ready ==='Y' ){
alert ('Alright lets go .');
score++;
} else{
alert('I think you can do it .' );
}
} | function questionThree(){
var ready = prompt("Alright the next question is a yes/no question. Please answer with Yes or No. Are you ready?" ).toUpperCase();
console.log('Ready', ready);
if (ready === 'YES' || ready ==='Y' ){
alert ('Alright lets go .');
score++;
} else{
alert('I think you can do it .' );
}
} |
JavaScript | function questionSix(){
for(var i = 0; i<3; i++){
var numDog = parseInt(prompt ('how many dogs do I have?'));
if (numDog === 2){
alert('You are correct');
score++;
break;
} else if (numDog < 2) {
alert('too low');
} else if (numDog > 2) {
alert('too high');
} else {
alert('a number plase');
}
}
console.log('number of dogs', numDog);
} | function questionSix(){
for(var i = 0; i<3; i++){
var numDog = parseInt(prompt ('how many dogs do I have?'));
if (numDog === 2){
alert('You are correct');
score++;
break;
} else if (numDog < 2) {
alert('too low');
} else if (numDog > 2) {
alert('too high');
} else {
alert('a number plase');
}
}
console.log('number of dogs', numDog);
} |
JavaScript | function questionNine(){
for(var i = 0;i < 3; i++){
var typeCar= prompt('What type of car do I drive?').toUpperCase();
if(typeCar === 'YELLOW CAR'){
alert('You are correct')
score++;
break;
}else{
alert('nope');
}
}
console.log('Make of car', typeCar);
} | function questionNine(){
for(var i = 0;i < 3; i++){
var typeCar= prompt('What type of car do I drive?').toUpperCase();
if(typeCar === 'YELLOW CAR'){
alert('You are correct')
score++;
break;
}else{
alert('nope');
}
}
console.log('Make of car', typeCar);
} |
JavaScript | function mpn_new(l) {
var n = new Array(l);
mpn_zero(n, l);
return n;
} | function mpn_new(l) {
var n = new Array(l);
mpn_zero(n, l);
return n;
} |
JavaScript | function mpn_zero_p(n, l) {
for (var i = 0; i < l; ++i) {
if (n[i] != 0) {
return false;
}
}
return true;
} | function mpn_zero_p(n, l) {
for (var i = 0; i < l; ++i) {
if (n[i] != 0) {
return false;
}
}
return true;
} |
JavaScript | function mpn_one_p(n, l) {
if (l <= 0 || n[0] != 1) {
return false;
}
for (var i = 1; i < l; ++i) {
if (n[i] != 0) {
return false;
}
}
return true;
} | function mpn_one_p(n, l) {
if (l <= 0 || n[0] != 1) {
return false;
}
for (var i = 1; i < l; ++i) {
if (n[i] != 0) {
return false;
}
}
return true;
} |
JavaScript | function mpn_cmp(n1, n2, l) {
while (l > 0) {
var c = n1[--l] - n2[l];
if (c != 0) {
return c;
}
}
return 0;
} | function mpn_cmp(n1, n2, l) {
while (l > 0) {
var c = n1[--l] - n2[l];
if (c != 0) {
return c;
}
}
return 0;
} |
JavaScript | function mpn_zero(r, l) {
for (var i = 0; i < l; ++i) {
r[i] = 0;
}
} | function mpn_zero(r, l) {
for (var i = 0; i < l; ++i) {
r[i] = 0;
}
} |
JavaScript | function mpn_copyi(r, s, l) {
for (var i = 0; i < l; ++i) {
r[i] = s[i];
}
} | function mpn_copyi(r, s, l) {
for (var i = 0; i < l; ++i) {
r[i] = s[i];
}
} |
JavaScript | function mpn_add(r, n1, n2, l) {
var c = 0;
for (var i = 0; i < l; ++i) {
r[i] = (c = (c >>> 31) + n1[i] + n2[i]) & 0x7FFFFFFF;
}
return c >>> 31;
} | function mpn_add(r, n1, n2, l) {
var c = 0;
for (var i = 0; i < l; ++i) {
r[i] = (c = (c >>> 31) + n1[i] + n2[i]) & 0x7FFFFFFF;
}
return c >>> 31;
} |
JavaScript | function mpn_sub(r, n1, n2, l) {
var c = 0;
for (var i = 0; i < l; ++i) {
r[i] = (c = (c >> 31) + n1[i] - n2[i]) & 0x7FFFFFFF;
}
return c >> 31;
} | function mpn_sub(r, n1, n2, l) {
var c = 0;
for (var i = 0; i < l; ++i) {
r[i] = (c = (c >> 31) + n1[i] - n2[i]) & 0x7FFFFFFF;
}
return c >> 31;
} |
JavaScript | function mpn_dbl(r, n, l) {
var c = 0;
for (var i = 0; i < l; ++i) {
r[i] = (c = c >>> 31 | n[i] << 1) & 0x7FFFFFFF;
}
return c >>> 31;
} | function mpn_dbl(r, n, l) {
var c = 0;
for (var i = 0; i < l; ++i) {
r[i] = (c = c >>> 31 | n[i] << 1) & 0x7FFFFFFF;
}
return c >>> 31;
} |
JavaScript | function mpn_shr1(r, n, l) {
var c = 0;
while (l > 0) {
var w = n[--l] | c;
c = w << 31;
r[l] = w >>> 1;
}
return c;
} | function mpn_shr1(r, n, l) {
var c = 0;
while (l > 0) {
var w = n[--l] | c;
c = w << 31;
r[l] = w >>> 1;
}
return c;
} |
JavaScript | function fp_add(r, n1, n2, p, l) {
if (mpn_add(r, n1, n2, l) || mpn_cmp(r, p, l) >= 0) {
mpn_sub(r, r, p, l);
}
return r;
} | function fp_add(r, n1, n2, p, l) {
if (mpn_add(r, n1, n2, l) || mpn_cmp(r, p, l) >= 0) {
mpn_sub(r, r, p, l);
}
return r;
} |
JavaScript | function fp_sub(r, n1, n2, p, l) {
if (mpn_sub(r, n1, n2, l)) {
mpn_add(r, r, p, l);
}
return r;
} | function fp_sub(r, n1, n2, p, l) {
if (mpn_sub(r, n1, n2, l)) {
mpn_add(r, r, p, l);
}
return r;
} |
JavaScript | function fp_dbl(r, n, p, l) {
if (mpn_dbl(r, n, l) || mpn_cmp(r, p, l) >= 0) {
mpn_sub(r, r, p, l);
}
return r;
} | function fp_dbl(r, n, p, l) {
if (mpn_dbl(r, n, l) || mpn_cmp(r, p, l) >= 0) {
mpn_sub(r, r, p, l);
}
return r;
} |
JavaScript | function fp_mul(r, n1, n2, p, l) {
mpn_zero(r, l);
var active = false;
for (var i = l; i > 0;) {
var w = n2[--i];
for (var j = 31; j > 0; --j) {
if (active) {
fp_dbl(r, r, p, l);
}
if ((w <<= 1) < 0) {
fp_add(r, r, n1, p, l);
active = true;
}
}
}
return r;
} | function fp_mul(r, n1, n2, p, l) {
mpn_zero(r, l);
var active = false;
for (var i = l; i > 0;) {
var w = n2[--i];
for (var j = 31; j > 0; --j) {
if (active) {
fp_dbl(r, r, p, l);
}
if ((w <<= 1) < 0) {
fp_add(r, r, n1, p, l);
active = true;
}
}
}
return r;
} |
JavaScript | function fp_inv(r, n, p, l) {
if (mpn_zero_p(n, l)) {
throw new RangeError("not invertible");
}
var u = _fp_u, v = _fp_v, s = _fp_s;
mpn_copyi(u, n, l), mpn_copyi(v, p, l);
mpn_zero(r, l), mpn_zero(s, l);
r[0] = 1;
for (;;) {
if (mpn_one_p(u, l)) {
return r;
}
if (mpn_one_p(v, l)) {
mpn_copyi(r, s, l);
return r;
}
while (mpn_even_p(u, l)) {
mpn_shr1(u, u, l);
if (mpn_even_p(r, l)) {
mpn_shr1(r, r, l);
}
else {
var c = mpn_add(r, r, p, l) << 30;
mpn_shr1(r, r, l);
r[l - 1] |= c;
}
}
while (mpn_even_p(v, l)) {
mpn_shr1(v, v, l);
if (mpn_even_p(s, l)) {
mpn_shr1(s, s, l);
}
else {
var c = mpn_add(s, s, p, l) << 30;
mpn_shr1(s, s, l);
s[l - 1] |= c;
}
}
if (mpn_cmp(u, v, l) >= 0) {
mpn_sub(u, u, v, l);
fp_sub(r, r, s, p, l);
}
else {
mpn_sub(v, v, u, l);
fp_sub(s, s, r, p, l);
}
}
} | function fp_inv(r, n, p, l) {
if (mpn_zero_p(n, l)) {
throw new RangeError("not invertible");
}
var u = _fp_u, v = _fp_v, s = _fp_s;
mpn_copyi(u, n, l), mpn_copyi(v, p, l);
mpn_zero(r, l), mpn_zero(s, l);
r[0] = 1;
for (;;) {
if (mpn_one_p(u, l)) {
return r;
}
if (mpn_one_p(v, l)) {
mpn_copyi(r, s, l);
return r;
}
while (mpn_even_p(u, l)) {
mpn_shr1(u, u, l);
if (mpn_even_p(r, l)) {
mpn_shr1(r, r, l);
}
else {
var c = mpn_add(r, r, p, l) << 30;
mpn_shr1(r, r, l);
r[l - 1] |= c;
}
}
while (mpn_even_p(v, l)) {
mpn_shr1(v, v, l);
if (mpn_even_p(s, l)) {
mpn_shr1(s, s, l);
}
else {
var c = mpn_add(s, s, p, l) << 30;
mpn_shr1(s, s, l);
s[l - 1] |= c;
}
}
if (mpn_cmp(u, v, l) >= 0) {
mpn_sub(u, u, v, l);
fp_sub(r, r, s, p, l);
}
else {
mpn_sub(v, v, u, l);
fp_sub(s, s, r, p, l);
}
}
} |
JavaScript | function ecp_dbl(R, N, a, p, l) {
var x = N[0], y = N[1], z = N[2];
var xr = R[0], yr = R[1], zr = R[2];
if (mpn_zero_p(z, l)) {
mpn_zero(xr, l), mpn_zero(yr, l), mpn_zero(zr, l);
return R;
}
var t0 = _ecp_t0, t1 = _ecp_t1, t2 = _ecp_t2, t3 = _ecp_t3;
fp_add(t0, t0, fp_dbl(t1, fp_sqr(t0, x, p, l), p, l), p, l);
if (!mpn_zero_p(a, l)) {
fp_add(t0, t0, fp_mul(t1, a, fp_sqr(t2, fp_sqr(t1, z, p, l), p, l), p, l), p, l);
}
fp_dbl(t1, fp_sqr(t1, y, p, l), p, l);
fp_dbl(t2, fp_mul(t2, x, t1, p, l), p, l);
fp_dbl(t3, fp_sqr(t3, t1, p, l), p, l);
fp_sub(xr, fp_sqr(xr, t0, p, l), fp_dbl(t1, t2, p, l), p, l);
fp_sub(yr, fp_mul(yr, t0, fp_sub(t1, t2, xr, p, l), p, l), t3, p, l);
fp_dbl(zr, fp_mul(zr, y, z, p, l), p, l);
return R;
} | function ecp_dbl(R, N, a, p, l) {
var x = N[0], y = N[1], z = N[2];
var xr = R[0], yr = R[1], zr = R[2];
if (mpn_zero_p(z, l)) {
mpn_zero(xr, l), mpn_zero(yr, l), mpn_zero(zr, l);
return R;
}
var t0 = _ecp_t0, t1 = _ecp_t1, t2 = _ecp_t2, t3 = _ecp_t3;
fp_add(t0, t0, fp_dbl(t1, fp_sqr(t0, x, p, l), p, l), p, l);
if (!mpn_zero_p(a, l)) {
fp_add(t0, t0, fp_mul(t1, a, fp_sqr(t2, fp_sqr(t1, z, p, l), p, l), p, l), p, l);
}
fp_dbl(t1, fp_sqr(t1, y, p, l), p, l);
fp_dbl(t2, fp_mul(t2, x, t1, p, l), p, l);
fp_dbl(t3, fp_sqr(t3, t1, p, l), p, l);
fp_sub(xr, fp_sqr(xr, t0, p, l), fp_dbl(t1, t2, p, l), p, l);
fp_sub(yr, fp_mul(yr, t0, fp_sub(t1, t2, xr, p, l), p, l), t3, p, l);
fp_dbl(zr, fp_mul(zr, y, z, p, l), p, l);
return R;
} |
JavaScript | function ecp_add_aff(R, N1, N2, a, p, l) {
var x1 = N1[0], y1 = N1[1], z1 = N1[2], x2 = N2[0], y2 = N2[1];
var xr = R[0], yr = R[1], zr = R[2];
var t0 = _ecp_t0, t1 = _ecp_t1, t2 = _ecp_t2, t3 = _ecp_t3, t4 = _ecp_t4;
fp_sqr(t0, z1, p, l);
fp_mul(t1, x2, t0, p, l);
fp_mul(t2, z1, t0, p, l);
fp_mul(t0, y2, t2, p, l);
if (mpn_cmp(t1, x1, l) == 0) {
if (mpn_cmp(t0, y1, l) == 0) {
return ecp_dbl(R, N1, a, p, l);
}
mpn_zero(xr, l), mpn_zero(yr, l), mpn_zero(zr, l);
xr[0] = yr[0] = 1;
return R;
}
fp_sub(t2, t1, x1, p, l);
fp_sub(t1, t0, y1, p, l);
fp_sqr(t0, t2, p, l);
fp_mul(t3, t0, t2, p, l);
fp_mul(t4, x1, t0, p, l);
fp_sub(xr, fp_sub(xr, fp_sqr(xr, t1, p, l), t3, p, l), fp_dbl(t0, t4, p, l), p, l);
fp_sub(yr, fp_mul(yr, t1, fp_sub(t4, t4, xr, p, l), p, l), fp_mul(t0, y1, t3, p, l), p, l);
fp_mul(zr, z1, t2, p, l);
return R;
} | function ecp_add_aff(R, N1, N2, a, p, l) {
var x1 = N1[0], y1 = N1[1], z1 = N1[2], x2 = N2[0], y2 = N2[1];
var xr = R[0], yr = R[1], zr = R[2];
var t0 = _ecp_t0, t1 = _ecp_t1, t2 = _ecp_t2, t3 = _ecp_t3, t4 = _ecp_t4;
fp_sqr(t0, z1, p, l);
fp_mul(t1, x2, t0, p, l);
fp_mul(t2, z1, t0, p, l);
fp_mul(t0, y2, t2, p, l);
if (mpn_cmp(t1, x1, l) == 0) {
if (mpn_cmp(t0, y1, l) == 0) {
return ecp_dbl(R, N1, a, p, l);
}
mpn_zero(xr, l), mpn_zero(yr, l), mpn_zero(zr, l);
xr[0] = yr[0] = 1;
return R;
}
fp_sub(t2, t1, x1, p, l);
fp_sub(t1, t0, y1, p, l);
fp_sqr(t0, t2, p, l);
fp_mul(t3, t0, t2, p, l);
fp_mul(t4, x1, t0, p, l);
fp_sub(xr, fp_sub(xr, fp_sqr(xr, t1, p, l), t3, p, l), fp_dbl(t0, t4, p, l), p, l);
fp_sub(yr, fp_mul(yr, t1, fp_sub(t4, t4, xr, p, l), p, l), fp_mul(t0, y1, t3, p, l), p, l);
fp_mul(zr, z1, t2, p, l);
return R;
} |
JavaScript | function ecp_add(R, N1, N2, a, p, l) {
var x1 = N1[0], y1 = N1[1], z1 = N1[2], x2 = N2[0], y2 = N2[1], z2 = N2[2];
var xr = R[0], yr = R[1], zr = R[2];
if (mpn_zero_p(z1, l)) {
if (mpn_zero_p(z2, l)) {
mpn_zero(xr, l), mpn_zero(yr, l), mpn_zero(zr, l);
return R;
}
return ecp_copy(R, N2, l);
}
if (mpn_zero_p(z2, l)) {
return ecp_copy(R, N1, l);
}
if (mpn_one_p(z2, l)) {
return ecp_add_aff(R, N1, N2, a, p, l);
}
var t0 = _ecp_t0, t1 = _ecp_t1, t2 = _ecp_t2, t3 = _ecp_t3, t4 = _ecp_t4, t5 = _ecp_t5, t6 = _ecp_t6;
fp_sqr(t0, z1, p, l);
fp_mul(t1, x2, t0, p, l);
fp_mul(t2, z1, t0, p, l);
fp_mul(t0, y2, t2, p, l);
fp_sqr(t2, z2, p, l);
fp_mul(t3, x1, t2, p, l);
fp_mul(t4, z2, t2, p, l);
fp_mul(t2, y1, t4, p, l);
if (mpn_cmp(t3, t1, l) == 0) {
if (mpn_cmp(t2, t0, l) == 0) {
return ecp_dbl(R, N1, a, p, l);
}
mpn_zero(xr, l), mpn_zero(yr, l), mpn_zero(zr, l);
xr[0] = yr[0] = 1;
return R;
}
fp_sub(t4, t1, t3, p, l);
fp_sub(t1, t0, t2, p, l);
fp_sqr(t0, t4, p, l);
fp_mul(t5, t4, t0, p, l);
fp_mul(t6, t3, t0, p, l);
fp_sub(xr, fp_sub(xr, fp_sqr(xr, t1, p, l), t5, p, l), fp_dbl(t0, t6, p, l), p, l);
fp_sub(yr, fp_mul(yr, t1, fp_sub(t6, t6, xr, p, l), p, l), fp_mul(t0, t2, t5, p, l), p, l);
fp_mul(zr, t4, fp_mul(t0, z1, z2, p, l), p, l);
return R;
} | function ecp_add(R, N1, N2, a, p, l) {
var x1 = N1[0], y1 = N1[1], z1 = N1[2], x2 = N2[0], y2 = N2[1], z2 = N2[2];
var xr = R[0], yr = R[1], zr = R[2];
if (mpn_zero_p(z1, l)) {
if (mpn_zero_p(z2, l)) {
mpn_zero(xr, l), mpn_zero(yr, l), mpn_zero(zr, l);
return R;
}
return ecp_copy(R, N2, l);
}
if (mpn_zero_p(z2, l)) {
return ecp_copy(R, N1, l);
}
if (mpn_one_p(z2, l)) {
return ecp_add_aff(R, N1, N2, a, p, l);
}
var t0 = _ecp_t0, t1 = _ecp_t1, t2 = _ecp_t2, t3 = _ecp_t3, t4 = _ecp_t4, t5 = _ecp_t5, t6 = _ecp_t6;
fp_sqr(t0, z1, p, l);
fp_mul(t1, x2, t0, p, l);
fp_mul(t2, z1, t0, p, l);
fp_mul(t0, y2, t2, p, l);
fp_sqr(t2, z2, p, l);
fp_mul(t3, x1, t2, p, l);
fp_mul(t4, z2, t2, p, l);
fp_mul(t2, y1, t4, p, l);
if (mpn_cmp(t3, t1, l) == 0) {
if (mpn_cmp(t2, t0, l) == 0) {
return ecp_dbl(R, N1, a, p, l);
}
mpn_zero(xr, l), mpn_zero(yr, l), mpn_zero(zr, l);
xr[0] = yr[0] = 1;
return R;
}
fp_sub(t4, t1, t3, p, l);
fp_sub(t1, t0, t2, p, l);
fp_sqr(t0, t4, p, l);
fp_mul(t5, t4, t0, p, l);
fp_mul(t6, t3, t0, p, l);
fp_sub(xr, fp_sub(xr, fp_sqr(xr, t1, p, l), t5, p, l), fp_dbl(t0, t6, p, l), p, l);
fp_sub(yr, fp_mul(yr, t1, fp_sub(t6, t6, xr, p, l), p, l), fp_mul(t0, t2, t5, p, l), p, l);
fp_mul(zr, t4, fp_mul(t0, z1, z2, p, l), p, l);
return R;
} |
JavaScript | function ecp_mul(R, n1, N2, a, p, l) {
var add = mpn_one_p(N2[2], l) ? ecp_add_aff : ecp_add;
var active = false, swaps = 0, S = _ecp_S, T;
for (var i = l; i > 0;) {
var w = n1[--i];
for (var j = 31; j > 0; --j) {
if (active) {
ecp_dbl(S, R, a, p, l);
T = S, S = R, R = T, ++swaps;
}
if ((w <<= 1) < 0) {
if (active) {
add(S, R, N2, a, p, l);
T = S, S = R, R = T, ++swaps;
}
else {
ecp_copy(R, N2, l);
active = true;
}
}
}
}
if (swaps & 1) {
return ecp_copy(S, R, l);
}
return R;
} | function ecp_mul(R, n1, N2, a, p, l) {
var add = mpn_one_p(N2[2], l) ? ecp_add_aff : ecp_add;
var active = false, swaps = 0, S = _ecp_S, T;
for (var i = l; i > 0;) {
var w = n1[--i];
for (var j = 31; j > 0; --j) {
if (active) {
ecp_dbl(S, R, a, p, l);
T = S, S = R, R = T, ++swaps;
}
if ((w <<= 1) < 0) {
if (active) {
add(S, R, N2, a, p, l);
T = S, S = R, R = T, ++swaps;
}
else {
ecp_copy(R, N2, l);
active = true;
}
}
}
}
if (swaps & 1) {
return ecp_copy(S, R, l);
}
return R;
} |
JavaScript | function ecp_proj(R, N, p, l) {
var x = N[0], y = N[1], z = N[2];
var xr = R[0], yr = R[1], zr = R[2];
var t0 = _ecp_t0, t1 = _ecp_t1, t2 = _ecp_t2;
fp_mul(t2, t0, fp_sqr(t1, fp_inv(t0, z, p, l), p, l), p, l);
fp_mul(xr, x, t1, p, l);
fp_mul(yr, y, t2, p, l);
mpn_zero(zr, l), zr[0] = 1;
return R;
} | function ecp_proj(R, N, p, l) {
var x = N[0], y = N[1], z = N[2];
var xr = R[0], yr = R[1], zr = R[2];
var t0 = _ecp_t0, t1 = _ecp_t1, t2 = _ecp_t2;
fp_mul(t2, t0, fp_sqr(t1, fp_inv(t0, z, p, l), p, l), p, l);
fp_mul(xr, x, t1, p, l);
fp_mul(yr, y, t2, p, l);
mpn_zero(zr, l), zr[0] = 1;
return R;
} |
JavaScript | function ecp_sign(r, s, p, a, G, n, d, z, l) {
var R = ecp_new(l), S = ecp_new(l), k = mpn_new(l);
for (;;) {
for (var i = 0; i < l; ++i) {
k[i] = Math.random() * 0x80000000 | 0;
}
var r0 = ecp_proj(R, ecp_mul(S, k, G, a, p, l), p, l)[0];
if (mpn_cmp(r0, n, l) >= 0) {
mpn_sub(r0, r0, n, l);
}
if (!mpn_zero_p(r0, l)) {
var t0 = _ecp_t0, t1 = _ecp_t1;
fp_mul(s, fp_inv(t0, k, n, l), fp_add(t1, z, fp_mul(t1, r0, d, n, l), n, l), n, l);
if (!mpn_zero_p(s, l)) {
mpn_copyi(r, r0, l);
break;
}
}
}
} | function ecp_sign(r, s, p, a, G, n, d, z, l) {
var R = ecp_new(l), S = ecp_new(l), k = mpn_new(l);
for (;;) {
for (var i = 0; i < l; ++i) {
k[i] = Math.random() * 0x80000000 | 0;
}
var r0 = ecp_proj(R, ecp_mul(S, k, G, a, p, l), p, l)[0];
if (mpn_cmp(r0, n, l) >= 0) {
mpn_sub(r0, r0, n, l);
}
if (!mpn_zero_p(r0, l)) {
var t0 = _ecp_t0, t1 = _ecp_t1;
fp_mul(s, fp_inv(t0, k, n, l), fp_add(t1, z, fp_mul(t1, r0, d, n, l), n, l), n, l);
if (!mpn_zero_p(s, l)) {
mpn_copyi(r, r0, l);
break;
}
}
}
} |
JavaScript | function toggleAnnotationList(){
if ($('#all-annotations').hasClass('hidden')) {
$('#all-annotations').removeClass('hidden').hide().slideToggle('slow');
} else {
$('#all-annotations').slideToggle('slow');
}
} | function toggleAnnotationList(){
if ($('#all-annotations').hasClass('hidden')) {
$('#all-annotations').removeClass('hidden').hide().slideToggle('slow');
} else {
$('#all-annotations').slideToggle('slow');
}
} |
JavaScript | function polling (opts) {
var xhr
, xd = false;
if (global.location) {
var isSSL = 'https:' == location.protocol;
var port = location.port;
// some user agents have empty `location.port`
if (!port) {
port = isSSL ? 443 : 80;
}
xd = opts.hostname != location.hostname || port != opts.port;
}
opts.xdomain = xd;
xhr = new XMLHttpRequest(opts);
if ('open' in xhr && !opts.forceJSONP) {
return new XHR(opts);
} else {
return new JSONP(opts);
}
} | function polling (opts) {
var xhr
, xd = false;
if (global.location) {
var isSSL = 'https:' == location.protocol;
var port = location.port;
// some user agents have empty `location.port`
if (!port) {
port = isSSL ? 443 : 80;
}
xd = opts.hostname != location.hostname || port != opts.port;
}
opts.xdomain = xd;
xhr = new XMLHttpRequest(opts);
if ('open' in xhr && !opts.forceJSONP) {
return new XHR(opts);
} else {
return new JSONP(opts);
}
} |
JavaScript | function Modal({ display, children }) {
return (
<div className={classnames({ [styles.hidden]: !display })}>
<div className={styles.overlay} />
<div className={`${styles.modal} ${styles.center}`}>{children}</div>
</div>
);
} | function Modal({ display, children }) {
return (
<div className={classnames({ [styles.hidden]: !display })}>
<div className={styles.overlay} />
<div className={`${styles.modal} ${styles.center}`}>{children}</div>
</div>
);
} |
JavaScript | function WrapperButton({ children, cls, onClick, ...props }) {
return (
<div className={`${styles.btn} ${cls}`}>
{/* Pass down external props */}
<Button onClick={onClick} {...props}>
{children}
</Button>
</div>
);
} | function WrapperButton({ children, cls, onClick, ...props }) {
return (
<div className={`${styles.btn} ${cls}`}>
{/* Pass down external props */}
<Button onClick={onClick} {...props}>
{children}
</Button>
</div>
);
} |
JavaScript | function idSearchCallback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var currPlace = {
placeId: results[0].place_id
};
self.placeService.getDetails(currPlace, detailsCallback);
} else {
placeHtmlData('<div id="place-div" class="alert alert-danger" role="alert">' +
'<h4>Google Place Details</h4><strong>ERROR!</strong> Failed to get Google Place ID ' +
'</div>');
}
} | function idSearchCallback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var currPlace = {
placeId: results[0].place_id
};
self.placeService.getDetails(currPlace, detailsCallback);
} else {
placeHtmlData('<div id="place-div" class="alert alert-danger" role="alert">' +
'<h4>Google Place Details</h4><strong>ERROR!</strong> Failed to get Google Place ID ' +
'</div>');
}
} |
JavaScript | function detailsCallback(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var placeHTML = '';
if (place.icon) {
placeHTML += '<h4>Google Place Details <img src="' + place.icon +
'"height="15" width="15" /></h4>';
} else {
placeHTML += '<h4>Google Place Details</h4>';
}
if (place.website) {
// RegExp match used to display URL. Some were causing scolling InfoWindow
// Displayed link only shows 'https://www.example.com', href is full path
placeHTML += '<br><b><span class="glyphicon glyphicon-link"></span>: </b><a target="_blank" href="' + place.website + '">' +
place.website.match(/^(http[s]?:\/)?\/?([^:\/\s]+)/g) + '</a>';
}
if (place.formatted_phone_number) {
placeHTML += '<br><b><span class="glyphicon glyphicon-phone-alt"></span>: </b>' + place.formatted_phone_number;
}
if (place.rating) {
placeHTML += '<br><b><span class="glyphicon glyphicon-star"></span>: </b>' + place.rating;
}
var hoursToday = '';
if (place.opening_hours) {
// See if the place is open or closed now
if (typeof(place.opening_hours.open_now) === 'boolean' && place.opening_hours.open_now === false) {
placeHTML += '<br><b><span class="glyphicon glyphicon-time"></span></span>: </b>Closed now';
} else if (place.opening_hours.open_now === true) {
placeHTML += '<br><b><span class="glyphicon glyphicon-time"></span></span>: </b>Open now';
}
// Get the place's hours of business today.
hoursToday = getOpenHours(place.opening_hours.weekday_text);
}
if (hoursToday) {
placeHTML += '<br>' + hoursToday;
}
console.log('Got Place data. Updating InfoWindow...');
placeHtmlData('<div id="place-div">' +
placeHTML +
'</div>');
} else {
placeHtmlData('<div id="place-div" class="alert alert-danger" role="alert">' +
'<h4>Google Place Details</h4><strong>ERROR!</strong> Failed to get Google Place details ' +
'</div>');
}
/**
* @description Gets today's open hours.
* @param {Array.string} placeHours Array of strings containing the place open hours each day of the week.
* @return {string} Place hours of business today.
*/
function getOpenHours(placeHours) {
var weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var weekday = weekdays[new Date().getDay()];
if (placeHours) {
for (var i = 0; i < placeHours.length; i++) {
if (placeHours[i].includes(weekday)) {
return placeHours[i].slice(placeHours[i].indexOf(':') + 1);
}
}
}
}
} | function detailsCallback(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var placeHTML = '';
if (place.icon) {
placeHTML += '<h4>Google Place Details <img src="' + place.icon +
'"height="15" width="15" /></h4>';
} else {
placeHTML += '<h4>Google Place Details</h4>';
}
if (place.website) {
// RegExp match used to display URL. Some were causing scolling InfoWindow
// Displayed link only shows 'https://www.example.com', href is full path
placeHTML += '<br><b><span class="glyphicon glyphicon-link"></span>: </b><a target="_blank" href="' + place.website + '">' +
place.website.match(/^(http[s]?:\/)?\/?([^:\/\s]+)/g) + '</a>';
}
if (place.formatted_phone_number) {
placeHTML += '<br><b><span class="glyphicon glyphicon-phone-alt"></span>: </b>' + place.formatted_phone_number;
}
if (place.rating) {
placeHTML += '<br><b><span class="glyphicon glyphicon-star"></span>: </b>' + place.rating;
}
var hoursToday = '';
if (place.opening_hours) {
// See if the place is open or closed now
if (typeof(place.opening_hours.open_now) === 'boolean' && place.opening_hours.open_now === false) {
placeHTML += '<br><b><span class="glyphicon glyphicon-time"></span></span>: </b>Closed now';
} else if (place.opening_hours.open_now === true) {
placeHTML += '<br><b><span class="glyphicon glyphicon-time"></span></span>: </b>Open now';
}
// Get the place's hours of business today.
hoursToday = getOpenHours(place.opening_hours.weekday_text);
}
if (hoursToday) {
placeHTML += '<br>' + hoursToday;
}
console.log('Got Place data. Updating InfoWindow...');
placeHtmlData('<div id="place-div">' +
placeHTML +
'</div>');
} else {
placeHtmlData('<div id="place-div" class="alert alert-danger" role="alert">' +
'<h4>Google Place Details</h4><strong>ERROR!</strong> Failed to get Google Place details ' +
'</div>');
}
/**
* @description Gets today's open hours.
* @param {Array.string} placeHours Array of strings containing the place open hours each day of the week.
* @return {string} Place hours of business today.
*/
function getOpenHours(placeHours) {
var weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var weekday = weekdays[new Date().getDay()];
if (placeHours) {
for (var i = 0; i < placeHours.length; i++) {
if (placeHours[i].includes(weekday)) {
return placeHours[i].slice(placeHours[i].indexOf(':') + 1);
}
}
}
}
} |
JavaScript | function compileServiceWorker({ config, paths, mode }) {
// Choose appropriate destination for compiled SW based on 'mode'
const outputPath =
mode === 'production'
? paths.shellBuildServiceWorker
: paths.shellPublicServiceWorker
const { dir: outputDir, base: outputFilename } = path.parse(outputPath)
// This is part of a bit of a hacky way to provide the same env vars to dev
// SWs as in production by adding them to `process.env` using the plugin
// below.
// TODO: This could be cleaner if the production SW is built in the same
// way instead of using the CRA webpack config, so both can more easily
// share environment variables.
const prefixedPWAEnvVars = Object.entries(getPWAEnvVars(config)).reduce(
(output, [key, value]) => ({
...output,
[`REACT_APP_DHIS2_APP_${key.toUpperCase()}`]: value,
}),
{}
)
const webpackConfig = {
mode, // "production" or "development"
entry: paths.shellSrcServiceWorker,
output: {
path: outputDir,
filename: outputFilename,
},
target: 'webworker',
plugins: [
new webpack.DefinePlugin({
'process.env': JSON.stringify({
...process.env,
...prefixedPWAEnvVars,
}),
}),
],
}
return new Promise((resolve, reject) => {
const logErr = err => {
reporter.debugErr(err.stack || err)
if (err.details) {
reporter.debugErr(err.details)
}
}
webpack(webpackConfig, (err, stats) => {
if (err) {
logErr(err)
reject('Service worker compilation error')
}
const info = stats.toJson()
if (stats.hasWarnings()) {
reporter.warn(`There are ${info.warnings.length} warnings`)
reporter.debug('Warnings:', info.warnings)
}
if (stats.hasErrors()) {
info.errors.forEach(logErr)
reject('Service worker compilation error')
return
}
reporter.debug('Service Worker compilation successful')
resolve()
})
})
} | function compileServiceWorker({ config, paths, mode }) {
// Choose appropriate destination for compiled SW based on 'mode'
const outputPath =
mode === 'production'
? paths.shellBuildServiceWorker
: paths.shellPublicServiceWorker
const { dir: outputDir, base: outputFilename } = path.parse(outputPath)
// This is part of a bit of a hacky way to provide the same env vars to dev
// SWs as in production by adding them to `process.env` using the plugin
// below.
// TODO: This could be cleaner if the production SW is built in the same
// way instead of using the CRA webpack config, so both can more easily
// share environment variables.
const prefixedPWAEnvVars = Object.entries(getPWAEnvVars(config)).reduce(
(output, [key, value]) => ({
...output,
[`REACT_APP_DHIS2_APP_${key.toUpperCase()}`]: value,
}),
{}
)
const webpackConfig = {
mode, // "production" or "development"
entry: paths.shellSrcServiceWorker,
output: {
path: outputDir,
filename: outputFilename,
},
target: 'webworker',
plugins: [
new webpack.DefinePlugin({
'process.env': JSON.stringify({
...process.env,
...prefixedPWAEnvVars,
}),
}),
],
}
return new Promise((resolve, reject) => {
const logErr = err => {
reporter.debugErr(err.stack || err)
if (err.details) {
reporter.debugErr(err.details)
}
}
webpack(webpackConfig, (err, stats) => {
if (err) {
logErr(err)
reject('Service worker compilation error')
}
const info = stats.toJson()
if (stats.hasWarnings()) {
reporter.warn(`There are ${info.warnings.length} warnings`)
reporter.debug('Warnings:', info.warnings)
}
if (stats.hasErrors()) {
info.errors.forEach(logErr)
reject('Service worker compilation error')
return
}
reporter.debug('Service Worker compilation successful')
resolve()
})
})
} |
JavaScript | function openSectionsDB() {
return openDB(SECTIONS_DB, DB_VERSION, {
upgrade(db, oldVersion /* newVersion, transaction */) {
// DB versioning trick that can iteratively apply upgrades
// https://developers.google.com/web/ilt/pwa/working-with-indexeddb#using_database_versioning
switch (oldVersion) {
case 0: {
db.createObjectStore(SECTIONS_STORE, {
keyPath: 'sectionId',
})
}
// falls through (this comment satisfies eslint)
default: {
console.debug('[sections-db] Done upgrading DB')
}
}
},
})
} | function openSectionsDB() {
return openDB(SECTIONS_DB, DB_VERSION, {
upgrade(db, oldVersion /* newVersion, transaction */) {
// DB versioning trick that can iteratively apply upgrades
// https://developers.google.com/web/ilt/pwa/working-with-indexeddb#using_database_versioning
switch (oldVersion) {
case 0: {
db.createObjectStore(SECTIONS_STORE, {
keyPath: 'sectionId',
})
}
// falls through (this comment satisfies eslint)
default: {
console.debug('[sections-db] Done upgrading DB')
}
}
},
})
} |
JavaScript | function VisualizationsList() {
const [vizList, setVizList] = useState([])
const engine = useDataEngine()
useEffect(() => {
setVizList([])
const cascadingFetch = async () => {
for (let i = 0; i < 4; i++) {
// wait 0ms, 250ms, 500ms, 750ms
await wait(i * 250)
const res = await engine.query(query, {
variables: { page: i + 1 },
})
setVizList(prev =>
prev.concat(res.visualizations.visualizations)
)
}
}
cascadingFetch()
}, [])
return (
<>
<h2>Visualizations</h2>
<div>
<em>These will load incrementally</em>
</div>
<ul>
{vizList.map(({ id, name }) => (
<li key={id}>{name}</li>
))}
</ul>
</>
)
} | function VisualizationsList() {
const [vizList, setVizList] = useState([])
const engine = useDataEngine()
useEffect(() => {
setVizList([])
const cascadingFetch = async () => {
for (let i = 0; i < 4; i++) {
// wait 0ms, 250ms, 500ms, 750ms
await wait(i * 250)
const res = await engine.query(query, {
variables: { page: i + 1 },
})
setVizList(prev =>
prev.concat(res.visualizations.visualizations)
)
}
}
cascadingFetch()
}, [])
return (
<>
<h2>Visualizations</h2>
<div>
<em>These will load incrementally</em>
</div>
<ul>
{vizList.map(({ id, name }) => (
<li key={id}>{name}</li>
))}
</ul>
</>
)
} |
JavaScript | function startRecording(event) {
console.debug('[SW] Starting recording')
if (!event.data.payload?.sectionId) {
throw new Error('[SW] No section ID specified to record')
}
const clientId = event.source.id // clientId from MessageEvent
// Throw error if another recording is in process
if (isClientRecording(clientId)) {
throw new Error(
"[SW] Can't start a new recording; a recording is already in process"
)
}
const newClientRecordingState = {
sectionId: event.data.payload?.sectionId,
pendingRequests: new Set(),
// `fulfilledRequests` can later hold useful data for normalization.
// Until then, it's just a count
fulfilledRequests: 0,
recordingTimeout: undefined,
recordingTimeoutDelay:
event.data.payload?.recordingTimeoutDelay || 1000,
confirmationTimeout: undefined,
}
self.clientRecordingStates[clientId] = newClientRecordingState
// Send confirmation message to client
self.clients.get(clientId).then(client => {
client.postMessage({ type: swMsgs.recordingStarted })
})
} | function startRecording(event) {
console.debug('[SW] Starting recording')
if (!event.data.payload?.sectionId) {
throw new Error('[SW] No section ID specified to record')
}
const clientId = event.source.id // clientId from MessageEvent
// Throw error if another recording is in process
if (isClientRecording(clientId)) {
throw new Error(
"[SW] Can't start a new recording; a recording is already in process"
)
}
const newClientRecordingState = {
sectionId: event.data.payload?.sectionId,
pendingRequests: new Set(),
// `fulfilledRequests` can later hold useful data for normalization.
// Until then, it's just a count
fulfilledRequests: 0,
recordingTimeout: undefined,
recordingTimeoutDelay:
event.data.payload?.recordingTimeoutDelay || 1000,
confirmationTimeout: undefined,
}
self.clientRecordingStates[clientId] = newClientRecordingState
// Send confirmation message to client
self.clients.get(clientId).then(client => {
client.postMessage({ type: swMsgs.recordingStarted })
})
} |
JavaScript | function isClientRecordingRequests(clientId) {
// Don't record requests when waiting for completion confirmation
return (
isClientRecording(clientId) &&
self.clientRecordingStates[clientId].confirmationTimeout === undefined
)
} | function isClientRecordingRequests(clientId) {
// Don't record requests when waiting for completion confirmation
return (
isClientRecording(clientId) &&
self.clientRecordingStates[clientId].confirmationTimeout === undefined
)
} |
JavaScript | function startRecordingTimeout(clientId) {
const recordingState = self.clientRecordingStates[clientId]
recordingState.recordingTimeout = setTimeout(
() => stopRecording(null, clientId),
recordingState.recordingTimeoutDelay
)
} | function startRecordingTimeout(clientId) {
const recordingState = self.clientRecordingStates[clientId]
recordingState.recordingTimeout = setTimeout(
() => stopRecording(null, clientId),
recordingState.recordingTimeoutDelay
)
} |
JavaScript | function stopRecording(error, clientId) {
const recordingState = self.clientRecordingStates[clientId]
if (recordingState) {
console.debug('[SW] Stopping recording', { clientId, recordingState })
clearTimeout(recordingState.recordingTimeout)
}
// In case of error, notify client and remove recording.
// Post message even if !recordingState to ensure client stops.
if (error) {
self.clients.get(clientId).then(client => {
// use plain object instead of Error for firefox compatibility
client.postMessage({
type: swMsgs.recordingError,
payload: {
msg: error.message,
},
})
})
removeRecording(clientId)
return
}
// On success, prompt client to confirm saving recording
requestCompletionConfirmation(clientId)
} | function stopRecording(error, clientId) {
const recordingState = self.clientRecordingStates[clientId]
if (recordingState) {
console.debug('[SW] Stopping recording', { clientId, recordingState })
clearTimeout(recordingState.recordingTimeout)
}
// In case of error, notify client and remove recording.
// Post message even if !recordingState to ensure client stops.
if (error) {
self.clients.get(clientId).then(client => {
// use plain object instead of Error for firefox compatibility
client.postMessage({
type: swMsgs.recordingError,
payload: {
msg: error.message,
},
})
})
removeRecording(clientId)
return
}
// On success, prompt client to confirm saving recording
requestCompletionConfirmation(clientId)
} |
JavaScript | async function requestCompletionConfirmation(clientId) {
const client = await self.clients.get(clientId)
if (!client) {
console.debug('[SW] Client not found for ID', clientId)
removeRecording(clientId)
return
}
client.postMessage({ type: swMsgs.confirmRecordingCompletion })
startConfirmationTimeout(clientId)
} | async function requestCompletionConfirmation(clientId) {
const client = await self.clients.get(clientId)
if (!client) {
console.debug('[SW] Client not found for ID', clientId)
removeRecording(clientId)
return
}
client.postMessage({ type: swMsgs.confirmRecordingCompletion })
startConfirmationTimeout(clientId)
} |
JavaScript | function startConfirmationTimeout(clientId) {
const recordingState = self.clientRecordingStates[clientId]
recordingState.confirmationTimeout = setTimeout(() => {
console.warn(
'[SW] Completion confirmation timed out. Clearing recording for client',
clientId
)
removeRecording(clientId)
}, 10000)
} | function startConfirmationTimeout(clientId) {
const recordingState = self.clientRecordingStates[clientId]
recordingState.confirmationTimeout = setTimeout(() => {
console.warn(
'[SW] Completion confirmation timed out. Clearing recording for client',
clientId
)
removeRecording(clientId)
}, 10000)
} |
JavaScript | async function completeRecording(clientId) {
try {
const recordingState = self.clientRecordingStates[clientId]
console.debug('[SW] Completing recording', { clientId, recordingState })
clearTimeout(recordingState.confirmationTimeout)
// If global state has reset, reopen IndexedDB
if (self.dbPromise === undefined) {
self.dbPromise = openSectionsDB()
}
// Add content to DB
const db = await self.dbPromise
db.put(SECTIONS_STORE, {
// Note that request objects can't be stored in the IDB
// https://stackoverflow.com/questions/32880073/whats-the-best-option-for-structured-cloning-of-a-fetch-api-request-object
sectionId: recordingState.sectionId, // the key path
lastUpdated: new Date(),
// 'requests' can later hold data for normalization
requests: recordingState.fulfilledRequests,
}).catch(console.error)
// Move requests from temp cache to section-<ID> cache
const sectionCache = await caches.open(recordingState.sectionId)
const tempCache = await caches.open(getCacheKey('temp', clientId))
const tempCacheItemKeys = await tempCache.keys()
tempCacheItemKeys.forEach(async request => {
const response = await tempCache.match(request)
sectionCache.put(request, response)
})
// Clean up
removeRecording(clientId)
// Send confirmation message to client
self.clients.get(clientId).then(client => {
client.postMessage({ type: swMsgs.recordingCompleted })
})
} catch (err) {
stopRecording(err, clientId)
}
} | async function completeRecording(clientId) {
try {
const recordingState = self.clientRecordingStates[clientId]
console.debug('[SW] Completing recording', { clientId, recordingState })
clearTimeout(recordingState.confirmationTimeout)
// If global state has reset, reopen IndexedDB
if (self.dbPromise === undefined) {
self.dbPromise = openSectionsDB()
}
// Add content to DB
const db = await self.dbPromise
db.put(SECTIONS_STORE, {
// Note that request objects can't be stored in the IDB
// https://stackoverflow.com/questions/32880073/whats-the-best-option-for-structured-cloning-of-a-fetch-api-request-object
sectionId: recordingState.sectionId, // the key path
lastUpdated: new Date(),
// 'requests' can later hold data for normalization
requests: recordingState.fulfilledRequests,
}).catch(console.error)
// Move requests from temp cache to section-<ID> cache
const sectionCache = await caches.open(recordingState.sectionId)
const tempCache = await caches.open(getCacheKey('temp', clientId))
const tempCacheItemKeys = await tempCache.keys()
tempCacheItemKeys.forEach(async request => {
const response = await tempCache.match(request)
sectionCache.put(request, response)
})
// Clean up
removeRecording(clientId)
// Send confirmation message to client
self.clients.get(clientId).then(client => {
client.postMessage({ type: swMsgs.recordingCompleted })
})
} catch (err) {
stopRecording(err, clientId)
}
} |
JavaScript | function swMessage(type, payload) {
if (!navigator.serviceWorker.controller) {
throw new Error(
'[Offine interface] Cannot send service worker message - no service worker is registered'
)
}
navigator.serviceWorker.controller.postMessage({ type, payload })
} | function swMessage(type, payload) {
if (!navigator.serviceWorker.controller) {
throw new Error(
'[Offine interface] Cannot send service worker message - no service worker is registered'
)
}
navigator.serviceWorker.controller.postMessage({ type, payload })
} |
JavaScript | init({ promptUpdate }) {
if (!('serviceWorker' in navigator)) {
return null
}
function onUpdate(registration) {
if (!promptUpdate) {
return
}
const reloadMessage = i18n.t(
'App updates are ready and will be activated after all tabs of this app are closed. Skip waiting and reload to update now?'
)
const onConfirm = () =>
registration.waiting.postMessage({
type: swMsgs.skipWaiting,
})
promptUpdate({
message: reloadMessage,
action: i18n.t('Update'),
onConfirm: onConfirm,
})
}
// Check for SW updates
checkForUpdates({ onUpdate })
// This event emitter helps coordinate with service worker messages
this.offlineEvents = new EventEmitter()
// Receives messages from service worker and forwards to event emitter
const handleServiceWorkerMessage = event => {
if (!event.data) {
return
}
const { type, payload } = event.data
this.offlineEvents.emit(type, payload)
}
navigator.serviceWorker.addEventListener(
'message',
handleServiceWorkerMessage
)
// Okay to use 'startRecording' now
this.initialized = true
// Cleanup function to be returned by useEffect
return () => {
navigator.serviceWorker.removeEventListener(
'message',
handleServiceWorkerMessage
)
}
} | init({ promptUpdate }) {
if (!('serviceWorker' in navigator)) {
return null
}
function onUpdate(registration) {
if (!promptUpdate) {
return
}
const reloadMessage = i18n.t(
'App updates are ready and will be activated after all tabs of this app are closed. Skip waiting and reload to update now?'
)
const onConfirm = () =>
registration.waiting.postMessage({
type: swMsgs.skipWaiting,
})
promptUpdate({
message: reloadMessage,
action: i18n.t('Update'),
onConfirm: onConfirm,
})
}
// Check for SW updates
checkForUpdates({ onUpdate })
// This event emitter helps coordinate with service worker messages
this.offlineEvents = new EventEmitter()
// Receives messages from service worker and forwards to event emitter
const handleServiceWorkerMessage = event => {
if (!event.data) {
return
}
const { type, payload } = event.data
this.offlineEvents.emit(type, payload)
}
navigator.serviceWorker.addEventListener(
'message',
handleServiceWorkerMessage
)
// Okay to use 'startRecording' now
this.initialized = true
// Cleanup function to be returned by useEffect
return () => {
navigator.serviceWorker.removeEventListener(
'message',
handleServiceWorkerMessage
)
}
} |
JavaScript | async startRecording({
sectionId,
recordingTimeoutDelay,
onStarted,
onCompleted,
onError,
}) {
if (!this.initialized) {
throw new Error(
'OfflineInterface has not been initialized. Make sure `pwa.enabled` is `true` in `d2.config.js`'
)
}
if (!sectionId || !onStarted || !onCompleted || !onError) {
throw new Error(
'[Offline interface] The options { sectionId, onStarted, onCompleted, onError } are required when calling startRecording()'
)
}
// Send SW message to start recording
swMessage(swMsgs.startRecording, {
sectionId,
recordingTimeoutDelay,
})
/** Cleans up SW recording listeners */
const cleanUpListeners = () => {
const messageTypes = [
swMsgs.recordingStarted,
swMsgs.recordingError,
swMsgs.recordingCompleted,
swMsgs.confirmRecordingCompletion,
]
messageTypes.forEach(messageType =>
this.offlineEvents.removeAllListeners(messageType)
)
}
// Prep for subsequent events after recording starts:
this.offlineEvents.once(swMsgs.recordingStarted, onStarted)
this.offlineEvents.once(
swMsgs.confirmRecordingCompletion,
// Confirms recording is okay to save
() => swMessage(swMsgs.completeRecording)
)
this.offlineEvents.once(swMsgs.recordingCompleted, () => {
cleanUpListeners()
onCompleted()
})
this.offlineEvents.once(swMsgs.recordingError, ({ msg }) => {
cleanUpListeners()
// Make error out of message from SW (firefox SW message interface
// doesn't handle payloads other than simple objects)
const error = new Error(msg)
onError(error)
})
} | async startRecording({
sectionId,
recordingTimeoutDelay,
onStarted,
onCompleted,
onError,
}) {
if (!this.initialized) {
throw new Error(
'OfflineInterface has not been initialized. Make sure `pwa.enabled` is `true` in `d2.config.js`'
)
}
if (!sectionId || !onStarted || !onCompleted || !onError) {
throw new Error(
'[Offline interface] The options { sectionId, onStarted, onCompleted, onError } are required when calling startRecording()'
)
}
// Send SW message to start recording
swMessage(swMsgs.startRecording, {
sectionId,
recordingTimeoutDelay,
})
/** Cleans up SW recording listeners */
const cleanUpListeners = () => {
const messageTypes = [
swMsgs.recordingStarted,
swMsgs.recordingError,
swMsgs.recordingCompleted,
swMsgs.confirmRecordingCompletion,
]
messageTypes.forEach(messageType =>
this.offlineEvents.removeAllListeners(messageType)
)
}
// Prep for subsequent events after recording starts:
this.offlineEvents.once(swMsgs.recordingStarted, onStarted)
this.offlineEvents.once(
swMsgs.confirmRecordingCompletion,
// Confirms recording is okay to save
() => swMessage(swMsgs.completeRecording)
)
this.offlineEvents.once(swMsgs.recordingCompleted, () => {
cleanUpListeners()
onCompleted()
})
this.offlineEvents.once(swMsgs.recordingError, ({ msg }) => {
cleanUpListeners()
// Make error out of message from SW (firefox SW message interface
// doesn't handle payloads other than simple objects)
const error = new Error(msg)
onError(error)
})
} |
JavaScript | async removeSection(sectionId) {
if (!this.pwaEnabled) {
throw new Error(
'Cannot remove section - PWA is not enabled in d2.config.js'
)
}
if (!sectionId) {
throw new Error('No section ID specified to delete')
}
await navigator.serviceWorker.ready
if (this.dbPromise === undefined) {
this.dbPromise = openSectionsDB()
}
const db = await this.dbPromise
const sectionExists = await db.count(SECTIONS_STORE, sectionId)
return Promise.all([
caches.delete(sectionId),
!!sectionExists &&
db.delete(SECTIONS_STORE, sectionId).then(() => true),
]).then(
([cacheDeleted, dbEntryDeleted]) => cacheDeleted || dbEntryDeleted
)
} | async removeSection(sectionId) {
if (!this.pwaEnabled) {
throw new Error(
'Cannot remove section - PWA is not enabled in d2.config.js'
)
}
if (!sectionId) {
throw new Error('No section ID specified to delete')
}
await navigator.serviceWorker.ready
if (this.dbPromise === undefined) {
this.dbPromise = openSectionsDB()
}
const db = await this.dbPromise
const sectionExists = await db.count(SECTIONS_STORE, sectionId)
return Promise.all([
caches.delete(sectionId),
!!sectionExists &&
db.delete(SECTIONS_STORE, sectionId).then(() => true),
]).then(
([cacheDeleted, dbEntryDeleted]) => cacheDeleted || dbEntryDeleted
)
} |
JavaScript | function useVerifyLatestUser() {
const { pwaEnabled } = useConfig()
const [finished, setFinished] = useState(false)
const { loading, error } = useDataQuery(USER_QUERY, {
onComplete: async data => {
const latestUserId = localStorage.getItem(LATEST_USER_KEY)
const currentUserId = data.user.id
if (currentUserId !== latestUserId) {
const cachesCleared = await clearSensitiveCaches()
localStorage.setItem(LATEST_USER_KEY, currentUserId)
if (cachesCleared && pwaEnabled) {
// If this is a PWA app, the app-shell cache will need to
// be restored with a page reload
return window.location.reload()
}
}
setFinished(true)
},
})
if (error) {
throw new Error('Failed to fetch user ID: ' + error)
}
return { loading: loading || !finished }
} | function useVerifyLatestUser() {
const { pwaEnabled } = useConfig()
const [finished, setFinished] = useState(false)
const { loading, error } = useDataQuery(USER_QUERY, {
onComplete: async data => {
const latestUserId = localStorage.getItem(LATEST_USER_KEY)
const currentUserId = data.user.id
if (currentUserId !== latestUserId) {
const cachesCleared = await clearSensitiveCaches()
localStorage.setItem(LATEST_USER_KEY, currentUserId)
if (cachesCleared && pwaEnabled) {
// If this is a PWA app, the app-shell cache will need to
// be restored with a page reload
return window.location.reload()
}
}
setFinished(true)
},
})
if (error) {
throw new Error('Failed to fetch user ID: ' + error)
}
return { loading: loading || !finished }
} |
JavaScript | async function opendota(message, args) {
// Checks for id
if (args[0] === "me") {
details = await discordToSteamID(message.author.id);
if (details) {
args[0] = details.steamID;
} else {
let response = `${message.author} Invalid response from database. `;
response += "In order to use the me argument, you have to have your id added. ";
response += "Either you haven't added your id, or there was a database error. ";
response += `You can add you id with the id command!`;
message.channel.send(response);
return;
}
}
let time_recieved = Date.now();
let url = `https://api.opendota.com/api/players/${args[0]}`;
Promise.all([
fetch(url), // 0 For basic information
fetch(`${url}/wl`), // 1 For won and lost game totals
fetch(`${url}/heroes`), // 2 For top heroes
fetch(`https://api.opendota.com/api/heroes`), // 3 For hero names
fetch(`${url}/rankings`), // 4 For hero rankings
fetch(`${url}/recentMatches`) // 5 For most recent match data
])
// Convert data to .json
.then(response => Promise.all(response.map(response => response.json())))
// Extract and format data
.then(data => {
return formatData(data[0], data[1], data[2], data[3], data[4], data[5]);
})
// Add data onto embed
.then(player_data => {
sendEmbed(message, time_recieved, player_data, player_data.recent);
})
.catch(function(error) {
message.channel.send(`There was an error: ${error}`);
})
} | async function opendota(message, args) {
// Checks for id
if (args[0] === "me") {
details = await discordToSteamID(message.author.id);
if (details) {
args[0] = details.steamID;
} else {
let response = `${message.author} Invalid response from database. `;
response += "In order to use the me argument, you have to have your id added. ";
response += "Either you haven't added your id, or there was a database error. ";
response += `You can add you id with the id command!`;
message.channel.send(response);
return;
}
}
let time_recieved = Date.now();
let url = `https://api.opendota.com/api/players/${args[0]}`;
Promise.all([
fetch(url), // 0 For basic information
fetch(`${url}/wl`), // 1 For won and lost game totals
fetch(`${url}/heroes`), // 2 For top heroes
fetch(`https://api.opendota.com/api/heroes`), // 3 For hero names
fetch(`${url}/rankings`), // 4 For hero rankings
fetch(`${url}/recentMatches`) // 5 For most recent match data
])
// Convert data to .json
.then(response => Promise.all(response.map(response => response.json())))
// Extract and format data
.then(data => {
return formatData(data[0], data[1], data[2], data[3], data[4], data[5]);
})
// Add data onto embed
.then(player_data => {
sendEmbed(message, time_recieved, player_data, player_data.recent);
})
.catch(function(error) {
message.channel.send(`There was an error: ${error}`);
})
} |
JavaScript | function formatData(profile, wl, player_heroes, heroes, rankings, recentMatches) {
// Profile details
let p = profile;
p.w = wl.win;
p.l = wl.lose;
p.wr = (100 * p.w / (p.w + p.l)).toPrecision(4);
// Top 3 heroes
p.heroes = [];
for (let i = 0; i < 3; i++) {
p.heroes.push(player_heroes[i]);
for (let j = 0; j < rankings.length - 1; j++) {
if (rankings[j].hero_id == player_heroes[i].hero_id) {
p.heroes[i].percentile = +(100 * rankings[j].percent_rank).toFixed(2);
break;
}
}
for (let j = 0; i < heroes.length - 1; j++) {
if (heroes[j].id == player_heroes[i].hero_id) {
p.heroes[i].name = heroes[j].localized_name;
break;
}
}
p.heroes[i].winAs = (100 * p.heroes[i].win / p.heroes[i].games).toPrecision(2);
}
// Most recent match
p.recent = recentMatches[0];
p.recent.time = Date(p.recent.start_time).substr(0, 15);
p.recent.skill = ['invalid', 'normal', 'high', 'very high'][p.recent.skill];
// Find game mode and lobby, for some reason lobby is not always updated
try {
p.recent.game_mode = game_modes[p.recent.game_mode].replace(/_/g, " ");
} catch {
p.recent.game_mode = "";
}
try {
p.recent.lobby_type = lobby_types[p.recent.lobby_type].replace(/_/g, " ");
} catch {
p.recent.lobby_type = "";
}
// Check if they've won or lost
p.recent.outcome = 'Lost';
if ((p.recent.player_slot < 6 && p.recent.radiant_win == true)
|| (p.recent.player_slot > 5 && p.recent.radiant_win == false)) {
p.recent.outcome = 'Won';
}
// Find name of hero they played
for (let i = 0; i < heroes.length - 1; i++) {
if (heroes[i].id == p.recent.hero_id) {
p.recent.hero = heroes[i].localized_name;
break;
}
}
return p;
} | function formatData(profile, wl, player_heroes, heroes, rankings, recentMatches) {
// Profile details
let p = profile;
p.w = wl.win;
p.l = wl.lose;
p.wr = (100 * p.w / (p.w + p.l)).toPrecision(4);
// Top 3 heroes
p.heroes = [];
for (let i = 0; i < 3; i++) {
p.heroes.push(player_heroes[i]);
for (let j = 0; j < rankings.length - 1; j++) {
if (rankings[j].hero_id == player_heroes[i].hero_id) {
p.heroes[i].percentile = +(100 * rankings[j].percent_rank).toFixed(2);
break;
}
}
for (let j = 0; i < heroes.length - 1; j++) {
if (heroes[j].id == player_heroes[i].hero_id) {
p.heroes[i].name = heroes[j].localized_name;
break;
}
}
p.heroes[i].winAs = (100 * p.heroes[i].win / p.heroes[i].games).toPrecision(2);
}
// Most recent match
p.recent = recentMatches[0];
p.recent.time = Date(p.recent.start_time).substr(0, 15);
p.recent.skill = ['invalid', 'normal', 'high', 'very high'][p.recent.skill];
// Find game mode and lobby, for some reason lobby is not always updated
try {
p.recent.game_mode = game_modes[p.recent.game_mode].replace(/_/g, " ");
} catch {
p.recent.game_mode = "";
}
try {
p.recent.lobby_type = lobby_types[p.recent.lobby_type].replace(/_/g, " ");
} catch {
p.recent.lobby_type = "";
}
// Check if they've won or lost
p.recent.outcome = 'Lost';
if ((p.recent.player_slot < 6 && p.recent.radiant_win == true)
|| (p.recent.player_slot > 5 && p.recent.radiant_win == false)) {
p.recent.outcome = 'Won';
}
// Find name of hero they played
for (let i = 0; i < heroes.length - 1; i++) {
if (heroes[i].id == p.recent.hero_id) {
p.recent.hero = heroes[i].localized_name;
break;
}
}
return p;
} |
JavaScript | function sendEmbed(message, time_recieved, p, match) {
const profileEmbed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle(`${p.profile.personaname}`)
.setURL(`https://www.opendota.com/players/${p.profile.account_id}`)
.setAuthor(
'Lonely Bot',
'https://i.imgur.com/b0sTfNL.png',
'https://github.com/Gy74S/Lonely-Bot'
)
.setDescription(
`Medal: **${medal(p)}**
MMR Estimate: **${p.mmr_estimate.estimate}**
Country: **${p.profile.loccountrycode}**`
)
.setThumbnail(p.profile.avatarfull)
.setTimestamp()
.setFooter(
`Total Processing Time: ${Date.now() - message.createdTimestamp} ms | Generating Time: ${Date.now() - time_recieved} ms`
)
.addFields({
name: '**General Match Data**',
value: `Total: **${p.w + p.l}** | Won: **${p.w}** | Lost: **${p.l}** | Winrate: **${p.wr}%**\n`
})
// Add player's top three heroes
for (let i = 0; i < p.heroes.length; i++) {
profileEmbed.addFields({
name: `**${p.heroes[i].name}**`,
value: `
Games: **${p.heroes[i].games}**
Win as: **${p.heroes[i].winAs}%**
Percentile: **${p.heroes[i].percentile}%**
`,
inline: true
})
}
// Add most recent match data
profileEmbed.addFields({
name: `**Most Recent Match**`,
value: `*${match.time} ${secondsToHms(match.duration)}*
**${match.outcome}** playing a **${match.skill}** skill **${match.lobby_type} ${match.game_mode}** as **${match.hero}**
KDA: **${match.kills}/${match.deaths}/${match.assists}** | GPM: **${match.gold_per_min}** | XPM: **${match.xp_per_min}**`
})
message.channel.send(profileEmbed);
} | function sendEmbed(message, time_recieved, p, match) {
const profileEmbed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle(`${p.profile.personaname}`)
.setURL(`https://www.opendota.com/players/${p.profile.account_id}`)
.setAuthor(
'Lonely Bot',
'https://i.imgur.com/b0sTfNL.png',
'https://github.com/Gy74S/Lonely-Bot'
)
.setDescription(
`Medal: **${medal(p)}**
MMR Estimate: **${p.mmr_estimate.estimate}**
Country: **${p.profile.loccountrycode}**`
)
.setThumbnail(p.profile.avatarfull)
.setTimestamp()
.setFooter(
`Total Processing Time: ${Date.now() - message.createdTimestamp} ms | Generating Time: ${Date.now() - time_recieved} ms`
)
.addFields({
name: '**General Match Data**',
value: `Total: **${p.w + p.l}** | Won: **${p.w}** | Lost: **${p.l}** | Winrate: **${p.wr}%**\n`
})
// Add player's top three heroes
for (let i = 0; i < p.heroes.length; i++) {
profileEmbed.addFields({
name: `**${p.heroes[i].name}**`,
value: `
Games: **${p.heroes[i].games}**
Win as: **${p.heroes[i].winAs}%**
Percentile: **${p.heroes[i].percentile}%**
`,
inline: true
})
}
// Add most recent match data
profileEmbed.addFields({
name: `**Most Recent Match**`,
value: `*${match.time} ${secondsToHms(match.duration)}*
**${match.outcome}** playing a **${match.skill}** skill **${match.lobby_type} ${match.game_mode}** as **${match.hero}**
KDA: **${match.kills}/${match.deaths}/${match.assists}** | GPM: **${match.gold_per_min}** | XPM: **${match.xp_per_min}**`
})
message.channel.send(profileEmbed);
} |
JavaScript | function medal(player) {
if (player.rank_tier === null) return "unranked";
if (player.leader_board) return `Immortal ** | rank **${player.leaderboard_rank}`;
if (player.rank_tier[0] === 8) return `Immortal`;
let medal_tier = player.rank_tier.toString();
let medals = ["Lower than Herald?", "Herald", "Guardian", "Crusader", "Archon", "Legend", "Ancient", "Divine"];
return `${medals[medal_tier[0]]} ${medal_tier[1]}`;
} | function medal(player) {
if (player.rank_tier === null) return "unranked";
if (player.leader_board) return `Immortal ** | rank **${player.leaderboard_rank}`;
if (player.rank_tier[0] === 8) return `Immortal`;
let medal_tier = player.rank_tier.toString();
let medals = ["Lower than Herald?", "Herald", "Guardian", "Crusader", "Archon", "Legend", "Ancient", "Divine"];
return `${medals[medal_tier[0]]} ${medal_tier[1]}`;
} |
JavaScript | function secondsToHms(duration) {
let hours = duration / 3600;
duration = duration % (3600);
let min = parseInt(duration / 60);
duration = duration % (60);
let sec = parseInt(duration);
if (sec < 10) sec = `0${sec}`;
if (min < 10) min = `0${min}`;
if (parseInt(hours, 10) > 0) return `${parseInt(hours, 10)}h ${min}m ${sec}s`;
else if (min == 0) return `${sec}s`;
return `${min}m ${sec}s`;
} | function secondsToHms(duration) {
let hours = duration / 3600;
duration = duration % (3600);
let min = parseInt(duration / 60);
duration = duration % (60);
let sec = parseInt(duration);
if (sec < 10) sec = `0${sec}`;
if (min < 10) min = `0${min}`;
if (parseInt(hours, 10) > 0) return `${parseInt(hours, 10)}h ${min}m ${sec}s`;
else if (min == 0) return `${sec}s`;
return `${min}m ${sec}s`;
} |
JavaScript | initColor(parent, type, mtl) {
parent.traverse((child) => {
if (child.isMesh) {
if (child.name.includes(type)) {
child.material = mtl;
child.nameID = type;
}
}
});
} | initColor(parent, type, mtl) {
parent.traverse((child) => {
if (child.isMesh) {
if (child.name.includes(type)) {
child.material = mtl;
child.nameID = type;
}
}
});
} |
JavaScript | function collectCoreMethods(raxExported) {
const vaildList = [];
raxExported.forEach(exported => {
if (coreMethodList.indexOf(exported.local) > -1) {
vaildList.push(exported.local);
}
});
return vaildList;
} | function collectCoreMethods(raxExported) {
const vaildList = [];
raxExported.forEach(exported => {
if (coreMethodList.indexOf(exported.local) > -1) {
vaildList.push(exported.local);
}
});
return vaildList;
} |
JavaScript | function runApp(appConfig, pageProps = {}) {
if (_appConfig) {
throw new Error('runApp can only be called once.');
}
_appConfig = appConfig; // Store raw app config to parse router.
_pageProps = pageProps; // Store global page props to inject to every page props
__updateRouterMap(appConfig);
const appOptions = {
// Bridge app launch.
onLaunch(launchOptions) {
const launchQueue = appCycles.launch;
if (Array.isArray(launchQueue) && launchQueue.length > 0) {
let fn;
while (fn = launchQueue.pop()) { // eslint-disable-line
fn.call(this, launchOptions);
}
}
},
};
// eslint-disable-next-line
App(appOptions);
} | function runApp(appConfig, pageProps = {}) {
if (_appConfig) {
throw new Error('runApp can only be called once.');
}
_appConfig = appConfig; // Store raw app config to parse router.
_pageProps = pageProps; // Store global page props to inject to every page props
__updateRouterMap(appConfig);
const appOptions = {
// Bridge app launch.
onLaunch(launchOptions) {
const launchQueue = appCycles.launch;
if (Array.isArray(launchQueue) && launchQueue.length > 0) {
let fn;
while (fn = launchQueue.pop()) { // eslint-disable-line
fn.call(this, launchOptions);
}
}
},
};
// eslint-disable-next-line
App(appOptions);
} |
JavaScript | function configureStore(initailState) {
const store = createStore(persistedReducer, initailState, composeEnhancers(applyMiddleware(thunk)));
const persistor = persistStore(store);
return { store, persistor };
} | function configureStore(initailState) {
const store = createStore(persistedReducer, initailState, composeEnhancers(applyMiddleware(thunk)));
const persistor = persistStore(store);
return { store, persistor };
} |
JavaScript | function reverseString(s) {
let f = s;
try {
const sp = s.split("");
const re = sp.reverse();
f = re.join('');
} catch (e) {
console.log(e.message);
} finally {
console.log(f);
}
} | function reverseString(s) {
let f = s;
try {
const sp = s.split("");
const re = sp.reverse();
f = re.join('');
} catch (e) {
console.log(e.message);
} finally {
console.log(f);
}
} |
JavaScript | function showBtn() {
$("#button-container").empty()
// For loop to crate btns for movies array
for (let index = 0; index < movies.length; index++) {
// Creat new variable, assign attributes, class, text
let addMovie = $(`<button style="margin: 5px;">`);
addMovie.addClass('newBtn btn text-light bg-dark')
addMovie.attr("data-name", movies[index])
addMovie.text(movies[index])
$("#button-container").append(addMovie) // Append the button to html
}
} | function showBtn() {
$("#button-container").empty()
// For loop to crate btns for movies array
for (let index = 0; index < movies.length; index++) {
// Creat new variable, assign attributes, class, text
let addMovie = $(`<button style="margin: 5px;">`);
addMovie.addClass('newBtn btn text-light bg-dark')
addMovie.attr("data-name", movies[index])
addMovie.text(movies[index])
$("#button-container").append(addMovie) // Append the button to html
}
} |
JavaScript | function showGif() {
let apiKey = "Ad44EQ6P3tOqlByyTgrK2gohrEnHW0EA" // Giphy API Key
let movieAdded = $(this).attr("data-name") // Assign data-name attribute to user input
console.log(movieAdded)
let queryURL = `https://api.giphy.com/v1/gifs/search?api_key=${apiKey}&q="${movieAdded}"&limit=10&offset=0&rating=R&lang=en`
$('.gif-container').empty(); // use ajax to retrieve user input from Giphy api
$.ajax({
url: queryURL,
method: "GET"
})
.then(function (response) {
console.log(JSON.stringify(response)) // console.log object
let results = response.data // put object into variable
for (index = 0; index < results.length; index++) { // for loop to set up index array for gifs
let animateURL = response.data[index].images.downsized.url // variable for animated Gif
let stillURL = response.data[index].images.downsized_still.url // variable for still Gif
let newGif = $(`<div class=shadow p-3 mb-5 bg-white rounded style="margin: 25px">`); // creat container to hold gifs
newGif.append(`<b>Rating: ${results[index].rating}</b><br>`); // append rating to the newGifs container
let gif = $('<img>').addClass('switch rounded img-fluid') // assign gifs and image and attributes
gif.attr('src', animateURL)
gif.attr('data-still', stillURL)
gif.attr('data-animate', animateURL)
gif.attr('data-state', 'animate')
newGif.append(gif)
$('.gif-container').append(newGif) //append the newGiff to the container
}
})
} | function showGif() {
let apiKey = "Ad44EQ6P3tOqlByyTgrK2gohrEnHW0EA" // Giphy API Key
let movieAdded = $(this).attr("data-name") // Assign data-name attribute to user input
console.log(movieAdded)
let queryURL = `https://api.giphy.com/v1/gifs/search?api_key=${apiKey}&q="${movieAdded}"&limit=10&offset=0&rating=R&lang=en`
$('.gif-container').empty(); // use ajax to retrieve user input from Giphy api
$.ajax({
url: queryURL,
method: "GET"
})
.then(function (response) {
console.log(JSON.stringify(response)) // console.log object
let results = response.data // put object into variable
for (index = 0; index < results.length; index++) { // for loop to set up index array for gifs
let animateURL = response.data[index].images.downsized.url // variable for animated Gif
let stillURL = response.data[index].images.downsized_still.url // variable for still Gif
let newGif = $(`<div class=shadow p-3 mb-5 bg-white rounded style="margin: 25px">`); // creat container to hold gifs
newGif.append(`<b>Rating: ${results[index].rating}</b><br>`); // append rating to the newGifs container
let gif = $('<img>').addClass('switch rounded img-fluid') // assign gifs and image and attributes
gif.attr('src', animateURL)
gif.attr('data-still', stillURL)
gif.attr('data-animate', animateURL)
gif.attr('data-state', 'animate')
newGif.append(gif)
$('.gif-container').append(newGif) //append the newGiff to the container
}
})
} |
JavaScript | function _get_largest_index(type, fields) {
// Turn the attributes and indexes into sets.
var field_set = new sets.Set(fields);
var indexes = self.indexes[type].map(function(index) { return [new sets.Set(index), index];});
// Compare each index set to the field set only if it contains all parameters (super set).
// XXX: If the database can use partial indexes, we might not need to only
// select subsets of the parameters here.
var min = findMin(indexes, function(index) {
if (field_set.issuperset(index[0])) {
return field_set.difference(index[0]).size();
}
return Number.NaN;
});
if (!min) {
return [];
}
// Return the index that has the most fields in common with the query.
return min[1]
} | function _get_largest_index(type, fields) {
// Turn the attributes and indexes into sets.
var field_set = new sets.Set(fields);
var indexes = self.indexes[type].map(function(index) { return [new sets.Set(index), index];});
// Compare each index set to the field set only if it contains all parameters (super set).
// XXX: If the database can use partial indexes, we might not need to only
// select subsets of the parameters here.
var min = findMin(indexes, function(index) {
if (field_set.issuperset(index[0])) {
return field_set.difference(index[0]).size();
}
return Number.NaN;
});
if (!min) {
return [];
}
// Return the index that has the most fields in common with the query.
return min[1]
} |
JavaScript | function pathStartPoint(path) {
var d = path.attr("d"),
dsplitted = d.split(" ");
return dsplitted[1];
} | function pathStartPoint(path) {
var d = path.attr("d"),
dsplitted = d.split(" ");
return dsplitted[1];
} |
JavaScript | function resourceSkills() {
$http.get(ApiUrlPrefix + "fetchEmployeeResourceSkillDetailsSelf/UserId=" + $scope.userinfodata.EmployeeId).success(function (response) {
$scope.currentEmployeeResource = response;
console.log(response);
});
} | function resourceSkills() {
$http.get(ApiUrlPrefix + "fetchEmployeeResourceSkillDetailsSelf/UserId=" + $scope.userinfodata.EmployeeId).success(function (response) {
$scope.currentEmployeeResource = response;
console.log(response);
});
} |
JavaScript | function DataCall() {
$http.get(ApiUrlPrefix + "fetchAllEmployeeDataByHR").success(function (data) {
$scope.currentEmployeeList = data;
console.log(data);
});
} | function DataCall() {
$http.get(ApiUrlPrefix + "fetchAllEmployeeDataByHR").success(function (data) {
$scope.currentEmployeeList = data;
console.log(data);
});
} |
JavaScript | function employeeManagerList() {
$http.get(ApiUrlPrefix + "fetchEmployeeMasterdetailsByManager/managerEmpId=" + $scope.userinfodata.EmployeeId).success(function (response) {
$scope.managerEmployeeList = response;
console.log(response);
});
} | function employeeManagerList() {
$http.get(ApiUrlPrefix + "fetchEmployeeMasterdetailsByManager/managerEmpId=" + $scope.userinfodata.EmployeeId).success(function (response) {
$scope.managerEmployeeList = response;
console.log(response);
});
} |
JavaScript | function employeeHeader() {
$http.get(ApiUrlPrefix + "fetchEmployeeMasterDetailsBasedOnUsername/Username=" + $scope.userInfo.Username).success(function (response) {
$scope.EmployeeList = response[0];
console.log(response);
});
} | function employeeHeader() {
$http.get(ApiUrlPrefix + "fetchEmployeeMasterDetailsBasedOnUsername/Username=" + $scope.userInfo.Username).success(function (response) {
$scope.EmployeeList = response[0];
console.log(response);
});
} |
JavaScript | function requireTask(taskName, path, options, dependencies) {
let settings = options || {};
const taskFunction = function (callback) {
let task = require(path + taskName + '.js').call(this, settings);
return task(callback);
}
settings.taskName = taskName;
if (!Array.isArray(dependencies)) {
gulp.task(taskName, taskFunction);
} else if (dependencies.length === 1) {
gulp.task(taskName, gulp.series(dependencies[0], taskFunction));
} else {
gulp.task(taskName, gulp.series(dependencies, taskFunction));
}
} | function requireTask(taskName, path, options, dependencies) {
let settings = options || {};
const taskFunction = function (callback) {
let task = require(path + taskName + '.js').call(this, settings);
return task(callback);
}
settings.taskName = taskName;
if (!Array.isArray(dependencies)) {
gulp.task(taskName, taskFunction);
} else if (dependencies.length === 1) {
gulp.task(taskName, gulp.series(dependencies[0], taskFunction));
} else {
gulp.task(taskName, gulp.series(dependencies, taskFunction));
}
} |
JavaScript | function showError(preffix, err) {
gutil.log(gutil.colors.white.bgRed(' ' + preffix + ' '), gutil.colors.white.bgBlue(' ' + err.message + ' '));
notifier.notify({
title: preffix,
message: err.message
});
this.emit('end');
} | function showError(preffix, err) {
gutil.log(gutil.colors.white.bgRed(' ' + preffix + ' '), gutil.colors.white.bgBlue(' ' + err.message + ' '));
notifier.notify({
title: preffix,
message: err.message
});
this.emit('end');
} |
JavaScript | function colorTimeBlocks() {
$('textarea').each(function () {
let hourNow = moment().hour();
let blockHour = parseInt($(this).attr('data-index')) + startTime;
if (hourNow > blockHour) {
$(this).removeClass('future');
$(this).removeClass('present');
$(this).addClass('past');
} else if (hourNow < blockHour) {
$(this).removeClass('past');
$(this).removeClass('present');
$(this).addClass('future');
} else {
$(this).removeClass('future');
$(this).removeClass('past');
$(this).addClass('present');
}
});
} | function colorTimeBlocks() {
$('textarea').each(function () {
let hourNow = moment().hour();
let blockHour = parseInt($(this).attr('data-index')) + startTime;
if (hourNow > blockHour) {
$(this).removeClass('future');
$(this).removeClass('present');
$(this).addClass('past');
} else if (hourNow < blockHour) {
$(this).removeClass('past');
$(this).removeClass('present');
$(this).addClass('future');
} else {
$(this).removeClass('future');
$(this).removeClass('past');
$(this).addClass('present');
}
});
} |
JavaScript | function updateEvents() {
let schedule = JSON.parse(localStorage.getItem("schedule"));
if (!schedule) {
schedule = buildDay();
};
$('textarea').each(function () {
let index = parseInt($(this).attr('data-index'));
$(this).val(schedule[index].description);
});
} | function updateEvents() {
let schedule = JSON.parse(localStorage.getItem("schedule"));
if (!schedule) {
schedule = buildDay();
};
$('textarea').each(function () {
let index = parseInt($(this).attr('data-index'));
$(this).val(schedule[index].description);
});
} |
JavaScript | function buildDay() {
let schedule = [];
for (let hour = 9; hour <= 17; hour++) {
schedule.push({hour, description: " "});
}
return schedule;
} | function buildDay() {
let schedule = [];
for (let hour = 9; hour <= 17; hour++) {
schedule.push({hour, description: " "});
}
return schedule;
} |
JavaScript | function computeSha256(body, done) {
if (util.isNode()) {
var Stream = util.stream.Stream;
var fs = __webpack_require__(5747);
if (typeof Stream === 'function' && body instanceof Stream) {
if (typeof body.path === 'string') { // assume file object
var settings = {};
if (typeof body.start === 'number') {
settings.start = body.start;
}
if (typeof body.end === 'number') {
settings.end = body.end;
}
body = fs.createReadStream(body.path, settings);
} else { // TODO support other stream types
return done(new Error('Non-file stream objects are ' +
'not supported with SigV4'));
}
}
}
util.crypto.sha256(body, 'hex', function(err, sha) {
if (err) done(err);
else done(null, sha);
});
} | function computeSha256(body, done) {
if (util.isNode()) {
var Stream = util.stream.Stream;
var fs = __webpack_require__(5747);
if (typeof Stream === 'function' && body instanceof Stream) {
if (typeof body.path === 'string') { // assume file object
var settings = {};
if (typeof body.start === 'number') {
settings.start = body.start;
}
if (typeof body.end === 'number') {
settings.end = body.end;
}
body = fs.createReadStream(body.path, settings);
} else { // TODO support other stream types
return done(new Error('Non-file stream objects are ' +
'not supported with SigV4'));
}
}
}
util.crypto.sha256(body, 'hex', function(err, sha) {
if (err) done(err);
else done(null, sha);
});
} |
JavaScript | static buildDefaultLoadHandler(loadingContainerClassName, loadingInnerClassName) {
return function(element) {
let loadingDummy = document.createElement("div");
let loadingDummyInner = document.createElement("div");
// need it because inner's properties can be overwritten
let loadingDummyInnerContainer = document.createElement("div");
loadingDummy.classList.add(loadingContainerClassName);
loadingDummyInner.classList.add(loadingInnerClassName);
loadingDummy.style.position = "relative";
loadingDummyInnerContainer.style.position = "absolute";
loadingDummyInnerContainer.style.top = "50%";
loadingDummyInnerContainer.style.left = "50%";
loadingDummyInnerContainer.style.transform = "translate(-50%, -50%)";
let loadingInnerStyle = getComputedStyle(loadingDummyInner);
loadingDummyInnerContainer.style.width = loadingInnerStyle.width;
loadingDummyInnerContainer.style.height = loadingInnerStyle.height;
loadingDummy.append(loadingDummyInnerContainer);
loadingDummyInnerContainer.append(loadingDummyInner);
// parentNode can not exist(iframes)
if(element.parentNode) element.parentNode.replaceChild(loadingDummy, element);
loadingDummy.append(element);
const visibility = element.style.visibility;
element.style.visibility = "hidden";
return function() {
if(loadingDummy.parentNode) loadingDummy.parentNode.replaceChild(element, loadingDummy);
element.style.visibility = visibility;
};
}
} | static buildDefaultLoadHandler(loadingContainerClassName, loadingInnerClassName) {
return function(element) {
let loadingDummy = document.createElement("div");
let loadingDummyInner = document.createElement("div");
// need it because inner's properties can be overwritten
let loadingDummyInnerContainer = document.createElement("div");
loadingDummy.classList.add(loadingContainerClassName);
loadingDummyInner.classList.add(loadingInnerClassName);
loadingDummy.style.position = "relative";
loadingDummyInnerContainer.style.position = "absolute";
loadingDummyInnerContainer.style.top = "50%";
loadingDummyInnerContainer.style.left = "50%";
loadingDummyInnerContainer.style.transform = "translate(-50%, -50%)";
let loadingInnerStyle = getComputedStyle(loadingDummyInner);
loadingDummyInnerContainer.style.width = loadingInnerStyle.width;
loadingDummyInnerContainer.style.height = loadingInnerStyle.height;
loadingDummy.append(loadingDummyInnerContainer);
loadingDummyInnerContainer.append(loadingDummyInner);
// parentNode can not exist(iframes)
if(element.parentNode) element.parentNode.replaceChild(loadingDummy, element);
loadingDummy.append(element);
const visibility = element.style.visibility;
element.style.visibility = "hidden";
return function() {
if(loadingDummy.parentNode) loadingDummy.parentNode.replaceChild(element, loadingDummy);
element.style.visibility = visibility;
};
}
} |
JavaScript | function throttle(func, timeout) {
let lastCalledTimestamp = 0;
return function() {
let currentTimestamp = Date.now();
// calling only if timeout has passed
if ((currentTimestamp - lastCalledTimestamp) > timeout) {
func.apply(null, arguments);
lastCalledTimestamp = currentTimestamp;
}
}
} | function throttle(func, timeout) {
let lastCalledTimestamp = 0;
return function() {
let currentTimestamp = Date.now();
// calling only if timeout has passed
if ((currentTimestamp - lastCalledTimestamp) > timeout) {
func.apply(null, arguments);
lastCalledTimestamp = currentTimestamp;
}
}
} |
JavaScript | function isFirstTimeVisitor() {
if (localStorage.getItem("firstTime") == null) {
localStorage.setItem("firstTime", true)
return true
} else {
return false
}
} | function isFirstTimeVisitor() {
if (localStorage.getItem("firstTime") == null) {
localStorage.setItem("firstTime", true)
return true
} else {
return false
}
} |
JavaScript | function populateChartData(result, country) {
let population = countryData.find(x => x.country === country).population;
console.log(country, population)
let dates = []
let active = []
let deaths = []
let confirmed = []
let recovered = []
$.each(result, function() {
//result per 100 000 inhabitants
let activePC = Math.round((this.Active/population) * 100000)
let deathsPC = Math.round((this.Deaths/population) * 100000)
let confirmedPC = Math.round((this.Confirmed/population) * 100000)
let recoveredPC = Math.round((this.Recovered/population) * 100000)
active.push(activePC)
deaths.push(deathsPC)
confirmed.push(confirmedPC)
recovered.push(recoveredPC)
dates.push(this.Date.substr(0, 10))
})
let dataset = {
country: country,
active: active,
deaths: deaths,
confirmed: confirmed,
recovered: recovered,
dates: dates
}
chartData.coronaDatasets.push(dataset)
} | function populateChartData(result, country) {
let population = countryData.find(x => x.country === country).population;
console.log(country, population)
let dates = []
let active = []
let deaths = []
let confirmed = []
let recovered = []
$.each(result, function() {
//result per 100 000 inhabitants
let activePC = Math.round((this.Active/population) * 100000)
let deathsPC = Math.round((this.Deaths/population) * 100000)
let confirmedPC = Math.round((this.Confirmed/population) * 100000)
let recoveredPC = Math.round((this.Recovered/population) * 100000)
active.push(activePC)
deaths.push(deathsPC)
confirmed.push(confirmedPC)
recovered.push(recoveredPC)
dates.push(this.Date.substr(0, 10))
})
let dataset = {
country: country,
active: active,
deaths: deaths,
confirmed: confirmed,
recovered: recovered,
dates: dates
}
chartData.coronaDatasets.push(dataset)
} |
JavaScript | function success(position) {
console.log("This is your position: ", position);
let lat = position.coords.latitude
let lng = position.coords.longitude
getCountry(lat, lng)
} | function success(position) {
console.log("This is your position: ", position);
let lat = position.coords.latitude
let lng = position.coords.longitude
getCountry(lat, lng)
} |
JavaScript | function esPar(numero){
if(numero%2 === 0)
return true;
else
return false;
} | function esPar(numero){
if(numero%2 === 0)
return true;
else
return false;
} |
JavaScript | function handler(event) {
var target = $(event.target);
var searchListEl = $(".list-item");
if (target.is(searchListEl)) {
let cityName, coordinatesQuery;
let spanEl = target.find("span");
cityName = target[0].innerText;
coordinatesQuery = spanEl[0].innerHTML.replace("amp;", "").trim();
getWeatherCurrentAndForecast(coordinatesQuery).then((response) => {
dispayCurrentWeather(response, cityName);
displayFiveDayForecast(response);
});
}
} | function handler(event) {
var target = $(event.target);
var searchListEl = $(".list-item");
if (target.is(searchListEl)) {
let cityName, coordinatesQuery;
let spanEl = target.find("span");
cityName = target[0].innerText;
coordinatesQuery = spanEl[0].innerHTML.replace("amp;", "").trim();
getWeatherCurrentAndForecast(coordinatesQuery).then((response) => {
dispayCurrentWeather(response, cityName);
displayFiveDayForecast(response);
});
}
} |
JavaScript | function backoffRequest(
requestOpts,
backoffOpts = defaultBackoffOpts,
) {
return new Promise((resolve, reject) => {
const fibonacciBackoff = backoff.fibonacci(backoffOpts);
fibonacciBackoff.failAfter(backoffOpts.failAfter);
let lastError;
let lastStatus;
fibonacciBackoff.on('ready', () => {
// Do something when backoff ends, e.g. retry a failed
// operation (DNS lookup, API call, etc.). If it fails
// again then backoff, otherwise reset the backoff
// instance.
request(requestOpts, (error, res) => {
// body should be a string or buffer
if (error || res.statusCode !== 200) {
lastError = error;
lastStatus = res.statusCode;
fibonacciBackoff.backoff();
} else {
fibonacciBackoff.reset();
resolve(res);
}
});
});
fibonacciBackoff.on('fail', () => {
// Do something when the maximum number of backoffs is
// reached, e.g. ask the user to check its connection.
reject(new Error({ lastError, lastStatus }));
});
fibonacciBackoff.backoff();
});
} | function backoffRequest(
requestOpts,
backoffOpts = defaultBackoffOpts,
) {
return new Promise((resolve, reject) => {
const fibonacciBackoff = backoff.fibonacci(backoffOpts);
fibonacciBackoff.failAfter(backoffOpts.failAfter);
let lastError;
let lastStatus;
fibonacciBackoff.on('ready', () => {
// Do something when backoff ends, e.g. retry a failed
// operation (DNS lookup, API call, etc.). If it fails
// again then backoff, otherwise reset the backoff
// instance.
request(requestOpts, (error, res) => {
// body should be a string or buffer
if (error || res.statusCode !== 200) {
lastError = error;
lastStatus = res.statusCode;
fibonacciBackoff.backoff();
} else {
fibonacciBackoff.reset();
resolve(res);
}
});
});
fibonacciBackoff.on('fail', () => {
// Do something when the maximum number of backoffs is
// reached, e.g. ask the user to check its connection.
reject(new Error({ lastError, lastStatus }));
});
fibonacciBackoff.backoff();
});
} |
JavaScript | function Annotator() {
this.wavesurfer;
this.playBar;
this.stages;
this.workflowBtns;
this.currentTask;
this.taskStartTime;
this.hiddenImage;
// only automatically open instructions modal when first loaded
this.instructionsViewed = false;
// Boolean, true if currently sending http post request
this.sendingResponse = false;
// Create color map for spectrogram
var spectrogramColorMap = colormap({
colormap: magma,
nshades: 256,
format: 'rgb',
alpha: 1
});
// Create wavesurfer (audio visualization component)
var height = 256;
this.wavesurfer = Object.create(WaveSurfer);
this.wavesurfer.init({
container: '.audio_visual',
waveColor: '#FF00FF',
progressColor: '#FF00FF',
// For the spectrogram the height is half the number of fftSamples
fftSamples: height * 2,
height: height,
colorMap: spectrogramColorMap
});
// Create labels (labels that appear above each region)
var labels = Object.create(WaveSurfer.Labels);
labels.init({
wavesurfer: this.wavesurfer,
container: '.labels'
});
// Create hiddenImage, an image that is slowly revealed to a user as they annotate
// (only for this.currentTask.feedback === 'hiddenImage')
this.hiddenImage = new HiddenImg('.hidden_img', 100);
this.hiddenImage.create();
// Create the play button and time that appear below the wavesurfer
this.playBar = new PlayBar(this.wavesurfer);
this.playBar.create();
// Create the annotation stages that appear below the wavesurfer. The stages contain tags
// the users use to label a region in the audio clip
this.stages = new AnnotationStages(this.wavesurfer, this.hiddenImage);
this.stages.create();
// Create Workflow btns (submit and exit)
this.workflowBtns = new WorkflowBtns();
this.workflowBtns.create();
this.addEvents();
} | function Annotator() {
this.wavesurfer;
this.playBar;
this.stages;
this.workflowBtns;
this.currentTask;
this.taskStartTime;
this.hiddenImage;
// only automatically open instructions modal when first loaded
this.instructionsViewed = false;
// Boolean, true if currently sending http post request
this.sendingResponse = false;
// Create color map for spectrogram
var spectrogramColorMap = colormap({
colormap: magma,
nshades: 256,
format: 'rgb',
alpha: 1
});
// Create wavesurfer (audio visualization component)
var height = 256;
this.wavesurfer = Object.create(WaveSurfer);
this.wavesurfer.init({
container: '.audio_visual',
waveColor: '#FF00FF',
progressColor: '#FF00FF',
// For the spectrogram the height is half the number of fftSamples
fftSamples: height * 2,
height: height,
colorMap: spectrogramColorMap
});
// Create labels (labels that appear above each region)
var labels = Object.create(WaveSurfer.Labels);
labels.init({
wavesurfer: this.wavesurfer,
container: '.labels'
});
// Create hiddenImage, an image that is slowly revealed to a user as they annotate
// (only for this.currentTask.feedback === 'hiddenImage')
this.hiddenImage = new HiddenImg('.hidden_img', 100);
this.hiddenImage.create();
// Create the play button and time that appear below the wavesurfer
this.playBar = new PlayBar(this.wavesurfer);
this.playBar.create();
// Create the annotation stages that appear below the wavesurfer. The stages contain tags
// the users use to label a region in the audio clip
this.stages = new AnnotationStages(this.wavesurfer, this.hiddenImage);
this.stages.create();
// Create Workflow btns (submit and exit)
this.workflowBtns = new WorkflowBtns();
this.workflowBtns.create();
this.addEvents();
} |
JavaScript | function StageThreeView() {
this.dom = null;
this.editOptionsDom = null;
// Note that this assumes there are never more than 3 proximity labels
this.colors = ['#870f4f', '#000080', '#6a1b9a'];
this.colors.forEach(function (color, index) {
$('<style>.proximity1_tag:hover,.proximity' + index + '_tag.selected{background-color: ' + color + '}</style>').appendTo('head');
});
} | function StageThreeView() {
this.dom = null;
this.editOptionsDom = null;
// Note that this assumes there are never more than 3 proximity labels
this.colors = ['#870f4f', '#000080', '#6a1b9a'];
this.colors.forEach(function (color, index) {
$('<style>.proximity1_tag:hover,.proximity' + index + '_tag.selected{background-color: ' + color + '}</style>').appendTo('head');
});
} |
JavaScript | function AnnotationStages(wavesurfer, hiddenImage) {
this.currentStage = 0;
this.currentRegion = null;
this.usingProximity = false;
this.stageOneView = new StageOneView();
this.stageTwoView = new StageTwoView();
this.stageThreeView = new StageThreeView();
this.wavesurfer = wavesurfer;
this.hiddenImage = hiddenImage;
this.deletedAnnotations = [];
this.annotationSolutions = [];
this.city = '';
this.previousF1Score = 0;
this.events = [];
this.alwaysShowTags = false;
// These are not reset, since they should only be shown for the first clip
this.shownTagHint = false;
this.shownSelectHint = false;
this.blockDeselect = false;
} | function AnnotationStages(wavesurfer, hiddenImage) {
this.currentStage = 0;
this.currentRegion = null;
this.usingProximity = false;
this.stageOneView = new StageOneView();
this.stageTwoView = new StageTwoView();
this.stageThreeView = new StageThreeView();
this.wavesurfer = wavesurfer;
this.hiddenImage = hiddenImage;
this.deletedAnnotations = [];
this.annotationSolutions = [];
this.city = '';
this.previousF1Score = 0;
this.events = [];
this.alwaysShowTags = false;
// These are not reset, since they should only be shown for the first clip
this.shownTagHint = false;
this.shownSelectHint = false;
this.blockDeselect = false;
} |
JavaScript | function PlayBar(wavesurfer) {
this.wavesurfer = wavesurfer;
// Dom element containing play button and progress timestamp
this.playBarDom = null;
// List of user actions (click-pause, click-play, spacebar-pause, spacebar-play) with
// timestamps of when the user took the action
this.events = [];
} | function PlayBar(wavesurfer) {
this.wavesurfer = wavesurfer;
// Dom element containing play button and progress timestamp
this.playBarDom = null;
// List of user actions (click-pause, click-play, spacebar-pause, spacebar-play) with
// timestamps of when the user took the action
this.events = [];
} |
JavaScript | function WorkflowBtns(exitUrl) {
// Dom of submit and load next btn
this.nextBtn = null;
// Dom of exit task btn
this.exitBtn = null;
// The url the user will be directed to when they exit
this.exitUrl = exitUrl;
// Boolean that determined if the exit button is shown
this.showExitBtn = false;
} | function WorkflowBtns(exitUrl) {
// Dom of submit and load next btn
this.nextBtn = null;
// Dom of exit task btn
this.exitBtn = null;
// The url the user will be directed to when they exit
this.exitUrl = exitUrl;
// Boolean that determined if the exit button is shown
this.showExitBtn = false;
} |
JavaScript | function HiddenImg(container, height, width) {
this.container = document.querySelector(container);
this.canvas = null;
this.height = height;
this.width = this.container.offsetWidth;
this.shuffleTitles = [];
} | function HiddenImg(container, height, width) {
this.container = document.querySelector(container);
this.canvas = null;
this.height = height;
this.width = this.container.offsetWidth;
this.shuffleTitles = [];
} |
JavaScript | function buildInquirerChoices(cards) {
return cards.cards.map(card => {
const _default = card.id === cards.defaultCardId
? ' ' + chalk.bold('(default)')
: '';
const id = `${chalk.cyan(`ID: ${card.id}`)}${_default}`;
const number = `${chalk.gray('#### ').repeat(3)}${card.last4}`;
const str = [
id,
indent(card.name, 2),
indent(`${card.brand} ${number}`, 2)
].join('\n');
return {
name: str, // Will be displayed by Inquirer
value: card.id, // Will be used to identify the answer
short: card.id // Will be displayed after the users answers
};
});
} | function buildInquirerChoices(cards) {
return cards.cards.map(card => {
const _default = card.id === cards.defaultCardId
? ' ' + chalk.bold('(default)')
: '';
const id = `${chalk.cyan(`ID: ${card.id}`)}${_default}`;
const number = `${chalk.gray('#### ').repeat(3)}${card.last4}`;
const str = [
id,
indent(card.name, 2),
indent(`${card.brand} ${number}`, 2)
].join('\n');
return {
name: str, // Will be displayed by Inquirer
value: card.id, // Will be used to identify the answer
short: card.id // Will be displayed after the users answers
};
});
} |
JavaScript | async function main(username = 'testuser') {
try {
let result = {};
// load the network configuration
const ccpPath = path.resolve(__dirname, '..', '..', 'test-network', 'organizations', 'peerOrganizations', 'org1.example.com', 'connection-org1.json');
const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
// Create a new CA client for interacting with the CA.
const caURL = ccp.certificateAuthorities['ca.org1.example.com'].url;
const ca = new FabricCAServices(caURL);
// Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = await Wallets.newFileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
// Check to see if we've already enrolled the user.
const userIdentity = await wallet.get(username);
if (userIdentity) {
result.message = `An identity for the user ${username} already exists in the wallet`;
result.result = false;
return result;
}
// Check to see if we've already enrolled the admin user.
// The admin user need to exist within the network to register other users.
const adminIdentity = await wallet.get('admin');
if (!adminIdentity) {
result.result = false;
result.message = 'An identity for the admin user "admin" does not exist in the wallet. Run enrollAdmin.js first.';
return result;
}
// build a user object for authenticating with the CA
const provider = wallet.getProviderRegistry().getProvider(adminIdentity.type);
const adminUser = await provider.getUserContext(adminIdentity, 'admin');
// Register the user, enroll the user, and import the new identity into the wallet.
const secret = await ca.register({
affiliation: 'org1.department1',
enrollmentID: username,
role: 'client'
}, adminUser);
const enrollment = await ca.enroll({
enrollmentID: username,
enrollmentSecret: secret
});
const x509Identity = {
credentials: {
certificate: enrollment.certificate,
privateKey: enrollment.key.toBytes(),
},
mspId: 'Org1MSP',
type: 'X.509',
};
await wallet.put(username, x509Identity);
result.message = `Successfully registered and enrolled admin user ${username} and imported it into the wallet`;
result.result = true;
return result;
} catch (error) {
console.error(`Failed to register user : ${error}`);
process.exit(1);
}
} | async function main(username = 'testuser') {
try {
let result = {};
// load the network configuration
const ccpPath = path.resolve(__dirname, '..', '..', 'test-network', 'organizations', 'peerOrganizations', 'org1.example.com', 'connection-org1.json');
const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
// Create a new CA client for interacting with the CA.
const caURL = ccp.certificateAuthorities['ca.org1.example.com'].url;
const ca = new FabricCAServices(caURL);
// Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = await Wallets.newFileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
// Check to see if we've already enrolled the user.
const userIdentity = await wallet.get(username);
if (userIdentity) {
result.message = `An identity for the user ${username} already exists in the wallet`;
result.result = false;
return result;
}
// Check to see if we've already enrolled the admin user.
// The admin user need to exist within the network to register other users.
const adminIdentity = await wallet.get('admin');
if (!adminIdentity) {
result.result = false;
result.message = 'An identity for the admin user "admin" does not exist in the wallet. Run enrollAdmin.js first.';
return result;
}
// build a user object for authenticating with the CA
const provider = wallet.getProviderRegistry().getProvider(adminIdentity.type);
const adminUser = await provider.getUserContext(adminIdentity, 'admin');
// Register the user, enroll the user, and import the new identity into the wallet.
const secret = await ca.register({
affiliation: 'org1.department1',
enrollmentID: username,
role: 'client'
}, adminUser);
const enrollment = await ca.enroll({
enrollmentID: username,
enrollmentSecret: secret
});
const x509Identity = {
credentials: {
certificate: enrollment.certificate,
privateKey: enrollment.key.toBytes(),
},
mspId: 'Org1MSP',
type: 'X.509',
};
await wallet.put(username, x509Identity);
result.message = `Successfully registered and enrolled admin user ${username} and imported it into the wallet`;
result.result = true;
return result;
} catch (error) {
console.error(`Failed to register user : ${error}`);
process.exit(1);
}
} |
JavaScript | and() {
// Get the last where query.
if(this.query[this.last].length === 0) {
throw new Error('No ' + this.last + ' clauses found!');
}
var item = this.query[this.last][this.query[this.last].length - 1];
item.next = 'and';
return this;
} | and() {
// Get the last where query.
if(this.query[this.last].length === 0) {
throw new Error('No ' + this.last + ' clauses found!');
}
var item = this.query[this.last][this.query[this.last].length - 1];
item.next = 'and';
return this;
} |
JavaScript | or() {
if(this.query[this.last].length === 0) {
throw new Error('No ' + this.last + ' clauses found!');
}
var item = this.query[this.last][this.query[this.last].length - 1];
item.next = 'or';
return this;
} | or() {
if(this.query[this.last].length === 0) {
throw new Error('No ' + this.last + ' clauses found!');
}
var item = this.query[this.last][this.query[this.last].length - 1];
item.next = 'or';
return this;
} |
JavaScript | select(name, alias) {
this.last = 'select';
if(name.toString() === '[object Object]') {
for(var index in name) {
if(name.hasOwnProperty(index)) {
this.select(index, (name[index] || null));
}
}
} else {
if(!this.query.columns[name]) {
this.query.columns.push({
name: name,
alias: alias
});
}
}
return this;
} | select(name, alias) {
this.last = 'select';
if(name.toString() === '[object Object]') {
for(var index in name) {
if(name.hasOwnProperty(index)) {
this.select(index, (name[index] || null));
}
}
} else {
if(!this.query.columns[name]) {
this.query.columns.push({
name: name,
alias: alias
});
}
}
return this;
} |
JavaScript | count(column, alias) {
this.query.count.column = column;
this.query.count.alias = alias;
return this;
} | count(column, alias) {
this.query.count.column = column;
this.query.count.alias = alias;
return this;
} |
JavaScript | from(table, alias) {
this.last = 'from';
this.query.from = {
table: table,
alias: alias
};
return this;
} | from(table, alias) {
this.last = 'from';
this.query.from = {
table: table,
alias: alias
};
return this;
} |
JavaScript | limit(limit) {
this.query.limit = limit;
return this;
} | limit(limit) {
this.query.limit = limit;
return this;
} |
Subsets and Splits