language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
function validateMongoUri() { if (!process.env.MONGO_URI) { console.log('No value set for MONGO_URI...'); console.log('Using the supplied value from config object...') switch (process.env.NODE_ENV) { case 'development': process.env.MONGO_URI = config.MONGO_URI.DEVELOPMENT; console.log("MONGO_URI set for ${process.env.NODE_ENV}"); break; case 'production': process.env.MONGO_URI = config.MONGO_URI.PRODUCTION; console.log("MONGO_URI set for ${process.env.NODE_ENV}"); break; case 'test': process.env.MONGO_URI = config.MONGO_URI.TEST; console.log("MONGO_URI set for ${process.env.NODE_ENV}"); break; default: console.log('Unexpected behavior! process.env.NODE_ENV set to ' + 'unexpected value!'); break; } } }
function validateMongoUri() { if (!process.env.MONGO_URI) { console.log('No value set for MONGO_URI...'); console.log('Using the supplied value from config object...') switch (process.env.NODE_ENV) { case 'development': process.env.MONGO_URI = config.MONGO_URI.DEVELOPMENT; console.log("MONGO_URI set for ${process.env.NODE_ENV}"); break; case 'production': process.env.MONGO_URI = config.MONGO_URI.PRODUCTION; console.log("MONGO_URI set for ${process.env.NODE_ENV}"); break; case 'test': process.env.MONGO_URI = config.MONGO_URI.TEST; console.log("MONGO_URI set for ${process.env.NODE_ENV}"); break; default: console.log('Unexpected behavior! process.env.NODE_ENV set to ' + 'unexpected value!'); break; } } }
JavaScript
addOptions(options) { // options must be an object if (typeof(options) != 'object') throw `Type exception on options, must be an object (got ${typeof(options)})`; for (let key in options) { // check if passed parameter is permitted if (!this.allowedOptions.indexOf(options.key)) throw `Index exception on options, ${key} not allowed`; let that = this; switch(key) { case 'enableLogging': // type check enableLogging (boolean) if (typeof(options[key]) != 'boolean') throw `Type exception on parameter options ${key}, must be boolean (got ${typeof(options[key])})`; this.enableLogging = options[key]; break; case 'logToFile': // type check must be an object if(typeof(options[key]) != 'object') throw `Type exception on parameter options ${key}, must be object (got ${typeof(options[key])})`; // loop the inner object for (let k in options[key]) { if(typeof(options[key][k]) != 'boolean') throw `Type exception on parameter options ${k}, must be boolean (got ${typeof(options[key][k])})`; this.logToFile[k] = options[key][k]; } break; case 'callerGlobal': // type check callerGlobal (boolean) if (typeof(options[key]) != 'boolean') throw `Type exception on parameter options ${key}, must be boolean (got ${typeof(options[key])})`; this.callerGlobal = options[key]; break; case 'level': // type check level (object) if (typeof(options[key]) != 'object') throw `Type exception on parameter options ${key}, must be object (got ${typeof(options[key])})`; // loop through the nested object for (let k in options[key]) { // type check on value must be number if (typeof(options[key][k]) != 'number') throw `Type exception on parameter options ${key} ${k} must be number (got ${typeof(options[key][k])})`; this.level[k] = options[key][k]; // set logToFile for k to default true this.logToFile = { [k]: true }; } break; case 'services': // type check services (array) if(typeof(options.services) != 'object') throw `Type exception on parameter options ${key}, must be object (got ${typeof(options.services)})`; // loop through the array for (let i=0; i < options.services.lenght; i++) { // type check on array content if(typeof(options.services[i]) != 'string') throw `Type exception on content of parameter options services must be string (got ${typeof(options.services[i])})`; // index check no duplicates if (this.services.indexOf(options.services[i])) throw `Index exception duplicate detected for services ${options.services[i]}`; } // push value to the array options.services.forEach(pushToArray); function pushToArray(value) { that.services.push(value); } break; } } }
addOptions(options) { // options must be an object if (typeof(options) != 'object') throw `Type exception on options, must be an object (got ${typeof(options)})`; for (let key in options) { // check if passed parameter is permitted if (!this.allowedOptions.indexOf(options.key)) throw `Index exception on options, ${key} not allowed`; let that = this; switch(key) { case 'enableLogging': // type check enableLogging (boolean) if (typeof(options[key]) != 'boolean') throw `Type exception on parameter options ${key}, must be boolean (got ${typeof(options[key])})`; this.enableLogging = options[key]; break; case 'logToFile': // type check must be an object if(typeof(options[key]) != 'object') throw `Type exception on parameter options ${key}, must be object (got ${typeof(options[key])})`; // loop the inner object for (let k in options[key]) { if(typeof(options[key][k]) != 'boolean') throw `Type exception on parameter options ${k}, must be boolean (got ${typeof(options[key][k])})`; this.logToFile[k] = options[key][k]; } break; case 'callerGlobal': // type check callerGlobal (boolean) if (typeof(options[key]) != 'boolean') throw `Type exception on parameter options ${key}, must be boolean (got ${typeof(options[key])})`; this.callerGlobal = options[key]; break; case 'level': // type check level (object) if (typeof(options[key]) != 'object') throw `Type exception on parameter options ${key}, must be object (got ${typeof(options[key])})`; // loop through the nested object for (let k in options[key]) { // type check on value must be number if (typeof(options[key][k]) != 'number') throw `Type exception on parameter options ${key} ${k} must be number (got ${typeof(options[key][k])})`; this.level[k] = options[key][k]; // set logToFile for k to default true this.logToFile = { [k]: true }; } break; case 'services': // type check services (array) if(typeof(options.services) != 'object') throw `Type exception on parameter options ${key}, must be object (got ${typeof(options.services)})`; // loop through the array for (let i=0; i < options.services.lenght; i++) { // type check on array content if(typeof(options.services[i]) != 'string') throw `Type exception on content of parameter options services must be string (got ${typeof(options.services[i])})`; // index check no duplicates if (this.services.indexOf(options.services[i])) throw `Index exception duplicate detected for services ${options.services[i]}`; } // push value to the array options.services.forEach(pushToArray); function pushToArray(value) { that.services.push(value); } break; } } }
JavaScript
function createFile(msg) { fs.writeFile(that.logfile, msg + '\r\n', (error) => { if (error) throw error; // for testing only if (process.env.NODE_ENV === 'dev') { return true; } }); }
function createFile(msg) { fs.writeFile(that.logfile, msg + '\r\n', (error) => { if (error) throw error; // for testing only if (process.env.NODE_ENV === 'dev') { return true; } }); }
JavaScript
_deleteIndex(key, tableNames) { return Promise.all(tableNames.map(table => { return new Promise((resolve, reject) => { const store = this.transaction.objectStore(table); store.onerror = reject; const requests = []; const req = store.index('key').openKeyCursor(this._KeyRange.only(key)); req.onerror = reject; req.onsuccess = ev => { const cursor = ev.target.result; if (cursor) { requests.push(new Promise((resolve, reject) => { const d = store.delete(cursor.primaryKey); d.onsuccess = resolve; d.onerror = reject })); cursor.continue(); } else { resolve(Promise.all(requests)); } } }); })); }
_deleteIndex(key, tableNames) { return Promise.all(tableNames.map(table => { return new Promise((resolve, reject) => { const store = this.transaction.objectStore(table); store.onerror = reject; const requests = []; const req = store.index('key').openKeyCursor(this._KeyRange.only(key)); req.onerror = reject; req.onsuccess = ev => { const cursor = ev.target.result; if (cursor) { requests.push(new Promise((resolve, reject) => { const d = store.delete(cursor.primaryKey); d.onsuccess = resolve; d.onerror = reject })); cursor.continue(); } else { resolve(Promise.all(requests)); } } }); })); }
JavaScript
delete(...keys) { for (let i=0; i<keys.length; i++) { if (keys[i] === null || keys[i] === undefined) { return Promise.reject(new InvalidKeyError(keys[i])); } } return Promise.all(fastMap(keys, key => { return new Promise((resolve, reject) => { const req = this.transaction.objectStore('data').delete(key); req.onerror = reject; req.onsuccess = resolve; }) .then(() => this._deleteIndex(key, [ ...[...this.db.schema.ngramIndexes].map(x => this.db.index_prefix + 'ngram_' + x), ...[...this.db.schema.wordIndexes].map(x => this.db.index_prefix + 'word_' + x), ])) })).then(() => this); }
delete(...keys) { for (let i=0; i<keys.length; i++) { if (keys[i] === null || keys[i] === undefined) { return Promise.reject(new InvalidKeyError(keys[i])); } } return Promise.all(fastMap(keys, key => { return new Promise((resolve, reject) => { const req = this.transaction.objectStore('data').delete(key); req.onerror = reject; req.onsuccess = resolve; }) .then(() => this._deleteIndex(key, [ ...[...this.db.schema.ngramIndexes].map(x => this.db.index_prefix + 'ngram_' + x), ...[...this.db.schema.wordIndexes].map(x => this.db.index_prefix + 'word_' + x), ])) })).then(() => this); }
JavaScript
_readCursor(cursorRequest, filter=null, map=null, limit=undefined) { filter = filter || ((x, i) => true); map = map || ((x, i) => x); return new IFTSArrayPromise(this.db.schema.indexes, new Promise((resolve, reject) => { const result = []; let index = 0; cursorRequest.onsuccess = ev => { const cursor = ev.target.result; if (cursor) { const value = cursor.value; if (this.db.schema.primaryKey === null) { value._key = cursor.key; } this._cache[cursor.key] = value; if (filter(value, index)) { result.push(map(value, index)); } index++; if (limit === undefined || index < limit) { cursor.continue(); } else { resolve(result); } } else { resolve(result); } }; cursorRequest.onerror = err => reject(err); })); }
_readCursor(cursorRequest, filter=null, map=null, limit=undefined) { filter = filter || ((x, i) => true); map = map || ((x, i) => x); return new IFTSArrayPromise(this.db.schema.indexes, new Promise((resolve, reject) => { const result = []; let index = 0; cursorRequest.onsuccess = ev => { const cursor = ev.target.result; if (cursor) { const value = cursor.value; if (this.db.schema.primaryKey === null) { value._key = cursor.key; } this._cache[cursor.key] = value; if (filter(value, index)) { result.push(map(value, index)); } index++; if (limit === undefined || index < limit) { cursor.continue(); } else { resolve(result); } } else { resolve(result); } }; cursorRequest.onerror = err => reject(err); })); }
JavaScript
_getAllWithKeys() { return new IFTSArrayPromise(this.db.schema.indexes, new Promise((resolve, reject) => { const request = this.transaction.objectStore('data').openCursor(); const result = []; request.onsuccess = ev => { const cursor = ev.target.result; if (cursor) { const value = cursor.value; if (this.db.schema.primaryKey === null) { value._key = cursor.key; } this._cache[cursor.key] = value; result.push({key: cursor.key, data: value}); cursor.continue(); } else { resolve(result); } }; request.onerror = err => reject(err); })); }
_getAllWithKeys() { return new IFTSArrayPromise(this.db.schema.indexes, new Promise((resolve, reject) => { const request = this.transaction.objectStore('data').openCursor(); const result = []; request.onsuccess = ev => { const cursor = ev.target.result; if (cursor) { const value = cursor.value; if (this.db.schema.primaryKey === null) { value._key = cursor.key; } this._cache[cursor.key] = value; result.push({key: cursor.key, data: value}); cursor.continue(); } else { resolve(result); } }; request.onerror = err => reject(err); })); }
JavaScript
_getAllWithIndex(column, keyRange) { if (!this.db.schema.indexes.has(column)) { return IFTSArrayPromise.reject(this.db.schema.indexes, new NoSuchColumnError(column)); } const store = this.transaction.objectStore('data'); if (column === this.db.schema.primaryKey) { return this._readCursor(store.openCursor(keyRange)); } else { return this._readCursor(store.index(column).openCursor(keyRange)); } }
_getAllWithIndex(column, keyRange) { if (!this.db.schema.indexes.has(column)) { return IFTSArrayPromise.reject(this.db.schema.indexes, new NoSuchColumnError(column)); } const store = this.transaction.objectStore('data'); if (column === this.db.schema.primaryKey) { return this._readCursor(store.openCursor(keyRange)); } else { return this._readCursor(store.index(column).openCursor(keyRange)); } }
JavaScript
_takeCandidatesBySingleColumn(column, queries, options={}) { const store = this.transaction.objectStore(this.db.index_prefix + 'ngram_' + column); const index = options.ignoreCase ? store.index('lower') : store.index('token'); const result = []; for (let q in queries) { const checkIncludes = ( options.ignoreCase ? (x => x.data[column].toLowerCase().includes(q)) : (x => x.data[column].includes(q)) ); if (queries[q].length === 0) { result.push(this._getAllWithKeys().filter(checkIncludes).map(x => x.key).then(xs => ({query: q, keys: xs}))); continue; } const promises = new Array(queries[q].length); for (let i=0; i<queries[q].length; i++) { promises[i] = this._readCursor(index.openCursor(queries[q][i]), null, data => data.key); } const candidate = Promise.all(promises) .then(founds => { if (founds.length === 0) { return Promise.resolve([]); } founds = flatten(founds); const deduped = new Array(founds.length); let dedup_num = 0; const hit_count = {}; for (let i=0; i<founds.length; i++) { if (!(founds[i] in hit_count)) { hit_count[founds[i]] = 0; deduped[dedup_num] = founds[i]; dedup_num++; } hit_count[founds[i]]++; } const candidates = new Array(dedup_num); let candidate_num = 0; for (let i=0; i<dedup_num; i++) { if (hit_count[deduped[i]] >= queries[q].length) { candidates[candidate_num] = this.get(deduped[i]).then(data => ({key: deduped[i], data: data})); candidate_num++; } } return Promise.all(candidates.slice(0, candidate_num)); }) .then(xs => ({query: q, keys: xs.filter(checkIncludes).map(x => x.key)})) result.push(candidate); } return result; }
_takeCandidatesBySingleColumn(column, queries, options={}) { const store = this.transaction.objectStore(this.db.index_prefix + 'ngram_' + column); const index = options.ignoreCase ? store.index('lower') : store.index('token'); const result = []; for (let q in queries) { const checkIncludes = ( options.ignoreCase ? (x => x.data[column].toLowerCase().includes(q)) : (x => x.data[column].includes(q)) ); if (queries[q].length === 0) { result.push(this._getAllWithKeys().filter(checkIncludes).map(x => x.key).then(xs => ({query: q, keys: xs}))); continue; } const promises = new Array(queries[q].length); for (let i=0; i<queries[q].length; i++) { promises[i] = this._readCursor(index.openCursor(queries[q][i]), null, data => data.key); } const candidate = Promise.all(promises) .then(founds => { if (founds.length === 0) { return Promise.resolve([]); } founds = flatten(founds); const deduped = new Array(founds.length); let dedup_num = 0; const hit_count = {}; for (let i=0; i<founds.length; i++) { if (!(founds[i] in hit_count)) { hit_count[founds[i]] = 0; deduped[dedup_num] = founds[i]; dedup_num++; } hit_count[founds[i]]++; } const candidates = new Array(dedup_num); let candidate_num = 0; for (let i=0; i<dedup_num; i++) { if (hit_count[deduped[i]] >= queries[q].length) { candidates[candidate_num] = this.get(deduped[i]).then(data => ({key: deduped[i], data: data})); candidate_num++; } } return Promise.all(candidates.slice(0, candidate_num)); }) .then(xs => ({query: q, keys: xs.filter(checkIncludes).map(x => x.key)})) result.push(candidate); } return result; }
JavaScript
_checkAndFilter(column, fun) { if (!this.indexes.has(column)) { return IFTSArrayPromise.reject(this.indexes, new NoSuchColumnError(column)); } return this.filter(fun); }
_checkAndFilter(column, fun) { if (!this.indexes.has(column)) { return IFTSArrayPromise.reject(this.indexes, new NoSuchColumnError(column)); } return this.filter(fun); }
JavaScript
update(){ //Check if patticle is still within canvas. if(this.x > canvas.width || this.x <0){ this.directionX = -this.directionX; } if(this.y > canvas.height || this.y <0){ this.directionY = -this.directionY; } //Check Collision Detection - mouse position / particle position let dx = mouse.x - this.x; let dy = mouse.y - this.y; let distance = Math.sqrt(dx*dx + dy*dy); if(enableMouseInteraction){ if(mouseRepel){ if(distance < mouse.radius + this.size){ if(mouse.x < this.x && this.x <canvas.width - this.size * 10){ this.x += particleMagnetizationSpeed; } if(mouse.x > this.x && this.x > this.size * 10){ this.x -= particleMagnetizationSpeed; } if(mouse.y < this.y && this.y <canvas.height - this.size *10){ this.y += particleMagnetizationSpeed; } if(mouse.y > this.y && this.y > this.size * 10){ this.y -= particleMagnetizationSpeed; } } }else{ if(distance < mouse.radius + this.size){ if(mouse.x < this.x && this.x <canvas.width - this.size * 10){ this.x -= particleMagnetizationSpeed; } if(mouse.x > this.x && this.x > this.size * 10){ this.x += particleMagnetizationSpeed; } if(mouse.y < this.y && this.y <canvas.height - this.size *10){ this.y -= particleMagnetizationSpeed; } if(mouse.y > this.y && this.y > this.size * 10){ this.y += particleMagnetizationSpeed; } } } } //Move Particle if(!isStill){ this.x += this.directionX; this.y += this.directionY; } //Draw the particle this.draw(); }
update(){ //Check if patticle is still within canvas. if(this.x > canvas.width || this.x <0){ this.directionX = -this.directionX; } if(this.y > canvas.height || this.y <0){ this.directionY = -this.directionY; } //Check Collision Detection - mouse position / particle position let dx = mouse.x - this.x; let dy = mouse.y - this.y; let distance = Math.sqrt(dx*dx + dy*dy); if(enableMouseInteraction){ if(mouseRepel){ if(distance < mouse.radius + this.size){ if(mouse.x < this.x && this.x <canvas.width - this.size * 10){ this.x += particleMagnetizationSpeed; } if(mouse.x > this.x && this.x > this.size * 10){ this.x -= particleMagnetizationSpeed; } if(mouse.y < this.y && this.y <canvas.height - this.size *10){ this.y += particleMagnetizationSpeed; } if(mouse.y > this.y && this.y > this.size * 10){ this.y -= particleMagnetizationSpeed; } } }else{ if(distance < mouse.radius + this.size){ if(mouse.x < this.x && this.x <canvas.width - this.size * 10){ this.x -= particleMagnetizationSpeed; } if(mouse.x > this.x && this.x > this.size * 10){ this.x += particleMagnetizationSpeed; } if(mouse.y < this.y && this.y <canvas.height - this.size *10){ this.y -= particleMagnetizationSpeed; } if(mouse.y > this.y && this.y > this.size * 10){ this.y += particleMagnetizationSpeed; } } } } //Move Particle if(!isStill){ this.x += this.directionX; this.y += this.directionY; } //Draw the particle this.draw(); }
JavaScript
function removeZAnimals () { // 1) declare an array with some strings const animals = ["alligator", "zebra", "crocodile", "giraffe"] // create an empty array (we will fill this with strings from the previous array) let animalsWithoutZ = [] // 2) loop through "animals" // 3) add every item in "animals" to "animalsWithoutZ" unless the animal name // contains the letter "z" // HINT: remember you can search within a string // 4) return "animalsWithoutZ" for (let a = 0; a < animals.length; a++) { if (animals[a].indexOf('z') === -1) { animalsWithoutZ.push(animals[a]) } } return animalsWithoutZ }
function removeZAnimals () { // 1) declare an array with some strings const animals = ["alligator", "zebra", "crocodile", "giraffe"] // create an empty array (we will fill this with strings from the previous array) let animalsWithoutZ = [] // 2) loop through "animals" // 3) add every item in "animals" to "animalsWithoutZ" unless the animal name // contains the letter "z" // HINT: remember you can search within a string // 4) return "animalsWithoutZ" for (let a = 0; a < animals.length; a++) { if (animals[a].indexOf('z') === -1) { animalsWithoutZ.push(animals[a]) } } return animalsWithoutZ }
JavaScript
function numberJoinerFor (startNum, endNum){ var joinString = '' for (let i = startNum; i <= endNum; i++) { joinString = joinString + i.toString() if (i < endNum) { joinString = joinString + '_' } } return joinString }
function numberJoinerFor (startNum, endNum){ var joinString = '' for (let i = startNum; i <= endNum; i++) { joinString = joinString + i.toString() if (i < endNum) { joinString = joinString + '_' } } return joinString }
JavaScript
function chatInit(key = 84) { chatKey = key; chatView = new alt.WebView('http://resource/client/html/index.html'); chatView.on('chat:Ready', () => { chatLoaded = true; chatVisible = true; }); chatView.on('chat:StopInput', () => { chatView.unfocus(); alt.emitServer('chat:Typing', false); chatTyping = false; if (!alt.gameControlsEnabled()) { alt.toggleGameControls(true); } }); chatView.on('chat:Send', message => { alt.emitServer('chat:NewMessage', message); chatTyping = false; if (!alt.gameControlsEnabled()) { alt.toggleGameControls(true); } }); }
function chatInit(key = 84) { chatKey = key; chatView = new alt.WebView('http://resource/client/html/index.html'); chatView.on('chat:Ready', () => { chatLoaded = true; chatVisible = true; }); chatView.on('chat:StopInput', () => { chatView.unfocus(); alt.emitServer('chat:Typing', false); chatTyping = false; if (!alt.gameControlsEnabled()) { alt.toggleGameControls(true); } }); chatView.on('chat:Send', message => { alt.emitServer('chat:NewMessage', message); chatTyping = false; if (!alt.gameControlsEnabled()) { alt.toggleGameControls(true); } }); }
JavaScript
function chatMessage(message) { if (!chatLoaded) return; chatView.emit('chat:Message', message); }
function chatMessage(message) { if (!chatLoaded) return; chatView.emit('chat:Message', message); }
JavaScript
function chatToggle(state = null) { if (!chatLoaded) return; if (state == null) { chatVisible = !chatVisible; } else { chatVisible = state; } chatView.emit('chat:Visibility', chatVisible); alt.emitServer('chat:SetVisibleMeta', chatVisible); }
function chatToggle(state = null) { if (!chatLoaded) return; if (state == null) { chatVisible = !chatVisible; } else { chatVisible = state; } chatView.emit('chat:Visibility', chatVisible); alt.emitServer('chat:SetVisibleMeta', chatVisible); }
JavaScript
function isChallengeActive(challenge) { if (!challenge.published) { return false; } const now = new Date(); if (challenge.activeFrom && now < new Date(challenge.activeFrom)) { return false; } if (challenge.activeTo && now > new Date(challenge.activeTo)) { return false; } return true; }
function isChallengeActive(challenge) { if (!challenge.published) { return false; } const now = new Date(); if (challenge.activeFrom && now < new Date(challenge.activeFrom)) { return false; } if (challenge.activeTo && now > new Date(challenge.activeTo)) { return false; } return true; }
JavaScript
async function createSolution(api, challengeId, userId, solved) { const queryResult = await api.request( ` mutation createSolution($userId: ID!, $challengeId: ID!, $solved: Boolean!) { createSolution( userId: $userId challengeId: $challengeId solved: $solved ) { id } } `, { userId, challengeId, solved }, ); return queryResult.createSolution; }
async function createSolution(api, challengeId, userId, solved) { const queryResult = await api.request( ` mutation createSolution($userId: ID!, $challengeId: ID!, $solved: Boolean!) { createSolution( userId: $userId challengeId: $challengeId solved: $solved ) { id } } `, { userId, challengeId, solved }, ); return queryResult.createSolution; }
JavaScript
function generateMarkdown(response) { let spaceTitle = response.license.replace(/ /g, "%20"); let licenseLink = ""; for (var i = 0; i < licenseArray.length; i++) { if (response.license === licenseArray[i].name) { licenseLink = licenseArray[i].link; } } return `# ${response.title} ![GitHub license](https://img.shields.io/badge/license-${spaceTitle}-blue.svg) # Live Site ${response.url} ## Description ${response.description} ## Table of Contents * [Installation](#installation) * [Usage](#usage) * [License](#license) * [Credits](#credits) * [Tests](#tests) * [Questions](#questions) ## Installation ${response.installation} ## Usage ${response.usage} ## License Copyright (c) [2020] The license is ${response.license}. Read more about it at ${licenseLink}. ## Credits ${response.credits} ## Tests ${response.tests} ## Questions If you have any additional questions please contact me at ${response.email}. GitHub: https://github.com/${response.github} `; }
function generateMarkdown(response) { let spaceTitle = response.license.replace(/ /g, "%20"); let licenseLink = ""; for (var i = 0; i < licenseArray.length; i++) { if (response.license === licenseArray[i].name) { licenseLink = licenseArray[i].link; } } return `# ${response.title} ![GitHub license](https://img.shields.io/badge/license-${spaceTitle}-blue.svg) # Live Site ${response.url} ## Description ${response.description} ## Table of Contents * [Installation](#installation) * [Usage](#usage) * [License](#license) * [Credits](#credits) * [Tests](#tests) * [Questions](#questions) ## Installation ${response.installation} ## Usage ${response.usage} ## License Copyright (c) [2020] The license is ${response.license}. Read more about it at ${licenseLink}. ## Credits ${response.credits} ## Tests ${response.tests} ## Questions If you have any additional questions please contact me at ${response.email}. GitHub: https://github.com/${response.github} `; }
JavaScript
onAfterCommand (jsonWireMsg) { const command = jsonWireMsg.endpoint.match(/[^\/]+$/); const commandName = command ? command[0] : 'undefined'; helpers.debugLog('Incomming command: ' + jsonWireMsg.endpoint + ' => [' + commandName + ']\n'); // Filter out non-action commands and keep only last action command if (config.excludedActions.includes(commandName) || !config.jsonWireActions.includes(commandName) || !this.recordingPath) { return; } const filename = this.frameNr.toString().padStart(4, '0') + '.png'; const filePath = path.resolve(this.recordingPath, filename); try { browser.saveScreenshot(filePath); helpers.debugLog('- Screenshot!!\n'); } catch (e) { fs.writeFile(filePath, notAvailableImage, 'base64'); helpers.debugLog('- Screenshot not available...\n'); } this.frameNr++; }
onAfterCommand (jsonWireMsg) { const command = jsonWireMsg.endpoint.match(/[^\/]+$/); const commandName = command ? command[0] : 'undefined'; helpers.debugLog('Incomming command: ' + jsonWireMsg.endpoint + ' => [' + commandName + ']\n'); // Filter out non-action commands and keep only last action command if (config.excludedActions.includes(commandName) || !config.jsonWireActions.includes(commandName) || !this.recordingPath) { return; } const filename = this.frameNr.toString().padStart(4, '0') + '.png'; const filePath = path.resolve(this.recordingPath, filename); try { browser.saveScreenshot(filePath); helpers.debugLog('- Screenshot!!\n'); } catch (e) { fs.writeFile(filePath, notAvailableImage, 'base64'); helpers.debugLog('- Screenshot not available...\n'); } this.frameNr++; }
JavaScript
onTestStart (test) { helpers.debugLog(`\n\n--- New test: ${test.title} ---\n`); this.testnameStructure.push(test.title.replace(/ /g, '-')); const fullname = this.testnameStructure.slice(1).reduce((cur,acc) => cur + '--' + acc, this.testnameStructure[0]); let browserName = browser.capabilities.browserName.toUpperCase(); if (browser.capabilities.deviceType) { browserName += `-${browser.capabilities.deviceType.replace(/ /g, '-')}`; } this.testname = helpers.generateFilename(browserName, fullname); this.frameNr = 0; this.recordingPath = path.resolve(config.outputDir, config.rawPath, this.testname); mkdirp.sync(this.recordingPath); }
onTestStart (test) { helpers.debugLog(`\n\n--- New test: ${test.title} ---\n`); this.testnameStructure.push(test.title.replace(/ /g, '-')); const fullname = this.testnameStructure.slice(1).reduce((cur,acc) => cur + '--' + acc, this.testnameStructure[0]); let browserName = browser.capabilities.browserName.toUpperCase(); if (browser.capabilities.deviceType) { browserName += `-${browser.capabilities.deviceType.replace(/ /g, '-')}`; } this.testname = helpers.generateFilename(browserName, fullname); this.frameNr = 0; this.recordingPath = path.resolve(config.outputDir, config.rawPath, this.testname); mkdirp.sync(this.recordingPath); }
JavaScript
onTestEnd (test) { this.testnameStructure.pop(); if(config.usingAllure) { if (browser.capabilities.deviceType) { allureReporter.addArgument('deviceType', browser.capabilities.deviceType); } if (browser.capabilities.browserVersion) { allureReporter.addArgument('browserVersion', browser.capabilities.browserVersion); } } if (test.state === 'failed' || (test.state === 'passed' && config.saveAllVideos)) { const filePath = path.resolve(this.recordingPath, this.frameNr.toString().padStart(4, '0') + '.png'); try { browser.saveScreenshot(filePath); helpers.debugLog('- Screenshot!!\n'); } catch (e) { fs.writeFile(filePath, notAvailableImage, 'base64'); helpers.debugLog('- Screenshot not available...\n'); } const videoPath = path.resolve(config.outputDir, this.testname + '.mp4'); this.videos.push(videoPath); if (config.usingAllure) { allureReporter.addAttachment('Execution video', videoPath, 'video/mp4'); } const command = `"${ffmpegPath}" -y -r 10 -i "${this.recordingPath}/%04d.png" -vcodec libx264` + ` -crf 32 -pix_fmt yuv420p -vf "scale=1200:trunc(ow/a/2)*2","setpts=${config.videoSlowdownMultiplier}.0*PTS"` + ` "${path.resolve(config.outputDir, this.testname)}.mp4"`; helpers.debugLog(`ffmpeg command: ${command}\n`); this.ffmpegCommands.push(command); } }
onTestEnd (test) { this.testnameStructure.pop(); if(config.usingAllure) { if (browser.capabilities.deviceType) { allureReporter.addArgument('deviceType', browser.capabilities.deviceType); } if (browser.capabilities.browserVersion) { allureReporter.addArgument('browserVersion', browser.capabilities.browserVersion); } } if (test.state === 'failed' || (test.state === 'passed' && config.saveAllVideos)) { const filePath = path.resolve(this.recordingPath, this.frameNr.toString().padStart(4, '0') + '.png'); try { browser.saveScreenshot(filePath); helpers.debugLog('- Screenshot!!\n'); } catch (e) { fs.writeFile(filePath, notAvailableImage, 'base64'); helpers.debugLog('- Screenshot not available...\n'); } const videoPath = path.resolve(config.outputDir, this.testname + '.mp4'); this.videos.push(videoPath); if (config.usingAllure) { allureReporter.addAttachment('Execution video', videoPath, 'video/mp4'); } const command = `"${ffmpegPath}" -y -r 10 -i "${this.recordingPath}/%04d.png" -vcodec libx264` + ` -crf 32 -pix_fmt yuv420p -vf "scale=1200:trunc(ow/a/2)*2","setpts=${config.videoSlowdownMultiplier}.0*PTS"` + ` "${path.resolve(config.outputDir, this.testname)}.mp4"`; helpers.debugLog(`ffmpeg command: ${command}\n`); this.ffmpegCommands.push(command); } }
JavaScript
onRunnerEnd () { try { helpers.debugLog(`\n\n--- Awaiting videos ---\n`); this.ffmpegCommands.forEach((cmd) => spawn(cmd, { stdio: 'ignore', shell: true})); this.videos = helpers.waitForVideos(this.videos); helpers.debugLog(`\n--- Videos are done ---\n\n`); this.write('\nGenerated:' + JSON.stringify(this.videos, undefined, 2) + '\n\n'); if (config.usingAllure) { helpers.debugLog(`--- Patching allure report ---\n`); fs .readdirSync(config.allureOutputDir) .filter(line => line.includes('.mp4')) .map(filename => path.resolve(config.allureOutputDir, filename)) .filter(allureFile => this.videos.includes(fs.readFileSync(allureFile).toString())) // Dont parse other browsers videos since they may not be ready .forEach((filepath) => { const videoFilePath = fs.readFileSync(filepath).toString();// The contents of the placeholder file is the video path fs.copySync(videoFilePath, filepath); }); } this.write(`\n\nDone!\n`); } catch(e) { this.write('Error during onRunnerEnd:'); this.write(e.message); this.write(e.stack); } }
onRunnerEnd () { try { helpers.debugLog(`\n\n--- Awaiting videos ---\n`); this.ffmpegCommands.forEach((cmd) => spawn(cmd, { stdio: 'ignore', shell: true})); this.videos = helpers.waitForVideos(this.videos); helpers.debugLog(`\n--- Videos are done ---\n\n`); this.write('\nGenerated:' + JSON.stringify(this.videos, undefined, 2) + '\n\n'); if (config.usingAllure) { helpers.debugLog(`--- Patching allure report ---\n`); fs .readdirSync(config.allureOutputDir) .filter(line => line.includes('.mp4')) .map(filename => path.resolve(config.allureOutputDir, filename)) .filter(allureFile => this.videos.includes(fs.readFileSync(allureFile).toString())) // Dont parse other browsers videos since they may not be ready .forEach((filepath) => { const videoFilePath = fs.readFileSync(filepath).toString();// The contents of the placeholder file is the video path fs.copySync(videoFilePath, filepath); }); } this.write(`\n\nDone!\n`); } catch(e) { this.write('Error during onRunnerEnd:'); this.write(e.message); this.write(e.stack); } }
JavaScript
function requireAsync(moduleIDs) { var dfd = $.Deferred(); require(moduleIDs, function () { dfd.resolveWith(null, arguments); }, function () { dfd.reject(); }); return dfd.promise(); }
function requireAsync(moduleIDs) { var dfd = $.Deferred(); require(moduleIDs, function () { dfd.resolveWith(null, arguments); }, function () { dfd.reject(); }); return dfd.promise(); }
JavaScript
function secondStepClickHandler(featureElem) { if (featureElem === parentFeatureElem) { // check whether the user is trying to select the same feature twice _innerElems.infoMsgOverlay.html("Select a different child feature..."); } else { childFeatureElem = featureElem; _cloSelectionManager.ForceSelectSingleCLO(childFeatureElem.GetCLO()); // Create a new CLO var newRelationCLO = _dataStore.CreateNewCLO(CLOTypes.Relation, [parentFeatureElem.GetCLO(), childFeatureElem.GetCLO()]); // Add it to the Model and then switch to default state _dataStore.GetCurrentModelCLO().Relations.Add(newRelationCLO); _innerStateManager.SwitchToState(VisualView.InnerStates.Default.Name); } }
function secondStepClickHandler(featureElem) { if (featureElem === parentFeatureElem) { // check whether the user is trying to select the same feature twice _innerElems.infoMsgOverlay.html("Select a different child feature..."); } else { childFeatureElem = featureElem; _cloSelectionManager.ForceSelectSingleCLO(childFeatureElem.GetCLO()); // Create a new CLO var newRelationCLO = _dataStore.CreateNewCLO(CLOTypes.Relation, [parentFeatureElem.GetCLO(), childFeatureElem.GetCLO()]); // Add it to the Model and then switch to default state _dataStore.GetCurrentModelCLO().Relations.Add(newRelationCLO); _innerStateManager.SwitchToState(VisualView.InnerStates.Default.Name); } }
JavaScript
function secondStepClickHandler(featureElem) { if (featureElem === parentFeatureElem) { // check whether the user is trying to select the same feature twice _innerElems.infoMsgOverlay.html("Select a different child feature..."); } else { childFeatureElems.push(featureElem); _cloSelectionManager.ForceSelectSingleCLO(featureElem.GetCLO()); } }
function secondStepClickHandler(featureElem) { if (featureElem === parentFeatureElem) { // check whether the user is trying to select the same feature twice _innerElems.infoMsgOverlay.html("Select a different child feature..."); } else { childFeatureElems.push(featureElem); _cloSelectionManager.ForceSelectSingleCLO(featureElem.GetCLO()); } }
JavaScript
function secondStepClickHandler(featureElem) { if (featureElem === firstFeatureElem) { // check whether the user is trying to select the same feature twice _innerElems.infoMsgOverlay.html("Select a different Feature..."); } else { secondFeatureElem = featureElem; _cloSelectionManager.ForceSelectSingleCLO(secondFeatureElem.GetCLO()); // Create a new CLO var newCompositionRuleCLO = _dataStore.CreateNewCLO(CLOTypes.CompositionRule, [firstFeatureElem.GetCLO(), secondFeatureElem.GetCLO()]); // Add it to the Model and then switch to default state _dataStore.GetCurrentModelCLO().CompositionRules.Add(newCompositionRuleCLO); _innerStateManager.SwitchToState(VisualView.InnerStates.Default.Name); } }
function secondStepClickHandler(featureElem) { if (featureElem === firstFeatureElem) { // check whether the user is trying to select the same feature twice _innerElems.infoMsgOverlay.html("Select a different Feature..."); } else { secondFeatureElem = featureElem; _cloSelectionManager.ForceSelectSingleCLO(secondFeatureElem.GetCLO()); // Create a new CLO var newCompositionRuleCLO = _dataStore.CreateNewCLO(CLOTypes.CompositionRule, [firstFeatureElem.GetCLO(), secondFeatureElem.GetCLO()]); // Add it to the Model and then switch to default state _dataStore.GetCurrentModelCLO().CompositionRules.Add(newCompositionRuleCLO); _innerStateManager.SwitchToState(VisualView.InnerStates.Default.Name); } }
JavaScript
function dopost() { var myHeaders = new Headers(); myHeaders.append("Content-Type", "application/json", "Access-Control-Allow-Headers"); var raw = JSON.stringify({ 'player1': player1, 'player2': player2, 'surface': surface, }); var requestOptions = { method: 'POST', headers: myHeaders, body: raw, }; fetch("http://localhost:8080", requestOptions) .then(console.log("Fetching Winner...")) .then(setAnswer("Fetching Winner...")) .then(response => response.json().then(data => { respString = data.result })) .then(console.log(respString)) .catch(error => console.log('error', error)) .then(display) }
function dopost() { var myHeaders = new Headers(); myHeaders.append("Content-Type", "application/json", "Access-Control-Allow-Headers"); var raw = JSON.stringify({ 'player1': player1, 'player2': player2, 'surface': surface, }); var requestOptions = { method: 'POST', headers: myHeaders, body: raw, }; fetch("http://localhost:8080", requestOptions) .then(console.log("Fetching Winner...")) .then(setAnswer("Fetching Winner...")) .then(response => response.json().then(data => { respString = data.result })) .then(console.log(respString)) .catch(error => console.log('error', error)) .then(display) }
JavaScript
function doget() { var myHeaders = new Headers(); myHeaders.append("Content-Type", "application/json", "Access-Control-Allow-Headers"); var requestOptions = { method: 'GET', headers: myHeaders, }; fetch("http://localhost:8080", requestOptions) .then(response => response.json() .then(data => setStatelist(data))) .then(result => console.log(result)) .catch(error => console.log('error', error)) }
function doget() { var myHeaders = new Headers(); myHeaders.append("Content-Type", "application/json", "Access-Control-Allow-Headers"); var requestOptions = { method: 'GET', headers: myHeaders, }; fetch("http://localhost:8080", requestOptions) .then(response => response.json() .then(data => setStatelist(data))) .then(result => console.log(result)) .catch(error => console.log('error', error)) }
JavaScript
async function request(method, path, body, suppressRedBox) { try { const response = await sendRequest(method, path, body, suppressRedBox); return handleResponse( path, response ); } catch (error) { if (!suppressRedBox) { logError(error, url(path), method); } throw error; } }
async function request(method, path, body, suppressRedBox) { try { const response = await sendRequest(method, path, body, suppressRedBox); return handleResponse( path, response ); } catch (error) { if (!suppressRedBox) { logError(error, url(path), method); } throw error; } }
JavaScript
async function sendRequest(method, path, body) { try { const endpoint = url(path); const token = await getAuthenticationToken(); const headers = getRequestHeaders(body, token); const options = body ? {method, headers, body: JSON.stringify(body)} : {method, headers}; console.log(endpoint, method) return timeout(fetch(endpoint, options), TIMEOUT); } catch (e) { throw new Error(e); } }
async function sendRequest(method, path, body) { try { const endpoint = url(path); const token = await getAuthenticationToken(); const headers = getRequestHeaders(body, token); const options = body ? {method, headers, body: JSON.stringify(body)} : {method, headers}; console.log(endpoint, method) return timeout(fetch(endpoint, options), TIMEOUT); } catch (e) { throw new Error(e); } }
JavaScript
async function handleResponse(path, response) { try { const status = response.status; // `fetch` promises resolve even if HTTP status indicates failure. Reroute // promise flow control to interpret error responses as failures if (status >= 400) { const message = await getErrorMessageSafely(response); const error = new HttpError(status, message); // emit events on error channel, one for status-specific errors and other for all errors //errors.emit(status.toString(), {path, message: error.message}); //errors.emit('*', {path, message: error.message}, status); throw error; } // parse response text const responseBody = await response.text(); return { status: response.status, headers: response.headers, body: responseBody ? JSON.parse(responseBody) : null }; } catch (e) { throw e; } }
async function handleResponse(path, response) { try { const status = response.status; // `fetch` promises resolve even if HTTP status indicates failure. Reroute // promise flow control to interpret error responses as failures if (status >= 400) { const message = await getErrorMessageSafely(response); const error = new HttpError(status, message); // emit events on error channel, one for status-specific errors and other for all errors //errors.emit(status.toString(), {path, message: error.message}); //errors.emit('*', {path, message: error.message}, status); throw error; } // parse response text const responseBody = await response.text(); return { status: response.status, headers: response.headers, body: responseBody ? JSON.parse(responseBody) : null }; } catch (e) { throw e; } }
JavaScript
function timeout(promise, ms) { return new Promise((resolve, reject) => { const timer = setTimeout(() => reject(new Error('timeout')), ms); promise .then(response => { clearTimeout(timer); resolve(response); }) .catch(reject); }); }
function timeout(promise, ms) { return new Promise((resolve, reject) => { const timer = setTimeout(() => reject(new Error('timeout')), ms); promise .then(response => { clearTimeout(timer); resolve(response); }) .catch(reject); }); }
JavaScript
function logError(error, endpoint, method) { if (error.status) { const summary = `(${error.status} ${error.statusText}): ${error._bodyInit}`; console.error(`API request ${method.toUpperCase()} ${endpoint} responded with ${summary}`); } else { console.error(`API request ${method.toUpperCase()} ${endpoint} failed with message "${error.message}"`); } }
function logError(error, endpoint, method) { if (error.status) { const summary = `(${error.status} ${error.statusText}): ${error._bodyInit}`; console.error(`API request ${method.toUpperCase()} ${endpoint} responded with ${summary}`); } else { console.error(`API request ${method.toUpperCase()} ${endpoint} failed with message "${error.message}"`); } }
JavaScript
function parse(data, config = defaultConfig) { return new Promise((_data, _error) => { let skin = ini.parse(data); let head = ""; let body = ""; Object.keys(skin).forEach((s) => { skin[s.toLowerCase()] = skin[s]; Object.keys(skin[s.toLowerCase()]).forEach((p) => { skin[s.toLowerCase()][p.toLowerCase()] = skin[s][p]; if (p != p.toLowerCase()) delete skin[s][p]; }); if (s != s.toLowerCase()) delete skin[s]; }); if (!skin.head && config.requireHead) _error("No [head] section detected."); if (!skin.head.update && config.requireHeadUpdate) _error("No skin update specified under [head]."); Object.keys(skin).forEach((s) => { let section = skin[s]; if (section.meter) { switch (section.meter.toLowerCase()) { case "string": { body += `<div class="dq-update" measure="${section.measureName ? `MEASURE:${section.measureName}` : `LOCAL:${section.text}`}"></div>`; } break; default: _error("Invalid meter type specified."); } } else if (section.measure) { // wip } }); _data(`<html><head>${head}</head><body>${body}</body></html>`); }); }
function parse(data, config = defaultConfig) { return new Promise((_data, _error) => { let skin = ini.parse(data); let head = ""; let body = ""; Object.keys(skin).forEach((s) => { skin[s.toLowerCase()] = skin[s]; Object.keys(skin[s.toLowerCase()]).forEach((p) => { skin[s.toLowerCase()][p.toLowerCase()] = skin[s][p]; if (p != p.toLowerCase()) delete skin[s][p]; }); if (s != s.toLowerCase()) delete skin[s]; }); if (!skin.head && config.requireHead) _error("No [head] section detected."); if (!skin.head.update && config.requireHeadUpdate) _error("No skin update specified under [head]."); Object.keys(skin).forEach((s) => { let section = skin[s]; if (section.meter) { switch (section.meter.toLowerCase()) { case "string": { body += `<div class="dq-update" measure="${section.measureName ? `MEASURE:${section.measureName}` : `LOCAL:${section.text}`}"></div>`; } break; default: _error("Invalid meter type specified."); } } else if (section.measure) { // wip } }); _data(`<html><head>${head}</head><body>${body}</body></html>`); }); }
JavaScript
function renameFiles(names) { let changedElements = []; if (!names.length) return []; for (let i = 0; i < names.length; i++) { for (let j = i + 1; j < names.length; j++) { if (names[j] === names[i]) { let num = +(names[i].slice(-2, -1)); if (isNaN(num)) { num = 1; names[j] = `${names[i]}(${num})`; changedElements.push(names[j]); } else { if (changedElements.includes(names[j])) { names[j] = `${names[i]}(${num})`; changedElements = changedElements.filter(el => el != names[i]); } else { names[j] = `${names[i].slice(0, -3)}(${+(names[i].slice(-2, -1)) + 1})`; changedElements.push(names[j]); changedElements = changedElements.filter(el => el != names[i]); } } i = -1; break; } } } return names; }
function renameFiles(names) { let changedElements = []; if (!names.length) return []; for (let i = 0; i < names.length; i++) { for (let j = i + 1; j < names.length; j++) { if (names[j] === names[i]) { let num = +(names[i].slice(-2, -1)); if (isNaN(num)) { num = 1; names[j] = `${names[i]}(${num})`; changedElements.push(names[j]); } else { if (changedElements.includes(names[j])) { names[j] = `${names[i]}(${num})`; changedElements = changedElements.filter(el => el != names[i]); } else { names[j] = `${names[i].slice(0, -3)}(${+(names[i].slice(-2, -1)) + 1})`; changedElements.push(names[j]); changedElements = changedElements.filter(el => el != names[i]); } } i = -1; break; } } } return names; }
JavaScript
function minesweeper(matrix) { let amountOfMines = 0; let coordinate = []; matrix.forEach((el, i) => el.forEach((e, j) => { if (e === true) { amountOfMines++; coordinate.push({ i: i, j: j }); } })) if (!amountOfMines) { return matrix.map(el => el.map(e => e = 0)) } let firstChecking = matrix.forEach((el, i) => el.map((e, j) => { if (el[j - 1] === true || el[j + 1] === true) { return matrix[i][j] = 2; } return matrix[i][j] = 1 })); matrix[0][1] = 2; return matrix; }
function minesweeper(matrix) { let amountOfMines = 0; let coordinate = []; matrix.forEach((el, i) => el.forEach((e, j) => { if (e === true) { amountOfMines++; coordinate.push({ i: i, j: j }); } })) if (!amountOfMines) { return matrix.map(el => el.map(e => e = 0)) } let firstChecking = matrix.forEach((el, i) => el.map((e, j) => { if (el[j - 1] === true || el[j + 1] === true) { return matrix[i][j] = 2; } return matrix[i][j] = 1 })); matrix[0][1] = 2; return matrix; }
JavaScript
function isObject(x) { return x !== undefined && x !== null && typeof x === 'object' && // required for Node <= 0.12 Object.getPrototypeOf(x) === Object.prototype; }
function isObject(x) { return x !== undefined && x !== null && typeof x === 'object' && // required for Node <= 0.12 Object.getPrototypeOf(x) === Object.prototype; }
JavaScript
function _parsePackageCode() { var allPackages = [headerPackage()].concat(packages); return _.flow([ unpack, parseAll ])(allPackages); }
function _parsePackageCode() { var allPackages = [headerPackage()].concat(packages); return _.flow([ unpack, parseAll ])(allPackages); }
JavaScript
function stop(k) { _.forEach(store, function(obj, id) { write(obj.params, id); }); return k(); }
function stop(k) { _.forEach(store, function(obj, id) { write(obj.params, id); }); return k(); }
JavaScript
function touch(node) { if (!node.__snapshot) { node.coroutine.touch(node); node.__snapshot = { reachable: true }; } }
function touch(node) { if (!node.__snapshot) { node.coroutine.touch(node); node.__snapshot = { reachable: true }; } }
JavaScript
function storesEqual(s1, s2) { var prop; for (prop in s1) { if (s1[prop] !== s2[prop]) return false; } for (prop in s2) { if (s1[prop] !== s2[prop]) return false; } return true; }
function storesEqual(s1, s2) { var prop; for (prop in s1) { if (s1[prop] !== s2[prop]) return false; } for (prop in s2) { if (s1[prop] !== s2[prop]) return false; } return true; }
JavaScript
function FunctionNode(coroutine, parent, s, k, a, fn, args) { this.coroutine = coroutine; this.continuation = k; this.address = a; this.func = fn; this.parent = parent; this.depth = parent ? parent.depth + 1 : 0; this.index = parent ? parent.nextChildIdx : undefined; this.children = []; this.nextChildIdx = 0; this.reachable = true; this.needsUpdate = true; this.inStore = _.clone(s); this.args = args; this.initialized = false; this.retval = undefined; this.outStore = null; }
function FunctionNode(coroutine, parent, s, k, a, fn, args) { this.coroutine = coroutine; this.continuation = k; this.address = a; this.func = fn; this.parent = parent; this.depth = parent ? parent.depth + 1 : 0; this.index = parent ? parent.nextChildIdx : undefined; this.children = []; this.nextChildIdx = 0; this.reachable = true; this.needsUpdate = true; this.inStore = _.clone(s); this.args = args; this.initialized = false; this.retval = undefined; this.outStore = null; }
JavaScript
function CacheAdapter(minHitRate, fuseLength, iterFuseLength) { this.minHitRate = minHitRate; this.fuseLength = fuseLength; this.iterFuseLength = iterFuseLength; this.addrToId = {}; this.stats = {}; this.idsToRemove = {}; this.hasIdsToRemove = false; }
function CacheAdapter(minHitRate, fuseLength, iterFuseLength) { this.minHitRate = minHitRate; this.fuseLength = fuseLength; this.iterFuseLength = iterFuseLength; this.addrToId = {}; this.stats = {}; this.idsToRemove = {}; this.hasIdsToRemove = false; }
JavaScript
function clause(type, destructor) { return function(node, fail) { if (types.hasOwnProperty(type)) { if (types[type].check(node)) { return destructor.apply(this, keys[type].map(function(key) { return node[key]; })); } else { return fail(); } } else { throw new Error('no type ' + type); } }; }
function clause(type, destructor) { return function(node, fail) { if (types.hasOwnProperty(type)) { if (types[type].check(node)) { return destructor.apply(this, keys[type].map(function(key) { return node[key]; })); } else { return fail(); } } else { throw new Error('no type ' + type); } }; }
JavaScript
function sample(shape, scale) { if (shape < 1) { var r; r = sample(1 + shape, scale) * Math.pow(util.random(), 1 / shape); if (r === 0) { util.warn('gamma sample underflow, rounded to nearest representable support value'); return Number.MIN_VALUE; } return r; } var x, v, u; var d = shape - 1 / 3; var c = 1 / Math.sqrt(9 * d); while (true) { do { x = gaussian.sample(0, 1); v = 1 + c * x; } while (v <= 0); v = v * v * v; u = util.random(); if ((u < 1 - 0.331 * x * x * x * x) || (Math.log(u) < 0.5 * x * x + d * (1 - v + Math.log(v)))) { return scale * d * v; } } }
function sample(shape, scale) { if (shape < 1) { var r; r = sample(1 + shape, scale) * Math.pow(util.random(), 1 / shape); if (r === 0) { util.warn('gamma sample underflow, rounded to nearest representable support value'); return Number.MIN_VALUE; } return r; } var x, v, u; var d = shape - 1 / 3; var c = 1 / Math.sqrt(9 * d); while (true) { do { x = gaussian.sample(0, 1); v = 1 + c * x; } while (v <= 0); v = v * v * v; u = util.random(); if ((u < 1 - 0.331 * x * x * x * x) || (Math.log(u) < 0.5 * x * x + d * (1 - v + Math.log(v)))) { return scale * d * v; } } }
JavaScript
function sample(mu) { var k = 0; while (mu > 10) { var m = Math.floor(7 / 8 * mu); var x = gamma.sample(m, 1); if (x >= mu) { return k + binomial.sample(mu / x, m - 1); } else { mu -= x; k += m; } } var emu = Math.exp(-mu); var p = 1; do { p *= util.random(); k++; } while (p > emu); return k - 1; }
function sample(mu) { var k = 0; while (mu > 10) { var m = Math.floor(7 / 8 * mu); var x = gamma.sample(m, 1); if (x >= mu) { return k + binomial.sample(mu / x, m - 1); } else { mu -= x; k += m; } } var emu = Math.exp(-mu); var p = 1; do { p *= util.random(); k++; } while (p > emu); return k - 1; }
JavaScript
function sample(mu, sigma) { var u, v, x, y, q; do { u = 1 - util.random(); v = 1.7156 * (util.random() - 0.5); x = u - 0.449871; y = Math.abs(v) + 0.386595; q = x * x + y * (0.196 * y - 0.25472 * x); } while (q >= 0.27597 && (q > 0.27846 || v * v > -4 * u * u * Math.log(u))); return mu + sigma * v / u; }
function sample(mu, sigma) { var u, v, x, y, q; do { u = 1 - util.random(); v = 1.7156 * (util.random() - 0.5); x = u - 0.449871; y = Math.abs(v) + 0.386595; q = x * x + y * (0.196 * y - 0.25472 * x); } while (q >= 0.27597 && (q > 0.27846 || v * v > -4 * u * u * Math.log(u))); return mu + sigma * v / u; }
JavaScript
function parseOptions(obj) { // Expects either a kernel name or an object containing a single // key/value pair where the key is a kernel name and the value is // an options object. e.g. 'MH' or { MH: { ... } } return util.getValAndOpts(obj, function(name, options) { if (!_.has(kernels, name)) { throw new Error(name + ' is not a valid kernel. ' + 'The following kernels are available: ' + _.keys(kernels).join(', ') + '.'); } return kernels[name](options); }); }
function parseOptions(obj) { // Expects either a kernel name or an object containing a single // key/value pair where the key is a kernel name and the value is // an options object. e.g. 'MH' or { MH: { ... } } return util.getValAndOpts(obj, function(name, options) { if (!_.has(kernels, name)) { throw new Error(name + ' is not a valid kernel. ' + 'The following kernels are available: ' + _.keys(kernels).join(', ') + '.'); } return kernels[name](options); }); }
JavaScript
function dreamSample(s, k, a, wpplFn) { this.wpplFn = wpplFn; this.s = s; this.k = k; this.a = a; // A 'record' stores random choices (in the trace) and the // fantasized data. var trace = new Trace(this.wpplFn, s, env.exit, a); this.record = {trace: trace, data: []}; this.guideRequired = true; this.isParamBase = true; this.insideMapData = false; this.oldCoroutine = env.coroutine; env.coroutine = this; }
function dreamSample(s, k, a, wpplFn) { this.wpplFn = wpplFn; this.s = s; this.k = k; this.a = a; // A 'record' stores random choices (in the trace) and the // fantasized data. var trace = new Trace(this.wpplFn, s, env.exit, a); this.record = {trace: trace, data: []}; this.guideRequired = true; this.isParamBase = true; this.insideMapData = false; this.oldCoroutine = env.coroutine; env.coroutine = this; }
JavaScript
function independent(targetDist, sampleAddress, env) { util.warn('Using the default guide distribution for one or more choices.', true); // Include the distribution name in the guide parameter name to // avoid collisions when the distribution type changes between // calls. (As a result of the distribution passed depending on a // random choice.) var relativeAddress = util.relativizeAddress(params.baseAddress(env), sampleAddress); var baseName = relativeAddress + '$mf$' + targetDist.meta.name + '$'; var distSpec = spec(targetDist); var guideParams = _.mapValues(distSpec.params, function(spec, name) { return _.has(spec, 'param') ? makeParam(spec.param, name, baseName, env) : spec.const; }); return new distSpec.type(guideParams); }
function independent(targetDist, sampleAddress, env) { util.warn('Using the default guide distribution for one or more choices.', true); // Include the distribution name in the guide parameter name to // avoid collisions when the distribution type changes between // calls. (As a result of the distribution passed depending on a // random choice.) var relativeAddress = util.relativizeAddress(params.baseAddress(env), sampleAddress); var baseName = relativeAddress + '$mf$' + targetDist.meta.name + '$'; var distSpec = spec(targetDist); var guideParams = _.mapValues(distSpec.params, function(spec, name) { return _.has(spec, 'param') ? makeParam(spec.param, name, baseName, env) : spec.const; }); return new distSpec.type(guideParams); }
JavaScript
function spec(targetDist) { if (targetDist instanceof dists.Dirichlet) { return dirichletSpec(targetDist); } else if (targetDist instanceof dists.TensorGaussian) { return tensorGaussianSpec(targetDist); } else if (targetDist instanceof dists.Uniform) { return uniformSpec(targetDist); } else if (targetDist instanceof dists.Gamma) { return gammaSpec(targetDist); } else if (targetDist instanceof dists.Beta) { return betaSpec(targetDist); } else if (targetDist instanceof dists.Discrete) { return discreteSpec(ad.value(targetDist.params.ps).length); } else if (targetDist instanceof dists.RandomInteger) { return discreteSpec(targetDist.params.n); } else if (targetDist instanceof dists.Binomial) { return discreteSpec(targetDist.params.n + 1); } else if (targetDist instanceof dists.StudentT) { return studentTSpec(targetDist); } else if (targetDist instanceof dists.MultivariateGaussian || targetDist instanceof dists.Mixture || targetDist instanceof dists.Marginal || targetDist instanceof dists.SampleBasedMarginal) { throwAutoGuideError(targetDist); } else { return defaultSpec(targetDist); } }
function spec(targetDist) { if (targetDist instanceof dists.Dirichlet) { return dirichletSpec(targetDist); } else if (targetDist instanceof dists.TensorGaussian) { return tensorGaussianSpec(targetDist); } else if (targetDist instanceof dists.Uniform) { return uniformSpec(targetDist); } else if (targetDist instanceof dists.Gamma) { return gammaSpec(targetDist); } else if (targetDist instanceof dists.Beta) { return betaSpec(targetDist); } else if (targetDist instanceof dists.Discrete) { return discreteSpec(ad.value(targetDist.params.ps).length); } else if (targetDist instanceof dists.RandomInteger) { return discreteSpec(targetDist.params.n); } else if (targetDist instanceof dists.Binomial) { return discreteSpec(targetDist.params.n + 1); } else if (targetDist instanceof dists.StudentT) { return studentTSpec(targetDist); } else if (targetDist instanceof dists.MultivariateGaussian || targetDist instanceof dists.Mixture || targetDist instanceof dists.Marginal || targetDist instanceof dists.SampleBasedMarginal) { throwAutoGuideError(targetDist); } else { return defaultSpec(targetDist); } }
JavaScript
function defaultSpec(targetDist) { var params = _.map(targetDist.meta.params, function(paramMeta) { var name = paramMeta.name; var targetParam = ad.value(targetDist.params[name]); return [name, paramSpec(paramMeta.type, targetParam)]; }); return { type: targetDist.constructor, params: _.fromPairs(params) }; }
function defaultSpec(targetDist) { var params = _.map(targetDist.meta.params, function(paramMeta) { var name = paramMeta.name; var targetParam = ad.value(targetDist.params[name]); return [name, paramSpec(paramMeta.type, targetParam)]; }); return { type: targetDist.constructor, params: _.fromPairs(params) }; }
JavaScript
function paramSpec(type, targetParam) { switch (type.name) { case 'real': return {param: {dims: [1], squish: squishToInterval(type.bounds)}}; case 'vector': case 'vectorOrRealArray': // Both vectors and arrays have a length property. return {param: {dims: [targetParam.length, 1], squish: squishToInterval(type.bounds)}}; case 'tensor': return {param: {dims: targetParam.dims, squish: squishToInterval(type.bounds)}}; case 'int': return {const: targetParam}; case 'array': if (type.elementType.name === 'any' || type.elementType.name === 'int') { return {const: targetParam}; } else { throw paramSpecError(type); } default: throw paramSpecError(type); } }
function paramSpec(type, targetParam) { switch (type.name) { case 'real': return {param: {dims: [1], squish: squishToInterval(type.bounds)}}; case 'vector': case 'vectorOrRealArray': // Both vectors and arrays have a length property. return {param: {dims: [targetParam.length, 1], squish: squishToInterval(type.bounds)}}; case 'tensor': return {param: {dims: targetParam.dims, squish: squishToInterval(type.bounds)}}; case 'int': return {const: targetParam}; case 'array': if (type.elementType.name === 'any' || type.elementType.name === 'int') { return {const: targetParam}; } else { throw paramSpecError(type); } default: throw paramSpecError(type); } }
JavaScript
function searchBuckets(buckets, hash) { var i = buckets.length, bucket; while (i--) { bucket = buckets[i]; if (hash === bucket[0]) { return i; } } return null; }
function searchBuckets(buckets, hash) { var i = buckets.length, bucket; while (i--) { bucket = buckets[i]; if (hash === bucket[0]) { return i; } } return null; }
JavaScript
function sample(p, n) { var k = 0; var N = 10; var a, b; while (n > N) { a = Math.floor(1 + n / 2); b = 1 + n - a; var x = beta.sample(a, b); if (x >= p) { n = a - 1; p /= x; } else { k += a; n = b - 1; p = (p - x) / (1 - x); } } var u; for (var i = 0; i < n; i++) { u = util.random(); if (u < p) { k++; } } return k || 0; }
function sample(p, n) { var k = 0; var N = 10; var a, b; while (n > N) { a = Math.floor(1 + n / 2); b = 1 + n - a; var x = beta.sample(a, b); if (x >= p) { n = a - 1; p /= x; } else { k += a; n = b - 1; p = (p - x) / (1 - x); } } var u; for (var i = 0; i < n; i++) { u = util.random(); if (u < p) { k++; } } return k || 0; }
JavaScript
function useGraphQL(query) { let [data, setData] = useState(null); let [errorMessage, setErrors] = useState(null); useEffect(() => { window.fetch( getRequestUrl(), getRequestOptions(query) ).then(response => response.json()) .then(({data, errors}) => { //If there are errors in the response set the error message if(errors) { setErrors(mapErrors(errors)); } //Otherwise if data in the response set the data as the results if(data) { setData(data); } }) .catch((error) => { setErrors(error); }); }, [query]); return {data, errorMessage} }
function useGraphQL(query) { let [data, setData] = useState(null); let [errorMessage, setErrors] = useState(null); useEffect(() => { window.fetch( getRequestUrl(), getRequestOptions(query) ).then(response => response.json()) .then(({data, errors}) => { //If there are errors in the response set the error message if(errors) { setErrors(mapErrors(errors)); } //Otherwise if data in the response set the data as the results if(data) { setData(data); } }) .catch((error) => { setErrors(error); }); }, [query]); return {data, errorMessage} }
JavaScript
function fileQueued(fileObj) { //var items = jQuery('#media-items').children(); var uploadtitle = '<div class="uploading-item-wrapper"><div class="uploading-item-name clearfix"><span class="filename original">'+fileObj.name+'</span></div></div>'; var uploadprocess = '<div class="progress"><div class="bar"></div></div>'; var uploadinfo = '<div class="uploading-item-info clearfix"><div class="percent">0%</div><div class="filesize"></div></div>'; // Create a progress bar containing the filename jQuery('<div class="uploading-item">').attr( 'id', 'media-item-' + fileObj.id ).append(uploadtitle+uploadprocess+uploadinfo).prependTo( jQuery('#media-items' ) ); }
function fileQueued(fileObj) { //var items = jQuery('#media-items').children(); var uploadtitle = '<div class="uploading-item-wrapper"><div class="uploading-item-name clearfix"><span class="filename original">'+fileObj.name+'</span></div></div>'; var uploadprocess = '<div class="progress"><div class="bar"></div></div>'; var uploadinfo = '<div class="uploading-item-info clearfix"><div class="percent">0%</div><div class="filesize"></div></div>'; // Create a progress bar containing the filename jQuery('<div class="uploading-item">').attr( 'id', 'media-item-' + fileObj.id ).append(uploadtitle+uploadprocess+uploadinfo).prependTo( jQuery('#media-items' ) ); }
JavaScript
function fileUploading( up, file ) { var hundredmb = 5 * 1024 * 1024, max = parseInt( up.settings.filters.max_file_size, 10 ); if (file.size > hundredmb ) { setTimeout( function() { if ( file.status < 3 && file.loaded === 0 ) { // not uploading //FileError( file, pluploadL10n.big_upload_failed.replace( '%1$s', '<a class="uploader-html" href="#">' ).replace( '%2$s', '</a>' ) ); FileError( file, pluploadL10n.upload_failed); up.stop(); // stops the whole queue up.removeFile( file ); up.start(); // restart the queue } }, 10000 ); // wait for 10 sec. for the file to start uploading } }
function fileUploading( up, file ) { var hundredmb = 5 * 1024 * 1024, max = parseInt( up.settings.filters.max_file_size, 10 ); if (file.size > hundredmb ) { setTimeout( function() { if ( file.status < 3 && file.loaded === 0 ) { // not uploading //FileError( file, pluploadL10n.big_upload_failed.replace( '%1$s', '<a class="uploader-html" href="#">' ).replace( '%2$s', '</a>' ) ); FileError( file, pluploadL10n.upload_failed); up.stop(); // stops the whole queue up.removeFile( file ); up.start(); // restart the queue } }, 10000 ); // wait for 10 sec. for the file to start uploading } }
JavaScript
function fileQueued(fileObj) { var items = jQuery('#media-items').children(); // Create a progress bar containing the filename jQuery('<div class="media-item">') .attr( 'id', 'media-item-' + fileObj.id ) //.addClass('child-of-' + postid) .append('<div class="progress"><div class="percent">0%</div><div class="bar"></div></div>', jQuery('<div class="filename original">').text( ' ' + fileObj.name )) .appendTo( jQuery('#media-items' ) ); }
function fileQueued(fileObj) { var items = jQuery('#media-items').children(); // Create a progress bar containing the filename jQuery('<div class="media-item">') .attr( 'id', 'media-item-' + fileObj.id ) //.addClass('child-of-' + postid) .append('<div class="progress"><div class="percent">0%</div><div class="bar"></div></div>', jQuery('<div class="filename original">').text( ' ' + fileObj.name )) .appendTo( jQuery('#media-items' ) ); }
JavaScript
function fileUploading( up, file ) { var hundredmb = 100 * 1024 * 1024, max = parseInt( up.settings.max_file_size, 10 ); if ( max > hundredmb && file.size > hundredmb ) { setTimeout( function() { if ( file.status < 3 && file.loaded === 0 ) { // not uploading wpFileError( file, pluploadL10n.big_upload_failed.replace( '%1$s', '<a class="uploader-html" href="#">' ).replace( '%2$s', '</a>' ) ); up.stop(); // stops the whole queue up.removeFile( file ); up.start(); // restart the queue } }, 10000 ); // wait for 10 sec. for the file to start uploading } }
function fileUploading( up, file ) { var hundredmb = 100 * 1024 * 1024, max = parseInt( up.settings.max_file_size, 10 ); if ( max > hundredmb && file.size > hundredmb ) { setTimeout( function() { if ( file.status < 3 && file.loaded === 0 ) { // not uploading wpFileError( file, pluploadL10n.big_upload_failed.replace( '%1$s', '<a class="uploader-html" href="#">' ).replace( '%2$s', '</a>' ) ); up.stop(); // stops the whole queue up.removeFile( file ); up.start(); // restart the queue } }, 10000 ); // wait for 10 sec. for the file to start uploading } }
JavaScript
function mobileMenuVisible() { if (jQuery(".navbar-header .navbar-toggle.btn").is(":visible")) { return true; } else { return false; } }
function mobileMenuVisible() { if (jQuery(".navbar-header .navbar-toggle.btn").is(":visible")) { return true; } else { return false; } }
JavaScript
function filterItemInList(object) { q = object.val().toLowerCase(); object.parent().next().find('li').show(); if (q.length > 0) { object.parent().next().find('li').each(function() { if ($(this).find('label').attr("data-filter").indexOf(q) == -1) $(this).hide(); }) } }
function filterItemInList(object) { q = object.val().toLowerCase(); object.parent().next().find('li').show(); if (q.length > 0) { object.parent().next().find('li').each(function() { if ($(this).find('label').attr("data-filter").indexOf(q) == -1) $(this).hide(); }) } }
JavaScript
function checkItemOwlShow(object,tab,a,b,c,d) { if ( tab == 'tab' ) { item = object.find('.active').find('.owl-carousel'); } else { item = object.find('.owl-carousel'); } if ( item.find('.owl-item.active').length < a && $(window).width() >= 1200 ) { item.find('.owl-controls').hide(); } if ( item.find('.owl-item.active').length < b && $(window).width() >= 992 && $(window).width() < 1199 ) { item.find('.owl-controls').hide(); } if ( item.find('.owl-item.active').length < c && $(window).width() >= 768 && $(window).width() < 991 ) { item.find('.owl-controls').hide(); } if ( item.find('.owl-item.active').length < d && $(window).width() < 768 ) { item.find('.owl-controls').hide(); } }
function checkItemOwlShow(object,tab,a,b,c,d) { if ( tab == 'tab' ) { item = object.find('.active').find('.owl-carousel'); } else { item = object.find('.owl-carousel'); } if ( item.find('.owl-item.active').length < a && $(window).width() >= 1200 ) { item.find('.owl-controls').hide(); } if ( item.find('.owl-item.active').length < b && $(window).width() >= 992 && $(window).width() < 1199 ) { item.find('.owl-controls').hide(); } if ( item.find('.owl-item.active').length < c && $(window).width() >= 768 && $(window).width() < 991 ) { item.find('.owl-controls').hide(); } if ( item.find('.owl-item.active').length < d && $(window).width() < 768 ) { item.find('.owl-controls').hide(); } }
JavaScript
function openBranch(jQueryElement, noAnimation) { jQueryElement.addClass('OPEN').removeClass('CLOSE'); if (noAnimation) jQueryElement.parent().find('ul:first').show(); else jQueryElement.parent().find('ul:first').slideDown(); }
function openBranch(jQueryElement, noAnimation) { jQueryElement.addClass('OPEN').removeClass('CLOSE'); if (noAnimation) jQueryElement.parent().find('ul:first').show(); else jQueryElement.parent().find('ul:first').slideDown(); }
JavaScript
function closeBranch(jQueryElement, noAnimation) { jQueryElement.addClass('CLOSE').removeClass('OPEN'); if (noAnimation) jQueryElement.parent().find('ul:first').hide(); else jQueryElement.parent().find('ul:first').slideUp(); }
function closeBranch(jQueryElement, noAnimation) { jQueryElement.addClass('CLOSE').removeClass('OPEN'); if (noAnimation) jQueryElement.parent().find('ul:first').hide(); else jQueryElement.parent().find('ul:first').slideUp(); }
JavaScript
function bindGrid() { var view = $.totalStorage('display'); if (!view && (typeof displayList != 'undefined') && displayList) view = 'list'; if (view && view != 'grid') display(view); else $('.display').find('li#grid').addClass('selected'); $(document).on('click', '#grid', function(e) { e.preventDefault(); display('grid'); }); $(document).on('click', '#list', function(e) { e.preventDefault(); display('list'); }); }
function bindGrid() { var view = $.totalStorage('display'); if (!view && (typeof displayList != 'undefined') && displayList) view = 'list'; if (view && view != 'grid') display(view); else $('.display').find('li#grid').addClass('selected'); $(document).on('click', '#grid', function(e) { e.preventDefault(); display('grid'); }); $(document).on('click', '#list', function(e) { e.preventDefault(); display('list'); }); }
JavaScript
function notifyProduct($info){ var wait = setTimeout(function(){ $.jGrowl($info,{ life: 5000 }); }); }
function notifyProduct($info){ var wait = setTimeout(function(){ $.jGrowl($info,{ life: 5000 }); }); }
JavaScript
function shouldCreateLocalTemplate() { // Given - When const template = new Template( '#template-id', '#template-content', { "msg": "Hello World" } ); // Then let errorOccurred = false; let predicate = template.templateIdentifier === '#template-id'; console.assert(predicate, 'templateIdentifier not valid'); errorOccurred = predicate ? false : true; predicate = template.parentBlockIdentifier === '#template-content' console.assert(predicate, 'parentBloackIdentifier not valid'); errorOccurred = predicate ? false : true; predicate = JSON.stringify(template.data) === JSON.stringify({"msg": "Hello World"}); console.assert(predicate, 'data not valid'); errorOccurred = predicate ? false : true; // Complete const $div = $('#test1'); if (errorOccurred) { $div.html('<p>An error occure during shouldCreateLocalTemplate() unit test. Press <kbd>F12</kbd> for more detail about the error.</p>'); } else { $div.html('<p>shouldCreateLocalTemplate() unit test work with success !</p>'); } }
function shouldCreateLocalTemplate() { // Given - When const template = new Template( '#template-id', '#template-content', { "msg": "Hello World" } ); // Then let errorOccurred = false; let predicate = template.templateIdentifier === '#template-id'; console.assert(predicate, 'templateIdentifier not valid'); errorOccurred = predicate ? false : true; predicate = template.parentBlockIdentifier === '#template-content' console.assert(predicate, 'parentBloackIdentifier not valid'); errorOccurred = predicate ? false : true; predicate = JSON.stringify(template.data) === JSON.stringify({"msg": "Hello World"}); console.assert(predicate, 'data not valid'); errorOccurred = predicate ? false : true; // Complete const $div = $('#test1'); if (errorOccurred) { $div.html('<p>An error occure during shouldCreateLocalTemplate() unit test. Press <kbd>F12</kbd> for more detail about the error.</p>'); } else { $div.html('<p>shouldCreateLocalTemplate() unit test work with success !</p>'); } }
JavaScript
function _renderLocalTemplate() { const template = new Template( '#local-template-id', '#local-template-content', { "title": "Render local template", "description": "I'm a template store directly on the webpage. Type <kbd>CTRL</kbd> + <kbd>U</kbd> to see in source code of the webpage." } ); const render = new RenderLocalTemplate(); render.render(template); }
function _renderLocalTemplate() { const template = new Template( '#local-template-id', '#local-template-content', { "title": "Render local template", "description": "I'm a template store directly on the webpage. Type <kbd>CTRL</kbd> + <kbd>U</kbd> to see in source code of the webpage." } ); const render = new RenderLocalTemplate(); render.render(template); }
JavaScript
function _renderExternalTemplateJsr() { const template = new Template( './templates/external-template.jsr', '#external-jsr-template-content', { "title": "Render external template.jsr", "description": "I'm a template store in folder <strong>templates/</strong> with <em>.jsr</em> extension !!!" } ); const render = new RenderExternalTemplate(); render.render(template); }
function _renderExternalTemplateJsr() { const template = new Template( './templates/external-template.jsr', '#external-jsr-template-content', { "title": "Render external template.jsr", "description": "I'm a template store in folder <strong>templates/</strong> with <em>.jsr</em> extension !!!" } ); const render = new RenderExternalTemplate(); render.render(template); }
JavaScript
function _renderExternalTemplateHtml() { const template = new Template( './templates/external-template.html', '#external-html-template-content', { "title": "Render external template.html", "description": "I'm a template store in folder <strong>templates/</strong> with <em>.html</em> extension !!!" } ); const render = new RenderExternalTemplate(); render.render(template); }
function _renderExternalTemplateHtml() { const template = new Template( './templates/external-template.html', '#external-html-template-content', { "title": "Render external template.html", "description": "I'm a template store in folder <strong>templates/</strong> with <em>.html</em> extension !!!" } ); const render = new RenderExternalTemplate(); render.render(template); }
JavaScript
render(template) { $.when( $.get(template.templateName) ).done(function(tmplData) { $.templates({ tmpl: tmplData }); $(template.parentBlock).html($.render.tmpl(template.data)); }); }
render(template) { $.when( $.get(template.templateName) ).done(function(tmplData) { $.templates({ tmpl: tmplData }); $(template.parentBlock).html($.render.tmpl(template.data)); }); }
JavaScript
function disable(behavior) { behavior = this.behaviors[behavior]; if (behavior._enabled) { behavior.disable(); behavior._enabled = false; return true; } else { return false; } }
function disable(behavior) { behavior = this.behaviors[behavior]; if (behavior._enabled) { behavior.disable(); behavior._enabled = false; return true; } else { return false; } }
JavaScript
async function compararRolUsuario(){ const respuestausuarios = await dataBase.collection("ng_users").where('email','==',usuarioEmail).get(); console.log(usuarioEmail); /* let rolmod = "" */ const usuariosBD = []; respuestausuarios.forEach(function (item){ usuariosBD.push(item.data()); }); usuariosBD.forEach((t) => { if (t.rol == "Vendedor") { btnAdicionarUser.disabled = true document.getElementById('modaladicionar').disabled = true document.getElementById('modalModificar').disabled = true document.getElementById('modalEliminar').disabled = true } }); }
async function compararRolUsuario(){ const respuestausuarios = await dataBase.collection("ng_users").where('email','==',usuarioEmail).get(); console.log(usuarioEmail); /* let rolmod = "" */ const usuariosBD = []; respuestausuarios.forEach(function (item){ usuariosBD.push(item.data()); }); usuariosBD.forEach((t) => { if (t.rol == "Vendedor") { btnAdicionarUser.disabled = true document.getElementById('modaladicionar').disabled = true document.getElementById('modalModificar').disabled = true document.getElementById('modalEliminar').disabled = true } }); }
JavaScript
function modificarUsuario() { let tablaUsuarios = document.getElementById("tabla_usuarios"); let radios = tablaUsuarios.getElementsByTagName("input"); let filas = tablaUsuarios.getElementsByTagName("tr"); let totalFilas = radios.length; for (i = 0; i < totalFilas; i++) { if (radios[i].checked) { filaSeleccionada = filas[i] document.getElementById("MinputCodigo").value = filaSeleccionada.cells[1].innerText document.getElementById("Minputnombre").value = filaSeleccionada.cells[2].innerText /* document.getElementById("MinputApellido").value = filaSeleccionada.cells[3].innerText */ document.getElementById("MinputEmail").value = filaSeleccionada.cells[3].innerText document.getElementById("MinputRol").value = filaSeleccionada.cells[4].innerText document.getElementById("MinputEstado").value = filaSeleccionada.cells[5].innerText if (filaSeleccionada.cells[5].innerText == "Pendiente") { document.getElementById("MinputEstado").value ="Pendiente"; } else if (filaSeleccionada.cells[5].innerText == "Autorizado") { document.getElementById("MinputEstado").value = "Autorizado"; } else { document.getElementById("MinputEstado").value = "No autorizado"; } filaObjetivo = filaSeleccionada } } }
function modificarUsuario() { let tablaUsuarios = document.getElementById("tabla_usuarios"); let radios = tablaUsuarios.getElementsByTagName("input"); let filas = tablaUsuarios.getElementsByTagName("tr"); let totalFilas = radios.length; for (i = 0; i < totalFilas; i++) { if (radios[i].checked) { filaSeleccionada = filas[i] document.getElementById("MinputCodigo").value = filaSeleccionada.cells[1].innerText document.getElementById("Minputnombre").value = filaSeleccionada.cells[2].innerText /* document.getElementById("MinputApellido").value = filaSeleccionada.cells[3].innerText */ document.getElementById("MinputEmail").value = filaSeleccionada.cells[3].innerText document.getElementById("MinputRol").value = filaSeleccionada.cells[4].innerText document.getElementById("MinputEstado").value = filaSeleccionada.cells[5].innerText if (filaSeleccionada.cells[5].innerText == "Pendiente") { document.getElementById("MinputEstado").value ="Pendiente"; } else if (filaSeleccionada.cells[5].innerText == "Autorizado") { document.getElementById("MinputEstado").value = "Autorizado"; } else { document.getElementById("MinputEstado").value = "No autorizado"; } filaObjetivo = filaSeleccionada } } }
JavaScript
function modificarProducto() { let tablaProductos = document.getElementById("cuerpoTablaProductos"); let radios = tablaProductos.getElementsByTagName("input"); let filas = tablaProductos.getElementsByTagName("tr"); let totalFilas = radios.length; console.log(radios) for (i = 0; i < totalFilas; i++) { if (radios[i].checked) { console.log(radios[i]) filaSeleccionada = filas[i] document.getElementById("modifyCodigo").value = filaSeleccionada.cells[1].innerText document.getElementById("modifyDescripcion").value = filaSeleccionada.cells[2].innerText document.getElementById("modifyPeso").value = filaSeleccionada.cells[3].innerText document.getElementById("modifyValorUnitario").value = filaSeleccionada.cells[4].innerText document.getElementById("modifyEstado").value = filaSeleccionada.cells[5].innerText if (filaSeleccionada.cells[5].innerText == "Disponible") { document.getElementById("modifyEstado").value = "2"; } document.getElementById("modifyEstado").value = "1"; } filaObjetivo = filaSeleccionada } }
function modificarProducto() { let tablaProductos = document.getElementById("cuerpoTablaProductos"); let radios = tablaProductos.getElementsByTagName("input"); let filas = tablaProductos.getElementsByTagName("tr"); let totalFilas = radios.length; console.log(radios) for (i = 0; i < totalFilas; i++) { if (radios[i].checked) { console.log(radios[i]) filaSeleccionada = filas[i] document.getElementById("modifyCodigo").value = filaSeleccionada.cells[1].innerText document.getElementById("modifyDescripcion").value = filaSeleccionada.cells[2].innerText document.getElementById("modifyPeso").value = filaSeleccionada.cells[3].innerText document.getElementById("modifyValorUnitario").value = filaSeleccionada.cells[4].innerText document.getElementById("modifyEstado").value = filaSeleccionada.cells[5].innerText if (filaSeleccionada.cells[5].innerText == "Disponible") { document.getElementById("modifyEstado").value = "2"; } document.getElementById("modifyEstado").value = "1"; } filaObjetivo = filaSeleccionada } }
JavaScript
async function compararRolUsuario(){ const respuestausuarios = await dataBase.collection("ng_users").where('email','==',usuarioEmail).get(); console.log(usuarioEmail); /* let rolmod = "" */ const usuariosBD = []; respuestausuarios.forEach(function (item){ usuariosBD.push(item.data()); }); usuariosBD.forEach((t) => { if (t.rol == "Vendedor") { console.log('soy de verdad!') // btnAdicionarUser.disabled = true document.getElementById('btnAdicionarPrincipal').disabled = true document.getElementById('btnModificarPrincial').disabled = true document.getElementById('btnEliminarPrincipal').disabled = true // document.getElementById('modalEliminar').disabled = true } }); }
async function compararRolUsuario(){ const respuestausuarios = await dataBase.collection("ng_users").where('email','==',usuarioEmail).get(); console.log(usuarioEmail); /* let rolmod = "" */ const usuariosBD = []; respuestausuarios.forEach(function (item){ usuariosBD.push(item.data()); }); usuariosBD.forEach((t) => { if (t.rol == "Vendedor") { console.log('soy de verdad!') // btnAdicionarUser.disabled = true document.getElementById('btnAdicionarPrincipal').disabled = true document.getElementById('btnModificarPrincial').disabled = true document.getElementById('btnEliminarPrincipal').disabled = true // document.getElementById('modalEliminar').disabled = true } }); }
JavaScript
function nuevaFila() { // se crea input container el cual busca el elemento con el id="AquiVaLaFila" var dondeInsertar = document.getElementById("AquiVaLaFila"); // se Crean los imputs // for (var i = 0; i < 10; i++) { var Check = document.createElement("input"); Check.setAttribute("class", "form-check-input") Check.setAttribute("type", "radio"); Check.setAttribute("name", "flexRadioDefault") Check.setAttribute("id", "flexRadioDefault"); var Id = document.createElement("input"); Id.setAttribute("type", "text"); Id.setAttribute("id", "Id"); var Articulo = document.createElement("input"); Articulo.setAttribute("type", "text"); Articulo.setAttribute("id", "Articulo"); var Cliente = document.createElement("input"); Cliente.setAttribute("type", "text"); Cliente.setAttribute("id", "Cliente"); var Valor = document.createElement("input"); Valor.setAttribute("type", "text"); Valor.setAttribute("id", "Valor"); var FechaVenta = document.createElement("input"); FechaVenta.setAttribute("type", "text"); FechaVenta.setAttribute("id", "FechaVenta"); var FechaPago = document.createElement("input"); FechaPago.setAttribute("type", "text"); FechaPago.setAttribute("id", "FechaPago"); var Vendedor = document.createElement("input"); Vendedor.setAttribute("type", "text"); Vendedor.setAttribute("id", "Vendedor"); var Estado = document.createElement("input"); Estado.setAttribute("type", "text"); Estado.setAttribute("id", "Estado"); // no es necesario crear la tabla solo las filas // los estilos se le aplicaran automaticamente a esta fila cuando sean // insertados en la tabla // se crea la fila Fila = document.createElement("tr"); div = document.createElement("div") div.setAttribute("class","form-check") // se crea la primer columnita de la fila y se le agrega el check col1 = document.createElement("th"); div.appendChild(Check) col1.appendChild(div); // se crea la segunda columnita he la fila y se le agrega Id col2 = document.createElement("td"); col2.appendChild(Id); col3 = document.createElement("td"); col3.appendChild(Articulo); col4 = document.createElement("td"); col4.appendChild(Cliente); col5 = document.createElement("td"); col5.appendChild(Valor); col6 = document.createElement("td"); col6.appendChild(FechaVenta); col7 = document.createElement("td"); col7.appendChild(FechaPago); col8 = document.createElement("td"); col8.appendChild(Vendedor); col9 = document.createElement("td"); col9.appendChild(Estado); // luego agregamos cada columnita a la fila Fila.appendChild(col1) Fila.appendChild(col2) Fila.appendChild(col3) Fila.appendChild(col4) Fila.appendChild(col5) Fila.appendChild(col6) Fila.appendChild(col7) Fila.appendChild(col8) Fila.appendChild(col9) // por ultimo le decimos a la fila donde aparecer agregandola a dondeInsertar dondeInsertar.appendChild(Fila) // } }
function nuevaFila() { // se crea input container el cual busca el elemento con el id="AquiVaLaFila" var dondeInsertar = document.getElementById("AquiVaLaFila"); // se Crean los imputs // for (var i = 0; i < 10; i++) { var Check = document.createElement("input"); Check.setAttribute("class", "form-check-input") Check.setAttribute("type", "radio"); Check.setAttribute("name", "flexRadioDefault") Check.setAttribute("id", "flexRadioDefault"); var Id = document.createElement("input"); Id.setAttribute("type", "text"); Id.setAttribute("id", "Id"); var Articulo = document.createElement("input"); Articulo.setAttribute("type", "text"); Articulo.setAttribute("id", "Articulo"); var Cliente = document.createElement("input"); Cliente.setAttribute("type", "text"); Cliente.setAttribute("id", "Cliente"); var Valor = document.createElement("input"); Valor.setAttribute("type", "text"); Valor.setAttribute("id", "Valor"); var FechaVenta = document.createElement("input"); FechaVenta.setAttribute("type", "text"); FechaVenta.setAttribute("id", "FechaVenta"); var FechaPago = document.createElement("input"); FechaPago.setAttribute("type", "text"); FechaPago.setAttribute("id", "FechaPago"); var Vendedor = document.createElement("input"); Vendedor.setAttribute("type", "text"); Vendedor.setAttribute("id", "Vendedor"); var Estado = document.createElement("input"); Estado.setAttribute("type", "text"); Estado.setAttribute("id", "Estado"); // no es necesario crear la tabla solo las filas // los estilos se le aplicaran automaticamente a esta fila cuando sean // insertados en la tabla // se crea la fila Fila = document.createElement("tr"); div = document.createElement("div") div.setAttribute("class","form-check") // se crea la primer columnita de la fila y se le agrega el check col1 = document.createElement("th"); div.appendChild(Check) col1.appendChild(div); // se crea la segunda columnita he la fila y se le agrega Id col2 = document.createElement("td"); col2.appendChild(Id); col3 = document.createElement("td"); col3.appendChild(Articulo); col4 = document.createElement("td"); col4.appendChild(Cliente); col5 = document.createElement("td"); col5.appendChild(Valor); col6 = document.createElement("td"); col6.appendChild(FechaVenta); col7 = document.createElement("td"); col7.appendChild(FechaPago); col8 = document.createElement("td"); col8.appendChild(Vendedor); col9 = document.createElement("td"); col9.appendChild(Estado); // luego agregamos cada columnita a la fila Fila.appendChild(col1) Fila.appendChild(col2) Fila.appendChild(col3) Fila.appendChild(col4) Fila.appendChild(col5) Fila.appendChild(col6) Fila.appendChild(col7) Fila.appendChild(col8) Fila.appendChild(col9) // por ultimo le decimos a la fila donde aparecer agregandola a dondeInsertar dondeInsertar.appendChild(Fila) // } }
JavaScript
function InsertarDatos() { for (var i = 0; i <= filasDB; i++) { const ColumnId = document.getElementById("Id" + i) const ColumnArticulo = document.getElementById("Articulo" + i) const ColumnCliente = document.getElementById("Cliente" + i) const ColumnValor = document.getElementById("Valor" + i) const ColumnFechaVenta = document.getElementById("FechaVenta" + i) const ColumnFechaPago = document.getElementById("FechaPago" + i) const ColumnVendedor = document.getElementById("Vendedor" + i) const ColumnEstado = document.getElementById("Estado" + i) ColumnId.textContent = Id[i] ColumnArticulo.textContent = Articulo[i] ColumnCliente.textContent = Cliente[i] ColumnValor.textContent = Valor[i] ColumnFechaVenta.textContent = FechaVenta[i] ColumnFechaPago.textContent = FechaPago[i] ColumnVendedor.textContent = Vendedor[i] ColumnEstado.textContent = Estado[i] } }
function InsertarDatos() { for (var i = 0; i <= filasDB; i++) { const ColumnId = document.getElementById("Id" + i) const ColumnArticulo = document.getElementById("Articulo" + i) const ColumnCliente = document.getElementById("Cliente" + i) const ColumnValor = document.getElementById("Valor" + i) const ColumnFechaVenta = document.getElementById("FechaVenta" + i) const ColumnFechaPago = document.getElementById("FechaPago" + i) const ColumnVendedor = document.getElementById("Vendedor" + i) const ColumnEstado = document.getElementById("Estado" + i) ColumnId.textContent = Id[i] ColumnArticulo.textContent = Articulo[i] ColumnCliente.textContent = Cliente[i] ColumnValor.textContent = Valor[i] ColumnFechaVenta.textContent = FechaVenta[i] ColumnFechaPago.textContent = FechaPago[i] ColumnVendedor.textContent = Vendedor[i] ColumnEstado.textContent = Estado[i] } }
JavaScript
function initStaticFields() { config = app.config; util = app.util; log = new app.Log('textColorSlider'); log.d('initStaticFields', 'Module initialized'); }
function initStaticFields() { config = app.config; util = app.util; log = new app.Log('textColorSlider'); log.d('initStaticFields', 'Module initialized'); }
JavaScript
function reset() { TextColorSlider = app.TextColorSlider; TextColorSlider.initStaticFields(); log.i('reset', 'All modules initialized'); checkBrowserCompatibility(); setUpColorSlider(); }
function reset() { TextColorSlider = app.TextColorSlider; TextColorSlider.initStaticFields(); log.i('reset', 'All modules initialized'); checkBrowserCompatibility(); setUpColorSlider(); }
JavaScript
function onDocumentLoad() { log.i('onDocumentLoad'); reset(); util.stopListening(window, 'load', onDocumentLoad); }
function onDocumentLoad() { log.i('onDocumentLoad'); reset(); util.stopListening(window, 'load', onDocumentLoad); }
JavaScript
function checkBrowserCompatibility() { if (!util.isBrowserCompatible) { showErrorMessage(config.L18N.EN.BAD_BROWSER_MESSAGE); } }
function checkBrowserCompatibility() { if (!util.isBrowserCompatible) { showErrorMessage(config.L18N.EN.BAD_BROWSER_MESSAGE); } }
JavaScript
function showErrorMessage(message) { var body, errorMessageElement; body = document.getElementsByTagName('body')[0]; errorMessageElement = util.createElement('div', body, null, ['errorMessage']); errorMessageElement.innerHTML = message; errorMessageElement.onclick = function () { body.removeChild(errorMessageElement); }; }
function showErrorMessage(message) { var body, errorMessageElement; body = document.getElementsByTagName('body')[0]; errorMessageElement = util.createElement('div', body, null, ['errorMessage']); errorMessageElement.innerHTML = message; errorMessageElement.onclick = function () { body.removeChild(errorMessageElement); }; }
JavaScript
function planetVSplayer(player, planet) { // for each turn the player has 3 options of attack, "attack", "charge"(this will give the player a multipier for their attack), and "block" var turns = 0; // 3 for xs, 6 for sm, 9 for md, 12 for lg // player and planet are both given the same number of turns var planet = { attk: 75, hp: 0, level: player.level, name: planet.planet_name, orbital_period: planet.orbital_period }; // these will be effected by the players level at each battle var player = { userName: player.userName, avatar: player.avatar, score: player.score, attk: player.attk, hp: player.hp, level: player.level, id: player.id }; // these will be effected by the players level at each battle $("#playerName").text(player.userName); $("#planetName").text(planet.name); // planet is extra small 3 TURNS if (planet.orbital_period <= 25) { turns = 3; planet.hp = 40; $("#player-move").text(battleText.startBattle.tooSmall); } // planet is small 6 TURNS else if (planet.orbital_period <= 500) { turns = 6; planet.hp = 100; $("#player-move").text(battleText.startBattle.tooSmall); } // planet is medium 9 TURNS else if (planet.orbital_period <= 1000) { turns = 9; planet.hp = 150; $("#player-move").text(battleText.startBattle.justRight); } // planet is large 12 TURNS else { turns = 12; planet.hp = 200; $("#player-move").text(battleText.startBattle.tooBig); } this.battle(turns, player, planet); console.log(player) console.log(planet) }
function planetVSplayer(player, planet) { // for each turn the player has 3 options of attack, "attack", "charge"(this will give the player a multipier for their attack), and "block" var turns = 0; // 3 for xs, 6 for sm, 9 for md, 12 for lg // player and planet are both given the same number of turns var planet = { attk: 75, hp: 0, level: player.level, name: planet.planet_name, orbital_period: planet.orbital_period }; // these will be effected by the players level at each battle var player = { userName: player.userName, avatar: player.avatar, score: player.score, attk: player.attk, hp: player.hp, level: player.level, id: player.id }; // these will be effected by the players level at each battle $("#playerName").text(player.userName); $("#planetName").text(planet.name); // planet is extra small 3 TURNS if (planet.orbital_period <= 25) { turns = 3; planet.hp = 40; $("#player-move").text(battleText.startBattle.tooSmall); } // planet is small 6 TURNS else if (planet.orbital_period <= 500) { turns = 6; planet.hp = 100; $("#player-move").text(battleText.startBattle.tooSmall); } // planet is medium 9 TURNS else if (planet.orbital_period <= 1000) { turns = 9; planet.hp = 150; $("#player-move").text(battleText.startBattle.justRight); } // planet is large 12 TURNS else { turns = 12; planet.hp = 200; $("#player-move").text(battleText.startBattle.tooBig); } this.battle(turns, player, planet); console.log(player) console.log(planet) }
JavaScript
function checkIfDead() { if (player.hp <= 0) { console.log("death"); console.log(badEnding.stuff); // go back to start screen } else { // return to game } }
function checkIfDead() { if (player.hp <= 0) { console.log("death"); console.log(badEnding.stuff); // go back to start screen } else { // return to game } }
JavaScript
handleServerFormErrors(data) { if ('payload' in data) { data = data['payload']; } if ('errors' in data) { if (Array.isArray(data['errors'])) { data['errors'].forEach(item => { this.get('flashMessages').danger(item['detail']); }); } if ('non_field_errors' in data['errors']) { data['errors']['non_field_errors'].forEach(item => { this.get('flashMessages').danger(item); }); } } }
handleServerFormErrors(data) { if ('payload' in data) { data = data['payload']; } if ('errors' in data) { if (Array.isArray(data['errors'])) { data['errors'].forEach(item => { this.get('flashMessages').danger(item['detail']); }); } if ('non_field_errors' in data['errors']) { data['errors']['non_field_errors'].forEach(item => { this.get('flashMessages').danger(item); }); } } }
JavaScript
willDestroyElement() { this._super(...arguments); if (get(this, 'model.isNew')) { this.get('model').deleteRecord(); } }
willDestroyElement() { this._super(...arguments); if (get(this, 'model.isNew')) { this.get('model').deleteRecord(); } }
JavaScript
submit(changeset) { // Deprecated. this.setFormState('pending'); return this.get('submit').perform(changeset); }
submit(changeset) { // Deprecated. this.setFormState('pending'); return this.get('submit').perform(changeset); }
JavaScript
init() { this._super(...arguments); // Determine initial state if (this.get('value')) { this.set('value_file_url', this.get('value')); this.set('state', 'default'); } else { this.set('state', 'upload'); } }
init() { this._super(...arguments); // Determine initial state if (this.get('value')) { this.set('value_file_url', this.get('value')); this.set('state', 'default'); } else { this.set('state', 'upload'); } }
JavaScript
submit(query) { // // Before every submit, if possible, we call the preFilterAlter hook if (this.get('preFilterAlter')) { query = this.get('preFilterAlter')(query); } // // Using a string representation of the query object, determine if // anything as actually changed before // filtering the table. if (JSON.stringify(query) !== JSON.stringify(this.get('defaultRecordFilter'))) { this.get('parentComponent').set('recordQuery', query); this.get('parentComponent').resetTable(); this.set('hasFiltered', true); } }
submit(query) { // // Before every submit, if possible, we call the preFilterAlter hook if (this.get('preFilterAlter')) { query = this.get('preFilterAlter')(query); } // // Using a string representation of the query object, determine if // anything as actually changed before // filtering the table. if (JSON.stringify(query) !== JSON.stringify(this.get('defaultRecordFilter'))) { this.get('parentComponent').set('recordQuery', query); this.get('parentComponent').resetTable(); this.set('hasFiltered', true); } }
JavaScript
toggleIcon (icon) { if (icon.classList.contains('fa-unlock')) { icon.classList.replace('fa-unlock', 'fa-lock') icon.parentElement.setAttribute('data-color-unlocked', false) } else { icon.classList.replace('fa-lock', 'fa-unlock') icon.parentElement.setAttribute('data-color-unlocked', true) } }
toggleIcon (icon) { if (icon.classList.contains('fa-unlock')) { icon.classList.replace('fa-unlock', 'fa-lock') icon.parentElement.setAttribute('data-color-unlocked', false) } else { icon.classList.replace('fa-lock', 'fa-unlock') icon.parentElement.setAttribute('data-color-unlocked', true) } }
JavaScript
function transformRequires (contents, fn) { const regexp = /require\(['"](.+?)["']\)/g let match while (match = regexp.exec(contents)) { // eslint-disable-line const start = match.index const end = start + match[0].length const length = end - start // Escape quotes const transformed = JSON.stringify(fn(match[1])) // Replace `require` with transformed contents contents = contents.slice(0, start) + transformed + contents.slice(end) // Tweak the start position for next match // by transformed contents regexp.lastIndex += transformed.length - length } return contents }
function transformRequires (contents, fn) { const regexp = /require\(['"](.+?)["']\)/g let match while (match = regexp.exec(contents)) { // eslint-disable-line const start = match.index const end = start + match[0].length const length = end - start // Escape quotes const transformed = JSON.stringify(fn(match[1])) // Replace `require` with transformed contents contents = contents.slice(0, start) + transformed + contents.slice(end) // Tweak the start position for next match // by transformed contents regexp.lastIndex += transformed.length - length } return contents }
JavaScript
function consoleTable(data) { function dividerRow(startChar, midChar, endChar, fields) { return ( startChar + fields.map(f => '─'.repeat(f.width + 2)).join(midChar) + endChar ); } function dataRow(rowValues) { return `β”‚ ${rowValues.join(' β”‚ ')} β”‚`; } // Width calculations let fields = [{ name: 'test name', width: longestNameLength }]; const firstEntry = Object.values(data)[0]; for (let field of Object.keys(firstEntry)) { fields.push({ name: field, width: digitsLeft + digitsRight + 1 }); } // Header console.log(dividerRow('β”Œ', '┬', '┐', fields)); console.log(dataRow(fields.map(f => f.name.padEnd(f.width)))); console.log(dividerRow('β”œ', 'β”Ό', '─', fields)); // Body for (let [testName, testData] of Object.entries(data)) { let cells = [testName.padEnd(fields[0].width)]; for (let value of Object.values(testData)) { cells.push(tableNum(value)); } console.log(dataRow(cells)); } // Footer console.log(dividerRow('β””', 'β”΄', 'β”˜', fields)); }
function consoleTable(data) { function dividerRow(startChar, midChar, endChar, fields) { return ( startChar + fields.map(f => '─'.repeat(f.width + 2)).join(midChar) + endChar ); } function dataRow(rowValues) { return `β”‚ ${rowValues.join(' β”‚ ')} β”‚`; } // Width calculations let fields = [{ name: 'test name', width: longestNameLength }]; const firstEntry = Object.values(data)[0]; for (let field of Object.keys(firstEntry)) { fields.push({ name: field, width: digitsLeft + digitsRight + 1 }); } // Header console.log(dividerRow('β”Œ', '┬', '┐', fields)); console.log(dataRow(fields.map(f => f.name.padEnd(f.width)))); console.log(dividerRow('β”œ', 'β”Ό', '─', fields)); // Body for (let [testName, testData] of Object.entries(data)) { let cells = [testName.padEnd(fields[0].width)]; for (let value of Object.values(testData)) { cells.push(tableNum(value)); } console.log(dataRow(cells)); } // Footer console.log(dividerRow('β””', 'β”΄', 'β”˜', fields)); }
JavaScript
function flatMap(arr, mapper) { if (typeof arr.flatMap === 'function') { return arr.flatMap(mapper); } let ret = []; arr.forEach((...args) => { let result = mapper.call(this, ...args); if (Array.isArray(result)) { for (let thing of result) { ret.push(thing); } } else { ret.push(result); } }); return ret; }
function flatMap(arr, mapper) { if (typeof arr.flatMap === 'function') { return arr.flatMap(mapper); } let ret = []; arr.forEach((...args) => { let result = mapper.call(this, ...args); if (Array.isArray(result)) { for (let thing of result) { ret.push(thing); } } else { ret.push(result); } }); return ret; }
JavaScript
function unique(items) { if (!Array.isArray(items) && typeof items !== 'string') { return []; } return Array.from(new Set(items)); }
function unique(items) { if (!Array.isArray(items) && typeof items !== 'string') { return []; } return Array.from(new Set(items)); }
JavaScript
function createMatchers(matchItems) { if (!matchItems) { // For invalid input, return a RegExp that matches anything return [/.?/]; } const exactRegExp = (pattern) => new RegExp('^(?:' + pattern + ')$'); const arrayRegExp = (arr) => exactRegExp( arr.map(value => RegExp.escape(value.toString()) ).join('|') ); if (matchItems instanceof RegExp) { return [matchItems]; } if (Array.isArray(matchItems)) { const hasRegExp = matchItems.some(mz => mz instanceof RegExp); // Quick shortcut β€” combine array of strings into a single regexp if (!hasRegExp) { return [arrayRegExp(matchItems)]; } // Find all string values and combine them let ret = []; let strings = []; matchItems.forEach(mz => { (mz instanceof RegExp ? ret : strings).push(mz); }); if (strings.length) { ret.push(arrayRegExp(strings)); } return ret; } return [exactRegExp(RegExp.escape(matchItems.toString()))]; }
function createMatchers(matchItems) { if (!matchItems) { // For invalid input, return a RegExp that matches anything return [/.?/]; } const exactRegExp = (pattern) => new RegExp('^(?:' + pattern + ')$'); const arrayRegExp = (arr) => exactRegExp( arr.map(value => RegExp.escape(value.toString()) ).join('|') ); if (matchItems instanceof RegExp) { return [matchItems]; } if (Array.isArray(matchItems)) { const hasRegExp = matchItems.some(mz => mz instanceof RegExp); // Quick shortcut β€” combine array of strings into a single regexp if (!hasRegExp) { return [arrayRegExp(matchItems)]; } // Find all string values and combine them let ret = []; let strings = []; matchItems.forEach(mz => { (mz instanceof RegExp ? ret : strings).push(mz); }); if (strings.length) { ret.push(arrayRegExp(strings)); } return ret; } return [exactRegExp(RegExp.escape(matchItems.toString()))]; }
JavaScript
function anyMatch(item, regExpMatchers, extraMatchers) { if (extraMatchers !== undefined) { return ( anyMatch(item, regExpMatchers) && anyMatch(item, extraMatchers) ); } if (!regExpMatchers || !regExpMatchers.length) { return true; } return regExpMatchers.some(matcher => matcher.test(item)); }
function anyMatch(item, regExpMatchers, extraMatchers) { if (extraMatchers !== undefined) { return ( anyMatch(item, regExpMatchers) && anyMatch(item, extraMatchers) ); } if (!regExpMatchers || !regExpMatchers.length) { return true; } return regExpMatchers.some(matcher => matcher.test(item)); }
JavaScript
function buildWebpack(options) { const compiler = webpack({ mode: 'development', devtool: 'hidden-source-map', entry: path.resolve(__dirname, 'fixtures', 'index.js'), output: { path: __dirname, filename: 'test-output.[filehash].js', }, plugins: [ new MomentTimezoneDataPlugin(options), new MomentLocalesPlugin(), // Required for making tests faster ], }); compiler.outputFileSystem = new MemoryFS(); return new Promise((resolve, reject) => { compiler.run((err, stats) => { if (err) { reject(err); } const module = Array.from(stats.compilation.modules).find(mod => rGeneratedFile.test(mod.request) // Matches only if data processed (and cache generated) ); const data = module ? module.buildInfo.jsonData : null; // In case no processing happened resolve({ stats, module, data }); }); }); }
function buildWebpack(options) { const compiler = webpack({ mode: 'development', devtool: 'hidden-source-map', entry: path.resolve(__dirname, 'fixtures', 'index.js'), output: { path: __dirname, filename: 'test-output.[filehash].js', }, plugins: [ new MomentTimezoneDataPlugin(options), new MomentLocalesPlugin(), // Required for making tests faster ], }); compiler.outputFileSystem = new MemoryFS(); return new Promise((resolve, reject) => { compiler.run((err, stats) => { if (err) { reject(err); } const module = Array.from(stats.compilation.modules).find(mod => rGeneratedFile.test(mod.request) // Matches only if data processed (and cache generated) ); const data = module ? module.buildInfo.jsonData : null; // In case no processing happened resolve({ stats, module, data }); }); }); }