language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function pickColor()
{
var random = Math.floor(Math.random() * colors.length);
return colors[random];
} | function pickColor()
{
var random = Math.floor(Math.random() * colors.length);
return colors[random];
} |
JavaScript | function kebabcase(value) {
return value
.toString()
.replace(
/([A-Z])/g,
(_, char) => `-${char.toLowerCase()}`
);
} | function kebabcase(value) {
return value
.toString()
.replace(
/([A-Z])/g,
(_, char) => `-${char.toLowerCase()}`
);
} |
JavaScript | _getValue(str) {
try {
// Get token from parser
const token = this.#parser.parse(str);
// DEV (fixed with throwed errors?)
// if (token === null) {
// Snitchy._displayWarnings(`Invalid value, no matching results for '${str}' [@snitchy/parser]`);
// return null;
// }
const { param, value: rawValue, extra, element, name, filters, defaults, optional } = token;
// Main rule comes from 'param'
const rule = this.#rules[param];
// Apply optional formating
const value = rule.format ? rule.format(rawValue) : rawValue;
// Get the "getters" (properties and/or methods)
const getters = rule.getters(value, extra);
// Root is the element on which we will apply the getters
let root = null;
if (element) {
// Get 'root()' of rule 'element'
root = rules[element].root(this, name);
} else if (rule.root) {
// For 'param', it's optional
root = rule.root(this, name);
} else {
root = document.documentElement.querySelector(`[${value}]`) || document.documentElement;
}
// Now let's have some data for pushing
let data = null;
data = Snitchy._processValue(root, getters);
// Post-processing through filters
if (filters) {
filters.forEach(filter => {
/* istanbul ignore else */
if (filter.match(/lowercase/)) {
data = data.toLowerCase();
}
/* istanbul ignore else */
if (filter.match(/uppercase/)) {
data = data.toUpperCase();
}
/* istanbul ignore else */
if (filter.match(/^.+\(.+\)$/)) {
const match = filter.match(/^(.+)\((?:'|")(.+)(?:'|")\)$/);
if (match === null) {
Snitchy._displayWarnings(`Invalid filter value for '${filter}' [@snitchy/core]`);
} else {
const [, method, arg] = match;
data = data[method](arg);
}
}
});
}
// No data but defaults
if (!data && defaults) {
data = defaults;
}
// No data but not optional
if (!data && !optional) {
Snitchy._displayWarnings(`No value found for '${str}', try 'defaults' or optional parameter [@snitchy/core]`);
}
return data;
} catch (error) {
// Something went wrong
Snitchy._displayWarnings(`Invalid value, no matching results for '${str}' [@snitchy/core]`);
Snitchy._displayWarnings(error);
return null;
}
} | _getValue(str) {
try {
// Get token from parser
const token = this.#parser.parse(str);
// DEV (fixed with throwed errors?)
// if (token === null) {
// Snitchy._displayWarnings(`Invalid value, no matching results for '${str}' [@snitchy/parser]`);
// return null;
// }
const { param, value: rawValue, extra, element, name, filters, defaults, optional } = token;
// Main rule comes from 'param'
const rule = this.#rules[param];
// Apply optional formating
const value = rule.format ? rule.format(rawValue) : rawValue;
// Get the "getters" (properties and/or methods)
const getters = rule.getters(value, extra);
// Root is the element on which we will apply the getters
let root = null;
if (element) {
// Get 'root()' of rule 'element'
root = rules[element].root(this, name);
} else if (rule.root) {
// For 'param', it's optional
root = rule.root(this, name);
} else {
root = document.documentElement.querySelector(`[${value}]`) || document.documentElement;
}
// Now let's have some data for pushing
let data = null;
data = Snitchy._processValue(root, getters);
// Post-processing through filters
if (filters) {
filters.forEach(filter => {
/* istanbul ignore else */
if (filter.match(/lowercase/)) {
data = data.toLowerCase();
}
/* istanbul ignore else */
if (filter.match(/uppercase/)) {
data = data.toUpperCase();
}
/* istanbul ignore else */
if (filter.match(/^.+\(.+\)$/)) {
const match = filter.match(/^(.+)\((?:'|")(.+)(?:'|")\)$/);
if (match === null) {
Snitchy._displayWarnings(`Invalid filter value for '${filter}' [@snitchy/core]`);
} else {
const [, method, arg] = match;
data = data[method](arg);
}
}
});
}
// No data but defaults
if (!data && defaults) {
data = defaults;
}
// No data but not optional
if (!data && !optional) {
Snitchy._displayWarnings(`No value found for '${str}', try 'defaults' or optional parameter [@snitchy/core]`);
}
return data;
} catch (error) {
// Something went wrong
Snitchy._displayWarnings(`Invalid value, no matching results for '${str}' [@snitchy/core]`);
Snitchy._displayWarnings(error);
return null;
}
} |
JavaScript | static _processValue(root, getters) {
return getters.reduce((acc, getter) => getter.type === 'property' ?
acc[getter.name] :
acc[getter.name](...Array.isArray(getter.value) ? getter.value : [getter.value]), root);
} | static _processValue(root, getters) {
return getters.reduce((acc, getter) => getter.type === 'property' ?
acc[getter.name] :
acc[getter.name](...Array.isArray(getter.value) ? getter.value : [getter.value]), root);
} |
JavaScript | open() {
return new Promise((resolve, reject)=>{
var request = indexedDB.open(this._name, this._version);
request.onsuccess = (event)=> {
this._db = event.target.result;
resolve();
};
request.onupgradeneeded = (event)=> {
try {
this._onUpgrade(event);
} catch(e) {
reject(e);
}
};
request.onerror = reject;
request.onblocked = reject;
});
} | open() {
return new Promise((resolve, reject)=>{
var request = indexedDB.open(this._name, this._version);
request.onsuccess = (event)=> {
this._db = event.target.result;
resolve();
};
request.onupgradeneeded = (event)=> {
try {
this._onUpgrade(event);
} catch(e) {
reject(e);
}
};
request.onerror = reject;
request.onblocked = reject;
});
} |
JavaScript | readAll() {
return new Promise((resolve, reject)=> {
var files = [];
var transaction = this._db.transaction(this._storeName, 'readonly');
transaction.oncomplete = ()=> {
resolve(files);
};
transaction.onerror = reject;
transaction.onabort = reject;
var store = transaction.objectStore(this._storeName);
var request = store.openCursor();
request.onsuccess = (event)=> {
var cursor = event.target.result;
if (cursor) {
files.push(cursor.value);
cursor.continue();
}
}
});
} | readAll() {
return new Promise((resolve, reject)=> {
var files = [];
var transaction = this._db.transaction(this._storeName, 'readonly');
transaction.oncomplete = ()=> {
resolve(files);
};
transaction.onerror = reject;
transaction.onabort = reject;
var store = transaction.objectStore(this._storeName);
var request = store.openCursor();
request.onsuccess = (event)=> {
var cursor = event.target.result;
if (cursor) {
files.push(cursor.value);
cursor.continue();
}
}
});
} |
JavaScript | removeAll() {
return new Promise((resolve, reject)=> {
var transaction = this._db.transaction(this._storeName, 'readwrite');
transaction.oncomplete = resolve;
transaction.onerror = reject;
transaction.onabort = reject;
var store = transaction.objectStore(this._storeName);
store.clear();
});
} | removeAll() {
return new Promise((resolve, reject)=> {
var transaction = this._db.transaction(this._storeName, 'readwrite');
transaction.oncomplete = resolve;
transaction.onerror = reject;
transaction.onabort = reject;
var store = transaction.objectStore(this._storeName);
store.clear();
});
} |
JavaScript | deleteStorage() {
if (this._db) {
this._db.close();
}
var request = indexedDB.deleteDatabase(this._name);
request.onerror = ()=> {
throw new request.error;
};
} | deleteStorage() {
if (this._db) {
this._db.close();
}
var request = indexedDB.deleteDatabase(this._name);
request.onerror = ()=> {
throw new request.error;
};
} |
JavaScript | function async(generatorFunction) {
var gen = generatorFunction();
return new Promise(function(resolve, reject){
onFulfilled();
function onFulfilled(val) {
try {
var result = gen.next(val);
} catch (e) {
return reject(e);
}
return chain(result);
}
function onRejected(e) {
try {
var result = gen.throw(e);
} catch (e) {
return reject(e);
}
return chain(result);
}
function chain(result) {
if (result.done) {
return resolve(result.value);
}
var promise = toPromise(result.value);
if (promise instanceof Promise) {
return promise.then(onFulfilled).catch(onRejected);
} else {
reject(new Error('value can not be converted to promise. value = ' + result.value));
}
}
});
} | function async(generatorFunction) {
var gen = generatorFunction();
return new Promise(function(resolve, reject){
onFulfilled();
function onFulfilled(val) {
try {
var result = gen.next(val);
} catch (e) {
return reject(e);
}
return chain(result);
}
function onRejected(e) {
try {
var result = gen.throw(e);
} catch (e) {
return reject(e);
}
return chain(result);
}
function chain(result) {
if (result.done) {
return resolve(result.value);
}
var promise = toPromise(result.value);
if (promise instanceof Promise) {
return promise.then(onFulfilled).catch(onRejected);
} else {
reject(new Error('value can not be converted to promise. value = ' + result.value));
}
}
});
} |
JavaScript | function toPromise(value) {
if (value instanceof Promise) {
return value;
}
if (Array.isArray(value)) {
var result = value.every((v)=>{
return v instanceof Promise;
});
if (result) {
return Promise.all(value);
}
}
if (value.constructor === Object) {
var result = {};
var promises = [];
for (var key of Object.keys(value)) {
var promise = value[key];
if (!(promise instanceof Promise)) {
return null;
}
promise = promise.then(function(key, value){
result[key] = value;
}.bind(this, key));
promises.push(promise);
}
return Promise.all(promises).then(()=>{
return result;
});
}
return null;
} | function toPromise(value) {
if (value instanceof Promise) {
return value;
}
if (Array.isArray(value)) {
var result = value.every((v)=>{
return v instanceof Promise;
});
if (result) {
return Promise.all(value);
}
}
if (value.constructor === Object) {
var result = {};
var promises = [];
for (var key of Object.keys(value)) {
var promise = value[key];
if (!(promise instanceof Promise)) {
return null;
}
promise = promise.then(function(key, value){
result[key] = value;
}.bind(this, key));
promises.push(promise);
}
return Promise.all(promises).then(()=>{
return result;
});
}
return null;
} |
JavaScript | function selectError(drawn) {
if (!checkSelectedID()) return;
var selection = context.surface()
.selectAll('.error_id-' + selectedErrorID + '.' + selectedErrorService);
if (selection.empty()) {
// Return to browse mode if selected DOM elements have
// disappeared because the user moved them out of view..
var source = d3_event && d3_event.type === 'zoom' && d3_event.sourceEvent;
if (drawn && source && (source.type === 'mousemove' || source.type === 'touchmove')) {
context.enter(modeBrowse(context));
}
} else {
selection
.classed('selected', true);
context.selectedErrorID(selectedErrorID);
}
} | function selectError(drawn) {
if (!checkSelectedID()) return;
var selection = context.surface()
.selectAll('.error_id-' + selectedErrorID + '.' + selectedErrorService);
if (selection.empty()) {
// Return to browse mode if selected DOM elements have
// disappeared because the user moved them out of view..
var source = d3_event && d3_event.type === 'zoom' && d3_event.sourceEvent;
if (drawn && source && (source.type === 'mousemove' || source.type === 'touchmove')) {
context.enter(modeBrowse(context));
}
} else {
selection
.classed('selected', true);
context.selectedErrorID(selectedErrorID);
}
} |
JavaScript | function runValidation(which) {
if (ran[which]) return true;
if (_disabledValidations[which]) {
// don't run disabled validations but mark as having run
ran[which] = true;
return true;
}
var fn = validations[which];
var typeIssues = fn(entity, context);
_issues = _issues.concat(typeIssues);
ran[which] = true; // mark this validation as having run
return !typeIssues.length;
} | function runValidation(which) {
if (ran[which]) return true;
if (_disabledValidations[which]) {
// don't run disabled validations but mark as having run
ran[which] = true;
return true;
}
var fn = validations[which];
var typeIssues = fn(entity, context);
_issues = _issues.concat(typeIssues);
ran[which] = true; // mark this validation as having run
return !typeIssues.length;
} |
JavaScript | function askQuestion() {
// Inquirer package to gather responses from user
inquirer.prompt([
{
name: "name",
type: "input",
message: "Enter the Team Manager's name."
},
{
name: "id",
type: "input",
message: "Enter the Team Manager's employee ID."
},
{
name: "email",
type: "input",
message: "Enter the Team Manager's email address."
},
{
name: "office",
type: "input",
message: "Enter the Team Manager's office number."
},
{
name: "question",
type: "list",
message: "Would you like to add an engineer or an intern to your team?",
choices: ["Add engineer", "Add intern"]
}
])
.then(response => {
// Sets responses to variables
const managerName = response.name;
const id = response.id;
const email = response.email
const office = response.office;
const question = response.question;
// Sets responses to our new instance of the constructor
const newManager = new Manager(managerName, id, email, office)
console.log(newManager);
employees.push(newManager);
// Directs user to appropriate function based on their input
switch (question) {
case "Add engineer":
console.log("add engineer!")
addEngineer();
break;
case "Add intern":
console.log("add intern!")
addIntern();
break;
default:
break;
}
})
} | function askQuestion() {
// Inquirer package to gather responses from user
inquirer.prompt([
{
name: "name",
type: "input",
message: "Enter the Team Manager's name."
},
{
name: "id",
type: "input",
message: "Enter the Team Manager's employee ID."
},
{
name: "email",
type: "input",
message: "Enter the Team Manager's email address."
},
{
name: "office",
type: "input",
message: "Enter the Team Manager's office number."
},
{
name: "question",
type: "list",
message: "Would you like to add an engineer or an intern to your team?",
choices: ["Add engineer", "Add intern"]
}
])
.then(response => {
// Sets responses to variables
const managerName = response.name;
const id = response.id;
const email = response.email
const office = response.office;
const question = response.question;
// Sets responses to our new instance of the constructor
const newManager = new Manager(managerName, id, email, office)
console.log(newManager);
employees.push(newManager);
// Directs user to appropriate function based on their input
switch (question) {
case "Add engineer":
console.log("add engineer!")
addEngineer();
break;
case "Add intern":
console.log("add intern!")
addIntern();
break;
default:
break;
}
})
} |
JavaScript | function gotData() {
var currentString = serial.readLine(); // read the incoming data
trim(currentString);
if (!currentString) return;
// console.log(currentString);
// expecting:
// 1234.56, 1
// where the first number is a float representing resistance in ohms,
// the second is the autoranging range, 0 to 2
const re = /^(.*),\s+(.*)/;
const match = re.exec(currentString);
if (!match) return;
// console.log('sensor = ' + match[1] + ' range = ' + match[2]);
if (!isNaN(match[1])) {
sensorValue = match[1];
autorangeValue = match[2];
}
} | function gotData() {
var currentString = serial.readLine(); // read the incoming data
trim(currentString);
if (!currentString) return;
// console.log(currentString);
// expecting:
// 1234.56, 1
// where the first number is a float representing resistance in ohms,
// the second is the autoranging range, 0 to 2
const re = /^(.*),\s+(.*)/;
const match = re.exec(currentString);
if (!match) return;
// console.log('sensor = ' + match[1] + ' range = ' + match[2]);
if (!isNaN(match[1])) {
sensorValue = match[1];
autorangeValue = match[2];
}
} |
JavaScript | async onAttached() {
console.log('onAttached ScreenSharePlugin !!!!!!!!!!!!!!!!!!!!!!');
this.logger.info('Asking user to share media. Please wait...');
let localmedia;
try {
localmedia = await navigator.mediaDevices.getDisplayMedia();
this.logger.info('Got local user Screen .');
console.log('Got local user Screen localmedia:', localmedia);
} catch (e) {
console.error('No screen share on this browser ...');
return;
}
const joinResualt = await this.sendMessage({
request: 'join', room: this.room_id, ptype: 'publisher', display: 'Screen Share', opaque_id: this.opaqueId,
});
console.log('Playing local user media in video element.', joinResualt);
this.logger.info('Playing local user media in video element.');
this.vid_local_screen.srcObject = localmedia;
this.vid_local_screen.play();
this.logger.info('Adding local user media to RTCPeerConnection.');
this.rtcconn.addStream(localmedia);
this.logger.info('Creating SDP offer. Please wait...');
const jsepOffer = await this.rtcconn.createOffer({
audio: false,
video: true,
});
this.logger.info('SDP offer created.');
this.logger.info('Setting SDP offer on RTCPeerConnection');
await this.rtcconn.setLocalDescription(jsepOffer);
this.logger.info('Getting SDP answer from Janus to our SDP offer. Please wait...');
/* const { jsep: jsep } = await this.sendJsep(jsepOffer);
this.logger.debug('Received SDP answer from Janus.');
*/
//
// await this.send({janus: "attach",opaque_id: this.opaqueId,plugin: "janus.plugin.videoroom"})
const confResult = await this.sendMessage({ request: 'configure', audio: false, video: true }, jsepOffer);
console.log('Received SDP answer from Janus for ScreenShare.', confResult);
this.logger.debug('Setting the SDP answer on RTCPeerConnection. The `onaddstream` event will fire soon.');
await this.rtcconn.setRemoteDescription(confResult.jsep);
} | async onAttached() {
console.log('onAttached ScreenSharePlugin !!!!!!!!!!!!!!!!!!!!!!');
this.logger.info('Asking user to share media. Please wait...');
let localmedia;
try {
localmedia = await navigator.mediaDevices.getDisplayMedia();
this.logger.info('Got local user Screen .');
console.log('Got local user Screen localmedia:', localmedia);
} catch (e) {
console.error('No screen share on this browser ...');
return;
}
const joinResualt = await this.sendMessage({
request: 'join', room: this.room_id, ptype: 'publisher', display: 'Screen Share', opaque_id: this.opaqueId,
});
console.log('Playing local user media in video element.', joinResualt);
this.logger.info('Playing local user media in video element.');
this.vid_local_screen.srcObject = localmedia;
this.vid_local_screen.play();
this.logger.info('Adding local user media to RTCPeerConnection.');
this.rtcconn.addStream(localmedia);
this.logger.info('Creating SDP offer. Please wait...');
const jsepOffer = await this.rtcconn.createOffer({
audio: false,
video: true,
});
this.logger.info('SDP offer created.');
this.logger.info('Setting SDP offer on RTCPeerConnection');
await this.rtcconn.setLocalDescription(jsepOffer);
this.logger.info('Getting SDP answer from Janus to our SDP offer. Please wait...');
/* const { jsep: jsep } = await this.sendJsep(jsepOffer);
this.logger.debug('Received SDP answer from Janus.');
*/
//
// await this.send({janus: "attach",opaque_id: this.opaqueId,plugin: "janus.plugin.videoroom"})
const confResult = await this.sendMessage({ request: 'configure', audio: false, video: true }, jsepOffer);
console.log('Received SDP answer from Janus for ScreenShare.', confResult);
this.logger.debug('Setting the SDP answer on RTCPeerConnection. The `onaddstream` event will fire soon.');
await this.rtcconn.setRemoteDescription(confResult.jsep);
} |
JavaScript | function primeSummation (num) {
var sigma = 0
function makePrimes (max) {
// Eratosthenes algorithm to find all primes under n
const array = []
// let upperLimit = Math.sqrt(max)
const output = []
// Make an array from 2 to (n - 1)
for (var i = 0; i <= max; i++) {
array.push(true)
}
// Remove multiples of primes starting from 2, 3, 5,...
for (let i = 2; i <= max; i++) {
if (array[i]) {
for (var j = i * i; j <= max; j += i) {
array[j] = false
}
}
}
// All array[i] set to true are primes
for (let i = 2; i <= max; i++) {
if (array[i]) {
output.push(i)
}
}
return output
}
var primes = makePrimes(num)
for (var p = 0; p < primes.length; p++) {
// Check if last is given number
if (primes[p] < num) { sigma += primes[p] }
}
return sigma
} | function primeSummation (num) {
var sigma = 0
function makePrimes (max) {
// Eratosthenes algorithm to find all primes under n
const array = []
// let upperLimit = Math.sqrt(max)
const output = []
// Make an array from 2 to (n - 1)
for (var i = 0; i <= max; i++) {
array.push(true)
}
// Remove multiples of primes starting from 2, 3, 5,...
for (let i = 2; i <= max; i++) {
if (array[i]) {
for (var j = i * i; j <= max; j += i) {
array[j] = false
}
}
}
// All array[i] set to true are primes
for (let i = 2; i <= max; i++) {
if (array[i]) {
output.push(i)
}
}
return output
}
var primes = makePrimes(num)
for (var p = 0; p < primes.length; p++) {
// Check if last is given number
if (primes[p] < num) { sigma += primes[p] }
}
return sigma
} |
JavaScript | function isPalindrome (num) {
const numStr = num.toString()
// do we need Zeros? only Heroes
if (numStr === '0') { return false }
if (numStr.split('').reverse().join('') === numStr) {
return true
} else {
return false
}
} | function isPalindrome (num) {
const numStr = num.toString()
// do we need Zeros? only Heroes
if (numStr === '0') { return false }
if (numStr.split('').reverse().join('') === numStr) {
return true
} else {
return false
}
} |
JavaScript | function matrix (num) {
var max = 0
for (var i = Math.floor(num * (8 / 9)); i < num + 1; i++) {
for (var j = i; j < num + 1; j++) {
if (isPalindrome(i * j) && (max < i * j)) {
max = i * j
}
}
}
return max
} | function matrix (num) {
var max = 0
for (var i = Math.floor(num * (8 / 9)); i < num + 1; i++) {
for (var j = i; j < num + 1; j++) {
if (isPalindrome(i * j) && (max < i * j)) {
max = i * j
}
}
}
return max
} |
JavaScript | function largeSum (arr) {
// Good luck!
const arraySum = arr.reduce(function (a, b) { return add(a, b) }, 1)
// LAME RESTRICTION in ten symbols.
return parseInt(arraySum.toString().split('').slice(0, 10).join(''), 10)
// return arraySum
} | function largeSum (arr) {
// Good luck!
const arraySum = arr.reduce(function (a, b) { return add(a, b) }, 1)
// LAME RESTRICTION in ten symbols.
return parseInt(arraySum.toString().split('').slice(0, 10).join(''), 10)
// return arraySum
} |
JavaScript | function sumPair (a, b, result, carry, base) {
if (a.length === 0 && b.length === 0 && !carry) {
return result
}
/* get the smallest char, i.e. right one */
const left = parseInt(a.pop() || '0', 10)
const rigth = parseInt(b.pop() || '0', 10)
/* Add them up and add carry from previous iteration */
const nextNum = left + rigth + (carry || 0)
return sumPair(a, b, nextNum % base + (result || ''), Math.floor(nextNum / base), base)
} | function sumPair (a, b, result, carry, base) {
if (a.length === 0 && b.length === 0 && !carry) {
return result
}
/* get the smallest char, i.e. right one */
const left = parseInt(a.pop() || '0', 10)
const rigth = parseInt(b.pop() || '0', 10)
/* Add them up and add carry from previous iteration */
const nextNum = left + rigth + (carry || 0)
return sumPair(a, b, nextNum % base + (result || ''), Math.floor(nextNum / base), base)
} |
JavaScript | function isPrime (num) {
if (isNaN(num) || !isFinite(num) || num % 1 || num < 2) return false
if (num % 2 === 0) return (num === 2)
if (num % 3 === 0) return (num === 3)
var m = Math.floor(Math.sqrt(num)) + 1
for (var i = 5; i <= m; i += 6) {
if (num % i === 0) return false
if (num % (i + 2) === 0) return false
}
return true
} | function isPrime (num) {
if (isNaN(num) || !isFinite(num) || num % 1 || num < 2) return false
if (num % 2 === 0) return (num === 2)
if (num % 3 === 0) return (num === 3)
var m = Math.floor(Math.sqrt(num)) + 1
for (var i = 5; i <= m; i += 6) {
if (num % i === 0) return false
if (num % (i + 2) === 0) return false
}
return true
} |
JavaScript | function smallestMult (n) {
const sM = numArr(n).reduce(function (accumulator, currentValue) {
return lcm(accumulator, currentValue)
}, 1)
return sM
} | function smallestMult (n) {
const sM = numArr(n).reduce(function (accumulator, currentValue) {
return lcm(accumulator, currentValue)
}, 1)
return sM
} |
JavaScript | function sieveAtkin (n) {
const isPrime = []
isPrime[0] = isPrime[1] = false
isPrime[2] = isPrime[3] = true
const max = 1500000
const upperLimit = Math.floor(Math.sqrt(max))
const output = [2, 3, 5]
for (var i = 4; i <= upperLimit; i++) {
isPrime.push(false)
}
let x2 = 0
// x2 y2 are squares of i j, presumably all primes are quadratic forms
for (let i = 1; i <= upperLimit; i++) {
x2 += 2 * i - 1
let y2 = 0
for (let j = 1; j <= upperLimit; j++) {
y2 += 2 * j - 1
let n = 4 * x2 + y2
if ((n <= upperLimit) && (n % 12 === 1 || n % 12 === 5)) {
isPrime[n] = !isPrime[n]
}
n -= x2
if ((n <= upperLimit) && (n % 12 === 7)) {
isPrime[n] = !isPrime[n]
}
n -= 2 * y2
if ((i > j) && (n <= upperLimit) && (n % 12 === 11)) {
isPrime[n] = !isPrime[n]
}
}
}
// Remove all prime squares in interval 5 - upperLimit
for (let i = 5; i <= upperLimit; i++) {
if (isPrime[i]) {
const n = i * i
for (let j = n; j <= upperLimit; j += n) {
isPrime[j] = false
}
}
}
// All array[i] set to true are primes and if they're multiple of num push them to result
for (let i = 6; i <= upperLimit; i++) {
if (isPrime[i] && (i % 3 !== 0) && (i % 5 !== 0) && (i < n)) {
output.push(i)
}
}
return output
} | function sieveAtkin (n) {
const isPrime = []
isPrime[0] = isPrime[1] = false
isPrime[2] = isPrime[3] = true
const max = 1500000
const upperLimit = Math.floor(Math.sqrt(max))
const output = [2, 3, 5]
for (var i = 4; i <= upperLimit; i++) {
isPrime.push(false)
}
let x2 = 0
// x2 y2 are squares of i j, presumably all primes are quadratic forms
for (let i = 1; i <= upperLimit; i++) {
x2 += 2 * i - 1
let y2 = 0
for (let j = 1; j <= upperLimit; j++) {
y2 += 2 * j - 1
let n = 4 * x2 + y2
if ((n <= upperLimit) && (n % 12 === 1 || n % 12 === 5)) {
isPrime[n] = !isPrime[n]
}
n -= x2
if ((n <= upperLimit) && (n % 12 === 7)) {
isPrime[n] = !isPrime[n]
}
n -= 2 * y2
if ((i > j) && (n <= upperLimit) && (n % 12 === 11)) {
isPrime[n] = !isPrime[n]
}
}
}
// Remove all prime squares in interval 5 - upperLimit
for (let i = 5; i <= upperLimit; i++) {
if (isPrime[i]) {
const n = i * i
for (let j = n; j <= upperLimit; j += n) {
isPrime[j] = false
}
}
}
// All array[i] set to true are primes and if they're multiple of num push them to result
for (let i = 6; i <= upperLimit; i++) {
if (isPrime[i] && (i % 3 !== 0) && (i % 5 !== 0) && (i < n)) {
output.push(i)
}
}
return output
} |
JavaScript | function falsePowerDigitSum (exponent) {
// Good luck!
let result = 0
let num = Math.pow(2, exponent)
while (num > 0) {
result += num % 10
num = Math.floor(num / 10)
}
return result
} | function falsePowerDigitSum (exponent) {
// Good luck!
let result = 0
let num = Math.pow(2, exponent)
while (num > 0) {
result += num % 10
num = Math.floor(num / 10)
}
return result
} |
JavaScript | function largestPrimeFactor (num) {
var sigma = 0
function makePrimes (max) {
// Eratosthenes algorithm to find all primes under n
const array = []
array[0] = array[1] = false
// let upperLimit = Math.sqrt(max)
const output = []
// Make an array from 2 to (n - 1)
for (var i = 2; i <= max; i++) {
array.push(true)
}
// Remove multiples of primes starting from 2, 3, 5,...
for (let i = 2; i <= max; i++) {
if (array[i]) {
for (var j = i * i; j <= max; j += i) {
array[j] = false
}
}
}
// All array[i] set to true are primes and if they're multiple of num push them to result
for (let i = 2; i <= max; i++) {
if (array[i] && (num % i === 0)) {
output.push(i)
}
}
return output
}
const upperLimit = Math.sqrt(num)
const primes = makePrimes(upperLimit)
primes.length === 0 ? sigma = num : sigma = Math.max.apply(Math, primes)
console.log(primes)
return sigma
} | function largestPrimeFactor (num) {
var sigma = 0
function makePrimes (max) {
// Eratosthenes algorithm to find all primes under n
const array = []
array[0] = array[1] = false
// let upperLimit = Math.sqrt(max)
const output = []
// Make an array from 2 to (n - 1)
for (var i = 2; i <= max; i++) {
array.push(true)
}
// Remove multiples of primes starting from 2, 3, 5,...
for (let i = 2; i <= max; i++) {
if (array[i]) {
for (var j = i * i; j <= max; j += i) {
array[j] = false
}
}
}
// All array[i] set to true are primes and if they're multiple of num push them to result
for (let i = 2; i <= max; i++) {
if (array[i] && (num % i === 0)) {
output.push(i)
}
}
return output
}
const upperLimit = Math.sqrt(num)
const primes = makePrimes(upperLimit)
primes.length === 0 ? sigma = num : sigma = Math.max.apply(Math, primes)
console.log(primes)
return sigma
} |
JavaScript | function fiboEvenSum (num) {
var i1 = 0
var i2 = 1
var i3 = 0
var sigma = 0
while (i2 <= num) {
(i2 % 2 === 0) ? (sigma += i2) : (sigma += 0)
i3 = i2 + i1
i1 = i2
i2 = i3
}
return sigma
} | function fiboEvenSum (num) {
var i1 = 0
var i2 = 1
var i3 = 0
var sigma = 0
while (i2 <= num) {
(i2 % 2 === 0) ? (sigma += i2) : (sigma += 0)
i3 = i2 + i1
i1 = i2
i2 = i3
}
return sigma
} |
JavaScript | function cycleLength (b) {
var a = 1
var t = 0
do {
a = a * 10 % b
t++
} while (a !== 1)
return t
} | function cycleLength (b) {
var a = 1
var t = 0
do {
a = a * 10 % b
t++
} while (a !== 1)
return t
} |
JavaScript | function reciprocalCycles (n) {
const originalPrimes = [7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157,
163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241,
251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347,
349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439,
443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547,
557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643,
647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751,
757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859,
863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977,
983, 991, 997]
var primes = originalPrimes.filter(el => el < n + 1)
var max = 0
var maxPeriod = 0
for (var i = 0; i < primes.length; i++) {
var tmp = cycleLength(primes[i])
if (max < tmp) {
maxPeriod = primes[i]
max = tmp
}
}
return maxPeriod
} | function reciprocalCycles (n) {
const originalPrimes = [7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157,
163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241,
251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347,
349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439,
443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547,
557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643,
647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751,
757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859,
863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977,
983, 991, 997]
var primes = originalPrimes.filter(el => el < n + 1)
var max = 0
var maxPeriod = 0
for (var i = 0; i < primes.length; i++) {
var tmp = cycleLength(primes[i])
if (max < tmp) {
maxPeriod = primes[i]
max = tmp
}
}
return maxPeriod
} |
JavaScript | function sumAmicableNum (n) {
let factorOne = 0
let factorTwo = 0
var sumAmicible = 0
for (let i = 2; i <= n; i++) {
factorOne = sumFactor(i)
if (factorOne > i && factorOne <= n) {
factorTwo = sumFactor(factorOne)
if (factorTwo === i) {
sumAmicible += (i + factorOne)
}
}
}
return sumAmicible
} | function sumAmicableNum (n) {
let factorOne = 0
let factorTwo = 0
var sumAmicible = 0
for (let i = 2; i <= n; i++) {
factorOne = sumFactor(i)
if (factorOne > i && factorOne <= n) {
factorTwo = sumFactor(factorOne)
if (factorTwo === i) {
sumAmicible += (i + factorOne)
}
}
}
return sumAmicible
} |
JavaScript | function coinSums (n) {
const target = n
const coinSizes = [1, 2, 5, 10, 20, 50, 100, 200]
// array of length of needed amount with 0, on eacg step we will populate each element starting from 1st
var ways = [...Array(n + 1).keys()].map(i => 0)
ways[0] = 1
for (let i = 0; i < coinSizes.length; i++) {
for (let j = coinSizes[i]; j <= target; j++) {
ways[j] += ways[j - coinSizes[i]]
}
}
return ways[target]
} | function coinSums (n) {
const target = n
const coinSizes = [1, 2, 5, 10, 20, 50, 100, 200]
// array of length of needed amount with 0, on eacg step we will populate each element starting from 1st
var ways = [...Array(n + 1).keys()].map(i => 0)
ways[0] = 1
for (let i = 0; i < coinSizes.length; i++) {
for (let j = coinSizes[i]; j <= target; j++) {
ways[j] += ways[j - coinSizes[i]]
}
}
return ways[target]
} |
JavaScript | function sumSquareDifference (n) {
const squaredSum = n * n * (n + 1) * (n + 1) / 4
const sumSquares = n * (n + 1) * (2 * n + 1) / 6
return squaredSum - sumSquares
} | function sumSquareDifference (n) {
const squaredSum = n * n * (n + 1) * (n + 1) / 4
const sumSquares = n * (n + 1) * (2 * n + 1) / 6
return squaredSum - sumSquares
} |
JavaScript | function sumPrimes (num) {
var sigma = 0
function makePrimes (max) {
// Eratosthenes algorithm to find all primes under n
const array = []
// let upperLimit = Math.sqrt(max)
const output = []
// Make an array from 2 to (n - 1)
for (var i = 0; i <= max; i++) {
array.push(true)
}
// Remove multiples of primes starting from 2, 3, 5,...
for (let i = 2; i <= max; i++) {
if (array[i]) {
for (var j = i * i; j <= max; j += i) {
array[j] = false
}
}
}
// All array[i] set to true are primes
for (let i = 2; i <= max; i++) {
if (array[i]) {
output.push(i)
}
}
return output
}
var primes = makePrimes(num)
for (var p = 0; p < primes.length; p++) {
sigma += primes[p]
}
console.log(primes)
return sigma
} | function sumPrimes (num) {
var sigma = 0
function makePrimes (max) {
// Eratosthenes algorithm to find all primes under n
const array = []
// let upperLimit = Math.sqrt(max)
const output = []
// Make an array from 2 to (n - 1)
for (var i = 0; i <= max; i++) {
array.push(true)
}
// Remove multiples of primes starting from 2, 3, 5,...
for (let i = 2; i <= max; i++) {
if (array[i]) {
for (var j = i * i; j <= max; j += i) {
array[j] = false
}
}
}
// All array[i] set to true are primes
for (let i = 2; i <= max; i++) {
if (array[i]) {
output.push(i)
}
}
return output
}
var primes = makePrimes(num)
for (var p = 0; p < primes.length; p++) {
sigma += primes[p]
}
console.log(primes)
return sigma
} |
JavaScript | function substringDivisibility () {
// Good luck!
const arr = []
arr.push(1430952867)
arr.push(4130952867)
arr.push(1460357289)
arr.push(4160357289)
arr.push(1406357289)
arr.push(1406357289)
arr.sort()
return arr
} | function substringDivisibility () {
// Good luck!
const arr = []
arr.push(1430952867)
arr.push(4130952867)
arr.push(1460357289)
arr.push(4160357289)
arr.push(1406357289)
arr.push(1406357289)
arr.sort()
return arr
} |
JavaScript | function showSlides(n) {
// Get all the slides by their class name.
let slides = document.getElementsByClassName("slides");
// If the index is greater than the slide length, loop it back.
if (n > slides.length) {
slideIndex = 1
}
// If the index is less than one, loop it to the last slide.
if (n < 1) {
slideIndex = slides.length
}
// Set all the slides to not appearing.
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
// Make the slide that the index is one to appear.
slides[slideIndex - 1].style.display = "block";
} | function showSlides(n) {
// Get all the slides by their class name.
let slides = document.getElementsByClassName("slides");
// If the index is greater than the slide length, loop it back.
if (n > slides.length) {
slideIndex = 1
}
// If the index is less than one, loop it to the last slide.
if (n < 1) {
slideIndex = slides.length
}
// Set all the slides to not appearing.
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
// Make the slide that the index is one to appear.
slides[slideIndex - 1].style.display = "block";
} |
JavaScript | function startServer(PORT) {
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.get('/api/object', (req, res) => {
res.send({
data: 'object'
})
})
app.get('/api/object2', (req, res) => {
if (typeof req.headers.specialheader === 'string') {
res.send({
data: `object2 with special header: '${req.headers.specialheader}'`
})
} else {
res.send({
data: 'object2'
})
}
})
app.post('/api/formUrlEncoded', (req, res) => {
res.send(req.body)
})
app.get('/api/cars/:id', (req, res) => {
res.send(`Car ID: ${req.params.id}`)
})
app.get('/api/cacti/:cactusId', (req, res) => {
res.send(`Cactus ID: ${req.params.cactusId}`)
})
app.get(
'/api/eateries/:eatery/breads/:breadName/dishes/:dishKey',
(req, res) => {
res.send(
`Parameters combined: ${req.params.eatery} ${req.params.breadName} ${req.params.dishKey}`
)
}
)
function stringifyRussianDolls(russianDoll) {
if (!typeof russianDoll.name === 'string') {
return ''
}
if (typeof russianDoll.nestedDoll === 'object') {
return `${russianDoll.name}, ${stringifyRussianDolls(
russianDoll.nestedDoll
)}`
} else {
return russianDoll.name
}
}
app.get('/api/nestedReferenceInParameter', (req, res) => {
res.send(stringifyRussianDolls(req.query.russianDoll))
})
app.get('/api/strictGetOperation', (req, res) => {
if (req.headers['content-type']) {
res
.status(400)
.set('Content-Type', 'text/plain')
.send('Get request should not have Content-Type')
} else {
res.set('Content-Type', 'text/plain').send('Perfect!')
}
})
app.get('/api/noResponseSchema', (req, res) => {
res.set('Content-Type', 'text/plain').send('Hello world')
})
app.get('/api/returnNumber', (req, res) => {
res.set('Content-Type', 'text/plain').send(req.headers.number)
})
app.get('/api/testLinkWithNonStringParam', (req, res) => {
res.send({"hello": "world"})
})
app.get('/api/testLinkwithNestedParam', (req, res) => {
res.send({"nesting1": {"nesting2": 5} })
})
return new Promise((resolve) => {
server = app.listen(PORT, () => {
console.log(`Example API accessible on port ${PORT}`)
resolve()
})
})
} | function startServer(PORT) {
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.get('/api/object', (req, res) => {
res.send({
data: 'object'
})
})
app.get('/api/object2', (req, res) => {
if (typeof req.headers.specialheader === 'string') {
res.send({
data: `object2 with special header: '${req.headers.specialheader}'`
})
} else {
res.send({
data: 'object2'
})
}
})
app.post('/api/formUrlEncoded', (req, res) => {
res.send(req.body)
})
app.get('/api/cars/:id', (req, res) => {
res.send(`Car ID: ${req.params.id}`)
})
app.get('/api/cacti/:cactusId', (req, res) => {
res.send(`Cactus ID: ${req.params.cactusId}`)
})
app.get(
'/api/eateries/:eatery/breads/:breadName/dishes/:dishKey',
(req, res) => {
res.send(
`Parameters combined: ${req.params.eatery} ${req.params.breadName} ${req.params.dishKey}`
)
}
)
function stringifyRussianDolls(russianDoll) {
if (!typeof russianDoll.name === 'string') {
return ''
}
if (typeof russianDoll.nestedDoll === 'object') {
return `${russianDoll.name}, ${stringifyRussianDolls(
russianDoll.nestedDoll
)}`
} else {
return russianDoll.name
}
}
app.get('/api/nestedReferenceInParameter', (req, res) => {
res.send(stringifyRussianDolls(req.query.russianDoll))
})
app.get('/api/strictGetOperation', (req, res) => {
if (req.headers['content-type']) {
res
.status(400)
.set('Content-Type', 'text/plain')
.send('Get request should not have Content-Type')
} else {
res.set('Content-Type', 'text/plain').send('Perfect!')
}
})
app.get('/api/noResponseSchema', (req, res) => {
res.set('Content-Type', 'text/plain').send('Hello world')
})
app.get('/api/returnNumber', (req, res) => {
res.set('Content-Type', 'text/plain').send(req.headers.number)
})
app.get('/api/testLinkWithNonStringParam', (req, res) => {
res.send({"hello": "world"})
})
app.get('/api/testLinkwithNestedParam', (req, res) => {
res.send({"nesting1": {"nesting2": 5} })
})
return new Promise((resolve) => {
server = app.listen(PORT, () => {
console.log(`Example API accessible on port ${PORT}`)
resolve()
})
})
} |
JavaScript | function hasAttribute(ts, node) {
const properties = node.properties;
if (!properties) {
return false;
}
for (let i = 0; i < properties.length; i++) {
const property = properties[i];
if (!ts.isPropertyAssignment(property)) {
continue;
}
if (property.name.getText() === 'attribute') {
if (property.initializer.kind === ts.SyntaxKind.StringLiteral) {
return true;
} else if (property.initializer.kind === ts.SyntaxKind.TrueKeyword) {
return true;
}
return false;
}
}
return false;
} | function hasAttribute(ts, node) {
const properties = node.properties;
if (!properties) {
return false;
}
for (let i = 0; i < properties.length; i++) {
const property = properties[i];
if (!ts.isPropertyAssignment(property)) {
continue;
}
if (property.name.getText() === 'attribute') {
if (property.initializer.kind === ts.SyntaxKind.StringLiteral) {
return true;
} else if (property.initializer.kind === ts.SyntaxKind.TrueKeyword) {
return true;
}
return false;
}
}
return false;
} |
JavaScript | function Rocky (opts) {
if (!(this instanceof Rocky)) return new Rocky(opts)
opts = opts || {}
Base.call(this, opts)
this.server = null
this.router = router(opts.router)
this._setupMiddleware()
} | function Rocky (opts) {
if (!(this instanceof Rocky)) return new Rocky(opts)
opts = opts || {}
Base.call(this, opts)
this.server = null
this.router = router(opts.router)
this._setupMiddleware()
} |
JavaScript | function Base (opts) {
Emitter.call(this)
this.replays = []
this.opts = opts || {}
this.mw = new MwPool()
} | function Base (opts) {
Emitter.call(this)
this.replays = []
this.opts = opts || {}
this.mw = new MwPool()
} |
JavaScript | function createLocalForwarder(host, hubPort, localPort) {
debug(`Creating forwarder at hub:${hubPort}`)
const hub = net.createConnection({host, port: hubPort})
const local = net.createConnection({port: localPort})
const cleanup = _.once(function() {
debug(`Closing forwarder at hub:${hubPort}`)
hub.destroy()
local.destroy()
})
hub.on('data', d => local.write(d))
hub.on('close', () => cleanup())
local.on('data', d => hub.write(d))
local.on('close', () => cleanup())
} | function createLocalForwarder(host, hubPort, localPort) {
debug(`Creating forwarder at hub:${hubPort}`)
const hub = net.createConnection({host, port: hubPort})
const local = net.createConnection({port: localPort})
const cleanup = _.once(function() {
debug(`Closing forwarder at hub:${hubPort}`)
hub.destroy()
local.destroy()
})
hub.on('data', d => local.write(d))
hub.on('close', () => cleanup())
local.on('data', d => hub.write(d))
local.on('close', () => cleanup())
} |
JavaScript | async function expose(host, requestedPublicPort, localPort) {
const {ctrlPort, pubPort} = await fetch(
`http://${host}:3000/create-tunnel/${requestedPublicPort || ''}`
).then(r => r.json())
debug('ctrlPort is', ctrlPort)
console.log('Public port is', pubPort)
const sock = net.createConnection({
host,
port: ctrlPort,
})
sock.on('data', d => {
const hubPort = parseInt(d.toString('utf-8'))
createLocalForwarder(host, hubPort, localPort)
})
} | async function expose(host, requestedPublicPort, localPort) {
const {ctrlPort, pubPort} = await fetch(
`http://${host}:3000/create-tunnel/${requestedPublicPort || ''}`
).then(r => r.json())
debug('ctrlPort is', ctrlPort)
console.log('Public port is', pubPort)
const sock = net.createConnection({
host,
port: ctrlPort,
})
sock.on('data', d => {
const hubPort = parseInt(d.toString('utf-8'))
createLocalForwarder(host, hubPort, localPort)
})
} |
JavaScript | function clearGrid(){
if(gridContainer.hasChildNodes()){
while(gridContainer.hasChildNodes()){
gridContainer.removeChild(gridContainer.lastChild);
}
}
} | function clearGrid(){
if(gridContainer.hasChildNodes()){
while(gridContainer.hasChildNodes()){
gridContainer.removeChild(gridContainer.lastChild);
}
}
} |
JavaScript | writeFile(filename, data, create = false, exclusive = true) {
const name = filename.split('/').pop();
const path = Url.dirname(filename);
if (data instanceof ArrayBuffer) {
data = new Blob([data]);
}
return new Promise((resolve, reject) => {
if (!create) {
window.resolveLocalFileSystemURL(filename, (fileEntry) => {
if (!fileEntry.isFile) reject(new Error('Expected file but got directory.'));
fileEntry.createWriter((file) => {
file.onwriteend = () => resolve(filename);
file.onerror = (err) => reject(err.target.error);
file.write(data);
});
}, reject);
} else {
window.resolveLocalFileSystemURL(path, (fs) => {
fs.getFile(name, {
create,
exclusive: create ? exclusive : false,
}, (fileEntry) => {
fileEntry.createWriter((file) => {
file.onwriteend = () => resolve(filename);
file.onerror = (err) => reject(err.target.error);
file.write(data);
});
}, reject);
}, reject);
}
});
} | writeFile(filename, data, create = false, exclusive = true) {
const name = filename.split('/').pop();
const path = Url.dirname(filename);
if (data instanceof ArrayBuffer) {
data = new Blob([data]);
}
return new Promise((resolve, reject) => {
if (!create) {
window.resolveLocalFileSystemURL(filename, (fileEntry) => {
if (!fileEntry.isFile) reject(new Error('Expected file but got directory.'));
fileEntry.createWriter((file) => {
file.onwriteend = () => resolve(filename);
file.onerror = (err) => reject(err.target.error);
file.write(data);
});
}, reject);
} else {
window.resolveLocalFileSystemURL(path, (fs) => {
fs.getFile(name, {
create,
exclusive: create ? exclusive : false,
}, (fileEntry) => {
fileEntry.createWriter((file) => {
file.onwriteend = () => resolve(filename);
file.onerror = (err) => reject(err.target.error);
file.write(data);
});
}, reject);
}, reject);
}
});
} |
JavaScript | function generateMarkdown(data) {
// set url for license badge
data.licenseBadge = licenseBadgeLinks[data.license];
// return markdown content
return `# ${data.title}
${data.licenseBadge}
## Description
${data.description}
## Table of Contents
* [Installation](#installation)
* [Usage](#usage)
* [License](#license)
* [Contributing](#contributing)
* [Tests](#tests)
* [Questions](#questions)
## Installation
To install dependencies, run the following:
\`
${data.installation}
\`
## Usage
${data.usage}
## License
This repository is licensed under the ${data.license} license.
## Contributing
${data.contribute}
## Tests
To run tests, run the following:
\`
${data.tests}
\`
## Questions
Questions about this repository? Please contact me at [${data.email}](mailto:${data.email}). View more of my work in GitHub at [${data.username}](https://github.com/${data.username})
`;
} | function generateMarkdown(data) {
// set url for license badge
data.licenseBadge = licenseBadgeLinks[data.license];
// return markdown content
return `# ${data.title}
${data.licenseBadge}
## Description
${data.description}
## Table of Contents
* [Installation](#installation)
* [Usage](#usage)
* [License](#license)
* [Contributing](#contributing)
* [Tests](#tests)
* [Questions](#questions)
## Installation
To install dependencies, run the following:
\`
${data.installation}
\`
## Usage
${data.usage}
## License
This repository is licensed under the ${data.license} license.
## Contributing
${data.contribute}
## Tests
To run tests, run the following:
\`
${data.tests}
\`
## Questions
Questions about this repository? Please contact me at [${data.email}](mailto:${data.email}). View more of my work in GitHub at [${data.username}](https://github.com/${data.username})
`;
} |
JavaScript | componentDidMount() {
API.getEmployees()
.then(response => {
let employeeData = response.data.results.map(emp => {
return {
id: emp.id.value,
image: emp.picture.medium,
firstName: emp.name.first,
lastName: emp.name.last,
email: emp.email,
phone: emp.phone
}
})
this.setState({
employees: employeeData,
loadedEmployees: employeeData
})
})
.catch(err => console.log(err));
} | componentDidMount() {
API.getEmployees()
.then(response => {
let employeeData = response.data.results.map(emp => {
return {
id: emp.id.value,
image: emp.picture.medium,
firstName: emp.name.first,
lastName: emp.name.last,
email: emp.email,
phone: emp.phone
}
})
this.setState({
employees: employeeData,
loadedEmployees: employeeData
})
})
.catch(err => console.log(err));
} |
JavaScript | init() {
this.listenTo(CartActions.AddToCart, this.onAddToCart);
this.listenTo(CartActions.RemoveFromCart, this.onRemoveFromCart);
this.listenTo(CartActions.ClearCart, this.onClearCart);
} | init() {
this.listenTo(CartActions.AddToCart, this.onAddToCart);
this.listenTo(CartActions.RemoveFromCart, this.onRemoveFromCart);
this.listenTo(CartActions.ClearCart, this.onClearCart);
} |
JavaScript | function useWindowDimensions() {
const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return windowDimensions;
} | function useWindowDimensions() {
const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return windowDimensions;
} |
JavaScript | function generateData() {
var dataArray = [];
for(var i = 0; i < users.length; i++) {
let objectItem = users[i];
let newObject = {
key: objectItem._id,
id: objectItem._id,
name: objectItem.name,
email: objectItem.email,
role: objectItem.role,
action_user_id: objectItem._id
};
dataArray.push(newObject);
}
return dataArray;
} | function generateData() {
var dataArray = [];
for(var i = 0; i < users.length; i++) {
let objectItem = users[i];
let newObject = {
key: objectItem._id,
id: objectItem._id,
name: objectItem.name,
email: objectItem.email,
role: objectItem.role,
action_user_id: objectItem._id
};
dataArray.push(newObject);
}
return dataArray;
} |
JavaScript | function addActiveLink () {
let navLinks = document.querySelectorAll('header .lg-navbar .nav-link'),
pageUrl = window.location.href,
activeLinks = [],
i;
for (i = 0; i < navLinks.length; i++) {
let linkHref = navLinks[i].getAttribute('href');
navLinks[i].classList.remove('active')
if ( pageUrl.includes(linkHref) ) {
activeLinks.push(navLinks[i]);
}
}
activeLinks[activeLinks.length - 1].classList.add('active');
} | function addActiveLink () {
let navLinks = document.querySelectorAll('header .lg-navbar .nav-link'),
pageUrl = window.location.href,
activeLinks = [],
i;
for (i = 0; i < navLinks.length; i++) {
let linkHref = navLinks[i].getAttribute('href');
navLinks[i].classList.remove('active')
if ( pageUrl.includes(linkHref) ) {
activeLinks.push(navLinks[i]);
}
}
activeLinks[activeLinks.length - 1].classList.add('active');
} |
JavaScript | function addActiveLink() {
var navLinks = document.querySelectorAll('header .lg-navbar .nav-link'),
pageUrl = window.location.href,
activeLinks = [],
i;
for (i = 0; i < navLinks.length; i++) {
var linkHref = navLinks[i].getAttribute('href');
navLinks[i].classList.remove('active');
if (pageUrl.includes(linkHref)) {
activeLinks.push(navLinks[i]);
}
}
activeLinks[activeLinks.length - 1].classList.add('active');
} | function addActiveLink() {
var navLinks = document.querySelectorAll('header .lg-navbar .nav-link'),
pageUrl = window.location.href,
activeLinks = [],
i;
for (i = 0; i < navLinks.length; i++) {
var linkHref = navLinks[i].getAttribute('href');
navLinks[i].classList.remove('active');
if (pageUrl.includes(linkHref)) {
activeLinks.push(navLinks[i]);
}
}
activeLinks[activeLinks.length - 1].classList.add('active');
} |
JavaScript | function initComments()
{
_c_ = new xhr.Comments;
_c_.setCommentsDiv();
if (_c_.divComments && _c_.isBrowserXmlHttpCapable()) {
_c_.interval = _c_.mininterval; // override default 60 second interval and set to 10 seconds
getComments(); // start recursive loop watching for new comments
} else if (_c_.divComments) {
_c_.divComments.className = "visible";
}
} | function initComments()
{
_c_ = new xhr.Comments;
_c_.setCommentsDiv();
if (_c_.divComments && _c_.isBrowserXmlHttpCapable()) {
_c_.interval = _c_.mininterval; // override default 60 second interval and set to 10 seconds
getComments(); // start recursive loop watching for new comments
} else if (_c_.divComments) {
_c_.divComments.className = "visible";
}
} |
JavaScript | createdCallback() {
if (!this.hasAttribute('_compiled')) {
this._compile();
} else {
this._scroll = this.getElementsByClassName('scrollbar')[0];
}
this._timeout = false;
this._limitReached = 0;
this.onInfiniteScrollLimit = 0.75;
this._boundOnDragStart = this._onDragStart.bind(this);
this._boundOnScroll = this._onScroll.bind(this);
this._boundOnResize = this._onResize.bind(this);
['height', 'draggable', 'autohide', 'autohide-delay', 'hidden', 'update-on-scroll'].forEach(e => {
this.attributeChangedCallback(e, null, this.getAttribute(e));
});
} | createdCallback() {
if (!this.hasAttribute('_compiled')) {
this._compile();
} else {
this._scroll = this.getElementsByClassName('scrollbar')[0];
}
this._timeout = false;
this._limitReached = 0;
this.onInfiniteScrollLimit = 0.75;
this._boundOnDragStart = this._onDragStart.bind(this);
this._boundOnScroll = this._onScroll.bind(this);
this._boundOnResize = this._onResize.bind(this);
['height', 'draggable', 'autohide', 'autohide-delay', 'hidden', 'update-on-scroll'].forEach(e => {
this.attributeChangedCallback(e, null, this.getAttribute(e));
});
} |
JavaScript | _registerToolbar(element) {
this._contentElement.setAttribute('no-status-bar-fill', '');
if (util.findChild(this, '.page__status-bar-fill')) {
this.insertBefore(element, this.children[1]);
} else {
this.insertBefore(element, this.children[0]);
}
} | _registerToolbar(element) {
this._contentElement.setAttribute('no-status-bar-fill', '');
if (util.findChild(this, '.page__status-bar-fill')) {
this.insertBefore(element, this.children[1]);
} else {
this.insertBefore(element, this.children[0]);
}
} |
JavaScript | _registerBottomToolbar(element) {
if (!util.findChild(this, '.page__status-bar-fill')) {
const fill = document.createElement('div');
fill.classList.add('page__bottom-bar-fill');
fill.style.width = '0px';
fill.style.height = '0px';
this.insertBefore(fill, this.children[0]);
this.insertBefore(element, null);
}
} | _registerBottomToolbar(element) {
if (!util.findChild(this, '.page__status-bar-fill')) {
const fill = document.createElement('div');
fill.classList.add('page__bottom-bar-fill');
fill.style.width = '0px';
fill.style.height = '0px';
this.insertBefore(fill, this.children[0]);
this.insertBefore(element, null);
}
} |
JavaScript | function OnInit(initData) {
// Basic information about the script.
initData.name = "Trim Movies";
initData.desc = "Creates trimmed versions of movie files by chopping the beginning of the data stream while preserving all the metadata of the original file.";
initData.copyright = "CC0 Public Domain by AndersonNNunes.org";
var version = "0.2";
initData.version = version;
initData.url = "https://github.com/andersonnnunes/TrimMovies";
initData.default_enable = true;
initData.min_version = "12.2.5"
// Create a new ScriptCommand object and initialize it to add the command to Opus.
var cmd = initData.AddCommand();
cmd.name = "TrimMovies";
cmd.method = "OnTrimMovies";
cmd.desc = initData.desc;
cmd.label = "Trim Movies";
cmd.template = "";
} | function OnInit(initData) {
// Basic information about the script.
initData.name = "Trim Movies";
initData.desc = "Creates trimmed versions of movie files by chopping the beginning of the data stream while preserving all the metadata of the original file.";
initData.copyright = "CC0 Public Domain by AndersonNNunes.org";
var version = "0.2";
initData.version = version;
initData.url = "https://github.com/andersonnnunes/TrimMovies";
initData.default_enable = true;
initData.min_version = "12.2.5"
// Create a new ScriptCommand object and initialize it to add the command to Opus.
var cmd = initData.AddCommand();
cmd.name = "TrimMovies";
cmd.method = "OnTrimMovies";
cmd.desc = initData.desc;
cmd.label = "Trim Movies";
cmd.template = "";
} |
JavaScript | function OnTrimMovies(scriptCmdData) {
// ------------------------------- Preferences
// Name of tag to apply to trimmed files.
// Must end with a semicolon.
// Set as empty string if no tag should be applied.
var tagForTrimmedFiles = "Trimmed To Favorite Scene";
// --------------------
// Text to append to the name of the output file.
var stringToAppendToTrimmedFiles = " - Trimmed";
// --------------------
// Name of file type group for movies.
// If you defined a personalized file type group for your movies, type it here.
var localizedMovieGroupTypeName = "Movies";
// --------------------
// Should the new file always overwrite the old?
// If so, set this variable to true. Else shift should be pressed when the button is clicked to activate overwrite.
var alwaysOverwrite = false;
// --------------------
// Determine verbosity level.
// 1 - Print informative log.
// 0 - Print nothing.
var verbose = 1;
// --------------------
// Should the script prevent the display of external windows?
// If so, set this variable to true.
var hideWindows = true;
// --------------------
// Enable development mode.
// During development, set this to true to make it easier to test this script.
var developmentMode = false;
// --------------------
// Clear output on run?
var clearOutput = false;
// --------------------
// ------------------------------- Main
if (clearOutput) {
DOpus.ClearOutput();
}
// Check that there are files selected.
if (scriptCmdData.func.sourcetab.selected_files.count == 0)
{
error("No files are selected.");
}
else
{
// Adjust command behavior.
var cmd = scriptCmdData.func.command;
cmd.deselect = false;
cmd.SetQualifiers("none");
cmd.ClearFiles;
// Filter selected files to consider only movie files.
for (var eSel = new Enumerator(scriptCmdData.func.sourcetab.selected_files); !eSel.atEnd(); eSel.moveNext())
{
var selectedItem = eSel.item();
for (var i=0; i<selectedItem.groups.length; i++){
if (selectedItem.groups(i).display_name == localizedMovieGroupTypeName)
{
cmd.AddFile(selectedItem);
}
}
}
// Ask for the start time.
if (developmentMode) {
var initTime = "00:00:01";
}
else {
var dialogObj = askTime();
if (!dialogObj.result) {
print("Operation aborted by the user.");
return;
}
else {
var initTime = dialogObj.input;
}
}
// Set window display mode.
var intWindowStyle = 1;
if (hideWindows) {
cmd.AddLine("@runmode:hide");
intWindowStyle = 0;
}
// Prepare objects.
var wsh = new ActiveXObject("WScript.Shell");
// For each movie file, define what to do.
for (var iSel = new Enumerator(cmd.files); !iSel.atEnd(); iSel.moveNext())
{
// Define paths.
var cItem = iSel.item()
var inputPath = "\"" + cItem + "\"";
var outputPath = inputPath.replace(cItem.ext, stringToAppendToTrimmedFiles + cItem.ext);
print("Input: " + inputPath);
print("Output: " + outputPath);
// Define how to produce the output file.
var trimCmdLine = "ffmpeg -xerror -hide_banner -y -ss " + initTime + " -i " + inputPath + " -threads 6 -map 0:v -map 0:a? -map 0:s? -map_metadata g -c:v copy -c:a copy -c:s copy " + outputPath;
print("Command sent to produce the file: " + trimCmdLine);
// Execute trim operation.
var runReturnCode = wsh.Run(trimCmdLine, intWindowStyle, true);
if (runReturnCode == 0) {
// -------------------- Copy metadata to the trimmed file.
// Define how to set the tags for the output file.
var tagString = tagForTrimmedFiles;
for (var tagEnum = new Enumerator(cItem.metadata.tags); !tagEnum.atEnd(); tagEnum.moveNext())
{
if (tagString != "") {
tagString += ";";
tagString += tagEnum.item();
}else {
tagString = tagEnum.item();
}
}
if (tagString != "") {
setTagCmdLine = "SetAttr " + outputPath + " META \"tags:" + tagString + "\"";
print("Command sent to set tags: " + setTagCmdLine);
cmd.AddLine(setTagCmdLine);
}
// Define how to set the labels for the output file.
var labelVector = cItem.labels;
if (!labelVector.empty) {
var labelString = "";
labelVector.sort();
for(var i=0; i<labelVector.count; i++)
{
labelString += labelVector(i);
if (i < (labelVector.count - 1)) {
labelString += ",";
}
}
setLabelCmdLine = "Properties " + outputPath + " SetLabel=" + labelString;
print("Command sent to set label: " + setLabelCmdLine);
cmd.AddLine(setLabelCmdLine);
}
// Define how to set the rating for the output file.
var ratingValue = cItem.metadata.other.rating;
if (ratingValue > 0) {
var setRatingCmdLine = "SetAttr " + outputPath + " META Rating:" + ratingValue;
print("Command sent to set the rating: " + setRatingCmdLine);
cmd.AddLine(setRatingCmdLine);
}
// Define how to set the movie specific metadata for the output file.
var setMovieMetatadaCmdLine = "SetAttr " + outputPath + " META \"copyfrom:9," + cItem + "\"";
print("Command sent to set the movie specific metadata: " + setMovieMetatadaCmdLine);
cmd.AddLine(setMovieMetatadaCmdLine);
// Define how to set the user comment for the output file.
var commentString = cItem.metadata.other.usercomment;
if (commentString)
{
var setCommentCmdLine = "SetAttr " + outputPath + " META \"Comment:" + commentString + "\"";
print("Command sent to set the user's comment: " + setCommentCmdLine);
cmd.AddLine(setCommentCmdLine);
}
// Define how to replace the original .
if (alwaysOverwrite || scriptCmdData.func.qualifiers == "shift") {
cmd.AddLine("Delete " + inputPath);
cmd.AddLine("Rename " + outputPath + " To " + inputPath);
}
// Execute commands.
cmd.Run;
// Clear commands.
cmd.Clear;
print("Success!");
} else {
error("FFmpeg was unable to trim the file.");
}
}
}
// Dialog used to request the time.
function askTime() {
var dlg = scriptCmdData.func.Dlg;
dlg.window = DOpus.Listers(0);
dlg.defvalue = "00:00:00";
dlg.message = "Input the initial seek time.";
dlg.title = "Seek Position";
dlg.max = 8;
var answer = dlg.Show;
return dlg;
}
// Print informative log only if requested.
function print(text) {
if (verbose) {
DOpus.Output(text);
}
}
// Display error message.
function error(text) {
DOpus.Output(text, true);
}
} | function OnTrimMovies(scriptCmdData) {
// ------------------------------- Preferences
// Name of tag to apply to trimmed files.
// Must end with a semicolon.
// Set as empty string if no tag should be applied.
var tagForTrimmedFiles = "Trimmed To Favorite Scene";
// --------------------
// Text to append to the name of the output file.
var stringToAppendToTrimmedFiles = " - Trimmed";
// --------------------
// Name of file type group for movies.
// If you defined a personalized file type group for your movies, type it here.
var localizedMovieGroupTypeName = "Movies";
// --------------------
// Should the new file always overwrite the old?
// If so, set this variable to true. Else shift should be pressed when the button is clicked to activate overwrite.
var alwaysOverwrite = false;
// --------------------
// Determine verbosity level.
// 1 - Print informative log.
// 0 - Print nothing.
var verbose = 1;
// --------------------
// Should the script prevent the display of external windows?
// If so, set this variable to true.
var hideWindows = true;
// --------------------
// Enable development mode.
// During development, set this to true to make it easier to test this script.
var developmentMode = false;
// --------------------
// Clear output on run?
var clearOutput = false;
// --------------------
// ------------------------------- Main
if (clearOutput) {
DOpus.ClearOutput();
}
// Check that there are files selected.
if (scriptCmdData.func.sourcetab.selected_files.count == 0)
{
error("No files are selected.");
}
else
{
// Adjust command behavior.
var cmd = scriptCmdData.func.command;
cmd.deselect = false;
cmd.SetQualifiers("none");
cmd.ClearFiles;
// Filter selected files to consider only movie files.
for (var eSel = new Enumerator(scriptCmdData.func.sourcetab.selected_files); !eSel.atEnd(); eSel.moveNext())
{
var selectedItem = eSel.item();
for (var i=0; i<selectedItem.groups.length; i++){
if (selectedItem.groups(i).display_name == localizedMovieGroupTypeName)
{
cmd.AddFile(selectedItem);
}
}
}
// Ask for the start time.
if (developmentMode) {
var initTime = "00:00:01";
}
else {
var dialogObj = askTime();
if (!dialogObj.result) {
print("Operation aborted by the user.");
return;
}
else {
var initTime = dialogObj.input;
}
}
// Set window display mode.
var intWindowStyle = 1;
if (hideWindows) {
cmd.AddLine("@runmode:hide");
intWindowStyle = 0;
}
// Prepare objects.
var wsh = new ActiveXObject("WScript.Shell");
// For each movie file, define what to do.
for (var iSel = new Enumerator(cmd.files); !iSel.atEnd(); iSel.moveNext())
{
// Define paths.
var cItem = iSel.item()
var inputPath = "\"" + cItem + "\"";
var outputPath = inputPath.replace(cItem.ext, stringToAppendToTrimmedFiles + cItem.ext);
print("Input: " + inputPath);
print("Output: " + outputPath);
// Define how to produce the output file.
var trimCmdLine = "ffmpeg -xerror -hide_banner -y -ss " + initTime + " -i " + inputPath + " -threads 6 -map 0:v -map 0:a? -map 0:s? -map_metadata g -c:v copy -c:a copy -c:s copy " + outputPath;
print("Command sent to produce the file: " + trimCmdLine);
// Execute trim operation.
var runReturnCode = wsh.Run(trimCmdLine, intWindowStyle, true);
if (runReturnCode == 0) {
// -------------------- Copy metadata to the trimmed file.
// Define how to set the tags for the output file.
var tagString = tagForTrimmedFiles;
for (var tagEnum = new Enumerator(cItem.metadata.tags); !tagEnum.atEnd(); tagEnum.moveNext())
{
if (tagString != "") {
tagString += ";";
tagString += tagEnum.item();
}else {
tagString = tagEnum.item();
}
}
if (tagString != "") {
setTagCmdLine = "SetAttr " + outputPath + " META \"tags:" + tagString + "\"";
print("Command sent to set tags: " + setTagCmdLine);
cmd.AddLine(setTagCmdLine);
}
// Define how to set the labels for the output file.
var labelVector = cItem.labels;
if (!labelVector.empty) {
var labelString = "";
labelVector.sort();
for(var i=0; i<labelVector.count; i++)
{
labelString += labelVector(i);
if (i < (labelVector.count - 1)) {
labelString += ",";
}
}
setLabelCmdLine = "Properties " + outputPath + " SetLabel=" + labelString;
print("Command sent to set label: " + setLabelCmdLine);
cmd.AddLine(setLabelCmdLine);
}
// Define how to set the rating for the output file.
var ratingValue = cItem.metadata.other.rating;
if (ratingValue > 0) {
var setRatingCmdLine = "SetAttr " + outputPath + " META Rating:" + ratingValue;
print("Command sent to set the rating: " + setRatingCmdLine);
cmd.AddLine(setRatingCmdLine);
}
// Define how to set the movie specific metadata for the output file.
var setMovieMetatadaCmdLine = "SetAttr " + outputPath + " META \"copyfrom:9," + cItem + "\"";
print("Command sent to set the movie specific metadata: " + setMovieMetatadaCmdLine);
cmd.AddLine(setMovieMetatadaCmdLine);
// Define how to set the user comment for the output file.
var commentString = cItem.metadata.other.usercomment;
if (commentString)
{
var setCommentCmdLine = "SetAttr " + outputPath + " META \"Comment:" + commentString + "\"";
print("Command sent to set the user's comment: " + setCommentCmdLine);
cmd.AddLine(setCommentCmdLine);
}
// Define how to replace the original .
if (alwaysOverwrite || scriptCmdData.func.qualifiers == "shift") {
cmd.AddLine("Delete " + inputPath);
cmd.AddLine("Rename " + outputPath + " To " + inputPath);
}
// Execute commands.
cmd.Run;
// Clear commands.
cmd.Clear;
print("Success!");
} else {
error("FFmpeg was unable to trim the file.");
}
}
}
// Dialog used to request the time.
function askTime() {
var dlg = scriptCmdData.func.Dlg;
dlg.window = DOpus.Listers(0);
dlg.defvalue = "00:00:00";
dlg.message = "Input the initial seek time.";
dlg.title = "Seek Position";
dlg.max = 8;
var answer = dlg.Show;
return dlg;
}
// Print informative log only if requested.
function print(text) {
if (verbose) {
DOpus.Output(text);
}
}
// Display error message.
function error(text) {
DOpus.Output(text, true);
}
} |
JavaScript | function askTime() {
var dlg = scriptCmdData.func.Dlg;
dlg.window = DOpus.Listers(0);
dlg.defvalue = "00:00:00";
dlg.message = "Input the initial seek time.";
dlg.title = "Seek Position";
dlg.max = 8;
var answer = dlg.Show;
return dlg;
} | function askTime() {
var dlg = scriptCmdData.func.Dlg;
dlg.window = DOpus.Listers(0);
dlg.defvalue = "00:00:00";
dlg.message = "Input the initial seek time.";
dlg.title = "Seek Position";
dlg.max = 8;
var answer = dlg.Show;
return dlg;
} |
JavaScript | function print(text) {
if (verbose) {
DOpus.Output(text);
}
} | function print(text) {
if (verbose) {
DOpus.Output(text);
}
} |
JavaScript | function loadAvailableSlotsBySelectedDate(param, url, formattedDate) {
var cardSlots = document.getElementById("time_slot_cards");
// Remove the time slot
cardSlots.classList.remove('slot_selection_show');
// The calendar was just cleared...
if (param.value == null) {
// Exit the method
return;
}
$.ajax({
url: url,
method: 'post',
data: {
date: formattedDate
},
dataType: 'json',
error: function (res) {
// TODO: Find a more proper way to log error
// Alert error
alert("An error occurred. Please try again.");
// Exit the method
return;
},
success: function(response) {
// Display the time slot
cardSlots.classList.add('slot_selection_show');
// Get the slot indices
var slotIndex1 = $( "label[slot-index='0']" );
var slotIndex2 = $( "label[slot-index='1']" );
var slotIndex3 = $( "label[slot-index='2']" );
var slotIndex4 = $( "label[slot-index='3']" );
var slotIndex5 = $( "label[slot-index='4']" );
var slotIndex6 = $( "label[slot-index='5']" );
var slotIndexValue1 = slotIndex1.attr("slot-index");
var slotIndexValue2 = slotIndex2.attr("slot-index");
var slotIndexValue3 = slotIndex3.attr("slot-index");
var slotIndexValue4 = slotIndex4.attr("slot-index");
var slotIndexValue5 = slotIndex5.attr("slot-index");
var slotIndexValue6 = slotIndex6.attr("slot-index");
// Verify slot indices
// Slot 1
if (!slotIsAvailable(slotIndexValue1, response.availableSlots)) {
slotIndex1.attr("aria-disabled", true);
slotIndex1.attr("class", "ms-RadioButton-field is-disabled custom-radio");
}
else {
slotIndex1.attr("aria-disabled", false);
slotIndex1.attr("class", "ms-RadioButton-field custom-radio");
}
// Slot 2
if (!slotIsAvailable(slotIndexValue2, response.availableSlots)) {
slotIndex2.attr("aria-disabled", true);
slotIndex2.attr("class", "ms-RadioButton-field is-disabled custom-radio");
}
else {
slotIndex2.attr("aria-disabled", false);
slotIndex2.attr("class", "ms-RadioButton-field custom-radio");
}
// Slot 3
if (!slotIsAvailable(slotIndexValue3, response.availableSlots)) {
slotIndex3.attr("aria-disabled", true);
slotIndex3.attr("class", "ms-RadioButton-field is-disabled custom-radio");
}
else {
slotIndex3.attr("aria-disabled", false);
slotIndex3.attr("class", "ms-RadioButton-field custom-radio");
}
// Slot 4
if (!slotIsAvailable(slotIndexValue4, response.availableSlots)) {
slotIndex4.attr("aria-disabled", true);
slotIndex4.attr("class", "ms-RadioButton-field is-disabled custom-radio");
}
else {
slotIndex4.attr("aria-disabled", false);
slotIndex4.attr("class", "ms-RadioButton-field custom-radio");
}
// Slot 5
if (!slotIsAvailable(slotIndexValue5, response.availableSlots)) {
slotIndex5.attr("aria-disabled", true);
slotIndex5.attr("class", "ms-RadioButton-field is-disabled custom-radio");
}
else {
slotIndex5.attr("aria-disabled", false);
slotIndex5.attr("class", "ms-RadioButton-field custom-radio");
}
// Slot 6
if (!slotIsAvailable(slotIndexValue6, response.availableSlots)) {
slotIndex6.attr("aria-disabled", true);
slotIndex6.attr("class", "ms-RadioButton-field is-disabled custom-radio");
}
else {
slotIndex6.attr("aria-disabled", false);
slotIndex6.attr("class", "ms-RadioButton-field custom-radio");
}
}
});
} | function loadAvailableSlotsBySelectedDate(param, url, formattedDate) {
var cardSlots = document.getElementById("time_slot_cards");
// Remove the time slot
cardSlots.classList.remove('slot_selection_show');
// The calendar was just cleared...
if (param.value == null) {
// Exit the method
return;
}
$.ajax({
url: url,
method: 'post',
data: {
date: formattedDate
},
dataType: 'json',
error: function (res) {
// TODO: Find a more proper way to log error
// Alert error
alert("An error occurred. Please try again.");
// Exit the method
return;
},
success: function(response) {
// Display the time slot
cardSlots.classList.add('slot_selection_show');
// Get the slot indices
var slotIndex1 = $( "label[slot-index='0']" );
var slotIndex2 = $( "label[slot-index='1']" );
var slotIndex3 = $( "label[slot-index='2']" );
var slotIndex4 = $( "label[slot-index='3']" );
var slotIndex5 = $( "label[slot-index='4']" );
var slotIndex6 = $( "label[slot-index='5']" );
var slotIndexValue1 = slotIndex1.attr("slot-index");
var slotIndexValue2 = slotIndex2.attr("slot-index");
var slotIndexValue3 = slotIndex3.attr("slot-index");
var slotIndexValue4 = slotIndex4.attr("slot-index");
var slotIndexValue5 = slotIndex5.attr("slot-index");
var slotIndexValue6 = slotIndex6.attr("slot-index");
// Verify slot indices
// Slot 1
if (!slotIsAvailable(slotIndexValue1, response.availableSlots)) {
slotIndex1.attr("aria-disabled", true);
slotIndex1.attr("class", "ms-RadioButton-field is-disabled custom-radio");
}
else {
slotIndex1.attr("aria-disabled", false);
slotIndex1.attr("class", "ms-RadioButton-field custom-radio");
}
// Slot 2
if (!slotIsAvailable(slotIndexValue2, response.availableSlots)) {
slotIndex2.attr("aria-disabled", true);
slotIndex2.attr("class", "ms-RadioButton-field is-disabled custom-radio");
}
else {
slotIndex2.attr("aria-disabled", false);
slotIndex2.attr("class", "ms-RadioButton-field custom-radio");
}
// Slot 3
if (!slotIsAvailable(slotIndexValue3, response.availableSlots)) {
slotIndex3.attr("aria-disabled", true);
slotIndex3.attr("class", "ms-RadioButton-field is-disabled custom-radio");
}
else {
slotIndex3.attr("aria-disabled", false);
slotIndex3.attr("class", "ms-RadioButton-field custom-radio");
}
// Slot 4
if (!slotIsAvailable(slotIndexValue4, response.availableSlots)) {
slotIndex4.attr("aria-disabled", true);
slotIndex4.attr("class", "ms-RadioButton-field is-disabled custom-radio");
}
else {
slotIndex4.attr("aria-disabled", false);
slotIndex4.attr("class", "ms-RadioButton-field custom-radio");
}
// Slot 5
if (!slotIsAvailable(slotIndexValue5, response.availableSlots)) {
slotIndex5.attr("aria-disabled", true);
slotIndex5.attr("class", "ms-RadioButton-field is-disabled custom-radio");
}
else {
slotIndex5.attr("aria-disabled", false);
slotIndex5.attr("class", "ms-RadioButton-field custom-radio");
}
// Slot 6
if (!slotIsAvailable(slotIndexValue6, response.availableSlots)) {
slotIndex6.attr("aria-disabled", true);
slotIndex6.attr("class", "ms-RadioButton-field is-disabled custom-radio");
}
else {
slotIndex6.attr("aria-disabled", false);
slotIndex6.attr("class", "ms-RadioButton-field custom-radio");
}
}
});
} |
JavaScript | function findFacilities(buffer, layer, centerPoint) {
const query = layer.createQuery();
query.returnGeometry = true;
// query.distance = radius;
// query.units = distanceUnits;
query.outFields = ["*"];
query.geometry = buffer;
layer.queryFeatures(query).then((results) => {
if (results.features.length) {
displayLocations(results.features, centerPoint);
populateCards(results.features, centerPoint);
} else {
// clear the panel
const cardList = document.getElementById("cardsList");
const panelDiv = document.getElementById("panelTitle");
panelDiv.innerHTML = `Sorry no hospitals founds within ${radius} ${distanceUnits}.`;
cardList.innerHTML = "";
console.log("no results returned from query");
// clear the graphics
facilityGraphicsLayer.removeAll();
}
});
} | function findFacilities(buffer, layer, centerPoint) {
const query = layer.createQuery();
query.returnGeometry = true;
// query.distance = radius;
// query.units = distanceUnits;
query.outFields = ["*"];
query.geometry = buffer;
layer.queryFeatures(query).then((results) => {
if (results.features.length) {
displayLocations(results.features, centerPoint);
populateCards(results.features, centerPoint);
} else {
// clear the panel
const cardList = document.getElementById("cardsList");
const panelDiv = document.getElementById("panelTitle");
panelDiv.innerHTML = `Sorry no hospitals founds within ${radius} ${distanceUnits}.`;
cardList.innerHTML = "";
console.log("no results returned from query");
// clear the graphics
facilityGraphicsLayer.removeAll();
}
});
} |
JavaScript | function radiusFilter() {
modalDiv.className = "js-modal modal-overlay";
const selectDistance = document.getElementById("distanceSelect").value;
const selectUnits = document.getElementById("unitsSelect").value;
radius = selectDistance;
distanceUnits = selectUnits;
// clear to begin a new search
if (view.graphics) {
view.graphics.removeAll();
facilityGraphicsLayer.removeAll();
// set the new graphics with new radius
addPointToMap(currentPointLocation);
// create the buffer to display and for the query
const buffer = addBuffer(currentPointLocation);
findFacilities(buffer, facilitiesLayer, currentPointLocation);
}
} | function radiusFilter() {
modalDiv.className = "js-modal modal-overlay";
const selectDistance = document.getElementById("distanceSelect").value;
const selectUnits = document.getElementById("unitsSelect").value;
radius = selectDistance;
distanceUnits = selectUnits;
// clear to begin a new search
if (view.graphics) {
view.graphics.removeAll();
facilityGraphicsLayer.removeAll();
// set the new graphics with new radius
addPointToMap(currentPointLocation);
// create the buffer to display and for the query
const buffer = addBuffer(currentPointLocation);
findFacilities(buffer, facilitiesLayer, currentPointLocation);
}
} |
JavaScript | async canAppend (entry, identityProvider) {
try {
console.log('canAppend entry: ', entry)
let validTx = false
const txid = entry.payload.key
const mongoRes = await this.KeyValue.find({ key: txid })
if (mongoRes.length > 0) {
console.log('mongoRes: ', mongoRes)
const mongoKey = mongoRes[0].key
if (mongoKey === txid) {
// Entry is already in the database.
return true
}
}
// TODO: Validate the signature of the address used for the input to the tx.
// validSignature = await this._validateSignature(txid, signature)
// Note: Don't need an address, as you can use the address from the
// second output of the TX. That's the first reciever of the SLP TX.
// That allows this function to use a simple call to the full node, and
// does not require SLP-hydrated UTXOs.
// Validate the transaction matches the burning rules.
validTx = await this._validateTx(txid)
return validTx
} catch (err) {
console.log(
'Error in pay-to-write-access-controller.js/canAppend(). Returning false. Error: \n',
err
)
return false
}
} | async canAppend (entry, identityProvider) {
try {
console.log('canAppend entry: ', entry)
let validTx = false
const txid = entry.payload.key
const mongoRes = await this.KeyValue.find({ key: txid })
if (mongoRes.length > 0) {
console.log('mongoRes: ', mongoRes)
const mongoKey = mongoRes[0].key
if (mongoKey === txid) {
// Entry is already in the database.
return true
}
}
// TODO: Validate the signature of the address used for the input to the tx.
// validSignature = await this._validateSignature(txid, signature)
// Note: Don't need an address, as you can use the address from the
// second output of the TX. That's the first reciever of the SLP TX.
// That allows this function to use a simple call to the full node, and
// does not require SLP-hydrated UTXOs.
// Validate the transaction matches the burning rules.
validTx = await this._validateTx(txid)
return validTx
} catch (err) {
console.log(
'Error in pay-to-write-access-controller.js/canAppend(). Returning false. Error: \n',
err
)
return false
}
} |
JavaScript | async _validateTx (txid) {
try {
let isValid = false
const txInfo = await _this.bchjs.Transaction.get(txid)
console.log(`txInfo: ${JSON.stringify(txInfo, null, 2)}`)
// Return false if txid is not a valid SLP tx.
if (!txInfo.isValidSLPTx) return false
// Return false if tokenId does not match.
if (txInfo.tokenId !== TOKENID) return false
// Sum up all the token inputs
let inputTokenQty = 0
for (let i = 0; i < txInfo.vin.length; i++) {
let tokenQty = 0
if (!txInfo.vin[i].tokenQty) {
tokenQty = 0
} else {
tokenQty = Number(txInfo.vin[i].tokenQty)
}
inputTokenQty += tokenQty
}
console.log(`inputTokenQty: ${inputTokenQty}`)
// Sum up all the token outputs
let outputTokenQty = 0
for (let i = 0; i < txInfo.vout.length; i++) {
let tokenQty = 0
if (!txInfo.vout[i].tokenQty) {
tokenQty = 0
} else {
tokenQty = Number(txInfo.vout[i].tokenQty)
}
outputTokenQty += tokenQty
}
console.log(`outputTokenQty: ${outputTokenQty}`)
const diff = inputTokenQty - outputTokenQty
console.log(`difference: ${diff}`)
// If the difference is above a positive threshold, then it's a burn
// transaction.
if (diff > 0.001) {
console.log(
`TX ${txid} proved burn of tokens. Will be allowed to write to DB.`
)
isValid = true
}
return isValid
} catch (err) {
console.error('Error in _valideTx: ', err)
return false
}
} | async _validateTx (txid) {
try {
let isValid = false
const txInfo = await _this.bchjs.Transaction.get(txid)
console.log(`txInfo: ${JSON.stringify(txInfo, null, 2)}`)
// Return false if txid is not a valid SLP tx.
if (!txInfo.isValidSLPTx) return false
// Return false if tokenId does not match.
if (txInfo.tokenId !== TOKENID) return false
// Sum up all the token inputs
let inputTokenQty = 0
for (let i = 0; i < txInfo.vin.length; i++) {
let tokenQty = 0
if (!txInfo.vin[i].tokenQty) {
tokenQty = 0
} else {
tokenQty = Number(txInfo.vin[i].tokenQty)
}
inputTokenQty += tokenQty
}
console.log(`inputTokenQty: ${inputTokenQty}`)
// Sum up all the token outputs
let outputTokenQty = 0
for (let i = 0; i < txInfo.vout.length; i++) {
let tokenQty = 0
if (!txInfo.vout[i].tokenQty) {
tokenQty = 0
} else {
tokenQty = Number(txInfo.vout[i].tokenQty)
}
outputTokenQty += tokenQty
}
console.log(`outputTokenQty: ${outputTokenQty}`)
const diff = inputTokenQty - outputTokenQty
console.log(`difference: ${diff}`)
// If the difference is above a positive threshold, then it's a burn
// transaction.
if (diff > 0.001) {
console.log(
`TX ${txid} proved burn of tokens. Will be allowed to write to DB.`
)
isValid = true
}
return isValid
} catch (err) {
console.error('Error in _valideTx: ', err)
return false
}
} |
JavaScript | function rgb2hex(rgb) {
rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
return (rgb && rgb.length === 4) ? "#" +
("0" + parseInt(rgb[1], 10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2], 10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3], 10).toString(16)).slice(-2) : '';
} | function rgb2hex(rgb) {
rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
return (rgb && rgb.length === 4) ? "#" +
("0" + parseInt(rgb[1], 10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2], 10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3], 10).toString(16)).slice(-2) : '';
} |
JavaScript | function makeGrid(height, width) {
for(let i = 0; i < height; i++) {
let row = document.createElement('tr');
row.className = 'row';
for(let j = 0; j < width; j++) {
let column = document.createElement('td');
row.appendChild(column);
}
table.appendChild(row);
}
const td = document.querySelectorAll('#pixelCanvas td');
td.forEach(function(elem) {
elem.addEventListener("click", function() {
this.style.backgroundColor = getColorValue();
});
});
} | function makeGrid(height, width) {
for(let i = 0; i < height; i++) {
let row = document.createElement('tr');
row.className = 'row';
for(let j = 0; j < width; j++) {
let column = document.createElement('td');
row.appendChild(column);
}
table.appendChild(row);
}
const td = document.querySelectorAll('#pixelCanvas td');
td.forEach(function(elem) {
elem.addEventListener("click", function() {
this.style.backgroundColor = getColorValue();
});
});
} |
JavaScript | function clearGrid() {
while (table.firstChild) {
table.removeChild(table.firstChild);
}
} | function clearGrid() {
while (table.firstChild) {
table.removeChild(table.firstChild);
}
} |
JavaScript | function makeGrid(height, width) {
for(var i = 0; i < height; i++) {
var tableRow = $("<tr class='row'></tr>");
for(var j = 0; j < width; j++) {
tableRow.append("<td class='column'></td>");
}
pixelCanvas.append(tableRow);
}
} | function makeGrid(height, width) {
for(var i = 0; i < height; i++) {
var tableRow = $("<tr class='row'></tr>");
for(var j = 0; j < width; j++) {
tableRow.append("<td class='column'></td>");
}
pixelCanvas.append(tableRow);
}
} |
JavaScript | function _setPatternBgImg(image) {
var imagePath = $(image).attr('xlink:href');
$(SELECTORS.pattern).css('background-image', 'url(' + imagePath + ')');
} | function _setPatternBgImg(image) {
var imagePath = $(image).attr('xlink:href');
$(SELECTORS.pattern).css('background-image', 'url(' + imagePath + ')');
} |
JavaScript | function isBigger(array,position) {
var arrayLength = array.length;
if(arrayLength < position)
return false;
else{
var number = array[position];
var leftNumber = array[position-1] ;
var rightNumber = array[position+1];
if(leftNumber != null && rightNumber != null){
if(number > leftNumber && number > rightNumber)
return true;
else
return false;
}
else
return false;
}
} | function isBigger(array,position) {
var arrayLength = array.length;
if(arrayLength < position)
return false;
else{
var number = array[position];
var leftNumber = array[position-1] ;
var rightNumber = array[position+1];
if(leftNumber != null && rightNumber != null){
if(number > leftNumber && number > rightNumber)
return true;
else
return false;
}
else
return false;
}
} |
JavaScript | function checkBrackets(string){
var count = 0;
for(var i in string){
if(string[i] == '('){
count ++;
} else if(string[i] == ')') {
count --;
}
if (count < 0)
return false;
}
if(count > 0) return false;
return true;
} | function checkBrackets(string){
var count = 0;
for(var i in string){
if(string[i] == '('){
count ++;
} else if(string[i] == ')') {
count --;
}
if (count < 0)
return false;
}
if(count > 0) return false;
return true;
} |
JavaScript | register(html) {
if (html && typeof html === 'string') {
try {
const manifest = generateManifest(html);
this.graph[manifest.appName] = manifest;
} catch (e) {
throw new Error(e);
}
} else {
throw new Error('mfhml.register requires an html');
}
} | register(html) {
if (html && typeof html === 'string') {
try {
const manifest = generateManifest(html);
this.graph[manifest.appName] = manifest;
} catch (e) {
throw new Error(e);
}
} else {
throw new Error('mfhml.register requires an html');
}
} |
JavaScript | async register() {
const {
ctx: { credentials, uuid }
} = this;
return this.authClient.post("/doregister", {
body: {
signature: sign.payload(uuid),
...defaults.login,
nextAction: "0",
type: "1",
account: credentials.username,
password: credentials.password
}
});
} | async register() {
const {
ctx: { credentials, uuid }
} = this;
return this.authClient.post("/doregister", {
body: {
signature: sign.payload(uuid),
...defaults.login,
nextAction: "0",
type: "1",
account: credentials.username,
password: credentials.password
}
});
} |
JavaScript | function engine(opts){
var me = this;
var viewableCounterStart = 0;
/**
* Internal object to hold event listeners
*/
var eventListeners = {
viewabilityReached: []
}
/**
* Parameters required for viewability
*/
this.viewableParams = {
seconds: VIEWABLE_SEC,
percent: VIEWABLE_PERCENT,
requireFocus: VIEWABLE_MUST_FOCUS
}
function trigger(eventName, params){
var i, fn,
el = eventListeners,
list = el[eventName];
if(list == null || list.length == 0){
return;
}
for(i=0;i<list.length;i++){
fn = list[i];
if(isfunc(fn)){
try{
fn(params);
}
catch(ex){
console.error('[ovvtest ViewEngine] ' + ex.message, ex);
}
}
}
}
/**
* Tests to see if the data params state that the ad is in view
*/
function eventInView(data){
var vp = me.viewableParams;
var pctVal, inFocus = true;
if(!data){
return false;
}
pctVal = data.percentViewable || 0;
if(data.focus === false){
inFocus = false;
}
else{
inFocus = true;
}
if(pctVal >= vp.percent){
if(inFocus || vp.requireFocus == false){
return true;
}
}
return false;
}
function testViewabilityLimits(ticks){
var vp = me.viewableParams;
var tm = me.tickMeasure;
var ms;
var limMs = vp.seconds * 1000;
if(tm.viewableMsSum == 0){
return false;
}
if(tm.viewableMsSum >= (limMs)){
return true;
}
}
this.viewabilityReached = false;
this.previouslyInView = false;
this.currentViewTickStart
this.startTicks = 0;
this.ovvTime = {
start: 0,
end: 0
}
this.tickMeasure = {
currentViewTickStart : 0,
lastMeasureTicks: 0,
viewableMsSum: 0
}
this.addEventListener = function(eventName, func){
if(!isfunc(func)){
return;
}
if(eventListeners[eventName] == null){
eventListeners[eventName] = [];
}
eventListeners[eventName].push(func);
}
/**
* Process the OVV event and calculate how it affects the state of the view engine
*/
this.processEvent = function(eventName, ovvtime, data){
var inView;
var ticks = Date.now();
var isStart = false;
var viewResult, ltm = me.tickMeasure.lastMeasureTicks;
if(me.startTicks == 0){
isStart = true;
me.startTicks = ticks;
}
if(this.ovvTime.start === 0){
this.ovvTime.start = ovvtime;
}
inView = eventInView(data);
if(inView == true){
if(!me.previouslyInView){
me.previouslyInView = true;
me.tickMeasure.currentViewTickStart = ticks;
}
else{
if(ltm > 0){
me.tickMeasure.viewableMsSum += (ticks - ltm);
}
}
// look for our thresholds
if(!me.viewabilityReached){
viewResult = testViewabilityLimits(ticks);
if(viewResult){
me.viewabilityReached = true;
trigger('viewabilityReached', { viewabilityReached: true, viewTime: me.tickMeasure.viewableMsSum});
}
}
me.tickMeasure.lastMeasureTicks = ticks;
}
else{
if(me.previouslyInView){
me.previouslyInView = false;
me.tickMeasure.currentViewTickStart = 0;
if(ltm > 0){
me.tickMeasure.viewableMsSum += (ticks - ltm);
}
}
}
}
} | function engine(opts){
var me = this;
var viewableCounterStart = 0;
/**
* Internal object to hold event listeners
*/
var eventListeners = {
viewabilityReached: []
}
/**
* Parameters required for viewability
*/
this.viewableParams = {
seconds: VIEWABLE_SEC,
percent: VIEWABLE_PERCENT,
requireFocus: VIEWABLE_MUST_FOCUS
}
function trigger(eventName, params){
var i, fn,
el = eventListeners,
list = el[eventName];
if(list == null || list.length == 0){
return;
}
for(i=0;i<list.length;i++){
fn = list[i];
if(isfunc(fn)){
try{
fn(params);
}
catch(ex){
console.error('[ovvtest ViewEngine] ' + ex.message, ex);
}
}
}
}
/**
* Tests to see if the data params state that the ad is in view
*/
function eventInView(data){
var vp = me.viewableParams;
var pctVal, inFocus = true;
if(!data){
return false;
}
pctVal = data.percentViewable || 0;
if(data.focus === false){
inFocus = false;
}
else{
inFocus = true;
}
if(pctVal >= vp.percent){
if(inFocus || vp.requireFocus == false){
return true;
}
}
return false;
}
function testViewabilityLimits(ticks){
var vp = me.viewableParams;
var tm = me.tickMeasure;
var ms;
var limMs = vp.seconds * 1000;
if(tm.viewableMsSum == 0){
return false;
}
if(tm.viewableMsSum >= (limMs)){
return true;
}
}
this.viewabilityReached = false;
this.previouslyInView = false;
this.currentViewTickStart
this.startTicks = 0;
this.ovvTime = {
start: 0,
end: 0
}
this.tickMeasure = {
currentViewTickStart : 0,
lastMeasureTicks: 0,
viewableMsSum: 0
}
this.addEventListener = function(eventName, func){
if(!isfunc(func)){
return;
}
if(eventListeners[eventName] == null){
eventListeners[eventName] = [];
}
eventListeners[eventName].push(func);
}
/**
* Process the OVV event and calculate how it affects the state of the view engine
*/
this.processEvent = function(eventName, ovvtime, data){
var inView;
var ticks = Date.now();
var isStart = false;
var viewResult, ltm = me.tickMeasure.lastMeasureTicks;
if(me.startTicks == 0){
isStart = true;
me.startTicks = ticks;
}
if(this.ovvTime.start === 0){
this.ovvTime.start = ovvtime;
}
inView = eventInView(data);
if(inView == true){
if(!me.previouslyInView){
me.previouslyInView = true;
me.tickMeasure.currentViewTickStart = ticks;
}
else{
if(ltm > 0){
me.tickMeasure.viewableMsSum += (ticks - ltm);
}
}
// look for our thresholds
if(!me.viewabilityReached){
viewResult = testViewabilityLimits(ticks);
if(viewResult){
me.viewabilityReached = true;
trigger('viewabilityReached', { viewabilityReached: true, viewTime: me.tickMeasure.viewableMsSum});
}
}
me.tickMeasure.lastMeasureTicks = ticks;
}
else{
if(me.previouslyInView){
me.previouslyInView = false;
me.tickMeasure.currentViewTickStart = 0;
if(ltm > 0){
me.tickMeasure.viewableMsSum += (ticks - ltm);
}
}
}
}
} |
JavaScript | function eventInView(data){
var vp = me.viewableParams;
var pctVal, inFocus = true;
if(!data){
return false;
}
pctVal = data.percentViewable || 0;
if(data.focus === false){
inFocus = false;
}
else{
inFocus = true;
}
if(pctVal >= vp.percent){
if(inFocus || vp.requireFocus == false){
return true;
}
}
return false;
} | function eventInView(data){
var vp = me.viewableParams;
var pctVal, inFocus = true;
if(!data){
return false;
}
pctVal = data.percentViewable || 0;
if(data.focus === false){
inFocus = false;
}
else{
inFocus = true;
}
if(pctVal >= vp.percent){
if(inFocus || vp.requireFocus == false){
return true;
}
}
return false;
} |
JavaScript | function displayViewableData(data){
var el = opts.valuesOutputElem;
var id, arr;
var k, val, i;
if(el == null){
return;
}
if(data == null){
return;
}
// check for empty object
var keyCount = 0;
if(typeof(data) === 'object'){
for(k in data){
if(data.hasOwnProperty(k)){
keyCount++;
if(keyCount > 10){
break;
}
}
}
}
if(keyCount == 0){
impl.log('[ovvtest] - No data to show');
return;
}
else if(keyCount == 2){
if(data['ovvData'] == null){
impl.log('[ovvtest] - No data to show');
return;
}
}
if(typeof(el) === 'string'){
id = el;
el = doc.getElementById(id);
if(el == null){
el = doc.querySelector(id);
}
_displayViewableDataImpl(data, el);
}
else if(isArray(el)){
arr = el;
for(i=0;i<arr.length;i++){
el = arr[i];
_displayViewableDataImpl(data, el);
}
}
} | function displayViewableData(data){
var el = opts.valuesOutputElem;
var id, arr;
var k, val, i;
if(el == null){
return;
}
if(data == null){
return;
}
// check for empty object
var keyCount = 0;
if(typeof(data) === 'object'){
for(k in data){
if(data.hasOwnProperty(k)){
keyCount++;
if(keyCount > 10){
break;
}
}
}
}
if(keyCount == 0){
impl.log('[ovvtest] - No data to show');
return;
}
else if(keyCount == 2){
if(data['ovvData'] == null){
impl.log('[ovvtest] - No data to show');
return;
}
}
if(typeof(el) === 'string'){
id = el;
el = doc.getElementById(id);
if(el == null){
el = doc.querySelector(id);
}
_displayViewableDataImpl(data, el);
}
else if(isArray(el)){
arr = el;
for(i=0;i<arr.length;i++){
el = arr[i];
_displayViewableDataImpl(data, el);
}
}
} |
JavaScript | function _displayViewableDataImpl(data, el){
var id;
var k, val, i;
if(el == null){
return;
}
if(typeof(el) === 'string'){
id = el;
el = doc.getElementById(id);
if(el == null){
el = doc.querySelector(id);
}
_displayViewableDataImpl(data, el);
}
for(i=0;i<valOutput.length;i++){
showData(data, valOutput[i], el);
}
} | function _displayViewableDataImpl(data, el){
var id;
var k, val, i;
if(el == null){
return;
}
if(typeof(el) === 'string'){
id = el;
el = doc.getElementById(id);
if(el == null){
el = doc.querySelector(id);
}
_displayViewableDataImpl(data, el);
}
for(i=0;i<valOutput.length;i++){
showData(data, valOutput[i], el);
}
} |
JavaScript | function buildInfoWindow(elemOrId, options){
var el;
var ibox = infoBox;
var options = options || {};
var i, k, d;
var sumbuf = [], detbuf = [];
var twin, tdoc;
var regTopWindow = false;
if(options.infoBox != null){
ibox = mixin(infoBox, options.infoBox);
}
var html = ibox.viewabilityInfoMarkup;
var line, tp = ibox.lineMarkup;
var id;
for(i=0;i<ibox.detailDef.length;i++){
d = ibox.detailDef[i];
line = tp.replace('##label##', d.label).replace('##ovv##', d.ovv);
detbuf.push(line);
}
for(i=0;i<ibox.summaryDef.length;i++){
d = ibox.summaryDef[i];
line = tp.replace('##label##', d.label).replace('##ovv##', d.ovv);
sumbuf.push(line);
}
html = html.replace('###DETAILS###', detbuf.join(''));
html = html.replace('###SUMMARY###', sumbuf.join(''));
if(opts.valuesOutputElem == null){
opts.valuesOutputElem = [];
}
if(options.topFrame && !ovvtest.isTopFrame()){
twin = window.top;
tdoc = twin.document;
el = util.getEl(elemOrId, tdoc);
regTopWindow = true;
id = el.getAttribute('id');
opts.valuesOutputElem.push(el);
}
else{
el = util.getEl(elemOrId);
id = el.getAttribute('id');
if(id != null){
opts.valuesOutputElem.push(id);
}
else{
opts.valuesOutputElem.push(el);
}
}
el.innerHTML = html;
var closeBtn = el.querySelector('button.close');
if(closeBtn != null){
closeBtn.addEventListener('click', function(evt){
var box = document.getElementById('ovvParamValues');
box.style.display = 'none';
});
}
} | function buildInfoWindow(elemOrId, options){
var el;
var ibox = infoBox;
var options = options || {};
var i, k, d;
var sumbuf = [], detbuf = [];
var twin, tdoc;
var regTopWindow = false;
if(options.infoBox != null){
ibox = mixin(infoBox, options.infoBox);
}
var html = ibox.viewabilityInfoMarkup;
var line, tp = ibox.lineMarkup;
var id;
for(i=0;i<ibox.detailDef.length;i++){
d = ibox.detailDef[i];
line = tp.replace('##label##', d.label).replace('##ovv##', d.ovv);
detbuf.push(line);
}
for(i=0;i<ibox.summaryDef.length;i++){
d = ibox.summaryDef[i];
line = tp.replace('##label##', d.label).replace('##ovv##', d.ovv);
sumbuf.push(line);
}
html = html.replace('###DETAILS###', detbuf.join(''));
html = html.replace('###SUMMARY###', sumbuf.join(''));
if(opts.valuesOutputElem == null){
opts.valuesOutputElem = [];
}
if(options.topFrame && !ovvtest.isTopFrame()){
twin = window.top;
tdoc = twin.document;
el = util.getEl(elemOrId, tdoc);
regTopWindow = true;
id = el.getAttribute('id');
opts.valuesOutputElem.push(el);
}
else{
el = util.getEl(elemOrId);
id = el.getAttribute('id');
if(id != null){
opts.valuesOutputElem.push(id);
}
else{
opts.valuesOutputElem.push(el);
}
}
el.innerHTML = html;
var closeBtn = el.querySelector('button.close');
if(closeBtn != null){
closeBtn.addEventListener('click', function(evt){
var box = document.getElementById('ovvParamValues');
box.style.display = 'none';
});
}
} |
JavaScript | function registerOvvListeners(ad_id){
var ovv;
var ad_id = ad_id || opts.adId;
if(regTimer !== 0){
clearTimeout(regTimer);
regTimer = 0;
}
if(!window['$ovv']){
if(++attachRetries < 60000){
regTimer = setTimeout(function(){
registerOvvListeners();
}, 300);
}
return;
}
var eventNames = [
'AdLoaded', 'AdImpression', 'AdPlaying', 'AdPaused', 'AdVolumeChange',
'AdVideoStart', 'AdVideoFirstQuartile', 'AdVideoMidpoint', 'AdVideoThirdQuartile',
'AdVideoComplete'
];
// list of OVV events. We must listen to OVVLog in order to get up to date viewability information
var ovvEvents = ['OVVReady', 'OVVImpression', 'OVVImpressionUnmeasurable', 'OVVLog'];
ovv = window['$ovv'];
ovv.subscribe(ovvEvents, ad_id, function(id, eventData){
if(eventData.ovvArgs != null){
handleOvvEvent(eventData, eventData.ovvArgs);
}
}, true);
ovv.subscribe(eventNames, ad_id, function(id, eventData){
if(eventData.ovvArgs != null){
handleVpaidEvent(eventData, eventData.ovvArgs);
}
}, true);
// Error handles
ovv.subscribe(['AdError', 'OVVError'], ad_id, function(id, eventData, more){
handleAdError(id, eventData, more);
}, true);
// place the test ad id in the ovvtest object
if(win['ovvtest'] != null){
win['ovvtest'].ad_id = ad_id;
}
setTimeout(function(){
console.log('=========================================')
console.log(ovv.getAds());
var ads = ovv.getAds();
console.log(ads['my_ovv_test_ad_id'].checkViewability());
}, 1000);
} | function registerOvvListeners(ad_id){
var ovv;
var ad_id = ad_id || opts.adId;
if(regTimer !== 0){
clearTimeout(regTimer);
regTimer = 0;
}
if(!window['$ovv']){
if(++attachRetries < 60000){
regTimer = setTimeout(function(){
registerOvvListeners();
}, 300);
}
return;
}
var eventNames = [
'AdLoaded', 'AdImpression', 'AdPlaying', 'AdPaused', 'AdVolumeChange',
'AdVideoStart', 'AdVideoFirstQuartile', 'AdVideoMidpoint', 'AdVideoThirdQuartile',
'AdVideoComplete'
];
// list of OVV events. We must listen to OVVLog in order to get up to date viewability information
var ovvEvents = ['OVVReady', 'OVVImpression', 'OVVImpressionUnmeasurable', 'OVVLog'];
ovv = window['$ovv'];
ovv.subscribe(ovvEvents, ad_id, function(id, eventData){
if(eventData.ovvArgs != null){
handleOvvEvent(eventData, eventData.ovvArgs);
}
}, true);
ovv.subscribe(eventNames, ad_id, function(id, eventData){
if(eventData.ovvArgs != null){
handleVpaidEvent(eventData, eventData.ovvArgs);
}
}, true);
// Error handles
ovv.subscribe(['AdError', 'OVVError'], ad_id, function(id, eventData, more){
handleAdError(id, eventData, more);
}, true);
// place the test ad id in the ovvtest object
if(win['ovvtest'] != null){
win['ovvtest'].ad_id = ad_id;
}
setTimeout(function(){
console.log('=========================================')
console.log(ovv.getAds());
var ads = ovv.getAds();
console.log(ads['my_ovv_test_ad_id'].checkViewability());
}, 1000);
} |
JavaScript | function mandelbrot(real, imaginary) {
var cr = real,
ci = imaginary,
xr = real,
xi = imaginary,
t = 0,
i = MAX_ITERATIONS,
timeIn = (new Date).valueOf();
while (xr > -2 && xr < 2 && xi > -2 && xi < 2 && i--) {
t = xr*xr - xi*xi + cr;
xi = 2*xr*xi + ci;
xr = t;
}
iterationTimer += (new Date).valueOf() - timeIn;
return MAX_ITERATIONS - i;
} | function mandelbrot(real, imaginary) {
var cr = real,
ci = imaginary,
xr = real,
xi = imaginary,
t = 0,
i = MAX_ITERATIONS,
timeIn = (new Date).valueOf();
while (xr > -2 && xr < 2 && xi > -2 && xi < 2 && i--) {
t = xr*xr - xi*xi + cr;
xi = 2*xr*xi + ci;
xr = t;
}
iterationTimer += (new Date).valueOf() - timeIn;
return MAX_ITERATIONS - i;
} |
JavaScript | function exportDataJSON() {
var blob = new Blob([JSON.stringify(notes, null, 2)], {
type: 'octet/stream',
});
window.saveAs(blob, `Notoj ${new Date().toISOString().split('T')[0]}.json`);
} | function exportDataJSON() {
var blob = new Blob([JSON.stringify(notes, null, 2)], {
type: 'octet/stream',
});
window.saveAs(blob, `Notoj ${new Date().toISOString().split('T')[0]}.json`);
} |
JavaScript | function openHTML(n) {
var iframe_browser = document.querySelector('#iframe_browser');
var iframe = document.querySelector('#iframe_browser iframe');
iframe.src = iframe.src;
iframe_browser.setAttribute('color', n.color);
iframe_browser.className = 'open';
var slime = new Blob([decodeURI(n.note)], { type: 'text/html' });
iframe.src = URL.createObjectURL(slime);
// iframe.contentWindow.eval(`document.write(${note_decoded})`);
// failure, i'll use blobs instead
document.querySelector('iframe').addEventListener('load', (e) => {
iframe.contentWindow.eval(
`document.querySelector("html").insertAdjacentHTML( 'beforeend', "<style>body{background-color:${window
.getComputedStyle(iframe_browser)
.getPropertyValue('background-color')};}</style>" )`
);
});
document.getElementById('iframe_focus').focus();
} | function openHTML(n) {
var iframe_browser = document.querySelector('#iframe_browser');
var iframe = document.querySelector('#iframe_browser iframe');
iframe.src = iframe.src;
iframe_browser.setAttribute('color', n.color);
iframe_browser.className = 'open';
var slime = new Blob([decodeURI(n.note)], { type: 'text/html' });
iframe.src = URL.createObjectURL(slime);
// iframe.contentWindow.eval(`document.write(${note_decoded})`);
// failure, i'll use blobs instead
document.querySelector('iframe').addEventListener('load', (e) => {
iframe.contentWindow.eval(
`document.querySelector("html").insertAdjacentHTML( 'beforeend', "<style>body{background-color:${window
.getComputedStyle(iframe_browser)
.getPropertyValue('background-color')};}</style>" )`
);
});
document.getElementById('iframe_focus').focus();
} |
JavaScript | function schedule(args, sandbox, eventContext) {
debug("Action schedule");
if (!args.event) {
debug("Missing the event argument, not executed");
return;
}
let event = args.event;
let date = args.date;
let jobIdentifier = args.job;
let job = scheduleLib.scheduleJob(date, function () {
debug("Fired '%s' event on scheduled date '%s'", event, date);
if (jobIdentifier) {
delete jobs[jobIdentifier];
}
this.send({name: event});
}.bind(this));
if (args.job) {
jobs[args.job] = job;
}
} | function schedule(args, sandbox, eventContext) {
debug("Action schedule");
if (!args.event) {
debug("Missing the event argument, not executed");
return;
}
let event = args.event;
let date = args.date;
let jobIdentifier = args.job;
let job = scheduleLib.scheduleJob(date, function () {
debug("Fired '%s' event on scheduled date '%s'", event, date);
if (jobIdentifier) {
delete jobs[jobIdentifier];
}
this.send({name: event});
}.bind(this));
if (args.job) {
jobs[args.job] = job;
}
} |
JavaScript | _createSandbox(){
let execute = this.execute;
//Define the sandbox for the v8 virtual machine
let sandbox = {
Date: Date,
//The server global variables and functions
// globals: serverGlobal,
//The function that will process the custom actions
postMessage: function(message) {
let type = message.data["$type"];
let stripNsPrefixRe = /^(?:{(?:[^}]*)})?(.*)$/;
let arr = stripNsPrefixRe.exec(type);
let ns;
let action;
if(arr.length === 2) {
ns = type.substring(1, type.indexOf("}"));
action = arr[1];
} else {
ns = "";
action = arr[0];
}
execute.call(this, ns, action, sandbox, message._event, message.data);
}
};
return vm.createContext(sandbox);
} | _createSandbox(){
let execute = this.execute;
//Define the sandbox for the v8 virtual machine
let sandbox = {
Date: Date,
//The server global variables and functions
// globals: serverGlobal,
//The function that will process the custom actions
postMessage: function(message) {
let type = message.data["$type"];
let stripNsPrefixRe = /^(?:{(?:[^}]*)})?(.*)$/;
let arr = stripNsPrefixRe.exec(type);
let ns;
let action;
if(arr.length === 2) {
ns = type.substring(1, type.indexOf("}"));
action = arr[1];
} else {
ns = "";
action = arr[0];
}
execute.call(this, ns, action, sandbox, message._event, message.data);
}
};
return vm.createContext(sandbox);
} |
JavaScript | sendEvent(data){
if(!this.hasStarted) {
throw new Error("Can't send event, the interpreter hasn't started");
}
this.sc.gen(data);
process.send({
action: "snapshot",
snapshot: this.sc.getSnapshot()
});
} | sendEvent(data){
if(!this.hasStarted) {
throw new Error("Can't send event, the interpreter hasn't started");
}
this.sc.gen(data);
process.send({
action: "snapshot",
snapshot: this.sc.getSnapshot()
});
} |
JavaScript | function buildMenus(menus) {
// generate HTML for the menus
var i = 0,
html = "<ul>";
for (i = 0; i < menus.length; i++) {
html += getMenuHTML(menus[i]);
}
html += "</ul>";
elm.html(html);
// Add indicators and hovers to submenu parents.
// The slides look pretty, but cause problems for Selenium,
// so they're disabled when testing.
elm.find("li").each(function() {
var header = jQuery(this).children(":first"),
menu = jQuery(this).find("ul"),
showMenu = function() {
if (typeof openmdao_test_mode === "undefined") {
menu.stop(true, true).slideDown();
}
},
hideMenu = function() {
if (typeof openmdao_test_mode === "undefined") {
menu.stop(true, true).slideUp();
}
},
settings = {
timeout: 500,
over: showMenu,
out: hideMenu
};
// When testing, toggle this menu and hide all the others on click.
header.click(function() {
if (typeof openmdao_test_mode !== "undefined") {
menu.toggle();
header.parent().siblings().find("ul").hide();
}
});
if (menu.length > 0) {
jQuery("<span>").text("^").appendTo(header);
jQuery(this).hoverIntent( settings );
menu.find("li").click(function() { menu.toggle(); });
}
});
} | function buildMenus(menus) {
// generate HTML for the menus
var i = 0,
html = "<ul>";
for (i = 0; i < menus.length; i++) {
html += getMenuHTML(menus[i]);
}
html += "</ul>";
elm.html(html);
// Add indicators and hovers to submenu parents.
// The slides look pretty, but cause problems for Selenium,
// so they're disabled when testing.
elm.find("li").each(function() {
var header = jQuery(this).children(":first"),
menu = jQuery(this).find("ul"),
showMenu = function() {
if (typeof openmdao_test_mode === "undefined") {
menu.stop(true, true).slideDown();
}
},
hideMenu = function() {
if (typeof openmdao_test_mode === "undefined") {
menu.stop(true, true).slideUp();
}
},
settings = {
timeout: 500,
over: showMenu,
out: hideMenu
};
// When testing, toggle this menu and hide all the others on click.
header.click(function() {
if (typeof openmdao_test_mode !== "undefined") {
menu.toggle();
header.parent().siblings().find("ul").hide();
}
});
if (menu.length > 0) {
jQuery("<span>").text("^").appendTo(header);
jQuery(this).hoverIntent( settings );
menu.find("li").click(function() { menu.toggle(); });
}
});
} |
JavaScript | function disableById(id) {
var button = jQuery('#'+id),
binding = button.attr('onclick');
if (binding) { // We can get multiple disables in a row.
_onclick[id] = binding;
button.attr('onclick', null);
button.addClass('omg-disabled');
}
} | function disableById(id) {
var button = jQuery('#'+id),
binding = button.attr('onclick');
if (binding) { // We can get multiple disables in a row.
_onclick[id] = binding;
button.attr('onclick', null);
button.addClass('omg-disabled');
}
} |
JavaScript | function enableById(id) {
var button = jQuery('#'+id),
binding = _onclick[id];
if (binding) {
button.attr('onclick', binding);
button.removeClass('omg-disabled');
}
} | function enableById(id) {
var button = jQuery('#'+id),
binding = _onclick[id];
if (binding) {
button.attr('onclick', binding);
button.removeClass('omg-disabled');
}
} |
JavaScript | function modelModified(message) {
var modified = message[1];
if (modified) {
enableById('project-commit');
enableById('project-revert');
} else {
disableById('project-commit');
disableById('project-revert');
}
} | function modelModified(message) {
var modified = message[1];
if (modified) {
enableById('project-commit');
enableById('project-revert');
} else {
disableById('project-commit');
disableById('project-revert');
}
} |
JavaScript | function createDrawPass(sortMethod, opt_drawList) {
return that.createDrawPass(
sortMethod,
undefined,
undefined,
undefined,
opt_drawList);
} | function createDrawPass(sortMethod, opt_drawList) {
return that.createDrawPass(
sortMethod,
undefined,
undefined,
undefined,
opt_drawList);
} |
JavaScript | function selectTab(ev, ui) {
var tabName = nameSplit(ui.newTab[0].innerText);
selectedTabName = tabName;
editor.setSession(sessions[tabName].editSession);
} | function selectTab(ev, ui) {
var tabName = nameSplit(ui.newTab[0].innerText);
selectedTabName = tabName;
editor.setSession(sessions[tabName].editSession);
} |
JavaScript | function closeTab(tab) {
var tabIndex = tab.index(),
tabName = tab.attr('aria-controls'),
filepath = tab.text(),
session = sessions[tabName];
function closeIt() {
if (fileTabs.tabs("length") === 1) {
editor.setSession(defaultSession);
editor.setReadOnly(true);
}
delete sessions[tabName];
tab.remove();
fileTabs.tabs("refresh");
}
if (session.editSession.getValue() === session.prevContent) {
//nothing changed, close tab
closeIt();
}
else {
//file changed. require user choice
var win = jQuery('<div>"'+filepath+'" has been changed. Save before closing?</div>');
jQuery(win).dialog({
'modal': true,
'title': 'Save',
'buttons': [
{
text: 'Save file',
id: saveID,
click: function() {
saveFile(tabName, closeIt);
jQuery(this).dialog('close');
}
},
{
text: 'Close without saving',
id: closeID,
click: function() {
closeIt();
jQuery(this).dialog('close');
}
},
{
text: 'Cancel',
id: cancelID,
click: function() {
jQuery(this).dialog('close');
return false;
}
}
]
});
}
return false;
} | function closeTab(tab) {
var tabIndex = tab.index(),
tabName = tab.attr('aria-controls'),
filepath = tab.text(),
session = sessions[tabName];
function closeIt() {
if (fileTabs.tabs("length") === 1) {
editor.setSession(defaultSession);
editor.setReadOnly(true);
}
delete sessions[tabName];
tab.remove();
fileTabs.tabs("refresh");
}
if (session.editSession.getValue() === session.prevContent) {
//nothing changed, close tab
closeIt();
}
else {
//file changed. require user choice
var win = jQuery('<div>"'+filepath+'" has been changed. Save before closing?</div>');
jQuery(win).dialog({
'modal': true,
'title': 'Save',
'buttons': [
{
text: 'Save file',
id: saveID,
click: function() {
saveFile(tabName, closeIt);
jQuery(this).dialog('close');
}
},
{
text: 'Close without saving',
id: closeID,
click: function() {
closeIt();
jQuery(this).dialog('close');
}
},
{
text: 'Cancel',
id: cancelID,
click: function() {
jQuery(this).dialog('close');
return false;
}
}
]
});
}
return false;
} |
JavaScript | function saveFile(tabName, callback) {
if (! tabName) {
tabName = selectedTabName;
}
var session = sessions[tabName],
currentCode = session.editSession.getValue(),
lastCode = session.prevContent,
filepath = session.filepath;
/** display error message if file save failed */
function failedSave(jqXHR, textStatus, errorThrown) {
debug.error("file save failed: "+textStatus, jqXHR, errorThrown);
// 409 gets special handling.
// 400 is (normally) related to msg reported via publisher.
if (jqXHR.status !== 409 && jqXHR.status !== 400) {
var msg = jqXHR.responseXML || textStatus;
openmdao.Util.notify(msg, 'Save Failed');
}
}
/** 409 response when saving file indicates model reload will be necessary */
function handle409(jqXHR, textStatus, errorThrown) {
var win = jQuery('<div>Changing this file can alter the model configuration. '+
'If you save this file, you must reload the project.</div>');
jQuery(win).dialog({
'modal': true,
'title': 'Save File and Reload Project',
'buttons': [
{
text: 'Save File and Reload Project',
id: overwriteID,
click: function() {
jQuery(this).dialog('close');
model.setFile(filepath,currentCode, 1,
function() {
model.reload();
},
failedSave);
}
},
{
text: 'Cancel',
id: cancelID,
click: function() {
jQuery(this).dialog('close');
}
}
]
}
);
}
if (currentCode !== lastCode) {
model.setFile(filepath, currentCode, 0,
function (data, textStatus, jqXHR) { // success
// store saved file for comparison
session.prevContent = currentCode;
// mark as not modified
renameTab("#"+tabName, filepath);
session.modifed = false;
if (typeof openmdao_test_mode !== 'undefined') {
openmdao.Util.notify('Save complete: ' + textStatus);
}
if (typeof callback === 'function') {
callback();
}
},
failedSave,
handle409);
}
} | function saveFile(tabName, callback) {
if (! tabName) {
tabName = selectedTabName;
}
var session = sessions[tabName],
currentCode = session.editSession.getValue(),
lastCode = session.prevContent,
filepath = session.filepath;
/** display error message if file save failed */
function failedSave(jqXHR, textStatus, errorThrown) {
debug.error("file save failed: "+textStatus, jqXHR, errorThrown);
// 409 gets special handling.
// 400 is (normally) related to msg reported via publisher.
if (jqXHR.status !== 409 && jqXHR.status !== 400) {
var msg = jqXHR.responseXML || textStatus;
openmdao.Util.notify(msg, 'Save Failed');
}
}
/** 409 response when saving file indicates model reload will be necessary */
function handle409(jqXHR, textStatus, errorThrown) {
var win = jQuery('<div>Changing this file can alter the model configuration. '+
'If you save this file, you must reload the project.</div>');
jQuery(win).dialog({
'modal': true,
'title': 'Save File and Reload Project',
'buttons': [
{
text: 'Save File and Reload Project',
id: overwriteID,
click: function() {
jQuery(this).dialog('close');
model.setFile(filepath,currentCode, 1,
function() {
model.reload();
},
failedSave);
}
},
{
text: 'Cancel',
id: cancelID,
click: function() {
jQuery(this).dialog('close');
}
}
]
}
);
}
if (currentCode !== lastCode) {
model.setFile(filepath, currentCode, 0,
function (data, textStatus, jqXHR) { // success
// store saved file for comparison
session.prevContent = currentCode;
// mark as not modified
renameTab("#"+tabName, filepath);
session.modifed = false;
if (typeof openmdao_test_mode !== 'undefined') {
openmdao.Util.notify('Save complete: ' + textStatus);
}
if (typeof callback === 'function') {
callback();
}
},
failedSave,
handle409);
}
} |
JavaScript | function failedSave(jqXHR, textStatus, errorThrown) {
debug.error("file save failed: "+textStatus, jqXHR, errorThrown);
// 409 gets special handling.
// 400 is (normally) related to msg reported via publisher.
if (jqXHR.status !== 409 && jqXHR.status !== 400) {
var msg = jqXHR.responseXML || textStatus;
openmdao.Util.notify(msg, 'Save Failed');
}
} | function failedSave(jqXHR, textStatus, errorThrown) {
debug.error("file save failed: "+textStatus, jqXHR, errorThrown);
// 409 gets special handling.
// 400 is (normally) related to msg reported via publisher.
if (jqXHR.status !== 409 && jqXHR.status !== 400) {
var msg = jqXHR.responseXML || textStatus;
openmdao.Util.notify(msg, 'Save Failed');
}
} |
JavaScript | function handle409(jqXHR, textStatus, errorThrown) {
var win = jQuery('<div>Changing this file can alter the model configuration. '+
'If you save this file, you must reload the project.</div>');
jQuery(win).dialog({
'modal': true,
'title': 'Save File and Reload Project',
'buttons': [
{
text: 'Save File and Reload Project',
id: overwriteID,
click: function() {
jQuery(this).dialog('close');
model.setFile(filepath,currentCode, 1,
function() {
model.reload();
},
failedSave);
}
},
{
text: 'Cancel',
id: cancelID,
click: function() {
jQuery(this).dialog('close');
}
}
]
}
);
} | function handle409(jqXHR, textStatus, errorThrown) {
var win = jQuery('<div>Changing this file can alter the model configuration. '+
'If you save this file, you must reload the project.</div>');
jQuery(win).dialog({
'modal': true,
'title': 'Save File and Reload Project',
'buttons': [
{
text: 'Save File and Reload Project',
id: overwriteID,
click: function() {
jQuery(this).dialog('close');
model.setFile(filepath,currentCode, 1,
function() {
model.reload();
},
failedSave);
}
},
{
text: 'Cancel',
id: cancelID,
click: function() {
jQuery(this).dialog('close');
}
}
]
}
);
} |
JavaScript | function findMode(filename) {
chunks = filename.split('.');
if (chunks.length === 2){
if (chunks[1] === "py") {
return "ace/mode/python";
}
else if (chunks[1] === "js") {
return "ace/mode/javascript";
}
else {
return "ace/mode/python";
}
}
else {
return "ace/mode/python";
}
} | function findMode(filename) {
chunks = filename.split('.');
if (chunks.length === 2){
if (chunks[1] === "py") {
return "ace/mode/python";
}
else if (chunks[1] === "js") {
return "ace/mode/javascript";
}
else {
return "ace/mode/python";
}
}
else {
return "ace/mode/python";
}
} |
JavaScript | function newTab(contents, filepath, tabName, mode) {
editor.setReadOnly(false);
if (!tabName) {
tabName = nameSplit(filepath);
}
if (!mode) {
mode = findMode(filepath);
}
var newSession = new EditSession(contents); // new code session for ace
newSession.setUseSoftTabs(true);
newSession.setTabSize(4);
newSession.setUndoManager(new UndoManager());
newSession.setMode(mode);
newSession.on('change', function(evt) {
if (sessions[tabName].editSession.getValue() !== contents) {
renameTab("#"+tabName, filepath+"*");
sessions[tabName].modified = true;
}
else {
renameTab("#"+tabName, filepath);
sessions[tabName].modified = false;
}
});
editor.setSession(newSession);
// store session for efficent switching
sessions[tabName] = {
'editSession': newSession,
'prevContent': contents,
'filepath': filepath,
'modified': false
};
jQuery('<div id="'+tabName+'"></div>').appendTo(fileInner); // new empty div
fileTabs.tabs("add", '#'+tabName, filepath);
fileTabs.tabs('select', "#"+tabName);
selectedTabName = tabName;
if (Object.keys(sessions) > 1) {
// On OS X an initial self.resize() would result in a blank display.
// Keeping original resize code for possibly handling lots 'o tabs.
self.resize();
editor.resize();
}
} | function newTab(contents, filepath, tabName, mode) {
editor.setReadOnly(false);
if (!tabName) {
tabName = nameSplit(filepath);
}
if (!mode) {
mode = findMode(filepath);
}
var newSession = new EditSession(contents); // new code session for ace
newSession.setUseSoftTabs(true);
newSession.setTabSize(4);
newSession.setUndoManager(new UndoManager());
newSession.setMode(mode);
newSession.on('change', function(evt) {
if (sessions[tabName].editSession.getValue() !== contents) {
renameTab("#"+tabName, filepath+"*");
sessions[tabName].modified = true;
}
else {
renameTab("#"+tabName, filepath);
sessions[tabName].modified = false;
}
});
editor.setSession(newSession);
// store session for efficent switching
sessions[tabName] = {
'editSession': newSession,
'prevContent': contents,
'filepath': filepath,
'modified': false
};
jQuery('<div id="'+tabName+'"></div>').appendTo(fileInner); // new empty div
fileTabs.tabs("add", '#'+tabName, filepath);
fileTabs.tabs('select', "#"+tabName);
selectedTabName = tabName;
if (Object.keys(sessions) > 1) {
// On OS X an initial self.resize() would result in a blank display.
// Keeping original resize code for possibly handling lots 'o tabs.
self.resize();
editor.resize();
}
} |
JavaScript | function nameSplit(filepath) {
return filepath.split('.').join('')
.split('/').join('')
.split('*').join('')
.trim();
} | function nameSplit(filepath) {
return filepath.split('.').join('')
.split('/').join('')
.split('*').join('')
.trim();
} |
JavaScript | function loadTabs(properties) {
if (!properties || properties.length === 0) {
alert('No properties found for ',self.pathname);
return;
}
var tabbed_pane = jQuery('<div id="'+self.id+'_tabs">'),
tabs = jQuery('<ul>');
self.elm.html("");
self.elm.append(tabbed_pane);
tabbed_pane.append(tabs);
var tabcount = 0, selected = 0;
jQuery.each(properties,function (name,val) {
if (name === 'type') {
if (self.elm.parent().hasClass('ui-dialog')) {
self.elm.dialog("option","title",val+': '+self.pathname);
}
}
// Don't show empty slots tab.
else if (name !== 'Slots' || val.length) {
if (name.length > 12) {
tabname = name.substr(0,12);
}
else {
tabname = name;
}
var contentID = self.id+'_'+name,
tab = jQuery('<li id="'+contentID+'_tab">')
.append('<a href="#'+contentID+'">'+tabname+'</a>'),
contentPane = jQuery('<div id="'+contentID+'" style="overflow:auto"></div>');
tabs.append(tab);
tabbed_pane.append(contentPane);
getContent(contentPane,name,val);
if (self.initiallySelected === name) {
selected = tabcount;
}
tabcount = tabcount + 1;
}
});
self.elm.height(400);
self.elm.width(640);
self.elm.tabs({selected: selected})
.on('tabsshow', function(event, ui) {
if (ui.tab.text === 'Workflow') {
self.elm.find('.WorkflowFigure').trigger('setBackground');
}
});
if (typeof openmdao_test_mode !== 'undefined') {
openmdao.Util.notify(self.pathname+' loaded');
}
} | function loadTabs(properties) {
if (!properties || properties.length === 0) {
alert('No properties found for ',self.pathname);
return;
}
var tabbed_pane = jQuery('<div id="'+self.id+'_tabs">'),
tabs = jQuery('<ul>');
self.elm.html("");
self.elm.append(tabbed_pane);
tabbed_pane.append(tabs);
var tabcount = 0, selected = 0;
jQuery.each(properties,function (name,val) {
if (name === 'type') {
if (self.elm.parent().hasClass('ui-dialog')) {
self.elm.dialog("option","title",val+': '+self.pathname);
}
}
// Don't show empty slots tab.
else if (name !== 'Slots' || val.length) {
if (name.length > 12) {
tabname = name.substr(0,12);
}
else {
tabname = name;
}
var contentID = self.id+'_'+name,
tab = jQuery('<li id="'+contentID+'_tab">')
.append('<a href="#'+contentID+'">'+tabname+'</a>'),
contentPane = jQuery('<div id="'+contentID+'" style="overflow:auto"></div>');
tabs.append(tab);
tabbed_pane.append(contentPane);
getContent(contentPane,name,val);
if (self.initiallySelected === name) {
selected = tabcount;
}
tabcount = tabcount + 1;
}
});
self.elm.height(400);
self.elm.width(640);
self.elm.tabs({selected: selected})
.on('tabsshow', function(event, ui) {
if (ui.tab.text === 'Workflow') {
self.elm.find('.WorkflowFigure').trigger('setBackground');
}
});
if (typeof openmdao_test_mode !== 'undefined') {
openmdao.Util.notify(self.pathname+' loaded');
}
} |
JavaScript | function updateData(newValues) {
if (!newValues) {
debug.error('PlotFrame received bad data:',newValues);
return;
}
//newValues = jQuery.parseJSON(newValues);
jQuery.each(newValues,function (name,val) {
if (! data[name]) {
data[name] = [];
}
// don't exceed max number of points
if (data[name].length > maxPoints) {
data[name] = data[name].slice(1);
}
val = parseFloat(val);
data[name].push(val);
});
} | function updateData(newValues) {
if (!newValues) {
debug.error('PlotFrame received bad data:',newValues);
return;
}
//newValues = jQuery.parseJSON(newValues);
jQuery.each(newValues,function (name,val) {
if (! data[name]) {
data[name] = [];
}
// don't exceed max number of points
if (data[name].length > maxPoints) {
data[name] = data[name].slice(1);
}
val = parseFloat(val);
data[name].push(val);
});
} |
JavaScript | function updatePlot() {
var plotdata = [];
jQuery.each(data,function (name,vals) {
// generate index values for x-axis, zip with y values
var x = 0,
xydata = [];
for (x = 0; x < vals.length; ++x) {
xydata.push([x, vals[x]]);
}
plotdata.push({ 'data':xydata, 'label':name });
});
plot.setData(plotdata);
plot.resize(); // in case the frame was resized
plot.setupGrid();
plot.draw();
} | function updatePlot() {
var plotdata = [];
jQuery.each(data,function (name,vals) {
// generate index values for x-axis, zip with y values
var x = 0,
xydata = [];
for (x = 0; x < vals.length; ++x) {
xydata.push([x, vals[x]]);
}
plotdata.push({ 'data':xydata, 'label':name });
});
plot.setData(plotdata);
plot.resize(); // in case the frame was resized
plot.setupGrid();
plot.draw();
} |
JavaScript | function addVariable() {
openmdao.Util.promptForValue('Enter pathname of variable to plot:',
function(pathname) {
plotVariable(pathname);
}
);
} | function addVariable() {
openmdao.Util.promptForValue('Enter pathname of variable to plot:',
function(pathname) {
plotVariable(pathname);
}
);
} |
Subsets and Splits