id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
34,500
TeaEntityLab/fpEs
fp.js
fill
function fill(list, value, startIndex=0, endIndex=list.length){ if (!(list && Array.isArray(list))) { // Manually currying let args = arguments; return (list) => fill(list, ...args); } return Array(...list).map((x,i)=> { if(i>= startIndex && i <= endIndex) { return x=value; } else { return x; } }); }
javascript
function fill(list, value, startIndex=0, endIndex=list.length){ if (!(list && Array.isArray(list))) { // Manually currying let args = arguments; return (list) => fill(list, ...args); } return Array(...list).map((x,i)=> { if(i>= startIndex && i <= endIndex) { return x=value; } else { return x; } }); }
[ "function", "fill", "(", "list", ",", "value", ",", "startIndex", "=", "0", ",", "endIndex", "=", "list", ".", "length", ")", "{", "if", "(", "!", "(", "list", "&&", "Array", ".", "isArray", "(", "list", ")", ")", ")", "{", "// Manually currying", ...
Fills array using specified values. Can optionally pass in start and index of array to fill. Default startIndex = 0. Default endIndex = length of array.
[ "Fills", "array", "using", "specified", "values", ".", "Can", "optionally", "pass", "in", "start", "and", "index", "of", "array", "to", "fill", ".", "Default", "startIndex", "=", "0", ".", "Default", "endIndex", "=", "length", "of", "array", "." ]
bc64fe46162583de31d340d3cb832c3e15e42f45
https://github.com/TeaEntityLab/fpEs/blob/bc64fe46162583de31d340d3cb832c3e15e42f45/fp.js#L275-L289
34,501
TeaEntityLab/fpEs
fp.js
function (...values) { let list = []; let {main, follower} = reuseables.getMainAndFollower(values); main.forEach(x=>{ if(list.indexOf(x) ==-1) { if(follower.indexOf(x) >=0) { if(list[x] ==undefined) list.push(x) } } }) return list; }
javascript
function (...values) { let list = []; let {main, follower} = reuseables.getMainAndFollower(values); main.forEach(x=>{ if(list.indexOf(x) ==-1) { if(follower.indexOf(x) >=0) { if(list[x] ==undefined) list.push(x) } } }) return list; }
[ "function", "(", "...", "values", ")", "{", "let", "list", "=", "[", "]", ";", "let", "{", "main", ",", "follower", "}", "=", "reuseables", ".", "getMainAndFollower", "(", "values", ")", ";", "main", ".", "forEach", "(", "x", "=>", "{", "if", "(", ...
Returns values in two comparing arrays without repetition. Arrangement of resulting array is determined by main array. @param 1st Any number of individual arrays @param 2nd {number} Position number of array to be used as main @param 3rd {number} Position number of to be used as follower @returns values found in both arrays
[ "Returns", "values", "in", "two", "comparing", "arrays", "without", "repetition", ".", "Arrangement", "of", "resulting", "array", "is", "determined", "by", "main", "array", "." ]
bc64fe46162583de31d340d3cb832c3e15e42f45
https://github.com/TeaEntityLab/fpEs/blob/bc64fe46162583de31d340d3cb832c3e15e42f45/fp.js#L363-L374
34,502
TeaEntityLab/fpEs
fp.js
join
function join(joiner, ...values) { if (values.length > 0) { return concat([],...values).join(joiner); } // Manually currying return (...values) => join(joiner, ...values); }
javascript
function join(joiner, ...values) { if (values.length > 0) { return concat([],...values).join(joiner); } // Manually currying return (...values) => join(joiner, ...values); }
[ "function", "join", "(", "joiner", ",", "...", "values", ")", "{", "if", "(", "values", ".", "length", ">", "0", ")", "{", "return", "concat", "(", "[", "]", ",", "...", "values", ")", ".", "join", "(", "joiner", ")", ";", "}", "// Manually curryin...
Converts array elements to string joined by specified joiner. @param joiner Joins array elements @param values different individual arrays
[ "Converts", "array", "elements", "to", "string", "joined", "by", "specified", "joiner", "." ]
bc64fe46162583de31d340d3cb832c3e15e42f45
https://github.com/TeaEntityLab/fpEs/blob/bc64fe46162583de31d340d3cb832c3e15e42f45/fp.js#L380-L387
34,503
TeaEntityLab/fpEs
fp.js
nth
function nth(list, indexNum) { if (arguments.length == 1) { // Manually currying indexNum = list; return (list) => nth(list, indexNum); } if(indexNum >= 0) { return list[+indexNum] }; return [...list].reverse()[list.length+indexNum]; }
javascript
function nth(list, indexNum) { if (arguments.length == 1) { // Manually currying indexNum = list; return (list) => nth(list, indexNum); } if(indexNum >= 0) { return list[+indexNum] }; return [...list].reverse()[list.length+indexNum]; }
[ "function", "nth", "(", "list", ",", "indexNum", ")", "{", "if", "(", "arguments", ".", "length", "==", "1", ")", "{", "// Manually currying", "indexNum", "=", "list", ";", "return", "(", "list", ")", "=>", "nth", "(", "list", ",", "indexNum", ")", "...
Returns the nth value at the specified index. If index is negative, it returns value starting from the right @param list the array to be operated on @param indexNum the index number of the value to be retrieved
[ "Returns", "the", "nth", "value", "at", "the", "specified", "index", ".", "If", "index", "is", "negative", "it", "returns", "value", "starting", "from", "the", "right" ]
bc64fe46162583de31d340d3cb832c3e15e42f45
https://github.com/TeaEntityLab/fpEs/blob/bc64fe46162583de31d340d3cb832c3e15e42f45/fp.js#L394-L405
34,504
TeaEntityLab/fpEs
fp.js
sortedIndex
function sortedIndex(list, value, valueIndex) { if (!(list && Array.isArray(list))) { // Manually currying let args = arguments; return (list) => sortedIndex(list, ...args); } return reuseables.sorter(list, value, valueIndex); }
javascript
function sortedIndex(list, value, valueIndex) { if (!(list && Array.isArray(list))) { // Manually currying let args = arguments; return (list) => sortedIndex(list, ...args); } return reuseables.sorter(list, value, valueIndex); }
[ "function", "sortedIndex", "(", "list", ",", "value", ",", "valueIndex", ")", "{", "if", "(", "!", "(", "list", "&&", "Array", ".", "isArray", "(", "list", ")", ")", ")", "{", "// Manually currying", "let", "args", "=", "arguments", ";", "return", "(",...
Returns the lowest index number of a value if it is to be added to an array. @param list {Array} array that value will be added to @param value value to evaluate @param valueIndex {string} accepts either 'first' or 'last'. Specifies either to return the first or last index if the value is to be added to the array. Default is 'first' @returns {number}
[ "Returns", "the", "lowest", "index", "number", "of", "a", "value", "if", "it", "is", "to", "be", "added", "to", "an", "array", "." ]
bc64fe46162583de31d340d3cb832c3e15e42f45
https://github.com/TeaEntityLab/fpEs/blob/bc64fe46162583de31d340d3cb832c3e15e42f45/fp.js#L424-L432
34,505
TeaEntityLab/fpEs
fp.js
function(list){ const listNoDuplicate = difference([],list); if(typeof list[0] == "number") { return listNoDuplicate.sort((a,b)=>a-b); } return listNoDuplicate.sort(); }
javascript
function(list){ const listNoDuplicate = difference([],list); if(typeof list[0] == "number") { return listNoDuplicate.sort((a,b)=>a-b); } return listNoDuplicate.sort(); }
[ "function", "(", "list", ")", "{", "const", "listNoDuplicate", "=", "difference", "(", "[", "]", ",", "list", ")", ";", "if", "(", "typeof", "list", "[", "0", "]", "==", "\"number\"", ")", "{", "return", "listNoDuplicate", ".", "sort", "(", "(", "a",...
Returns sorted array without duplicates @param list {Array} array to be sorted @returns {Array} sorted array
[ "Returns", "sorted", "array", "without", "duplicates" ]
bc64fe46162583de31d340d3cb832c3e15e42f45
https://github.com/TeaEntityLab/fpEs/blob/bc64fe46162583de31d340d3cb832c3e15e42f45/fp.js#L438-L445
34,506
TeaEntityLab/fpEs
fp.js
union
function union(list1, list2, duplicate=false) { if ( arguments.length < 2 ) { // Manually currying let args1 = arguments; return (...args2) => union(...args1, ...args2); } else if (arguments.length === 2 && (! Array.isArray(list2))) { // curring union(_, list, duplicate) cases // Manually currying let args = arguments; return (list) => union(list, ...args); } if(duplicate) { return differenceWithDup([],list1.concat(list2)); } return difference([],list1.concat(list2)); }
javascript
function union(list1, list2, duplicate=false) { if ( arguments.length < 2 ) { // Manually currying let args1 = arguments; return (...args2) => union(...args1, ...args2); } else if (arguments.length === 2 && (! Array.isArray(list2))) { // curring union(_, list, duplicate) cases // Manually currying let args = arguments; return (list) => union(list, ...args); } if(duplicate) { return differenceWithDup([],list1.concat(list2)); } return difference([],list1.concat(list2)); }
[ "function", "union", "(", "list1", ",", "list2", ",", "duplicate", "=", "false", ")", "{", "if", "(", "arguments", ".", "length", "<", "2", ")", "{", "// Manually currying", "let", "args1", "=", "arguments", ";", "return", "(", "...", "args2", ")", "=>...
Returns unified array with or without duplicates. @param list1 {Array} first array @param list2 {Array} second array @param duplicate {boolean} boolean to include duplicates @returns {Array} array with/without duplicates
[ "Returns", "unified", "array", "with", "or", "without", "duplicates", "." ]
bc64fe46162583de31d340d3cb832c3e15e42f45
https://github.com/TeaEntityLab/fpEs/blob/bc64fe46162583de31d340d3cb832c3e15e42f45/fp.js#L453-L470
34,507
jaruba/multipass-torrent
lib/indexer.js
merge
function merge(torrents) { // NOTE: here, on the merge logic, we can set properties that should always be set // Or just rip out the model logic from LinvoDB into a separate module and use it return torrents.reduce(function(a, b) { return _.merge(a, b, function(x, y) { // this is for the files array, and we want more complicated behaviour if (_.isArray(a) && _.isArray(b)) return b; }) }) }
javascript
function merge(torrents) { // NOTE: here, on the merge logic, we can set properties that should always be set // Or just rip out the model logic from LinvoDB into a separate module and use it return torrents.reduce(function(a, b) { return _.merge(a, b, function(x, y) { // this is for the files array, and we want more complicated behaviour if (_.isArray(a) && _.isArray(b)) return b; }) }) }
[ "function", "merge", "(", "torrents", ")", "{", "// NOTE: here, on the merge logic, we can set properties that should always be set", "// Or just rip out the model logic from LinvoDB into a separate module and use it", "return", "torrents", ".", "reduce", "(", "function", "(", "a", "...
Conflict resolution logic is here
[ "Conflict", "resolution", "logic", "is", "here" ]
3cfa821760d956d3d104af04365c2a9d85226a9f
https://github.com/jaruba/multipass-torrent/blob/3cfa821760d956d3d104af04365c2a9d85226a9f/lib/indexer.js#L106-L116
34,508
cody-greene/scssify
lib/index.js
through
function through(transform, flush, objectMode) { const stream = new TransformStream({objectMode}) stream._transform = transform || pass if (flush) stream._flush = flush return stream }
javascript
function through(transform, flush, objectMode) { const stream = new TransformStream({objectMode}) stream._transform = transform || pass if (flush) stream._flush = flush return stream }
[ "function", "through", "(", "transform", ",", "flush", ",", "objectMode", ")", "{", "const", "stream", "=", "new", "TransformStream", "(", "{", "objectMode", "}", ")", "stream", ".", "_transform", "=", "transform", "||", "pass", "if", "(", "flush", ")", ...
Quickly create a object-mode duplex stream @param {function?} transform(chunk, encoding, done) @param {function?} flush(done) @param {boolean} objectMode @return {DuplexStream}
[ "Quickly", "create", "a", "object", "-", "mode", "duplex", "stream" ]
1db5ea75e0039ba17fc1c898e3a4ea6c32a655bf
https://github.com/cody-greene/scssify/blob/1db5ea75e0039ba17fc1c898e3a4ea6c32a655bf/lib/index.js#L143-L148
34,509
eddyystop/feathers-service-verify-reset
src/index.js
patchUser
function patchUser(user, patchToUser) { return users.patch(user.id || user._id, patchToUser, {}) // needs users from closure .then(() => Object.assign(user, patchToUser)); }
javascript
function patchUser(user, patchToUser) { return users.patch(user.id || user._id, patchToUser, {}) // needs users from closure .then(() => Object.assign(user, patchToUser)); }
[ "function", "patchUser", "(", "user", ",", "patchToUser", ")", "{", "return", "users", ".", "patch", "(", "user", ".", "id", "||", "user", ".", "_id", ",", "patchToUser", ",", "{", "}", ")", "// needs users from closure\r", ".", "then", "(", "(", ")", ...
Helpers requiring this closure
[ "Helpers", "requiring", "this", "closure" ]
dee9722dda8642ac1169120f7fe305684eb616c0
https://github.com/eddyystop/feathers-service-verify-reset/blob/dee9722dda8642ac1169120f7fe305684eb616c0/src/index.js#L724-L727
34,510
SchizoDuckie/CreateReadUpdateDelete.js
cli/entitybuilder.js
injectForeignFields
function injectForeignFields(targetEntity) { switch (type) { case '1:1': return entityModifier.readEntityProperty(targetEntity, 'fields').then(function(fields) { fields.push(entity.primary); entityModifier.modifyEntityProperty(targetEntity, 'fields', JSON.stringify(fields)); return targetEntity; }); case '1:many': break; case 'many:1': return entityModifier.readEntityProperty(targetEntity, 'fields').then(function(fields) { fields.push(entity.primary); entityModifier.modifyEntityProperty(targetEntity, 'fields', JSON.stringify(fields)); return targetEntity; }); case 'many:many': break; } }
javascript
function injectForeignFields(targetEntity) { switch (type) { case '1:1': return entityModifier.readEntityProperty(targetEntity, 'fields').then(function(fields) { fields.push(entity.primary); entityModifier.modifyEntityProperty(targetEntity, 'fields', JSON.stringify(fields)); return targetEntity; }); case '1:many': break; case 'many:1': return entityModifier.readEntityProperty(targetEntity, 'fields').then(function(fields) { fields.push(entity.primary); entityModifier.modifyEntityProperty(targetEntity, 'fields', JSON.stringify(fields)); return targetEntity; }); case 'many:many': break; } }
[ "function", "injectForeignFields", "(", "targetEntity", ")", "{", "switch", "(", "type", ")", "{", "case", "'1:1'", ":", "return", "entityModifier", ".", "readEntityProperty", "(", "targetEntity", ",", "'fields'", ")", ".", "then", "(", "function", "(", "field...
- find foreign entities to modify - inject foreign keys where needed - output changes to foreign entity
[ "-", "find", "foreign", "entities", "to", "modify", "-", "inject", "foreign", "keys", "where", "needed", "-", "output", "changes", "to", "foreign", "entity" ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/cli/entitybuilder.js#L69-L88
34,511
graphology/graphology-layout-forceatlas2
supervisor.js
FA2LayoutSupervisor
function FA2LayoutSupervisor(graph, params) { params = params || {}; // Validation if (!isGraph(graph)) throw new Error('graphology-layout-forceatlas2/worker: the given graph is not a valid graphology instance.'); // Validating settings var settings = helpers.assign({}, DEFAULT_SETTINGS, params.settings), validationError = helpers.validateSettings(settings); if (validationError) throw new Error('graphology-layout-forceatlas2/worker: ' + validationError.message); // Properties this.worker = new Worker(); this.graph = graph; this.settings = settings; this.matrices = null; this.running = false; this.killed = false; // Binding listeners this.handleMessage = this.handleMessage.bind(this); this.worker.addEventListener('message', this.handleMessage.bind(this)); }
javascript
function FA2LayoutSupervisor(graph, params) { params = params || {}; // Validation if (!isGraph(graph)) throw new Error('graphology-layout-forceatlas2/worker: the given graph is not a valid graphology instance.'); // Validating settings var settings = helpers.assign({}, DEFAULT_SETTINGS, params.settings), validationError = helpers.validateSettings(settings); if (validationError) throw new Error('graphology-layout-forceatlas2/worker: ' + validationError.message); // Properties this.worker = new Worker(); this.graph = graph; this.settings = settings; this.matrices = null; this.running = false; this.killed = false; // Binding listeners this.handleMessage = this.handleMessage.bind(this); this.worker.addEventListener('message', this.handleMessage.bind(this)); }
[ "function", "FA2LayoutSupervisor", "(", "graph", ",", "params", ")", "{", "params", "=", "params", "||", "{", "}", ";", "// Validation", "if", "(", "!", "isGraph", "(", "graph", ")", ")", "throw", "new", "Error", "(", "'graphology-layout-forceatlas2/worker: th...
Class representing a FA2 layout run by a webworker. @constructor @param {Graph} graph - Target graph. @param {object|number} params - Parameters: @param {object} [settings] - Settings.
[ "Class", "representing", "a", "FA2", "layout", "run", "by", "a", "webworker", "." ]
87c8664603ab15f8aa0e7aeb4960b9425a2811e2
https://github.com/graphology/graphology-layout-forceatlas2/blob/87c8664603ab15f8aa0e7aeb4960b9425a2811e2/supervisor.js#L22-L48
34,512
lemire/StablePriorityQueue.js
StablePriorityQueue.js
StablePriorityQueue
function StablePriorityQueue(comparator) { this.array = []; this.size = 0; this.runningcounter = 0; this.compare = comparator || defaultcomparator; this.stable_compare = function(a, b) { var cmp = this.compare(a.value,b.value); return (cmp < 0) || ( (cmp == 0) && (a.counter < b.counter) ); } }
javascript
function StablePriorityQueue(comparator) { this.array = []; this.size = 0; this.runningcounter = 0; this.compare = comparator || defaultcomparator; this.stable_compare = function(a, b) { var cmp = this.compare(a.value,b.value); return (cmp < 0) || ( (cmp == 0) && (a.counter < b.counter) ); } }
[ "function", "StablePriorityQueue", "(", "comparator", ")", "{", "this", ".", "array", "=", "[", "]", ";", "this", ".", "size", "=", "0", ";", "this", ".", "runningcounter", "=", "0", ";", "this", ".", "compare", "=", "comparator", "||", "defaultcomparato...
the provided comparator function should take a, b and return a negative number when a < b and equality when a == b
[ "the", "provided", "comparator", "function", "should", "take", "a", "b", "and", "return", "a", "negative", "number", "when", "a", "<", "b", "and", "equality", "when", "a", "==", "b" ]
4cd847cb93cae050f87b6dddba8d2252f947ac6d
https://github.com/lemire/StablePriorityQueue.js/blob/4cd847cb93cae050f87b6dddba8d2252f947ac6d/StablePriorityQueue.js#L36-L45
34,513
lemire/StablePriorityQueue.js
StablePriorityQueue.js
function () { // main code var x = new StablePriorityQueue(function (a, b) { return a.name < b.name ? -1 : (a.name > b.name ? 1 : 0) ; }); x.add({name:"Jack", age:31}); x.add({name:"Anna", age:111}); x.add({name:"Jack", age:46}); x.add({name:"Jack", age:11}); x.add({name:"Abba", age:31}); x.add({name:"Abba", age:30}); while (!x.isEmpty()) { console.log(x.poll()); } x = new StablePriorityQueue(function(a, b) { return a.energy - b.energy; }); [{ name: 'player', energy: 10}, { name: 'monster1', energy: 10}, { name: 'monster2', energy: 10}, { name: 'monster3', energy: 10} ].forEach(function(o){ x.add(o); }) while (!x.isEmpty()) { console.log(x.poll()); } }
javascript
function () { // main code var x = new StablePriorityQueue(function (a, b) { return a.name < b.name ? -1 : (a.name > b.name ? 1 : 0) ; }); x.add({name:"Jack", age:31}); x.add({name:"Anna", age:111}); x.add({name:"Jack", age:46}); x.add({name:"Jack", age:11}); x.add({name:"Abba", age:31}); x.add({name:"Abba", age:30}); while (!x.isEmpty()) { console.log(x.poll()); } x = new StablePriorityQueue(function(a, b) { return a.energy - b.energy; }); [{ name: 'player', energy: 10}, { name: 'monster1', energy: 10}, { name: 'monster2', energy: 10}, { name: 'monster3', energy: 10} ].forEach(function(o){ x.add(o); }) while (!x.isEmpty()) { console.log(x.poll()); } }
[ "function", "(", ")", "{", "// main code", "var", "x", "=", "new", "StablePriorityQueue", "(", "function", "(", "a", ",", "b", ")", "{", "return", "a", ".", "name", "<", "b", ".", "name", "?", "-", "1", ":", "(", "a", ".", "name", ">", "b", "."...
just for illustration purposes
[ "just", "for", "illustration", "purposes" ]
4cd847cb93cae050f87b6dddba8d2252f947ac6d
https://github.com/lemire/StablePriorityQueue.js/blob/4cd847cb93cae050f87b6dddba8d2252f947ac6d/StablePriorityQueue.js#L185-L213
34,514
FormidableLabs/express-winston-middleware
Gruntfile.js
function (obj) { var toc = [], tocTmpl = _.template("* [<%= heading %>](#<%= id %>)\n"), sectionTmpl = _.template("### <%= summary %>\n\n<%= body %>\n"); // Finesse comment markdown data. // Also, statefully create TOC. var sections = _.chain(obj) .filter(function (c) { return !c.isPrivate && !c.ignore && _.any(c.tags, function (t) { return t.type === "api" && t.visibility === "public"; }); }) .map(function (c) { // Add to TOC. toc.push(tocTmpl({ heading: c.description.summary, id: _headingId(c.description.summary) })); return sectionTmpl(c.description); }) .value() .join(""); return "\n" + toc.join("") + "\n" + sections; }
javascript
function (obj) { var toc = [], tocTmpl = _.template("* [<%= heading %>](#<%= id %>)\n"), sectionTmpl = _.template("### <%= summary %>\n\n<%= body %>\n"); // Finesse comment markdown data. // Also, statefully create TOC. var sections = _.chain(obj) .filter(function (c) { return !c.isPrivate && !c.ignore && _.any(c.tags, function (t) { return t.type === "api" && t.visibility === "public"; }); }) .map(function (c) { // Add to TOC. toc.push(tocTmpl({ heading: c.description.summary, id: _headingId(c.description.summary) })); return sectionTmpl(c.description); }) .value() .join(""); return "\n" + toc.join("") + "\n" + sections; }
[ "function", "(", "obj", ")", "{", "var", "toc", "=", "[", "]", ",", "tocTmpl", "=", "_", ".", "template", "(", "\"* [<%= heading %>](#<%= id %>)\\n\"", ")", ",", "sectionTmpl", "=", "_", ".", "template", "(", "\"### <%= summary %>\\n\\n<%= body %>\\n\"", ")", ...
Generate Markdown API snippets from dox object.
[ "Generate", "Markdown", "API", "snippets", "from", "dox", "object", "." ]
50714a16eaf191adfba03f00d0827e56ed4a30f9
https://github.com/FormidableLabs/express-winston-middleware/blob/50714a16eaf191adfba03f00d0827e56ed4a30f9/Gruntfile.js#L10-L36
34,515
graphology/graphology-layout-forceatlas2
index.js
abstractSynchronousLayout
function abstractSynchronousLayout(assign, graph, params) { if (!isGraph(graph)) throw new Error('graphology-layout-forceatlas2: the given graph is not a valid graphology instance.'); if (typeof params === 'number') params = {iterations: params}; var iterations = params.iterations; if (typeof iterations !== 'number') throw new Error('graphology-layout-forceatlas2: invalid number of iterations.'); if (iterations <= 0) throw new Error('graphology-layout-forceatlas2: you should provide a positive number of iterations.'); // Validating settings var settings = helpers.assign({}, DEFAULT_SETTINGS, params.settings), validationError = helpers.validateSettings(settings); if (validationError) throw new Error('graphology-layout-forceatlas2: ' + validationError.message); // Building matrices var matrices = helpers.graphToByteArrays(graph), i; // Iterating for (i = 0; i < iterations; i++) iterate(settings, matrices.nodes, matrices.edges); // Applying if (assign) { helpers.applyLayoutChanges(graph, matrices.nodes); return; } return helpers.collectLayoutChanges(graph, matrices.nodes); }
javascript
function abstractSynchronousLayout(assign, graph, params) { if (!isGraph(graph)) throw new Error('graphology-layout-forceatlas2: the given graph is not a valid graphology instance.'); if (typeof params === 'number') params = {iterations: params}; var iterations = params.iterations; if (typeof iterations !== 'number') throw new Error('graphology-layout-forceatlas2: invalid number of iterations.'); if (iterations <= 0) throw new Error('graphology-layout-forceatlas2: you should provide a positive number of iterations.'); // Validating settings var settings = helpers.assign({}, DEFAULT_SETTINGS, params.settings), validationError = helpers.validateSettings(settings); if (validationError) throw new Error('graphology-layout-forceatlas2: ' + validationError.message); // Building matrices var matrices = helpers.graphToByteArrays(graph), i; // Iterating for (i = 0; i < iterations; i++) iterate(settings, matrices.nodes, matrices.edges); // Applying if (assign) { helpers.applyLayoutChanges(graph, matrices.nodes); return; } return helpers.collectLayoutChanges(graph, matrices.nodes); }
[ "function", "abstractSynchronousLayout", "(", "assign", ",", "graph", ",", "params", ")", "{", "if", "(", "!", "isGraph", "(", "graph", ")", ")", "throw", "new", "Error", "(", "'graphology-layout-forceatlas2: the given graph is not a valid graphology instance.'", ")", ...
Asbtract function used to run a certain number of iterations. @param {boolean} assign - Whether to assign positions. @param {Graph} graph - Target graph. @param {object|number} params - If number, params.iterations, else: @param {number} iterations - Number of iterations. @param {object} [settings] - Settings. @return {object|undefined}
[ "Asbtract", "function", "used", "to", "run", "a", "certain", "number", "of", "iterations", "." ]
87c8664603ab15f8aa0e7aeb4960b9425a2811e2
https://github.com/graphology/graphology-layout-forceatlas2/blob/87c8664603ab15f8aa0e7aeb4960b9425a2811e2/index.js#L23-L60
34,516
graphology/graphology-layout-forceatlas2
index.js
inferSettings
function inferSettings(graph) { var order = graph.order; return { barnesHutOptimize: order > 2000, strongGravityMode: true, gravity: 0.05, scalingRatio: 10, slowDown: 1 + Math.log(order) }; }
javascript
function inferSettings(graph) { var order = graph.order; return { barnesHutOptimize: order > 2000, strongGravityMode: true, gravity: 0.05, scalingRatio: 10, slowDown: 1 + Math.log(order) }; }
[ "function", "inferSettings", "(", "graph", ")", "{", "var", "order", "=", "graph", ".", "order", ";", "return", "{", "barnesHutOptimize", ":", "order", ">", "2000", ",", "strongGravityMode", ":", "true", ",", "gravity", ":", "0.05", ",", "scalingRatio", ":...
Function returning sane layout settings for the given graph. @param {Graph} graph - Target graph. @return {object}
[ "Function", "returning", "sane", "layout", "settings", "for", "the", "given", "graph", "." ]
87c8664603ab15f8aa0e7aeb4960b9425a2811e2
https://github.com/graphology/graphology-layout-forceatlas2/blob/87c8664603ab15f8aa0e7aeb4960b9425a2811e2/index.js#L68-L78
34,517
jaredhanson/kerouac
lib/page.js
Page
function Page(path, ctx) { events.EventEmitter.call(this); this.path = path; this.context = ctx; this._isOpen = false; }
javascript
function Page(path, ctx) { events.EventEmitter.call(this); this.path = path; this.context = ctx; this._isOpen = false; }
[ "function", "Page", "(", "path", ",", "ctx", ")", "{", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "path", "=", "path", ";", "this", ".", "context", "=", "ctx", ";", "this", ".", "_isOpen", "=", "false", ";", "...
Initialize a new `Page`. `Page` represents a page in a site. In the process of generating a page, it will pass through a chain of middleware functions. It is expected that one of these middleware will write a page, either directly by calling `write()` and `end()`, or indirectly by `render()`ing a layout. @param {String} path @api private
[ "Initialize", "a", "new", "Page", "." ]
ab479484f56c1a530467e726f1271d08593b29c8
https://github.com/jaredhanson/kerouac/blob/ab479484f56c1a530467e726f1271d08593b29c8/lib/page.js#L22-L27
34,518
jaredhanson/kerouac
lib/application.js
dispatch
function dispatch(req, done) { var site = req.site , path = upath.join(site.path || '', req.path) , parent = site.parent; while (parent) { path = upath.join(parent.path || '', path); parent = parent.parent; } console.log('# ' + path); var page = new Page(path, req.context); pages.push(page); page.once('close', done); //page.site = self; //page.pages = pages; self.handle(page); }
javascript
function dispatch(req, done) { var site = req.site , path = upath.join(site.path || '', req.path) , parent = site.parent; while (parent) { path = upath.join(parent.path || '', path); parent = parent.parent; } console.log('# ' + path); var page = new Page(path, req.context); pages.push(page); page.once('close', done); //page.site = self; //page.pages = pages; self.handle(page); }
[ "function", "dispatch", "(", "req", ",", "done", ")", "{", "var", "site", "=", "req", ".", "site", ",", "path", "=", "upath", ".", "join", "(", "site", ".", "path", "||", "''", ",", "req", ".", "path", ")", ",", "parent", "=", "site", ".", "par...
Binding is complete, producing a complete list of all pages that need to be generated. Dispatch those pages into the application, so that the content can be written to files which constitute the static site.
[ "Binding", "is", "complete", "producing", "a", "complete", "list", "of", "all", "pages", "that", "need", "to", "be", "generated", ".", "Dispatch", "those", "pages", "into", "the", "application", "so", "that", "the", "content", "can", "be", "written", "to", ...
ab479484f56c1a530467e726f1271d08593b29c8
https://github.com/jaredhanson/kerouac/blob/ab479484f56c1a530467e726f1271d08593b29c8/lib/application.js#L650-L668
34,519
SchizoDuckie/CreateReadUpdateDelete.js
cli/existingentitymodifier.js
rewrite_code
function rewrite_code(code, node, replacement_string) { return code.substr(0, node.start.pos) + replacement_string + code.substr(node.end.endpos); }
javascript
function rewrite_code(code, node, replacement_string) { return code.substr(0, node.start.pos) + replacement_string + code.substr(node.end.endpos); }
[ "function", "rewrite_code", "(", "code", ",", "node", ",", "replacement_string", ")", "{", "return", "code", ".", "substr", "(", "0", ",", "node", ".", "start", ".", "pos", ")", "+", "replacement_string", "+", "code", ".", "substr", "(", "node", ".", "...
Modify code string with a new value based on start and end position of an UglifyJS.AST_Node @param {string} code code to modify @param {UglifyJS.AST_Node} node node to replace the content for @param {string} replacement_string replacement js encoded value for the property @return {string} modified code
[ "Modify", "code", "string", "with", "a", "new", "value", "based", "on", "start", "and", "end", "position", "of", "an", "UglifyJS", ".", "AST_Node" ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/cli/existingentitymodifier.js#L40-L42
34,520
ceee/grunt-datauri
tasks/datauri.js
generateData
function generateData( filepath ) { var dataObj = new datauri( filepath ); return { data: dataObj.content, path: filepath }; }
javascript
function generateData( filepath ) { var dataObj = new datauri( filepath ); return { data: dataObj.content, path: filepath }; }
[ "function", "generateData", "(", "filepath", ")", "{", "var", "dataObj", "=", "new", "datauri", "(", "filepath", ")", ";", "return", "{", "data", ":", "dataObj", ".", "content", ",", "path", ":", "filepath", "}", ";", "}" ]
generates a datauri object from file ~~~~~~~~~~~~~~~~~~~~~
[ "generates", "a", "datauri", "object", "from", "file", "~~~~~~~~~~~~~~~~~~~~~" ]
462a0ab9a72886f2a54ec8ba5dcc41a747777cca
https://github.com/ceee/grunt-datauri/blob/462a0ab9a72886f2a54ec8ba5dcc41a747777cca/tasks/datauri.js#L72-L80
34,521
ceee/grunt-datauri
tasks/datauri.js
generateCss
function generateCss( filepath, data ) { var filetype = filepath.split( '.' ).pop().toLowerCase(); var className; var template; className = options.classPrefix + path.basename( data.path ).split( '.' )[0] + options.classSuffix; filetype = options.usePlaceholder ? filetype : filetype + '_no'; if (options.variables) { template = cssTemplates.variables; } else { template = cssTemplates[ filetype ] || cssTemplates.default; } return template.replace( '{{class}}', className ).replace( '{{data}}', data.data ); }
javascript
function generateCss( filepath, data ) { var filetype = filepath.split( '.' ).pop().toLowerCase(); var className; var template; className = options.classPrefix + path.basename( data.path ).split( '.' )[0] + options.classSuffix; filetype = options.usePlaceholder ? filetype : filetype + '_no'; if (options.variables) { template = cssTemplates.variables; } else { template = cssTemplates[ filetype ] || cssTemplates.default; } return template.replace( '{{class}}', className ).replace( '{{data}}', data.data ); }
[ "function", "generateCss", "(", "filepath", ",", "data", ")", "{", "var", "filetype", "=", "filepath", ".", "split", "(", "'.'", ")", ".", "pop", "(", ")", ".", "toLowerCase", "(", ")", ";", "var", "className", ";", "var", "template", ";", "className",...
wraps daturi in css class ~~~~~~~~~~~~~~~~~~~~~
[ "wraps", "daturi", "in", "css", "class", "~~~~~~~~~~~~~~~~~~~~~" ]
462a0ab9a72886f2a54ec8ba5dcc41a747777cca
https://github.com/ceee/grunt-datauri/blob/462a0ab9a72886f2a54ec8ba5dcc41a747777cca/tasks/datauri.js#L85-L104
34,522
nathanpdaniel/uber-api
lib/index.js
getHistory
function getHistory(callback) { if (_.isUndefined(callback)) { } else { var u = config.baseUrl + ((api_version == "v1") ? "v1.1" : api_version) + "/history", tokenData = this.getAuthToken(); if (tokenData.type != "bearer") { throw new Error("Invalid token type. Must use a token of type bearer."); } return helper.get(tokenData, u, callback); } }
javascript
function getHistory(callback) { if (_.isUndefined(callback)) { } else { var u = config.baseUrl + ((api_version == "v1") ? "v1.1" : api_version) + "/history", tokenData = this.getAuthToken(); if (tokenData.type != "bearer") { throw new Error("Invalid token type. Must use a token of type bearer."); } return helper.get(tokenData, u, callback); } }
[ "function", "getHistory", "(", "callback", ")", "{", "if", "(", "_", ".", "isUndefined", "(", "callback", ")", ")", "{", "}", "else", "{", "var", "u", "=", "config", ".", "baseUrl", "+", "(", "(", "api_version", "==", "\"v1\"", ")", "?", "\"v1.1\"", ...
getHistory Get the currently logged in user history @param Function A callback function which takes two paramenters
[ "getHistory", "Get", "the", "currently", "logged", "in", "user", "history" ]
75682acf50fa84ad2d0e0bc144ec3d4b779da8b4
https://github.com/nathanpdaniel/uber-api/blob/75682acf50fa84ad2d0e0bc144ec3d4b779da8b4/lib/index.js#L150-L160
34,523
nathanpdaniel/uber-api
lib/index.js
getUserProfile
function getUserProfile(callback) { if (_.isUndefined(callback)) { } else { var u = baseUrl + "/me"; var tokenData = this.getAuthToken(); if (tokenData.type != "bearer") { throw new Error("Invalid token type. Must use a token of type bearer."); } return helper.get(tokenData, u, callback); } }
javascript
function getUserProfile(callback) { if (_.isUndefined(callback)) { } else { var u = baseUrl + "/me"; var tokenData = this.getAuthToken(); if (tokenData.type != "bearer") { throw new Error("Invalid token type. Must use a token of type bearer."); } return helper.get(tokenData, u, callback); } }
[ "function", "getUserProfile", "(", "callback", ")", "{", "if", "(", "_", ".", "isUndefined", "(", "callback", ")", ")", "{", "}", "else", "{", "var", "u", "=", "baseUrl", "+", "\"/me\"", ";", "var", "tokenData", "=", "this", ".", "getAuthToken", "(", ...
getMe Get the currently logged in user profile. @param Function A callback function which takes two parameters
[ "getMe", "Get", "the", "currently", "logged", "in", "user", "profile", "." ]
75682acf50fa84ad2d0e0bc144ec3d4b779da8b4
https://github.com/nathanpdaniel/uber-api/blob/75682acf50fa84ad2d0e0bc144ec3d4b779da8b4/lib/index.js#L167-L177
34,524
SchizoDuckie/CreateReadUpdateDelete.js
cli/entityfinder.js
function() { return new Promise(function(resolve, reject) { exec("find . ! -name '" + __filename.split('/').pop() + "' -iname '*\.js' | xargs grep 'CRUD.Entity.call(this);' -isl", { timeout: 3000, cwd: process.cwd() }, function(err, stdout, stdin) { var results = stdout.trim().split('\n'); for (var i = 0; i < results.length; i++) { eval(fs.readFileSync(results[i]) + ''); } resolve(Object.keys(CRUD.entities)); }); }); }
javascript
function() { return new Promise(function(resolve, reject) { exec("find . ! -name '" + __filename.split('/').pop() + "' -iname '*\.js' | xargs grep 'CRUD.Entity.call(this);' -isl", { timeout: 3000, cwd: process.cwd() }, function(err, stdout, stdin) { var results = stdout.trim().split('\n'); for (var i = 0; i < results.length; i++) { eval(fs.readFileSync(results[i]) + ''); } resolve(Object.keys(CRUD.entities)); }); }); }
[ "function", "(", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "exec", "(", "\"find . ! -name '\"", "+", "__filename", ".", "split", "(", "'/'", ")", ".", "pop", "(", ")", "+", "\"' -iname '*\\.js' | xargs ...
Find and register all CRUD entities under the base dir. evaluates the files @return {Promise} array of defined CRUD entities
[ "Find", "and", "register", "all", "CRUD", "entities", "under", "the", "base", "dir", ".", "evaluates", "the", "files" ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/cli/entityfinder.js#L13-L26
34,525
SchizoDuckie/CreateReadUpdateDelete.js
cli/entityfinder.js
function() { return new Promise(function(resolve, reject) { exec("find . ! -name '" + __filename.split('/').pop() + "' -iname '*\.js' | xargs grep 'CRUD.Entity.call(this);' -isl", { timeout: 3000, cwd: process.cwd() }, function(err, stdout, stdin) { var results = stdout.trim().split('\n'); var entities = {}; // iterate all found js files and search for CRUD.define calls results.map(function(filename) { if (filename.trim() == '') return; var code = fs.readFileSync(filename) + ''; var ast = UglifyJS.parse(code); ast.walk(new UglifyJS.TreeWalker(function(node) { if (node instanceof UglifyJS.AST_Call && node.start.value == 'CRUD' && node.expression.property == 'define') { entities[node.args[0].start.value] = filename; } })); }); resolve(entities); }); }); }
javascript
function() { return new Promise(function(resolve, reject) { exec("find . ! -name '" + __filename.split('/').pop() + "' -iname '*\.js' | xargs grep 'CRUD.Entity.call(this);' -isl", { timeout: 3000, cwd: process.cwd() }, function(err, stdout, stdin) { var results = stdout.trim().split('\n'); var entities = {}; // iterate all found js files and search for CRUD.define calls results.map(function(filename) { if (filename.trim() == '') return; var code = fs.readFileSync(filename) + ''; var ast = UglifyJS.parse(code); ast.walk(new UglifyJS.TreeWalker(function(node) { if (node instanceof UglifyJS.AST_Call && node.start.value == 'CRUD' && node.expression.property == 'define') { entities[node.args[0].start.value] = filename; } })); }); resolve(entities); }); }); }
[ "function", "(", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "exec", "(", "\"find . ! -name '\"", "+", "__filename", ".", "split", "(", "'/'", ")", ".", "pop", "(", ")", "+", "\"' -iname '*\\.js' | xargs ...
Find the filenames for all CRUD entities under the base dir @return {Promise} object with keys: entity names, values: filename
[ "Find", "the", "filenames", "for", "all", "CRUD", "entities", "under", "the", "base", "dir" ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/cli/entityfinder.js#L31-L55
34,526
sapegin/react-group
index.js
Group
function Group(props) { var children = React.Children.toArray(props.children).filter(Boolean); if (children.length === 1) { return children; } // Insert separators var separator = props.separator; var separatorIsElement = React.isValidElement(separator); var items = [children.shift()]; children.forEach(function(item, index) { if (separatorIsElement) { var key = 'separator-' + (item.key || index); separator = React.cloneElement(separator, { key: key }); } items.push(separator, item); }); return items; }
javascript
function Group(props) { var children = React.Children.toArray(props.children).filter(Boolean); if (children.length === 1) { return children; } // Insert separators var separator = props.separator; var separatorIsElement = React.isValidElement(separator); var items = [children.shift()]; children.forEach(function(item, index) { if (separatorIsElement) { var key = 'separator-' + (item.key || index); separator = React.cloneElement(separator, { key: key }); } items.push(separator, item); }); return items; }
[ "function", "Group", "(", "props", ")", "{", "var", "children", "=", "React", ".", "Children", ".", "toArray", "(", "props", ".", "children", ")", ".", "filter", "(", "Boolean", ")", ";", "if", "(", "children", ".", "length", "===", "1", ")", "{", ...
React component to render collection of items separated by space or other separator. @visibleName React Group
[ "React", "component", "to", "render", "collection", "of", "items", "separated", "by", "space", "or", "other", "separator", "." ]
13dbc3a37be17a1bcccb86277f04685fdbb7aeeb
https://github.com/sapegin/react-group/blob/13dbc3a37be17a1bcccb86277f04685fdbb7aeeb/index.js#L9-L28
34,527
jaredhanson/kerouac
lib/index.js
createSite
function createSite() { function app(page) { app.handle(page); } mixin(app, EventEmitter.prototype, false); mixin(app, proto, false); app.init(); return app; }
javascript
function createSite() { function app(page) { app.handle(page); } mixin(app, EventEmitter.prototype, false); mixin(app, proto, false); app.init(); return app; }
[ "function", "createSite", "(", ")", "{", "function", "app", "(", "page", ")", "{", "app", ".", "handle", "(", "page", ")", ";", "}", "mixin", "(", "app", ",", "EventEmitter", ".", "prototype", ",", "false", ")", ";", "mixin", "(", "app", ",", "prot...
Create a Kerouac site. @return {Function} @api public
[ "Create", "a", "Kerouac", "site", "." ]
ab479484f56c1a530467e726f1271d08593b29c8
https://github.com/jaredhanson/kerouac/blob/ab479484f56c1a530467e726f1271d08593b29c8/lib/index.js#L16-L22
34,528
ethjs/ethjs-provider-http
src/index.js
invalidResponseError
function invalidResponseError(result, host) { const message = !!result && !!result.error && !!result.error.message ? `[ethjs-provider-http] ${result.error.message}` : `[ethjs-provider-http] Invalid JSON RPC response from host provider ${host}: ${JSON.stringify(result, null, 2)}`; return new Error(message); }
javascript
function invalidResponseError(result, host) { const message = !!result && !!result.error && !!result.error.message ? `[ethjs-provider-http] ${result.error.message}` : `[ethjs-provider-http] Invalid JSON RPC response from host provider ${host}: ${JSON.stringify(result, null, 2)}`; return new Error(message); }
[ "function", "invalidResponseError", "(", "result", ",", "host", ")", "{", "const", "message", "=", "!", "!", "result", "&&", "!", "!", "result", ".", "error", "&&", "!", "!", "result", ".", "error", ".", "message", "?", "`", "${", "result", ".", "err...
InvalidResponseError helper for invalid errors.
[ "InvalidResponseError", "helper", "for", "invalid", "errors", "." ]
03f911db08757bd5edeb5b613255a25df0124d84
https://github.com/ethjs/ethjs-provider-http/blob/03f911db08757bd5edeb5b613255a25df0124d84/src/index.js#L15-L18
34,529
ethjs/ethjs-provider-http
src/index.js
HttpProvider
function HttpProvider(host, timeout) { if (!(this instanceof HttpProvider)) { throw new Error('[ethjs-provider-http] the HttpProvider instance requires the "new" flag in order to function normally (e.g. `const eth = new Eth(new HttpProvider());`).'); } if (typeof host !== 'string') { throw new Error('[ethjs-provider-http] the HttpProvider instance requires that the host be specified (e.g. `new HttpProvider("http://localhost:8545")` or via service like infura `new HttpProvider("http://ropsten.infura.io")`)'); } const self = this; self.host = host; self.timeout = timeout || 0; }
javascript
function HttpProvider(host, timeout) { if (!(this instanceof HttpProvider)) { throw new Error('[ethjs-provider-http] the HttpProvider instance requires the "new" flag in order to function normally (e.g. `const eth = new Eth(new HttpProvider());`).'); } if (typeof host !== 'string') { throw new Error('[ethjs-provider-http] the HttpProvider instance requires that the host be specified (e.g. `new HttpProvider("http://localhost:8545")` or via service like infura `new HttpProvider("http://ropsten.infura.io")`)'); } const self = this; self.host = host; self.timeout = timeout || 0; }
[ "function", "HttpProvider", "(", "host", ",", "timeout", ")", "{", "if", "(", "!", "(", "this", "instanceof", "HttpProvider", ")", ")", "{", "throw", "new", "Error", "(", "'[ethjs-provider-http] the HttpProvider instance requires the \"new\" flag in order to function norm...
HttpProvider should be used to send rpc calls over http
[ "HttpProvider", "should", "be", "used", "to", "send", "rpc", "calls", "over", "http" ]
03f911db08757bd5edeb5b613255a25df0124d84
https://github.com/ethjs/ethjs-provider-http/blob/03f911db08757bd5edeb5b613255a25df0124d84/src/index.js#L23-L30
34,530
k3erg/marantz-denon-telnet
index.js
function(ip) { this.connectionparams = { host: ip, port: 23, timeout: 1000, // The RESPONSE should be sent within 200ms of receiving the request COMMAND. (plus network delay) sendTimeout: 1200, negotiationMandatory: false, ors: '\r', // Set outbound record separator irs: '\r' }; this.cmdCue = []; this.connection = null; }
javascript
function(ip) { this.connectionparams = { host: ip, port: 23, timeout: 1000, // The RESPONSE should be sent within 200ms of receiving the request COMMAND. (plus network delay) sendTimeout: 1200, negotiationMandatory: false, ors: '\r', // Set outbound record separator irs: '\r' }; this.cmdCue = []; this.connection = null; }
[ "function", "(", "ip", ")", "{", "this", ".", "connectionparams", "=", "{", "host", ":", "ip", ",", "port", ":", "23", ",", "timeout", ":", "1000", ",", "// The RESPONSE should be sent within 200ms of receiving the request COMMAND. (plus network delay)", "sendTimeout",...
Returns an instance of MarantzDenonTelnet that can handle telnet commands to the given IP. @constructor @param {string} ip Address of the AVR.
[ "Returns", "an", "instance", "of", "MarantzDenonTelnet", "that", "can", "handle", "telnet", "commands", "to", "the", "given", "IP", "." ]
94ec2a19afd462a5ed82b38cfac33967519a03b5
https://github.com/k3erg/marantz-denon-telnet/blob/94ec2a19afd462a5ed82b38cfac33967519a03b5/index.js#L27-L39
34,531
MicrosoftDX/kurvejs
Samples/Client/Angular2/protractor.config.js
sendKeys
function sendKeys(element, str) { return str.split('').reduce(function (promise, char) { return promise.then(function () { return element.sendKeys(char); }); }, element.getAttribute('value')); // better to create a resolved promise here but ... don't know how with protractor; }
javascript
function sendKeys(element, str) { return str.split('').reduce(function (promise, char) { return promise.then(function () { return element.sendKeys(char); }); }, element.getAttribute('value')); // better to create a resolved promise here but ... don't know how with protractor; }
[ "function", "sendKeys", "(", "element", ",", "str", ")", "{", "return", "str", ".", "split", "(", "''", ")", ".", "reduce", "(", "function", "(", "promise", ",", "char", ")", "{", "return", "promise", ".", "then", "(", "function", "(", ")", "{", "r...
Hack - because of bug with protractor send keys
[ "Hack", "-", "because", "of", "bug", "with", "protractor", "send", "keys" ]
72996425f1041ece8b4aa151db26c19a79f72f98
https://github.com/MicrosoftDX/kurvejs/blob/72996425f1041ece8b4aa151db26c19a79f72f98/Samples/Client/Angular2/protractor.config.js#L70-L77
34,532
SchizoDuckie/CreateReadUpdateDelete.js
src/CRUD.SqliteAdapter.js
insertQuerySuccess
function insertQuerySuccess(resultSet) { resultSet.Action = 'inserted'; resultSet.ID = resultSet.rs.insertId; CRUD.stats.writesExecuted++; return resultSet; }
javascript
function insertQuerySuccess(resultSet) { resultSet.Action = 'inserted'; resultSet.ID = resultSet.rs.insertId; CRUD.stats.writesExecuted++; return resultSet; }
[ "function", "insertQuerySuccess", "(", "resultSet", ")", "{", "resultSet", ".", "Action", "=", "'inserted'", ";", "resultSet", ".", "ID", "=", "resultSet", ".", "rs", ".", "insertId", ";", "CRUD", ".", "stats", ".", "writesExecuted", "++", ";", "return", "...
Generic insert query callback that logs writesExecuted and sets inserted action + id @param {resultSet} resultSet resulting from an insert query. @return {resultSet} enriched resultSet with Action executed and ID property
[ "Generic", "insert", "query", "callback", "that", "logs", "writesExecuted", "and", "sets", "inserted", "action", "+", "id" ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/src/CRUD.SqliteAdapter.js#L71-L76
34,533
SchizoDuckie/CreateReadUpdateDelete.js
src/CRUD.SqliteAdapter.js
insertQueryError
function insertQueryError(err, tx) { CRUD.stats.writesExecuted++; console.error("Insert query error: ", err); return err; }
javascript
function insertQueryError(err, tx) { CRUD.stats.writesExecuted++; console.error("Insert query error: ", err); return err; }
[ "function", "insertQueryError", "(", "err", ",", "tx", ")", "{", "CRUD", ".", "stats", ".", "writesExecuted", "++", ";", "console", ".", "error", "(", "\"Insert query error: \"", ",", "err", ")", ";", "return", "err", ";", "}" ]
Generic insert query error callback that logs writesExecuted and the error. @param {Error} err WebSQL error @param {Transaction} tx WebSQL Transaction @return {error}
[ "Generic", "insert", "query", "error", "callback", "that", "logs", "writesExecuted", "and", "the", "error", "." ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/src/CRUD.SqliteAdapter.js#L84-L88
34,534
SchizoDuckie/CreateReadUpdateDelete.js
src/CRUD.SqliteAdapter.js
parseSchemaInfo
function parseSchemaInfo(resultset) { for (var i = 0; i < resultset.rs.rows.length; i++) { var row = resultset.rs.rows.item(i); if (row.name.indexOf('sqlite_autoindex') > -1 || row.name == '__WebKitDatabaseInfoTable__') continue; if (row.type == 'table') { tables.push(row.tbl_name); } else if (row.type == 'index') { if (!(row.tbl_name in indexes)) { indexes[row.tbl_name] = []; } indexes[row.tbl_name].push(row.name); } } return; }
javascript
function parseSchemaInfo(resultset) { for (var i = 0; i < resultset.rs.rows.length; i++) { var row = resultset.rs.rows.item(i); if (row.name.indexOf('sqlite_autoindex') > -1 || row.name == '__WebKitDatabaseInfoTable__') continue; if (row.type == 'table') { tables.push(row.tbl_name); } else if (row.type == 'index') { if (!(row.tbl_name in indexes)) { indexes[row.tbl_name] = []; } indexes[row.tbl_name].push(row.name); } } return; }
[ "function", "parseSchemaInfo", "(", "resultset", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "resultset", ".", "rs", ".", "rows", ".", "length", ";", "i", "++", ")", "{", "var", "row", "=", "resultset", ".", "rs", ".", "rows", ".",...
Pre-Parse database schema info for further processing. Finds tables and indexes. @param {resultSet} database description @return {void} void
[ "Pre", "-", "Parse", "database", "schema", "info", "for", "further", "processing", ".", "Finds", "tables", "and", "indexes", "." ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/src/CRUD.SqliteAdapter.js#L111-L125
34,535
SchizoDuckie/CreateReadUpdateDelete.js
src/CRUD.SqliteAdapter.js
createTables
function createTables() { return Promise.all(Object.keys(CRUD.EntityManager.entities).map(function(entityName) { var entity = CRUD.EntityManager.entities[entityName]; if (tables.indexOf(entity.table) == -1) { if (!entity.createStatement) { throw "No create statement found for " + entity.getType() + ". Don't know how to create table."; } return db.execute(entity.createStatement).then(function() { tables.push(entity.table); localStorage.setItem('database.version.' + entity.table, ('migrations' in entity) ? Math.max.apply(Math, Object.keys(entity.migrations)) : 1); CRUD.log(entity.table + " table created."); return entity; }, function(err) { CRUD.log("Error creating " + entity.table, err, entity.createStatement); throw "Error creating table: " + entity.table; }).then(createFixtures).then(function() { CRUD.log("Table created and fixtures inserted for ", entityName); return; }); } return; })); }
javascript
function createTables() { return Promise.all(Object.keys(CRUD.EntityManager.entities).map(function(entityName) { var entity = CRUD.EntityManager.entities[entityName]; if (tables.indexOf(entity.table) == -1) { if (!entity.createStatement) { throw "No create statement found for " + entity.getType() + ". Don't know how to create table."; } return db.execute(entity.createStatement).then(function() { tables.push(entity.table); localStorage.setItem('database.version.' + entity.table, ('migrations' in entity) ? Math.max.apply(Math, Object.keys(entity.migrations)) : 1); CRUD.log(entity.table + " table created."); return entity; }, function(err) { CRUD.log("Error creating " + entity.table, err, entity.createStatement); throw "Error creating table: " + entity.table; }).then(createFixtures).then(function() { CRUD.log("Table created and fixtures inserted for ", entityName); return; }); } return; })); }
[ "function", "createTables", "(", ")", "{", "return", "Promise", ".", "all", "(", "Object", ".", "keys", "(", "CRUD", ".", "EntityManager", ".", "entities", ")", ".", "map", "(", "function", "(", "entityName", ")", "{", "var", "entity", "=", "CRUD", "."...
Iterate the list of registered entities and creates their tables if they don't exist. Run the migrations when needed if the table version is out of sync @return {void} void
[ "Iterate", "the", "list", "of", "registered", "entities", "and", "creates", "their", "tables", "if", "they", "don", "t", "exist", ".", "Run", "the", "migrations", "when", "needed", "if", "the", "table", "version", "is", "out", "of", "sync" ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/src/CRUD.SqliteAdapter.js#L132-L154
34,536
SchizoDuckie/CreateReadUpdateDelete.js
src/CRUD.SqliteAdapter.js
createIndexes
function createIndexes() { // create listed indexes if they don't already exist. return Promise.all(Object.keys(CRUD.EntityManager.entities).map(function(entityName) { var entity = CRUD.EntityManager.entities[entityName]; if (('indexes' in entity)) { return Promise.all(entity.indexes.map(function(index) { var indexName = index.replace(/\W/g, '') + '_idx'; if (!(entity.table in indexes) || indexes[entity.table].indexOf(indexName) == -1) { return db.execute("create index if not exists " + indexName + " on " + entity.table + " (" + index + ")").then(function(result) { CRUD.log("index created: ", entity.table, index, indexName); if (!(entity.table in indexes)) { indexes[entity.table] = []; } indexes[entity.table].push(indexName); return; }); } return; })); } })); }
javascript
function createIndexes() { // create listed indexes if they don't already exist. return Promise.all(Object.keys(CRUD.EntityManager.entities).map(function(entityName) { var entity = CRUD.EntityManager.entities[entityName]; if (('indexes' in entity)) { return Promise.all(entity.indexes.map(function(index) { var indexName = index.replace(/\W/g, '') + '_idx'; if (!(entity.table in indexes) || indexes[entity.table].indexOf(indexName) == -1) { return db.execute("create index if not exists " + indexName + " on " + entity.table + " (" + index + ")").then(function(result) { CRUD.log("index created: ", entity.table, index, indexName); if (!(entity.table in indexes)) { indexes[entity.table] = []; } indexes[entity.table].push(indexName); return; }); } return; })); } })); }
[ "function", "createIndexes", "(", ")", "{", "// create listed indexes if they don't already exist.", "return", "Promise", ".", "all", "(", "Object", ".", "keys", "(", "CRUD", ".", "EntityManager", ".", "entities", ")", ".", "map", "(", "function", "(", "entityName...
Iterate the list of existing and non-existing indexes for each entity and create the ones that don't exist. @return {void} void
[ "Iterate", "the", "list", "of", "existing", "and", "non", "-", "existing", "indexes", "for", "each", "entity", "and", "create", "the", "ones", "that", "don", "t", "exist", "." ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/src/CRUD.SqliteAdapter.js#L198-L219
34,537
SchizoDuckie/CreateReadUpdateDelete.js
src/CRUD.SqliteAdapter.js
createFixtures
function createFixtures(entity) { return new Promise(function(resolve, reject) { if (!entity.fixtures) return resolve(); return Promise.all(entity.fixtures.map(function(fixture) { CRUD.fromCache(entity.getType(), fixture).Persist(true); })).then(resolve, reject); }); }
javascript
function createFixtures(entity) { return new Promise(function(resolve, reject) { if (!entity.fixtures) return resolve(); return Promise.all(entity.fixtures.map(function(fixture) { CRUD.fromCache(entity.getType(), fixture).Persist(true); })).then(resolve, reject); }); }
[ "function", "createFixtures", "(", "entity", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "!", "entity", ".", "fixtures", ")", "return", "resolve", "(", ")", ";", "return", "Promise", ".", "...
Insert fixtures for an entity if they exist @param {CRUD.Entity} entity entity to insert fixtures for @return {Promise} that resolves when all fixtures were inserted or immediately when none are defined
[ "Insert", "fixtures", "for", "an", "entity", "if", "they", "exist" ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/src/CRUD.SqliteAdapter.js#L237-L244
34,538
SchizoDuckie/CreateReadUpdateDelete.js
src/CRUD.js
function(field, def) { var ret; if (field in this.__dirtyValues__) { ret = this.__dirtyValues__[field]; } else if (field in this.__values__) { ret = this.__values__[field]; } else if (CRUD.EntityManager.entities[this.getType()].fields.indexOf(field) > -1) { ret = (field in CRUD.EntityManager.entities[this.getType()].defaultValues) ? CRUD.EntityManager.entities[this.getType()].defaultValues[field] : null; } else { CRUD.log('Could not find field \'' + field + '\' in \'' + this.getType() + '\' (for get)'); } return ret; }
javascript
function(field, def) { var ret; if (field in this.__dirtyValues__) { ret = this.__dirtyValues__[field]; } else if (field in this.__values__) { ret = this.__values__[field]; } else if (CRUD.EntityManager.entities[this.getType()].fields.indexOf(field) > -1) { ret = (field in CRUD.EntityManager.entities[this.getType()].defaultValues) ? CRUD.EntityManager.entities[this.getType()].defaultValues[field] : null; } else { CRUD.log('Could not find field \'' + field + '\' in \'' + this.getType() + '\' (for get)'); } return ret; }
[ "function", "(", "field", ",", "def", ")", "{", "var", "ret", ";", "if", "(", "field", "in", "this", ".", "__dirtyValues__", ")", "{", "ret", "=", "this", ".", "__dirtyValues__", "[", "field", "]", ";", "}", "else", "if", "(", "field", "in", "this"...
Accessor. Gets one field, optionally returns the default value.
[ "Accessor", ".", "Gets", "one", "field", "optionally", "returns", "the", "default", "value", "." ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/src/CRUD.js#L366-L378
34,539
jaredhanson/kerouac
lib/route.js
Route
function Route(path, fns, options) { options = options || {}; this.path = path; this.fns = fns; this.regexp = pathRegexp(path, this.keys = [], options); }
javascript
function Route(path, fns, options) { options = options || {}; this.path = path; this.fns = fns; this.regexp = pathRegexp(path, this.keys = [], options); }
[ "function", "Route", "(", "path", ",", "fns", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "path", "=", "path", ";", "this", ".", "fns", "=", "fns", ";", "this", ".", "regexp", "=", "pathRegexp", "(", "pa...
Initialize a new `Route` with the given `path`, an array of callback `fns`, and `options`. Options: - `sensitive` enable case-sensitive routes - `strict` enable strict matching for trailing slashes @param {String} path @param {Array} fns @param {Object} options @api private
[ "Initialize", "a", "new", "Route", "with", "the", "given", "path", "an", "array", "of", "callback", "fns", "and", "options", "." ]
ab479484f56c1a530467e726f1271d08593b29c8
https://github.com/jaredhanson/kerouac/blob/ab479484f56c1a530467e726f1271d08593b29c8/lib/route.js#L18-L23
34,540
ShaneGH/analogue-time-picker
tools/generateHtmlFile.js
buildFile
function buildFile() { var reader = readline.createInterface({ input: fs.createReadStream(path.resolve("./src/assets/template.html")) }); var lines = []; reader.on("line", line => lines.push(line)); return new Promise(resolve => { reader.on("close", () => resolve(buildJsFileContents(lines))); }); }
javascript
function buildFile() { var reader = readline.createInterface({ input: fs.createReadStream(path.resolve("./src/assets/template.html")) }); var lines = []; reader.on("line", line => lines.push(line)); return new Promise(resolve => { reader.on("close", () => resolve(buildJsFileContents(lines))); }); }
[ "function", "buildFile", "(", ")", "{", "var", "reader", "=", "readline", ".", "createInterface", "(", "{", "input", ":", "fs", ".", "createReadStream", "(", "path", ".", "resolve", "(", "\"./src/assets/template.html\"", ")", ")", "}", ")", ";", "var", "li...
Build a promise which will generate css -> js file contents
[ "Build", "a", "promise", "which", "will", "generate", "css", "-", ">", "js", "file", "contents" ]
026c0c37608f749041dde375551f5ff16cd5621e
https://github.com/ShaneGH/analogue-time-picker/blob/026c0c37608f749041dde375551f5ff16cd5621e/tools/generateHtmlFile.js#L76-L87
34,541
chemerisuk/cordova-plugin-core-android-extensions
www/android/coreextensions.js
function(moveBack) { return new Promise(function(resolve, reject) { exec(resolve, reject, APP_PLUGIN_NAME, "minimizeApp", [moveBack || false]); }); }
javascript
function(moveBack) { return new Promise(function(resolve, reject) { exec(resolve, reject, APP_PLUGIN_NAME, "minimizeApp", [moveBack || false]); }); }
[ "function", "(", "moveBack", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "exec", "(", "resolve", ",", "reject", ",", "APP_PLUGIN_NAME", ",", "\"minimizeApp\"", ",", "[", "moveBack", "||", "false", "]", ...
Go to home screen
[ "Go", "to", "home", "screen" ]
d65ad5dbde7bd3024d4e978f71fa5214b02b18e6
https://github.com/chemerisuk/cordova-plugin-core-android-extensions/blob/d65ad5dbde7bd3024d4e978f71fa5214b02b18e6/www/android/coreextensions.js#L8-L12
34,542
chemerisuk/cordova-plugin-core-android-extensions
www/android/coreextensions.js
function(packageName, componentName) { return new Promise(function(resolve, reject) { exec(resolve, reject, APP_PLUGIN_NAME, "startApp", [packageName, componentName]); }); }
javascript
function(packageName, componentName) { return new Promise(function(resolve, reject) { exec(resolve, reject, APP_PLUGIN_NAME, "startApp", [packageName, componentName]); }); }
[ "function", "(", "packageName", ",", "componentName", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "exec", "(", "resolve", ",", "reject", ",", "APP_PLUGIN_NAME", ",", "\"startApp\"", ",", "[", "packageName",...
Starts app intent
[ "Starts", "app", "intent" ]
d65ad5dbde7bd3024d4e978f71fa5214b02b18e6
https://github.com/chemerisuk/cordova-plugin-core-android-extensions/blob/d65ad5dbde7bd3024d4e978f71fa5214b02b18e6/www/android/coreextensions.js#L44-L48
34,543
SchizoDuckie/CreateReadUpdateDelete.js
cli/questions.js
promisePrompt
function promisePrompt(questions) { return new Promise(function(resolve, reject) { inquirer.prompt(questions, function(results) { resolve(results); }); }); }
javascript
function promisePrompt(questions) { return new Promise(function(resolve, reject) { inquirer.prompt(questions, function(results) { resolve(results); }); }); }
[ "function", "promisePrompt", "(", "questions", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "inquirer", ".", "prompt", "(", "questions", ",", "function", "(", "results", ")", "{", "resolve", "(", "results"...
Convert inquirer.prompt to a promise.
[ "Convert", "inquirer", ".", "prompt", "to", "a", "promise", "." ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/cli/questions.js#L20-L26
34,544
ShaneGH/analogue-time-picker
tools/generateCssFile.js
buildJsFileContent
function buildJsFileContent(lines) { var ls = lines .map(l => l // remove space at beginning of line .replace(/^\s*/g, "") // remove space at end of line .replace(/\s*$/g, "") // convert \ to \\ .replace(/\\/g, "\\\\") // convert " to \" .replace(/"/g, "\\\"") // convert " { " to "{" .replace(/\s*\{\s*/g, "{") // convert " : " to ":" .replace(/\s*:\s*/g, ":")) .join("") // remove comments .replace(/\/\*.+?\*\//g, ""); return [ // add css string `var css = "${ls}";`, "var enabled = false;", "", // add function which injects css into page "function enable () {", "\tif (enabled) return;", "\tenabled = true;", "", "\tvar el = document.createElement('style');", "\tel.innerHTML = css;", "", "\tvar parent = document.head || document.body;", "\tparent.firstChild ?", "\t\tparent.insertBefore(el, parent.firstChild) :", "\t\tparent.appendChild(el);", "}", "", "export {", "\tenable", "}" ].join("\n"); }
javascript
function buildJsFileContent(lines) { var ls = lines .map(l => l // remove space at beginning of line .replace(/^\s*/g, "") // remove space at end of line .replace(/\s*$/g, "") // convert \ to \\ .replace(/\\/g, "\\\\") // convert " to \" .replace(/"/g, "\\\"") // convert " { " to "{" .replace(/\s*\{\s*/g, "{") // convert " : " to ":" .replace(/\s*:\s*/g, ":")) .join("") // remove comments .replace(/\/\*.+?\*\//g, ""); return [ // add css string `var css = "${ls}";`, "var enabled = false;", "", // add function which injects css into page "function enable () {", "\tif (enabled) return;", "\tenabled = true;", "", "\tvar el = document.createElement('style');", "\tel.innerHTML = css;", "", "\tvar parent = document.head || document.body;", "\tparent.firstChild ?", "\t\tparent.insertBefore(el, parent.firstChild) :", "\t\tparent.appendChild(el);", "}", "", "export {", "\tenable", "}" ].join("\n"); }
[ "function", "buildJsFileContent", "(", "lines", ")", "{", "var", "ls", "=", "lines", ".", "map", "(", "l", "=>", "l", "// remove space at beginning of line", ".", "replace", "(", "/", "^\\s*", "/", "g", ",", "\"\"", ")", "// remove space at end of line", ".", ...
Create the js content of the file to add css
[ "Create", "the", "js", "content", "of", "the", "file", "to", "add", "css" ]
026c0c37608f749041dde375551f5ff16cd5621e
https://github.com/ShaneGH/analogue-time-picker/blob/026c0c37608f749041dde375551f5ff16cd5621e/tools/generateCssFile.js#L6-L48
34,545
bvaughn/jasmine-es6-promise-matchers
jasmine-es6-promise-matchers.js
function(done, promise, expectedState, expectedData, isNegative) { function verify(promiseState) { return function(data) { var test = verifyState(promiseState, expectedState); if (test.pass) { test = verifyData(data, expectedData); } if (!test.pass && !isNegative) { done.fail(new Error(test.message)); return; } done(); } } promise.then( verify(PROMISE_STATE.RESOLVED), verify(PROMISE_STATE.REJECTED) ); return { pass: true }; }
javascript
function(done, promise, expectedState, expectedData, isNegative) { function verify(promiseState) { return function(data) { var test = verifyState(promiseState, expectedState); if (test.pass) { test = verifyData(data, expectedData); } if (!test.pass && !isNegative) { done.fail(new Error(test.message)); return; } done(); } } promise.then( verify(PROMISE_STATE.RESOLVED), verify(PROMISE_STATE.REJECTED) ); return { pass: true }; }
[ "function", "(", "done", ",", "promise", ",", "expectedState", ",", "expectedData", ",", "isNegative", ")", "{", "function", "verify", "(", "promiseState", ")", "{", "return", "function", "(", "data", ")", "{", "var", "test", "=", "verifyState", "(", "prom...
Helper method to verify expectations and return a Jasmine-friendly info-object
[ "Helper", "method", "to", "verify", "expectations", "and", "return", "a", "Jasmine", "-", "friendly", "info", "-", "object" ]
7c1eabf0919b2b28d19628ecd49e5d7a092104b7
https://github.com/bvaughn/jasmine-es6-promise-matchers/blob/7c1eabf0919b2b28d19628ecd49e5d7a092104b7/jasmine-es6-promise-matchers.js#L81-L105
34,546
kogarashisan/ClassManager
lib/class_manager.js
function(class_data, path) { var implements_source = this._sources[path], name, references_offset; if (Lava.schema.DEBUG) { if (!implements_source) Lava.t('Implements: class not found - "' + path + '"'); for (name in implements_source.shared) Lava.t("Implements: unable to use a class with Shared as mixin."); if (class_data.implements.indexOf(path) != -1) Lava.t("Implements: class " + class_data.path + " already implements " + path); } class_data.implements.push(path); references_offset = class_data.references.length; // array copy is inexpensive, cause it contains only reference types class_data.references = class_data.references.concat(implements_source.references); this._extend(class_data, class_data.skeleton, implements_source, implements_source.skeleton, true, references_offset); }
javascript
function(class_data, path) { var implements_source = this._sources[path], name, references_offset; if (Lava.schema.DEBUG) { if (!implements_source) Lava.t('Implements: class not found - "' + path + '"'); for (name in implements_source.shared) Lava.t("Implements: unable to use a class with Shared as mixin."); if (class_data.implements.indexOf(path) != -1) Lava.t("Implements: class " + class_data.path + " already implements " + path); } class_data.implements.push(path); references_offset = class_data.references.length; // array copy is inexpensive, cause it contains only reference types class_data.references = class_data.references.concat(implements_source.references); this._extend(class_data, class_data.skeleton, implements_source, implements_source.skeleton, true, references_offset); }
[ "function", "(", "class_data", ",", "path", ")", "{", "var", "implements_source", "=", "this", ".", "_sources", "[", "path", "]", ",", "name", ",", "references_offset", ";", "if", "(", "Lava", ".", "schema", ".", "DEBUG", ")", "{", "if", "(", "!", "i...
Implement members from another class into current class data @param {_cClassData} class_data @param {string} path
[ "Implement", "members", "from", "another", "class", "into", "current", "class", "data" ]
75d6e0262b1bd74359e41c6c51bf8b174b38e8ca
https://github.com/kogarashisan/ClassManager/blob/75d6e0262b1bd74359e41c6c51bf8b174b38e8ca/lib/class_manager.js#L427-L448
34,547
kogarashisan/ClassManager
lib/class_manager.js
function(class_data, source_object, is_root) { var name, skeleton = {}, value, type, skeleton_value; for (name in source_object) { if (is_root && (this._reserved_members.indexOf(name) != -1 || (name in class_data.shared))) { continue; } value = source_object[name]; type = Firestorm.getType(value); switch (type) { case 'null': case 'boolean': case 'number': skeleton_value = {type: this.MEMBER_TYPES.PRIMITIVE, value: value}; break; case 'string': skeleton_value = {type: this.MEMBER_TYPES.STRING, value: value}; break; case 'function': skeleton_value = {type: this.MEMBER_TYPES.FUNCTION, index: class_data.references.length}; class_data.references.push(value); break; case 'regexp': skeleton_value = {type: this.MEMBER_TYPES.REGEXP, index: class_data.references.length}; class_data.references.push(value); break; case 'object': skeleton_value = { type: this.MEMBER_TYPES.OBJECT, skeleton: this._disassemble(class_data, value, false) }; break; case 'array': if (value.length == 0) { skeleton_value = {type: this.MEMBER_TYPES.EMPTY_ARRAY}; } else if (this.inline_simple_arrays && this.isInlineArray(value)) { skeleton_value = {type: this.MEMBER_TYPES.INLINE_ARRAY, value: value}; } else { skeleton_value = {type: this.MEMBER_TYPES.SLICE_ARRAY, index: class_data.references.length}; class_data.references.push(value); } break; case 'undefined': Lava.t("[ClassManager] Forced code style restriction: please, replace undefined member values with null. Member name: " + name); break; default: Lava.t("[ClassManager] Unsupported property type in source object: " + type); break; } skeleton[name] = skeleton_value; } return skeleton; }
javascript
function(class_data, source_object, is_root) { var name, skeleton = {}, value, type, skeleton_value; for (name in source_object) { if (is_root && (this._reserved_members.indexOf(name) != -1 || (name in class_data.shared))) { continue; } value = source_object[name]; type = Firestorm.getType(value); switch (type) { case 'null': case 'boolean': case 'number': skeleton_value = {type: this.MEMBER_TYPES.PRIMITIVE, value: value}; break; case 'string': skeleton_value = {type: this.MEMBER_TYPES.STRING, value: value}; break; case 'function': skeleton_value = {type: this.MEMBER_TYPES.FUNCTION, index: class_data.references.length}; class_data.references.push(value); break; case 'regexp': skeleton_value = {type: this.MEMBER_TYPES.REGEXP, index: class_data.references.length}; class_data.references.push(value); break; case 'object': skeleton_value = { type: this.MEMBER_TYPES.OBJECT, skeleton: this._disassemble(class_data, value, false) }; break; case 'array': if (value.length == 0) { skeleton_value = {type: this.MEMBER_TYPES.EMPTY_ARRAY}; } else if (this.inline_simple_arrays && this.isInlineArray(value)) { skeleton_value = {type: this.MEMBER_TYPES.INLINE_ARRAY, value: value}; } else { skeleton_value = {type: this.MEMBER_TYPES.SLICE_ARRAY, index: class_data.references.length}; class_data.references.push(value); } break; case 'undefined': Lava.t("[ClassManager] Forced code style restriction: please, replace undefined member values with null. Member name: " + name); break; default: Lava.t("[ClassManager] Unsupported property type in source object: " + type); break; } skeleton[name] = skeleton_value; } return skeleton; }
[ "function", "(", "class_data", ",", "source_object", ",", "is_root", ")", "{", "var", "name", ",", "skeleton", "=", "{", "}", ",", "value", ",", "type", ",", "skeleton_value", ";", "for", "(", "name", "in", "source_object", ")", "{", "if", "(", "is_roo...
Recursively create skeletons for all objects inside class body @param {_cClassData} class_data @param {Object} source_object @param {boolean} is_root @returns {Object}
[ "Recursively", "create", "skeletons", "for", "all", "objects", "inside", "class", "body" ]
75d6e0262b1bd74359e41c6c51bf8b174b38e8ca
https://github.com/kogarashisan/ClassManager/blob/75d6e0262b1bd74359e41c6c51bf8b174b38e8ca/lib/class_manager.js#L524-L590
34,548
kogarashisan/ClassManager
lib/class_manager.js
function(skeleton, class_data, padding, serialized_properties) { var name, serialized_value, uses_references = false, object_properties; for (name in skeleton) { switch (skeleton[name].type) { case this.MEMBER_TYPES.STRING: serialized_value = Firestorm.String.quote(skeleton[name].value); break; case this.MEMBER_TYPES.PRIMITIVE: // null, boolean, number serialized_value = skeleton[name].value + ''; break; case this.MEMBER_TYPES.REGEXP: case this.MEMBER_TYPES.FUNCTION: serialized_value = 'r[' + skeleton[name].index + ']'; uses_references = true; break; case this.MEMBER_TYPES.EMPTY_ARRAY: serialized_value = "[]"; break; case this.MEMBER_TYPES.INLINE_ARRAY: serialized_value = this._serializeInlineArray(skeleton[name].value); break; case this.MEMBER_TYPES.SLICE_ARRAY: serialized_value = 'r[' + skeleton[name].index + '].slice()'; uses_references = true; break; case this.MEMBER_TYPES.OBJECT: object_properties = []; if (this._serializeSkeleton(skeleton[name].skeleton, class_data, padding + "\t", object_properties)) { uses_references = true; } serialized_value = object_properties.length ? "{\n\t" + padding + object_properties.join(",\n\t" + padding) + "\n" + padding + "}" : "{}"; break; default: Lava.t("[_serializeSkeleton] unknown property descriptor type: " + skeleton[name].type); } if (Lava.VALID_PROPERTY_NAME_REGEX.test(name) && Lava.JS_KEYWORDS.indexOf(name) == -1) { serialized_properties.push(name + ': ' + serialized_value); } else { serialized_properties.push(Firestorm.String.quote(name) + ': ' + serialized_value); } } return uses_references; }
javascript
function(skeleton, class_data, padding, serialized_properties) { var name, serialized_value, uses_references = false, object_properties; for (name in skeleton) { switch (skeleton[name].type) { case this.MEMBER_TYPES.STRING: serialized_value = Firestorm.String.quote(skeleton[name].value); break; case this.MEMBER_TYPES.PRIMITIVE: // null, boolean, number serialized_value = skeleton[name].value + ''; break; case this.MEMBER_TYPES.REGEXP: case this.MEMBER_TYPES.FUNCTION: serialized_value = 'r[' + skeleton[name].index + ']'; uses_references = true; break; case this.MEMBER_TYPES.EMPTY_ARRAY: serialized_value = "[]"; break; case this.MEMBER_TYPES.INLINE_ARRAY: serialized_value = this._serializeInlineArray(skeleton[name].value); break; case this.MEMBER_TYPES.SLICE_ARRAY: serialized_value = 'r[' + skeleton[name].index + '].slice()'; uses_references = true; break; case this.MEMBER_TYPES.OBJECT: object_properties = []; if (this._serializeSkeleton(skeleton[name].skeleton, class_data, padding + "\t", object_properties)) { uses_references = true; } serialized_value = object_properties.length ? "{\n\t" + padding + object_properties.join(",\n\t" + padding) + "\n" + padding + "}" : "{}"; break; default: Lava.t("[_serializeSkeleton] unknown property descriptor type: " + skeleton[name].type); } if (Lava.VALID_PROPERTY_NAME_REGEX.test(name) && Lava.JS_KEYWORDS.indexOf(name) == -1) { serialized_properties.push(name + ': ' + serialized_value); } else { serialized_properties.push(Firestorm.String.quote(name) + ': ' + serialized_value); } } return uses_references; }
[ "function", "(", "skeleton", ",", "class_data", ",", "padding", ",", "serialized_properties", ")", "{", "var", "name", ",", "serialized_value", ",", "uses_references", "=", "false", ",", "object_properties", ";", "for", "(", "name", "in", "skeleton", ")", "{",...
Perform special class serialization, that takes functions and resources from class data and can be used in constructors @param {Object} skeleton @param {_cClassData} class_data @param {string} padding @param {Array} serialized_properties @returns {boolean} <kw>true</kw>, if object uses {@link _cClassData#references}
[ "Perform", "special", "class", "serialization", "that", "takes", "functions", "and", "resources", "from", "class", "data", "and", "can", "be", "used", "in", "constructors" ]
75d6e0262b1bd74359e41c6c51bf8b174b38e8ca
https://github.com/kogarashisan/ClassManager/blob/75d6e0262b1bd74359e41c6c51bf8b174b38e8ca/lib/class_manager.js#L706-L763
34,549
kogarashisan/ClassManager
lib/class_manager.js
function(path_segments) { var namespace, segment_name, count = path_segments.length, i = 1; if (!count) Lava.t("ClassManager: class names must include a namespace, even for global classes."); if (!(path_segments[0] in this._root)) Lava.t("[ClassManager] namespace is not registered: " + path_segments[0]); namespace = this._root[path_segments[0]]; for (; i < count; i++) { segment_name = path_segments[i]; if (!(segment_name in namespace)) { namespace[segment_name] = {}; } namespace = namespace[segment_name]; } return namespace; }
javascript
function(path_segments) { var namespace, segment_name, count = path_segments.length, i = 1; if (!count) Lava.t("ClassManager: class names must include a namespace, even for global classes."); if (!(path_segments[0] in this._root)) Lava.t("[ClassManager] namespace is not registered: " + path_segments[0]); namespace = this._root[path_segments[0]]; for (; i < count; i++) { segment_name = path_segments[i]; if (!(segment_name in namespace)) { namespace[segment_name] = {}; } namespace = namespace[segment_name]; } return namespace; }
[ "function", "(", "path_segments", ")", "{", "var", "namespace", ",", "segment_name", ",", "count", "=", "path_segments", ".", "length", ",", "i", "=", "1", ";", "if", "(", "!", "count", ")", "Lava", ".", "t", "(", "\"ClassManager: class names must include a ...
Get namespace for a class constructor @param {Array.<string>} path_segments Path to the namespace of a class. Must start with one of registered roots @returns {Object}
[ "Get", "namespace", "for", "a", "class", "constructor" ]
75d6e0262b1bd74359e41c6c51bf8b174b38e8ca
https://github.com/kogarashisan/ClassManager/blob/75d6e0262b1bd74359e41c6c51bf8b174b38e8ca/lib/class_manager.js#L770-L797
34,550
kogarashisan/ClassManager
lib/class_manager.js
function(class_path, default_namespace) { if (!(class_path in this.constructors) && default_namespace) { class_path = default_namespace + '.' + class_path; } return this.constructors[class_path]; }
javascript
function(class_path, default_namespace) { if (!(class_path in this.constructors) && default_namespace) { class_path = default_namespace + '.' + class_path; } return this.constructors[class_path]; }
[ "function", "(", "class_path", ",", "default_namespace", ")", "{", "if", "(", "!", "(", "class_path", "in", "this", ".", "constructors", ")", "&&", "default_namespace", ")", "{", "class_path", "=", "default_namespace", "+", "'.'", "+", "class_path", ";", "}"...
Get class constructor @param {string} class_path Full name of a class, or a short name (if namespace is provided) @param {string} [default_namespace] The default prefix where to search for the class, like <str>"Lava.widget"</str> @returns {function}
[ "Get", "class", "constructor" ]
75d6e0262b1bd74359e41c6c51bf8b174b38e8ca
https://github.com/kogarashisan/ClassManager/blob/75d6e0262b1bd74359e41c6c51bf8b174b38e8ca/lib/class_manager.js#L805-L815
34,551
kogarashisan/ClassManager
lib/class_manager.js
function(data) { var tempResult = [], i = 0, count = data.length, type, value; for (; i < count; i++) { type = Firestorm.getType(data[i]); switch (type) { case 'string': value = Firestorm.String.quote(data[i]); break; case 'null': case 'undefined': case 'boolean': case 'number': value = data[i] + ''; break; default: Lava.t(); } tempResult.push(value); } return '[' + tempResult.join(", ") + ']'; }
javascript
function(data) { var tempResult = [], i = 0, count = data.length, type, value; for (; i < count; i++) { type = Firestorm.getType(data[i]); switch (type) { case 'string': value = Firestorm.String.quote(data[i]); break; case 'null': case 'undefined': case 'boolean': case 'number': value = data[i] + ''; break; default: Lava.t(); } tempResult.push(value); } return '[' + tempResult.join(", ") + ']'; }
[ "function", "(", "data", ")", "{", "var", "tempResult", "=", "[", "]", ",", "i", "=", "0", ",", "count", "=", "data", ".", "length", ",", "type", ",", "value", ";", "for", "(", ";", "i", "<", "count", ";", "i", "++", ")", "{", "type", "=", ...
Serialize an array which contains only certain primitive types from `SIMPLE_TYPES` property @param {Array} data @returns {string}
[ "Serialize", "an", "array", "which", "contains", "only", "certain", "primitive", "types", "from", "SIMPLE_TYPES", "property" ]
75d6e0262b1bd74359e41c6c51bf8b174b38e8ca
https://github.com/kogarashisan/ClassManager/blob/75d6e0262b1bd74359e41c6c51bf8b174b38e8ca/lib/class_manager.js#L847-L877
34,552
kogarashisan/ClassManager
lib/class_manager.js
function(class_data) { var skeleton = class_data.skeleton, name, serialized_value, serialized_actions = [], is_polymorphic = !class_data.is_monomorphic; for (name in skeleton) { switch (skeleton[name].type) { case this.MEMBER_TYPES.REGEXP: case this.MEMBER_TYPES.FUNCTION: serialized_value = 'r[' + skeleton[name].index + ']'; break; //case 'undefined': case this.MEMBER_TYPES.STRING: if (is_polymorphic) { serialized_value = '"' + skeleton[name].value.replace(/\"/g, "\\\"") + '"'; } break; case this.MEMBER_TYPES.PRIMITIVE: // null, boolean, number if (is_polymorphic) { serialized_value = skeleton[name].value + ''; } break; } if (serialized_value) { if (Lava.VALID_PROPERTY_NAME_REGEX.test(name)) { serialized_actions.push('p.' + name + ' = ' + serialized_value + ';'); } else { serialized_actions.push('p[' + Firestorm.String.quote(name) + '] = ' + serialized_value + ';'); } serialized_value = null; } } for (name in class_data.shared) { serialized_actions.push('p.' + name + ' = s.' + name + ';'); } return serialized_actions.length ? new Function('cd,p', "\tvar r=cd.references,\n\t\ts=cd.shared;\n\n\t" + serialized_actions.join('\n\t') + "\n") : null; }
javascript
function(class_data) { var skeleton = class_data.skeleton, name, serialized_value, serialized_actions = [], is_polymorphic = !class_data.is_monomorphic; for (name in skeleton) { switch (skeleton[name].type) { case this.MEMBER_TYPES.REGEXP: case this.MEMBER_TYPES.FUNCTION: serialized_value = 'r[' + skeleton[name].index + ']'; break; //case 'undefined': case this.MEMBER_TYPES.STRING: if (is_polymorphic) { serialized_value = '"' + skeleton[name].value.replace(/\"/g, "\\\"") + '"'; } break; case this.MEMBER_TYPES.PRIMITIVE: // null, boolean, number if (is_polymorphic) { serialized_value = skeleton[name].value + ''; } break; } if (serialized_value) { if (Lava.VALID_PROPERTY_NAME_REGEX.test(name)) { serialized_actions.push('p.' + name + ' = ' + serialized_value + ';'); } else { serialized_actions.push('p[' + Firestorm.String.quote(name) + '] = ' + serialized_value + ';'); } serialized_value = null; } } for (name in class_data.shared) { serialized_actions.push('p.' + name + ' = s.' + name + ';'); } return serialized_actions.length ? new Function('cd,p', "\tvar r=cd.references,\n\t\ts=cd.shared;\n\n\t" + serialized_actions.join('\n\t') + "\n") : null; }
[ "function", "(", "class_data", ")", "{", "var", "skeleton", "=", "class_data", ".", "skeleton", ",", "name", ",", "serialized_value", ",", "serialized_actions", "=", "[", "]", ",", "is_polymorphic", "=", "!", "class_data", ".", "is_monomorphic", ";", "for", ...
Build a function that creates class constructor's prototype. Used in export @param {_cClassData} class_data @returns {function}
[ "Build", "a", "function", "that", "creates", "class", "constructor", "s", "prototype", ".", "Used", "in", "export" ]
75d6e0262b1bd74359e41c6c51bf8b174b38e8ca
https://github.com/kogarashisan/ClassManager/blob/75d6e0262b1bd74359e41c6c51bf8b174b38e8ca/lib/class_manager.js#L918-L974
34,553
kogarashisan/ClassManager
lib/class_manager.js
function(class_datas) { for (var i = 0, count = class_datas.length; i <count; i++) { this.loadClass(class_datas[i]); } }
javascript
function(class_datas) { for (var i = 0, count = class_datas.length; i <count; i++) { this.loadClass(class_datas[i]); } }
[ "function", "(", "class_datas", ")", "{", "for", "(", "var", "i", "=", "0", ",", "count", "=", "class_datas", ".", "length", ";", "i", "<", "count", ";", "i", "++", ")", "{", "this", ".", "loadClass", "(", "class_datas", "[", "i", "]", ")", ";", ...
Batch load exported classes. Constructors, references and skeletons can be provided as separate arrays @param {Array.<_cClassData>} class_datas
[ "Batch", "load", "exported", "classes", ".", "Constructors", "references", "and", "skeletons", "can", "be", "provided", "as", "separate", "arrays" ]
75d6e0262b1bd74359e41c6c51bf8b174b38e8ca
https://github.com/kogarashisan/ClassManager/blob/75d6e0262b1bd74359e41c6c51bf8b174b38e8ca/lib/class_manager.js#L1122-L1130
34,554
kogarashisan/ClassManager
lib/class_manager.js
function(class_data) { var class_path = class_data.path, namespace_path, class_name, namespace; if ((class_path in this._sources) || (class_path in this.constructors)) Lava.t("Class is already defined: " + class_path); this._sources[class_path] = class_data; if (class_data.constructor) { namespace_path = class_path.split('.'); class_name = namespace_path.pop(); namespace = this._getNamespace(namespace_path); if ((class_name in namespace) && namespace[class_name] != null) Lava.t("Class name conflict: '" + class_path + "' property is already defined in namespace path"); this.constructors[class_path] = class_data.constructor; namespace[class_name] = class_data.constructor; } }
javascript
function(class_data) { var class_path = class_data.path, namespace_path, class_name, namespace; if ((class_path in this._sources) || (class_path in this.constructors)) Lava.t("Class is already defined: " + class_path); this._sources[class_path] = class_data; if (class_data.constructor) { namespace_path = class_path.split('.'); class_name = namespace_path.pop(); namespace = this._getNamespace(namespace_path); if ((class_name in namespace) && namespace[class_name] != null) Lava.t("Class name conflict: '" + class_path + "' property is already defined in namespace path"); this.constructors[class_path] = class_data.constructor; namespace[class_name] = class_data.constructor; } }
[ "function", "(", "class_data", ")", "{", "var", "class_path", "=", "class_data", ".", "path", ",", "namespace_path", ",", "class_name", ",", "namespace", ";", "if", "(", "(", "class_path", "in", "this", ".", "_sources", ")", "||", "(", "class_path", "in", ...
Put a newly built class constructor into it's namespace @param {_cClassData} class_data
[ "Put", "a", "newly", "built", "class", "constructor", "into", "it", "s", "namespace" ]
75d6e0262b1bd74359e41c6c51bf8b174b38e8ca
https://github.com/kogarashisan/ClassManager/blob/75d6e0262b1bd74359e41c6c51bf8b174b38e8ca/lib/class_manager.js#L1148-L1171
34,555
kogarashisan/ClassManager
lib/class_manager.js
function(base_path, suffix) { if (Lava.schema.DEBUG && !(base_path in this._sources)) Lava.t("[getPackageConstructor] Class not found: " + base_path); var path, current_class = this._sources[base_path], result = null; do { path = current_class.path + suffix; if (path in this.constructors) { result = this.constructors[path]; break; } current_class = current_class.parent_class_data; } while (current_class); return result; }
javascript
function(base_path, suffix) { if (Lava.schema.DEBUG && !(base_path in this._sources)) Lava.t("[getPackageConstructor] Class not found: " + base_path); var path, current_class = this._sources[base_path], result = null; do { path = current_class.path + suffix; if (path in this.constructors) { result = this.constructors[path]; break; } current_class = current_class.parent_class_data; } while (current_class); return result; }
[ "function", "(", "base_path", ",", "suffix", ")", "{", "if", "(", "Lava", ".", "schema", ".", "DEBUG", "&&", "!", "(", "base_path", "in", "this", ".", "_sources", ")", ")", "Lava", ".", "t", "(", "\"[getPackageConstructor] Class not found: \"", "+", "base_...
Find a class that begins with `base_path` or names of it's parents, and ends with `suffix` @param {string} base_path @param {string} suffix @returns {function}
[ "Find", "a", "class", "that", "begins", "with", "base_path", "or", "names", "of", "it", "s", "parents", "and", "ends", "with", "suffix" ]
75d6e0262b1bd74359e41c6c51bf8b174b38e8ca
https://github.com/kogarashisan/ClassManager/blob/75d6e0262b1bd74359e41c6c51bf8b174b38e8ca/lib/class_manager.js#L1179-L1203
34,556
mozilla/webmaker-core
src/static/js/Intl.js
$$core$$ResolveLocale
function /* 9.2.5 */$$core$$ResolveLocale (availableLocales, requestedLocales, options, relevantExtensionKeys, localeData) { if (availableLocales.length === 0) { throw new ReferenceError('No locale data has been provided for this object yet.'); } // The following steps are taken: var // 1. Let matcher be the value of options.[[localeMatcher]]. matcher = options['[[localeMatcher]]']; // 2. If matcher is "lookup", then if (matcher === 'lookup') var // a. Let r be the result of calling the LookupMatcher abstract operation // (defined in 9.2.3) with arguments availableLocales and // requestedLocales. r = $$core$$LookupMatcher(availableLocales, requestedLocales); // 3. Else else var // a. Let r be the result of calling the BestFitMatcher abstract // operation (defined in 9.2.4) with arguments availableLocales and // requestedLocales. r = $$core$$BestFitMatcher(availableLocales, requestedLocales); var // 4. Let foundLocale be the value of r.[[locale]]. foundLocale = r['[[locale]]']; // 5. If r has an [[extension]] field, then if ($$core$$hop.call(r, '[[extension]]')) var // a. Let extension be the value of r.[[extension]]. extension = r['[[extension]]'], // b. Let extensionIndex be the value of r.[[extensionIndex]]. extensionIndex = r['[[extensionIndex]]'], // c. Let split be the standard built-in function object defined in ES5, // 15.5.4.14. split = String.prototype.split, // d. Let extensionSubtags be the result of calling the [[Call]] internal // method of split with extension as the this value and an argument // list containing the single item "-". extensionSubtags = split.call(extension, '-'), // e. Let extensionSubtagsLength be the result of calling the [[Get]] // internal method of extensionSubtags with argument "length". extensionSubtagsLength = extensionSubtags.length; var // 6. Let result be a new Record. result = new $$core$$Record(); // 7. Set result.[[dataLocale]] to foundLocale. result['[[dataLocale]]'] = foundLocale; var // 8. Let supportedExtension be "-u". supportedExtension = '-u', // 9. Let i be 0. i = 0, // 10. Let len be the result of calling the [[Get]] internal method of // relevantExtensionKeys with argument "length". len = relevantExtensionKeys.length; // 11 Repeat while i < len: while (i < len) { var // a. Let key be the result of calling the [[Get]] internal method of // relevantExtensionKeys with argument ToString(i). key = relevantExtensionKeys[i], // b. Let foundLocaleData be the result of calling the [[Get]] internal // method of localeData with the argument foundLocale. foundLocaleData = localeData[foundLocale], // c. Let keyLocaleData be the result of calling the [[Get]] internal // method of foundLocaleData with the argument key. keyLocaleData = foundLocaleData[key], // d. Let value be the result of calling the [[Get]] internal method of // keyLocaleData with argument "0". value = keyLocaleData['0'], // e. Let supportedExtensionAddition be "". supportedExtensionAddition = '', // f. Let indexOf be the standard built-in function object defined in // ES5, 15.4.4.14. indexOf = $$core$$arrIndexOf; // g. If extensionSubtags is not undefined, then if (extensionSubtags !== undefined) { var // i. Let keyPos be the result of calling the [[Call]] internal // method of indexOf with extensionSubtags as the this value and // an argument list containing the single item key. keyPos = indexOf.call(extensionSubtags, key); // ii. If keyPos ≠ -1, then if (keyPos !== -1) { // 1. If keyPos + 1 < extensionSubtagsLength and the length of the // result of calling the [[Get]] internal method of // extensionSubtags with argument ToString(keyPos +1) is greater // than 2, then if (keyPos + 1 < extensionSubtagsLength && extensionSubtags[keyPos + 1].length > 2) { var // a. Let requestedValue be the result of calling the [[Get]] // internal method of extensionSubtags with argument // ToString(keyPos + 1). requestedValue = extensionSubtags[keyPos + 1], // b. Let valuePos be the result of calling the [[Call]] // internal method of indexOf with keyLocaleData as the // this value and an argument list containing the single // item requestedValue. valuePos = indexOf.call(keyLocaleData, requestedValue); // c. If valuePos ≠ -1, then if (valuePos !== -1) var // i. Let value be requestedValue. value = requestedValue, // ii. Let supportedExtensionAddition be the // concatenation of "-", key, "-", and value. supportedExtensionAddition = '-' + key + '-' + value; } // 2. Else else { var // a. Let valuePos be the result of calling the [[Call]] // internal method of indexOf with keyLocaleData as the this // value and an argument list containing the single item // "true". valuePos = indexOf(keyLocaleData, 'true'); // b. If valuePos ≠ -1, then if (valuePos !== -1) var // i. Let value be "true". value = 'true'; } } } // h. If options has a field [[<key>]], then if ($$core$$hop.call(options, '[[' + key + ']]')) { var // i. Let optionsValue be the value of options.[[<key>]]. optionsValue = options['[[' + key + ']]']; // ii. If the result of calling the [[Call]] internal method of indexOf // with keyLocaleData as the this value and an argument list // containing the single item optionsValue is not -1, then if (indexOf.call(keyLocaleData, optionsValue) !== -1) { // 1. If optionsValue is not equal to value, then if (optionsValue !== value) { // a. Let value be optionsValue. value = optionsValue; // b. Let supportedExtensionAddition be "". supportedExtensionAddition = ''; } } } // i. Set result.[[<key>]] to value. result['[[' + key + ']]'] = value; // j. Append supportedExtensionAddition to supportedExtension. supportedExtension += supportedExtensionAddition; // k. Increase i by 1. i++; } // 12. If the length of supportedExtension is greater than 2, then if (supportedExtension.length > 2) { var // a. Let preExtension be the substring of foundLocale from position 0, // inclusive, to position extensionIndex, exclusive. preExtension = foundLocale.substring(0, extensionIndex), // b. Let postExtension be the substring of foundLocale from position // extensionIndex to the end of the string. postExtension = foundLocale.substring(extensionIndex), // c. Let foundLocale be the concatenation of preExtension, // supportedExtension, and postExtension. foundLocale = preExtension + supportedExtension + postExtension; } // 13. Set result.[[locale]] to foundLocale. result['[[locale]]'] = foundLocale; // 14. Return result. return result; }
javascript
function /* 9.2.5 */$$core$$ResolveLocale (availableLocales, requestedLocales, options, relevantExtensionKeys, localeData) { if (availableLocales.length === 0) { throw new ReferenceError('No locale data has been provided for this object yet.'); } // The following steps are taken: var // 1. Let matcher be the value of options.[[localeMatcher]]. matcher = options['[[localeMatcher]]']; // 2. If matcher is "lookup", then if (matcher === 'lookup') var // a. Let r be the result of calling the LookupMatcher abstract operation // (defined in 9.2.3) with arguments availableLocales and // requestedLocales. r = $$core$$LookupMatcher(availableLocales, requestedLocales); // 3. Else else var // a. Let r be the result of calling the BestFitMatcher abstract // operation (defined in 9.2.4) with arguments availableLocales and // requestedLocales. r = $$core$$BestFitMatcher(availableLocales, requestedLocales); var // 4. Let foundLocale be the value of r.[[locale]]. foundLocale = r['[[locale]]']; // 5. If r has an [[extension]] field, then if ($$core$$hop.call(r, '[[extension]]')) var // a. Let extension be the value of r.[[extension]]. extension = r['[[extension]]'], // b. Let extensionIndex be the value of r.[[extensionIndex]]. extensionIndex = r['[[extensionIndex]]'], // c. Let split be the standard built-in function object defined in ES5, // 15.5.4.14. split = String.prototype.split, // d. Let extensionSubtags be the result of calling the [[Call]] internal // method of split with extension as the this value and an argument // list containing the single item "-". extensionSubtags = split.call(extension, '-'), // e. Let extensionSubtagsLength be the result of calling the [[Get]] // internal method of extensionSubtags with argument "length". extensionSubtagsLength = extensionSubtags.length; var // 6. Let result be a new Record. result = new $$core$$Record(); // 7. Set result.[[dataLocale]] to foundLocale. result['[[dataLocale]]'] = foundLocale; var // 8. Let supportedExtension be "-u". supportedExtension = '-u', // 9. Let i be 0. i = 0, // 10. Let len be the result of calling the [[Get]] internal method of // relevantExtensionKeys with argument "length". len = relevantExtensionKeys.length; // 11 Repeat while i < len: while (i < len) { var // a. Let key be the result of calling the [[Get]] internal method of // relevantExtensionKeys with argument ToString(i). key = relevantExtensionKeys[i], // b. Let foundLocaleData be the result of calling the [[Get]] internal // method of localeData with the argument foundLocale. foundLocaleData = localeData[foundLocale], // c. Let keyLocaleData be the result of calling the [[Get]] internal // method of foundLocaleData with the argument key. keyLocaleData = foundLocaleData[key], // d. Let value be the result of calling the [[Get]] internal method of // keyLocaleData with argument "0". value = keyLocaleData['0'], // e. Let supportedExtensionAddition be "". supportedExtensionAddition = '', // f. Let indexOf be the standard built-in function object defined in // ES5, 15.4.4.14. indexOf = $$core$$arrIndexOf; // g. If extensionSubtags is not undefined, then if (extensionSubtags !== undefined) { var // i. Let keyPos be the result of calling the [[Call]] internal // method of indexOf with extensionSubtags as the this value and // an argument list containing the single item key. keyPos = indexOf.call(extensionSubtags, key); // ii. If keyPos ≠ -1, then if (keyPos !== -1) { // 1. If keyPos + 1 < extensionSubtagsLength and the length of the // result of calling the [[Get]] internal method of // extensionSubtags with argument ToString(keyPos +1) is greater // than 2, then if (keyPos + 1 < extensionSubtagsLength && extensionSubtags[keyPos + 1].length > 2) { var // a. Let requestedValue be the result of calling the [[Get]] // internal method of extensionSubtags with argument // ToString(keyPos + 1). requestedValue = extensionSubtags[keyPos + 1], // b. Let valuePos be the result of calling the [[Call]] // internal method of indexOf with keyLocaleData as the // this value and an argument list containing the single // item requestedValue. valuePos = indexOf.call(keyLocaleData, requestedValue); // c. If valuePos ≠ -1, then if (valuePos !== -1) var // i. Let value be requestedValue. value = requestedValue, // ii. Let supportedExtensionAddition be the // concatenation of "-", key, "-", and value. supportedExtensionAddition = '-' + key + '-' + value; } // 2. Else else { var // a. Let valuePos be the result of calling the [[Call]] // internal method of indexOf with keyLocaleData as the this // value and an argument list containing the single item // "true". valuePos = indexOf(keyLocaleData, 'true'); // b. If valuePos ≠ -1, then if (valuePos !== -1) var // i. Let value be "true". value = 'true'; } } } // h. If options has a field [[<key>]], then if ($$core$$hop.call(options, '[[' + key + ']]')) { var // i. Let optionsValue be the value of options.[[<key>]]. optionsValue = options['[[' + key + ']]']; // ii. If the result of calling the [[Call]] internal method of indexOf // with keyLocaleData as the this value and an argument list // containing the single item optionsValue is not -1, then if (indexOf.call(keyLocaleData, optionsValue) !== -1) { // 1. If optionsValue is not equal to value, then if (optionsValue !== value) { // a. Let value be optionsValue. value = optionsValue; // b. Let supportedExtensionAddition be "". supportedExtensionAddition = ''; } } } // i. Set result.[[<key>]] to value. result['[[' + key + ']]'] = value; // j. Append supportedExtensionAddition to supportedExtension. supportedExtension += supportedExtensionAddition; // k. Increase i by 1. i++; } // 12. If the length of supportedExtension is greater than 2, then if (supportedExtension.length > 2) { var // a. Let preExtension be the substring of foundLocale from position 0, // inclusive, to position extensionIndex, exclusive. preExtension = foundLocale.substring(0, extensionIndex), // b. Let postExtension be the substring of foundLocale from position // extensionIndex to the end of the string. postExtension = foundLocale.substring(extensionIndex), // c. Let foundLocale be the concatenation of preExtension, // supportedExtension, and postExtension. foundLocale = preExtension + supportedExtension + postExtension; } // 13. Set result.[[locale]] to foundLocale. result['[[locale]]'] = foundLocale; // 14. Return result. return result; }
[ "function", "/* 9.2.5 */", "$$core$$ResolveLocale", "(", "availableLocales", ",", "requestedLocales", ",", "options", ",", "relevantExtensionKeys", ",", "localeData", ")", "{", "if", "(", "availableLocales", ".", "length", "===", "0", ")", "{", "throw", "new", "Re...
The ResolveLocale abstract operation compares a BCP 47 language priority list requestedLocales against the locales in availableLocales and determines the best available language to meet the request. availableLocales and requestedLocales must be provided as List values, options as a Record.
[ "The", "ResolveLocale", "abstract", "operation", "compares", "a", "BCP", "47", "language", "priority", "list", "requestedLocales", "against", "the", "locales", "in", "availableLocales", "and", "determines", "the", "best", "available", "language", "to", "meet", "the"...
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/static/js/Intl.js#L875-L1059
34,557
mozilla/webmaker-core
src/static/js/Intl.js
$$core$$GetOption
function /*9.2.9 */$$core$$GetOption (options, property, type, values, fallback) { var // 1. Let value be the result of calling the [[Get]] internal method of // options with argument property. value = options[property]; // 2. If value is not undefined, then if (value !== undefined) { // a. Assert: type is "boolean" or "string". // b. If type is "boolean", then let value be ToBoolean(value). // c. If type is "string", then let value be ToString(value). value = type === 'boolean' ? Boolean(value) : (type === 'string' ? String(value) : value); // d. If values is not undefined, then if (values !== undefined) { // i. If values does not contain an element equal to value, then throw a // RangeError exception. if ($$core$$arrIndexOf.call(values, value) === -1) throw new RangeError("'" + value + "' is not an allowed value for `" + property +'`'); } // e. Return value. return value; } // Else return fallback. return fallback; }
javascript
function /*9.2.9 */$$core$$GetOption (options, property, type, values, fallback) { var // 1. Let value be the result of calling the [[Get]] internal method of // options with argument property. value = options[property]; // 2. If value is not undefined, then if (value !== undefined) { // a. Assert: type is "boolean" or "string". // b. If type is "boolean", then let value be ToBoolean(value). // c. If type is "string", then let value be ToString(value). value = type === 'boolean' ? Boolean(value) : (type === 'string' ? String(value) : value); // d. If values is not undefined, then if (values !== undefined) { // i. If values does not contain an element equal to value, then throw a // RangeError exception. if ($$core$$arrIndexOf.call(values, value) === -1) throw new RangeError("'" + value + "' is not an allowed value for `" + property +'`'); } // e. Return value. return value; } // Else return fallback. return fallback; }
[ "function", "/*9.2.9 */", "$$core$$GetOption", "(", "options", ",", "property", ",", "type", ",", "values", ",", "fallback", ")", "{", "var", "// 1. Let value be the result of calling the [[Get]] internal method of", "// options with argument property.", "value", "=", "opt...
The GetOption abstract operation extracts the value of the property named property from the provided options object, converts it to the required type, checks whether it is one of a List of allowed values, and fills in a fallback value if necessary.
[ "The", "GetOption", "abstract", "operation", "extracts", "the", "value", "of", "the", "property", "named", "property", "from", "the", "provided", "options", "object", "converts", "it", "to", "the", "required", "type", "checks", "whether", "it", "is", "one", "o...
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/static/js/Intl.js#L1193-L1220
34,558
mozilla/webmaker-core
src/static/js/Intl.js
$$core$$GetNumberOption
function /* 9.2.10 */$$core$$GetNumberOption (options, property, minimum, maximum, fallback) { var // 1. Let value be the result of calling the [[Get]] internal method of // options with argument property. value = options[property]; // 2. If value is not undefined, then if (value !== undefined) { // a. Let value be ToNumber(value). value = Number(value); // b. If value is NaN or less than minimum or greater than maximum, throw a // RangeError exception. if (isNaN(value) || value < minimum || value > maximum) throw new RangeError('Value is not a number or outside accepted range'); // c. Return floor(value). return Math.floor(value); } // 3. Else return fallback. return fallback; }
javascript
function /* 9.2.10 */$$core$$GetNumberOption (options, property, minimum, maximum, fallback) { var // 1. Let value be the result of calling the [[Get]] internal method of // options with argument property. value = options[property]; // 2. If value is not undefined, then if (value !== undefined) { // a. Let value be ToNumber(value). value = Number(value); // b. If value is NaN or less than minimum or greater than maximum, throw a // RangeError exception. if (isNaN(value) || value < minimum || value > maximum) throw new RangeError('Value is not a number or outside accepted range'); // c. Return floor(value). return Math.floor(value); } // 3. Else return fallback. return fallback; }
[ "function", "/* 9.2.10 */", "$$core$$GetNumberOption", "(", "options", ",", "property", ",", "minimum", ",", "maximum", ",", "fallback", ")", "{", "var", "// 1. Let value be the result of calling the [[Get]] internal method of", "// options with argument property.", "value", ...
The GetNumberOption abstract operation extracts a property value from the provided options object, converts it to a Number value, checks whether it is in the allowed range, and fills in a fallback value if necessary.
[ "The", "GetNumberOption", "abstract", "operation", "extracts", "a", "property", "value", "from", "the", "provided", "options", "object", "converts", "it", "to", "a", "Number", "value", "checks", "whether", "it", "is", "in", "the", "allowed", "range", "and", "f...
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/static/js/Intl.js#L1227-L1248
34,559
mozilla/webmaker-core
src/static/js/Intl.js
$$core$$calculateScore
function $$core$$calculateScore (options, formats, bestFit) { var // Additional penalty type when bestFit === true diffDataTypePenalty = 8, // 1. Let removalPenalty be 120. removalPenalty = 120, // 2. Let additionPenalty be 20. additionPenalty = 20, // 3. Let longLessPenalty be 8. longLessPenalty = 8, // 4. Let longMorePenalty be 6. longMorePenalty = 6, // 5. Let shortLessPenalty be 6. shortLessPenalty = 6, // 6. Let shortMorePenalty be 3. shortMorePenalty = 3, // 7. Let bestScore be -Infinity. bestScore = -Infinity, // 8. Let bestFormat be undefined. bestFormat, // 9. Let i be 0. i = 0, // 10. Let len be the result of calling the [[Get]] internal method of formats with argument "length". len = formats.length; // 11. Repeat while i < len: while (i < len) { var // a. Let format be the result of calling the [[Get]] internal method of formats with argument ToString(i). format = formats[i], // b. Let score be 0. score = 0; // c. For each property shown in Table 3: for (var property in $$core$$dateTimeComponents) { if (!$$core$$hop.call($$core$$dateTimeComponents, property)) continue; var // i. Let optionsProp be options.[[<property>]]. optionsProp = options['[['+ property +']]'], // ii. Let formatPropDesc be the result of calling the [[GetOwnProperty]] internal method of format // with argument property. // iii. If formatPropDesc is not undefined, then // 1. Let formatProp be the result of calling the [[Get]] internal method of format with argument property. formatProp = $$core$$hop.call(format, property) ? format[property] : undefined; // iv. If optionsProp is undefined and formatProp is not undefined, then decrease score by // additionPenalty. if (optionsProp === undefined && formatProp !== undefined) score -= additionPenalty; // v. Else if optionsProp is not undefined and formatProp is undefined, then decrease score by // removalPenalty. else if (optionsProp !== undefined && formatProp === undefined) score -= removalPenalty; // vi. Else else { var // 1. Let values be the array ["2-digit", "numeric", "narrow", "short", // "long"]. values = [ '2-digit', 'numeric', 'narrow', 'short', 'long' ], // 2. Let optionsPropIndex be the index of optionsProp within values. optionsPropIndex = $$core$$arrIndexOf.call(values, optionsProp), // 3. Let formatPropIndex be the index of formatProp within values. formatPropIndex = $$core$$arrIndexOf.call(values, formatProp), // 4. Let delta be max(min(formatPropIndex - optionsPropIndex, 2), -2). delta = Math.max(Math.min(formatPropIndex - optionsPropIndex, 2), -2); // When the bestFit argument is true, subtract additional penalty where data types are not the same if (bestFit && ( ((optionsProp === 'numeric' || optionsProp === '2-digit') && (formatProp !== 'numeric' && formatProp !== '2-digit') || (optionsProp !== 'numeric' && optionsProp !== '2-digit') && (formatProp === '2-digit' || formatProp === 'numeric')) )) score -= diffDataTypePenalty; // 5. If delta = 2, decrease score by longMorePenalty. if (delta === 2) score -= longMorePenalty; // 6. Else if delta = 1, decrease score by shortMorePenalty. else if (delta === 1) score -= shortMorePenalty; // 7. Else if delta = -1, decrease score by shortLessPenalty. else if (delta === -1) score -= shortLessPenalty; // 8. Else if delta = -2, decrease score by longLessPenalty. else if (delta === -2) score -= longLessPenalty; } } // d. If score > bestScore, then if (score > bestScore) { // i. Let bestScore be score. bestScore = score; // ii. Let bestFormat be format. bestFormat = format; } // e. Increase i by 1. i++; } // 12. Return bestFormat. return bestFormat; }
javascript
function $$core$$calculateScore (options, formats, bestFit) { var // Additional penalty type when bestFit === true diffDataTypePenalty = 8, // 1. Let removalPenalty be 120. removalPenalty = 120, // 2. Let additionPenalty be 20. additionPenalty = 20, // 3. Let longLessPenalty be 8. longLessPenalty = 8, // 4. Let longMorePenalty be 6. longMorePenalty = 6, // 5. Let shortLessPenalty be 6. shortLessPenalty = 6, // 6. Let shortMorePenalty be 3. shortMorePenalty = 3, // 7. Let bestScore be -Infinity. bestScore = -Infinity, // 8. Let bestFormat be undefined. bestFormat, // 9. Let i be 0. i = 0, // 10. Let len be the result of calling the [[Get]] internal method of formats with argument "length". len = formats.length; // 11. Repeat while i < len: while (i < len) { var // a. Let format be the result of calling the [[Get]] internal method of formats with argument ToString(i). format = formats[i], // b. Let score be 0. score = 0; // c. For each property shown in Table 3: for (var property in $$core$$dateTimeComponents) { if (!$$core$$hop.call($$core$$dateTimeComponents, property)) continue; var // i. Let optionsProp be options.[[<property>]]. optionsProp = options['[['+ property +']]'], // ii. Let formatPropDesc be the result of calling the [[GetOwnProperty]] internal method of format // with argument property. // iii. If formatPropDesc is not undefined, then // 1. Let formatProp be the result of calling the [[Get]] internal method of format with argument property. formatProp = $$core$$hop.call(format, property) ? format[property] : undefined; // iv. If optionsProp is undefined and formatProp is not undefined, then decrease score by // additionPenalty. if (optionsProp === undefined && formatProp !== undefined) score -= additionPenalty; // v. Else if optionsProp is not undefined and formatProp is undefined, then decrease score by // removalPenalty. else if (optionsProp !== undefined && formatProp === undefined) score -= removalPenalty; // vi. Else else { var // 1. Let values be the array ["2-digit", "numeric", "narrow", "short", // "long"]. values = [ '2-digit', 'numeric', 'narrow', 'short', 'long' ], // 2. Let optionsPropIndex be the index of optionsProp within values. optionsPropIndex = $$core$$arrIndexOf.call(values, optionsProp), // 3. Let formatPropIndex be the index of formatProp within values. formatPropIndex = $$core$$arrIndexOf.call(values, formatProp), // 4. Let delta be max(min(formatPropIndex - optionsPropIndex, 2), -2). delta = Math.max(Math.min(formatPropIndex - optionsPropIndex, 2), -2); // When the bestFit argument is true, subtract additional penalty where data types are not the same if (bestFit && ( ((optionsProp === 'numeric' || optionsProp === '2-digit') && (formatProp !== 'numeric' && formatProp !== '2-digit') || (optionsProp !== 'numeric' && optionsProp !== '2-digit') && (formatProp === '2-digit' || formatProp === 'numeric')) )) score -= diffDataTypePenalty; // 5. If delta = 2, decrease score by longMorePenalty. if (delta === 2) score -= longMorePenalty; // 6. Else if delta = 1, decrease score by shortMorePenalty. else if (delta === 1) score -= shortMorePenalty; // 7. Else if delta = -1, decrease score by shortLessPenalty. else if (delta === -1) score -= shortLessPenalty; // 8. Else if delta = -2, decrease score by longLessPenalty. else if (delta === -2) score -= longLessPenalty; } } // d. If score > bestScore, then if (score > bestScore) { // i. Let bestScore be score. bestScore = score; // ii. Let bestFormat be format. bestFormat = format; } // e. Increase i by 1. i++; } // 12. Return bestFormat. return bestFormat; }
[ "function", "$$core$$calculateScore", "(", "options", ",", "formats", ",", "bestFit", ")", "{", "var", "// Additional penalty type when bestFit === true", "diffDataTypePenalty", "=", "8", ",", "// 1. Let removalPenalty be 120.", "removalPenalty", "=", "120", ",", "// 2. Let...
Calculates score for BestFitFormatMatcher and BasicFormatMatcher. Abstracted from BasicFormatMatcher section.
[ "Calculates", "score", "for", "BestFitFormatMatcher", "and", "BasicFormatMatcher", ".", "Abstracted", "from", "BasicFormatMatcher", "section", "." ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/static/js/Intl.js#L2389-L2513
34,560
mozilla/webmaker-core
src/static/js/Intl.js
$$core$$resolveDateString
function $$core$$resolveDateString(data, ca, component, width, key) { // From http://www.unicode.org/reports/tr35/tr35.html#Multiple_Inheritance: // 'In clearly specified instances, resources may inherit from within the same locale. // For example, ... the Buddhist calendar inherits from the Gregorian calendar.' var obj = data[ca] && data[ca][component] ? data[ca][component] : data.gregory[component], // "sideways" inheritance resolves strings when a key doesn't exist alts = { narrow: ['short', 'long'], short: ['long', 'narrow'], long: ['short', 'narrow'] }, // resolved = $$core$$hop.call(obj, width) ? obj[width] : $$core$$hop.call(obj, alts[width][0]) ? obj[alts[width][0]] : obj[alts[width][1]]; // `key` wouldn't be specified for components 'dayPeriods' return key != null ? resolved[key] : resolved; }
javascript
function $$core$$resolveDateString(data, ca, component, width, key) { // From http://www.unicode.org/reports/tr35/tr35.html#Multiple_Inheritance: // 'In clearly specified instances, resources may inherit from within the same locale. // For example, ... the Buddhist calendar inherits from the Gregorian calendar.' var obj = data[ca] && data[ca][component] ? data[ca][component] : data.gregory[component], // "sideways" inheritance resolves strings when a key doesn't exist alts = { narrow: ['short', 'long'], short: ['long', 'narrow'], long: ['short', 'narrow'] }, // resolved = $$core$$hop.call(obj, width) ? obj[width] : $$core$$hop.call(obj, alts[width][0]) ? obj[alts[width][0]] : obj[alts[width][1]]; // `key` wouldn't be specified for components 'dayPeriods' return key != null ? resolved[key] : resolved; }
[ "function", "$$core$$resolveDateString", "(", "data", ",", "ca", ",", "component", ",", "width", ",", "key", ")", "{", "// From http://www.unicode.org/reports/tr35/tr35.html#Multiple_Inheritance:", "// 'In clearly specified instances, resources may inherit from within the same locale."...
Returns a string for a date component, resolved using multiple inheritance as specified as specified in the Unicode Technical Standard 35.
[ "Returns", "a", "string", "for", "a", "date", "component", "resolved", "using", "multiple", "inheritance", "as", "specified", "as", "specified", "in", "the", "Unicode", "Technical", "Standard", "35", "." ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/static/js/Intl.js#L3113-L3137
34,561
mozilla/webmaker-core
src/static/js/Intl.js
$$core$$createRegExpRestore
function $$core$$createRegExpRestore () { var esc = /[.?*+^$[\]\\(){}|-]/g, lm = RegExp.lastMatch || '', ml = RegExp.multiline ? 'm' : '', ret = { input: RegExp.input }, reg = new $$core$$List(), has = false, cap = {}; // Create a snapshot of all the 'captured' properties for (var i = 1; i <= 9; i++) has = (cap['$'+i] = RegExp['$'+i]) || has; // Now we've snapshotted some properties, escape the lastMatch string lm = lm.replace(esc, '\\$&'); // If any of the captured strings were non-empty, iterate over them all if (has) { for (var i = 1; i <= 9; i++) { var m = cap['$'+i]; // If it's empty, add an empty capturing group if (!m) lm = '()' + lm; // Else find the string in lm and escape & wrap it to capture it else { m = m.replace(esc, '\\$&'); lm = lm.replace(m, '(' + m + ')'); } // Push it to the reg and chop lm to make sure further groups come after $$core$$arrPush.call(reg, lm.slice(0, lm.indexOf('(') + 1)); lm = lm.slice(lm.indexOf('(') + 1); } } // Create the regular expression that will reconstruct the RegExp properties ret.exp = new RegExp($$core$$arrJoin.call(reg, '') + lm, ml); return ret; }
javascript
function $$core$$createRegExpRestore () { var esc = /[.?*+^$[\]\\(){}|-]/g, lm = RegExp.lastMatch || '', ml = RegExp.multiline ? 'm' : '', ret = { input: RegExp.input }, reg = new $$core$$List(), has = false, cap = {}; // Create a snapshot of all the 'captured' properties for (var i = 1; i <= 9; i++) has = (cap['$'+i] = RegExp['$'+i]) || has; // Now we've snapshotted some properties, escape the lastMatch string lm = lm.replace(esc, '\\$&'); // If any of the captured strings were non-empty, iterate over them all if (has) { for (var i = 1; i <= 9; i++) { var m = cap['$'+i]; // If it's empty, add an empty capturing group if (!m) lm = '()' + lm; // Else find the string in lm and escape & wrap it to capture it else { m = m.replace(esc, '\\$&'); lm = lm.replace(m, '(' + m + ')'); } // Push it to the reg and chop lm to make sure further groups come after $$core$$arrPush.call(reg, lm.slice(0, lm.indexOf('(') + 1)); lm = lm.slice(lm.indexOf('(') + 1); } } // Create the regular expression that will reconstruct the RegExp properties ret.exp = new RegExp($$core$$arrJoin.call(reg, '') + lm, ml); return ret; }
[ "function", "$$core$$createRegExpRestore", "(", ")", "{", "var", "esc", "=", "/", "[.?*+^$[\\]\\\\(){}|-]", "/", "g", ",", "lm", "=", "RegExp", ".", "lastMatch", "||", "''", ",", "ml", "=", "RegExp", ".", "multiline", "?", "'m'", ":", "''", ",", "ret", ...
Constructs a regular expression to restore tainted RegExp properties
[ "Constructs", "a", "regular", "expression", "to", "restore", "tainted", "RegExp", "properties" ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/static/js/Intl.js#L3165-L3206
34,562
mozilla/webmaker-core
src/static/js/Intl.js
$$core$$toLatinUpperCase
function $$core$$toLatinUpperCase (str) { var i = str.length; while (i--) { var ch = str.charAt(i); if (ch >= "a" && ch <= "z") str = str.slice(0, i) + ch.toUpperCase() + str.slice(i+1); } return str; }
javascript
function $$core$$toLatinUpperCase (str) { var i = str.length; while (i--) { var ch = str.charAt(i); if (ch >= "a" && ch <= "z") str = str.slice(0, i) + ch.toUpperCase() + str.slice(i+1); } return str; }
[ "function", "$$core$$toLatinUpperCase", "(", "str", ")", "{", "var", "i", "=", "str", ".", "length", ";", "while", "(", "i", "--", ")", "{", "var", "ch", "=", "str", ".", "charAt", "(", "i", ")", ";", "if", "(", "ch", ">=", "\"a\"", "&&", "ch", ...
Convert only a-z to uppercase as per section 6.1 of the spec
[ "Convert", "only", "a", "-", "z", "to", "uppercase", "as", "per", "section", "6", ".", "1", "of", "the", "spec" ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/static/js/Intl.js#L3211-L3222
34,563
DeanCording/node-red-contrib-persist
persist.js
PersistInNode
function PersistInNode(n) { RED.nodes.createNode(this,n); var node = this; node.name = n.name; node.storageNode = RED.nodes.getNode(n.storageNode); node.on("input", function(msg) { node.storageNode.store(node.name, msg); }); }
javascript
function PersistInNode(n) { RED.nodes.createNode(this,n); var node = this; node.name = n.name; node.storageNode = RED.nodes.getNode(n.storageNode); node.on("input", function(msg) { node.storageNode.store(node.name, msg); }); }
[ "function", "PersistInNode", "(", "n", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "n", ")", ";", "var", "node", "=", "this", ";", "node", ".", "name", "=", "n", ".", "name", ";", "node", ".", "storageNode", "=", "RED", "....
Record data to persist
[ "Record", "data", "to", "persist" ]
8c6a70ffcc13b71ea6f533f1e475223d373c0d8d
https://github.com/DeanCording/node-red-contrib-persist/blob/8c6a70ffcc13b71ea6f533f1e475223d373c0d8d/persist.js#L137-L147
34,564
DeanCording/node-red-contrib-persist
persist.js
PersistOutNode
function PersistOutNode(n) { RED.nodes.createNode(this,n); var node = this; node.name = n.name; node.storageNode = RED.nodes.getNode(n.storageNode); node.restore = function() { var msg = node.storageNode.getMessage(node.name); node.send(msg); }; RED.events.on("nodes-started", node.restore); node.on("input", function(msg) { node.restore(); }); node.on('close', function(removed, done) { RED.events.removeListener("nodes-started", node.restore); done(); }); }
javascript
function PersistOutNode(n) { RED.nodes.createNode(this,n); var node = this; node.name = n.name; node.storageNode = RED.nodes.getNode(n.storageNode); node.restore = function() { var msg = node.storageNode.getMessage(node.name); node.send(msg); }; RED.events.on("nodes-started", node.restore); node.on("input", function(msg) { node.restore(); }); node.on('close', function(removed, done) { RED.events.removeListener("nodes-started", node.restore); done(); }); }
[ "function", "PersistOutNode", "(", "n", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "n", ")", ";", "var", "node", "=", "this", ";", "node", ".", "name", "=", "n", ".", "name", ";", "node", ".", "storageNode", "=", "RED", "...
Replay persisted data
[ "Replay", "persisted", "data" ]
8c6a70ffcc13b71ea6f533f1e475223d373c0d8d
https://github.com/DeanCording/node-red-contrib-persist/blob/8c6a70ffcc13b71ea6f533f1e475223d373c0d8d/persist.js#L151-L174
34,565
johnstonbl01/eslint-no-inferred-method-name
lib/rules/no-inferred-method-name.js
isMethodCall
function isMethodCall(node) { var nodeParentType = node.parent.type, nodeParentParentParentType = node.parent.parent.parent.type; if (nodeParentType === "CallExpression" && nodeParentParentParentType === "BlockStatement" && !variable) { return true; } else { return false; } }
javascript
function isMethodCall(node) { var nodeParentType = node.parent.type, nodeParentParentParentType = node.parent.parent.parent.type; if (nodeParentType === "CallExpression" && nodeParentParentParentType === "BlockStatement" && !variable) { return true; } else { return false; } }
[ "function", "isMethodCall", "(", "node", ")", "{", "var", "nodeParentType", "=", "node", ".", "parent", ".", "type", ",", "nodeParentParentParentType", "=", "node", ".", "parent", ".", "parent", ".", "parent", ".", "type", ";", "if", "(", "nodeParentType", ...
Checks for object literal method @param {ASTNode} node The AST node being checked. @returns true if parent node is a call expression and is part of an object literal
[ "Checks", "for", "object", "literal", "method" ]
427bca541b204e68a284070f51c6382c544dd200
https://github.com/johnstonbl01/eslint-no-inferred-method-name/blob/427bca541b204e68a284070f51c6382c544dd200/lib/rules/no-inferred-method-name.js#L77-L86
34,566
nullobject/bulb
packages/bulb/src/Signal.js
broadcast
function broadcast (subscriptions, type) { return value => { subscriptions.forEach(s => { if (typeof s.emit[type] === 'function') { s.emit[type](value) } }) } }
javascript
function broadcast (subscriptions, type) { return value => { subscriptions.forEach(s => { if (typeof s.emit[type] === 'function') { s.emit[type](value) } }) } }
[ "function", "broadcast", "(", "subscriptions", ",", "type", ")", "{", "return", "value", "=>", "{", "subscriptions", ".", "forEach", "(", "s", "=>", "{", "if", "(", "typeof", "s", ".", "emit", "[", "type", "]", "===", "'function'", ")", "{", "s", "."...
Creates a callback function that emits values to a list of subscribers. @private @param {Array} subscriptions An array of subscriptions. @param {String} type The type of callback to create. @returns {Function} A function that emits a value to all of the subscriptions.
[ "Creates", "a", "callback", "function", "that", "emits", "values", "to", "a", "list", "of", "subscribers", "." ]
bf0768e42d972ebca51438e74927b0cac8dfbd8e
https://github.com/nullobject/bulb/blob/bf0768e42d972ebca51438e74927b0cac8dfbd8e/packages/bulb/src/Signal.js#L47-L55
34,567
datavis-tech/reactive-model
index.js
function (){ var outputPropertyName, callback, inputPropertyNames, inputs, output; if(arguments.length === 0){ return configurationProperty(); } else if(arguments.length === 1){ if(typeof arguments[0] === "object"){ // The invocation is of the form model(configuration) return setConfiguration(arguments[0]); } else { // The invocation is of the form model(propertyName) return addProperty(arguments[0]); } } else if(arguments.length === 2){ if(typeof arguments[0] === "function"){ // The invocation is of the form model(callback, inputPropertyNames) inputPropertyNames = arguments[1]; callback = arguments[0]; outputPropertyName = undefined; } else { // The invocation is of the form model(propertyName, defaultValue) return addProperty(arguments[0], arguments[1]); } } else if(arguments.length === 3){ outputPropertyName = arguments[0]; callback = arguments[1]; inputPropertyNames = arguments[2]; } // inputPropertyNames may be a string of comma-separated property names, // or an array of property names. if(typeof inputPropertyNames === "string"){ inputPropertyNames = inputPropertyNames.split(",").map(invoke("trim")); } inputs = inputPropertyNames.map(function (propertyName){ var property = getProperty(propertyName); if(typeof property === "undefined"){ throw new Error([ "The property \"", propertyName, "\" was referenced as a dependency for a reactive function before it was defined. ", "Please define each property first before referencing them in reactive functions." ].join("")); } return property; }); // Create a new reactive property for the output and assign it to the model. if(outputPropertyName){ addProperty(outputPropertyName); output = model[outputPropertyName]; } // If the number of arguments expected by the callback is one greater than the // number of inputs, then the last argument is the "done" callback, and this // reactive function will be set up to be asynchronous. The "done" callback should // be called with the new value of the output property asynchronously. var isAsynchronous = (callback.length === inputs.length + 1); if(isAsynchronous){ reactiveFunctions.push(ReactiveFunction({ inputs: inputs, callback: function (){ // Convert the arguments passed into this function into an array. var args = Array.prototype.slice.call(arguments); // Push the "done" callback onto the args array. // We are actally passing the output reactive property here, invoking it // as the "done" callback will set the value of the output property. args.push(output); // Wrap in setTimeout to guarantee that the output property is set // asynchronously, outside of the current digest. This is necessary // to ensure that if developers inadvertently invoke the "done" callback // synchronously, their code will still have the expected behavior. setTimeout(function (){ // Invoke the original callback with the args array as arguments. callback.apply(null, args); }); } })); } else { reactiveFunctions.push(ReactiveFunction({ inputs: inputs, output: output, // This may be undefined. callback: callback })); } return model; }
javascript
function (){ var outputPropertyName, callback, inputPropertyNames, inputs, output; if(arguments.length === 0){ return configurationProperty(); } else if(arguments.length === 1){ if(typeof arguments[0] === "object"){ // The invocation is of the form model(configuration) return setConfiguration(arguments[0]); } else { // The invocation is of the form model(propertyName) return addProperty(arguments[0]); } } else if(arguments.length === 2){ if(typeof arguments[0] === "function"){ // The invocation is of the form model(callback, inputPropertyNames) inputPropertyNames = arguments[1]; callback = arguments[0]; outputPropertyName = undefined; } else { // The invocation is of the form model(propertyName, defaultValue) return addProperty(arguments[0], arguments[1]); } } else if(arguments.length === 3){ outputPropertyName = arguments[0]; callback = arguments[1]; inputPropertyNames = arguments[2]; } // inputPropertyNames may be a string of comma-separated property names, // or an array of property names. if(typeof inputPropertyNames === "string"){ inputPropertyNames = inputPropertyNames.split(",").map(invoke("trim")); } inputs = inputPropertyNames.map(function (propertyName){ var property = getProperty(propertyName); if(typeof property === "undefined"){ throw new Error([ "The property \"", propertyName, "\" was referenced as a dependency for a reactive function before it was defined. ", "Please define each property first before referencing them in reactive functions." ].join("")); } return property; }); // Create a new reactive property for the output and assign it to the model. if(outputPropertyName){ addProperty(outputPropertyName); output = model[outputPropertyName]; } // If the number of arguments expected by the callback is one greater than the // number of inputs, then the last argument is the "done" callback, and this // reactive function will be set up to be asynchronous. The "done" callback should // be called with the new value of the output property asynchronously. var isAsynchronous = (callback.length === inputs.length + 1); if(isAsynchronous){ reactiveFunctions.push(ReactiveFunction({ inputs: inputs, callback: function (){ // Convert the arguments passed into this function into an array. var args = Array.prototype.slice.call(arguments); // Push the "done" callback onto the args array. // We are actally passing the output reactive property here, invoking it // as the "done" callback will set the value of the output property. args.push(output); // Wrap in setTimeout to guarantee that the output property is set // asynchronously, outside of the current digest. This is necessary // to ensure that if developers inadvertently invoke the "done" callback // synchronously, their code will still have the expected behavior. setTimeout(function (){ // Invoke the original callback with the args array as arguments. callback.apply(null, args); }); } })); } else { reactiveFunctions.push(ReactiveFunction({ inputs: inputs, output: output, // This may be undefined. callback: callback })); } return model; }
[ "function", "(", ")", "{", "var", "outputPropertyName", ",", "callback", ",", "inputPropertyNames", ",", "inputs", ",", "output", ";", "if", "(", "arguments", ".", "length", "===", "0", ")", "{", "return", "configurationProperty", "(", ")", ";", "}", "else...
The model instance object. This is the value returned from the constructor.
[ "The", "model", "instance", "object", ".", "This", "is", "the", "value", "returned", "from", "the", "constructor", "." ]
c64c13c37216baa39cb7aafee5787a5a0a15e659
https://github.com/datavis-tech/reactive-model/blob/c64c13c37216baa39cb7aafee5787a5a0a15e659/index.js#L46-L146
34,568
datavis-tech/reactive-model
index.js
addProperty
function addProperty(propertyName, defaultValue){ if(model[propertyName]){ throw new Error("The property \"" + propertyName + "\" is already defined."); } var property = ReactiveProperty(defaultValue); property.propertyName = propertyName; model[propertyName] = property; lastPropertyAdded = propertyName; return model; }
javascript
function addProperty(propertyName, defaultValue){ if(model[propertyName]){ throw new Error("The property \"" + propertyName + "\" is already defined."); } var property = ReactiveProperty(defaultValue); property.propertyName = propertyName; model[propertyName] = property; lastPropertyAdded = propertyName; return model; }
[ "function", "addProperty", "(", "propertyName", ",", "defaultValue", ")", "{", "if", "(", "model", "[", "propertyName", "]", ")", "{", "throw", "new", "Error", "(", "\"The property \\\"\"", "+", "propertyName", "+", "\"\\\" is already defined.\"", ")", ";", "}",...
Adds a property to the model that is not exposed, meaning that it is not included in the configuration object.
[ "Adds", "a", "property", "to", "the", "model", "that", "is", "not", "exposed", "meaning", "that", "it", "is", "not", "included", "in", "the", "configuration", "object", "." ]
c64c13c37216baa39cb7aafee5787a5a0a15e659
https://github.com/datavis-tech/reactive-model/blob/c64c13c37216baa39cb7aafee5787a5a0a15e659/index.js#L156-L167
34,569
datavis-tech/reactive-model
index.js
expose
function expose(){ // TODO test this // if(!isDefined(defaultValue)){ // throw new Error("model.addPublicProperty() is being " + // "invoked with an undefined default value. Default values for exposed properties " + // "must be defined, to guarantee predictable behavior. For exposed properties that " + // "are optional and should have the semantics of an undefined value, " + // "use null as the default value."); //} // TODO test this if(!lastPropertyAdded){ throw Error("Expose() was called without first adding a property."); } var propertyName = lastPropertyAdded; if(!exposedProperties){ exposedProperties = []; } exposedProperties.push(propertyName); // Destroy the previous reactive function that was listening for changes // in all exposed properties except the newly added one. // TODO think about how this might be done only once, at the same time isFinalized is set. if(configurationReactiveFunction){ configurationReactiveFunction.destroy(); } // Set up the new reactive function that will listen for changes // in all exposed properties including the newly added one. var inputPropertyNames = exposedProperties; //console.log(inputPropertyNames); configurationReactiveFunction = ReactiveFunction({ inputs: inputPropertyNames.map(getProperty), output: configurationProperty, callback: function (){ var configuration = {}; inputPropertyNames.forEach(function (propertyName){ var property = getProperty(propertyName); // Omit default values from the returned configuration object. if(property() !== property.default()){ configuration[propertyName] = property(); } }); return configuration; } }); // Support method chaining. return model; }
javascript
function expose(){ // TODO test this // if(!isDefined(defaultValue)){ // throw new Error("model.addPublicProperty() is being " + // "invoked with an undefined default value. Default values for exposed properties " + // "must be defined, to guarantee predictable behavior. For exposed properties that " + // "are optional and should have the semantics of an undefined value, " + // "use null as the default value."); //} // TODO test this if(!lastPropertyAdded){ throw Error("Expose() was called without first adding a property."); } var propertyName = lastPropertyAdded; if(!exposedProperties){ exposedProperties = []; } exposedProperties.push(propertyName); // Destroy the previous reactive function that was listening for changes // in all exposed properties except the newly added one. // TODO think about how this might be done only once, at the same time isFinalized is set. if(configurationReactiveFunction){ configurationReactiveFunction.destroy(); } // Set up the new reactive function that will listen for changes // in all exposed properties including the newly added one. var inputPropertyNames = exposedProperties; //console.log(inputPropertyNames); configurationReactiveFunction = ReactiveFunction({ inputs: inputPropertyNames.map(getProperty), output: configurationProperty, callback: function (){ var configuration = {}; inputPropertyNames.forEach(function (propertyName){ var property = getProperty(propertyName); // Omit default values from the returned configuration object. if(property() !== property.default()){ configuration[propertyName] = property(); } }); return configuration; } }); // Support method chaining. return model; }
[ "function", "expose", "(", ")", "{", "// TODO test this", "// if(!isDefined(defaultValue)){", "// throw new Error(\"model.addPublicProperty() is being \" +", "// \"invoked with an undefined default value. Default values for exposed properties \" +", "// \"must be defined, to guarantee predi...
Exposes the last added property to the configuration.
[ "Exposes", "the", "last", "added", "property", "to", "the", "configuration", "." ]
c64c13c37216baa39cb7aafee5787a5a0a15e659
https://github.com/datavis-tech/reactive-model/blob/c64c13c37216baa39cb7aafee5787a5a0a15e659/index.js#L170-L224
34,570
datavis-tech/reactive-model
index.js
destroy
function destroy(){ // Destroy reactive functions. reactiveFunctions.forEach(invoke("destroy")); if(configurationReactiveFunction){ configurationReactiveFunction.destroy(); } // Destroy properties (removes listeners). Object.keys(model).forEach(function (propertyName){ var property = model[propertyName]; if(property.destroy){ property.destroy(); } }); // Release references. reactiveFunctions = undefined; configurationReactiveFunction = undefined; }
javascript
function destroy(){ // Destroy reactive functions. reactiveFunctions.forEach(invoke("destroy")); if(configurationReactiveFunction){ configurationReactiveFunction.destroy(); } // Destroy properties (removes listeners). Object.keys(model).forEach(function (propertyName){ var property = model[propertyName]; if(property.destroy){ property.destroy(); } }); // Release references. reactiveFunctions = undefined; configurationReactiveFunction = undefined; }
[ "function", "destroy", "(", ")", "{", "// Destroy reactive functions.", "reactiveFunctions", ".", "forEach", "(", "invoke", "(", "\"destroy\"", ")", ")", ";", "if", "(", "configurationReactiveFunction", ")", "{", "configurationReactiveFunction", ".", "destroy", "(", ...
Destroys all reactive functions and properties that have been added to the model.
[ "Destroys", "all", "reactive", "functions", "and", "properties", "that", "have", "been", "added", "to", "the", "model", "." ]
c64c13c37216baa39cb7aafee5787a5a0a15e659
https://github.com/datavis-tech/reactive-model/blob/c64c13c37216baa39cb7aafee5787a5a0a15e659/index.js#L248-L267
34,571
fuzhenn/tiler-arcgis-bundle
index.js
tiler
function tiler(root, options) { this.root = root; options = options || {}; options.packSize = options.packSize || 128; if (!options.storageFormat) { options.storageFormat = guessStorageFormat(root); } this.options = options; }
javascript
function tiler(root, options) { this.root = root; options = options || {}; options.packSize = options.packSize || 128; if (!options.storageFormat) { options.storageFormat = guessStorageFormat(root); } this.options = options; }
[ "function", "tiler", "(", "root", ",", "options", ")", "{", "this", ".", "root", "=", "root", ";", "options", "=", "options", "||", "{", "}", ";", "options", ".", "packSize", "=", "options", ".", "packSize", "||", "128", ";", "if", "(", "!", "optio...
Constructor for the tiler-arcgis-bundle @param {String} root - the root folder of ArcGIS bundle tiles, where the Conf.xml stands. @param {Object} options - options passed in. @param {integer} options.packSize - packet size. @param {String} options.storageFormat - bundle storage format. @class
[ "Constructor", "for", "the", "tiler", "-", "arcgis", "-", "bundle" ]
16643acc7d02dd095d184ff75b42f4169ffe6e03
https://github.com/fuzhenn/tiler-arcgis-bundle/blob/16643acc7d02dd095d184ff75b42f4169ffe6e03/index.js#L21-L29
34,572
mozilla/webmaker-core
src/pages/project/pageadmin.js
function (id, type) { if (this.state.sourcePageID !== id) { var selectedPage; this.state.pages.forEach(function (page) { if (parseInt(page.id, 10) === parseInt(id, 10)) { selectedPage = page; } }); if (!selectedPage) { console.warn('Page not found.'); return; } var currentZoom = this.state.matrix[0]; var {x, y} = this.cartesian.getFocusTransform(selectedPage.coords, this.state.matrix[0]); var newState = { matrix: [currentZoom, 0, 0, currentZoom, x, y] }; if (type === 'selected') { newState.selectedEl = id; } else if (type === 'source') { newState.sourcePageID = id; } this.setState(newState); } }
javascript
function (id, type) { if (this.state.sourcePageID !== id) { var selectedPage; this.state.pages.forEach(function (page) { if (parseInt(page.id, 10) === parseInt(id, 10)) { selectedPage = page; } }); if (!selectedPage) { console.warn('Page not found.'); return; } var currentZoom = this.state.matrix[0]; var {x, y} = this.cartesian.getFocusTransform(selectedPage.coords, this.state.matrix[0]); var newState = { matrix: [currentZoom, 0, 0, currentZoom, x, y] }; if (type === 'selected') { newState.selectedEl = id; } else if (type === 'source') { newState.sourcePageID = id; } this.setState(newState); } }
[ "function", "(", "id", ",", "type", ")", "{", "if", "(", "this", ".", "state", ".", "sourcePageID", "!==", "id", ")", "{", "var", "selectedPage", ";", "this", ".", "state", ".", "pages", ".", "forEach", "(", "function", "(", "page", ")", "{", "if",...
Highlight a page in the UI and move camera to center it @param {Number|String} id ID of page @param {Number|String} type Type of highlight ("selected", "source")
[ "Highlight", "a", "page", "in", "the", "UI", "and", "move", "camera", "to", "center", "it" ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/pages/project/pageadmin.js#L19-L48
34,573
SnakeskinTpl/Snakeskin
src/parser/jadeLike.js
appendDirEnd
function appendDirEnd(str, struct) { if (!struct.block) { return str; } const [rightSpace] = rightWSRgxp.exec(str); str = str.replace(rightPartRgxp, ''); const s = alb + lb, e = rb; let tmp; if (needSpace) { tmp = `${struct.trim.right ? '' : eol}${endDirInit ? '' : `${s}__&+__${e}`}${struct.trim.right ? eol : ''}`; } else { tmp = eol + struct.space.slice(1); } endDirInit = true; str += `${tmp}${struct.adv + lb}__end__${e}${s}__cutLine__${e}`; if (rightSpace && needSpace) { str += `${s}__&-__${rb}`; } return str + rightSpace; }
javascript
function appendDirEnd(str, struct) { if (!struct.block) { return str; } const [rightSpace] = rightWSRgxp.exec(str); str = str.replace(rightPartRgxp, ''); const s = alb + lb, e = rb; let tmp; if (needSpace) { tmp = `${struct.trim.right ? '' : eol}${endDirInit ? '' : `${s}__&+__${e}`}${struct.trim.right ? eol : ''}`; } else { tmp = eol + struct.space.slice(1); } endDirInit = true; str += `${tmp}${struct.adv + lb}__end__${e}${s}__cutLine__${e}`; if (rightSpace && needSpace) { str += `${s}__&-__${rb}`; } return str + rightSpace; }
[ "function", "appendDirEnd", "(", "str", ",", "struct", ")", "{", "if", "(", "!", "struct", ".", "block", ")", "{", "return", "str", ";", "}", "const", "[", "rightSpace", "]", "=", "rightWSRgxp", ".", "exec", "(", "str", ")", ";", "str", "=", "str",...
Appends the directive end for a resulting string and returns a new string @param {string} str - resulting string @param {!Object} struct - structure object @return {string}
[ "Appends", "the", "directive", "end", "for", "a", "resulting", "string", "and", "returns", "a", "new", "string" ]
3e92aa6c5ae9f242ef80adb5e278e9054225205a
https://github.com/SnakeskinTpl/Snakeskin/blob/3e92aa6c5ae9f242ef80adb5e278e9054225205a/src/parser/jadeLike.js#L362-L390
34,574
mozilla/webmaker-core
src/pages/element/font-selector.js
function() { var fonts = ["Roboto", "Bitter", "Pacifico"]; var options = fonts.map(name => { // setting style on an <option> does not work in WebView... return <option key={name} value={name}>{name}</option>; }); return <select className="select" valueLink={this.linkState('fontFamily')}>{ options }</select>; }
javascript
function() { var fonts = ["Roboto", "Bitter", "Pacifico"]; var options = fonts.map(name => { // setting style on an <option> does not work in WebView... return <option key={name} value={name}>{name}</option>; }); return <select className="select" valueLink={this.linkState('fontFamily')}>{ options }</select>; }
[ "function", "(", ")", "{", "var", "fonts", "=", "[", "\"Roboto\"", ",", "\"Bitter\"", ",", "\"Pacifico\"", "]", ";", "var", "options", "=", "fonts", ".", "map", "(", "name", "=>", "{", "// setting style on an <option> does not work in WebView...", "return", "<",...
Generate the dropdown selector for fonts, with each font option styled in the appropriate font. @return {[type]}
[ "Generate", "the", "dropdown", "selector", "for", "fonts", "with", "each", "font", "option", "styled", "in", "the", "appropriate", "font", "." ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/pages/element/font-selector.js#L14-L21
34,575
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
callback
function callback(fn, context, event) { //window.setTimeout(function(){ event.target = context; (typeof context[fn] === "function") && context[fn].apply(context, [event]); //}, 1); }
javascript
function callback(fn, context, event) { //window.setTimeout(function(){ event.target = context; (typeof context[fn] === "function") && context[fn].apply(context, [event]); //}, 1); }
[ "function", "callback", "(", "fn", ",", "context", ",", "event", ")", "{", "//window.setTimeout(function(){\r", "event", ".", "target", "=", "context", ";", "(", "typeof", "context", "[", "fn", "]", "===", "\"function\"", ")", "&&", "context", "[", "fn", "...
A utility method to callback onsuccess, onerror, etc as soon as the calling function's context is over @param {Object} fn @param {Object} context @param {Object} argArray
[ "A", "utility", "method", "to", "callback", "onsuccess", "onerror", "etc", "as", "soon", "as", "the", "calling", "function", "s", "context", "is", "over" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L33-L38
34,576
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
polyfill
function polyfill() { if (navigator.userAgent.match(/MSIE/) || navigator.userAgent.match(/Trident/) || navigator.userAgent.match(/Edge/)) { // Internet Explorer's native IndexedDB does not support compound keys compoundKeyPolyfill(); } }
javascript
function polyfill() { if (navigator.userAgent.match(/MSIE/) || navigator.userAgent.match(/Trident/) || navigator.userAgent.match(/Edge/)) { // Internet Explorer's native IndexedDB does not support compound keys compoundKeyPolyfill(); } }
[ "function", "polyfill", "(", ")", "{", "if", "(", "navigator", ".", "userAgent", ".", "match", "(", "/", "MSIE", "/", ")", "||", "navigator", ".", "userAgent", ".", "match", "(", "/", "Trident", "/", ")", "||", "navigator", ".", "userAgent", ".", "ma...
Polyfills missing features in the browser's native IndexedDB implementation. This is used for browsers that DON'T support WebSQL but DO support IndexedDB
[ "Polyfills", "missing", "features", "in", "the", "browser", "s", "native", "IndexedDB", "implementation", ".", "This", "is", "used", "for", "browsers", "that", "DON", "T", "support", "WebSQL", "but", "DO", "support", "IndexedDB" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L114-L121
34,577
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
readBlobAsDataURL
function readBlobAsDataURL(blob, path) { var reader = new FileReader(); reader.onloadend = function(loadedEvent) { var dataURL = loadedEvent.target.result; var blobtype = 'Blob'; if (blob instanceof File) { //blobtype = 'File'; } updateEncodedBlob(dataURL, path, blobtype); }; reader.readAsDataURL(blob); }
javascript
function readBlobAsDataURL(blob, path) { var reader = new FileReader(); reader.onloadend = function(loadedEvent) { var dataURL = loadedEvent.target.result; var blobtype = 'Blob'; if (blob instanceof File) { //blobtype = 'File'; } updateEncodedBlob(dataURL, path, blobtype); }; reader.readAsDataURL(blob); }
[ "function", "readBlobAsDataURL", "(", "blob", ",", "path", ")", "{", "var", "reader", "=", "new", "FileReader", "(", ")", ";", "reader", ".", "onloadend", "=", "function", "(", "loadedEvent", ")", "{", "var", "dataURL", "=", "loadedEvent", ".", "target", ...
Convert a blob to a data URL. @param {Blob} blob to convert. @param {String} path of blob in object being encoded.
[ "Convert", "a", "blob", "to", "a", "data", "URL", "." ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L519-L530
34,578
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
updateEncodedBlob
function updateEncodedBlob(dataURL, path, blobtype) { var encoded = queuedObjects.indexOf(path); path = path.replace('$','derezObj'); eval(path+'.$enc="'+dataURL+'"'); eval(path+'.$type="'+blobtype+'"'); queuedObjects.splice(encoded, 1); checkForCompletion(); }
javascript
function updateEncodedBlob(dataURL, path, blobtype) { var encoded = queuedObjects.indexOf(path); path = path.replace('$','derezObj'); eval(path+'.$enc="'+dataURL+'"'); eval(path+'.$type="'+blobtype+'"'); queuedObjects.splice(encoded, 1); checkForCompletion(); }
[ "function", "updateEncodedBlob", "(", "dataURL", ",", "path", ",", "blobtype", ")", "{", "var", "encoded", "=", "queuedObjects", ".", "indexOf", "(", "path", ")", ";", "path", "=", "path", ".", "replace", "(", "'$'", ",", "'derezObj'", ")", ";", "eval", ...
Async handler to update a blob object to a data URL for encoding. @param {String} dataURL @param {String} path @param {String} blobtype - file if the blob is a file; blob otherwise
[ "Async", "handler", "to", "update", "a", "blob", "object", "to", "a", "data", "URL", "for", "encoding", "." ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L538-L545
34,579
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
dataURLToBlob
function dataURLToBlob(dataURL) { var BASE64_MARKER = ';base64,', contentType, parts, raw; if (dataURL.indexOf(BASE64_MARKER) === -1) { parts = dataURL.split(','); contentType = parts[0].split(':')[1]; raw = parts[1]; return new Blob([raw], {type: contentType}); } parts = dataURL.split(BASE64_MARKER); contentType = parts[0].split(':')[1]; raw = window.atob(parts[1]); var rawLength = raw.length; var uInt8Array = new Uint8Array(rawLength); for (var i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i); } return new Blob([uInt8Array.buffer], {type: contentType}); }
javascript
function dataURLToBlob(dataURL) { var BASE64_MARKER = ';base64,', contentType, parts, raw; if (dataURL.indexOf(BASE64_MARKER) === -1) { parts = dataURL.split(','); contentType = parts[0].split(':')[1]; raw = parts[1]; return new Blob([raw], {type: contentType}); } parts = dataURL.split(BASE64_MARKER); contentType = parts[0].split(':')[1]; raw = window.atob(parts[1]); var rawLength = raw.length; var uInt8Array = new Uint8Array(rawLength); for (var i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i); } return new Blob([uInt8Array.buffer], {type: contentType}); }
[ "function", "dataURLToBlob", "(", "dataURL", ")", "{", "var", "BASE64_MARKER", "=", "';base64,'", ",", "contentType", ",", "parts", ",", "raw", ";", "if", "(", "dataURL", ".", "indexOf", "(", "BASE64_MARKER", ")", "===", "-", "1", ")", "{", "parts", "=",...
Converts the specified data URL to a Blob object @param {String} dataURL to convert to a Blob @returns {Blob} the converted Blob object
[ "Converts", "the", "specified", "data", "URL", "to", "a", "Blob", "object" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L676-L699
34,580
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
function(key) { var key32 = Math.abs(key).toString(32); // Get the index of the decimal. var decimalIndex = key32.indexOf("."); // Remove the decimal. key32 = (decimalIndex !== -1) ? key32.replace(".", "") : key32; // Get the index of the first significant digit. var significantDigitIndex = key32.search(/[^0]/); // Truncate leading zeros. key32 = key32.slice(significantDigitIndex); var sign, exponent = zeros(2), mantissa = zeros(11); // Finite cases: if (isFinite(key)) { // Negative cases: if (key < 0) { // Negative exponent case: if (key > -1) { sign = signValues.indexOf("smallNegative"); exponent = padBase32Exponent(significantDigitIndex); mantissa = flipBase32(padBase32Mantissa(key32)); } // Non-negative exponent case: else { sign = signValues.indexOf("bigNegative"); exponent = flipBase32(padBase32Exponent( (decimalIndex !== -1) ? decimalIndex : key32.length )); mantissa = flipBase32(padBase32Mantissa(key32)); } } // Non-negative cases: else { // Negative exponent case: if (key < 1) { sign = signValues.indexOf("smallPositive"); exponent = flipBase32(padBase32Exponent(significantDigitIndex)); mantissa = padBase32Mantissa(key32); } // Non-negative exponent case: else { sign = signValues.indexOf("bigPositive"); exponent = padBase32Exponent( (decimalIndex !== -1) ? decimalIndex : key32.length ); mantissa = padBase32Mantissa(key32); } } } // Infinite cases: else { sign = signValues.indexOf( key > 0 ? "positiveInfinity" : "negativeInfinity" ); } return collations.indexOf("number") + "-" + sign + exponent + mantissa; }
javascript
function(key) { var key32 = Math.abs(key).toString(32); // Get the index of the decimal. var decimalIndex = key32.indexOf("."); // Remove the decimal. key32 = (decimalIndex !== -1) ? key32.replace(".", "") : key32; // Get the index of the first significant digit. var significantDigitIndex = key32.search(/[^0]/); // Truncate leading zeros. key32 = key32.slice(significantDigitIndex); var sign, exponent = zeros(2), mantissa = zeros(11); // Finite cases: if (isFinite(key)) { // Negative cases: if (key < 0) { // Negative exponent case: if (key > -1) { sign = signValues.indexOf("smallNegative"); exponent = padBase32Exponent(significantDigitIndex); mantissa = flipBase32(padBase32Mantissa(key32)); } // Non-negative exponent case: else { sign = signValues.indexOf("bigNegative"); exponent = flipBase32(padBase32Exponent( (decimalIndex !== -1) ? decimalIndex : key32.length )); mantissa = flipBase32(padBase32Mantissa(key32)); } } // Non-negative cases: else { // Negative exponent case: if (key < 1) { sign = signValues.indexOf("smallPositive"); exponent = flipBase32(padBase32Exponent(significantDigitIndex)); mantissa = padBase32Mantissa(key32); } // Non-negative exponent case: else { sign = signValues.indexOf("bigPositive"); exponent = padBase32Exponent( (decimalIndex !== -1) ? decimalIndex : key32.length ); mantissa = padBase32Mantissa(key32); } } } // Infinite cases: else { sign = signValues.indexOf( key > 0 ? "positiveInfinity" : "negativeInfinity" ); } return collations.indexOf("number") + "-" + sign + exponent + mantissa; }
[ "function", "(", "key", ")", "{", "var", "key32", "=", "Math", ".", "abs", "(", "key", ")", ".", "toString", "(", "32", ")", ";", "// Get the index of the decimal.\r", "var", "decimalIndex", "=", "key32", ".", "indexOf", "(", "\".\"", ")", ";", "// Remov...
The encode step checks for six numeric cases and generates 14-digit encoded sign-exponent-mantissa strings.
[ "The", "encode", "step", "checks", "for", "six", "numeric", "cases", "and", "generates", "14", "-", "digit", "encoded", "sign", "-", "exponent", "-", "mantissa", "strings", "." ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L852-L909
34,581
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
function(key) { var sign = +key.substr(2, 1); var exponent = key.substr(3, 2); var mantissa = key.substr(5, 11); switch (signValues[sign]) { case "negativeInfinity": return -Infinity; case "positiveInfinity": return Infinity; case "bigPositive": return pow32(mantissa, exponent); case "smallPositive": exponent = negate(flipBase32(exponent)); return pow32(mantissa, exponent); case "smallNegative": exponent = negate(exponent); mantissa = flipBase32(mantissa); return -pow32(mantissa, exponent); case "bigNegative": exponent = flipBase32(exponent); mantissa = flipBase32(mantissa); return -pow32(mantissa, exponent); default: throw new Error("Invalid number."); } }
javascript
function(key) { var sign = +key.substr(2, 1); var exponent = key.substr(3, 2); var mantissa = key.substr(5, 11); switch (signValues[sign]) { case "negativeInfinity": return -Infinity; case "positiveInfinity": return Infinity; case "bigPositive": return pow32(mantissa, exponent); case "smallPositive": exponent = negate(flipBase32(exponent)); return pow32(mantissa, exponent); case "smallNegative": exponent = negate(exponent); mantissa = flipBase32(mantissa); return -pow32(mantissa, exponent); case "bigNegative": exponent = flipBase32(exponent); mantissa = flipBase32(mantissa); return -pow32(mantissa, exponent); default: throw new Error("Invalid number."); } }
[ "function", "(", "key", ")", "{", "var", "sign", "=", "+", "key", ".", "substr", "(", "2", ",", "1", ")", ";", "var", "exponent", "=", "key", ".", "substr", "(", "3", ",", "2", ")", ";", "var", "mantissa", "=", "key", ".", "substr", "(", "5",...
The decode step must interpret the sign, reflip values encoded as the 32's complements, apply signs to the exponent and mantissa, do the base-32 power operation, and return the original JavaScript number values.
[ "The", "decode", "step", "must", "interpret", "the", "sign", "reflip", "values", "encoded", "as", "the", "32", "s", "complements", "apply", "signs", "to", "the", "exponent", "and", "mantissa", "do", "the", "base", "-", "32", "power", "operation", "and", "r...
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L913-L939
34,582
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
flipBase32
function flipBase32(encoded) { var flipped = ""; for (var i = 0; i < encoded.length; i++) { flipped += (31 - parseInt(encoded[i], 32)).toString(32); } return flipped; }
javascript
function flipBase32(encoded) { var flipped = ""; for (var i = 0; i < encoded.length; i++) { flipped += (31 - parseInt(encoded[i], 32)).toString(32); } return flipped; }
[ "function", "flipBase32", "(", "encoded", ")", "{", "var", "flipped", "=", "\"\"", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "encoded", ".", "length", ";", "i", "++", ")", "{", "flipped", "+=", "(", "31", "-", "parseInt", "(", "encode...
Flips each digit of a base-32 encoded string. @param {string} encoded
[ "Flips", "each", "digit", "of", "a", "base", "-", "32", "encoded", "string", "." ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L1017-L1023
34,583
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
validate
function validate(key) { var type = getType(key); if (type === "array") { for (var i = 0; i < key.length; i++) { validate(key[i]); } } else if (!types[type] || (type !== "string" && isNaN(key))) { throw idbModules.util.createDOMException("DataError", "Not a valid key"); } }
javascript
function validate(key) { var type = getType(key); if (type === "array") { for (var i = 0; i < key.length; i++) { validate(key[i]); } } else if (!types[type] || (type !== "string" && isNaN(key))) { throw idbModules.util.createDOMException("DataError", "Not a valid key"); } }
[ "function", "validate", "(", "key", ")", "{", "var", "type", "=", "getType", "(", "key", ")", ";", "if", "(", "type", "===", "\"array\"", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "key", ".", "length", ";", "i", "++", ")", "{...
Keys must be strings, numbers, Dates, or Arrays
[ "Keys", "must", "be", "strings", "numbers", "Dates", "or", "Arrays" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L1106-L1116
34,584
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
getValue
function getValue(source, keyPath) { try { if (keyPath instanceof Array) { var arrayValue = []; for (var i = 0; i < keyPath.length; i++) { arrayValue.push(eval("source." + keyPath[i])); } return arrayValue; } else { return eval("source." + keyPath); } } catch (e) { return undefined; } }
javascript
function getValue(source, keyPath) { try { if (keyPath instanceof Array) { var arrayValue = []; for (var i = 0; i < keyPath.length; i++) { arrayValue.push(eval("source." + keyPath[i])); } return arrayValue; } else { return eval("source." + keyPath); } } catch (e) { return undefined; } }
[ "function", "getValue", "(", "source", ",", "keyPath", ")", "{", "try", "{", "if", "(", "keyPath", "instanceof", "Array", ")", "{", "var", "arrayValue", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keyPath", ".", "length", ...
Returns the value of an inline key @param {object} source @param {string|array} keyPath
[ "Returns", "the", "value", "of", "an", "inline", "key" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L1123-L1138
34,585
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
setValue
function setValue(source, keyPath, value) { var props = keyPath.split('.'); for (var i = 0; i < props.length - 1; i++) { var prop = props[i]; source = source[prop] = source[prop] || {}; } source[props[props.length - 1]] = value; }
javascript
function setValue(source, keyPath, value) { var props = keyPath.split('.'); for (var i = 0; i < props.length - 1; i++) { var prop = props[i]; source = source[prop] = source[prop] || {}; } source[props[props.length - 1]] = value; }
[ "function", "setValue", "(", "source", ",", "keyPath", ",", "value", ")", "{", "var", "props", "=", "keyPath", ".", "split", "(", "'.'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "props", ".", "length", "-", "1", ";", "i", "++"...
Sets the inline key value @param {object} source @param {string} keyPath @param {*} value
[ "Sets", "the", "inline", "key", "value" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L1146-L1153
34,586
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
isMultiEntryMatch
function isMultiEntryMatch(encodedEntry, encodedKey) { var keyType = collations[encodedKey.substring(0, 1)]; if (keyType === "array") { return encodedKey.indexOf(encodedEntry) > 1; } else { return encodedKey === encodedEntry; } }
javascript
function isMultiEntryMatch(encodedEntry, encodedKey) { var keyType = collations[encodedKey.substring(0, 1)]; if (keyType === "array") { return encodedKey.indexOf(encodedEntry) > 1; } else { return encodedKey === encodedEntry; } }
[ "function", "isMultiEntryMatch", "(", "encodedEntry", ",", "encodedKey", ")", "{", "var", "keyType", "=", "collations", "[", "encodedKey", ".", "substring", "(", "0", ",", "1", ")", "]", ";", "if", "(", "keyType", "===", "\"array\"", ")", "{", "return", ...
Determines whether an index entry matches a multi-entry key value. @param {string} encodedEntry The entry value (already encoded) @param {string} encodedKey The full index key (already encoded) @returns {boolean}
[ "Determines", "whether", "an", "index", "entry", "matches", "a", "multi", "-", "entry", "key", "value", "." ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L1161-L1170
34,587
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
createNativeEvent
function createNativeEvent(type, debug) { var event = new Event(type); event.debug = debug; // Make the "target" writable Object.defineProperty(event, 'target', { writable: true }); return event; }
javascript
function createNativeEvent(type, debug) { var event = new Event(type); event.debug = debug; // Make the "target" writable Object.defineProperty(event, 'target', { writable: true }); return event; }
[ "function", "createNativeEvent", "(", "type", ",", "debug", ")", "{", "var", "event", "=", "new", "Event", "(", "type", ")", ";", "event", ".", "debug", "=", "debug", ";", "// Make the \"target\" writable\r", "Object", ".", "defineProperty", "(", "event", ",...
Creates a native Event object, for browsers that support it @returns {Event}
[ "Creates", "a", "native", "Event", "object", "for", "browsers", "that", "support", "it" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L1259-L1269
34,588
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
ShimEvent
function ShimEvent(type, debug) { this.type = type; this.debug = debug; this.bubbles = false; this.cancelable = false; this.eventPhase = 0; this.timeStamp = new Date().valueOf(); }
javascript
function ShimEvent(type, debug) { this.type = type; this.debug = debug; this.bubbles = false; this.cancelable = false; this.eventPhase = 0; this.timeStamp = new Date().valueOf(); }
[ "function", "ShimEvent", "(", "type", ",", "debug", ")", "{", "this", ".", "type", "=", "type", ";", "this", ".", "debug", "=", "debug", ";", "this", ".", "bubbles", "=", "false", ";", "this", ".", "cancelable", "=", "false", ";", "this", ".", "eve...
A shim Event class, for browsers that don't allow us to create native Event objects. @constructor
[ "A", "shim", "Event", "class", "for", "browsers", "that", "don", "t", "allow", "us", "to", "create", "native", "Event", "objects", "." ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L1275-L1282
34,589
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
createNativeDOMException
function createNativeDOMException(name, message) { var e = new DOMException.prototype.constructor(0, message); e.name = name || 'DOMException'; e.message = message; return e; }
javascript
function createNativeDOMException(name, message) { var e = new DOMException.prototype.constructor(0, message); e.name = name || 'DOMException'; e.message = message; return e; }
[ "function", "createNativeDOMException", "(", "name", ",", "message", ")", "{", "var", "e", "=", "new", "DOMException", ".", "prototype", ".", "constructor", "(", "0", ",", "message", ")", ";", "e", ".", "name", "=", "name", "||", "'DOMException'", ";", "...
Creates a native DOMException, for browsers that support it @returns {DOMException}
[ "Creates", "a", "native", "DOMException", "for", "browsers", "that", "support", "it" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L1319-L1324
34,590
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
createNativeDOMError
function createNativeDOMError(name, message) { name = name || 'DOMError'; var e = new DOMError(name, message); e.name === name || (e.name = name); e.message === message || (e.message = message); return e; }
javascript
function createNativeDOMError(name, message) { name = name || 'DOMError'; var e = new DOMError(name, message); e.name === name || (e.name = name); e.message === message || (e.message = message); return e; }
[ "function", "createNativeDOMError", "(", "name", ",", "message", ")", "{", "name", "=", "name", "||", "'DOMError'", ";", "var", "e", "=", "new", "DOMError", "(", "name", ",", "message", ")", ";", "e", ".", "name", "===", "name", "||", "(", "e", ".", ...
Creates a native DOMError, for browsers that support it @returns {DOMError}
[ "Creates", "a", "native", "DOMError", "for", "browsers", "that", "support", "it" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L1330-L1336
34,591
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
createError
function createError(name, message) { var e = new Error(message); e.name = name || 'DOMException'; e.message = message; return e; }
javascript
function createError(name, message) { var e = new Error(message); e.name = name || 'DOMException'; e.message = message; return e; }
[ "function", "createError", "(", "name", ",", "message", ")", "{", "var", "e", "=", "new", "Error", "(", "message", ")", ";", "e", ".", "name", "=", "name", "||", "'DOMException'", ";", "e", ".", "message", "=", "message", ";", "return", "e", ";", "...
Creates a generic Error object @returns {Error}
[ "Creates", "a", "generic", "Error", "object" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L1342-L1347
34,592
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
createSysDB
function createSysDB(success, failure) { function sysDbCreateError(tx, err) { err = idbModules.util.findError(arguments); idbModules.DEBUG && console.log("Error in sysdb transaction - when creating dbVersions", err); failure(err); } if (sysdb) { success(); } else { sysdb = window.openDatabase("__sysdb__", 1, "System Database", DEFAULT_DB_SIZE); sysdb.transaction(function(tx) { tx.executeSql("CREATE TABLE IF NOT EXISTS dbVersions (name VARCHAR(255), version INT);", [], success, sysDbCreateError); }, sysDbCreateError); } }
javascript
function createSysDB(success, failure) { function sysDbCreateError(tx, err) { err = idbModules.util.findError(arguments); idbModules.DEBUG && console.log("Error in sysdb transaction - when creating dbVersions", err); failure(err); } if (sysdb) { success(); } else { sysdb = window.openDatabase("__sysdb__", 1, "System Database", DEFAULT_DB_SIZE); sysdb.transaction(function(tx) { tx.executeSql("CREATE TABLE IF NOT EXISTS dbVersions (name VARCHAR(255), version INT);", [], success, sysDbCreateError); }, sysDbCreateError); } }
[ "function", "createSysDB", "(", "success", ",", "failure", ")", "{", "function", "sysDbCreateError", "(", "tx", ",", "err", ")", "{", "err", "=", "idbModules", ".", "util", ".", "findError", "(", "arguments", ")", ";", "idbModules", ".", "DEBUG", "&&", "...
Craetes the sysDB to keep track of version numbers for databases
[ "Craetes", "the", "sysDB", "to", "keep", "track", "of", "version", "numbers", "for", "databases" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L3027-L3043
34,593
tomterl/metalsmith-convert
lib/index.js
function(args) { if (!args.src) { ret = new Error('metalsmith-convert: "src" arg is required'); return; } if (!args.target) { // use source-format for target in convertFile args.target = '__source__'; } var ext = args.extension || '.' + args.target; if (!args.nameFormat) { if (args.resize) { args.nameFormat = '%b_%x_%y%e'; } else { args.nameFormat = '%b%e'; } } if (!!args.remove // don't remove source-files from build if && args.nameFormat === '%b%e' // the converted target has the && args.target === '__source__') { // same name args.remove = false; } Object.keys(files).forEach(function (file) { convertFile(file, ext, args, files, results); }); }
javascript
function(args) { if (!args.src) { ret = new Error('metalsmith-convert: "src" arg is required'); return; } if (!args.target) { // use source-format for target in convertFile args.target = '__source__'; } var ext = args.extension || '.' + args.target; if (!args.nameFormat) { if (args.resize) { args.nameFormat = '%b_%x_%y%e'; } else { args.nameFormat = '%b%e'; } } if (!!args.remove // don't remove source-files from build if && args.nameFormat === '%b%e' // the converted target has the && args.target === '__source__') { // same name args.remove = false; } Object.keys(files).forEach(function (file) { convertFile(file, ext, args, files, results); }); }
[ "function", "(", "args", ")", "{", "if", "(", "!", "args", ".", "src", ")", "{", "ret", "=", "new", "Error", "(", "'metalsmith-convert: \"src\" arg is required'", ")", ";", "return", ";", "}", "if", "(", "!", "args", ".", "target", ")", "{", "// use so...
what to return;
[ "what", "to", "return", ";" ]
0370a6dc268d6288be8620faa620820843b538e7
https://github.com/tomterl/metalsmith-convert/blob/0370a6dc268d6288be8620faa620820843b538e7/lib/index.js#L13-L39
34,594
mozilla/webmaker-core
src/lib/touchhandler.js
timedLog
function timedLog(msg) { console.log(Date.now() + ":" + window.performance.now() + ": " + msg); }
javascript
function timedLog(msg) { console.log(Date.now() + ":" + window.performance.now() + ": " + msg); }
[ "function", "timedLog", "(", "msg", ")", "{", "console", ".", "log", "(", "Date", ".", "now", "(", ")", "+", "\":\"", "+", "window", ".", "performance", ".", "now", "(", ")", "+", "\": \"", "+", "msg", ")", ";", "}" ]
A timed logging function for tracing touch calls during debug
[ "A", "timed", "logging", "function", "for", "tracing", "touch", "calls", "during", "debug" ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/lib/touchhandler.js#L10-L12
34,595
mozilla/webmaker-core
src/lib/touchhandler.js
function(evt) { evt.preventDefault(); evt.stopPropagation(); // Calculate actual height of element so we can calculate bounds properly positionable.rect = positionable.refs.styleWrapper.getBoundingClientRect(); if (debug) { timedLog("startmark"); } if(!evt.touches || evt.touches.length === 1) { if (debug) { timedLog("startmark - continued"); } mark = copy(positionable.state); transform.x1 = evt.clientX || evt.touches[0].pageX; transform.y1 = evt.clientY || evt.touches[0].pageY; positionable.setState({ touchactive: true }); } else { handlers.secondFinger(evt); } var timeStart = new Date(); //For detecting taps tapStart = { x1: evt.touches[0].pageX, y1: evt.touches[0].pageY, timeStart: timeStart }; }
javascript
function(evt) { evt.preventDefault(); evt.stopPropagation(); // Calculate actual height of element so we can calculate bounds properly positionable.rect = positionable.refs.styleWrapper.getBoundingClientRect(); if (debug) { timedLog("startmark"); } if(!evt.touches || evt.touches.length === 1) { if (debug) { timedLog("startmark - continued"); } mark = copy(positionable.state); transform.x1 = evt.clientX || evt.touches[0].pageX; transform.y1 = evt.clientY || evt.touches[0].pageY; positionable.setState({ touchactive: true }); } else { handlers.secondFinger(evt); } var timeStart = new Date(); //For detecting taps tapStart = { x1: evt.touches[0].pageX, y1: evt.touches[0].pageY, timeStart: timeStart }; }
[ "function", "(", "evt", ")", "{", "evt", ".", "preventDefault", "(", ")", ";", "evt", ".", "stopPropagation", "(", ")", ";", "// Calculate actual height of element so we can calculate bounds properly", "positionable", ".", "rect", "=", "positionable", ".", "refs", "...
mark the first touch event so we can perform computation relative to that coordinate.
[ "mark", "the", "first", "touch", "event", "so", "we", "can", "perform", "computation", "relative", "to", "that", "coordinate", "." ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/lib/touchhandler.js#L41-L65
34,596
mozilla/webmaker-core
src/lib/touchhandler.js
function(evt) { if (debug) { timedLog("endmark"); } if(evt.touches && evt.touches.length > 0) { if (handlers.endSecondFinger(evt)) { return; } } if (debug) { timedLog("endmark - continued"); } mark = copy(positionable.state); var modified = transform.modified; transform = resetTransform(); // Only fire a tap if it's under the threshold if (tapDiff < MAX_TAP_THRESHOLD && (new Date() - tapStart.timeStart <= tapDuration) && positionable.onTap) { positionable.setState({touchactive: false}, function() { if(positionable.onTap){ positionable.onTap(); } }); return; } // Reset tapDiff = 0; positionable.setState({ touchactive: false }, function() { if (positionable.onTouchEnd) { positionable.onTouchEnd(modified); } }); }
javascript
function(evt) { if (debug) { timedLog("endmark"); } if(evt.touches && evt.touches.length > 0) { if (handlers.endSecondFinger(evt)) { return; } } if (debug) { timedLog("endmark - continued"); } mark = copy(positionable.state); var modified = transform.modified; transform = resetTransform(); // Only fire a tap if it's under the threshold if (tapDiff < MAX_TAP_THRESHOLD && (new Date() - tapStart.timeStart <= tapDuration) && positionable.onTap) { positionable.setState({touchactive: false}, function() { if(positionable.onTap){ positionable.onTap(); } }); return; } // Reset tapDiff = 0; positionable.setState({ touchactive: false }, function() { if (positionable.onTouchEnd) { positionable.onTouchEnd(modified); } }); }
[ "function", "(", "evt", ")", "{", "if", "(", "debug", ")", "{", "timedLog", "(", "\"endmark\"", ")", ";", "}", "if", "(", "evt", ".", "touches", "&&", "evt", ".", "touches", ".", "length", ">", "0", ")", "{", "if", "(", "handlers", ".", "endSecon...
When all fingers are off the device, stop being in "touch mode"
[ "When", "all", "fingers", "are", "off", "the", "device", "stop", "being", "in", "touch", "mode" ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/lib/touchhandler.js#L106-L134
34,597
mozilla/webmaker-core
src/lib/touchhandler.js
function(evt) { evt.preventDefault(); evt.stopPropagation(); if (debug) { timedLog("secondFinger"); } if (evt.touches.length < 2) { return; } // we need to rebind finger 1, because it may have moved! transform.x1 = evt.touches[0].pageX; transform.y1 = evt.touches[0].pageY; transform.x2 = evt.touches[1].pageX; transform.y2 = evt.touches[1].pageY; var x1 = transform.x1, y1 = transform.y1, x2 = transform.x2, y2 = transform.y2, dx = x2 - x1, dy = y2 - y1, d = Math.sqrt(dx*dx + dy*dy), a = Math.atan2(dy,dx); transform.distance = d; transform.angle = a; }
javascript
function(evt) { evt.preventDefault(); evt.stopPropagation(); if (debug) { timedLog("secondFinger"); } if (evt.touches.length < 2) { return; } // we need to rebind finger 1, because it may have moved! transform.x1 = evt.touches[0].pageX; transform.y1 = evt.touches[0].pageY; transform.x2 = evt.touches[1].pageX; transform.y2 = evt.touches[1].pageY; var x1 = transform.x1, y1 = transform.y1, x2 = transform.x2, y2 = transform.y2, dx = x2 - x1, dy = y2 - y1, d = Math.sqrt(dx*dx + dy*dy), a = Math.atan2(dy,dx); transform.distance = d; transform.angle = a; }
[ "function", "(", "evt", ")", "{", "evt", ".", "preventDefault", "(", ")", ";", "evt", ".", "stopPropagation", "(", ")", ";", "if", "(", "debug", ")", "{", "timedLog", "(", "\"secondFinger\"", ")", ";", "}", "if", "(", "evt", ".", "touches", ".", "l...
A second finger means we need to start tracking another event coordinate, which may lead to rotation and scaling updates for the element we're working for.
[ "A", "second", "finger", "means", "we", "need", "to", "start", "tracking", "another", "event", "coordinate", "which", "may", "lead", "to", "rotation", "and", "scaling", "updates", "for", "the", "element", "we", "re", "working", "for", "." ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/lib/touchhandler.js#L141-L165
34,598
mozilla/webmaker-core
src/lib/touchhandler.js
function(evt) { evt.preventDefault(); evt.stopPropagation(); if (debug) { timedLog("endSecondFinger"); } if (evt.touches.length > 1) { if (debug) { timedLog("endSecondFinger - capped"); } return true; } if (debug) { timedLog("endSecondFinger - continued"); } handlers.startmark(evt); // If there are no fingers left on the screen, // we have not finished the handling return evt.touches.length !== 0; }
javascript
function(evt) { evt.preventDefault(); evt.stopPropagation(); if (debug) { timedLog("endSecondFinger"); } if (evt.touches.length > 1) { if (debug) { timedLog("endSecondFinger - capped"); } return true; } if (debug) { timedLog("endSecondFinger - continued"); } handlers.startmark(evt); // If there are no fingers left on the screen, // we have not finished the handling return evt.touches.length !== 0; }
[ "function", "(", "evt", ")", "{", "evt", ".", "preventDefault", "(", ")", ";", "evt", ".", "stopPropagation", "(", ")", ";", "if", "(", "debug", ")", "{", "timedLog", "(", "\"endSecondFinger\"", ")", ";", "}", "if", "(", "evt", ".", "touches", ".", ...
When the second touch event ends, we might still need to keep processing plain single touch updates.
[ "When", "the", "second", "touch", "event", "ends", "we", "might", "still", "need", "to", "keep", "processing", "plain", "single", "touch", "updates", "." ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/lib/touchhandler.js#L197-L210
34,599
sanity-io/get-it
src/middleware/debug.js
tryFormat
function tryFormat(body) { try { const parsed = typeof body === 'string' ? JSON.parse(body) : body return JSON.stringify(parsed, null, 2) } catch (err) { return body } }
javascript
function tryFormat(body) { try { const parsed = typeof body === 'string' ? JSON.parse(body) : body return JSON.stringify(parsed, null, 2) } catch (err) { return body } }
[ "function", "tryFormat", "(", "body", ")", "{", "try", "{", "const", "parsed", "=", "typeof", "body", "===", "'string'", "?", "JSON", ".", "parse", "(", "body", ")", ":", "body", "return", "JSON", ".", "stringify", "(", "parsed", ",", "null", ",", "2...
Attempt pretty-formatting JSON
[ "Attempt", "pretty", "-", "formatting", "JSON" ]
765ff1e0203e5ad0109e2f959f5c6008b47e8103
https://github.com/sanity-io/get-it/blob/765ff1e0203e5ad0109e2f959f5c6008b47e8103/src/middleware/debug.js#L94-L101