language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function replaceIterestSavingPlaceholder() {
$('#chart_heading').each(function() {
var text = $(this).text();
$(this).html(text.replace('[%interest_saving%]', '<span id="amount-saved" class="text-green-media"></span>'));
$('#chart_heading').show();
});
} | function replaceIterestSavingPlaceholder() {
$('#chart_heading').each(function() {
var text = $(this).text();
$(this).html(text.replace('[%interest_saving%]', '<span id="amount-saved" class="text-green-media"></span>'));
$('#chart_heading').show();
});
} |
JavaScript | function parseBigIntFrom36(units) {
let n = 0n, sign = 1n;
if ( units[0] == '-' ) {
sign = -1n;
}
units.split('').forEach(u => n = (n * 36n) + BigInt(parseInt(u,36)));
return n*sign;
} | function parseBigIntFrom36(units) {
let n = 0n, sign = 1n;
if ( units[0] == '-' ) {
sign = -1n;
}
units.split('').forEach(u => n = (n * 36n) + BigInt(parseInt(u,36)));
return n*sign;
} |
JavaScript | function parseFloatFrom36(val) {
// this code came from checking and mentally reversing
// the toString(radix) code for float numbers in v8
// here: https://github.com/v8/v8/blob/4b9b23521e6fd42373ebbcb20ebe03bf445494f9/src/conversions.cc#L1227
val = val.slice(1);
let [whole, part] = val.split('.');
let number = parseInt(whole, 36);
let fraction = 0;
let divisor = 36;
for( const unit of part ) {
const part = parseInt(unit, 36);
fraction += part/divisor;
divisor *= 36;
// DEBUG
//console.log({fraction, whole, part, unit});
}
const result = number + fraction;
// DEBUG
//console.log({floatRevive:{result}});
return result;
} | function parseFloatFrom36(val) {
// this code came from checking and mentally reversing
// the toString(radix) code for float numbers in v8
// here: https://github.com/v8/v8/blob/4b9b23521e6fd42373ebbcb20ebe03bf445494f9/src/conversions.cc#L1227
val = val.slice(1);
let [whole, part] = val.split('.');
let number = parseInt(whole, 36);
let fraction = 0;
let divisor = 36;
for( const unit of part ) {
const part = parseInt(unit, 36);
fraction += part/divisor;
divisor *= 36;
// DEBUG
//console.log({fraction, whole, part, unit});
}
const result = number + fraction;
// DEBUG
//console.log({floatRevive:{result}});
return result;
} |
JavaScript | async function createUser(discord_ID, url) {
user = {};
// Attempt to fetch user ID
console.log("Attempting to fetch steamID for: " + url);
return_value = await steam.resolve(url).then(async function (id) {
// Attempt to fetch user summary
console.log("Attempting to fetch user summary for: " + id);
info_promise = steam.getUserSummary(id).then((summary) => {
// Update user's stats
user["ID"] = summary["steamID"];
user["url"] = summary["url"];
user["nickname"] = summary["nickname"];
return {status: true, msg: "Successfully retrieved user info"};
}).catch((err) => { // Print errors
console.log("createUser had an error on steam.getUserSummary(id)");
console.log(err);
return {status: false, msg: "Failed to retrieve user info"};
});
// Attempt to fetch user games
console.log("Attempting to fetch user games for: " + id);
games_promise = steam.getUserOwnedGames(id).then((games) => {
// Organize games
games_dict = {};
for (x = 0; x < games.length; x++) {
games_dict[games[x]["name"]] = {appID: games[x]["appID"]};
}
// Update user's games
user["games"] = games_dict;
// Call GAMES update
updateGames(games_dict);
return {status: true, msg: "Successfully retrieved user games"};
}).catch((err) => { // Print errors
console.log("createUser had an error on steam.getUserOwnedGames(id)");
console.log(err);
return {status: false, msg: "Failed to retrieve user games"}
});
info_promise = await info_promise;
games_promise = await games_promise;
// Make sure that both data requests worked
if (info_promise.status && games_promise.status) {
// Update the global variable USERS
USERS[discord_ID] = user;
// Save USERS
fs.writeFileSync("../data/users.json", JSON.stringify(USERS, null, 4));
console.log("Saved users");
return "Successfully added user";
} else { // For all the failure areas
if (!info_promise.status && games_promise.status) {
return info_promise.msg;
} else if (info_promise.status && !games_promise.status) {
return games_promise.msg + "\nAre your games private/friends only? Bot will not work.";
} else {
return "Failed to retrieve both user info and games"
}
}
}).catch((err) => {
console.log("createUser had an error on steam.resolve(url)");
console.log(err);
return "Failed to find user\nCheck your steam url?";
});
return return_value;
} | async function createUser(discord_ID, url) {
user = {};
// Attempt to fetch user ID
console.log("Attempting to fetch steamID for: " + url);
return_value = await steam.resolve(url).then(async function (id) {
// Attempt to fetch user summary
console.log("Attempting to fetch user summary for: " + id);
info_promise = steam.getUserSummary(id).then((summary) => {
// Update user's stats
user["ID"] = summary["steamID"];
user["url"] = summary["url"];
user["nickname"] = summary["nickname"];
return {status: true, msg: "Successfully retrieved user info"};
}).catch((err) => { // Print errors
console.log("createUser had an error on steam.getUserSummary(id)");
console.log(err);
return {status: false, msg: "Failed to retrieve user info"};
});
// Attempt to fetch user games
console.log("Attempting to fetch user games for: " + id);
games_promise = steam.getUserOwnedGames(id).then((games) => {
// Organize games
games_dict = {};
for (x = 0; x < games.length; x++) {
games_dict[games[x]["name"]] = {appID: games[x]["appID"]};
}
// Update user's games
user["games"] = games_dict;
// Call GAMES update
updateGames(games_dict);
return {status: true, msg: "Successfully retrieved user games"};
}).catch((err) => { // Print errors
console.log("createUser had an error on steam.getUserOwnedGames(id)");
console.log(err);
return {status: false, msg: "Failed to retrieve user games"}
});
info_promise = await info_promise;
games_promise = await games_promise;
// Make sure that both data requests worked
if (info_promise.status && games_promise.status) {
// Update the global variable USERS
USERS[discord_ID] = user;
// Save USERS
fs.writeFileSync("../data/users.json", JSON.stringify(USERS, null, 4));
console.log("Saved users");
return "Successfully added user";
} else { // For all the failure areas
if (!info_promise.status && games_promise.status) {
return info_promise.msg;
} else if (info_promise.status && !games_promise.status) {
return games_promise.msg + "\nAre your games private/friends only? Bot will not work.";
} else {
return "Failed to retrieve both user info and games"
}
}
}).catch((err) => {
console.log("createUser had an error on steam.resolve(url)");
console.log(err);
return "Failed to find user\nCheck your steam url?";
});
return return_value;
} |
JavaScript | function AddonModScormDataModel12(eventsProvider, scormProvider, siteId, scorm, scoId, attempt, userData, mode, offline) {
this.eventsProvider = eventsProvider;
this.scormProvider = scormProvider;
this.siteId = siteId;
this.scorm = scorm;
this.scoId = scoId;
this.attempt = attempt;
this.mode = mode;
this.offline = offline;
// Standard Data Type Definition.
this.CMI_STRING_256 = '^[\\u0000-\\uFFFF]{0,255}$';
this.CMI_STRING_4096 = '^[\\u0000-\\uFFFF]{0,4096}$';
this.CMI_TIME = '^([0-2]{1}[0-9]{1}):([0-5]{1}[0-9]{1}):([0-5]{1}[0-9]{1})(\.[0-9]{1,2})?$';
this.CMI_TIMESPAN = '^([0-9]{2,4}):([0-9]{2}):([0-9]{2})(\.[0-9]{1,2})?$';
this.CMI_INTEGER = '^\\d+$';
this.CMI_SINTEGER = '^-?([0-9]+)$';
this.CMI_DECIMAL = '^-?([0-9]{0,3})(\.[0-9]*)?$';
this.CMI_IDENTIFIER = '^[\\u0021-\\u007E]{0,255}$';
this.CMI_FEEDBACK = this.CMI_STRING_256; // This must be redefined.
this.CMI_INDEX = '[._](\\d+).';
// Vocabulary Data Type Definition.
this.CMI_STATUS = '^passed$|^completed$|^failed$|^incomplete$|^browsed$';
this.CMI_STATUS_2 = '^passed$|^completed$|^failed$|^incomplete$|^browsed$|^not attempted$';
this.CMI_EXIT = '^time-out$|^suspend$|^logout$|^$';
this.CMI_TYPE = '^true-false$|^choice$|^fill-in$|^matching$|^performance$|^sequencing$|^likert$|^numeric$';
this.CMI_RESULT = '^correct$|^wrong$|^unanticipated$|^neutral$|^([0-9]{0,3})?(\.[0-9]*)?$';
this.NAV_EVENT = '^previous$|^continue$';
// Children lists.
this.CMI_CHILDREN = 'core,suspend_data,launch_data,comments,objectives,student_data,student_preference,interactions';
this.CORE_CHILDREN = 'student_id,student_name,lesson_location,credit,lesson_status,entry,score,total_time,lesson_mode,' +
'exit,session_time';
this.SCORE_CHILDREN = 'raw,min,max';
this.COMMENTS_CHILDREN = 'content,location,time';
this.OBJECTIVES_CHILDREN = 'id,score,status';
this.CORRECT_RESPONSES_CHILDREN = 'pattern';
this.STUDENT_DATA_CHILDREN = 'mastery_score,max_time_allowed,time_limit_action';
this.STUDENT_PREFERENCE_CHILDREN = 'audio,language,speed,text';
this.INTERACTIONS_CHILDREN = 'id,objectives,time,type,correct_responses,weighting,student_response,result,latency';
// Data ranges.
this.SCORE_RANGE = '0#100';
this.AUDIO_RANGE = '-1#100';
this.SPEED_RANGE = '-100#100';
this.WEIGHTING_RANGE = '-100#100';
this.TEXT_RANGE = '-1#1';
// Error messages.
this.ERROR_STRINGS = {
0: 'No error',
101: 'General exception',
201: 'Invalid argument error',
202: 'Element cannot have children',
203: 'Element not an array - cannot have count',
301: 'Not initialized',
401: 'Not implemented error',
402: 'Invalid set value, element is a keyword',
403: 'Element is read only',
404: 'Element is write only',
405: 'Incorrect data type'
};
this.currentUserData = {}; // Current user data.
this.def = {}; // Object containing the default values.
this.defExtra = {}; // Extra object that will contain the objectives and interactions data (all the .n. elements).
this.dataModel = {}; // The SCORM 1.2 data model.
this.initialized = false; // Whether LMSInitialize has been called.
this.mode = mode || __WEBPACK_IMPORTED_MODULE_0__providers_scorm__["a" /* AddonModScormProvider */].MODENORMAL;
this.offline = !!offline;
this.init(userData);
} | function AddonModScormDataModel12(eventsProvider, scormProvider, siteId, scorm, scoId, attempt, userData, mode, offline) {
this.eventsProvider = eventsProvider;
this.scormProvider = scormProvider;
this.siteId = siteId;
this.scorm = scorm;
this.scoId = scoId;
this.attempt = attempt;
this.mode = mode;
this.offline = offline;
// Standard Data Type Definition.
this.CMI_STRING_256 = '^[\\u0000-\\uFFFF]{0,255}$';
this.CMI_STRING_4096 = '^[\\u0000-\\uFFFF]{0,4096}$';
this.CMI_TIME = '^([0-2]{1}[0-9]{1}):([0-5]{1}[0-9]{1}):([0-5]{1}[0-9]{1})(\.[0-9]{1,2})?$';
this.CMI_TIMESPAN = '^([0-9]{2,4}):([0-9]{2}):([0-9]{2})(\.[0-9]{1,2})?$';
this.CMI_INTEGER = '^\\d+$';
this.CMI_SINTEGER = '^-?([0-9]+)$';
this.CMI_DECIMAL = '^-?([0-9]{0,3})(\.[0-9]*)?$';
this.CMI_IDENTIFIER = '^[\\u0021-\\u007E]{0,255}$';
this.CMI_FEEDBACK = this.CMI_STRING_256; // This must be redefined.
this.CMI_INDEX = '[._](\\d+).';
// Vocabulary Data Type Definition.
this.CMI_STATUS = '^passed$|^completed$|^failed$|^incomplete$|^browsed$';
this.CMI_STATUS_2 = '^passed$|^completed$|^failed$|^incomplete$|^browsed$|^not attempted$';
this.CMI_EXIT = '^time-out$|^suspend$|^logout$|^$';
this.CMI_TYPE = '^true-false$|^choice$|^fill-in$|^matching$|^performance$|^sequencing$|^likert$|^numeric$';
this.CMI_RESULT = '^correct$|^wrong$|^unanticipated$|^neutral$|^([0-9]{0,3})?(\.[0-9]*)?$';
this.NAV_EVENT = '^previous$|^continue$';
// Children lists.
this.CMI_CHILDREN = 'core,suspend_data,launch_data,comments,objectives,student_data,student_preference,interactions';
this.CORE_CHILDREN = 'student_id,student_name,lesson_location,credit,lesson_status,entry,score,total_time,lesson_mode,' +
'exit,session_time';
this.SCORE_CHILDREN = 'raw,min,max';
this.COMMENTS_CHILDREN = 'content,location,time';
this.OBJECTIVES_CHILDREN = 'id,score,status';
this.CORRECT_RESPONSES_CHILDREN = 'pattern';
this.STUDENT_DATA_CHILDREN = 'mastery_score,max_time_allowed,time_limit_action';
this.STUDENT_PREFERENCE_CHILDREN = 'audio,language,speed,text';
this.INTERACTIONS_CHILDREN = 'id,objectives,time,type,correct_responses,weighting,student_response,result,latency';
// Data ranges.
this.SCORE_RANGE = '0#100';
this.AUDIO_RANGE = '-1#100';
this.SPEED_RANGE = '-100#100';
this.WEIGHTING_RANGE = '-100#100';
this.TEXT_RANGE = '-1#1';
// Error messages.
this.ERROR_STRINGS = {
0: 'No error',
101: 'General exception',
201: 'Invalid argument error',
202: 'Element cannot have children',
203: 'Element not an array - cannot have count',
301: 'Not initialized',
401: 'Not implemented error',
402: 'Invalid set value, element is a keyword',
403: 'Element is read only',
404: 'Element is write only',
405: 'Incorrect data type'
};
this.currentUserData = {}; // Current user data.
this.def = {}; // Object containing the default values.
this.defExtra = {}; // Extra object that will contain the objectives and interactions data (all the .n. elements).
this.dataModel = {}; // The SCORM 1.2 data model.
this.initialized = false; // Whether LMSInitialize has been called.
this.mode = mode || __WEBPACK_IMPORTED_MODULE_0__providers_scorm__["a" /* AddonModScormProvider */].MODENORMAL;
this.offline = !!offline;
this.init(userData);
} |
JavaScript | function helperProcessTestResult(test) {
if (test.status === constants.TEST_STATUS_FAILED) {
reject (test.error);
return;
}
resolve();
} | function helperProcessTestResult(test) {
if (test.status === constants.TEST_STATUS_FAILED) {
reject (test.error);
return;
}
resolve();
} |
JavaScript | function dispatchPointerEvent(element, type, positionX, positionY) {
var eventInit = {
clientX: positionX,
clientY: positionY,
bubbles: true,
pointerType: "mouse"
};
if (window.PointerEvent) {
element.dispatchEvent(new PointerEvent(type, eventInit));
} else if (window.MSPointerEvent && window.navigator.msPointerEnabled) {
if (type === "pointerdown") {
type = "MSPointerDown";
} else if (type === "pointermove") {
type = "MSPointerMove";
} else {
type = "MSPointerUp";
}
element.dispatchEvent(new MSPointerEvent(type, eventInit));
} else {
if (type === "pointerdown") {
type = "mousedown";
} else if (type === "pointermove") {
type = "mousemove";
} else {
type = "mouseup";
}
element.dispatchEvent(new MouseEvent(type, eventInit));
}
} | function dispatchPointerEvent(element, type, positionX, positionY) {
var eventInit = {
clientX: positionX,
clientY: positionY,
bubbles: true,
pointerType: "mouse"
};
if (window.PointerEvent) {
element.dispatchEvent(new PointerEvent(type, eventInit));
} else if (window.MSPointerEvent && window.navigator.msPointerEnabled) {
if (type === "pointerdown") {
type = "MSPointerDown";
} else if (type === "pointermove") {
type = "MSPointerMove";
} else {
type = "MSPointerUp";
}
element.dispatchEvent(new MSPointerEvent(type, eventInit));
} else {
if (type === "pointerdown") {
type = "mousedown";
} else if (type === "pointermove") {
type = "mousemove";
} else {
type = "mouseup";
}
element.dispatchEvent(new MouseEvent(type, eventInit));
}
} |
JavaScript | function _super() {
// Figure out which function called us.
var callerFn = ( _super && _super.caller ) ? _super.caller : arguments.callee.caller,
superFn = __super.call(this,callerFn);
return superFn ? superFn.apply(this, arguments) : undefined;
} | function _super() {
// Figure out which function called us.
var callerFn = ( _super && _super.caller ) ? _super.caller : arguments.callee.caller,
superFn = __super.call(this,callerFn);
return superFn ? superFn.apply(this, arguments) : undefined;
} |
JavaScript | function isAnagram(original, test) {
// Parameters must be strings
if (typeof(original) !== 'string' || typeof(test) !== 'string') {
return false;
}
// Words with different length doesn't are anagrams
if (original.length !== test.length) {
return false;
}
// Create a flag to validate the words are anagrams
let flag = true;
// These variables are to parse the parameters to lowercase and split it into an array
let original_array = original.toLowerCase().split('');
let test_array = test.toLowerCase().split('');
let i = 0;
// When flag is false, I don't need to check the rest of the letters
while (i < original_array.length && flag) {
if (!test_array.some(elem => elem === original_array[i])) {
flag = false;
}
i++;
}
return flag;
} | function isAnagram(original, test) {
// Parameters must be strings
if (typeof(original) !== 'string' || typeof(test) !== 'string') {
return false;
}
// Words with different length doesn't are anagrams
if (original.length !== test.length) {
return false;
}
// Create a flag to validate the words are anagrams
let flag = true;
// These variables are to parse the parameters to lowercase and split it into an array
let original_array = original.toLowerCase().split('');
let test_array = test.toLowerCase().split('');
let i = 0;
// When flag is false, I don't need to check the rest of the letters
while (i < original_array.length && flag) {
if (!test_array.some(elem => elem === original_array[i])) {
flag = false;
}
i++;
}
return flag;
} |
JavaScript | function demo1() {
var btnTest = document.getElementById('demo1');
var demo;
btnTest.addEventListener('click', function(){
demo = new ZMODAL();
})
} | function demo1() {
var btnTest = document.getElementById('demo1');
var demo;
btnTest.addEventListener('click', function(){
demo = new ZMODAL();
})
} |
JavaScript | static checkNotNil(object, name) {
if (lodash.isNil(object)) {
let message = lodash.isString(name)
? `${name} cannot be undefined or null`
: "Encounter undefined or null";
throw new Error(message);
}
} | static checkNotNil(object, name) {
if (lodash.isNil(object)) {
let message = lodash.isString(name)
? `${name} cannot be undefined or null`
: "Encounter undefined or null";
throw new Error(message);
}
} |
JavaScript | function filterElementList(e) {
var query = $(e.target).val().toLowerCase();
// Filter if the length of the query is at least 2 characters.
if (query.length >= 2) {
// Reset count.
totalItems = 0;
if ($details.length) {
$details.hide();
}
$filterRows.each(toggleEntry);
// Announce filter changes.
// @see Drupal.behaviors.blockFilterByText
Drupal.announce(Drupal.formatPlural(
totalItems,
'1 @item is available in the modified list.',
'@total @items are available in the modified list.',
args
));
}
else {
totalItems = $filterRows.length;
$filterRows.each(function (index) {
$(this).closest(parentSelector).show();
if ($details.length) {
$details.show();
}
});
}
// Set total.
args['@total'] = totalItems;
// Hide/show no results.
$noResults[totalItems ? 'hide' : 'show']();
// Hide/show reset.
$reset[query.length ? 'show' : 'hide']();
// Update summary.
if ($summary.length) {
$summary.html(Drupal.formatPlural(
totalItems,
'1 @item',
'@total @items',
args
));
$summary[totalItems ? 'show' : 'hide']();
}
/**
* Shows or hides the webform element entry based on the query.
*
* @param {number} index
* The index in the loop, as provided by `jQuery.each`
* @param {HTMLElement} label
* The label of the webform.
*/
function toggleEntry(index, label) {
var $label = $(label);
var $row = $label.closest(parentSelector);
var textMatch = $label.text().toLowerCase().indexOf(query) !== -1;
var isSelected = (selectedSelector && $row.find(selectedSelector).length) ? true : false;
var isVisible = textMatch || isSelected;
$row.toggle(isVisible);
if (isVisible) {
totalItems++;
if (hasDetails) {
$row.closest('details').show();
}
}
}
} | function filterElementList(e) {
var query = $(e.target).val().toLowerCase();
// Filter if the length of the query is at least 2 characters.
if (query.length >= 2) {
// Reset count.
totalItems = 0;
if ($details.length) {
$details.hide();
}
$filterRows.each(toggleEntry);
// Announce filter changes.
// @see Drupal.behaviors.blockFilterByText
Drupal.announce(Drupal.formatPlural(
totalItems,
'1 @item is available in the modified list.',
'@total @items are available in the modified list.',
args
));
}
else {
totalItems = $filterRows.length;
$filterRows.each(function (index) {
$(this).closest(parentSelector).show();
if ($details.length) {
$details.show();
}
});
}
// Set total.
args['@total'] = totalItems;
// Hide/show no results.
$noResults[totalItems ? 'hide' : 'show']();
// Hide/show reset.
$reset[query.length ? 'show' : 'hide']();
// Update summary.
if ($summary.length) {
$summary.html(Drupal.formatPlural(
totalItems,
'1 @item',
'@total @items',
args
));
$summary[totalItems ? 'show' : 'hide']();
}
/**
* Shows or hides the webform element entry based on the query.
*
* @param {number} index
* The index in the loop, as provided by `jQuery.each`
* @param {HTMLElement} label
* The label of the webform.
*/
function toggleEntry(index, label) {
var $label = $(label);
var $row = $label.closest(parentSelector);
var textMatch = $label.text().toLowerCase().indexOf(query) !== -1;
var isSelected = (selectedSelector && $row.find(selectedSelector).length) ? true : false;
var isVisible = textMatch || isSelected;
$row.toggle(isVisible);
if (isVisible) {
totalItems++;
if (hasDetails) {
$row.closest('details').show();
}
}
}
} |
JavaScript | function toggleEntry(index, label) {
var $label = $(label);
var $row = $label.closest(parentSelector);
var textMatch = $label.text().toLowerCase().indexOf(query) !== -1;
var isSelected = (selectedSelector && $row.find(selectedSelector).length) ? true : false;
var isVisible = textMatch || isSelected;
$row.toggle(isVisible);
if (isVisible) {
totalItems++;
if (hasDetails) {
$row.closest('details').show();
}
}
} | function toggleEntry(index, label) {
var $label = $(label);
var $row = $label.closest(parentSelector);
var textMatch = $label.text().toLowerCase().indexOf(query) !== -1;
var isSelected = (selectedSelector && $row.find(selectedSelector).length) ? true : false;
var isVisible = textMatch || isSelected;
$row.toggle(isVisible);
if (isVisible) {
totalItems++;
if (hasDetails) {
$row.closest('details').show();
}
}
} |
JavaScript | hookSetup(whitelist = null, blacklist = null, functionWhitelist = null, functionBlacklist = null) {
if (whitelist === null) {
whitelist = ".*"
}
if (functionWhitelist === null) {
functionWhitelist = ".*"
}
let watchClasses = [];
let watchMethods = [];
let java = this;
Java.performNow(() => {
Java.enumerateLoadedClasses({
onMatch: function (className) {
if (java.seen[className] === undefined) {
if (className.match(whitelist)) {
if (blacklist !== null) {
if (className.match(blacklist)) {
return
}
}
java.seen[className] = true
watchClasses.push(className);
let methods = java.getClassMethods(className);
let hookMethods = [];
methods.forEach((_method) => {
if (_method.match(functionWhitelist)) {
if (functionBlacklist !== null) {
if (_method.match(functionBlacklist)) {
return
}
}
let x = className + "." + _method;
watchMethods.push(x);
hookMethods.push(_method);
return;
}
});
if (hookMethods.length > 0)
java.hook(className, hookMethods)
}
}
},
onComplete: function () {
},
});
});
} | hookSetup(whitelist = null, blacklist = null, functionWhitelist = null, functionBlacklist = null) {
if (whitelist === null) {
whitelist = ".*"
}
if (functionWhitelist === null) {
functionWhitelist = ".*"
}
let watchClasses = [];
let watchMethods = [];
let java = this;
Java.performNow(() => {
Java.enumerateLoadedClasses({
onMatch: function (className) {
if (java.seen[className] === undefined) {
if (className.match(whitelist)) {
if (blacklist !== null) {
if (className.match(blacklist)) {
return
}
}
java.seen[className] = true
watchClasses.push(className);
let methods = java.getClassMethods(className);
let hookMethods = [];
methods.forEach((_method) => {
if (_method.match(functionWhitelist)) {
if (functionBlacklist !== null) {
if (_method.match(functionBlacklist)) {
return
}
}
let x = className + "." + _method;
watchMethods.push(x);
hookMethods.push(_method);
return;
}
});
if (hookMethods.length > 0)
java.hook(className, hookMethods)
}
}
},
onComplete: function () {
},
});
});
} |
JavaScript | function normalizeAttrs (attrs) {
if (!attrs) return attrs
for (let key in attrs) {
if (attrs.hasOwnProperty(key) && propertyMap[key]) {
attrs[propertyMap[key]] = attrs[key]
delete attrs[key]
}
}
if (attrs.className) {
attrs.className = classSugar(attrs.className)
}
if (attrs.focused) {
attrs.focused = new FocusHook()
}
return attrs
} | function normalizeAttrs (attrs) {
if (!attrs) return attrs
for (let key in attrs) {
if (attrs.hasOwnProperty(key) && propertyMap[key]) {
attrs[propertyMap[key]] = attrs[key]
delete attrs[key]
}
}
if (attrs.className) {
attrs.className = classSugar(attrs.className)
}
if (attrs.focused) {
attrs.focused = new FocusHook()
}
return attrs
} |
JavaScript | function classSugar (cls) {
if (isPlainObject(cls)) {
cls = Object.keys(cls).filter(key => cls[key])
}
return Array.isArray(cls)
? cls.join(' ')
: cls
} | function classSugar (cls) {
if (isPlainObject(cls)) {
cls = Object.keys(cls).filter(key => cls[key])
}
return Array.isArray(cls)
? cls.join(' ')
: cls
} |
JavaScript | init() {
initErrorTracking();
initFeatureDetection();
initFlexboxSupport();
tabFocus();
GA.init();
} | init() {
initErrorTracking();
initFeatureDetection();
initFlexboxSupport();
tabFocus();
GA.init();
} |
JavaScript | componentDidMount() {
const videoDiv = document.createElement('div');
const innerDiv = document.createElement('div');
const spinner = document.createElement('img');
spinner.setAttribute('src', '/static/images/spinner-black.gif');
videoDiv.className = 'modal__video-wrapper';
innerDiv.className = 'modal__video-inner';
videoDiv.appendChild(spinner);
innerDiv.appendChild(videoDiv);
this.contentNode.appendChild(innerDiv);
this.videoDiv = videoDiv;
this.innerDiv = innerDiv;
} | componentDidMount() {
const videoDiv = document.createElement('div');
const innerDiv = document.createElement('div');
const spinner = document.createElement('img');
spinner.setAttribute('src', '/static/images/spinner-black.gif');
videoDiv.className = 'modal__video-wrapper';
innerDiv.className = 'modal__video-inner';
videoDiv.appendChild(spinner);
innerDiv.appendChild(videoDiv);
this.contentNode.appendChild(innerDiv);
this.videoDiv = videoDiv;
this.innerDiv = innerDiv;
} |
JavaScript | initialize() {
const url = `/recommendations/products.json?product_id=${this.productId}&limit=${this.options.limit}`;
const context = this;
// TODO: if data has already been stored and product id is the same, do not run another fetch
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
context.data = data;
appendProducts(data, context);
/**
* Initialize event.
*
* @event recommendations.initialize
* @type {Object}
* @property {Object} context - The Recommendations instance this event was fired from
* @property {Object} data - The product data from the fetch request to Shopify
*/
dispatchEvent('recommendations.initialized', {
context,
data,
});
this.isInitialized = true;
})
.catch((err) => {
throw err;
});
} | initialize() {
const url = `/recommendations/products.json?product_id=${this.productId}&limit=${this.options.limit}`;
const context = this;
// TODO: if data has already been stored and product id is the same, do not run another fetch
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
context.data = data;
appendProducts(data, context);
/**
* Initialize event.
*
* @event recommendations.initialize
* @type {Object}
* @property {Object} context - The Recommendations instance this event was fired from
* @property {Object} data - The product data from the fetch request to Shopify
*/
dispatchEvent('recommendations.initialized', {
context,
data,
});
this.isInitialized = true;
})
.catch((err) => {
throw err;
});
} |
JavaScript | reinitialize() {
if (!this.isInitialized) {
throw new Error('Cannot reinitialize Recommendations object (has not been initialized)');
}
this.uninitialize();
this.initialize();
} | reinitialize() {
if (!this.isInitialized) {
throw new Error('Cannot reinitialize Recommendations object (has not been initialized)');
}
this.uninitialize();
this.initialize();
} |
JavaScript | uninitialize(preventEvent) {
if (!this.isInitialized) {
throw new Error('Cannot unitialize Recommendations object (has not been initialized)');
}
this.isInitialized = false;
const parents = document.querySelectorAll(`[data-recommendations-id="${this.recommendationsId}"]`);
if (!parent) {
throw new Error(`Cannot uninitiale Recommendations object (cannot find insertion with ID ${this.recommendationsId})`);
}
parents.forEach((parent) => {
while (parent.firstChild) {
parent.firstChild.remove();
}
});
if (!preventEvent) {
dispatchEvent('recommendations.uninitialized', {
context: this,
data: this.data,
});
}
} | uninitialize(preventEvent) {
if (!this.isInitialized) {
throw new Error('Cannot unitialize Recommendations object (has not been initialized)');
}
this.isInitialized = false;
const parents = document.querySelectorAll(`[data-recommendations-id="${this.recommendationsId}"]`);
if (!parent) {
throw new Error(`Cannot uninitiale Recommendations object (cannot find insertion with ID ${this.recommendationsId})`);
}
parents.forEach((parent) => {
while (parent.firstChild) {
parent.firstChild.remove();
}
});
if (!preventEvent) {
dispatchEvent('recommendations.uninitialized', {
context: this,
data: this.data,
});
}
} |
JavaScript | function generateMarkdown(data, githubInfo) {
return `
# ${data.title}
## GitHub

- ${githubInfo.name}
- [GitHub Profile](${githubInfo.profile})
${data.badge}
## Description
${data.description}
## Table of contents
- [Description](#Description)
- [Installation](#Installation)
- [Usage](#Usage)
- [License](#License)
- [Contributors](#Contributors)
- [Tests](#Tests)
- [Questions](#questions)
- [GitHub Info](#GitHub)
## Installation
${data.installation}
## Usage
${data.usage}
## License

## Contributors

## Tests
${data.test}
## Questions
For any other questions, please send me an email at: ${data.email}.
`;
} | function generateMarkdown(data, githubInfo) {
return `
# ${data.title}
## GitHub

- ${githubInfo.name}
- [GitHub Profile](${githubInfo.profile})
${data.badge}
## Description
${data.description}
## Table of contents
- [Description](#Description)
- [Installation](#Installation)
- [Usage](#Usage)
- [License](#License)
- [Contributors](#Contributors)
- [Tests](#Tests)
- [Questions](#questions)
- [GitHub Info](#GitHub)
## Installation
${data.installation}
## Usage
${data.usage}
## License

## Contributors

## Tests
${data.test}
## Questions
For any other questions, please send me an email at: ${data.email}.
`;
} |
JavaScript | async function dump (rootCid) {
const map = await load(store, rootCid, { blockHasher, blockCodec })
console.log('ENTRIES ===========================')
for await (const [key, value] of map.entries()) {
console.log(`[${key}]:`, value)
}
console.log('STATS =============================')
console.log('size:', await map.size())
console.log('blocks:')
for await (const cid of map.cids()) {
console.log('\t', cid, cid.equals(map.cid) ? '(ROOT)' : '')
// console.dir(blockCodec.decode(store.get(cid)), { depth: Infinity })
}
} | async function dump (rootCid) {
const map = await load(store, rootCid, { blockHasher, blockCodec })
console.log('ENTRIES ===========================')
for await (const [key, value] of map.entries()) {
console.log(`[${key}]:`, value)
}
console.log('STATS =============================')
console.log('size:', await map.size())
console.log('blocks:')
for await (const cid of map.cids()) {
console.log('\t', cid, cid.equals(map.cid) ? '(ROOT)' : '')
// console.dir(blockCodec.decode(store.get(cid)), { depth: Infinity })
}
} |
JavaScript | async * keys () {
for await (const key of this._iamap.keys()) {
// IAMap keys are Uint8Arrays, make them strings
yield textDecoder.decode(key)
}
} | async * keys () {
for await (const key of this._iamap.keys()) {
// IAMap keys are Uint8Arrays, make them strings
yield textDecoder.decode(key)
}
} |
JavaScript | async * entries () {
for await (const { key, value } of this._iamap.entries()) {
// IAMap keys are Uint8Arrays, make them strings
yield [textDecoder.decode(key), value]
}
} | async * entries () {
for await (const { key, value } of this._iamap.entries()) {
// IAMap keys are Uint8Arrays, make them strings
yield [textDecoder.decode(key), value]
}
} |
JavaScript | async * entriesRaw () {
for await (const { key, value } of this._iamap.entries()) {
yield [key, value]
}
} | async * entriesRaw () {
for await (const { key, value } of this._iamap.entries()) {
yield [key, value]
}
} |
JavaScript | function version() {
var portal = this;
var url = portal.portalUrl + "sharing/rest";
var parameters = {
f: "json"
};
var options = {
withCredentials: portal.withCredentials
};
return request.get(url, parameters, options);
} | function version() {
var portal = this;
var url = portal.portalUrl + "sharing/rest";
var parameters = {
f: "json"
};
var options = {
withCredentials: portal.withCredentials
};
return request.get(url, parameters, options);
} |
JavaScript | function updateDescription(username, id, folder, description) {
let portal = this;
let url = `${portal.portalUrl}sharing/rest/content/users/${username}/${folder}/items/${id}/update`;
/*
* Clean up description items for posting.
* This is necessary because some of the item descriptions (e.g. tags and extent)
* are returned as arrays, but the POST operation expects comma separated strings.
*/
for (let [key, value] of description) {
if (value === null) {
description[key] = "";
} else if (value instanceof Array) {
description[key] = value.toString();
}
}
let payload = JSON.parse(description);
payload.token = portal.token;
payload.f = "json";
let options = {
withCredentials: portal.withCredentials
};
return request.post(url, payload, options);
} | function updateDescription(username, id, folder, description) {
let portal = this;
let url = `${portal.portalUrl}sharing/rest/content/users/${username}/${folder}/items/${id}/update`;
/*
* Clean up description items for posting.
* This is necessary because some of the item descriptions (e.g. tags and extent)
* are returned as arrays, but the POST operation expects comma separated strings.
*/
for (let [key, value] of description) {
if (value === null) {
description[key] = "";
} else if (value instanceof Array) {
description[key] = value.toString();
}
}
let payload = JSON.parse(description);
payload.token = portal.token;
payload.f = "json";
let options = {
withCredentials: portal.withCredentials
};
return request.post(url, payload, options);
} |
JavaScript | function Crumpler(options) {
if(!(this instanceof Crumpler)) // allow instantiation without "new"
return new Crumpler(options);
options = options || {};
if (_.isUndefined(options.normBracketSize))
options.normBracketSize = 2;
if (_.isUndefined(options.diffBracketSize))
options.diffBracketSize = 2;
if (_.isUndefined(options.minCollapsedLines))
options.minCollapsedLines = 2;
else if (options.minCollapsedLines < 1)
throw new Error("minCollapsedLines must be >= 1");
if (_.isUndefined(options.maxNormLineLength))
options.maxNormLineLength = 0;
if (_.isUndefined(options.maxLineDiffLength))
options.maxLineDiffLength = 0;
if (_.isUndefined(options.sameHeadLengthLimit))
options.sameHeadLengthLimit = -1;
if (_.isUndefined(options.sameTailLengthLimit))
options.sameTailLengthLimit = -1;
if (_.isUndefined(options.normCollapseEllipsis))
options.normCollapseEllipsis = DEFAULT_NORM_COLLAPSE_ELLIPSIS;
if (_.isUndefined(options.subjectCollapseEllipsis))
options.subjectCollapseEllipsis = DEFAULT_SUBJECT_COLLAPSE_ELLIPSIS;
if (_.isUndefined(options.modelCollapseEllipsis))
options.modelCollapseEllipsis = DEFAULT_MODEL_COLLAPSE_ELLIPSIS;
if (_.isUndefined(options.headCropEllipsis))
options.headCropEllipsis = DEFAULT_HEAD_CROP_ELLIPSIS;
if (_.isUndefined(options.tailCropEllipsis))
options.tailCropEllipsis = DEFAULT_TAIL_CROP_ELLIPSIS;
if (_.isUndefined(options.indentCollapseEllipses))
options.indentCollapseEllipses = false;
if (_.isUndefined(options.sectionTitleRegex))
options.sectionTitleRegex = null;
if (_.isUndefined(options.sectionTitlePrefix))
options.sectionTitlePrefix = null;
else if (options.sectionTitlePrefix === '')
options.sectionTitlePrefix = null;
if (_.isUndefined(options.minNumberedLines))
options.minNumberedLines = 2;
if (_.isUndefined(options.lineNumberPadding))
options.lineNumberPadding = null;
else if (options.lineNumberPadding === '')
options.lineNumberPadding = null;
if (options.lineNumberDelim === null)
options.lineNumberDelim = '';
else if (_.isUndefined(options.lineNumberDelim))
options.lineNumberDelim = ':';
var config = {};
config.headInfo = Extent.getCropInfo(options.headCropEllipsis);
config.tailInfo = Extent.getCropInfo(options.tailCropEllipsis);
config.paddingByWidth = [];
var padding = options.lineNumberPadding;
if (padding !== null) {
// this padding cache is more resource-efficient than _.padStart()
for (var i = 0; i < 10; ++i)
config.paddingByWidth[i] = padding.repeat(i); //works for i==0 too
}
this.opts = options; // bundled for easy passing to TextSection
this.config = config;
} | function Crumpler(options) {
if(!(this instanceof Crumpler)) // allow instantiation without "new"
return new Crumpler(options);
options = options || {};
if (_.isUndefined(options.normBracketSize))
options.normBracketSize = 2;
if (_.isUndefined(options.diffBracketSize))
options.diffBracketSize = 2;
if (_.isUndefined(options.minCollapsedLines))
options.minCollapsedLines = 2;
else if (options.minCollapsedLines < 1)
throw new Error("minCollapsedLines must be >= 1");
if (_.isUndefined(options.maxNormLineLength))
options.maxNormLineLength = 0;
if (_.isUndefined(options.maxLineDiffLength))
options.maxLineDiffLength = 0;
if (_.isUndefined(options.sameHeadLengthLimit))
options.sameHeadLengthLimit = -1;
if (_.isUndefined(options.sameTailLengthLimit))
options.sameTailLengthLimit = -1;
if (_.isUndefined(options.normCollapseEllipsis))
options.normCollapseEllipsis = DEFAULT_NORM_COLLAPSE_ELLIPSIS;
if (_.isUndefined(options.subjectCollapseEllipsis))
options.subjectCollapseEllipsis = DEFAULT_SUBJECT_COLLAPSE_ELLIPSIS;
if (_.isUndefined(options.modelCollapseEllipsis))
options.modelCollapseEllipsis = DEFAULT_MODEL_COLLAPSE_ELLIPSIS;
if (_.isUndefined(options.headCropEllipsis))
options.headCropEllipsis = DEFAULT_HEAD_CROP_ELLIPSIS;
if (_.isUndefined(options.tailCropEllipsis))
options.tailCropEllipsis = DEFAULT_TAIL_CROP_ELLIPSIS;
if (_.isUndefined(options.indentCollapseEllipses))
options.indentCollapseEllipses = false;
if (_.isUndefined(options.sectionTitleRegex))
options.sectionTitleRegex = null;
if (_.isUndefined(options.sectionTitlePrefix))
options.sectionTitlePrefix = null;
else if (options.sectionTitlePrefix === '')
options.sectionTitlePrefix = null;
if (_.isUndefined(options.minNumberedLines))
options.minNumberedLines = 2;
if (_.isUndefined(options.lineNumberPadding))
options.lineNumberPadding = null;
else if (options.lineNumberPadding === '')
options.lineNumberPadding = null;
if (options.lineNumberDelim === null)
options.lineNumberDelim = '';
else if (_.isUndefined(options.lineNumberDelim))
options.lineNumberDelim = ':';
var config = {};
config.headInfo = Extent.getCropInfo(options.headCropEllipsis);
config.tailInfo = Extent.getCropInfo(options.tailCropEllipsis);
config.paddingByWidth = [];
var padding = options.lineNumberPadding;
if (padding !== null) {
// this padding cache is more resource-efficient than _.padStart()
for (var i = 0; i < 10; ++i)
config.paddingByWidth[i] = padding.repeat(i); //works for i==0 too
}
this.opts = options; // bundled for easy passing to TextSection
this.config = config;
} |
JavaScript | function Extent(options, config, maxLineLength, bracketSize,
collapseEllipsis, numberingLines, padWidth)
{
// all instance variables are private
this.opts = options;
this.config = config;
this.maxLineLength = maxLineLength;
this.bracketSize = bracketSize;
this.collapseEllipsis = collapseEllipsis;
this.numberingLines = numberingLines;
this.padWidth = padWidth;
} | function Extent(options, config, maxLineLength, bracketSize,
collapseEllipsis, numberingLines, padWidth)
{
// all instance variables are private
this.opts = options;
this.config = config;
this.maxLineLength = maxLineLength;
this.bracketSize = bracketSize;
this.collapseEllipsis = collapseEllipsis;
this.numberingLines = numberingLines;
this.padWidth = padWidth;
} |
JavaScript | function recursiveCategories(category, parentNode) {
// we only snakeCase one level at a time instead of all of them at once
category = camelcaseKeys(category)
// if parent, get the id
// parentNodeID = null
// if (parentNode.id != null) {
// parentNodeID = parentNode.id
// }
// create Gatsby ids for any subcategories
subCatIDs = []
if ('subCategories' in category) {
category.subCategories.forEach((subCat) => {
scid = createNodeId(`category-${subCat.id}`)
subCatIDs.push(scid)
})
}
// get Gasby IDs for all products in this
// category. Unfortunately, we have SKUs, not
// the internal CV3 IDs we need to create the right
// Gatsby IDs, so we need to match on the products
// we already added above to the rootObject.
catProdIDs = []
category.products.skus.forEach((sku) => {
rootObj.products.forEach((product) => {
if (sku == product.sku) {
nid = product.id
catProdIDs.push(nid)
}
})
})
// same with featured products
featuredProdIDs = []
category.featuredProducts.skus.forEach((sku) => {
rootObj.products.forEach((product) => {
if (sku == product.sku) {
nid = product.id
featuredProdIDs.push(nid)
}
})
})
// custom fields is a large object from the api, returning
// here as a simple array. Need to test ease of use vs. schema
customFields = []
if ('customFields' in category) {
for (let [key, value] of Object.entries(category.customFields)) {
customFields.push(value)
}
}
// create Gatsby IDs for linking relatedCategories
relCats = []
if ('relatedCategories' in category) {
category.relatedCategories.forEach((catId) => {
rcid = createNodeId(`category-${catId}`)
relCats.push(rcid)
})
}
// build our final category object
nodeID = createNodeId(`category-${category.id}`)
var obj = {
...category,
id: nodeID,
cv3ID: category.id,
name: category.name,
parentCategory: parentNode.id,
productIDs: catProdIDs,
products: catProdIDs,
featuredProducts: featuredProdIDs,
subCategories: subCatIDs,
customFields: customFields,
relatedCategories: relCats,
internal: {
type: 'Category',
},
}
// add to our root object
rootObj.categories.push(obj)
// if we have more subcategories, recurse
if ('subCategories' in category) {
category.subCategories.forEach((subCat) => {
recursiveCategories(subCat, obj)
})
}
} | function recursiveCategories(category, parentNode) {
// we only snakeCase one level at a time instead of all of them at once
category = camelcaseKeys(category)
// if parent, get the id
// parentNodeID = null
// if (parentNode.id != null) {
// parentNodeID = parentNode.id
// }
// create Gatsby ids for any subcategories
subCatIDs = []
if ('subCategories' in category) {
category.subCategories.forEach((subCat) => {
scid = createNodeId(`category-${subCat.id}`)
subCatIDs.push(scid)
})
}
// get Gasby IDs for all products in this
// category. Unfortunately, we have SKUs, not
// the internal CV3 IDs we need to create the right
// Gatsby IDs, so we need to match on the products
// we already added above to the rootObject.
catProdIDs = []
category.products.skus.forEach((sku) => {
rootObj.products.forEach((product) => {
if (sku == product.sku) {
nid = product.id
catProdIDs.push(nid)
}
})
})
// same with featured products
featuredProdIDs = []
category.featuredProducts.skus.forEach((sku) => {
rootObj.products.forEach((product) => {
if (sku == product.sku) {
nid = product.id
featuredProdIDs.push(nid)
}
})
})
// custom fields is a large object from the api, returning
// here as a simple array. Need to test ease of use vs. schema
customFields = []
if ('customFields' in category) {
for (let [key, value] of Object.entries(category.customFields)) {
customFields.push(value)
}
}
// create Gatsby IDs for linking relatedCategories
relCats = []
if ('relatedCategories' in category) {
category.relatedCategories.forEach((catId) => {
rcid = createNodeId(`category-${catId}`)
relCats.push(rcid)
})
}
// build our final category object
nodeID = createNodeId(`category-${category.id}`)
var obj = {
...category,
id: nodeID,
cv3ID: category.id,
name: category.name,
parentCategory: parentNode.id,
productIDs: catProdIDs,
products: catProdIDs,
featuredProducts: featuredProdIDs,
subCategories: subCatIDs,
customFields: customFields,
relatedCategories: relCats,
internal: {
type: 'Category',
},
}
// add to our root object
rootObj.categories.push(obj)
// if we have more subcategories, recurse
if ('subCategories' in category) {
category.subCategories.forEach((subCat) => {
recursiveCategories(subCat, obj)
})
}
} |
JavaScript | function receive(message, robot) {
if (message.startsWith('init:')) {
totalDistance = parseFloat(message.substr(5));
console.log(totalDistance)
document.getElementById("remainingDistanceProgressBar").max = totalDistance-0.2;
}
else if (message.startsWith('distance:')) {
let distanceValue = totalDistance - parseFloat(message.substr(9));
document.getElementById('remainingDistanceProgressBar').value = distanceValue;
}
else if (message.startsWith('success')){
log("Success: " + RobotName + " reached the target of the " + challengeName + " challenge !");
}
else if (message.startsWith('failure'))
log("Failure: " + RobotName + " did not reach the target of the " + challengeName + " challenge.");
} | function receive(message, robot) {
if (message.startsWith('init:')) {
totalDistance = parseFloat(message.substr(5));
console.log(totalDistance)
document.getElementById("remainingDistanceProgressBar").max = totalDistance-0.2;
}
else if (message.startsWith('distance:')) {
let distanceValue = totalDistance - parseFloat(message.substr(9));
document.getElementById('remainingDistanceProgressBar').value = distanceValue;
}
else if (message.startsWith('success')){
log("Success: " + RobotName + " reached the target of the " + challengeName + " challenge !");
}
else if (message.startsWith('failure'))
log("Failure: " + RobotName + " did not reach the target of the " + challengeName + " challenge.");
} |
JavaScript | function receive(message, robot) {
if (message.startsWith('velocity: ')) {
message = message.substr(9).split(',');
let velocity = Math.abs(parseFloat(message[0]));
let time = parseFloat(message[1]);
updateChart(time, velocity);
}
} | function receive(message, robot) {
if (message.startsWith('velocity: ')) {
message = message.substr(9).split(',');
let velocity = Math.abs(parseFloat(message[0]));
let time = parseFloat(message[1]);
updateChart(time, velocity);
}
} |
JavaScript | function transposeVTree(vtree) {
if (typeof vtree.subscribe === `function`) {
return vtree.flatMapLatest(transposeVTree)
} else if (vtree.type === `VirtualText`) {
return Rx.Observable.just(vtree)
} else if (vtree.type === `VirtualNode` && Array.isArray(vtree.children) &&
vtree.children.length > 0)
{
return Rx.Observable
.combineLatest(vtree.children.map(transposeVTree), (...arr) =>
new VirtualNode(
vtree.tagName, vtree.properties, arr, vtree.key, vtree.namespace
)
)
} else if (vtree.type === `VirtualNode` ||
vtree.type === `Widget` ||
vtree.type === `Thunk`)
{
return Rx.Observable.just(vtree)
} else {
throw new Error(`Unhandled case in transposeVTree()`)
}
} | function transposeVTree(vtree) {
if (typeof vtree.subscribe === `function`) {
return vtree.flatMapLatest(transposeVTree)
} else if (vtree.type === `VirtualText`) {
return Rx.Observable.just(vtree)
} else if (vtree.type === `VirtualNode` && Array.isArray(vtree.children) &&
vtree.children.length > 0)
{
return Rx.Observable
.combineLatest(vtree.children.map(transposeVTree), (...arr) =>
new VirtualNode(
vtree.tagName, vtree.properties, arr, vtree.key, vtree.namespace
)
)
} else if (vtree.type === `VirtualNode` ||
vtree.type === `Widget` ||
vtree.type === `Thunk`)
{
return Rx.Observable.just(vtree)
} else {
throw new Error(`Unhandled case in transposeVTree()`)
}
} |
JavaScript | function addPermissionRules(doc, changes) {
changes["_permissionRulesApplied"] = [];
if (typeof doc._acl !== "undefined" && doc._acl.length > 0) {
changes["_userAcls"] = doc._acl;
} else {
changes["_userAcls"] = [];
}
} | function addPermissionRules(doc, changes) {
changes["_permissionRulesApplied"] = [];
if (typeof doc._acl !== "undefined" && doc._acl.length > 0) {
changes["_userAcls"] = doc._acl;
} else {
changes["_userAcls"] = [];
}
} |
JavaScript | function cleanup(plugin_name) {
var names = [service_name, controller_name, css_name, locale_name]
var deletelist = []
// loop thru the differnet sets of files we found
for (var name of names) {
// loop thru all the files of a type (service, controllers, ...)
for (var i in pluginFiles[name]) {
if (debug)
console.log(
"cleanup looking for " + plugin_name + " in " + pluginFiles[name][i]
)
// if the saved info matches the disabled plugin
if (
pluginFiles[name][i].toLowerCase().includes(plugin_name.toLowerCase())
) {
// lets remove it from the list
// if this is not a locale file
if (name !== locale_name) {
if (debug)
console.log(
"removing " +
name +
" entry for i=" +
i +
" " +
pluginFiles[name][i]
)
// we can remove it as we only look at the list once
// only 1 file of a type by plugin
pluginFiles[name].splice(i, 1)
break
} else {
// can't delete from the list while we are searching it
// save index, in reverse order for delete later
// add new higher number to front of list
deletelist.unshift(i)
}
}
}
}
// if we have stuff to delete, only one plugin at a time
if (deletelist.length > 0) {
// do it, depends on changing later in the array before earlier
// list is highest index to lowest
for (var d of deletelist) {
if (debug) console.log("deleteing " + pluginFiles[locale_name][d])
pluginFiles[locale_name].splice(d, 1)
}
}
} | function cleanup(plugin_name) {
var names = [service_name, controller_name, css_name, locale_name]
var deletelist = []
// loop thru the differnet sets of files we found
for (var name of names) {
// loop thru all the files of a type (service, controllers, ...)
for (var i in pluginFiles[name]) {
if (debug)
console.log(
"cleanup looking for " + plugin_name + " in " + pluginFiles[name][i]
)
// if the saved info matches the disabled plugin
if (
pluginFiles[name][i].toLowerCase().includes(plugin_name.toLowerCase())
) {
// lets remove it from the list
// if this is not a locale file
if (name !== locale_name) {
if (debug)
console.log(
"removing " +
name +
" entry for i=" +
i +
" " +
pluginFiles[name][i]
)
// we can remove it as we only look at the list once
// only 1 file of a type by plugin
pluginFiles[name].splice(i, 1)
break
} else {
// can't delete from the list while we are searching it
// save index, in reverse order for delete later
// add new higher number to front of list
deletelist.unshift(i)
}
}
}
}
// if we have stuff to delete, only one plugin at a time
if (deletelist.length > 0) {
// do it, depends on changing later in the array before earlier
// list is highest index to lowest
for (var d of deletelist) {
if (debug) console.log("deleteing " + pluginFiles[locale_name][d])
pluginFiles[locale_name].splice(d, 1)
}
}
} |
JavaScript | function init(target) {
target = target || document;
target.addEventListener('mousedown', function(ev) {
if (ev.button === 0) {
// trigger on left click only
startRipple(ev.type, ev);
}
}, {passive: true});
target.addEventListener('touchstart', function(ev) {
for (var i = 0; i < ev.changedTouches.length; ++i) {
startRipple(ev.type, ev.changedTouches[i]);
}
}, {passive: true});
} | function init(target) {
target = target || document;
target.addEventListener('mousedown', function(ev) {
if (ev.button === 0) {
// trigger on left click only
startRipple(ev.type, ev);
}
}, {passive: true});
target.addEventListener('touchstart', function(ev) {
for (var i = 0; i < ev.changedTouches.length; ++i) {
startRipple(ev.type, ev.changedTouches[i]);
}
}, {passive: true});
} |
JavaScript | update(position) {
if (this.fpsCount > 30) {
const coord = Util.XYZ2LatLon(position);
this.get(coord);
if (this.cityList.length > 0) {
this.rotationIndex = this.rotationIndex % this.cityLabels.length;
this.cityLabels[this.rotationIndex].setCity(this.cityList[0]);
this.rotationIndex += 1;
this.cityList.shift();
}
this.fpsCount = 0;
}
this.fpsCount += 1;
} | update(position) {
if (this.fpsCount > 30) {
const coord = Util.XYZ2LatLon(position);
this.get(coord);
if (this.cityList.length > 0) {
this.rotationIndex = this.rotationIndex % this.cityLabels.length;
this.cityLabels[this.rotationIndex].setCity(this.cityList[0]);
this.rotationIndex += 1;
this.cityList.shift();
}
this.fpsCount = 0;
}
this.fpsCount += 1;
} |
JavaScript | start(config) {
this.active = true;
this.config = config;
this.values = [];
this.alpha = 0;
this.time = config.time_start;
if (!this.config.time_start) this.config.time_start = 0;
if (!this.config.interval) this.config.interval = 1;
this.config.init_values.forEach((v) => {
this.values.push(v);
});
} | start(config) {
this.active = true;
this.config = config;
this.values = [];
this.alpha = 0;
this.time = config.time_start;
if (!this.config.time_start) this.config.time_start = 0;
if (!this.config.interval) this.config.interval = 1;
this.config.init_values.forEach((v) => {
this.values.push(v);
});
} |
JavaScript | update(elapsedTime) {
if (this.active) {
this.alpha = (this.time - this.config.time_start) / this.config.time_interval;
if (this.alpha <= 1 && this.alpha >= 0) {
/* sine interpolation */
if (this.config.sine_interpolation) { this.alpha = Math.sin(this.alpha * Math.PI * 0.5); }
for (let i = 0; i < this.values.length; i += 1) {
this.values[i] = (this.config.init_values[i] * (1.0 - this.alpha)) +
(this.config.end_values[i] * this.alpha);
}
if (this.config.onAnimationUpdate) { this.config.onAnimationUpdate(this.values); }
} else {
this.active = false;
if (this.config.onAnimationEnd) { this.config.onAnimationEnd(); }
}
this.time += elapsedTime;
}
} | update(elapsedTime) {
if (this.active) {
this.alpha = (this.time - this.config.time_start) / this.config.time_interval;
if (this.alpha <= 1 && this.alpha >= 0) {
/* sine interpolation */
if (this.config.sine_interpolation) { this.alpha = Math.sin(this.alpha * Math.PI * 0.5); }
for (let i = 0; i < this.values.length; i += 1) {
this.values[i] = (this.config.init_values[i] * (1.0 - this.alpha)) +
(this.config.end_values[i] * this.alpha);
}
if (this.config.onAnimationUpdate) { this.config.onAnimationUpdate(this.values); }
} else {
this.active = false;
if (this.config.onAnimationEnd) { this.config.onAnimationEnd(); }
}
this.time += elapsedTime;
}
} |
JavaScript | show(explorerIndex, explorers) {
this.setVisible(false);
for (let j = explorerIndex + 1; j <= this.daysLabels.length; j += 1) {
const dt = new Date();// this.valueOf()
dt.setDate(dt.getDate() + j);
const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const text = `${dt.getDate()} ${monthNames[dt.getMonth()]}`;
const alpha = j / 16.0;
if (alpha < explorers[explorerIndex].getAlpha()) {
this.daysLabels[j - 1].set(text, explorers[explorerIndex].getPosition(alpha));
this.daysLabels[j - 1].updatePosition();
} else {
break;
}
}
} | show(explorerIndex, explorers) {
this.setVisible(false);
for (let j = explorerIndex + 1; j <= this.daysLabels.length; j += 1) {
const dt = new Date();// this.valueOf()
dt.setDate(dt.getDate() + j);
const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const text = `${dt.getDate()} ${monthNames[dt.getMonth()]}`;
const alpha = j / 16.0;
if (alpha < explorers[explorerIndex].getAlpha()) {
this.daysLabels[j - 1].set(text, explorers[explorerIndex].getPosition(alpha));
this.daysLabels[j - 1].updatePosition();
} else {
break;
}
}
} |
JavaScript | function doneTyping (event) {
// Get query without white spaces
var query = event.target.value.trim();
// clear previous results
resultdiv.hide();
resultdiv.empty();
//chekc for valid query
if (query != "" && query.length > 1){
//set result dir value for search item
resultdiv.append('<li class="searchMatch">Matches for "' + query + '"</li>');
// Search for it
var result = index.search(query);
// check if we found matches
if (result.length === 0) {
// nothing found
resultdiv.append('<li class="searchItem">No results found</li>');
} else {
// display what we found
for (var item in result) {
var href = result[item].ref;
var searchitem = '<li class="searchItem"><a class="searchLink" href="./../' + href + '" target="_blank" style="font-size:30px;">' + store[href].title + '</a><p class="location">' + store[href].section + '</p></li>';
resultdiv.append(searchitem);
}
}
};
//show results
resultdiv.show();
} | function doneTyping (event) {
// Get query without white spaces
var query = event.target.value.trim();
// clear previous results
resultdiv.hide();
resultdiv.empty();
//chekc for valid query
if (query != "" && query.length > 1){
//set result dir value for search item
resultdiv.append('<li class="searchMatch">Matches for "' + query + '"</li>');
// Search for it
var result = index.search(query);
// check if we found matches
if (result.length === 0) {
// nothing found
resultdiv.append('<li class="searchItem">No results found</li>');
} else {
// display what we found
for (var item in result) {
var href = result[item].ref;
var searchitem = '<li class="searchItem"><a class="searchLink" href="./../' + href + '" target="_blank" style="font-size:30px;">' + store[href].title + '</a><p class="location">' + store[href].section + '</p></li>';
resultdiv.append(searchitem);
}
}
};
//show results
resultdiv.show();
} |
JavaScript | function hideTooltip(btn) {
setTimeout(function() {
$(btn).tooltip('hide');
}, 750);
} | function hideTooltip(btn) {
setTimeout(function() {
$(btn).tooltip('hide');
}, 750);
} |
JavaScript | function solve(){
function theSum(arrayOfNumbers) {
if(arrayOfNumbers.length === 0){
return null;
}
var sum = 0;
//first variant of solution
/*for (var i= 0; i< arrayOfNumbers.length; i+=1){
if(isNaN(arrayOfNumbers[i])){
throw new Error;
}
sum += +arrayOfNumbers[i]; //with +arrayOfNumbers parsing the string numbers to Number
}*/
//second variant of solution
if(arrayOfNumbers.some(function(item){
return isNaN(item);
})){
throw new Error('Array must contains only numbers');
}
sum = arrayOfNumbers.reduce(function(sum, number){
return Number(sum) +Number(number);
});
return sum;
}
var array = ['1', 2, 3];
return theSum(array);
} | function solve(){
function theSum(arrayOfNumbers) {
if(arrayOfNumbers.length === 0){
return null;
}
var sum = 0;
//first variant of solution
/*for (var i= 0; i< arrayOfNumbers.length; i+=1){
if(isNaN(arrayOfNumbers[i])){
throw new Error;
}
sum += +arrayOfNumbers[i]; //with +arrayOfNumbers parsing the string numbers to Number
}*/
//second variant of solution
if(arrayOfNumbers.some(function(item){
return isNaN(item);
})){
throw new Error('Array must contains only numbers');
}
sum = arrayOfNumbers.reduce(function(sum, number){
return Number(sum) +Number(number);
});
return sum;
}
var array = ['1', 2, 3];
return theSum(array);
} |
JavaScript | function solve(){
var Person = (function () {
function Person(firstName, lastName, inputAge) {
this.firstname = firstName;
this.lastname = lastName;
this.age = inputAge
}
function validateAge(value) {
var age = parseInt(value);
if (age < 0 || age > 150 || isNaN(age)) {
throw new Error('Age must be number between 0 and 150')
}
}
function validateName(value) {
if (!(value.length > 2 && value.length < 21)) {
throw new Error('Name length must be between 3 and 20 characters');
}
for (var i = 0; i < value.length; i += 1) {
if (!((value.charCodeAt(i) >= 65 && value.charCodeAt(i) <= 90) || (value.charCodeAt(i) >= 97 && value.charCodeAt(i) <= 122))) {
throw new Error('Name can contain only Latin letters');
}
}
}
Object.defineProperty(Person.prototype, 'firstname', {
get: function () {
return this._firstname;
},
set: function (value) {
validateName(value);
this._firstname = value;
return this;
}
});
Object.defineProperty(Person.prototype, 'lastname', {
get: function () {
return this._lastname;
},
set: function (value) {
validateName(value);
this._lastname = value;
return this;
}
});
Object.defineProperty(Person.prototype, 'age', {
get: function () {
return this._age;
},
set: function (value) {
validateAge(value);
this._age = parseInt(value);
return this;
}
});
Object.defineProperty(Person.prototype, 'fullname', {
get: function () {
return this._firstname + ' ' + this._lastname;
},
set: function (value) {
var names = value.split(' ');
validateName(names[0]);
validateName(names[1]);
this._firstname = names[0];
this._lastname = names[1];
return this;
}
});
Person.prototype.introduce = function () {
return 'Hello! My name is ' + this.fullname + ' and I am ' + this.age + '-years-old';
};
return Person;
}());
var Student = (function (parent) {
function Student(firstName, lastName, inputAge, inputGrade) {
parent.call(this, firstName, lastName, inputAge);
this.grade = inputGrade;
}
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Student.prototype = Object.create(Person.prototype);//TODO -the best solution
Student.prototype.constructor = Student;
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
function validateGrade(value) {
if (value < 2 || value > 6) {
throw new Error('Grade is invalid');
}
}
Object.defineProperty(Student.prototype, 'grade', {
get: function () {
return this._grade;
},
set: function (value) {
validateGrade(value);
this._grade = value;
return this;
}
});
Student.prototype.introduce = function(){
var baseResult = Person.prototype.introduce.call(this);
return baseResult + ' and my grade is: ' + this.grade;
};
return Student;
}(Person));
return {
Person: Person,
Student: Student
};
} | function solve(){
var Person = (function () {
function Person(firstName, lastName, inputAge) {
this.firstname = firstName;
this.lastname = lastName;
this.age = inputAge
}
function validateAge(value) {
var age = parseInt(value);
if (age < 0 || age > 150 || isNaN(age)) {
throw new Error('Age must be number between 0 and 150')
}
}
function validateName(value) {
if (!(value.length > 2 && value.length < 21)) {
throw new Error('Name length must be between 3 and 20 characters');
}
for (var i = 0; i < value.length; i += 1) {
if (!((value.charCodeAt(i) >= 65 && value.charCodeAt(i) <= 90) || (value.charCodeAt(i) >= 97 && value.charCodeAt(i) <= 122))) {
throw new Error('Name can contain only Latin letters');
}
}
}
Object.defineProperty(Person.prototype, 'firstname', {
get: function () {
return this._firstname;
},
set: function (value) {
validateName(value);
this._firstname = value;
return this;
}
});
Object.defineProperty(Person.prototype, 'lastname', {
get: function () {
return this._lastname;
},
set: function (value) {
validateName(value);
this._lastname = value;
return this;
}
});
Object.defineProperty(Person.prototype, 'age', {
get: function () {
return this._age;
},
set: function (value) {
validateAge(value);
this._age = parseInt(value);
return this;
}
});
Object.defineProperty(Person.prototype, 'fullname', {
get: function () {
return this._firstname + ' ' + this._lastname;
},
set: function (value) {
var names = value.split(' ');
validateName(names[0]);
validateName(names[1]);
this._firstname = names[0];
this._lastname = names[1];
return this;
}
});
Person.prototype.introduce = function () {
return 'Hello! My name is ' + this.fullname + ' and I am ' + this.age + '-years-old';
};
return Person;
}());
var Student = (function (parent) {
function Student(firstName, lastName, inputAge, inputGrade) {
parent.call(this, firstName, lastName, inputAge);
this.grade = inputGrade;
}
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Student.prototype = Object.create(Person.prototype);//TODO -the best solution
Student.prototype.constructor = Student;
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
function validateGrade(value) {
if (value < 2 || value > 6) {
throw new Error('Grade is invalid');
}
}
Object.defineProperty(Student.prototype, 'grade', {
get: function () {
return this._grade;
},
set: function (value) {
validateGrade(value);
this._grade = value;
return this;
}
});
Student.prototype.introduce = function(){
var baseResult = Person.prototype.introduce.call(this);
return baseResult + ' and my grade is: ' + this.grade;
};
return Student;
}(Person));
return {
Person: Person,
Student: Student
};
} |
JavaScript | function createServiceInputs(parameters) {
return omitUndefined(
{
Name: parameters.Name,
Description: parameters.Description,
DnsConfig: parameters.DnsConfig,
HealthCheckConfig: parameters.HealthCheckConfig,
HealthCheckCustomConfig: parameters.HealthCheckCustomConfig,
NamespaceId: parameters.NamespaceId,
Tags: parameters.Tags,
Type: parameters.Type,
},
);
} | function createServiceInputs(parameters) {
return omitUndefined(
{
Name: parameters.Name,
Description: parameters.Description,
DnsConfig: parameters.DnsConfig,
HealthCheckConfig: parameters.HealthCheckConfig,
HealthCheckCustomConfig: parameters.HealthCheckCustomConfig,
NamespaceId: parameters.NamespaceId,
Tags: parameters.Tags,
Type: parameters.Type,
},
);
} |
JavaScript | async function createService(client, parameters) {
const command = new CreateServiceCommand(parameters);
const response = await client.send(command);
return response;
} | async function createService(client, parameters) {
const command = new CreateServiceCommand(parameters);
const response = await client.send(command);
return response;
} |
JavaScript | async function deleteService(client, parameters) {
const command = new DeleteServiceCommand(parameters);
const response = await client.send(command);
return response;
} | async function deleteService(client, parameters) {
const command = new DeleteServiceCommand(parameters);
const response = await client.send(command);
return response;
} |
JavaScript | function postToGithub(response) {
let arn;
if (response.Arn) {
arn = response.Arn;
} else if (response.Service && response.Service.Arn) {
arn = response.Service.Arn;
} else {
throw new Error('Unable to determine ARN');
}
const id = arn.match(/^arn:aws:servicediscovery:[\w-]*:[0-9]*:service\/(srv-[\w]+)?/)[1];
core.info('ARN found or created: ' + arn);
core.setOutput('response', response);
core.setOutput('arn', arn);
core.setOutput('id', id);
} | function postToGithub(response) {
let arn;
if (response.Arn) {
arn = response.Arn;
} else if (response.Service && response.Service.Arn) {
arn = response.Service.Arn;
} else {
throw new Error('Unable to determine ARN');
}
const id = arn.match(/^arn:aws:servicediscovery:[\w-]*:[0-9]*:service\/(srv-[\w]+)?/)[1];
core.info('ARN found or created: ' + arn);
core.setOutput('response', response);
core.setOutput('arn', arn);
core.setOutput('id', id);
} |
JavaScript | async function run() {
const client = new ServiceDiscoveryClient({
customUserAgent: 'amazon-servicediscovery-service-for-github-actions',
});
client.middlewareStack.add((next, context) => (args) => {
core.debug(`Middleware sending ${context.commandName} to ${context.clientName} with: ${JSON.stringify(Object.assign({}, args.request, {body: JSON.parse(args.request.body)}))}`);
return next(args);
},
{
step: 'build', // add to `finalize` or `deserialize` for greater verbosity
},
);
// Get input parameters
const parameters = getParameters();
let response;
if (parameters.action == 'delete') {
response = await deleteService(client, deleteServiceInputs(parameters));
core.setOutput('response', response);
if (response.$metadata.httpStatusCode === 200) {
core.info(`Successfully deleted service with Id: ${parameters.Id}`);
} else {
throw new Error(`Failed to delete service: ${JSON.stringify(response)}`);
}
} else {
response = await createDescribeService(client, parameters);
postToGithub(response);
}
return response;
} | async function run() {
const client = new ServiceDiscoveryClient({
customUserAgent: 'amazon-servicediscovery-service-for-github-actions',
});
client.middlewareStack.add((next, context) => (args) => {
core.debug(`Middleware sending ${context.commandName} to ${context.clientName} with: ${JSON.stringify(Object.assign({}, args.request, {body: JSON.parse(args.request.body)}))}`);
return next(args);
},
{
step: 'build', // add to `finalize` or `deserialize` for greater verbosity
},
);
// Get input parameters
const parameters = getParameters();
let response;
if (parameters.action == 'delete') {
response = await deleteService(client, deleteServiceInputs(parameters));
core.setOutput('response', response);
if (response.$metadata.httpStatusCode === 200) {
core.info(`Successfully deleted service with Id: ${parameters.Id}`);
} else {
throw new Error(`Failed to delete service: ${JSON.stringify(response)}`);
}
} else {
response = await createDescribeService(client, parameters);
postToGithub(response);
}
return response;
} |
JavaScript | function parseLine(line) {
const element = {
type: 'text',
content: '',
block: false
};
// For each char in the string, check if its a new symbol.
// Otherwise add text to the buffer.
for (let index = 0; index < line.length; index++) {
const char = line[index];
const nextChar = line[index + 1];
if (char === '#' && nextChar === '#') {
element.type = 'header-secondary';
index++;
}
else if (char === '~' && nextChar === 'l') {
element.type = 'latest';
element.block = true;
return element;
}
else if (char === '~' && nextChar === 'i') {
element.type = 'image';
index++;
}
else if (char === '#') {
element.type = 'title';
}
else {
element.content += char;
}
}
return element;
} | function parseLine(line) {
const element = {
type: 'text',
content: '',
block: false
};
// For each char in the string, check if its a new symbol.
// Otherwise add text to the buffer.
for (let index = 0; index < line.length; index++) {
const char = line[index];
const nextChar = line[index + 1];
if (char === '#' && nextChar === '#') {
element.type = 'header-secondary';
index++;
}
else if (char === '~' && nextChar === 'l') {
element.type = 'latest';
element.block = true;
return element;
}
else if (char === '~' && nextChar === 'i') {
element.type = 'image';
index++;
}
else if (char === '#') {
element.type = 'title';
}
else {
element.content += char;
}
}
return element;
} |
JavaScript | function transformMarkdown(markdown) {
const content = {
title: '',
elements: []
}
const lines = markdown.split('\n');
lines.forEach(line => {
const element = parseLine(line);
if (element.type === 'title') {
content.title = element.content;
}
else if (element.content !== '' || element.block) {
content.elements.push(element);
}
});
return content;
} | function transformMarkdown(markdown) {
const content = {
title: '',
elements: []
}
const lines = markdown.split('\n');
lines.forEach(line => {
const element = parseLine(line);
if (element.type === 'title') {
content.title = element.content;
}
else if (element.content !== '' || element.block) {
content.elements.push(element);
}
});
return content;
} |
JavaScript | function display() {
document.getElementById("result").style.visibility = "visible";
document.getElementById("orderconfirm").style.visibility = "visible";
return false;
} | function display() {
document.getElementById("result").style.visibility = "visible";
document.getElementById("orderconfirm").style.visibility = "visible";
return false;
} |
JavaScript | function display2() {
document.getElementById("qn").style.visibility = "visible";
document.getElementById("phonenumber").style.visibility = "visible";
document.getElementById("zone").style.visibility = "visible";
document.getElementById("confirmphone").style.visibility = "visible";
return false;
} | function display2() {
document.getElementById("qn").style.visibility = "visible";
document.getElementById("phonenumber").style.visibility = "visible";
document.getElementById("zone").style.visibility = "visible";
document.getElementById("confirmphone").style.visibility = "visible";
return false;
} |
JavaScript | function loadAreas() {
//Send request
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "https://www.finnkino.fi/xml/TheatreAreas/", true);
xmlhttp.send();
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState == 4 && xmlhttp.status==200) {
//Save the response data in a variable for easy processing
var xmlDoc = xmlhttp.responseXML;
//Use getElementsByTagName to dig out theatre names and Ids (it is in array)
var theatreNames = xmlDoc.getElementsByTagName("Name");
var theatreIDs = xmlDoc.getElementsByTagName("ID");
//Loop through the whole array list
for(var i = 0; i < theatreNames.length; i++) {
//Gets the text from the XML files
var theatreText = theatreNames[i].innerHTML;
var theatreID = theatreIDs[i].innerHTML;
//Creates new option for the select list and makes it's value theatreID(from xml file)
document.getElementById("theatreList").innerHTML += '<option value = ' + theatreID + '>' + theatreText + '</option>';
}
}
}
} | function loadAreas() {
//Send request
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "https://www.finnkino.fi/xml/TheatreAreas/", true);
xmlhttp.send();
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState == 4 && xmlhttp.status==200) {
//Save the response data in a variable for easy processing
var xmlDoc = xmlhttp.responseXML;
//Use getElementsByTagName to dig out theatre names and Ids (it is in array)
var theatreNames = xmlDoc.getElementsByTagName("Name");
var theatreIDs = xmlDoc.getElementsByTagName("ID");
//Loop through the whole array list
for(var i = 0; i < theatreNames.length; i++) {
//Gets the text from the XML files
var theatreText = theatreNames[i].innerHTML;
var theatreID = theatreIDs[i].innerHTML;
//Creates new option for the select list and makes it's value theatreID(from xml file)
document.getElementById("theatreList").innerHTML += '<option value = ' + theatreID + '>' + theatreText + '</option>';
}
}
}
} |
JavaScript | function createColumnContent(params, str) {
var dataRows = createDataRows(params);
dataRows.forEach(function (dataElement) {
//if null do nothing, if empty object without includeEmptyRows do nothing
if (dataElement && (Object.getOwnPropertyNames(dataElement).length > 0 || params.includeEmptyRows)) {
var line = '';
var eol = params.newLine || os.EOL || '\n';
params.fields.forEach(function (fieldElement) {
var val;
var defaultValue = params.defaultValue;
if (typeof fieldElement === 'object' && 'default' in fieldElement) {
defaultValue = fieldElement.default;
}
if (fieldElement && (typeof fieldElement === 'string' || typeof fieldElement.value === 'string')) {
var path = (typeof fieldElement === 'string') ? fieldElement : fieldElement.value;
val = lodashGet(dataElement, path, defaultValue);
} else if (fieldElement && typeof fieldElement.value === 'function') {
var field = {
label: fieldElement.label,
default: fieldElement.default
};
val = fieldElement.value(dataElement, field, params.data);
}
if (val === null || val === undefined){
val = defaultValue;
}
if (val !== undefined) {
var stringifiedElement = JSON.stringify(val);
if (typeof val === 'object') stringifiedElement = JSON.stringify(stringifiedElement);
if (params.quotes !== '"') {
stringifiedElement = replaceQuotationMarks(stringifiedElement, params.quotes);
}
//JSON.stringify('\\') results in a string with two backslash
//characters in it. I.e. '\\\\'.
stringifiedElement = stringifiedElement.replace(/\\\\/g, '\\');
if (params.excelStrings && typeof val === 'string') {
stringifiedElement = '"="' + stringifiedElement + '""';
}
line += stringifiedElement;
}
line += params.del;
});
//remove last delimeter
line = line.substring(0, line.length - 1);
//Replace single quotes with double quotes. Single quotes are preceeded by
//a backslash. Be careful not to remove backslash content from the string.
line = line.split('\\\\').map(function (portion) {
return portion.replace(/\\"/g, params.doubleQuotes);
}).join('\\\\');
//Remove the final excess backslashes from the stringified value.
line = line.replace(/\\\\/g, '\\');
//If header exists, add it, otherwise, print only content
if (str !== '') {
str += eol + line + params.eol;
} else {
str = line + params.eol;
}
}
});
return str;
} | function createColumnContent(params, str) {
var dataRows = createDataRows(params);
dataRows.forEach(function (dataElement) {
//if null do nothing, if empty object without includeEmptyRows do nothing
if (dataElement && (Object.getOwnPropertyNames(dataElement).length > 0 || params.includeEmptyRows)) {
var line = '';
var eol = params.newLine || os.EOL || '\n';
params.fields.forEach(function (fieldElement) {
var val;
var defaultValue = params.defaultValue;
if (typeof fieldElement === 'object' && 'default' in fieldElement) {
defaultValue = fieldElement.default;
}
if (fieldElement && (typeof fieldElement === 'string' || typeof fieldElement.value === 'string')) {
var path = (typeof fieldElement === 'string') ? fieldElement : fieldElement.value;
val = lodashGet(dataElement, path, defaultValue);
} else if (fieldElement && typeof fieldElement.value === 'function') {
var field = {
label: fieldElement.label,
default: fieldElement.default
};
val = fieldElement.value(dataElement, field, params.data);
}
if (val === null || val === undefined){
val = defaultValue;
}
if (val !== undefined) {
var stringifiedElement = JSON.stringify(val);
if (typeof val === 'object') stringifiedElement = JSON.stringify(stringifiedElement);
if (params.quotes !== '"') {
stringifiedElement = replaceQuotationMarks(stringifiedElement, params.quotes);
}
//JSON.stringify('\\') results in a string with two backslash
//characters in it. I.e. '\\\\'.
stringifiedElement = stringifiedElement.replace(/\\\\/g, '\\');
if (params.excelStrings && typeof val === 'string') {
stringifiedElement = '"="' + stringifiedElement + '""';
}
line += stringifiedElement;
}
line += params.del;
});
//remove last delimeter
line = line.substring(0, line.length - 1);
//Replace single quotes with double quotes. Single quotes are preceeded by
//a backslash. Be careful not to remove backslash content from the string.
line = line.split('\\\\').map(function (portion) {
return portion.replace(/\\"/g, params.doubleQuotes);
}).join('\\\\');
//Remove the final excess backslashes from the stringified value.
line = line.replace(/\\\\/g, '\\');
//If header exists, add it, otherwise, print only content
if (str !== '') {
str += eol + line + params.eol;
} else {
str = line + params.eol;
}
}
});
return str;
} |
JavaScript | function createDataRows(params) {
var dataRows = params.data;
if (params.unwindPath) {
dataRows = [];
params.data.forEach(function(dataEl) {
var unwindArray = lodashGet(dataEl, params.unwindPath);
if (Array.isArray(unwindArray)) {
unwindArray.forEach(function(unwindEl) {
var dataCopy = lodashCloneDeep(dataEl);
lodashSet(dataCopy, params.unwindPath, unwindEl);
dataRows.push(dataCopy);
});
} else {
dataRows.push(dataEl);
}
});
}
return dataRows;
} | function createDataRows(params) {
var dataRows = params.data;
if (params.unwindPath) {
dataRows = [];
params.data.forEach(function(dataEl) {
var unwindArray = lodashGet(dataEl, params.unwindPath);
if (Array.isArray(unwindArray)) {
unwindArray.forEach(function(unwindEl) {
var dataCopy = lodashCloneDeep(dataEl);
lodashSet(dataCopy, params.unwindPath, unwindEl);
dataRows.push(dataCopy);
});
} else {
dataRows.push(dataEl);
}
});
}
return dataRows;
} |
JavaScript | isPalindromeNumber(n) {
if (Number.isInteger(n) || n > 0) {
return (n.toString() == n.toString().split('').reverse().join(''))
}
return false
} | isPalindromeNumber(n) {
if (Number.isInteger(n) || n > 0) {
return (n.toString() == n.toString().split('').reverse().join(''))
}
return false
} |
JavaScript | gcd(arr) {
if (arr.every((cur) => Number.isInteger(cur))) {
if (arr.length == 2) return this.gcdEuclidean(...arr)
let gcd = Math.max(...arr)
for (let i=0; i < arr.length; i++) {
gcd = this.gcdEuclidean(gcd, arr[i])
}
return gcd
}
return false
} | gcd(arr) {
if (arr.every((cur) => Number.isInteger(cur))) {
if (arr.length == 2) return this.gcdEuclidean(...arr)
let gcd = Math.max(...arr)
for (let i=0; i < arr.length; i++) {
gcd = this.gcdEuclidean(gcd, arr[i])
}
return gcd
}
return false
} |
JavaScript | lcm(arr) {
if (arr.every((cur) => Number.isInteger(cur) && cur > 0)) {
return arr.reduce((a, b) => (a*b)/this.gcd([a, b]))
}
return false
} | lcm(arr) {
if (arr.every((cur) => Number.isInteger(cur) && cur > 0)) {
return arr.reduce((a, b) => (a*b)/this.gcd([a, b]))
}
return false
} |
JavaScript | sumOfSquares(n) {
if (Number.isInteger(n) && n > 1) {
return Array.from(Array(n+1).keys())
.slice(1)
.reduce((acc, cur) => {
return acc + Math.pow(cur, 2)
}
)
}
return false
} | sumOfSquares(n) {
if (Number.isInteger(n) && n > 1) {
return Array.from(Array(n+1).keys())
.slice(1)
.reduce((acc, cur) => {
return acc + Math.pow(cur, 2)
}
)
}
return false
} |
JavaScript | squareOfSum(n) {
if (Number.isInteger(n) && n > 1) {
const sum = Array.from(Array(n+1).keys())
.slice(1)
.reduce((acc, cur) => {
return acc + cur
}
)
return Math.pow(sum, 2)
}
return false
} | squareOfSum(n) {
if (Number.isInteger(n) && n > 1) {
const sum = Array.from(Array(n+1).keys())
.slice(1)
.reduce((acc, cur) => {
return acc + cur
}
)
return Math.pow(sum, 2)
}
return false
} |
JavaScript | nthPrime(n) {
if (Number.isInteger(n)) {
// The upper bound works for n > 5, so I am settings bounds for n <= 5.
if (n > 5) {
return this.primeSieve(this.nthPrimeUpperBound(n))[n-1]
} else if (n == 5) {
return 11
} else if (n == 4) {
return 7
} else if (n == 3) {
return 5
} else if (n == 2) {
return 3
} else if (n == 1) {
return 2
}
}
return false
} | nthPrime(n) {
if (Number.isInteger(n)) {
// The upper bound works for n > 5, so I am settings bounds for n <= 5.
if (n > 5) {
return this.primeSieve(this.nthPrimeUpperBound(n))[n-1]
} else if (n == 5) {
return 11
} else if (n == 4) {
return 7
} else if (n == 3) {
return 5
} else if (n == 2) {
return 3
} else if (n == 1) {
return 2
}
}
return false
} |
JavaScript | nthPrimeUpperBound(n) {
return (Number.isInteger(n) && n > 5)
? Math.ceil(n*Math.log(n*Math.log(n)))
: false
} | nthPrimeUpperBound(n) {
return (Number.isInteger(n) && n > 5)
? Math.ceil(n*Math.log(n*Math.log(n)))
: false
} |
JavaScript | trueValues(arr) {
if (Array.isArray(arr)) {
return arr.filter((a) => a === true).length
}
return false
} | trueValues(arr) {
if (Array.isArray(arr)) {
return arr.filter((a) => a === true).length
}
return false
} |
JavaScript | _close() {
if (this._wss) {
this._wss.close();
this._wss = undefined;
this.emit("closed");
}
this._watcher.stop();
} | _close() {
if (this._wss) {
this._wss.close();
this._wss = undefined;
this.emit("closed");
}
this._watcher.stop();
} |
JavaScript | _connect() {
if (!this._wss) {
let streams = [].concat(
Array.from(this._tradeSubs.keys()).map(
p => p + (this.useAggTrades ? "@aggTrade" : "@trade")
),
Array.from(this._level2SnapshotSubs.keys()).map(p => p + "@depth20"),
Array.from(this._level2UpdateSubs.keys()).map(p => p + "@depth")
);
if (this._tickerSubs.size > 0) {
streams.push("!ticker@arr");
}
let wssPath = "wss://stream.binance.com:9443/stream?streams=" + streams.join("/");
this._wss = new SmartWss(wssPath);
this._wss.on("message", this._onMessage.bind(this));
this._wss.on("open", this._onConnected.bind(this));
this._wss.on("disconnected", this._onDisconnected.bind(this));
this._wss.connect();
}
} | _connect() {
if (!this._wss) {
let streams = [].concat(
Array.from(this._tradeSubs.keys()).map(
p => p + (this.useAggTrades ? "@aggTrade" : "@trade")
),
Array.from(this._level2SnapshotSubs.keys()).map(p => p + "@depth20"),
Array.from(this._level2UpdateSubs.keys()).map(p => p + "@depth")
);
if (this._tickerSubs.size > 0) {
streams.push("!ticker@arr");
}
let wssPath = "wss://stream.binance.com:9443/stream?streams=" + streams.join("/");
this._wss = new SmartWss(wssPath);
this._wss.on("message", this._onMessage.bind(this));
this._wss.on("open", this._onConnected.bind(this));
this._wss.on("disconnected", this._onDisconnected.bind(this));
this._wss.connect();
}
} |
JavaScript | update(dt, walls) {
super.update(dt, walls);
this.lifespan -= dt;
if (this.collide == 1){
this.direction = (this.direction % (2 * Math.PI)) + Math.PI/2;
} else if (this.collide == 2){
this.direction = (this.direction % (2 * Math.PI)) - Math.PI;
}
if (this.lifespan < 0){
return true;
} else {
return false;
}
} | update(dt, walls) {
super.update(dt, walls);
this.lifespan -= dt;
if (this.collide == 1){
this.direction = (this.direction % (2 * Math.PI)) + Math.PI/2;
} else if (this.collide == 2){
this.direction = (this.direction % (2 * Math.PI)) - Math.PI;
}
if (this.lifespan < 0){
return true;
} else {
return false;
}
} |
JavaScript | function applyCollisions(players, bullets) {
const destroyedBullets = [];
for (let i = 0; i < bullets.length; i++) {
// Look for a player (who didn't create the bullet) to collide each bullet with.
// As soon as we find one, break out of the loop to prevent double counting a bullet.
for (let j = 0; j < players.length; j++) {
const bullet = bullets[i];
const player = players[j];
if (
bullet.lifespan < Constants.BULLET_LIFESPAN * 4/5 &&
player.distanceTo(bullet) <= Constants.PLAYER_RADIUS + Constants.BULLET_RADIUS
) {
destroyedBullets.push(bullet);
player.takeBulletDamage();
break;
}
}
}
return destroyedBullets;
} | function applyCollisions(players, bullets) {
const destroyedBullets = [];
for (let i = 0; i < bullets.length; i++) {
// Look for a player (who didn't create the bullet) to collide each bullet with.
// As soon as we find one, break out of the loop to prevent double counting a bullet.
for (let j = 0; j < players.length; j++) {
const bullet = bullets[i];
const player = players[j];
if (
bullet.lifespan < Constants.BULLET_LIFESPAN * 4/5 &&
player.distanceTo(bullet) <= Constants.PLAYER_RADIUS + Constants.BULLET_RADIUS
) {
destroyedBullets.push(bullet);
player.takeBulletDamage();
break;
}
}
}
return destroyedBullets;
} |
JavaScript | update(dt, walls) {
super.update(dt, walls);
if (this.speed > 0)
this.speed -= Constants.PLAYER_SPEED / 5;
else if (this.speed < 0)
this.speed += Constants.PLAYER_SPEED / 5;
if (this.keys.up)
this.speed = Constants.PLAYER_SPEED;
else if (this.keys.down)
this.speed = -Constants.PLAYER_SPEED;
if (this.keys.left)
this.direction -= 0.05;
if (this.keys.right)
this.direction += 0.05;
// Update score
this.score += dt * Constants.SCORE_PER_SECOND;
// Fire a bullet, if needed
this.fireCooldown -= dt;
if (this.fireCooldown < 0)
this.fireCooldown = 0;
if (this.fireCooldown <= 0 && this.fire) {
this.fireCooldown += Constants.PLAYER_FIRE_COOLDOWN / 5;
this.fire = false;
return new Bullet(this.id, this.x, this.y, this.direction);
}
this.collide = false;
return null;
} | update(dt, walls) {
super.update(dt, walls);
if (this.speed > 0)
this.speed -= Constants.PLAYER_SPEED / 5;
else if (this.speed < 0)
this.speed += Constants.PLAYER_SPEED / 5;
if (this.keys.up)
this.speed = Constants.PLAYER_SPEED;
else if (this.keys.down)
this.speed = -Constants.PLAYER_SPEED;
if (this.keys.left)
this.direction -= 0.05;
if (this.keys.right)
this.direction += 0.05;
// Update score
this.score += dt * Constants.SCORE_PER_SECOND;
// Fire a bullet, if needed
this.fireCooldown -= dt;
if (this.fireCooldown < 0)
this.fireCooldown = 0;
if (this.fireCooldown <= 0 && this.fire) {
this.fireCooldown += Constants.PLAYER_FIRE_COOLDOWN / 5;
this.fire = false;
return new Bullet(this.id, this.x, this.y, this.direction);
}
this.collide = false;
return null;
} |
JavaScript | function handleQuery(message) {
chrome.storage.sync.get(['defaultSearchEngine'], result => {
/*
* Stores the default search engine.
*/
var engine = result.defaultSearchEngine;
if(!message.query) {
throw 'No Input';
}
if (message.query.startsWith('url:')) {
chrome.tabs.update(null, {url: 'https://'
+ message.query.substring(4).trim()});
} else {
switch (engine) {
case 'google':
chrome.tabs.update(null, {
url: 'https://www.google.com/search?q='
+ message.query
}
);
break;
case 'duckduckgo':
chrome.tabs.update(null, {
url: 'https://duckduckgo.com/?q='
+ message.query
}
);
break;
case 'startpage':
chrome.tabs.update(null, {
url: 'https://www.startpage.com/do/dsearch?query='
+ message.query
}
);
break;
default:
alert('Error with search engine preference');
break;
}
}
});
} | function handleQuery(message) {
chrome.storage.sync.get(['defaultSearchEngine'], result => {
/*
* Stores the default search engine.
*/
var engine = result.defaultSearchEngine;
if(!message.query) {
throw 'No Input';
}
if (message.query.startsWith('url:')) {
chrome.tabs.update(null, {url: 'https://'
+ message.query.substring(4).trim()});
} else {
switch (engine) {
case 'google':
chrome.tabs.update(null, {
url: 'https://www.google.com/search?q='
+ message.query
}
);
break;
case 'duckduckgo':
chrome.tabs.update(null, {
url: 'https://duckduckgo.com/?q='
+ message.query
}
);
break;
case 'startpage':
chrome.tabs.update(null, {
url: 'https://www.startpage.com/do/dsearch?query='
+ message.query
}
);
break;
default:
alert('Error with search engine preference');
break;
}
}
});
} |
JavaScript | function saveOptions() {
let searchEngine = document.getElementById('search-engine').value;
chrome.storage.sync.set({
defaultSearchEngine: searchEngine
}, function() {
let status = document.getElementById('status');
status.textContent = 'Options Saved!';
setTimeout(function() {
status.textContent = '';
}, 1000);
});
} | function saveOptions() {
let searchEngine = document.getElementById('search-engine').value;
chrome.storage.sync.set({
defaultSearchEngine: searchEngine
}, function() {
let status = document.getElementById('status');
status.textContent = 'Options Saved!';
setTimeout(function() {
status.textContent = '';
}, 1000);
});
} |
JavaScript | function restoreOptions() {
chrome.storage.sync.get(['defaultSearchEngine'], function(items) {
document.getElementById('search-engine').value =
items.defaultSearchEngine;
});
} | function restoreOptions() {
chrome.storage.sync.get(['defaultSearchEngine'], function(items) {
document.getElementById('search-engine').value =
items.defaultSearchEngine;
});
} |
JavaScript | function defineManyPermissions(permissionNames, validationFunction) {
if (!angular.isArray(permissionNames)) {
throw new TypeError('Parameter "permissionNames" name must be Array');
}
angular.forEach(permissionNames, function (permissionName) {
definePermission(permissionName, validationFunction);
});
} | function defineManyPermissions(permissionNames, validationFunction) {
if (!angular.isArray(permissionNames)) {
throw new TypeError('Parameter "permissionNames" name must be Array');
}
angular.forEach(permissionNames, function (permissionName) {
definePermission(permissionName, validationFunction);
});
} |
JavaScript | function compensatePermissionMap(statePermissionMap) {
var permissionMap = new PermissionMap({redirectTo: statePermissionMap.redirectTo});
var toStatePath = $state
.get(toState.name)
.getState().path
.slice()
.reverse();
angular.forEach(toStatePath, function (state) {
if (areSetStatePermissions(state)) {
permissionMap.extendPermissionMap(new PermissionMap(state.data.permissions));
}
});
return permissionMap;
} | function compensatePermissionMap(statePermissionMap) {
var permissionMap = new PermissionMap({redirectTo: statePermissionMap.redirectTo});
var toStatePath = $state
.get(toState.name)
.getState().path
.slice()
.reverse();
angular.forEach(toStatePath, function (state) {
if (areSetStatePermissions(state)) {
permissionMap.extendPermissionMap(new PermissionMap(state.data.permissions));
}
});
return permissionMap;
} |
JavaScript | function authorizeForState(permissions) {
Authorization
.authorize(permissions, toParams)
.then(function () {
$rootScope.$broadcast('$stateChangePermissionAccepted', toState, toParams, options);
$state
.go(toState.name, toParams, {notify: false})
.then(function () {
$rootScope.$broadcast('$stateChangeSuccess', toState, toParams);
});
})
.catch(function (rejectedPermission) {
$rootScope.$broadcast('$stateChangePermissionDenied', toState, toParams, options);
return permissions
.resolveRedirectState(rejectedPermission)
.then(function (redirectStateName) {
$state.go(redirectStateName, toParams);
});
})
.finally(function () {
setStateAuthorizationStatus(false);
$rootScope.$broadcast('$stateChangeSuccess');
});
} | function authorizeForState(permissions) {
Authorization
.authorize(permissions, toParams)
.then(function () {
$rootScope.$broadcast('$stateChangePermissionAccepted', toState, toParams, options);
$state
.go(toState.name, toParams, {notify: false})
.then(function () {
$rootScope.$broadcast('$stateChangeSuccess', toState, toParams);
});
})
.catch(function (rejectedPermission) {
$rootScope.$broadcast('$stateChangePermissionDenied', toState, toParams, options);
return permissions
.resolveRedirectState(rejectedPermission)
.then(function (redirectStateName) {
$state.go(redirectStateName, toParams);
});
})
.finally(function () {
setStateAuthorizationStatus(false);
$rootScope.$broadcast('$stateChangeSuccess');
});
} |
JavaScript | function resolveFunctionRedirect(redirectFunction, permission) {
return $q
.when(redirectFunction.call(null, permission))
.then(function (redirectState) {
if (!angular.isString(redirectState)) {
throw new TypeError('When used "redirectTo" as function, returned value must be string with state name');
}
return redirectState;
});
} | function resolveFunctionRedirect(redirectFunction, permission) {
return $q
.when(redirectFunction.call(null, permission))
.then(function (redirectState) {
if (!angular.isString(redirectState)) {
throw new TypeError('When used "redirectTo" as function, returned value must be string with state name');
}
return redirectState;
});
} |
JavaScript | function resolveObjectRedirect(redirectObject, permission) {
if (!angular.isDefined(redirectObject['default'])) {
throw new ReferenceError('When used "redirectTo" as object, property "default" must be defined');
}
var redirectState = redirectObject[permission];
if (!angular.isDefined(redirectState)) {
redirectState = redirectObject['default'];
}
if (angular.isFunction(redirectState)) {
return resolveFunctionRedirect(redirectState, permission);
}
if (angular.isString(redirectState)) {
return $q.resolve(redirectState);
}
} | function resolveObjectRedirect(redirectObject, permission) {
if (!angular.isDefined(redirectObject['default'])) {
throw new ReferenceError('When used "redirectTo" as object, property "default" must be defined');
}
var redirectState = redirectObject[permission];
if (!angular.isDefined(redirectState)) {
redirectState = redirectObject['default'];
}
if (angular.isFunction(redirectState)) {
return resolveFunctionRedirect(redirectState, permission);
}
if (angular.isString(redirectState)) {
return $q.resolve(redirectState);
}
} |
JavaScript | function wrapInPromise(result, permissionName) {
var dfd = $q.defer();
if (result) {
dfd.resolve(permissionName);
} else {
dfd.reject(permissionName);
}
return dfd.promise;
} | function wrapInPromise(result, permissionName) {
var dfd = $q.defer();
if (result) {
dfd.resolve(permissionName);
} else {
dfd.reject(permissionName);
}
return dfd.promise;
} |
JavaScript | function Role(roleName, permissionNames, validationFunction) {
validateConstructor(roleName, permissionNames, validationFunction);
this.roleName = roleName;
this.permissionNames = permissionNames || [];
this.validationFunction = validationFunction;
if (validationFunction) {
PermissionStore.defineManyPermissions(permissionNames, validationFunction);
}
} | function Role(roleName, permissionNames, validationFunction) {
validateConstructor(roleName, permissionNames, validationFunction);
this.roleName = roleName;
this.permissionNames = permissionNames || [];
this.validationFunction = validationFunction;
if (validationFunction) {
PermissionStore.defineManyPermissions(permissionNames, validationFunction);
}
} |
JavaScript | function wrapInPromise(result, roleName) {
var dfd = $q.defer();
if (result) {
dfd.resolve(roleName);
} else {
dfd.reject(roleName);
}
return dfd.promise;
} | function wrapInPromise(result, roleName) {
var dfd = $q.defer();
if (result) {
dfd.resolve(roleName);
} else {
dfd.reject(roleName);
}
return dfd.promise;
} |
JavaScript | function handleAuthorization(permissionsMap, toParams) {
var deferred = $q.defer();
var exceptPromises = findMatchingPermissions(permissionsMap.except, toParams);
only(exceptPromises)
.then(function (rejectedPermissions) {
deferred.reject(rejectedPermissions);
})
.catch(function () {
if (!permissionsMap.only.length) {
deferred.resolve(null);
}
var onlyPromises = findMatchingPermissions(permissionsMap.only, toParams);
only(onlyPromises)
.then(function (resolvedPermissions) {
deferred.resolve(resolvedPermissions);
})
.catch(function (rejectedPermission) {
deferred.reject(rejectedPermission);
});
});
return deferred.promise;
} | function handleAuthorization(permissionsMap, toParams) {
var deferred = $q.defer();
var exceptPromises = findMatchingPermissions(permissionsMap.except, toParams);
only(exceptPromises)
.then(function (rejectedPermissions) {
deferred.reject(rejectedPermissions);
})
.catch(function () {
if (!permissionsMap.only.length) {
deferred.resolve(null);
}
var onlyPromises = findMatchingPermissions(permissionsMap.only, toParams);
only(onlyPromises)
.then(function (resolvedPermissions) {
deferred.resolve(resolvedPermissions);
})
.catch(function (rejectedPermission) {
deferred.reject(rejectedPermission);
});
});
return deferred.promise;
} |
JavaScript | function only(promises) {
var deferred = $q.defer(),
counter = 0,
results = angular.isArray(promises) ? [] : {};
angular.forEach(promises, function (promise, key) {
counter++;
$q.when(promise)
.then(function (value) {
if (results.hasOwnProperty(key)) {
return;
}
deferred.resolve(value);
})
.catch(function (reason) {
if (results.hasOwnProperty(key)) {
return;
}
results[key] = reason;
if (!(--counter)) {
deferred.reject(reason);
}
});
});
if (counter === 0) {
deferred.reject(results);
}
return deferred.promise;
} | function only(promises) {
var deferred = $q.defer(),
counter = 0,
results = angular.isArray(promises) ? [] : {};
angular.forEach(promises, function (promise, key) {
counter++;
$q.when(promise)
.then(function (value) {
if (results.hasOwnProperty(key)) {
return;
}
deferred.resolve(value);
})
.catch(function (reason) {
if (results.hasOwnProperty(key)) {
return;
}
results[key] = reason;
if (!(--counter)) {
deferred.reject(reason);
}
});
});
if (counter === 0) {
deferred.reject(results);
}
return deferred.promise;
} |
JavaScript | function findMatchingPermissions(permissionNames, toParams) {
return permissionNames.map(function (permissionName) {
if (RoleStore.hasRoleDefinition(permissionName)) {
var role = RoleStore.getRoleDefinition(permissionName);
return role.validateRole(toParams);
}
if (PermissionStore.hasPermissionDefinition(permissionName)) {
var permission = PermissionStore.getPermissionDefinition(permissionName);
return permission.validatePermission(toParams);
}
if (permissionName) {
return $q.reject(permissionName);
}
});
} | function findMatchingPermissions(permissionNames, toParams) {
return permissionNames.map(function (permissionName) {
if (RoleStore.hasRoleDefinition(permissionName)) {
var role = RoleStore.getRoleDefinition(permissionName);
return role.validateRole(toParams);
}
if (PermissionStore.hasPermissionDefinition(permissionName)) {
var permission = PermissionStore.getPermissionDefinition(permissionName);
return permission.validatePermission(toParams);
}
if (permissionName) {
return $q.reject(permissionName);
}
});
} |
JavaScript | function showCart() {
// TODO: Find the table body
for (var i in cart.items) {
// TODO: Iterate over the items in the cart
// TODO: Create a TR
// TODO: Create a TD for the delete link, quantity, and the item
// TODO: Add the TR to the TBODY and each of the TD's to the TR
var trEl = document.createElement('tr');
var tdEl = document.createElement('td');
var tdEl2 = document.createElement('td');
var tdEl0 = document.createElement('td');
tdEl0.id=i;
tdEl0.addEventListener('click', removeItemFromCart);
tbody1.appendChild(trEl);
trEl.appendChild(tdEl0);
trEl.appendChild(tdEl);
trEl.appendChild(tdEl2);
tdEl2.textContent = cart.items[i].product;
tdEl.textContent = cart.items[i].quantity;
tdEl0.textContent = 'x';
}
} | function showCart() {
// TODO: Find the table body
for (var i in cart.items) {
// TODO: Iterate over the items in the cart
// TODO: Create a TR
// TODO: Create a TD for the delete link, quantity, and the item
// TODO: Add the TR to the TBODY and each of the TD's to the TR
var trEl = document.createElement('tr');
var tdEl = document.createElement('td');
var tdEl2 = document.createElement('td');
var tdEl0 = document.createElement('td');
tdEl0.id=i;
tdEl0.addEventListener('click', removeItemFromCart);
tbody1.appendChild(trEl);
trEl.appendChild(tdEl0);
trEl.appendChild(tdEl);
trEl.appendChild(tdEl2);
tdEl2.textContent = cart.items[i].product;
tdEl.textContent = cart.items[i].quantity;
tdEl0.textContent = 'x';
}
} |
JavaScript | function renderpager(pagenumber, pagecount, buttonClickCallback) {
// setup $pager to hold render
var $pager = $('<ul class="pages"></ul>');
// add in the previous and next buttons
$pager.append(renderButton('首页', pagenumber, pagecount, buttonClickCallback)).append(renderButton('上一页', pagenumber, pagecount, buttonClickCallback));
// pager currently only handles 10 viewable pages ( could be easily parameterized, maybe in next version ) so handle edge cases
var startPoint = 1;
var endPoint = 5;
if (pagenumber >= 5) {
startPoint = pagenumber - 2;
endPoint = pagenumber + 2;
}
if (endPoint > pagecount) {
startPoint = pagecount - 4;
endPoint = pagecount;
}
if (startPoint < 1) {
startPoint = 1;
}
// loop thru visible pages and render buttons
for (var page = startPoint; page <= endPoint; page++) {
var currentButton = $('<li class="page-number">' + (page) + '</li>');
page == pagenumber ? currentButton.addClass('pgCurrent') : currentButton.click(function() { buttonClickCallback(this.firstChild.data); });
currentButton.appendTo($pager);
}
// render in the next and 末页 buttons before returning the whole rendered control back.
$pager.append(renderButton('下一页', pagenumber, pagecount, buttonClickCallback)).append(renderButton('末页', pagenumber, pagecount, buttonClickCallback));
return $pager;
} | function renderpager(pagenumber, pagecount, buttonClickCallback) {
// setup $pager to hold render
var $pager = $('<ul class="pages"></ul>');
// add in the previous and next buttons
$pager.append(renderButton('首页', pagenumber, pagecount, buttonClickCallback)).append(renderButton('上一页', pagenumber, pagecount, buttonClickCallback));
// pager currently only handles 10 viewable pages ( could be easily parameterized, maybe in next version ) so handle edge cases
var startPoint = 1;
var endPoint = 5;
if (pagenumber >= 5) {
startPoint = pagenumber - 2;
endPoint = pagenumber + 2;
}
if (endPoint > pagecount) {
startPoint = pagecount - 4;
endPoint = pagecount;
}
if (startPoint < 1) {
startPoint = 1;
}
// loop thru visible pages and render buttons
for (var page = startPoint; page <= endPoint; page++) {
var currentButton = $('<li class="page-number">' + (page) + '</li>');
page == pagenumber ? currentButton.addClass('pgCurrent') : currentButton.click(function() { buttonClickCallback(this.firstChild.data); });
currentButton.appendTo($pager);
}
// render in the next and 末页 buttons before returning the whole rendered control back.
$pager.append(renderButton('下一页', pagenumber, pagecount, buttonClickCallback)).append(renderButton('末页', pagenumber, pagecount, buttonClickCallback));
return $pager;
} |
JavaScript | function inputTextFix(){
$("input[type='text'], input[type='password']").each(function(){
//each time a user clicks on a input field
$(this).click(function(){
//save the current value, if any
if($(this).attr("value")!=""){
$(this).attr("previous_value", $(this).attr("value"));
$(this).attr("value","");
}
});
//on blur, if left empty, restore the saved value, if any
$(this).blur(function(){
if($(this).attr("value") == "")
$(this).attr("value",$(this).attr("previous_value"));
});
});
} | function inputTextFix(){
$("input[type='text'], input[type='password']").each(function(){
//each time a user clicks on a input field
$(this).click(function(){
//save the current value, if any
if($(this).attr("value")!=""){
$(this).attr("previous_value", $(this).attr("value"));
$(this).attr("value","");
}
});
//on blur, if left empty, restore the saved value, if any
$(this).blur(function(){
if($(this).attr("value") == "")
$(this).attr("value",$(this).attr("previous_value"));
});
});
} |
JavaScript | function universalPreloader(){
var pre = $("#universal-preloader>div");
//centering function
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", (($(window).height() - this.outerHeight()) / 2) + "px");
this.css("left", (($(window).width() - this.outerWidth()) / 2) + "px");
return this;
}
//center to the screen
pre.center();
//run each time user resizes window
$(window).resize(function() {
pre.center();
});
} | function universalPreloader(){
var pre = $("#universal-preloader>div");
//centering function
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", (($(window).height() - this.outerHeight()) / 2) + "px");
this.css("left", (($(window).width() - this.outerWidth()) / 2) + "px");
return this;
}
//center to the screen
pre.center();
//run each time user resizes window
$(window).resize(function() {
pre.center();
});
} |
JavaScript | function universalPreloaderRemove(){
var parentD = $("#universal-preloader");
var pre = $("#universal-preloader>div");
var logo = $("#universal-preloader .universal-preloader-logo");
var loader = $("#universal-preloader .universal-preloader-preloader");
//when the logo and ajax-loader fades out, fade out the curtain; when that completes, remove the universal preloader from the DOM
pre.delay(1000).animate({opacity:'0'},{duration:400, complete:function(){
parentD.animate({opacity:'0'},{duration:400, complete:function(){
parentD.remove();
}});
}});
} | function universalPreloaderRemove(){
var parentD = $("#universal-preloader");
var pre = $("#universal-preloader>div");
var logo = $("#universal-preloader .universal-preloader-logo");
var loader = $("#universal-preloader .universal-preloader-preloader");
//when the logo and ajax-loader fades out, fade out the curtain; when that completes, remove the universal preloader from the DOM
pre.delay(1000).animate({opacity:'0'},{duration:400, complete:function(){
parentD.animate({opacity:'0'},{duration:400, complete:function(){
parentD.remove();
}});
}});
} |
JavaScript | function dogTalk(){
var timer = setTimeout(function() {
//change the bubble html code
$temp = "<p>"+$("div.bubble-options p.dog-bubble:nth-child("+talkbubble+")").html()+"</p>";
$("div.dog-bubble").html($temp);
//browse through bubble-options
if(talkbubble<maxtalk)
talkbubble++;
else
talkbubble = 1;
//show the bubble
$(".dog-bubble").animate({"opacity":'1', "bottom":'10px'}, 400);
//hide the bubble
setTimeout(function() {
$(".dog-bubble").animate({"opacity":'0', "bottom":'0px'}, 400);
dogTalk();
}, 5000);
}, 2000);
} | function dogTalk(){
var timer = setTimeout(function() {
//change the bubble html code
$temp = "<p>"+$("div.bubble-options p.dog-bubble:nth-child("+talkbubble+")").html()+"</p>";
$("div.dog-bubble").html($temp);
//browse through bubble-options
if(talkbubble<maxtalk)
talkbubble++;
else
talkbubble = 1;
//show the bubble
$(".dog-bubble").animate({"opacity":'1', "bottom":'10px'}, 400);
//hide the bubble
setTimeout(function() {
$(".dog-bubble").animate({"opacity":'0', "bottom":'0px'}, 400);
dogTalk();
}, 5000);
}, 2000);
} |
JavaScript | function rotate() {
$planet = $("div.planet");
//CSS3
$planet.css({ 'transform' : 'rotate(' + degree + 'deg)'});
// For webkit browsers: e.g. Chrome
$planet.css({ WebkitTransform : 'rotate(' + degree*2 + 'deg)'});
// For Mozilla browser: e.g. Firefox
$planet.css({ '-moz-transform' : 'rotate(' + degree + 'deg)'});
//IE9
$planet.css({ '-ms-transform' : 'rotate(' + degree + 'deg)'});
//Opera
$planet.css({ '-o-transform' : 'rotate(' + degree + 'deg)'});
// Animate rotation with a recursive call
var timer = setTimeout(function() {
degree-=0.1;
rotate();
},10);
} | function rotate() {
$planet = $("div.planet");
//CSS3
$planet.css({ 'transform' : 'rotate(' + degree + 'deg)'});
// For webkit browsers: e.g. Chrome
$planet.css({ WebkitTransform : 'rotate(' + degree*2 + 'deg)'});
// For Mozilla browser: e.g. Firefox
$planet.css({ '-moz-transform' : 'rotate(' + degree + 'deg)'});
//IE9
$planet.css({ '-ms-transform' : 'rotate(' + degree + 'deg)'});
//Opera
$planet.css({ '-o-transform' : 'rotate(' + degree + 'deg)'});
// Animate rotation with a recursive call
var timer = setTimeout(function() {
degree-=0.1;
rotate();
},10);
} |
JavaScript | function dogRun(){
var dog = $("div.dog");
var timer2 = setTimeout(function() {
if(dog.css("background-position") == "0px 0px")
dog.css({"background-position":"-80px -2px"});
else
dog.css({"background-position":"0px 0px"});
dogRun();
}, 130);
} | function dogRun(){
var dog = $("div.dog");
var timer2 = setTimeout(function() {
if(dog.css("background-position") == "0px 0px")
dog.css({"background-position":"-80px -2px"});
else
dog.css({"background-position":"0px 0px"});
dogRun();
}, 130);
} |
JavaScript | remove(ctx, id) {
if (ctx.state.data[id]) {
ctx.commit('remove', id);
ctx.dispatch('start');
}
} | remove(ctx, id) {
if (ctx.state.data[id]) {
ctx.commit('remove', id);
ctx.dispatch('start');
}
} |
JavaScript | start(ctx) {
var id,
timer,
timeout;
id = ctx.state.queue[ctx.state.queue.length - 1];
if (!id) {
return;
}
timeout = ctx.state.data[id].timeout || ctx.state.timeout;
clearTimeout(ctx.state.timer);
timer = setTimeout(() => {
ctx.dispatch('remove', id);
ctx.dispatch('end');
}, timeout);
ctx.commit('timer', timer);
} | start(ctx) {
var id,
timer,
timeout;
id = ctx.state.queue[ctx.state.queue.length - 1];
if (!id) {
return;
}
timeout = ctx.state.data[id].timeout || ctx.state.timeout;
clearTimeout(ctx.state.timer);
timer = setTimeout(() => {
ctx.dispatch('remove', id);
ctx.dispatch('end');
}, timeout);
ctx.commit('timer', timer);
} |
JavaScript | end(ctx) {
if (!ctx.state.queue.length) {
clearTimeout(ctx.state.timer);
ctx.commit('timer', null);
ctx.commit('clear');
}
else {
ctx.dispatch('start');
}
} | end(ctx) {
if (!ctx.state.queue.length) {
clearTimeout(ctx.state.timer);
ctx.commit('timer', null);
ctx.commit('clear');
}
else {
ctx.dispatch('start');
}
} |
JavaScript | data(state) {
var i, ii,
data = [];
for (i = 0, ii = state.queue.length; i < ii; i++) {
if (state.data[state.queue[i]]) {
data.push(state.data[state.queue[i]]);
}
}
return data;
} | data(state) {
var i, ii,
data = [];
for (i = 0, ii = state.queue.length; i < ii; i++) {
if (state.data[state.queue[i]]) {
data.push(state.data[state.queue[i]]);
}
}
return data;
} |
JavaScript | show(ctx, name) {
ctx.dispatch('hideable');
ctx.commit('previous', ctx.state.current);
ctx.commit('current', name);
} | show(ctx, name) {
ctx.dispatch('hideable');
ctx.commit('previous', ctx.state.current);
ctx.commit('current', name);
} |
JavaScript | action(ctx, data) {
var index;
if (
data.cb &&
data.data &&
ctx.state.data &&
ctx.state.data.items &&
ctx.state.data.items.constructor === Array
) {
index = findIndexByKey(ctx.state.data.items, data.data.id);
data.cb(index, data.data);
}
} | action(ctx, data) {
var index;
if (
data.cb &&
data.data &&
ctx.state.data &&
ctx.state.data.items &&
ctx.state.data.items.constructor === Array
) {
index = findIndexByKey(ctx.state.data.items, data.data.id);
data.cb(index, data.data);
}
} |
JavaScript | function stikyHeader() {
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
} | function stikyHeader() {
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
} |
JavaScript | function collapseAll() {
var elements = document.getElementsByClassName("paddingCollapsible");
var buttonCollapseAll = document.getElementById('buttonCollapseAll');
var collapsed = buttonCollapseAll.value;
if (elements.length == collapsed) {
// all of them are collapsed, so uncollapse all
for (let element of elements) {
// elements have the form 'collapsible#{neume.id}'
// so the 11th position is the start of the neume id
var id = element.id.substr(11,);
uncollapse(id);
}
buttonCollapseAll.value = 0;
}
else {
// at least one of them is collapsed, so collapse all
for (let element of elements) {
// elements have the form 'collapsible#{neume.id}'
// so the 11th position is the start of the neume id
var id = element.id.substr(11,);
collapse(id);
}
buttonCollapseAll.value = elements.length;
}
} | function collapseAll() {
var elements = document.getElementsByClassName("paddingCollapsible");
var buttonCollapseAll = document.getElementById('buttonCollapseAll');
var collapsed = buttonCollapseAll.value;
if (elements.length == collapsed) {
// all of them are collapsed, so uncollapse all
for (let element of elements) {
// elements have the form 'collapsible#{neume.id}'
// so the 11th position is the start of the neume id
var id = element.id.substr(11,);
uncollapse(id);
}
buttonCollapseAll.value = 0;
}
else {
// at least one of them is collapsed, so collapse all
for (let element of elements) {
// elements have the form 'collapsible#{neume.id}'
// so the 11th position is the start of the neume id
var id = element.id.substr(11,);
collapse(id);
}
buttonCollapseAll.value = elements.length;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.