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
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
57,900
sreenaths/em-tgraph
addon/utils/data-processor.js
_normalizeRawData
function _normalizeRawData(data) { var EmObj = Ember.Object, vertices, // Hash of vertices edges, // Hash of edges rootVertices = []; // Vertices without out-edges are considered root vertices vertices = data.vertices.reduce(function (obj, vertex) { vertex = VertexDataNode.create(vertex); if(!vertex.outEdgeIds) { rootVertices.push(vertex); } obj[vertex.vertexName] = vertex; return obj; }, {}); edges = !data.edges ? [] : data.edges.reduce(function (obj, edge) { obj[edge.edgeId] = EmObj.create(edge); return obj; }, {}); if(data.vertexGroups) { data.vertexGroups.forEach(function (group) { group.groupMembers.forEach(function (vertex) { vertices[vertex].vertexGroup = EmObj.create(group); }); }); } return { vertices: EmObj.create(vertices), edges: EmObj.create(edges), rootVertices: rootVertices }; }
javascript
function _normalizeRawData(data) { var EmObj = Ember.Object, vertices, // Hash of vertices edges, // Hash of edges rootVertices = []; // Vertices without out-edges are considered root vertices vertices = data.vertices.reduce(function (obj, vertex) { vertex = VertexDataNode.create(vertex); if(!vertex.outEdgeIds) { rootVertices.push(vertex); } obj[vertex.vertexName] = vertex; return obj; }, {}); edges = !data.edges ? [] : data.edges.reduce(function (obj, edge) { obj[edge.edgeId] = EmObj.create(edge); return obj; }, {}); if(data.vertexGroups) { data.vertexGroups.forEach(function (group) { group.groupMembers.forEach(function (vertex) { vertices[vertex].vertexGroup = EmObj.create(group); }); }); } return { vertices: EmObj.create(vertices), edges: EmObj.create(edges), rootVertices: rootVertices }; }
[ "function", "_normalizeRawData", "(", "data", ")", "{", "var", "EmObj", "=", "Ember", ".", "Object", ",", "vertices", ",", "// Hash of vertices", "edges", ",", "// Hash of edges", "rootVertices", "=", "[", "]", ";", "// Vertices without out-edges are considered root vertices", "vertices", "=", "data", ".", "vertices", ".", "reduce", "(", "function", "(", "obj", ",", "vertex", ")", "{", "vertex", "=", "VertexDataNode", ".", "create", "(", "vertex", ")", ";", "if", "(", "!", "vertex", ".", "outEdgeIds", ")", "{", "rootVertices", ".", "push", "(", "vertex", ")", ";", "}", "obj", "[", "vertex", ".", "vertexName", "]", "=", "vertex", ";", "return", "obj", ";", "}", ",", "{", "}", ")", ";", "edges", "=", "!", "data", ".", "edges", "?", "[", "]", ":", "data", ".", "edges", ".", "reduce", "(", "function", "(", "obj", ",", "edge", ")", "{", "obj", "[", "edge", ".", "edgeId", "]", "=", "EmObj", ".", "create", "(", "edge", ")", ";", "return", "obj", ";", "}", ",", "{", "}", ")", ";", "if", "(", "data", ".", "vertexGroups", ")", "{", "data", ".", "vertexGroups", ".", "forEach", "(", "function", "(", "group", ")", "{", "group", ".", "groupMembers", ".", "forEach", "(", "function", "(", "vertex", ")", "{", "vertices", "[", "vertex", "]", ".", "vertexGroup", "=", "EmObj", ".", "create", "(", "group", ")", ";", "}", ")", ";", "}", ")", ";", "}", "return", "{", "vertices", ":", "EmObj", ".", "create", "(", "vertices", ")", ",", "edges", ":", "EmObj", ".", "create", "(", "edges", ")", ",", "rootVertices", ":", "rootVertices", "}", ";", "}" ]
Converts vertices & edges into hashes for easy access. Makes vertexGroup a property of the respective vertices. @param data {Object} @return {Object} An object with vertices hash, edges hash and array of root vertices.
[ "Converts", "vertices", "&", "edges", "into", "hashes", "for", "easy", "access", ".", "Makes", "vertexGroup", "a", "property", "of", "the", "respective", "vertices", "." ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/data-processor.js#L664-L697
57,901
sreenaths/em-tgraph
addon/utils/data-processor.js
function (data) { var dummy = DataNode.create({ type: types.DUMMY, vertexName: 'dummy', depth: 1 }), root = RootDataNode.create({ dummy: dummy }); if(!data.vertices) { return "Vertices not found!"; } _data = _normalizeRawData(data); if(!_data.rootVertices.length) { return "Sink vertex not found!"; } dummy._setChildren(centericMap(_data.rootVertices, function (vertex) { return _normalizeVertexTree(_treefyData(vertex, 2)); })); _addOutputs(root); _cacheChildren(root); return _getGraphDetails(root); }
javascript
function (data) { var dummy = DataNode.create({ type: types.DUMMY, vertexName: 'dummy', depth: 1 }), root = RootDataNode.create({ dummy: dummy }); if(!data.vertices) { return "Vertices not found!"; } _data = _normalizeRawData(data); if(!_data.rootVertices.length) { return "Sink vertex not found!"; } dummy._setChildren(centericMap(_data.rootVertices, function (vertex) { return _normalizeVertexTree(_treefyData(vertex, 2)); })); _addOutputs(root); _cacheChildren(root); return _getGraphDetails(root); }
[ "function", "(", "data", ")", "{", "var", "dummy", "=", "DataNode", ".", "create", "(", "{", "type", ":", "types", ".", "DUMMY", ",", "vertexName", ":", "'dummy'", ",", "depth", ":", "1", "}", ")", ",", "root", "=", "RootDataNode", ".", "create", "(", "{", "dummy", ":", "dummy", "}", ")", ";", "if", "(", "!", "data", ".", "vertices", ")", "{", "return", "\"Vertices not found!\"", ";", "}", "_data", "=", "_normalizeRawData", "(", "data", ")", ";", "if", "(", "!", "_data", ".", "rootVertices", ".", "length", ")", "{", "return", "\"Sink vertex not found!\"", ";", "}", "dummy", ".", "_setChildren", "(", "centericMap", "(", "_data", ".", "rootVertices", ",", "function", "(", "vertex", ")", "{", "return", "_normalizeVertexTree", "(", "_treefyData", "(", "vertex", ",", "2", ")", ")", ";", "}", ")", ")", ";", "_addOutputs", "(", "root", ")", ";", "_cacheChildren", "(", "root", ")", ";", "return", "_getGraphDetails", "(", "root", ")", ";", "}" ]
Converts raw DAG-plan into an internal data representation that graph-view, and in turn d3.layout.tree can digest. @param data {Object} Dag-plan data @return {Object/String} - Object with values tree, links, maxDepth & maxHeight - Error message if the data was not as expected.
[ "Converts", "raw", "DAG", "-", "plan", "into", "an", "internal", "data", "representation", "that", "graph", "-", "view", "and", "in", "turn", "d3", ".", "layout", ".", "tree", "can", "digest", "." ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/data-processor.js#L711-L740
57,902
arpadHegedus/postcss-plugin-utilities
inc/sass-get-var.js
gather
function gather (variable, node) { if (node.parent) { let values = [] for (let n of Object.values(node.parent.nodes)) { if (n.type === 'decl' && n.prop === `$${variable}`) { values.push(n.value) } } values.reverse() let parentValues = node.parent.parent ? gather(variable, node.parent) : null if (parentValues) { values = values.concat(parentValues) } return values } return null }
javascript
function gather (variable, node) { if (node.parent) { let values = [] for (let n of Object.values(node.parent.nodes)) { if (n.type === 'decl' && n.prop === `$${variable}`) { values.push(n.value) } } values.reverse() let parentValues = node.parent.parent ? gather(variable, node.parent) : null if (parentValues) { values = values.concat(parentValues) } return values } return null }
[ "function", "gather", "(", "variable", ",", "node", ")", "{", "if", "(", "node", ".", "parent", ")", "{", "let", "values", "=", "[", "]", "for", "(", "let", "n", "of", "Object", ".", "values", "(", "node", ".", "parent", ".", "nodes", ")", ")", "{", "if", "(", "n", ".", "type", "===", "'decl'", "&&", "n", ".", "prop", "===", "`", "${", "variable", "}", "`", ")", "{", "values", ".", "push", "(", "n", ".", "value", ")", "}", "}", "values", ".", "reverse", "(", ")", "let", "parentValues", "=", "node", ".", "parent", ".", "parent", "?", "gather", "(", "variable", ",", "node", ".", "parent", ")", ":", "null", "if", "(", "parentValues", ")", "{", "values", "=", "values", ".", "concat", "(", "parentValues", ")", "}", "return", "values", "}", "return", "null", "}" ]
get the value of a sass variable @param {string} variable @param {object} node
[ "get", "the", "value", "of", "a", "sass", "variable" ]
1edbeb95e30d2965ffb6c3907e8b87f887c58018
https://github.com/arpadHegedus/postcss-plugin-utilities/blob/1edbeb95e30d2965ffb6c3907e8b87f887c58018/inc/sass-get-var.js#L7-L23
57,903
digiaonline/generator-nord-backbone
app/templates/core/app.js
function (selector, args, cb) { selector = selector || document; args = args || {}; var self = this; $(selector).find('*[data-view]').each(function () { var viewArgs = _.extend({}, args); viewArgs.el = this; self.getComponent('viewManager').createView($(this).data('view'), viewArgs) .then(cb); }); }
javascript
function (selector, args, cb) { selector = selector || document; args = args || {}; var self = this; $(selector).find('*[data-view]').each(function () { var viewArgs = _.extend({}, args); viewArgs.el = this; self.getComponent('viewManager').createView($(this).data('view'), viewArgs) .then(cb); }); }
[ "function", "(", "selector", ",", "args", ",", "cb", ")", "{", "selector", "=", "selector", "||", "document", ";", "args", "=", "args", "||", "{", "}", ";", "var", "self", "=", "this", ";", "$", "(", "selector", ")", ".", "find", "(", "'*[data-view]'", ")", ".", "each", "(", "function", "(", ")", "{", "var", "viewArgs", "=", "_", ".", "extend", "(", "{", "}", ",", "args", ")", ";", "viewArgs", ".", "el", "=", "this", ";", "self", ".", "getComponent", "(", "'viewManager'", ")", ".", "createView", "(", "$", "(", "this", ")", ".", "data", "(", "'view'", ")", ",", "viewArgs", ")", ".", "then", "(", "cb", ")", ";", "}", ")", ";", "}" ]
Initializes views within a specific DOM element. @param {string} selector element CSS selector @param {Object<string, *>} args view options @param {Function} cb optional callback function to call when the view is loaded.
[ "Initializes", "views", "within", "a", "specific", "DOM", "element", "." ]
bc962e16b6354c7a4034ce09cf4030b9d300202e
https://github.com/digiaonline/generator-nord-backbone/blob/bc962e16b6354c7a4034ce09cf4030b9d300202e/app/templates/core/app.js#L53-L65
57,904
AndiDittrich/Node.async-magic
lib/promisify-all.js
promisifyAll
function promisifyAll(sourceObject, keys){ // promisified output const promisifiedFunctions = {}; // process each object key for (const name of keys){ // function exist in source object ? if (name in sourceObject && typeof sourceObject[name] === 'function'){ // create promisified named version promisifiedFunctions[name] = _promisify(sourceObject[name], name); } } return promisifiedFunctions; }
javascript
function promisifyAll(sourceObject, keys){ // promisified output const promisifiedFunctions = {}; // process each object key for (const name of keys){ // function exist in source object ? if (name in sourceObject && typeof sourceObject[name] === 'function'){ // create promisified named version promisifiedFunctions[name] = _promisify(sourceObject[name], name); } } return promisifiedFunctions; }
[ "function", "promisifyAll", "(", "sourceObject", ",", "keys", ")", "{", "// promisified output", "const", "promisifiedFunctions", "=", "{", "}", ";", "// process each object key", "for", "(", "const", "name", "of", "keys", ")", "{", "// function exist in source object ?", "if", "(", "name", "in", "sourceObject", "&&", "typeof", "sourceObject", "[", "name", "]", "===", "'function'", ")", "{", "// create promisified named version", "promisifiedFunctions", "[", "name", "]", "=", "_promisify", "(", "sourceObject", "[", "name", "]", ",", "name", ")", ";", "}", "}", "return", "promisifiedFunctions", ";", "}" ]
apply promisify function to all elements of sourceObject included in key list
[ "apply", "promisify", "function", "to", "all", "elements", "of", "sourceObject", "included", "in", "key", "list" ]
0c41dd27d8f7539bb24034bc23ce870f5f8a10b3
https://github.com/AndiDittrich/Node.async-magic/blob/0c41dd27d8f7539bb24034bc23ce870f5f8a10b3/lib/promisify-all.js#L4-L18
57,905
dpjanes/iotdb-helpers
lib/q.js
function (name, paramd) { var self = this; paramd = (paramd !== undefined) ? paramd : {}; self.name = (name !== undefined) ? name : "unnamed-queue"; self.qitems = []; self.qurrents = []; self.qn = (paramd.qn !== undefined) ? paramd.qn : 1; self.qid = 0; self.paused = false; }
javascript
function (name, paramd) { var self = this; paramd = (paramd !== undefined) ? paramd : {}; self.name = (name !== undefined) ? name : "unnamed-queue"; self.qitems = []; self.qurrents = []; self.qn = (paramd.qn !== undefined) ? paramd.qn : 1; self.qid = 0; self.paused = false; }
[ "function", "(", "name", ",", "paramd", ")", "{", "var", "self", "=", "this", ";", "paramd", "=", "(", "paramd", "!==", "undefined", ")", "?", "paramd", ":", "{", "}", ";", "self", ".", "name", "=", "(", "name", "!==", "undefined", ")", "?", "name", ":", "\"unnamed-queue\"", ";", "self", ".", "qitems", "=", "[", "]", ";", "self", ".", "qurrents", "=", "[", "]", ";", "self", ".", "qn", "=", "(", "paramd", ".", "qn", "!==", "undefined", ")", "?", "paramd", ".", "qn", ":", "1", ";", "self", ".", "qid", "=", "0", ";", "self", ".", "paused", "=", "false", ";", "}" ]
Make a FIFOQueue called 'name'. @param {string} name A human friendly name for this queue, occassionally printed out @param {dictionary} paramd @param {integer} paramd.qn How many items this queue can be executing at once. Defaults to 1. @classdesc FIFO Queue stuff. This is useful e.g. in {@link Driver Drivers} when you don't want to be pounding on a device's URL with multiple requests at the same time. <hr /> @constructor
[ "Make", "a", "FIFOQueue", "called", "name", "." ]
c31ecb2302b9c6a4f41ef3f0b835d483b1d53c0e
https://github.com/dpjanes/iotdb-helpers/blob/c31ecb2302b9c6a4f41ef3f0b835d483b1d53c0e/lib/q.js#L51-L62
57,906
twolfson/finder
finder.js
startSearch
function startSearch() { iface.question('Enter search: ', function (query) { // Get the results of our query var matches = fileFinder.query(query), len = matches.length; // If no results were found if (len === 0) { console.log('No results found for: ' + query); startSearch(); } else if (len === 1) { var item = matches[0]; // If there is one, skip to go console.log('Opening: ' + item); fileFinder.open(item); // Begin the search again startSearch(); } else { // Otherwise, list options console.log(''); console.log('----------------'); console.log('Search Results'); console.log('----------------'); for (i = 0; i < len; i++) { console.log(i + ': ' + matches[i]); } // Ask for a number iface.question('Which item would you like to open? ', function (numStr) { var num = +numStr, item; // If the number is not NaN and we were not given an empty string if (num === num && numStr !== '') { // and if it is in our result set if (num >= 0 && num < len) { // Open it item = matches[num]; console.log('Opening: ' + item); fileFinder.open(item); } } else { // Otherwise, if there was a word in there so we are assuming it was 'rescan' // Rescan console.log('Rescanning...'); fileFinder.scan(); } // Begin the search again startSearch(); }); } }); }
javascript
function startSearch() { iface.question('Enter search: ', function (query) { // Get the results of our query var matches = fileFinder.query(query), len = matches.length; // If no results were found if (len === 0) { console.log('No results found for: ' + query); startSearch(); } else if (len === 1) { var item = matches[0]; // If there is one, skip to go console.log('Opening: ' + item); fileFinder.open(item); // Begin the search again startSearch(); } else { // Otherwise, list options console.log(''); console.log('----------------'); console.log('Search Results'); console.log('----------------'); for (i = 0; i < len; i++) { console.log(i + ': ' + matches[i]); } // Ask for a number iface.question('Which item would you like to open? ', function (numStr) { var num = +numStr, item; // If the number is not NaN and we were not given an empty string if (num === num && numStr !== '') { // and if it is in our result set if (num >= 0 && num < len) { // Open it item = matches[num]; console.log('Opening: ' + item); fileFinder.open(item); } } else { // Otherwise, if there was a word in there so we are assuming it was 'rescan' // Rescan console.log('Rescanning...'); fileFinder.scan(); } // Begin the search again startSearch(); }); } }); }
[ "function", "startSearch", "(", ")", "{", "iface", ".", "question", "(", "'Enter search: '", ",", "function", "(", "query", ")", "{", "// Get the results of our query\r", "var", "matches", "=", "fileFinder", ".", "query", "(", "query", ")", ",", "len", "=", "matches", ".", "length", ";", "// If no results were found\r", "if", "(", "len", "===", "0", ")", "{", "console", ".", "log", "(", "'No results found for: '", "+", "query", ")", ";", "startSearch", "(", ")", ";", "}", "else", "if", "(", "len", "===", "1", ")", "{", "var", "item", "=", "matches", "[", "0", "]", ";", "// If there is one, skip to go\r", "console", ".", "log", "(", "'Opening: '", "+", "item", ")", ";", "fileFinder", ".", "open", "(", "item", ")", ";", "// Begin the search again\r", "startSearch", "(", ")", ";", "}", "else", "{", "// Otherwise, list options\r", "console", ".", "log", "(", "''", ")", ";", "console", ".", "log", "(", "'----------------'", ")", ";", "console", ".", "log", "(", "'Search Results'", ")", ";", "console", ".", "log", "(", "'----------------'", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "console", ".", "log", "(", "i", "+", "': '", "+", "matches", "[", "i", "]", ")", ";", "}", "// Ask for a number\r", "iface", ".", "question", "(", "'Which item would you like to open? '", ",", "function", "(", "numStr", ")", "{", "var", "num", "=", "+", "numStr", ",", "item", ";", "// If the number is not NaN and we were not given an empty string\r", "if", "(", "num", "===", "num", "&&", "numStr", "!==", "''", ")", "{", "// and if it is in our result set\r", "if", "(", "num", ">=", "0", "&&", "num", "<", "len", ")", "{", "// Open it\r", "item", "=", "matches", "[", "num", "]", ";", "console", ".", "log", "(", "'Opening: '", "+", "item", ")", ";", "fileFinder", ".", "open", "(", "item", ")", ";", "}", "}", "else", "{", "// Otherwise, if there was a word in there so we are assuming it was 'rescan'\r", "// Rescan\r", "console", ".", "log", "(", "'Rescanning...'", ")", ";", "fileFinder", ".", "scan", "(", ")", ";", "}", "// Begin the search again\r", "startSearch", "(", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
Set up startSearch for calling later
[ "Set", "up", "startSearch", "for", "calling", "later" ]
e365823cc35f1aaefaf7c1a75fbfea18234fa379
https://github.com/twolfson/finder/blob/e365823cc35f1aaefaf7c1a75fbfea18234fa379/finder.js#L128-L182
57,907
Ma3Route/node-sdk
example/utils.js
getAuth
function getAuth() { if (!auth.key || auth.key.indexOf("goes-here") !== -1) { var err = new Error("API key missing"); out.error(err.message); throw err; } if (!auth.secret || auth.secret.indexOf("goes-here") !== -1) { var err = new Error("API secret missing"); out.error(err.message); throw err; } return auth; }
javascript
function getAuth() { if (!auth.key || auth.key.indexOf("goes-here") !== -1) { var err = new Error("API key missing"); out.error(err.message); throw err; } if (!auth.secret || auth.secret.indexOf("goes-here") !== -1) { var err = new Error("API secret missing"); out.error(err.message); throw err; } return auth; }
[ "function", "getAuth", "(", ")", "{", "if", "(", "!", "auth", ".", "key", "||", "auth", ".", "key", ".", "indexOf", "(", "\"goes-here\"", ")", "!==", "-", "1", ")", "{", "var", "err", "=", "new", "Error", "(", "\"API key missing\"", ")", ";", "out", ".", "error", "(", "err", ".", "message", ")", ";", "throw", "err", ";", "}", "if", "(", "!", "auth", ".", "secret", "||", "auth", ".", "secret", ".", "indexOf", "(", "\"goes-here\"", ")", "!==", "-", "1", ")", "{", "var", "err", "=", "new", "Error", "(", "\"API secret missing\"", ")", ";", "out", ".", "error", "(", "err", ".", "message", ")", ";", "throw", "err", ";", "}", "return", "auth", ";", "}" ]
Return the authentication parameters, if available. Otherwise, log to stderr and throw an error indicating missing authentication parameters. @return {Object} auth
[ "Return", "the", "authentication", "parameters", "if", "available", ".", "Otherwise", "log", "to", "stderr", "and", "throw", "an", "error", "indicating", "missing", "authentication", "parameters", "." ]
a2769d97d77d6f762d23e743bf4c749e2bad0d8a
https://github.com/Ma3Route/node-sdk/blob/a2769d97d77d6f762d23e743bf4c749e2bad0d8a/example/utils.js#L25-L37
57,908
allanmboyd/docit
lib/parser.js
sortComments
function sortComments(comments) { var moduleComments = []; var typeComments = []; var varComments = []; var methodComments = []; var typelessComments = []; comments.forEach(function (comment) { if(comment.type) { switch(comment.type) { case exports.COMMENT_TYPES.MODULE: moduleComments.push(comment); break; case exports.COMMENT_TYPES.METHOD: methodComments.push(comment); break; case exports.COMMENT_TYPES.TYPE: typeComments.push(comment); break; case exports.COMMENT_TYPES.VARIABLE: varComments.push(comment); break; } } else { typelessComments.push(comment); } }); return moduleComments.concat(typeComments.concat(varComments.concat(methodComments.concat(typelessComments)))); }
javascript
function sortComments(comments) { var moduleComments = []; var typeComments = []; var varComments = []; var methodComments = []; var typelessComments = []; comments.forEach(function (comment) { if(comment.type) { switch(comment.type) { case exports.COMMENT_TYPES.MODULE: moduleComments.push(comment); break; case exports.COMMENT_TYPES.METHOD: methodComments.push(comment); break; case exports.COMMENT_TYPES.TYPE: typeComments.push(comment); break; case exports.COMMENT_TYPES.VARIABLE: varComments.push(comment); break; } } else { typelessComments.push(comment); } }); return moduleComments.concat(typeComments.concat(varComments.concat(methodComments.concat(typelessComments)))); }
[ "function", "sortComments", "(", "comments", ")", "{", "var", "moduleComments", "=", "[", "]", ";", "var", "typeComments", "=", "[", "]", ";", "var", "varComments", "=", "[", "]", ";", "var", "methodComments", "=", "[", "]", ";", "var", "typelessComments", "=", "[", "]", ";", "comments", ".", "forEach", "(", "function", "(", "comment", ")", "{", "if", "(", "comment", ".", "type", ")", "{", "switch", "(", "comment", ".", "type", ")", "{", "case", "exports", ".", "COMMENT_TYPES", ".", "MODULE", ":", "moduleComments", ".", "push", "(", "comment", ")", ";", "break", ";", "case", "exports", ".", "COMMENT_TYPES", ".", "METHOD", ":", "methodComments", ".", "push", "(", "comment", ")", ";", "break", ";", "case", "exports", ".", "COMMENT_TYPES", ".", "TYPE", ":", "typeComments", ".", "push", "(", "comment", ")", ";", "break", ";", "case", "exports", ".", "COMMENT_TYPES", ".", "VARIABLE", ":", "varComments", ".", "push", "(", "comment", ")", ";", "break", ";", "}", "}", "else", "{", "typelessComments", ".", "push", "(", "comment", ")", ";", "}", "}", ")", ";", "return", "moduleComments", ".", "concat", "(", "typeComments", ".", "concat", "(", "varComments", ".", "concat", "(", "methodComments", ".", "concat", "(", "typelessComments", ")", ")", ")", ")", ";", "}" ]
Sort mapped reduced comments. Module comments first followed by class, variables and methods. @param {Comment[]} comments an array of mapped-reduced comments @return {Comment[]} sorted comments array @private
[ "Sort", "mapped", "reduced", "comments", ".", "Module", "comments", "first", "followed", "by", "class", "variables", "and", "methods", "." ]
e972b6e3a9792f649e9fed9115b45cb010c90c8f
https://github.com/allanmboyd/docit/blob/e972b6e3a9792f649e9fed9115b45cb010c90c8f/lib/parser.js#L303-L332
57,909
allanmboyd/docit
lib/parser.js
identifyCommentType
function identifyCommentType(tag) { var commentType = null; for (var tagName in tag) { if (tag.hasOwnProperty(tagName)) { switch (tagName) { case exports.TAG_NAMES.API: case exports.TAG_NAMES.METHOD: case exports.TAG_NAMES.METHOD_SIGNATURE: case exports.TAG_NAMES.METHOD_NAME: case exports.TAG_NAMES.PARAM: case exports.TAG_NAMES.RETURN: case exports.TAG_NAMES.THROWS: commentType = exports.COMMENT_TYPES.METHOD; break; case exports.TAG_NAMES.MODULE: case exports.TAG_NAMES.REQUIRES: commentType = exports.COMMENT_TYPES.MODULE; break; case exports.TAG_NAMES.CLASS: commentType = exports.COMMENT_TYPES.TYPE; break; case exports.TAG_NAMES.VARIABLE_NAME: commentType = exports.COMMENT_TYPES.VARIABLE; break; } } } return commentType; }
javascript
function identifyCommentType(tag) { var commentType = null; for (var tagName in tag) { if (tag.hasOwnProperty(tagName)) { switch (tagName) { case exports.TAG_NAMES.API: case exports.TAG_NAMES.METHOD: case exports.TAG_NAMES.METHOD_SIGNATURE: case exports.TAG_NAMES.METHOD_NAME: case exports.TAG_NAMES.PARAM: case exports.TAG_NAMES.RETURN: case exports.TAG_NAMES.THROWS: commentType = exports.COMMENT_TYPES.METHOD; break; case exports.TAG_NAMES.MODULE: case exports.TAG_NAMES.REQUIRES: commentType = exports.COMMENT_TYPES.MODULE; break; case exports.TAG_NAMES.CLASS: commentType = exports.COMMENT_TYPES.TYPE; break; case exports.TAG_NAMES.VARIABLE_NAME: commentType = exports.COMMENT_TYPES.VARIABLE; break; } } } return commentType; }
[ "function", "identifyCommentType", "(", "tag", ")", "{", "var", "commentType", "=", "null", ";", "for", "(", "var", "tagName", "in", "tag", ")", "{", "if", "(", "tag", ".", "hasOwnProperty", "(", "tagName", ")", ")", "{", "switch", "(", "tagName", ")", "{", "case", "exports", ".", "TAG_NAMES", ".", "API", ":", "case", "exports", ".", "TAG_NAMES", ".", "METHOD", ":", "case", "exports", ".", "TAG_NAMES", ".", "METHOD_SIGNATURE", ":", "case", "exports", ".", "TAG_NAMES", ".", "METHOD_NAME", ":", "case", "exports", ".", "TAG_NAMES", ".", "PARAM", ":", "case", "exports", ".", "TAG_NAMES", ".", "RETURN", ":", "case", "exports", ".", "TAG_NAMES", ".", "THROWS", ":", "commentType", "=", "exports", ".", "COMMENT_TYPES", ".", "METHOD", ";", "break", ";", "case", "exports", ".", "TAG_NAMES", ".", "MODULE", ":", "case", "exports", ".", "TAG_NAMES", ".", "REQUIRES", ":", "commentType", "=", "exports", ".", "COMMENT_TYPES", ".", "MODULE", ";", "break", ";", "case", "exports", ".", "TAG_NAMES", ".", "CLASS", ":", "commentType", "=", "exports", ".", "COMMENT_TYPES", ".", "TYPE", ";", "break", ";", "case", "exports", ".", "TAG_NAMES", ".", "VARIABLE_NAME", ":", "commentType", "=", "exports", ".", "COMMENT_TYPES", ".", "VARIABLE", ";", "break", ";", "}", "}", "}", "return", "commentType", ";", "}" ]
Try to identify the type of a comment from a comment tag. @param tag a tag @return {String} the type of the comment or null if not identified @private
[ "Try", "to", "identify", "the", "type", "of", "a", "comment", "from", "a", "comment", "tag", "." ]
e972b6e3a9792f649e9fed9115b45cb010c90c8f
https://github.com/allanmboyd/docit/blob/e972b6e3a9792f649e9fed9115b45cb010c90c8f/lib/parser.js#L339-L368
57,910
jkroso/balance-svg-paths
index.js
balance
function balance(a, b){ var diff = a.length - b.length var short = diff >= 0 ? b : a diff = Math.abs(diff) while (diff--) short.push(['c',0,0,0,0,0,0]) return [a, b] }
javascript
function balance(a, b){ var diff = a.length - b.length var short = diff >= 0 ? b : a diff = Math.abs(diff) while (diff--) short.push(['c',0,0,0,0,0,0]) return [a, b] }
[ "function", "balance", "(", "a", ",", "b", ")", "{", "var", "diff", "=", "a", ".", "length", "-", "b", ".", "length", "var", "short", "=", "diff", ">=", "0", "?", "b", ":", "a", "diff", "=", "Math", ".", "abs", "(", "diff", ")", "while", "(", "diff", "--", ")", "short", ".", "push", "(", "[", "'c'", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", "]", ")", "return", "[", "a", ",", "b", "]", "}" ]
define `a` and `b` using the same number of path segments while preserving their shape @param {Array} a @param {Array} b @return {Array}
[ "define", "a", "and", "b", "using", "the", "same", "number", "of", "path", "segments", "while", "preserving", "their", "shape" ]
3985c03857ef3e7811ab3a0a25fffba96cd3f2aa
https://github.com/jkroso/balance-svg-paths/blob/3985c03857ef3e7811ab3a0a25fffba96cd3f2aa/index.js#L13-L19
57,911
tlid/tlid
src/vscode/tlid-vscode/extension.js
activate
function activate(context) { // Use the console to output diagnostic information (console.log) and errors (console.error) // This line of code will only be executed once when your extension is activated console.log('Congratulations, your extension "Tlid" is now active!'); // // The command has been defined in the package.json file // // Now provide the implementation of the command with registerCommand // // The commandId parameter must match the command field in package.json // let disposable = vscode.commands.registerCommand('extension.sayHello', function () { // // The code you place here will be executed every time your command is executed // // Display a message box to the user // vscode.window.showInformationMessage('Hello World!'); // }); let disposableTlidGet = vscode.commands.registerCommand('extension.TlidGet', function () { // The code you place here will be executed every time your command is executed vscode.window.showInformationMessage("Creating Tlid..."); var tlidValue = tlid.get(); clipboardy.writeSync(tlidValue); // Display a message box to the user vscode.window.showInformationMessage(tlidValue); }); let disposableTlidLineToJSON = vscode.commands.registerCommand('extension.TlidLineToJSON', function () { // The code you place here will be executed every time your command is executed // vscode.window.showInformationMessage("Transforming Tlid line..."); var tlidLine = clipboardy.readSync(); var tlidValue = tlid.get(); var r = gixdeco.geto(tlidLine); try { if (r['tlid'] == null) r['tlid'] = tlidValue; //setting it up } catch (error) { } // if (r.tlid == null || r.tlid == "-1") var out = JSON.stringify(r); clipboardy.writeSync(out); // Display a message box to the user vscode.window.showInformationMessage(out); // vscode.window.showInformationMessage(tlidLine); }); let disposableTlidGetJSON = vscode.commands.registerCommand('extension.TlidGetJSON', function () { // The code you place here will be executed every time your command is executed vscode.window.showInformationMessage("Creating JSON Tlid..."); var tlidValue = tlid.json(); clipboardy.writeSync(tlidValue); // Display a message box to the user vscode.window.showInformationMessage(tlidValue); }); let disposableTlidugGet = vscode.commands.registerCommand('extension.TlidugGet', function () { // The code you place here will be executed every time your command is executed vscode.window.showInformationMessage("Creating Tlidug..."); var tlidugValue = tlidug.get(); clipboardy.writeSync(tlidugValue); // Display a message box to the user vscode.window.showInformationMessage(tlidugValue); }); let disposableIdugGet = vscode.commands.registerCommand('extension.IdugGet', function () { // The code you place here will be executed every time your command is executed vscode.window.showInformationMessage("Creating Idug..."); var idugValue = idug.get(); clipboardy.writeSync(idugValue); // Display a message box to the user vscode.window.showInformationMessage(idugValue); }); let disposableUnIdugGet = vscode.commands.registerCommand('extension.UnIdugGet', function () { // The code you place here will be executed every time your command is executed vscode.window.showInformationMessage("Creating UnDashed Idug..."); var idugValue = idug.un(); clipboardy.writeSync(idugValue); // Display a message box to the user vscode.window.showInformationMessage(idugValue); }); context.subscriptions.push(disposableTlidLineToJSON); context.subscriptions.push(disposableUnIdugGet); context.subscriptions.push(disposableIdugGet); context.subscriptions.push(disposableTlidGet); context.subscriptions.push(disposableTlidGetJSON); context.subscriptions.push(disposableTlidugGet); }
javascript
function activate(context) { // Use the console to output diagnostic information (console.log) and errors (console.error) // This line of code will only be executed once when your extension is activated console.log('Congratulations, your extension "Tlid" is now active!'); // // The command has been defined in the package.json file // // Now provide the implementation of the command with registerCommand // // The commandId parameter must match the command field in package.json // let disposable = vscode.commands.registerCommand('extension.sayHello', function () { // // The code you place here will be executed every time your command is executed // // Display a message box to the user // vscode.window.showInformationMessage('Hello World!'); // }); let disposableTlidGet = vscode.commands.registerCommand('extension.TlidGet', function () { // The code you place here will be executed every time your command is executed vscode.window.showInformationMessage("Creating Tlid..."); var tlidValue = tlid.get(); clipboardy.writeSync(tlidValue); // Display a message box to the user vscode.window.showInformationMessage(tlidValue); }); let disposableTlidLineToJSON = vscode.commands.registerCommand('extension.TlidLineToJSON', function () { // The code you place here will be executed every time your command is executed // vscode.window.showInformationMessage("Transforming Tlid line..."); var tlidLine = clipboardy.readSync(); var tlidValue = tlid.get(); var r = gixdeco.geto(tlidLine); try { if (r['tlid'] == null) r['tlid'] = tlidValue; //setting it up } catch (error) { } // if (r.tlid == null || r.tlid == "-1") var out = JSON.stringify(r); clipboardy.writeSync(out); // Display a message box to the user vscode.window.showInformationMessage(out); // vscode.window.showInformationMessage(tlidLine); }); let disposableTlidGetJSON = vscode.commands.registerCommand('extension.TlidGetJSON', function () { // The code you place here will be executed every time your command is executed vscode.window.showInformationMessage("Creating JSON Tlid..."); var tlidValue = tlid.json(); clipboardy.writeSync(tlidValue); // Display a message box to the user vscode.window.showInformationMessage(tlidValue); }); let disposableTlidugGet = vscode.commands.registerCommand('extension.TlidugGet', function () { // The code you place here will be executed every time your command is executed vscode.window.showInformationMessage("Creating Tlidug..."); var tlidugValue = tlidug.get(); clipboardy.writeSync(tlidugValue); // Display a message box to the user vscode.window.showInformationMessage(tlidugValue); }); let disposableIdugGet = vscode.commands.registerCommand('extension.IdugGet', function () { // The code you place here will be executed every time your command is executed vscode.window.showInformationMessage("Creating Idug..."); var idugValue = idug.get(); clipboardy.writeSync(idugValue); // Display a message box to the user vscode.window.showInformationMessage(idugValue); }); let disposableUnIdugGet = vscode.commands.registerCommand('extension.UnIdugGet', function () { // The code you place here will be executed every time your command is executed vscode.window.showInformationMessage("Creating UnDashed Idug..."); var idugValue = idug.un(); clipboardy.writeSync(idugValue); // Display a message box to the user vscode.window.showInformationMessage(idugValue); }); context.subscriptions.push(disposableTlidLineToJSON); context.subscriptions.push(disposableUnIdugGet); context.subscriptions.push(disposableIdugGet); context.subscriptions.push(disposableTlidGet); context.subscriptions.push(disposableTlidGetJSON); context.subscriptions.push(disposableTlidugGet); }
[ "function", "activate", "(", "context", ")", "{", "// Use the console to output diagnostic information (console.log) and errors (console.error)", "// This line of code will only be executed once when your extension is activated", "console", ".", "log", "(", "'Congratulations, your extension \"Tlid\" is now active!'", ")", ";", "// // The command has been defined in the package.json file", "// // Now provide the implementation of the command with registerCommand", "// // The commandId parameter must match the command field in package.json", "// let disposable = vscode.commands.registerCommand('extension.sayHello', function () {", "// // The code you place here will be executed every time your command is executed", "// // Display a message box to the user", "// vscode.window.showInformationMessage('Hello World!');", "// });", "let", "disposableTlidGet", "=", "vscode", ".", "commands", ".", "registerCommand", "(", "'extension.TlidGet'", ",", "function", "(", ")", "{", "// The code you place here will be executed every time your command is executed", "vscode", ".", "window", ".", "showInformationMessage", "(", "\"Creating Tlid...\"", ")", ";", "var", "tlidValue", "=", "tlid", ".", "get", "(", ")", ";", "clipboardy", ".", "writeSync", "(", "tlidValue", ")", ";", "// Display a message box to the user", "vscode", ".", "window", ".", "showInformationMessage", "(", "tlidValue", ")", ";", "}", ")", ";", "let", "disposableTlidLineToJSON", "=", "vscode", ".", "commands", ".", "registerCommand", "(", "'extension.TlidLineToJSON'", ",", "function", "(", ")", "{", "// The code you place here will be executed every time your command is executed", "// vscode.window.showInformationMessage(\"Transforming Tlid line...\");", "var", "tlidLine", "=", "clipboardy", ".", "readSync", "(", ")", ";", "var", "tlidValue", "=", "tlid", ".", "get", "(", ")", ";", "var", "r", "=", "gixdeco", ".", "geto", "(", "tlidLine", ")", ";", "try", "{", "if", "(", "r", "[", "'tlid'", "]", "==", "null", ")", "r", "[", "'tlid'", "]", "=", "tlidValue", ";", "//setting it up", "}", "catch", "(", "error", ")", "{", "}", "// if (r.tlid == null || r.tlid == \"-1\")", "var", "out", "=", "JSON", ".", "stringify", "(", "r", ")", ";", "clipboardy", ".", "writeSync", "(", "out", ")", ";", "// Display a message box to the user", "vscode", ".", "window", ".", "showInformationMessage", "(", "out", ")", ";", "// vscode.window.showInformationMessage(tlidLine);", "}", ")", ";", "let", "disposableTlidGetJSON", "=", "vscode", ".", "commands", ".", "registerCommand", "(", "'extension.TlidGetJSON'", ",", "function", "(", ")", "{", "// The code you place here will be executed every time your command is executed", "vscode", ".", "window", ".", "showInformationMessage", "(", "\"Creating JSON Tlid...\"", ")", ";", "var", "tlidValue", "=", "tlid", ".", "json", "(", ")", ";", "clipboardy", ".", "writeSync", "(", "tlidValue", ")", ";", "// Display a message box to the user", "vscode", ".", "window", ".", "showInformationMessage", "(", "tlidValue", ")", ";", "}", ")", ";", "let", "disposableTlidugGet", "=", "vscode", ".", "commands", ".", "registerCommand", "(", "'extension.TlidugGet'", ",", "function", "(", ")", "{", "// The code you place here will be executed every time your command is executed", "vscode", ".", "window", ".", "showInformationMessage", "(", "\"Creating Tlidug...\"", ")", ";", "var", "tlidugValue", "=", "tlidug", ".", "get", "(", ")", ";", "clipboardy", ".", "writeSync", "(", "tlidugValue", ")", ";", "// Display a message box to the user", "vscode", ".", "window", ".", "showInformationMessage", "(", "tlidugValue", ")", ";", "}", ")", ";", "let", "disposableIdugGet", "=", "vscode", ".", "commands", ".", "registerCommand", "(", "'extension.IdugGet'", ",", "function", "(", ")", "{", "// The code you place here will be executed every time your command is executed", "vscode", ".", "window", ".", "showInformationMessage", "(", "\"Creating Idug...\"", ")", ";", "var", "idugValue", "=", "idug", ".", "get", "(", ")", ";", "clipboardy", ".", "writeSync", "(", "idugValue", ")", ";", "// Display a message box to the user", "vscode", ".", "window", ".", "showInformationMessage", "(", "idugValue", ")", ";", "}", ")", ";", "let", "disposableUnIdugGet", "=", "vscode", ".", "commands", ".", "registerCommand", "(", "'extension.UnIdugGet'", ",", "function", "(", ")", "{", "// The code you place here will be executed every time your command is executed", "vscode", ".", "window", ".", "showInformationMessage", "(", "\"Creating UnDashed Idug...\"", ")", ";", "var", "idugValue", "=", "idug", ".", "un", "(", ")", ";", "clipboardy", ".", "writeSync", "(", "idugValue", ")", ";", "// Display a message box to the user", "vscode", ".", "window", ".", "showInformationMessage", "(", "idugValue", ")", ";", "}", ")", ";", "context", ".", "subscriptions", ".", "push", "(", "disposableTlidLineToJSON", ")", ";", "context", ".", "subscriptions", ".", "push", "(", "disposableUnIdugGet", ")", ";", "context", ".", "subscriptions", ".", "push", "(", "disposableIdugGet", ")", ";", "context", ".", "subscriptions", ".", "push", "(", "disposableTlidGet", ")", ";", "context", ".", "subscriptions", ".", "push", "(", "disposableTlidGetJSON", ")", ";", "context", ".", "subscriptions", ".", "push", "(", "disposableTlidugGet", ")", ";", "}" ]
this method is called when your extension is activated your extension is activated the very first time the command is executed
[ "this", "method", "is", "called", "when", "your", "extension", "is", "activated", "your", "extension", "is", "activated", "the", "very", "first", "time", "the", "command", "is", "executed" ]
ddfab991965c1cf01abdde0311e1ee96f8defab3
https://github.com/tlid/tlid/blob/ddfab991965c1cf01abdde0311e1ee96f8defab3/src/vscode/tlid-vscode/extension.js#L22-L126
57,912
byu-oit/fully-typed
bin/string.js
TypedString
function TypedString (config) { const string = this; // validate min length if (config.hasOwnProperty('minLength') && (!util.isInteger(config.minLength) || config.minLength < 0)) { const message = util.propertyErrorMessage('minLength', config.minLength, 'Must be an integer that is greater than or equal to zero.'); throw Error(message); } const minLength = config.hasOwnProperty('minLength') ? config.minLength : 0; // validate max length if (config.hasOwnProperty('maxLength') && (!util.isInteger(config.maxLength) || config.maxLength < minLength)) { const message = util.propertyErrorMessage('maxLength', config.maxLength, 'Must be an integer that is greater than or equal to the minLength.'); throw Error(message); } // validate pattern if (config.hasOwnProperty('pattern') && !(config.pattern instanceof RegExp)) { const message = util.propertyErrorMessage('pattern', config.pattern, 'Must be a regular expression object.'); throw Error(message); } // define properties Object.defineProperties(string, { maxLength: { /** * @property * @name TypedString#maxLength * @type {number} */ value: Math.round(config.maxLength), writable: false }, minLength: { /** * @property * @name TypedString#minLength * @type {number} */ value: Math.round(config.minLength), writable: false }, pattern: { /** * @property * @name TypedString#pattern * @type {RegExp} */ value: config.pattern, writable: false } }); return string; }
javascript
function TypedString (config) { const string = this; // validate min length if (config.hasOwnProperty('minLength') && (!util.isInteger(config.minLength) || config.minLength < 0)) { const message = util.propertyErrorMessage('minLength', config.minLength, 'Must be an integer that is greater than or equal to zero.'); throw Error(message); } const minLength = config.hasOwnProperty('minLength') ? config.minLength : 0; // validate max length if (config.hasOwnProperty('maxLength') && (!util.isInteger(config.maxLength) || config.maxLength < minLength)) { const message = util.propertyErrorMessage('maxLength', config.maxLength, 'Must be an integer that is greater than or equal to the minLength.'); throw Error(message); } // validate pattern if (config.hasOwnProperty('pattern') && !(config.pattern instanceof RegExp)) { const message = util.propertyErrorMessage('pattern', config.pattern, 'Must be a regular expression object.'); throw Error(message); } // define properties Object.defineProperties(string, { maxLength: { /** * @property * @name TypedString#maxLength * @type {number} */ value: Math.round(config.maxLength), writable: false }, minLength: { /** * @property * @name TypedString#minLength * @type {number} */ value: Math.round(config.minLength), writable: false }, pattern: { /** * @property * @name TypedString#pattern * @type {RegExp} */ value: config.pattern, writable: false } }); return string; }
[ "function", "TypedString", "(", "config", ")", "{", "const", "string", "=", "this", ";", "// validate min length", "if", "(", "config", ".", "hasOwnProperty", "(", "'minLength'", ")", "&&", "(", "!", "util", ".", "isInteger", "(", "config", ".", "minLength", ")", "||", "config", ".", "minLength", "<", "0", ")", ")", "{", "const", "message", "=", "util", ".", "propertyErrorMessage", "(", "'minLength'", ",", "config", ".", "minLength", ",", "'Must be an integer that is greater than or equal to zero.'", ")", ";", "throw", "Error", "(", "message", ")", ";", "}", "const", "minLength", "=", "config", ".", "hasOwnProperty", "(", "'minLength'", ")", "?", "config", ".", "minLength", ":", "0", ";", "// validate max length", "if", "(", "config", ".", "hasOwnProperty", "(", "'maxLength'", ")", "&&", "(", "!", "util", ".", "isInteger", "(", "config", ".", "maxLength", ")", "||", "config", ".", "maxLength", "<", "minLength", ")", ")", "{", "const", "message", "=", "util", ".", "propertyErrorMessage", "(", "'maxLength'", ",", "config", ".", "maxLength", ",", "'Must be an integer that is greater than or equal to the minLength.'", ")", ";", "throw", "Error", "(", "message", ")", ";", "}", "// validate pattern", "if", "(", "config", ".", "hasOwnProperty", "(", "'pattern'", ")", "&&", "!", "(", "config", ".", "pattern", "instanceof", "RegExp", ")", ")", "{", "const", "message", "=", "util", ".", "propertyErrorMessage", "(", "'pattern'", ",", "config", ".", "pattern", ",", "'Must be a regular expression object.'", ")", ";", "throw", "Error", "(", "message", ")", ";", "}", "// define properties", "Object", ".", "defineProperties", "(", "string", ",", "{", "maxLength", ":", "{", "/**\n * @property\n * @name TypedString#maxLength\n * @type {number}\n */", "value", ":", "Math", ".", "round", "(", "config", ".", "maxLength", ")", ",", "writable", ":", "false", "}", ",", "minLength", ":", "{", "/**\n * @property\n * @name TypedString#minLength\n * @type {number}\n */", "value", ":", "Math", ".", "round", "(", "config", ".", "minLength", ")", ",", "writable", ":", "false", "}", ",", "pattern", ":", "{", "/**\n * @property\n * @name TypedString#pattern\n * @type {RegExp}\n */", "value", ":", "config", ".", "pattern", ",", "writable", ":", "false", "}", "}", ")", ";", "return", "string", ";", "}" ]
Create a TypedString instance. @param {object} config @returns {TypedString} @augments Typed @constructor
[ "Create", "a", "TypedString", "instance", "." ]
ed6b3ed88ffc72990acffb765232eaaee261afef
https://github.com/byu-oit/fully-typed/blob/ed6b3ed88ffc72990acffb765232eaaee261afef/bin/string.js#L29-L87
57,913
frankwallis/component-resolve-fields
lib/index.js
custom
function custom(options, onfile, done) { if ((!options) || (typeof(options) == 'function')) throw new Error("please provide some options"); if (!options.fields) throw new Error("please provide some fields"); return resolveList(builder.files, options, [], onfile, done); }
javascript
function custom(options, onfile, done) { if ((!options) || (typeof(options) == 'function')) throw new Error("please provide some options"); if (!options.fields) throw new Error("please provide some fields"); return resolveList(builder.files, options, [], onfile, done); }
[ "function", "custom", "(", "options", ",", "onfile", ",", "done", ")", "{", "if", "(", "(", "!", "options", ")", "||", "(", "typeof", "(", "options", ")", "==", "'function'", ")", ")", "throw", "new", "Error", "(", "\"please provide some options\"", ")", ";", "if", "(", "!", "options", ".", "fields", ")", "throw", "new", "Error", "(", "\"please provide some fields\"", ")", ";", "return", "resolveList", "(", "builder", ".", "files", ",", "options", ",", "[", "]", ",", "onfile", ",", "done", ")", ";", "}" ]
lets you specifiy all the fields
[ "lets", "you", "specifiy", "all", "the", "fields" ]
b376968181302d9a41511668ef5d44b8f23edb4e
https://github.com/frankwallis/component-resolve-fields/blob/b376968181302d9a41511668ef5d44b8f23edb4e/lib/index.js#L32-L41
57,914
mnichols/ankh
lib/index.js
Ankh
function Ankh(kernel) { Object.defineProperty(this,'kernel',{ value: (kernel || new Kernel()) ,configurable: false ,writable: false ,enumerable: true }) }
javascript
function Ankh(kernel) { Object.defineProperty(this,'kernel',{ value: (kernel || new Kernel()) ,configurable: false ,writable: false ,enumerable: true }) }
[ "function", "Ankh", "(", "kernel", ")", "{", "Object", ".", "defineProperty", "(", "this", ",", "'kernel'", ",", "{", "value", ":", "(", "kernel", "||", "new", "Kernel", "(", ")", ")", ",", "configurable", ":", "false", ",", "writable", ":", "false", ",", "enumerable", ":", "true", "}", ")", "}" ]
The primary object for interacting with the container. @class Ankh
[ "The", "primary", "object", "for", "interacting", "with", "the", "container", "." ]
b5f6eae24b2dece4025b4f11cea7f1560d3b345f
https://github.com/mnichols/ankh/blob/b5f6eae24b2dece4025b4f11cea7f1560d3b345f/lib/index.js#L13-L20
57,915
prodest/node-mw-api-prodest
lib/errors.js
notFound
function notFound( req, res, next ) { var err = new Error( 'Not Found' ); err.status = 404; next( err ); }
javascript
function notFound( req, res, next ) { var err = new Error( 'Not Found' ); err.status = 404; next( err ); }
[ "function", "notFound", "(", "req", ",", "res", ",", "next", ")", "{", "var", "err", "=", "new", "Error", "(", "'Not Found'", ")", ";", "err", ".", "status", "=", "404", ";", "next", "(", "err", ")", ";", "}" ]
catch 404 and forward to error handler
[ "catch", "404", "and", "forward", "to", "error", "handler" ]
b9b34fbd92d14e996629d6ddb5ea1700076ee83e
https://github.com/prodest/node-mw-api-prodest/blob/b9b34fbd92d14e996629d6ddb5ea1700076ee83e/lib/errors.js#L8-L13
57,916
prodest/node-mw-api-prodest
lib/errors.js
debug
function debug( err, req, res, next ) { res.status( err.status || 500 ); err.guid = uuid.v4(); console.error( err ); res.json( { error: err.message, message: err.userMessage, handled: err.handled || false, guid: err.guid, stack: err.stack } ); }
javascript
function debug( err, req, res, next ) { res.status( err.status || 500 ); err.guid = uuid.v4(); console.error( err ); res.json( { error: err.message, message: err.userMessage, handled: err.handled || false, guid: err.guid, stack: err.stack } ); }
[ "function", "debug", "(", "err", ",", "req", ",", "res", ",", "next", ")", "{", "res", ".", "status", "(", "err", ".", "status", "||", "500", ")", ";", "err", ".", "guid", "=", "uuid", ".", "v4", "(", ")", ";", "console", ".", "error", "(", "err", ")", ";", "res", ".", "json", "(", "{", "error", ":", "err", ".", "message", ",", "message", ":", "err", ".", "userMessage", ",", "handled", ":", "err", ".", "handled", "||", "false", ",", "guid", ":", "err", ".", "guid", ",", "stack", ":", "err", ".", "stack", "}", ")", ";", "}" ]
development error handler will print full error
[ "development", "error", "handler", "will", "print", "full", "error" ]
b9b34fbd92d14e996629d6ddb5ea1700076ee83e
https://github.com/prodest/node-mw-api-prodest/blob/b9b34fbd92d14e996629d6ddb5ea1700076ee83e/lib/errors.js#L17-L31
57,917
Fauntleroy/Igneous
examples/jquery-tmpl/assets/scripts/jquery.tmpl.js
function( tmpl, data, options, parentItem ) { var ret, topLevel = !parentItem; if ( topLevel ) { // This is a top-level tmpl call (not from a nested template using {{tmpl}}) parentItem = topTmplItem; tmpl = jQuery.template[tmpl] || jQuery.template( null, tmpl ); wrappedItems = {}; // Any wrapped items will be rebuilt, since this is top level } else if ( !tmpl ) { // The template item is already associated with DOM - this is a refresh. // Re-evaluate rendered template for the parentItem tmpl = parentItem.tmpl; newTmplItems[parentItem.key] = parentItem; parentItem.nodes = []; if ( parentItem.wrapped ) { updateWrapped( parentItem, parentItem.wrapped ); } // Rebuild, without creating a new template item return jQuery( build( parentItem, null, parentItem.tmpl( jQuery, parentItem ) )); } if ( !tmpl ) { return []; // Could throw... } if ( typeof data === "function" ) { data = data.call( parentItem || {} ); } if ( options && options.wrapped ) { updateWrapped( options, options.wrapped ); } ret = jQuery.isArray( data ) ? jQuery.map( data, function( dataItem ) { return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null; }) : [ newTmplItem( options, parentItem, tmpl, data ) ]; return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret; }
javascript
function( tmpl, data, options, parentItem ) { var ret, topLevel = !parentItem; if ( topLevel ) { // This is a top-level tmpl call (not from a nested template using {{tmpl}}) parentItem = topTmplItem; tmpl = jQuery.template[tmpl] || jQuery.template( null, tmpl ); wrappedItems = {}; // Any wrapped items will be rebuilt, since this is top level } else if ( !tmpl ) { // The template item is already associated with DOM - this is a refresh. // Re-evaluate rendered template for the parentItem tmpl = parentItem.tmpl; newTmplItems[parentItem.key] = parentItem; parentItem.nodes = []; if ( parentItem.wrapped ) { updateWrapped( parentItem, parentItem.wrapped ); } // Rebuild, without creating a new template item return jQuery( build( parentItem, null, parentItem.tmpl( jQuery, parentItem ) )); } if ( !tmpl ) { return []; // Could throw... } if ( typeof data === "function" ) { data = data.call( parentItem || {} ); } if ( options && options.wrapped ) { updateWrapped( options, options.wrapped ); } ret = jQuery.isArray( data ) ? jQuery.map( data, function( dataItem ) { return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null; }) : [ newTmplItem( options, parentItem, tmpl, data ) ]; return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret; }
[ "function", "(", "tmpl", ",", "data", ",", "options", ",", "parentItem", ")", "{", "var", "ret", ",", "topLevel", "=", "!", "parentItem", ";", "if", "(", "topLevel", ")", "{", "// This is a top-level tmpl call (not from a nested template using {{tmpl}})", "parentItem", "=", "topTmplItem", ";", "tmpl", "=", "jQuery", ".", "template", "[", "tmpl", "]", "||", "jQuery", ".", "template", "(", "null", ",", "tmpl", ")", ";", "wrappedItems", "=", "{", "}", ";", "// Any wrapped items will be rebuilt, since this is top level", "}", "else", "if", "(", "!", "tmpl", ")", "{", "// The template item is already associated with DOM - this is a refresh.", "// Re-evaluate rendered template for the parentItem", "tmpl", "=", "parentItem", ".", "tmpl", ";", "newTmplItems", "[", "parentItem", ".", "key", "]", "=", "parentItem", ";", "parentItem", ".", "nodes", "=", "[", "]", ";", "if", "(", "parentItem", ".", "wrapped", ")", "{", "updateWrapped", "(", "parentItem", ",", "parentItem", ".", "wrapped", ")", ";", "}", "// Rebuild, without creating a new template item", "return", "jQuery", "(", "build", "(", "parentItem", ",", "null", ",", "parentItem", ".", "tmpl", "(", "jQuery", ",", "parentItem", ")", ")", ")", ";", "}", "if", "(", "!", "tmpl", ")", "{", "return", "[", "]", ";", "// Could throw...", "}", "if", "(", "typeof", "data", "===", "\"function\"", ")", "{", "data", "=", "data", ".", "call", "(", "parentItem", "||", "{", "}", ")", ";", "}", "if", "(", "options", "&&", "options", ".", "wrapped", ")", "{", "updateWrapped", "(", "options", ",", "options", ".", "wrapped", ")", ";", "}", "ret", "=", "jQuery", ".", "isArray", "(", "data", ")", "?", "jQuery", ".", "map", "(", "data", ",", "function", "(", "dataItem", ")", "{", "return", "dataItem", "?", "newTmplItem", "(", "options", ",", "parentItem", ",", "tmpl", ",", "dataItem", ")", ":", "null", ";", "}", ")", ":", "[", "newTmplItem", "(", "options", ",", "parentItem", ",", "tmpl", ",", "data", ")", "]", ";", "return", "topLevel", "?", "jQuery", "(", "build", "(", "parentItem", ",", "null", ",", "ret", ")", ")", ":", "ret", ";", "}" ]
Return wrapped set of template items, obtained by rendering template against data.
[ "Return", "wrapped", "set", "of", "template", "items", "obtained", "by", "rendering", "template", "against", "data", "." ]
73318fad5cac8a1b5114b8b80ff39dfd2a4542fa
https://github.com/Fauntleroy/Igneous/blob/73318fad5cac8a1b5114b8b80ff39dfd2a4542fa/examples/jquery-tmpl/assets/scripts/jquery.tmpl.js#L119-L153
57,918
Fauntleroy/Igneous
examples/jquery-tmpl/assets/scripts/jquery.tmpl.js
function( elem ) { var tmplItem; if ( elem instanceof jQuery ) { elem = elem[0]; } while ( elem && elem.nodeType === 1 && !(tmplItem = jQuery.data( elem, "tmplItem" )) && (elem = elem.parentNode) ) {} return tmplItem || topTmplItem; }
javascript
function( elem ) { var tmplItem; if ( elem instanceof jQuery ) { elem = elem[0]; } while ( elem && elem.nodeType === 1 && !(tmplItem = jQuery.data( elem, "tmplItem" )) && (elem = elem.parentNode) ) {} return tmplItem || topTmplItem; }
[ "function", "(", "elem", ")", "{", "var", "tmplItem", ";", "if", "(", "elem", "instanceof", "jQuery", ")", "{", "elem", "=", "elem", "[", "0", "]", ";", "}", "while", "(", "elem", "&&", "elem", ".", "nodeType", "===", "1", "&&", "!", "(", "tmplItem", "=", "jQuery", ".", "data", "(", "elem", ",", "\"tmplItem\"", ")", ")", "&&", "(", "elem", "=", "elem", ".", "parentNode", ")", ")", "{", "}", "return", "tmplItem", "||", "topTmplItem", ";", "}" ]
Return rendered template item for an element.
[ "Return", "rendered", "template", "item", "for", "an", "element", "." ]
73318fad5cac8a1b5114b8b80ff39dfd2a4542fa
https://github.com/Fauntleroy/Igneous/blob/73318fad5cac8a1b5114b8b80ff39dfd2a4542fa/examples/jquery-tmpl/assets/scripts/jquery.tmpl.js#L156-L163
57,919
nicktindall/cyclon.p2p-common
lib/ConsoleLogger.js
ConsoleLogger
function ConsoleLogger() { this.error = function () { if (loggingLevel(ERROR)) { console.error.apply(this, arguments); } }; this.warn = function () { if (loggingLevel(WARN)) { console.warn.apply(this, arguments); } }; this.info = function () { if (loggingLevel(INFO)) { console.info.apply(this, arguments); } }; this.log = function () { if (loggingLevel(INFO)) { console.log.apply(this, arguments); } }; this.debug = function () { if (loggingLevel(DEBUG)) { console.log.apply(this, arguments); } }; this.setLevelToInfo = function () { setLevel(INFO); }; this.setLevelToDebug = function() { setLevel(DEBUG); }; this.setLevelToWarning = function() { setLevel(WARN); }; this.setLevelToError = function() { setLevel(ERROR); }; }
javascript
function ConsoleLogger() { this.error = function () { if (loggingLevel(ERROR)) { console.error.apply(this, arguments); } }; this.warn = function () { if (loggingLevel(WARN)) { console.warn.apply(this, arguments); } }; this.info = function () { if (loggingLevel(INFO)) { console.info.apply(this, arguments); } }; this.log = function () { if (loggingLevel(INFO)) { console.log.apply(this, arguments); } }; this.debug = function () { if (loggingLevel(DEBUG)) { console.log.apply(this, arguments); } }; this.setLevelToInfo = function () { setLevel(INFO); }; this.setLevelToDebug = function() { setLevel(DEBUG); }; this.setLevelToWarning = function() { setLevel(WARN); }; this.setLevelToError = function() { setLevel(ERROR); }; }
[ "function", "ConsoleLogger", "(", ")", "{", "this", ".", "error", "=", "function", "(", ")", "{", "if", "(", "loggingLevel", "(", "ERROR", ")", ")", "{", "console", ".", "error", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "}", ";", "this", ".", "warn", "=", "function", "(", ")", "{", "if", "(", "loggingLevel", "(", "WARN", ")", ")", "{", "console", ".", "warn", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "}", ";", "this", ".", "info", "=", "function", "(", ")", "{", "if", "(", "loggingLevel", "(", "INFO", ")", ")", "{", "console", ".", "info", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "}", ";", "this", ".", "log", "=", "function", "(", ")", "{", "if", "(", "loggingLevel", "(", "INFO", ")", ")", "{", "console", ".", "log", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "}", ";", "this", ".", "debug", "=", "function", "(", ")", "{", "if", "(", "loggingLevel", "(", "DEBUG", ")", ")", "{", "console", ".", "log", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "}", ";", "this", ".", "setLevelToInfo", "=", "function", "(", ")", "{", "setLevel", "(", "INFO", ")", ";", "}", ";", "this", ".", "setLevelToDebug", "=", "function", "(", ")", "{", "setLevel", "(", "DEBUG", ")", ";", "}", ";", "this", ".", "setLevelToWarning", "=", "function", "(", ")", "{", "setLevel", "(", "WARN", ")", ";", "}", ";", "this", ".", "setLevelToError", "=", "function", "(", ")", "{", "setLevel", "(", "ERROR", ")", ";", "}", ";", "}" ]
Configurable console logger, default level is INFO @constructor
[ "Configurable", "console", "logger", "default", "level", "is", "INFO" ]
04ee34984c9d5145e265a886bf261cb64dc20e3c
https://github.com/nicktindall/cyclon.p2p-common/blob/04ee34984c9d5145e265a886bf261cb64dc20e3c/lib/ConsoleLogger.js#L13-L60
57,920
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/iterator.js
getNestedEditableIn
function getNestedEditableIn( editablesContainer, remainingEditables ) { if ( remainingEditables == null ) remainingEditables = findNestedEditables( editablesContainer ); var editable; while ( ( editable = remainingEditables.shift() ) ) { if ( isIterableEditable( editable ) ) return { element: editable, remaining: remainingEditables }; } return null; }
javascript
function getNestedEditableIn( editablesContainer, remainingEditables ) { if ( remainingEditables == null ) remainingEditables = findNestedEditables( editablesContainer ); var editable; while ( ( editable = remainingEditables.shift() ) ) { if ( isIterableEditable( editable ) ) return { element: editable, remaining: remainingEditables }; } return null; }
[ "function", "getNestedEditableIn", "(", "editablesContainer", ",", "remainingEditables", ")", "{", "if", "(", "remainingEditables", "==", "null", ")", "remainingEditables", "=", "findNestedEditables", "(", "editablesContainer", ")", ";", "var", "editable", ";", "while", "(", "(", "editable", "=", "remainingEditables", ".", "shift", "(", ")", ")", ")", "{", "if", "(", "isIterableEditable", "(", "editable", ")", ")", "return", "{", "element", ":", "editable", ",", "remaining", ":", "remainingEditables", "}", ";", "}", "return", "null", ";", "}" ]
Does a nested editables lookup inside editablesContainer. If remainingEditables is set will lookup inside this array. @param {CKEDITOR.dom.element} editablesContainer @param {CKEDITOR.dom.element[]} [remainingEditables]
[ "Does", "a", "nested", "editables", "lookup", "inside", "editablesContainer", ".", "If", "remainingEditables", "is", "set", "will", "lookup", "inside", "this", "array", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/iterator.js#L438-L450
57,921
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/iterator.js
rangeAtInnerBlockBoundary
function rangeAtInnerBlockBoundary( range, block, checkEnd ) { if ( !block ) return false; var testRange = range.clone(); testRange.collapse( !checkEnd ); return testRange.checkBoundaryOfElement( block, checkEnd ? CKEDITOR.START : CKEDITOR.END ); }
javascript
function rangeAtInnerBlockBoundary( range, block, checkEnd ) { if ( !block ) return false; var testRange = range.clone(); testRange.collapse( !checkEnd ); return testRange.checkBoundaryOfElement( block, checkEnd ? CKEDITOR.START : CKEDITOR.END ); }
[ "function", "rangeAtInnerBlockBoundary", "(", "range", ",", "block", ",", "checkEnd", ")", "{", "if", "(", "!", "block", ")", "return", "false", ";", "var", "testRange", "=", "range", ".", "clone", "(", ")", ";", "testRange", ".", "collapse", "(", "!", "checkEnd", ")", ";", "return", "testRange", ".", "checkBoundaryOfElement", "(", "block", ",", "checkEnd", "?", "CKEDITOR", ".", "START", ":", "CKEDITOR", ".", "END", ")", ";", "}" ]
Checks whether range starts or ends at inner block boundary. See usage comments to learn more.
[ "Checks", "whether", "range", "starts", "or", "ends", "at", "inner", "block", "boundary", ".", "See", "usage", "comments", "to", "learn", "more", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/iterator.js#L515-L522
57,922
jonschlinkert/orgs
index.js
orgs
async function orgs(users, options) { const opts = Object.assign({}, options); const acc = { orgs: [], names: [] }; if (isObject(users)) { return github('paged', '/user/orgs', users).then(res => addOrgs(acc, res)); } if (typeof users === 'string') users = [users]; if (!Array.isArray(users)) { return Promise.reject(new TypeError('expected users to be a string or array')); } const pending = []; for (const name of users) { pending.push(getOrgs(acc, name, options)); } await Promise.all(pending); if (opts.sort !== false) { return acc.orgs.sort(compare('login')); } return acc.orgs; }
javascript
async function orgs(users, options) { const opts = Object.assign({}, options); const acc = { orgs: [], names: [] }; if (isObject(users)) { return github('paged', '/user/orgs', users).then(res => addOrgs(acc, res)); } if (typeof users === 'string') users = [users]; if (!Array.isArray(users)) { return Promise.reject(new TypeError('expected users to be a string or array')); } const pending = []; for (const name of users) { pending.push(getOrgs(acc, name, options)); } await Promise.all(pending); if (opts.sort !== false) { return acc.orgs.sort(compare('login')); } return acc.orgs; }
[ "async", "function", "orgs", "(", "users", ",", "options", ")", "{", "const", "opts", "=", "Object", ".", "assign", "(", "{", "}", ",", "options", ")", ";", "const", "acc", "=", "{", "orgs", ":", "[", "]", ",", "names", ":", "[", "]", "}", ";", "if", "(", "isObject", "(", "users", ")", ")", "{", "return", "github", "(", "'paged'", ",", "'/user/orgs'", ",", "users", ")", ".", "then", "(", "res", "=>", "addOrgs", "(", "acc", ",", "res", ")", ")", ";", "}", "if", "(", "typeof", "users", "===", "'string'", ")", "users", "=", "[", "users", "]", ";", "if", "(", "!", "Array", ".", "isArray", "(", "users", ")", ")", "{", "return", "Promise", ".", "reject", "(", "new", "TypeError", "(", "'expected users to be a string or array'", ")", ")", ";", "}", "const", "pending", "=", "[", "]", ";", "for", "(", "const", "name", "of", "users", ")", "{", "pending", ".", "push", "(", "getOrgs", "(", "acc", ",", "name", ",", "options", ")", ")", ";", "}", "await", "Promise", ".", "all", "(", "pending", ")", ";", "if", "(", "opts", ".", "sort", "!==", "false", ")", "{", "return", "acc", ".", "orgs", ".", "sort", "(", "compare", "(", "'login'", ")", ")", ";", "}", "return", "acc", ".", "orgs", ";", "}" ]
Get publicly available information from the GitHub API for one or more users or organizations. If user names are passed, all orgs for those users are returned. If organization names are passed, an object is returned with information about each org. ```js const orgs = require('orgs'); // see github-base for other authentication options orgs(['doowb', 'jonschlinkert'], { token: 'YOUR_GITHUB_AUTH_TOKEN' }) .then(orgs => { // array of organization objects from the GitHub API console.log(orgs); }) .catch(console.error)l ``` @param {String|Array} `users` One or more users or organization names. @param {Object} `options` @return {Promise} @api public
[ "Get", "publicly", "available", "information", "from", "the", "GitHub", "API", "for", "one", "or", "more", "users", "or", "organizations", ".", "If", "user", "names", "are", "passed", "all", "orgs", "for", "those", "users", "are", "returned", ".", "If", "organization", "names", "are", "passed", "an", "object", "is", "returned", "with", "information", "about", "each", "org", "." ]
1f11e3d2c08bd7d54934b74dfce350ae9b7a4f58
https://github.com/jonschlinkert/orgs/blob/1f11e3d2c08bd7d54934b74dfce350ae9b7a4f58/index.js#L29-L53
57,923
moraispgsi/fsm-core
src/indexOld.js
init
function init(){ debug("Checking if there is a repository"); return co(function*(){ let repo; try { repo = yield nodegit.Repository.open(repositoryPath); } catch(err) { debug("Repository not found."); repo = yield _createRepository(); } debug("Repository is ready"); return repo; }); }
javascript
function init(){ debug("Checking if there is a repository"); return co(function*(){ let repo; try { repo = yield nodegit.Repository.open(repositoryPath); } catch(err) { debug("Repository not found."); repo = yield _createRepository(); } debug("Repository is ready"); return repo; }); }
[ "function", "init", "(", ")", "{", "debug", "(", "\"Checking if there is a repository\"", ")", ";", "return", "co", "(", "function", "*", "(", ")", "{", "let", "repo", ";", "try", "{", "repo", "=", "yield", "nodegit", ".", "Repository", ".", "open", "(", "repositoryPath", ")", ";", "}", "catch", "(", "err", ")", "{", "debug", "(", "\"Repository not found.\"", ")", ";", "repo", "=", "yield", "_createRepository", "(", ")", ";", "}", "debug", "(", "\"Repository is ready\"", ")", ";", "return", "repo", ";", "}", ")", ";", "}" ]
Initializes the repository connection @method init @returns {Promise} Repository connection
[ "Initializes", "the", "repository", "connection" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L34-L50
57,924
moraispgsi/fsm-core
src/indexOld.js
_getFiles
function _getFiles(path){ let files = []; fs.readdirSync(path).forEach(function(file){ let subpath = path + '/' + file; if(fs.lstatSync(subpath).isDirectory()){ let filesReturned = _getFiles(subpath); files = files.concat(filesReturned); } else { files.push(path + '/' + file); } }); return files; }
javascript
function _getFiles(path){ let files = []; fs.readdirSync(path).forEach(function(file){ let subpath = path + '/' + file; if(fs.lstatSync(subpath).isDirectory()){ let filesReturned = _getFiles(subpath); files = files.concat(filesReturned); } else { files.push(path + '/' + file); } }); return files; }
[ "function", "_getFiles", "(", "path", ")", "{", "let", "files", "=", "[", "]", ";", "fs", ".", "readdirSync", "(", "path", ")", ".", "forEach", "(", "function", "(", "file", ")", "{", "let", "subpath", "=", "path", "+", "'/'", "+", "file", ";", "if", "(", "fs", ".", "lstatSync", "(", "subpath", ")", ".", "isDirectory", "(", ")", ")", "{", "let", "filesReturned", "=", "_getFiles", "(", "subpath", ")", ";", "files", "=", "files", ".", "concat", "(", "filesReturned", ")", ";", "}", "else", "{", "files", ".", "push", "(", "path", "+", "'/'", "+", "file", ")", ";", "}", "}", ")", ";", "return", "files", ";", "}" ]
Recursively gather the paths of the files inside a directory path @method _getFiles @param {String} path The directory path to search @returns {Array} An Array of file paths belonging to the directory path provided
[ "Recursively", "gather", "the", "paths", "of", "the", "files", "inside", "a", "directory", "path" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L58-L70
57,925
moraispgsi/fsm-core
src/indexOld.js
_commit
function _commit(repo, pathsToStage, message, pathsToUnstage) { return co(function*(){ repo = repo || (yield nodegit.Repository.open(repositoryPath)); debug("Adding files to the index"); let index = yield repo.refreshIndex(repositoryPath + "/.git/index"); if(pathsToUnstage && pathsToUnstage.length && pathsToUnstage.length > 0) { for(let file of pathsToUnstage) { yield index.removeByPath(file); } yield index.write(); yield index.writeTree(); } debug("Creating main files"); let signature = nodegit.Signature.default(repo); debug("Commiting"); yield repo.createCommitOnHead(pathsToStage, signature, signature, message || "Automatic initialization"); }); }
javascript
function _commit(repo, pathsToStage, message, pathsToUnstage) { return co(function*(){ repo = repo || (yield nodegit.Repository.open(repositoryPath)); debug("Adding files to the index"); let index = yield repo.refreshIndex(repositoryPath + "/.git/index"); if(pathsToUnstage && pathsToUnstage.length && pathsToUnstage.length > 0) { for(let file of pathsToUnstage) { yield index.removeByPath(file); } yield index.write(); yield index.writeTree(); } debug("Creating main files"); let signature = nodegit.Signature.default(repo); debug("Commiting"); yield repo.createCommitOnHead(pathsToStage, signature, signature, message || "Automatic initialization"); }); }
[ "function", "_commit", "(", "repo", ",", "pathsToStage", ",", "message", ",", "pathsToUnstage", ")", "{", "return", "co", "(", "function", "*", "(", ")", "{", "repo", "=", "repo", "||", "(", "yield", "nodegit", ".", "Repository", ".", "open", "(", "repositoryPath", ")", ")", ";", "debug", "(", "\"Adding files to the index\"", ")", ";", "let", "index", "=", "yield", "repo", ".", "refreshIndex", "(", "repositoryPath", "+", "\"/.git/index\"", ")", ";", "if", "(", "pathsToUnstage", "&&", "pathsToUnstage", ".", "length", "&&", "pathsToUnstage", ".", "length", ">", "0", ")", "{", "for", "(", "let", "file", "of", "pathsToUnstage", ")", "{", "yield", "index", ".", "removeByPath", "(", "file", ")", ";", "}", "yield", "index", ".", "write", "(", ")", ";", "yield", "index", ".", "writeTree", "(", ")", ";", "}", "debug", "(", "\"Creating main files\"", ")", ";", "let", "signature", "=", "nodegit", ".", "Signature", ".", "default", "(", "repo", ")", ";", "debug", "(", "\"Commiting\"", ")", ";", "yield", "repo", ".", "createCommitOnHead", "(", "pathsToStage", ",", "signature", ",", "signature", ",", "message", "||", "\"Automatic initialization\"", ")", ";", "}", ")", ";", "}" ]
Commit to the repository @method _commit @param {Repository} repo The repository connection object @param {Array} pathsToStage The array of file paths(relative to the repository) to be staged @param {String} message The message to go along with this commit @param {Array} pathsToUnstage The array of file paths(relative to the repository) to be un-staged @returns {Array} An Array of file paths belonging to the directory path provided
[ "Commit", "to", "the", "repository" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L81-L100
57,926
moraispgsi/fsm-core
src/indexOld.js
_createRepository
function _createRepository() { return co(function*(){ try { debug("Creating a new one"); let repo = yield nodegit.Repository.init(repositoryPath, 0); debug("Connection established"); debug("Creating main files"); yield _createManifest(repo); yield _createConfig(repo); fs.mkdirSync(machinesDirPath); yield _commit(repo, ["manifest.json", "config.json"]); debug("Repository was successfully created"); return repo; } catch (err) { debug(err); debug("Nuking the repository"); yield new Promise(function(resolve, reject) { rimraf(repositoryPath, function () { resolve(); }); }).then(); throw new Error(err); } }); }
javascript
function _createRepository() { return co(function*(){ try { debug("Creating a new one"); let repo = yield nodegit.Repository.init(repositoryPath, 0); debug("Connection established"); debug("Creating main files"); yield _createManifest(repo); yield _createConfig(repo); fs.mkdirSync(machinesDirPath); yield _commit(repo, ["manifest.json", "config.json"]); debug("Repository was successfully created"); return repo; } catch (err) { debug(err); debug("Nuking the repository"); yield new Promise(function(resolve, reject) { rimraf(repositoryPath, function () { resolve(); }); }).then(); throw new Error(err); } }); }
[ "function", "_createRepository", "(", ")", "{", "return", "co", "(", "function", "*", "(", ")", "{", "try", "{", "debug", "(", "\"Creating a new one\"", ")", ";", "let", "repo", "=", "yield", "nodegit", ".", "Repository", ".", "init", "(", "repositoryPath", ",", "0", ")", ";", "debug", "(", "\"Connection established\"", ")", ";", "debug", "(", "\"Creating main files\"", ")", ";", "yield", "_createManifest", "(", "repo", ")", ";", "yield", "_createConfig", "(", "repo", ")", ";", "fs", ".", "mkdirSync", "(", "machinesDirPath", ")", ";", "yield", "_commit", "(", "repo", ",", "[", "\"manifest.json\"", ",", "\"config.json\"", "]", ")", ";", "debug", "(", "\"Repository was successfully created\"", ")", ";", "return", "repo", ";", "}", "catch", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "debug", "(", "\"Nuking the repository\"", ")", ";", "yield", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "rimraf", "(", "repositoryPath", ",", "function", "(", ")", "{", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ".", "then", "(", ")", ";", "throw", "new", "Error", "(", "err", ")", ";", "}", "}", ")", ";", "}" ]
Create a new repository @method _createRepository @returns {Promise} Repository connection
[ "Create", "a", "new", "repository" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L107-L131
57,927
moraispgsi/fsm-core
src/indexOld.js
_createManifest
function _createManifest(){ let file = repositoryPath + '/manifest.json'; let manifest = { machines: {} }; return new Promise(function(resolve, reject) { debug("Creating manifest file"); jsonfile.writeFile(file, manifest, function (err) { if(err){ debug("Failed to create the manifest file"); reject(err); return; } resolve(); }); }); }
javascript
function _createManifest(){ let file = repositoryPath + '/manifest.json'; let manifest = { machines: {} }; return new Promise(function(resolve, reject) { debug("Creating manifest file"); jsonfile.writeFile(file, manifest, function (err) { if(err){ debug("Failed to create the manifest file"); reject(err); return; } resolve(); }); }); }
[ "function", "_createManifest", "(", ")", "{", "let", "file", "=", "repositoryPath", "+", "'/manifest.json'", ";", "let", "manifest", "=", "{", "machines", ":", "{", "}", "}", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "debug", "(", "\"Creating manifest file\"", ")", ";", "jsonfile", ".", "writeFile", "(", "file", ",", "manifest", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "\"Failed to create the manifest file\"", ")", ";", "reject", "(", "err", ")", ";", "return", ";", "}", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Create the manifest file inside the repository @method _createManifest @returns {Promise}
[ "Create", "the", "manifest", "file", "inside", "the", "repository" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L138-L155
57,928
moraispgsi/fsm-core
src/indexOld.js
_createConfig
function _createConfig(){ let file = repositoryPath + '/config.json'; let config = { simulation: false }; return new Promise(function(resolve, reject) { jsonfile.writeFile(file, config, function (err) { if(err){ reject(err); return; } resolve(); }); }); }
javascript
function _createConfig(){ let file = repositoryPath + '/config.json'; let config = { simulation: false }; return new Promise(function(resolve, reject) { jsonfile.writeFile(file, config, function (err) { if(err){ reject(err); return; } resolve(); }); }); }
[ "function", "_createConfig", "(", ")", "{", "let", "file", "=", "repositoryPath", "+", "'/config.json'", ";", "let", "config", "=", "{", "simulation", ":", "false", "}", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "jsonfile", ".", "writeFile", "(", "file", ",", "config", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "return", ";", "}", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Create the config file inside the repository @method _createManifest @returns {Promise}
[ "Create", "the", "config", "file", "inside", "the", "repository" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L162-L177
57,929
moraispgsi/fsm-core
src/indexOld.js
setManifest
function setManifest(manifest, withCommit, message){ jsonfile.writeFileSync(manifestPath, manifest, {spaces: 2}); if(withCommit) { return _commit(null, ["manifest.json"], message || "Changed the manifest file"); } }
javascript
function setManifest(manifest, withCommit, message){ jsonfile.writeFileSync(manifestPath, manifest, {spaces: 2}); if(withCommit) { return _commit(null, ["manifest.json"], message || "Changed the manifest file"); } }
[ "function", "setManifest", "(", "manifest", ",", "withCommit", ",", "message", ")", "{", "jsonfile", ".", "writeFileSync", "(", "manifestPath", ",", "manifest", ",", "{", "spaces", ":", "2", "}", ")", ";", "if", "(", "withCommit", ")", "{", "return", "_commit", "(", "null", ",", "[", "\"manifest.json\"", "]", ",", "message", "||", "\"Changed the manifest file\"", ")", ";", "}", "}" ]
Update the repository manifest.json file using a JavasScript Object @method setManifest @param {Object} manifest The manifest Object to save @param {boolean} withCommit If true commits the changes to the repository @param {String} message If supplied it is used as the message for the commit @returns {Promise} If withCommit is true, the function returns a Promise
[ "Update", "the", "repository", "manifest", ".", "json", "file", "using", "a", "JavasScript", "Object" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L205-L211
57,930
moraispgsi/fsm-core
src/indexOld.js
setConfig
function setConfig(config, withCommit, message){ jsonfile.writeFileSync(configPath, config, {spaces: 2}); if(withCommit) { return _commit(null, ["config.json"], message || "Changed the config file"); } }
javascript
function setConfig(config, withCommit, message){ jsonfile.writeFileSync(configPath, config, {spaces: 2}); if(withCommit) { return _commit(null, ["config.json"], message || "Changed the config file"); } }
[ "function", "setConfig", "(", "config", ",", "withCommit", ",", "message", ")", "{", "jsonfile", ".", "writeFileSync", "(", "configPath", ",", "config", ",", "{", "spaces", ":", "2", "}", ")", ";", "if", "(", "withCommit", ")", "{", "return", "_commit", "(", "null", ",", "[", "\"config.json\"", "]", ",", "message", "||", "\"Changed the config file\"", ")", ";", "}", "}" ]
Update the repository config.json file using a JavasScript Object @method setConfig @param {Object} config The config Object to save @param {boolean} withCommit If true commits the changes to the repository @param {String} message If supplied it is used as the message for the commit @returns {Promise} If withCommit is true, the function returns a Promise
[ "Update", "the", "repository", "config", ".", "json", "file", "using", "a", "JavasScript", "Object" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L230-L236
57,931
moraispgsi/fsm-core
src/indexOld.js
addMachine
function addMachine(name) { return co(function*(){ debug("Adding a new machine with the name '%s'", name); let manifest = getManifest(); if(manifest.machines[name]) { debug("Machine already exists"); throw new Error("Machine already exists"); } manifest.machines[name] = { route: "machines/" + name, "versions": { "version1": { "route": "machines/" + name + "/versions/version1", "instances": {} } } }; let machineDirPath = "machines/" + name; let machineVersionsDirPath = machineDirPath + "/versions"; let version1DirPath = machineVersionsDirPath + "/version1"; let version1InstancesDirPath = version1DirPath + "/instances"; let modelFile = version1DirPath + '/model.scxml'; let infoFile = version1DirPath + "/info.json"; debug("Creating the directories"); fs.mkdirSync(repositoryPath + "/" + machineDirPath); fs.mkdirSync(repositoryPath + "/" + machineVersionsDirPath); fs.mkdirSync(repositoryPath + "/" + version1DirPath); fs.mkdirSync(repositoryPath + "/" + version1InstancesDirPath); debug("Creating the base.scxml file"); fs.copySync(__dirname + '/base.scxml', repositoryPath + "/" + modelFile); debug("Creating the version info.json file"); let infoVersion1 = { "isSealed": false }; jsonfile.writeFileSync(repositoryPath + "/" + infoFile, infoVersion1); debug("Setting the manifest"); setManifest(manifest); yield _commit(null, ["manifest.json", modelFile, infoFile], "Added '" + name + "' machine"); debug("A new machine with the name '%s' was successfully added", name); }); }
javascript
function addMachine(name) { return co(function*(){ debug("Adding a new machine with the name '%s'", name); let manifest = getManifest(); if(manifest.machines[name]) { debug("Machine already exists"); throw new Error("Machine already exists"); } manifest.machines[name] = { route: "machines/" + name, "versions": { "version1": { "route": "machines/" + name + "/versions/version1", "instances": {} } } }; let machineDirPath = "machines/" + name; let machineVersionsDirPath = machineDirPath + "/versions"; let version1DirPath = machineVersionsDirPath + "/version1"; let version1InstancesDirPath = version1DirPath + "/instances"; let modelFile = version1DirPath + '/model.scxml'; let infoFile = version1DirPath + "/info.json"; debug("Creating the directories"); fs.mkdirSync(repositoryPath + "/" + machineDirPath); fs.mkdirSync(repositoryPath + "/" + machineVersionsDirPath); fs.mkdirSync(repositoryPath + "/" + version1DirPath); fs.mkdirSync(repositoryPath + "/" + version1InstancesDirPath); debug("Creating the base.scxml file"); fs.copySync(__dirname + '/base.scxml', repositoryPath + "/" + modelFile); debug("Creating the version info.json file"); let infoVersion1 = { "isSealed": false }; jsonfile.writeFileSync(repositoryPath + "/" + infoFile, infoVersion1); debug("Setting the manifest"); setManifest(manifest); yield _commit(null, ["manifest.json", modelFile, infoFile], "Added '" + name + "' machine"); debug("A new machine with the name '%s' was successfully added", name); }); }
[ "function", "addMachine", "(", "name", ")", "{", "return", "co", "(", "function", "*", "(", ")", "{", "debug", "(", "\"Adding a new machine with the name '%s'\"", ",", "name", ")", ";", "let", "manifest", "=", "getManifest", "(", ")", ";", "if", "(", "manifest", ".", "machines", "[", "name", "]", ")", "{", "debug", "(", "\"Machine already exists\"", ")", ";", "throw", "new", "Error", "(", "\"Machine already exists\"", ")", ";", "}", "manifest", ".", "machines", "[", "name", "]", "=", "{", "route", ":", "\"machines/\"", "+", "name", ",", "\"versions\"", ":", "{", "\"version1\"", ":", "{", "\"route\"", ":", "\"machines/\"", "+", "name", "+", "\"/versions/version1\"", ",", "\"instances\"", ":", "{", "}", "}", "}", "}", ";", "let", "machineDirPath", "=", "\"machines/\"", "+", "name", ";", "let", "machineVersionsDirPath", "=", "machineDirPath", "+", "\"/versions\"", ";", "let", "version1DirPath", "=", "machineVersionsDirPath", "+", "\"/version1\"", ";", "let", "version1InstancesDirPath", "=", "version1DirPath", "+", "\"/instances\"", ";", "let", "modelFile", "=", "version1DirPath", "+", "'/model.scxml'", ";", "let", "infoFile", "=", "version1DirPath", "+", "\"/info.json\"", ";", "debug", "(", "\"Creating the directories\"", ")", ";", "fs", ".", "mkdirSync", "(", "repositoryPath", "+", "\"/\"", "+", "machineDirPath", ")", ";", "fs", ".", "mkdirSync", "(", "repositoryPath", "+", "\"/\"", "+", "machineVersionsDirPath", ")", ";", "fs", ".", "mkdirSync", "(", "repositoryPath", "+", "\"/\"", "+", "version1DirPath", ")", ";", "fs", ".", "mkdirSync", "(", "repositoryPath", "+", "\"/\"", "+", "version1InstancesDirPath", ")", ";", "debug", "(", "\"Creating the base.scxml file\"", ")", ";", "fs", ".", "copySync", "(", "__dirname", "+", "'/base.scxml'", ",", "repositoryPath", "+", "\"/\"", "+", "modelFile", ")", ";", "debug", "(", "\"Creating the version info.json file\"", ")", ";", "let", "infoVersion1", "=", "{", "\"isSealed\"", ":", "false", "}", ";", "jsonfile", ".", "writeFileSync", "(", "repositoryPath", "+", "\"/\"", "+", "infoFile", ",", "infoVersion1", ")", ";", "debug", "(", "\"Setting the manifest\"", ")", ";", "setManifest", "(", "manifest", ")", ";", "yield", "_commit", "(", "null", ",", "[", "\"manifest.json\"", ",", "modelFile", ",", "infoFile", "]", ",", "\"Added '\"", "+", "name", "+", "\"' machine\"", ")", ";", "debug", "(", "\"A new machine with the name '%s' was successfully added\"", ",", "name", ")", ";", "}", ")", ";", "}" ]
Add a new machine to the repository @method addMachine @param {String} name The name of the new machine @returns {Promise}
[ "Add", "a", "new", "machine", "to", "the", "repository" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L254-L300
57,932
moraispgsi/fsm-core
src/indexOld.js
removeMachine
function removeMachine(name) { return co(function*(){ debug("Removing the machine"); let manifest = getManifest(); if(!manifest.machines[name]) { debug("Machine doesn't exists"); return; } let machinePath = machinesDirPath + "/" + name; let removedFileNames = _getFiles(machinePath).map((f)=>f.substring(repositoryPath.length + 1)); delete manifest.machines[name]; yield new Promise(function(resolve, reject) { rimraf(machinesDirPath + "/" + name, function () { resolve(); }); }).then(); debug("Setting the manifest"); setManifest(manifest); yield _commit(null, ["manifest.json"], "Removed '" + name + "' machine.", removedFileNames); return Object.keys(manifest.machines); }); }
javascript
function removeMachine(name) { return co(function*(){ debug("Removing the machine"); let manifest = getManifest(); if(!manifest.machines[name]) { debug("Machine doesn't exists"); return; } let machinePath = machinesDirPath + "/" + name; let removedFileNames = _getFiles(machinePath).map((f)=>f.substring(repositoryPath.length + 1)); delete manifest.machines[name]; yield new Promise(function(resolve, reject) { rimraf(machinesDirPath + "/" + name, function () { resolve(); }); }).then(); debug("Setting the manifest"); setManifest(manifest); yield _commit(null, ["manifest.json"], "Removed '" + name + "' machine.", removedFileNames); return Object.keys(manifest.machines); }); }
[ "function", "removeMachine", "(", "name", ")", "{", "return", "co", "(", "function", "*", "(", ")", "{", "debug", "(", "\"Removing the machine\"", ")", ";", "let", "manifest", "=", "getManifest", "(", ")", ";", "if", "(", "!", "manifest", ".", "machines", "[", "name", "]", ")", "{", "debug", "(", "\"Machine doesn't exists\"", ")", ";", "return", ";", "}", "let", "machinePath", "=", "machinesDirPath", "+", "\"/\"", "+", "name", ";", "let", "removedFileNames", "=", "_getFiles", "(", "machinePath", ")", ".", "map", "(", "(", "f", ")", "=>", "f", ".", "substring", "(", "repositoryPath", ".", "length", "+", "1", ")", ")", ";", "delete", "manifest", ".", "machines", "[", "name", "]", ";", "yield", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "rimraf", "(", "machinesDirPath", "+", "\"/\"", "+", "name", ",", "function", "(", ")", "{", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ".", "then", "(", ")", ";", "debug", "(", "\"Setting the manifest\"", ")", ";", "setManifest", "(", "manifest", ")", ";", "yield", "_commit", "(", "null", ",", "[", "\"manifest.json\"", "]", ",", "\"Removed '\"", "+", "name", "+", "\"' machine.\"", ",", "removedFileNames", ")", ";", "return", "Object", ".", "keys", "(", "manifest", ".", "machines", ")", ";", "}", ")", ";", "}" ]
Remove a machine from the repository @method removeMachine @param {String} name The name of the machine @returns {Promise}
[ "Remove", "a", "machine", "from", "the", "repository" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L308-L336
57,933
moraispgsi/fsm-core
src/indexOld.js
getVersionsKeys
function getVersionsKeys(machineName) { let manifest = getManifest(); if (!manifest.machines[machineName]) { throw new Error("Machine does not exists"); } return Object.keys(manifest.machines[machineName].versions); }
javascript
function getVersionsKeys(machineName) { let manifest = getManifest(); if (!manifest.machines[machineName]) { throw new Error("Machine does not exists"); } return Object.keys(manifest.machines[machineName].versions); }
[ "function", "getVersionsKeys", "(", "machineName", ")", "{", "let", "manifest", "=", "getManifest", "(", ")", ";", "if", "(", "!", "manifest", ".", "machines", "[", "machineName", "]", ")", "{", "throw", "new", "Error", "(", "\"Machine does not exists\"", ")", ";", "}", "return", "Object", ".", "keys", "(", "manifest", ".", "machines", "[", "machineName", "]", ".", "versions", ")", ";", "}" ]
Get the keys of all of the versions of machine in the repository @method getVersionsKeys @param {String} machineName The name of the machine to get the version's keys @returns {Array} An array with all the version's keys of the machine
[ "Get", "the", "keys", "of", "all", "of", "the", "versions", "of", "machine", "in", "the", "repository" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L344-L350
57,934
moraispgsi/fsm-core
src/indexOld.js
getVersionRoute
function getVersionRoute(machineName, versionKey) { let manifest = getManifest(); if (!manifest.machines[machineName]) { throw new Error("Machine does not exists"); } if (!manifest.machines[machineName].versions[versionKey]) { throw new Error("Version does not exists"); } return manifest.machines[machineName].versions[versionKey].route; }
javascript
function getVersionRoute(machineName, versionKey) { let manifest = getManifest(); if (!manifest.machines[machineName]) { throw new Error("Machine does not exists"); } if (!manifest.machines[machineName].versions[versionKey]) { throw new Error("Version does not exists"); } return manifest.machines[machineName].versions[versionKey].route; }
[ "function", "getVersionRoute", "(", "machineName", ",", "versionKey", ")", "{", "let", "manifest", "=", "getManifest", "(", ")", ";", "if", "(", "!", "manifest", ".", "machines", "[", "machineName", "]", ")", "{", "throw", "new", "Error", "(", "\"Machine does not exists\"", ")", ";", "}", "if", "(", "!", "manifest", ".", "machines", "[", "machineName", "]", ".", "versions", "[", "versionKey", "]", ")", "{", "throw", "new", "Error", "(", "\"Version does not exists\"", ")", ";", "}", "return", "manifest", ".", "machines", "[", "machineName", "]", ".", "versions", "[", "versionKey", "]", ".", "route", ";", "}" ]
Retrieve the version directory path @method getVersionRoute @param {String} machineName The name of the machine @param {String} versionKey The key of the version @returns {String} The route
[ "Retrieve", "the", "version", "directory", "path" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L359-L371
57,935
moraispgsi/fsm-core
src/indexOld.js
getVersionInfo
function getVersionInfo(machineName, versionKey) { let route = getVersionInfoRoute(machineName, versionKey); return jsonfile.readFileSync(repositoryPath + "/" + route); }
javascript
function getVersionInfo(machineName, versionKey) { let route = getVersionInfoRoute(machineName, versionKey); return jsonfile.readFileSync(repositoryPath + "/" + route); }
[ "function", "getVersionInfo", "(", "machineName", ",", "versionKey", ")", "{", "let", "route", "=", "getVersionInfoRoute", "(", "machineName", ",", "versionKey", ")", ";", "return", "jsonfile", ".", "readFileSync", "(", "repositoryPath", "+", "\"/\"", "+", "route", ")", ";", "}" ]
Retrieve the version info.json file as a JavasScript Object @method getVersionInfo @param {String} machineName The name of the machine @param {String} versionKey The key of the version @returns {Object} The info Object
[ "Retrieve", "the", "version", "info", ".", "json", "file", "as", "a", "JavasScript", "Object" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L402-L405
57,936
moraispgsi/fsm-core
src/indexOld.js
setVersionInfo
function setVersionInfo(machineName, versionKey, info, withCommit, message) { let route = getVersionInfoRoute(machineName, versionKey); let previousInfo = jsonfile.readFileSync(repositoryPath + "/" + route); if(previousInfo.isSealed) { throw new Error("Cannot change the version SCXML because the version is sealed.") } jsonfile.writeFileSync(repositoryPath + "/" + route, info, {spaces: 2}); if(withCommit) { return _commit(null, [route], message || "Changed the info for the " + versionKey + " of the '" + machineName + "' machine" ); } }
javascript
function setVersionInfo(machineName, versionKey, info, withCommit, message) { let route = getVersionInfoRoute(machineName, versionKey); let previousInfo = jsonfile.readFileSync(repositoryPath + "/" + route); if(previousInfo.isSealed) { throw new Error("Cannot change the version SCXML because the version is sealed.") } jsonfile.writeFileSync(repositoryPath + "/" + route, info, {spaces: 2}); if(withCommit) { return _commit(null, [route], message || "Changed the info for the " + versionKey + " of the '" + machineName + "' machine" ); } }
[ "function", "setVersionInfo", "(", "machineName", ",", "versionKey", ",", "info", ",", "withCommit", ",", "message", ")", "{", "let", "route", "=", "getVersionInfoRoute", "(", "machineName", ",", "versionKey", ")", ";", "let", "previousInfo", "=", "jsonfile", ".", "readFileSync", "(", "repositoryPath", "+", "\"/\"", "+", "route", ")", ";", "if", "(", "previousInfo", ".", "isSealed", ")", "{", "throw", "new", "Error", "(", "\"Cannot change the version SCXML because the version is sealed.\"", ")", "}", "jsonfile", ".", "writeFileSync", "(", "repositoryPath", "+", "\"/\"", "+", "route", ",", "info", ",", "{", "spaces", ":", "2", "}", ")", ";", "if", "(", "withCommit", ")", "{", "return", "_commit", "(", "null", ",", "[", "route", "]", ",", "message", "||", "\"Changed the info for the \"", "+", "versionKey", "+", "\" of the '\"", "+", "machineName", "+", "\"' machine\"", ")", ";", "}", "}" ]
Update the version info.json file using a JavasScript Object @method setVersionInfo @param {String} machineName The name of the machine @param {String} versionKey The key of the version @param {Object} info The info Object to save @param {boolean} withCommit If true commits the changes to the repository @param {String} message If supplied it is used as the message for the commit @returns {Promise} If withCommit is true, the function returns a Promise
[ "Update", "the", "version", "info", ".", "json", "file", "using", "a", "JavasScript", "Object" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L417-L432
57,937
moraispgsi/fsm-core
src/indexOld.js
addVersion
function addVersion(machineName) { return co(function*() { debug("Adding a new version to the '" + machineName + "' machine"); let manifest = getManifest(); if (!manifest.machines[machineName]) { throw new Error("Machine does not exists"); } let versions = manifest.machines[machineName].versions; let versionKeys = Object.keys(versions); let lastVersionKey = versionKeys[versionKeys.length - 1]; let lastVersion = versions[lastVersionKey]; let lastVersionInfoFile = lastVersion.route + "/info.json"; let lastVersionInfo = jsonfile.readFileSync(repositoryPath + "/" + lastVersionInfoFile); let lastVersionModelFile = lastVersion.route + '/model.scxml'; if(!lastVersionInfo.isSealed) { throw new Error("The last versions is not sealed yet"); } let newVersionKey = "version" + (versionKeys.length + 1); let versionDirPath = manifest.machines[machineName].route + "/versions/" + newVersionKey; manifest.machines[machineName].versions[newVersionKey] = { "route": versionDirPath, "instances": {} }; let versionInstancesDirPath = versionDirPath + "/instances"; let modelFile = versionDirPath + '/model.scxml'; let infoFile = versionDirPath + "/info.json"; debug("Creating the directories"); fs.mkdirSync(repositoryPath + "/" + versionDirPath); fs.mkdirSync(repositoryPath + "/" + versionInstancesDirPath); debug("Copying the previous version's model.scxml"); fs.copySync(repositoryPath + "/" + lastVersionModelFile, repositoryPath + "/" + modelFile); debug("Creating the version info.json file"); let infoVersion = { "isSealed": false }; jsonfile.writeFileSync(repositoryPath + "/" + infoFile, infoVersion); debug("Setting the manifest"); setManifest(manifest); yield _commit(null, ["manifest.json", modelFile, infoFile], "Created the "+newVersionKey+" for the '" + machineName + "' machine"); return newVersionKey; }); }
javascript
function addVersion(machineName) { return co(function*() { debug("Adding a new version to the '" + machineName + "' machine"); let manifest = getManifest(); if (!manifest.machines[machineName]) { throw new Error("Machine does not exists"); } let versions = manifest.machines[machineName].versions; let versionKeys = Object.keys(versions); let lastVersionKey = versionKeys[versionKeys.length - 1]; let lastVersion = versions[lastVersionKey]; let lastVersionInfoFile = lastVersion.route + "/info.json"; let lastVersionInfo = jsonfile.readFileSync(repositoryPath + "/" + lastVersionInfoFile); let lastVersionModelFile = lastVersion.route + '/model.scxml'; if(!lastVersionInfo.isSealed) { throw new Error("The last versions is not sealed yet"); } let newVersionKey = "version" + (versionKeys.length + 1); let versionDirPath = manifest.machines[machineName].route + "/versions/" + newVersionKey; manifest.machines[machineName].versions[newVersionKey] = { "route": versionDirPath, "instances": {} }; let versionInstancesDirPath = versionDirPath + "/instances"; let modelFile = versionDirPath + '/model.scxml'; let infoFile = versionDirPath + "/info.json"; debug("Creating the directories"); fs.mkdirSync(repositoryPath + "/" + versionDirPath); fs.mkdirSync(repositoryPath + "/" + versionInstancesDirPath); debug("Copying the previous version's model.scxml"); fs.copySync(repositoryPath + "/" + lastVersionModelFile, repositoryPath + "/" + modelFile); debug("Creating the version info.json file"); let infoVersion = { "isSealed": false }; jsonfile.writeFileSync(repositoryPath + "/" + infoFile, infoVersion); debug("Setting the manifest"); setManifest(manifest); yield _commit(null, ["manifest.json", modelFile, infoFile], "Created the "+newVersionKey+" for the '" + machineName + "' machine"); return newVersionKey; }); }
[ "function", "addVersion", "(", "machineName", ")", "{", "return", "co", "(", "function", "*", "(", ")", "{", "debug", "(", "\"Adding a new version to the '\"", "+", "machineName", "+", "\"' machine\"", ")", ";", "let", "manifest", "=", "getManifest", "(", ")", ";", "if", "(", "!", "manifest", ".", "machines", "[", "machineName", "]", ")", "{", "throw", "new", "Error", "(", "\"Machine does not exists\"", ")", ";", "}", "let", "versions", "=", "manifest", ".", "machines", "[", "machineName", "]", ".", "versions", ";", "let", "versionKeys", "=", "Object", ".", "keys", "(", "versions", ")", ";", "let", "lastVersionKey", "=", "versionKeys", "[", "versionKeys", ".", "length", "-", "1", "]", ";", "let", "lastVersion", "=", "versions", "[", "lastVersionKey", "]", ";", "let", "lastVersionInfoFile", "=", "lastVersion", ".", "route", "+", "\"/info.json\"", ";", "let", "lastVersionInfo", "=", "jsonfile", ".", "readFileSync", "(", "repositoryPath", "+", "\"/\"", "+", "lastVersionInfoFile", ")", ";", "let", "lastVersionModelFile", "=", "lastVersion", ".", "route", "+", "'/model.scxml'", ";", "if", "(", "!", "lastVersionInfo", ".", "isSealed", ")", "{", "throw", "new", "Error", "(", "\"The last versions is not sealed yet\"", ")", ";", "}", "let", "newVersionKey", "=", "\"version\"", "+", "(", "versionKeys", ".", "length", "+", "1", ")", ";", "let", "versionDirPath", "=", "manifest", ".", "machines", "[", "machineName", "]", ".", "route", "+", "\"/versions/\"", "+", "newVersionKey", ";", "manifest", ".", "machines", "[", "machineName", "]", ".", "versions", "[", "newVersionKey", "]", "=", "{", "\"route\"", ":", "versionDirPath", ",", "\"instances\"", ":", "{", "}", "}", ";", "let", "versionInstancesDirPath", "=", "versionDirPath", "+", "\"/instances\"", ";", "let", "modelFile", "=", "versionDirPath", "+", "'/model.scxml'", ";", "let", "infoFile", "=", "versionDirPath", "+", "\"/info.json\"", ";", "debug", "(", "\"Creating the directories\"", ")", ";", "fs", ".", "mkdirSync", "(", "repositoryPath", "+", "\"/\"", "+", "versionDirPath", ")", ";", "fs", ".", "mkdirSync", "(", "repositoryPath", "+", "\"/\"", "+", "versionInstancesDirPath", ")", ";", "debug", "(", "\"Copying the previous version's model.scxml\"", ")", ";", "fs", ".", "copySync", "(", "repositoryPath", "+", "\"/\"", "+", "lastVersionModelFile", ",", "repositoryPath", "+", "\"/\"", "+", "modelFile", ")", ";", "debug", "(", "\"Creating the version info.json file\"", ")", ";", "let", "infoVersion", "=", "{", "\"isSealed\"", ":", "false", "}", ";", "jsonfile", ".", "writeFileSync", "(", "repositoryPath", "+", "\"/\"", "+", "infoFile", ",", "infoVersion", ")", ";", "debug", "(", "\"Setting the manifest\"", ")", ";", "setManifest", "(", "manifest", ")", ";", "yield", "_commit", "(", "null", ",", "[", "\"manifest.json\"", ",", "modelFile", ",", "infoFile", "]", ",", "\"Created the \"", "+", "newVersionKey", "+", "\" for the '\"", "+", "machineName", "+", "\"' machine\"", ")", ";", "return", "newVersionKey", ";", "}", ")", ";", "}" ]
Add a new version to a machine @method addVersion @param {String} machineName The name of the machine @returns {Promise} The version key
[ "Add", "a", "new", "version", "to", "a", "machine" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L440-L492
57,938
moraispgsi/fsm-core
src/indexOld.js
sealVersion
function sealVersion(machineName, versionKey) { return co(function*(){ debug("Attempting to seal the version '%s' of the machine '%s'", versionKey, machineName); let info = yield getVersionInfo(machineName, versionKey); if(info.isSealed) { throw new Error("Version it already sealed"); } debug("Getting manifest"); let manifest = getManifest(); let model = getVersionSCXML(machineName, versionKey); let isValid = isSCXMLValid(model); if(!isValid) { throw new Error("The model is not valid."); } info.isSealed = true; setVersionInfo(machineName, versionKey, info); debug("The version '%s' of the machine '%s' was sealed successfully", versionKey, machineName); }); }
javascript
function sealVersion(machineName, versionKey) { return co(function*(){ debug("Attempting to seal the version '%s' of the machine '%s'", versionKey, machineName); let info = yield getVersionInfo(machineName, versionKey); if(info.isSealed) { throw new Error("Version it already sealed"); } debug("Getting manifest"); let manifest = getManifest(); let model = getVersionSCXML(machineName, versionKey); let isValid = isSCXMLValid(model); if(!isValid) { throw new Error("The model is not valid."); } info.isSealed = true; setVersionInfo(machineName, versionKey, info); debug("The version '%s' of the machine '%s' was sealed successfully", versionKey, machineName); }); }
[ "function", "sealVersion", "(", "machineName", ",", "versionKey", ")", "{", "return", "co", "(", "function", "*", "(", ")", "{", "debug", "(", "\"Attempting to seal the version '%s' of the machine '%s'\"", ",", "versionKey", ",", "machineName", ")", ";", "let", "info", "=", "yield", "getVersionInfo", "(", "machineName", ",", "versionKey", ")", ";", "if", "(", "info", ".", "isSealed", ")", "{", "throw", "new", "Error", "(", "\"Version it already sealed\"", ")", ";", "}", "debug", "(", "\"Getting manifest\"", ")", ";", "let", "manifest", "=", "getManifest", "(", ")", ";", "let", "model", "=", "getVersionSCXML", "(", "machineName", ",", "versionKey", ")", ";", "let", "isValid", "=", "isSCXMLValid", "(", "model", ")", ";", "if", "(", "!", "isValid", ")", "{", "throw", "new", "Error", "(", "\"The model is not valid.\"", ")", ";", "}", "info", ".", "isSealed", "=", "true", ";", "setVersionInfo", "(", "machineName", ",", "versionKey", ",", "info", ")", ";", "debug", "(", "\"The version '%s' of the machine '%s' was sealed successfully\"", ",", "versionKey", ",", "machineName", ")", ";", "}", ")", ";", "}" ]
Seal a version of a machine @method addMachine @param {String} machineName The name of the machine @param {String} versionKey The key of the version @returns {Promise}
[ "Seal", "a", "version", "of", "a", "machine" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L501-L523
57,939
moraispgsi/fsm-core
src/indexOld.js
getVersionSCXML
function getVersionSCXML(machineName, versionKey) { let route = getVersionModelRoute(machineName, versionKey); return fs.readFileSync(repositoryPath + "/" + route).toString('utf8'); }
javascript
function getVersionSCXML(machineName, versionKey) { let route = getVersionModelRoute(machineName, versionKey); return fs.readFileSync(repositoryPath + "/" + route).toString('utf8'); }
[ "function", "getVersionSCXML", "(", "machineName", ",", "versionKey", ")", "{", "let", "route", "=", "getVersionModelRoute", "(", "machineName", ",", "versionKey", ")", ";", "return", "fs", ".", "readFileSync", "(", "repositoryPath", "+", "\"/\"", "+", "route", ")", ".", "toString", "(", "'utf8'", ")", ";", "}" ]
Retrieve the version model.scxml file as a String @method getVersionSCXML @param {String} machineName The name of the machine @param {String} versionKey The key of the version @returns {String} The model
[ "Retrieve", "the", "version", "model", ".", "scxml", "file", "as", "a", "String" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L533-L536
57,940
moraispgsi/fsm-core
src/indexOld.js
setVersionSCXML
function setVersionSCXML(machineName, versionKey, model, withCommit, message) { let route = getVersionInfoRoute(machineName, versionKey); let previousInfo = jsonfile.readFileSync(repositoryPath + "/" + route); if(previousInfo.isSealed) { throw new Error("Cannot change the version SCXML because the version is sealed.") } let modelRoute = getVersionModelRoute(machineName, versionKey); fs.writeFileSync(repositoryPath + "/" + modelRoute, model); if(withCommit) { return _commit(null, [modelRoute], "Changed the model.scxml for the " + versionKey + " of the '" + machineName + "' machine"); } }
javascript
function setVersionSCXML(machineName, versionKey, model, withCommit, message) { let route = getVersionInfoRoute(machineName, versionKey); let previousInfo = jsonfile.readFileSync(repositoryPath + "/" + route); if(previousInfo.isSealed) { throw new Error("Cannot change the version SCXML because the version is sealed.") } let modelRoute = getVersionModelRoute(machineName, versionKey); fs.writeFileSync(repositoryPath + "/" + modelRoute, model); if(withCommit) { return _commit(null, [modelRoute], "Changed the model.scxml for the " + versionKey + " of the '" + machineName + "' machine"); } }
[ "function", "setVersionSCXML", "(", "machineName", ",", "versionKey", ",", "model", ",", "withCommit", ",", "message", ")", "{", "let", "route", "=", "getVersionInfoRoute", "(", "machineName", ",", "versionKey", ")", ";", "let", "previousInfo", "=", "jsonfile", ".", "readFileSync", "(", "repositoryPath", "+", "\"/\"", "+", "route", ")", ";", "if", "(", "previousInfo", ".", "isSealed", ")", "{", "throw", "new", "Error", "(", "\"Cannot change the version SCXML because the version is sealed.\"", ")", "}", "let", "modelRoute", "=", "getVersionModelRoute", "(", "machineName", ",", "versionKey", ")", ";", "fs", ".", "writeFileSync", "(", "repositoryPath", "+", "\"/\"", "+", "modelRoute", ",", "model", ")", ";", "if", "(", "withCommit", ")", "{", "return", "_commit", "(", "null", ",", "[", "modelRoute", "]", ",", "\"Changed the model.scxml for the \"", "+", "versionKey", "+", "\" of the '\"", "+", "machineName", "+", "\"' machine\"", ")", ";", "}", "}" ]
Update the version model.scxml file using a String @method setVersionSCXML @param {String} model The model @param {String} machineName The name of the machine @param {String} versionKey The key of the version @param {boolean} withCommit If true commits the changes to the repository @param {String} message If supplied it is used as the message for the commit @returns {Promise} If withCommit is true, the function returns a Promise
[ "Update", "the", "version", "model", ".", "scxml", "file", "using", "a", "String" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L548-L562
57,941
moraispgsi/fsm-core
src/indexOld.js
isSCXMLValid
function isSCXMLValid(model){ return new Promise(function(resolve, reject) { if(model === "") { reject("Model is empty"); return; } validator.validateXML(model, __dirname + '/xmlSchemas/scxml.xsd', function(err, result) { if (err) { reject(err); return; } resolve(result.valid); }) }); }
javascript
function isSCXMLValid(model){ return new Promise(function(resolve, reject) { if(model === "") { reject("Model is empty"); return; } validator.validateXML(model, __dirname + '/xmlSchemas/scxml.xsd', function(err, result) { if (err) { reject(err); return; } resolve(result.valid); }) }); }
[ "function", "isSCXMLValid", "(", "model", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "model", "===", "\"\"", ")", "{", "reject", "(", "\"Model is empty\"", ")", ";", "return", ";", "}", "validator", ".", "validateXML", "(", "model", ",", "__dirname", "+", "'/xmlSchemas/scxml.xsd'", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "return", ";", "}", "resolve", "(", "result", ".", "valid", ")", ";", "}", ")", "}", ")", ";", "}" ]
Validates SCXML markup as a string @method isSCXMLValid @param {String} model A string with the SCXML document to validate @returns {Promise} True if the SCXML is valid false otherwise
[ "Validates", "SCXML", "markup", "as", "a", "string" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L570-L585
57,942
moraispgsi/fsm-core
src/indexOld.js
getInstancesKeys
function getInstancesKeys(machineName, versionKey){ let manifest = getManifest(); let machine = manifest.machines[machineName]; if (!machine) { throw new Error("Machine does not exists"); } let version = machine.versions[versionKey]; if (!version) { throw new Error("Version does not exists"); } return Object.keys(version.instances); }
javascript
function getInstancesKeys(machineName, versionKey){ let manifest = getManifest(); let machine = manifest.machines[machineName]; if (!machine) { throw new Error("Machine does not exists"); } let version = machine.versions[versionKey]; if (!version) { throw new Error("Version does not exists"); } return Object.keys(version.instances); }
[ "function", "getInstancesKeys", "(", "machineName", ",", "versionKey", ")", "{", "let", "manifest", "=", "getManifest", "(", ")", ";", "let", "machine", "=", "manifest", ".", "machines", "[", "machineName", "]", ";", "if", "(", "!", "machine", ")", "{", "throw", "new", "Error", "(", "\"Machine does not exists\"", ")", ";", "}", "let", "version", "=", "machine", ".", "versions", "[", "versionKey", "]", ";", "if", "(", "!", "version", ")", "{", "throw", "new", "Error", "(", "\"Version does not exists\"", ")", ";", "}", "return", "Object", ".", "keys", "(", "version", ".", "instances", ")", ";", "}" ]
Gets the keys of all of the instances of a version of the machine in the repository @method getInstancesKeys @param {String} machineName The name of the machine to get the instances's keys @param {String} versionKey The key of the version to get the instances's keys @returns {Array} An array with all the instance's keys of the the version
[ "Gets", "the", "keys", "of", "all", "of", "the", "instances", "of", "a", "version", "of", "the", "machine", "in", "the", "repository" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L594-L609
57,943
moraispgsi/fsm-core
src/indexOld.js
getInstanceRoute
function getInstanceRoute(machineName, versionKey, instanceKey){ let manifest = getManifest(); let machine = manifest.machines[machineName]; if (!machine) { throw new Error("Machine does not exists"); } let version = machine.versions[versionKey]; if (!version) { throw new Error("Version does not exists"); } let instance = version.instances[instanceKey]; if (!instance) { throw new Error("Instance does not exists"); } return instance.route; }
javascript
function getInstanceRoute(machineName, versionKey, instanceKey){ let manifest = getManifest(); let machine = manifest.machines[machineName]; if (!machine) { throw new Error("Machine does not exists"); } let version = machine.versions[versionKey]; if (!version) { throw new Error("Version does not exists"); } let instance = version.instances[instanceKey]; if (!instance) { throw new Error("Instance does not exists"); } return instance.route; }
[ "function", "getInstanceRoute", "(", "machineName", ",", "versionKey", ",", "instanceKey", ")", "{", "let", "manifest", "=", "getManifest", "(", ")", ";", "let", "machine", "=", "manifest", ".", "machines", "[", "machineName", "]", ";", "if", "(", "!", "machine", ")", "{", "throw", "new", "Error", "(", "\"Machine does not exists\"", ")", ";", "}", "let", "version", "=", "machine", ".", "versions", "[", "versionKey", "]", ";", "if", "(", "!", "version", ")", "{", "throw", "new", "Error", "(", "\"Version does not exists\"", ")", ";", "}", "let", "instance", "=", "version", ".", "instances", "[", "instanceKey", "]", ";", "if", "(", "!", "instance", ")", "{", "throw", "new", "Error", "(", "\"Instance does not exists\"", ")", ";", "}", "return", "instance", ".", "route", ";", "}" ]
Retrieve the instance's directory path @method getInstanceRoute @param {String} machineName The name of the machine @param {String} versionKey The key of the version @param {String} instanceKey The key of the instance @returns {String} The route
[ "Retrieve", "the", "instance", "s", "directory", "path" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L619-L639
57,944
moraispgsi/fsm-core
src/indexOld.js
getInstanceInfo
function getInstanceInfo(machineName, versionKey, instanceKey) { let route = getInstanceInfoRoute(machineName, versionKey, instanceKey); return jsonfile.readFileSync(repositoryPath + "/" + route); }
javascript
function getInstanceInfo(machineName, versionKey, instanceKey) { let route = getInstanceInfoRoute(machineName, versionKey, instanceKey); return jsonfile.readFileSync(repositoryPath + "/" + route); }
[ "function", "getInstanceInfo", "(", "machineName", ",", "versionKey", ",", "instanceKey", ")", "{", "let", "route", "=", "getInstanceInfoRoute", "(", "machineName", ",", "versionKey", ",", "instanceKey", ")", ";", "return", "jsonfile", ".", "readFileSync", "(", "repositoryPath", "+", "\"/\"", "+", "route", ")", ";", "}" ]
Retrieve the instance's info.json file as a JavasScript Object @method getInstanceInfo @param {String} machineName The name of the machine @param {String} versionKey The key of the version @param {String} instanceKey The key of the instance @returns {Object} The info Object
[ "Retrieve", "the", "instance", "s", "info", ".", "json", "file", "as", "a", "JavasScript", "Object" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L661-L664
57,945
moraispgsi/fsm-core
src/indexOld.js
setInstanceInfo
function setInstanceInfo(machineName, versionKey, instanceKey, info, withCommit, message) { let route = getInstanceInfoRoute(machineName, versionKey, instanceKey); jsonfile.writeFileSync(repositoryPath + "/" + route, info, {spaces: 2}); if(withCommit) { return _commit(null, [route], message || "Changed the info for the " + instanceKey + " of the " + versionKey + " of the '" + machineName + "' machine"); } }
javascript
function setInstanceInfo(machineName, versionKey, instanceKey, info, withCommit, message) { let route = getInstanceInfoRoute(machineName, versionKey, instanceKey); jsonfile.writeFileSync(repositoryPath + "/" + route, info, {spaces: 2}); if(withCommit) { return _commit(null, [route], message || "Changed the info for the " + instanceKey + " of the " + versionKey + " of the '" + machineName + "' machine"); } }
[ "function", "setInstanceInfo", "(", "machineName", ",", "versionKey", ",", "instanceKey", ",", "info", ",", "withCommit", ",", "message", ")", "{", "let", "route", "=", "getInstanceInfoRoute", "(", "machineName", ",", "versionKey", ",", "instanceKey", ")", ";", "jsonfile", ".", "writeFileSync", "(", "repositoryPath", "+", "\"/\"", "+", "route", ",", "info", ",", "{", "spaces", ":", "2", "}", ")", ";", "if", "(", "withCommit", ")", "{", "return", "_commit", "(", "null", ",", "[", "route", "]", ",", "message", "||", "\"Changed the info for the \"", "+", "instanceKey", "+", "\" of the \"", "+", "versionKey", "+", "\" of the '\"", "+", "machineName", "+", "\"' machine\"", ")", ";", "}", "}" ]
Update the instance's info.json file using a JavasScript Object @method setInstanceInfo @param {String} machineName The name of the machine @param {String} versionKey The key of the version @param {String} instanceKey The key of the instance @param {Object} info The info Object to save @param {boolean} withCommit If true commits the changes to the repository @param {String} message If supplied it is used as the message for the commit @returns {Promise} If withCommit is true, the function returns a Promise
[ "Update", "the", "instance", "s", "info", ".", "json", "file", "using", "a", "JavasScript", "Object" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L677-L688
57,946
moraispgsi/fsm-core
src/indexOld.js
addInstance
function addInstance(machineName, versionKey) { return co(function*() { debug("Adding a new instance to the " + versionKey + " of the '" + machineName + "' machine"); let manifest = getManifest(); let machine = manifest.machines[machineName]; if (!machine) { throw new Error("Machine does not exists"); } let version = machine.versions[versionKey]; if (!version) { throw new Error("Version does not exists"); } let versionInfo = getVersionInfo(machineName, versionKey); if(!versionInfo.isSealed) { throw new Error("The version is not sealed yet"); } let newInstanceKey = "instance" + (Object.keys(version.instances).length + 1); let instanceDirPath = version.route + "/instances/" + newInstanceKey; let instanceSnapshotsDirPath = instanceDirPath + "/snapshots"; version.instances[newInstanceKey] = { "route": instanceDirPath, "snapshots": {} }; let infoFile = instanceDirPath + "/info.json"; debug("Creating the directories"); fs.mkdirSync(repositoryPath + "/" + instanceDirPath); fs.mkdirSync(repositoryPath + "/" + instanceSnapshotsDirPath); debug("Creating the instance info.json file"); let info = { "hasStarted": false, "hasEnded": false }; jsonfile.writeFileSync(repositoryPath + "/" + infoFile, info); debug("Setting the manifest"); setManifest(manifest); yield _commit(null, ["manifest.json", infoFile], "Created the "+newInstanceKey+" for the "+versionKey+" of the '" + machineName + "' machine"); return newInstanceKey; }); }
javascript
function addInstance(machineName, versionKey) { return co(function*() { debug("Adding a new instance to the " + versionKey + " of the '" + machineName + "' machine"); let manifest = getManifest(); let machine = manifest.machines[machineName]; if (!machine) { throw new Error("Machine does not exists"); } let version = machine.versions[versionKey]; if (!version) { throw new Error("Version does not exists"); } let versionInfo = getVersionInfo(machineName, versionKey); if(!versionInfo.isSealed) { throw new Error("The version is not sealed yet"); } let newInstanceKey = "instance" + (Object.keys(version.instances).length + 1); let instanceDirPath = version.route + "/instances/" + newInstanceKey; let instanceSnapshotsDirPath = instanceDirPath + "/snapshots"; version.instances[newInstanceKey] = { "route": instanceDirPath, "snapshots": {} }; let infoFile = instanceDirPath + "/info.json"; debug("Creating the directories"); fs.mkdirSync(repositoryPath + "/" + instanceDirPath); fs.mkdirSync(repositoryPath + "/" + instanceSnapshotsDirPath); debug("Creating the instance info.json file"); let info = { "hasStarted": false, "hasEnded": false }; jsonfile.writeFileSync(repositoryPath + "/" + infoFile, info); debug("Setting the manifest"); setManifest(manifest); yield _commit(null, ["manifest.json", infoFile], "Created the "+newInstanceKey+" for the "+versionKey+" of the '" + machineName + "' machine"); return newInstanceKey; }); }
[ "function", "addInstance", "(", "machineName", ",", "versionKey", ")", "{", "return", "co", "(", "function", "*", "(", ")", "{", "debug", "(", "\"Adding a new instance to the \"", "+", "versionKey", "+", "\" of the '\"", "+", "machineName", "+", "\"' machine\"", ")", ";", "let", "manifest", "=", "getManifest", "(", ")", ";", "let", "machine", "=", "manifest", ".", "machines", "[", "machineName", "]", ";", "if", "(", "!", "machine", ")", "{", "throw", "new", "Error", "(", "\"Machine does not exists\"", ")", ";", "}", "let", "version", "=", "machine", ".", "versions", "[", "versionKey", "]", ";", "if", "(", "!", "version", ")", "{", "throw", "new", "Error", "(", "\"Version does not exists\"", ")", ";", "}", "let", "versionInfo", "=", "getVersionInfo", "(", "machineName", ",", "versionKey", ")", ";", "if", "(", "!", "versionInfo", ".", "isSealed", ")", "{", "throw", "new", "Error", "(", "\"The version is not sealed yet\"", ")", ";", "}", "let", "newInstanceKey", "=", "\"instance\"", "+", "(", "Object", ".", "keys", "(", "version", ".", "instances", ")", ".", "length", "+", "1", ")", ";", "let", "instanceDirPath", "=", "version", ".", "route", "+", "\"/instances/\"", "+", "newInstanceKey", ";", "let", "instanceSnapshotsDirPath", "=", "instanceDirPath", "+", "\"/snapshots\"", ";", "version", ".", "instances", "[", "newInstanceKey", "]", "=", "{", "\"route\"", ":", "instanceDirPath", ",", "\"snapshots\"", ":", "{", "}", "}", ";", "let", "infoFile", "=", "instanceDirPath", "+", "\"/info.json\"", ";", "debug", "(", "\"Creating the directories\"", ")", ";", "fs", ".", "mkdirSync", "(", "repositoryPath", "+", "\"/\"", "+", "instanceDirPath", ")", ";", "fs", ".", "mkdirSync", "(", "repositoryPath", "+", "\"/\"", "+", "instanceSnapshotsDirPath", ")", ";", "debug", "(", "\"Creating the instance info.json file\"", ")", ";", "let", "info", "=", "{", "\"hasStarted\"", ":", "false", ",", "\"hasEnded\"", ":", "false", "}", ";", "jsonfile", ".", "writeFileSync", "(", "repositoryPath", "+", "\"/\"", "+", "infoFile", ",", "info", ")", ";", "debug", "(", "\"Setting the manifest\"", ")", ";", "setManifest", "(", "manifest", ")", ";", "yield", "_commit", "(", "null", ",", "[", "\"manifest.json\"", ",", "infoFile", "]", ",", "\"Created the \"", "+", "newInstanceKey", "+", "\" for the \"", "+", "versionKey", "+", "\" of the '\"", "+", "machineName", "+", "\"' machine\"", ")", ";", "return", "newInstanceKey", ";", "}", ")", ";", "}" ]
Add a new instance to a version of a machine @method addInstance @param {String} machineName The name of the machine @param {String} versionKey The key of the version @returns {Promise} The instance key
[ "Add", "a", "new", "instance", "to", "a", "version", "of", "a", "machine" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L697-L746
57,947
moraispgsi/fsm-core
src/indexOld.js
getSnapshotsKeys
function getSnapshotsKeys(machineName, versionKey, instanceKey){ let manifest = getManifest(); let machine = manifest.machines[machineName]; if (!machine) { throw new Error("Machine does not exists"); } let version = machine.versions[versionKey]; if (!version) { throw new Error("Version does not exists"); } let instance = version.instances[instanceKey]; if (!instance) { throw new Error("Instance does not exists"); } return Object.keys(instance.snapshots); }
javascript
function getSnapshotsKeys(machineName, versionKey, instanceKey){ let manifest = getManifest(); let machine = manifest.machines[machineName]; if (!machine) { throw new Error("Machine does not exists"); } let version = machine.versions[versionKey]; if (!version) { throw new Error("Version does not exists"); } let instance = version.instances[instanceKey]; if (!instance) { throw new Error("Instance does not exists"); } return Object.keys(instance.snapshots); }
[ "function", "getSnapshotsKeys", "(", "machineName", ",", "versionKey", ",", "instanceKey", ")", "{", "let", "manifest", "=", "getManifest", "(", ")", ";", "let", "machine", "=", "manifest", ".", "machines", "[", "machineName", "]", ";", "if", "(", "!", "machine", ")", "{", "throw", "new", "Error", "(", "\"Machine does not exists\"", ")", ";", "}", "let", "version", "=", "machine", ".", "versions", "[", "versionKey", "]", ";", "if", "(", "!", "version", ")", "{", "throw", "new", "Error", "(", "\"Version does not exists\"", ")", ";", "}", "let", "instance", "=", "version", ".", "instances", "[", "instanceKey", "]", ";", "if", "(", "!", "instance", ")", "{", "throw", "new", "Error", "(", "\"Instance does not exists\"", ")", ";", "}", "return", "Object", ".", "keys", "(", "instance", ".", "snapshots", ")", ";", "}" ]
Gets the keys of all of the snapshots of the instance of a version of the machine in the repository @method getSnapshotsKeys @param {String} machineName The name of the machine to get the snapshots's keys @param {String} versionKey The key of the version to get the snapshots's keys @param {String} instanceKey The key of the instance to get the snapshot's keys @returns {Array} An array with all the snapshot's keys of the instance
[ "Gets", "the", "keys", "of", "all", "of", "the", "snapshots", "of", "the", "instance", "of", "a", "version", "of", "the", "machine", "in", "the", "repository" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L756-L776
57,948
moraispgsi/fsm-core
src/indexOld.js
getSnapshotRoute
function getSnapshotRoute(machineName, versionKey, instanceKey, snapshotKey){ let manifest = getManifest(); let machine = manifest.machines[machineName]; if (!machine) { throw new Error("Machine does not exists"); } let version = machine.versions[versionKey]; if (!version) { throw new Error("Version does not exists"); } let instance = version.instances[instanceKey]; if (!instance) { throw new Error("Instance does not exists"); } let snapshot = instance.snapshots[snapshotKey]; if (!snapshot) { throw new Error("Snapshot does not exists"); } return snapshot.route; }
javascript
function getSnapshotRoute(machineName, versionKey, instanceKey, snapshotKey){ let manifest = getManifest(); let machine = manifest.machines[machineName]; if (!machine) { throw new Error("Machine does not exists"); } let version = machine.versions[versionKey]; if (!version) { throw new Error("Version does not exists"); } let instance = version.instances[instanceKey]; if (!instance) { throw new Error("Instance does not exists"); } let snapshot = instance.snapshots[snapshotKey]; if (!snapshot) { throw new Error("Snapshot does not exists"); } return snapshot.route; }
[ "function", "getSnapshotRoute", "(", "machineName", ",", "versionKey", ",", "instanceKey", ",", "snapshotKey", ")", "{", "let", "manifest", "=", "getManifest", "(", ")", ";", "let", "machine", "=", "manifest", ".", "machines", "[", "machineName", "]", ";", "if", "(", "!", "machine", ")", "{", "throw", "new", "Error", "(", "\"Machine does not exists\"", ")", ";", "}", "let", "version", "=", "machine", ".", "versions", "[", "versionKey", "]", ";", "if", "(", "!", "version", ")", "{", "throw", "new", "Error", "(", "\"Version does not exists\"", ")", ";", "}", "let", "instance", "=", "version", ".", "instances", "[", "instanceKey", "]", ";", "if", "(", "!", "instance", ")", "{", "throw", "new", "Error", "(", "\"Instance does not exists\"", ")", ";", "}", "let", "snapshot", "=", "instance", ".", "snapshots", "[", "snapshotKey", "]", ";", "if", "(", "!", "snapshot", ")", "{", "throw", "new", "Error", "(", "\"Snapshot does not exists\"", ")", ";", "}", "return", "snapshot", ".", "route", ";", "}" ]
Retrieve the snapshot's directory path @method getSnapshotRoute @param {String} machineName The name of the machine @param {String} versionKey The key of the version @param {String} instanceKey The key of the instance @param {String} snapshotKey The key of the snapshot @returns {String} The route
[ "Retrieve", "the", "snapshot", "s", "directory", "path" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L787-L812
57,949
moraispgsi/fsm-core
src/indexOld.js
getSnapshotInfoRoute
function getSnapshotInfoRoute(machineName, versionKey, instanceKey, snapshotKey) { return getSnapshotRoute(machineName, versionKey, instanceKey, snapshotKey) + "/info.json"; }
javascript
function getSnapshotInfoRoute(machineName, versionKey, instanceKey, snapshotKey) { return getSnapshotRoute(machineName, versionKey, instanceKey, snapshotKey) + "/info.json"; }
[ "function", "getSnapshotInfoRoute", "(", "machineName", ",", "versionKey", ",", "instanceKey", ",", "snapshotKey", ")", "{", "return", "getSnapshotRoute", "(", "machineName", ",", "versionKey", ",", "instanceKey", ",", "snapshotKey", ")", "+", "\"/info.json\"", ";", "}" ]
Retrieve the snapshot's info.json path @method getSnapshotInfoRoute @param {String} machineName The name of the machine @param {String} versionKey The key of the version @param {String} instanceKey The key of the instance @param {String} snapshotKey The key of the snapshot @returns {String} The route
[ "Retrieve", "the", "snapshot", "s", "info", ".", "json", "path" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L823-L825
57,950
moraispgsi/fsm-core
src/indexOld.js
getSnapshotInfo
function getSnapshotInfo(machineName, versionKey, instanceKey, snapshotKey) { let route = getSnapshotInfoRoute(machineName, versionKey, instanceKey, snapshotKey); return jsonfile.readFileSync(repositoryPath + "/" + route); }
javascript
function getSnapshotInfo(machineName, versionKey, instanceKey, snapshotKey) { let route = getSnapshotInfoRoute(machineName, versionKey, instanceKey, snapshotKey); return jsonfile.readFileSync(repositoryPath + "/" + route); }
[ "function", "getSnapshotInfo", "(", "machineName", ",", "versionKey", ",", "instanceKey", ",", "snapshotKey", ")", "{", "let", "route", "=", "getSnapshotInfoRoute", "(", "machineName", ",", "versionKey", ",", "instanceKey", ",", "snapshotKey", ")", ";", "return", "jsonfile", ".", "readFileSync", "(", "repositoryPath", "+", "\"/\"", "+", "route", ")", ";", "}" ]
Retrieve the snapshot's info.json file as a JavasScript Object @method getSnapshotInfo @param {String} machineName The name of the machine @param {String} versionKey The key of the version @param {String} instanceKey The key of the instance @param {String} snapshotKey The key of the snapshot @returns {Object} The info Object
[ "Retrieve", "the", "snapshot", "s", "info", ".", "json", "file", "as", "a", "JavasScript", "Object" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L836-L839
57,951
moraispgsi/fsm-core
src/indexOld.js
addSnapshot
function addSnapshot(machineName, versionKey, instanceKey, info) { return co(function*() { debug("Adding a new snapshot to the " + instanceKey + " of the " + versionKey + " of the '" + machineName + "' machine"); let manifest = getManifest(); let machine = manifest.machines[machineName]; if (!machine) { throw new Error("Machine does not exists"); } let version = machine.versions[versionKey]; if (!version) { throw new Error("Version does not exists"); } let instance = version.instances[instanceKey]; if (!instance) { throw new Error("Instance does not exists"); } let newSnapshotKey = "snapshot" + (Object.keys(instance.snapshots).length + 1); let snapshotDirPath = instance.route + "/snapshots/" + newSnapshotKey; instance.snapshots[newSnapshotKey] = { "route": snapshotDirPath }; let infoFile = snapshotDirPath + "/info.json"; debug("Creating the directories"); fs.mkdirSync(repositoryPath + "/" + snapshotDirPath); debug("Creating the snapshot info.json file"); let info = { }; jsonfile.writeFileSync(repositoryPath + "/" + infoFile, info); debug("Setting the manifest"); setManifest(manifest); yield _commit(null, ["manifest.json", infoFile], "Created the "+newSnapshotKey+" for the "+instanceKey+" of the "+ versionKey+" of the '" + machineName + "' machine"); return newSnapshotKey; }); }
javascript
function addSnapshot(machineName, versionKey, instanceKey, info) { return co(function*() { debug("Adding a new snapshot to the " + instanceKey + " of the " + versionKey + " of the '" + machineName + "' machine"); let manifest = getManifest(); let machine = manifest.machines[machineName]; if (!machine) { throw new Error("Machine does not exists"); } let version = machine.versions[versionKey]; if (!version) { throw new Error("Version does not exists"); } let instance = version.instances[instanceKey]; if (!instance) { throw new Error("Instance does not exists"); } let newSnapshotKey = "snapshot" + (Object.keys(instance.snapshots).length + 1); let snapshotDirPath = instance.route + "/snapshots/" + newSnapshotKey; instance.snapshots[newSnapshotKey] = { "route": snapshotDirPath }; let infoFile = snapshotDirPath + "/info.json"; debug("Creating the directories"); fs.mkdirSync(repositoryPath + "/" + snapshotDirPath); debug("Creating the snapshot info.json file"); let info = { }; jsonfile.writeFileSync(repositoryPath + "/" + infoFile, info); debug("Setting the manifest"); setManifest(manifest); yield _commit(null, ["manifest.json", infoFile], "Created the "+newSnapshotKey+" for the "+instanceKey+" of the "+ versionKey+" of the '" + machineName + "' machine"); return newSnapshotKey; }); }
[ "function", "addSnapshot", "(", "machineName", ",", "versionKey", ",", "instanceKey", ",", "info", ")", "{", "return", "co", "(", "function", "*", "(", ")", "{", "debug", "(", "\"Adding a new snapshot to the \"", "+", "instanceKey", "+", "\" of the \"", "+", "versionKey", "+", "\" of the '\"", "+", "machineName", "+", "\"' machine\"", ")", ";", "let", "manifest", "=", "getManifest", "(", ")", ";", "let", "machine", "=", "manifest", ".", "machines", "[", "machineName", "]", ";", "if", "(", "!", "machine", ")", "{", "throw", "new", "Error", "(", "\"Machine does not exists\"", ")", ";", "}", "let", "version", "=", "machine", ".", "versions", "[", "versionKey", "]", ";", "if", "(", "!", "version", ")", "{", "throw", "new", "Error", "(", "\"Version does not exists\"", ")", ";", "}", "let", "instance", "=", "version", ".", "instances", "[", "instanceKey", "]", ";", "if", "(", "!", "instance", ")", "{", "throw", "new", "Error", "(", "\"Instance does not exists\"", ")", ";", "}", "let", "newSnapshotKey", "=", "\"snapshot\"", "+", "(", "Object", ".", "keys", "(", "instance", ".", "snapshots", ")", ".", "length", "+", "1", ")", ";", "let", "snapshotDirPath", "=", "instance", ".", "route", "+", "\"/snapshots/\"", "+", "newSnapshotKey", ";", "instance", ".", "snapshots", "[", "newSnapshotKey", "]", "=", "{", "\"route\"", ":", "snapshotDirPath", "}", ";", "let", "infoFile", "=", "snapshotDirPath", "+", "\"/info.json\"", ";", "debug", "(", "\"Creating the directories\"", ")", ";", "fs", ".", "mkdirSync", "(", "repositoryPath", "+", "\"/\"", "+", "snapshotDirPath", ")", ";", "debug", "(", "\"Creating the snapshot info.json file\"", ")", ";", "let", "info", "=", "{", "}", ";", "jsonfile", ".", "writeFileSync", "(", "repositoryPath", "+", "\"/\"", "+", "infoFile", ",", "info", ")", ";", "debug", "(", "\"Setting the manifest\"", ")", ";", "setManifest", "(", "manifest", ")", ";", "yield", "_commit", "(", "null", ",", "[", "\"manifest.json\"", ",", "infoFile", "]", ",", "\"Created the \"", "+", "newSnapshotKey", "+", "\" for the \"", "+", "instanceKey", "+", "\" of the \"", "+", "versionKey", "+", "\" of the '\"", "+", "machineName", "+", "\"' machine\"", ")", ";", "return", "newSnapshotKey", ";", "}", ")", ";", "}" ]
Add a new snapshot to an instance of a version of a machine @method addSnapshot @param {String} machineName The name of the machine @param {String} versionKey The key of the version @param {String} instanceKey The key of the instance @param {Object} info The info Object @returns {Promise} The instance key
[ "Add", "a", "new", "snapshot", "to", "an", "instance", "of", "a", "version", "of", "a", "machine" ]
c07e7c1509b823d5c438a26b29fbf8f40e1e8be7
https://github.com/moraispgsi/fsm-core/blob/c07e7c1509b823d5c438a26b29fbf8f40e1e8be7/src/indexOld.js#L850-L896
57,952
ethul/grunt-roy
tasks/roy.js
writeSourceMap
function writeSourceMap(srcpath, destpath, options, f) { var path = require('path') , SourceMapGenerator = require('source-map').SourceMapGenerator , sourceMap = new SourceMapGenerator({file: path.basename(destpath)}) , sourceMapDest = destpath + '.map' , sourceMappingUrl = encodeURIComponent(path.basename(sourceMapDest)) , res = f(sourceMap) + (options.sourceMap ? '//@ sourceMappingURL=' + sourceMappingUrl + '\n' : '' ) , _ = (function(){ if (options.sourceMap) { grunt.file.write(sourceMapDest, sourceMap.toString()); grunt.file.copy(srcpath, path.join.apply(path, [ path.dirname(destpath), path.basename(srcpath) ])); } }()) ; return res; }
javascript
function writeSourceMap(srcpath, destpath, options, f) { var path = require('path') , SourceMapGenerator = require('source-map').SourceMapGenerator , sourceMap = new SourceMapGenerator({file: path.basename(destpath)}) , sourceMapDest = destpath + '.map' , sourceMappingUrl = encodeURIComponent(path.basename(sourceMapDest)) , res = f(sourceMap) + (options.sourceMap ? '//@ sourceMappingURL=' + sourceMappingUrl + '\n' : '' ) , _ = (function(){ if (options.sourceMap) { grunt.file.write(sourceMapDest, sourceMap.toString()); grunt.file.copy(srcpath, path.join.apply(path, [ path.dirname(destpath), path.basename(srcpath) ])); } }()) ; return res; }
[ "function", "writeSourceMap", "(", "srcpath", ",", "destpath", ",", "options", ",", "f", ")", "{", "var", "path", "=", "require", "(", "'path'", ")", ",", "SourceMapGenerator", "=", "require", "(", "'source-map'", ")", ".", "SourceMapGenerator", ",", "sourceMap", "=", "new", "SourceMapGenerator", "(", "{", "file", ":", "path", ".", "basename", "(", "destpath", ")", "}", ")", ",", "sourceMapDest", "=", "destpath", "+", "'.map'", ",", "sourceMappingUrl", "=", "encodeURIComponent", "(", "path", ".", "basename", "(", "sourceMapDest", ")", ")", ",", "res", "=", "f", "(", "sourceMap", ")", "+", "(", "options", ".", "sourceMap", "?", "'//@ sourceMappingURL='", "+", "sourceMappingUrl", "+", "'\\n'", ":", "''", ")", ",", "_", "=", "(", "function", "(", ")", "{", "if", "(", "options", ".", "sourceMap", ")", "{", "grunt", ".", "file", ".", "write", "(", "sourceMapDest", ",", "sourceMap", ".", "toString", "(", ")", ")", ";", "grunt", ".", "file", ".", "copy", "(", "srcpath", ",", "path", ".", "join", ".", "apply", "(", "path", ",", "[", "path", ".", "dirname", "(", "destpath", ")", ",", "path", ".", "basename", "(", "srcpath", ")", "]", ")", ")", ";", "}", "}", "(", ")", ")", ";", "return", "res", ";", "}" ]
The sources in the source map file are not specified as absolute urls, which means that they will be resolved relative to the location of the source map file. Also, we specify a relative path for the source mapping url, which causes the script source of the JS to be used as the source origin. Also, this url must adhere to RFC3986.
[ "The", "sources", "in", "the", "source", "map", "file", "are", "not", "specified", "as", "absolute", "urls", "which", "means", "that", "they", "will", "be", "resolved", "relative", "to", "the", "location", "of", "the", "source", "map", "file", ".", "Also", "we", "specify", "a", "relative", "path", "for", "the", "source", "mapping", "url", "which", "causes", "the", "script", "source", "of", "the", "JS", "to", "be", "used", "as", "the", "source", "origin", ".", "Also", "this", "url", "must", "adhere", "to", "RFC3986", "." ]
63df011442f1c53bc3637d8d780db811ee2a8065
https://github.com/ethul/grunt-roy/blob/63df011442f1c53bc3637d8d780db811ee2a8065/tasks/roy.js#L60-L80
57,953
xat/mutate.js
mutate.js
function (sig, fn) { var isArr = toType(fn) === 'array'; sig || (sig = []); map[sig.join('::').toLowerCase()] = { fn: isArr ? passObject(fn) : fn, inject: isArr ? true : (fn.length > sig.length) }; return this; }
javascript
function (sig, fn) { var isArr = toType(fn) === 'array'; sig || (sig = []); map[sig.join('::').toLowerCase()] = { fn: isArr ? passObject(fn) : fn, inject: isArr ? true : (fn.length > sig.length) }; return this; }
[ "function", "(", "sig", ",", "fn", ")", "{", "var", "isArr", "=", "toType", "(", "fn", ")", "===", "'array'", ";", "sig", "||", "(", "sig", "=", "[", "]", ")", ";", "map", "[", "sig", ".", "join", "(", "'::'", ")", ".", "toLowerCase", "(", ")", "]", "=", "{", "fn", ":", "isArr", "?", "passObject", "(", "fn", ")", ":", "fn", ",", "inject", ":", "isArr", "?", "true", ":", "(", "fn", ".", "length", ">", "sig", ".", "length", ")", "}", ";", "return", "this", ";", "}" ]
add a new method
[ "add", "a", "new", "method" ]
4d82c4cd2fe859724a934c9ad4f99ebd58d95d69
https://github.com/xat/mutate.js/blob/4d82c4cd2fe859724a934c9ad4f99ebd58d95d69/mutate.js#L9-L19
57,954
xat/mutate.js
mutate.js
function () { return function () { var args = Array.prototype.slice.call(arguments, 0); var sig = (function () { var ret = []; for (var i = 0, len = args.length; i < len; i++) { ret.push(toType(args[i])); } return ret; })().join('::'); if (map[sig]) { if (map[sig].inject) args.unshift(input); return map[sig].fn.apply(ctx || null, args); } return input && input.apply(ctx || null, args); } }
javascript
function () { return function () { var args = Array.prototype.slice.call(arguments, 0); var sig = (function () { var ret = []; for (var i = 0, len = args.length; i < len; i++) { ret.push(toType(args[i])); } return ret; })().join('::'); if (map[sig]) { if (map[sig].inject) args.unshift(input); return map[sig].fn.apply(ctx || null, args); } return input && input.apply(ctx || null, args); } }
[ "function", "(", ")", "{", "return", "function", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ";", "var", "sig", "=", "(", "function", "(", ")", "{", "var", "ret", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "args", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "ret", ".", "push", "(", "toType", "(", "args", "[", "i", "]", ")", ")", ";", "}", "return", "ret", ";", "}", ")", "(", ")", ".", "join", "(", "'::'", ")", ";", "if", "(", "map", "[", "sig", "]", ")", "{", "if", "(", "map", "[", "sig", "]", ".", "inject", ")", "args", ".", "unshift", "(", "input", ")", ";", "return", "map", "[", "sig", "]", ".", "fn", ".", "apply", "(", "ctx", "||", "null", ",", "args", ")", ";", "}", "return", "input", "&&", "input", ".", "apply", "(", "ctx", "||", "null", ",", "args", ")", ";", "}", "}" ]
return the composed new function
[ "return", "the", "composed", "new", "function" ]
4d82c4cd2fe859724a934c9ad4f99ebd58d95d69
https://github.com/xat/mutate.js/blob/4d82c4cd2fe859724a934c9ad4f99ebd58d95d69/mutate.js#L22-L40
57,955
restorecommerce/service-config
lib/service_new.js
request
async function request(cb) { // get name of current service, stop if it's `config-srv` itself const name = nconf.get('server:name') || 'test-srv'; let data = {}; if (name === 'config-srv') return cb(null, data); // setup & connect with config-srv on first run // if (!client && fs.existsSync(fullProtoPath)) const config = _.clone(nconf.get('config-srv')); let service; if (config.transports && config.transports.grpc && config.transports.service) { client = new grpcClient.Client(config); service = await co(client.connect()); } else { throw new Error('Missing configuration details'); } await co(service.get({ filter: client.toStruct({ name: name }) })); // TODO: continue // fetch the latest configuration data if possible client.get({ field: [{ name }] }, (err, res) => { if (err) return cb(err, null); if (res.data) data = res.data; // update/mutate the nconf store and return nconf.use('default', data); return cb(null, nconf); }); return true; }
javascript
async function request(cb) { // get name of current service, stop if it's `config-srv` itself const name = nconf.get('server:name') || 'test-srv'; let data = {}; if (name === 'config-srv') return cb(null, data); // setup & connect with config-srv on first run // if (!client && fs.existsSync(fullProtoPath)) const config = _.clone(nconf.get('config-srv')); let service; if (config.transports && config.transports.grpc && config.transports.service) { client = new grpcClient.Client(config); service = await co(client.connect()); } else { throw new Error('Missing configuration details'); } await co(service.get({ filter: client.toStruct({ name: name }) })); // TODO: continue // fetch the latest configuration data if possible client.get({ field: [{ name }] }, (err, res) => { if (err) return cb(err, null); if (res.data) data = res.data; // update/mutate the nconf store and return nconf.use('default', data); return cb(null, nconf); }); return true; }
[ "async", "function", "request", "(", "cb", ")", "{", "// get name of current service, stop if it's `config-srv` itself", "const", "name", "=", "nconf", ".", "get", "(", "'server:name'", ")", "||", "'test-srv'", ";", "let", "data", "=", "{", "}", ";", "if", "(", "name", "===", "'config-srv'", ")", "return", "cb", "(", "null", ",", "data", ")", ";", "// setup & connect with config-srv on first run", "// if (!client && fs.existsSync(fullProtoPath))", "const", "config", "=", "_", ".", "clone", "(", "nconf", ".", "get", "(", "'config-srv'", ")", ")", ";", "let", "service", ";", "if", "(", "config", ".", "transports", "&&", "config", ".", "transports", ".", "grpc", "&&", "config", ".", "transports", ".", "service", ")", "{", "client", "=", "new", "grpcClient", ".", "Client", "(", "config", ")", ";", "service", "=", "await", "co", "(", "client", ".", "connect", "(", ")", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Missing configuration details'", ")", ";", "}", "await", "co", "(", "service", ".", "get", "(", "{", "filter", ":", "client", ".", "toStruct", "(", "{", "name", ":", "name", "}", ")", "}", ")", ")", ";", "// TODO: continue", "// fetch the latest configuration data if possible", "client", ".", "get", "(", "{", "field", ":", "[", "{", "name", "}", "]", "}", ",", "(", "err", ",", "res", ")", "=>", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ",", "null", ")", ";", "if", "(", "res", ".", "data", ")", "data", "=", "res", ".", "data", ";", "// update/mutate the nconf store and return", "nconf", ".", "use", "(", "'default'", ",", "data", ")", ";", "return", "cb", "(", "null", ",", "nconf", ")", ";", "}", ")", ";", "return", "true", ";", "}" ]
function to update the nconf object with data from the remote `config-srv`.
[ "function", "to", "update", "the", "nconf", "object", "with", "data", "from", "the", "remote", "config", "-", "srv", "." ]
f7ae2183ceaf78e2b6cb9d426c8606b71377ea87
https://github.com/restorecommerce/service-config/blob/f7ae2183ceaf78e2b6cb9d426c8606b71377ea87/lib/service_new.js#L20-L55
57,956
leolmi/install-here
core.js
function() { this.force_first = true; this.relpath = ''; this.root = process.cwd(); this.counters = { files: 0, dependencies: 0, depAddUpd: 0 }; this.error = null; this.exit = null; this.temp = ''; this.files = []; this.dependecies = []; this.package = null; this.settings = null; this.options = null; }
javascript
function() { this.force_first = true; this.relpath = ''; this.root = process.cwd(); this.counters = { files: 0, dependencies: 0, depAddUpd: 0 }; this.error = null; this.exit = null; this.temp = ''; this.files = []; this.dependecies = []; this.package = null; this.settings = null; this.options = null; }
[ "function", "(", ")", "{", "this", ".", "force_first", "=", "true", ";", "this", ".", "relpath", "=", "''", ";", "this", ".", "root", "=", "process", ".", "cwd", "(", ")", ";", "this", ".", "counters", "=", "{", "files", ":", "0", ",", "dependencies", ":", "0", ",", "depAddUpd", ":", "0", "}", ";", "this", ".", "error", "=", "null", ";", "this", ".", "exit", "=", "null", ";", "this", ".", "temp", "=", "''", ";", "this", ".", "files", "=", "[", "]", ";", "this", ".", "dependecies", "=", "[", "]", ";", "this", ".", "package", "=", "null", ";", "this", ".", "settings", "=", "null", ";", "this", ".", "options", "=", "null", ";", "}" ]
resetta lo stato
[ "resetta", "lo", "stato" ]
ef6532c711737e295753f47b202a5ad3b05b34f3
https://github.com/leolmi/install-here/blob/ef6532c711737e295753f47b202a5ad3b05b34f3/core.js#L52-L69
57,957
leolmi/install-here
core.js
function(xdata, ndata) { try { const npkg = JSON.parse(ndata||'{}'); const xpkg = xdata?JSON.parse(xdata):JSON.parse(ndata||'{}'); _managePkg(npkg, xpkg); _initPkg(xpkg); xdata = JSON.stringify(xpkg, null, 2); _log('package.json managed: %s', xdata); } catch(err){ console.error(err); } return xdata; }
javascript
function(xdata, ndata) { try { const npkg = JSON.parse(ndata||'{}'); const xpkg = xdata?JSON.parse(xdata):JSON.parse(ndata||'{}'); _managePkg(npkg, xpkg); _initPkg(xpkg); xdata = JSON.stringify(xpkg, null, 2); _log('package.json managed: %s', xdata); } catch(err){ console.error(err); } return xdata; }
[ "function", "(", "xdata", ",", "ndata", ")", "{", "try", "{", "const", "npkg", "=", "JSON", ".", "parse", "(", "ndata", "||", "'{}'", ")", ";", "const", "xpkg", "=", "xdata", "?", "JSON", ".", "parse", "(", "xdata", ")", ":", "JSON", ".", "parse", "(", "ndata", "||", "'{}'", ")", ";", "_managePkg", "(", "npkg", ",", "xpkg", ")", ";", "_initPkg", "(", "xpkg", ")", ";", "xdata", "=", "JSON", ".", "stringify", "(", "xpkg", ",", "null", ",", "2", ")", ";", "_log", "(", "'package.json managed: %s'", ",", "xdata", ")", ";", "}", "catch", "(", "err", ")", "{", "console", ".", "error", "(", "err", ")", ";", "}", "return", "xdata", ";", "}" ]
gestisce le modifiche al package.json
[ "gestisce", "le", "modifiche", "al", "package", ".", "json" ]
ef6532c711737e295753f47b202a5ad3b05b34f3
https://github.com/leolmi/install-here/blob/ef6532c711737e295753f47b202a5ad3b05b34f3/core.js#L74-L86
57,958
leolmi/install-here
core.js
_checkPathX
function _checkPathX(relfolder, skipCreation) { if (!relfolder) return; const parts = relfolder.split(path.sep); var checked = _state.root; var checkedParts = ''; var index = 0; var skip = false; do { checked = path.join(checked, parts[index]); if (!fs.existsSync(checked)) { if (!skipCreation) { fs.mkdirSync(checked); checkedParts = path.join(checkedParts, parts[index]); } else { skip = true; } } else { checkedParts = path.join(checkedParts, parts[index]); } index++; } while (!skip && index < parts.length); return checkedParts; }
javascript
function _checkPathX(relfolder, skipCreation) { if (!relfolder) return; const parts = relfolder.split(path.sep); var checked = _state.root; var checkedParts = ''; var index = 0; var skip = false; do { checked = path.join(checked, parts[index]); if (!fs.existsSync(checked)) { if (!skipCreation) { fs.mkdirSync(checked); checkedParts = path.join(checkedParts, parts[index]); } else { skip = true; } } else { checkedParts = path.join(checkedParts, parts[index]); } index++; } while (!skip && index < parts.length); return checkedParts; }
[ "function", "_checkPathX", "(", "relfolder", ",", "skipCreation", ")", "{", "if", "(", "!", "relfolder", ")", "return", ";", "const", "parts", "=", "relfolder", ".", "split", "(", "path", ".", "sep", ")", ";", "var", "checked", "=", "_state", ".", "root", ";", "var", "checkedParts", "=", "''", ";", "var", "index", "=", "0", ";", "var", "skip", "=", "false", ";", "do", "{", "checked", "=", "path", ".", "join", "(", "checked", ",", "parts", "[", "index", "]", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "checked", ")", ")", "{", "if", "(", "!", "skipCreation", ")", "{", "fs", ".", "mkdirSync", "(", "checked", ")", ";", "checkedParts", "=", "path", ".", "join", "(", "checkedParts", ",", "parts", "[", "index", "]", ")", ";", "}", "else", "{", "skip", "=", "true", ";", "}", "}", "else", "{", "checkedParts", "=", "path", ".", "join", "(", "checkedParts", ",", "parts", "[", "index", "]", ")", ";", "}", "index", "++", ";", "}", "while", "(", "!", "skip", "&&", "index", "<", "parts", ".", "length", ")", ";", "return", "checkedParts", ";", "}" ]
check the path
[ "check", "the", "path" ]
ef6532c711737e295753f47b202a5ad3b05b34f3
https://github.com/leolmi/install-here/blob/ef6532c711737e295753f47b202a5ad3b05b34f3/core.js#L492-L514
57,959
angeloocana/joj-core
dist/Score.js
getColorScore
function getColorScore(_ref, positions) { var startRow = _ref.startRow, endRow = _ref.endRow; var score = positions.reduce(function (newScore, p) { if (p.y === endRow) newScore.winners += 1;else newScore.preWinnersPoints += endRow === 0 ? startRow - p.y : p.y; return newScore; }, getInitialColorScore()); score.won = score.winners === positions.length; return score; }
javascript
function getColorScore(_ref, positions) { var startRow = _ref.startRow, endRow = _ref.endRow; var score = positions.reduce(function (newScore, p) { if (p.y === endRow) newScore.winners += 1;else newScore.preWinnersPoints += endRow === 0 ? startRow - p.y : p.y; return newScore; }, getInitialColorScore()); score.won = score.winners === positions.length; return score; }
[ "function", "getColorScore", "(", "_ref", ",", "positions", ")", "{", "var", "startRow", "=", "_ref", ".", "startRow", ",", "endRow", "=", "_ref", ".", "endRow", ";", "var", "score", "=", "positions", ".", "reduce", "(", "function", "(", "newScore", ",", "p", ")", "{", "if", "(", "p", ".", "y", "===", "endRow", ")", "newScore", ".", "winners", "+=", "1", ";", "else", "newScore", ".", "preWinnersPoints", "+=", "endRow", "===", "0", "?", "startRow", "-", "p", ".", "y", ":", "p", ".", "y", ";", "return", "newScore", ";", "}", ",", "getInitialColorScore", "(", ")", ")", ";", "score", ".", "won", "=", "score", ".", "winners", "===", "positions", ".", "length", ";", "return", "score", ";", "}" ]
Get color score returns { won, winners, preWinnersPoints }
[ "Get", "color", "score" ]
14bc7801c004271cefafff6cc0abb0c3173c805a
https://github.com/angeloocana/joj-core/blob/14bc7801c004271cefafff6cc0abb0c3173c805a/dist/Score.js#L33-L43
57,960
angeloocana/joj-core
dist/Score.js
getScore
function getScore(board) { var pieces = Board.getPiecesFromBoard(board); var startEndRows = Board.getStartEndRows(board); var white = getColorScore(startEndRows.white, pieces.white); var black = getColorScore(startEndRows.black, pieces.black); return { ended: white.won || black.won, white: white, black: black }; }
javascript
function getScore(board) { var pieces = Board.getPiecesFromBoard(board); var startEndRows = Board.getStartEndRows(board); var white = getColorScore(startEndRows.white, pieces.white); var black = getColorScore(startEndRows.black, pieces.black); return { ended: white.won || black.won, white: white, black: black }; }
[ "function", "getScore", "(", "board", ")", "{", "var", "pieces", "=", "Board", ".", "getPiecesFromBoard", "(", "board", ")", ";", "var", "startEndRows", "=", "Board", ".", "getStartEndRows", "(", "board", ")", ";", "var", "white", "=", "getColorScore", "(", "startEndRows", ".", "white", ",", "pieces", ".", "white", ")", ";", "var", "black", "=", "getColorScore", "(", "startEndRows", ".", "black", ",", "pieces", ".", "black", ")", ";", "return", "{", "ended", ":", "white", ".", "won", "||", "black", ".", "won", ",", "white", ":", "white", ",", "black", ":", "black", "}", ";", "}" ]
Takes a board and return Score
[ "Takes", "a", "board", "and", "return", "Score" ]
14bc7801c004271cefafff6cc0abb0c3173c805a
https://github.com/angeloocana/joj-core/blob/14bc7801c004271cefafff6cc0abb0c3173c805a/dist/Score.js#L47-L57
57,961
byu-oit/aws-scatter-gather
bin/aggregator.js
gatherer
function gatherer(received) { // delete reference from the wait map const index = missing.indexOf(received.name); if (index !== -1) missing.splice(index, 1); // determine if the response was requested const requested = received.requestId === event.requestId; // if already resolved or rejected then exit now, also verify that the event is being listened for if (pending && requested) { // store response if (!received.error) { result[received.name] = received.data; debug('Received response to request ' + received.requestId + ' from ' + received.name); if (config.circuitbreaker && received.circuitbreakerSuccess) { config.circuitbreaker.success(); } } else if (config.circuitbreaker && received.circuitbreakerFault) { debug('Received response to request ' + received.requestId + ' from ' + received.name + ' which triggered a circuitbreaker fault with the error: ' + received.error); config.circuitbreaker.fault(); } else { debug('Received response to request ' + received.requestId + ' from ' + received.name + ' as an error: ' + received.error); } // all expected responses received and min timeout passed, so resolve the deferred promise if (missing.length === 0) { clearTimeout(maxTimeoutId); debug('Received all expected responses for request ' + received.requestId); if (minTimeoutReached) { pending = false; deferred.resolve(result); } } if (config.each) { const meta = { active: pending, minWaitReached: minTimeoutReached, missing: missing.slice(0) }; const done = function (err) { pending = false; if (err) return deferred.reject(err); deferred.resolve(result); }; config.each(received, meta, done); } } }
javascript
function gatherer(received) { // delete reference from the wait map const index = missing.indexOf(received.name); if (index !== -1) missing.splice(index, 1); // determine if the response was requested const requested = received.requestId === event.requestId; // if already resolved or rejected then exit now, also verify that the event is being listened for if (pending && requested) { // store response if (!received.error) { result[received.name] = received.data; debug('Received response to request ' + received.requestId + ' from ' + received.name); if (config.circuitbreaker && received.circuitbreakerSuccess) { config.circuitbreaker.success(); } } else if (config.circuitbreaker && received.circuitbreakerFault) { debug('Received response to request ' + received.requestId + ' from ' + received.name + ' which triggered a circuitbreaker fault with the error: ' + received.error); config.circuitbreaker.fault(); } else { debug('Received response to request ' + received.requestId + ' from ' + received.name + ' as an error: ' + received.error); } // all expected responses received and min timeout passed, so resolve the deferred promise if (missing.length === 0) { clearTimeout(maxTimeoutId); debug('Received all expected responses for request ' + received.requestId); if (minTimeoutReached) { pending = false; deferred.resolve(result); } } if (config.each) { const meta = { active: pending, minWaitReached: minTimeoutReached, missing: missing.slice(0) }; const done = function (err) { pending = false; if (err) return deferred.reject(err); deferred.resolve(result); }; config.each(received, meta, done); } } }
[ "function", "gatherer", "(", "received", ")", "{", "// delete reference from the wait map", "const", "index", "=", "missing", ".", "indexOf", "(", "received", ".", "name", ")", ";", "if", "(", "index", "!==", "-", "1", ")", "missing", ".", "splice", "(", "index", ",", "1", ")", ";", "// determine if the response was requested", "const", "requested", "=", "received", ".", "requestId", "===", "event", ".", "requestId", ";", "// if already resolved or rejected then exit now, also verify that the event is being listened for", "if", "(", "pending", "&&", "requested", ")", "{", "// store response", "if", "(", "!", "received", ".", "error", ")", "{", "result", "[", "received", ".", "name", "]", "=", "received", ".", "data", ";", "debug", "(", "'Received response to request '", "+", "received", ".", "requestId", "+", "' from '", "+", "received", ".", "name", ")", ";", "if", "(", "config", ".", "circuitbreaker", "&&", "received", ".", "circuitbreakerSuccess", ")", "{", "config", ".", "circuitbreaker", ".", "success", "(", ")", ";", "}", "}", "else", "if", "(", "config", ".", "circuitbreaker", "&&", "received", ".", "circuitbreakerFault", ")", "{", "debug", "(", "'Received response to request '", "+", "received", ".", "requestId", "+", "' from '", "+", "received", ".", "name", "+", "' which triggered a circuitbreaker fault with the error: '", "+", "received", ".", "error", ")", ";", "config", ".", "circuitbreaker", ".", "fault", "(", ")", ";", "}", "else", "{", "debug", "(", "'Received response to request '", "+", "received", ".", "requestId", "+", "' from '", "+", "received", ".", "name", "+", "' as an error: '", "+", "received", ".", "error", ")", ";", "}", "// all expected responses received and min timeout passed, so resolve the deferred promise", "if", "(", "missing", ".", "length", "===", "0", ")", "{", "clearTimeout", "(", "maxTimeoutId", ")", ";", "debug", "(", "'Received all expected responses for request '", "+", "received", ".", "requestId", ")", ";", "if", "(", "minTimeoutReached", ")", "{", "pending", "=", "false", ";", "deferred", ".", "resolve", "(", "result", ")", ";", "}", "}", "if", "(", "config", ".", "each", ")", "{", "const", "meta", "=", "{", "active", ":", "pending", ",", "minWaitReached", ":", "minTimeoutReached", ",", "missing", ":", "missing", ".", "slice", "(", "0", ")", "}", ";", "const", "done", "=", "function", "(", "err", ")", "{", "pending", "=", "false", ";", "if", "(", "err", ")", "return", "deferred", ".", "reject", "(", "err", ")", ";", "deferred", ".", "resolve", "(", "result", ")", ";", "}", ";", "config", ".", "each", "(", "received", ",", "meta", ",", "done", ")", ";", "}", "}", "}" ]
define the gatherer function
[ "define", "the", "gatherer", "function" ]
708e7caa6bea706276d55b3678d8468438d6d163
https://github.com/byu-oit/aws-scatter-gather/blob/708e7caa6bea706276d55b3678d8468438d6d163/bin/aggregator.js#L63-L114
57,962
RnbWd/parse-browserify
lib/role.js
function(name, acl) { if (_.isString(name) && (acl instanceof Parse.ACL)) { Parse.Object.prototype.constructor.call(this, null, null); this.setName(name); this.setACL(acl); } else { Parse.Object.prototype.constructor.call(this, name, acl); } }
javascript
function(name, acl) { if (_.isString(name) && (acl instanceof Parse.ACL)) { Parse.Object.prototype.constructor.call(this, null, null); this.setName(name); this.setACL(acl); } else { Parse.Object.prototype.constructor.call(this, name, acl); } }
[ "function", "(", "name", ",", "acl", ")", "{", "if", "(", "_", ".", "isString", "(", "name", ")", "&&", "(", "acl", "instanceof", "Parse", ".", "ACL", ")", ")", "{", "Parse", ".", "Object", ".", "prototype", ".", "constructor", ".", "call", "(", "this", ",", "null", ",", "null", ")", ";", "this", ".", "setName", "(", "name", ")", ";", "this", ".", "setACL", "(", "acl", ")", ";", "}", "else", "{", "Parse", ".", "Object", ".", "prototype", ".", "constructor", ".", "call", "(", "this", ",", "name", ",", "acl", ")", ";", "}", "}" ]
Instance Methods Constructs a new ParseRole with the given name and ACL. @param {String} name The name of the Role to create. @param {Parse.ACL} acl The ACL for this role. Roles must have an ACL.
[ "Instance", "Methods", "Constructs", "a", "new", "ParseRole", "with", "the", "given", "name", "and", "ACL", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/role.js#L27-L35
57,963
silvertoad/color.log.js
loggers.js
MultiLine
function MultiLine() { MultiLine.prototype.parse_and_print = function(msg, colour) { var out = []; for (var i = 0; i < msg.length; i++) { var msg_item = msg[i]; if (typeof msg_item == 'object') out.push(colour + RESET + util.inspect(msg_item, false, 50, true) + RESET + colour); else out.push(msg_item); } this.print(colour + out.join(' ') + colour + " " + RESET); }; MultiLine.prototype.info = function(msg) { this.parse_and_print(msg, GREEN); }; MultiLine.prototype.mark = function(msg) { this.parse_and_print(msg, LIGHT_GREEN); }; MultiLine.prototype.error = function(msg) { this.parse_and_print(msg, RED); }; MultiLine.prototype.warn = function(msg) { this.parse_and_print(msg, YELLOW); }; MultiLine.prototype.print = function(msg) { console.log(msg); }; }
javascript
function MultiLine() { MultiLine.prototype.parse_and_print = function(msg, colour) { var out = []; for (var i = 0; i < msg.length; i++) { var msg_item = msg[i]; if (typeof msg_item == 'object') out.push(colour + RESET + util.inspect(msg_item, false, 50, true) + RESET + colour); else out.push(msg_item); } this.print(colour + out.join(' ') + colour + " " + RESET); }; MultiLine.prototype.info = function(msg) { this.parse_and_print(msg, GREEN); }; MultiLine.prototype.mark = function(msg) { this.parse_and_print(msg, LIGHT_GREEN); }; MultiLine.prototype.error = function(msg) { this.parse_and_print(msg, RED); }; MultiLine.prototype.warn = function(msg) { this.parse_and_print(msg, YELLOW); }; MultiLine.prototype.print = function(msg) { console.log(msg); }; }
[ "function", "MultiLine", "(", ")", "{", "MultiLine", ".", "prototype", ".", "parse_and_print", "=", "function", "(", "msg", ",", "colour", ")", "{", "var", "out", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "msg", ".", "length", ";", "i", "++", ")", "{", "var", "msg_item", "=", "msg", "[", "i", "]", ";", "if", "(", "typeof", "msg_item", "==", "'object'", ")", "out", ".", "push", "(", "colour", "+", "RESET", "+", "util", ".", "inspect", "(", "msg_item", ",", "false", ",", "50", ",", "true", ")", "+", "RESET", "+", "colour", ")", ";", "else", "out", ".", "push", "(", "msg_item", ")", ";", "}", "this", ".", "print", "(", "colour", "+", "out", ".", "join", "(", "' '", ")", "+", "colour", "+", "\" \"", "+", "RESET", ")", ";", "}", ";", "MultiLine", ".", "prototype", ".", "info", "=", "function", "(", "msg", ")", "{", "this", ".", "parse_and_print", "(", "msg", ",", "GREEN", ")", ";", "}", ";", "MultiLine", ".", "prototype", ".", "mark", "=", "function", "(", "msg", ")", "{", "this", ".", "parse_and_print", "(", "msg", ",", "LIGHT_GREEN", ")", ";", "}", ";", "MultiLine", ".", "prototype", ".", "error", "=", "function", "(", "msg", ")", "{", "this", ".", "parse_and_print", "(", "msg", ",", "RED", ")", ";", "}", ";", "MultiLine", ".", "prototype", ".", "warn", "=", "function", "(", "msg", ")", "{", "this", ".", "parse_and_print", "(", "msg", ",", "YELLOW", ")", ";", "}", ";", "MultiLine", ".", "prototype", ".", "print", "=", "function", "(", "msg", ")", "{", "console", ".", "log", "(", "msg", ")", ";", "}", ";", "}" ]
Print every message in new line @constructor
[ "Print", "every", "message", "in", "new", "line" ]
5b9979e26fadb5201db0683207ced0a1fd335ab0
https://github.com/silvertoad/color.log.js/blob/5b9979e26fadb5201db0683207ced0a1fd335ab0/loggers.js#L14-L55
57,964
silvertoad/color.log.js
loggers.js
SingleLine
function SingleLine() { SingleLine.prototype.print = function(msg) { var result = check(); if (result.success) { process.stdout.clearLine(); process.stdout.cursorTo(0); process.stdout.write(msg); } else MultiLine.prototype.print('missed method: ' + result.required_method + ' ' + msg); }; SingleLine.prototype.info = function(msg) { this.parse_and_print(arguments, GREEN); }; SingleLine.prototype.mark = function(msg) { this.parse_and_print(arguments, LIGHT_GREEN); }; SingleLine.prototype.error = function(msg) { this.parse_and_print(arguments, RED); }; SingleLine.prototype.warn = function(msg) { this.parse_and_print(arguments, YELLOW); }; function check() { var check = ['clearLine', 'cursorTo', 'write']; for (var i = 0; i < check.length; i++) { var method = check[i]; if (!(method in process.stdout)) return {required_method: method}; } return {success: true}; } }
javascript
function SingleLine() { SingleLine.prototype.print = function(msg) { var result = check(); if (result.success) { process.stdout.clearLine(); process.stdout.cursorTo(0); process.stdout.write(msg); } else MultiLine.prototype.print('missed method: ' + result.required_method + ' ' + msg); }; SingleLine.prototype.info = function(msg) { this.parse_and_print(arguments, GREEN); }; SingleLine.prototype.mark = function(msg) { this.parse_and_print(arguments, LIGHT_GREEN); }; SingleLine.prototype.error = function(msg) { this.parse_and_print(arguments, RED); }; SingleLine.prototype.warn = function(msg) { this.parse_and_print(arguments, YELLOW); }; function check() { var check = ['clearLine', 'cursorTo', 'write']; for (var i = 0; i < check.length; i++) { var method = check[i]; if (!(method in process.stdout)) return {required_method: method}; } return {success: true}; } }
[ "function", "SingleLine", "(", ")", "{", "SingleLine", ".", "prototype", ".", "print", "=", "function", "(", "msg", ")", "{", "var", "result", "=", "check", "(", ")", ";", "if", "(", "result", ".", "success", ")", "{", "process", ".", "stdout", ".", "clearLine", "(", ")", ";", "process", ".", "stdout", ".", "cursorTo", "(", "0", ")", ";", "process", ".", "stdout", ".", "write", "(", "msg", ")", ";", "}", "else", "MultiLine", ".", "prototype", ".", "print", "(", "'missed method: '", "+", "result", ".", "required_method", "+", "' '", "+", "msg", ")", ";", "}", ";", "SingleLine", ".", "prototype", ".", "info", "=", "function", "(", "msg", ")", "{", "this", ".", "parse_and_print", "(", "arguments", ",", "GREEN", ")", ";", "}", ";", "SingleLine", ".", "prototype", ".", "mark", "=", "function", "(", "msg", ")", "{", "this", ".", "parse_and_print", "(", "arguments", ",", "LIGHT_GREEN", ")", ";", "}", ";", "SingleLine", ".", "prototype", ".", "error", "=", "function", "(", "msg", ")", "{", "this", ".", "parse_and_print", "(", "arguments", ",", "RED", ")", ";", "}", ";", "SingleLine", ".", "prototype", ".", "warn", "=", "function", "(", "msg", ")", "{", "this", ".", "parse_and_print", "(", "arguments", ",", "YELLOW", ")", ";", "}", ";", "function", "check", "(", ")", "{", "var", "check", "=", "[", "'clearLine'", ",", "'cursorTo'", ",", "'write'", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "check", ".", "length", ";", "i", "++", ")", "{", "var", "method", "=", "check", "[", "i", "]", ";", "if", "(", "!", "(", "method", "in", "process", ".", "stdout", ")", ")", "return", "{", "required_method", ":", "method", "}", ";", "}", "return", "{", "success", ":", "true", "}", ";", "}", "}" ]
Print every message in single line @constructor
[ "Print", "every", "message", "in", "single", "line" ]
5b9979e26fadb5201db0683207ced0a1fd335ab0
https://github.com/silvertoad/color.log.js/blob/5b9979e26fadb5201db0683207ced0a1fd335ab0/loggers.js#L61-L107
57,965
tether/manner-test
index.js
salute
function salute (cb) { let value try { value = cb() if (value instanceof Error) value = Promise.reject(value) } catch (e) { value = Promise.reject(e) } return value }
javascript
function salute (cb) { let value try { value = cb() if (value instanceof Error) value = Promise.reject(value) } catch (e) { value = Promise.reject(e) } return value }
[ "function", "salute", "(", "cb", ")", "{", "let", "value", "try", "{", "value", "=", "cb", "(", ")", "if", "(", "value", "instanceof", "Error", ")", "value", "=", "Promise", ".", "reject", "(", "value", ")", "}", "catch", "(", "e", ")", "{", "value", "=", "Promise", ".", "reject", "(", "e", ")", "}", "return", "value", "}" ]
Simulate salute behavious. @param {Function} cb @see https://github.com/bredele/salute @api private
[ "Simulate", "salute", "behavious", "." ]
8fde3f969325155ffbff54f7c78c7e36f69b1fc2
https://github.com/tether/manner-test/blob/8fde3f969325155ffbff54f7c78c7e36f69b1fc2/index.js#L76-L85
57,966
paulrayes/gaze-cli
index.js
run
function run(filepath) { var startTime = process.hrtime(); var uniqueCommand = command.replace('$path', filepath); if (!argv.silent) { console.log('>', uniqueCommand); } execshell(uniqueCommand); if (!argv.silent) { console.log('Finished in', prettyHrtime(process.hrtime(startTime))); } }
javascript
function run(filepath) { var startTime = process.hrtime(); var uniqueCommand = command.replace('$path', filepath); if (!argv.silent) { console.log('>', uniqueCommand); } execshell(uniqueCommand); if (!argv.silent) { console.log('Finished in', prettyHrtime(process.hrtime(startTime))); } }
[ "function", "run", "(", "filepath", ")", "{", "var", "startTime", "=", "process", ".", "hrtime", "(", ")", ";", "var", "uniqueCommand", "=", "command", ".", "replace", "(", "'$path'", ",", "filepath", ")", ";", "if", "(", "!", "argv", ".", "silent", ")", "{", "console", ".", "log", "(", "'>'", ",", "uniqueCommand", ")", ";", "}", "execshell", "(", "uniqueCommand", ")", ";", "if", "(", "!", "argv", ".", "silent", ")", "{", "console", ".", "log", "(", "'Finished in'", ",", "prettyHrtime", "(", "process", ".", "hrtime", "(", "startTime", ")", ")", ")", ";", "}", "}" ]
Function to run when something changes
[ "Function", "to", "run", "when", "something", "changes" ]
09cbeaaae049e03af62e200631b6d21ac10b1650
https://github.com/paulrayes/gaze-cli/blob/09cbeaaae049e03af62e200631b6d21ac10b1650/index.js#L82-L92
57,967
oskarhagberg/gbgcity
lib/parking.js
getParkings
function getParkings(latitude, longitude, radius, type, params, callback) { if(!latitude || !longitude || !radius) { callback(new Error("Parking.getParkings: latitude, longitude and radius required")); return; } params = params || {}; params.latitude = latitude; params.longitude = longitude; params.radius = radius; var subResource; switch(type) { case 'bus': subResource = 'BusParkings'; break; case 'handicap': subResource = 'HandicapParkings'; break; case 'mc': subResource = 'MCParkings'; break; case 'private': subResource = 'PrivateParkings'; break; case 'publicTime': subResource = 'PublicTimeParkings'; break; case 'publicToll': subResource = 'PublicTollParkings'; break; case 'residential': subResource = 'ResidentialParkings'; break; case 'truck': subResource = 'TruckParkings'; break; default: callback(new Error("Parking.getParkings: unknown type: " + type)); } core.callApi('/ParkingService/v1.0/' + subResource, params, callback); }
javascript
function getParkings(latitude, longitude, radius, type, params, callback) { if(!latitude || !longitude || !radius) { callback(new Error("Parking.getParkings: latitude, longitude and radius required")); return; } params = params || {}; params.latitude = latitude; params.longitude = longitude; params.radius = radius; var subResource; switch(type) { case 'bus': subResource = 'BusParkings'; break; case 'handicap': subResource = 'HandicapParkings'; break; case 'mc': subResource = 'MCParkings'; break; case 'private': subResource = 'PrivateParkings'; break; case 'publicTime': subResource = 'PublicTimeParkings'; break; case 'publicToll': subResource = 'PublicTollParkings'; break; case 'residential': subResource = 'ResidentialParkings'; break; case 'truck': subResource = 'TruckParkings'; break; default: callback(new Error("Parking.getParkings: unknown type: " + type)); } core.callApi('/ParkingService/v1.0/' + subResource, params, callback); }
[ "function", "getParkings", "(", "latitude", ",", "longitude", ",", "radius", ",", "type", ",", "params", ",", "callback", ")", "{", "if", "(", "!", "latitude", "||", "!", "longitude", "||", "!", "radius", ")", "{", "callback", "(", "new", "Error", "(", "\"Parking.getParkings: latitude, longitude and radius required\"", ")", ")", ";", "return", ";", "}", "params", "=", "params", "||", "{", "}", ";", "params", ".", "latitude", "=", "latitude", ";", "params", ".", "longitude", "=", "longitude", ";", "params", ".", "radius", "=", "radius", ";", "var", "subResource", ";", "switch", "(", "type", ")", "{", "case", "'bus'", ":", "subResource", "=", "'BusParkings'", ";", "break", ";", "case", "'handicap'", ":", "subResource", "=", "'HandicapParkings'", ";", "break", ";", "case", "'mc'", ":", "subResource", "=", "'MCParkings'", ";", "break", ";", "case", "'private'", ":", "subResource", "=", "'PrivateParkings'", ";", "break", ";", "case", "'publicTime'", ":", "subResource", "=", "'PublicTimeParkings'", ";", "break", ";", "case", "'publicToll'", ":", "subResource", "=", "'PublicTollParkings'", ";", "break", ";", "case", "'residential'", ":", "subResource", "=", "'ResidentialParkings'", ";", "break", ";", "case", "'truck'", ":", "subResource", "=", "'TruckParkings'", ";", "break", ";", "default", ":", "callback", "(", "new", "Error", "(", "\"Parking.getParkings: unknown type: \"", "+", "type", ")", ")", ";", "}", "core", ".", "callApi", "(", "'/ParkingService/v1.0/'", "+", "subResource", ",", "params", ",", "callback", ")", ";", "}" ]
Returns all public parkings of the given type. @memberof module:gbgcity/Parking @param {String|Number} latitude The latitude of the location around which to explore. @param {String|Number} longitude The longitude of the location around which to explore. @param {String|Number} radius The radius of the area to explore. @param {String} type The parking type. Any of: bus, handicap, mc, private, publicTime, publicToll, residential, truck @param {Object} [params] An object containing additional parameters. @param {Function} callback The function to call with results, function({Error} error, {Object} results)/ @see http://data.goteborg.se/ParkingService/v1.0/help/operations/GetBusParkings and similar
[ "Returns", "all", "public", "parkings", "of", "the", "given", "type", "." ]
d2de903b2fba83cc953ae218905380fef080cb2d
https://github.com/oskarhagberg/gbgcity/blob/d2de903b2fba83cc953ae218905380fef080cb2d/lib/parking.js#L17-L48
57,968
oskarhagberg/gbgcity
lib/parking.js
getPublicPayMachines
function getPublicPayMachines(latitude, longitude, radius, params, callback) { if(!latitude || !longitude || !radius) { callback(new Error("Parking.getPublicPayMachines: latitude, longitude and radius required")); return; } params = params || {}; params.latitude = latitude; params.longitude = longitude; params.radius = radius; core.callApi('/ParkingService/v1.0/PublicPayMachines', params, callback); }
javascript
function getPublicPayMachines(latitude, longitude, radius, params, callback) { if(!latitude || !longitude || !radius) { callback(new Error("Parking.getPublicPayMachines: latitude, longitude and radius required")); return; } params = params || {}; params.latitude = latitude; params.longitude = longitude; params.radius = radius; core.callApi('/ParkingService/v1.0/PublicPayMachines', params, callback); }
[ "function", "getPublicPayMachines", "(", "latitude", ",", "longitude", ",", "radius", ",", "params", ",", "callback", ")", "{", "if", "(", "!", "latitude", "||", "!", "longitude", "||", "!", "radius", ")", "{", "callback", "(", "new", "Error", "(", "\"Parking.getPublicPayMachines: latitude, longitude and radius required\"", ")", ")", ";", "return", ";", "}", "params", "=", "params", "||", "{", "}", ";", "params", ".", "latitude", "=", "latitude", ";", "params", ".", "longitude", "=", "longitude", ";", "params", ".", "radius", "=", "radius", ";", "core", ".", "callApi", "(", "'/ParkingService/v1.0/PublicPayMachines'", ",", "params", ",", "callback", ")", ";", "}" ]
Returns all public pay machines. @memberof module:gbgcity/Parking @param {String|Number} latitude The latitude of the location around which to explore. @param {String|Number} longitude The longitude of the location around which to explore. @param {String|Number} radius The radius of the area to explore. @param {Object} [params] An object containing additional parameters. @param {Function} callback The function to call with results, function({Error} error, {Object} results)/ @see http://data.goteborg.se/ParkingService/v1.0/help/operations/GetPublicPaymachines
[ "Returns", "all", "public", "pay", "machines", "." ]
d2de903b2fba83cc953ae218905380fef080cb2d
https://github.com/oskarhagberg/gbgcity/blob/d2de903b2fba83cc953ae218905380fef080cb2d/lib/parking.js#L61-L71
57,969
doowb/sessionify
index.js
sessionify
function sessionify (fn, session, context) { if (!session) { throw new Error('sessionify expects a session-cache object as `session`'); } var bind = session.bind; if (typeof fn === 'object' && fn.on) { bind = session.bindEmitter; } if (context) { bind.call(session, fn, context); } else { bind.call(session, fn); } return fn; }
javascript
function sessionify (fn, session, context) { if (!session) { throw new Error('sessionify expects a session-cache object as `session`'); } var bind = session.bind; if (typeof fn === 'object' && fn.on) { bind = session.bindEmitter; } if (context) { bind.call(session, fn, context); } else { bind.call(session, fn); } return fn; }
[ "function", "sessionify", "(", "fn", ",", "session", ",", "context", ")", "{", "if", "(", "!", "session", ")", "{", "throw", "new", "Error", "(", "'sessionify expects a session-cache object as `session`'", ")", ";", "}", "var", "bind", "=", "session", ".", "bind", ";", "if", "(", "typeof", "fn", "===", "'object'", "&&", "fn", ".", "on", ")", "{", "bind", "=", "session", ".", "bindEmitter", ";", "}", "if", "(", "context", ")", "{", "bind", ".", "call", "(", "session", ",", "fn", ",", "context", ")", ";", "}", "else", "{", "bind", ".", "call", "(", "session", ",", "fn", ")", ";", "}", "return", "fn", ";", "}" ]
Bind a function, EventEmitter, or Stream to the provided session object with an optional context. @param {Function|EventEmitter|Stream} `fn` Object to bind to. @param {Object} `session` session-cache object to bind with. @param {Object} `context` Optional context to bind to the sesssion. @return {*} Bound object @api public
[ "Bind", "a", "function", "EventEmitter", "or", "Stream", "to", "the", "provided", "session", "object", "with", "an", "optional", "context", "." ]
1a49eb39d771cc5e60db4008312edd4792ef6ed8
https://github.com/doowb/sessionify/blob/1a49eb39d771cc5e60db4008312edd4792ef6ed8/index.js#L23-L39
57,970
tunnckoCore/capture-spawn
index.js
SpawnError
function SpawnError (message, options) { return errorBase('SpawnError', function (message, options) { this.name = 'SpawnError' this.message = message this.code = options.code this.buffer = options.buffer }).call(this, message, options) }
javascript
function SpawnError (message, options) { return errorBase('SpawnError', function (message, options) { this.name = 'SpawnError' this.message = message this.code = options.code this.buffer = options.buffer }).call(this, message, options) }
[ "function", "SpawnError", "(", "message", ",", "options", ")", "{", "return", "errorBase", "(", "'SpawnError'", ",", "function", "(", "message", ",", "options", ")", "{", "this", ".", "name", "=", "'SpawnError'", "this", ".", "message", "=", "message", "this", ".", "code", "=", "options", ".", "code", "this", ".", "buffer", "=", "options", ".", "buffer", "}", ")", ".", "call", "(", "this", ",", "message", ",", "options", ")", "}" ]
> Custom error class that is thrown on error. @param {String} `message` @param {Object} `options` @api private
[ ">", "Custom", "error", "class", "that", "is", "thrown", "on", "error", "." ]
a7253d7b3f1bb74912aec8638b20bad094334dc8
https://github.com/tunnckoCore/capture-spawn/blob/a7253d7b3f1bb74912aec8638b20bad094334dc8/index.js#L87-L94
57,971
dak0rn/espressojs
lib/utils/handler.js
function(api, handler) { if( 0 === arguments.length ) throw new Error('utils.handler.register needs arguments'); if( ! _.isObject(api) ) throw new Error('utils.handler.register needs an espressojs API'); if( ! (handler instanceof Handler) ) throw new Error('utils.handler.register needs a Handler'); // Add it to _ids api._ids[ handler.getPattern().getExpression().toString() ] = handler; // Add it to _names if any var name = handler.getOption('name'); if( _.isString(name) && ! _.isEmpty(name) ) api._names[ name ] = handler; }
javascript
function(api, handler) { if( 0 === arguments.length ) throw new Error('utils.handler.register needs arguments'); if( ! _.isObject(api) ) throw new Error('utils.handler.register needs an espressojs API'); if( ! (handler instanceof Handler) ) throw new Error('utils.handler.register needs a Handler'); // Add it to _ids api._ids[ handler.getPattern().getExpression().toString() ] = handler; // Add it to _names if any var name = handler.getOption('name'); if( _.isString(name) && ! _.isEmpty(name) ) api._names[ name ] = handler; }
[ "function", "(", "api", ",", "handler", ")", "{", "if", "(", "0", "===", "arguments", ".", "length", ")", "throw", "new", "Error", "(", "'utils.handler.register needs arguments'", ")", ";", "if", "(", "!", "_", ".", "isObject", "(", "api", ")", ")", "throw", "new", "Error", "(", "'utils.handler.register needs an espressojs API'", ")", ";", "if", "(", "!", "(", "handler", "instanceof", "Handler", ")", ")", "throw", "new", "Error", "(", "'utils.handler.register needs a Handler'", ")", ";", "// Add it to _ids", "api", ".", "_ids", "[", "handler", ".", "getPattern", "(", ")", ".", "getExpression", "(", ")", ".", "toString", "(", ")", "]", "=", "handler", ";", "// Add it to _names if any", "var", "name", "=", "handler", ".", "getOption", "(", "'name'", ")", ";", "if", "(", "_", ".", "isString", "(", "name", ")", "&&", "!", "_", ".", "isEmpty", "(", "name", ")", ")", "api", ".", "_names", "[", "name", "]", "=", "handler", ";", "}" ]
Registers a handler in the API
[ "Registers", "a", "handler", "in", "the", "API" ]
7f8e015f31113215abbe9988ae7f2c7dd5d8572b
https://github.com/dak0rn/espressojs/blob/7f8e015f31113215abbe9988ae7f2c7dd5d8572b/lib/utils/handler.js#L14-L33
57,972
dak0rn/espressojs
lib/utils/handler.js
function(api) { if( ! _.isObject(api) ) throw new Error('utils.handler.buildResourceTable needs an espressojs API'); api._resources = _( api._ids ).values().reject( _.isUndefined ).value(); }
javascript
function(api) { if( ! _.isObject(api) ) throw new Error('utils.handler.buildResourceTable needs an espressojs API'); api._resources = _( api._ids ).values().reject( _.isUndefined ).value(); }
[ "function", "(", "api", ")", "{", "if", "(", "!", "_", ".", "isObject", "(", "api", ")", ")", "throw", "new", "Error", "(", "'utils.handler.buildResourceTable needs an espressojs API'", ")", ";", "api", ".", "_resources", "=", "_", "(", "api", ".", "_ids", ")", ".", "values", "(", ")", ".", "reject", "(", "_", ".", "isUndefined", ")", ".", "value", "(", ")", ";", "}" ]
Builds the APIs resource table
[ "Builds", "the", "APIs", "resource", "table" ]
7f8e015f31113215abbe9988ae7f2c7dd5d8572b
https://github.com/dak0rn/espressojs/blob/7f8e015f31113215abbe9988ae7f2c7dd5d8572b/lib/utils/handler.js#L58-L63
57,973
hgoebl/entintar
lib/LineInfoEmitter.js
analyzeLine
function analyzeLine(line, rules) { var result = { line: line }; rules.rules.forEach(function (rule) { if (rule.re.test(line)) { line = line.replace(rule.re, rule.replace); if (rule.emitLevel) { if (result.emitLevel) { result.emitLevel = Math.min(result.emitLevel, rule.emitLevel); } else { result.emitLevel = rule.emitLevel; } } } }); if (!result.emitLevel) { result.emitLevel = rules.defaultEmitLevel || 5; } result.colored = line; return result; }
javascript
function analyzeLine(line, rules) { var result = { line: line }; rules.rules.forEach(function (rule) { if (rule.re.test(line)) { line = line.replace(rule.re, rule.replace); if (rule.emitLevel) { if (result.emitLevel) { result.emitLevel = Math.min(result.emitLevel, rule.emitLevel); } else { result.emitLevel = rule.emitLevel; } } } }); if (!result.emitLevel) { result.emitLevel = rules.defaultEmitLevel || 5; } result.colored = line; return result; }
[ "function", "analyzeLine", "(", "line", ",", "rules", ")", "{", "var", "result", "=", "{", "line", ":", "line", "}", ";", "rules", ".", "rules", ".", "forEach", "(", "function", "(", "rule", ")", "{", "if", "(", "rule", ".", "re", ".", "test", "(", "line", ")", ")", "{", "line", "=", "line", ".", "replace", "(", "rule", ".", "re", ",", "rule", ".", "replace", ")", ";", "if", "(", "rule", ".", "emitLevel", ")", "{", "if", "(", "result", ".", "emitLevel", ")", "{", "result", ".", "emitLevel", "=", "Math", ".", "min", "(", "result", ".", "emitLevel", ",", "rule", ".", "emitLevel", ")", ";", "}", "else", "{", "result", ".", "emitLevel", "=", "rule", ".", "emitLevel", ";", "}", "}", "}", "}", ")", ";", "if", "(", "!", "result", ".", "emitLevel", ")", "{", "result", ".", "emitLevel", "=", "rules", ".", "defaultEmitLevel", "||", "5", ";", "}", "result", ".", "colored", "=", "line", ";", "return", "result", ";", "}" ]
Replace color codes in str with real curses colors. @returns object with following attributes: colored: the line with color marker e.g. #{c_cyan} line: the original line coming from the input stream emitLevel: the minimal level (1=very import, 9=very verbose)
[ "Replace", "color", "codes", "in", "str", "with", "real", "curses", "colors", "." ]
cc6be17961bebfa25e247992d06af5ffaa618f4e
https://github.com/hgoebl/entintar/blob/cc6be17961bebfa25e247992d06af5ffaa618f4e/lib/LineInfoEmitter.js#L15-L37
57,974
wojtkowiak/meteor-desktop-test-suite
src/suite.js
getNpm
function getNpm() { let execResult; let version; let version3; let npm; if (shell.which('npm')) { execResult = shell.exec('npm --version', { silent: true }); if (execResult.code === 0) { version = execResult.stdout; } } if (version !== null && semver.satisfies(version, '>= 3.0.0')) { npm = 'npm'; } if (!npm) { if (shell.which('npm3')) { execResult = shell.exec('npm3 --version', { silent: true }); if (execResult.code === 0) { version3 = execResult.stdout; } } if (version3 === null) { npm = 'npm'; } else { npm = 'npm3'; } } return npm; }
javascript
function getNpm() { let execResult; let version; let version3; let npm; if (shell.which('npm')) { execResult = shell.exec('npm --version', { silent: true }); if (execResult.code === 0) { version = execResult.stdout; } } if (version !== null && semver.satisfies(version, '>= 3.0.0')) { npm = 'npm'; } if (!npm) { if (shell.which('npm3')) { execResult = shell.exec('npm3 --version', { silent: true }); if (execResult.code === 0) { version3 = execResult.stdout; } } if (version3 === null) { npm = 'npm'; } else { npm = 'npm3'; } } return npm; }
[ "function", "getNpm", "(", ")", "{", "let", "execResult", ";", "let", "version", ";", "let", "version3", ";", "let", "npm", ";", "if", "(", "shell", ".", "which", "(", "'npm'", ")", ")", "{", "execResult", "=", "shell", ".", "exec", "(", "'npm --version'", ",", "{", "silent", ":", "true", "}", ")", ";", "if", "(", "execResult", ".", "code", "===", "0", ")", "{", "version", "=", "execResult", ".", "stdout", ";", "}", "}", "if", "(", "version", "!==", "null", "&&", "semver", ".", "satisfies", "(", "version", ",", "'>= 3.0.0'", ")", ")", "{", "npm", "=", "'npm'", ";", "}", "if", "(", "!", "npm", ")", "{", "if", "(", "shell", ".", "which", "(", "'npm3'", ")", ")", "{", "execResult", "=", "shell", ".", "exec", "(", "'npm3 --version'", ",", "{", "silent", ":", "true", "}", ")", ";", "if", "(", "execResult", ".", "code", "===", "0", ")", "{", "version3", "=", "execResult", ".", "stdout", ";", "}", "}", "if", "(", "version3", "===", "null", ")", "{", "npm", "=", "'npm'", ";", "}", "else", "{", "npm", "=", "'npm3'", ";", "}", "}", "return", "npm", ";", "}" ]
Looks for npm. @returns {*}
[ "Looks", "for", "npm", "." ]
41ac662e5b28890d9c456d48768f04ee388a7b63
https://github.com/wojtkowiak/meteor-desktop-test-suite/blob/41ac662e5b28890d9c456d48768f04ee388a7b63/src/suite.js#L15-L46
57,975
vtardia/varo-flux
lib/Dispatcher.js
invoke
function invoke(id) { this.isPending[id] = true; this.callbacks[id](this.pendingPayload); this.isHandled[id] = true; }
javascript
function invoke(id) { this.isPending[id] = true; this.callbacks[id](this.pendingPayload); this.isHandled[id] = true; }
[ "function", "invoke", "(", "id", ")", "{", "this", ".", "isPending", "[", "id", "]", "=", "true", ";", "this", ".", "callbacks", "[", "id", "]", "(", "this", ".", "pendingPayload", ")", ";", "this", ".", "isHandled", "[", "id", "]", "=", "true", ";", "}" ]
Invoke a callback
[ "Invoke", "a", "callback" ]
e1b07901f0ac70e09b25a23c14f8e2e796f95e54
https://github.com/vtardia/varo-flux/blob/e1b07901f0ac70e09b25a23c14f8e2e796f95e54/lib/Dispatcher.js#L26-L30
57,976
vtardia/varo-flux
lib/Dispatcher.js
start
function start(payload) { for (var id in this.callbacks) { this.isPending[id] = false; this.isHandled[id] = false; } this.isDispatching = true; this.pendingPayload = payload; }
javascript
function start(payload) { for (var id in this.callbacks) { this.isPending[id] = false; this.isHandled[id] = false; } this.isDispatching = true; this.pendingPayload = payload; }
[ "function", "start", "(", "payload", ")", "{", "for", "(", "var", "id", "in", "this", ".", "callbacks", ")", "{", "this", ".", "isPending", "[", "id", "]", "=", "false", ";", "this", ".", "isHandled", "[", "id", "]", "=", "false", ";", "}", "this", ".", "isDispatching", "=", "true", ";", "this", ".", "pendingPayload", "=", "payload", ";", "}" ]
Set up dispatch action
[ "Set", "up", "dispatch", "action" ]
e1b07901f0ac70e09b25a23c14f8e2e796f95e54
https://github.com/vtardia/varo-flux/blob/e1b07901f0ac70e09b25a23c14f8e2e796f95e54/lib/Dispatcher.js#L35-L42
57,977
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/htmlparser/filter.js
function( rules, options ) { var priority; // Backward compatibility. if ( typeof options == 'number' ) priority = options; // New version - try reading from options. else if ( options && ( 'priority' in options ) ) priority = options.priority; // Defaults. if ( typeof priority != 'number' ) priority = 10; if ( typeof options != 'object' ) options = {}; // Add the elementNames. if ( rules.elementNames ) this.elementNameRules.addMany( rules.elementNames, priority, options ); // Add the attributeNames. if ( rules.attributeNames ) this.attributeNameRules.addMany( rules.attributeNames, priority, options ); // Add the elements. if ( rules.elements ) addNamedRules( this.elementsRules, rules.elements, priority, options ); // Add the attributes. if ( rules.attributes ) addNamedRules( this.attributesRules, rules.attributes, priority, options ); // Add the text. if ( rules.text ) this.textRules.add( rules.text, priority, options ); // Add the comment. if ( rules.comment ) this.commentRules.add( rules.comment, priority, options ); // Add root node rules. if ( rules.root ) this.rootRules.add( rules.root, priority, options ); }
javascript
function( rules, options ) { var priority; // Backward compatibility. if ( typeof options == 'number' ) priority = options; // New version - try reading from options. else if ( options && ( 'priority' in options ) ) priority = options.priority; // Defaults. if ( typeof priority != 'number' ) priority = 10; if ( typeof options != 'object' ) options = {}; // Add the elementNames. if ( rules.elementNames ) this.elementNameRules.addMany( rules.elementNames, priority, options ); // Add the attributeNames. if ( rules.attributeNames ) this.attributeNameRules.addMany( rules.attributeNames, priority, options ); // Add the elements. if ( rules.elements ) addNamedRules( this.elementsRules, rules.elements, priority, options ); // Add the attributes. if ( rules.attributes ) addNamedRules( this.attributesRules, rules.attributes, priority, options ); // Add the text. if ( rules.text ) this.textRules.add( rules.text, priority, options ); // Add the comment. if ( rules.comment ) this.commentRules.add( rules.comment, priority, options ); // Add root node rules. if ( rules.root ) this.rootRules.add( rules.root, priority, options ); }
[ "function", "(", "rules", ",", "options", ")", "{", "var", "priority", ";", "// Backward compatibility.", "if", "(", "typeof", "options", "==", "'number'", ")", "priority", "=", "options", ";", "// New version - try reading from options.", "else", "if", "(", "options", "&&", "(", "'priority'", "in", "options", ")", ")", "priority", "=", "options", ".", "priority", ";", "// Defaults.", "if", "(", "typeof", "priority", "!=", "'number'", ")", "priority", "=", "10", ";", "if", "(", "typeof", "options", "!=", "'object'", ")", "options", "=", "{", "}", ";", "// Add the elementNames.", "if", "(", "rules", ".", "elementNames", ")", "this", ".", "elementNameRules", ".", "addMany", "(", "rules", ".", "elementNames", ",", "priority", ",", "options", ")", ";", "// Add the attributeNames.", "if", "(", "rules", ".", "attributeNames", ")", "this", ".", "attributeNameRules", ".", "addMany", "(", "rules", ".", "attributeNames", ",", "priority", ",", "options", ")", ";", "// Add the elements.", "if", "(", "rules", ".", "elements", ")", "addNamedRules", "(", "this", ".", "elementsRules", ",", "rules", ".", "elements", ",", "priority", ",", "options", ")", ";", "// Add the attributes.", "if", "(", "rules", ".", "attributes", ")", "addNamedRules", "(", "this", ".", "attributesRules", ",", "rules", ".", "attributes", ",", "priority", ",", "options", ")", ";", "// Add the text.", "if", "(", "rules", ".", "text", ")", "this", ".", "textRules", ".", "add", "(", "rules", ".", "text", ",", "priority", ",", "options", ")", ";", "// Add the comment.", "if", "(", "rules", ".", "comment", ")", "this", ".", "commentRules", ".", "add", "(", "rules", ".", "comment", ",", "priority", ",", "options", ")", ";", "// Add root node rules.", "if", "(", "rules", ".", "root", ")", "this", ".", "rootRules", ".", "add", "(", "rules", ".", "root", ",", "priority", ",", "options", ")", ";", "}" ]
Add rules to this filter. @param {CKEDITOR.htmlParser.filterRulesDefinition} rules Object containing filter rules. @param {Object/Number} [options] Object containing rules' options or a priority (for a backward compatibility with CKEditor versions up to 4.2.x). @param {Number} [options.priority=10] The priority of a rule. @param {Boolean} [options.applyToAll=false] Whether to apply rule to non-editable elements and their descendants too.
[ "Add", "rules", "to", "this", "filter", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/htmlparser/filter.js#L117-L160
57,978
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/htmlparser/filter.js
function( rule, priority, options ) { this.rules.splice( this.findIndex( priority ), 0, { value: rule, priority: priority, options: options } ); }
javascript
function( rule, priority, options ) { this.rules.splice( this.findIndex( priority ), 0, { value: rule, priority: priority, options: options } ); }
[ "function", "(", "rule", ",", "priority", ",", "options", ")", "{", "this", ".", "rules", ".", "splice", "(", "this", ".", "findIndex", "(", "priority", ")", ",", "0", ",", "{", "value", ":", "rule", ",", "priority", ":", "priority", ",", "options", ":", "options", "}", ")", ";", "}" ]
Adds specified rule to this group. @param {Function/Array} rule Function for function based rule or [ pattern, replacement ] array for rule applicable to names. @param {Number} priority @param options
[ "Adds", "specified", "rule", "to", "this", "group", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/htmlparser/filter.js#L262-L268
57,979
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/htmlparser/filter.js
function( rules, priority, options ) { var args = [ this.findIndex( priority ), 0 ]; for ( var i = 0, len = rules.length; i < len; i++ ) { args.push( { value: rules[ i ], priority: priority, options: options } ); } this.rules.splice.apply( this.rules, args ); }
javascript
function( rules, priority, options ) { var args = [ this.findIndex( priority ), 0 ]; for ( var i = 0, len = rules.length; i < len; i++ ) { args.push( { value: rules[ i ], priority: priority, options: options } ); } this.rules.splice.apply( this.rules, args ); }
[ "function", "(", "rules", ",", "priority", ",", "options", ")", "{", "var", "args", "=", "[", "this", ".", "findIndex", "(", "priority", ")", ",", "0", "]", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "rules", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "args", ".", "push", "(", "{", "value", ":", "rules", "[", "i", "]", ",", "priority", ":", "priority", ",", "options", ":", "options", "}", ")", ";", "}", "this", ".", "rules", ".", "splice", ".", "apply", "(", "this", ".", "rules", ",", "args", ")", ";", "}" ]
Adds specified rules to this group. @param {Array} rules Array of rules - see {@link #add}. @param {Number} priority @param options
[ "Adds", "specified", "rules", "to", "this", "group", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/htmlparser/filter.js#L277-L289
57,980
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/htmlparser/filter.js
function( priority ) { var rules = this.rules, len = rules.length, i = len - 1; // Search from the end, because usually rules will be added with default priority, so // we will be able to stop loop quickly. while ( i >= 0 && priority < rules[ i ].priority ) i--; return i + 1; }
javascript
function( priority ) { var rules = this.rules, len = rules.length, i = len - 1; // Search from the end, because usually rules will be added with default priority, so // we will be able to stop loop quickly. while ( i >= 0 && priority < rules[ i ].priority ) i--; return i + 1; }
[ "function", "(", "priority", ")", "{", "var", "rules", "=", "this", ".", "rules", ",", "len", "=", "rules", ".", "length", ",", "i", "=", "len", "-", "1", ";", "// Search from the end, because usually rules will be added with default priority, so", "// we will be able to stop loop quickly.", "while", "(", "i", ">=", "0", "&&", "priority", "<", "rules", "[", "i", "]", ".", "priority", ")", "i", "--", ";", "return", "i", "+", "1", ";", "}" ]
Finds an index at which rule with given priority should be inserted. @param {Number} priority @returns {Number} Index.
[ "Finds", "an", "index", "at", "which", "rule", "with", "given", "priority", "should", "be", "inserted", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/htmlparser/filter.js#L297-L308
57,981
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/htmlparser/filter.js
function( context, currentValue ) { var isNode = currentValue instanceof CKEDITOR.htmlParser.node || currentValue instanceof CKEDITOR.htmlParser.fragment, // Splice '1' to remove context, which we don't want to pass to filter rules. args = Array.prototype.slice.call( arguments, 1 ), rules = this.rules, len = rules.length, orgType, orgName, ret, i, rule; for ( i = 0; i < len; i++ ) { // Backup the node info before filtering. if ( isNode ) { orgType = currentValue.type; orgName = currentValue.name; } rule = rules[ i ]; if ( isRuleApplicable( context, rule ) ) { ret = rule.value.apply( null, args ); if ( ret === false ) return ret; // We're filtering node (element/fragment). // No further filtering if it's not anymore fitable for the subsequent filters. if ( isNode && ret && ( ret.name != orgName || ret.type != orgType ) ) return ret; // Update currentValue and corresponding argument in args array. // Updated values will be used in next for-loop step. if ( ret != null ) args[ 0 ] = currentValue = ret; // ret == undefined will continue loop as nothing has happened. } } return currentValue; }
javascript
function( context, currentValue ) { var isNode = currentValue instanceof CKEDITOR.htmlParser.node || currentValue instanceof CKEDITOR.htmlParser.fragment, // Splice '1' to remove context, which we don't want to pass to filter rules. args = Array.prototype.slice.call( arguments, 1 ), rules = this.rules, len = rules.length, orgType, orgName, ret, i, rule; for ( i = 0; i < len; i++ ) { // Backup the node info before filtering. if ( isNode ) { orgType = currentValue.type; orgName = currentValue.name; } rule = rules[ i ]; if ( isRuleApplicable( context, rule ) ) { ret = rule.value.apply( null, args ); if ( ret === false ) return ret; // We're filtering node (element/fragment). // No further filtering if it's not anymore fitable for the subsequent filters. if ( isNode && ret && ( ret.name != orgName || ret.type != orgType ) ) return ret; // Update currentValue and corresponding argument in args array. // Updated values will be used in next for-loop step. if ( ret != null ) args[ 0 ] = currentValue = ret; // ret == undefined will continue loop as nothing has happened. } } return currentValue; }
[ "function", "(", "context", ",", "currentValue", ")", "{", "var", "isNode", "=", "currentValue", "instanceof", "CKEDITOR", ".", "htmlParser", ".", "node", "||", "currentValue", "instanceof", "CKEDITOR", ".", "htmlParser", ".", "fragment", ",", "// Splice '1' to remove context, which we don't want to pass to filter rules.", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ",", "rules", "=", "this", ".", "rules", ",", "len", "=", "rules", ".", "length", ",", "orgType", ",", "orgName", ",", "ret", ",", "i", ",", "rule", ";", "for", "(", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "// Backup the node info before filtering.", "if", "(", "isNode", ")", "{", "orgType", "=", "currentValue", ".", "type", ";", "orgName", "=", "currentValue", ".", "name", ";", "}", "rule", "=", "rules", "[", "i", "]", ";", "if", "(", "isRuleApplicable", "(", "context", ",", "rule", ")", ")", "{", "ret", "=", "rule", ".", "value", ".", "apply", "(", "null", ",", "args", ")", ";", "if", "(", "ret", "===", "false", ")", "return", "ret", ";", "// We're filtering node (element/fragment).", "// No further filtering if it's not anymore fitable for the subsequent filters.", "if", "(", "isNode", "&&", "ret", "&&", "(", "ret", ".", "name", "!=", "orgName", "||", "ret", ".", "type", "!=", "orgType", ")", ")", "return", "ret", ";", "// Update currentValue and corresponding argument in args array.", "// Updated values will be used in next for-loop step.", "if", "(", "ret", "!=", "null", ")", "args", "[", "0", "]", "=", "currentValue", "=", "ret", ";", "// ret == undefined will continue loop as nothing has happened.", "}", "}", "return", "currentValue", ";", "}" ]
Executes this rules group on given value. Applicable only if function based rules were added. All arguments passed to this function will be forwarded to rules' functions. @param {CKEDITOR.htmlParser.node/CKEDITOR.htmlParser.fragment/String} currentValue The value to be filtered. @returns {CKEDITOR.htmlParser.node/CKEDITOR.htmlParser.fragment/String} Filtered value.
[ "Executes", "this", "rules", "group", "on", "given", "value", ".", "Applicable", "only", "if", "function", "based", "rules", "were", "added", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/htmlparser/filter.js#L318-L355
57,982
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/htmlparser/filter.js
function( context, currentName ) { var i = 0, rules = this.rules, len = rules.length, rule; for ( ; currentName && i < len; i++ ) { rule = rules[ i ]; if ( isRuleApplicable( context, rule ) ) currentName = currentName.replace( rule.value[ 0 ], rule.value[ 1 ] ); } return currentName; }
javascript
function( context, currentName ) { var i = 0, rules = this.rules, len = rules.length, rule; for ( ; currentName && i < len; i++ ) { rule = rules[ i ]; if ( isRuleApplicable( context, rule ) ) currentName = currentName.replace( rule.value[ 0 ], rule.value[ 1 ] ); } return currentName; }
[ "function", "(", "context", ",", "currentName", ")", "{", "var", "i", "=", "0", ",", "rules", "=", "this", ".", "rules", ",", "len", "=", "rules", ".", "length", ",", "rule", ";", "for", "(", ";", "currentName", "&&", "i", "<", "len", ";", "i", "++", ")", "{", "rule", "=", "rules", "[", "i", "]", ";", "if", "(", "isRuleApplicable", "(", "context", ",", "rule", ")", ")", "currentName", "=", "currentName", ".", "replace", "(", "rule", ".", "value", "[", "0", "]", ",", "rule", ".", "value", "[", "1", "]", ")", ";", "}", "return", "currentName", ";", "}" ]
Executes this rules group on name. Applicable only if filter rules for names were added. @param {String} currentName The name to be filtered. @returns {String} Filtered name.
[ "Executes", "this", "rules", "group", "on", "name", ".", "Applicable", "only", "if", "filter", "rules", "for", "names", "were", "added", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/htmlparser/filter.js#L363-L376
57,983
jurca/idb-entity
es2015/utils.js
getField
function getField(object, fieldPath) { let currentObject = object for (let fieldName of fieldPath.split(".")) { if (!currentObject.hasOwnProperty(fieldName)) { return undefined } currentObject = currentObject[fieldName] } return currentObject }
javascript
function getField(object, fieldPath) { let currentObject = object for (let fieldName of fieldPath.split(".")) { if (!currentObject.hasOwnProperty(fieldName)) { return undefined } currentObject = currentObject[fieldName] } return currentObject }
[ "function", "getField", "(", "object", ",", "fieldPath", ")", "{", "let", "currentObject", "=", "object", "for", "(", "let", "fieldName", "of", "fieldPath", ".", "split", "(", "\".\"", ")", ")", "{", "if", "(", "!", "currentObject", ".", "hasOwnProperty", "(", "fieldName", ")", ")", "{", "return", "undefined", "}", "currentObject", "=", "currentObject", "[", "fieldName", "]", "}", "return", "currentObject", "}" ]
Returns the value of the field at the specified field path of the provided object. @param {Object} object The object from which the field path value should be extracted. @param {string} fieldPath The path to the field from which the value should be returned. The field path must be a sequence of valid ECMAScript identifiers separated by dots. @return {*} The value of the field at the specified field path.
[ "Returns", "the", "value", "of", "the", "field", "at", "the", "specified", "field", "path", "of", "the", "provided", "object", "." ]
361ef8482872d9fc9a0d83b86970d49d391dc276
https://github.com/jurca/idb-entity/blob/361ef8482872d9fc9a0d83b86970d49d391dc276/es2015/utils.js#L164-L176
57,984
jurca/idb-entity
es2015/utils.js
setField
function setField(object, fieldPath, value) { let currentObject = object let fieldNames = fieldPath.split(".") for (let fieldName of fieldNames.slice(0, -1)) { if (!currentObject.hasOwnProperty(fieldName)) { currentObject[fieldName] = {} } currentObject = currentObject[fieldName] } currentObject[fieldNames.pop()] = value }
javascript
function setField(object, fieldPath, value) { let currentObject = object let fieldNames = fieldPath.split(".") for (let fieldName of fieldNames.slice(0, -1)) { if (!currentObject.hasOwnProperty(fieldName)) { currentObject[fieldName] = {} } currentObject = currentObject[fieldName] } currentObject[fieldNames.pop()] = value }
[ "function", "setField", "(", "object", ",", "fieldPath", ",", "value", ")", "{", "let", "currentObject", "=", "object", "let", "fieldNames", "=", "fieldPath", ".", "split", "(", "\".\"", ")", "for", "(", "let", "fieldName", "of", "fieldNames", ".", "slice", "(", "0", ",", "-", "1", ")", ")", "{", "if", "(", "!", "currentObject", ".", "hasOwnProperty", "(", "fieldName", ")", ")", "{", "currentObject", "[", "fieldName", "]", "=", "{", "}", "}", "currentObject", "=", "currentObject", "[", "fieldName", "]", "}", "currentObject", "[", "fieldNames", ".", "pop", "(", ")", "]", "=", "value", "}" ]
Sets the field at the specified field path to the provided value in the provided object. The function creates the field path out of empty plain objects if it does not already exist. @param {Object} object The object in which the specified field path should be set to the provided value. @param {string} fieldPath The field path at which the value should be set. The field path must be a sequence of valid ECMAScript identifiers separated by dots. @param {*} value The value to set.
[ "Sets", "the", "field", "at", "the", "specified", "field", "path", "to", "the", "provided", "value", "in", "the", "provided", "object", "." ]
361ef8482872d9fc9a0d83b86970d49d391dc276
https://github.com/jurca/idb-entity/blob/361ef8482872d9fc9a0d83b86970d49d391dc276/es2015/utils.js#L192-L205
57,985
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/removeformat/plugin.js
function( editor, element ) { // If editor#addRemoveFotmatFilter hasn't been executed yet value is not initialized. var filters = editor._.removeFormatFilters || []; for ( var i = 0; i < filters.length; i++ ) { if ( filters[ i ]( element ) === false ) return false; } return true; }
javascript
function( editor, element ) { // If editor#addRemoveFotmatFilter hasn't been executed yet value is not initialized. var filters = editor._.removeFormatFilters || []; for ( var i = 0; i < filters.length; i++ ) { if ( filters[ i ]( element ) === false ) return false; } return true; }
[ "function", "(", "editor", ",", "element", ")", "{", "// If editor#addRemoveFotmatFilter hasn't been executed yet value is not initialized.\r", "var", "filters", "=", "editor", ".", "_", ".", "removeFormatFilters", "||", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "filters", ".", "length", ";", "i", "++", ")", "{", "if", "(", "filters", "[", "i", "]", "(", "element", ")", "===", "false", ")", "return", "false", ";", "}", "return", "true", ";", "}" ]
Perform the remove format filters on the passed element. @param {CKEDITOR.editor} editor @param {CKEDITOR.dom.element} element
[ "Perform", "the", "remove", "format", "filters", "on", "the", "passed", "element", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/removeformat/plugin.js#L131-L139
57,986
sourdough-css/preprocessor
bin/logger.js
format
function format (type, msg, typeColor, msgColor) { type = type || ''; msg = msg || ''; typeColor = typeColor || 'blue'; msgColor = msgColor || 'grey'; type = pad(type, 12); return type[typeColor] + ' · ' + msg[msgColor]; }
javascript
function format (type, msg, typeColor, msgColor) { type = type || ''; msg = msg || ''; typeColor = typeColor || 'blue'; msgColor = msgColor || 'grey'; type = pad(type, 12); return type[typeColor] + ' · ' + msg[msgColor]; }
[ "function", "format", "(", "type", ",", "msg", ",", "typeColor", ",", "msgColor", ")", "{", "type", "=", "type", "||", "''", ";", "msg", "=", "msg", "||", "''", ";", "typeColor", "=", "typeColor", "||", "'blue'", ";", "msgColor", "=", "msgColor", "||", "'grey'", ";", "type", "=", "pad", "(", "type", ",", "12", ")", ";", "return", "type", "[", "typeColor", "]", "+", "' · ' ", " ", "sg[", "m", "sgColor]", ";", "", "}" ]
Format a `type` and `msg` with `typeColor` and `msgColor`. @param {String} type @param {String} msg @param {String} typeColor (optional) @param {String} msgColor (optional)
[ "Format", "a", "type", "and", "msg", "with", "typeColor", "and", "msgColor", "." ]
d065000ac3c7c31524058793409de2f78a092d04
https://github.com/sourdough-css/preprocessor/blob/d065000ac3c7c31524058793409de2f78a092d04/bin/logger.js#L97-L104
57,987
meisterplayer/js-dev
gulp/versioning.js
createBumpVersion
function createBumpVersion(inPath, type) { if (!inPath) { throw new Error('Input path(s) argument is required'); } return function bumpVersion() { return gulp.src(inPath) .pipe(bump({ type })) .pipe(gulp.dest(file => file.base)); }; }
javascript
function createBumpVersion(inPath, type) { if (!inPath) { throw new Error('Input path(s) argument is required'); } return function bumpVersion() { return gulp.src(inPath) .pipe(bump({ type })) .pipe(gulp.dest(file => file.base)); }; }
[ "function", "createBumpVersion", "(", "inPath", ",", "type", ")", "{", "if", "(", "!", "inPath", ")", "{", "throw", "new", "Error", "(", "'Input path(s) argument is required'", ")", ";", "}", "return", "function", "bumpVersion", "(", ")", "{", "return", "gulp", ".", "src", "(", "inPath", ")", ".", "pipe", "(", "bump", "(", "{", "type", "}", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "file", "=>", "file", ".", "base", ")", ")", ";", "}", ";", "}" ]
Higher order function to create gulp function that bumps the version in the package.json. @param {string} inPath Path to the project's package.json @return {function} Function that can be used as a gulp task
[ "Higher", "order", "function", "to", "create", "gulp", "function", "that", "bumps", "the", "version", "in", "the", "package", ".", "json", "." ]
c2646678c49dcdaa120ba3f24824da52b0c63e31
https://github.com/meisterplayer/js-dev/blob/c2646678c49dcdaa120ba3f24824da52b0c63e31/gulp/versioning.js#L11-L21
57,988
meisterplayer/js-dev
gulp/versioning.js
createReplaceVersion
function createReplaceVersion(inPath, version, opts = {}) { if (!inPath) { throw new Error('Input path(s) argument is required'); } if (!version) { throw new Error('Version argument is required'); } const dropV = !!opts.dropV; const versionRegex = dropV ? /[0-9]+\.[0-9]+\.[0-9]+\b/g : /v[0-9]+\.[0-9]+\.[0-9]+\b/g; const versionString = dropV ? version : `v${version}`; return function updateVersions() { return gulp.src(inPath) .pipe(replace(versionRegex, versionString)) .pipe(gulp.dest(file => file.base)); }; }
javascript
function createReplaceVersion(inPath, version, opts = {}) { if (!inPath) { throw new Error('Input path(s) argument is required'); } if (!version) { throw new Error('Version argument is required'); } const dropV = !!opts.dropV; const versionRegex = dropV ? /[0-9]+\.[0-9]+\.[0-9]+\b/g : /v[0-9]+\.[0-9]+\.[0-9]+\b/g; const versionString = dropV ? version : `v${version}`; return function updateVersions() { return gulp.src(inPath) .pipe(replace(versionRegex, versionString)) .pipe(gulp.dest(file => file.base)); }; }
[ "function", "createReplaceVersion", "(", "inPath", ",", "version", ",", "opts", "=", "{", "}", ")", "{", "if", "(", "!", "inPath", ")", "{", "throw", "new", "Error", "(", "'Input path(s) argument is required'", ")", ";", "}", "if", "(", "!", "version", ")", "{", "throw", "new", "Error", "(", "'Version argument is required'", ")", ";", "}", "const", "dropV", "=", "!", "!", "opts", ".", "dropV", ";", "const", "versionRegex", "=", "dropV", "?", "/", "[0-9]+\\.[0-9]+\\.[0-9]+\\b", "/", "g", ":", "/", "v[0-9]+\\.[0-9]+\\.[0-9]+\\b", "/", "g", ";", "const", "versionString", "=", "dropV", "?", "version", ":", "`", "${", "version", "}", "`", ";", "return", "function", "updateVersions", "(", ")", "{", "return", "gulp", ".", "src", "(", "inPath", ")", ".", "pipe", "(", "replace", "(", "versionRegex", ",", "versionString", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "file", "=>", "file", ".", "base", ")", ")", ";", "}", ";", "}" ]
Higher order function to create gulp function that replaces instances of the version number with the new version. @param {string|string[]} inPath The globs to the files that need to be searched @param {string} version The version to update to without a leading 'v' @param {Object} [opts={}] Extra options for replace @param {string} [opts.dropV=false] Optional flag to search/replace 'X.Y.Z' instead of 'vX.Y.Z' @return {function} Function that can be used as a gulp task
[ "Higher", "order", "function", "to", "create", "gulp", "function", "that", "replaces", "instances", "of", "the", "version", "number", "with", "the", "new", "version", "." ]
c2646678c49dcdaa120ba3f24824da52b0c63e31
https://github.com/meisterplayer/js-dev/blob/c2646678c49dcdaa120ba3f24824da52b0c63e31/gulp/versioning.js#L32-L50
57,989
meisterplayer/js-dev
gulp/versioning.js
extractPackageVersion
function extractPackageVersion(inPath) { if (!inPath) { throw new Error('Input path argument is required'); } // Require here so we have the update version. const pkg = fs.readFileSync(inPath, 'utf-8'); // index 0 is line that matched, index 1 is first control group (version number in this case) const matches = /"version": "([0-9]+\.[0-9]+\.[0-9]+)"/.exec(pkg); const version = matches[1]; return version; }
javascript
function extractPackageVersion(inPath) { if (!inPath) { throw new Error('Input path argument is required'); } // Require here so we have the update version. const pkg = fs.readFileSync(inPath, 'utf-8'); // index 0 is line that matched, index 1 is first control group (version number in this case) const matches = /"version": "([0-9]+\.[0-9]+\.[0-9]+)"/.exec(pkg); const version = matches[1]; return version; }
[ "function", "extractPackageVersion", "(", "inPath", ")", "{", "if", "(", "!", "inPath", ")", "{", "throw", "new", "Error", "(", "'Input path argument is required'", ")", ";", "}", "// Require here so we have the update version.", "const", "pkg", "=", "fs", ".", "readFileSync", "(", "inPath", ",", "'utf-8'", ")", ";", "// index 0 is line that matched, index 1 is first control group (version number in this case)", "const", "matches", "=", "/", "\"version\": \"([0-9]+\\.[0-9]+\\.[0-9]+)\"", "/", ".", "exec", "(", "pkg", ")", ";", "const", "version", "=", "matches", "[", "1", "]", ";", "return", "version", ";", "}" ]
Sync function that takes a package.json path and extracts the version from it. @param {string} inPath Path to the project's package.json @return {string} The extracted version number in the form 'X.Y.Z'
[ "Sync", "function", "that", "takes", "a", "package", ".", "json", "path", "and", "extracts", "the", "version", "from", "it", "." ]
c2646678c49dcdaa120ba3f24824da52b0c63e31
https://github.com/meisterplayer/js-dev/blob/c2646678c49dcdaa120ba3f24824da52b0c63e31/gulp/versioning.js#L57-L70
57,990
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialogadvtab/plugin.js
function( tabConfig ) { if ( !tabConfig ) tabConfig = defaultTabConfig; var allowedAttrs = []; if ( tabConfig.id ) allowedAttrs.push( 'id' ); if ( tabConfig.dir ) allowedAttrs.push( 'dir' ); var allowed = ''; if ( allowedAttrs.length ) allowed += '[' + allowedAttrs.join( ',' ) + ']'; if ( tabConfig.classes ) allowed += '(*)'; if ( tabConfig.styles ) allowed += '{*}'; return allowed; }
javascript
function( tabConfig ) { if ( !tabConfig ) tabConfig = defaultTabConfig; var allowedAttrs = []; if ( tabConfig.id ) allowedAttrs.push( 'id' ); if ( tabConfig.dir ) allowedAttrs.push( 'dir' ); var allowed = ''; if ( allowedAttrs.length ) allowed += '[' + allowedAttrs.join( ',' ) + ']'; if ( tabConfig.classes ) allowed += '(*)'; if ( tabConfig.styles ) allowed += '{*}'; return allowed; }
[ "function", "(", "tabConfig", ")", "{", "if", "(", "!", "tabConfig", ")", "tabConfig", "=", "defaultTabConfig", ";", "var", "allowedAttrs", "=", "[", "]", ";", "if", "(", "tabConfig", ".", "id", ")", "allowedAttrs", ".", "push", "(", "'id'", ")", ";", "if", "(", "tabConfig", ".", "dir", ")", "allowedAttrs", ".", "push", "(", "'dir'", ")", ";", "var", "allowed", "=", "''", ";", "if", "(", "allowedAttrs", ".", "length", ")", "allowed", "+=", "'['", "+", "allowedAttrs", ".", "join", "(", "','", ")", "+", "']'", ";", "if", "(", "tabConfig", ".", "classes", ")", "allowed", "+=", "'(*)'", ";", "if", "(", "tabConfig", ".", "styles", ")", "allowed", "+=", "'{*}'", ";", "return", "allowed", ";", "}" ]
Returns allowed content rule for the content created by this plugin.
[ "Returns", "allowed", "content", "rule", "for", "the", "content", "created", "by", "this", "plugin", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialogadvtab/plugin.js#L46-L67
57,991
fs-utils/download-cache
index.js
download
function download(url) { if (!validator.isURL(url)) return Promise.reject(error(400, 'Invalid URL: ' + url)); // download in progress if (progress[sha]) return progress[sha]; var sha = hash(url); return progress[sha] = cache.access(sha).then(function (filename) { if (filename) return filename; return request(url) .redirects(3) .agent(false) .then(function (response) { assert(response.status < 400, response.status, 'Got status code ' + response.status + ' from ' + url); assert(response.status === 200, 'Got status code ' + response.status + ' from ' + url); debug('Downloading %s -> %s', url, sha); return cache.copy(sha, response.response); }); }).then(function (filename) { delete progress[sha]; return filename; }, /* istanbul ignore next */ function (err) { delete progress[sha]; throw err; }); }
javascript
function download(url) { if (!validator.isURL(url)) return Promise.reject(error(400, 'Invalid URL: ' + url)); // download in progress if (progress[sha]) return progress[sha]; var sha = hash(url); return progress[sha] = cache.access(sha).then(function (filename) { if (filename) return filename; return request(url) .redirects(3) .agent(false) .then(function (response) { assert(response.status < 400, response.status, 'Got status code ' + response.status + ' from ' + url); assert(response.status === 200, 'Got status code ' + response.status + ' from ' + url); debug('Downloading %s -> %s', url, sha); return cache.copy(sha, response.response); }); }).then(function (filename) { delete progress[sha]; return filename; }, /* istanbul ignore next */ function (err) { delete progress[sha]; throw err; }); }
[ "function", "download", "(", "url", ")", "{", "if", "(", "!", "validator", ".", "isURL", "(", "url", ")", ")", "return", "Promise", ".", "reject", "(", "error", "(", "400", ",", "'Invalid URL: '", "+", "url", ")", ")", ";", "// download in progress", "if", "(", "progress", "[", "sha", "]", ")", "return", "progress", "[", "sha", "]", ";", "var", "sha", "=", "hash", "(", "url", ")", ";", "return", "progress", "[", "sha", "]", "=", "cache", ".", "access", "(", "sha", ")", ".", "then", "(", "function", "(", "filename", ")", "{", "if", "(", "filename", ")", "return", "filename", ";", "return", "request", "(", "url", ")", ".", "redirects", "(", "3", ")", ".", "agent", "(", "false", ")", ".", "then", "(", "function", "(", "response", ")", "{", "assert", "(", "response", ".", "status", "<", "400", ",", "response", ".", "status", ",", "'Got status code '", "+", "response", ".", "status", "+", "' from '", "+", "url", ")", ";", "assert", "(", "response", ".", "status", "===", "200", ",", "'Got status code '", "+", "response", ".", "status", "+", "' from '", "+", "url", ")", ";", "debug", "(", "'Downloading %s -> %s'", ",", "url", ",", "sha", ")", ";", "return", "cache", ".", "copy", "(", "sha", ",", "response", ".", "response", ")", ";", "}", ")", ";", "}", ")", ".", "then", "(", "function", "(", "filename", ")", "{", "delete", "progress", "[", "sha", "]", ";", "return", "filename", ";", "}", ",", "/* istanbul ignore next */", "function", "(", "err", ")", "{", "delete", "progress", "[", "sha", "]", ";", "throw", "err", ";", "}", ")", ";", "}" ]
If the locally exists locally, use that. Otherwise, download it and return the filename. We cache by the sha of the URL.
[ "If", "the", "locally", "exists", "locally", "use", "that", ".", "Otherwise", "download", "it", "and", "return", "the", "filename", ".", "We", "cache", "by", "the", "sha", "of", "the", "URL", "." ]
67229900608e211082d36d5419fffc6270669dd6
https://github.com/fs-utils/download-cache/blob/67229900608e211082d36d5419fffc6270669dd6/index.js#L30-L56
57,992
airbrite/muni
adapter.js
function(body) { if (_.isString(body)) { return body; } else if (_.isObject(body) && _.isString(body.error)) { return body.error; } else if (_.isObject(body) && _.isString(body.msg)) { return body.msg; } else if (_.isObject(body) && _.isObject(body.error)) { return this._extractError(body.error); } else if (_.isObject(body) && _.isString(body.message)) { return body.message; } else if (_.isObject(body) && body.meta && _.isString(body.meta.error_message)) { return body.meta.error_message; } else { return 'Unknown Request Error'; } }
javascript
function(body) { if (_.isString(body)) { return body; } else if (_.isObject(body) && _.isString(body.error)) { return body.error; } else if (_.isObject(body) && _.isString(body.msg)) { return body.msg; } else if (_.isObject(body) && _.isObject(body.error)) { return this._extractError(body.error); } else if (_.isObject(body) && _.isString(body.message)) { return body.message; } else if (_.isObject(body) && body.meta && _.isString(body.meta.error_message)) { return body.meta.error_message; } else { return 'Unknown Request Error'; } }
[ "function", "(", "body", ")", "{", "if", "(", "_", ".", "isString", "(", "body", ")", ")", "{", "return", "body", ";", "}", "else", "if", "(", "_", ".", "isObject", "(", "body", ")", "&&", "_", ".", "isString", "(", "body", ".", "error", ")", ")", "{", "return", "body", ".", "error", ";", "}", "else", "if", "(", "_", ".", "isObject", "(", "body", ")", "&&", "_", ".", "isString", "(", "body", ".", "msg", ")", ")", "{", "return", "body", ".", "msg", ";", "}", "else", "if", "(", "_", ".", "isObject", "(", "body", ")", "&&", "_", ".", "isObject", "(", "body", ".", "error", ")", ")", "{", "return", "this", ".", "_extractError", "(", "body", ".", "error", ")", ";", "}", "else", "if", "(", "_", ".", "isObject", "(", "body", ")", "&&", "_", ".", "isString", "(", "body", ".", "message", ")", ")", "{", "return", "body", ".", "message", ";", "}", "else", "if", "(", "_", ".", "isObject", "(", "body", ")", "&&", "body", ".", "meta", "&&", "_", ".", "isString", "(", "body", ".", "meta", ".", "error_message", ")", ")", "{", "return", "body", ".", "meta", ".", "error_message", ";", "}", "else", "{", "return", "'Unknown Request Error'", ";", "}", "}" ]
If there's an error, try your damndest to find it. APIs hide errors in all sorts of places these days @param {String|Object} body @return {String}
[ "If", "there", "s", "an", "error", "try", "your", "damndest", "to", "find", "it", ".", "APIs", "hide", "errors", "in", "all", "sorts", "of", "places", "these", "days" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/adapter.js#L23-L41
57,993
airbrite/muni
adapter.js
function(options) { options = options || {}; // Set default path if (!options.url && !options.path) { options.path = ''; } // Prepare the request var requestOptions = { method: options.method || 'GET', url: options.url || this.urlRoot + options.path, qs: options.qs || {}, headers: options.headers || {}, }; // Add `form`, `body`, or `json` as Request Payload (only one per request) // // If `json` is a Boolean, // Request will set` Content-Type` // and call `JSON.stringify()` on `body` if (options.body) { requestOptions.body = options.body; requestOptions.json = _.isBoolean(options.json) ? options.json : true; } else if (options.form) { requestOptions.form = options.form; requestOptions.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'; } else if (_.isBoolean(options.json) || _.isObject(options.json)) { requestOptions.json = options.json; } // Basic HTTP Auth if (options.auth) { requestOptions.auth = options.auth; } // Access Token var accessToken = options.access_token || this.get('access_token'); if (accessToken) { _.defaults(requestOptions.headers, { Authorization: ['Bearer', accessToken].join(' ') }); } // OAuth Token var oauthToken = options.oauth_token || this.get('oauth_token'); if (oauthToken) { _.defaults(requestOptions.headers, { Authorization: ['OAuth', oauthToken].join(' ') }); } // Authorization Token (No Scheme) var authorizationToken = options.authorization_token || this.get('authorization_token'); if (authorizationToken) { _.defaults(requestOptions.headers, { Authorization: authorizationToken }); } return requestOptions; }
javascript
function(options) { options = options || {}; // Set default path if (!options.url && !options.path) { options.path = ''; } // Prepare the request var requestOptions = { method: options.method || 'GET', url: options.url || this.urlRoot + options.path, qs: options.qs || {}, headers: options.headers || {}, }; // Add `form`, `body`, or `json` as Request Payload (only one per request) // // If `json` is a Boolean, // Request will set` Content-Type` // and call `JSON.stringify()` on `body` if (options.body) { requestOptions.body = options.body; requestOptions.json = _.isBoolean(options.json) ? options.json : true; } else if (options.form) { requestOptions.form = options.form; requestOptions.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'; } else if (_.isBoolean(options.json) || _.isObject(options.json)) { requestOptions.json = options.json; } // Basic HTTP Auth if (options.auth) { requestOptions.auth = options.auth; } // Access Token var accessToken = options.access_token || this.get('access_token'); if (accessToken) { _.defaults(requestOptions.headers, { Authorization: ['Bearer', accessToken].join(' ') }); } // OAuth Token var oauthToken = options.oauth_token || this.get('oauth_token'); if (oauthToken) { _.defaults(requestOptions.headers, { Authorization: ['OAuth', oauthToken].join(' ') }); } // Authorization Token (No Scheme) var authorizationToken = options.authorization_token || this.get('authorization_token'); if (authorizationToken) { _.defaults(requestOptions.headers, { Authorization: authorizationToken }); } return requestOptions; }
[ "function", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "// Set default path", "if", "(", "!", "options", ".", "url", "&&", "!", "options", ".", "path", ")", "{", "options", ".", "path", "=", "''", ";", "}", "// Prepare the request", "var", "requestOptions", "=", "{", "method", ":", "options", ".", "method", "||", "'GET'", ",", "url", ":", "options", ".", "url", "||", "this", ".", "urlRoot", "+", "options", ".", "path", ",", "qs", ":", "options", ".", "qs", "||", "{", "}", ",", "headers", ":", "options", ".", "headers", "||", "{", "}", ",", "}", ";", "// Add `form`, `body`, or `json` as Request Payload (only one per request)", "//", "// If `json` is a Boolean,", "// Request will set` Content-Type`", "// and call `JSON.stringify()` on `body`", "if", "(", "options", ".", "body", ")", "{", "requestOptions", ".", "body", "=", "options", ".", "body", ";", "requestOptions", ".", "json", "=", "_", ".", "isBoolean", "(", "options", ".", "json", ")", "?", "options", ".", "json", ":", "true", ";", "}", "else", "if", "(", "options", ".", "form", ")", "{", "requestOptions", ".", "form", "=", "options", ".", "form", ";", "requestOptions", ".", "headers", "[", "'Content-Type'", "]", "=", "'application/x-www-form-urlencoded; charset=utf-8'", ";", "}", "else", "if", "(", "_", ".", "isBoolean", "(", "options", ".", "json", ")", "||", "_", ".", "isObject", "(", "options", ".", "json", ")", ")", "{", "requestOptions", ".", "json", "=", "options", ".", "json", ";", "}", "// Basic HTTP Auth", "if", "(", "options", ".", "auth", ")", "{", "requestOptions", ".", "auth", "=", "options", ".", "auth", ";", "}", "// Access Token", "var", "accessToken", "=", "options", ".", "access_token", "||", "this", ".", "get", "(", "'access_token'", ")", ";", "if", "(", "accessToken", ")", "{", "_", ".", "defaults", "(", "requestOptions", ".", "headers", ",", "{", "Authorization", ":", "[", "'Bearer'", ",", "accessToken", "]", ".", "join", "(", "' '", ")", "}", ")", ";", "}", "// OAuth Token", "var", "oauthToken", "=", "options", ".", "oauth_token", "||", "this", ".", "get", "(", "'oauth_token'", ")", ";", "if", "(", "oauthToken", ")", "{", "_", ".", "defaults", "(", "requestOptions", ".", "headers", ",", "{", "Authorization", ":", "[", "'OAuth'", ",", "oauthToken", "]", ".", "join", "(", "' '", ")", "}", ")", ";", "}", "// Authorization Token (No Scheme)", "var", "authorizationToken", "=", "options", ".", "authorization_token", "||", "this", ".", "get", "(", "'authorization_token'", ")", ";", "if", "(", "authorizationToken", ")", "{", "_", ".", "defaults", "(", "requestOptions", ".", "headers", ",", "{", "Authorization", ":", "authorizationToken", "}", ")", ";", "}", "return", "requestOptions", ";", "}" ]
Build and configure the request options @param {Object} options @param {String} options.url @param {String} [options.path=] @param {String} [options.method=GET] @param {String} [options.qs={}] @param {String} [options.headers={}] @param {String} options.json @param {String} options.form @param {String} options.body @param {String} options.access_token @param {String} options.oauth_token @param {String} options.authorization_token @param {String} options.auth @return {Object}
[ "Build", "and", "configure", "the", "request", "options" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/adapter.js#L62-L123
57,994
airbrite/muni
adapter.js
function(options, callback) { // Create a promise to defer to later var deferred = Bluebird.defer(); // Fire the request request(this._buildRequestOptions(options), function(err, response, body) { // Handle Errors if (err) { // Usually a connection error (server unresponsive) err = new MuniError(err.message || 'Internal Server Error', err.code || 500); } else if (response.statusCode >= 400) { // Usually an intentional error from the server err = new MuniError(this._extractError(body), response.statusCode); } if (err) { debug.warn('Adapter Request Error with Code: %d', err.code); callback && callback(err); return deferred.reject(err); } // Handle Success debug.info('Adapter Request Sent with code: %d', response.statusCode); callback && callback(null, body); return deferred.resolve(body); }.bind(this)); return deferred.promise; }
javascript
function(options, callback) { // Create a promise to defer to later var deferred = Bluebird.defer(); // Fire the request request(this._buildRequestOptions(options), function(err, response, body) { // Handle Errors if (err) { // Usually a connection error (server unresponsive) err = new MuniError(err.message || 'Internal Server Error', err.code || 500); } else if (response.statusCode >= 400) { // Usually an intentional error from the server err = new MuniError(this._extractError(body), response.statusCode); } if (err) { debug.warn('Adapter Request Error with Code: %d', err.code); callback && callback(err); return deferred.reject(err); } // Handle Success debug.info('Adapter Request Sent with code: %d', response.statusCode); callback && callback(null, body); return deferred.resolve(body); }.bind(this)); return deferred.promise; }
[ "function", "(", "options", ",", "callback", ")", "{", "// Create a promise to defer to later", "var", "deferred", "=", "Bluebird", ".", "defer", "(", ")", ";", "// Fire the request", "request", "(", "this", ".", "_buildRequestOptions", "(", "options", ")", ",", "function", "(", "err", ",", "response", ",", "body", ")", "{", "// Handle Errors", "if", "(", "err", ")", "{", "// Usually a connection error (server unresponsive)", "err", "=", "new", "MuniError", "(", "err", ".", "message", "||", "'Internal Server Error'", ",", "err", ".", "code", "||", "500", ")", ";", "}", "else", "if", "(", "response", ".", "statusCode", ">=", "400", ")", "{", "// Usually an intentional error from the server", "err", "=", "new", "MuniError", "(", "this", ".", "_extractError", "(", "body", ")", ",", "response", ".", "statusCode", ")", ";", "}", "if", "(", "err", ")", "{", "debug", ".", "warn", "(", "'Adapter Request Error with Code: %d'", ",", "err", ".", "code", ")", ";", "callback", "&&", "callback", "(", "err", ")", ";", "return", "deferred", ".", "reject", "(", "err", ")", ";", "}", "// Handle Success", "debug", ".", "info", "(", "'Adapter Request Sent with code: %d'", ",", "response", ".", "statusCode", ")", ";", "callback", "&&", "callback", "(", "null", ",", "body", ")", ";", "return", "deferred", ".", "resolve", "(", "body", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Send an HTTP Request with provided request options @param {Object} options @param {Function} callback @return {Promise}
[ "Send", "an", "HTTP", "Request", "with", "provided", "request", "options" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/adapter.js#L133-L160
57,995
Industryswarm/isnode-mod-data
lib/mongodb/mongodb-core/lib/sdam/monitoring.js
monitorServer
function monitorServer(server) { // executes a single check of a server const checkServer = callback => { let start = process.hrtime(); // emit a signal indicating we have started the heartbeat server.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(server.name)); server.command( 'admin.$cmd', { ismaster: true }, { monitoring: true, socketTimeout: server.s.options.connectionTimeout || 2000 }, function(err, result) { let duration = calculateDurationInMs(start); if (err) { server.emit( 'serverHeartbeatFailed', new ServerHeartbeatFailedEvent(duration, err, server.name) ); return callback(err, null); } const isMaster = result.result; server.emit( 'serverHeartbeatSucceded', new ServerHeartbeatSucceededEvent(duration, isMaster, server.name) ); return callback(null, isMaster); } ); }; const successHandler = isMaster => { server.s.monitoring = false; // emit an event indicating that our description has changed server.emit('descriptionReceived', new ServerDescription(server.description.address, isMaster)); // schedule the next monitoring process server.s.monitorId = setTimeout( () => monitorServer(server), server.s.options.heartbeatFrequencyMS ); }; // run the actual monitoring loop server.s.monitoring = true; checkServer((err, isMaster) => { if (!err) { successHandler(isMaster); return; } // According to the SDAM specification's "Network error during server check" section, if // an ismaster call fails we reset the server's pool. If a server was once connected, // change its type to `Unknown` only after retrying once. // TODO: we need to reset the pool here return checkServer((err, isMaster) => { if (err) { server.s.monitoring = false; // revert to `Unknown` by emitting a default description with no isMaster server.emit('descriptionReceived', new ServerDescription(server.description.address)); // do not reschedule monitoring in this case return; } successHandler(isMaster); }); }); }
javascript
function monitorServer(server) { // executes a single check of a server const checkServer = callback => { let start = process.hrtime(); // emit a signal indicating we have started the heartbeat server.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(server.name)); server.command( 'admin.$cmd', { ismaster: true }, { monitoring: true, socketTimeout: server.s.options.connectionTimeout || 2000 }, function(err, result) { let duration = calculateDurationInMs(start); if (err) { server.emit( 'serverHeartbeatFailed', new ServerHeartbeatFailedEvent(duration, err, server.name) ); return callback(err, null); } const isMaster = result.result; server.emit( 'serverHeartbeatSucceded', new ServerHeartbeatSucceededEvent(duration, isMaster, server.name) ); return callback(null, isMaster); } ); }; const successHandler = isMaster => { server.s.monitoring = false; // emit an event indicating that our description has changed server.emit('descriptionReceived', new ServerDescription(server.description.address, isMaster)); // schedule the next monitoring process server.s.monitorId = setTimeout( () => monitorServer(server), server.s.options.heartbeatFrequencyMS ); }; // run the actual monitoring loop server.s.monitoring = true; checkServer((err, isMaster) => { if (!err) { successHandler(isMaster); return; } // According to the SDAM specification's "Network error during server check" section, if // an ismaster call fails we reset the server's pool. If a server was once connected, // change its type to `Unknown` only after retrying once. // TODO: we need to reset the pool here return checkServer((err, isMaster) => { if (err) { server.s.monitoring = false; // revert to `Unknown` by emitting a default description with no isMaster server.emit('descriptionReceived', new ServerDescription(server.description.address)); // do not reschedule monitoring in this case return; } successHandler(isMaster); }); }); }
[ "function", "monitorServer", "(", "server", ")", "{", "// executes a single check of a server", "const", "checkServer", "=", "callback", "=>", "{", "let", "start", "=", "process", ".", "hrtime", "(", ")", ";", "// emit a signal indicating we have started the heartbeat", "server", ".", "emit", "(", "'serverHeartbeatStarted'", ",", "new", "ServerHeartbeatStartedEvent", "(", "server", ".", "name", ")", ")", ";", "server", ".", "command", "(", "'admin.$cmd'", ",", "{", "ismaster", ":", "true", "}", ",", "{", "monitoring", ":", "true", ",", "socketTimeout", ":", "server", ".", "s", ".", "options", ".", "connectionTimeout", "||", "2000", "}", ",", "function", "(", "err", ",", "result", ")", "{", "let", "duration", "=", "calculateDurationInMs", "(", "start", ")", ";", "if", "(", "err", ")", "{", "server", ".", "emit", "(", "'serverHeartbeatFailed'", ",", "new", "ServerHeartbeatFailedEvent", "(", "duration", ",", "err", ",", "server", ".", "name", ")", ")", ";", "return", "callback", "(", "err", ",", "null", ")", ";", "}", "const", "isMaster", "=", "result", ".", "result", ";", "server", ".", "emit", "(", "'serverHeartbeatSucceded'", ",", "new", "ServerHeartbeatSucceededEvent", "(", "duration", ",", "isMaster", ",", "server", ".", "name", ")", ")", ";", "return", "callback", "(", "null", ",", "isMaster", ")", ";", "}", ")", ";", "}", ";", "const", "successHandler", "=", "isMaster", "=>", "{", "server", ".", "s", ".", "monitoring", "=", "false", ";", "// emit an event indicating that our description has changed", "server", ".", "emit", "(", "'descriptionReceived'", ",", "new", "ServerDescription", "(", "server", ".", "description", ".", "address", ",", "isMaster", ")", ")", ";", "// schedule the next monitoring process", "server", ".", "s", ".", "monitorId", "=", "setTimeout", "(", "(", ")", "=>", "monitorServer", "(", "server", ")", ",", "server", ".", "s", ".", "options", ".", "heartbeatFrequencyMS", ")", ";", "}", ";", "// run the actual monitoring loop", "server", ".", "s", ".", "monitoring", "=", "true", ";", "checkServer", "(", "(", "err", ",", "isMaster", ")", "=>", "{", "if", "(", "!", "err", ")", "{", "successHandler", "(", "isMaster", ")", ";", "return", ";", "}", "// According to the SDAM specification's \"Network error during server check\" section, if", "// an ismaster call fails we reset the server's pool. If a server was once connected,", "// change its type to `Unknown` only after retrying once.", "// TODO: we need to reset the pool here", "return", "checkServer", "(", "(", "err", ",", "isMaster", ")", "=>", "{", "if", "(", "err", ")", "{", "server", ".", "s", ".", "monitoring", "=", "false", ";", "// revert to `Unknown` by emitting a default description with no isMaster", "server", ".", "emit", "(", "'descriptionReceived'", ",", "new", "ServerDescription", "(", "server", ".", "description", ".", "address", ")", ")", ";", "// do not reschedule monitoring in this case", "return", ";", "}", "successHandler", "(", "isMaster", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Performs a server check as described by the SDAM spec. NOTE: This method automatically reschedules itself, so that there is always an active monitoring process @param {Server} server The server to monitor
[ "Performs", "a", "server", "check", "as", "described", "by", "the", "SDAM", "spec", "." ]
5adc639b88a0d72cbeef23a6b5df7f4540745089
https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb-core/lib/sdam/monitoring.js#L125-L204
57,996
brettz9/handle-node
src/index.js
handleNode
function handleNode (node, ...extraArgs) { const cbObj = extraArgs[extraArgs.length - 1]; if (!nodeTypeToMethodMap.has(node.nodeType)) { throw new TypeError('Not a valid `nodeType` value'); } const methodName = nodeTypeToMethodMap.get(node.nodeType); if (!cbObj[methodName]) { return undefined; } return cbObj[methodName](node, ...extraArgs); }
javascript
function handleNode (node, ...extraArgs) { const cbObj = extraArgs[extraArgs.length - 1]; if (!nodeTypeToMethodMap.has(node.nodeType)) { throw new TypeError('Not a valid `nodeType` value'); } const methodName = nodeTypeToMethodMap.get(node.nodeType); if (!cbObj[methodName]) { return undefined; } return cbObj[methodName](node, ...extraArgs); }
[ "function", "handleNode", "(", "node", ",", "...", "extraArgs", ")", "{", "const", "cbObj", "=", "extraArgs", "[", "extraArgs", ".", "length", "-", "1", "]", ";", "if", "(", "!", "nodeTypeToMethodMap", ".", "has", "(", "node", ".", "nodeType", ")", ")", "{", "throw", "new", "TypeError", "(", "'Not a valid `nodeType` value'", ")", ";", "}", "const", "methodName", "=", "nodeTypeToMethodMap", ".", "get", "(", "node", ".", "nodeType", ")", ";", "if", "(", "!", "cbObj", "[", "methodName", "]", ")", "{", "return", "undefined", ";", "}", "return", "cbObj", "[", "methodName", "]", "(", "node", ",", "...", "extraArgs", ")", ";", "}" ]
Returns the value from executing a callback on a supplied callback object according to the type of node supplied. @param {Node} node An XML or HTML node @param {Object} extraArgs Callback object whose properties–all optional (`element`, `attribute`, `text`, `cdata`, `entityReference`, `entity`, `processingInstruction`, `comment`, `document`, `documentType`, `documentFragment`, `notation`) are callbacks which will be passed the supplied arguments @returns {any|void} The result of calling the relevant callback (or `undefined` if no handler present)
[ "Returns", "the", "value", "from", "executing", "a", "callback", "on", "a", "supplied", "callback", "object", "according", "to", "the", "type", "of", "node", "supplied", "." ]
f8bab328ba1ad3895c5b4761a40cd18ae99a5c51
https://github.com/brettz9/handle-node/blob/f8bab328ba1ad3895c5b4761a40cd18ae99a5c51/src/index.js#L28-L39
57,997
arnau/stylus-palette
lib/palette.js
parseColor
function parseColor (str) { if (str.substr(0,1) === '#') { // Handle color shorthands (like #abc) var shorthand = str.length === 4, m = str.match(shorthand ? /\w/g : /\w{2}/g); if (!m) return; m = m.map(function(s) { return parseInt(shorthand ? s+s : s, 16) }); return new nodes.RGBA(m[0],m[1],m[2],1); } else if (str.substr(0,3) === 'rgb'){ var m = str.match(/([0-9]*\.?[0-9]+)/g); if (!m) return; m = m.map(function(s){return parseFloat(s, 10)}); return new nodes.RGBA(m[0], m[1], m[2], m[3] || 1); } else { var rgb = colors[str]; if (!rgb) return; return new nodes.RGBA(rgb[0], rgb[1], rgb[2], 1); } }
javascript
function parseColor (str) { if (str.substr(0,1) === '#') { // Handle color shorthands (like #abc) var shorthand = str.length === 4, m = str.match(shorthand ? /\w/g : /\w{2}/g); if (!m) return; m = m.map(function(s) { return parseInt(shorthand ? s+s : s, 16) }); return new nodes.RGBA(m[0],m[1],m[2],1); } else if (str.substr(0,3) === 'rgb'){ var m = str.match(/([0-9]*\.?[0-9]+)/g); if (!m) return; m = m.map(function(s){return parseFloat(s, 10)}); return new nodes.RGBA(m[0], m[1], m[2], m[3] || 1); } else { var rgb = colors[str]; if (!rgb) return; return new nodes.RGBA(rgb[0], rgb[1], rgb[2], 1); } }
[ "function", "parseColor", "(", "str", ")", "{", "if", "(", "str", ".", "substr", "(", "0", ",", "1", ")", "===", "'#'", ")", "{", "// Handle color shorthands (like #abc)", "var", "shorthand", "=", "str", ".", "length", "===", "4", ",", "m", "=", "str", ".", "match", "(", "shorthand", "?", "/", "\\w", "/", "g", ":", "/", "\\w{2}", "/", "g", ")", ";", "if", "(", "!", "m", ")", "return", ";", "m", "=", "m", ".", "map", "(", "function", "(", "s", ")", "{", "return", "parseInt", "(", "shorthand", "?", "s", "+", "s", ":", "s", ",", "16", ")", "}", ")", ";", "return", "new", "nodes", ".", "RGBA", "(", "m", "[", "0", "]", ",", "m", "[", "1", "]", ",", "m", "[", "2", "]", ",", "1", ")", ";", "}", "else", "if", "(", "str", ".", "substr", "(", "0", ",", "3", ")", "===", "'rgb'", ")", "{", "var", "m", "=", "str", ".", "match", "(", "/", "([0-9]*\\.?[0-9]+)", "/", "g", ")", ";", "if", "(", "!", "m", ")", "return", ";", "m", "=", "m", ".", "map", "(", "function", "(", "s", ")", "{", "return", "parseFloat", "(", "s", ",", "10", ")", "}", ")", ";", "return", "new", "nodes", ".", "RGBA", "(", "m", "[", "0", "]", ",", "m", "[", "1", "]", ",", "m", "[", "2", "]", ",", "m", "[", "3", "]", "||", "1", ")", ";", "}", "else", "{", "var", "rgb", "=", "colors", "[", "str", "]", ";", "if", "(", "!", "rgb", ")", "return", ";", "return", "new", "nodes", ".", "RGBA", "(", "rgb", "[", "0", "]", ",", "rgb", "[", "1", "]", ",", "rgb", "[", "2", "]", ",", "1", ")", ";", "}", "}" ]
Attempt to parse color. Copied from Stylus source code. @param {String} str @return {RGBA} @api private
[ "Attempt", "to", "parse", "color", ".", "Copied", "from", "Stylus", "source", "code", "." ]
21777ce91dfad3530925cd138d65cd9dc43d91e4
https://github.com/arnau/stylus-palette/blob/21777ce91dfad3530925cd138d65cd9dc43d91e4/lib/palette.js#L34-L55
57,998
amooj/node-xcheck
benchmark/main.js
profileBlock
function profileBlock(block, repeat){ repeat = repeat || DEFAULT_REPEAT_COUNT; let start = process.hrtime(); for (let i = 0; i < repeat; ++i){ block(); } let diff = process.hrtime(start); return Math.floor(diff[0] + diff[1] / 1e3); }
javascript
function profileBlock(block, repeat){ repeat = repeat || DEFAULT_REPEAT_COUNT; let start = process.hrtime(); for (let i = 0; i < repeat; ++i){ block(); } let diff = process.hrtime(start); return Math.floor(diff[0] + diff[1] / 1e3); }
[ "function", "profileBlock", "(", "block", ",", "repeat", ")", "{", "repeat", "=", "repeat", "||", "DEFAULT_REPEAT_COUNT", ";", "let", "start", "=", "process", ".", "hrtime", "(", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "repeat", ";", "++", "i", ")", "{", "block", "(", ")", ";", "}", "let", "diff", "=", "process", ".", "hrtime", "(", "start", ")", ";", "return", "Math", ".", "floor", "(", "diff", "[", "0", "]", "+", "diff", "[", "1", "]", "/", "1e3", ")", ";", "}" ]
Profile code block. @param {function} block - code to run. @param {Number} [repeat] - Number of repeated times @returns {Number} Total running time in microseconds.
[ "Profile", "code", "block", "." ]
33b2b59f7d81a8e0421a468a405f15a19126bedf
https://github.com/amooj/node-xcheck/blob/33b2b59f7d81a8e0421a468a405f15a19126bedf/benchmark/main.js#L13-L21
57,999
dlindahl/zamora
src/luminosity.js
shiftLuminosity
function shiftLuminosity (hue, shiftAmount, huePoints) { if (hue === 360) { hue = 0 } const hueShift = nearestHue(hue, huePoints) const phi = PHI(hue, hueShift) if (phi === 0) { return hue } let newHue if (phi > 0) { newHue = hue + shiftAmount } else { newHue = hue - shiftAmount } return limit(newHue, 0, 360) }
javascript
function shiftLuminosity (hue, shiftAmount, huePoints) { if (hue === 360) { hue = 0 } const hueShift = nearestHue(hue, huePoints) const phi = PHI(hue, hueShift) if (phi === 0) { return hue } let newHue if (phi > 0) { newHue = hue + shiftAmount } else { newHue = hue - shiftAmount } return limit(newHue, 0, 360) }
[ "function", "shiftLuminosity", "(", "hue", ",", "shiftAmount", ",", "huePoints", ")", "{", "if", "(", "hue", "===", "360", ")", "{", "hue", "=", "0", "}", "const", "hueShift", "=", "nearestHue", "(", "hue", ",", "huePoints", ")", "const", "phi", "=", "PHI", "(", "hue", ",", "hueShift", ")", "if", "(", "phi", "===", "0", ")", "{", "return", "hue", "}", "let", "newHue", "if", "(", "phi", ">", "0", ")", "{", "newHue", "=", "hue", "+", "shiftAmount", "}", "else", "{", "newHue", "=", "hue", "-", "shiftAmount", "}", "return", "limit", "(", "newHue", ",", "0", ",", "360", ")", "}" ]
Shift perceived luminance towards or away from a specific max hue value
[ "Shift", "perceived", "luminance", "towards", "or", "away", "from", "a", "specific", "max", "hue", "value" ]
0cf13ddea1c0664f40e8d2234e2f33ad91a8be32
https://github.com/dlindahl/zamora/blob/0cf13ddea1c0664f40e8d2234e2f33ad91a8be32/src/luminosity.js#L13-L29