language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | noContentHandler_() {
// If a fallback does not exist attempt to collapse the ad.
if (!this.fallback_) {
this.attemptChangeHeight(0, () => {
this.element.style.display = 'none';
});
}
this.deferMutate(() => {
if (this.fallback_) {
this.toggleFallback(true);
}
this.element.removeChild(this.iframe_);
});
} | noContentHandler_() {
// If a fallback does not exist attempt to collapse the ad.
if (!this.fallback_) {
this.attemptChangeHeight(0, () => {
this.element.style.display = 'none';
});
}
this.deferMutate(() => {
if (this.fallback_) {
this.toggleFallback(true);
}
this.element.removeChild(this.iframe_);
});
} |
JavaScript | dismiss() {
this.element.classList.remove('amp-active');
this.element.classList.add('amp-hidden');
this.dialogResolve_();
// Store and post.
if (this.storageKey_) {
this.storagePromise_.then(storage => {
storage.set(this.storageKey_, true);
});
}
if (this.dismissHref_) {
this.postDismissEnpoint_();
}
} | dismiss() {
this.element.classList.remove('amp-active');
this.element.classList.add('amp-hidden');
this.dialogResolve_();
// Store and post.
if (this.storageKey_) {
this.storagePromise_.then(storage => {
storage.set(this.storageKey_, true);
});
}
if (this.dismissHref_) {
this.postDismissEnpoint_();
}
} |
JavaScript | createOrReturnDefer_(id) {
if (this.deferRegistry_[id]) {
return this.deferRegistry_[id];
}
let resolve;
const promise = new Promise(r => {
resolve = r;
});
return this.deferRegistry_[id] = {
promise: promise,
resolve: resolve
};
} | createOrReturnDefer_(id) {
if (this.deferRegistry_[id]) {
return this.deferRegistry_[id];
}
let resolve;
const promise = new Promise(r => {
resolve = r;
});
return this.deferRegistry_[id] = {
promise: promise,
resolve: resolve
};
} |
JavaScript | function assertSuccess(response) {
if (response.status < 200 || response.status > 299) {
throw new Error(`HTTP error ${response.status}`);
}
return response;
} | function assertSuccess(response) {
if (response.status < 200 || response.status > 299) {
throw new Error(`HTTP error ${response.status}`);
}
return response;
} |
JavaScript | function computeInMasterFrame(global, taskId, work, cb) {
const master = global.context.master;
let tasks = master.__ampMasterTasks;
if (!tasks) {
tasks = master.__ampMasterTasks = {};
}
let cbs = tasks[taskId];
if (!tasks[taskId]) {
cbs = tasks[taskId] = [];
}
cbs.push(cb);
if (!global.context.isMaster) {
return; // Only do work in master.
}
work(result => {
for (let i = 0; i < cbs.length; i++) {
cbs[i].call(null, result);
}
tasks[taskId] = {
push: function(cb) {
cb(result);
}
};
});
} | function computeInMasterFrame(global, taskId, work, cb) {
const master = global.context.master;
let tasks = master.__ampMasterTasks;
if (!tasks) {
tasks = master.__ampMasterTasks = {};
}
let cbs = tasks[taskId];
if (!tasks[taskId]) {
cbs = tasks[taskId] = [];
}
cbs.push(cb);
if (!global.context.isMaster) {
return; // Only do work in master.
}
work(result => {
for (let i = 0; i < cbs.length; i++) {
cbs[i].call(null, result);
}
tasks[taskId] = {
push: function(cb) {
cb(result);
}
};
});
} |
JavaScript | function validateExactlyOne(data, alternativeFields) {
let countFileds = 0;
for (let i = 0; i < alternativeFields.length; i++) {
const field = alternativeFields[i];
if (data[field]) {
countFileds += 1;
}
}
assert(countFileds === 1,
'%s must contain exactly one of attributes: %s.',
data.type,
alternativeFields.join(', '));
} | function validateExactlyOne(data, alternativeFields) {
let countFileds = 0;
for (let i = 0; i < alternativeFields.length; i++) {
const field = alternativeFields[i];
if (data[field]) {
countFileds += 1;
}
}
assert(countFileds === 1,
'%s must contain exactly one of attributes: %s.',
data.type,
alternativeFields.join(', '));
} |
JavaScript | receiveMessage(eventType, data, unusedAwaitResponse) {
if (eventType == 'viewport') {
if (data['width'] !== undefined) {
this.viewportWidth_ = data['width'];
}
if (data['height'] !== undefined) {
this.viewportHeight_ = data['height'];
}
if (data['paddingTop'] !== undefined) {
this.paddingTop_ = data['paddingTop'];
}
if (data['scrollTop'] !== undefined) {
this./*OK*/scrollTop_ = data['scrollTop'];
}
this.viewportObservable_.fire();
return undefined;
}
if (eventType == 'historyPopped') {
this.historyPoppedObservable_.fire({
newStackIndex: data['newStackIndex']
});
return Promise.resolve();
}
if (eventType == 'visibilitychange') {
if (data['state'] !== undefined) {
this.visibilityState_ = data['state'];
}
if (data['prerenderSize'] !== undefined) {
this.prerenderSize_ = data['prerenderSize'];
}
log.fine(TAG_, 'visibilitychange event:', this.visibilityState_,
this.prerenderSize_);
this.onVisibilityChange_();
return Promise.resolve();
}
if (eventType == 'broadcast') {
this.broadcastObservable_.fire(data);
return Promise.resolve();
}
log.fine(TAG_, 'unknown message:', eventType);
return undefined;
} | receiveMessage(eventType, data, unusedAwaitResponse) {
if (eventType == 'viewport') {
if (data['width'] !== undefined) {
this.viewportWidth_ = data['width'];
}
if (data['height'] !== undefined) {
this.viewportHeight_ = data['height'];
}
if (data['paddingTop'] !== undefined) {
this.paddingTop_ = data['paddingTop'];
}
if (data['scrollTop'] !== undefined) {
this./*OK*/scrollTop_ = data['scrollTop'];
}
this.viewportObservable_.fire();
return undefined;
}
if (eventType == 'historyPopped') {
this.historyPoppedObservable_.fire({
newStackIndex: data['newStackIndex']
});
return Promise.resolve();
}
if (eventType == 'visibilitychange') {
if (data['state'] !== undefined) {
this.visibilityState_ = data['state'];
}
if (data['prerenderSize'] !== undefined) {
this.prerenderSize_ = data['prerenderSize'];
}
log.fine(TAG_, 'visibilitychange event:', this.visibilityState_,
this.prerenderSize_);
this.onVisibilityChange_();
return Promise.resolve();
}
if (eventType == 'broadcast') {
this.broadcastObservable_.fire(data);
return Promise.resolve();
}
log.fine(TAG_, 'unknown message:', eventType);
return undefined;
} |
JavaScript | function addDataAndJsonAttributes_(element, attributes) {
for (let i = 0; i < element.attributes.length; i++) {
const attr = element.attributes[i];
if (attr.name.indexOf('data-') != 0) {
continue;
}
attributes[dashToCamelCase(attr.name.substr(5))] = attr.value;
}
const json = element.getAttribute('json');
if (json) {
let obj;
try {
obj = JSON.parse(json);
} catch (e) {
assert(false, 'Error parsing JSON in json attribute in element %s',
element);
}
for (const key in obj) {
attributes[key] = obj[key];
}
}
} | function addDataAndJsonAttributes_(element, attributes) {
for (let i = 0; i < element.attributes.length; i++) {
const attr = element.attributes[i];
if (attr.name.indexOf('data-') != 0) {
continue;
}
attributes[dashToCamelCase(attr.name.substr(5))] = attr.value;
}
const json = element.getAttribute('json');
if (json) {
let obj;
try {
obj = JSON.parse(json);
} catch (e) {
assert(false, 'Error parsing JSON in json attribute in element %s',
element);
}
for (const key in obj) {
attributes[key] = obj[key];
}
}
} |
JavaScript | function listen(iframe, typeOfMessage, callback, opt_is3P) {
assert(iframe.src, 'only iframes with src supported');
const origin = parseUrl(iframe.src).origin;
const win = iframe.ownerDocument.defaultView;
const sentinel = getSentinel_(opt_is3P);
const listener = function(event) {
if (event.origin != origin) {
return;
}
if (event.source != iframe.contentWindow) {
return;
}
if (!event.data || event.data.sentinel != sentinel) {
return;
}
if (event.data.type != typeOfMessage) {
return;
}
callback(event.data);
};
win.addEventListener('message', listener);
return function() {
win.removeEventListener('message', listener);
};
} | function listen(iframe, typeOfMessage, callback, opt_is3P) {
assert(iframe.src, 'only iframes with src supported');
const origin = parseUrl(iframe.src).origin;
const win = iframe.ownerDocument.defaultView;
const sentinel = getSentinel_(opt_is3P);
const listener = function(event) {
if (event.origin != origin) {
return;
}
if (event.source != iframe.contentWindow) {
return;
}
if (!event.data || event.data.sentinel != sentinel) {
return;
}
if (event.data.type != typeOfMessage) {
return;
}
callback(event.data);
};
win.addEventListener('message', listener);
return function() {
win.removeEventListener('message', listener);
};
} |
JavaScript | coreServicesAvailable() {
this.viewer_ = viewerFor(this.win);
this.resources_ = resourcesFor(this.win);
this.viewer_.onVisibilityChanged(this.flush.bind(this));
this.measureUserPerceivedVisualCompletenessTime_();
} | coreServicesAvailable() {
this.viewer_ = viewerFor(this.win);
this.resources_ = resourcesFor(this.win);
this.viewer_.onVisibilityChanged(this.flush.bind(this));
this.measureUserPerceivedVisualCompletenessTime_();
} |
JavaScript | whenViewportLayoutComplete_() {
return this.whenReadyToRetrieveResources_().then(() => {
return all(this.resources_.getResourcesInViewport().map(r => {
// We're ok with the layout failing and still reporting.
return r.loaded().catch(function() {});
}));
});
} | whenViewportLayoutComplete_() {
return this.whenReadyToRetrieveResources_().then(() => {
return all(this.resources_.getResourcesInViewport().map(r => {
// We're ok with the layout failing and still reporting.
return r.loaded().catch(function() {});
}));
});
} |
JavaScript | function manageWin(win) {
try {
manageWin_(win);
} catch (e) {
// We use a try block, because the ad integrations often swallow errors.
console./*OK*/error(e.message, e.stack);
}
} | function manageWin(win) {
try {
manageWin_(win);
} catch (e) {
// We use a try block, because the ad integrations often swallow errors.
console./*OK*/error(e.message, e.stack);
}
} |
JavaScript | function installObserver(win) {
if (!window.MutationObserver) {
return;
}
const observer = new MutationObserver(function(mutations) {
for (let i = 0; i < mutations.length; i++) {
maybeInstrumentsNodes(win, mutations[i].addedNodes);
}
});
observer.observe(win.document.documentElement, {
subtree: true,
childList: true,
});
} | function installObserver(win) {
if (!window.MutationObserver) {
return;
}
const observer = new MutationObserver(function(mutations) {
for (let i = 0; i < mutations.length; i++) {
maybeInstrumentsNodes(win, mutations[i].addedNodes);
}
});
observer.observe(win.document.documentElement, {
subtree: true,
childList: true,
});
} |
JavaScript | function instrumentEntryPoints(win) {
// Change setTimeout to respect a minimum timeout.
const setTimeout = win.setTimeout;
win.setTimeout = function(fn, time) {
time = minTime(time);
return setTimeout(fn, time);
};
// Implement setInterval in terms of setTimeout to make
// it respect the same rules
const intervals = {};
let intervalId = 0;
win.setInterval = function(fn, time) {
const id = intervalId++;
function next() {
intervals[id] = win.setTimeout(function() {
next();
return fn.apply(this, arguments);
}, time);
}
next();
return id;
};
win.clearInterval = function(id) {
win.clearTimeout(intervals[id]);
delete intervals[id];
};
// Throttle requestAnimationFrame.
const requestAnimationFrame = win.requestAnimationFrame ||
win.webkitRequestAnimationFrame;
win.requestAnimationFrame = function(cb) {
if (!inViewport) {
// If the doc is not visible, queue up the frames until we become
// visible again.
const id = rafId++;
rafQueue[id] = [win, cb];
// Only queue 20 frame requests to avoid mem leaks.
delete rafQueue[id - 20];
return id;
}
return requestAnimationFrame.call(this, cb);
};
const cancelAnimationFrame = win.cancelAnimationFrame;
win.cancelAnimationFrame = function(id) {
cancelAnimationFrame.call(this, id);
delete rafQueue[id];
};
if (win.webkitRequestAnimationFrame) {
win.webkitRequestAnimationFrame = win.requestAnimationFrame;
win.webkitCancelAnimationFrame = win.webkitCancelRequestAnimationFrame =
win.cancelAnimationFrame;
}
} | function instrumentEntryPoints(win) {
// Change setTimeout to respect a minimum timeout.
const setTimeout = win.setTimeout;
win.setTimeout = function(fn, time) {
time = minTime(time);
return setTimeout(fn, time);
};
// Implement setInterval in terms of setTimeout to make
// it respect the same rules
const intervals = {};
let intervalId = 0;
win.setInterval = function(fn, time) {
const id = intervalId++;
function next() {
intervals[id] = win.setTimeout(function() {
next();
return fn.apply(this, arguments);
}, time);
}
next();
return id;
};
win.clearInterval = function(id) {
win.clearTimeout(intervals[id]);
delete intervals[id];
};
// Throttle requestAnimationFrame.
const requestAnimationFrame = win.requestAnimationFrame ||
win.webkitRequestAnimationFrame;
win.requestAnimationFrame = function(cb) {
if (!inViewport) {
// If the doc is not visible, queue up the frames until we become
// visible again.
const id = rafId++;
rafQueue[id] = [win, cb];
// Only queue 20 frame requests to avoid mem leaks.
delete rafQueue[id - 20];
return id;
}
return requestAnimationFrame.call(this, cb);
};
const cancelAnimationFrame = win.cancelAnimationFrame;
win.cancelAnimationFrame = function(id) {
cancelAnimationFrame.call(this, id);
delete rafQueue[id];
};
if (win.webkitRequestAnimationFrame) {
win.webkitRequestAnimationFrame = win.requestAnimationFrame;
win.webkitCancelAnimationFrame = win.webkitCancelRequestAnimationFrame =
win.cancelAnimationFrame;
}
} |
JavaScript | function becomeVisible() {
for (const id in rafQueue) {
if (rafQueue.hasOwnProperty(id)) {
const f = rafQueue[id];
f[0].requestAnimationFrame(f[1]);
}
}
rafQueue = {};
} | function becomeVisible() {
for (const id in rafQueue) {
if (rafQueue.hasOwnProperty(id)) {
const f = rafQueue[id];
f[0].requestAnimationFrame(f[1]);
}
}
rafQueue = {};
} |
JavaScript | function trySetCookie(win, name, value, expirationTime, domain) {
win.document.cookie = encodeURIComponent(name) + '=' +
encodeURIComponent(value) +
'; path=/' +
(domain ? '; domain=' + domain : '') +
'; expires=' + new Date(expirationTime).toUTCString();
} | function trySetCookie(win, name, value, expirationTime, domain) {
win.document.cookie = encodeURIComponent(name) + '=' +
encodeURIComponent(value) +
'; path=/' +
(domain ? '; domain=' + domain : '') +
'; expires=' + new Date(expirationTime).toUTCString();
} |
JavaScript | function csv_to_JSON(csv) {
var lines = csv.split("\n");
var result = [];
var headers = lines[0].split(",");
for (var i = 1; i < lines.length; i++) {
var obj = {};
var currentline = lines[i].split(",");
for (var j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
// console.log(result);
return result; //JavaScript object
// return JSON.stringify(result); //JSON
} | function csv_to_JSON(csv) {
var lines = csv.split("\n");
var result = [];
var headers = lines[0].split(",");
for (var i = 1; i < lines.length; i++) {
var obj = {};
var currentline = lines[i].split(",");
for (var j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
// console.log(result);
return result; //JavaScript object
// return JSON.stringify(result); //JSON
} |
JavaScript | DFSUtil(vert, visited) {
visited[vert] = true;
document.write(vert);
var get_neighbours = this.AdjList.get(vert);
for (var i in get_neighbours) {
var get_elem = get_neighbours[i];
if (!visited[get_elem])
this.DFSUtil(get_elem, visited);
}
} | DFSUtil(vert, visited) {
visited[vert] = true;
document.write(vert);
var get_neighbours = this.AdjList.get(vert);
for (var i in get_neighbours) {
var get_elem = get_neighbours[i];
if (!visited[get_elem])
this.DFSUtil(get_elem, visited);
}
} |
JavaScript | function highZ(parent, limit){
limit = limit || Infinity;
parent = parent || document.body;
var who, temp, max= 1, A= [], i= 0;
var children = parent.childNodes, length = children.length;
while(i<length){
who = children[i++];
if (who.nodeType != 1) continue;
if (deepCss(who,"position") !== "static") { // element nodes only
temp = deepCss(who,"z-index");
if (temp == "auto") { // z-index is auto, so not a new stacking context
temp = highZ(who);
} else {
temp = parseInt(temp, 10) || 0;
}
} else { // non-positioned element, so not a new stacking context
temp = highZ(who);
}
if (temp > max && temp <= limit) max = temp;
}
return max;
} | function highZ(parent, limit){
limit = limit || Infinity;
parent = parent || document.body;
var who, temp, max= 1, A= [], i= 0;
var children = parent.childNodes, length = children.length;
while(i<length){
who = children[i++];
if (who.nodeType != 1) continue;
if (deepCss(who,"position") !== "static") { // element nodes only
temp = deepCss(who,"z-index");
if (temp == "auto") { // z-index is auto, so not a new stacking context
temp = highZ(who);
} else {
temp = parseInt(temp, 10) || 0;
}
} else { // non-positioned element, so not a new stacking context
temp = highZ(who);
}
if (temp > max && temp <= limit) max = temp;
}
return max;
} |
JavaScript | function exec_callback(args) {
if (callback_func && (callback_force || !con || !con.log)) {
callback_func.apply(window, args);
}
} | function exec_callback(args) {
if (callback_func && (callback_force || !con || !con.log)) {
callback_func.apply(window, args);
}
} |
JavaScript | function build_url( url, params, merge_mode, fragment_mode ) {
var qs,
re = fragment_mode
? /^([^#]*)[#]?(.*)$/
: /^([^#?]*)[?]?([^#]*)(#?.*)/,
matches = url.match( re ),
url_params = deserialize( matches[2], 0, fragment_mode ),
hash = matches[3] || '';
if ( is_string(params) ) {
params = deserialize( params, 0, fragment_mode );
}
if ( merge_mode === 2 ) {
qs = params;
} else if ( merge_mode === 1 ) {
qs = $.extend( {}, params, url_params );
} else {
qs = $.extend( {}, url_params, params );
}
qs = $.param( qs );
return matches[1] + ( fragment_mode ? '#' : qs || !matches[1] ? '?' : '' ) + qs + hash;
} | function build_url( url, params, merge_mode, fragment_mode ) {
var qs,
re = fragment_mode
? /^([^#]*)[#]?(.*)$/
: /^([^#?]*)[?]?([^#]*)(#?.*)/,
matches = url.match( re ),
url_params = deserialize( matches[2], 0, fragment_mode ),
hash = matches[3] || '';
if ( is_string(params) ) {
params = deserialize( params, 0, fragment_mode );
}
if ( merge_mode === 2 ) {
qs = params;
} else if ( merge_mode === 1 ) {
qs = $.extend( {}, params, url_params );
} else {
qs = $.extend( {}, url_params, params );
}
qs = $.param( qs );
return matches[1] + ( fragment_mode ? '#' : qs || !matches[1] ? '?' : '' ) + qs + hash;
} |
JavaScript | function ie_history() {
var iframe,
browser = $.browser,
that = {};
that[str_update] = that[str_fragment] = function( val ){ return val; };
if ( browser.msie && browser.version < 8 ) {
that[str_update] = function( frag, ie_frag ) {
var doc = iframe.document;
if ( frag !== ie_frag ) {
doc.open();
doc.close();
doc.location.hash = '#' + frag;
}
};
that[str_fragment] = function() {
return iframe.document.location.hash.replace( /^#/, '' );
};
iframe = $('<iframe/>').hide().appendTo( 'body' )
.get(0).contentWindow;
that[str_update]( get_fragment() );
}
return that;
} | function ie_history() {
var iframe,
browser = $.browser,
that = {};
that[str_update] = that[str_fragment] = function( val ){ return val; };
if ( browser.msie && browser.version < 8 ) {
that[str_update] = function( frag, ie_frag ) {
var doc = iframe.document;
if ( frag !== ie_frag ) {
doc.open();
doc.close();
doc.location.hash = '#' + frag;
}
};
that[str_fragment] = function() {
return iframe.document.location.hash.replace( /^#/, '' );
};
iframe = $('<iframe/>').hide().appendTo( 'body' )
.get(0).contentWindow;
that[str_update]( get_fragment() );
}
return that;
} |
JavaScript | function parseMessage(line) { // {{{
var message = {};
var match;
// Parse prefix
if ( match = line.match(/^:([^ ]+) +/) ) {
message.prefix = match[1];
line = line.replace(/^:[^ ]+ +/, '');
if ( match = message.prefix.match(/^([_a-zA-Z0-9\[\]\\`^{}|-]*)(!([^@]+)@(.*))?$/) ) {
message.nick = match[1];
message.user = match[3];
message.host = match[4];
}
else {
message.server = message.prefix;
}
}
// Parse command
match = line.match(/^([^ ]+) +/);
message.command = match[1];
message.rawCommand = match[1];
message.commandType = 'normal';
line = line.replace(/^[^ ]+ +/, '');
if ( replyFor[message.rawCommand] ) {
message.command = replyFor[message.rawCommand].name;
message.commandType = replyFor[message.rawCommand].type;
}
message.args = [];
var middle, trailing;
// Parse parameters
if ( line.indexOf(':') != -1 ) {
var index = line.indexOf(':');
middle = line.substr(0, index).replace(/ +$/, "");
trailing = line.substr(index+1);
}
else {
middle = line;
}
if ( middle.length )
message.args = middle.split(/ +/);
if ( typeof(trailing) != 'undefined' && trailing.length )
message.args.push(trailing);
return message;
} // }}} | function parseMessage(line) { // {{{
var message = {};
var match;
// Parse prefix
if ( match = line.match(/^:([^ ]+) +/) ) {
message.prefix = match[1];
line = line.replace(/^:[^ ]+ +/, '');
if ( match = message.prefix.match(/^([_a-zA-Z0-9\[\]\\`^{}|-]*)(!([^@]+)@(.*))?$/) ) {
message.nick = match[1];
message.user = match[3];
message.host = match[4];
}
else {
message.server = message.prefix;
}
}
// Parse command
match = line.match(/^([^ ]+) +/);
message.command = match[1];
message.rawCommand = match[1];
message.commandType = 'normal';
line = line.replace(/^[^ ]+ +/, '');
if ( replyFor[message.rawCommand] ) {
message.command = replyFor[message.rawCommand].name;
message.commandType = replyFor[message.rawCommand].type;
}
message.args = [];
var middle, trailing;
// Parse parameters
if ( line.indexOf(':') != -1 ) {
var index = line.indexOf(':');
middle = line.substr(0, index).replace(/ +$/, "");
trailing = line.substr(index+1);
}
else {
middle = line;
}
if ( middle.length )
message.args = middle.split(/ +/);
if ( typeof(trailing) != 'undefined' && trailing.length )
message.args.push(trailing);
return message;
} // }}} |
JavaScript | function bufferToManufacturer (buffer) {
if (buffer == null || !Buffer.isBuffer(buffer) || buffer.length < 4) {
return null
}
const id = toHex(buffer.readUInt16LE(0), 4, false)
return {
code: id,
name: definitions.companies[id] == null
? '0x' + id
: definitions.companies[id]
}
} | function bufferToManufacturer (buffer) {
if (buffer == null || !Buffer.isBuffer(buffer) || buffer.length < 4) {
return null
}
const id = toHex(buffer.readUInt16LE(0), 4, false)
return {
code: id,
name: definitions.companies[id] == null
? '0x' + id
: definitions.companies[id]
}
} |
JavaScript | function nameToKey (name) {
if (name == null || typeof name !== 'string') {
return null
}
const key = name.replace(/-/g, ' ')
const a = key.split(' ')
for (const i in a) {
if (i === '0') {
a[i] = a[i].toLowerCase()
} else {
a[i] = a[i].charAt(0).toUpperCase() + a[i].slice(1).toLowerCase()
}
}
return a.join('')
} | function nameToKey (name) {
if (name == null || typeof name !== 'string') {
return null
}
const key = name.replace(/-/g, ' ')
const a = key.split(' ')
for (const i in a) {
if (i === '0') {
a[i] = a[i].toLowerCase()
} else {
a[i] = a[i].charAt(0).toUpperCase() + a[i].slice(1).toLowerCase()
}
}
return a.join('')
} |
JavaScript | processKey (key) {
for (const wordKey in upperCaseWords) {
const word = upperCaseWords[wordKey]
const a = word.regexp.exec(key)
if (a != null) {
key = a[1] + (a[1] === '' ? word.lower : word.camel) + a[2]
}
}
key = key.charAt(0).toLowerCase() + key.slice(1)
if (replacementKeys[key] != null) {
key = replacementKeys[key]
}
return key
} | processKey (key) {
for (const wordKey in upperCaseWords) {
const word = upperCaseWords[wordKey]
const a = word.regexp.exec(key)
if (a != null) {
key = a[1] + (a[1] === '' ? word.lower : word.camel) + a[2]
}
}
key = key.charAt(0).toLowerCase() + key.slice(1)
if (replacementKeys[key] != null) {
key = replacementKeys[key]
}
return key
} |
JavaScript | async process (value) {
// Recursively post-process arrays.
if (Array.isArray(value)) {
const list = []
for (const elt of value) {
list.push(await this.process(elt))
}
return list
}
// Recursively post-process objects.
if (typeof value === 'object') {
// Ignore xmlns schemas.
for (const key in value) {
if (key.startsWith('xmlns') || key.startsWith('xsi:')) {
delete value[key]
}
}
// Handle single-key objects.
const keys = Object.keys(value)
if (keys.length === 1) {
if (rootKeys.includes(keys[0])) {
return this.process(value[keys[0]])
}
}
// Recursively post-process key/value pairs.
const obj = {}
for (const key in value) {
// Handle lists.
if (arrayKeys[key] != null) {
const childKey = arrayKeys[key]
let newValue = await this.process(value[key])
const listKeys = Object.keys(newValue)
if (listKeys.length === 1 && listKeys[0] === childKey) {
newValue = newValue[childKey]
}
if (Array.isArray(newValue)) {
obj[key] = newValue
} else if (
typeof newValue === 'object' || typeof newValue === 'string'
) {
obj[key] = [newValue]
} else {
obj[key] = []
}
continue
}
if (key === 'value') {
let newValue = await this.process(value[key])
const listKeys = Object.keys(newValue)
if (listKeys.length === 1 && listKeys[0] === 'field') {
newValue = newValue.field
if (Array.isArray(newValue)) {
obj.values = newValue
} else if (
typeof newValue === 'object' || typeof newValue === 'string'
) {
obj.values = [newValue]
} else {
obj.values = []
}
continue
}
obj.value = newValue
}
obj[key] = await this.process(value[key])
}
return obj
}
return value
} | async process (value) {
// Recursively post-process arrays.
if (Array.isArray(value)) {
const list = []
for (const elt of value) {
list.push(await this.process(elt))
}
return list
}
// Recursively post-process objects.
if (typeof value === 'object') {
// Ignore xmlns schemas.
for (const key in value) {
if (key.startsWith('xmlns') || key.startsWith('xsi:')) {
delete value[key]
}
}
// Handle single-key objects.
const keys = Object.keys(value)
if (keys.length === 1) {
if (rootKeys.includes(keys[0])) {
return this.process(value[keys[0]])
}
}
// Recursively post-process key/value pairs.
const obj = {}
for (const key in value) {
// Handle lists.
if (arrayKeys[key] != null) {
const childKey = arrayKeys[key]
let newValue = await this.process(value[key])
const listKeys = Object.keys(newValue)
if (listKeys.length === 1 && listKeys[0] === childKey) {
newValue = newValue[childKey]
}
if (Array.isArray(newValue)) {
obj[key] = newValue
} else if (
typeof newValue === 'object' || typeof newValue === 'string'
) {
obj[key] = [newValue]
} else {
obj[key] = []
}
continue
}
if (key === 'value') {
let newValue = await this.process(value[key])
const listKeys = Object.keys(newValue)
if (listKeys.length === 1 && listKeys[0] === 'field') {
newValue = newValue.field
if (Array.isArray(newValue)) {
obj.values = newValue
} else if (
typeof newValue === 'object' || typeof newValue === 'string'
) {
obj.values = [newValue]
} else {
obj.values = []
}
continue
}
obj.value = newValue
}
obj[key] = await this.process(value[key])
}
return obj
}
return value
} |
JavaScript | function populateInfoWindow(marker, infowindow) {
// Check to make sure the infowindow is not already opened on this marker.
if (infowindow.marker != marker) {
infowindow.marker = marker;
// Wiki(marker.location);
marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function() {
marker.setAnimation(null);
}, 1000);
// Wiki(marker.location);
// console.log(marker.location);
infowindow.setContent(wikicontent + '<hr>' + '<div>' + marker.title + '</div>');
console.log('information window : '+ wikicontent);
infowindow.open(map, marker);
// Make sure the marker property is cleared if the infowindow is closed.
infowindow.addListener('closeclick', function() {
infowindow.marker = null;
});
}
} | function populateInfoWindow(marker, infowindow) {
// Check to make sure the infowindow is not already opened on this marker.
if (infowindow.marker != marker) {
infowindow.marker = marker;
// Wiki(marker.location);
marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function() {
marker.setAnimation(null);
}, 1000);
// Wiki(marker.location);
// console.log(marker.location);
infowindow.setContent(wikicontent + '<hr>' + '<div>' + marker.title + '</div>');
console.log('information window : '+ wikicontent);
infowindow.open(map, marker);
// Make sure the marker property is cleared if the infowindow is closed.
infowindow.addListener('closeclick', function() {
infowindow.marker = null;
});
}
} |
JavaScript | windowMake(p1, p2){
const c = Term.colors["WHITE"];
for(let x = p1.x+1; x < p2.x; x++)
for(let y = p1.y+1; y < p2.y; y++)
this.draw({x:x,y:y}, c, ' ');
this.draw(p1, c, '+');
this.draw({x:p2.x,y:p1.y}, c, '+');
this.draw({x:p1.x,y:p2.y}, c, '+');
this.draw(p2, c, '+');
for(let x = p1.x+1; x < p2.x; x++){
this.draw({x:x,y:p1.y}, c, '-');
this.draw({x:x,y:p2.y}, c, '-');
}
for(let y = p1.y+1; y < p2.y; y++){
this.draw({x:p1.x,y:y}, c, '|');
this.draw({x:p2.x,y:y}, c, '|');
}
} | windowMake(p1, p2){
const c = Term.colors["WHITE"];
for(let x = p1.x+1; x < p2.x; x++)
for(let y = p1.y+1; y < p2.y; y++)
this.draw({x:x,y:y}, c, ' ');
this.draw(p1, c, '+');
this.draw({x:p2.x,y:p1.y}, c, '+');
this.draw({x:p1.x,y:p2.y}, c, '+');
this.draw(p2, c, '+');
for(let x = p1.x+1; x < p2.x; x++){
this.draw({x:x,y:p1.y}, c, '-');
this.draw({x:x,y:p2.y}, c, '-');
}
for(let y = p1.y+1; y < p2.y; y++){
this.draw({x:p1.x,y:y}, c, '|');
this.draw({x:p2.x,y:y}, c, '|');
}
} |
JavaScript | assortUrls(stringList, arrayLocation){
stringList.split("\n").forEach(url=>{
if (url !== ""){
arrayLocation.push(url);
}
})
} | assortUrls(stringList, arrayLocation){
stringList.split("\n").forEach(url=>{
if (url !== ""){
arrayLocation.push(url);
}
})
} |
JavaScript | filterUrl(inputUrl){
inputUrl = inputUrl.toLowerCase();
var res = this.getToolTipFromName("Safe URL").urlClass;
unsafeUrls.forEach(url=>{
url = url.split(/\s+/).join('');
if (url !== "" && inputUrl.includes(url.toLowerCase())){
res = this.getToolTipFromName("Unsafe URL").urlClass;
}
})
dangerousUrls.forEach(url=>{
url = url.split(/\s+/).join('');
if (url !== "" && inputUrl.includes(url.toLowerCase())){
res = this.getToolTipFromName("Dangerous URL").urlClass;
}
})
bypassedUrls.forEach(url=>{
url = url.split(/\s+/).join('');
if (url !== "" && inputUrl.includes(url.toLowerCase())){
res = false
}
})
if (inputUrl.startsWith("http://")){
res = this.getToolTipFromName("Http URL").urlClass;
}
return res;
} | filterUrl(inputUrl){
inputUrl = inputUrl.toLowerCase();
var res = this.getToolTipFromName("Safe URL").urlClass;
unsafeUrls.forEach(url=>{
url = url.split(/\s+/).join('');
if (url !== "" && inputUrl.includes(url.toLowerCase())){
res = this.getToolTipFromName("Unsafe URL").urlClass;
}
})
dangerousUrls.forEach(url=>{
url = url.split(/\s+/).join('');
if (url !== "" && inputUrl.includes(url.toLowerCase())){
res = this.getToolTipFromName("Dangerous URL").urlClass;
}
})
bypassedUrls.forEach(url=>{
url = url.split(/\s+/).join('');
if (url !== "" && inputUrl.includes(url.toLowerCase())){
res = false
}
})
if (inputUrl.startsWith("http://")){
res = this.getToolTipFromName("Http URL").urlClass;
}
return res;
} |
JavaScript | function parseNumber(string) {
string = string.toLowerCase();
if (string.length === 0) {
return NaN;
}
let negative = false;
if (string[0] === '-') {
string = string.slice(1);
negative = true;
}
let num;
if (string[0] === 'x') {
const hexDigits = string.slice(1);
if (hexDigits.match(/[^0-9a-f]/)) {
return NaN;
}
num = parseInt(hexDigits, 16);
} else {
if (string.match(/[^0-9]/)) {
return NaN;
}
num = parseInt(string);
}
return negative ? -num : num;
} | function parseNumber(string) {
string = string.toLowerCase();
if (string.length === 0) {
return NaN;
}
let negative = false;
if (string[0] === '-') {
string = string.slice(1);
negative = true;
}
let num;
if (string[0] === 'x') {
const hexDigits = string.slice(1);
if (hexDigits.match(/[^0-9a-f]/)) {
return NaN;
}
num = parseInt(hexDigits, 16);
} else {
if (string.match(/[^0-9]/)) {
return NaN;
}
num = parseInt(string);
}
return negative ? -num : num;
} |
JavaScript | function toHexString(number, padLength=4, prefix='x') {
let hex = number.toString(16).toUpperCase();
if (hex.length < padLength) {
hex = Array(padLength - hex.length + 1).join('0') + hex;
}
return prefix + hex;
} | function toHexString(number, padLength=4, prefix='x') {
let hex = number.toString(16).toUpperCase();
if (hex.length < padLength) {
hex = Array(padLength - hex.length + 1).join('0') + hex;
}
return prefix + hex;
} |
JavaScript | function toInt16(n) {
n = (n % (1 << WORD_BITS)) & ((1 << WORD_BITS) - 1);
if (n & (1 << WORD_BITS - 1)) {
return n - (1 << WORD_BITS);
}
return n;
} | function toInt16(n) {
n = (n % (1 << WORD_BITS)) & ((1 << WORD_BITS) - 1);
if (n & (1 << WORD_BITS - 1)) {
return n - (1 << WORD_BITS);
}
return n;
} |
JavaScript | function signExtend16(n, bits) {
const justSignBit = n & (1 << (bits - 1));
if (justSignBit) {
return toInt16(n - (1 << bits));
} else {
return toInt16(n & (1 << bits) - 1);
}
} | function signExtend16(n, bits) {
const justSignBit = n & (1 << (bits - 1));
if (justSignBit) {
return toInt16(n - (1 << bits));
} else {
return toInt16(n & (1 << bits) - 1);
}
} |
JavaScript | function formatConditionCode(psr) {
switch (getConditionCode(psr)) {
case null:
return "Invalid";
case -1:
return "N";
case 0:
return "Z";
case 1:
return "P";
}
} | function formatConditionCode(psr) {
switch (getConditionCode(psr)) {
case null:
return "Invalid";
case -1:
return "N";
case 0:
return "Z";
case 1:
return "P";
}
} |
JavaScript | function createActionCreator(description) {
const {type, parameters = [], parameterTransforms = {}} = description;
return function actionCreator(...args) {
if (args.length !== parameters.length) {
throw new Error(
`Expected ${parameters.length} arguments ` +
`in action creator ${type}, `
`but found ${args.length}`);
}
return parameters.reduce((acc, key, idx) => {
const transformer = parameterTransforms[key] || (x => x);
return {
...acc,
[key]: transformer(args[idx]),
};
}, {type});
};
} | function createActionCreator(description) {
const {type, parameters = [], parameterTransforms = {}} = description;
return function actionCreator(...args) {
if (args.length !== parameters.length) {
throw new Error(
`Expected ${parameters.length} arguments ` +
`in action creator ${type}, `
`but found ${args.length}`);
}
return parameters.reduce((acc, key, idx) => {
const transformer = parameterTransforms[key] || (x => x);
return {
...acc,
[key]: transformer(args[idx]),
};
}, {type});
};
} |
JavaScript | function createActionCreators(descriptions) {
return Object.keys(descriptions).reduce((acc, key) => {
return {
...acc,
[key]: createActionCreator(descriptions[key]),
};
}, {});
} | function createActionCreators(descriptions) {
return Object.keys(descriptions).reduce((acc, key) => {
return {
...acc,
[key]: createActionCreator(descriptions[key]),
};
}, {});
} |
JavaScript | function parseString(text) {
const error = (message) => {
throw new Error(`while parsing the string ${text}: ${message}`);
};
if (text.length < 2) {
error(`this string is way too short! ` +
"You need at least two characters just for the quote marks.");
}
const quote = '"';
if (text.charAt(0) !== quote || text.charAt(text.length - 1) !== quote) {
error(`the string needs to start and end with ` +
`double quotation marks (e.g.: ${quote}I'm a string${quote}).`);
}
// We'll build up this list of single-character strings,
// then join them at the end.
// (This might end up being a tad sparse if we skip some backslashes;
// that's okay, because Array.join will deal with these holes fine.)
let chars = new Array(text.length - 2);
// This has to be a mutable-style for loop instead of a call to map
// because we need to be able to conditionally move the iterator
// (e.g., read the next character to process and escape sequence).
let i;
for (i = 1; i < text.length - 1; i++) {
const here = text.charAt(i);
const errorHere = (message) => error(`at index ${i}: ${message}`);
if (here === '"') {
errorHere(`unescaped double quote found before end of string`);
}
if (here === '\\') {
// Supported escape sequences: \0, \n, \r, \", \\.
const escapeSequence = text.charAt(++i);
// Note: if the backslash is the last character of the string,
// meaning that the closing quote is escaped
// and the string is invalid,
// this particular character will just resolve to a quote,
// and no error will be raised.
// We check for this case separately down below.
const escaped = ({
'0': '\0',
'n': '\n',
'r': '\r',
'"': '\"',
'\\': '\\',
})[escapeSequence];
if (escapeSequence === undefined) {
errorHere(`unsupported escape character '${escapeSequence}'`);
}
chars[i] = (escaped);
} else {
chars[i] = here;
}
}
// Now make sure that the last body character wasn't a backslash,
// which would mean that we escaped the final closing quote.
if (i >= text.length || text.charAt(i) !== '"') {
error("unterminated string literal! " +
"Did you accidentally backslash-escape the closing quote?");
}
return chars.join('');
} | function parseString(text) {
const error = (message) => {
throw new Error(`while parsing the string ${text}: ${message}`);
};
if (text.length < 2) {
error(`this string is way too short! ` +
"You need at least two characters just for the quote marks.");
}
const quote = '"';
if (text.charAt(0) !== quote || text.charAt(text.length - 1) !== quote) {
error(`the string needs to start and end with ` +
`double quotation marks (e.g.: ${quote}I'm a string${quote}).`);
}
// We'll build up this list of single-character strings,
// then join them at the end.
// (This might end up being a tad sparse if we skip some backslashes;
// that's okay, because Array.join will deal with these holes fine.)
let chars = new Array(text.length - 2);
// This has to be a mutable-style for loop instead of a call to map
// because we need to be able to conditionally move the iterator
// (e.g., read the next character to process and escape sequence).
let i;
for (i = 1; i < text.length - 1; i++) {
const here = text.charAt(i);
const errorHere = (message) => error(`at index ${i}: ${message}`);
if (here === '"') {
errorHere(`unescaped double quote found before end of string`);
}
if (here === '\\') {
// Supported escape sequences: \0, \n, \r, \", \\.
const escapeSequence = text.charAt(++i);
// Note: if the backslash is the last character of the string,
// meaning that the closing quote is escaped
// and the string is invalid,
// this particular character will just resolve to a quote,
// and no error will be raised.
// We check for this case separately down below.
const escaped = ({
'0': '\0',
'n': '\n',
'r': '\r',
'"': '\"',
'\\': '\\',
})[escapeSequence];
if (escapeSequence === undefined) {
errorHere(`unsupported escape character '${escapeSequence}'`);
}
chars[i] = (escaped);
} else {
chars[i] = here;
}
}
// Now make sure that the last body character wasn't a backslash,
// which would mean that we escaped the final closing quote.
if (i >= text.length || text.charAt(i) !== '"') {
error("unterminated string literal! " +
"Did you accidentally backslash-escape the closing quote?");
}
return chars.join('');
} |
JavaScript | function findOrig(tokenizedLines) {
// The .ORIG directive needs to be on the first non-blank line
// (after tokenizing, which strips whitespace and comments).
const lineNumber = tokenizedLines.findIndex(line => line.length > 0);
if (lineNumber === -1) {
throw new Error("Looks like your program's empty! " +
"You need at least an .ORIG directive and an .END directive.");
}
const line = tokenizedLines[lineNumber];
// Check if there's an .ORIG directive anywhere in the line.
const hasOrig = line.some(token => token.toUpperCase() === ".ORIG");
if (!hasOrig) {
throw new Error(
"The first non-empty, non-comment line of your program " +
"needs to have an .ORIG directive!");
}
// There's a directive somewhere.
// If it's not the first, then there's a label. Not allowed.
if (line[0].toUpperCase() !== ".ORIG") {
throw new Error(".ORIG directive cannot have a label!");
}
// If there's additional junk, that's not okay.
// If there's no operand, that's not okay, either.
const operands = line.length - 1;
if (operands !== 1) {
throw new Error(`The .ORIG directive expects exactly one operand, ` +
`but it looks like you have ${operands}!`);
}
// Well, there's something. Is it a number?
const operand = line[1];
const orig = withContext(parseLiteral,
"while parsing .ORIG directive operand")(operand);
// Is it in range?
if (orig !== Utils.toUint16(orig)) {
throw new Error(`.ORIG operand (${operand}) is out of range! ` +
`It should be between 0 and 0xFFFF, inclusive.`);
}
// Looks like we're good.
return {
orig: orig,
begin: lineNumber + 1,
};
} | function findOrig(tokenizedLines) {
// The .ORIG directive needs to be on the first non-blank line
// (after tokenizing, which strips whitespace and comments).
const lineNumber = tokenizedLines.findIndex(line => line.length > 0);
if (lineNumber === -1) {
throw new Error("Looks like your program's empty! " +
"You need at least an .ORIG directive and an .END directive.");
}
const line = tokenizedLines[lineNumber];
// Check if there's an .ORIG directive anywhere in the line.
const hasOrig = line.some(token => token.toUpperCase() === ".ORIG");
if (!hasOrig) {
throw new Error(
"The first non-empty, non-comment line of your program " +
"needs to have an .ORIG directive!");
}
// There's a directive somewhere.
// If it's not the first, then there's a label. Not allowed.
if (line[0].toUpperCase() !== ".ORIG") {
throw new Error(".ORIG directive cannot have a label!");
}
// If there's additional junk, that's not okay.
// If there's no operand, that's not okay, either.
const operands = line.length - 1;
if (operands !== 1) {
throw new Error(`The .ORIG directive expects exactly one operand, ` +
`but it looks like you have ${operands}!`);
}
// Well, there's something. Is it a number?
const operand = line[1];
const orig = withContext(parseLiteral,
"while parsing .ORIG directive operand")(operand);
// Is it in range?
if (orig !== Utils.toUint16(orig)) {
throw new Error(`.ORIG operand (${operand}) is out of range! ` +
`It should be between 0 and 0xFFFF, inclusive.`);
}
// Looks like we're good.
return {
orig: orig,
begin: lineNumber + 1,
};
} |
JavaScript | function isValidLabelName(label) {
if (label.match(/[^A-Za-z0-9_]/)) {
// Invalid characters.
return false;
}
const asLiteral = handleErrors(parseLiteral)(label);
if (asLiteral.success) {
// Valid literal; could be ambiguous.
return false;
}
return true;
} | function isValidLabelName(label) {
if (label.match(/[^A-Za-z0-9_]/)) {
// Invalid characters.
return false;
}
const asLiteral = handleErrors(parseLiteral)(label);
if (asLiteral.success) {
// Valid literal; could be ambiguous.
return false;
}
return true;
} |
JavaScript | function determineRequiredMemory(command, operand) {
switch (command.toUpperCase()) {
case ".FILL":
return 1;
case ".BLKW":
if (operand < 0) {
throw new Error(
`a .BLKW needs to have a non-negative length, ` +
`but I found ${operand}`);
}
return operand;
case ".STRINGZ":
return operand.length + 1; // for the null-terminator
default:
// Assume it's a normal instruction.
return 1;
}
} | function determineRequiredMemory(command, operand) {
switch (command.toUpperCase()) {
case ".FILL":
return 1;
case ".BLKW":
if (operand < 0) {
throw new Error(
`a .BLKW needs to have a non-negative length, ` +
`but I found ${operand}`);
}
return operand;
case ".STRINGZ":
return operand.length + 1; // for the null-terminator
default:
// Assume it's a normal instruction.
return 1;
}
} |
JavaScript | function parseOffset(pc, operand, symbols, bits) {
const ensureInRange = (x) => {
const min = -(1 << (bits - 1));
const max = (1 << (bits - 1)) - 1;
if (!(min <= x && x <= max)) {
throw new Error(`offset ${x} is out of range; ` +
`it must fit into ${bits} bits, ` +
`so it should be between ${min} and ${max}, inclusive`);
}
return x;
};
// First, see if it's a valid literal.
const asLiteral = handleErrors(parseLiteral)(operand);
if (asLiteral.success) {
return ensureInRange(asLiteral.result);
}
// If it's not a literal, it must be a symbol to be valid.
if (!(operand in symbols)) {
throw new Error(
`the offset '${operand}' is not a valid numeric literal, ` +
`but I can't find it in the symbol table either; ` +
`did you misspell a label name?`);
}
const symbolAddress = symbols[operand];
return ensureInRange(symbolAddress - pc);
} | function parseOffset(pc, operand, symbols, bits) {
const ensureInRange = (x) => {
const min = -(1 << (bits - 1));
const max = (1 << (bits - 1)) - 1;
if (!(min <= x && x <= max)) {
throw new Error(`offset ${x} is out of range; ` +
`it must fit into ${bits} bits, ` +
`so it should be between ${min} and ${max}, inclusive`);
}
return x;
};
// First, see if it's a valid literal.
const asLiteral = handleErrors(parseLiteral)(operand);
if (asLiteral.success) {
return ensureInRange(asLiteral.result);
}
// If it's not a literal, it must be a symbol to be valid.
if (!(operand in symbols)) {
throw new Error(
`the offset '${operand}' is not a valid numeric literal, ` +
`but I can't find it in the symbol table either; ` +
`did you misspell a label name?`);
}
const symbolAddress = symbols[operand];
return ensureInRange(symbolAddress - pc);
} |
JavaScript | function encodeDirective(tokens) {
const directive = tokens[0];
const operand = tokens[1];
switch (directive.toUpperCase()) {
case ".FILL":
return [Utils.toUint16(parseLiteral(operand))];
case ".BLKW":
return new Array(Utils.toUint16(parseLiteral(operand))).fill(0);
case ".STRINGZ":
return operand.split('').map(c => c.charCodeAt(0)).concat([0]);
default:
throw new Error(`unrecognized directive: ${directive}`);
}
} | function encodeDirective(tokens) {
const directive = tokens[0];
const operand = tokens[1];
switch (directive.toUpperCase()) {
case ".FILL":
return [Utils.toUint16(parseLiteral(operand))];
case ".BLKW":
return new Array(Utils.toUint16(parseLiteral(operand))).fill(0);
case ".STRINGZ":
return operand.split('').map(c => c.charCodeAt(0)).concat([0]);
default:
throw new Error(`unrecognized directive: ${directive}`);
}
} |
JavaScript | function reduceProgram(lines, begin, handlers, initialState) {
const id = x => x;
const {
handleLabel = id,
handleDirective = id,
handleInstruction = id,
handleEnd = id,
} = handlers;
// Here are all the things that can come at the start of a line.
// We use these to determine whether the first token in a line
// is a label or an actual operation of some kind.
const trapVectors = "GETC OUT PUTS IN PUTSP HALT".split(' ');
const instructions = [
"ADD", "AND", "NOT",
"BR", "BRP", "BRZ", "BRZP", "BRN", "BRNP", "BRNZ", "BRNZP",
"JMP", "RET",
"JSR", "JSRR",
"LD", "LDI", "LDR",
"LEA",
"RTI",
"ST", "STI", "STR",
"TRAP",
];
const directives = [".FILL", ".BLKW", ".STRINGZ"];
const commands = [...trapVectors, ...instructions, ...directives];
const program = lines.slice(begin);
return program.reduce((state, line, lineIndex) => {
if (line.length === 0) {
return state;
}
const ctx = `at line ${lineIndex + begin + 1}`;
const delegate = (cb, _state = state, _line = line) =>
withContext(cb, ctx)(_state, _line, lineIndex);
const fst = line[0];
if (fst.toUpperCase() === ".END") {
return delegate(handleEnd);
}
const hasLabel = !commands.includes(fst.toUpperCase());
if (hasLabel && !isValidLabelName(fst)) {
throw new Error(
`${ctx}: this line looks like a label, ` +
`but '${fst}' is not a valid label name; ` +
`you either misspelled an instruction ` +
`or entered an invalid name for a label`);
}
const labeledState = hasLabel ? delegate(handleLabel) : state;
const rest = line.slice(hasLabel ? 1 : 0);
if (rest.length === 0) {
// It's a label-only line. No problem.
return labeledState;
}
const command = rest[0].toUpperCase();
const isDirective = (command.charAt(0) === '.');
if (isDirective) {
return delegate(handleDirective, labeledState, rest);
} else {
return delegate(handleInstruction, labeledState, rest);
}
}, initialState);
} | function reduceProgram(lines, begin, handlers, initialState) {
const id = x => x;
const {
handleLabel = id,
handleDirective = id,
handleInstruction = id,
handleEnd = id,
} = handlers;
// Here are all the things that can come at the start of a line.
// We use these to determine whether the first token in a line
// is a label or an actual operation of some kind.
const trapVectors = "GETC OUT PUTS IN PUTSP HALT".split(' ');
const instructions = [
"ADD", "AND", "NOT",
"BR", "BRP", "BRZ", "BRZP", "BRN", "BRNP", "BRNZ", "BRNZP",
"JMP", "RET",
"JSR", "JSRR",
"LD", "LDI", "LDR",
"LEA",
"RTI",
"ST", "STI", "STR",
"TRAP",
];
const directives = [".FILL", ".BLKW", ".STRINGZ"];
const commands = [...trapVectors, ...instructions, ...directives];
const program = lines.slice(begin);
return program.reduce((state, line, lineIndex) => {
if (line.length === 0) {
return state;
}
const ctx = `at line ${lineIndex + begin + 1}`;
const delegate = (cb, _state = state, _line = line) =>
withContext(cb, ctx)(_state, _line, lineIndex);
const fst = line[0];
if (fst.toUpperCase() === ".END") {
return delegate(handleEnd);
}
const hasLabel = !commands.includes(fst.toUpperCase());
if (hasLabel && !isValidLabelName(fst)) {
throw new Error(
`${ctx}: this line looks like a label, ` +
`but '${fst}' is not a valid label name; ` +
`you either misspelled an instruction ` +
`or entered an invalid name for a label`);
}
const labeledState = hasLabel ? delegate(handleLabel) : state;
const rest = line.slice(hasLabel ? 1 : 0);
if (rest.length === 0) {
// It's a label-only line. No problem.
return labeledState;
}
const command = rest[0].toUpperCase();
const isDirective = (command.charAt(0) === '.');
if (isDirective) {
return delegate(handleDirective, labeledState, rest);
} else {
return delegate(handleInstruction, labeledState, rest);
}
}, initialState);
} |
JavaScript | function withContext(callback, context) {
return (...args) => {
try {
return callback(...args);
} catch (e) {
throw new Error(`${context}: ${e.message}`);
}
};
} | function withContext(callback, context) {
return (...args) => {
try {
return callback(...args);
} catch (e) {
throw new Error(`${context}: ${e.message}`);
}
};
} |
JavaScript | function decode(instruction) {
instruction = Utils.toUint16(instruction);
const opcode = instruction >> 12 & 0xF;
let op = {
raw: instruction,
strictValid: true,
opcode: opcode,
};
const bits = List(Array(16)).map((_, i) => (instruction >> i) & 0x1).toJS();
// Commonly used subsequences of bits, as numbers.
const bits05 = instruction & 0x3F;
const bits68 = (instruction >> 6) & 0x7;
const bits08 = instruction & 0x1FF;
const bits911 = (instruction >> 9) & 0x7;
const bits010 = instruction & 0x7FF;
switch (opcode) {
case 0b0001: // ADD
case 0b0101: // ADD
op.opname = op.opcode === 1 ? 'ADD' : 'AND';
op.dr = bits911;
op.sr1 = bits68;
op.mode = "none";
if (bits[5] === 0) {
op.arithmeticMode = "register";
op.sr2 = instruction & 0x7;
if (bits[4] !== 0 || bits[3] !== 0) {
op.strictValid = false;
}
} else {
op.arithmeticMode = "immediate";
op.immediateField = Utils.signExtend16(instruction & 0x1F, 5);
}
break;
case 0b0000: // BR
op.opname = "BR";
op.mode = "pcOffset";
op.offset = Utils.signExtend16(bits08, 9);
op.strictValid = true;
[op.n, op.z, op.p] = [11, 10, 9].map(b => !!bits[b]);
break;
case 0b1100: // JMP, RET
op.opname = (bits68 === 0b111) ? "RET" : "JMP"; // RET = JMP R7
op.mode = "baseOffset",
op.baseR = bits68;
op.offset = 0;
if (bits911 !== 0 || bits05 !== 0) {
op.strictValid = false;
}
break;
case 0b0100: // JSR, JSRR
if (bits[11] === 0) {
op.opname = "JSRR";
op.mode = "baseOffset";
op.baseR = bits68;
op.offset = 0;
if (bits911 !== 0 || bits05 !== 0) {
op.strictValid = false;
}
} else {
op.opname = "JSR";
op.mode = "pcOffset";
op.offset = Utils.signExtend16(bits010, 11);
}
break;
case 0b0010: // LD
case 0b1010: // LDI
case 0b1110: // LEA
op.opname = ({
0b0010: "LD",
0b1010: "LDI",
0b1110: "LEA",
})[opcode];
op.mode = "pcOffset";
op.dr = bits911;
op.offset = Utils.signExtend16(bits08, 9);
break;
case 0b0110: // LDR
op.opname = "LDR";
op.mode = "baseOffset";
op.dr = bits911;
op.baseR = bits68;
op.offset = Utils.signExtend16(bits05, 6);
break;
case 0b1001: // NOT
op.opname = "NOT";
op.mode = "none";
op.dr = bits911;
op.sr = bits68;
if ((instruction & 0b111111) !== 0b111111) {
op.strictValid = false;
}
break;
case 0b0011: // ST
case 0b1011: // STI
op.opname = (op.opcode === 0b0011) ? "ST" : "STI";
op.mode = "pcOffset";
op.sr = bits911;
op.offset = Utils.signExtend16(bits08, 9);
break;
case 0b0111: // STR
op.opname = "STR";
op.mode = "baseOffset";
op.sr = bits911;
op.baseR = bits68;
op.offset = Utils.signExtend16(bits05, 6);
break;
case 0b1111: // TRAP
op.opname = "TRAP";
op.mode = "trap";
op.trapVector = instruction & 0xFF;
if (instruction & 0x0F00) {
op.strictValid = false;
}
break;
case 0b1000: // RTI
op.opname = "RTI";
op.mode = "none";
if (instruction !== 0x8000) {
op.strictValid = false;
}
break;
case 0b1101: // RSRV (the reserved instruction)
op.opname = "RSRV";
op.mode = "none";
op.strictValid = false;
break;
default:
throw new Error(`Unrecognized opcode: ${opcode}`);
}
return Map(op);
} | function decode(instruction) {
instruction = Utils.toUint16(instruction);
const opcode = instruction >> 12 & 0xF;
let op = {
raw: instruction,
strictValid: true,
opcode: opcode,
};
const bits = List(Array(16)).map((_, i) => (instruction >> i) & 0x1).toJS();
// Commonly used subsequences of bits, as numbers.
const bits05 = instruction & 0x3F;
const bits68 = (instruction >> 6) & 0x7;
const bits08 = instruction & 0x1FF;
const bits911 = (instruction >> 9) & 0x7;
const bits010 = instruction & 0x7FF;
switch (opcode) {
case 0b0001: // ADD
case 0b0101: // ADD
op.opname = op.opcode === 1 ? 'ADD' : 'AND';
op.dr = bits911;
op.sr1 = bits68;
op.mode = "none";
if (bits[5] === 0) {
op.arithmeticMode = "register";
op.sr2 = instruction & 0x7;
if (bits[4] !== 0 || bits[3] !== 0) {
op.strictValid = false;
}
} else {
op.arithmeticMode = "immediate";
op.immediateField = Utils.signExtend16(instruction & 0x1F, 5);
}
break;
case 0b0000: // BR
op.opname = "BR";
op.mode = "pcOffset";
op.offset = Utils.signExtend16(bits08, 9);
op.strictValid = true;
[op.n, op.z, op.p] = [11, 10, 9].map(b => !!bits[b]);
break;
case 0b1100: // JMP, RET
op.opname = (bits68 === 0b111) ? "RET" : "JMP"; // RET = JMP R7
op.mode = "baseOffset",
op.baseR = bits68;
op.offset = 0;
if (bits911 !== 0 || bits05 !== 0) {
op.strictValid = false;
}
break;
case 0b0100: // JSR, JSRR
if (bits[11] === 0) {
op.opname = "JSRR";
op.mode = "baseOffset";
op.baseR = bits68;
op.offset = 0;
if (bits911 !== 0 || bits05 !== 0) {
op.strictValid = false;
}
} else {
op.opname = "JSR";
op.mode = "pcOffset";
op.offset = Utils.signExtend16(bits010, 11);
}
break;
case 0b0010: // LD
case 0b1010: // LDI
case 0b1110: // LEA
op.opname = ({
0b0010: "LD",
0b1010: "LDI",
0b1110: "LEA",
})[opcode];
op.mode = "pcOffset";
op.dr = bits911;
op.offset = Utils.signExtend16(bits08, 9);
break;
case 0b0110: // LDR
op.opname = "LDR";
op.mode = "baseOffset";
op.dr = bits911;
op.baseR = bits68;
op.offset = Utils.signExtend16(bits05, 6);
break;
case 0b1001: // NOT
op.opname = "NOT";
op.mode = "none";
op.dr = bits911;
op.sr = bits68;
if ((instruction & 0b111111) !== 0b111111) {
op.strictValid = false;
}
break;
case 0b0011: // ST
case 0b1011: // STI
op.opname = (op.opcode === 0b0011) ? "ST" : "STI";
op.mode = "pcOffset";
op.sr = bits911;
op.offset = Utils.signExtend16(bits08, 9);
break;
case 0b0111: // STR
op.opname = "STR";
op.mode = "baseOffset";
op.sr = bits911;
op.baseR = bits68;
op.offset = Utils.signExtend16(bits05, 6);
break;
case 0b1111: // TRAP
op.opname = "TRAP";
op.mode = "trap";
op.trapVector = instruction & 0xFF;
if (instruction & 0x0F00) {
op.strictValid = false;
}
break;
case 0b1000: // RTI
op.opname = "RTI";
op.mode = "none";
if (instruction !== 0x8000) {
op.strictValid = false;
}
break;
case 0b1101: // RSRV (the reserved instruction)
op.opname = "RSRV";
op.mode = "none";
op.strictValid = false;
break;
default:
throw new Error(`Unrecognized opcode: ${opcode}`);
}
return Map(op);
} |
JavaScript | function _getPostings (options, markup) {
let
$ = cheerio.load(markup),
// hostname = options.hostname,
posting = {},
postings = [],
secure = options.secure;
$('div.content')
.find('.result-row')
.each((i, element) => {
let
// introducing fix for #11 - Craigslist markup changed
details = $(element)
.find('.result-title')
.attr('href')
.split(/\//g)
.filter((term) => term.length)
.map((term) => term.split(RE_HTML)[0]),
// fix for #6 and #24
detailsUrl = parse($(element)
.find('.result-title')
.attr('href'));
// ensure hostname and protocol are properly set
detailsUrl.set('hostname', detailsUrl.hostname || options.hostname);
detailsUrl.set('protocol', secure ? PROTOCOL_SECURE : PROTOCOL_INSECURE);
posting = {
category : details[DEFAULT_CATEGORY_DETAILS_INDEX],
coordinates : {
lat : $(element).attr('data-latitude'),
lon : $(element).attr('data-longitude')
},
date : ($(element)
.find('time')
.attr('datetime') || '')
.trim(),
hasPic : RE_TAGS_MAP
.test($(element)
.find('.result-tags')
.text() || ''),
location : ($(element)
.find('.result-hood')
.text() || '')
.trim(),
pid : ($(element)
.attr('data-pid') || '')
.trim(),
price : ($(element)
.find('.result-meta .result-price')
.text() || '')
.replace(/^\&\#x0024\;/g, '')
.trim(), // sanitize
title : ($(element)
.find('.result-title')
.text() || '')
.trim(),
url : detailsUrl.toString()
};
// make sure lat / lon is valid
if (typeof posting.coordinates.lat === 'undefined' ||
typeof posting.coordinates.lon === 'undefined') {
delete posting.coordinates;
}
postings.push(posting);
});
return postings;
} | function _getPostings (options, markup) {
let
$ = cheerio.load(markup),
// hostname = options.hostname,
posting = {},
postings = [],
secure = options.secure;
$('div.content')
.find('.result-row')
.each((i, element) => {
let
// introducing fix for #11 - Craigslist markup changed
details = $(element)
.find('.result-title')
.attr('href')
.split(/\//g)
.filter((term) => term.length)
.map((term) => term.split(RE_HTML)[0]),
// fix for #6 and #24
detailsUrl = parse($(element)
.find('.result-title')
.attr('href'));
// ensure hostname and protocol are properly set
detailsUrl.set('hostname', detailsUrl.hostname || options.hostname);
detailsUrl.set('protocol', secure ? PROTOCOL_SECURE : PROTOCOL_INSECURE);
posting = {
category : details[DEFAULT_CATEGORY_DETAILS_INDEX],
coordinates : {
lat : $(element).attr('data-latitude'),
lon : $(element).attr('data-longitude')
},
date : ($(element)
.find('time')
.attr('datetime') || '')
.trim(),
hasPic : RE_TAGS_MAP
.test($(element)
.find('.result-tags')
.text() || ''),
location : ($(element)
.find('.result-hood')
.text() || '')
.trim(),
pid : ($(element)
.attr('data-pid') || '')
.trim(),
price : ($(element)
.find('.result-meta .result-price')
.text() || '')
.replace(/^\&\#x0024\;/g, '')
.trim(), // sanitize
title : ($(element)
.find('.result-title')
.text() || '')
.trim(),
url : detailsUrl.toString()
};
// make sure lat / lon is valid
if (typeof posting.coordinates.lat === 'undefined' ||
typeof posting.coordinates.lon === 'undefined') {
delete posting.coordinates;
}
postings.push(posting);
});
return postings;
} |
JavaScript | function _getRequestOptions (options, query) {
var
requestOptions = JSON.parse(JSON.stringify(DEFAULT_REQUEST_OPTIONS)),
/*eslint no-invalid-this:0*/
self = this;
// ensure default options are set, even if omitted from input options
requestOptions.hostname = [
core.Validation.coalesce(options.city, self.options.city, ''),
// introducing fix for #7
core.Validation.coalesce(
options.baseHost,
self.options.baseHost,
DEFAULT_BASE_HOST)
].join('.');
// preserve any extraneous input option keys (may have addition instructions for underlying request object)
Object
.keys(options)
.forEach((key) => {
if (!QUERY_KEYS.indexOf(key) &&
core.Validation.isEmpty(requestOptions[key]) &&
core.Validation.isEmpty(DEFAULT_REQUEST_OPTIONS[key])) {
requestOptions[key] = options[key];
}
});
// setup path
if (core.Validation.isEmpty(requestOptions.path)) {
requestOptions.path = DEFAULT_PATH;
}
// setup category
requestOptions.path = [
requestOptions.path,
core.Validation.coalesce(options.category, DEFAULT_CATEGORY)].join('');
// setup querystring
requestOptions.path = [requestOptions.path, DEFAULT_QUERYSTRING].join('');
// add search query (if specified)
if (!core.Validation.isEmpty(query)) {
requestOptions.path = [
requestOptions.path,
QUERY_PARAM_QUERY,
encodeURIComponent(query)].join('');
}
// add bundleDuplicates (if specified)
if (options.bundleDuplicates) {
requestOptions.path = [
requestOptions.path,
QUERY_PARAM_BUNDLE_DUPLICATES].join('');
}
// add hasPic (if specified)
if (options.hasImage || options.hasPic) {
requestOptions.path = [
requestOptions.path,
QUERY_PARAM_HAS_IMAGE].join('');
}
// add min asking price (if specified)
if (!core.Validation.isEmpty(options.minAsk)) {
requestOptions.path = [
requestOptions.path,
QUERY_PARAM_MIN,
options.minAsk].join('');
}
// add max asking price (if specified)
if (!core.Validation.isEmpty(options.maxAsk)) {
requestOptions.path = [
requestOptions.path,
QUERY_PARAM_MAX,
options.maxAsk].join('');
}
// add postal (if specified)
if (!core.Validation.isEmpty(options.postal)) {
requestOptions.path = [
requestOptions.path,
QUERY_PARAM_POSTAL,
options.postal].join('');
}
// add postedToday (if specified)
if (options.postedToday) {
requestOptions.path = [
requestOptions.path,
QUERY_PARAM_POSTED_TODAY].join('');
}
// add searchDistance (if specified)
if (!core.Validation.isEmpty(options.searchDistance)) {
requestOptions.path = [
requestOptions.path,
QUERY_PARAM_SEARCH_DISTANCE,
options.searchDistance].join('');
}
// add searchNearby (if specified)
if (options.searchNearby) {
requestOptions.path = [
requestOptions.path,
QUERY_PARAM_SEARCH_NEARBY].join('');
}
// add searchTitlesOnly (if specified)
if (options.searchTitlesOnly) {
requestOptions.path = [
requestOptions.path,
QUERY_PARAM_SEARCH_TITLES_ONLY].join('');
}
// add offset (if specified)
if (options.offset) {
requestOptions.path = [requestOptions.path, QUERY_PARAM_OFFSET, options.offset].join('');
}
debug('setting request options: %o', requestOptions);
return requestOptions;
} | function _getRequestOptions (options, query) {
var
requestOptions = JSON.parse(JSON.stringify(DEFAULT_REQUEST_OPTIONS)),
/*eslint no-invalid-this:0*/
self = this;
// ensure default options are set, even if omitted from input options
requestOptions.hostname = [
core.Validation.coalesce(options.city, self.options.city, ''),
// introducing fix for #7
core.Validation.coalesce(
options.baseHost,
self.options.baseHost,
DEFAULT_BASE_HOST)
].join('.');
// preserve any extraneous input option keys (may have addition instructions for underlying request object)
Object
.keys(options)
.forEach((key) => {
if (!QUERY_KEYS.indexOf(key) &&
core.Validation.isEmpty(requestOptions[key]) &&
core.Validation.isEmpty(DEFAULT_REQUEST_OPTIONS[key])) {
requestOptions[key] = options[key];
}
});
// setup path
if (core.Validation.isEmpty(requestOptions.path)) {
requestOptions.path = DEFAULT_PATH;
}
// setup category
requestOptions.path = [
requestOptions.path,
core.Validation.coalesce(options.category, DEFAULT_CATEGORY)].join('');
// setup querystring
requestOptions.path = [requestOptions.path, DEFAULT_QUERYSTRING].join('');
// add search query (if specified)
if (!core.Validation.isEmpty(query)) {
requestOptions.path = [
requestOptions.path,
QUERY_PARAM_QUERY,
encodeURIComponent(query)].join('');
}
// add bundleDuplicates (if specified)
if (options.bundleDuplicates) {
requestOptions.path = [
requestOptions.path,
QUERY_PARAM_BUNDLE_DUPLICATES].join('');
}
// add hasPic (if specified)
if (options.hasImage || options.hasPic) {
requestOptions.path = [
requestOptions.path,
QUERY_PARAM_HAS_IMAGE].join('');
}
// add min asking price (if specified)
if (!core.Validation.isEmpty(options.minAsk)) {
requestOptions.path = [
requestOptions.path,
QUERY_PARAM_MIN,
options.minAsk].join('');
}
// add max asking price (if specified)
if (!core.Validation.isEmpty(options.maxAsk)) {
requestOptions.path = [
requestOptions.path,
QUERY_PARAM_MAX,
options.maxAsk].join('');
}
// add postal (if specified)
if (!core.Validation.isEmpty(options.postal)) {
requestOptions.path = [
requestOptions.path,
QUERY_PARAM_POSTAL,
options.postal].join('');
}
// add postedToday (if specified)
if (options.postedToday) {
requestOptions.path = [
requestOptions.path,
QUERY_PARAM_POSTED_TODAY].join('');
}
// add searchDistance (if specified)
if (!core.Validation.isEmpty(options.searchDistance)) {
requestOptions.path = [
requestOptions.path,
QUERY_PARAM_SEARCH_DISTANCE,
options.searchDistance].join('');
}
// add searchNearby (if specified)
if (options.searchNearby) {
requestOptions.path = [
requestOptions.path,
QUERY_PARAM_SEARCH_NEARBY].join('');
}
// add searchTitlesOnly (if specified)
if (options.searchTitlesOnly) {
requestOptions.path = [
requestOptions.path,
QUERY_PARAM_SEARCH_TITLES_ONLY].join('');
}
// add offset (if specified)
if (options.offset) {
requestOptions.path = [requestOptions.path, QUERY_PARAM_OFFSET, options.offset].join('');
}
debug('setting request options: %o', requestOptions);
return requestOptions;
} |
JavaScript | function topXByY (data, config) {
const x = config.key;
const y = config.value;
data.measure(x);
const results = data.breakdown(y);
return _.take(_.sortBy(results, (row) => row.rank), results.length);
} | function topXByY (data, config) {
const x = config.key;
const y = config.value;
data.measure(x);
const results = data.breakdown(y);
return _.take(_.sortBy(results, (row) => row.rank), results.length);
} |
JavaScript | reload (state, arg) {
navigationStateKeys.forEach(k => state[k] = '');
this.commit('detail/reset');
Object.keys(arg).forEach(k => {
const readFromURL = complexStateAdapters[k] || (x => x);
state[k] = readFromURL(arg[k]);
});
} | reload (state, arg) {
navigationStateKeys.forEach(k => state[k] = '');
this.commit('detail/reset');
Object.keys(arg).forEach(k => {
const readFromURL = complexStateAdapters[k] || (x => x);
state[k] = readFromURL(arg[k]);
});
} |
JavaScript | muteAudio() {
if (!this.audio || (this.audio && !this.audio.toggle)) {
return Promise.reject(new ParameterError('no audio control associated to the meeting'));
}
return this.audio.toggle({
mute: true,
self: true
})
.then(() => {
LoggerProxy.logger.info('Meeting:index#muteAudio --> Audio mute successful.');
Metrics.postEvent({
event: eventType.MUTED,
meeting: this,
data: {trigger: trigger.USER_INTERACTION, mediaType: mediaType.AUDIO}
});
return Promise.resolve();
})
.catch((e) => {
LoggerProxy.logger.error(`Meeting:index#muteAudio --> Audio mute error ${e}`);
});
} | muteAudio() {
if (!this.audio || (this.audio && !this.audio.toggle)) {
return Promise.reject(new ParameterError('no audio control associated to the meeting'));
}
return this.audio.toggle({
mute: true,
self: true
})
.then(() => {
LoggerProxy.logger.info('Meeting:index#muteAudio --> Audio mute successful.');
Metrics.postEvent({
event: eventType.MUTED,
meeting: this,
data: {trigger: trigger.USER_INTERACTION, mediaType: mediaType.AUDIO}
});
return Promise.resolve();
})
.catch((e) => {
LoggerProxy.logger.error(`Meeting:index#muteAudio --> Audio mute error ${e}`);
});
} |
JavaScript | function toggleTextTrack() {
$scope.isTextTrackVisible = !$scope.isTextTrackVisible;
if ($scope.isTextTrackVisible) {
_.forEach(video.textTracks, function (value, key) {
if ($scope.selectedLanguage) {
if (value.language === $scope.selectedLanguage) {
value.mode = 'showing';
}
} else {
video.textTracks[0].mode = 'showing';
}
});
} else {
_.forEach(video.textTracks, function (value, key) {
value.mode = 'hidden';
});
}
} | function toggleTextTrack() {
$scope.isTextTrackVisible = !$scope.isTextTrackVisible;
if ($scope.isTextTrackVisible) {
_.forEach(video.textTracks, function (value, key) {
if ($scope.selectedLanguage) {
if (value.language === $scope.selectedLanguage) {
value.mode = 'showing';
}
} else {
video.textTracks[0].mode = 'showing';
}
});
} else {
_.forEach(video.textTracks, function (value, key) {
value.mode = 'hidden';
});
}
} |
JavaScript | function changeVolume(amount) {
$scope.volumeChanged = true;
$timeout.cancel(volumeChangeTimeout);
//console.log('%c event', 'color: deeppink; font-weight: bold; text-shadow: 0 0 5px deeppink;', event);
$scope.volumeLevel += amount;
//console.log('%c event', 'color: deeppink; font-weight: bold; text-shadow: 0 0 5px deeppink;', event.deltaY, $scope.volumeLevel);
$scope.volumeLevel = $scope.volumeLevel.clamp(0, 10);
$scope.$apply();
volumeChangeTimeout = $timeout(function () {
$scope.volumeChanged = false;
}, 1500);
} | function changeVolume(amount) {
$scope.volumeChanged = true;
$timeout.cancel(volumeChangeTimeout);
//console.log('%c event', 'color: deeppink; font-weight: bold; text-shadow: 0 0 5px deeppink;', event);
$scope.volumeLevel += amount;
//console.log('%c event', 'color: deeppink; font-weight: bold; text-shadow: 0 0 5px deeppink;', event.deltaY, $scope.volumeLevel);
$scope.volumeLevel = $scope.volumeLevel.clamp(0, 10);
$scope.$apply();
volumeChangeTimeout = $timeout(function () {
$scope.volumeChanged = false;
}, 1500);
} |
JavaScript | function skipActivated() {
$scope.currentTimeChanged = true;
$scope.options.onTimeChange(video.currentTime, $scope.videoDuration);
$timeout.cancel(currentTimeChangeTimeout);
$scope.$apply();
currentTimeChangeTimeout = $timeout(function () {
$scope.currentTimeChanged = false;
}, 10000);
} | function skipActivated() {
$scope.currentTimeChanged = true;
$scope.options.onTimeChange(video.currentTime, $scope.videoDuration);
$timeout.cancel(currentTimeChangeTimeout);
$scope.$apply();
currentTimeChangeTimeout = $timeout(function () {
$scope.currentTimeChanged = false;
}, 10000);
} |
JavaScript | function createWinsockAlert(message) {
var tmpDiv = document.createElement("div");
tmpDiv.setAttribute("class", "WinsockAlertBoxID");
tmpDiv.setAttribute("role", "alert");
tmpDiv.className = "alert alert-info";
tmpDiv.appendChild(document.createTextNode(message));
document.getElementById("alertBox").appendChild(tmpDiv);
scrollToBottom();
} | function createWinsockAlert(message) {
var tmpDiv = document.createElement("div");
tmpDiv.setAttribute("class", "WinsockAlertBoxID");
tmpDiv.setAttribute("role", "alert");
tmpDiv.className = "alert alert-info";
tmpDiv.appendChild(document.createTextNode(message));
document.getElementById("alertBox").appendChild(tmpDiv);
scrollToBottom();
} |
JavaScript | function createNormalAlert(message) {
var tmpDiv = document.createElement("div");
tmpDiv.setAttribute("class", "NormalAlertBoxID");
tmpDiv.setAttribute("role", "alert");
tmpDiv.className = "alert alert-secondary";
tmpDiv.appendChild(document.createTextNode(message));
document.getElementById("alertBox").appendChild(tmpDiv);
scrollToBottom();
} | function createNormalAlert(message) {
var tmpDiv = document.createElement("div");
tmpDiv.setAttribute("class", "NormalAlertBoxID");
tmpDiv.setAttribute("role", "alert");
tmpDiv.className = "alert alert-secondary";
tmpDiv.appendChild(document.createTextNode(message));
document.getElementById("alertBox").appendChild(tmpDiv);
scrollToBottom();
} |
JavaScript | function createGoodAlert(message) {
var tmpDiv = document.createElement("div");
tmpDiv.setAttribute("class", "GoodAlertBoxID");
tmpDiv.setAttribute("role", "alert");
tmpDiv.className = "alert alert-success";
tmpDiv.appendChild(document.createTextNode(message));
document.getElementById("alertBox").appendChild(tmpDiv);
scrollToBottom();
} | function createGoodAlert(message) {
var tmpDiv = document.createElement("div");
tmpDiv.setAttribute("class", "GoodAlertBoxID");
tmpDiv.setAttribute("role", "alert");
tmpDiv.className = "alert alert-success";
tmpDiv.appendChild(document.createTextNode(message));
document.getElementById("alertBox").appendChild(tmpDiv);
scrollToBottom();
} |
JavaScript | waitAndShiftEvent(eventName) {
return new Promise((resolve, reject) => {
if (this._events[eventName].length > 0) {
return resolve(this._events[eventName].shift());
}
this.waitForEventImpl(this, Date.now(), eventName, 1, error => {
if (error) return reject(error);
resolve(this._events[eventName].shift());
});
});
} | waitAndShiftEvent(eventName) {
return new Promise((resolve, reject) => {
if (this._events[eventName].length > 0) {
return resolve(this._events[eventName].shift());
}
this.waitForEventImpl(this, Date.now(), eventName, 1, error => {
if (error) return reject(error);
resolve(this._events[eventName].shift());
});
});
} |
JavaScript | function guardDirections (options) {
const dir = options.direction
if (typeof dir === 'string') {
const hammerDirection = 'DIRECTION_' + dir.toUpperCase()
if (directions.indexOf(dir) > -1 && Hammer.hasOwnProperty(hammerDirection)) {
options.direction = Hammer[hammerDirection]
} else {
console.warn('[vue-touch] invalid direction: ' + dir)
}
}
return options
} | function guardDirections (options) {
const dir = options.direction
if (typeof dir === 'string') {
const hammerDirection = 'DIRECTION_' + dir.toUpperCase()
if (directions.indexOf(dir) > -1 && Hammer.hasOwnProperty(hammerDirection)) {
options.direction = Hammer[hammerDirection]
} else {
console.warn('[vue-touch] invalid direction: ' + dir)
}
}
return options
} |
JavaScript | function addRecognizer (gesture, options, { mainGesture } = {}) {
// create recognizer, e.g. new Hammer['Swipe'](options)
if (!this.recognizers[gesture]) {
this.recognizers[gesture] = new HammerNew[capitalize(mainGesture || gesture)](guardDirections(options))
this.hammer.add(this.recognizers[gesture])
}
} | function addRecognizer (gesture, options, { mainGesture } = {}) {
// create recognizer, e.g. new Hammer['Swipe'](options)
if (!this.recognizers[gesture]) {
this.recognizers[gesture] = new HammerNew[capitalize(mainGesture || gesture)](guardDirections(options))
this.hammer.add(this.recognizers[gesture])
}
} |
JavaScript | function propagating(hammer, options) {
var _options = options || {
preventDefault: false
};
if (hammer.Manager) {
// This looks like the Hammer constructor.
// Overload the constructors with our own.
var Hammer = hammer;
var PropagatingHammer = function(element, options) {
var o = Object.create(_options);
if (options) { Hammer.assign(o, options); }
return propagating(new Hammer(element, o), o);
};
Hammer.assign(PropagatingHammer, Hammer);
PropagatingHammer.Manager = function (element, options) {
var o = Object.create(_options);
if (options) { Hammer.assign(o, options); }
return propagating(new Hammer.Manager(element, o), o);
};
return PropagatingHammer;
}
// create a wrapper object which will override the functions
// `on`, `off`, `destroy`, and `emit` of the hammer instance
var wrapper = Object.create(hammer);
// attach to DOM element
var element = hammer.element;
if(!element.hammer) { element.hammer = []; }
element.hammer.push(wrapper);
// register an event to catch the start of a gesture and store the
// target in a singleton
hammer.on('hammer.input', function (event) {
if (_options.preventDefault === true || (_options.preventDefault === event.pointerType)) {
event.preventDefault();
}
if (event.isFirst) {
_firstTarget = event.target;
}
});
/** @type {Object.<String, Array.<function>>} */
wrapper._handlers = {};
/**
* Register a handler for one or multiple events
* @param {String} events A space separated string with events
* @param {function} handler A callback function, called as handler(event)
* @returns {Hammer.Manager} Returns the hammer instance
*/
wrapper.on = function (events, handler) {
// register the handler
split(events).forEach(function (event) {
var _handlers = wrapper._handlers[event];
if (!_handlers) {
wrapper._handlers[event] = _handlers = [];
// register the static, propagated handler
hammer.on(event, propagatedHandler);
}
_handlers.push(handler);
});
return wrapper;
};
/**
* Unregister a handler for one or multiple events
* @param {String} events A space separated string with events
* @param {function} [handler] Optional. The registered handler. If not
* provided, all handlers for given events
* are removed.
* @returns {Hammer.Manager} Returns the hammer instance
*/
wrapper.off = function (events, handler) {
// unregister the handler
split(events).forEach(function (event) {
var _handlers = wrapper._handlers[event];
if (_handlers) {
_handlers = handler ? _handlers.filter(function (h) {
return h !== handler;
}) : [];
if (_handlers.length > 0) {
wrapper._handlers[event] = _handlers;
}
else {
// remove static, propagated handler
hammer.off(event, propagatedHandler);
delete wrapper._handlers[event];
}
}
});
return wrapper;
};
/**
* Emit to the event listeners
* @param {string} eventType
* @param {Event} event
*/
wrapper.emit = function(eventType, event) {
_firstTarget = event.target;
hammer.emit(eventType, event);
};
wrapper.destroy = function () {
// Detach from DOM element
var hammers = hammer.element.hammer;
var idx = hammers.indexOf(wrapper);
if(idx !== -1) { hammers.splice(idx,1); }
if(!hammers.length) { delete hammer.element.hammer; }
// clear all handlers
wrapper._handlers = {};
// call original hammer destroy
hammer.destroy();
};
// split a string with space separated words
function split(events) {
return events.match(/[^ ]+/g);
}
/**
* A static event handler, applying event propagation.
* @param {Object} event
*/
function propagatedHandler(event) {
// let only a single hammer instance handle this event
if (event.type !== 'hammer.input') {
// it is possible that the same srcEvent is used with multiple hammer events,
// we keep track on which events are handled in an object _handled
if (!event.srcEvent._handled) {
event.srcEvent._handled = {};
}
if (event.srcEvent._handled[event.type]) {
return;
}
else {
event.srcEvent._handled[event.type] = true;
}
}
// attach a stopPropagation function to the event
var stopped = false;
event.stopPropagation = function () {
stopped = true;
};
//wrap the srcEvent's stopPropagation to also stop hammer propagation:
var srcStop = event.srcEvent.stopPropagation.bind(event.srcEvent);
if(typeof srcStop == "function") {
event.srcEvent.stopPropagation = function(){
srcStop();
event.stopPropagation();
};
}
// attach firstTarget property to the event
event.firstTarget = _firstTarget;
// propagate over all elements (until stopped)
var elem = _firstTarget;
while (elem && !stopped) {
var elemHammer = elem.hammer;
if(elemHammer){
var _handlers;
for(var k = 0; k < elemHammer.length; k++){
_handlers = elemHammer[k]._handlers[event.type];
if(_handlers) { for (var i = 0; i < _handlers.length && !stopped; i++) {
_handlers[i](event);
} }
}
}
elem = elem.parentNode;
}
}
return wrapper;
} | function propagating(hammer, options) {
var _options = options || {
preventDefault: false
};
if (hammer.Manager) {
// This looks like the Hammer constructor.
// Overload the constructors with our own.
var Hammer = hammer;
var PropagatingHammer = function(element, options) {
var o = Object.create(_options);
if (options) { Hammer.assign(o, options); }
return propagating(new Hammer(element, o), o);
};
Hammer.assign(PropagatingHammer, Hammer);
PropagatingHammer.Manager = function (element, options) {
var o = Object.create(_options);
if (options) { Hammer.assign(o, options); }
return propagating(new Hammer.Manager(element, o), o);
};
return PropagatingHammer;
}
// create a wrapper object which will override the functions
// `on`, `off`, `destroy`, and `emit` of the hammer instance
var wrapper = Object.create(hammer);
// attach to DOM element
var element = hammer.element;
if(!element.hammer) { element.hammer = []; }
element.hammer.push(wrapper);
// register an event to catch the start of a gesture and store the
// target in a singleton
hammer.on('hammer.input', function (event) {
if (_options.preventDefault === true || (_options.preventDefault === event.pointerType)) {
event.preventDefault();
}
if (event.isFirst) {
_firstTarget = event.target;
}
});
/** @type {Object.<String, Array.<function>>} */
wrapper._handlers = {};
/**
* Register a handler for one or multiple events
* @param {String} events A space separated string with events
* @param {function} handler A callback function, called as handler(event)
* @returns {Hammer.Manager} Returns the hammer instance
*/
wrapper.on = function (events, handler) {
// register the handler
split(events).forEach(function (event) {
var _handlers = wrapper._handlers[event];
if (!_handlers) {
wrapper._handlers[event] = _handlers = [];
// register the static, propagated handler
hammer.on(event, propagatedHandler);
}
_handlers.push(handler);
});
return wrapper;
};
/**
* Unregister a handler for one or multiple events
* @param {String} events A space separated string with events
* @param {function} [handler] Optional. The registered handler. If not
* provided, all handlers for given events
* are removed.
* @returns {Hammer.Manager} Returns the hammer instance
*/
wrapper.off = function (events, handler) {
// unregister the handler
split(events).forEach(function (event) {
var _handlers = wrapper._handlers[event];
if (_handlers) {
_handlers = handler ? _handlers.filter(function (h) {
return h !== handler;
}) : [];
if (_handlers.length > 0) {
wrapper._handlers[event] = _handlers;
}
else {
// remove static, propagated handler
hammer.off(event, propagatedHandler);
delete wrapper._handlers[event];
}
}
});
return wrapper;
};
/**
* Emit to the event listeners
* @param {string} eventType
* @param {Event} event
*/
wrapper.emit = function(eventType, event) {
_firstTarget = event.target;
hammer.emit(eventType, event);
};
wrapper.destroy = function () {
// Detach from DOM element
var hammers = hammer.element.hammer;
var idx = hammers.indexOf(wrapper);
if(idx !== -1) { hammers.splice(idx,1); }
if(!hammers.length) { delete hammer.element.hammer; }
// clear all handlers
wrapper._handlers = {};
// call original hammer destroy
hammer.destroy();
};
// split a string with space separated words
function split(events) {
return events.match(/[^ ]+/g);
}
/**
* A static event handler, applying event propagation.
* @param {Object} event
*/
function propagatedHandler(event) {
// let only a single hammer instance handle this event
if (event.type !== 'hammer.input') {
// it is possible that the same srcEvent is used with multiple hammer events,
// we keep track on which events are handled in an object _handled
if (!event.srcEvent._handled) {
event.srcEvent._handled = {};
}
if (event.srcEvent._handled[event.type]) {
return;
}
else {
event.srcEvent._handled[event.type] = true;
}
}
// attach a stopPropagation function to the event
var stopped = false;
event.stopPropagation = function () {
stopped = true;
};
//wrap the srcEvent's stopPropagation to also stop hammer propagation:
var srcStop = event.srcEvent.stopPropagation.bind(event.srcEvent);
if(typeof srcStop == "function") {
event.srcEvent.stopPropagation = function(){
srcStop();
event.stopPropagation();
};
}
// attach firstTarget property to the event
event.firstTarget = _firstTarget;
// propagate over all elements (until stopped)
var elem = _firstTarget;
while (elem && !stopped) {
var elemHammer = elem.hammer;
if(elemHammer){
var _handlers;
for(var k = 0; k < elemHammer.length; k++){
_handlers = elemHammer[k]._handlers[event.type];
if(_handlers) { for (var i = 0; i < _handlers.length && !stopped; i++) {
_handlers[i](event);
} }
}
}
elem = elem.parentNode;
}
}
return wrapper;
} |
JavaScript | function propagatedHandler(event) {
// let only a single hammer instance handle this event
if (event.type !== 'hammer.input') {
// it is possible that the same srcEvent is used with multiple hammer events,
// we keep track on which events are handled in an object _handled
if (!event.srcEvent._handled) {
event.srcEvent._handled = {};
}
if (event.srcEvent._handled[event.type]) {
return;
}
else {
event.srcEvent._handled[event.type] = true;
}
}
// attach a stopPropagation function to the event
var stopped = false;
event.stopPropagation = function () {
stopped = true;
};
//wrap the srcEvent's stopPropagation to also stop hammer propagation:
var srcStop = event.srcEvent.stopPropagation.bind(event.srcEvent);
if(typeof srcStop == "function") {
event.srcEvent.stopPropagation = function(){
srcStop();
event.stopPropagation();
};
}
// attach firstTarget property to the event
event.firstTarget = _firstTarget;
// propagate over all elements (until stopped)
var elem = _firstTarget;
while (elem && !stopped) {
var elemHammer = elem.hammer;
if(elemHammer){
var _handlers;
for(var k = 0; k < elemHammer.length; k++){
_handlers = elemHammer[k]._handlers[event.type];
if(_handlers) { for (var i = 0; i < _handlers.length && !stopped; i++) {
_handlers[i](event);
} }
}
}
elem = elem.parentNode;
}
} | function propagatedHandler(event) {
// let only a single hammer instance handle this event
if (event.type !== 'hammer.input') {
// it is possible that the same srcEvent is used with multiple hammer events,
// we keep track on which events are handled in an object _handled
if (!event.srcEvent._handled) {
event.srcEvent._handled = {};
}
if (event.srcEvent._handled[event.type]) {
return;
}
else {
event.srcEvent._handled[event.type] = true;
}
}
// attach a stopPropagation function to the event
var stopped = false;
event.stopPropagation = function () {
stopped = true;
};
//wrap the srcEvent's stopPropagation to also stop hammer propagation:
var srcStop = event.srcEvent.stopPropagation.bind(event.srcEvent);
if(typeof srcStop == "function") {
event.srcEvent.stopPropagation = function(){
srcStop();
event.stopPropagation();
};
}
// attach firstTarget property to the event
event.firstTarget = _firstTarget;
// propagate over all elements (until stopped)
var elem = _firstTarget;
while (elem && !stopped) {
var elemHammer = elem.hammer;
if(elemHammer){
var _handlers;
for(var k = 0; k < elemHammer.length; k++){
_handlers = elemHammer[k]._handlers[event.type];
if(_handlers) { for (var i = 0; i < _handlers.length && !stopped; i++) {
_handlers[i](event);
} }
}
}
elem = elem.parentNode;
}
} |
JavaScript | function guardDirections (options) {
var dir = options.direction;
if (typeof dir === 'string') {
var hammerDirection = 'DIRECTION_' + dir.toUpperCase();
if (directions.indexOf(dir) > -1 && hammer.hasOwnProperty(hammerDirection)) {
options.direction = hammer[hammerDirection];
} else {
console.warn('[vue-touch] invalid direction: ' + dir);
}
}
return options
} | function guardDirections (options) {
var dir = options.direction;
if (typeof dir === 'string') {
var hammerDirection = 'DIRECTION_' + dir.toUpperCase();
if (directions.indexOf(dir) > -1 && hammer.hasOwnProperty(hammerDirection)) {
options.direction = hammer[hammerDirection];
} else {
console.warn('[vue-touch] invalid direction: ' + dir);
}
}
return options
} |
JavaScript | function addRecognizer (gesture, options, ref) {
if ( ref === void 0 ) ref = {};
var mainGesture = ref.mainGesture;
// create recognizer, e.g. new Hammer['Swipe'](options)
if (!this.recognizers[gesture]) {
this.recognizers[gesture] = new HammerNew[capitalize(mainGesture || gesture)](guardDirections(options));
this.hammer.add(this.recognizers[gesture]);
}
} | function addRecognizer (gesture, options, ref) {
if ( ref === void 0 ) ref = {};
var mainGesture = ref.mainGesture;
// create recognizer, e.g. new Hammer['Swipe'](options)
if (!this.recognizers[gesture]) {
this.recognizers[gesture] = new HammerNew[capitalize(mainGesture || gesture)](guardDirections(options));
this.hammer.add(this.recognizers[gesture]);
}
} |
JavaScript | function createInstanceFromTemplate (template, spy = noop) {
const el = document.createElement('div')
const i = new Vue({
el,
template: `<div id="app">${template}</div>`,
methods: {
cb (e) {
spy(e)
}
}
}).$mount()
return i
} | function createInstanceFromTemplate (template, spy = noop) {
const el = document.createElement('div')
const i = new Vue({
el,
template: `<div id="app">${template}</div>`,
methods: {
cb (e) {
spy(e)
}
}
}).$mount()
return i
} |
JavaScript | function hasHandler (vt, gesture) {
const handlers = vt.hammer.handlers
const keys = Object.keys(handlers)
return keys.some(h => h === gesture && handlers[h].length > 0)
} | function hasHandler (vt, gesture) {
const handlers = vt.hammer.handlers
const keys = Object.keys(handlers)
return keys.some(h => h === gesture && handlers[h].length > 0)
} |
JavaScript | _ruleIdToActionType(ruleId) {
let actionType
// Test if it matches format "ListingPurchase<listingId>"
// otherwise use the ruleIdToActionType dictionary.
if (ruleId.match(/^ListingPurchase[\d-]+$/)) {
actionType = 'ListingIdPurchased'
} else if (ruleId.match(/^TwitterShare[\d-]+$/)) {
actionType = 'TwitterShare'
} else if (ruleId.match(/^FacebookShare[\d-]+$/)) {
actionType = 'FacebookShare'
} else {
actionType = ruleIdToActionType[ruleId]
}
if (!actionType) {
throw new Error(`Unexpected ruleId ${ruleId}`)
}
return actionType
} | _ruleIdToActionType(ruleId) {
let actionType
// Test if it matches format "ListingPurchase<listingId>"
// otherwise use the ruleIdToActionType dictionary.
if (ruleId.match(/^ListingPurchase[\d-]+$/)) {
actionType = 'ListingIdPurchased'
} else if (ruleId.match(/^TwitterShare[\d-]+$/)) {
actionType = 'TwitterShare'
} else if (ruleId.match(/^FacebookShare[\d-]+$/)) {
actionType = 'FacebookShare'
} else {
actionType = ruleIdToActionType[ruleId]
}
if (!actionType) {
throw new Error(`Unexpected ruleId ${ruleId}`)
}
return actionType
} |
JavaScript | async function addLockup(userId, amount, data = {}) {
const user = await hasBalance(userId, amount)
const unconfirmedLockups = await Lockup.findAll({
where: {
userId: user.id,
confirmed: null, // Unconfirmed
created_at: {
[Sequelize.Op.gte]: moment
.utc()
.subtract(lockupConfirmationTimeout, 'minutes')
}
}
})
if (unconfirmedLockups.length > 0) {
throw new ReferenceError(
'Unconfirmed lockups exist, please confirm or wait until expiry'
)
}
let lockup
const txn = await sequelize.transaction()
try {
lockup = await Lockup.create({
userId: user.id,
start: moment.utc(),
end: moment.utc().add(lockupDuration, 'months'),
bonusRate: lockupBonusRate,
amount,
data
})
await Event.create({
userId: user.id,
action: LOCKUP_REQUEST,
data: JSON.stringify({
lockupId: lockup.id
})
})
await txn.commit()
} catch (e) {
await txn.rollback()
logger.error(`Failed to add lockup for user ${userId}: ${e}`)
throw e
}
await sendLockupConfirmationEmail(lockup, user)
return lockup
} | async function addLockup(userId, amount, data = {}) {
const user = await hasBalance(userId, amount)
const unconfirmedLockups = await Lockup.findAll({
where: {
userId: user.id,
confirmed: null, // Unconfirmed
created_at: {
[Sequelize.Op.gte]: moment
.utc()
.subtract(lockupConfirmationTimeout, 'minutes')
}
}
})
if (unconfirmedLockups.length > 0) {
throw new ReferenceError(
'Unconfirmed lockups exist, please confirm or wait until expiry'
)
}
let lockup
const txn = await sequelize.transaction()
try {
lockup = await Lockup.create({
userId: user.id,
start: moment.utc(),
end: moment.utc().add(lockupDuration, 'months'),
bonusRate: lockupBonusRate,
amount,
data
})
await Event.create({
userId: user.id,
action: LOCKUP_REQUEST,
data: JSON.stringify({
lockupId: lockup.id
})
})
await txn.commit()
} catch (e) {
await txn.rollback()
logger.error(`Failed to add lockup for user ${userId}: ${e}`)
throw e
}
await sendLockupConfirmationEmail(lockup, user)
return lockup
} |
JavaScript | async function sendLockupConfirmationEmail(lockup, user) {
const token = jwt.sign(
{
lockupId: lockup.id
},
encryptionSecret,
{ expiresIn: `${lockupConfirmationTimeout}m` }
)
const vars = {
url: `${clientUrl}/lockup/${lockup.id}/${token}`,
employee: user.employee
}
await sendEmail(user.email, 'lockup', vars)
logger.info(
`Sent email lockup confirmation token to ${user.email} for lockup ${lockup.id}`
)
} | async function sendLockupConfirmationEmail(lockup, user) {
const token = jwt.sign(
{
lockupId: lockup.id
},
encryptionSecret,
{ expiresIn: `${lockupConfirmationTimeout}m` }
)
const vars = {
url: `${clientUrl}/lockup/${lockup.id}/${token}`,
employee: user.employee
}
await sendEmail(user.email, 'lockup', vars)
logger.info(
`Sent email lockup confirmation token to ${user.email} for lockup ${lockup.id}`
)
} |
JavaScript | function momentizeLockup(lockup) {
return {
...lockup,
start: toMoment(lockup.start),
end: toMoment(lockup.end)
}
} | function momentizeLockup(lockup) {
return {
...lockup,
start: toMoment(lockup.start),
end: toMoment(lockup.end)
}
} |
JavaScript | function calculateGranted(grants) {
return grants.reduce((total, grant) => {
return total.plus(grant.amount)
}, BigNumber(0))
} | function calculateGranted(grants) {
return grants.reduce((total, grant) => {
return total.plus(grant.amount)
}, BigNumber(0))
} |
JavaScript | function calculateVested(user, grants) {
return grants.reduce((total, grant) => {
if (grant.dataValues) {
// Convert if instance of sequelize model
grant = grant.get({ plain: true })
}
return total.plus(vestedAmount(user, grant))
}, BigNumber(0))
} | function calculateVested(user, grants) {
return grants.reduce((total, grant) => {
if (grant.dataValues) {
// Convert if instance of sequelize model
grant = grant.get({ plain: true })
}
return total.plus(vestedAmount(user, grant))
}, BigNumber(0))
} |
JavaScript | function calculateUnlockedEarnings(lockups) {
return lockups.reduce((total, lockup) => {
if (lockup.confirmed && lockup.end <= moment.utc()) {
const earnings = BigNumber(lockup.amount)
.times(lockup.bonusRate)
.div(BigNumber(100))
.toFixed(0, BigNumber.ROUND_HALF_UP)
return total.plus(earnings)
}
return total
}, BigNumber(0))
} | function calculateUnlockedEarnings(lockups) {
return lockups.reduce((total, lockup) => {
if (lockup.confirmed && lockup.end <= moment.utc()) {
const earnings = BigNumber(lockup.amount)
.times(lockup.bonusRate)
.div(BigNumber(100))
.toFixed(0, BigNumber.ROUND_HALF_UP)
return total.plus(earnings)
}
return total
}, BigNumber(0))
} |
JavaScript | function calculateEarnings(lockups) {
return lockups.reduce((total, lockup) => {
if (lockup.confirmed) {
const earnings = BigNumber(lockup.amount)
.times(lockup.bonusRate)
.div(BigNumber(100))
.toFixed(0, BigNumber.ROUND_HALF_UP)
return total.plus(earnings)
}
return total
}, BigNumber(0))
} | function calculateEarnings(lockups) {
return lockups.reduce((total, lockup) => {
if (lockup.confirmed) {
const earnings = BigNumber(lockup.amount)
.times(lockup.bonusRate)
.div(BigNumber(100))
.toFixed(0, BigNumber.ROUND_HALF_UP)
return total.plus(earnings)
}
return total
}, BigNumber(0))
} |
JavaScript | function calculateLocked(lockups) {
return lockups.reduce((total, lockup) => {
if (
lockup.start < moment.utc() && // Lockup has started
lockup.end > moment.utc() // Lockup has not yet ended
) {
return total.plus(BigNumber(lockup.amount))
}
return total
}, BigNumber(0))
} | function calculateLocked(lockups) {
return lockups.reduce((total, lockup) => {
if (
lockup.start < moment.utc() && // Lockup has started
lockup.end > moment.utc() // Lockup has not yet ended
) {
return total.plus(BigNumber(lockup.amount))
}
return total
}, BigNumber(0))
} |
JavaScript | function calculateWithdrawn(transfers) {
// Sum the amount from transfers that are in a pending or success state
const pendingOrCompleteTransfers = [
enums.TransferStatuses.WaitingEmailConfirm,
enums.TransferStatuses.Enqueued,
enums.TransferStatuses.Paused,
enums.TransferStatuses.WaitingConfirmation,
enums.TransferStatuses.Success,
enums.TransferStatuses.Processing
]
return transfers.reduce((total, transfer) => {
if (pendingOrCompleteTransfers.includes(transfer.status)) {
if (
transfer.status === enums.TransferStatuses.WaitingEmailConfirm &&
transferHasExpired(transfer)
) {
return total
} else {
return total.plus(BigNumber(transfer.amount))
}
}
return total
}, BigNumber(0))
} | function calculateWithdrawn(transfers) {
// Sum the amount from transfers that are in a pending or success state
const pendingOrCompleteTransfers = [
enums.TransferStatuses.WaitingEmailConfirm,
enums.TransferStatuses.Enqueued,
enums.TransferStatuses.Paused,
enums.TransferStatuses.WaitingConfirmation,
enums.TransferStatuses.Success,
enums.TransferStatuses.Processing
]
return transfers.reduce((total, transfer) => {
if (pendingOrCompleteTransfers.includes(transfer.status)) {
if (
transfer.status === enums.TransferStatuses.WaitingEmailConfirm &&
transferHasExpired(transfer)
) {
return total
} else {
return total.plus(BigNumber(transfer.amount))
}
}
return total
}, BigNumber(0))
} |
JavaScript | async function sendTransferConfirmationEmail(transfer, user) {
const confirmationToken = jwt.sign(
{
transferId: transfer.id
},
encryptionSecret,
{ expiresIn: `${transferConfirmationTimeout}m` }
)
const vars = {
url: `${clientUrl}/withdrawal/${transfer.id}/${confirmationToken}`,
employee: user.employee
}
await sendEmail(user.email, 'transfer', vars)
logger.info(
`Sent email transfer confirmation token to ${user.email} for transfer ${transfer.id}`
)
} | async function sendTransferConfirmationEmail(transfer, user) {
const confirmationToken = jwt.sign(
{
transferId: transfer.id
},
encryptionSecret,
{ expiresIn: `${transferConfirmationTimeout}m` }
)
const vars = {
url: `${clientUrl}/withdrawal/${transfer.id}/${confirmationToken}`,
employee: user.employee
}
await sendEmail(user.email, 'transfer', vars)
logger.info(
`Sent email transfer confirmation token to ${user.email} for transfer ${transfer.id}`
)
} |
JavaScript | async function confirmTransfer(transfer, user) {
if (transfer.status !== enums.TransferStatuses.WaitingEmailConfirm) {
throw new Error('Transfer is not waiting for confirmation')
}
if (transferHasExpired(transfer)) {
await transfer.update({
status: enums.TransferStatuses.Expired
})
throw new Error('Transfer was not confirmed in the required time')
}
const txn = await sequelize.transaction()
// Change state of transfer and add event
try {
await transfer.update({
status: enums.TransferStatuses.Enqueued
})
const event = {
userId: user.id,
action: TRANSFER_CONFIRMED,
data: JSON.stringify({
transferId: transfer.id
})
}
await Event.create(event)
await txn.commit()
} catch (e) {
await txn.rollback()
logger.error(
`Failed writing confirmation data for transfer ${transfer.id}: ${e}`
)
throw e
}
try {
if (discordWebhookUrl) {
const countryDisplay = get(
transfer.data.location,
'countryName',
'Unknown'
)
const webhookData = {
embeds: [
{
title: `A transfer of \`${transfer.amount} OGN\` was queued by \`${user.email}\``,
description: [
`**ID:** \`${transfer.id}\``,
`**Address:** \`${transfer.toAddress}\``,
`**Country:** ${countryDisplay}`
].join('\n')
}
]
}
await postToWebhook(discordWebhookUrl, JSON.stringify(webhookData))
}
} catch (e) {
logger.error(
`Failed sending Discord webhook for token transfer confirmation:`,
e
)
}
logger.info(
`Transfer ${transfer.id} was confirmed by email token for ${user.email}`
)
return true
} | async function confirmTransfer(transfer, user) {
if (transfer.status !== enums.TransferStatuses.WaitingEmailConfirm) {
throw new Error('Transfer is not waiting for confirmation')
}
if (transferHasExpired(transfer)) {
await transfer.update({
status: enums.TransferStatuses.Expired
})
throw new Error('Transfer was not confirmed in the required time')
}
const txn = await sequelize.transaction()
// Change state of transfer and add event
try {
await transfer.update({
status: enums.TransferStatuses.Enqueued
})
const event = {
userId: user.id,
action: TRANSFER_CONFIRMED,
data: JSON.stringify({
transferId: transfer.id
})
}
await Event.create(event)
await txn.commit()
} catch (e) {
await txn.rollback()
logger.error(
`Failed writing confirmation data for transfer ${transfer.id}: ${e}`
)
throw e
}
try {
if (discordWebhookUrl) {
const countryDisplay = get(
transfer.data.location,
'countryName',
'Unknown'
)
const webhookData = {
embeds: [
{
title: `A transfer of \`${transfer.amount} OGN\` was queued by \`${user.email}\``,
description: [
`**ID:** \`${transfer.id}\``,
`**Address:** \`${transfer.toAddress}\``,
`**Country:** ${countryDisplay}`
].join('\n')
}
]
}
await postToWebhook(discordWebhookUrl, JSON.stringify(webhookData))
}
} catch (e) {
logger.error(
`Failed sending Discord webhook for token transfer confirmation:`,
e
)
}
logger.info(
`Transfer ${transfer.id} was confirmed by email token for ${user.email}`
)
return true
} |
JavaScript | async function executeTransfer(transfer, transferTaskId, token) {
const user = await hasBalance(transfer.userId, transfer.amount, transfer.id)
await transfer.update({
status: enums.TransferStatuses.Processing,
transferTaskId
})
// Send transaction to transfer the tokens and record txHash in the DB.
const naturalAmount = token.toNaturalUnit(transfer.amount)
const supplier = await token.defaultAccount()
const opts = {}
if (gasPriceMultiplier) {
opts.gasPriceMultiplier = gasPriceMultiplier
}
let txHash
try {
txHash = await token.credit(transfer.toAddress, naturalAmount, opts)
} catch (error) {
logger.error('Error crediting tokens', error.message)
await updateTransferStatus(
user,
transfer,
enums.TransferStatuses.Failed,
TRANSFER_FAILED,
error.message
)
return false
}
logger.info(`Transfer ${transfer.id} processed with hash ${txHash}`)
await transfer.update({
status: enums.TransferStatuses.WaitingConfirmation,
fromAddress: supplier.toLowerCase(),
txHash
})
return txHash
} | async function executeTransfer(transfer, transferTaskId, token) {
const user = await hasBalance(transfer.userId, transfer.amount, transfer.id)
await transfer.update({
status: enums.TransferStatuses.Processing,
transferTaskId
})
// Send transaction to transfer the tokens and record txHash in the DB.
const naturalAmount = token.toNaturalUnit(transfer.amount)
const supplier = await token.defaultAccount()
const opts = {}
if (gasPriceMultiplier) {
opts.gasPriceMultiplier = gasPriceMultiplier
}
let txHash
try {
txHash = await token.credit(transfer.toAddress, naturalAmount, opts)
} catch (error) {
logger.error('Error crediting tokens', error.message)
await updateTransferStatus(
user,
transfer,
enums.TransferStatuses.Failed,
TRANSFER_FAILED,
error.message
)
return false
}
logger.info(`Transfer ${transfer.id} processed with hash ${txHash}`)
await transfer.update({
status: enums.TransferStatuses.WaitingConfirmation,
fromAddress: supplier.toLowerCase(),
txHash
})
return txHash
} |
JavaScript | async function updateTransferStatus(
user,
transfer,
transferStatus,
eventAction,
failureReason
) {
// Update the status in the transfer table.
const txn = await sequelize.transaction()
try {
await transfer.update({
status: transferStatus
})
const event = {
userId: user.id,
action: eventAction,
data: {
transferId: transfer.id
}
}
if (failureReason) {
event.data.failureReason = failureReason
}
await Event.create(event)
await txn.commit()
} catch (e) {
await txn.rollback()
logger.error(
`Failed writing confirmation data for transfer ${transfer.id}: ${e}`
)
throw e
}
} | async function updateTransferStatus(
user,
transfer,
transferStatus,
eventAction,
failureReason
) {
// Update the status in the transfer table.
const txn = await sequelize.transaction()
try {
await transfer.update({
status: transferStatus
})
const event = {
userId: user.id,
action: eventAction,
data: {
transferId: transfer.id
}
}
if (failureReason) {
event.data.failureReason = failureReason
}
await Event.create(event)
await txn.commit()
} catch (e) {
await txn.rollback()
logger.error(
`Failed writing confirmation data for transfer ${transfer.id}: ${e}`
)
throw e
}
} |
JavaScript | function vestedAmount(user, grantObj) {
return vestingSchedule(user, grantObj)
.filter(v => v.vested)
.reduce((total, vestingEvent) => {
return total.plus(BigNumber(vestingEvent.amount))
}, BigNumber(0))
} | function vestedAmount(user, grantObj) {
return vestingSchedule(user, grantObj)
.filter(v => v.vested)
.reduce((total, vestingEvent) => {
return total.plus(BigNumber(vestingEvent.amount))
}, BigNumber(0))
} |
JavaScript | async _confirmTransaction(payout, currentBlockNumber) {
if (!this.config.doIt) {
return true
}
// Consistency checks.
if (payout.status === enums.GrowthPayoutStatuses.Confirmed) {
// Already confirmed. Nothing to do.
return true
}
if (payout.status !== enums.GrowthPayoutStatuses.Paid) {
throw new Error(
`Can't confirm payout id ${payout.id}, status is ${payout.status} rather than Paid`
)
}
if (!payout.txnHash) {
throw new Error(`Can't confirm payout id ${payout.id}, txnHash is empty`)
}
// Load the transaction receipt form the blockchain.
logger.info(`Verifying payout ${payout.id}`)
const txnReceipt = await this.web3.eth.getTransactionReceipt(payout.txnHash)
// Make sure we've waited long enough to verify the confirmation.
const numConfirmations = currentBlockNumber - txnReceipt.blockNumber
if (numConfirmations < MinBlockConfirmation) {
throw new Error('_confirmTransaction called too early.')
}
if (!txnReceipt.status) {
// The transaction did not get confirmed.
// Rollback the payout status from Paid to Failed so that the transaction
// gets attempted again next time the job runs.
logger.error(`Account ${payout.toAddress} Payout ${payout.id}`)
logger.error(' Transaction hash ${payout.txnHash} failed confirmation.')
logger.error(' Setting status to PaymentFailed.')
await payout.update({ status: enums.GrowthPayoutStatuses.Failed })
return false
}
logger.info(`Payout ${payout.id} confirmed.`)
await payout.update({ status: enums.GrowthPayoutStatuses.Confirmed })
return true
} | async _confirmTransaction(payout, currentBlockNumber) {
if (!this.config.doIt) {
return true
}
// Consistency checks.
if (payout.status === enums.GrowthPayoutStatuses.Confirmed) {
// Already confirmed. Nothing to do.
return true
}
if (payout.status !== enums.GrowthPayoutStatuses.Paid) {
throw new Error(
`Can't confirm payout id ${payout.id}, status is ${payout.status} rather than Paid`
)
}
if (!payout.txnHash) {
throw new Error(`Can't confirm payout id ${payout.id}, txnHash is empty`)
}
// Load the transaction receipt form the blockchain.
logger.info(`Verifying payout ${payout.id}`)
const txnReceipt = await this.web3.eth.getTransactionReceipt(payout.txnHash)
// Make sure we've waited long enough to verify the confirmation.
const numConfirmations = currentBlockNumber - txnReceipt.blockNumber
if (numConfirmations < MinBlockConfirmation) {
throw new Error('_confirmTransaction called too early.')
}
if (!txnReceipt.status) {
// The transaction did not get confirmed.
// Rollback the payout status from Paid to Failed so that the transaction
// gets attempted again next time the job runs.
logger.error(`Account ${payout.toAddress} Payout ${payout.id}`)
logger.error(' Transaction hash ${payout.txnHash} failed confirmation.')
logger.error(' Setting status to PaymentFailed.')
await payout.update({ status: enums.GrowthPayoutStatuses.Failed })
return false
}
logger.info(`Payout ${payout.id} confirmed.`)
await payout.update({ status: enums.GrowthPayoutStatuses.Confirmed })
return true
} |
JavaScript | async _confirmAllTransactions(campaignId) {
// Wait a bit for the last transaction to settle.
const waitMsec = this.config.doIt
? 2 * MinBlockConfirmation * BlockMiningTimeMsec
: 1000
logger.info(
`Waiting ${waitMsec / 1000} seconds to allow transactions to settle...`
)
await new Promise(resolve => setTimeout(resolve, waitMsec))
// Get current blockNumber from the blockchain.
const blockNumber = await this.web3.eth.getBlockNumber()
// Reload the payouts that are in status Paid.
const payouts = await db.GrowthPayout.findAll({
where: {
campaignId,
status: enums.GrowthPayoutStatuses.Paid
}
})
let allConfirmed = true
for (const payout of payouts) {
let confirmed
try {
confirmed = await this._confirmTransaction(payout, blockNumber)
} catch (e) {
logger.error('Failed verifying transaction:', e)
confirmed = false
}
allConfirmed = allConfirmed && confirmed
}
return allConfirmed
} | async _confirmAllTransactions(campaignId) {
// Wait a bit for the last transaction to settle.
const waitMsec = this.config.doIt
? 2 * MinBlockConfirmation * BlockMiningTimeMsec
: 1000
logger.info(
`Waiting ${waitMsec / 1000} seconds to allow transactions to settle...`
)
await new Promise(resolve => setTimeout(resolve, waitMsec))
// Get current blockNumber from the blockchain.
const blockNumber = await this.web3.eth.getBlockNumber()
// Reload the payouts that are in status Paid.
const payouts = await db.GrowthPayout.findAll({
where: {
campaignId,
status: enums.GrowthPayoutStatuses.Paid
}
})
let allConfirmed = true
for (const payout of payouts) {
let confirmed
try {
confirmed = await this._confirmTransaction(payout, blockNumber)
} catch (e) {
logger.error('Failed verifying transaction:', e)
confirmed = false
}
allConfirmed = allConfirmed && confirmed
}
return allConfirmed
} |
JavaScript | async _checkAllUsersPaid(campaignId, ethAddresses) {
if (!this.config.doIt) {
return true
}
let allPaid = true
for (const ethAddress of ethAddresses) {
const payout = await db.GrowthPayout.findOne({
where: {
toAddress: ethAddress,
campaignId,
status: enums.GrowthPayoutStatuses.Confirmed
}
})
if (!payout) {
logger.error(`Account ${ethAddress} was not paid.`)
allPaid = false
}
}
return allPaid
} | async _checkAllUsersPaid(campaignId, ethAddresses) {
if (!this.config.doIt) {
return true
}
let allPaid = true
for (const ethAddress of ethAddresses) {
const payout = await db.GrowthPayout.findOne({
where: {
toAddress: ethAddress,
campaignId,
status: enums.GrowthPayoutStatuses.Confirmed
}
})
if (!payout) {
logger.error(`Account ${ethAddress} was not paid.`)
allPaid = false
}
}
return allPaid
} |
JavaScript | async function hasBalance(userId, amount, currentTransferId = null) {
const user = await User.findOne({
where: {
id: userId
},
include: [{ model: Grant }, { model: Transfer }, { model: Lockup }]
})
// Load the user and check there enough tokens available to fulfill the
// transfer request
if (!user) {
throw new Error(`Could not find specified user id ${userId}`)
}
// Sum the vested tokens for all of the users grants
const vested = calculateVested(user, user.Grants)
logger.debug(`User ${user.email} vested tokens`, vested.toString())
// Sum the unlocked tokens from lockup earnings
const lockupEarnings = calculateUnlockedEarnings(user.Lockups)
logger.debug(
`User ${user.email} unlocked earnings from lockups`,
lockupEarnings.toString()
)
// Sum amount withdrawn or pending in transfers excluding the current transfer
// if provided (balance check while exeucting transfer)
const transferWithdrawnAmount = calculateWithdrawn(
user.Transfers.filter(t => t.id !== currentTransferId)
)
logger.debug(
`User ${user.email} pending or transferred tokens`,
transferWithdrawnAmount.toString()
)
// Sum locked by lockups
const lockedAmount = calculateLocked(user.Lockups)
logger.debug(`User ${user.email} tokens in lockup`, lockedAmount.toString())
// Calculate total available tokens
const available = vested
.plus(lockupEarnings)
.minus(transferWithdrawnAmount)
.minus(lockedAmount)
if (available.lt(0)) {
throw new RangeError(`Amount of available OGN is below 0`)
}
if (BigNumber(amount).gt(available)) {
throw new RangeError(
`Amount of ${amount} OGN exceeds the ${available} available for ${user.email}`
)
}
return user
} | async function hasBalance(userId, amount, currentTransferId = null) {
const user = await User.findOne({
where: {
id: userId
},
include: [{ model: Grant }, { model: Transfer }, { model: Lockup }]
})
// Load the user and check there enough tokens available to fulfill the
// transfer request
if (!user) {
throw new Error(`Could not find specified user id ${userId}`)
}
// Sum the vested tokens for all of the users grants
const vested = calculateVested(user, user.Grants)
logger.debug(`User ${user.email} vested tokens`, vested.toString())
// Sum the unlocked tokens from lockup earnings
const lockupEarnings = calculateUnlockedEarnings(user.Lockups)
logger.debug(
`User ${user.email} unlocked earnings from lockups`,
lockupEarnings.toString()
)
// Sum amount withdrawn or pending in transfers excluding the current transfer
// if provided (balance check while exeucting transfer)
const transferWithdrawnAmount = calculateWithdrawn(
user.Transfers.filter(t => t.id !== currentTransferId)
)
logger.debug(
`User ${user.email} pending or transferred tokens`,
transferWithdrawnAmount.toString()
)
// Sum locked by lockups
const lockedAmount = calculateLocked(user.Lockups)
logger.debug(`User ${user.email} tokens in lockup`, lockedAmount.toString())
// Calculate total available tokens
const available = vested
.plus(lockupEarnings)
.minus(transferWithdrawnAmount)
.minus(lockedAmount)
if (available.lt(0)) {
throw new RangeError(`Amount of available OGN is below 0`)
}
if (BigNumber(amount).gt(available)) {
throw new RangeError(
`Amount of ${amount} OGN exceeds the ${available} available for ${user.email}`
)
}
return user
} |
JavaScript | async _calcGasPrice() {
// Get default gas price from web3 which is determined by the
// last few blocks median gas price.
const medianGasPrice = await this.web3.eth.getGasPrice()
if (this.gasPriceMultiplier) {
// Apply our ratio.
const gasPrice = BigNumber(medianGasPrice).times(this.gasPriceMultiplier)
return gasPrice.integerValue()
}
return BigNumber(medianGasPrice)
} | async _calcGasPrice() {
// Get default gas price from web3 which is determined by the
// last few blocks median gas price.
const medianGasPrice = await this.web3.eth.getGasPrice()
if (this.gasPriceMultiplier) {
// Apply our ratio.
const gasPrice = BigNumber(medianGasPrice).times(this.gasPriceMultiplier)
return gasPrice.integerValue()
}
return BigNumber(medianGasPrice)
} |
JavaScript | function matchDispatchToProps(dispatch){
return bindActionCreators({
setupCharBlock: setupCharBlock,
setOriginalWordToGuess: setOriginalWordToGuess,
setupGuessWordBlock: setupGuessWordBlock
}, dispatch);
} | function matchDispatchToProps(dispatch){
return bindActionCreators({
setupCharBlock: setupCharBlock,
setOriginalWordToGuess: setOriginalWordToGuess,
setupGuessWordBlock: setupGuessWordBlock
}, dispatch);
} |
JavaScript | function drawPieChart() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
var centerX = Math.floor(canvas.width / 2);
var centerY = Math.floor(canvas.height / 2);
var radius = Math.floor(canvas.width / 3);
// Filling verified percentage of pie chart starting at 12 o'clock.
var percentage = factPct;
var startingAngle = Math.PI * 1.5;
var arcSize = degreesToRadians(percentage * 360); // Multiply % by 360 degrees for proportion of circle.
if(arcSize <= 0) arcSize = 0.000001;
var endingAngle = startingAngle + arcSize;
ctx.lineWidth = 20;
ctx.strokeStyle = "#4ED25E";
ctx.beginPath();
ctx.arc(centerX, centerY, radius, startingAngle, endingAngle, false);
ctx.stroke();
// Complementing it, for the full doughnut chart effect.
ctx.lineWidth = 20;
ctx.strokeStyle = "#ECF0F1";
ctx.beginPath();
ctx.arc(centerX, centerY, radius, endingAngle, startingAngle, false);
ctx.stroke();
// Add percentage readout.
if(percentage == 1.0) {
ctx.fillStyle = "#267F00";
ctx.font = "45px Arial";
}
if(percentage >= 0.8 && percentage < 1.0) {
ctx.fillStyle = "#267F00";
ctx.font = "50px Arial";
}
if(percentage < 0.8 && percentage > 0.6) {
ctx.fillStyle = "#FFFF00";
ctx.font = "50px Arial";
}
if(percentage <= 0.6 && percentage >= 0.1) {
ctx.fillStyle = "#E67E22";
ctx.font = "50px Arial";
}
if(percentage < 0.1) {
ctx.fillStyle = "#FF0000";
ctx.font = "50px Arial";
}
ctx.textAlign="center";
if(percentage == -1 || isNaN(percentage) || parsedData.length != totalFactoids) {
// Make pie chart a loading animation.
ctx.strokeStyle = "#4ED25E";
loadStartAngle = (1.5 * Math.PI * loadInc) / 100;
var loadEndAngle = loadStartAngle + loadArcSize;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, loadStartAngle, loadEndAngle, false);
ctx.stroke();
// Complementing it, for the full doughnut chart effect.
ctx.strokeStyle = "#ECF0F1";
ctx.beginPath();
ctx.arc(centerX, centerY, radius, loadEndAngle, loadStartAngle, false);
ctx.stroke();
ctx.font = "bold 30px Arial";
ctx.fillStyle = "#000000";
ctx.fillText("Loading...", centerX, centerY + 15);
loadInc = (loadInc + 1) % (134);
}
else {
ctx.fillText(Math.round(percentage * 100) + "%", centerX, centerY + 15);
ctx.font = "bold 15px Arial";
ctx.fillStyle = "#000000";
ctx.fillText("Verified", centerX, centerY + 40);
}
} | function drawPieChart() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
var centerX = Math.floor(canvas.width / 2);
var centerY = Math.floor(canvas.height / 2);
var radius = Math.floor(canvas.width / 3);
// Filling verified percentage of pie chart starting at 12 o'clock.
var percentage = factPct;
var startingAngle = Math.PI * 1.5;
var arcSize = degreesToRadians(percentage * 360); // Multiply % by 360 degrees for proportion of circle.
if(arcSize <= 0) arcSize = 0.000001;
var endingAngle = startingAngle + arcSize;
ctx.lineWidth = 20;
ctx.strokeStyle = "#4ED25E";
ctx.beginPath();
ctx.arc(centerX, centerY, radius, startingAngle, endingAngle, false);
ctx.stroke();
// Complementing it, for the full doughnut chart effect.
ctx.lineWidth = 20;
ctx.strokeStyle = "#ECF0F1";
ctx.beginPath();
ctx.arc(centerX, centerY, radius, endingAngle, startingAngle, false);
ctx.stroke();
// Add percentage readout.
if(percentage == 1.0) {
ctx.fillStyle = "#267F00";
ctx.font = "45px Arial";
}
if(percentage >= 0.8 && percentage < 1.0) {
ctx.fillStyle = "#267F00";
ctx.font = "50px Arial";
}
if(percentage < 0.8 && percentage > 0.6) {
ctx.fillStyle = "#FFFF00";
ctx.font = "50px Arial";
}
if(percentage <= 0.6 && percentage >= 0.1) {
ctx.fillStyle = "#E67E22";
ctx.font = "50px Arial";
}
if(percentage < 0.1) {
ctx.fillStyle = "#FF0000";
ctx.font = "50px Arial";
}
ctx.textAlign="center";
if(percentage == -1 || isNaN(percentage) || parsedData.length != totalFactoids) {
// Make pie chart a loading animation.
ctx.strokeStyle = "#4ED25E";
loadStartAngle = (1.5 * Math.PI * loadInc) / 100;
var loadEndAngle = loadStartAngle + loadArcSize;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, loadStartAngle, loadEndAngle, false);
ctx.stroke();
// Complementing it, for the full doughnut chart effect.
ctx.strokeStyle = "#ECF0F1";
ctx.beginPath();
ctx.arc(centerX, centerY, radius, loadEndAngle, loadStartAngle, false);
ctx.stroke();
ctx.font = "bold 30px Arial";
ctx.fillStyle = "#000000";
ctx.fillText("Loading...", centerX, centerY + 15);
loadInc = (loadInc + 1) % (134);
}
else {
ctx.fillText(Math.round(percentage * 100) + "%", centerX, centerY + 15);
ctx.font = "bold 15px Arial";
ctx.fillStyle = "#000000";
ctx.fillText("Verified", centerX, centerY + 40);
}
} |
JavaScript | function buildUI() {
var facts = document.getElementById('facts');
document.getElementById("fact_num").innerHTML = parsedData.length.toLocaleString();
drawPieChart();
// Generate a list of facts so the user knows what was checked and what to disregard.
facts.onclick = function() {
var list = document.createElement('ul');
$(list).css("list-style", "none");
$(list).css("padding", "0");
$(list).css("margin", "0");
list.id = "genList";
if(!isFactListVisible && parsedData && parsedData.length > 0) {
for(var i = 0; i < parsedData.length; i++) {
var factItem = document.createElement('li');
var factError = document.createElement('span');
var factBefore = "";
if(factRecord[i] == '1') {
factBefore = "✅";
}
else {
factBefore = "❌";
}
if(factRecord[i] == "404") {
factError.append(document.createTextNode("[404 Error - Could Not Check]"));
$(factError).css("color", "#AD0000");
}
factItem.append(document.createTextNode(factBefore + " "));
factItem.append(factError);
factItem.append(document.createTextNode(parsedData[i]));
$(factItem).css("padding", "5px 0px");
list.appendChild(factItem);
}
document.getElementById('factList').appendChild(list);
isFactListVisible = true;
}
else {
document.getElementById('factList').innerHTML = "";
isFactListVisible = false;
}
return false;
};
var linkSearch = document.getElementById('links');
if(keyWords) {
keyWords = keyWords.replace(/\s/g, "%20");
linkSearch.href = "https://www.google.com/search?q=" + keyWords;
$('#links').show();
}
else {
$('#links').hide();
}
} | function buildUI() {
var facts = document.getElementById('facts');
document.getElementById("fact_num").innerHTML = parsedData.length.toLocaleString();
drawPieChart();
// Generate a list of facts so the user knows what was checked and what to disregard.
facts.onclick = function() {
var list = document.createElement('ul');
$(list).css("list-style", "none");
$(list).css("padding", "0");
$(list).css("margin", "0");
list.id = "genList";
if(!isFactListVisible && parsedData && parsedData.length > 0) {
for(var i = 0; i < parsedData.length; i++) {
var factItem = document.createElement('li');
var factError = document.createElement('span');
var factBefore = "";
if(factRecord[i] == '1') {
factBefore = "✅";
}
else {
factBefore = "❌";
}
if(factRecord[i] == "404") {
factError.append(document.createTextNode("[404 Error - Could Not Check]"));
$(factError).css("color", "#AD0000");
}
factItem.append(document.createTextNode(factBefore + " "));
factItem.append(factError);
factItem.append(document.createTextNode(parsedData[i]));
$(factItem).css("padding", "5px 0px");
list.appendChild(factItem);
}
document.getElementById('factList').appendChild(list);
isFactListVisible = true;
}
else {
document.getElementById('factList').innerHTML = "";
isFactListVisible = false;
}
return false;
};
var linkSearch = document.getElementById('links');
if(keyWords) {
keyWords = keyWords.replace(/\s/g, "%20");
linkSearch.href = "https://www.google.com/search?q=" + keyWords;
$('#links').show();
}
else {
$('#links').hide();
}
} |
JavaScript | function startFactCheck() {
var factsToCheck = document.getElementById('fact_box').value;
var contentParse = contentScrape(factsToCheck, this.url);
// Immediately post relevant data to background.js
bgWorker.postMessage({"contentParse" : contentParse.data, "tags" : contentParse.tags, "url" : contentParse.url});
// Query the background script for factoid data. This should probably be a listener of sorts.
pollFactData();
clearInterval(pollInterval);
pollInterval = setInterval(pollFactData, 500);
// Continuously build/update the UI as factoid data is processed.
buildUI();
clearInterval(buildUIInterval);
buildUIInterval = setInterval(buildUI, 250);
setAnalysisUI(); // Transition from initial screen to factoid analysis UI.
// if(urlToCheck != url) {
// $.ajax({
// type: "GET",
// url: urlToCheck,
// dataType: "html",
// async: true,
// success: function (html) {
//
// },
// error: function (xhr, status, error) {
// console.error("Error: startFactCheck() could not get requested page to check. Message: " + error +
// "." + "\n" + "Site: " + url);
//
// document.getElementById("fact_text").style.color="#FF0000";
// document.getElementById("fact_text").innerHTML = "404 Page Not Found.<br><br>URL Invalid or Site Is Offline.";
// }
// });
// }
} | function startFactCheck() {
var factsToCheck = document.getElementById('fact_box').value;
var contentParse = contentScrape(factsToCheck, this.url);
// Immediately post relevant data to background.js
bgWorker.postMessage({"contentParse" : contentParse.data, "tags" : contentParse.tags, "url" : contentParse.url});
// Query the background script for factoid data. This should probably be a listener of sorts.
pollFactData();
clearInterval(pollInterval);
pollInterval = setInterval(pollFactData, 500);
// Continuously build/update the UI as factoid data is processed.
buildUI();
clearInterval(buildUIInterval);
buildUIInterval = setInterval(buildUI, 250);
setAnalysisUI(); // Transition from initial screen to factoid analysis UI.
// if(urlToCheck != url) {
// $.ajax({
// type: "GET",
// url: urlToCheck,
// dataType: "html",
// async: true,
// success: function (html) {
//
// },
// error: function (xhr, status, error) {
// console.error("Error: startFactCheck() could not get requested page to check. Message: " + error +
// "." + "\n" + "Site: " + url);
//
// document.getElementById("fact_text").style.color="#FF0000";
// document.getElementById("fact_text").innerHTML = "404 Page Not Found.<br><br>URL Invalid or Site Is Offline.";
// }
// });
// }
} |
JavaScript | function scrollPage(element, callback, isMovementUp){
//requestAnimFrame is used in order to prevent a Chrome 44 bug (http://stackoverflow.com/a/31961816/1081396)
requestAnimFrame(function(){
var dest = element.position();
if(typeof dest === 'undefined'){ return; } //there's no element to scroll, leaving the function
//auto height? Scrolling only a bit, the next element's height. Otherwise the whole viewport.
var dtop = element.hasClass(AUTO_HEIGHT) ? (dest.top == 0 ? 0 : dest.top - windowsHeight + element.height()) : dest.top;
//local variables
var v = {
element: element,
callback: callback,
isMovementUp: isMovementUp,
dest: dest,
dtop: dtop,
yMovement: getYmovement(element),
anchorLink: element.data('anchor'),
sectionIndex: element.index(SECTION_SEL),
activeSlide: element.find(SLIDE_ACTIVE_SEL),
activeSection: $(SECTION_ACTIVE_SEL),
leavingSection: $(SECTION_ACTIVE_SEL).index(SECTION_SEL) + 1,
//caching the value of isResizing at the momment the function is called
//because it will be checked later inside a setTimeout and the value might change
localIsResizing: isResizing
};
//quiting when destination scroll is the same as the current one
if((v.activeSection.is(element) && !isResizing) || (options.scrollBar && $window.scrollTop() === v.dtop && !element.hasClass(AUTO_HEIGHT) )){ return; }
if(v.activeSlide.length){
var slideAnchorLink = v.activeSlide.data('anchor');
var slideIndex = v.activeSlide.index();
}
// If continuousVertical && we need to wrap around
if (options.autoScrolling && options.continuousVertical && typeof (v.isMovementUp) !== "undefined" &&
((!v.isMovementUp && v.yMovement == 'up') || // Intending to scroll down but about to go up or
(v.isMovementUp && v.yMovement == 'down'))) { // intending to scroll up but about to go down
v = createInfiniteSections(v);
}
//callback (onLeave) if the site is not just resizing and readjusting the slides
if($.isFunction(options.onLeave) && !v.localIsResizing){
if(options.onLeave.call(v.activeSection, v.leavingSection, (v.sectionIndex + 1), v.yMovement) === false){
return;
}else{
stopMedia(v.activeSection);
}
}
element.addClass(ACTIVE).siblings().removeClass(ACTIVE);
lazyLoad(element);
//preventing from activating the MouseWheelHandler event
//more than once if the page is scrolling
canScroll = false;
setState(slideIndex, slideAnchorLink, v.anchorLink, v.sectionIndex);
performMovement(v);
//flag to avoid callingn `scrollPage()` twice in case of using anchor links
lastScrolledDestiny = v.anchorLink;
//avoid firing it twice (as it does also on scroll)
activateMenuAndNav(v.anchorLink, v.sectionIndex);
});
} | function scrollPage(element, callback, isMovementUp){
//requestAnimFrame is used in order to prevent a Chrome 44 bug (http://stackoverflow.com/a/31961816/1081396)
requestAnimFrame(function(){
var dest = element.position();
if(typeof dest === 'undefined'){ return; } //there's no element to scroll, leaving the function
//auto height? Scrolling only a bit, the next element's height. Otherwise the whole viewport.
var dtop = element.hasClass(AUTO_HEIGHT) ? (dest.top == 0 ? 0 : dest.top - windowsHeight + element.height()) : dest.top;
//local variables
var v = {
element: element,
callback: callback,
isMovementUp: isMovementUp,
dest: dest,
dtop: dtop,
yMovement: getYmovement(element),
anchorLink: element.data('anchor'),
sectionIndex: element.index(SECTION_SEL),
activeSlide: element.find(SLIDE_ACTIVE_SEL),
activeSection: $(SECTION_ACTIVE_SEL),
leavingSection: $(SECTION_ACTIVE_SEL).index(SECTION_SEL) + 1,
//caching the value of isResizing at the momment the function is called
//because it will be checked later inside a setTimeout and the value might change
localIsResizing: isResizing
};
//quiting when destination scroll is the same as the current one
if((v.activeSection.is(element) && !isResizing) || (options.scrollBar && $window.scrollTop() === v.dtop && !element.hasClass(AUTO_HEIGHT) )){ return; }
if(v.activeSlide.length){
var slideAnchorLink = v.activeSlide.data('anchor');
var slideIndex = v.activeSlide.index();
}
// If continuousVertical && we need to wrap around
if (options.autoScrolling && options.continuousVertical && typeof (v.isMovementUp) !== "undefined" &&
((!v.isMovementUp && v.yMovement == 'up') || // Intending to scroll down but about to go up or
(v.isMovementUp && v.yMovement == 'down'))) { // intending to scroll up but about to go down
v = createInfiniteSections(v);
}
//callback (onLeave) if the site is not just resizing and readjusting the slides
if($.isFunction(options.onLeave) && !v.localIsResizing){
if(options.onLeave.call(v.activeSection, v.leavingSection, (v.sectionIndex + 1), v.yMovement) === false){
return;
}else{
stopMedia(v.activeSection);
}
}
element.addClass(ACTIVE).siblings().removeClass(ACTIVE);
lazyLoad(element);
//preventing from activating the MouseWheelHandler event
//more than once if the page is scrolling
canScroll = false;
setState(slideIndex, slideAnchorLink, v.anchorLink, v.sectionIndex);
performMovement(v);
//flag to avoid callingn `scrollPage()` twice in case of using anchor links
lastScrolledDestiny = v.anchorLink;
//avoid firing it twice (as it does also on scroll)
activateMenuAndNav(v.anchorLink, v.sectionIndex);
});
} |
JavaScript | function DLCL_setOptions(obj)
{
var myOptions = {};
myOptions.dataWebScript = "alfdev/create-link";
myOptions.viewMode = Alfresco.util.isValueSet(this.options.siteId) ? Alfresco.module.DoclibGlobalFolder.VIEW_MODE_RECENT_SITES : Alfresco.module.DoclibGlobalFolder.VIEW_MODE_REPOSITORY;
// Actions module
this.modules.actions = new Alfresco.module.DoclibActions();
return Alfresco.module.alfdev.DoclibCreateLink.superclass.setOptions.call(this, YAHOO.lang.merge(myOptions, obj));
} | function DLCL_setOptions(obj)
{
var myOptions = {};
myOptions.dataWebScript = "alfdev/create-link";
myOptions.viewMode = Alfresco.util.isValueSet(this.options.siteId) ? Alfresco.module.DoclibGlobalFolder.VIEW_MODE_RECENT_SITES : Alfresco.module.DoclibGlobalFolder.VIEW_MODE_REPOSITORY;
// Actions module
this.modules.actions = new Alfresco.module.DoclibActions();
return Alfresco.module.alfdev.DoclibCreateLink.superclass.setOptions.call(this, YAHOO.lang.merge(myOptions, obj));
} |
JavaScript | function DLCL_onTemplateLoaded(response)
{
// Load the UI template, which only will bring in new i18n-messages, from the server
Alfresco.util.Ajax.request(
{
url: this.options.extendedTemplateUrl,
dataObj:
{
htmlid: this.id
},
successCallback:
{
fn: this.onExtendedTemplateLoaded,
obj: response,
scope: this
},
failureMessage: "Could not load 'copy-link-to' template:" + this.options.extendedTemplateUrl,
execScripts: true
});
} | function DLCL_onTemplateLoaded(response)
{
// Load the UI template, which only will bring in new i18n-messages, from the server
Alfresco.util.Ajax.request(
{
url: this.options.extendedTemplateUrl,
dataObj:
{
htmlid: this.id
},
successCallback:
{
fn: this.onExtendedTemplateLoaded,
obj: response,
scope: this
},
failureMessage: "Could not load 'copy-link-to' template:" + this.options.extendedTemplateUrl,
execScripts: true
});
} |
JavaScript | function DLCL_onExtendedTemplateLoaded(response, superClassResponse)
{
// Now that we have loaded this components i18n messages let the original template get rendered.
Alfresco.module.alfdev.DoclibCreateLink.superclass.onTemplateLoaded.call(this, superClassResponse);
} | function DLCL_onExtendedTemplateLoaded(response, superClassResponse)
{
// Now that we have loaded this components i18n messages let the original template get rendered.
Alfresco.module.alfdev.DoclibCreateLink.superclass.onTemplateLoaded.call(this, superClassResponse);
} |
JavaScript | function DLCL_onOK(e, p_obj)
{
var files, multipleFiles = [], params, i, j,
eventSuffix = "LinkCreated";
// Single/multi files into array of nodeRefs
if (YAHOO.lang.isArray(this.options.files))
{
files = this.options.files;
}
else
{
files = [this.options.files];
}
for (i = 0, j = files.length; i < j; i++)
{
multipleFiles.push(files[i].node.nodeRef);
}
// Success callback function
var fnSuccess = function DLCL__onOK_success(p_data)
{
var result,
successCount = p_data.json.successCount,
failureCount = p_data.json.failureCount;
this.widgets.dialog.hide();
// Did the operation succeed?
if (!p_data.json.overallSuccess)
{
Alfresco.util.PopupManager.displayMessage(
{
text: this.msg("message.failure")
});
return;
}
YAHOO.Bubbling.fire("files" + eventSuffix,
{
destination: this.currentPath,
successCount: successCount,
failureCount: failureCount
});
for (var i = 0, j = p_data.json.totalResults; i < j; i++)
{
result = p_data.json.results[i];
if (result.success)
{
YAHOO.Bubbling.fire((result.type == "folder" ? "folder" : "file") + eventSuffix,
{
multiple: true,
nodeRef: result.nodeRef,
destination: this.currentPath
});
}
}
Alfresco.util.PopupManager.displayMessage(
{
text: this.msg("message.success", successCount)
});
YAHOO.Bubbling.fire("metadataRefresh");
};
// Failure callback function
var fnFailure = function DLCL__onOK_failure(p_data)
{
this.widgets.dialog.hide();
Alfresco.util.PopupManager.displayMessage(
{
text: this.msg("message.failure")
});
};
// Construct webscript URI based on current viewMode
var webscriptName = this.options.dataWebScript + "/node/{nodeRef}",
nodeRef = new Alfresco.util.NodeRef(this.selectedNode.data.nodeRef);
// Construct the data object for the genericAction call
this.modules.actions.genericAction(
{
success:
{
callback:
{
fn: fnSuccess,
scope: this
}
},
failure:
{
callback:
{
fn: fnFailure,
scope: this
}
},
webscript:
{
method: Alfresco.util.Ajax.POST,
name: webscriptName,
params:
{
nodeRef: nodeRef.uri
}
},
wait:
{
message: this.msg("message.please-wait")
},
config:
{
requestContentType: Alfresco.util.Ajax.JSON,
dataObj:
{
nodeRefs: multipleFiles,
parentId: this.options.parentId
}
}
});
this.widgets.okButton.set("disabled", true);
this.widgets.cancelButton.set("disabled", true);
} | function DLCL_onOK(e, p_obj)
{
var files, multipleFiles = [], params, i, j,
eventSuffix = "LinkCreated";
// Single/multi files into array of nodeRefs
if (YAHOO.lang.isArray(this.options.files))
{
files = this.options.files;
}
else
{
files = [this.options.files];
}
for (i = 0, j = files.length; i < j; i++)
{
multipleFiles.push(files[i].node.nodeRef);
}
// Success callback function
var fnSuccess = function DLCL__onOK_success(p_data)
{
var result,
successCount = p_data.json.successCount,
failureCount = p_data.json.failureCount;
this.widgets.dialog.hide();
// Did the operation succeed?
if (!p_data.json.overallSuccess)
{
Alfresco.util.PopupManager.displayMessage(
{
text: this.msg("message.failure")
});
return;
}
YAHOO.Bubbling.fire("files" + eventSuffix,
{
destination: this.currentPath,
successCount: successCount,
failureCount: failureCount
});
for (var i = 0, j = p_data.json.totalResults; i < j; i++)
{
result = p_data.json.results[i];
if (result.success)
{
YAHOO.Bubbling.fire((result.type == "folder" ? "folder" : "file") + eventSuffix,
{
multiple: true,
nodeRef: result.nodeRef,
destination: this.currentPath
});
}
}
Alfresco.util.PopupManager.displayMessage(
{
text: this.msg("message.success", successCount)
});
YAHOO.Bubbling.fire("metadataRefresh");
};
// Failure callback function
var fnFailure = function DLCL__onOK_failure(p_data)
{
this.widgets.dialog.hide();
Alfresco.util.PopupManager.displayMessage(
{
text: this.msg("message.failure")
});
};
// Construct webscript URI based on current viewMode
var webscriptName = this.options.dataWebScript + "/node/{nodeRef}",
nodeRef = new Alfresco.util.NodeRef(this.selectedNode.data.nodeRef);
// Construct the data object for the genericAction call
this.modules.actions.genericAction(
{
success:
{
callback:
{
fn: fnSuccess,
scope: this
}
},
failure:
{
callback:
{
fn: fnFailure,
scope: this
}
},
webscript:
{
method: Alfresco.util.Ajax.POST,
name: webscriptName,
params:
{
nodeRef: nodeRef.uri
}
},
wait:
{
message: this.msg("message.please-wait")
},
config:
{
requestContentType: Alfresco.util.Ajax.JSON,
dataObj:
{
nodeRefs: multipleFiles,
parentId: this.options.parentId
}
}
});
this.widgets.okButton.set("disabled", true);
this.widgets.cancelButton.set("disabled", true);
} |
JavaScript | function DLCL_msg(messageId)
{
var result = Alfresco.util.message.call(this, this.options.mode + "." + messageId, this.name, Array.prototype.slice.call(arguments).slice(1));
if (result == (this.options.mode + "." + messageId))
{
result = Alfresco.util.message.call(this, messageId, this.name, Array.prototype.slice.call(arguments).slice(1))
}
if (result == messageId)
{
result = Alfresco.util.message(messageId, "Alfresco.module.DoclibGlobalFolder", Array.prototype.slice.call(arguments).slice(1));
}
return result;
} | function DLCL_msg(messageId)
{
var result = Alfresco.util.message.call(this, this.options.mode + "." + messageId, this.name, Array.prototype.slice.call(arguments).slice(1));
if (result == (this.options.mode + "." + messageId))
{
result = Alfresco.util.message.call(this, messageId, this.name, Array.prototype.slice.call(arguments).slice(1))
}
if (result == messageId)
{
result = Alfresco.util.message(messageId, "Alfresco.module.DoclibGlobalFolder", Array.prototype.slice.call(arguments).slice(1));
}
return result;
} |
JavaScript | function DLCL__showDialog()
{
this.widgets.okButton.set("label", this.msg("button"));
return Alfresco.module.alfdev.DoclibCreateLink.superclass._showDialog.apply(this, arguments);
} | function DLCL__showDialog()
{
this.widgets.okButton.set("label", this.msg("button"));
return Alfresco.module.alfdev.DoclibCreateLink.superclass._showDialog.apply(this, arguments);
} |
JavaScript | async function deleteUserHandler(req, res) {
const { id } = req.params;
try {
const user = await deleteUser(id);
if(!user) {
return res.status(404).json({
message: `user with ${id} not found`
})
}
return res.status(200).json(user)
} catch(err) {
return res.status(500).json({
error: err.message
})
}
} | async function deleteUserHandler(req, res) {
const { id } = req.params;
try {
const user = await deleteUser(id);
if(!user) {
return res.status(404).json({
message: `user with ${id} not found`
})
}
return res.status(200).json(user)
} catch(err) {
return res.status(500).json({
error: err.message
})
}
} |
JavaScript | async function createPost(post) {
const newPost = new Post(post);
const savedPost = await newPost.save();
return savedPost;
} | async function createPost(post) {
const newPost = new Post(post);
const savedPost = await newPost.save();
return savedPost;
} |
Subsets and Splits