id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
28,100
iatsiuk/vuegister
src/vuegister.js
installMapsSupport
function installMapsSupport() { require('source-map-support').install({ environment: 'node', handleUncaughtExceptions: false, retrieveSourceMap: (source) => { return sourceMapsCache.has(source) ? {map: sourceMapsCache.get(source), url: source} : null; }, }); }
javascript
function installMapsSupport() { require('source-map-support').install({ environment: 'node', handleUncaughtExceptions: false, retrieveSourceMap: (source) => { return sourceMapsCache.has(source) ? {map: sourceMapsCache.get(source), url: source} : null; }, }); }
[ "function", "installMapsSupport", "(", ")", "{", "require", "(", "'source-map-support'", ")", ".", "install", "(", "{", "environment", ":", "'node'", ",", "handleUncaughtExceptions", ":", "false", ",", "retrieveSourceMap", ":", "(", "source", ")", "=>", "{", "return", "sourceMapsCache", ".", "has", "(", "source", ")", "?", "{", "map", ":", "sourceMapsCache", ".", "get", "(", "source", ")", ",", "url", ":", "source", "}", ":", "null", ";", "}", ",", "}", ")", ";", "}" ]
Installs handler on prepareStackTrace
[ "Installs", "handler", "on", "prepareStackTrace" ]
38b30127df9f66a3d250229abcf2442c766c3b15
https://github.com/iatsiuk/vuegister/blob/38b30127df9f66a3d250229abcf2442c766c3b15/src/vuegister.js#L342-L352
28,101
anticoders/gagarin
lib/meteor/meteorProcess.js
kill
function kill (cb) { if (!meteor) { return cb(); } meteor.once('exit', function (code) { if (!code || code === 0 || code === 130) { cb(); } else { cb(new Error('exited with code ' + code)); } }); meteor.kill('SIGINT'); meteor = null; //-------------------------------------------- process.removeListener('exit', onProcessExit); }
javascript
function kill (cb) { if (!meteor) { return cb(); } meteor.once('exit', function (code) { if (!code || code === 0 || code === 130) { cb(); } else { cb(new Error('exited with code ' + code)); } }); meteor.kill('SIGINT'); meteor = null; //-------------------------------------------- process.removeListener('exit', onProcessExit); }
[ "function", "kill", "(", "cb", ")", "{", "if", "(", "!", "meteor", ")", "{", "return", "cb", "(", ")", ";", "}", "meteor", ".", "once", "(", "'exit'", ",", "function", "(", "code", ")", "{", "if", "(", "!", "code", "||", "code", "===", "0", "||", "code", "===", "130", ")", "{", "cb", "(", ")", ";", "}", "else", "{", "cb", "(", "new", "Error", "(", "'exited with code '", "+", "code", ")", ")", ";", "}", "}", ")", ";", "meteor", ".", "kill", "(", "'SIGINT'", ")", ";", "meteor", "=", "null", ";", "//--------------------------------------------", "process", ".", "removeListener", "(", "'exit'", ",", "onProcessExit", ")", ";", "}" ]
Kill the meteor process and cleanup. @param {Function} cb
[ "Kill", "the", "meteor", "process", "and", "cleanup", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/lib/meteor/meteorProcess.js#L141-L156
28,102
ciena-blueplanet/ember-test-utils
cli/lint-markdown.js
getIgnoredFiles
function getIgnoredFiles () { const filePath = path.join(process.cwd(), '.remarkignore') const ignoredFilesSource = fs.existsSync(filePath) ? fs.readFileSync(filePath, {encoding: 'utf8'}) : '' var ignoredFiles = ignoredFilesSource.split('\n') ignoredFiles = ignoredFiles.filter(function (item) { return item !== '' }) return ignoredFiles }
javascript
function getIgnoredFiles () { const filePath = path.join(process.cwd(), '.remarkignore') const ignoredFilesSource = fs.existsSync(filePath) ? fs.readFileSync(filePath, {encoding: 'utf8'}) : '' var ignoredFiles = ignoredFilesSource.split('\n') ignoredFiles = ignoredFiles.filter(function (item) { return item !== '' }) return ignoredFiles }
[ "function", "getIgnoredFiles", "(", ")", "{", "const", "filePath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "'.remarkignore'", ")", "const", "ignoredFilesSource", "=", "fs", ".", "existsSync", "(", "filePath", ")", "?", "fs", ".", "readFileSync", "(", "filePath", ",", "{", "encoding", ":", "'utf8'", "}", ")", ":", "''", "var", "ignoredFiles", "=", "ignoredFilesSource", ".", "split", "(", "'\\n'", ")", "ignoredFiles", "=", "ignoredFiles", ".", "filter", "(", "function", "(", "item", ")", "{", "return", "item", "!==", "''", "}", ")", "return", "ignoredFiles", "}" ]
The entries in the consumer's `.remarkignore` file @returns {Array} entries
[ "The", "entries", "in", "the", "consumer", "s", ".", "remarkignore", "file" ]
7e40f35d53c488b5f12968212110bb5a5ec138ea
https://github.com/ciena-blueplanet/ember-test-utils/blob/7e40f35d53c488b5f12968212110bb5a5ec138ea/cli/lint-markdown.js#L79-L89
28,103
anticoders/gagarin
lib/tools/index.js
function (err) { "use strict"; var message = ''; if (typeof err === 'string') { return new Error(err); } else if (typeof err === 'object') { if (err.cause) { // probably a webdriver error try { message = JSON.parse(err.cause.value.message).errorMessage; } catch ($) { message = err.cause.value.message; } } else { message = err.message || err.toString(); } return new Error(message); } return new Error(err.toString()); }
javascript
function (err) { "use strict"; var message = ''; if (typeof err === 'string') { return new Error(err); } else if (typeof err === 'object') { if (err.cause) { // probably a webdriver error try { message = JSON.parse(err.cause.value.message).errorMessage; } catch ($) { message = err.cause.value.message; } } else { message = err.message || err.toString(); } return new Error(message); } return new Error(err.toString()); }
[ "function", "(", "err", ")", "{", "\"use strict\"", ";", "var", "message", "=", "''", ";", "if", "(", "typeof", "err", "===", "'string'", ")", "{", "return", "new", "Error", "(", "err", ")", ";", "}", "else", "if", "(", "typeof", "err", "===", "'object'", ")", "{", "if", "(", "err", ".", "cause", ")", "{", "// probably a webdriver error", "try", "{", "message", "=", "JSON", ".", "parse", "(", "err", ".", "cause", ".", "value", ".", "message", ")", ".", "errorMessage", ";", "}", "catch", "(", "$", ")", "{", "message", "=", "err", ".", "cause", ".", "value", ".", "message", ";", "}", "}", "else", "{", "message", "=", "err", ".", "message", "||", "err", ".", "toString", "(", ")", ";", "}", "return", "new", "Error", "(", "message", ")", ";", "}", "return", "new", "Error", "(", "err", ".", "toString", "(", ")", ")", ";", "}" ]
Make an error comming from webdriver a little more readable.
[ "Make", "an", "error", "comming", "from", "webdriver", "a", "little", "more", "readable", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/lib/tools/index.js#L231-L254
28,104
anticoders/gagarin
lib/tools/index.js
function () { "use strict"; return new Promise(function (resolve, reject) { var numberOfRetries = 5; (function retry () { var port = 4000 + Math.floor(Math.random() * 1000); portscanner.checkPortStatus(port, 'localhost', function (err, status) { if (err || status !== 'closed') { if (--numberOfRetries > 0) { setTimeout(retry); } else { reject('Cannot find a free port... giving up'); } } else { resolve(port); } }); })(); }); }
javascript
function () { "use strict"; return new Promise(function (resolve, reject) { var numberOfRetries = 5; (function retry () { var port = 4000 + Math.floor(Math.random() * 1000); portscanner.checkPortStatus(port, 'localhost', function (err, status) { if (err || status !== 'closed') { if (--numberOfRetries > 0) { setTimeout(retry); } else { reject('Cannot find a free port... giving up'); } } else { resolve(port); } }); })(); }); }
[ "function", "(", ")", "{", "\"use strict\"", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "numberOfRetries", "=", "5", ";", "(", "function", "retry", "(", ")", "{", "var", "port", "=", "4000", "+", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "1000", ")", ";", "portscanner", ".", "checkPortStatus", "(", "port", ",", "'localhost'", ",", "function", "(", "err", ",", "status", ")", "{", "if", "(", "err", "||", "status", "!==", "'closed'", ")", "{", "if", "(", "--", "numberOfRetries", ">", "0", ")", "{", "setTimeout", "(", "retry", ")", ";", "}", "else", "{", "reject", "(", "'Cannot find a free port... giving up'", ")", ";", "}", "}", "else", "{", "resolve", "(", "port", ")", ";", "}", "}", ")", ";", "}", ")", "(", ")", ";", "}", ")", ";", "}" ]
Find a port, nobody is listening on.
[ "Find", "a", "port", "nobody", "is", "listening", "on", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/lib/tools/index.js#L328-L349
28,105
anticoders/gagarin
lib/tools/index.js
function (text, options) { "use strict"; var marginX = options.marginX !== undefined ? options.marginX : 2; var marginY = options.marginY !== undefined ? options.marginY : 1; var margin = new Array(marginX+1).join(" "); var indent = options.indent !== undefined ? options.indent : " "; var maxLength = 0; var linesOfText = text.split('\n'); var pattern = options.pattern || { T: "/", B: "/", TR: "//", BR: "//", TL: "//", BL: "//", R: "//", L: "//" }; linesOfText.forEach(function (line) { maxLength = Math.max(maxLength, line.length); }); var top = pattern.TL + new Array(2 * marginX + maxLength + 1).join(pattern.T) + pattern.TR; var empty = pattern.L + new Array(2 * marginX + maxLength + 1).join(" ") + pattern.R; var bottom = pattern.BL + new Array(2 * marginX + maxLength + 1).join(pattern.B) + pattern.BR; linesOfText = linesOfText.map(function (line) { while (line.length < maxLength) { line += " "; } return pattern.L + margin + line + margin + pattern.R; }); // vertical margin for (var i=0; i<marginY; i++) { linesOfText.unshift(empty); linesOfText.push(empty); } // top and bottom lines linesOfText.unshift(top); linesOfText.push(bottom); return linesOfText.map(function (line) { return indent + line; }).join('\n'); }
javascript
function (text, options) { "use strict"; var marginX = options.marginX !== undefined ? options.marginX : 2; var marginY = options.marginY !== undefined ? options.marginY : 1; var margin = new Array(marginX+1).join(" "); var indent = options.indent !== undefined ? options.indent : " "; var maxLength = 0; var linesOfText = text.split('\n'); var pattern = options.pattern || { T: "/", B: "/", TR: "//", BR: "//", TL: "//", BL: "//", R: "//", L: "//" }; linesOfText.forEach(function (line) { maxLength = Math.max(maxLength, line.length); }); var top = pattern.TL + new Array(2 * marginX + maxLength + 1).join(pattern.T) + pattern.TR; var empty = pattern.L + new Array(2 * marginX + maxLength + 1).join(" ") + pattern.R; var bottom = pattern.BL + new Array(2 * marginX + maxLength + 1).join(pattern.B) + pattern.BR; linesOfText = linesOfText.map(function (line) { while (line.length < maxLength) { line += " "; } return pattern.L + margin + line + margin + pattern.R; }); // vertical margin for (var i=0; i<marginY; i++) { linesOfText.unshift(empty); linesOfText.push(empty); } // top and bottom lines linesOfText.unshift(top); linesOfText.push(bottom); return linesOfText.map(function (line) { return indent + line; }).join('\n'); }
[ "function", "(", "text", ",", "options", ")", "{", "\"use strict\"", ";", "var", "marginX", "=", "options", ".", "marginX", "!==", "undefined", "?", "options", ".", "marginX", ":", "2", ";", "var", "marginY", "=", "options", ".", "marginY", "!==", "undefined", "?", "options", ".", "marginY", ":", "1", ";", "var", "margin", "=", "new", "Array", "(", "marginX", "+", "1", ")", ".", "join", "(", "\" \"", ")", ";", "var", "indent", "=", "options", ".", "indent", "!==", "undefined", "?", "options", ".", "indent", ":", "\" \"", ";", "var", "maxLength", "=", "0", ";", "var", "linesOfText", "=", "text", ".", "split", "(", "'\\n'", ")", ";", "var", "pattern", "=", "options", ".", "pattern", "||", "{", "T", ":", "\"/\"", ",", "B", ":", "\"/\"", ",", "TR", ":", "\"//\"", ",", "BR", ":", "\"//\"", ",", "TL", ":", "\"//\"", ",", "BL", ":", "\"//\"", ",", "R", ":", "\"//\"", ",", "L", ":", "\"//\"", "}", ";", "linesOfText", ".", "forEach", "(", "function", "(", "line", ")", "{", "maxLength", "=", "Math", ".", "max", "(", "maxLength", ",", "line", ".", "length", ")", ";", "}", ")", ";", "var", "top", "=", "pattern", ".", "TL", "+", "new", "Array", "(", "2", "*", "marginX", "+", "maxLength", "+", "1", ")", ".", "join", "(", "pattern", ".", "T", ")", "+", "pattern", ".", "TR", ";", "var", "empty", "=", "pattern", ".", "L", "+", "new", "Array", "(", "2", "*", "marginX", "+", "maxLength", "+", "1", ")", ".", "join", "(", "\" \"", ")", "+", "pattern", ".", "R", ";", "var", "bottom", "=", "pattern", ".", "BL", "+", "new", "Array", "(", "2", "*", "marginX", "+", "maxLength", "+", "1", ")", ".", "join", "(", "pattern", ".", "B", ")", "+", "pattern", ".", "BR", ";", "linesOfText", "=", "linesOfText", ".", "map", "(", "function", "(", "line", ")", "{", "while", "(", "line", ".", "length", "<", "maxLength", ")", "{", "line", "+=", "\" \"", ";", "}", "return", "pattern", ".", "L", "+", "margin", "+", "line", "+", "margin", "+", "pattern", ".", "R", ";", "}", ")", ";", "// vertical margin", "for", "(", "var", "i", "=", "0", ";", "i", "<", "marginY", ";", "i", "++", ")", "{", "linesOfText", ".", "unshift", "(", "empty", ")", ";", "linesOfText", ".", "push", "(", "empty", ")", ";", "}", "// top and bottom lines", "linesOfText", ".", "unshift", "(", "top", ")", ";", "linesOfText", ".", "push", "(", "bottom", ")", ";", "return", "linesOfText", ".", "map", "(", "function", "(", "line", ")", "{", "return", "indent", "+", "line", ";", "}", ")", ".", "join", "(", "'\\n'", ")", ";", "}" ]
Creates a nice banner containing the given text. @param {object} options
[ "Creates", "a", "nice", "banner", "containing", "the", "given", "text", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/lib/tools/index.js#L356-L398
28,106
css-modules/postcss-modules-resolve-imports
src/resolveDeps.js
resolveDeps
function resolveDeps(ast, result) { const { from: selfPath, graph, resolve, rootPath, rootTree, } = result.opts; const cwd = dirname(selfPath); const rootDir = dirname(rootPath); const processor = result.processor; const self = graph[selfPath] = graph[selfPath] || {}; self.mark = TEMPORARY_MARK; const moduleExports = {}; const translations = {}; ast.walkRules(moduleDeclaration, rule => { if (importDeclaration.exec(rule.selector)) { rule.walkDecls(decl => translations[decl.prop] = decl.value); const dependencyPath = RegExp.$1.replace(/['"]/g, ''); const absDependencyPath = resolveModule(dependencyPath, {cwd, resolve}); if (!absDependencyPath) throw new Error( 'Can\'t resolve module path from `' + cwd + '` to `' + dependencyPath + '`' ); if ( graph[absDependencyPath] && graph[absDependencyPath].mark === TEMPORARY_MARK ) throw new Error( 'Circular dependency was found between `' + selfPath + '` and `' + absDependencyPath + '`. ' + 'Circular dependencies lead to the unpredictable state and considered harmful.' ); if (!( graph[absDependencyPath] && graph[absDependencyPath].mark === PERMANENT_MARK )) { const css = readFileSync(absDependencyPath, 'utf8'); const lazyResult = processor.process(css, Object.assign({}, result.opts, {from: absDependencyPath})); updateTranslations(translations, lazyResult.root.exports); } else { updateTranslations(translations, graph[absDependencyPath].exports); } return void rule.remove(); } rule.walkDecls(decl => moduleExports[decl.prop] = decl.value); rule.remove(); }); replaceSymbols(ast, translations); for (const token in moduleExports) for (const genericId in translations) moduleExports[token] = moduleExports[token] .replace(genericId, translations[genericId]); self.mark = PERMANENT_MARK; self.exports = ast.exports = moduleExports; // resolve paths if (cwd !== rootDir) resolvePaths(ast, cwd, rootDir); const importNotes = comment({ parent: rootTree, raws: {before: rootTree.nodes.length === 0 ? '' : '\n\n'}, text: ` imported from ${normalizeUrl(relative(rootDir, selfPath))} `, }); const childNodes = ast.nodes.map(i => { const node = i.clone({parent: rootTree}); if ( typeof node.raws.before === 'undefined' || node.raws.before === '' ) node.raws.before = '\n\n'; return node; }); rootTree.nodes = rootTree.nodes.concat(importNotes, childNodes); }
javascript
function resolveDeps(ast, result) { const { from: selfPath, graph, resolve, rootPath, rootTree, } = result.opts; const cwd = dirname(selfPath); const rootDir = dirname(rootPath); const processor = result.processor; const self = graph[selfPath] = graph[selfPath] || {}; self.mark = TEMPORARY_MARK; const moduleExports = {}; const translations = {}; ast.walkRules(moduleDeclaration, rule => { if (importDeclaration.exec(rule.selector)) { rule.walkDecls(decl => translations[decl.prop] = decl.value); const dependencyPath = RegExp.$1.replace(/['"]/g, ''); const absDependencyPath = resolveModule(dependencyPath, {cwd, resolve}); if (!absDependencyPath) throw new Error( 'Can\'t resolve module path from `' + cwd + '` to `' + dependencyPath + '`' ); if ( graph[absDependencyPath] && graph[absDependencyPath].mark === TEMPORARY_MARK ) throw new Error( 'Circular dependency was found between `' + selfPath + '` and `' + absDependencyPath + '`. ' + 'Circular dependencies lead to the unpredictable state and considered harmful.' ); if (!( graph[absDependencyPath] && graph[absDependencyPath].mark === PERMANENT_MARK )) { const css = readFileSync(absDependencyPath, 'utf8'); const lazyResult = processor.process(css, Object.assign({}, result.opts, {from: absDependencyPath})); updateTranslations(translations, lazyResult.root.exports); } else { updateTranslations(translations, graph[absDependencyPath].exports); } return void rule.remove(); } rule.walkDecls(decl => moduleExports[decl.prop] = decl.value); rule.remove(); }); replaceSymbols(ast, translations); for (const token in moduleExports) for (const genericId in translations) moduleExports[token] = moduleExports[token] .replace(genericId, translations[genericId]); self.mark = PERMANENT_MARK; self.exports = ast.exports = moduleExports; // resolve paths if (cwd !== rootDir) resolvePaths(ast, cwd, rootDir); const importNotes = comment({ parent: rootTree, raws: {before: rootTree.nodes.length === 0 ? '' : '\n\n'}, text: ` imported from ${normalizeUrl(relative(rootDir, selfPath))} `, }); const childNodes = ast.nodes.map(i => { const node = i.clone({parent: rootTree}); if ( typeof node.raws.before === 'undefined' || node.raws.before === '' ) node.raws.before = '\n\n'; return node; }); rootTree.nodes = rootTree.nodes.concat(importNotes, childNodes); }
[ "function", "resolveDeps", "(", "ast", ",", "result", ")", "{", "const", "{", "from", ":", "selfPath", ",", "graph", ",", "resolve", ",", "rootPath", ",", "rootTree", ",", "}", "=", "result", ".", "opts", ";", "const", "cwd", "=", "dirname", "(", "selfPath", ")", ";", "const", "rootDir", "=", "dirname", "(", "rootPath", ")", ";", "const", "processor", "=", "result", ".", "processor", ";", "const", "self", "=", "graph", "[", "selfPath", "]", "=", "graph", "[", "selfPath", "]", "||", "{", "}", ";", "self", ".", "mark", "=", "TEMPORARY_MARK", ";", "const", "moduleExports", "=", "{", "}", ";", "const", "translations", "=", "{", "}", ";", "ast", ".", "walkRules", "(", "moduleDeclaration", ",", "rule", "=>", "{", "if", "(", "importDeclaration", ".", "exec", "(", "rule", ".", "selector", ")", ")", "{", "rule", ".", "walkDecls", "(", "decl", "=>", "translations", "[", "decl", ".", "prop", "]", "=", "decl", ".", "value", ")", ";", "const", "dependencyPath", "=", "RegExp", ".", "$1", ".", "replace", "(", "/", "['\"]", "/", "g", ",", "''", ")", ";", "const", "absDependencyPath", "=", "resolveModule", "(", "dependencyPath", ",", "{", "cwd", ",", "resolve", "}", ")", ";", "if", "(", "!", "absDependencyPath", ")", "throw", "new", "Error", "(", "'Can\\'t resolve module path from `'", "+", "cwd", "+", "'` to `'", "+", "dependencyPath", "+", "'`'", ")", ";", "if", "(", "graph", "[", "absDependencyPath", "]", "&&", "graph", "[", "absDependencyPath", "]", ".", "mark", "===", "TEMPORARY_MARK", ")", "throw", "new", "Error", "(", "'Circular dependency was found between `'", "+", "selfPath", "+", "'` and `'", "+", "absDependencyPath", "+", "'`. '", "+", "'Circular dependencies lead to the unpredictable state and considered harmful.'", ")", ";", "if", "(", "!", "(", "graph", "[", "absDependencyPath", "]", "&&", "graph", "[", "absDependencyPath", "]", ".", "mark", "===", "PERMANENT_MARK", ")", ")", "{", "const", "css", "=", "readFileSync", "(", "absDependencyPath", ",", "'utf8'", ")", ";", "const", "lazyResult", "=", "processor", ".", "process", "(", "css", ",", "Object", ".", "assign", "(", "{", "}", ",", "result", ".", "opts", ",", "{", "from", ":", "absDependencyPath", "}", ")", ")", ";", "updateTranslations", "(", "translations", ",", "lazyResult", ".", "root", ".", "exports", ")", ";", "}", "else", "{", "updateTranslations", "(", "translations", ",", "graph", "[", "absDependencyPath", "]", ".", "exports", ")", ";", "}", "return", "void", "rule", ".", "remove", "(", ")", ";", "}", "rule", ".", "walkDecls", "(", "decl", "=>", "moduleExports", "[", "decl", ".", "prop", "]", "=", "decl", ".", "value", ")", ";", "rule", ".", "remove", "(", ")", ";", "}", ")", ";", "replaceSymbols", "(", "ast", ",", "translations", ")", ";", "for", "(", "const", "token", "in", "moduleExports", ")", "for", "(", "const", "genericId", "in", "translations", ")", "moduleExports", "[", "token", "]", "=", "moduleExports", "[", "token", "]", ".", "replace", "(", "genericId", ",", "translations", "[", "genericId", "]", ")", ";", "self", ".", "mark", "=", "PERMANENT_MARK", ";", "self", ".", "exports", "=", "ast", ".", "exports", "=", "moduleExports", ";", "// resolve paths", "if", "(", "cwd", "!==", "rootDir", ")", "resolvePaths", "(", "ast", ",", "cwd", ",", "rootDir", ")", ";", "const", "importNotes", "=", "comment", "(", "{", "parent", ":", "rootTree", ",", "raws", ":", "{", "before", ":", "rootTree", ".", "nodes", ".", "length", "===", "0", "?", "''", ":", "'\\n\\n'", "}", ",", "text", ":", "`", "${", "normalizeUrl", "(", "relative", "(", "rootDir", ",", "selfPath", ")", ")", "}", "`", ",", "}", ")", ";", "const", "childNodes", "=", "ast", ".", "nodes", ".", "map", "(", "i", "=>", "{", "const", "node", "=", "i", ".", "clone", "(", "{", "parent", ":", "rootTree", "}", ")", ";", "if", "(", "typeof", "node", ".", "raws", ".", "before", "===", "'undefined'", "||", "node", ".", "raws", ".", "before", "===", "''", ")", "node", ".", "raws", ".", "before", "=", "'\\n\\n'", ";", "return", "node", ";", "}", ")", ";", "rootTree", ".", "nodes", "=", "rootTree", ".", "nodes", ".", "concat", "(", "importNotes", ",", "childNodes", ")", ";", "}" ]
Topological sorting is used to resolve the deps order, actually depth-first search algorithm. @see https://en.wikipedia.org/wiki/Topological_sorting
[ "Topological", "sorting", "is", "used", "to", "resolve", "the", "deps", "order", "actually", "depth", "-", "first", "search", "algorithm", "." ]
31ba1f0ab6b727cf7c5630f56256f1f8dd34d67f
https://github.com/css-modules/postcss-modules-resolve-imports/blob/31ba1f0ab6b727cf7c5630f56256f1f8dd34d67f/src/resolveDeps.js#L25-L115
28,107
anticoders/gagarin
lib/tools/closure.js
Closure
function Closure (parent, listOfKeys, accessor) { "use strict"; var closure = {}; listOfKeys = listOfKeys || []; accessor = accessor || function () {}; parent && parent.__mixin__ && parent.__mixin__(closure); listOfKeys.forEach(function (key) { closure[key] = accessor.bind(null, key); }); this.getValues = function () { var values = {}; Object.keys(closure).forEach(function (key) { values[key] = closure[key](); if (values[key] === undefined) { values[key] = null; } if (typeof values[key] === 'function') { throw new Error('a closure variable must be serializable, so you cannot use a function'); } }); return values; } this.setValues = function (values) { Object.keys(values).forEach(function (key) { closure[key](values[key]); }); } this.__mixin__ = function (object) { Object.keys(closure).forEach(function (key) { object[key] = closure[key]; }); } }
javascript
function Closure (parent, listOfKeys, accessor) { "use strict"; var closure = {}; listOfKeys = listOfKeys || []; accessor = accessor || function () {}; parent && parent.__mixin__ && parent.__mixin__(closure); listOfKeys.forEach(function (key) { closure[key] = accessor.bind(null, key); }); this.getValues = function () { var values = {}; Object.keys(closure).forEach(function (key) { values[key] = closure[key](); if (values[key] === undefined) { values[key] = null; } if (typeof values[key] === 'function') { throw new Error('a closure variable must be serializable, so you cannot use a function'); } }); return values; } this.setValues = function (values) { Object.keys(values).forEach(function (key) { closure[key](values[key]); }); } this.__mixin__ = function (object) { Object.keys(closure).forEach(function (key) { object[key] = closure[key]; }); } }
[ "function", "Closure", "(", "parent", ",", "listOfKeys", ",", "accessor", ")", "{", "\"use strict\"", ";", "var", "closure", "=", "{", "}", ";", "listOfKeys", "=", "listOfKeys", "||", "[", "]", ";", "accessor", "=", "accessor", "||", "function", "(", ")", "{", "}", ";", "parent", "&&", "parent", ".", "__mixin__", "&&", "parent", ".", "__mixin__", "(", "closure", ")", ";", "listOfKeys", ".", "forEach", "(", "function", "(", "key", ")", "{", "closure", "[", "key", "]", "=", "accessor", ".", "bind", "(", "null", ",", "key", ")", ";", "}", ")", ";", "this", ".", "getValues", "=", "function", "(", ")", "{", "var", "values", "=", "{", "}", ";", "Object", ".", "keys", "(", "closure", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "values", "[", "key", "]", "=", "closure", "[", "key", "]", "(", ")", ";", "if", "(", "values", "[", "key", "]", "===", "undefined", ")", "{", "values", "[", "key", "]", "=", "null", ";", "}", "if", "(", "typeof", "values", "[", "key", "]", "===", "'function'", ")", "{", "throw", "new", "Error", "(", "'a closure variable must be serializable, so you cannot use a function'", ")", ";", "}", "}", ")", ";", "return", "values", ";", "}", "this", ".", "setValues", "=", "function", "(", "values", ")", "{", "Object", ".", "keys", "(", "values", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "closure", "[", "key", "]", "(", "values", "[", "key", "]", ")", ";", "}", ")", ";", "}", "this", ".", "__mixin__", "=", "function", "(", "object", ")", "{", "Object", ".", "keys", "(", "closure", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "object", "[", "key", "]", "=", "closure", "[", "key", "]", ";", "}", ")", ";", "}", "}" ]
Creates a new closure manager. @param {Object} parent @param {Array} listOfKeys (names) @param {Function} accessor
[ "Creates", "a", "new", "closure", "manager", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/lib/tools/closure.js#L11-L51
28,108
ionic-team/ionic-service-core
ionic-core.js
function(key, object) { // Convert object to JSON and store in localStorage var json = JSON.stringify(object); persistenceStrategy.set(key, json); // Then store it in the object cache objectCache[key] = object; }
javascript
function(key, object) { // Convert object to JSON and store in localStorage var json = JSON.stringify(object); persistenceStrategy.set(key, json); // Then store it in the object cache objectCache[key] = object; }
[ "function", "(", "key", ",", "object", ")", "{", "// Convert object to JSON and store in localStorage", "var", "json", "=", "JSON", ".", "stringify", "(", "object", ")", ";", "persistenceStrategy", ".", "set", "(", "key", ",", "json", ")", ";", "// Then store it in the object cache", "objectCache", "[", "key", "]", "=", "object", ";", "}" ]
Stores an object in local storage under the given key
[ "Stores", "an", "object", "in", "local", "storage", "under", "the", "given", "key" ]
8997fb52e8b8bc4545ba54a9a31d7e6f36b4a744
https://github.com/ionic-team/ionic-service-core/blob/8997fb52e8b8bc4545ba54a9a31d7e6f36b4a744/ionic-core.js#L28-L36
28,109
ionic-team/ionic-service-core
ionic-core.js
function(key) { // First check to see if it's the object cache var cached = objectCache[key]; if (cached) { return cached; } // Deserialize the object from JSON var json = persistenceStrategy.get(key); // null or undefined --> return null. if (json == null) { return null; } try { return JSON.parse(json); } catch (err) { return null; } }
javascript
function(key) { // First check to see if it's the object cache var cached = objectCache[key]; if (cached) { return cached; } // Deserialize the object from JSON var json = persistenceStrategy.get(key); // null or undefined --> return null. if (json == null) { return null; } try { return JSON.parse(json); } catch (err) { return null; } }
[ "function", "(", "key", ")", "{", "// First check to see if it's the object cache", "var", "cached", "=", "objectCache", "[", "key", "]", ";", "if", "(", "cached", ")", "{", "return", "cached", ";", "}", "// Deserialize the object from JSON", "var", "json", "=", "persistenceStrategy", ".", "get", "(", "key", ")", ";", "// null or undefined --> return null.", "if", "(", "json", "==", "null", ")", "{", "return", "null", ";", "}", "try", "{", "return", "JSON", ".", "parse", "(", "json", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "null", ";", "}", "}" ]
Either retrieves the cached copy of an object, or the object itself from localStorage. Returns null if the object couldn't be found.
[ "Either", "retrieves", "the", "cached", "copy", "of", "an", "object", "or", "the", "object", "itself", "from", "localStorage", ".", "Returns", "null", "if", "the", "object", "couldn", "t", "be", "found", "." ]
8997fb52e8b8bc4545ba54a9a31d7e6f36b4a744
https://github.com/ionic-team/ionic-service-core/blob/8997fb52e8b8bc4545ba54a9a31d7e6f36b4a744/ionic-core.js#L43-L64
28,110
ionic-team/ionic-service-core
ionic-core.js
function(lockKey, asyncFunction) { var deferred = $q.defer(); // If the memory lock is set, error out. if (memoryLocks[lockKey]) { deferred.reject('in_progress'); return deferred.promise; } // If there is a stored lock but no memory lock, flag a persistence error if (persistenceStrategy.get(lockKey) === 'locked') { deferred.reject('last_call_interrupted'); deferred.promise.then(null, function() { persistenceStrategy.remove(lockKey); }); return deferred.promise; } // Set stored and memory locks memoryLocks[lockKey] = true; persistenceStrategy.set(lockKey, 'locked'); // Perform the async operation asyncFunction().then(function(successData) { deferred.resolve(successData); // Remove stored and memory locks delete memoryLocks[lockKey]; persistenceStrategy.remove(lockKey); }, function(errorData) { deferred.reject(errorData); // Remove stored and memory locks delete memoryLocks[lockKey]; persistenceStrategy.remove(lockKey); }, function(notifyData) { deferred.notify(notifyData); }); return deferred.promise; }
javascript
function(lockKey, asyncFunction) { var deferred = $q.defer(); // If the memory lock is set, error out. if (memoryLocks[lockKey]) { deferred.reject('in_progress'); return deferred.promise; } // If there is a stored lock but no memory lock, flag a persistence error if (persistenceStrategy.get(lockKey) === 'locked') { deferred.reject('last_call_interrupted'); deferred.promise.then(null, function() { persistenceStrategy.remove(lockKey); }); return deferred.promise; } // Set stored and memory locks memoryLocks[lockKey] = true; persistenceStrategy.set(lockKey, 'locked'); // Perform the async operation asyncFunction().then(function(successData) { deferred.resolve(successData); // Remove stored and memory locks delete memoryLocks[lockKey]; persistenceStrategy.remove(lockKey); }, function(errorData) { deferred.reject(errorData); // Remove stored and memory locks delete memoryLocks[lockKey]; persistenceStrategy.remove(lockKey); }, function(notifyData) { deferred.notify(notifyData); }); return deferred.promise; }
[ "function", "(", "lockKey", ",", "asyncFunction", ")", "{", "var", "deferred", "=", "$q", ".", "defer", "(", ")", ";", "// If the memory lock is set, error out.", "if", "(", "memoryLocks", "[", "lockKey", "]", ")", "{", "deferred", ".", "reject", "(", "'in_progress'", ")", ";", "return", "deferred", ".", "promise", ";", "}", "// If there is a stored lock but no memory lock, flag a persistence error", "if", "(", "persistenceStrategy", ".", "get", "(", "lockKey", ")", "===", "'locked'", ")", "{", "deferred", ".", "reject", "(", "'last_call_interrupted'", ")", ";", "deferred", ".", "promise", ".", "then", "(", "null", ",", "function", "(", ")", "{", "persistenceStrategy", ".", "remove", "(", "lockKey", ")", ";", "}", ")", ";", "return", "deferred", ".", "promise", ";", "}", "// Set stored and memory locks", "memoryLocks", "[", "lockKey", "]", "=", "true", ";", "persistenceStrategy", ".", "set", "(", "lockKey", ",", "'locked'", ")", ";", "// Perform the async operation", "asyncFunction", "(", ")", ".", "then", "(", "function", "(", "successData", ")", "{", "deferred", ".", "resolve", "(", "successData", ")", ";", "// Remove stored and memory locks", "delete", "memoryLocks", "[", "lockKey", "]", ";", "persistenceStrategy", ".", "remove", "(", "lockKey", ")", ";", "}", ",", "function", "(", "errorData", ")", "{", "deferred", ".", "reject", "(", "errorData", ")", ";", "// Remove stored and memory locks", "delete", "memoryLocks", "[", "lockKey", "]", ";", "persistenceStrategy", ".", "remove", "(", "lockKey", ")", ";", "}", ",", "function", "(", "notifyData", ")", "{", "deferred", ".", "notify", "(", "notifyData", ")", ";", "}", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Locks the async call represented by the given promise and lock key. Only one asyncFunction given by the lockKey can be running at any time. @param lockKey should be a string representing the name of this async call. This is required for persistence. @param asyncFunction Returns a promise of the async call. @returns A new promise, identical to the one returned by asyncFunction, but with two new errors: 'in_progress', and 'last_call_interrupted'.
[ "Locks", "the", "async", "call", "represented", "by", "the", "given", "promise", "and", "lock", "key", ".", "Only", "one", "asyncFunction", "given", "by", "the", "lockKey", "can", "be", "running", "at", "any", "time", "." ]
8997fb52e8b8bc4545ba54a9a31d7e6f36b4a744
https://github.com/ionic-team/ionic-service-core/blob/8997fb52e8b8bc4545ba54a9a31d7e6f36b4a744/ionic-core.js#L76-L117
28,111
ionic-team/ionic-service-core
ionic-core.js
function(key, value, isUnique) { if(isUnique) { return this._op(key, value, 'pushUnique'); } else { return this._op(key, value, 'push'); } }
javascript
function(key, value, isUnique) { if(isUnique) { return this._op(key, value, 'pushUnique'); } else { return this._op(key, value, 'push'); } }
[ "function", "(", "key", ",", "value", ",", "isUnique", ")", "{", "if", "(", "isUnique", ")", "{", "return", "this", ".", "_op", "(", "key", ",", "value", ",", "'pushUnique'", ")", ";", "}", "else", "{", "return", "this", ".", "_op", "(", "key", ",", "value", ",", "'push'", ")", ";", "}", "}" ]
Push the given value into the array field identified by the key. Pass true to isUnique to only push the value if the value does not already exist in the array.
[ "Push", "the", "given", "value", "into", "the", "array", "field", "identified", "by", "the", "key", ".", "Pass", "true", "to", "isUnique", "to", "only", "push", "the", "value", "if", "the", "value", "does", "not", "already", "exist", "in", "the", "array", "." ]
8997fb52e8b8bc4545ba54a9a31d7e6f36b4a744
https://github.com/ionic-team/ionic-service-core/blob/8997fb52e8b8bc4545ba54a9a31d7e6f36b4a744/ionic-core.js#L377-L383
28,112
anticoders/gagarin
lib/meteor/build.js
BuildPromise
function BuildPromise(options) { "use strict"; options = options || {}; var pathToApp = options.pathToApp || path.resolve('.'); var mongoUrl = options.mongoUrl || "http://localhost:27017"; var timeout = options.timeout || 120000; var verbose = options.verbose !== undefined ? !!options.verbose : false; var pathToMain = path.join(pathToApp, '.gagarin', 'local', 'bundle', 'main.js'); var pathToLocal = path.join(pathToApp, '.gagarin', 'local'); var env = Object.create(process.env); return tools.getReleaseVersion(pathToApp).then(function (version) { return new Promise(function (resolve, reject) { var args; logs.system("detected METEOR@" + version); if (version >= '1.0.0') { args = [ 'build', '--debug', '--directory', pathToLocal ]; } else { args = [ 'bundle', '--debug', '--directory', path.join(pathToLocal, 'bundle') ]; } logs.system("spawning meteor process with the following args"); logs.system(JSON.stringify(args)); var buildTimeout = null; var meteorBinary = tools.getMeteorBinary(); //make sure that platforms file contains only server and browser //and cache this file under platforms.gagarin.backup var platformsFilePath = path.join(pathToApp,'.meteor','platforms'); var platformsBackupPath = path.join(pathToApp,'.meteor','platforms.gagarin.backup'); fs.rename(platformsFilePath,platformsBackupPath,function(err,data){ fs.writeFile(platformsFilePath,'server\nbrowser\n',function(){ spawnMeteorProcess(); }); }); var output = ""; var meteor = null; var spawnMeteorProcess = function(){ meteor = spawn(meteorBinary, args, { cwd: pathToApp, env: env, stdio: verbose ? 'inherit' : 'ignore' }); meteor.on('exit', function onExit (code) { //switch back to initial content of platforms file fs.rename(platformsBackupPath,platformsFilePath); if (code) { return reject(new Error('meteor build exited with code ' + code)); } /* var err = parseBuildErrors(output); if (err) { return reject(err); } */ logs.system('linking node_modules'); linkNodeModules(pathToApp).then(function () { logs.system('everything is fine'); resolve(pathToMain); }).catch(reject); buildTimeout = setTimeout(function () { meteor.once('exit', function () { reject(new Error('Timeout while waiting for meteor build to finish.')); }); meteor.kill('SIGINT') }, timeout); clearTimeout(buildTimeout); }); } //----------------------------------------------- /* meteor.stdout.on('data', function onData (data) { output += data.toString(); if (data.toString().match(/WARNING: The output directory is under your source tree./)) { logMeteorOutput(' creating your test build in ' + path.join(pathToLocal, 'bundle') + '\n'); return; } logMeteorOutput(data); }); meteor.stdout.on('error', function onError (data) { console.log(chalk.red(data.toString())); clearTimeout(buildTimeout); }); */ }); }); function logMeteorOutput(data) { if (!verbose) { return; } process.stdout.write(chalk.gray(stripAnsi(data))); } }
javascript
function BuildPromise(options) { "use strict"; options = options || {}; var pathToApp = options.pathToApp || path.resolve('.'); var mongoUrl = options.mongoUrl || "http://localhost:27017"; var timeout = options.timeout || 120000; var verbose = options.verbose !== undefined ? !!options.verbose : false; var pathToMain = path.join(pathToApp, '.gagarin', 'local', 'bundle', 'main.js'); var pathToLocal = path.join(pathToApp, '.gagarin', 'local'); var env = Object.create(process.env); return tools.getReleaseVersion(pathToApp).then(function (version) { return new Promise(function (resolve, reject) { var args; logs.system("detected METEOR@" + version); if (version >= '1.0.0') { args = [ 'build', '--debug', '--directory', pathToLocal ]; } else { args = [ 'bundle', '--debug', '--directory', path.join(pathToLocal, 'bundle') ]; } logs.system("spawning meteor process with the following args"); logs.system(JSON.stringify(args)); var buildTimeout = null; var meteorBinary = tools.getMeteorBinary(); //make sure that platforms file contains only server and browser //and cache this file under platforms.gagarin.backup var platformsFilePath = path.join(pathToApp,'.meteor','platforms'); var platformsBackupPath = path.join(pathToApp,'.meteor','platforms.gagarin.backup'); fs.rename(platformsFilePath,platformsBackupPath,function(err,data){ fs.writeFile(platformsFilePath,'server\nbrowser\n',function(){ spawnMeteorProcess(); }); }); var output = ""; var meteor = null; var spawnMeteorProcess = function(){ meteor = spawn(meteorBinary, args, { cwd: pathToApp, env: env, stdio: verbose ? 'inherit' : 'ignore' }); meteor.on('exit', function onExit (code) { //switch back to initial content of platforms file fs.rename(platformsBackupPath,platformsFilePath); if (code) { return reject(new Error('meteor build exited with code ' + code)); } /* var err = parseBuildErrors(output); if (err) { return reject(err); } */ logs.system('linking node_modules'); linkNodeModules(pathToApp).then(function () { logs.system('everything is fine'); resolve(pathToMain); }).catch(reject); buildTimeout = setTimeout(function () { meteor.once('exit', function () { reject(new Error('Timeout while waiting for meteor build to finish.')); }); meteor.kill('SIGINT') }, timeout); clearTimeout(buildTimeout); }); } //----------------------------------------------- /* meteor.stdout.on('data', function onData (data) { output += data.toString(); if (data.toString().match(/WARNING: The output directory is under your source tree./)) { logMeteorOutput(' creating your test build in ' + path.join(pathToLocal, 'bundle') + '\n'); return; } logMeteorOutput(data); }); meteor.stdout.on('error', function onError (data) { console.log(chalk.red(data.toString())); clearTimeout(buildTimeout); }); */ }); }); function logMeteorOutput(data) { if (!verbose) { return; } process.stdout.write(chalk.gray(stripAnsi(data))); } }
[ "function", "BuildPromise", "(", "options", ")", "{", "\"use strict\"", ";", "options", "=", "options", "||", "{", "}", ";", "var", "pathToApp", "=", "options", ".", "pathToApp", "||", "path", ".", "resolve", "(", "'.'", ")", ";", "var", "mongoUrl", "=", "options", ".", "mongoUrl", "||", "\"http://localhost:27017\"", ";", "var", "timeout", "=", "options", ".", "timeout", "||", "120000", ";", "var", "verbose", "=", "options", ".", "verbose", "!==", "undefined", "?", "!", "!", "options", ".", "verbose", ":", "false", ";", "var", "pathToMain", "=", "path", ".", "join", "(", "pathToApp", ",", "'.gagarin'", ",", "'local'", ",", "'bundle'", ",", "'main.js'", ")", ";", "var", "pathToLocal", "=", "path", ".", "join", "(", "pathToApp", ",", "'.gagarin'", ",", "'local'", ")", ";", "var", "env", "=", "Object", ".", "create", "(", "process", ".", "env", ")", ";", "return", "tools", ".", "getReleaseVersion", "(", "pathToApp", ")", ".", "then", "(", "function", "(", "version", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "args", ";", "logs", ".", "system", "(", "\"detected METEOR@\"", "+", "version", ")", ";", "if", "(", "version", ">=", "'1.0.0'", ")", "{", "args", "=", "[", "'build'", ",", "'--debug'", ",", "'--directory'", ",", "pathToLocal", "]", ";", "}", "else", "{", "args", "=", "[", "'bundle'", ",", "'--debug'", ",", "'--directory'", ",", "path", ".", "join", "(", "pathToLocal", ",", "'bundle'", ")", "]", ";", "}", "logs", ".", "system", "(", "\"spawning meteor process with the following args\"", ")", ";", "logs", ".", "system", "(", "JSON", ".", "stringify", "(", "args", ")", ")", ";", "var", "buildTimeout", "=", "null", ";", "var", "meteorBinary", "=", "tools", ".", "getMeteorBinary", "(", ")", ";", "//make sure that platforms file contains only server and browser", "//and cache this file under platforms.gagarin.backup", "var", "platformsFilePath", "=", "path", ".", "join", "(", "pathToApp", ",", "'.meteor'", ",", "'platforms'", ")", ";", "var", "platformsBackupPath", "=", "path", ".", "join", "(", "pathToApp", ",", "'.meteor'", ",", "'platforms.gagarin.backup'", ")", ";", "fs", ".", "rename", "(", "platformsFilePath", ",", "platformsBackupPath", ",", "function", "(", "err", ",", "data", ")", "{", "fs", ".", "writeFile", "(", "platformsFilePath", ",", "'server\\nbrowser\\n'", ",", "function", "(", ")", "{", "spawnMeteorProcess", "(", ")", ";", "}", ")", ";", "}", ")", ";", "var", "output", "=", "\"\"", ";", "var", "meteor", "=", "null", ";", "var", "spawnMeteorProcess", "=", "function", "(", ")", "{", "meteor", "=", "spawn", "(", "meteorBinary", ",", "args", ",", "{", "cwd", ":", "pathToApp", ",", "env", ":", "env", ",", "stdio", ":", "verbose", "?", "'inherit'", ":", "'ignore'", "}", ")", ";", "meteor", ".", "on", "(", "'exit'", ",", "function", "onExit", "(", "code", ")", "{", "//switch back to initial content of platforms file", "fs", ".", "rename", "(", "platformsBackupPath", ",", "platformsFilePath", ")", ";", "if", "(", "code", ")", "{", "return", "reject", "(", "new", "Error", "(", "'meteor build exited with code '", "+", "code", ")", ")", ";", "}", "/*\n var err = parseBuildErrors(output);\n\n if (err) {\n return reject(err);\n }\n */", "logs", ".", "system", "(", "'linking node_modules'", ")", ";", "linkNodeModules", "(", "pathToApp", ")", ".", "then", "(", "function", "(", ")", "{", "logs", ".", "system", "(", "'everything is fine'", ")", ";", "resolve", "(", "pathToMain", ")", ";", "}", ")", ".", "catch", "(", "reject", ")", ";", "buildTimeout", "=", "setTimeout", "(", "function", "(", ")", "{", "meteor", ".", "once", "(", "'exit'", ",", "function", "(", ")", "{", "reject", "(", "new", "Error", "(", "'Timeout while waiting for meteor build to finish.'", ")", ")", ";", "}", ")", ";", "meteor", ".", "kill", "(", "'SIGINT'", ")", "}", ",", "timeout", ")", ";", "clearTimeout", "(", "buildTimeout", ")", ";", "}", ")", ";", "}", "//-----------------------------------------------", "/*\n meteor.stdout.on('data', function onData (data) {\n\n output += data.toString();\n\n if (data.toString().match(/WARNING: The output directory is under your source tree./)) {\n logMeteorOutput(' creating your test build in ' + path.join(pathToLocal, 'bundle') + '\\n');\n return;\n }\n logMeteorOutput(data);\n });\n\n meteor.stdout.on('error', function onError (data) {\n console.log(chalk.red(data.toString()));\n clearTimeout(buildTimeout);\n });\n */", "}", ")", ";", "}", ")", ";", "function", "logMeteorOutput", "(", "data", ")", "{", "if", "(", "!", "verbose", ")", "{", "return", ";", "}", "process", ".", "stdout", ".", "write", "(", "chalk", ".", "gray", "(", "stripAnsi", "(", "data", ")", ")", ")", ";", "}", "}" ]
PRIVATE BUILD PROMISE IMPLEMENTATION
[ "PRIVATE", "BUILD", "PROMISE", "IMPLEMENTATION" ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/lib/meteor/build.js#L103-L224
28,113
anticoders/gagarin
lib/meteor/build.js
ensureGagarinVersionsMatch
function ensureGagarinVersionsMatch(pathToApp, verbose) { var pathToMeteorPackages = path.join(pathToApp, '.meteor', 'packages'); var nodeModuleVersion = require('../../package.json').version; return new Promise(function (resolve, reject) { utils.getGagarinPackageVersion(pathToApp).then(function (packageVersion) { if (packageVersion === nodeModuleVersion) { logs.system("node module and smart package versions match, " + packageVersion); return resolve(); } tools.getReleaseVersion(pathToApp).then(function (meteorReleaseVersion) { if (meteorReleaseVersion < "0.9.0") { // really, we can do nothing about package version // without a decent package management system logs.system("meteor version is too old to automatically fix package version"); return resolve(); } logs.system("meteor add anti:gagarin@=" + nodeModuleVersion); var meteor = spawn('meteor', [ 'add', 'anti:gagarin@=' + nodeModuleVersion ], { stdio: verbose ? 'inherit' : 'ignore', cwd: pathToApp }); /* meteor.stdout.on('data', function (data) { if (!verbose) { return; } process.stdout.write(chalk.gray(stripAnsi(data))); }); */ meteor.on('error', reject); meteor.on('exit', function (code) { if (code > 0) { return reject(new Error('meteor exited with code ' + code)); } logs.system("anti:gagarin is now in version " + nodeModuleVersion); resolve(); }); }).catch(reject); }).catch(reject); }); // Promise }
javascript
function ensureGagarinVersionsMatch(pathToApp, verbose) { var pathToMeteorPackages = path.join(pathToApp, '.meteor', 'packages'); var nodeModuleVersion = require('../../package.json').version; return new Promise(function (resolve, reject) { utils.getGagarinPackageVersion(pathToApp).then(function (packageVersion) { if (packageVersion === nodeModuleVersion) { logs.system("node module and smart package versions match, " + packageVersion); return resolve(); } tools.getReleaseVersion(pathToApp).then(function (meteorReleaseVersion) { if (meteorReleaseVersion < "0.9.0") { // really, we can do nothing about package version // without a decent package management system logs.system("meteor version is too old to automatically fix package version"); return resolve(); } logs.system("meteor add anti:gagarin@=" + nodeModuleVersion); var meteor = spawn('meteor', [ 'add', 'anti:gagarin@=' + nodeModuleVersion ], { stdio: verbose ? 'inherit' : 'ignore', cwd: pathToApp }); /* meteor.stdout.on('data', function (data) { if (!verbose) { return; } process.stdout.write(chalk.gray(stripAnsi(data))); }); */ meteor.on('error', reject); meteor.on('exit', function (code) { if (code > 0) { return reject(new Error('meteor exited with code ' + code)); } logs.system("anti:gagarin is now in version " + nodeModuleVersion); resolve(); }); }).catch(reject); }).catch(reject); }); // Promise }
[ "function", "ensureGagarinVersionsMatch", "(", "pathToApp", ",", "verbose", ")", "{", "var", "pathToMeteorPackages", "=", "path", ".", "join", "(", "pathToApp", ",", "'.meteor'", ",", "'packages'", ")", ";", "var", "nodeModuleVersion", "=", "require", "(", "'../../package.json'", ")", ".", "version", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "utils", ".", "getGagarinPackageVersion", "(", "pathToApp", ")", ".", "then", "(", "function", "(", "packageVersion", ")", "{", "if", "(", "packageVersion", "===", "nodeModuleVersion", ")", "{", "logs", ".", "system", "(", "\"node module and smart package versions match, \"", "+", "packageVersion", ")", ";", "return", "resolve", "(", ")", ";", "}", "tools", ".", "getReleaseVersion", "(", "pathToApp", ")", ".", "then", "(", "function", "(", "meteorReleaseVersion", ")", "{", "if", "(", "meteorReleaseVersion", "<", "\"0.9.0\"", ")", "{", "// really, we can do nothing about package version", "// without a decent package management system", "logs", ".", "system", "(", "\"meteor version is too old to automatically fix package version\"", ")", ";", "return", "resolve", "(", ")", ";", "}", "logs", ".", "system", "(", "\"meteor add anti:gagarin@=\"", "+", "nodeModuleVersion", ")", ";", "var", "meteor", "=", "spawn", "(", "'meteor'", ",", "[", "'add'", ",", "'anti:gagarin@='", "+", "nodeModuleVersion", "]", ",", "{", "stdio", ":", "verbose", "?", "'inherit'", ":", "'ignore'", ",", "cwd", ":", "pathToApp", "}", ")", ";", "/*\n meteor.stdout.on('data', function (data) {\n if (!verbose) {\n return;\n }\n process.stdout.write(chalk.gray(stripAnsi(data)));\n });\n */", "meteor", ".", "on", "(", "'error'", ",", "reject", ")", ";", "meteor", ".", "on", "(", "'exit'", ",", "function", "(", "code", ")", "{", "if", "(", "code", ">", "0", ")", "{", "return", "reject", "(", "new", "Error", "(", "'meteor exited with code '", "+", "code", ")", ")", ";", "}", "logs", ".", "system", "(", "\"anti:gagarin is now in version \"", "+", "nodeModuleVersion", ")", ";", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ".", "catch", "(", "reject", ")", ";", "}", ")", ".", "catch", "(", "reject", ")", ";", "}", ")", ";", "// Promise", "}" ]
Build Check smart package version and if it's wrong, install the right one. @param {string} pathToApp
[ "Build", "Check", "smart", "package", "version", "and", "if", "it", "s", "wrong", "install", "the", "right", "one", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/lib/meteor/build.js#L232-L286
28,114
anticoders/gagarin
lib/meteor/build.js
checkIfMeteorIsRunning
function checkIfMeteorIsRunning(pathToApp) { var pathToMongoLock = path.join(pathToApp, '.meteor', 'local', 'db', 'mongod.lock'); return new Promise(function (resolve, reject) { fs.readFile(pathToMongoLock, { encoding: 'utf8' }, function (err, data) { if (err) { // if the file does not exist, then we are ok anyway return err.code !== 'ENOENT' ? reject(err) : resolve(); } else { // isLocked iff the content is non empty resolve(!!data); } }); }); }
javascript
function checkIfMeteorIsRunning(pathToApp) { var pathToMongoLock = path.join(pathToApp, '.meteor', 'local', 'db', 'mongod.lock'); return new Promise(function (resolve, reject) { fs.readFile(pathToMongoLock, { encoding: 'utf8' }, function (err, data) { if (err) { // if the file does not exist, then we are ok anyway return err.code !== 'ENOENT' ? reject(err) : resolve(); } else { // isLocked iff the content is non empty resolve(!!data); } }); }); }
[ "function", "checkIfMeteorIsRunning", "(", "pathToApp", ")", "{", "var", "pathToMongoLock", "=", "path", ".", "join", "(", "pathToApp", ",", "'.meteor'", ",", "'local'", ",", "'db'", ",", "'mongod.lock'", ")", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "fs", ".", "readFile", "(", "pathToMongoLock", ",", "{", "encoding", ":", "'utf8'", "}", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "// if the file does not exist, then we are ok anyway", "return", "err", ".", "code", "!==", "'ENOENT'", "?", "reject", "(", "err", ")", ":", "resolve", "(", ")", ";", "}", "else", "{", "// isLocked iff the content is non empty", "resolve", "(", "!", "!", "data", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Guess if "develop" meteor is currently running. @param {string} pathToApp
[ "Guess", "if", "develop", "meteor", "is", "currently", "running", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/lib/meteor/build.js#L294-L307
28,115
anticoders/gagarin
lib/meteor/build.js
smartJsonWarning
function smartJsonWarning(pathToApp) { var pathToSmartJSON = path.join(pathToApp, 'smart.json'); return new Promise(function (resolve, reject) { fs.readFile(pathToSmartJSON, { endcoding: 'urf8' }, function (err, data) { if (err) { // if the file does not exist, then we are ok anyway return err.code !== 'ENOENT' ? reject(err) : resolve(); } else { // since the file exists, first print a warning, then resolve ... process.stdout.write(chalk.yellow( tools.banner([ 'we have detected a smart.json file in ' + pathToApp, 'since Gagarin no longer supports meteorite, this file will be ignored', ].join('\n'), {}) )); process.stdout.write('\n'); resolve(); } }); }); }
javascript
function smartJsonWarning(pathToApp) { var pathToSmartJSON = path.join(pathToApp, 'smart.json'); return new Promise(function (resolve, reject) { fs.readFile(pathToSmartJSON, { endcoding: 'urf8' }, function (err, data) { if (err) { // if the file does not exist, then we are ok anyway return err.code !== 'ENOENT' ? reject(err) : resolve(); } else { // since the file exists, first print a warning, then resolve ... process.stdout.write(chalk.yellow( tools.banner([ 'we have detected a smart.json file in ' + pathToApp, 'since Gagarin no longer supports meteorite, this file will be ignored', ].join('\n'), {}) )); process.stdout.write('\n'); resolve(); } }); }); }
[ "function", "smartJsonWarning", "(", "pathToApp", ")", "{", "var", "pathToSmartJSON", "=", "path", ".", "join", "(", "pathToApp", ",", "'smart.json'", ")", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "fs", ".", "readFile", "(", "pathToSmartJSON", ",", "{", "endcoding", ":", "'urf8'", "}", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "// if the file does not exist, then we are ok anyway", "return", "err", ".", "code", "!==", "'ENOENT'", "?", "reject", "(", "err", ")", ":", "resolve", "(", ")", ";", "}", "else", "{", "// since the file exists, first print a warning, then resolve ...", "process", ".", "stdout", ".", "write", "(", "chalk", ".", "yellow", "(", "tools", ".", "banner", "(", "[", "'we have detected a smart.json file in '", "+", "pathToApp", ",", "'since Gagarin no longer supports meteorite, this file will be ignored'", ",", "]", ".", "join", "(", "'\\n'", ")", ",", "{", "}", ")", ")", ")", ";", "process", ".", "stdout", ".", "write", "(", "'\\n'", ")", ";", "resolve", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Look for "smart.json" file. If there's one, print warning before resolving. @param {string} pathToApp
[ "Look", "for", "smart", ".", "json", "file", ".", "If", "there", "s", "one", "print", "warning", "before", "resolving", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/lib/meteor/build.js#L315-L335
28,116
velop-io/server
examples/4-react-app/server.js
start
async function start() { const mainRoute = server.addReactRoute( "", path.resolve(process.cwd(), "app/Routes.js") ); await server.start(); //start server console.log("started"); }
javascript
async function start() { const mainRoute = server.addReactRoute( "", path.resolve(process.cwd(), "app/Routes.js") ); await server.start(); //start server console.log("started"); }
[ "async", "function", "start", "(", ")", "{", "const", "mainRoute", "=", "server", ".", "addReactRoute", "(", "\"\"", ",", "path", ".", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "\"app/Routes.js\"", ")", ")", ";", "await", "server", ".", "start", "(", ")", ";", "//start server", "console", ".", "log", "(", "\"started\"", ")", ";", "}" ]
create a new instance
[ "create", "a", "new", "instance" ]
0d9521f2c6bacff0ab6b717432ab1cb87ccbc9bc
https://github.com/velop-io/server/blob/0d9521f2c6bacff0ab6b717432ab1cb87ccbc9bc/examples/4-react-app/server.js#L7-L15
28,117
anticoders/gagarin
meteor/backdoor.js
providePlugins
function providePlugins(code) { var chunks = []; if (typeof code === 'string') { code = code.split('\n'); } chunks.push("function (" + Object.keys(plugins).join(', ') + ") {"); chunks.push(" return " + code[0]); code.forEach(function (line, index) { if (index === 0) return; // omit the first line chunks.push(" " + line); }); chunks.push("}"); return chunks; }
javascript
function providePlugins(code) { var chunks = []; if (typeof code === 'string') { code = code.split('\n'); } chunks.push("function (" + Object.keys(plugins).join(', ') + ") {"); chunks.push(" return " + code[0]); code.forEach(function (line, index) { if (index === 0) return; // omit the first line chunks.push(" " + line); }); chunks.push("}"); return chunks; }
[ "function", "providePlugins", "(", "code", ")", "{", "var", "chunks", "=", "[", "]", ";", "if", "(", "typeof", "code", "===", "'string'", ")", "{", "code", "=", "code", ".", "split", "(", "'\\n'", ")", ";", "}", "chunks", ".", "push", "(", "\"function (\"", "+", "Object", ".", "keys", "(", "plugins", ")", ".", "join", "(", "', '", ")", "+", "\") {\"", ")", ";", "chunks", ".", "push", "(", "\" return \"", "+", "code", "[", "0", "]", ")", ";", "code", ".", "forEach", "(", "function", "(", "line", ",", "index", ")", "{", "if", "(", "index", "===", "0", ")", "return", ";", "// omit the first line", "chunks", ".", "push", "(", "\" \"", "+", "line", ")", ";", "}", ")", ";", "chunks", ".", "push", "(", "\"}\"", ")", ";", "return", "chunks", ";", "}" ]
Provide plugins the the local context. @param {(string|string[])} code @returns {string[]}
[ "Provide", "plugins", "the", "the", "local", "context", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/meteor/backdoor.js#L159-L173
28,118
anticoders/gagarin
meteor/backdoor.js
isolateScope
function isolateScope(code, closure) { if (typeof code === 'string') { code = code.split('\n'); } var keys = Object.keys(closure).map(function (key) { return stringify(key) + ": " + key; }); var chunks = []; chunks.push( "function (" + Object.keys(closure).join(', ') + ") {", " 'use strict';", " return (function (userFunc, getClosure, action) {", " try {", " return action(userFunc, getClosure);", " } catch (err) {", // this should never happen ... " return { error: err.message, closure: getClosure() };", " }", " })(" ); // the code provided by the user goes here align(code).forEach(function (line) { chunks.push(" " + line); }); chunks[chunks.length-1] += ','; chunks.push( // the function returning current state of the closure " function () {", " return { " + keys.join(', ') + " };", " },", // the custom action " arguments[arguments.length-1]", " );", "}" ); return chunks; }
javascript
function isolateScope(code, closure) { if (typeof code === 'string') { code = code.split('\n'); } var keys = Object.keys(closure).map(function (key) { return stringify(key) + ": " + key; }); var chunks = []; chunks.push( "function (" + Object.keys(closure).join(', ') + ") {", " 'use strict';", " return (function (userFunc, getClosure, action) {", " try {", " return action(userFunc, getClosure);", " } catch (err) {", // this should never happen ... " return { error: err.message, closure: getClosure() };", " }", " })(" ); // the code provided by the user goes here align(code).forEach(function (line) { chunks.push(" " + line); }); chunks[chunks.length-1] += ','; chunks.push( // the function returning current state of the closure " function () {", " return { " + keys.join(', ') + " };", " },", // the custom action " arguments[arguments.length-1]", " );", "}" ); return chunks; }
[ "function", "isolateScope", "(", "code", ",", "closure", ")", "{", "if", "(", "typeof", "code", "===", "'string'", ")", "{", "code", "=", "code", ".", "split", "(", "'\\n'", ")", ";", "}", "var", "keys", "=", "Object", ".", "keys", "(", "closure", ")", ".", "map", "(", "function", "(", "key", ")", "{", "return", "stringify", "(", "key", ")", "+", "\": \"", "+", "key", ";", "}", ")", ";", "var", "chunks", "=", "[", "]", ";", "chunks", ".", "push", "(", "\"function (\"", "+", "Object", ".", "keys", "(", "closure", ")", ".", "join", "(", "', '", ")", "+", "\") {\"", ",", "\" 'use strict';\"", ",", "\" return (function (userFunc, getClosure, action) {\"", ",", "\" try {\"", ",", "\" return action(userFunc, getClosure);\"", ",", "\" } catch (err) {\"", ",", "// this should never happen ...", "\" return { error: err.message, closure: getClosure() };\"", ",", "\" }\"", ",", "\" })(\"", ")", ";", "// the code provided by the user goes here", "align", "(", "code", ")", ".", "forEach", "(", "function", "(", "line", ")", "{", "chunks", ".", "push", "(", "\" \"", "+", "line", ")", ";", "}", ")", ";", "chunks", "[", "chunks", ".", "length", "-", "1", "]", "+=", "','", ";", "chunks", ".", "push", "(", "// the function returning current state of the closure", "\" function () {\"", ",", "\" return { \"", "+", "keys", ".", "join", "(", "', '", ")", "+", "\" };\"", ",", "\" },\"", ",", "// the custom action", "\" arguments[arguments.length-1]\"", ",", "\" );\"", ",", "\"}\"", ")", ";", "return", "chunks", ";", "}" ]
Make sure that the only local variables visible inside the code, are those from the closure object. @param {(string|string[])} code @param {Object} closure @returns {string[]}
[ "Make", "sure", "that", "the", "only", "local", "variables", "visible", "inside", "the", "code", "are", "those", "from", "the", "closure", "object", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/meteor/backdoor.js#L183-L224
28,119
anticoders/gagarin
meteor/backdoor.js
align
function align(code) { if (typeof code === 'string') { code = code.split('\n'); } var match = code[code.length-1].match(/^(\s+)\}/); var regex = null; if (match && code[0].match(/^function/)) { regex = new RegExp("^" + match[1]); return code.map(function (line) { return line.replace(regex, ""); }); } return code; }
javascript
function align(code) { if (typeof code === 'string') { code = code.split('\n'); } var match = code[code.length-1].match(/^(\s+)\}/); var regex = null; if (match && code[0].match(/^function/)) { regex = new RegExp("^" + match[1]); return code.map(function (line) { return line.replace(regex, ""); }); } return code; }
[ "function", "align", "(", "code", ")", "{", "if", "(", "typeof", "code", "===", "'string'", ")", "{", "code", "=", "code", ".", "split", "(", "'\\n'", ")", ";", "}", "var", "match", "=", "code", "[", "code", ".", "length", "-", "1", "]", ".", "match", "(", "/", "^(\\s+)\\}", "/", ")", ";", "var", "regex", "=", "null", ";", "if", "(", "match", "&&", "code", "[", "0", "]", ".", "match", "(", "/", "^function", "/", ")", ")", "{", "regex", "=", "new", "RegExp", "(", "\"^\"", "+", "match", "[", "1", "]", ")", ";", "return", "code", ".", "map", "(", "function", "(", "line", ")", "{", "return", "line", ".", "replace", "(", "regex", ",", "\"\"", ")", ";", "}", ")", ";", "}", "return", "code", ";", "}" ]
Fixes the source code indentation. @param {(string|string[])} code @returns {string[]}
[ "Fixes", "the", "source", "code", "indentation", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/meteor/backdoor.js#L232-L245
28,120
anticoders/gagarin
meteor/backdoor.js
compile
function compile(code, closure) { code = providePlugins(isolateScope(code, closure)).join('\n'); try { return vm.runInThisContext('(' + code + ')').apply({}, values(plugins)); } catch (err) { throw new Meteor.Error(400, err); } }
javascript
function compile(code, closure) { code = providePlugins(isolateScope(code, closure)).join('\n'); try { return vm.runInThisContext('(' + code + ')').apply({}, values(plugins)); } catch (err) { throw new Meteor.Error(400, err); } }
[ "function", "compile", "(", "code", ",", "closure", ")", "{", "code", "=", "providePlugins", "(", "isolateScope", "(", "code", ",", "closure", ")", ")", ".", "join", "(", "'\\n'", ")", ";", "try", "{", "return", "vm", ".", "runInThisContext", "(", "'('", "+", "code", "+", "')'", ")", ".", "apply", "(", "{", "}", ",", "values", "(", "plugins", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "throw", "new", "Meteor", ".", "Error", "(", "400", ",", "err", ")", ";", "}", "}" ]
Creates a function from the provided source code and closure object. @param {(string|string[])} code @param {Object} closure @returns {string[]}
[ "Creates", "a", "function", "from", "the", "provided", "source", "code", "and", "closure", "object", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/meteor/backdoor.js#L254-L261
28,121
anticoders/gagarin
lib/mocha/gagarin.js
Gagarin
function Gagarin (options) { "use strict"; var write = process.stdout.write.bind(process.stdout); var listOfFrameworks = []; var numberOfLinesPrinted = 0; // XXX gagarin user interface is defined here require('./interface'); options.settings = tools.getSettings(options.settings); options.ui = 'gagarin'; var factory = !options.parallel ? null : createParallelReporterFactory(function (allStats, elapsed) { if (numberOfLinesPrinted > 0) { write('\u001b[' + numberOfLinesPrinted + 'A') } write(' elapsed time: ' + Math.floor(elapsed / 100) / 10 + 's' + '\n\n'); numberOfLinesPrinted = 2 + table(allStats, write); }); function getMocha() { if (options.parallel === 0 && listOfFrameworks.length > 0) { return listOfFrameworks[0]; } var mocha = new Mocha(options); if (factory) { // overwrite the default reporter mocha._reporter = factory(listOfFrameworks.length); } var reporter = mocha._reporter; listOfFrameworks.push(mocha); return mocha; }; // getMocha this.options = options; this.addFile = function (file) { getMocha().addFile(file); } this.runAllFrameworks = function (callback) { var listOfErrors = []; var pending = listOfFrameworks.slice(0); var counter = 0; var running = 0; if (factory) { // looks like parallel test runner, so make sure // there are no logs which can break the table view factory.reset(); process.stdout.write('\n\n'); write = logs2.block(); logs.setSilentBuild(true); } listOfFrameworks.forEach(function (mocha) { mocha.loadFiles(); mocha.files = []; }); function finish() { if (factory) { logs2.unblock(); factory.epilogue(); } callback && callback(listOfErrors, counter); } function maybeFinish (action) { if (running <= 0 && pending <= 0) { finish(); } else { action && action(); } } function update() { var availableSlots = options.parallel > 0 ? options.parallel : 1; if (running >= availableSlots) { return false; } var next = pending.shift(); if (!next) { maybeFinish(); return false; } running += 1; try { next.run(function (numberOfFailures) { counter += numberOfFailures; running -= 1; maybeFinish(function () { // if not ... while (update()); // run as many suites as you can }); }); } catch (err) { listOfErrors.push(err); running -= 1; maybeFinish(); return false; } return true; } while (update()); // run as many suites as you can } }
javascript
function Gagarin (options) { "use strict"; var write = process.stdout.write.bind(process.stdout); var listOfFrameworks = []; var numberOfLinesPrinted = 0; // XXX gagarin user interface is defined here require('./interface'); options.settings = tools.getSettings(options.settings); options.ui = 'gagarin'; var factory = !options.parallel ? null : createParallelReporterFactory(function (allStats, elapsed) { if (numberOfLinesPrinted > 0) { write('\u001b[' + numberOfLinesPrinted + 'A') } write(' elapsed time: ' + Math.floor(elapsed / 100) / 10 + 's' + '\n\n'); numberOfLinesPrinted = 2 + table(allStats, write); }); function getMocha() { if (options.parallel === 0 && listOfFrameworks.length > 0) { return listOfFrameworks[0]; } var mocha = new Mocha(options); if (factory) { // overwrite the default reporter mocha._reporter = factory(listOfFrameworks.length); } var reporter = mocha._reporter; listOfFrameworks.push(mocha); return mocha; }; // getMocha this.options = options; this.addFile = function (file) { getMocha().addFile(file); } this.runAllFrameworks = function (callback) { var listOfErrors = []; var pending = listOfFrameworks.slice(0); var counter = 0; var running = 0; if (factory) { // looks like parallel test runner, so make sure // there are no logs which can break the table view factory.reset(); process.stdout.write('\n\n'); write = logs2.block(); logs.setSilentBuild(true); } listOfFrameworks.forEach(function (mocha) { mocha.loadFiles(); mocha.files = []; }); function finish() { if (factory) { logs2.unblock(); factory.epilogue(); } callback && callback(listOfErrors, counter); } function maybeFinish (action) { if (running <= 0 && pending <= 0) { finish(); } else { action && action(); } } function update() { var availableSlots = options.parallel > 0 ? options.parallel : 1; if (running >= availableSlots) { return false; } var next = pending.shift(); if (!next) { maybeFinish(); return false; } running += 1; try { next.run(function (numberOfFailures) { counter += numberOfFailures; running -= 1; maybeFinish(function () { // if not ... while (update()); // run as many suites as you can }); }); } catch (err) { listOfErrors.push(err); running -= 1; maybeFinish(); return false; } return true; } while (update()); // run as many suites as you can } }
[ "function", "Gagarin", "(", "options", ")", "{", "\"use strict\"", ";", "var", "write", "=", "process", ".", "stdout", ".", "write", ".", "bind", "(", "process", ".", "stdout", ")", ";", "var", "listOfFrameworks", "=", "[", "]", ";", "var", "numberOfLinesPrinted", "=", "0", ";", "// XXX gagarin user interface is defined here", "require", "(", "'./interface'", ")", ";", "options", ".", "settings", "=", "tools", ".", "getSettings", "(", "options", ".", "settings", ")", ";", "options", ".", "ui", "=", "'gagarin'", ";", "var", "factory", "=", "!", "options", ".", "parallel", "?", "null", ":", "createParallelReporterFactory", "(", "function", "(", "allStats", ",", "elapsed", ")", "{", "if", "(", "numberOfLinesPrinted", ">", "0", ")", "{", "write", "(", "'\\u001b['", "+", "numberOfLinesPrinted", "+", "'A'", ")", "}", "write", "(", "' elapsed time: '", "+", "Math", ".", "floor", "(", "elapsed", "/", "100", ")", "/", "10", "+", "'s'", "+", "'\\n\\n'", ")", ";", "numberOfLinesPrinted", "=", "2", "+", "table", "(", "allStats", ",", "write", ")", ";", "}", ")", ";", "function", "getMocha", "(", ")", "{", "if", "(", "options", ".", "parallel", "===", "0", "&&", "listOfFrameworks", ".", "length", ">", "0", ")", "{", "return", "listOfFrameworks", "[", "0", "]", ";", "}", "var", "mocha", "=", "new", "Mocha", "(", "options", ")", ";", "if", "(", "factory", ")", "{", "// overwrite the default reporter", "mocha", ".", "_reporter", "=", "factory", "(", "listOfFrameworks", ".", "length", ")", ";", "}", "var", "reporter", "=", "mocha", ".", "_reporter", ";", "listOfFrameworks", ".", "push", "(", "mocha", ")", ";", "return", "mocha", ";", "}", ";", "// getMocha", "this", ".", "options", "=", "options", ";", "this", ".", "addFile", "=", "function", "(", "file", ")", "{", "getMocha", "(", ")", ".", "addFile", "(", "file", ")", ";", "}", "this", ".", "runAllFrameworks", "=", "function", "(", "callback", ")", "{", "var", "listOfErrors", "=", "[", "]", ";", "var", "pending", "=", "listOfFrameworks", ".", "slice", "(", "0", ")", ";", "var", "counter", "=", "0", ";", "var", "running", "=", "0", ";", "if", "(", "factory", ")", "{", "// looks like parallel test runner, so make sure", "// there are no logs which can break the table view", "factory", ".", "reset", "(", ")", ";", "process", ".", "stdout", ".", "write", "(", "'\\n\\n'", ")", ";", "write", "=", "logs2", ".", "block", "(", ")", ";", "logs", ".", "setSilentBuild", "(", "true", ")", ";", "}", "listOfFrameworks", ".", "forEach", "(", "function", "(", "mocha", ")", "{", "mocha", ".", "loadFiles", "(", ")", ";", "mocha", ".", "files", "=", "[", "]", ";", "}", ")", ";", "function", "finish", "(", ")", "{", "if", "(", "factory", ")", "{", "logs2", ".", "unblock", "(", ")", ";", "factory", ".", "epilogue", "(", ")", ";", "}", "callback", "&&", "callback", "(", "listOfErrors", ",", "counter", ")", ";", "}", "function", "maybeFinish", "(", "action", ")", "{", "if", "(", "running", "<=", "0", "&&", "pending", "<=", "0", ")", "{", "finish", "(", ")", ";", "}", "else", "{", "action", "&&", "action", "(", ")", ";", "}", "}", "function", "update", "(", ")", "{", "var", "availableSlots", "=", "options", ".", "parallel", ">", "0", "?", "options", ".", "parallel", ":", "1", ";", "if", "(", "running", ">=", "availableSlots", ")", "{", "return", "false", ";", "}", "var", "next", "=", "pending", ".", "shift", "(", ")", ";", "if", "(", "!", "next", ")", "{", "maybeFinish", "(", ")", ";", "return", "false", ";", "}", "running", "+=", "1", ";", "try", "{", "next", ".", "run", "(", "function", "(", "numberOfFailures", ")", "{", "counter", "+=", "numberOfFailures", ";", "running", "-=", "1", ";", "maybeFinish", "(", "function", "(", ")", "{", "// if not ...", "while", "(", "update", "(", ")", ")", ";", "// run as many suites as you can", "}", ")", ";", "}", ")", ";", "}", "catch", "(", "err", ")", "{", "listOfErrors", ".", "push", "(", "err", ")", ";", "running", "-=", "1", ";", "maybeFinish", "(", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}", "while", "(", "update", "(", ")", ")", ";", "// run as many suites as you can", "}", "}" ]
Creates Gagarin with `options`. It inherits everything from Mocha except that the ui is always set to "gagarin". @param {Object} options
[ "Creates", "Gagarin", "with", "options", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/lib/mocha/gagarin.js#L33-L151
28,122
ciena-blueplanet/ember-test-utils
cli/lint-docker.js
getConfigFilePath
function getConfigFilePath () { // Look for configuration file in current working directory const files = fs.readdirSync(process.cwd()) const configFile = files.find((filePath) => { return CONFIG_FILE_NAMES.find((configFileName) => filePath.indexOf(configFileName) !== -1) }) // If no configuration file was found use recommend configuration if (!configFile) { return path.join(__dirname, '..', this.defaultConfig) } // Use configuration from current working directory return path.join(process.cwd(), configFile) }
javascript
function getConfigFilePath () { // Look for configuration file in current working directory const files = fs.readdirSync(process.cwd()) const configFile = files.find((filePath) => { return CONFIG_FILE_NAMES.find((configFileName) => filePath.indexOf(configFileName) !== -1) }) // If no configuration file was found use recommend configuration if (!configFile) { return path.join(__dirname, '..', this.defaultConfig) } // Use configuration from current working directory return path.join(process.cwd(), configFile) }
[ "function", "getConfigFilePath", "(", ")", "{", "// Look for configuration file in current working directory", "const", "files", "=", "fs", ".", "readdirSync", "(", "process", ".", "cwd", "(", ")", ")", "const", "configFile", "=", "files", ".", "find", "(", "(", "filePath", ")", "=>", "{", "return", "CONFIG_FILE_NAMES", ".", "find", "(", "(", "configFileName", ")", "=>", "filePath", ".", "indexOf", "(", "configFileName", ")", "!==", "-", "1", ")", "}", ")", "// If no configuration file was found use recommend configuration", "if", "(", "!", "configFile", ")", "{", "return", "path", ".", "join", "(", "__dirname", ",", "'..'", ",", "this", ".", "defaultConfig", ")", "}", "// Use configuration from current working directory", "return", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "configFile", ")", "}" ]
Get configuration options for dockerfile_lint @returns {DockerfileLintConfig} dockerfile lint configuration options
[ "Get", "configuration", "options", "for", "dockerfile_lint" ]
7e40f35d53c488b5f12968212110bb5a5ec138ea
https://github.com/ciena-blueplanet/ember-test-utils/blob/7e40f35d53c488b5f12968212110bb5a5ec138ea/cli/lint-docker.js#L32-L46
28,123
ciena-blueplanet/ember-test-utils
cli/lint-docker.js
lintFile
function lintFile (linter, fileName) { const fileContents = fs.readFileSync(fileName, {encoding: 'utf8'}).toString() const report = linter.validate(fileContents) const errors = report.error.count const warnings = report.warn.count if (errors || warnings) { this.printFilePath(fileName) report.error.data.forEach(logItem.bind(this)) report.warn.data.forEach(logItem.bind(this)) console.log('') // logging empty line } return report }
javascript
function lintFile (linter, fileName) { const fileContents = fs.readFileSync(fileName, {encoding: 'utf8'}).toString() const report = linter.validate(fileContents) const errors = report.error.count const warnings = report.warn.count if (errors || warnings) { this.printFilePath(fileName) report.error.data.forEach(logItem.bind(this)) report.warn.data.forEach(logItem.bind(this)) console.log('') // logging empty line } return report }
[ "function", "lintFile", "(", "linter", ",", "fileName", ")", "{", "const", "fileContents", "=", "fs", ".", "readFileSync", "(", "fileName", ",", "{", "encoding", ":", "'utf8'", "}", ")", ".", "toString", "(", ")", "const", "report", "=", "linter", ".", "validate", "(", "fileContents", ")", "const", "errors", "=", "report", ".", "error", ".", "count", "const", "warnings", "=", "report", ".", "warn", ".", "count", "if", "(", "errors", "||", "warnings", ")", "{", "this", ".", "printFilePath", "(", "fileName", ")", "report", ".", "error", ".", "data", ".", "forEach", "(", "logItem", ".", "bind", "(", "this", ")", ")", "report", ".", "warn", ".", "data", ".", "forEach", "(", "logItem", ".", "bind", "(", "this", ")", ")", "console", ".", "log", "(", "''", ")", "// logging empty line", "}", "return", "report", "}" ]
Lint a single Dockerfile @param {Object} linter - linter @param {String} fileName - name of file to lint @returns {Object} lint result
[ "Lint", "a", "single", "Dockerfile" ]
7e40f35d53c488b5f12968212110bb5a5ec138ea
https://github.com/ciena-blueplanet/ember-test-utils/blob/7e40f35d53c488b5f12968212110bb5a5ec138ea/cli/lint-docker.js#L71-L87
28,124
Testlio/lambda-tools
lib/helpers/newlines.js
processByte
function processByte (stream, b) { assert.equal(typeof b, 'number'); if (b === NEWLINE) { stream.emit('newline'); } }
javascript
function processByte (stream, b) { assert.equal(typeof b, 'number'); if (b === NEWLINE) { stream.emit('newline'); } }
[ "function", "processByte", "(", "stream", ",", "b", ")", "{", "assert", ".", "equal", "(", "typeof", "b", ",", "'number'", ")", ";", "if", "(", "b", "===", "NEWLINE", ")", "{", "stream", ".", "emit", "(", "'newline'", ")", ";", "}", "}" ]
Processes an individual byte being written to a stream
[ "Processes", "an", "individual", "byte", "being", "written", "to", "a", "stream" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/helpers/newlines.js#L34-L39
28,125
Testlio/lambda-tools
lib/helpers/logger.js
log
function log(fn, args, indent) { if (args.length === 0) { return; } // Assumes args are something you would pass into console.log // Applies appropriate nesting const indentation = _.repeat('\t', indent); // Prepend tabs to first arg (if string) if (_.isString(args[0])) { args[0] = indentation + args[0]; } else { args.splice(0, 0, indentation); } fn.apply(this, args); }
javascript
function log(fn, args, indent) { if (args.length === 0) { return; } // Assumes args are something you would pass into console.log // Applies appropriate nesting const indentation = _.repeat('\t', indent); // Prepend tabs to first arg (if string) if (_.isString(args[0])) { args[0] = indentation + args[0]; } else { args.splice(0, 0, indentation); } fn.apply(this, args); }
[ "function", "log", "(", "fn", ",", "args", ",", "indent", ")", "{", "if", "(", "args", ".", "length", "===", "0", ")", "{", "return", ";", "}", "// Assumes args are something you would pass into console.log", "// Applies appropriate nesting", "const", "indentation", "=", "_", ".", "repeat", "(", "'\\t'", ",", "indent", ")", ";", "// Prepend tabs to first arg (if string)", "if", "(", "_", ".", "isString", "(", "args", "[", "0", "]", ")", ")", "{", "args", "[", "0", "]", "=", "indentation", "+", "args", "[", "0", "]", ";", "}", "else", "{", "args", ".", "splice", "(", "0", ",", "0", ",", "indentation", ")", ";", "}", "fn", ".", "apply", "(", "this", ",", "args", ")", ";", "}" ]
Internal helper for logging stuff out
[ "Internal", "helper", "for", "logging", "stuff", "out" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/helpers/logger.js#L15-L32
28,126
Testlio/lambda-tools
lib/cf-resources/lambda-version-resource/index.js
getFunction
function getFunction(name) { return new Promise((resolve, reject) => { lambda.getFunctionConfiguration({ FunctionName: name }, function(err, data) { if (err) return reject(err); resolve(data); }); }); }
javascript
function getFunction(name) { return new Promise((resolve, reject) => { lambda.getFunctionConfiguration({ FunctionName: name }, function(err, data) { if (err) return reject(err); resolve(data); }); }); }
[ "function", "getFunction", "(", "name", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "lambda", ".", "getFunctionConfiguration", "(", "{", "FunctionName", ":", "name", "}", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "resolve", "(", "data", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Get function configuration by its name @return {Promise} which resolves into the function configuration
[ "Get", "function", "configuration", "by", "its", "name" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/lambda-version-resource/index.js#L21-L30
28,127
Testlio/lambda-tools
lib/cf-resources/lambda-version-resource/index.js
getFunctionVersions
function getFunctionVersions(name, marker) { // Grab functions return new Promise((resolve, reject) => { lambda.listVersionsByFunction({ FunctionName: name, Marker: marker }, function(err, data) { if (err) return reject(err); // Check if we can grab even more if (data.NextMarker) { return getFunctionVersions(name, data.NextMarker).then((versions) => { resolve(data.Versions.concat(versions)); }); } resolve(data.Versions); }); }); }
javascript
function getFunctionVersions(name, marker) { // Grab functions return new Promise((resolve, reject) => { lambda.listVersionsByFunction({ FunctionName: name, Marker: marker }, function(err, data) { if (err) return reject(err); // Check if we can grab even more if (data.NextMarker) { return getFunctionVersions(name, data.NextMarker).then((versions) => { resolve(data.Versions.concat(versions)); }); } resolve(data.Versions); }); }); }
[ "function", "getFunctionVersions", "(", "name", ",", "marker", ")", "{", "// Grab functions", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "lambda", ".", "listVersionsByFunction", "(", "{", "FunctionName", ":", "name", ",", "Marker", ":", "marker", "}", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "// Check if we can grab even more", "if", "(", "data", ".", "NextMarker", ")", "{", "return", "getFunctionVersions", "(", "name", ",", "data", ".", "NextMarker", ")", ".", "then", "(", "(", "versions", ")", "=>", "{", "resolve", "(", "data", ".", "Versions", ".", "concat", "(", "versions", ")", ")", ";", "}", ")", ";", "}", "resolve", "(", "data", ".", "Versions", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Get all function versions @return {Promise} which resolves into an array of version configurations
[ "Get", "all", "function", "versions" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/lambda-version-resource/index.js#L37-L56
28,128
Testlio/lambda-tools
lib/cf-resources/lambda-version-resource/index.js
functionPublishVersion
function functionPublishVersion(name, description, hash) { return new Promise((resolve, reject) => { lambda.publishVersion({ FunctionName: name, Description: description, CodeSha256: hash }, function(err, data) { if (err) return reject(err); resolve(data); }); }); }
javascript
function functionPublishVersion(name, description, hash) { return new Promise((resolve, reject) => { lambda.publishVersion({ FunctionName: name, Description: description, CodeSha256: hash }, function(err, data) { if (err) return reject(err); resolve(data); }); }); }
[ "function", "functionPublishVersion", "(", "name", ",", "description", ",", "hash", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "lambda", ".", "publishVersion", "(", "{", "FunctionName", ":", "name", ",", "Description", ":", "description", ",", "CodeSha256", ":", "hash", "}", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "resolve", "(", "data", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Publish a new Lambda function version @return {Promise} which resolves into the newly published version
[ "Publish", "a", "new", "Lambda", "function", "version" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/lambda-version-resource/index.js#L63-L74
28,129
Testlio/lambda-tools
lib/run/execution.js
getDirectoryTree
function getDirectoryTree(dir) { const items = []; return new Promise(function(resolve) { fs.walk(dir) .on('data', function (item) { items.push(item.path); }) .on('end', function () { resolve(items); }); }); }
javascript
function getDirectoryTree(dir) { const items = []; return new Promise(function(resolve) { fs.walk(dir) .on('data', function (item) { items.push(item.path); }) .on('end', function () { resolve(items); }); }); }
[ "function", "getDirectoryTree", "(", "dir", ")", "{", "const", "items", "=", "[", "]", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "fs", ".", "walk", "(", "dir", ")", ".", "on", "(", "'data'", ",", "function", "(", "item", ")", "{", "items", ".", "push", "(", "item", ".", "path", ")", ";", "}", ")", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "resolve", "(", "items", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Helper function for capturing the state of a directory
[ "Helper", "function", "for", "capturing", "the", "state", "of", "a", "directory" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/run/execution.js#L14-L25
28,130
Testlio/lambda-tools
lib/cf-resources/api-gateway-resource/index.js
replaceVariables
function replaceVariables(localPath, variables) { return new Promise(function(resolve, reject) { // Read the file let body = fs.readFileSync(localPath, 'utf8'); // Do the replacement for all of the variables const keys = Object.keys(variables); keys.forEach(function(key) { const value = variables[key]; const re = new RegExp(`"\\$${key}"`, 'g'); // Parse the value (to see if it is falsey) try { const parsed = JSON.parse(value); body = body.replace(re, parsed ? `"${parsed}"` : `null`); } catch (err) { // Not valid JSON, treat it as a string body = body.replace(re, `"${value}"`); } }); console.log('Variables replaced', body); fs.writeFile(localPath, body, function(err) { if (err) return reject(err); resolve(localPath); }); }); }
javascript
function replaceVariables(localPath, variables) { return new Promise(function(resolve, reject) { // Read the file let body = fs.readFileSync(localPath, 'utf8'); // Do the replacement for all of the variables const keys = Object.keys(variables); keys.forEach(function(key) { const value = variables[key]; const re = new RegExp(`"\\$${key}"`, 'g'); // Parse the value (to see if it is falsey) try { const parsed = JSON.parse(value); body = body.replace(re, parsed ? `"${parsed}"` : `null`); } catch (err) { // Not valid JSON, treat it as a string body = body.replace(re, `"${value}"`); } }); console.log('Variables replaced', body); fs.writeFile(localPath, body, function(err) { if (err) return reject(err); resolve(localPath); }); }); }
[ "function", "replaceVariables", "(", "localPath", ",", "variables", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "// Read the file", "let", "body", "=", "fs", ".", "readFileSync", "(", "localPath", ",", "'utf8'", ")", ";", "// Do the replacement for all of the variables", "const", "keys", "=", "Object", ".", "keys", "(", "variables", ")", ";", "keys", ".", "forEach", "(", "function", "(", "key", ")", "{", "const", "value", "=", "variables", "[", "key", "]", ";", "const", "re", "=", "new", "RegExp", "(", "`", "\\\\", "${", "key", "}", "`", ",", "'g'", ")", ";", "// Parse the value (to see if it is falsey)", "try", "{", "const", "parsed", "=", "JSON", ".", "parse", "(", "value", ")", ";", "body", "=", "body", ".", "replace", "(", "re", ",", "parsed", "?", "`", "${", "parsed", "}", "`", ":", "`", "`", ")", ";", "}", "catch", "(", "err", ")", "{", "// Not valid JSON, treat it as a string", "body", "=", "body", ".", "replace", "(", "re", ",", "`", "${", "value", "}", "`", ")", ";", "}", "}", ")", ";", "console", ".", "log", "(", "'Variables replaced'", ",", "body", ")", ";", "fs", ".", "writeFile", "(", "localPath", ",", "body", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "resolve", "(", "localPath", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Helper function for replacing variables in the API definition @returns {Promise} which resolves into the same localPath the file was written back to
[ "Helper", "function", "for", "replacing", "variables", "in", "the", "API", "definition" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/api-gateway-resource/index.js#L22-L49
28,131
Testlio/lambda-tools
lib/cf-resources/api-gateway-resource/apig-utility.js
function(apiId) { return APIG.getStages({ restApiId: apiId }).promise().then(function(data) { return data.item; }); }
javascript
function(apiId) { return APIG.getStages({ restApiId: apiId }).promise().then(function(data) { return data.item; }); }
[ "function", "(", "apiId", ")", "{", "return", "APIG", ".", "getStages", "(", "{", "restApiId", ":", "apiId", "}", ")", ".", "promise", "(", ")", ".", "then", "(", "function", "(", "data", ")", "{", "return", "data", ".", "item", ";", "}", ")", ";", "}" ]
Fetch existing stages for a specific API @return {Promise} which resolves to all stages for the specific API
[ "Fetch", "existing", "stages", "for", "a", "specific", "API" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/api-gateway-resource/apig-utility.js#L51-L57
28,132
Testlio/lambda-tools
lib/cf-resources/api-gateway-resource/apig-utility.js
function(apiId, stageName) { return new Promise(function(resolve, reject) { APIG.deleteStage({ restApiId: apiId, stageName: stageName }, function(err) { if (err) { // If no such stage, then success if (err.code === 404 || err.code === 'NotFoundException') { return resolve(apiId); } return reject(err); } resolve(apiId); }); }); }
javascript
function(apiId, stageName) { return new Promise(function(resolve, reject) { APIG.deleteStage({ restApiId: apiId, stageName: stageName }, function(err) { if (err) { // If no such stage, then success if (err.code === 404 || err.code === 'NotFoundException') { return resolve(apiId); } return reject(err); } resolve(apiId); }); }); }
[ "function", "(", "apiId", ",", "stageName", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "APIG", ".", "deleteStage", "(", "{", "restApiId", ":", "apiId", ",", "stageName", ":", "stageName", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "// If no such stage, then success", "if", "(", "err", ".", "code", "===", "404", "||", "err", ".", "code", "===", "'NotFoundException'", ")", "{", "return", "resolve", "(", "apiId", ")", ";", "}", "return", "reject", "(", "err", ")", ";", "}", "resolve", "(", "apiId", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Delete a specific stage on a specific API @return {Promise} which resolves to the API ID that the stage was deleted on
[ "Delete", "a", "specific", "stage", "on", "a", "specific", "API" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/api-gateway-resource/apig-utility.js#L71-L89
28,133
Testlio/lambda-tools
lib/cf-resources/api-gateway-resource/apig-utility.js
function(apiId) { return new Promise(function(resolve, reject) { APIG.deleteRestApi({ restApiId: apiId }, function(err) { if (err) { if (err.code === 404 || err.code === 'NotFoundException') { // API didn't exist to begin with return resolve(apiId); } return reject(err); } resolve(apiId); }); }); }
javascript
function(apiId) { return new Promise(function(resolve, reject) { APIG.deleteRestApi({ restApiId: apiId }, function(err) { if (err) { if (err.code === 404 || err.code === 'NotFoundException') { // API didn't exist to begin with return resolve(apiId); } return reject(err); } resolve(apiId); }); }); }
[ "function", "(", "apiId", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "APIG", ".", "deleteRestApi", "(", "{", "restApiId", ":", "apiId", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", ".", "code", "===", "404", "||", "err", ".", "code", "===", "'NotFoundException'", ")", "{", "// API didn't exist to begin with", "return", "resolve", "(", "apiId", ")", ";", "}", "return", "reject", "(", "err", ")", ";", "}", "resolve", "(", "apiId", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Delete the entire API ID @return {Promise} which resolves to the ID of the API that was deleted
[ "Delete", "the", "entire", "API", "ID" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/api-gateway-resource/apig-utility.js#L96-L113
28,134
Testlio/lambda-tools
lib/cf-resources/api-gateway-resource/apig-utility.js
function(apiId) { return module.exports.fetchExistingStages(apiId).then(function(stages) { // If there are no stages, then delete the API if (!stages || stages.length === 0) { return module.exports.deleteAPI(apiId); } return apiId; }); }
javascript
function(apiId) { return module.exports.fetchExistingStages(apiId).then(function(stages) { // If there are no stages, then delete the API if (!stages || stages.length === 0) { return module.exports.deleteAPI(apiId); } return apiId; }); }
[ "function", "(", "apiId", ")", "{", "return", "module", ".", "exports", ".", "fetchExistingStages", "(", "apiId", ")", ".", "then", "(", "function", "(", "stages", ")", "{", "// If there are no stages, then delete the API", "if", "(", "!", "stages", "||", "stages", ".", "length", "===", "0", ")", "{", "return", "module", ".", "exports", ".", "deleteAPI", "(", "apiId", ")", ";", "}", "return", "apiId", ";", "}", ")", ";", "}" ]
Delete the API if and only if there are no more stages deployed on it @return {Promise} which resolves to the ID of the API that was deleted
[ "Delete", "the", "API", "if", "and", "only", "if", "there", "are", "no", "more", "stages", "deployed", "on", "it" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/api-gateway-resource/apig-utility.js#L120-L129
28,135
Testlio/lambda-tools
lib/cf-resources/api-gateway-resource/apig-utility.js
function(apiName, swaggerPath) { return new Promise(function(resolve, reject) { fs.readFile(swaggerPath, function(err, data) { if (err) return reject(err); resolve(APIG.importRestApi({ body: data, failOnWarnings: false }).promise()); }); }); }
javascript
function(apiName, swaggerPath) { return new Promise(function(resolve, reject) { fs.readFile(swaggerPath, function(err, data) { if (err) return reject(err); resolve(APIG.importRestApi({ body: data, failOnWarnings: false }).promise()); }); }); }
[ "function", "(", "apiName", ",", "swaggerPath", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "fs", ".", "readFile", "(", "swaggerPath", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "resolve", "(", "APIG", ".", "importRestApi", "(", "{", "body", ":", "data", ",", "failOnWarnings", ":", "false", "}", ")", ".", "promise", "(", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Create a new API instance from a Swagger file @return {Promise} which resolves to the newly created API instance
[ "Create", "a", "new", "API", "instance", "from", "a", "Swagger", "file" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/api-gateway-resource/apig-utility.js#L161-L172
28,136
Testlio/lambda-tools
lib/cf-resources/api-gateway-resource/apig-utility.js
function(apiId, swaggerPath) { return new Promise(function(resolve, reject) { fs.readFile(swaggerPath, function(err, data) { if (err) return reject(err); resolve(APIG.putRestApi({ restApiId: apiId, body: data, mode: 'overwrite' }).promise()); }); }); }
javascript
function(apiId, swaggerPath) { return new Promise(function(resolve, reject) { fs.readFile(swaggerPath, function(err, data) { if (err) return reject(err); resolve(APIG.putRestApi({ restApiId: apiId, body: data, mode: 'overwrite' }).promise()); }); }); }
[ "function", "(", "apiId", ",", "swaggerPath", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "fs", ".", "readFile", "(", "swaggerPath", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "resolve", "(", "APIG", ".", "putRestApi", "(", "{", "restApiId", ":", "apiId", ",", "body", ":", "data", ",", "mode", ":", "'overwrite'", "}", ")", ".", "promise", "(", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Update an API with a specification from a Swagger file The update is done in the "overwrite" mode of API Gateway @return {Promise} which resolves to the updated API
[ "Update", "an", "API", "with", "a", "specification", "from", "a", "Swagger", "file", "The", "update", "is", "done", "in", "the", "overwrite", "mode", "of", "API", "Gateway" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/api-gateway-resource/apig-utility.js#L180-L192
28,137
Testlio/lambda-tools
lib/deploy/bundle-lambdas-step.js
archiveDependencies
function archiveDependencies(cwd, pkg) { let result = []; if (pkg.path) { result.push({ data: pkg.path, type: 'directory', name: path.relative(cwd, pkg.path) }); } pkg.dependencies.forEach(function(dep) { if (dep.path) { result.push({ data: dep.path, type: 'directory', name: path.relative(cwd, dep.path) }); } if (dep.dependencies) { result = result.concat(archiveDependencies(cwd, dep)); } }); return result; }
javascript
function archiveDependencies(cwd, pkg) { let result = []; if (pkg.path) { result.push({ data: pkg.path, type: 'directory', name: path.relative(cwd, pkg.path) }); } pkg.dependencies.forEach(function(dep) { if (dep.path) { result.push({ data: dep.path, type: 'directory', name: path.relative(cwd, dep.path) }); } if (dep.dependencies) { result = result.concat(archiveDependencies(cwd, dep)); } }); return result; }
[ "function", "archiveDependencies", "(", "cwd", ",", "pkg", ")", "{", "let", "result", "=", "[", "]", ";", "if", "(", "pkg", ".", "path", ")", "{", "result", ".", "push", "(", "{", "data", ":", "pkg", ".", "path", ",", "type", ":", "'directory'", ",", "name", ":", "path", ".", "relative", "(", "cwd", ",", "pkg", ".", "path", ")", "}", ")", ";", "}", "pkg", ".", "dependencies", ".", "forEach", "(", "function", "(", "dep", ")", "{", "if", "(", "dep", ".", "path", ")", "{", "result", ".", "push", "(", "{", "data", ":", "dep", ".", "path", ",", "type", ":", "'directory'", ",", "name", ":", "path", ".", "relative", "(", "cwd", ",", "dep", ".", "path", ")", "}", ")", ";", "}", "if", "(", "dep", ".", "dependencies", ")", "{", "result", "=", "result", ".", "concat", "(", "archiveDependencies", "(", "cwd", ",", "dep", ")", ")", ";", "}", "}", ")", ";", "return", "result", ";", "}" ]
Helper for recursively adding all dependencies to an archive
[ "Helper", "for", "recursively", "adding", "all", "dependencies", "to", "an", "archive" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/deploy/bundle-lambdas-step.js#L26-L52
28,138
Testlio/lambda-tools
lib/deploy/bundle-lambdas-step.js
bundleLambda
function bundleLambda(lambda, exclude, environment, bundlePath, sourceMapPath) { environment = environment || {}; exclude = exclude || []; return new Promise(function(resolve, reject) { const bundler = new Browserify(lambda.path, { basedir: path.dirname(lambda.path), standalone: lambda.name, browserField: false, builtins: false, commondir: false, ignoreMissing: true, detectGlobals: true, debug: !!sourceMapPath, insertGlobalVars: { process: function() {} } }); // AWS SDK should always be excluded bundler.exclude('aws-sdk'); // Further things to exclude [].concat(exclude).forEach(function(module) { bundler.exclude(module); }); // Envify (doesn't purge, as there are valid values // that can be used in Lambda functions) if (environment) { bundler.transform(envify(environment), { global: true }); } let stream = bundler.bundle(); if (sourceMapPath) { stream = stream.pipe(exorcist(sourceMapPath)); } stream.pipe(fs.createWriteStream(bundlePath)); stream.on('error', function(err) { reject(err); }).on('end', function() { resolve(); }); }); }
javascript
function bundleLambda(lambda, exclude, environment, bundlePath, sourceMapPath) { environment = environment || {}; exclude = exclude || []; return new Promise(function(resolve, reject) { const bundler = new Browserify(lambda.path, { basedir: path.dirname(lambda.path), standalone: lambda.name, browserField: false, builtins: false, commondir: false, ignoreMissing: true, detectGlobals: true, debug: !!sourceMapPath, insertGlobalVars: { process: function() {} } }); // AWS SDK should always be excluded bundler.exclude('aws-sdk'); // Further things to exclude [].concat(exclude).forEach(function(module) { bundler.exclude(module); }); // Envify (doesn't purge, as there are valid values // that can be used in Lambda functions) if (environment) { bundler.transform(envify(environment), { global: true }); } let stream = bundler.bundle(); if (sourceMapPath) { stream = stream.pipe(exorcist(sourceMapPath)); } stream.pipe(fs.createWriteStream(bundlePath)); stream.on('error', function(err) { reject(err); }).on('end', function() { resolve(); }); }); }
[ "function", "bundleLambda", "(", "lambda", ",", "exclude", ",", "environment", ",", "bundlePath", ",", "sourceMapPath", ")", "{", "environment", "=", "environment", "||", "{", "}", ";", "exclude", "=", "exclude", "||", "[", "]", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "const", "bundler", "=", "new", "Browserify", "(", "lambda", ".", "path", ",", "{", "basedir", ":", "path", ".", "dirname", "(", "lambda", ".", "path", ")", ",", "standalone", ":", "lambda", ".", "name", ",", "browserField", ":", "false", ",", "builtins", ":", "false", ",", "commondir", ":", "false", ",", "ignoreMissing", ":", "true", ",", "detectGlobals", ":", "true", ",", "debug", ":", "!", "!", "sourceMapPath", ",", "insertGlobalVars", ":", "{", "process", ":", "function", "(", ")", "{", "}", "}", "}", ")", ";", "// AWS SDK should always be excluded", "bundler", ".", "exclude", "(", "'aws-sdk'", ")", ";", "// Further things to exclude", "[", "]", ".", "concat", "(", "exclude", ")", ".", "forEach", "(", "function", "(", "module", ")", "{", "bundler", ".", "exclude", "(", "module", ")", ";", "}", ")", ";", "// Envify (doesn't purge, as there are valid values", "// that can be used in Lambda functions)", "if", "(", "environment", ")", "{", "bundler", ".", "transform", "(", "envify", "(", "environment", ")", ",", "{", "global", ":", "true", "}", ")", ";", "}", "let", "stream", "=", "bundler", ".", "bundle", "(", ")", ";", "if", "(", "sourceMapPath", ")", "{", "stream", "=", "stream", ".", "pipe", "(", "exorcist", "(", "sourceMapPath", ")", ")", ";", "}", "stream", ".", "pipe", "(", "fs", ".", "createWriteStream", "(", "bundlePath", ")", ")", ";", "stream", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", ")", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Processing pipeline, all functions should return a promise Bundles the lambda code, returning the bundled code @param lambda Lambda function to bundle, should at minimum have a path property with the entry point @param exclude Array of packages to exclude from the bundle, defaults to aws-sdk @param environment Env variables to envify @param bundlePath Path to save the bundled code to @param sourceMapPath Path to save the source maps to @returns Promise that bundles the code and writes it to a file
[ "Processing", "pipeline", "all", "functions", "should", "return", "a", "promise", "Bundles", "the", "lambda", "code", "returning", "the", "bundled", "code" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/deploy/bundle-lambdas-step.js#L70-L118
28,139
Testlio/lambda-tools
lib/cf-resources/api-gateway-resource/s3-utility.js
function(bucket, key, version, localPath) { return S3.getObject({ Bucket: bucket, Key: key, VersionId: version }).promise().then(function(data) { return new Promise(function(resolve, reject) { fs.writeFile(localPath, data.Body, function(err) { if (err) return reject(err); resolve(localPath); }); }); }); }
javascript
function(bucket, key, version, localPath) { return S3.getObject({ Bucket: bucket, Key: key, VersionId: version }).promise().then(function(data) { return new Promise(function(resolve, reject) { fs.writeFile(localPath, data.Body, function(err) { if (err) return reject(err); resolve(localPath); }); }); }); }
[ "function", "(", "bucket", ",", "key", ",", "version", ",", "localPath", ")", "{", "return", "S3", ".", "getObject", "(", "{", "Bucket", ":", "bucket", ",", "Key", ":", "key", ",", "VersionId", ":", "version", "}", ")", ".", "promise", "(", ")", ".", "then", "(", "function", "(", "data", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "fs", ".", "writeFile", "(", "localPath", ",", "data", ".", "Body", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "resolve", "(", "localPath", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Download a file from remote bucket to a local path @return {Promise} which resolves to the local path the file was saved to
[ "Download", "a", "file", "from", "remote", "bucket", "to", "a", "local", "path" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/api-gateway-resource/s3-utility.js#L16-L29
28,140
Testlio/lambda-tools
lib/cf-resources/api-gateway-resource/s3-utility.js
function(bucket, key, version) { return S3.headObject({ Bucket: bucket, Key: key, VersionId: version }).promise(); }
javascript
function(bucket, key, version) { return S3.headObject({ Bucket: bucket, Key: key, VersionId: version }).promise(); }
[ "function", "(", "bucket", ",", "key", ",", "version", ")", "{", "return", "S3", ".", "headObject", "(", "{", "Bucket", ":", "bucket", ",", "Key", ":", "key", ",", "VersionId", ":", "version", "}", ")", ".", "promise", "(", ")", ";", "}" ]
Execute a HEAD operation on a specific key in a bucket. The request can also contain an optional version for the file @returns {Promise} which resolves to the response data for the request
[ "Execute", "a", "HEAD", "operation", "on", "a", "specific", "key", "in", "a", "bucket", ".", "The", "request", "can", "also", "contain", "an", "optional", "version", "for", "the", "file" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/api-gateway-resource/s3-utility.js#L37-L43
28,141
Testlio/lambda-tools
lib/helpers/cf-template-functions.js
cloudFormationDependencies
function cloudFormationDependencies(value) { if (_.isString(value)) { return [value]; } if (!_.isObject(value)) { return []; } const keys = _.keys(value); if (keys.length !== 1) { // CF functions always have a single key return []; } const key = keys[0]; if (key === 'Fn::GetAtt') { // Logical name of resource is the first value in array return cloudFormationDependencies(value[key][0]); } if (key === 'Ref') { // Value should be the logical name (but may be a further function) return cloudFormationDependencies(value[key]); } if (key === 'Fn::Join') { // Value is the combined string, meaning parts that are not // string can all include dependencies return _.flatten(value[key][1].filter(_.isObject).map(cloudFormationDependencies)); } if (key === 'Fn::Select') { // Value is picked from an array const index = value[key][0]; const list = value[key][1]; return cloudFormationDependencies(list[index]); } // Unknown/Unhandled return []; }
javascript
function cloudFormationDependencies(value) { if (_.isString(value)) { return [value]; } if (!_.isObject(value)) { return []; } const keys = _.keys(value); if (keys.length !== 1) { // CF functions always have a single key return []; } const key = keys[0]; if (key === 'Fn::GetAtt') { // Logical name of resource is the first value in array return cloudFormationDependencies(value[key][0]); } if (key === 'Ref') { // Value should be the logical name (but may be a further function) return cloudFormationDependencies(value[key]); } if (key === 'Fn::Join') { // Value is the combined string, meaning parts that are not // string can all include dependencies return _.flatten(value[key][1].filter(_.isObject).map(cloudFormationDependencies)); } if (key === 'Fn::Select') { // Value is picked from an array const index = value[key][0]; const list = value[key][1]; return cloudFormationDependencies(list[index]); } // Unknown/Unhandled return []; }
[ "function", "cloudFormationDependencies", "(", "value", ")", "{", "if", "(", "_", ".", "isString", "(", "value", ")", ")", "{", "return", "[", "value", "]", ";", "}", "if", "(", "!", "_", ".", "isObject", "(", "value", ")", ")", "{", "return", "[", "]", ";", "}", "const", "keys", "=", "_", ".", "keys", "(", "value", ")", ";", "if", "(", "keys", ".", "length", "!==", "1", ")", "{", "// CF functions always have a single key", "return", "[", "]", ";", "}", "const", "key", "=", "keys", "[", "0", "]", ";", "if", "(", "key", "===", "'Fn::GetAtt'", ")", "{", "// Logical name of resource is the first value in array", "return", "cloudFormationDependencies", "(", "value", "[", "key", "]", "[", "0", "]", ")", ";", "}", "if", "(", "key", "===", "'Ref'", ")", "{", "// Value should be the logical name (but may be a further function)", "return", "cloudFormationDependencies", "(", "value", "[", "key", "]", ")", ";", "}", "if", "(", "key", "===", "'Fn::Join'", ")", "{", "// Value is the combined string, meaning parts that are not", "// string can all include dependencies", "return", "_", ".", "flatten", "(", "value", "[", "key", "]", "[", "1", "]", ".", "filter", "(", "_", ".", "isObject", ")", ".", "map", "(", "cloudFormationDependencies", ")", ")", ";", "}", "if", "(", "key", "===", "'Fn::Select'", ")", "{", "// Value is picked from an array", "const", "index", "=", "value", "[", "key", "]", "[", "0", "]", ";", "const", "list", "=", "value", "[", "key", "]", "[", "1", "]", ";", "return", "cloudFormationDependencies", "(", "list", "[", "index", "]", ")", ";", "}", "// Unknown/Unhandled", "return", "[", "]", ";", "}" ]
Helper function for deriving the list of resources that are referenced by a CF function @param value, CF value, may be a string, or an object @returns {array} array of strings, containing all resource names that are used by the value (that the value depends on)
[ "Helper", "function", "for", "deriving", "the", "list", "of", "resources", "that", "are", "referenced", "by", "a", "CF", "function" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/helpers/cf-template-functions.js#L13-L55
28,142
dashersw/erste
src/lib/base/eventemitter3.js
EE
function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; }
javascript
function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; }
[ "function", "EE", "(", "fn", ",", "context", ",", "once", ")", "{", "this", ".", "fn", "=", "fn", ";", "this", ".", "context", "=", "context", ";", "this", ".", "once", "=", "once", "||", "false", ";", "}" ]
Representation of a single event listener. @param {Function} fn The listener function. @param {*} context The context to invoke the listener with. @param {boolean} [once=false] Specify if the listener is a one-time listener. @constructor @private
[ "Representation", "of", "a", "single", "event", "listener", "." ]
f916bfdf87bdf6f939184d205c049bbd54a6574f
https://github.com/dashersw/erste/blob/f916bfdf87bdf6f939184d205c049bbd54a6574f/src/lib/base/eventemitter3.js#L76-L80
28,143
dashersw/erste
src/lib/base/eventemitter3.js
addListener
function addListener(emitter, event, fn, context, once) { if (typeof fn !== 'function') { throw new TypeError('The listener must be a function'); } var listener = new EE(fn, context || emitter, once) , evt = prefix ? prefix + event : event; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter; }
javascript
function addListener(emitter, event, fn, context, once) { if (typeof fn !== 'function') { throw new TypeError('The listener must be a function'); } var listener = new EE(fn, context || emitter, once) , evt = prefix ? prefix + event : event; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter; }
[ "function", "addListener", "(", "emitter", ",", "event", ",", "fn", ",", "context", ",", "once", ")", "{", "if", "(", "typeof", "fn", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", "'The listener must be a function'", ")", ";", "}", "var", "listener", "=", "new", "EE", "(", "fn", ",", "context", "||", "emitter", ",", "once", ")", ",", "evt", "=", "prefix", "?", "prefix", "+", "event", ":", "event", ";", "if", "(", "!", "emitter", ".", "_events", "[", "evt", "]", ")", "emitter", ".", "_events", "[", "evt", "]", "=", "listener", ",", "emitter", ".", "_eventsCount", "++", ";", "else", "if", "(", "!", "emitter", ".", "_events", "[", "evt", "]", ".", "fn", ")", "emitter", ".", "_events", "[", "evt", "]", ".", "push", "(", "listener", ")", ";", "else", "emitter", ".", "_events", "[", "evt", "]", "=", "[", "emitter", ".", "_events", "[", "evt", "]", ",", "listener", "]", ";", "return", "emitter", ";", "}" ]
Add a listener for a given event. @param {EventEmitter} emitter Reference to the `EventEmitter` instance. @param {(string|Symbol)} event The event name. @param {Function} fn The listener function. @param {*} context The context to invoke the listener with. @param {boolean} once Specify if the listener is a one-time listener. @returns {EventEmitter} @private
[ "Add", "a", "listener", "for", "a", "given", "event", "." ]
f916bfdf87bdf6f939184d205c049bbd54a6574f
https://github.com/dashersw/erste/blob/f916bfdf87bdf6f939184d205c049bbd54a6574f/src/lib/base/eventemitter3.js#L93-L106
28,144
dashersw/erste
src/lib/base/eventemitter3.js
clearEvent
function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events(); else delete emitter._events[evt]; }
javascript
function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events(); else delete emitter._events[evt]; }
[ "function", "clearEvent", "(", "emitter", ",", "evt", ")", "{", "if", "(", "--", "emitter", ".", "_eventsCount", "===", "0", ")", "emitter", ".", "_events", "=", "new", "Events", "(", ")", ";", "else", "delete", "emitter", ".", "_events", "[", "evt", "]", ";", "}" ]
Clear event by name. @param {EventEmitter} emitter Reference to the `EventEmitter` instance. @param {(string|Symbol|number)} evt The Event name. @private
[ "Clear", "event", "by", "name", "." ]
f916bfdf87bdf6f939184d205c049bbd54a6574f
https://github.com/dashersw/erste/blob/f916bfdf87bdf6f939184d205c049bbd54a6574f/src/lib/base/eventemitter3.js#L115-L118
28,145
meeroslav/gulp-inject-partials
src/index.js
handleStream
function handleStream(target, encoding, cb) { if (target.isNull()) { return cb(null, target); } if (target.isStream()) { return cb(error(target.path + ': Streams not supported for target templates!')); } try { const tagsRegExp = getRegExpTags(opt, null); target.contents = processContent(target, opt, tagsRegExp, [target.path]); this.push(target); return cb(); } catch (err) { this.emit('error', err); return cb(); } }
javascript
function handleStream(target, encoding, cb) { if (target.isNull()) { return cb(null, target); } if (target.isStream()) { return cb(error(target.path + ': Streams not supported for target templates!')); } try { const tagsRegExp = getRegExpTags(opt, null); target.contents = processContent(target, opt, tagsRegExp, [target.path]); this.push(target); return cb(); } catch (err) { this.emit('error', err); return cb(); } }
[ "function", "handleStream", "(", "target", ",", "encoding", ",", "cb", ")", "{", "if", "(", "target", ".", "isNull", "(", ")", ")", "{", "return", "cb", "(", "null", ",", "target", ")", ";", "}", "if", "(", "target", ".", "isStream", "(", ")", ")", "{", "return", "cb", "(", "error", "(", "target", ".", "path", "+", "': Streams not supported for target templates!'", ")", ")", ";", "}", "try", "{", "const", "tagsRegExp", "=", "getRegExpTags", "(", "opt", ",", "null", ")", ";", "target", ".", "contents", "=", "processContent", "(", "target", ",", "opt", ",", "tagsRegExp", ",", "[", "target", ".", "path", "]", ")", ";", "this", ".", "push", "(", "target", ")", ";", "return", "cb", "(", ")", ";", "}", "catch", "(", "err", ")", "{", "this", ".", "emit", "(", "'error'", ",", "err", ")", ";", "return", "cb", "(", ")", ";", "}", "}" ]
Handle injection of files @param target @param encoding @param cb @returns {*}
[ "Handle", "injection", "of", "files" ]
6a7fee734decb03f2537ee54897162da7bc0a634
https://github.com/meeroslav/gulp-inject-partials/blob/6a7fee734decb03f2537ee54897162da7bc0a634/src/index.js#L40-L58
28,146
meeroslav/gulp-inject-partials
src/index.js
processContent
function processContent(target, opt, tagsRegExp, listOfFiles) { let targetContent = String(target.contents); const targetPath = target.path; const files = extractFilePaths(targetContent, targetPath, opt, tagsRegExp); // recursively process files files.forEach(function (fileData) { if (listOfFiles.indexOf(fileData.file.path) !== -1) { throw error("Circular definition found. File: " + fileData.file.path + " referenced in a child file."); } listOfFiles.push(fileData.file.path); const content = processContent(fileData.file, opt, tagsRegExp, listOfFiles); listOfFiles.pop(); targetContent = inject(targetContent, String(content), opt, fileData.tags); }); if (listOfFiles.length === 1 && !opt.quiet && files.length) { log( colors.cyan(files.length.toString()) + ' partials injected into ' + colors.magenta(targetPath) + '.'); } return new Buffer.from(targetContent); }
javascript
function processContent(target, opt, tagsRegExp, listOfFiles) { let targetContent = String(target.contents); const targetPath = target.path; const files = extractFilePaths(targetContent, targetPath, opt, tagsRegExp); // recursively process files files.forEach(function (fileData) { if (listOfFiles.indexOf(fileData.file.path) !== -1) { throw error("Circular definition found. File: " + fileData.file.path + " referenced in a child file."); } listOfFiles.push(fileData.file.path); const content = processContent(fileData.file, opt, tagsRegExp, listOfFiles); listOfFiles.pop(); targetContent = inject(targetContent, String(content), opt, fileData.tags); }); if (listOfFiles.length === 1 && !opt.quiet && files.length) { log( colors.cyan(files.length.toString()) + ' partials injected into ' + colors.magenta(targetPath) + '.'); } return new Buffer.from(targetContent); }
[ "function", "processContent", "(", "target", ",", "opt", ",", "tagsRegExp", ",", "listOfFiles", ")", "{", "let", "targetContent", "=", "String", "(", "target", ".", "contents", ")", ";", "const", "targetPath", "=", "target", ".", "path", ";", "const", "files", "=", "extractFilePaths", "(", "targetContent", ",", "targetPath", ",", "opt", ",", "tagsRegExp", ")", ";", "// recursively process files", "files", ".", "forEach", "(", "function", "(", "fileData", ")", "{", "if", "(", "listOfFiles", ".", "indexOf", "(", "fileData", ".", "file", ".", "path", ")", "!==", "-", "1", ")", "{", "throw", "error", "(", "\"Circular definition found. File: \"", "+", "fileData", ".", "file", ".", "path", "+", "\" referenced in a child file.\"", ")", ";", "}", "listOfFiles", ".", "push", "(", "fileData", ".", "file", ".", "path", ")", ";", "const", "content", "=", "processContent", "(", "fileData", ".", "file", ",", "opt", ",", "tagsRegExp", ",", "listOfFiles", ")", ";", "listOfFiles", ".", "pop", "(", ")", ";", "targetContent", "=", "inject", "(", "targetContent", ",", "String", "(", "content", ")", ",", "opt", ",", "fileData", ".", "tags", ")", ";", "}", ")", ";", "if", "(", "listOfFiles", ".", "length", "===", "1", "&&", "!", "opt", ".", "quiet", "&&", "files", ".", "length", ")", "{", "log", "(", "colors", ".", "cyan", "(", "files", ".", "length", ".", "toString", "(", ")", ")", "+", "' partials injected into '", "+", "colors", ".", "magenta", "(", "targetPath", ")", "+", "'.'", ")", ";", "}", "return", "new", "Buffer", ".", "from", "(", "targetContent", ")", ";", "}" ]
Parse content and create new template with all injections made @param {Object} target @param {Object} opt @param {Object} tagsRegExp @param {Array} listOfFiles @returns {Buffer}
[ "Parse", "content", "and", "create", "new", "template", "with", "all", "injections", "made" ]
6a7fee734decb03f2537ee54897162da7bc0a634
https://github.com/meeroslav/gulp-inject-partials/blob/6a7fee734decb03f2537ee54897162da7bc0a634/src/index.js#L73-L97
28,147
meeroslav/gulp-inject-partials
src/index.js
inject
function inject(targetContent, sourceContent, opt, tagsRegExp) { const startTag = tagsRegExp.start; const endTag = tagsRegExp.end; let startMatch; let endMatch; while ((startMatch = startTag.exec(targetContent)) !== null) { // Take care of content length change endTag.lastIndex = startTag.lastIndex; endMatch = endTag.exec(targetContent); if (!endMatch) { throw error('Missing end tag for start tag: ' + startMatch[0]); } const toInject = [sourceContent]; // content part before start tag let newContent = targetContent.slice(0, startMatch.index); if (opt.removeTags) { // Take care of content length change startTag.lastIndex -= startMatch[0].length; } else { // <startMatch> + partial body + <endMatch> toInject.unshift(startMatch[0]); toInject.push(endMatch[0]); } const previousInnerContent = targetContent.substring(startTag.lastIndex, endMatch.index); const indent = getLeadingWhitespace(previousInnerContent); // add new content newContent += toInject.join(indent); // append rest of target file newContent += targetContent.slice(endTag.lastIndex); // replace old content with new targetContent = newContent; } startTag.lastIndex = 0; endTag.lastIndex = 0; return targetContent; }
javascript
function inject(targetContent, sourceContent, opt, tagsRegExp) { const startTag = tagsRegExp.start; const endTag = tagsRegExp.end; let startMatch; let endMatch; while ((startMatch = startTag.exec(targetContent)) !== null) { // Take care of content length change endTag.lastIndex = startTag.lastIndex; endMatch = endTag.exec(targetContent); if (!endMatch) { throw error('Missing end tag for start tag: ' + startMatch[0]); } const toInject = [sourceContent]; // content part before start tag let newContent = targetContent.slice(0, startMatch.index); if (opt.removeTags) { // Take care of content length change startTag.lastIndex -= startMatch[0].length; } else { // <startMatch> + partial body + <endMatch> toInject.unshift(startMatch[0]); toInject.push(endMatch[0]); } const previousInnerContent = targetContent.substring(startTag.lastIndex, endMatch.index); const indent = getLeadingWhitespace(previousInnerContent); // add new content newContent += toInject.join(indent); // append rest of target file newContent += targetContent.slice(endTag.lastIndex); // replace old content with new targetContent = newContent; } startTag.lastIndex = 0; endTag.lastIndex = 0; return targetContent; }
[ "function", "inject", "(", "targetContent", ",", "sourceContent", ",", "opt", ",", "tagsRegExp", ")", "{", "const", "startTag", "=", "tagsRegExp", ".", "start", ";", "const", "endTag", "=", "tagsRegExp", ".", "end", ";", "let", "startMatch", ";", "let", "endMatch", ";", "while", "(", "(", "startMatch", "=", "startTag", ".", "exec", "(", "targetContent", ")", ")", "!==", "null", ")", "{", "// Take care of content length change", "endTag", ".", "lastIndex", "=", "startTag", ".", "lastIndex", ";", "endMatch", "=", "endTag", ".", "exec", "(", "targetContent", ")", ";", "if", "(", "!", "endMatch", ")", "{", "throw", "error", "(", "'Missing end tag for start tag: '", "+", "startMatch", "[", "0", "]", ")", ";", "}", "const", "toInject", "=", "[", "sourceContent", "]", ";", "// content part before start tag", "let", "newContent", "=", "targetContent", ".", "slice", "(", "0", ",", "startMatch", ".", "index", ")", ";", "if", "(", "opt", ".", "removeTags", ")", "{", "// Take care of content length change", "startTag", ".", "lastIndex", "-=", "startMatch", "[", "0", "]", ".", "length", ";", "}", "else", "{", "// <startMatch> + partial body + <endMatch>", "toInject", ".", "unshift", "(", "startMatch", "[", "0", "]", ")", ";", "toInject", ".", "push", "(", "endMatch", "[", "0", "]", ")", ";", "}", "const", "previousInnerContent", "=", "targetContent", ".", "substring", "(", "startTag", ".", "lastIndex", ",", "endMatch", ".", "index", ")", ";", "const", "indent", "=", "getLeadingWhitespace", "(", "previousInnerContent", ")", ";", "// add new content", "newContent", "+=", "toInject", ".", "join", "(", "indent", ")", ";", "// append rest of target file", "newContent", "+=", "targetContent", ".", "slice", "(", "endTag", ".", "lastIndex", ")", ";", "// replace old content with new", "targetContent", "=", "newContent", ";", "}", "startTag", ".", "lastIndex", "=", "0", ";", "endTag", ".", "lastIndex", "=", "0", ";", "return", "targetContent", ";", "}" ]
Inject tags into target content between given start and end tags @param {String} targetContent @param {String} sourceContent @param {Object} opt @param {Object} tagsRegExp @returns {String}
[ "Inject", "tags", "into", "target", "content", "between", "given", "start", "and", "end", "tags" ]
6a7fee734decb03f2537ee54897162da7bc0a634
https://github.com/meeroslav/gulp-inject-partials/blob/6a7fee734decb03f2537ee54897162da7bc0a634/src/index.js#L109-L146
28,148
meeroslav/gulp-inject-partials
src/index.js
extractFilePaths
function extractFilePaths(content, targetPath, opt, tagsRegExp) { const files = []; const tagMatches = content.match(tagsRegExp.start); if (tagMatches) { tagMatches.forEach(function (tagMatch) { const fileUrl = tagsRegExp.startex.exec(tagMatch)[1]; const filePath = setFullPath(targetPath, opt.prefix + fileUrl); try { const fileContent = stripBomBuf(fs.readFileSync(filePath)); files.push({ file: new File({ path: filePath, cwd: __dirname, base: path.resolve(__dirname, 'expected', path.dirname(filePath)), contents: fileContent }), tags: getRegExpTags(opt, fileUrl) }); } catch (e) { if (opt.ignoreError) { log(colors.red(filePath + ' not found.')); } else { throw error(filePath + ' not found.'); } } // reset the regex tagsRegExp.startex.lastIndex = 0; }); } return files; }
javascript
function extractFilePaths(content, targetPath, opt, tagsRegExp) { const files = []; const tagMatches = content.match(tagsRegExp.start); if (tagMatches) { tagMatches.forEach(function (tagMatch) { const fileUrl = tagsRegExp.startex.exec(tagMatch)[1]; const filePath = setFullPath(targetPath, opt.prefix + fileUrl); try { const fileContent = stripBomBuf(fs.readFileSync(filePath)); files.push({ file: new File({ path: filePath, cwd: __dirname, base: path.resolve(__dirname, 'expected', path.dirname(filePath)), contents: fileContent }), tags: getRegExpTags(opt, fileUrl) }); } catch (e) { if (opt.ignoreError) { log(colors.red(filePath + ' not found.')); } else { throw error(filePath + ' not found.'); } } // reset the regex tagsRegExp.startex.lastIndex = 0; }); } return files; }
[ "function", "extractFilePaths", "(", "content", ",", "targetPath", ",", "opt", ",", "tagsRegExp", ")", "{", "const", "files", "=", "[", "]", ";", "const", "tagMatches", "=", "content", ".", "match", "(", "tagsRegExp", ".", "start", ")", ";", "if", "(", "tagMatches", ")", "{", "tagMatches", ".", "forEach", "(", "function", "(", "tagMatch", ")", "{", "const", "fileUrl", "=", "tagsRegExp", ".", "startex", ".", "exec", "(", "tagMatch", ")", "[", "1", "]", ";", "const", "filePath", "=", "setFullPath", "(", "targetPath", ",", "opt", ".", "prefix", "+", "fileUrl", ")", ";", "try", "{", "const", "fileContent", "=", "stripBomBuf", "(", "fs", ".", "readFileSync", "(", "filePath", ")", ")", ";", "files", ".", "push", "(", "{", "file", ":", "new", "File", "(", "{", "path", ":", "filePath", ",", "cwd", ":", "__dirname", ",", "base", ":", "path", ".", "resolve", "(", "__dirname", ",", "'expected'", ",", "path", ".", "dirname", "(", "filePath", ")", ")", ",", "contents", ":", "fileContent", "}", ")", ",", "tags", ":", "getRegExpTags", "(", "opt", ",", "fileUrl", ")", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "opt", ".", "ignoreError", ")", "{", "log", "(", "colors", ".", "red", "(", "filePath", "+", "' not found.'", ")", ")", ";", "}", "else", "{", "throw", "error", "(", "filePath", "+", "' not found.'", ")", ";", "}", "}", "// reset the regex", "tagsRegExp", ".", "startex", ".", "lastIndex", "=", "0", ";", "}", ")", ";", "}", "return", "files", ";", "}" ]
Parse content and get all partials to be injected @param {String} content @param {String} targetPath @param {Object} opt @param {Object} tagsRegExp @returns {Array}
[ "Parse", "content", "and", "get", "all", "partials", "to", "be", "injected" ]
6a7fee734decb03f2537ee54897162da7bc0a634
https://github.com/meeroslav/gulp-inject-partials/blob/6a7fee734decb03f2537ee54897162da7bc0a634/src/index.js#L183-L214
28,149
weepy/kaffeine
lib/token.js
function(child, parent) { var ctor = function(){ }; ctor.prototype = parent.prototype; child.__super__ = parent.prototype; child.prototype = new ctor(); child.prototype.constructor = child; child.fn = child.prototype }
javascript
function(child, parent) { var ctor = function(){ }; ctor.prototype = parent.prototype; child.__super__ = parent.prototype; child.prototype = new ctor(); child.prototype.constructor = child; child.fn = child.prototype }
[ "function", "(", "child", ",", "parent", ")", "{", "var", "ctor", "=", "function", "(", ")", "{", "}", ";", "ctor", ".", "prototype", "=", "parent", ".", "prototype", ";", "child", ".", "__super__", "=", "parent", ".", "prototype", ";", "child", ".", "prototype", "=", "new", "ctor", "(", ")", ";", "child", ".", "prototype", ".", "constructor", "=", "child", ";", "child", ".", "fn", "=", "child", ".", "prototype", "}" ]
var log = console.log
[ "var", "log", "=", "console", ".", "log" ]
231333e6563501235bc10b24e7efcafd2e2d9b91
https://github.com/weepy/kaffeine/blob/231333e6563501235bc10b24e7efcafd2e2d9b91/lib/token.js#L3-L10
28,150
sparkartgroup/gulp-markdown-to-json
lib/plugin.js
consolidateFiles
function consolidateFiles (files, config) { return Promise.resolve(files) .then(files => { var data = {}; files.forEach(file => { var path = file.relative.split('.').shift().split(Path.sep); if (path.length >= 2 && config.flattenIndex) { var relPath = path.splice(-2, 2); path = (relPath[0] === relPath[1] || relPath[1] === 'index') ? path.concat(relPath[0]) : path.concat(relPath); } data[path.join('.')] = JSON.parse(file.contents.toString()); }); data = sort(data); const tree = expand(data); const json = JSON.stringify(tree); return Promise.resolve(new Vinyl({ base: '/', cwd: '/', path: '/' + (config.name || 'content.json'), contents: new Buffer(json) })); }); }
javascript
function consolidateFiles (files, config) { return Promise.resolve(files) .then(files => { var data = {}; files.forEach(file => { var path = file.relative.split('.').shift().split(Path.sep); if (path.length >= 2 && config.flattenIndex) { var relPath = path.splice(-2, 2); path = (relPath[0] === relPath[1] || relPath[1] === 'index') ? path.concat(relPath[0]) : path.concat(relPath); } data[path.join('.')] = JSON.parse(file.contents.toString()); }); data = sort(data); const tree = expand(data); const json = JSON.stringify(tree); return Promise.resolve(new Vinyl({ base: '/', cwd: '/', path: '/' + (config.name || 'content.json'), contents: new Buffer(json) })); }); }
[ "function", "consolidateFiles", "(", "files", ",", "config", ")", "{", "return", "Promise", ".", "resolve", "(", "files", ")", ".", "then", "(", "files", "=>", "{", "var", "data", "=", "{", "}", ";", "files", ".", "forEach", "(", "file", "=>", "{", "var", "path", "=", "file", ".", "relative", ".", "split", "(", "'.'", ")", ".", "shift", "(", ")", ".", "split", "(", "Path", ".", "sep", ")", ";", "if", "(", "path", ".", "length", ">=", "2", "&&", "config", ".", "flattenIndex", ")", "{", "var", "relPath", "=", "path", ".", "splice", "(", "-", "2", ",", "2", ")", ";", "path", "=", "(", "relPath", "[", "0", "]", "===", "relPath", "[", "1", "]", "||", "relPath", "[", "1", "]", "===", "'index'", ")", "?", "path", ".", "concat", "(", "relPath", "[", "0", "]", ")", ":", "path", ".", "concat", "(", "relPath", ")", ";", "}", "data", "[", "path", ".", "join", "(", "'.'", ")", "]", "=", "JSON", ".", "parse", "(", "file", ".", "contents", ".", "toString", "(", ")", ")", ";", "}", ")", ";", "data", "=", "sort", "(", "data", ")", ";", "const", "tree", "=", "expand", "(", "data", ")", ";", "const", "json", "=", "JSON", ".", "stringify", "(", "tree", ")", ";", "return", "Promise", ".", "resolve", "(", "new", "Vinyl", "(", "{", "base", ":", "'/'", ",", "cwd", ":", "'/'", ",", "path", ":", "'/'", "+", "(", "config", ".", "name", "||", "'content.json'", ")", ",", "contents", ":", "new", "Buffer", "(", "json", ")", "}", ")", ")", ";", "}", ")", ";", "}" ]
Consolidates JSON output into a nested and sorted object whose hierarchy matches the input directory structure @param {Array} files - JSON output as Vinyl file objects @returns {Promise.<Vinyl>}
[ "Consolidates", "JSON", "output", "into", "a", "nested", "and", "sorted", "object", "whose", "hierarchy", "matches", "the", "input", "directory", "structure" ]
ef32234bec31171bb11f16a38d985d88f78640bc
https://github.com/sparkartgroup/gulp-markdown-to-json/blob/ef32234bec31171bb11f16a38d985d88f78640bc/lib/plugin.js#L85-L115
28,151
sparkartgroup/gulp-markdown-to-json
lib/plugin.js
isBinary
function isBinary (file) { return new Promise((resolve, reject) => { isTextOrBinary.isText(Path.basename(file.path), file.contents, (err, isText) => { if (err) return reject(err); if (isText) file.isText = true; resolve(file); }); }); }
javascript
function isBinary (file) { return new Promise((resolve, reject) => { isTextOrBinary.isText(Path.basename(file.path), file.contents, (err, isText) => { if (err) return reject(err); if (isText) file.isText = true; resolve(file); }); }); }
[ "function", "isBinary", "(", "file", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "isTextOrBinary", ".", "isText", "(", "Path", ".", "basename", "(", "file", ".", "path", ")", ",", "file", ".", "contents", ",", "(", "err", ",", "isText", ")", "=>", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "if", "(", "isText", ")", "file", ".", "isText", "=", "true", ";", "resolve", "(", "file", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Tests if file content is ASCII @param {Vinyl} file - Vinyl file object @returns {Promise.<boolean>} @private
[ "Tests", "if", "file", "content", "is", "ASCII" ]
ef32234bec31171bb11f16a38d985d88f78640bc
https://github.com/sparkartgroup/gulp-markdown-to-json/blob/ef32234bec31171bb11f16a38d985d88f78640bc/lib/plugin.js#L146-L154
28,152
sparkartgroup/gulp-markdown-to-json
lib/plugin.js
isJSON
function isJSON (file) { try { JSON.parse(file.contents.toString()); return true; } catch (err) { return false; } }
javascript
function isJSON (file) { try { JSON.parse(file.contents.toString()); return true; } catch (err) { return false; } }
[ "function", "isJSON", "(", "file", ")", "{", "try", "{", "JSON", ".", "parse", "(", "file", ".", "contents", ".", "toString", "(", ")", ")", ";", "return", "true", ";", "}", "catch", "(", "err", ")", "{", "return", "false", ";", "}", "}" ]
Tests if file content is valid JSON @param {object} Vinyl file @returns {boolean} @private
[ "Tests", "if", "file", "content", "is", "valid", "JSON" ]
ef32234bec31171bb11f16a38d985d88f78640bc
https://github.com/sparkartgroup/gulp-markdown-to-json/blob/ef32234bec31171bb11f16a38d985d88f78640bc/lib/plugin.js#L163-L170
28,153
sparkartgroup/gulp-markdown-to-json
lib/plugin.js
toJSON
function toJSON (file, config) { if (Path.extname(file.path) === '.json') { if (!isJSON(file)) file.isInvalid = true; return Promise.resolve(file); } let jsonFile = file.clone(); return Promise.resolve(file) // parse YAML .then(file => { try { let parsed = frontmatter(file.contents.toString()); return Promise.resolve(parsed); } catch (err) { return Promise.reject(err); } // parse and render Markdown }).then(parsed => { try { let data = parsed.attributes; data.body = config.renderer.call(config.context, parsed.body); return Promise.resolve(data); } catch (err) { return Promise.reject(err); } // optional transforms and output }).then(data => { if (!data.title) { let extracted = extractTitle(data.body, config.stripTitle); if (typeof extracted === 'object') data = assign(data, extracted); } data.updatedAt = file.stat.mtime.toISOString(); if (config.transform) var transformedData = config.transform(data, file); jsonFile.extname = '.json'; jsonFile.contents = new Buffer(JSON.stringify(transformedData || data)); return Promise.resolve(jsonFile); }); }
javascript
function toJSON (file, config) { if (Path.extname(file.path) === '.json') { if (!isJSON(file)) file.isInvalid = true; return Promise.resolve(file); } let jsonFile = file.clone(); return Promise.resolve(file) // parse YAML .then(file => { try { let parsed = frontmatter(file.contents.toString()); return Promise.resolve(parsed); } catch (err) { return Promise.reject(err); } // parse and render Markdown }).then(parsed => { try { let data = parsed.attributes; data.body = config.renderer.call(config.context, parsed.body); return Promise.resolve(data); } catch (err) { return Promise.reject(err); } // optional transforms and output }).then(data => { if (!data.title) { let extracted = extractTitle(data.body, config.stripTitle); if (typeof extracted === 'object') data = assign(data, extracted); } data.updatedAt = file.stat.mtime.toISOString(); if (config.transform) var transformedData = config.transform(data, file); jsonFile.extname = '.json'; jsonFile.contents = new Buffer(JSON.stringify(transformedData || data)); return Promise.resolve(jsonFile); }); }
[ "function", "toJSON", "(", "file", ",", "config", ")", "{", "if", "(", "Path", ".", "extname", "(", "file", ".", "path", ")", "===", "'.json'", ")", "{", "if", "(", "!", "isJSON", "(", "file", ")", ")", "file", ".", "isInvalid", "=", "true", ";", "return", "Promise", ".", "resolve", "(", "file", ")", ";", "}", "let", "jsonFile", "=", "file", ".", "clone", "(", ")", ";", "return", "Promise", ".", "resolve", "(", "file", ")", "// parse YAML", ".", "then", "(", "file", "=>", "{", "try", "{", "let", "parsed", "=", "frontmatter", "(", "file", ".", "contents", ".", "toString", "(", ")", ")", ";", "return", "Promise", ".", "resolve", "(", "parsed", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "Promise", ".", "reject", "(", "err", ")", ";", "}", "// parse and render Markdown", "}", ")", ".", "then", "(", "parsed", "=>", "{", "try", "{", "let", "data", "=", "parsed", ".", "attributes", ";", "data", ".", "body", "=", "config", ".", "renderer", ".", "call", "(", "config", ".", "context", ",", "parsed", ".", "body", ")", ";", "return", "Promise", ".", "resolve", "(", "data", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "Promise", ".", "reject", "(", "err", ")", ";", "}", "// optional transforms and output", "}", ")", ".", "then", "(", "data", "=>", "{", "if", "(", "!", "data", ".", "title", ")", "{", "let", "extracted", "=", "extractTitle", "(", "data", ".", "body", ",", "config", ".", "stripTitle", ")", ";", "if", "(", "typeof", "extracted", "===", "'object'", ")", "data", "=", "assign", "(", "data", ",", "extracted", ")", ";", "}", "data", ".", "updatedAt", "=", "file", ".", "stat", ".", "mtime", ".", "toISOString", "(", ")", ";", "if", "(", "config", ".", "transform", ")", "var", "transformedData", "=", "config", ".", "transform", "(", "data", ",", "file", ")", ";", "jsonFile", ".", "extname", "=", "'.json'", ";", "jsonFile", ".", "contents", "=", "new", "Buffer", "(", "JSON", ".", "stringify", "(", "transformedData", "||", "data", ")", ")", ";", "return", "Promise", ".", "resolve", "(", "jsonFile", ")", ";", "}", ")", ";", "}" ]
Parse text files for YAML and Markdown, render to HTML and wrap in JSON @param {Vinyl} file - Vinyl file object @returns {Promise.<Vinyl>} @private
[ "Parse", "text", "files", "for", "YAML", "and", "Markdown", "render", "to", "HTML", "and", "wrap", "in", "JSON" ]
ef32234bec31171bb11f16a38d985d88f78640bc
https://github.com/sparkartgroup/gulp-markdown-to-json/blob/ef32234bec31171bb11f16a38d985d88f78640bc/lib/plugin.js#L179-L221
28,154
dashersw/erste
src/lib/base/component-manager.js
decorateEvents
function decorateEvents(comp) { const prototype = /** @type {!Function} */(comp.constructor).prototype; if (prototype.__events) return; let events = {}; if (prototype.events) { events = prototype.events; } Object.getOwnPropertyNames(prototype) .map(propertyName => handlerMethodPattern.exec(propertyName)) .filter(x => x) .forEach(([methodName, eventType, eventTarget]) => { events[eventType] = events[eventType] || {}; /** @suppress {checkTypes} */ events[eventType][eventTarget] = comp[methodName]; }) prototype.__events = events; }
javascript
function decorateEvents(comp) { const prototype = /** @type {!Function} */(comp.constructor).prototype; if (prototype.__events) return; let events = {}; if (prototype.events) { events = prototype.events; } Object.getOwnPropertyNames(prototype) .map(propertyName => handlerMethodPattern.exec(propertyName)) .filter(x => x) .forEach(([methodName, eventType, eventTarget]) => { events[eventType] = events[eventType] || {}; /** @suppress {checkTypes} */ events[eventType][eventTarget] = comp[methodName]; }) prototype.__events = events; }
[ "function", "decorateEvents", "(", "comp", ")", "{", "const", "prototype", "=", "/** @type {!Function} */", "(", "comp", ".", "constructor", ")", ".", "prototype", ";", "if", "(", "prototype", ".", "__events", ")", "return", ";", "let", "events", "=", "{", "}", ";", "if", "(", "prototype", ".", "events", ")", "{", "events", "=", "prototype", ".", "events", ";", "}", "Object", ".", "getOwnPropertyNames", "(", "prototype", ")", ".", "map", "(", "propertyName", "=>", "handlerMethodPattern", ".", "exec", "(", "propertyName", ")", ")", ".", "filter", "(", "x", "=>", "x", ")", ".", "forEach", "(", "(", "[", "methodName", ",", "eventType", ",", "eventTarget", "]", ")", "=>", "{", "events", "[", "eventType", "]", "=", "events", "[", "eventType", "]", "||", "{", "}", ";", "/** @suppress {checkTypes} */", "events", "[", "eventType", "]", "[", "eventTarget", "]", "=", "comp", "[", "methodName", "]", ";", "}", ")", "prototype", ".", "__events", "=", "events", ";", "}" ]
Fills events object of given component class from method names that match event handler pattern. @param {!Component} comp Component instance to decorate events for.
[ "Fills", "events", "object", "of", "given", "component", "class", "from", "method", "names", "that", "match", "event", "handler", "pattern", "." ]
f916bfdf87bdf6f939184d205c049bbd54a6574f
https://github.com/dashersw/erste/blob/f916bfdf87bdf6f939184d205c049bbd54a6574f/src/lib/base/component-manager.js#L191-L213
28,155
meeroslav/gulp-inject-partials
src/index.spec.js
expectedFile
function expectedFile(file) { const filePath = path.resolve(__dirname, 'expected', file); return new File({ path: filePath, cwd: __dirname, base: path.resolve(__dirname, 'expected', path.dirname(file)), contents: fs.readFileSync(filePath) }); }
javascript
function expectedFile(file) { const filePath = path.resolve(__dirname, 'expected', file); return new File({ path: filePath, cwd: __dirname, base: path.resolve(__dirname, 'expected', path.dirname(file)), contents: fs.readFileSync(filePath) }); }
[ "function", "expectedFile", "(", "file", ")", "{", "const", "filePath", "=", "path", ".", "resolve", "(", "__dirname", ",", "'expected'", ",", "file", ")", ";", "return", "new", "File", "(", "{", "path", ":", "filePath", ",", "cwd", ":", "__dirname", ",", "base", ":", "path", ".", "resolve", "(", "__dirname", ",", "'expected'", ",", "path", ".", "dirname", "(", "file", ")", ")", ",", "contents", ":", "fs", ".", "readFileSync", "(", "filePath", ")", "}", ")", ";", "}" ]
get expected file
[ "get", "expected", "file" ]
6a7fee734decb03f2537ee54897162da7bc0a634
https://github.com/meeroslav/gulp-inject-partials/blob/6a7fee734decb03f2537ee54897162da7bc0a634/src/index.spec.js#L131-L139
28,156
131/xterm2
lib/terminal.js
encode
function encode(data, ch) { if (!self.utfMouse) { if (ch === 255) return data.push(0); if (ch > 127) ch = 127; data.push(ch); } else { if (ch === 2047) return data.push(0); if (ch < 127) { data.push(ch); } else { if (ch > 2047) ch = 2047; data.push(0xC0 | (ch >> 6)); data.push(0x80 | (ch & 0x3F)); } } }
javascript
function encode(data, ch) { if (!self.utfMouse) { if (ch === 255) return data.push(0); if (ch > 127) ch = 127; data.push(ch); } else { if (ch === 2047) return data.push(0); if (ch < 127) { data.push(ch); } else { if (ch > 2047) ch = 2047; data.push(0xC0 | (ch >> 6)); data.push(0x80 | (ch & 0x3F)); } } }
[ "function", "encode", "(", "data", ",", "ch", ")", "{", "if", "(", "!", "self", ".", "utfMouse", ")", "{", "if", "(", "ch", "===", "255", ")", "return", "data", ".", "push", "(", "0", ")", ";", "if", "(", "ch", ">", "127", ")", "ch", "=", "127", ";", "data", ".", "push", "(", "ch", ")", ";", "}", "else", "{", "if", "(", "ch", "===", "2047", ")", "return", "data", ".", "push", "(", "0", ")", ";", "if", "(", "ch", "<", "127", ")", "{", "data", ".", "push", "(", "ch", ")", ";", "}", "else", "{", "if", "(", "ch", ">", "2047", ")", "ch", "=", "2047", ";", "data", ".", "push", "(", "0xC0", "|", "(", "ch", ">>", "6", ")", ")", ";", "data", ".", "push", "(", "0x80", "|", "(", "ch", "&", "0x3F", ")", ")", ";", "}", "}", "}" ]
encode button and position to characters
[ "encode", "button", "and", "position", "to", "characters" ]
d0724ac1e637241b37e7bdb6dc3ef64c22976343
https://github.com/131/xterm2/blob/d0724ac1e637241b37e7bdb6dc3ef64c22976343/lib/terminal.js#L643-L658
28,157
dhershman1/kyanite
src/_internals/_curry2.js
_curry2
function _curry2 (fn) { return function f2 (a, b) { if (!arguments.length) { return f2 } if (arguments.length === 1) { return function (_b) { return fn(a, _b) } } return fn(a, b) } }
javascript
function _curry2 (fn) { return function f2 (a, b) { if (!arguments.length) { return f2 } if (arguments.length === 1) { return function (_b) { return fn(a, _b) } } return fn(a, b) } }
[ "function", "_curry2", "(", "fn", ")", "{", "return", "function", "f2", "(", "a", ",", "b", ")", "{", "if", "(", "!", "arguments", ".", "length", ")", "{", "return", "f2", "}", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "return", "function", "(", "_b", ")", "{", "return", "fn", "(", "a", ",", "_b", ")", "}", "}", "return", "fn", "(", "a", ",", "b", ")", "}", "}" ]
This is an optimized internal curry function for 2 param functions @private @category Function @param {Function} fn The function to curry @return {Function} The curried function
[ "This", "is", "an", "optimized", "internal", "curry", "function", "for", "2", "param", "functions" ]
92524aaea522c3094ea339603125b149272926da
https://github.com/dhershman1/kyanite/blob/92524aaea522c3094ea339603125b149272926da/src/_internals/_curry2.js#L8-L22
28,158
dignifiedquire/pull-length-prefixed
src/decode.js
next
function next () { let doNext = true let decoded = false const decodeCb = (err, msg) => { decoded = true if (err) { p.end(err) doNext = false } else { p.push(msg) if (!doNext) { next() } } } while (doNext) { decoded = false _decodeFromReader(reader, opts, decodeCb) if (!decoded) { doNext = false } } }
javascript
function next () { let doNext = true let decoded = false const decodeCb = (err, msg) => { decoded = true if (err) { p.end(err) doNext = false } else { p.push(msg) if (!doNext) { next() } } } while (doNext) { decoded = false _decodeFromReader(reader, opts, decodeCb) if (!decoded) { doNext = false } } }
[ "function", "next", "(", ")", "{", "let", "doNext", "=", "true", "let", "decoded", "=", "false", "const", "decodeCb", "=", "(", "err", ",", "msg", ")", "=>", "{", "decoded", "=", "true", "if", "(", "err", ")", "{", "p", ".", "end", "(", "err", ")", "doNext", "=", "false", "}", "else", "{", "p", ".", "push", "(", "msg", ")", "if", "(", "!", "doNext", ")", "{", "next", "(", ")", "}", "}", "}", "while", "(", "doNext", ")", "{", "decoded", "=", "false", "_decodeFromReader", "(", "reader", ",", "opts", ",", "decodeCb", ")", "if", "(", "!", "decoded", ")", "{", "doNext", "=", "false", "}", "}", "}" ]
this function has to be written without recursion or it blows the stack in case of sync stream
[ "this", "function", "has", "to", "be", "written", "without", "recursion", "or", "it", "blows", "the", "stack", "in", "case", "of", "sync", "stream" ]
b22fbe1408447a0efbd6aff8d9bd4c42c9ea0366
https://github.com/dignifiedquire/pull-length-prefixed/blob/b22fbe1408447a0efbd6aff8d9bd4c42c9ea0366/src/decode.js#L26-L50
28,159
dignifiedquire/pull-length-prefixed
src/decode.js
decodeFromReader
function decodeFromReader (reader, opts, cb) { if (typeof opts === 'function') { cb = opts opts = {} } _decodeFromReader(reader, opts, function onComplete (err, msg) { if (err) { if (err === true) return cb(new Error('Unexpected end of input from reader.')) return cb(err) } cb(null, msg) }) }
javascript
function decodeFromReader (reader, opts, cb) { if (typeof opts === 'function') { cb = opts opts = {} } _decodeFromReader(reader, opts, function onComplete (err, msg) { if (err) { if (err === true) return cb(new Error('Unexpected end of input from reader.')) return cb(err) } cb(null, msg) }) }
[ "function", "decodeFromReader", "(", "reader", ",", "opts", ",", "cb", ")", "{", "if", "(", "typeof", "opts", "===", "'function'", ")", "{", "cb", "=", "opts", "opts", "=", "{", "}", "}", "_decodeFromReader", "(", "reader", ",", "opts", ",", "function", "onComplete", "(", "err", ",", "msg", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", "===", "true", ")", "return", "cb", "(", "new", "Error", "(", "'Unexpected end of input from reader.'", ")", ")", "return", "cb", "(", "err", ")", "}", "cb", "(", "null", ",", "msg", ")", "}", ")", "}" ]
wrapper to detect sudden pull-stream disconnects
[ "wrapper", "to", "detect", "sudden", "pull", "-", "stream", "disconnects" ]
b22fbe1408447a0efbd6aff8d9bd4c42c9ea0366
https://github.com/dignifiedquire/pull-length-prefixed/blob/b22fbe1408447a0efbd6aff8d9bd4c42c9ea0366/src/decode.js#L59-L72
28,160
131/xterm2
demo/main.js
function(str){ var ret = new Array(str.length), len = str.length; while(len--) ret[len] = str.charCodeAt(len); return Uint8Array.from(ret); }
javascript
function(str){ var ret = new Array(str.length), len = str.length; while(len--) ret[len] = str.charCodeAt(len); return Uint8Array.from(ret); }
[ "function", "(", "str", ")", "{", "var", "ret", "=", "new", "Array", "(", "str", ".", "length", ")", ",", "len", "=", "str", ".", "length", ";", "while", "(", "len", "--", ")", "ret", "[", "len", "]", "=", "str", ".", "charCodeAt", "(", "len", ")", ";", "return", "Uint8Array", ".", "from", "(", "ret", ")", ";", "}" ]
we do not need Buffer pollyfill for now
[ "we", "do", "not", "need", "Buffer", "pollyfill", "for", "now" ]
d0724ac1e637241b37e7bdb6dc3ef64c22976343
https://github.com/131/xterm2/blob/d0724ac1e637241b37e7bdb6dc3ef64c22976343/demo/main.js#L85-L89
28,161
gl-vis/gl-axes3d
axes.js
parseOption
function parseOption(nest, cons, name) { if(name in options) { var opt = options[name] var prev = this[name] var next if(nest ? (Array.isArray(opt) && Array.isArray(opt[0])) : Array.isArray(opt) ) { this[name] = next = [ cons(opt[0]), cons(opt[1]), cons(opt[2]) ] } else { this[name] = next = [ cons(opt), cons(opt), cons(opt) ] } for(var i=0; i<3; ++i) { if(next[i] !== prev[i]) { return true } } } return false }
javascript
function parseOption(nest, cons, name) { if(name in options) { var opt = options[name] var prev = this[name] var next if(nest ? (Array.isArray(opt) && Array.isArray(opt[0])) : Array.isArray(opt) ) { this[name] = next = [ cons(opt[0]), cons(opt[1]), cons(opt[2]) ] } else { this[name] = next = [ cons(opt), cons(opt), cons(opt) ] } for(var i=0; i<3; ++i) { if(next[i] !== prev[i]) { return true } } } return false }
[ "function", "parseOption", "(", "nest", ",", "cons", ",", "name", ")", "{", "if", "(", "name", "in", "options", ")", "{", "var", "opt", "=", "options", "[", "name", "]", "var", "prev", "=", "this", "[", "name", "]", "var", "next", "if", "(", "nest", "?", "(", "Array", ".", "isArray", "(", "opt", ")", "&&", "Array", ".", "isArray", "(", "opt", "[", "0", "]", ")", ")", ":", "Array", ".", "isArray", "(", "opt", ")", ")", "{", "this", "[", "name", "]", "=", "next", "=", "[", "cons", "(", "opt", "[", "0", "]", ")", ",", "cons", "(", "opt", "[", "1", "]", ")", ",", "cons", "(", "opt", "[", "2", "]", ")", "]", "}", "else", "{", "this", "[", "name", "]", "=", "next", "=", "[", "cons", "(", "opt", ")", ",", "cons", "(", "opt", ")", ",", "cons", "(", "opt", ")", "]", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "3", ";", "++", "i", ")", "{", "if", "(", "next", "[", "i", "]", "!==", "prev", "[", "i", "]", ")", "{", "return", "true", "}", "}", "}", "return", "false", "}" ]
Option parsing helper functions
[ "Option", "parsing", "helper", "functions" ]
a7a99d8047183657a4a288dc1c9e7341103b81d9
https://github.com/gl-vis/gl-axes3d/blob/a7a99d8047183657a4a288dc1c9e7341103b81d9/axes.js#L93-L111
28,162
Pier1/rocketbelt
templates/js/site.js
launchPlayground
function launchPlayground(){ $('.playground-item').playground(); // Eyedropper Helper Functions $('.cp_eyedropper').on('click', function() { if ($(this).next('.cp_grid').hasClass('visuallyhidden')) { $(".cp_grid").addClass('visuallyhidden'); $(this).next(".cp_grid").removeClass('visuallyhidden'); } else { $(this).next(".cp_grid").addClass('visuallyhidden'); } }) // Hides eyedropper if you click outside eyedropper $(document).on('click', function(event) { if (!$(event.target).closest('.cp_eyedropper').length && !$(event.target).hasClass('playground-list_item')) { $(".cp_grid").addClass('visuallyhidden'); } }); // Playground Event Handler $('body').on('playgroundUpdated', '.playground-item', function(){ var $input = $(this), base = $input.data('playground'), $playground = $input.closest('.playground'), $codeEl, targetHtmlStr; if ( !$playground.length ) $playground = $input.closest('article'); $codeEl = $playground.find('.exampleWithCode code'); if ( $playground.find('.copyable').length ) { targetHtmlStr = $playground.find('.copyable')[0].outerHTML; } else if ( $playground.find('.copyable-inner').length ) { targetHtmlStr = $playground.find('.copyable-inner').html(); } else { targetHtmlStr = base.$targetEl[0].outerHTML; } $codeEl.html(escapeHtml(targetHtmlStr)); Prism.highlightElement($codeEl[0]); }); // Sets the code section on page load. $('.playground-item').trigger('input'); }
javascript
function launchPlayground(){ $('.playground-item').playground(); // Eyedropper Helper Functions $('.cp_eyedropper').on('click', function() { if ($(this).next('.cp_grid').hasClass('visuallyhidden')) { $(".cp_grid").addClass('visuallyhidden'); $(this).next(".cp_grid").removeClass('visuallyhidden'); } else { $(this).next(".cp_grid").addClass('visuallyhidden'); } }) // Hides eyedropper if you click outside eyedropper $(document).on('click', function(event) { if (!$(event.target).closest('.cp_eyedropper').length && !$(event.target).hasClass('playground-list_item')) { $(".cp_grid").addClass('visuallyhidden'); } }); // Playground Event Handler $('body').on('playgroundUpdated', '.playground-item', function(){ var $input = $(this), base = $input.data('playground'), $playground = $input.closest('.playground'), $codeEl, targetHtmlStr; if ( !$playground.length ) $playground = $input.closest('article'); $codeEl = $playground.find('.exampleWithCode code'); if ( $playground.find('.copyable').length ) { targetHtmlStr = $playground.find('.copyable')[0].outerHTML; } else if ( $playground.find('.copyable-inner').length ) { targetHtmlStr = $playground.find('.copyable-inner').html(); } else { targetHtmlStr = base.$targetEl[0].outerHTML; } $codeEl.html(escapeHtml(targetHtmlStr)); Prism.highlightElement($codeEl[0]); }); // Sets the code section on page load. $('.playground-item').trigger('input'); }
[ "function", "launchPlayground", "(", ")", "{", "$", "(", "'.playground-item'", ")", ".", "playground", "(", ")", ";", "// Eyedropper Helper Functions", "$", "(", "'.cp_eyedropper'", ")", ".", "on", "(", "'click'", ",", "function", "(", ")", "{", "if", "(", "$", "(", "this", ")", ".", "next", "(", "'.cp_grid'", ")", ".", "hasClass", "(", "'visuallyhidden'", ")", ")", "{", "$", "(", "\".cp_grid\"", ")", ".", "addClass", "(", "'visuallyhidden'", ")", ";", "$", "(", "this", ")", ".", "next", "(", "\".cp_grid\"", ")", ".", "removeClass", "(", "'visuallyhidden'", ")", ";", "}", "else", "{", "$", "(", "this", ")", ".", "next", "(", "\".cp_grid\"", ")", ".", "addClass", "(", "'visuallyhidden'", ")", ";", "}", "}", ")", "// Hides eyedropper if you click outside eyedropper", "$", "(", "document", ")", ".", "on", "(", "'click'", ",", "function", "(", "event", ")", "{", "if", "(", "!", "$", "(", "event", ".", "target", ")", ".", "closest", "(", "'.cp_eyedropper'", ")", ".", "length", "&&", "!", "$", "(", "event", ".", "target", ")", ".", "hasClass", "(", "'playground-list_item'", ")", ")", "{", "$", "(", "\".cp_grid\"", ")", ".", "addClass", "(", "'visuallyhidden'", ")", ";", "}", "}", ")", ";", "// Playground Event Handler", "$", "(", "'body'", ")", ".", "on", "(", "'playgroundUpdated'", ",", "'.playground-item'", ",", "function", "(", ")", "{", "var", "$input", "=", "$", "(", "this", ")", ",", "base", "=", "$input", ".", "data", "(", "'playground'", ")", ",", "$playground", "=", "$input", ".", "closest", "(", "'.playground'", ")", ",", "$codeEl", ",", "targetHtmlStr", ";", "if", "(", "!", "$playground", ".", "length", ")", "$playground", "=", "$input", ".", "closest", "(", "'article'", ")", ";", "$codeEl", "=", "$playground", ".", "find", "(", "'.exampleWithCode code'", ")", ";", "if", "(", "$playground", ".", "find", "(", "'.copyable'", ")", ".", "length", ")", "{", "targetHtmlStr", "=", "$playground", ".", "find", "(", "'.copyable'", ")", "[", "0", "]", ".", "outerHTML", ";", "}", "else", "if", "(", "$playground", ".", "find", "(", "'.copyable-inner'", ")", ".", "length", ")", "{", "targetHtmlStr", "=", "$playground", ".", "find", "(", "'.copyable-inner'", ")", ".", "html", "(", ")", ";", "}", "else", "{", "targetHtmlStr", "=", "base", ".", "$targetEl", "[", "0", "]", ".", "outerHTML", ";", "}", "$codeEl", ".", "html", "(", "escapeHtml", "(", "targetHtmlStr", ")", ")", ";", "Prism", ".", "highlightElement", "(", "$codeEl", "[", "0", "]", ")", ";", "}", ")", ";", "// Sets the code section on page load.", "$", "(", "'.playground-item'", ")", ".", "trigger", "(", "'input'", ")", ";", "}" ]
Sets up all playground elements and makes the code copy function for dynamic elements
[ "Sets", "up", "all", "playground", "elements", "and", "makes", "the", "code", "copy", "function", "for", "dynamic", "elements" ]
73e1243e7fcedb731591dbafcc8ecf480ec4700f
https://github.com/Pier1/rocketbelt/blob/73e1243e7fcedb731591dbafcc8ecf480ec4700f/templates/js/site.js#L86-L129
28,163
gl-vis/gl-axes3d
example/example.js
f
function f(x,y,z) { return x*x + y*y + z*z - 2.0 }
javascript
function f(x,y,z) { return x*x + y*y + z*z - 2.0 }
[ "function", "f", "(", "x", ",", "y", ",", "z", ")", "{", "return", "x", "*", "x", "+", "y", "*", "y", "+", "z", "*", "z", "-", "2.0", "}" ]
Plot level set of f = 0
[ "Plot", "level", "set", "of", "f", "=", "0" ]
a7a99d8047183657a4a288dc1c9e7341103b81d9
https://github.com/gl-vis/gl-axes3d/blob/a7a99d8047183657a4a288dc1c9e7341103b81d9/example/example.js#L17-L19
28,164
Pier1/rocketbelt
rocketbelt/base/animation/rocketbelt.animate.js
animate
function animate(animationName, configOrCallback) { return this.each(function eachAnimate() { return window.rb.animate.animate(this, animationName, configOrCallback); }); }
javascript
function animate(animationName, configOrCallback) { return this.each(function eachAnimate() { return window.rb.animate.animate(this, animationName, configOrCallback); }); }
[ "function", "animate", "(", "animationName", ",", "configOrCallback", ")", "{", "return", "this", ".", "each", "(", "function", "eachAnimate", "(", ")", "{", "return", "window", ".", "rb", ".", "animate", ".", "animate", "(", "this", ",", "animationName", ",", "configOrCallback", ")", ";", "}", ")", ";", "}" ]
Add a Rocketbelt animation to a jQuery object. @param {string} animationName The Rocketbelt animation name. @param {(object|function)} configOrCallback A configuration object or a callback to run after the animation finishes. @returns {object} A chainable jQuery object.
[ "Add", "a", "Rocketbelt", "animation", "to", "a", "jQuery", "object", "." ]
73e1243e7fcedb731591dbafcc8ecf480ec4700f
https://github.com/Pier1/rocketbelt/blob/73e1243e7fcedb731591dbafcc8ecf480ec4700f/rocketbelt/base/animation/rocketbelt.animate.js#L145-L149
28,165
saneef/qgen
dist/lib/file-helpers.js
isFileOrDir
function isFileOrDir(filePath) { let fsStat; try { fsStat = fs.statSync(filePath); } catch (error) { return error; } let r = 'file'; if (fsStat.isDirectory()) { r = 'directory'; } return r; }
javascript
function isFileOrDir(filePath) { let fsStat; try { fsStat = fs.statSync(filePath); } catch (error) { return error; } let r = 'file'; if (fsStat.isDirectory()) { r = 'directory'; } return r; }
[ "function", "isFileOrDir", "(", "filePath", ")", "{", "let", "fsStat", ";", "try", "{", "fsStat", "=", "fs", ".", "statSync", "(", "filePath", ")", ";", "}", "catch", "(", "error", ")", "{", "return", "error", ";", "}", "let", "r", "=", "'file'", ";", "if", "(", "fsStat", ".", "isDirectory", "(", ")", ")", "{", "r", "=", "'directory'", ";", "}", "return", "r", ";", "}" ]
Check if a path points to a file or a directory @param {String} filePath - Path to a file or directory @return {String} 'directory' if paths points a directory, 'file' if path points to a file
[ "Check", "if", "a", "path", "points", "to", "a", "file", "or", "a", "directory" ]
c413d902f4ea79b628b0006fa08e9ae727738831
https://github.com/saneef/qgen/blob/c413d902f4ea79b628b0006fa08e9ae727738831/dist/lib/file-helpers.js#L12-L26
28,166
dhershman1/kyanite
src/_internals/_curry3.js
_curry3
function _curry3 (fn) { return function f3 (a, b, c) { switch (arguments.length) { case 0: return f3 case 1: return _curry2(function (_b, _c) { return fn(a, _b, _c) }) case 2: return function (_c) { return fn(a, b, _c) } default: return fn(a, b, c) } } }
javascript
function _curry3 (fn) { return function f3 (a, b, c) { switch (arguments.length) { case 0: return f3 case 1: return _curry2(function (_b, _c) { return fn(a, _b, _c) }) case 2: return function (_c) { return fn(a, b, _c) } default: return fn(a, b, c) } } }
[ "function", "_curry3", "(", "fn", ")", "{", "return", "function", "f3", "(", "a", ",", "b", ",", "c", ")", "{", "switch", "(", "arguments", ".", "length", ")", "{", "case", "0", ":", "return", "f3", "case", "1", ":", "return", "_curry2", "(", "function", "(", "_b", ",", "_c", ")", "{", "return", "fn", "(", "a", ",", "_b", ",", "_c", ")", "}", ")", "case", "2", ":", "return", "function", "(", "_c", ")", "{", "return", "fn", "(", "a", ",", "b", ",", "_c", ")", "}", "default", ":", "return", "fn", "(", "a", ",", "b", ",", "c", ")", "}", "}", "}" ]
This is an optimized internal curry function for 3 param functions @private @category Function @param {Function} fn The function to curry @return {Function} The curried function
[ "This", "is", "an", "optimized", "internal", "curry", "function", "for", "3", "param", "functions" ]
92524aaea522c3094ea339603125b149272926da
https://github.com/dhershman1/kyanite/blob/92524aaea522c3094ea339603125b149272926da/src/_internals/_curry3.js#L10-L27
28,167
saneef/qgen
src/qgen.js
qgen
function qgen(options) { const defaultOptions = { dest: DEFAULT_DESTINATION, cwd: process.cwd(), directory: 'qgen-templates', config: './qgen.json', helpers: undefined, force: false, preview: false }; const configfilePath = createConfigFilePath(defaultOptions, options); const configfileOptions = loadConfig(configfilePath); const config = Object.assign(defaultOptions, configfileOptions, options); /** Throw error if qgen template directory is missing */ if (isFileOrDir(config.directory) !== 'directory') { throw new QGenError(`qgen templates directory '${config.directory}' not found.`); } /** * Lists the available template names * * @return {Array} available template names */ const templates = () => { return globby.sync(['*'], { cwd: path.join(config.cwd, config.directory), expandDirectories: false, onlyFiles: false }); }; /** * Render the template file and save to the destination path * @param {String} template The name of the template * @param {String} destination Destination path */ const render = async (template, destination) => { const templatePath = path.join(config.directory, template); const templateType = isFileOrDir(path.join(config.cwd, templatePath)); const templateConfig = createTemplateConfig(config, template, DEFAULT_DESTINATION); const filepathRenderer = templateRenderer({ helpers: config.helpers, cwd: config.cwd }); // Override config dest with passed destination if (destination) { templateConfig.dest = destination; } let fileObjects; if (templateType === 'directory') { const files = globby.sync(['**/*'], { cwd: path.join(config.cwd, templatePath), nodir: true }); fileObjects = files.map(filePath => { return { src: path.join(templatePath, filePath), dest: path.join(templateConfig.cwd, templateConfig.dest, filepathRenderer.render(filePath, config)) }; }); } else if (templateType === 'file') { fileObjects = [{ src: templatePath, dest: path.join(templateConfig.cwd, templateConfig.dest, template) }]; } else { throw new QGenError(`Template '${templatePath}' not found.`); } const filesForRender = config.preview ? fileObjects : await enquireToOverwrite(fileObjects, config.force); if (!filesForRender.some(f => f.abort)) { renderFiles(filesForRender, templateConfig, config.preview); } }; return Object.freeze({ templates, render }); }
javascript
function qgen(options) { const defaultOptions = { dest: DEFAULT_DESTINATION, cwd: process.cwd(), directory: 'qgen-templates', config: './qgen.json', helpers: undefined, force: false, preview: false }; const configfilePath = createConfigFilePath(defaultOptions, options); const configfileOptions = loadConfig(configfilePath); const config = Object.assign(defaultOptions, configfileOptions, options); /** Throw error if qgen template directory is missing */ if (isFileOrDir(config.directory) !== 'directory') { throw new QGenError(`qgen templates directory '${config.directory}' not found.`); } /** * Lists the available template names * * @return {Array} available template names */ const templates = () => { return globby.sync(['*'], { cwd: path.join(config.cwd, config.directory), expandDirectories: false, onlyFiles: false }); }; /** * Render the template file and save to the destination path * @param {String} template The name of the template * @param {String} destination Destination path */ const render = async (template, destination) => { const templatePath = path.join(config.directory, template); const templateType = isFileOrDir(path.join(config.cwd, templatePath)); const templateConfig = createTemplateConfig(config, template, DEFAULT_DESTINATION); const filepathRenderer = templateRenderer({ helpers: config.helpers, cwd: config.cwd }); // Override config dest with passed destination if (destination) { templateConfig.dest = destination; } let fileObjects; if (templateType === 'directory') { const files = globby.sync(['**/*'], { cwd: path.join(config.cwd, templatePath), nodir: true }); fileObjects = files.map(filePath => { return { src: path.join(templatePath, filePath), dest: path.join(templateConfig.cwd, templateConfig.dest, filepathRenderer.render(filePath, config)) }; }); } else if (templateType === 'file') { fileObjects = [{ src: templatePath, dest: path.join(templateConfig.cwd, templateConfig.dest, template) }]; } else { throw new QGenError(`Template '${templatePath}' not found.`); } const filesForRender = config.preview ? fileObjects : await enquireToOverwrite(fileObjects, config.force); if (!filesForRender.some(f => f.abort)) { renderFiles(filesForRender, templateConfig, config.preview); } }; return Object.freeze({ templates, render }); }
[ "function", "qgen", "(", "options", ")", "{", "const", "defaultOptions", "=", "{", "dest", ":", "DEFAULT_DESTINATION", ",", "cwd", ":", "process", ".", "cwd", "(", ")", ",", "directory", ":", "'qgen-templates'", ",", "config", ":", "'./qgen.json'", ",", "helpers", ":", "undefined", ",", "force", ":", "false", ",", "preview", ":", "false", "}", ";", "const", "configfilePath", "=", "createConfigFilePath", "(", "defaultOptions", ",", "options", ")", ";", "const", "configfileOptions", "=", "loadConfig", "(", "configfilePath", ")", ";", "const", "config", "=", "Object", ".", "assign", "(", "defaultOptions", ",", "configfileOptions", ",", "options", ")", ";", "/** Throw error if qgen template directory is missing */", "if", "(", "isFileOrDir", "(", "config", ".", "directory", ")", "!==", "'directory'", ")", "{", "throw", "new", "QGenError", "(", "`", "${", "config", ".", "directory", "}", "`", ")", ";", "}", "/**\n\t * Lists the available template names\n\t *\n\t * @return {Array} available template names\n\t */", "const", "templates", "=", "(", ")", "=>", "{", "return", "globby", ".", "sync", "(", "[", "'*'", "]", ",", "{", "cwd", ":", "path", ".", "join", "(", "config", ".", "cwd", ",", "config", ".", "directory", ")", ",", "expandDirectories", ":", "false", ",", "onlyFiles", ":", "false", "}", ")", ";", "}", ";", "/**\n\t * Render the template file and save to the destination path\n\t * @param {String} template The name of the template\n\t * @param {String} destination Destination path\n\t */", "const", "render", "=", "async", "(", "template", ",", "destination", ")", "=>", "{", "const", "templatePath", "=", "path", ".", "join", "(", "config", ".", "directory", ",", "template", ")", ";", "const", "templateType", "=", "isFileOrDir", "(", "path", ".", "join", "(", "config", ".", "cwd", ",", "templatePath", ")", ")", ";", "const", "templateConfig", "=", "createTemplateConfig", "(", "config", ",", "template", ",", "DEFAULT_DESTINATION", ")", ";", "const", "filepathRenderer", "=", "templateRenderer", "(", "{", "helpers", ":", "config", ".", "helpers", ",", "cwd", ":", "config", ".", "cwd", "}", ")", ";", "// Override config dest with passed destination", "if", "(", "destination", ")", "{", "templateConfig", ".", "dest", "=", "destination", ";", "}", "let", "fileObjects", ";", "if", "(", "templateType", "===", "'directory'", ")", "{", "const", "files", "=", "globby", ".", "sync", "(", "[", "'**/*'", "]", ",", "{", "cwd", ":", "path", ".", "join", "(", "config", ".", "cwd", ",", "templatePath", ")", ",", "nodir", ":", "true", "}", ")", ";", "fileObjects", "=", "files", ".", "map", "(", "filePath", "=>", "{", "return", "{", "src", ":", "path", ".", "join", "(", "templatePath", ",", "filePath", ")", ",", "dest", ":", "path", ".", "join", "(", "templateConfig", ".", "cwd", ",", "templateConfig", ".", "dest", ",", "filepathRenderer", ".", "render", "(", "filePath", ",", "config", ")", ")", "}", ";", "}", ")", ";", "}", "else", "if", "(", "templateType", "===", "'file'", ")", "{", "fileObjects", "=", "[", "{", "src", ":", "templatePath", ",", "dest", ":", "path", ".", "join", "(", "templateConfig", ".", "cwd", ",", "templateConfig", ".", "dest", ",", "template", ")", "}", "]", ";", "}", "else", "{", "throw", "new", "QGenError", "(", "`", "${", "templatePath", "}", "`", ")", ";", "}", "const", "filesForRender", "=", "config", ".", "preview", "?", "fileObjects", ":", "await", "enquireToOverwrite", "(", "fileObjects", ",", "config", ".", "force", ")", ";", "if", "(", "!", "filesForRender", ".", "some", "(", "f", "=>", "f", ".", "abort", ")", ")", "{", "renderFiles", "(", "filesForRender", ",", "templateConfig", ",", "config", ".", "preview", ")", ";", "}", "}", ";", "return", "Object", ".", "freeze", "(", "{", "templates", ",", "render", "}", ")", ";", "}" ]
Creates new qgen object @param {Object} options - Options such as dest, config file path etc. @returns {qgen} qgen object
[ "Creates", "new", "qgen", "object" ]
c413d902f4ea79b628b0006fa08e9ae727738831
https://github.com/saneef/qgen/blob/c413d902f4ea79b628b0006fa08e9ae727738831/src/qgen.js#L71-L157
28,168
Pier1/rocketbelt
rocketbelt/components/dialogs/rocketbelt.dialogs.js
trapTabKey
function trapTabKey(node, event) { var focusableChildren = getFocusableChildren(node); var focusedItemIndex = focusableChildren.index($(document.activeElement)); if (event.shiftKey && focusedItemIndex === 0) { focusableChildren[focusableChildren.length - 1].focus(); event.preventDefault(); } else if (!event.shiftKey && focusedItemIndex === focusableChildren.length - 1) { focusableChildren[0].focus(); event.preventDefault(); } }
javascript
function trapTabKey(node, event) { var focusableChildren = getFocusableChildren(node); var focusedItemIndex = focusableChildren.index($(document.activeElement)); if (event.shiftKey && focusedItemIndex === 0) { focusableChildren[focusableChildren.length - 1].focus(); event.preventDefault(); } else if (!event.shiftKey && focusedItemIndex === focusableChildren.length - 1) { focusableChildren[0].focus(); event.preventDefault(); } }
[ "function", "trapTabKey", "(", "node", ",", "event", ")", "{", "var", "focusableChildren", "=", "getFocusableChildren", "(", "node", ")", ";", "var", "focusedItemIndex", "=", "focusableChildren", ".", "index", "(", "$", "(", "document", ".", "activeElement", ")", ")", ";", "if", "(", "event", ".", "shiftKey", "&&", "focusedItemIndex", "===", "0", ")", "{", "focusableChildren", "[", "focusableChildren", ".", "length", "-", "1", "]", ".", "focus", "(", ")", ";", "event", ".", "preventDefault", "(", ")", ";", "}", "else", "if", "(", "!", "event", ".", "shiftKey", "&&", "focusedItemIndex", "===", "focusableChildren", ".", "length", "-", "1", ")", "{", "focusableChildren", "[", "0", "]", ".", "focus", "(", ")", ";", "event", ".", "preventDefault", "(", ")", ";", "}", "}" ]
Helper function trapping the tab key inside a node
[ "Helper", "function", "trapping", "the", "tab", "key", "inside", "a", "node" ]
73e1243e7fcedb731591dbafcc8ecf480ec4700f
https://github.com/Pier1/rocketbelt/blob/73e1243e7fcedb731591dbafcc8ecf480ec4700f/rocketbelt/components/dialogs/rocketbelt.dialogs.js#L149-L160
28,169
jonschlinkert/regex-cache
index.js
regexCache
function regexCache(fn, str, opts) { var key = '_default_', regex, cached; if (!str && !opts) { if (typeof fn !== 'function') { return fn; } return basic[key] || (basic[key] = fn(str)); } var isString = typeof str === 'string'; if (isString) { if (!opts) { return basic[str] || (basic[str] = fn(str)); } key = str; } else { opts = str; } cached = cache[key]; if (cached && equal(cached.opts, opts)) { return cached.regex; } memo(key, opts, (regex = fn(str, opts))); return regex; }
javascript
function regexCache(fn, str, opts) { var key = '_default_', regex, cached; if (!str && !opts) { if (typeof fn !== 'function') { return fn; } return basic[key] || (basic[key] = fn(str)); } var isString = typeof str === 'string'; if (isString) { if (!opts) { return basic[str] || (basic[str] = fn(str)); } key = str; } else { opts = str; } cached = cache[key]; if (cached && equal(cached.opts, opts)) { return cached.regex; } memo(key, opts, (regex = fn(str, opts))); return regex; }
[ "function", "regexCache", "(", "fn", ",", "str", ",", "opts", ")", "{", "var", "key", "=", "'_default_'", ",", "regex", ",", "cached", ";", "if", "(", "!", "str", "&&", "!", "opts", ")", "{", "if", "(", "typeof", "fn", "!==", "'function'", ")", "{", "return", "fn", ";", "}", "return", "basic", "[", "key", "]", "||", "(", "basic", "[", "key", "]", "=", "fn", "(", "str", ")", ")", ";", "}", "var", "isString", "=", "typeof", "str", "===", "'string'", ";", "if", "(", "isString", ")", "{", "if", "(", "!", "opts", ")", "{", "return", "basic", "[", "str", "]", "||", "(", "basic", "[", "str", "]", "=", "fn", "(", "str", ")", ")", ";", "}", "key", "=", "str", ";", "}", "else", "{", "opts", "=", "str", ";", "}", "cached", "=", "cache", "[", "key", "]", ";", "if", "(", "cached", "&&", "equal", "(", "cached", ".", "opts", ",", "opts", ")", ")", "{", "return", "cached", ".", "regex", ";", "}", "memo", "(", "key", ",", "opts", ",", "(", "regex", "=", "fn", "(", "str", ",", "opts", ")", ")", ")", ";", "return", "regex", ";", "}" ]
Memoize the results of a call to the new RegExp constructor. @param {Function} fn [description] @param {String} str [description] @param {Options} options [description] @param {Boolean} nocompare [description] @return {RegExp}
[ "Memoize", "the", "results", "of", "a", "call", "to", "the", "new", "RegExp", "constructor", "." ]
1c001df1e266328fa9e34906660c79169ab9fa4f
https://github.com/jonschlinkert/regex-cache/blob/1c001df1e266328fa9e34906660c79169ab9fa4f/index.js#L30-L57
28,170
y-js/y-webrtc
src/WebRTC.js
function () { // check if the clients still exists var peer = self.swr.webrtc.getPeers(uid)[0] var success if (peer) { // success is true, if the message is successfully sent success = peer.sendDirectly('simplewebrtc', 'yjs', message) } if (!success) { // resend the message if it didn't work setTimeout(send, 500) } }
javascript
function () { // check if the clients still exists var peer = self.swr.webrtc.getPeers(uid)[0] var success if (peer) { // success is true, if the message is successfully sent success = peer.sendDirectly('simplewebrtc', 'yjs', message) } if (!success) { // resend the message if it didn't work setTimeout(send, 500) } }
[ "function", "(", ")", "{", "// check if the clients still exists", "var", "peer", "=", "self", ".", "swr", ".", "webrtc", ".", "getPeers", "(", "uid", ")", "[", "0", "]", "var", "success", "if", "(", "peer", ")", "{", "// success is true, if the message is successfully sent", "success", "=", "peer", ".", "sendDirectly", "(", "'simplewebrtc'", ",", "'yjs'", ",", "message", ")", "}", "if", "(", "!", "success", ")", "{", "// resend the message if it didn't work", "setTimeout", "(", "send", ",", "500", ")", "}", "}" ]
we have to make sure that the message is sent under all circumstances
[ "we", "have", "to", "make", "sure", "that", "the", "message", "is", "sent", "under", "all", "circumstances" ]
1c6559b57dae9f9e5da18b6755afd92577fda878
https://github.com/y-js/y-webrtc/blob/1c6559b57dae9f9e5da18b6755afd92577fda878/src/WebRTC.js#L73-L85
28,171
libp2p/js-libp2p-ping
src/handler.js
next
function next () { shake.read(PING_LENGTH, (err, buf) => { if (err === true) { // stream closed return } if (err) { return log.error(err) } shake.write(buf) return next() }) }
javascript
function next () { shake.read(PING_LENGTH, (err, buf) => { if (err === true) { // stream closed return } if (err) { return log.error(err) } shake.write(buf) return next() }) }
[ "function", "next", "(", ")", "{", "shake", ".", "read", "(", "PING_LENGTH", ",", "(", "err", ",", "buf", ")", "=>", "{", "if", "(", "err", "===", "true", ")", "{", "// stream closed", "return", "}", "if", "(", "err", ")", "{", "return", "log", ".", "error", "(", "err", ")", "}", "shake", ".", "write", "(", "buf", ")", "return", "next", "(", ")", "}", ")", "}" ]
receive and echo back
[ "receive", "and", "echo", "back" ]
349eecf68ae5f5fb7c35333cdb42c138bbf5c766
https://github.com/libp2p/js-libp2p-ping/blob/349eecf68ae5f5fb7c35333cdb42c138bbf5c766/src/handler.js#L19-L32
28,172
jeffijoe/yenv
lib/applyEnv.js
raw
function raw(obj) { const result = {} for (const key in obj) { const value = obj[key] if (value !== null && value !== undefined) { result[key] = value.toString() } } return result }
javascript
function raw(obj) { const result = {} for (const key in obj) { const value = obj[key] if (value !== null && value !== undefined) { result[key] = value.toString() } } return result }
[ "function", "raw", "(", "obj", ")", "{", "const", "result", "=", "{", "}", "for", "(", "const", "key", "in", "obj", ")", "{", "const", "value", "=", "obj", "[", "key", "]", "if", "(", "value", "!==", "null", "&&", "value", "!==", "undefined", ")", "{", "result", "[", "key", "]", "=", "value", ".", "toString", "(", ")", "}", "}", "return", "result", "}" ]
Serializes env values as strings.
[ "Serializes", "env", "values", "as", "strings", "." ]
fb3eaca3550718c89853fa891ecef837eecc2992
https://github.com/jeffijoe/yenv/blob/fb3eaca3550718c89853fa891ecef837eecc2992/lib/applyEnv.js#L38-L47
28,173
jeffijoe/yenv
lib/composeSections.js
circularSectionsError
function circularSectionsError(sectionName, path) { const joinedPath = path.join(' -> ') const message = `Circular sections! Path: ${joinedPath} -> [${sectionName}]` return new Error(message) }
javascript
function circularSectionsError(sectionName, path) { const joinedPath = path.join(' -> ') const message = `Circular sections! Path: ${joinedPath} -> [${sectionName}]` return new Error(message) }
[ "function", "circularSectionsError", "(", "sectionName", ",", "path", ")", "{", "const", "joinedPath", "=", "path", ".", "join", "(", "' -> '", ")", "const", "message", "=", "`", "${", "joinedPath", "}", "${", "sectionName", "}", "`", "return", "new", "Error", "(", "message", ")", "}" ]
Returns a new error indicating circular sections. @param {String} sectionName The section at which the circularity was determined. @param {String[]} path The circular sections path. @return {Error} Our beautiful error.
[ "Returns", "a", "new", "error", "indicating", "circular", "sections", "." ]
fb3eaca3550718c89853fa891ecef837eecc2992
https://github.com/jeffijoe/yenv/blob/fb3eaca3550718c89853fa891ecef837eecc2992/lib/composeSections.js#L17-L21
28,174
jeffijoe/yenv
lib/processImports.js
circularImportsError
function circularImportsError(fileBeingImported, importTrail) { const message = `Circular import of "${fileBeingImported}".\r\n` + 'Import trace:\r\n' + importTrail.map(f => ` -> ${f}`).join('\r\n') return new Error(message) }
javascript
function circularImportsError(fileBeingImported, importTrail) { const message = `Circular import of "${fileBeingImported}".\r\n` + 'Import trace:\r\n' + importTrail.map(f => ` -> ${f}`).join('\r\n') return new Error(message) }
[ "function", "circularImportsError", "(", "fileBeingImported", ",", "importTrail", ")", "{", "const", "message", "=", "`", "${", "fileBeingImported", "}", "\\r", "\\n", "`", "+", "'Import trace:\\r\\n'", "+", "importTrail", ".", "map", "(", "f", "=>", "`", "${", "f", "}", "`", ")", ".", "join", "(", "'\\r\\n'", ")", "return", "new", "Error", "(", "message", ")", "}" ]
Constructs a circular imports error. @param {string} fileBeingImported The file being imported. @param {string} importingFile The file that imported. @return {Error} An error.
[ "Constructs", "a", "circular", "imports", "error", "." ]
fb3eaca3550718c89853fa891ecef837eecc2992
https://github.com/jeffijoe/yenv/blob/fb3eaca3550718c89853fa891ecef837eecc2992/lib/processImports.js#L25-L31
28,175
jeffijoe/yenv
lib/processImports.js
mapFiles
function mapFiles(files, relative, required) { if (!files) { return [] } if (Array.isArray(files) === false) { files = [files] } return files.map(f => ({ file: resolvePath(relative, f), required: required })) }
javascript
function mapFiles(files, relative, required) { if (!files) { return [] } if (Array.isArray(files) === false) { files = [files] } return files.map(f => ({ file: resolvePath(relative, f), required: required })) }
[ "function", "mapFiles", "(", "files", ",", "relative", ",", "required", ")", "{", "if", "(", "!", "files", ")", "{", "return", "[", "]", "}", "if", "(", "Array", ".", "isArray", "(", "files", ")", "===", "false", ")", "{", "files", "=", "[", "files", "]", "}", "return", "files", ".", "map", "(", "f", "=>", "(", "{", "file", ":", "resolvePath", "(", "relative", ",", "f", ")", ",", "required", ":", "required", "}", ")", ")", "}" ]
Maps file paths as well as whether not they are required to descriptors.
[ "Maps", "file", "paths", "as", "well", "as", "whether", "not", "they", "are", "required", "to", "descriptors", "." ]
fb3eaca3550718c89853fa891ecef837eecc2992
https://github.com/jeffijoe/yenv/blob/fb3eaca3550718c89853fa891ecef837eecc2992/lib/processImports.js#L98-L111
28,176
KleeGroup/focus-core
src/definition/validator/validate.js
validate
function validate(property, validators) { //console.log("validate", property, validators); let errors = [], res, validator; if (validators) { for (let i = 0, _len = validators.length; i < _len; i++) { validator = validators[i]; res = validateProperty(property, validator); if (!isNull(res) && !isUndefined(res)) { errors.push(res); } } } //Check what's the good type to return. return { name: property.name, value: property.value, isValid: 0 === errors.length, errors: errors }; }
javascript
function validate(property, validators) { //console.log("validate", property, validators); let errors = [], res, validator; if (validators) { for (let i = 0, _len = validators.length; i < _len; i++) { validator = validators[i]; res = validateProperty(property, validator); if (!isNull(res) && !isUndefined(res)) { errors.push(res); } } } //Check what's the good type to return. return { name: property.name, value: property.value, isValid: 0 === errors.length, errors: errors }; }
[ "function", "validate", "(", "property", ",", "validators", ")", "{", "//console.log(\"validate\", property, validators);", "let", "errors", "=", "[", "]", ",", "res", ",", "validator", ";", "if", "(", "validators", ")", "{", "for", "(", "let", "i", "=", "0", ",", "_len", "=", "validators", ".", "length", ";", "i", "<", "_len", ";", "i", "++", ")", "{", "validator", "=", "validators", "[", "i", "]", ";", "res", "=", "validateProperty", "(", "property", ",", "validator", ")", ";", "if", "(", "!", "isNull", "(", "res", ")", "&&", "!", "isUndefined", "(", "res", ")", ")", "{", "errors", ".", "push", "(", "res", ")", ";", "}", "}", "}", "//Check what's the good type to return.", "return", "{", "name", ":", "property", ".", "name", ",", "value", ":", "property", ".", "value", ",", "isValid", ":", "0", "===", "errors", ".", "length", ",", "errors", ":", "errors", "}", ";", "}" ]
Validae a property given validators. @param {object} property - Property to validate which should be as follows: `{name: "field_name",value: "field_value", validators: [{...}] }`. @param {array} validators - The validators to apply on the property. @return {object} - The validation status.
[ "Validae", "a", "property", "given", "validators", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/definition/validator/validate.js#L19-L38
28,177
KleeGroup/focus-core
src/definition/validator/validate.js
getErrorLabel
function getErrorLabel(type, fieldName, options = {}) { options = options || {}; const translationKey = options.translationKey ? options.translationKey : `domain.validation.${type}`; const opts = { fieldName: translate(fieldName), ...options }; return translate(translationKey, opts); }
javascript
function getErrorLabel(type, fieldName, options = {}) { options = options || {}; const translationKey = options.translationKey ? options.translationKey : `domain.validation.${type}`; const opts = { fieldName: translate(fieldName), ...options }; return translate(translationKey, opts); }
[ "function", "getErrorLabel", "(", "type", ",", "fieldName", ",", "options", "=", "{", "}", ")", "{", "options", "=", "options", "||", "{", "}", ";", "const", "translationKey", "=", "options", ".", "translationKey", "?", "options", ".", "translationKey", ":", "`", "${", "type", "}", "`", ";", "const", "opts", "=", "{", "fieldName", ":", "translate", "(", "fieldName", ")", ",", "...", "options", "}", ";", "return", "translate", "(", "translationKey", ",", "opts", ")", ";", "}" ]
Get the error label from a type and a field name. @param {string} type - The type name. @param {string} fieldName - The field name. @param {object} options - The options to put such as the translationKey which could be defined in the domain. @return {string} The formatted error.
[ "Get", "the", "error", "label", "from", "a", "type", "and", "a", "field", "name", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/definition/validator/validate.js#L100-L105
28,178
KleeGroup/focus-core
src/list/load-action/builder.js
orderAndSort
function orderAndSort(sortConf) { return { sortFieldName: sortConf.sortBy, sortDesc: sortConf.sortAsc === undefined ? false : !sortConf.sortAsc }; }
javascript
function orderAndSort(sortConf) { return { sortFieldName: sortConf.sortBy, sortDesc: sortConf.sortAsc === undefined ? false : !sortConf.sortAsc }; }
[ "function", "orderAndSort", "(", "sortConf", ")", "{", "return", "{", "sortFieldName", ":", "sortConf", ".", "sortBy", ",", "sortDesc", ":", "sortConf", ".", "sortAsc", "===", "undefined", "?", "false", ":", "!", "sortConf", ".", "sortAsc", "}", ";", "}" ]
Build sort infotmation. @param {object} sortConf - The sort configuration. @return {object} - The builded sort configuration.
[ "Build", "sort", "infotmation", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/list/load-action/builder.js#L7-L12
28,179
KleeGroup/focus-core
src/list/load-action/builder.js
pagination
function pagination(opts) { let { isScroll, dataList, totalCount, nbElement } = opts; if (isScroll) { if (!isArray(dataList)) { throw new Error('The data list options sould exist and be an array') } if (dataList.length < totalCount) { return { top: nbElement, skip: dataList.length }; } } return { top: nbElement, skip: 0 } }
javascript
function pagination(opts) { let { isScroll, dataList, totalCount, nbElement } = opts; if (isScroll) { if (!isArray(dataList)) { throw new Error('The data list options sould exist and be an array') } if (dataList.length < totalCount) { return { top: nbElement, skip: dataList.length }; } } return { top: nbElement, skip: 0 } }
[ "function", "pagination", "(", "opts", ")", "{", "let", "{", "isScroll", ",", "dataList", ",", "totalCount", ",", "nbElement", "}", "=", "opts", ";", "if", "(", "isScroll", ")", "{", "if", "(", "!", "isArray", "(", "dataList", ")", ")", "{", "throw", "new", "Error", "(", "'The data list options sould exist and be an array'", ")", "}", "if", "(", "dataList", ".", "length", "<", "totalCount", ")", "{", "return", "{", "top", ":", "nbElement", ",", "skip", ":", "dataList", ".", "length", "}", ";", "}", "}", "return", "{", "top", ":", "nbElement", ",", "skip", ":", "0", "}", "}" ]
Build the pagination configuration given the options. @param {object} opts - The pagination options should be : isScroll (:bool) - Are we in a scroll context. totalCount (:number) - The total number of element. (intresting only in the scroll case) nbSearchElement (:number) - The number of elements you want to get back from the search. @return {object} - An object with {top, skip}.
[ "Build", "the", "pagination", "configuration", "given", "the", "options", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/list/load-action/builder.js#L22-L36
28,180
reflux/reflux-promise
src/index.js
triggerPromise
function triggerPromise() { var me = this; var args = arguments; var canHandlePromise = this.children.indexOf("completed") >= 0 && this.children.indexOf("failed") >= 0; var createdPromise = new PromiseFactory(function(resolve, reject) { // If `listenAndPromise` is listening // patch `promise` w/ context-loaded resolve/reject if (me.willCallPromise) { _.nextTick(function() { var previousPromise = me.promise; me.promise = function (inputPromise) { inputPromise.then(resolve, reject); // Back to your regularly schedule programming. me.promise = previousPromise; return me.promise.apply(me, arguments); }; me.trigger.apply(me, args); }); return; } if (canHandlePromise) { var removeSuccess = me.completed.listen(function () { var args = Array.prototype.slice.call(arguments); removeSuccess(); removeFailed(); resolve(args.length > 1 ? args : args[0]); }); var removeFailed = me.failed.listen(function () { var args = Array.prototype.slice.call(arguments); removeSuccess(); removeFailed(); reject(args.length > 1 ? args : args[0]); }); } _.nextTick(function () { me.trigger.apply(me, args); }); if (!canHandlePromise) { resolve(); } }); // Ensure that the promise does trigger "Uncaught (in promise)" errors in console if no error handler is added // See: https://github.com/reflux/reflux-promise/issues/4 createdPromise.catch(function() {}); return createdPromise; }
javascript
function triggerPromise() { var me = this; var args = arguments; var canHandlePromise = this.children.indexOf("completed") >= 0 && this.children.indexOf("failed") >= 0; var createdPromise = new PromiseFactory(function(resolve, reject) { // If `listenAndPromise` is listening // patch `promise` w/ context-loaded resolve/reject if (me.willCallPromise) { _.nextTick(function() { var previousPromise = me.promise; me.promise = function (inputPromise) { inputPromise.then(resolve, reject); // Back to your regularly schedule programming. me.promise = previousPromise; return me.promise.apply(me, arguments); }; me.trigger.apply(me, args); }); return; } if (canHandlePromise) { var removeSuccess = me.completed.listen(function () { var args = Array.prototype.slice.call(arguments); removeSuccess(); removeFailed(); resolve(args.length > 1 ? args : args[0]); }); var removeFailed = me.failed.listen(function () { var args = Array.prototype.slice.call(arguments); removeSuccess(); removeFailed(); reject(args.length > 1 ? args : args[0]); }); } _.nextTick(function () { me.trigger.apply(me, args); }); if (!canHandlePromise) { resolve(); } }); // Ensure that the promise does trigger "Uncaught (in promise)" errors in console if no error handler is added // See: https://github.com/reflux/reflux-promise/issues/4 createdPromise.catch(function() {}); return createdPromise; }
[ "function", "triggerPromise", "(", ")", "{", "var", "me", "=", "this", ";", "var", "args", "=", "arguments", ";", "var", "canHandlePromise", "=", "this", ".", "children", ".", "indexOf", "(", "\"completed\"", ")", ">=", "0", "&&", "this", ".", "children", ".", "indexOf", "(", "\"failed\"", ")", ">=", "0", ";", "var", "createdPromise", "=", "new", "PromiseFactory", "(", "function", "(", "resolve", ",", "reject", ")", "{", "// If `listenAndPromise` is listening", "// patch `promise` w/ context-loaded resolve/reject", "if", "(", "me", ".", "willCallPromise", ")", "{", "_", ".", "nextTick", "(", "function", "(", ")", "{", "var", "previousPromise", "=", "me", ".", "promise", ";", "me", ".", "promise", "=", "function", "(", "inputPromise", ")", "{", "inputPromise", ".", "then", "(", "resolve", ",", "reject", ")", ";", "// Back to your regularly schedule programming.", "me", ".", "promise", "=", "previousPromise", ";", "return", "me", ".", "promise", ".", "apply", "(", "me", ",", "arguments", ")", ";", "}", ";", "me", ".", "trigger", ".", "apply", "(", "me", ",", "args", ")", ";", "}", ")", ";", "return", ";", "}", "if", "(", "canHandlePromise", ")", "{", "var", "removeSuccess", "=", "me", ".", "completed", ".", "listen", "(", "function", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "removeSuccess", "(", ")", ";", "removeFailed", "(", ")", ";", "resolve", "(", "args", ".", "length", ">", "1", "?", "args", ":", "args", "[", "0", "]", ")", ";", "}", ")", ";", "var", "removeFailed", "=", "me", ".", "failed", ".", "listen", "(", "function", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "removeSuccess", "(", ")", ";", "removeFailed", "(", ")", ";", "reject", "(", "args", ".", "length", ">", "1", "?", "args", ":", "args", "[", "0", "]", ")", ";", "}", ")", ";", "}", "_", ".", "nextTick", "(", "function", "(", ")", "{", "me", ".", "trigger", ".", "apply", "(", "me", ",", "args", ")", ";", "}", ")", ";", "if", "(", "!", "canHandlePromise", ")", "{", "resolve", "(", ")", ";", "}", "}", ")", ";", "// Ensure that the promise does trigger \"Uncaught (in promise)\" errors in console if no error handler is added", "// See: https://github.com/reflux/reflux-promise/issues/4", "createdPromise", ".", "catch", "(", "function", "(", ")", "{", "}", ")", ";", "return", "createdPromise", ";", "}" ]
Returns a Promise for the triggered action @return {Promise} Resolved by completed child action. Rejected by failed child action. If listenAndPromise'd, then promise associated to this trigger. Otherwise, the promise is for next child action completion.
[ "Returns", "a", "Promise", "for", "the", "triggered", "action" ]
fa0633ee09f776f7b6d6d4d8fa2e9d3a3ef81cd6
https://github.com/reflux/reflux-promise/blob/fa0633ee09f776f7b6d6d4d8fa2e9d3a3ef81cd6/src/index.js#L14-L69
28,181
reflux/reflux-promise
src/index.js
promise
function promise(p) { var me = this; var canHandlePromise = this.children.indexOf("completed") >= 0 && this.children.indexOf("failed") >= 0; if (!canHandlePromise){ throw new Error("Publisher must have \"completed\" and \"failed\" child publishers"); } p.then(function(response) { return me.completed(response); }, function(error) { return me.failed(error); }); }
javascript
function promise(p) { var me = this; var canHandlePromise = this.children.indexOf("completed") >= 0 && this.children.indexOf("failed") >= 0; if (!canHandlePromise){ throw new Error("Publisher must have \"completed\" and \"failed\" child publishers"); } p.then(function(response) { return me.completed(response); }, function(error) { return me.failed(error); }); }
[ "function", "promise", "(", "p", ")", "{", "var", "me", "=", "this", ";", "var", "canHandlePromise", "=", "this", ".", "children", ".", "indexOf", "(", "\"completed\"", ")", ">=", "0", "&&", "this", ".", "children", ".", "indexOf", "(", "\"failed\"", ")", ">=", "0", ";", "if", "(", "!", "canHandlePromise", ")", "{", "throw", "new", "Error", "(", "\"Publisher must have \\\"completed\\\" and \\\"failed\\\" child publishers\"", ")", ";", "}", "p", ".", "then", "(", "function", "(", "response", ")", "{", "return", "me", ".", "completed", "(", "response", ")", ";", "}", ",", "function", "(", "error", ")", "{", "return", "me", ".", "failed", "(", "error", ")", ";", "}", ")", ";", "}" ]
Attach handlers to promise that trigger the completed and failed child publishers, if available. @param {Object} p The promise to attach to
[ "Attach", "handlers", "to", "promise", "that", "trigger", "the", "completed", "and", "failed", "child", "publishers", "if", "available", "." ]
fa0633ee09f776f7b6d6d4d8fa2e9d3a3ef81cd6
https://github.com/reflux/reflux-promise/blob/fa0633ee09f776f7b6d6d4d8fa2e9d3a3ef81cd6/src/index.js#L77-L93
28,182
reflux/reflux-promise
src/index.js
listenAndPromise
function listenAndPromise(callback, bindContext) { var me = this; bindContext = bindContext || this; this.willCallPromise = (this.willCallPromise || 0) + 1; var removeListen = this.listen(function() { if (!callback) { throw new Error("Expected a function returning a promise but got " + callback); } var args = arguments, returnedPromise = callback.apply(bindContext, args); return me.promise.call(me, returnedPromise); }, bindContext); return function () { me.willCallPromise--; removeListen.call(me); }; }
javascript
function listenAndPromise(callback, bindContext) { var me = this; bindContext = bindContext || this; this.willCallPromise = (this.willCallPromise || 0) + 1; var removeListen = this.listen(function() { if (!callback) { throw new Error("Expected a function returning a promise but got " + callback); } var args = arguments, returnedPromise = callback.apply(bindContext, args); return me.promise.call(me, returnedPromise); }, bindContext); return function () { me.willCallPromise--; removeListen.call(me); }; }
[ "function", "listenAndPromise", "(", "callback", ",", "bindContext", ")", "{", "var", "me", "=", "this", ";", "bindContext", "=", "bindContext", "||", "this", ";", "this", ".", "willCallPromise", "=", "(", "this", ".", "willCallPromise", "||", "0", ")", "+", "1", ";", "var", "removeListen", "=", "this", ".", "listen", "(", "function", "(", ")", "{", "if", "(", "!", "callback", ")", "{", "throw", "new", "Error", "(", "\"Expected a function returning a promise but got \"", "+", "callback", ")", ";", "}", "var", "args", "=", "arguments", ",", "returnedPromise", "=", "callback", ".", "apply", "(", "bindContext", ",", "args", ")", ";", "return", "me", ".", "promise", ".", "call", "(", "me", ",", "returnedPromise", ")", ";", "}", ",", "bindContext", ")", ";", "return", "function", "(", ")", "{", "me", ".", "willCallPromise", "--", ";", "removeListen", ".", "call", "(", "me", ")", ";", "}", ";", "}" ]
Subscribes the given callback for action triggered, which should return a promise that in turn is passed to `this.promise` @param {Function} callback The callback to register as event handler
[ "Subscribes", "the", "given", "callback", "for", "action", "triggered", "which", "should", "return", "a", "promise", "that", "in", "turn", "is", "passed", "to", "this", ".", "promise" ]
fa0633ee09f776f7b6d6d4d8fa2e9d3a3ef81cd6
https://github.com/reflux/reflux-promise/blob/fa0633ee09f776f7b6d6d4d8fa2e9d3a3ef81cd6/src/index.js#L101-L122
28,183
KleeGroup/focus-core
src/user/index.js
hasRole
function hasRole(role) { role = isArray(role) ? role : [role]; return 0 < intersection(role, userBuiltInStore.getRoles()).length; }
javascript
function hasRole(role) { role = isArray(role) ? role : [role]; return 0 < intersection(role, userBuiltInStore.getRoles()).length; }
[ "function", "hasRole", "(", "role", ")", "{", "role", "=", "isArray", "(", "role", ")", "?", "role", ":", "[", "role", "]", ";", "return", "0", "<", "intersection", "(", "role", ",", "userBuiltInStore", ".", "getRoles", "(", ")", ")", ".", "length", ";", "}" ]
Check if a user has the givent role or roles. @param {string | array} role - Check if the user has one or many roles. @return {Boolean} - True if the user has at least on of the givent roles.
[ "Check", "if", "a", "user", "has", "the", "givent", "role", "or", "roles", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/user/index.js#L19-L22
28,184
ExtraHop/metalsmith-sitemap
lib/index.js
check
function check(file, frontmatter) { // Only process files that match the pattern if (!match(file, pattern)[0]) { return false; } // Don't process private files if (get(frontmatter, privateProperty)) { return false; } return true; }
javascript
function check(file, frontmatter) { // Only process files that match the pattern if (!match(file, pattern)[0]) { return false; } // Don't process private files if (get(frontmatter, privateProperty)) { return false; } return true; }
[ "function", "check", "(", "file", ",", "frontmatter", ")", "{", "// Only process files that match the pattern", "if", "(", "!", "match", "(", "file", ",", "pattern", ")", "[", "0", "]", ")", "{", "return", "false", ";", "}", "// Don't process private files", "if", "(", "get", "(", "frontmatter", ",", "privateProperty", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Checks whether files should be processed
[ "Checks", "whether", "files", "should", "be", "processed" ]
6b69101e96c1d3c6e7fedac74fbd45a867615944
https://github.com/ExtraHop/metalsmith-sitemap/blob/6b69101e96c1d3c6e7fedac74fbd45a867615944/lib/index.js#L77-L89
28,185
ExtraHop/metalsmith-sitemap
lib/index.js
buildUrl
function buildUrl(file, frontmatter) { // Frontmatter settings take precedence var canonicalUrl = get(frontmatter, urlProperty); if (is.string(canonicalUrl)) { return canonicalUrl; } // Remove index.html if necessary var indexFile = 'index.html'; if (omitIndex && path.basename(file) === indexFile) { return replaceBackslash(file.slice(0, 0 - indexFile.length)); } // Remove extension if necessary if (omitExtension) { return replaceBackslash(file.slice(0, 0 - path.extname(file).length)); } // Otherwise just use 'file' return replaceBackslash(file); }
javascript
function buildUrl(file, frontmatter) { // Frontmatter settings take precedence var canonicalUrl = get(frontmatter, urlProperty); if (is.string(canonicalUrl)) { return canonicalUrl; } // Remove index.html if necessary var indexFile = 'index.html'; if (omitIndex && path.basename(file) === indexFile) { return replaceBackslash(file.slice(0, 0 - indexFile.length)); } // Remove extension if necessary if (omitExtension) { return replaceBackslash(file.slice(0, 0 - path.extname(file).length)); } // Otherwise just use 'file' return replaceBackslash(file); }
[ "function", "buildUrl", "(", "file", ",", "frontmatter", ")", "{", "// Frontmatter settings take precedence", "var", "canonicalUrl", "=", "get", "(", "frontmatter", ",", "urlProperty", ")", ";", "if", "(", "is", ".", "string", "(", "canonicalUrl", ")", ")", "{", "return", "canonicalUrl", ";", "}", "// Remove index.html if necessary", "var", "indexFile", "=", "'index.html'", ";", "if", "(", "omitIndex", "&&", "path", ".", "basename", "(", "file", ")", "===", "indexFile", ")", "{", "return", "replaceBackslash", "(", "file", ".", "slice", "(", "0", ",", "0", "-", "indexFile", ".", "length", ")", ")", ";", "}", "// Remove extension if necessary", "if", "(", "omitExtension", ")", "{", "return", "replaceBackslash", "(", "file", ".", "slice", "(", "0", ",", "0", "-", "path", ".", "extname", "(", "file", ")", ".", "length", ")", ")", ";", "}", "// Otherwise just use 'file'", "return", "replaceBackslash", "(", "file", ")", ";", "}" ]
Builds a url
[ "Builds", "a", "url" ]
6b69101e96c1d3c6e7fedac74fbd45a867615944
https://github.com/ExtraHop/metalsmith-sitemap/blob/6b69101e96c1d3c6e7fedac74fbd45a867615944/lib/index.js#L92-L112
28,186
KleeGroup/focus-core
src/definition/formatter/number.js
init
function init(format = DEFAULT_FORMAT, locale = 'fr') { numeral.locale(locale); numeral.defaultFormat(format); }
javascript
function init(format = DEFAULT_FORMAT, locale = 'fr') { numeral.locale(locale); numeral.defaultFormat(format); }
[ "function", "init", "(", "format", "=", "DEFAULT_FORMAT", ",", "locale", "=", "'fr'", ")", "{", "numeral", ".", "locale", "(", "locale", ")", ";", "numeral", ".", "defaultFormat", "(", "format", ")", ";", "}" ]
Initialize numeral locale and default format. @param {string} [format='0,0'] format to use @param {string} [locale='fr'] locale to use
[ "Initialize", "numeral", "locale", "and", "default", "format", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/definition/formatter/number.js#L21-L24
28,187
KleeGroup/focus-core
src/network/fetch.js
updateRequestStatus
function updateRequestStatus(request) { if (!request || !request.id || !request.status) { return; } dispatcher.handleViewAction({ data: { request: request }, type: 'update' }); return request; }
javascript
function updateRequestStatus(request) { if (!request || !request.id || !request.status) { return; } dispatcher.handleViewAction({ data: { request: request }, type: 'update' }); return request; }
[ "function", "updateRequestStatus", "(", "request", ")", "{", "if", "(", "!", "request", "||", "!", "request", ".", "id", "||", "!", "request", ".", "status", ")", "{", "return", ";", "}", "dispatcher", ".", "handleViewAction", "(", "{", "data", ":", "{", "request", ":", "request", "}", ",", "type", ":", "'update'", "}", ")", ";", "return", "request", ";", "}" ]
Update the request status. @param {object} request - The request to treat. @return {object} - The request to dispatch.
[ "Update", "the", "request", "status", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/network/fetch.js#L22-L29
28,188
KleeGroup/focus-core
src/network/fetch.js
getResponseContent
function getResponseContent(response, dataType) { const { type, status, ok } = response; // Handling errors if (type === 'opaque') { console.error('You tried to make a Cross Domain Request with no-cors options'); return Promise.reject({ status: status, globalErrors: ['error.noCorsOptsOnCors'] }); } if (type === 'error') { console.error('An unknown network issue has happened'); return Promise.reject({ status: status, globalErrors: ['error.unknownNetworkIssue'] }); } if (!ok && dataType === 'json') { return response.json().catch(err => Promise.reject({ globalErrors: [err] })).then(data => Promise.reject({ status, ...data })); } if (!ok) { return response.text().then(text => Promise.reject({ status, globalErrors: [text] })); } // Handling success if (ok && status === '204') { return Promise.resolve(null); } return ['arrayBuffer', 'blob', 'formData', 'json'].includes(dataType) ? response[dataType]().catch(err => Promise.reject({ globalErrors: [err] })) : response.text(); }
javascript
function getResponseContent(response, dataType) { const { type, status, ok } = response; // Handling errors if (type === 'opaque') { console.error('You tried to make a Cross Domain Request with no-cors options'); return Promise.reject({ status: status, globalErrors: ['error.noCorsOptsOnCors'] }); } if (type === 'error') { console.error('An unknown network issue has happened'); return Promise.reject({ status: status, globalErrors: ['error.unknownNetworkIssue'] }); } if (!ok && dataType === 'json') { return response.json().catch(err => Promise.reject({ globalErrors: [err] })).then(data => Promise.reject({ status, ...data })); } if (!ok) { return response.text().then(text => Promise.reject({ status, globalErrors: [text] })); } // Handling success if (ok && status === '204') { return Promise.resolve(null); } return ['arrayBuffer', 'blob', 'formData', 'json'].includes(dataType) ? response[dataType]().catch(err => Promise.reject({ globalErrors: [err] })) : response.text(); }
[ "function", "getResponseContent", "(", "response", ",", "dataType", ")", "{", "const", "{", "type", ",", "status", ",", "ok", "}", "=", "response", ";", "// Handling errors", "if", "(", "type", "===", "'opaque'", ")", "{", "console", ".", "error", "(", "'You tried to make a Cross Domain Request with no-cors options'", ")", ";", "return", "Promise", ".", "reject", "(", "{", "status", ":", "status", ",", "globalErrors", ":", "[", "'error.noCorsOptsOnCors'", "]", "}", ")", ";", "}", "if", "(", "type", "===", "'error'", ")", "{", "console", ".", "error", "(", "'An unknown network issue has happened'", ")", ";", "return", "Promise", ".", "reject", "(", "{", "status", ":", "status", ",", "globalErrors", ":", "[", "'error.unknownNetworkIssue'", "]", "}", ")", ";", "}", "if", "(", "!", "ok", "&&", "dataType", "===", "'json'", ")", "{", "return", "response", ".", "json", "(", ")", ".", "catch", "(", "err", "=>", "Promise", ".", "reject", "(", "{", "globalErrors", ":", "[", "err", "]", "}", ")", ")", ".", "then", "(", "data", "=>", "Promise", ".", "reject", "(", "{", "status", ",", "...", "data", "}", ")", ")", ";", "}", "if", "(", "!", "ok", ")", "{", "return", "response", ".", "text", "(", ")", ".", "then", "(", "text", "=>", "Promise", ".", "reject", "(", "{", "status", ",", "globalErrors", ":", "[", "text", "]", "}", ")", ")", ";", "}", "// Handling success", "if", "(", "ok", "&&", "status", "===", "'204'", ")", "{", "return", "Promise", ".", "resolve", "(", "null", ")", ";", "}", "return", "[", "'arrayBuffer'", ",", "'blob'", ",", "'formData'", ",", "'json'", "]", ".", "includes", "(", "dataType", ")", "?", "response", "[", "dataType", "]", "(", ")", ".", "catch", "(", "err", "=>", "Promise", ".", "reject", "(", "{", "globalErrors", ":", "[", "err", "]", "}", ")", ")", ":", "response", ".", "text", "(", ")", ";", "}" ]
Extract the data from the response, and handle network or server errors or wrong data format. @param {Response} response the response to extract from @param {string} dataType the datatype (can be 'arrayBuffer', 'blob', 'formData', 'json' or 'text') @returns {Promise} a Promise containing response data, or error data
[ "Extract", "the", "data", "from", "the", "response", "and", "handle", "network", "or", "server", "errors", "or", "wrong", "data", "format", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/network/fetch.js#L38-L65
28,189
KleeGroup/focus-core
src/network/fetch.js
checkErrors
function checkErrors(response, xhrErrors) { let { status, ok } = response; if (!ok) { if (xhrErrors[status]) { xhrErrors[status](response); } } }
javascript
function checkErrors(response, xhrErrors) { let { status, ok } = response; if (!ok) { if (xhrErrors[status]) { xhrErrors[status](response); } } }
[ "function", "checkErrors", "(", "response", ",", "xhrErrors", ")", "{", "let", "{", "status", ",", "ok", "}", "=", "response", ";", "if", "(", "!", "ok", ")", "{", "if", "(", "xhrErrors", "[", "status", "]", ")", "{", "xhrErrors", "[", "status", "]", "(", "response", ")", ";", "}", "}", "}" ]
Check if a special treatment is specify for a specific error code @param {Object} response The fetch response @param {Object} xhrErrors The specific treatment
[ "Check", "if", "a", "special", "treatment", "is", "specify", "for", "a", "specific", "error", "code" ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/network/fetch.js#L73-L80
28,190
KleeGroup/focus-core
src/network/fetch.js
wrappingFetch
function wrappingFetch({ url, method, data }, optionsArg) { let requestStatus = createRequestStatus(); // Here we are using destruct to filter properties we do not want to give to fetch. // CORS and isCORS are useless legacy code, xhrErrors is used only in error parsing // eslint-disable-next-line no-unused-vars let { CORS, isCORS, xhrErrors, ...config } = configGetter(); const { noStringify, ...options } = optionsArg || {}; const reqOptions = merge({ headers: {} }, config, options, { method, body: noStringify ? data : JSON.stringify(data) }); //By default, add json content-type if (!reqOptions.noContentType && !reqOptions.headers['Content-Type']) { reqOptions.headers['Content-Type'] = 'application/json'; } // Set the requesting as pending updateRequestStatus({ id: requestStatus.id, status: 'pending' }); // Do the request return fetch(url, reqOptions) // Catch the possible TypeError from fetch .catch(error => { updateRequestStatus({ id: requestStatus.id, status: 'error' }); return Promise.reject({ globalErrors: [error] }); }).then(response => { updateRequestStatus({ id: requestStatus.id, status: response.ok ? 'success' : 'error' }); const contentType = response.headers.get('content-type'); return getResponseContent(response, reqOptions.dataType ? reqOptions.dataType : contentType && contentType.includes('application/json') ? 'json' : 'text'); }).catch(data => { checkErrors(data, xhrErrors); return Promise.reject(data); }); }
javascript
function wrappingFetch({ url, method, data }, optionsArg) { let requestStatus = createRequestStatus(); // Here we are using destruct to filter properties we do not want to give to fetch. // CORS and isCORS are useless legacy code, xhrErrors is used only in error parsing // eslint-disable-next-line no-unused-vars let { CORS, isCORS, xhrErrors, ...config } = configGetter(); const { noStringify, ...options } = optionsArg || {}; const reqOptions = merge({ headers: {} }, config, options, { method, body: noStringify ? data : JSON.stringify(data) }); //By default, add json content-type if (!reqOptions.noContentType && !reqOptions.headers['Content-Type']) { reqOptions.headers['Content-Type'] = 'application/json'; } // Set the requesting as pending updateRequestStatus({ id: requestStatus.id, status: 'pending' }); // Do the request return fetch(url, reqOptions) // Catch the possible TypeError from fetch .catch(error => { updateRequestStatus({ id: requestStatus.id, status: 'error' }); return Promise.reject({ globalErrors: [error] }); }).then(response => { updateRequestStatus({ id: requestStatus.id, status: response.ok ? 'success' : 'error' }); const contentType = response.headers.get('content-type'); return getResponseContent(response, reqOptions.dataType ? reqOptions.dataType : contentType && contentType.includes('application/json') ? 'json' : 'text'); }).catch(data => { checkErrors(data, xhrErrors); return Promise.reject(data); }); }
[ "function", "wrappingFetch", "(", "{", "url", ",", "method", ",", "data", "}", ",", "optionsArg", ")", "{", "let", "requestStatus", "=", "createRequestStatus", "(", ")", ";", "// Here we are using destruct to filter properties we do not want to give to fetch.", "// CORS and isCORS are useless legacy code, xhrErrors is used only in error parsing", "// eslint-disable-next-line no-unused-vars", "let", "{", "CORS", ",", "isCORS", ",", "xhrErrors", ",", "...", "config", "}", "=", "configGetter", "(", ")", ";", "const", "{", "noStringify", ",", "...", "options", "}", "=", "optionsArg", "||", "{", "}", ";", "const", "reqOptions", "=", "merge", "(", "{", "headers", ":", "{", "}", "}", ",", "config", ",", "options", ",", "{", "method", ",", "body", ":", "noStringify", "?", "data", ":", "JSON", ".", "stringify", "(", "data", ")", "}", ")", ";", "//By default, add json content-type", "if", "(", "!", "reqOptions", ".", "noContentType", "&&", "!", "reqOptions", ".", "headers", "[", "'Content-Type'", "]", ")", "{", "reqOptions", ".", "headers", "[", "'Content-Type'", "]", "=", "'application/json'", ";", "}", "// Set the requesting as pending", "updateRequestStatus", "(", "{", "id", ":", "requestStatus", ".", "id", ",", "status", ":", "'pending'", "}", ")", ";", "// Do the request", "return", "fetch", "(", "url", ",", "reqOptions", ")", "// Catch the possible TypeError from fetch", ".", "catch", "(", "error", "=>", "{", "updateRequestStatus", "(", "{", "id", ":", "requestStatus", ".", "id", ",", "status", ":", "'error'", "}", ")", ";", "return", "Promise", ".", "reject", "(", "{", "globalErrors", ":", "[", "error", "]", "}", ")", ";", "}", ")", ".", "then", "(", "response", "=>", "{", "updateRequestStatus", "(", "{", "id", ":", "requestStatus", ".", "id", ",", "status", ":", "response", ".", "ok", "?", "'success'", ":", "'error'", "}", ")", ";", "const", "contentType", "=", "response", ".", "headers", ".", "get", "(", "'content-type'", ")", ";", "return", "getResponseContent", "(", "response", ",", "reqOptions", ".", "dataType", "?", "reqOptions", ".", "dataType", ":", "contentType", "&&", "contentType", ".", "includes", "(", "'application/json'", ")", "?", "'json'", ":", "'text'", ")", ";", "}", ")", ".", "catch", "(", "data", "=>", "{", "checkErrors", "(", "data", ",", "xhrErrors", ")", ";", "return", "Promise", ".", "reject", "(", "data", ")", ";", "}", ")", ";", "}" ]
Fetch function to ease http request. @param {object} obj - method: http verb, url: http url, data:The json to save. @param {object} options - The options object. @return {CancellablePromise} The promise of the execution of the HTTP request.
[ "Fetch", "function", "to", "ease", "http", "request", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/network/fetch.js#L88-L116
28,191
KleeGroup/focus-core
src/reference/config.js
setConfig
function setConfig(newConf, isClearPrevious) { checkIsObject(newConf); config = isClearPrevious ? Immutable.fromJS(newConf) : config.merge(newConf); }
javascript
function setConfig(newConf, isClearPrevious) { checkIsObject(newConf); config = isClearPrevious ? Immutable.fromJS(newConf) : config.merge(newConf); }
[ "function", "setConfig", "(", "newConf", ",", "isClearPrevious", ")", "{", "checkIsObject", "(", "newConf", ")", ";", "config", "=", "isClearPrevious", "?", "Immutable", ".", "fromJS", "(", "newConf", ")", ":", "config", ".", "merge", "(", "newConf", ")", ";", "}" ]
Set the reference configuration. @param {object} newConf - The new configuration to set. @param {Boolean} isClearPrevious - Does the config should be reset.
[ "Set", "the", "reference", "configuration", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/reference/config.js#L27-L30
28,192
KleeGroup/focus-core
src/reference/config.js
getConfigElement
function getConfigElement(name) { checkIsString('name', name); if (config.has(name)) { return config.get(name); } }
javascript
function getConfigElement(name) { checkIsString('name', name); if (config.has(name)) { return config.get(name); } }
[ "function", "getConfigElement", "(", "name", ")", "{", "checkIsString", "(", "'name'", ",", "name", ")", ";", "if", "(", "config", ".", "has", "(", "name", ")", ")", "{", "return", "config", ".", "get", "(", "name", ")", ";", "}", "}" ]
Get an element from the configuration using its name. @param {string} name - The key identifier of the configuration. @returns {object} - The configuration of the list element.
[ "Get", "an", "element", "from", "the", "configuration", "using", "its", "name", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/reference/config.js#L45-L50
28,193
terkelg/globrex
index.js
add
function add(str, {split, last, only}={}) { if (only !== 'path') regex += str; if (filepath && only !== 'regex') { path.regex += (str === '\\/' ? SEP : str); if (split) { if (last) segment += str; if (segment !== '') { if (!flags.includes('g')) segment = `^${segment}$`; // change it 'includes' path.segments.push(new RegExp(segment, flags)); } segment = ''; } else { segment += str; } } }
javascript
function add(str, {split, last, only}={}) { if (only !== 'path') regex += str; if (filepath && only !== 'regex') { path.regex += (str === '\\/' ? SEP : str); if (split) { if (last) segment += str; if (segment !== '') { if (!flags.includes('g')) segment = `^${segment}$`; // change it 'includes' path.segments.push(new RegExp(segment, flags)); } segment = ''; } else { segment += str; } } }
[ "function", "add", "(", "str", ",", "{", "split", ",", "last", ",", "only", "}", "=", "{", "}", ")", "{", "if", "(", "only", "!==", "'path'", ")", "regex", "+=", "str", ";", "if", "(", "filepath", "&&", "only", "!==", "'regex'", ")", "{", "path", ".", "regex", "+=", "(", "str", "===", "'\\\\/'", "?", "SEP", ":", "str", ")", ";", "if", "(", "split", ")", "{", "if", "(", "last", ")", "segment", "+=", "str", ";", "if", "(", "segment", "!==", "''", ")", "{", "if", "(", "!", "flags", ".", "includes", "(", "'g'", ")", ")", "segment", "=", "`", "${", "segment", "}", "`", ";", "// change it 'includes'", "path", ".", "segments", ".", "push", "(", "new", "RegExp", "(", "segment", ",", "flags", ")", ")", ";", "}", "segment", "=", "''", ";", "}", "else", "{", "segment", "+=", "str", ";", "}", "}", "}" ]
Helper function to build string and segments
[ "Helper", "function", "to", "build", "string", "and", "segments" ]
891332f350052f5db3e382a13ba6cbd4e9656e51
https://github.com/terkelg/globrex/blob/891332f350052f5db3e382a13ba6cbd4e9656e51/index.js#L34-L49
28,194
KleeGroup/focus-core
src/reference/built-in-action.js
builtInReferenceAction
function builtInReferenceAction(referenceNames, skipCache = false) { return () => { if (!referenceNames) { return undefined; } return Promise.all(loadManyReferenceList(referenceNames, skipCache)) .then(function successReferenceLoading(data) { //Rebuilt a constructed information from the map. const reconstructedData = data.reduce((acc, item) => { acc[item.name] = item.dataList; return acc; }, {}) dispatcher.handleViewAction({ data: reconstructedData, type: 'update', subject: 'reference' }); }, function errorReferenceLoading(err) { dispatcher.handleViewAction({ data: err, type: 'error' }); }); }; }
javascript
function builtInReferenceAction(referenceNames, skipCache = false) { return () => { if (!referenceNames) { return undefined; } return Promise.all(loadManyReferenceList(referenceNames, skipCache)) .then(function successReferenceLoading(data) { //Rebuilt a constructed information from the map. const reconstructedData = data.reduce((acc, item) => { acc[item.name] = item.dataList; return acc; }, {}) dispatcher.handleViewAction({ data: reconstructedData, type: 'update', subject: 'reference' }); }, function errorReferenceLoading(err) { dispatcher.handleViewAction({ data: err, type: 'error' }); }); }; }
[ "function", "builtInReferenceAction", "(", "referenceNames", ",", "skipCache", "=", "false", ")", "{", "return", "(", ")", "=>", "{", "if", "(", "!", "referenceNames", ")", "{", "return", "undefined", ";", "}", "return", "Promise", ".", "all", "(", "loadManyReferenceList", "(", "referenceNames", ",", "skipCache", ")", ")", ".", "then", "(", "function", "successReferenceLoading", "(", "data", ")", "{", "//Rebuilt a constructed information from the map.", "const", "reconstructedData", "=", "data", ".", "reduce", "(", "(", "acc", ",", "item", ")", "=>", "{", "acc", "[", "item", ".", "name", "]", "=", "item", ".", "dataList", ";", "return", "acc", ";", "}", ",", "{", "}", ")", "dispatcher", ".", "handleViewAction", "(", "{", "data", ":", "reconstructedData", ",", "type", ":", "'update'", ",", "subject", ":", "'reference'", "}", ")", ";", "}", ",", "function", "errorReferenceLoading", "(", "err", ")", "{", "dispatcher", ".", "handleViewAction", "(", "{", "data", ":", "err", ",", "type", ":", "'error'", "}", ")", ";", "}", ")", ";", "}", ";", "}" ]
Focus reference action. @param {array} referenceNames - An array which contains the name of all the references to load. @returns {Promise} - The promise of loading all the references.
[ "Focus", "reference", "action", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/reference/built-in-action.js#L9-L23
28,195
KleeGroup/focus-core
src/application/action-builder.js
_preServiceCall
function _preServiceCall({ node, type, preStatus, callerId, shouldDumpStoreOnActionCall }, payload) { //There is a problem if the node is empty. //Node should be an array let data = {}; let status = {}; const STATUS = { name: preStatus, isLoading: true }; type = shouldDumpStoreOnActionCall ? 'update' : 'updateStatus'; // When there is a multi node update it should be an array. if (Array.isArray(node)) { node.forEach((nd) => { data[nd] = shouldDumpStoreOnActionCall ? null : (payload && payload[nd]) || null; status[nd] = STATUS; }); } else { data[node] = shouldDumpStoreOnActionCall ? null : (payload || null); status[node] = STATUS; } //Dispatch store cleaning. dispatcher.handleViewAction({ data, type, status, callerId }); }
javascript
function _preServiceCall({ node, type, preStatus, callerId, shouldDumpStoreOnActionCall }, payload) { //There is a problem if the node is empty. //Node should be an array let data = {}; let status = {}; const STATUS = { name: preStatus, isLoading: true }; type = shouldDumpStoreOnActionCall ? 'update' : 'updateStatus'; // When there is a multi node update it should be an array. if (Array.isArray(node)) { node.forEach((nd) => { data[nd] = shouldDumpStoreOnActionCall ? null : (payload && payload[nd]) || null; status[nd] = STATUS; }); } else { data[node] = shouldDumpStoreOnActionCall ? null : (payload || null); status[node] = STATUS; } //Dispatch store cleaning. dispatcher.handleViewAction({ data, type, status, callerId }); }
[ "function", "_preServiceCall", "(", "{", "node", ",", "type", ",", "preStatus", ",", "callerId", ",", "shouldDumpStoreOnActionCall", "}", ",", "payload", ")", "{", "//There is a problem if the node is empty. //Node should be an array", "let", "data", "=", "{", "}", ";", "let", "status", "=", "{", "}", ";", "const", "STATUS", "=", "{", "name", ":", "preStatus", ",", "isLoading", ":", "true", "}", ";", "type", "=", "shouldDumpStoreOnActionCall", "?", "'update'", ":", "'updateStatus'", ";", "// When there is a multi node update it should be an array.", "if", "(", "Array", ".", "isArray", "(", "node", ")", ")", "{", "node", ".", "forEach", "(", "(", "nd", ")", "=>", "{", "data", "[", "nd", "]", "=", "shouldDumpStoreOnActionCall", "?", "null", ":", "(", "payload", "&&", "payload", "[", "nd", "]", ")", "||", "null", ";", "status", "[", "nd", "]", "=", "STATUS", ";", "}", ")", ";", "}", "else", "{", "data", "[", "node", "]", "=", "shouldDumpStoreOnActionCall", "?", "null", ":", "(", "payload", "||", "null", ")", ";", "status", "[", "node", "]", "=", "STATUS", ";", "}", "//Dispatch store cleaning.", "dispatcher", ".", "handleViewAction", "(", "{", "data", ",", "type", ",", "status", ",", "callerId", "}", ")", ";", "}" ]
Method call before the service. @param {object} config The action builder config. @param {obejct} payload Payload to dispatch.
[ "Method", "call", "before", "the", "service", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/application/action-builder.js#L10-L28
28,196
KleeGroup/focus-core
src/application/action-builder.js
_dispatchServiceResponse
function _dispatchServiceResponse({ node, type, status, callerId }, json) { const isMultiNode = Array.isArray(node); const data = isMultiNode ? json : { [node]: json }; const postStatus = { name: status, isLoading: false }; let newStatus = {}; if (isMultiNode) { node.forEach((nd) => { newStatus[nd] = postStatus; }); } else { newStatus[node] = postStatus; } dispatcher.handleServerAction({ data, type, status: newStatus, callerId }); // Update information similar to store::afterChange return { properties: Object.keys(data), data, status: newStatus, informations: { callerId } }; }
javascript
function _dispatchServiceResponse({ node, type, status, callerId }, json) { const isMultiNode = Array.isArray(node); const data = isMultiNode ? json : { [node]: json }; const postStatus = { name: status, isLoading: false }; let newStatus = {}; if (isMultiNode) { node.forEach((nd) => { newStatus[nd] = postStatus; }); } else { newStatus[node] = postStatus; } dispatcher.handleServerAction({ data, type, status: newStatus, callerId }); // Update information similar to store::afterChange return { properties: Object.keys(data), data, status: newStatus, informations: { callerId } }; }
[ "function", "_dispatchServiceResponse", "(", "{", "node", ",", "type", ",", "status", ",", "callerId", "}", ",", "json", ")", "{", "const", "isMultiNode", "=", "Array", ".", "isArray", "(", "node", ")", ";", "const", "data", "=", "isMultiNode", "?", "json", ":", "{", "[", "node", "]", ":", "json", "}", ";", "const", "postStatus", "=", "{", "name", ":", "status", ",", "isLoading", ":", "false", "}", ";", "let", "newStatus", "=", "{", "}", ";", "if", "(", "isMultiNode", ")", "{", "node", ".", "forEach", "(", "(", "nd", ")", "=>", "{", "newStatus", "[", "nd", "]", "=", "postStatus", ";", "}", ")", ";", "}", "else", "{", "newStatus", "[", "node", "]", "=", "postStatus", ";", "}", "dispatcher", ".", "handleServerAction", "(", "{", "data", ",", "type", ",", "status", ":", "newStatus", ",", "callerId", "}", ")", ";", "// Update information similar to store::afterChange", "return", "{", "properties", ":", "Object", ".", "keys", "(", "data", ")", ",", "data", ",", "status", ":", "newStatus", ",", "informations", ":", "{", "callerId", "}", "}", ";", "}" ]
Method call after the service call. @param {object} config Action builder config. @param {object} json The data return from the service call. @returns {promise} Update information.
[ "Method", "call", "after", "the", "service", "call", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/application/action-builder.js#L36-L60
28,197
KleeGroup/focus-core
src/application/action-builder.js
_dispatchFieldErrors
function _dispatchFieldErrors({ node, callerId }, errorResult) { const isMultiNode = Array.isArray(node); const data = {}; if (isMultiNode) { node.forEach((nd) => { data[nd] = (errorResult || {})[nd] || null; }); } else { data[node] = errorResult; } const errorStatus = { name: 'error', isLoading: false }; let newStatus = {}; if (isMultiNode) { node.forEach((nd) => { newStatus[nd] = errorStatus; }); } else { newStatus[node] = errorStatus; } dispatcher.handleServerAction({ data, type: 'updateError', status: newStatus, callerId }); }
javascript
function _dispatchFieldErrors({ node, callerId }, errorResult) { const isMultiNode = Array.isArray(node); const data = {}; if (isMultiNode) { node.forEach((nd) => { data[nd] = (errorResult || {})[nd] || null; }); } else { data[node] = errorResult; } const errorStatus = { name: 'error', isLoading: false }; let newStatus = {}; if (isMultiNode) { node.forEach((nd) => { newStatus[nd] = errorStatus; }); } else { newStatus[node] = errorStatus; } dispatcher.handleServerAction({ data, type: 'updateError', status: newStatus, callerId }); }
[ "function", "_dispatchFieldErrors", "(", "{", "node", ",", "callerId", "}", ",", "errorResult", ")", "{", "const", "isMultiNode", "=", "Array", ".", "isArray", "(", "node", ")", ";", "const", "data", "=", "{", "}", ";", "if", "(", "isMultiNode", ")", "{", "node", ".", "forEach", "(", "(", "nd", ")", "=>", "{", "data", "[", "nd", "]", "=", "(", "errorResult", "||", "{", "}", ")", "[", "nd", "]", "||", "null", ";", "}", ")", ";", "}", "else", "{", "data", "[", "node", "]", "=", "errorResult", ";", "}", "const", "errorStatus", "=", "{", "name", ":", "'error'", ",", "isLoading", ":", "false", "}", ";", "let", "newStatus", "=", "{", "}", ";", "if", "(", "isMultiNode", ")", "{", "node", ".", "forEach", "(", "(", "nd", ")", "=>", "{", "newStatus", "[", "nd", "]", "=", "errorStatus", ";", "}", ")", ";", "}", "else", "{", "newStatus", "[", "node", "]", "=", "errorStatus", ";", "}", "dispatcher", ".", "handleServerAction", "(", "{", "data", ",", "type", ":", "'updateError'", ",", "status", ":", "newStatus", ",", "callerId", "}", ")", ";", "}" ]
The main objective of this function is to cancel the loading state on all the nodes concerned by the service call. @param {obejct} config Action builder config. @param {object} errorResult Error returned.
[ "The", "main", "objective", "of", "this", "function", "is", "to", "cancel", "the", "loading", "state", "on", "all", "the", "nodes", "concerned", "by", "the", "service", "call", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/application/action-builder.js#L67-L96
28,198
KleeGroup/focus-core
src/application/action-builder.js
_errorOnCall
function _errorOnCall(config, err) { const errorResult = manageResponseErrors(err, config); _dispatchFieldErrors(config, errorResult.fields); }
javascript
function _errorOnCall(config, err) { const errorResult = manageResponseErrors(err, config); _dispatchFieldErrors(config, errorResult.fields); }
[ "function", "_errorOnCall", "(", "config", ",", "err", ")", "{", "const", "errorResult", "=", "manageResponseErrors", "(", "err", ",", "config", ")", ";", "_dispatchFieldErrors", "(", "config", ",", "errorResult", ".", "fields", ")", ";", "}" ]
Method call when there is an error. @param {object} config The action builder configuration. @param {object} err The error from the API call.
[ "Method", "call", "when", "there", "is", "an", "error", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/application/action-builder.js#L103-L106
28,199
KleeGroup/focus-core
src/site-description/builder.js
_processName
function _processName(pfx, eltDescName) { if (pfx === undefined || pfx === null) { pfx = EMPTY; } if (eltDescName === undefined || eltDescName === null) { return pfx; } if (pfx === EMPTY) { return eltDescName; } return pfx + '.' + eltDescName; }
javascript
function _processName(pfx, eltDescName) { if (pfx === undefined || pfx === null) { pfx = EMPTY; } if (eltDescName === undefined || eltDescName === null) { return pfx; } if (pfx === EMPTY) { return eltDescName; } return pfx + '.' + eltDescName; }
[ "function", "_processName", "(", "pfx", ",", "eltDescName", ")", "{", "if", "(", "pfx", "===", "undefined", "||", "pfx", "===", "null", ")", "{", "pfx", "=", "EMPTY", ";", "}", "if", "(", "eltDescName", "===", "undefined", "||", "eltDescName", "===", "null", ")", "{", "return", "pfx", ";", "}", "if", "(", "pfx", "===", "EMPTY", ")", "{", "return", "eltDescName", ";", "}", "return", "pfx", "+", "'.'", "+", "eltDescName", ";", "}" ]
Process the name of
[ "Process", "the", "name", "of" ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/site-description/builder.js#L13-L24