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
36,900
bigpipe/bigpipe.js
collection.js
each
function each(collection, iterator, context) { var i = 0; if ('array' === type(collection)) { for (; i < collection.length; i++) { if (false === iterator.call(context || iterator, collection[i], i, collection)) { return; // If false is returned by the callback we need to bail out. } } } else { for (i in collection) { if (hasOwn.call(collection, i)) { if (false === iterator.call(context || iterator, collection[i], i, collection)) { return; // If false is returned by the callback we need to bail out. } } } } }
javascript
function each(collection, iterator, context) { var i = 0; if ('array' === type(collection)) { for (; i < collection.length; i++) { if (false === iterator.call(context || iterator, collection[i], i, collection)) { return; // If false is returned by the callback we need to bail out. } } } else { for (i in collection) { if (hasOwn.call(collection, i)) { if (false === iterator.call(context || iterator, collection[i], i, collection)) { return; // If false is returned by the callback we need to bail out. } } } } }
[ "function", "each", "(", "collection", ",", "iterator", ",", "context", ")", "{", "var", "i", "=", "0", ";", "if", "(", "'array'", "===", "type", "(", "collection", ")", ")", "{", "for", "(", ";", "i", "<", "collection", ".", "length", ";", "i", "++", ")", "{", "if", "(", "false", "===", "iterator", ".", "call", "(", "context", "||", "iterator", ",", "collection", "[", "i", "]", ",", "i", ",", "collection", ")", ")", "{", "return", ";", "// If false is returned by the callback we need to bail out.", "}", "}", "}", "else", "{", "for", "(", "i", "in", "collection", ")", "{", "if", "(", "hasOwn", ".", "call", "(", "collection", ",", "i", ")", ")", "{", "if", "(", "false", "===", "iterator", ".", "call", "(", "context", "||", "iterator", ",", "collection", "[", "i", "]", ",", "i", ",", "collection", ")", ")", "{", "return", ";", "// If false is returned by the callback we need to bail out.", "}", "}", "}", "}", "}" ]
Iterate over a collection. @param {Mixed} collection The object we want to iterate over. @param {Function} iterator The function that's called for each iteration. @param {Mixed} context The context of the function. @api public
[ "Iterate", "over", "a", "collection", "." ]
80fe2630d363ed2b69f85d28792a9095a4167e3b
https://github.com/bigpipe/bigpipe.js/blob/80fe2630d363ed2b69f85d28792a9095a4167e3b/collection.js#L25-L43
36,901
bigpipe/bigpipe.js
collection.js
size
function size(collection) { var x, i = 0; if ('object' === type(collection)) { for (x in collection) i++; return i; } return +collection.length; }
javascript
function size(collection) { var x, i = 0; if ('object' === type(collection)) { for (x in collection) i++; return i; } return +collection.length; }
[ "function", "size", "(", "collection", ")", "{", "var", "x", ",", "i", "=", "0", ";", "if", "(", "'object'", "===", "type", "(", "collection", ")", ")", "{", "for", "(", "x", "in", "collection", ")", "i", "++", ";", "return", "i", ";", "}", "return", "+", "collection", ".", "length", ";", "}" ]
Determine the size of a collection. @param {Mixed} collection The object we want to know the size of. @returns {Number} The size of the collection. @api public
[ "Determine", "the", "size", "of", "a", "collection", "." ]
80fe2630d363ed2b69f85d28792a9095a4167e3b
https://github.com/bigpipe/bigpipe.js/blob/80fe2630d363ed2b69f85d28792a9095a4167e3b/collection.js#L67-L76
36,902
bigpipe/bigpipe.js
collection.js
array
function array(obj) { if ('array' === type(obj)) return obj; if ('arguments' === type(obj)) return Array.prototype.slice.call(obj, 0); return obj // Only transform objects in to an array when they exist. ? [obj] : []; }
javascript
function array(obj) { if ('array' === type(obj)) return obj; if ('arguments' === type(obj)) return Array.prototype.slice.call(obj, 0); return obj // Only transform objects in to an array when they exist. ? [obj] : []; }
[ "function", "array", "(", "obj", ")", "{", "if", "(", "'array'", "===", "type", "(", "obj", ")", ")", "return", "obj", ";", "if", "(", "'arguments'", "===", "type", "(", "obj", ")", ")", "return", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "obj", ",", "0", ")", ";", "return", "obj", "// Only transform objects in to an array when they exist.", "?", "[", "obj", "]", ":", "[", "]", ";", "}" ]
Wrap the given object in an array if it's not an array already. @param {Mixed} obj The thing we might need to wrap. @returns {Array} We promise! @api public
[ "Wrap", "the", "given", "object", "in", "an", "array", "if", "it", "s", "not", "an", "array", "already", "." ]
80fe2630d363ed2b69f85d28792a9095a4167e3b
https://github.com/bigpipe/bigpipe.js/blob/80fe2630d363ed2b69f85d28792a9095a4167e3b/collection.js#L85-L92
36,903
bigpipe/bigpipe.js
collection.js
copy
function copy() { var result = {} , depth = 2 , seen = []; (function worker() { each(array(arguments), function each(obj) { for (var prop in obj) { if (hasOwn.call(obj, prop) && !~index(seen, obj[prop])) { if (type(obj[prop]) !== 'object' || !depth) { result[prop] = obj[prop]; seen.push(obj[prop]); } else { depth--; worker(result[prop], obj[prop]); } } } }); }).apply(null, arguments); return result; }
javascript
function copy() { var result = {} , depth = 2 , seen = []; (function worker() { each(array(arguments), function each(obj) { for (var prop in obj) { if (hasOwn.call(obj, prop) && !~index(seen, obj[prop])) { if (type(obj[prop]) !== 'object' || !depth) { result[prop] = obj[prop]; seen.push(obj[prop]); } else { depth--; worker(result[prop], obj[prop]); } } } }); }).apply(null, arguments); return result; }
[ "function", "copy", "(", ")", "{", "var", "result", "=", "{", "}", ",", "depth", "=", "2", ",", "seen", "=", "[", "]", ";", "(", "function", "worker", "(", ")", "{", "each", "(", "array", "(", "arguments", ")", ",", "function", "each", "(", "obj", ")", "{", "for", "(", "var", "prop", "in", "obj", ")", "{", "if", "(", "hasOwn", ".", "call", "(", "obj", ",", "prop", ")", "&&", "!", "~", "index", "(", "seen", ",", "obj", "[", "prop", "]", ")", ")", "{", "if", "(", "type", "(", "obj", "[", "prop", "]", ")", "!==", "'object'", "||", "!", "depth", ")", "{", "result", "[", "prop", "]", "=", "obj", "[", "prop", "]", ";", "seen", ".", "push", "(", "obj", "[", "prop", "]", ")", ";", "}", "else", "{", "depth", "--", ";", "worker", "(", "result", "[", "prop", "]", ",", "obj", "[", "prop", "]", ")", ";", "}", "}", "}", "}", ")", ";", "}", ")", ".", "apply", "(", "null", ",", "arguments", ")", ";", "return", "result", ";", "}" ]
Merge all given objects in to one objects. @returns {Object} @api public
[ "Merge", "all", "given", "objects", "in", "to", "one", "objects", "." ]
80fe2630d363ed2b69f85d28792a9095a4167e3b
https://github.com/bigpipe/bigpipe.js/blob/80fe2630d363ed2b69f85d28792a9095a4167e3b/collection.js#L122-L144
36,904
Karnith/machinepack-sailsgulpify
machines/sails-gulpify.js
function (userInput){ var firstTimeRun = userInput.toLowerCase(); if(firstTimeRun === 'yes'){ createGulpFile({ gulpFileSrcPath: '../templates/gulpfile.js', outputDir: '../../../gulpfile.js' }).exec({ error: function (err){ console.error('an error occurred- error details:',err); return exits.error(); }, invalid: function (){ exits.invalid() }, success: function() { createGulpTasks({ gulpFolderSrcPath: '../templates/tasks-gulp', outputFolderDir: '../../../tasks-gulp' }).exec({ error: function (err){ console.error('an error occurred- error details:',err); return exits.error(); }, invalid: function (){ exits.invalid() }, success: function() { createGulpEngine({ gulpFolderSrcPath: '../lib/gulp', outputDir: '../../sails/lib/hooks/gulp' //outputDir: '../../../api/hooks/gulp' }).exec({ error: function (err){ console.error('an error occurred- error details:',err); return exits.error(); }, invalid: function (){ exits.invalid() }, success: function() { // return exits.success(); toggleSailsrc({ sailsrcSrc: '../json/gulp.sailsrc', outputDir: '../../../.sailsrc' }).exec({ error: function (err){ console.error('an error occurred- error details:',err); return exits.error(); }, invalid: function (){ exits.invalid() }, success: function() { // return exits.success(); installGulpDependencies({ }).exec({ error: function (err){ console.error('an error occurred- error details:',err); return exits.error(); }, invalid: function (){ exits.invalid() }, success: function() { return exits.success(); } }); } }); } }); } }); } }); } else if(firstTimeRun === 'no') { createGulpEngine({ gulpFolderSrcPath: '../lib/gulp', outputDir: '../../sails/lib/hooks/gulp' //outputDir: '../../../api/hooks/gulp' }).exec({ error: function (err){ console.error('an error occurred- error details:',err); return exits.error(); }, invalid: function (){ exits.invalid() }, success: function() { return exits.success(); } }); } }
javascript
function (userInput){ var firstTimeRun = userInput.toLowerCase(); if(firstTimeRun === 'yes'){ createGulpFile({ gulpFileSrcPath: '../templates/gulpfile.js', outputDir: '../../../gulpfile.js' }).exec({ error: function (err){ console.error('an error occurred- error details:',err); return exits.error(); }, invalid: function (){ exits.invalid() }, success: function() { createGulpTasks({ gulpFolderSrcPath: '../templates/tasks-gulp', outputFolderDir: '../../../tasks-gulp' }).exec({ error: function (err){ console.error('an error occurred- error details:',err); return exits.error(); }, invalid: function (){ exits.invalid() }, success: function() { createGulpEngine({ gulpFolderSrcPath: '../lib/gulp', outputDir: '../../sails/lib/hooks/gulp' //outputDir: '../../../api/hooks/gulp' }).exec({ error: function (err){ console.error('an error occurred- error details:',err); return exits.error(); }, invalid: function (){ exits.invalid() }, success: function() { // return exits.success(); toggleSailsrc({ sailsrcSrc: '../json/gulp.sailsrc', outputDir: '../../../.sailsrc' }).exec({ error: function (err){ console.error('an error occurred- error details:',err); return exits.error(); }, invalid: function (){ exits.invalid() }, success: function() { // return exits.success(); installGulpDependencies({ }).exec({ error: function (err){ console.error('an error occurred- error details:',err); return exits.error(); }, invalid: function (){ exits.invalid() }, success: function() { return exits.success(); } }); } }); } }); } }); } }); } else if(firstTimeRun === 'no') { createGulpEngine({ gulpFolderSrcPath: '../lib/gulp', outputDir: '../../sails/lib/hooks/gulp' //outputDir: '../../../api/hooks/gulp' }).exec({ error: function (err){ console.error('an error occurred- error details:',err); return exits.error(); }, invalid: function (){ exits.invalid() }, success: function() { return exits.success(); } }); } }
[ "function", "(", "userInput", ")", "{", "var", "firstTimeRun", "=", "userInput", ".", "toLowerCase", "(", ")", ";", "if", "(", "firstTimeRun", "===", "'yes'", ")", "{", "createGulpFile", "(", "{", "gulpFileSrcPath", ":", "'../templates/gulpfile.js'", ",", "outputDir", ":", "'../../../gulpfile.js'", "}", ")", ".", "exec", "(", "{", "error", ":", "function", "(", "err", ")", "{", "console", ".", "error", "(", "'an error occurred- error details:'", ",", "err", ")", ";", "return", "exits", ".", "error", "(", ")", ";", "}", ",", "invalid", ":", "function", "(", ")", "{", "exits", ".", "invalid", "(", ")", "}", ",", "success", ":", "function", "(", ")", "{", "createGulpTasks", "(", "{", "gulpFolderSrcPath", ":", "'../templates/tasks-gulp'", ",", "outputFolderDir", ":", "'../../../tasks-gulp'", "}", ")", ".", "exec", "(", "{", "error", ":", "function", "(", "err", ")", "{", "console", ".", "error", "(", "'an error occurred- error details:'", ",", "err", ")", ";", "return", "exits", ".", "error", "(", ")", ";", "}", ",", "invalid", ":", "function", "(", ")", "{", "exits", ".", "invalid", "(", ")", "}", ",", "success", ":", "function", "(", ")", "{", "createGulpEngine", "(", "{", "gulpFolderSrcPath", ":", "'../lib/gulp'", ",", "outputDir", ":", "'../../sails/lib/hooks/gulp'", "//outputDir: '../../../api/hooks/gulp'", "}", ")", ".", "exec", "(", "{", "error", ":", "function", "(", "err", ")", "{", "console", ".", "error", "(", "'an error occurred- error details:'", ",", "err", ")", ";", "return", "exits", ".", "error", "(", ")", ";", "}", ",", "invalid", ":", "function", "(", ")", "{", "exits", ".", "invalid", "(", ")", "}", ",", "success", ":", "function", "(", ")", "{", "// return exits.success();", "toggleSailsrc", "(", "{", "sailsrcSrc", ":", "'../json/gulp.sailsrc'", ",", "outputDir", ":", "'../../../.sailsrc'", "}", ")", ".", "exec", "(", "{", "error", ":", "function", "(", "err", ")", "{", "console", ".", "error", "(", "'an error occurred- error details:'", ",", "err", ")", ";", "return", "exits", ".", "error", "(", ")", ";", "}", ",", "invalid", ":", "function", "(", ")", "{", "exits", ".", "invalid", "(", ")", "}", ",", "success", ":", "function", "(", ")", "{", "// return exits.success();", "installGulpDependencies", "(", "{", "}", ")", ".", "exec", "(", "{", "error", ":", "function", "(", "err", ")", "{", "console", ".", "error", "(", "'an error occurred- error details:'", ",", "err", ")", ";", "return", "exits", ".", "error", "(", ")", ";", "}", ",", "invalid", ":", "function", "(", ")", "{", "exits", ".", "invalid", "(", ")", "}", ",", "success", ":", "function", "(", ")", "{", "return", "exits", ".", "success", "(", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}", "else", "if", "(", "firstTimeRun", "===", "'no'", ")", "{", "createGulpEngine", "(", "{", "gulpFolderSrcPath", ":", "'../lib/gulp'", ",", "outputDir", ":", "'../../sails/lib/hooks/gulp'", "//outputDir: '../../../api/hooks/gulp'", "}", ")", ".", "exec", "(", "{", "error", ":", "function", "(", "err", ")", "{", "console", ".", "error", "(", "'an error occurred- error details:'", ",", "err", ")", ";", "return", "exits", ".", "error", "(", ")", ";", "}", ",", "invalid", ":", "function", "(", ")", "{", "exits", ".", "invalid", "(", ")", "}", ",", "success", ":", "function", "(", ")", "{", "return", "exits", ".", "success", "(", ")", ";", "}", "}", ")", ";", "}", "}" ]
OK- got user input.
[ "OK", "-", "got", "user", "input", "." ]
38424f98d59cac4240e676159bd25e3bc82ad8ac
https://github.com/Karnith/machinepack-sailsgulpify/blob/38424f98d59cac4240e676159bd25e3bc82ad8ac/machines/sails-gulpify.js#L51-L133
36,905
ramonvictor/gulp-protractor-qa
index.js
readFiles
function readFiles() { /* jshint validthis:true */ var self = this; async.waterfall([ function(callback) { storeFileContent.init(self.options.testSrc, callback); }, function(data, callback) { self.testFiles = data; storeFileContent.init(self.options.viewSrc, callback); }, function(data, callback) { self.viewFiles = data; callback(null, 'success'); } ], function() { findElementSelectors.call(self); }); }
javascript
function readFiles() { /* jshint validthis:true */ var self = this; async.waterfall([ function(callback) { storeFileContent.init(self.options.testSrc, callback); }, function(data, callback) { self.testFiles = data; storeFileContent.init(self.options.viewSrc, callback); }, function(data, callback) { self.viewFiles = data; callback(null, 'success'); } ], function() { findElementSelectors.call(self); }); }
[ "function", "readFiles", "(", ")", "{", "/* jshint validthis:true */", "var", "self", "=", "this", ";", "async", ".", "waterfall", "(", "[", "function", "(", "callback", ")", "{", "storeFileContent", ".", "init", "(", "self", ".", "options", ".", "testSrc", ",", "callback", ")", ";", "}", ",", "function", "(", "data", ",", "callback", ")", "{", "self", ".", "testFiles", "=", "data", ";", "storeFileContent", ".", "init", "(", "self", ".", "options", ".", "viewSrc", ",", "callback", ")", ";", "}", ",", "function", "(", "data", ",", "callback", ")", "{", "self", ".", "viewFiles", "=", "data", ";", "callback", "(", "null", ",", "'success'", ")", ";", "}", "]", ",", "function", "(", ")", "{", "findElementSelectors", ".", "call", "(", "self", ")", ";", "}", ")", ";", "}" ]
Read `testSrc` and `viewSrc` files content.
[ "Read", "testSrc", "and", "viewSrc", "files", "content", "." ]
b5a462649bb9cbdcd9d852d865bb05f120cff84d
https://github.com/ramonvictor/gulp-protractor-qa/blob/b5a462649bb9cbdcd9d852d865bb05f120cff84d/index.js#L53-L72
36,906
lemire/TypedFastBitSet.js
TypedFastBitSet.js
TypedFastBitSet
function TypedFastBitSet(iterable) { this.count = 0 | 0; this.words = new Uint32Array(8); if (isIterable(iterable)) { for (var key of iterable) { this.add(key); } } }
javascript
function TypedFastBitSet(iterable) { this.count = 0 | 0; this.words = new Uint32Array(8); if (isIterable(iterable)) { for (var key of iterable) { this.add(key); } } }
[ "function", "TypedFastBitSet", "(", "iterable", ")", "{", "this", ".", "count", "=", "0", "|", "0", ";", "this", ".", "words", "=", "new", "Uint32Array", "(", "8", ")", ";", "if", "(", "isIterable", "(", "iterable", ")", ")", "{", "for", "(", "var", "key", "of", "iterable", ")", "{", "this", ".", "add", "(", "key", ")", ";", "}", "}", "}" ]
you can provide an iterable an exception is thrown if typed arrays are not supported
[ "you", "can", "provide", "an", "iterable", "an", "exception", "is", "thrown", "if", "typed", "arrays", "are", "not", "supported" ]
7f325b54ab9384aa590c2a85d97e46f3ffa5884b
https://github.com/lemire/TypedFastBitSet.js/blob/7f325b54ab9384aa590c2a85d97e46f3ffa5884b/TypedFastBitSet.js#L47-L55
36,907
WorldMobileCoin/wmcc-core
src/script/script.js
Script
function Script(options) { if (!(this instanceof Script)) return new Script(options); this.raw = EMPTY_BUFFER; this.code = []; if (options) this.fromOptions(options); }
javascript
function Script(options) { if (!(this instanceof Script)) return new Script(options); this.raw = EMPTY_BUFFER; this.code = []; if (options) this.fromOptions(options); }
[ "function", "Script", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Script", ")", ")", "return", "new", "Script", "(", "options", ")", ";", "this", ".", "raw", "=", "EMPTY_BUFFER", ";", "this", ".", "code", "=", "[", "]", ";", "if", "(", "options", ")", "this", ".", "fromOptions", "(", "options", ")", ";", "}" ]
Represents a input or output script. @alias module:script.Script @constructor @param {Buffer|Array|Object|NakedScript} code - Array of script code or a serialized script Buffer. @property {Array} code - Parsed script code. @property {Buffer?} raw - Serialized script. @property {Number} length - Number of parsed opcodes.
[ "Represents", "a", "input", "or", "output", "script", "." ]
29c3759a175341cedae6b744c53eda628c669317
https://github.com/WorldMobileCoin/wmcc-core/blob/29c3759a175341cedae6b744c53eda628c669317/src/script/script.js#L48-L57
36,908
WorldMobileCoin/wmcc-core
src/script/script.js
validateKey
function validateKey(key, flags, version) { assert(Buffer.isBuffer(key)); assert(typeof flags === 'number'); assert(typeof version === 'number'); if (flags & Script.flags.VERIFY_STRICTENC) { if (!common.isKeyEncoding(key)) throw new ScriptError('PUBKEYTYPE'); } if (version === 1) { if (flags & Script.flags.VERIFY_WITNESS_PUBKEYTYPE) { if (!common.isCompressedEncoding(key)) throw new ScriptError('WITNESS_PUBKEYTYPE'); } } return true; }
javascript
function validateKey(key, flags, version) { assert(Buffer.isBuffer(key)); assert(typeof flags === 'number'); assert(typeof version === 'number'); if (flags & Script.flags.VERIFY_STRICTENC) { if (!common.isKeyEncoding(key)) throw new ScriptError('PUBKEYTYPE'); } if (version === 1) { if (flags & Script.flags.VERIFY_WITNESS_PUBKEYTYPE) { if (!common.isCompressedEncoding(key)) throw new ScriptError('WITNESS_PUBKEYTYPE'); } } return true; }
[ "function", "validateKey", "(", "key", ",", "flags", ",", "version", ")", "{", "assert", "(", "Buffer", ".", "isBuffer", "(", "key", ")", ")", ";", "assert", "(", "typeof", "flags", "===", "'number'", ")", ";", "assert", "(", "typeof", "version", "===", "'number'", ")", ";", "if", "(", "flags", "&", "Script", ".", "flags", ".", "VERIFY_STRICTENC", ")", "{", "if", "(", "!", "common", ".", "isKeyEncoding", "(", "key", ")", ")", "throw", "new", "ScriptError", "(", "'PUBKEYTYPE'", ")", ";", "}", "if", "(", "version", "===", "1", ")", "{", "if", "(", "flags", "&", "Script", ".", "flags", ".", "VERIFY_WITNESS_PUBKEYTYPE", ")", "{", "if", "(", "!", "common", ".", "isCompressedEncoding", "(", "key", ")", ")", "throw", "new", "ScriptError", "(", "'WITNESS_PUBKEYTYPE'", ")", ";", "}", "}", "return", "true", ";", "}" ]
Test whether the data element is a valid key if VERIFY_STRICTENC is enabled. @param {Buffer} key @param {VerifyFlags?} flags @returns {Boolean} @throws {ScriptError}
[ "Test", "whether", "the", "data", "element", "is", "a", "valid", "key", "if", "VERIFY_STRICTENC", "is", "enabled", "." ]
29c3759a175341cedae6b744c53eda628c669317
https://github.com/WorldMobileCoin/wmcc-core/blob/29c3759a175341cedae6b744c53eda628c669317/src/script/script.js#L3558-L3576
36,909
WorldMobileCoin/wmcc-core
src/script/script.js
validateSignature
function validateSignature(sig, flags) { assert(Buffer.isBuffer(sig)); assert(typeof flags === 'number'); // Allow empty sigs if (sig.length === 0) return true; if ((flags & Script.flags.VERIFY_DERSIG) || (flags & Script.flags.VERIFY_LOW_S) || (flags & Script.flags.VERIFY_STRICTENC)) { if (!common.isSignatureEncoding(sig)) throw new ScriptError('SIG_DER'); } if (flags & Script.flags.VERIFY_LOW_S) { if (!common.isLowDER(sig)) throw new ScriptError('SIG_HIGH_S'); } if (flags & Script.flags.VERIFY_STRICTENC) { if (!common.isHashType(sig)) throw new ScriptError('SIG_HASHTYPE'); } return true; }
javascript
function validateSignature(sig, flags) { assert(Buffer.isBuffer(sig)); assert(typeof flags === 'number'); // Allow empty sigs if (sig.length === 0) return true; if ((flags & Script.flags.VERIFY_DERSIG) || (flags & Script.flags.VERIFY_LOW_S) || (flags & Script.flags.VERIFY_STRICTENC)) { if (!common.isSignatureEncoding(sig)) throw new ScriptError('SIG_DER'); } if (flags & Script.flags.VERIFY_LOW_S) { if (!common.isLowDER(sig)) throw new ScriptError('SIG_HIGH_S'); } if (flags & Script.flags.VERIFY_STRICTENC) { if (!common.isHashType(sig)) throw new ScriptError('SIG_HASHTYPE'); } return true; }
[ "function", "validateSignature", "(", "sig", ",", "flags", ")", "{", "assert", "(", "Buffer", ".", "isBuffer", "(", "sig", ")", ")", ";", "assert", "(", "typeof", "flags", "===", "'number'", ")", ";", "// Allow empty sigs", "if", "(", "sig", ".", "length", "===", "0", ")", "return", "true", ";", "if", "(", "(", "flags", "&", "Script", ".", "flags", ".", "VERIFY_DERSIG", ")", "||", "(", "flags", "&", "Script", ".", "flags", ".", "VERIFY_LOW_S", ")", "||", "(", "flags", "&", "Script", ".", "flags", ".", "VERIFY_STRICTENC", ")", ")", "{", "if", "(", "!", "common", ".", "isSignatureEncoding", "(", "sig", ")", ")", "throw", "new", "ScriptError", "(", "'SIG_DER'", ")", ";", "}", "if", "(", "flags", "&", "Script", ".", "flags", ".", "VERIFY_LOW_S", ")", "{", "if", "(", "!", "common", ".", "isLowDER", "(", "sig", ")", ")", "throw", "new", "ScriptError", "(", "'SIG_HIGH_S'", ")", ";", "}", "if", "(", "flags", "&", "Script", ".", "flags", ".", "VERIFY_STRICTENC", ")", "{", "if", "(", "!", "common", ".", "isHashType", "(", "sig", ")", ")", "throw", "new", "ScriptError", "(", "'SIG_HASHTYPE'", ")", ";", "}", "return", "true", ";", "}" ]
Test whether the data element is a valid signature based on the encoding, S value, and sighash type. Requires VERIFY_DERSIG|VERIFY_LOW_S|VERIFY_STRICTENC, VERIFY_LOW_S and VERIFY_STRING_ENC to be enabled respectively. Note that this will allow zero-length signatures. @param {Buffer} sig @param {VerifyFlags?} flags @returns {Boolean} @throws {ScriptError}
[ "Test", "whether", "the", "data", "element", "is", "a", "valid", "signature", "based", "on", "the", "encoding", "S", "value", "and", "sighash", "type", ".", "Requires", "VERIFY_DERSIG|VERIFY_LOW_S|VERIFY_STRICTENC", "VERIFY_LOW_S", "and", "VERIFY_STRING_ENC", "to", "be", "enabled", "respectively", ".", "Note", "that", "this", "will", "allow", "zero", "-", "length", "signatures", "." ]
29c3759a175341cedae6b744c53eda628c669317
https://github.com/WorldMobileCoin/wmcc-core/blob/29c3759a175341cedae6b744c53eda628c669317/src/script/script.js#L3590-L3616
36,910
WorldMobileCoin/wmcc-core
src/script/script.js
checksig
function checksig(msg, sig, key) { return secp256k1.verify(msg, sig.slice(0, -1), key); }
javascript
function checksig(msg, sig, key) { return secp256k1.verify(msg, sig.slice(0, -1), key); }
[ "function", "checksig", "(", "msg", ",", "sig", ",", "key", ")", "{", "return", "secp256k1", ".", "verify", "(", "msg", ",", "sig", ".", "slice", "(", "0", ",", "-", "1", ")", ",", "key", ")", ";", "}" ]
Verify a signature, taking into account sighash type. @param {Buffer} msg - Signature hash. @param {Buffer} sig @param {Buffer} key @returns {Boolean}
[ "Verify", "a", "signature", "taking", "into", "account", "sighash", "type", "." ]
29c3759a175341cedae6b744c53eda628c669317
https://github.com/WorldMobileCoin/wmcc-core/blob/29c3759a175341cedae6b744c53eda628c669317/src/script/script.js#L3626-L3628
36,911
WorldMobileCoin/wmcc-core
src/workers/master.js
Master
function Master() { if (!(this instanceof Master)) return new Master(); EventEmitter.call(this); this.parent = new Parent(); this.framer = new Framer(); this.parser = new Parser(); this.listening = false; this.color = false; this.init(); }
javascript
function Master() { if (!(this instanceof Master)) return new Master(); EventEmitter.call(this); this.parent = new Parent(); this.framer = new Framer(); this.parser = new Parser(); this.listening = false; this.color = false; this.init(); }
[ "function", "Master", "(", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Master", ")", ")", "return", "new", "Master", "(", ")", ";", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "parent", "=", "new", "Parent", "(", ")", ";", "this", ".", "framer", "=", "new", "Framer", "(", ")", ";", "this", ".", "parser", "=", "new", "Parser", "(", ")", ";", "this", ".", "listening", "=", "false", ";", "this", ".", "color", "=", "false", ";", "this", ".", "init", "(", ")", ";", "}" ]
Represents the master process. @alias module:workers.Master @constructor
[ "Represents", "the", "master", "process", "." ]
29c3759a175341cedae6b744c53eda628c669317
https://github.com/WorldMobileCoin/wmcc-core/blob/29c3759a175341cedae6b744c53eda628c669317/src/workers/master.js#L30-L43
36,912
WorldMobileCoin/wmcc-core
src/primitives/block.js
Block
function Block(options) { if (!(this instanceof Block)) return new Block(options); AbstractBlock.call(this); this.txs = []; this._raw = null; this._size = -1; this._witness = -1; if (options) this.fromOptions(options); }
javascript
function Block(options) { if (!(this instanceof Block)) return new Block(options); AbstractBlock.call(this); this.txs = []; this._raw = null; this._size = -1; this._witness = -1; if (options) this.fromOptions(options); }
[ "function", "Block", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Block", ")", ")", "return", "new", "Block", "(", "options", ")", ";", "AbstractBlock", ".", "call", "(", "this", ")", ";", "this", ".", "txs", "=", "[", "]", ";", "this", ".", "_raw", "=", "null", ";", "this", ".", "_size", "=", "-", "1", ";", "this", ".", "_witness", "=", "-", "1", ";", "if", "(", "options", ")", "this", ".", "fromOptions", "(", "options", ")", ";", "}" ]
Represents a full block. @alias module:primitives.Block @constructor @extends AbstractBlock @param {NakedBlock} options
[ "Represents", "a", "full", "block", "." ]
29c3759a175341cedae6b744c53eda628c669317
https://github.com/WorldMobileCoin/wmcc-core/blob/29c3759a175341cedae6b744c53eda628c669317/src/primitives/block.js#L36-L50
36,913
GitbookIO/tokenize-english
lib/index.js
isNameAbbreviation
function isNameAbbreviation(wordCount, words) { if (words.length > 0) { if (wordCount < 5 && words[0].length < 6 && isCapitalized(words[0])) { return true; } var capitalized = words.filter(function(str) { return /[A-Z]/.test(str.charAt(0)); }); return capitalized.length >= 3; } return false; }
javascript
function isNameAbbreviation(wordCount, words) { if (words.length > 0) { if (wordCount < 5 && words[0].length < 6 && isCapitalized(words[0])) { return true; } var capitalized = words.filter(function(str) { return /[A-Z]/.test(str.charAt(0)); }); return capitalized.length >= 3; } return false; }
[ "function", "isNameAbbreviation", "(", "wordCount", ",", "words", ")", "{", "if", "(", "words", ".", "length", ">", "0", ")", "{", "if", "(", "wordCount", "<", "5", "&&", "words", "[", "0", "]", ".", "length", "<", "6", "&&", "isCapitalized", "(", "words", "[", "0", "]", ")", ")", "{", "return", "true", ";", "}", "var", "capitalized", "=", "words", ".", "filter", "(", "function", "(", "str", ")", "{", "return", "/", "[A-Z]", "/", ".", "test", "(", "str", ".", "charAt", "(", "0", ")", ")", ";", "}", ")", ";", "return", "capitalized", ".", "length", ">=", "3", ";", "}", "return", "false", ";", "}" ]
Uses current word count in sentence and next few words to check if it is more likely an abbreviation + name or new sentence.
[ "Uses", "current", "word", "count", "in", "sentence", "and", "next", "few", "words", "to", "check", "if", "it", "is", "more", "likely", "an", "abbreviation", "+", "name", "or", "new", "sentence", "." ]
ea78d188e73b6a9161f876c434e24c02cebbfa3e
https://github.com/GitbookIO/tokenize-english/blob/ea78d188e73b6a9161f876c434e24c02cebbfa3e/lib/index.js#L58-L72
36,914
WorldMobileCoin/wmcc-core
src/utils/asyncobject.js
AsyncObject
function AsyncObject() { assert(this instanceof AsyncObject); EventEmitter.call(this); this._asyncLock = new Lock(); this._hooks = Object.create(null); this.loading = false; this.closing = false; this.loaded = false; }
javascript
function AsyncObject() { assert(this instanceof AsyncObject); EventEmitter.call(this); this._asyncLock = new Lock(); this._hooks = Object.create(null); this.loading = false; this.closing = false; this.loaded = false; }
[ "function", "AsyncObject", "(", ")", "{", "assert", "(", "this", "instanceof", "AsyncObject", ")", ";", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "_asyncLock", "=", "new", "Lock", "(", ")", ";", "this", ".", "_hooks", "=", "Object", ".", "create", "(", "null", ")", ";", "this", ".", "loading", "=", "false", ";", "this", ".", "closing", "=", "false", ";", "this", ".", "loaded", "=", "false", ";", "}" ]
An abstract object that handles state and provides recallable open and close methods. @alias module:utils.AsyncObject @constructor @property {Boolean} loading @property {Boolean} closing @property {Boolean} loaded
[ "An", "abstract", "object", "that", "handles", "state", "and", "provides", "recallable", "open", "and", "close", "methods", "." ]
29c3759a175341cedae6b744c53eda628c669317
https://github.com/WorldMobileCoin/wmcc-core/blob/29c3759a175341cedae6b744c53eda628c669317/src/utils/asyncobject.js#L27-L38
36,915
WorldMobileCoin/wmcc-core
src/crypto/aes-browser.js
AESKey
function AESKey(key, bits) { if (!(this instanceof AESKey)) return new AESKey(key, bits); this.rounds = null; this.userKey = key; this.bits = bits; switch (this.bits) { case 128: this.rounds = 10; break; case 192: this.rounds = 12; break; case 256: this.rounds = 14; break; default: throw new Error('Bad key size.'); } assert(Buffer.isBuffer(key)); assert(key.length === this.bits / 8); this.decryptKey = null; this.encryptKey = null; }
javascript
function AESKey(key, bits) { if (!(this instanceof AESKey)) return new AESKey(key, bits); this.rounds = null; this.userKey = key; this.bits = bits; switch (this.bits) { case 128: this.rounds = 10; break; case 192: this.rounds = 12; break; case 256: this.rounds = 14; break; default: throw new Error('Bad key size.'); } assert(Buffer.isBuffer(key)); assert(key.length === this.bits / 8); this.decryptKey = null; this.encryptKey = null; }
[ "function", "AESKey", "(", "key", ",", "bits", ")", "{", "if", "(", "!", "(", "this", "instanceof", "AESKey", ")", ")", "return", "new", "AESKey", "(", "key", ",", "bits", ")", ";", "this", ".", "rounds", "=", "null", ";", "this", ".", "userKey", "=", "key", ";", "this", ".", "bits", "=", "bits", ";", "switch", "(", "this", ".", "bits", ")", "{", "case", "128", ":", "this", ".", "rounds", "=", "10", ";", "break", ";", "case", "192", ":", "this", ".", "rounds", "=", "12", ";", "break", ";", "case", "256", ":", "this", ".", "rounds", "=", "14", ";", "break", ";", "default", ":", "throw", "new", "Error", "(", "'Bad key size.'", ")", ";", "}", "assert", "(", "Buffer", ".", "isBuffer", "(", "key", ")", ")", ";", "assert", "(", "key", ".", "length", "===", "this", ".", "bits", "/", "8", ")", ";", "this", ".", "decryptKey", "=", "null", ";", "this", ".", "encryptKey", "=", "null", ";", "}" ]
An AES key object for encrypting and decrypting blocks. @constructor @ignore @param {Buffer} key @param {Number} bits
[ "An", "AES", "key", "object", "for", "encrypting", "and", "decrypting", "blocks", "." ]
29c3759a175341cedae6b744c53eda628c669317
https://github.com/WorldMobileCoin/wmcc-core/blob/29c3759a175341cedae6b744c53eda628c669317/src/crypto/aes-browser.js#L612-L639
36,916
WorldMobileCoin/wmcc-core
src/crypto/aes-browser.js
AESCipher
function AESCipher(key, iv, bits, mode) { if (!(this instanceof AESCipher)) return new AESCipher(key, iv, mode); assert(mode === 'ecb' || mode === 'cbc', 'Unknown mode.'); this.key = new AESKey(key, bits); this.mode = mode; this.prev = iv; this.waiting = null; }
javascript
function AESCipher(key, iv, bits, mode) { if (!(this instanceof AESCipher)) return new AESCipher(key, iv, mode); assert(mode === 'ecb' || mode === 'cbc', 'Unknown mode.'); this.key = new AESKey(key, bits); this.mode = mode; this.prev = iv; this.waiting = null; }
[ "function", "AESCipher", "(", "key", ",", "iv", ",", "bits", ",", "mode", ")", "{", "if", "(", "!", "(", "this", "instanceof", "AESCipher", ")", ")", "return", "new", "AESCipher", "(", "key", ",", "iv", ",", "mode", ")", ";", "assert", "(", "mode", "===", "'ecb'", "||", "mode", "===", "'cbc'", ",", "'Unknown mode.'", ")", ";", "this", ".", "key", "=", "new", "AESKey", "(", "key", ",", "bits", ")", ";", "this", ".", "mode", "=", "mode", ";", "this", ".", "prev", "=", "iv", ";", "this", ".", "waiting", "=", "null", ";", "}" ]
AES cipher. @constructor @ignore @param {Buffer} key @param {Buffer} iv @param {Number} bits @param {String} mode
[ "AES", "cipher", "." ]
29c3759a175341cedae6b744c53eda628c669317
https://github.com/WorldMobileCoin/wmcc-core/blob/29c3759a175341cedae6b744c53eda628c669317/src/crypto/aes-browser.js#L1055-L1065
36,917
WorldMobileCoin/wmcc-core
src/crypto/aes-browser.js
AESDecipher
function AESDecipher(key, iv, bits, mode) { if (!(this instanceof AESDecipher)) return new AESDecipher(key, iv, mode); assert(mode === 'ecb' || mode === 'cbc', 'Unknown mode.'); this.key = new AESKey(key, bits); this.mode = mode; this.prev = iv; this.waiting = null; this.lastBlock = null; }
javascript
function AESDecipher(key, iv, bits, mode) { if (!(this instanceof AESDecipher)) return new AESDecipher(key, iv, mode); assert(mode === 'ecb' || mode === 'cbc', 'Unknown mode.'); this.key = new AESKey(key, bits); this.mode = mode; this.prev = iv; this.waiting = null; this.lastBlock = null; }
[ "function", "AESDecipher", "(", "key", ",", "iv", ",", "bits", ",", "mode", ")", "{", "if", "(", "!", "(", "this", "instanceof", "AESDecipher", ")", ")", "return", "new", "AESDecipher", "(", "key", ",", "iv", ",", "mode", ")", ";", "assert", "(", "mode", "===", "'ecb'", "||", "mode", "===", "'cbc'", ",", "'Unknown mode.'", ")", ";", "this", ".", "key", "=", "new", "AESKey", "(", "key", ",", "bits", ")", ";", "this", ".", "mode", "=", "mode", ";", "this", ".", "prev", "=", "iv", ";", "this", ".", "waiting", "=", "null", ";", "this", ".", "lastBlock", "=", "null", ";", "}" ]
AES decipher. @constructor @ignore @param {Buffer} key @param {Buffer} iv @param {Number} bits @param {String} mode
[ "AES", "decipher", "." ]
29c3759a175341cedae6b744c53eda628c669317
https://github.com/WorldMobileCoin/wmcc-core/blob/29c3759a175341cedae6b744c53eda628c669317/src/crypto/aes-browser.js#L1140-L1151
36,918
WorldMobileCoin/wmcc-core
src/mining/miner.js
Miner
function Miner(options) { if (!(this instanceof Miner)) return new Miner(options); AsyncObject.call(this); this.options = new MinerOptions(options); this.network = this.options.network; this.logger = this.options.logger.context('miner'); this.workers = this.options.workers; this.chain = this.options.chain; this.mempool = this.options.mempool; this.addresses = this.options.addresses; this.locker = this.chain.locker; this.cpu = new CPUMiner(this); this.address = null; this.init(); }
javascript
function Miner(options) { if (!(this instanceof Miner)) return new Miner(options); AsyncObject.call(this); this.options = new MinerOptions(options); this.network = this.options.network; this.logger = this.options.logger.context('miner'); this.workers = this.options.workers; this.chain = this.options.chain; this.mempool = this.options.mempool; this.addresses = this.options.addresses; this.locker = this.chain.locker; this.cpu = new CPUMiner(this); this.address = null; this.init(); }
[ "function", "Miner", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Miner", ")", ")", "return", "new", "Miner", "(", "options", ")", ";", "AsyncObject", ".", "call", "(", "this", ")", ";", "this", ".", "options", "=", "new", "MinerOptions", "(", "options", ")", ";", "this", ".", "network", "=", "this", ".", "options", ".", "network", ";", "this", ".", "logger", "=", "this", ".", "options", ".", "logger", ".", "context", "(", "'miner'", ")", ";", "this", ".", "workers", "=", "this", ".", "options", ".", "workers", ";", "this", ".", "chain", "=", "this", ".", "options", ".", "chain", ";", "this", ".", "mempool", "=", "this", ".", "options", ".", "mempool", ";", "this", ".", "addresses", "=", "this", ".", "options", ".", "addresses", ";", "this", ".", "locker", "=", "this", ".", "chain", ".", "locker", ";", "this", ".", "cpu", "=", "new", "CPUMiner", "(", "this", ")", ";", "this", ".", "address", "=", "null", ";", "this", ".", "init", "(", ")", ";", "}" ]
A WMCoin miner and block generator. @alias module:mining.Miner @constructor @param {Object} options
[ "A", "WMCoin", "miner", "and", "block", "generator", "." ]
29c3759a175341cedae6b744c53eda628c669317
https://github.com/WorldMobileCoin/wmcc-core/blob/29c3759a175341cedae6b744c53eda628c669317/src/mining/miner.js#L34-L53
36,919
WorldMobileCoin/wmcc-core
src/script/witness.js
Witness
function Witness(options) { if (!(this instanceof Witness)) return new Witness(options); Stack.call(this, []); if (options) this.fromOptions(options); }
javascript
function Witness(options) { if (!(this instanceof Witness)) return new Witness(options); Stack.call(this, []); if (options) this.fromOptions(options); }
[ "function", "Witness", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Witness", ")", ")", "return", "new", "Witness", "(", "options", ")", ";", "Stack", ".", "call", "(", "this", ",", "[", "]", ")", ";", "if", "(", "options", ")", "this", ".", "fromOptions", "(", "options", ")", ";", "}" ]
Refers to the witness field of segregated witness transactions. @alias module:script.Witness @constructor @param {Buffer[]|NakedWitness} items - Array of stack items. @property {Buffer[]} items @property {Script?} redeem @property {Number} length
[ "Refers", "to", "the", "witness", "field", "of", "segregated", "witness", "transactions", "." ]
29c3759a175341cedae6b744c53eda628c669317
https://github.com/WorldMobileCoin/wmcc-core/blob/29c3759a175341cedae6b744c53eda628c669317/src/script/witness.js#L37-L45
36,920
WorldMobileCoin/wmcc-core
src/net/hostlist.js
HostListOptions
function HostListOptions(options) { if (!(this instanceof HostListOptions)) return new HostListOptions(options); this.network = Network.primary; this.logger = Logger.global; this.resolve = dns.lookup; this.host = '0.0.0.0'; this.port = this.network.port; this.services = common.LOCAL_SERVICES; this.onion = false; this.banTime = common.BAN_TIME; this.address = new NetAddress(); this.address.services = this.services; this.address.time = this.network.now(); this.seeds = this.network.seeds; this.nodes = []; this.maxBuckets = 20; this.maxEntries = 50; this.prefix = null; this.filename = null; this.persistent = false; this.flushInterval = 120000; if (options) this.fromOptions(options); }
javascript
function HostListOptions(options) { if (!(this instanceof HostListOptions)) return new HostListOptions(options); this.network = Network.primary; this.logger = Logger.global; this.resolve = dns.lookup; this.host = '0.0.0.0'; this.port = this.network.port; this.services = common.LOCAL_SERVICES; this.onion = false; this.banTime = common.BAN_TIME; this.address = new NetAddress(); this.address.services = this.services; this.address.time = this.network.now(); this.seeds = this.network.seeds; this.nodes = []; this.maxBuckets = 20; this.maxEntries = 50; this.prefix = null; this.filename = null; this.persistent = false; this.flushInterval = 120000; if (options) this.fromOptions(options); }
[ "function", "HostListOptions", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "HostListOptions", ")", ")", "return", "new", "HostListOptions", "(", "options", ")", ";", "this", ".", "network", "=", "Network", ".", "primary", ";", "this", ".", "logger", "=", "Logger", ".", "global", ";", "this", ".", "resolve", "=", "dns", ".", "lookup", ";", "this", ".", "host", "=", "'0.0.0.0'", ";", "this", ".", "port", "=", "this", ".", "network", ".", "port", ";", "this", ".", "services", "=", "common", ".", "LOCAL_SERVICES", ";", "this", ".", "onion", "=", "false", ";", "this", ".", "banTime", "=", "common", ".", "BAN_TIME", ";", "this", ".", "address", "=", "new", "NetAddress", "(", ")", ";", "this", ".", "address", ".", "services", "=", "this", ".", "services", ";", "this", ".", "address", ".", "time", "=", "this", ".", "network", ".", "now", "(", ")", ";", "this", ".", "seeds", "=", "this", ".", "network", ".", "seeds", ";", "this", ".", "nodes", "=", "[", "]", ";", "this", ".", "maxBuckets", "=", "20", ";", "this", ".", "maxEntries", "=", "50", ";", "this", ".", "prefix", "=", "null", ";", "this", ".", "filename", "=", "null", ";", "this", ".", "persistent", "=", "false", ";", "this", ".", "flushInterval", "=", "120000", ";", "if", "(", "options", ")", "this", ".", "fromOptions", "(", "options", ")", ";", "}" ]
Host List Options @alias module:net.HostListOptions @constructor @param {Object?} options
[ "Host", "List", "Options" ]
29c3759a175341cedae6b744c53eda628c669317
https://github.com/WorldMobileCoin/wmcc-core/blob/29c3759a175341cedae6b744c53eda628c669317/src/net/hostlist.js#L1482-L1512
36,921
WorldMobileCoin/wmcc-core
src/mining/cpuminer.js
CPUMiner
function CPUMiner(miner) { if (!(this instanceof CPUMiner)) return new CPUMiner(miner); AsyncObject.call(this); this.miner = miner; this.network = this.miner.network; this.logger = this.miner.logger.context('cpuminer'); this.workers = this.miner.workers; this.chain = this.miner.chain; this.locker = new Lock(); this.locker2 = new Lock(); this.running = false; this.stopping = false; this.own = false; this.job = null; this.stopJob = null; this._init(); }
javascript
function CPUMiner(miner) { if (!(this instanceof CPUMiner)) return new CPUMiner(miner); AsyncObject.call(this); this.miner = miner; this.network = this.miner.network; this.logger = this.miner.logger.context('cpuminer'); this.workers = this.miner.workers; this.chain = this.miner.chain; this.locker = new Lock(); this.locker2 = new Lock(); this.running = false; this.stopping = false; this.own = false; this.job = null; this.stopJob = null; this._init(); }
[ "function", "CPUMiner", "(", "miner", ")", "{", "if", "(", "!", "(", "this", "instanceof", "CPUMiner", ")", ")", "return", "new", "CPUMiner", "(", "miner", ")", ";", "AsyncObject", ".", "call", "(", "this", ")", ";", "this", ".", "miner", "=", "miner", ";", "this", ".", "network", "=", "this", ".", "miner", ".", "network", ";", "this", ".", "logger", "=", "this", ".", "miner", ".", "logger", ".", "context", "(", "'cpuminer'", ")", ";", "this", ".", "workers", "=", "this", ".", "miner", ".", "workers", ";", "this", ".", "chain", "=", "this", ".", "miner", ".", "chain", ";", "this", ".", "locker", "=", "new", "Lock", "(", ")", ";", "this", ".", "locker2", "=", "new", "Lock", "(", ")", ";", "this", ".", "running", "=", "false", ";", "this", ".", "stopping", "=", "false", ";", "this", ".", "own", "=", "false", ";", "this", ".", "job", "=", "null", ";", "this", ".", "stopJob", "=", "null", ";", "this", ".", "_init", "(", ")", ";", "}" ]
CPU miner. @alias module:mining.CPUMiner @constructor @param {Miner} miner @emits CPUMiner#block @emits CPUMiner#status
[ "CPU", "miner", "." ]
29c3759a175341cedae6b744c53eda628c669317
https://github.com/WorldMobileCoin/wmcc-core/blob/29c3759a175341cedae6b744c53eda628c669317/src/mining/cpuminer.js#L30-L51
36,922
samccone/monocle
monocle.js
setAbsolutePath
function setAbsolutePath(file) { file.absolutePath = path.resolve(process.cwd(), file.fullPath); return file.absolutePath; }
javascript
function setAbsolutePath(file) { file.absolutePath = path.resolve(process.cwd(), file.fullPath); return file.absolutePath; }
[ "function", "setAbsolutePath", "(", "file", ")", "{", "file", ".", "absolutePath", "=", "path", ".", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "file", ".", "fullPath", ")", ";", "return", "file", ".", "absolutePath", ";", "}" ]
sets the absolute path to the file from the current working dir
[ "sets", "the", "absolute", "path", "to", "the", "file", "from", "the", "current", "working", "dir" ]
de6e84cee33695a04ce826039e8da33e707a88f8
https://github.com/samccone/monocle/blob/de6e84cee33695a04ce826039e8da33e707a88f8/monocle.js#L92-L95
36,923
samccone/monocle
monocle.js
watchFile
function watchFile(file, cb, partial) { setAbsolutePath(file); storeDirectory(file); if (!watched_files[file.fullPath]) { if (use_fs_watch) { (function() { watched_files[file.fullPath] = fs.watch(file.fullPath, function() { typeof cb === "function" && cb(file); }); partial && cb(file); })(file, cb); } else { (function(file, cb) { watched_files[file.fullPath] = true; fs.watchFile(file.fullPath, {interval: 150}, function() { typeof cb === "function" && cb(file); }); partial && cb(file); })(file, cb); } } }
javascript
function watchFile(file, cb, partial) { setAbsolutePath(file); storeDirectory(file); if (!watched_files[file.fullPath]) { if (use_fs_watch) { (function() { watched_files[file.fullPath] = fs.watch(file.fullPath, function() { typeof cb === "function" && cb(file); }); partial && cb(file); })(file, cb); } else { (function(file, cb) { watched_files[file.fullPath] = true; fs.watchFile(file.fullPath, {interval: 150}, function() { typeof cb === "function" && cb(file); }); partial && cb(file); })(file, cb); } } }
[ "function", "watchFile", "(", "file", ",", "cb", ",", "partial", ")", "{", "setAbsolutePath", "(", "file", ")", ";", "storeDirectory", "(", "file", ")", ";", "if", "(", "!", "watched_files", "[", "file", ".", "fullPath", "]", ")", "{", "if", "(", "use_fs_watch", ")", "{", "(", "function", "(", ")", "{", "watched_files", "[", "file", ".", "fullPath", "]", "=", "fs", ".", "watch", "(", "file", ".", "fullPath", ",", "function", "(", ")", "{", "typeof", "cb", "===", "\"function\"", "&&", "cb", "(", "file", ")", ";", "}", ")", ";", "partial", "&&", "cb", "(", "file", ")", ";", "}", ")", "(", "file", ",", "cb", ")", ";", "}", "else", "{", "(", "function", "(", "file", ",", "cb", ")", "{", "watched_files", "[", "file", ".", "fullPath", "]", "=", "true", ";", "fs", ".", "watchFile", "(", "file", ".", "fullPath", ",", "{", "interval", ":", "150", "}", ",", "function", "(", ")", "{", "typeof", "cb", "===", "\"function\"", "&&", "cb", "(", "file", ")", ";", "}", ")", ";", "partial", "&&", "cb", "(", "file", ")", ";", "}", ")", "(", "file", ",", "cb", ")", ";", "}", "}", "}" ]
Watches the file passed and its containing directory on change calls given listener with file object
[ "Watches", "the", "file", "passed", "and", "its", "containing", "directory", "on", "change", "calls", "given", "listener", "with", "file", "object" ]
de6e84cee33695a04ce826039e8da33e707a88f8
https://github.com/samccone/monocle/blob/de6e84cee33695a04ce826039e8da33e707a88f8/monocle.js#L99-L120
36,924
samccone/monocle
monocle.js
storeDirectory
function storeDirectory(file) { var directory = file.fullParentDir; if (!watched_directories[directory]) { fs.stat(directory, function(err, stats) { if (err) { watched_directories[directory] = (new Date).getTime(); } else { watched_directories[directory] = (new Date(stats.mtime)).getTime(); } }); } }
javascript
function storeDirectory(file) { var directory = file.fullParentDir; if (!watched_directories[directory]) { fs.stat(directory, function(err, stats) { if (err) { watched_directories[directory] = (new Date).getTime(); } else { watched_directories[directory] = (new Date(stats.mtime)).getTime(); } }); } }
[ "function", "storeDirectory", "(", "file", ")", "{", "var", "directory", "=", "file", ".", "fullParentDir", ";", "if", "(", "!", "watched_directories", "[", "directory", "]", ")", "{", "fs", ".", "stat", "(", "directory", ",", "function", "(", "err", ",", "stats", ")", "{", "if", "(", "err", ")", "{", "watched_directories", "[", "directory", "]", "=", "(", "new", "Date", ")", ".", "getTime", "(", ")", ";", "}", "else", "{", "watched_directories", "[", "directory", "]", "=", "(", "new", "Date", "(", "stats", ".", "mtime", ")", ")", ".", "getTime", "(", ")", ";", "}", "}", ")", ";", "}", "}" ]
Sets up a store of the folders being watched and saves the last modification timestamp for it
[ "Sets", "up", "a", "store", "of", "the", "folders", "being", "watched", "and", "saves", "the", "last", "modification", "timestamp", "for", "it" ]
de6e84cee33695a04ce826039e8da33e707a88f8
https://github.com/samccone/monocle/blob/de6e84cee33695a04ce826039e8da33e707a88f8/monocle.js#L124-L135
36,925
samccone/monocle
monocle.js
distinguishPaths
function distinguishPaths(paths) { paths = Array.isArray(paths) ? paths : [paths]; var result = { directories: [], files: [] }; paths.forEach(function(name) { if (fs.statSync(name).isDirectory()) { result.directories.push(name); } else { result.files.push(name); } }); return result; }
javascript
function distinguishPaths(paths) { paths = Array.isArray(paths) ? paths : [paths]; var result = { directories: [], files: [] }; paths.forEach(function(name) { if (fs.statSync(name).isDirectory()) { result.directories.push(name); } else { result.files.push(name); } }); return result; }
[ "function", "distinguishPaths", "(", "paths", ")", "{", "paths", "=", "Array", ".", "isArray", "(", "paths", ")", "?", "paths", ":", "[", "paths", "]", ";", "var", "result", "=", "{", "directories", ":", "[", "]", ",", "files", ":", "[", "]", "}", ";", "paths", ".", "forEach", "(", "function", "(", "name", ")", "{", "if", "(", "fs", ".", "statSync", "(", "name", ")", ".", "isDirectory", "(", ")", ")", "{", "result", ".", "directories", ".", "push", "(", "name", ")", ";", "}", "else", "{", "result", ".", "files", ".", "push", "(", "name", ")", ";", "}", "}", ")", ";", "return", "result", ";", "}" ]
distinguish between files and directories @returns {Object} contains directories and files array
[ "distinguish", "between", "files", "and", "directories" ]
de6e84cee33695a04ce826039e8da33e707a88f8
https://github.com/samccone/monocle/blob/de6e84cee33695a04ce826039e8da33e707a88f8/monocle.js#L140-L154
36,926
samccone/monocle
monocle.js
extend
function extend(prototype, attributes) { var object = {}; Object.keys(prototype).forEach(function(key) { object[key] = prototype[key]; }); Object.keys(attributes).forEach(function(key) { object[key] = attributes[key]; }); return object; }
javascript
function extend(prototype, attributes) { var object = {}; Object.keys(prototype).forEach(function(key) { object[key] = prototype[key]; }); Object.keys(attributes).forEach(function(key) { object[key] = attributes[key]; }); return object; }
[ "function", "extend", "(", "prototype", ",", "attributes", ")", "{", "var", "object", "=", "{", "}", ";", "Object", ".", "keys", "(", "prototype", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "object", "[", "key", "]", "=", "prototype", "[", "key", "]", ";", "}", ")", ";", "Object", ".", "keys", "(", "attributes", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "object", "[", "key", "]", "=", "attributes", "[", "key", "]", ";", "}", ")", ";", "return", "object", ";", "}" ]
for functions accepts an object as parameter copy the object and modify with attributes
[ "for", "functions", "accepts", "an", "object", "as", "parameter", "copy", "the", "object", "and", "modify", "with", "attributes" ]
de6e84cee33695a04ce826039e8da33e707a88f8
https://github.com/samccone/monocle/blob/de6e84cee33695a04ce826039e8da33e707a88f8/monocle.js#L158-L167
36,927
samccone/monocle
monocle.js
watchPaths
function watchPaths(args) { var result = distinguishPaths(args.path) if (result.directories.length) { result.directories.forEach(function(directory) { watchDirectory(extend(args, {root: directory})); }); } if (result.files.length) watchFiles(extend(args, {files: result.files})); }
javascript
function watchPaths(args) { var result = distinguishPaths(args.path) if (result.directories.length) { result.directories.forEach(function(directory) { watchDirectory(extend(args, {root: directory})); }); } if (result.files.length) watchFiles(extend(args, {files: result.files})); }
[ "function", "watchPaths", "(", "args", ")", "{", "var", "result", "=", "distinguishPaths", "(", "args", ".", "path", ")", "if", "(", "result", ".", "directories", ".", "length", ")", "{", "result", ".", "directories", ".", "forEach", "(", "function", "(", "directory", ")", "{", "watchDirectory", "(", "extend", "(", "args", ",", "{", "root", ":", "directory", "}", ")", ")", ";", "}", ")", ";", "}", "if", "(", "result", ".", "files", ".", "length", ")", "watchFiles", "(", "extend", "(", "args", ",", "{", "files", ":", "result", ".", "files", "}", ")", ")", ";", "}" ]
watch files if the paths refer to files, or directories
[ "watch", "files", "if", "the", "paths", "refer", "to", "files", "or", "directories" ]
de6e84cee33695a04ce826039e8da33e707a88f8
https://github.com/samccone/monocle/blob/de6e84cee33695a04ce826039e8da33e707a88f8/monocle.js#L170-L179
36,928
WorldMobileCoin/wmcc-core
src/crypto/siphash.js
siphash24
function siphash24(data, key, shift) { const blocks = Math.floor(data.length / 8); const c0 = U64(0x736f6d65, 0x70736575); const c1 = U64(0x646f7261, 0x6e646f6d); const c2 = U64(0x6c796765, 0x6e657261); const c3 = U64(0x74656462, 0x79746573); const f0 = U64(blocks << (shift - 32), 0); const f1 = U64(0, 0xff); const k0 = U64.fromRaw(key, 0); const k1 = U64.fromRaw(key, 8); // Init const v0 = c0.ixor(k0); const v1 = c1.ixor(k1); const v2 = c2.ixor(k0); const v3 = c3.ixor(k1); // Blocks let p = 0; for (let i = 0; i < blocks; i++) { const d = U64.fromRaw(data, p); p += 8; v3.ixor(d); sipround(v0, v1, v2, v3); sipround(v0, v1, v2, v3); v0.ixor(d); } switch (data.length & 7) { case 7: f0.hi |= data[p + 6] << 16; case 6: f0.hi |= data[p + 5] << 8; case 5: f0.hi |= data[p + 4]; case 4: f0.lo |= data[p + 3] << 24; case 3: f0.lo |= data[p + 2] << 16; case 2: f0.lo |= data[p + 1] << 8; case 1: f0.lo |= data[p]; } // Finalization v3.ixor(f0); sipround(v0, v1, v2, v3); sipround(v0, v1, v2, v3); v0.ixor(f0); v2.ixor(f1); sipround(v0, v1, v2, v3); sipround(v0, v1, v2, v3); sipround(v0, v1, v2, v3); sipround(v0, v1, v2, v3); v0.ixor(v1); v0.ixor(v2); v0.ixor(v3); return [v0.hi, v0.lo]; }
javascript
function siphash24(data, key, shift) { const blocks = Math.floor(data.length / 8); const c0 = U64(0x736f6d65, 0x70736575); const c1 = U64(0x646f7261, 0x6e646f6d); const c2 = U64(0x6c796765, 0x6e657261); const c3 = U64(0x74656462, 0x79746573); const f0 = U64(blocks << (shift - 32), 0); const f1 = U64(0, 0xff); const k0 = U64.fromRaw(key, 0); const k1 = U64.fromRaw(key, 8); // Init const v0 = c0.ixor(k0); const v1 = c1.ixor(k1); const v2 = c2.ixor(k0); const v3 = c3.ixor(k1); // Blocks let p = 0; for (let i = 0; i < blocks; i++) { const d = U64.fromRaw(data, p); p += 8; v3.ixor(d); sipround(v0, v1, v2, v3); sipround(v0, v1, v2, v3); v0.ixor(d); } switch (data.length & 7) { case 7: f0.hi |= data[p + 6] << 16; case 6: f0.hi |= data[p + 5] << 8; case 5: f0.hi |= data[p + 4]; case 4: f0.lo |= data[p + 3] << 24; case 3: f0.lo |= data[p + 2] << 16; case 2: f0.lo |= data[p + 1] << 8; case 1: f0.lo |= data[p]; } // Finalization v3.ixor(f0); sipround(v0, v1, v2, v3); sipround(v0, v1, v2, v3); v0.ixor(f0); v2.ixor(f1); sipround(v0, v1, v2, v3); sipround(v0, v1, v2, v3); sipround(v0, v1, v2, v3); sipround(v0, v1, v2, v3); v0.ixor(v1); v0.ixor(v2); v0.ixor(v3); return [v0.hi, v0.lo]; }
[ "function", "siphash24", "(", "data", ",", "key", ",", "shift", ")", "{", "const", "blocks", "=", "Math", ".", "floor", "(", "data", ".", "length", "/", "8", ")", ";", "const", "c0", "=", "U64", "(", "0x736f6d65", ",", "0x70736575", ")", ";", "const", "c1", "=", "U64", "(", "0x646f7261", ",", "0x6e646f6d", ")", ";", "const", "c2", "=", "U64", "(", "0x6c796765", ",", "0x6e657261", ")", ";", "const", "c3", "=", "U64", "(", "0x74656462", ",", "0x79746573", ")", ";", "const", "f0", "=", "U64", "(", "blocks", "<<", "(", "shift", "-", "32", ")", ",", "0", ")", ";", "const", "f1", "=", "U64", "(", "0", ",", "0xff", ")", ";", "const", "k0", "=", "U64", ".", "fromRaw", "(", "key", ",", "0", ")", ";", "const", "k1", "=", "U64", ".", "fromRaw", "(", "key", ",", "8", ")", ";", "// Init", "const", "v0", "=", "c0", ".", "ixor", "(", "k0", ")", ";", "const", "v1", "=", "c1", ".", "ixor", "(", "k1", ")", ";", "const", "v2", "=", "c2", ".", "ixor", "(", "k0", ")", ";", "const", "v3", "=", "c3", ".", "ixor", "(", "k1", ")", ";", "// Blocks", "let", "p", "=", "0", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "blocks", ";", "i", "++", ")", "{", "const", "d", "=", "U64", ".", "fromRaw", "(", "data", ",", "p", ")", ";", "p", "+=", "8", ";", "v3", ".", "ixor", "(", "d", ")", ";", "sipround", "(", "v0", ",", "v1", ",", "v2", ",", "v3", ")", ";", "sipround", "(", "v0", ",", "v1", ",", "v2", ",", "v3", ")", ";", "v0", ".", "ixor", "(", "d", ")", ";", "}", "switch", "(", "data", ".", "length", "&", "7", ")", "{", "case", "7", ":", "f0", ".", "hi", "|=", "data", "[", "p", "+", "6", "]", "<<", "16", ";", "case", "6", ":", "f0", ".", "hi", "|=", "data", "[", "p", "+", "5", "]", "<<", "8", ";", "case", "5", ":", "f0", ".", "hi", "|=", "data", "[", "p", "+", "4", "]", ";", "case", "4", ":", "f0", ".", "lo", "|=", "data", "[", "p", "+", "3", "]", "<<", "24", ";", "case", "3", ":", "f0", ".", "lo", "|=", "data", "[", "p", "+", "2", "]", "<<", "16", ";", "case", "2", ":", "f0", ".", "lo", "|=", "data", "[", "p", "+", "1", "]", "<<", "8", ";", "case", "1", ":", "f0", ".", "lo", "|=", "data", "[", "p", "]", ";", "}", "// Finalization", "v3", ".", "ixor", "(", "f0", ")", ";", "sipround", "(", "v0", ",", "v1", ",", "v2", ",", "v3", ")", ";", "sipround", "(", "v0", ",", "v1", ",", "v2", ",", "v3", ")", ";", "v0", ".", "ixor", "(", "f0", ")", ";", "v2", ".", "ixor", "(", "f1", ")", ";", "sipround", "(", "v0", ",", "v1", ",", "v2", ",", "v3", ")", ";", "sipround", "(", "v0", ",", "v1", ",", "v2", ",", "v3", ")", ";", "sipround", "(", "v0", ",", "v1", ",", "v2", ",", "v3", ")", ";", "sipround", "(", "v0", ",", "v1", ",", "v2", ",", "v3", ")", ";", "v0", ".", "ixor", "(", "v1", ")", ";", "v0", ".", "ixor", "(", "v2", ")", ";", "v0", ".", "ixor", "(", "v3", ")", ";", "return", "[", "v0", ".", "hi", ",", "v0", ".", "lo", "]", ";", "}" ]
Javascript siphash implementation. Used for compact block relay. @alias module:crypto/siphash.siphash24 @param {Buffer} data @param {Buffer} key - 128 bit key. @returns {Array} [hi, lo]
[ "Javascript", "siphash", "implementation", ".", "Used", "for", "compact", "block", "relay", "." ]
29c3759a175341cedae6b744c53eda628c669317
https://github.com/WorldMobileCoin/wmcc-core/blob/29c3759a175341cedae6b744c53eda628c669317/src/crypto/siphash.js#L30-L90
36,929
WorldMobileCoin/wmcc-core
src/utils/reader.js
BufferReader
function BufferReader(data, zeroCopy) { if (!(this instanceof BufferReader)) return new BufferReader(data, zeroCopy); assert(Buffer.isBuffer(data), 'Must pass a Buffer.'); this.data = data; this.offset = 0; this.zeroCopy = zeroCopy || false; this.stack = []; }
javascript
function BufferReader(data, zeroCopy) { if (!(this instanceof BufferReader)) return new BufferReader(data, zeroCopy); assert(Buffer.isBuffer(data), 'Must pass a Buffer.'); this.data = data; this.offset = 0; this.zeroCopy = zeroCopy || false; this.stack = []; }
[ "function", "BufferReader", "(", "data", ",", "zeroCopy", ")", "{", "if", "(", "!", "(", "this", "instanceof", "BufferReader", ")", ")", "return", "new", "BufferReader", "(", "data", ",", "zeroCopy", ")", ";", "assert", "(", "Buffer", ".", "isBuffer", "(", "data", ")", ",", "'Must pass a Buffer.'", ")", ";", "this", ".", "data", "=", "data", ";", "this", ".", "offset", "=", "0", ";", "this", ".", "zeroCopy", "=", "zeroCopy", "||", "false", ";", "this", ".", "stack", "=", "[", "]", ";", "}" ]
An object that allows reading of buffers in a sane manner. @alias module:utils.BufferReader @constructor @param {Buffer} data @param {Boolean?} zeroCopy - Do not reallocate buffers when slicing. Note that this can lead to memory leaks if not used carefully.
[ "An", "object", "that", "allows", "reading", "of", "buffers", "in", "a", "sane", "manner", "." ]
29c3759a175341cedae6b744c53eda628c669317
https://github.com/WorldMobileCoin/wmcc-core/blob/29c3759a175341cedae6b744c53eda628c669317/src/utils/reader.js#L30-L40
36,930
Spiffyk/twitch-node-sdk
lib/twitch.auth.js
updateSession
function updateSession(callback) { core.api({method: ''}, function(err, response) { var session; if (err) { core.log('error encountered updating session:', err); callback && callback(err, null); return; } if (!response.token.valid) { // Invalid token. Either it has expired or the user has // revoked permission, so clear out our stored data. logout(callback); return; } callback && callback(null, session); }); }
javascript
function updateSession(callback) { core.api({method: ''}, function(err, response) { var session; if (err) { core.log('error encountered updating session:', err); callback && callback(err, null); return; } if (!response.token.valid) { // Invalid token. Either it has expired or the user has // revoked permission, so clear out our stored data. logout(callback); return; } callback && callback(null, session); }); }
[ "function", "updateSession", "(", "callback", ")", "{", "core", ".", "api", "(", "{", "method", ":", "''", "}", ",", "function", "(", "err", ",", "response", ")", "{", "var", "session", ";", "if", "(", "err", ")", "{", "core", ".", "log", "(", "'error encountered updating session:'", ",", "err", ")", ";", "callback", "&&", "callback", "(", "err", ",", "null", ")", ";", "return", ";", "}", "if", "(", "!", "response", ".", "token", ".", "valid", ")", "{", "// Invalid token. Either it has expired or the user has", "// revoked permission, so clear out our stored data.", "logout", "(", "callback", ")", ";", "return", ";", "}", "callback", "&&", "callback", "(", "null", ",", "session", ")", ";", "}", ")", ";", "}" ]
Updates session info from the API. @private @method updateSession
[ "Updates", "session", "info", "from", "the", "API", "." ]
e98234ca52b12569298213869439d17169e26f27
https://github.com/Spiffyk/twitch-node-sdk/blob/e98234ca52b12569298213869439d17169e26f27/lib/twitch.auth.js#L18-L36
36,931
Spiffyk/twitch-node-sdk
lib/twitch.auth.js
makeSession
function makeSession(session) { return { authenticated: !!session.token, token: session.token, scope: session.scope, error: session.error, errorDescription: session.errorDescription }; }
javascript
function makeSession(session) { return { authenticated: !!session.token, token: session.token, scope: session.scope, error: session.error, errorDescription: session.errorDescription }; }
[ "function", "makeSession", "(", "session", ")", "{", "return", "{", "authenticated", ":", "!", "!", "session", ".", "token", ",", "token", ":", "session", ".", "token", ",", "scope", ":", "session", ".", "scope", ",", "error", ":", "session", ".", "error", ",", "errorDescription", ":", "session", ".", "errorDescription", "}", ";", "}" ]
Creates a session object @private @method makeSession @return {Object} Created session
[ "Creates", "a", "session", "object" ]
e98234ca52b12569298213869439d17169e26f27
https://github.com/Spiffyk/twitch-node-sdk/blob/e98234ca52b12569298213869439d17169e26f27/lib/twitch.auth.js#L44-L52
36,932
Spiffyk/twitch-node-sdk
lib/twitch.auth.js
getStatus
function getStatus(options, callback) { if (typeof options === 'function') { callback = options; } if (typeof callback !== 'function') { callback = function() {}; } if (!core.session) { throw new Error('You must call init() before getStatus()'); } if (options && options.force) { updateSession(function(err, session) { callback(err, makeSession(session || core.session)); }); } else { callback(null, makeSession(core.session)); } }
javascript
function getStatus(options, callback) { if (typeof options === 'function') { callback = options; } if (typeof callback !== 'function') { callback = function() {}; } if (!core.session) { throw new Error('You must call init() before getStatus()'); } if (options && options.force) { updateSession(function(err, session) { callback(err, makeSession(session || core.session)); }); } else { callback(null, makeSession(core.session)); } }
[ "function", "getStatus", "(", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", ";", "}", "if", "(", "typeof", "callback", "!==", "'function'", ")", "{", "callback", "=", "function", "(", ")", "{", "}", ";", "}", "if", "(", "!", "core", ".", "session", ")", "{", "throw", "new", "Error", "(", "'You must call init() before getStatus()'", ")", ";", "}", "if", "(", "options", "&&", "options", ".", "force", ")", "{", "updateSession", "(", "function", "(", "err", ",", "session", ")", "{", "callback", "(", "err", ",", "makeSession", "(", "session", "||", "core", ".", "session", ")", ")", ";", "}", ")", ";", "}", "else", "{", "callback", "(", "null", ",", "makeSession", "(", "core", ".", "session", ")", ")", ";", "}", "}" ]
Gets the current authentication status. The `force` property will trigger an API request to update session data. @method getStatus @param {Object} options @param {function} [callback]
[ "Gets", "the", "current", "authentication", "status", ".", "The", "force", "property", "will", "trigger", "an", "API", "request", "to", "update", "session", "data", "." ]
e98234ca52b12569298213869439d17169e26f27
https://github.com/Spiffyk/twitch-node-sdk/blob/e98234ca52b12569298213869439d17169e26f27/lib/twitch.auth.js#L74-L92
36,933
Spiffyk/twitch-node-sdk
lib/twitch.auth.js
login
function login(options) { if (!gui.isActive()) { throw new Error('Cannot login without a GUI.'); } if (!options.scope) { throw new Error('Must specify list of requested scopes'); } var params = { response_type: 'token', client_id: core.clientId, redirect_uri: 'https://api.twitch.tv/kraken/', scope: options.scope.join(' '), }; if(options.force_verify) { params.force_verify = true; } if (!params.client_id) { throw new Error('You must call init() before login()'); } gui.popupLogin(params); }
javascript
function login(options) { if (!gui.isActive()) { throw new Error('Cannot login without a GUI.'); } if (!options.scope) { throw new Error('Must specify list of requested scopes'); } var params = { response_type: 'token', client_id: core.clientId, redirect_uri: 'https://api.twitch.tv/kraken/', scope: options.scope.join(' '), }; if(options.force_verify) { params.force_verify = true; } if (!params.client_id) { throw new Error('You must call init() before login()'); } gui.popupLogin(params); }
[ "function", "login", "(", "options", ")", "{", "if", "(", "!", "gui", ".", "isActive", "(", ")", ")", "{", "throw", "new", "Error", "(", "'Cannot login without a GUI.'", ")", ";", "}", "if", "(", "!", "options", ".", "scope", ")", "{", "throw", "new", "Error", "(", "'Must specify list of requested scopes'", ")", ";", "}", "var", "params", "=", "{", "response_type", ":", "'token'", ",", "client_id", ":", "core", ".", "clientId", ",", "redirect_uri", ":", "'https://api.twitch.tv/kraken/'", ",", "scope", ":", "options", ".", "scope", ".", "join", "(", "' '", ")", ",", "}", ";", "if", "(", "options", ".", "force_verify", ")", "{", "params", ".", "force_verify", "=", "true", ";", "}", "if", "(", "!", "params", ".", "client_id", ")", "{", "throw", "new", "Error", "(", "'You must call init() before login()'", ")", ";", "}", "gui", ".", "popupLogin", "(", "params", ")", ";", "}" ]
Opens a login popup for Twitch if the SDK was initialized with a GUI and the user is not logged in yet. @method login @param {Object} options @example ```javascript Twitch.login({ scope: ['user_read', 'channel_read'] }); ```
[ "Opens", "a", "login", "popup", "for", "Twitch", "if", "the", "SDK", "was", "initialized", "with", "a", "GUI", "and", "the", "user", "is", "not", "logged", "in", "yet", "." ]
e98234ca52b12569298213869439d17169e26f27
https://github.com/Spiffyk/twitch-node-sdk/blob/e98234ca52b12569298213869439d17169e26f27/lib/twitch.auth.js#L107-L131
36,934
Spiffyk/twitch-node-sdk
lib/twitch.auth.js
logout
function logout(callback) { // Reset the current session core.setSession({}); core.events.emit('auth.logout'); if (typeof callback === 'function') { callback(null); } }
javascript
function logout(callback) { // Reset the current session core.setSession({}); core.events.emit('auth.logout'); if (typeof callback === 'function') { callback(null); } }
[ "function", "logout", "(", "callback", ")", "{", "// Reset the current session", "core", ".", "setSession", "(", "{", "}", ")", ";", "core", ".", "events", ".", "emit", "(", "'auth.logout'", ")", ";", "if", "(", "typeof", "callback", "===", "'function'", ")", "{", "callback", "(", "null", ")", ";", "}", "}" ]
Resets the session, which is akin to logging out. This does not deactivate the access token given to your app, so you can continue to perform actions if your server stored the token. @method logout @param {Function} [callback] @example ```javascript Twitch.logout(function(error) { // the user is now logged out }); ```
[ "Resets", "the", "session", "which", "is", "akin", "to", "logging", "out", ".", "This", "does", "not", "deactivate", "the", "access", "token", "given", "to", "your", "app", "so", "you", "can", "continue", "to", "perform", "actions", "if", "your", "server", "stored", "the", "token", "." ]
e98234ca52b12569298213869439d17169e26f27
https://github.com/Spiffyk/twitch-node-sdk/blob/e98234ca52b12569298213869439d17169e26f27/lib/twitch.auth.js#L147-L155
36,935
Spiffyk/twitch-node-sdk
lib/twitch.auth.js
initSession
function initSession(storedSession, callback) { if (typeof storedSession === "function") { callback = storedSession; } core.setSession((storedSession && makeSession(storedSession)) || {}); getStatus({ force: true }, function(err, status) { if (status.authenticated) { core.events.emit('auth.login', status); } if (typeof callback === "function") { callback(err, status); } }); }
javascript
function initSession(storedSession, callback) { if (typeof storedSession === "function") { callback = storedSession; } core.setSession((storedSession && makeSession(storedSession)) || {}); getStatus({ force: true }, function(err, status) { if (status.authenticated) { core.events.emit('auth.login', status); } if (typeof callback === "function") { callback(err, status); } }); }
[ "function", "initSession", "(", "storedSession", ",", "callback", ")", "{", "if", "(", "typeof", "storedSession", "===", "\"function\"", ")", "{", "callback", "=", "storedSession", ";", "}", "core", ".", "setSession", "(", "(", "storedSession", "&&", "makeSession", "(", "storedSession", ")", ")", "||", "{", "}", ")", ";", "getStatus", "(", "{", "force", ":", "true", "}", ",", "function", "(", "err", ",", "status", ")", "{", "if", "(", "status", ".", "authenticated", ")", "{", "core", ".", "events", ".", "emit", "(", "'auth.login'", ",", "status", ")", ";", "}", "if", "(", "typeof", "callback", "===", "\"function\"", ")", "{", "callback", "(", "err", ",", "status", ")", ";", "}", "}", ")", ";", "}" ]
Sets session to a stored one. @private @method initSession @param {Object} storedSession @param {Function} [callback]
[ "Sets", "session", "to", "a", "stored", "one", "." ]
e98234ca52b12569298213869439d17169e26f27
https://github.com/Spiffyk/twitch-node-sdk/blob/e98234ca52b12569298213869439d17169e26f27/lib/twitch.auth.js#L166-L182
36,936
perfectapi/node-perfectapi
lib/cligen.js
runWebServerInProcess
function runWebServerInProcess(rawConfig, serverConfig, emitter) { var server = require('./server.js'); if (serverConfig.command == 'stop') { logger.info('stopping server'); return server.stop(); } var app = server.listen(rawConfig, serverConfig, function(err, newCommandName, newConfig, finalCallback) { if (err) { logger.error("Error: " + err); if (callback) callback(err); } else { emitter.emit(newCommandName, newConfig, finalCallback); } }); }
javascript
function runWebServerInProcess(rawConfig, serverConfig, emitter) { var server = require('./server.js'); if (serverConfig.command == 'stop') { logger.info('stopping server'); return server.stop(); } var app = server.listen(rawConfig, serverConfig, function(err, newCommandName, newConfig, finalCallback) { if (err) { logger.error("Error: " + err); if (callback) callback(err); } else { emitter.emit(newCommandName, newConfig, finalCallback); } }); }
[ "function", "runWebServerInProcess", "(", "rawConfig", ",", "serverConfig", ",", "emitter", ")", "{", "var", "server", "=", "require", "(", "'./server.js'", ")", ";", "if", "(", "serverConfig", ".", "command", "==", "'stop'", ")", "{", "logger", ".", "info", "(", "'stopping server'", ")", ";", "return", "server", ".", "stop", "(", ")", ";", "}", "var", "app", "=", "server", ".", "listen", "(", "rawConfig", ",", "serverConfig", ",", "function", "(", "err", ",", "newCommandName", ",", "newConfig", ",", "finalCallback", ")", "{", "if", "(", "err", ")", "{", "logger", ".", "error", "(", "\"Error: \"", "+", "err", ")", ";", "if", "(", "callback", ")", "callback", "(", "err", ")", ";", "}", "else", "{", "emitter", ".", "emit", "(", "newCommandName", ",", "newConfig", ",", "finalCallback", ")", ";", "}", "}", ")", ";", "}" ]
Runs the web server in the same process as the user's code. This is quicker for a single cpu, but risks the user's code stealing cpu and preventing the web server from serving responses in a timely fashion
[ "Runs", "the", "web", "server", "in", "the", "same", "process", "as", "the", "user", "s", "code", ".", "This", "is", "quicker", "for", "a", "single", "cpu", "but", "risks", "the", "user", "s", "code", "stealing", "cpu", "and", "preventing", "the", "web", "server", "from", "serving", "responses", "in", "a", "timely", "fashion" ]
aea295ede31994bf7f3c2903cedbe6d316b30062
https://github.com/perfectapi/node-perfectapi/blob/aea295ede31994bf7f3c2903cedbe6d316b30062/lib/cligen.js#L117-L133
36,937
perfectapi/node-perfectapi
lib/cligen.js
runWebServerAsWorker
function runWebServerAsWorker(rawConfig, serverConfig, emitter, callback) { if (serverConfig.command == 'stop') { logger.info('stopping server workers'); if (netServer) { netServer.close(); netServer = null; } for (var i=0;i<webservers.length;i++) { var webserver = webservers[i]; webserver.kill(); } webservers = []; return; } netServer = require('net').createServer().listen(serverConfig.options.port, function() { var numWorkers = require('os').cpus().length; var readyCount = 0; for (var i=0;i<numWorkers;i++) { var webserver = fork(__dirname + '/worker.js', [], {env: process.env}); webservers.push(webserver); webserver.send({message: 'start', rawConfig: rawConfig, serverConfig: serverConfig}, netServer._handle) webserver.on('message', function(m) { if (m == 'ready') { //this is a reply from the worker indicating that the server is ready. readyCount += 1; if (readyCount == numWorkers) { //all servers are ready logger.info('started server workers'); if (callback) callback(); } return; } var webserverWorker = this; var id = m.id; if (m.err) { logger.error("Error: " + m.err); if (callback) callback(m.err); } else { emitter.emit(m.commandName, m.config, function(err, result) { webserverWorker.send({message: 'result', err: err, result: result, id: id}) }); } }) } }); }
javascript
function runWebServerAsWorker(rawConfig, serverConfig, emitter, callback) { if (serverConfig.command == 'stop') { logger.info('stopping server workers'); if (netServer) { netServer.close(); netServer = null; } for (var i=0;i<webservers.length;i++) { var webserver = webservers[i]; webserver.kill(); } webservers = []; return; } netServer = require('net').createServer().listen(serverConfig.options.port, function() { var numWorkers = require('os').cpus().length; var readyCount = 0; for (var i=0;i<numWorkers;i++) { var webserver = fork(__dirname + '/worker.js', [], {env: process.env}); webservers.push(webserver); webserver.send({message: 'start', rawConfig: rawConfig, serverConfig: serverConfig}, netServer._handle) webserver.on('message', function(m) { if (m == 'ready') { //this is a reply from the worker indicating that the server is ready. readyCount += 1; if (readyCount == numWorkers) { //all servers are ready logger.info('started server workers'); if (callback) callback(); } return; } var webserverWorker = this; var id = m.id; if (m.err) { logger.error("Error: " + m.err); if (callback) callback(m.err); } else { emitter.emit(m.commandName, m.config, function(err, result) { webserverWorker.send({message: 'result', err: err, result: result, id: id}) }); } }) } }); }
[ "function", "runWebServerAsWorker", "(", "rawConfig", ",", "serverConfig", ",", "emitter", ",", "callback", ")", "{", "if", "(", "serverConfig", ".", "command", "==", "'stop'", ")", "{", "logger", ".", "info", "(", "'stopping server workers'", ")", ";", "if", "(", "netServer", ")", "{", "netServer", ".", "close", "(", ")", ";", "netServer", "=", "null", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "webservers", ".", "length", ";", "i", "++", ")", "{", "var", "webserver", "=", "webservers", "[", "i", "]", ";", "webserver", ".", "kill", "(", ")", ";", "}", "webservers", "=", "[", "]", ";", "return", ";", "}", "netServer", "=", "require", "(", "'net'", ")", ".", "createServer", "(", ")", ".", "listen", "(", "serverConfig", ".", "options", ".", "port", ",", "function", "(", ")", "{", "var", "numWorkers", "=", "require", "(", "'os'", ")", ".", "cpus", "(", ")", ".", "length", ";", "var", "readyCount", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numWorkers", ";", "i", "++", ")", "{", "var", "webserver", "=", "fork", "(", "__dirname", "+", "'/worker.js'", ",", "[", "]", ",", "{", "env", ":", "process", ".", "env", "}", ")", ";", "webservers", ".", "push", "(", "webserver", ")", ";", "webserver", ".", "send", "(", "{", "message", ":", "'start'", ",", "rawConfig", ":", "rawConfig", ",", "serverConfig", ":", "serverConfig", "}", ",", "netServer", ".", "_handle", ")", "webserver", ".", "on", "(", "'message'", ",", "function", "(", "m", ")", "{", "if", "(", "m", "==", "'ready'", ")", "{", "//this is a reply from the worker indicating that the server is ready.", "readyCount", "+=", "1", ";", "if", "(", "readyCount", "==", "numWorkers", ")", "{", "//all servers are ready", "logger", ".", "info", "(", "'started server workers'", ")", ";", "if", "(", "callback", ")", "callback", "(", ")", ";", "}", "return", ";", "}", "var", "webserverWorker", "=", "this", ";", "var", "id", "=", "m", ".", "id", ";", "if", "(", "m", ".", "err", ")", "{", "logger", ".", "error", "(", "\"Error: \"", "+", "m", ".", "err", ")", ";", "if", "(", "callback", ")", "callback", "(", "m", ".", "err", ")", ";", "}", "else", "{", "emitter", ".", "emit", "(", "m", ".", "commandName", ",", "m", ".", "config", ",", "function", "(", "err", ",", "result", ")", "{", "webserverWorker", ".", "send", "(", "{", "message", ":", "'result'", ",", "err", ":", "err", ",", "result", ":", "result", ",", "id", ":", "id", "}", ")", "}", ")", ";", "}", "}", ")", "}", "}", ")", ";", "}" ]
Runs the web server in a forked process. This is not necessarily quicker, but it does allow the user's code to hog CPU without affecting the running of the web server
[ "Runs", "the", "web", "server", "in", "a", "forked", "process", ".", "This", "is", "not", "necessarily", "quicker", "but", "it", "does", "allow", "the", "user", "s", "code", "to", "hog", "CPU", "without", "affecting", "the", "running", "of", "the", "web", "server" ]
aea295ede31994bf7f3c2903cedbe6d316b30062
https://github.com/perfectapi/node-perfectapi/blob/aea295ede31994bf7f3c2903cedbe6d316b30062/lib/cligen.js#L141-L193
36,938
perfectapi/node-perfectapi
lib/cligen.js
function(err, result) { if (err && !util.isError(err)) { err = new Error(err); } if (callback) callback(err, result); }
javascript
function(err, result) { if (err && !util.isError(err)) { err = new Error(err); } if (callback) callback(err, result); }
[ "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", "&&", "!", "util", ".", "isError", "(", "err", ")", ")", "{", "err", "=", "new", "Error", "(", "err", ")", ";", "}", "if", "(", "callback", ")", "callback", "(", "err", ",", "result", ")", ";", "}" ]
stub callback to ensure we always return an Error object
[ "stub", "callback", "to", "ensure", "we", "always", "return", "an", "Error", "object" ]
aea295ede31994bf7f3c2903cedbe6d316b30062
https://github.com/perfectapi/node-perfectapi/blob/aea295ede31994bf7f3c2903cedbe6d316b30062/lib/cligen.js#L299-L304
36,939
WorldMobileCoin/wmcc-core
src/net/peer.js
Peer
function Peer(options) { if (!(this instanceof Peer)) return new Peer(options); EventEmitter.call(this); this.options = options; this.network = this.options.network; this.logger = this.options.logger.context('peer'); this.locker = new Lock(); this.parser = new Parser(this.network); this.framer = new Framer(this.network); this.id = -1; this.socket = null; this.opened = false; this.outbound = false; this.loader = false; this.address = new NetAddress(); this.local = new NetAddress(); this.connected = false; this.destroyed = false; this.ack = false; this.handshake = false; this.time = 0; this.lastSend = 0; this.lastRecv = 0; this.drainSize = 0; this.drainQueue = []; this.banScore = 0; this.invQueue = []; this.onPacket = null; this.next = null; this.prev = null; this.version = -1; this.services = 0; this.height = -1; this.agent = null; this.noRelay = false; this.preferHeaders = false; this.hashContinue = null; this.spvFilter = null; this.feeRate = -1; this.bip151 = null; this.bip150 = null; this.compactMode = -1; this.compactWitness = false; this.merkleBlock = null; this.merkleTime = -1; this.merkleMatches = 0; this.merkleMap = null; this.syncing = false; this.sentAddr = false; this.sentGetAddr = false; this.challenge = null; this.lastPong = -1; this.lastPing = -1; this.minPing = -1; this.blockTime = -1; this.bestHash = null; this.bestHeight = -1; this.connectTimeout = null; this.pingTimer = null; this.invTimer = null; this.stallTimer = null; this.addrFilter = new RollingFilter(5000, 0.001); this.invFilter = new RollingFilter(50000, 0.000001); this.blockMap = new Map(); this.txMap = new Map(); this.responseMap = new Map(); this.compactBlocks = new Map(); this._init(); }
javascript
function Peer(options) { if (!(this instanceof Peer)) return new Peer(options); EventEmitter.call(this); this.options = options; this.network = this.options.network; this.logger = this.options.logger.context('peer'); this.locker = new Lock(); this.parser = new Parser(this.network); this.framer = new Framer(this.network); this.id = -1; this.socket = null; this.opened = false; this.outbound = false; this.loader = false; this.address = new NetAddress(); this.local = new NetAddress(); this.connected = false; this.destroyed = false; this.ack = false; this.handshake = false; this.time = 0; this.lastSend = 0; this.lastRecv = 0; this.drainSize = 0; this.drainQueue = []; this.banScore = 0; this.invQueue = []; this.onPacket = null; this.next = null; this.prev = null; this.version = -1; this.services = 0; this.height = -1; this.agent = null; this.noRelay = false; this.preferHeaders = false; this.hashContinue = null; this.spvFilter = null; this.feeRate = -1; this.bip151 = null; this.bip150 = null; this.compactMode = -1; this.compactWitness = false; this.merkleBlock = null; this.merkleTime = -1; this.merkleMatches = 0; this.merkleMap = null; this.syncing = false; this.sentAddr = false; this.sentGetAddr = false; this.challenge = null; this.lastPong = -1; this.lastPing = -1; this.minPing = -1; this.blockTime = -1; this.bestHash = null; this.bestHeight = -1; this.connectTimeout = null; this.pingTimer = null; this.invTimer = null; this.stallTimer = null; this.addrFilter = new RollingFilter(5000, 0.001); this.invFilter = new RollingFilter(50000, 0.000001); this.blockMap = new Map(); this.txMap = new Map(); this.responseMap = new Map(); this.compactBlocks = new Map(); this._init(); }
[ "function", "Peer", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Peer", ")", ")", "return", "new", "Peer", "(", "options", ")", ";", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "options", "=", "options", ";", "this", ".", "network", "=", "this", ".", "options", ".", "network", ";", "this", ".", "logger", "=", "this", ".", "options", ".", "logger", ".", "context", "(", "'peer'", ")", ";", "this", ".", "locker", "=", "new", "Lock", "(", ")", ";", "this", ".", "parser", "=", "new", "Parser", "(", "this", ".", "network", ")", ";", "this", ".", "framer", "=", "new", "Framer", "(", "this", ".", "network", ")", ";", "this", ".", "id", "=", "-", "1", ";", "this", ".", "socket", "=", "null", ";", "this", ".", "opened", "=", "false", ";", "this", ".", "outbound", "=", "false", ";", "this", ".", "loader", "=", "false", ";", "this", ".", "address", "=", "new", "NetAddress", "(", ")", ";", "this", ".", "local", "=", "new", "NetAddress", "(", ")", ";", "this", ".", "connected", "=", "false", ";", "this", ".", "destroyed", "=", "false", ";", "this", ".", "ack", "=", "false", ";", "this", ".", "handshake", "=", "false", ";", "this", ".", "time", "=", "0", ";", "this", ".", "lastSend", "=", "0", ";", "this", ".", "lastRecv", "=", "0", ";", "this", ".", "drainSize", "=", "0", ";", "this", ".", "drainQueue", "=", "[", "]", ";", "this", ".", "banScore", "=", "0", ";", "this", ".", "invQueue", "=", "[", "]", ";", "this", ".", "onPacket", "=", "null", ";", "this", ".", "next", "=", "null", ";", "this", ".", "prev", "=", "null", ";", "this", ".", "version", "=", "-", "1", ";", "this", ".", "services", "=", "0", ";", "this", ".", "height", "=", "-", "1", ";", "this", ".", "agent", "=", "null", ";", "this", ".", "noRelay", "=", "false", ";", "this", ".", "preferHeaders", "=", "false", ";", "this", ".", "hashContinue", "=", "null", ";", "this", ".", "spvFilter", "=", "null", ";", "this", ".", "feeRate", "=", "-", "1", ";", "this", ".", "bip151", "=", "null", ";", "this", ".", "bip150", "=", "null", ";", "this", ".", "compactMode", "=", "-", "1", ";", "this", ".", "compactWitness", "=", "false", ";", "this", ".", "merkleBlock", "=", "null", ";", "this", ".", "merkleTime", "=", "-", "1", ";", "this", ".", "merkleMatches", "=", "0", ";", "this", ".", "merkleMap", "=", "null", ";", "this", ".", "syncing", "=", "false", ";", "this", ".", "sentAddr", "=", "false", ";", "this", ".", "sentGetAddr", "=", "false", ";", "this", ".", "challenge", "=", "null", ";", "this", ".", "lastPong", "=", "-", "1", ";", "this", ".", "lastPing", "=", "-", "1", ";", "this", ".", "minPing", "=", "-", "1", ";", "this", ".", "blockTime", "=", "-", "1", ";", "this", ".", "bestHash", "=", "null", ";", "this", ".", "bestHeight", "=", "-", "1", ";", "this", ".", "connectTimeout", "=", "null", ";", "this", ".", "pingTimer", "=", "null", ";", "this", ".", "invTimer", "=", "null", ";", "this", ".", "stallTimer", "=", "null", ";", "this", ".", "addrFilter", "=", "new", "RollingFilter", "(", "5000", ",", "0.001", ")", ";", "this", ".", "invFilter", "=", "new", "RollingFilter", "(", "50000", ",", "0.000001", ")", ";", "this", ".", "blockMap", "=", "new", "Map", "(", ")", ";", "this", ".", "txMap", "=", "new", "Map", "(", ")", ";", "this", ".", "responseMap", "=", "new", "Map", "(", ")", ";", "this", ".", "compactBlocks", "=", "new", "Map", "(", ")", ";", "this", ".", "_init", "(", ")", ";", "}" ]
Represents a remote peer. @alias module:net.Peer @constructor @param {PeerOptions} options @property {net.Socket} socket @property {NetAddress} address @property {Parser} parser @property {Framer} framer @property {Number} version @property {Boolean} destroyed @property {Boolean} ack - Whether verack has been received. @property {Boolean} connected @property {Number} time @property {Boolean} preferHeaders - Whether the peer has requested getheaders. @property {Hash?} hashContinue - The block hash at which to continue the sync for the peer. @property {Bloom?} spvFilter - The _peer's_ bloom spvFilter. @property {Boolean} noRelay - Whether to relay transactions immediately to the peer. @property {BN} challenge - Local nonce. @property {Number} lastPong - Timestamp for last `pong` received (unix time). @property {Number} lastPing - Timestamp for last `ping` sent (unix time). @property {Number} minPing - Lowest ping time seen. @property {Number} banScore @emits Peer#ack
[ "Represents", "a", "remote", "peer", "." ]
29c3759a175341cedae6b744c53eda628c669317
https://github.com/WorldMobileCoin/wmcc-core/blob/29c3759a175341cedae6b744c53eda628c669317/src/net/peer.js#L71-L151
36,940
myrmex-org/myrmex
packages/iam/src/helper.js
retrievePolicyArn
function retrievePolicyArn(identifier, context, searchParams) { if (/arn:aws:iam::\d{12}:policy\/?[a-zA-Z_0-9+=,.@\-_/]+]/.test(identifier)) { return Promise.resolve(identifier); } // @TODO make this code more beautiful // Try ENV_PolicyName_stage let policyIdentifier = context.environment + '_' + identifier + '_' + context.stage; return getPolicyByName(policyIdentifier, searchParams) .then(policy => { if (!policy) { // Try ENV_PolicyName policyIdentifier = context.environment + '_' + identifier; return getPolicyByName(policyIdentifier, searchParams) .then(policy => { if (!policy) { // Try PolicyName return getPolicyByName(identifier, searchParams) .then(policy => { if (!policy) { return findAndDeployPolicy(identifier, context) .then(report => { if (!report) { throw new Error('The policy ' + identifier + ' could not be found.'); } return { Arn: report.arn }; }); } return policy; }); } return policy; }); } return policy; }) .then(policy => { return policy.Arn; }); }
javascript
function retrievePolicyArn(identifier, context, searchParams) { if (/arn:aws:iam::\d{12}:policy\/?[a-zA-Z_0-9+=,.@\-_/]+]/.test(identifier)) { return Promise.resolve(identifier); } // @TODO make this code more beautiful // Try ENV_PolicyName_stage let policyIdentifier = context.environment + '_' + identifier + '_' + context.stage; return getPolicyByName(policyIdentifier, searchParams) .then(policy => { if (!policy) { // Try ENV_PolicyName policyIdentifier = context.environment + '_' + identifier; return getPolicyByName(policyIdentifier, searchParams) .then(policy => { if (!policy) { // Try PolicyName return getPolicyByName(identifier, searchParams) .then(policy => { if (!policy) { return findAndDeployPolicy(identifier, context) .then(report => { if (!report) { throw new Error('The policy ' + identifier + ' could not be found.'); } return { Arn: report.arn }; }); } return policy; }); } return policy; }); } return policy; }) .then(policy => { return policy.Arn; }); }
[ "function", "retrievePolicyArn", "(", "identifier", ",", "context", ",", "searchParams", ")", "{", "if", "(", "/", "arn:aws:iam::\\d{12}:policy\\/?[a-zA-Z_0-9+=,.@\\-_/]+]", "/", ".", "test", "(", "identifier", ")", ")", "{", "return", "Promise", ".", "resolve", "(", "identifier", ")", ";", "}", "// @TODO make this code more beautiful", "// Try ENV_PolicyName_stage", "let", "policyIdentifier", "=", "context", ".", "environment", "+", "'_'", "+", "identifier", "+", "'_'", "+", "context", ".", "stage", ";", "return", "getPolicyByName", "(", "policyIdentifier", ",", "searchParams", ")", ".", "then", "(", "policy", "=>", "{", "if", "(", "!", "policy", ")", "{", "// Try ENV_PolicyName", "policyIdentifier", "=", "context", ".", "environment", "+", "'_'", "+", "identifier", ";", "return", "getPolicyByName", "(", "policyIdentifier", ",", "searchParams", ")", ".", "then", "(", "policy", "=>", "{", "if", "(", "!", "policy", ")", "{", "// Try PolicyName", "return", "getPolicyByName", "(", "identifier", ",", "searchParams", ")", ".", "then", "(", "policy", "=>", "{", "if", "(", "!", "policy", ")", "{", "return", "findAndDeployPolicy", "(", "identifier", ",", "context", ")", ".", "then", "(", "report", "=>", "{", "if", "(", "!", "report", ")", "{", "throw", "new", "Error", "(", "'The policy '", "+", "identifier", "+", "' could not be found.'", ")", ";", "}", "return", "{", "Arn", ":", "report", ".", "arn", "}", ";", "}", ")", ";", "}", "return", "policy", ";", "}", ")", ";", "}", "return", "policy", ";", "}", ")", ";", "}", "return", "policy", ";", "}", ")", ".", "then", "(", "policy", "=>", "{", "return", "policy", ".", "Arn", ";", "}", ")", ";", "}" ]
Retrieve a policy Arn from a identifier that can be either the ARN or the name @param {String} identifier @param {[type]} context @param {[type]} searchParams @returns {[type]}
[ "Retrieve", "a", "policy", "Arn", "from", "a", "identifier", "that", "can", "be", "either", "the", "ARN", "or", "the", "name" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/iam/src/helper.js#L41-L80
36,941
myrmex-org/myrmex
packages/iam/src/helper.js
retrieveRoleArn
function retrieveRoleArn(identifier, context) { const iam = new AWS.IAM(); // First check if the parameter already is an ARN if (/arn:aws:iam::\d{12}:role\/?[a-zA-Z_0-9+=,.@\-_\/]+/.test(identifier)) { return Promise.resolve(identifier); } // Then, we check if a role exists with a name "ENVIRONMENT_identifier_stage" return iam.getRole({ RoleName: context.environment + '_' + identifier + '_' + context.stage }).promise() .then((data) => { return Promise.resolve(data.Role.Arn); }) .catch(e => { // If it failed, we check if a role exists with a name "ENVIRONMENT_identifier" return iam.getRole({ RoleName: context.environment + '_' + identifier }).promise() .then((data) => { return Promise.resolve(data.Role.Arn); }) .catch(e => { // If it failed again, we check if a role exists with a name "identifier" return iam.getRole({ RoleName: identifier }).promise() .then((data) => { return Promise.resolve(data.Role.Arn); }) .catch(e => { const plugin = require('./index'); return plugin.findRoles([identifier]) .then(roles => { if (roles.length === 1) { return roles[0].deploy(context) .then(report => { return Promise.resolve(report.arn); }); } return Promise.reject(new Error('Could not find role ' + identifier)); }); }); }); }); }
javascript
function retrieveRoleArn(identifier, context) { const iam = new AWS.IAM(); // First check if the parameter already is an ARN if (/arn:aws:iam::\d{12}:role\/?[a-zA-Z_0-9+=,.@\-_\/]+/.test(identifier)) { return Promise.resolve(identifier); } // Then, we check if a role exists with a name "ENVIRONMENT_identifier_stage" return iam.getRole({ RoleName: context.environment + '_' + identifier + '_' + context.stage }).promise() .then((data) => { return Promise.resolve(data.Role.Arn); }) .catch(e => { // If it failed, we check if a role exists with a name "ENVIRONMENT_identifier" return iam.getRole({ RoleName: context.environment + '_' + identifier }).promise() .then((data) => { return Promise.resolve(data.Role.Arn); }) .catch(e => { // If it failed again, we check if a role exists with a name "identifier" return iam.getRole({ RoleName: identifier }).promise() .then((data) => { return Promise.resolve(data.Role.Arn); }) .catch(e => { const plugin = require('./index'); return plugin.findRoles([identifier]) .then(roles => { if (roles.length === 1) { return roles[0].deploy(context) .then(report => { return Promise.resolve(report.arn); }); } return Promise.reject(new Error('Could not find role ' + identifier)); }); }); }); }); }
[ "function", "retrieveRoleArn", "(", "identifier", ",", "context", ")", "{", "const", "iam", "=", "new", "AWS", ".", "IAM", "(", ")", ";", "// First check if the parameter already is an ARN", "if", "(", "/", "arn:aws:iam::\\d{12}:role\\/?[a-zA-Z_0-9+=,.@\\-_\\/]+", "/", ".", "test", "(", "identifier", ")", ")", "{", "return", "Promise", ".", "resolve", "(", "identifier", ")", ";", "}", "// Then, we check if a role exists with a name \"ENVIRONMENT_identifier_stage\"", "return", "iam", ".", "getRole", "(", "{", "RoleName", ":", "context", ".", "environment", "+", "'_'", "+", "identifier", "+", "'_'", "+", "context", ".", "stage", "}", ")", ".", "promise", "(", ")", ".", "then", "(", "(", "data", ")", "=>", "{", "return", "Promise", ".", "resolve", "(", "data", ".", "Role", ".", "Arn", ")", ";", "}", ")", ".", "catch", "(", "e", "=>", "{", "// If it failed, we check if a role exists with a name \"ENVIRONMENT_identifier\"", "return", "iam", ".", "getRole", "(", "{", "RoleName", ":", "context", ".", "environment", "+", "'_'", "+", "identifier", "}", ")", ".", "promise", "(", ")", ".", "then", "(", "(", "data", ")", "=>", "{", "return", "Promise", ".", "resolve", "(", "data", ".", "Role", ".", "Arn", ")", ";", "}", ")", ".", "catch", "(", "e", "=>", "{", "// If it failed again, we check if a role exists with a name \"identifier\"", "return", "iam", ".", "getRole", "(", "{", "RoleName", ":", "identifier", "}", ")", ".", "promise", "(", ")", ".", "then", "(", "(", "data", ")", "=>", "{", "return", "Promise", ".", "resolve", "(", "data", ".", "Role", ".", "Arn", ")", ";", "}", ")", ".", "catch", "(", "e", "=>", "{", "const", "plugin", "=", "require", "(", "'./index'", ")", ";", "return", "plugin", ".", "findRoles", "(", "[", "identifier", "]", ")", ".", "then", "(", "roles", "=>", "{", "if", "(", "roles", ".", "length", "===", "1", ")", "{", "return", "roles", "[", "0", "]", ".", "deploy", "(", "context", ")", ".", "then", "(", "report", "=>", "{", "return", "Promise", ".", "resolve", "(", "report", ".", "arn", ")", ";", "}", ")", ";", "}", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "'Could not find role '", "+", "identifier", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Takes a role ARN, or a role name as parameter, requests AWS, and retruns the ARN of a role matching the ARN or the role name or the role name with context informations @param {string} identifier - a role ARN, or a role name @param {Object} context - an object containing the stage and the environment @return {string} - an AWS role ARN
[ "Takes", "a", "role", "ARN", "or", "a", "role", "name", "as", "parameter", "requests", "AWS", "and", "retruns", "the", "ARN", "of", "a", "role", "matching", "the", "ARN", "or", "the", "role", "name", "or", "the", "role", "name", "with", "context", "informations" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/iam/src/helper.js#L99-L137
36,942
borela-tech/js-toolbox
src/configs/webpack/rules/default.js
fileName
function fileName(file) { let prefix = null let reference = null if (isPathSubDirOf(file, PROJECT_DIR)) { // Assets from the target project. prefix = [] reference = PROJECT_DIR } else if (isPathSubDirOf(file, TOOLBOX_DIR)) { // Assets from the Toolbox. prefix = ['__borela__'] reference = TOOLBOX_DIR } const RELATIVE = relative(reference, file) let nodes = RELATIVE.split(sep) if (nodes[0] === 'src') nodes.shift() if (prefix.length > 0) nodes = [...prefix, ...nodes] return `${nodes.join('/')}?[sha512:hash:base64:8]` }
javascript
function fileName(file) { let prefix = null let reference = null if (isPathSubDirOf(file, PROJECT_DIR)) { // Assets from the target project. prefix = [] reference = PROJECT_DIR } else if (isPathSubDirOf(file, TOOLBOX_DIR)) { // Assets from the Toolbox. prefix = ['__borela__'] reference = TOOLBOX_DIR } const RELATIVE = relative(reference, file) let nodes = RELATIVE.split(sep) if (nodes[0] === 'src') nodes.shift() if (prefix.length > 0) nodes = [...prefix, ...nodes] return `${nodes.join('/')}?[sha512:hash:base64:8]` }
[ "function", "fileName", "(", "file", ")", "{", "let", "prefix", "=", "null", "let", "reference", "=", "null", "if", "(", "isPathSubDirOf", "(", "file", ",", "PROJECT_DIR", ")", ")", "{", "// Assets from the target project.", "prefix", "=", "[", "]", "reference", "=", "PROJECT_DIR", "}", "else", "if", "(", "isPathSubDirOf", "(", "file", ",", "TOOLBOX_DIR", ")", ")", "{", "// Assets from the Toolbox.", "prefix", "=", "[", "'__borela__'", "]", "reference", "=", "TOOLBOX_DIR", "}", "const", "RELATIVE", "=", "relative", "(", "reference", ",", "file", ")", "let", "nodes", "=", "RELATIVE", ".", "split", "(", "sep", ")", "if", "(", "nodes", "[", "0", "]", "===", "'src'", ")", "nodes", ".", "shift", "(", ")", "if", "(", "prefix", ".", "length", ">", "0", ")", "nodes", "=", "[", "...", "prefix", ",", "...", "nodes", "]", "return", "`", "${", "nodes", ".", "join", "(", "'/'", ")", "}", "`", "}" ]
Calculate the file path for the loaded asset.
[ "Calculate", "the", "file", "path", "for", "the", "loaded", "asset", "." ]
0ed75d373fa1573d64a3d715ee8e6e24852824e4
https://github.com/borela-tech/js-toolbox/blob/0ed75d373fa1573d64a3d715ee8e6e24852824e4/src/configs/webpack/rules/default.js#L26-L50
36,943
doug-martin/coddoc
lib/parser/index.js
function (commentObj, code, filepath, context, emitter) { var tagRegexp = tags.getTagRegexp(); var sym = new Symbol({file:filepath}); var comment = commentObj.comment, match = tagRegexp.exec(comment), description, l = comment.length, i; if (match && match[1]) { parseCode(code, commentObj.end, sym, context); i = match.index; sym.description = comment.substr(0, i); comment = comment.substr(i); i = 0; while (i < l) { var subComment = comment.substr(i), nextIndex; match = tagRegexp.exec(comment.substr(i + 2)); if (match && match[1]) { nextIndex = match.index; nextIndex += i + 1; parseTag(comment.substr(i, nextIndex - i), sym, context); i = nextIndex; } else { parseTag(subComment, sym, context); i = l; } } } else { parseCode(code, commentObj.end, sym, context); sym.description = comment; } sym.fullName = sym.memberof ? [sym.memberof, sym.name].join(".") : sym.name; return {symbol:sym, comment:comment}; }
javascript
function (commentObj, code, filepath, context, emitter) { var tagRegexp = tags.getTagRegexp(); var sym = new Symbol({file:filepath}); var comment = commentObj.comment, match = tagRegexp.exec(comment), description, l = comment.length, i; if (match && match[1]) { parseCode(code, commentObj.end, sym, context); i = match.index; sym.description = comment.substr(0, i); comment = comment.substr(i); i = 0; while (i < l) { var subComment = comment.substr(i), nextIndex; match = tagRegexp.exec(comment.substr(i + 2)); if (match && match[1]) { nextIndex = match.index; nextIndex += i + 1; parseTag(comment.substr(i, nextIndex - i), sym, context); i = nextIndex; } else { parseTag(subComment, sym, context); i = l; } } } else { parseCode(code, commentObj.end, sym, context); sym.description = comment; } sym.fullName = sym.memberof ? [sym.memberof, sym.name].join(".") : sym.name; return {symbol:sym, comment:comment}; }
[ "function", "(", "commentObj", ",", "code", ",", "filepath", ",", "context", ",", "emitter", ")", "{", "var", "tagRegexp", "=", "tags", ".", "getTagRegexp", "(", ")", ";", "var", "sym", "=", "new", "Symbol", "(", "{", "file", ":", "filepath", "}", ")", ";", "var", "comment", "=", "commentObj", ".", "comment", ",", "match", "=", "tagRegexp", ".", "exec", "(", "comment", ")", ",", "description", ",", "l", "=", "comment", ".", "length", ",", "i", ";", "if", "(", "match", "&&", "match", "[", "1", "]", ")", "{", "parseCode", "(", "code", ",", "commentObj", ".", "end", ",", "sym", ",", "context", ")", ";", "i", "=", "match", ".", "index", ";", "sym", ".", "description", "=", "comment", ".", "substr", "(", "0", ",", "i", ")", ";", "comment", "=", "comment", ".", "substr", "(", "i", ")", ";", "i", "=", "0", ";", "while", "(", "i", "<", "l", ")", "{", "var", "subComment", "=", "comment", ".", "substr", "(", "i", ")", ",", "nextIndex", ";", "match", "=", "tagRegexp", ".", "exec", "(", "comment", ".", "substr", "(", "i", "+", "2", ")", ")", ";", "if", "(", "match", "&&", "match", "[", "1", "]", ")", "{", "nextIndex", "=", "match", ".", "index", ";", "nextIndex", "+=", "i", "+", "1", ";", "parseTag", "(", "comment", ".", "substr", "(", "i", ",", "nextIndex", "-", "i", ")", ",", "sym", ",", "context", ")", ";", "i", "=", "nextIndex", ";", "}", "else", "{", "parseTag", "(", "subComment", ",", "sym", ",", "context", ")", ";", "i", "=", "l", ";", "}", "}", "}", "else", "{", "parseCode", "(", "code", ",", "commentObj", ".", "end", ",", "sym", ",", "context", ")", ";", "sym", ".", "description", "=", "comment", ";", "}", "sym", ".", "fullName", "=", "sym", ".", "memberof", "?", "[", "sym", ".", "memberof", ",", "sym", ".", "name", "]", ".", "join", "(", "\".\"", ")", ":", "sym", ".", "name", ";", "return", "{", "symbol", ":", "sym", ",", "comment", ":", "comment", "}", ";", "}" ]
Parses tags from a comment string. @ignore @param commentObj @param code @param filepath @param context @param emitter @return {Object}
[ "Parses", "tags", "from", "a", "comment", "string", "." ]
9950a4d5e76e7c77e25c3b56b54ba6690f30be1f
https://github.com/doug-martin/coddoc/blob/9950a4d5e76e7c77e25c3b56b54ba6690f30be1f/lib/parser/index.js#L31-L62
36,944
myrmex-org/myrmex
packages/cli/src/load-project.js
getProjectRootDirectory
function getProjectRootDirectory() { // From the current directory, check if parent directories have a package.json file and if it contains // a reference to the @myrmex/core node_module let cwd = process.cwd(); let packageJson; let found = false; do { try { packageJson = require(path.join(cwd, 'package.json')); if ((packageJson.dependencies && packageJson.dependencies['@myrmex/core']) || (packageJson.devDependencies && packageJson.devDependencies['@myrmex/core'])) { found = true; } else { cwd = path.dirname(cwd); } } catch (e) { cwd = path.dirname(cwd); } } while (cwd !== path.dirname(cwd) && !found); if (found) { return cwd; } return false; }
javascript
function getProjectRootDirectory() { // From the current directory, check if parent directories have a package.json file and if it contains // a reference to the @myrmex/core node_module let cwd = process.cwd(); let packageJson; let found = false; do { try { packageJson = require(path.join(cwd, 'package.json')); if ((packageJson.dependencies && packageJson.dependencies['@myrmex/core']) || (packageJson.devDependencies && packageJson.devDependencies['@myrmex/core'])) { found = true; } else { cwd = path.dirname(cwd); } } catch (e) { cwd = path.dirname(cwd); } } while (cwd !== path.dirname(cwd) && !found); if (found) { return cwd; } return false; }
[ "function", "getProjectRootDirectory", "(", ")", "{", "// From the current directory, check if parent directories have a package.json file and if it contains", "// a reference to the @myrmex/core node_module", "let", "cwd", "=", "process", ".", "cwd", "(", ")", ";", "let", "packageJson", ";", "let", "found", "=", "false", ";", "do", "{", "try", "{", "packageJson", "=", "require", "(", "path", ".", "join", "(", "cwd", ",", "'package.json'", ")", ")", ";", "if", "(", "(", "packageJson", ".", "dependencies", "&&", "packageJson", ".", "dependencies", "[", "'@myrmex/core'", "]", ")", "||", "(", "packageJson", ".", "devDependencies", "&&", "packageJson", ".", "devDependencies", "[", "'@myrmex/core'", "]", ")", ")", "{", "found", "=", "true", ";", "}", "else", "{", "cwd", "=", "path", ".", "dirname", "(", "cwd", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "cwd", "=", "path", ".", "dirname", "(", "cwd", ")", ";", "}", "}", "while", "(", "cwd", "!==", "path", ".", "dirname", "(", "cwd", ")", "&&", "!", "found", ")", ";", "if", "(", "found", ")", "{", "return", "cwd", ";", "}", "return", "false", ";", "}" ]
Check if the script is called from a myrmex project and return the root directory @return {string|bool} - false if the script is not called inside a myrmex project, or else, the path to the project root
[ "Check", "if", "the", "script", "is", "called", "from", "a", "myrmex", "project", "and", "return", "the", "root", "directory" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/cli/src/load-project.js#L59-L83
36,945
myrmex-org/myrmex
packages/cli/src/load-project.js
getConfig
function getConfig() { // Load the myrmex main configuration file let config = {}; try { // try to load a myrmex.json or myrmex.js file config = require(path.join(process.cwd(), 'myrmex')); } catch (e) { // Silently ignore if there is no configuration file return config; } config.config = config.config || {}; // Load sub-configuration files config.configPath = config.configPath || './config'; const configPath = path.join(process.cwd(), config.configPath); let files = []; try { files = fs.readdirSync(configPath); } catch (e) { // Silently ignore if there is no configuration directory } files.forEach(file => { const parse = path.parse(file); // We load all .js and .json files in the configuration directory if (['.js', '.json'].indexOf(parse.ext) !== -1) { config.config[parse.name] = _.merge(config.config[parse.name] || {}, require(path.join(configPath, file))); } }); // Add configuration passed by environment variables Object.keys(process.env).forEach(key => { const prefix = 'MYRMEX_'; if (key.substring(0, prefix.length) === prefix) { // We transform // MYRMEX_myConfig_levels = value // into // { config: { myConfig: { levels: value } } } function addParts(config, parts, value) { const part = parts.shift(); if (parts.length === 0) { // Convert string values "true" and "false" to booleans if (value === 'false') { value = false; } if (value === 'true') { value = true; } config[part] = value; } else { if (config[part] === undefined) { config[part] = {}; } addParts(config[part], parts, value); } } addParts(config.config, key.substring(prefix.length).split('_'), process.env[key]); } }); return config; }
javascript
function getConfig() { // Load the myrmex main configuration file let config = {}; try { // try to load a myrmex.json or myrmex.js file config = require(path.join(process.cwd(), 'myrmex')); } catch (e) { // Silently ignore if there is no configuration file return config; } config.config = config.config || {}; // Load sub-configuration files config.configPath = config.configPath || './config'; const configPath = path.join(process.cwd(), config.configPath); let files = []; try { files = fs.readdirSync(configPath); } catch (e) { // Silently ignore if there is no configuration directory } files.forEach(file => { const parse = path.parse(file); // We load all .js and .json files in the configuration directory if (['.js', '.json'].indexOf(parse.ext) !== -1) { config.config[parse.name] = _.merge(config.config[parse.name] || {}, require(path.join(configPath, file))); } }); // Add configuration passed by environment variables Object.keys(process.env).forEach(key => { const prefix = 'MYRMEX_'; if (key.substring(0, prefix.length) === prefix) { // We transform // MYRMEX_myConfig_levels = value // into // { config: { myConfig: { levels: value } } } function addParts(config, parts, value) { const part = parts.shift(); if (parts.length === 0) { // Convert string values "true" and "false" to booleans if (value === 'false') { value = false; } if (value === 'true') { value = true; } config[part] = value; } else { if (config[part] === undefined) { config[part] = {}; } addParts(config[part], parts, value); } } addParts(config.config, key.substring(prefix.length).split('_'), process.env[key]); } }); return config; }
[ "function", "getConfig", "(", ")", "{", "// Load the myrmex main configuration file", "let", "config", "=", "{", "}", ";", "try", "{", "// try to load a myrmex.json or myrmex.js file", "config", "=", "require", "(", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "'myrmex'", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "// Silently ignore if there is no configuration file", "return", "config", ";", "}", "config", ".", "config", "=", "config", ".", "config", "||", "{", "}", ";", "// Load sub-configuration files", "config", ".", "configPath", "=", "config", ".", "configPath", "||", "'./config'", ";", "const", "configPath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "config", ".", "configPath", ")", ";", "let", "files", "=", "[", "]", ";", "try", "{", "files", "=", "fs", ".", "readdirSync", "(", "configPath", ")", ";", "}", "catch", "(", "e", ")", "{", "// Silently ignore if there is no configuration directory", "}", "files", ".", "forEach", "(", "file", "=>", "{", "const", "parse", "=", "path", ".", "parse", "(", "file", ")", ";", "// We load all .js and .json files in the configuration directory", "if", "(", "[", "'.js'", ",", "'.json'", "]", ".", "indexOf", "(", "parse", ".", "ext", ")", "!==", "-", "1", ")", "{", "config", ".", "config", "[", "parse", ".", "name", "]", "=", "_", ".", "merge", "(", "config", ".", "config", "[", "parse", ".", "name", "]", "||", "{", "}", ",", "require", "(", "path", ".", "join", "(", "configPath", ",", "file", ")", ")", ")", ";", "}", "}", ")", ";", "// Add configuration passed by environment variables", "Object", ".", "keys", "(", "process", ".", "env", ")", ".", "forEach", "(", "key", "=>", "{", "const", "prefix", "=", "'MYRMEX_'", ";", "if", "(", "key", ".", "substring", "(", "0", ",", "prefix", ".", "length", ")", "===", "prefix", ")", "{", "// We transform", "// MYRMEX_myConfig_levels = value", "// into", "// { config: { myConfig: { levels: value } } }", "function", "addParts", "(", "config", ",", "parts", ",", "value", ")", "{", "const", "part", "=", "parts", ".", "shift", "(", ")", ";", "if", "(", "parts", ".", "length", "===", "0", ")", "{", "// Convert string values \"true\" and \"false\" to booleans", "if", "(", "value", "===", "'false'", ")", "{", "value", "=", "false", ";", "}", "if", "(", "value", "===", "'true'", ")", "{", "value", "=", "true", ";", "}", "config", "[", "part", "]", "=", "value", ";", "}", "else", "{", "if", "(", "config", "[", "part", "]", "===", "undefined", ")", "{", "config", "[", "part", "]", "=", "{", "}", ";", "}", "addParts", "(", "config", "[", "part", "]", ",", "parts", ",", "value", ")", ";", "}", "}", "addParts", "(", "config", ".", "config", ",", "key", ".", "substring", "(", "prefix", ".", "length", ")", ".", "split", "(", "'_'", ")", ",", "process", ".", "env", "[", "key", "]", ")", ";", "}", "}", ")", ";", "return", "config", ";", "}" ]
Check if the directory in which the command is launched contains a myrmex.json configuration file and return it @return {Object} - an object that will be consumed by a Myrmex instance
[ "Check", "if", "the", "directory", "in", "which", "the", "command", "is", "launched", "contains", "a", "myrmex", ".", "json", "configuration", "file", "and", "return", "it" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/cli/src/load-project.js#L108-L165
36,946
myrmex-org/myrmex
packages/cloud-formation/src/index.js
loadTemplate
function loadTemplate(templatePath, identifier) { return plugin.myrmex.fire('beforeTemplateLoad', templatePath, identifier) .spread((templatePath, name) => { const templateDoc = _.cloneDeep(require(path.join(templatePath))); // Lasy loading because the plugin has to be registered in a Myrmex instance before requiring the document const Template = require('./template'); const template = new Template(templateDoc, identifier); // This event allows to inject code to alter the template configuration return plugin.myrmex.fire('afterTemplateLoad', template); }) .spread(template => { return Promise.resolve(template); }); }
javascript
function loadTemplate(templatePath, identifier) { return plugin.myrmex.fire('beforeTemplateLoad', templatePath, identifier) .spread((templatePath, name) => { const templateDoc = _.cloneDeep(require(path.join(templatePath))); // Lasy loading because the plugin has to be registered in a Myrmex instance before requiring the document const Template = require('./template'); const template = new Template(templateDoc, identifier); // This event allows to inject code to alter the template configuration return plugin.myrmex.fire('afterTemplateLoad', template); }) .spread(template => { return Promise.resolve(template); }); }
[ "function", "loadTemplate", "(", "templatePath", ",", "identifier", ")", "{", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'beforeTemplateLoad'", ",", "templatePath", ",", "identifier", ")", ".", "spread", "(", "(", "templatePath", ",", "name", ")", "=>", "{", "const", "templateDoc", "=", "_", ".", "cloneDeep", "(", "require", "(", "path", ".", "join", "(", "templatePath", ")", ")", ")", ";", "// Lasy loading because the plugin has to be registered in a Myrmex instance before requiring the document", "const", "Template", "=", "require", "(", "'./template'", ")", ";", "const", "template", "=", "new", "Template", "(", "templateDoc", ",", "identifier", ")", ";", "// This event allows to inject code to alter the template configuration", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'afterTemplateLoad'", ",", "template", ")", ";", "}", ")", ".", "spread", "(", "template", "=>", "{", "return", "Promise", ".", "resolve", "(", "template", ")", ";", "}", ")", ";", "}" ]
Load a Template object @param {string} templatePath - path to the template file @param {string} identifier - identifier od the template @return {Promise<Template>} - promise of a Cloud Formation template
[ "Load", "a", "Template", "object" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/cloud-formation/src/index.js#L52-L67
36,947
shisama/toggle-fullscreen
lib/index.js
toggleFullscreen
function toggleFullscreen(element, callback) { if (callback && typeof callback === 'function') { if (!isFullscreen()) { var fn = function (e) { if (isFullscreen()) { callback(true); } else { callback(false); } }; fullscreenChange(fn); enterFullscreen(element); } else { exitFullscreen(); callback(false); } return Promise.resolve(); } return new Promise(function (resolve) { if (!isFullscreen()) { enterFullscreen(element); } else { exitFullscreen(); } resolve(); }); /** * enter fullscreen mode. * @param {Element} element */ function enterFullscreen(element) { var userAgent = navigator.userAgent.toLowerCase(); if (element.requestFullscreen) { element.requestFullscreen(); } else if (element.msRequestFullscreen) { element.msRequestFullscreen(); } else if (element.mozRequestFullScreen) { element.parentElement.mozRequestFullScreen(); } else if (userAgent.indexOf('edge') != -1) { element.parentElement.webkitRequestFullscreen(); } else if (element.webkitRequestFullscreen) { element.webkitRequestFullscreen(); } } /** * exit fullscreen mode. */ function exitFullscreen() { var _doument = document; if (document.exitFullscreen) { document.exitFullscreen(); } else if (_doument.msExitFullscreen) { _doument.msExitFullscreen(); } else if (_doument.mozCancelFullScreen) { _doument.mozCancelFullScreen(); } else if (_doument.webkitExitFullscreen) { _doument.webkitExitFullscreen(); } } }
javascript
function toggleFullscreen(element, callback) { if (callback && typeof callback === 'function') { if (!isFullscreen()) { var fn = function (e) { if (isFullscreen()) { callback(true); } else { callback(false); } }; fullscreenChange(fn); enterFullscreen(element); } else { exitFullscreen(); callback(false); } return Promise.resolve(); } return new Promise(function (resolve) { if (!isFullscreen()) { enterFullscreen(element); } else { exitFullscreen(); } resolve(); }); /** * enter fullscreen mode. * @param {Element} element */ function enterFullscreen(element) { var userAgent = navigator.userAgent.toLowerCase(); if (element.requestFullscreen) { element.requestFullscreen(); } else if (element.msRequestFullscreen) { element.msRequestFullscreen(); } else if (element.mozRequestFullScreen) { element.parentElement.mozRequestFullScreen(); } else if (userAgent.indexOf('edge') != -1) { element.parentElement.webkitRequestFullscreen(); } else if (element.webkitRequestFullscreen) { element.webkitRequestFullscreen(); } } /** * exit fullscreen mode. */ function exitFullscreen() { var _doument = document; if (document.exitFullscreen) { document.exitFullscreen(); } else if (_doument.msExitFullscreen) { _doument.msExitFullscreen(); } else if (_doument.mozCancelFullScreen) { _doument.mozCancelFullScreen(); } else if (_doument.webkitExitFullscreen) { _doument.webkitExitFullscreen(); } } }
[ "function", "toggleFullscreen", "(", "element", ",", "callback", ")", "{", "if", "(", "callback", "&&", "typeof", "callback", "===", "'function'", ")", "{", "if", "(", "!", "isFullscreen", "(", ")", ")", "{", "var", "fn", "=", "function", "(", "e", ")", "{", "if", "(", "isFullscreen", "(", ")", ")", "{", "callback", "(", "true", ")", ";", "}", "else", "{", "callback", "(", "false", ")", ";", "}", "}", ";", "fullscreenChange", "(", "fn", ")", ";", "enterFullscreen", "(", "element", ")", ";", "}", "else", "{", "exitFullscreen", "(", ")", ";", "callback", "(", "false", ")", ";", "}", "return", "Promise", ".", "resolve", "(", ")", ";", "}", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "if", "(", "!", "isFullscreen", "(", ")", ")", "{", "enterFullscreen", "(", "element", ")", ";", "}", "else", "{", "exitFullscreen", "(", ")", ";", "}", "resolve", "(", ")", ";", "}", ")", ";", "/**\n * enter fullscreen mode.\n * @param {Element} element\n */", "function", "enterFullscreen", "(", "element", ")", "{", "var", "userAgent", "=", "navigator", ".", "userAgent", ".", "toLowerCase", "(", ")", ";", "if", "(", "element", ".", "requestFullscreen", ")", "{", "element", ".", "requestFullscreen", "(", ")", ";", "}", "else", "if", "(", "element", ".", "msRequestFullscreen", ")", "{", "element", ".", "msRequestFullscreen", "(", ")", ";", "}", "else", "if", "(", "element", ".", "mozRequestFullScreen", ")", "{", "element", ".", "parentElement", ".", "mozRequestFullScreen", "(", ")", ";", "}", "else", "if", "(", "userAgent", ".", "indexOf", "(", "'edge'", ")", "!=", "-", "1", ")", "{", "element", ".", "parentElement", ".", "webkitRequestFullscreen", "(", ")", ";", "}", "else", "if", "(", "element", ".", "webkitRequestFullscreen", ")", "{", "element", ".", "webkitRequestFullscreen", "(", ")", ";", "}", "}", "/**\n * exit fullscreen mode.\n */", "function", "exitFullscreen", "(", ")", "{", "var", "_doument", "=", "document", ";", "if", "(", "document", ".", "exitFullscreen", ")", "{", "document", ".", "exitFullscreen", "(", ")", ";", "}", "else", "if", "(", "_doument", ".", "msExitFullscreen", ")", "{", "_doument", ".", "msExitFullscreen", "(", ")", ";", "}", "else", "if", "(", "_doument", ".", "mozCancelFullScreen", ")", "{", "_doument", ".", "mozCancelFullScreen", "(", ")", ";", "}", "else", "if", "(", "_doument", ".", "webkitExitFullscreen", ")", "{", "_doument", ".", "webkitExitFullscreen", "(", ")", ";", "}", "}", "}" ]
switch target DOMElement to fullscreen mode. @param element {Element} DOMElement that you want to make fullscreen.
[ "switch", "target", "DOMElement", "to", "fullscreen", "mode", "." ]
9bccd4fc00d829f747e1f8824b6753079068193e
https://github.com/shisama/toggle-fullscreen/blob/9bccd4fc00d829f747e1f8824b6753079068193e/lib/index.js#L8-L77
36,948
shisama/toggle-fullscreen
lib/index.js
enterFullscreen
function enterFullscreen(element) { var userAgent = navigator.userAgent.toLowerCase(); if (element.requestFullscreen) { element.requestFullscreen(); } else if (element.msRequestFullscreen) { element.msRequestFullscreen(); } else if (element.mozRequestFullScreen) { element.parentElement.mozRequestFullScreen(); } else if (userAgent.indexOf('edge') != -1) { element.parentElement.webkitRequestFullscreen(); } else if (element.webkitRequestFullscreen) { element.webkitRequestFullscreen(); } }
javascript
function enterFullscreen(element) { var userAgent = navigator.userAgent.toLowerCase(); if (element.requestFullscreen) { element.requestFullscreen(); } else if (element.msRequestFullscreen) { element.msRequestFullscreen(); } else if (element.mozRequestFullScreen) { element.parentElement.mozRequestFullScreen(); } else if (userAgent.indexOf('edge') != -1) { element.parentElement.webkitRequestFullscreen(); } else if (element.webkitRequestFullscreen) { element.webkitRequestFullscreen(); } }
[ "function", "enterFullscreen", "(", "element", ")", "{", "var", "userAgent", "=", "navigator", ".", "userAgent", ".", "toLowerCase", "(", ")", ";", "if", "(", "element", ".", "requestFullscreen", ")", "{", "element", ".", "requestFullscreen", "(", ")", ";", "}", "else", "if", "(", "element", ".", "msRequestFullscreen", ")", "{", "element", ".", "msRequestFullscreen", "(", ")", ";", "}", "else", "if", "(", "element", ".", "mozRequestFullScreen", ")", "{", "element", ".", "parentElement", ".", "mozRequestFullScreen", "(", ")", ";", "}", "else", "if", "(", "userAgent", ".", "indexOf", "(", "'edge'", ")", "!=", "-", "1", ")", "{", "element", ".", "parentElement", ".", "webkitRequestFullscreen", "(", ")", ";", "}", "else", "if", "(", "element", ".", "webkitRequestFullscreen", ")", "{", "element", ".", "webkitRequestFullscreen", "(", ")", ";", "}", "}" ]
enter fullscreen mode. @param {Element} element
[ "enter", "fullscreen", "mode", "." ]
9bccd4fc00d829f747e1f8824b6753079068193e
https://github.com/shisama/toggle-fullscreen/blob/9bccd4fc00d829f747e1f8824b6753079068193e/lib/index.js#L41-L58
36,949
shisama/toggle-fullscreen
lib/index.js
exitFullscreen
function exitFullscreen() { var _doument = document; if (document.exitFullscreen) { document.exitFullscreen(); } else if (_doument.msExitFullscreen) { _doument.msExitFullscreen(); } else if (_doument.mozCancelFullScreen) { _doument.mozCancelFullScreen(); } else if (_doument.webkitExitFullscreen) { _doument.webkitExitFullscreen(); } }
javascript
function exitFullscreen() { var _doument = document; if (document.exitFullscreen) { document.exitFullscreen(); } else if (_doument.msExitFullscreen) { _doument.msExitFullscreen(); } else if (_doument.mozCancelFullScreen) { _doument.mozCancelFullScreen(); } else if (_doument.webkitExitFullscreen) { _doument.webkitExitFullscreen(); } }
[ "function", "exitFullscreen", "(", ")", "{", "var", "_doument", "=", "document", ";", "if", "(", "document", ".", "exitFullscreen", ")", "{", "document", ".", "exitFullscreen", "(", ")", ";", "}", "else", "if", "(", "_doument", ".", "msExitFullscreen", ")", "{", "_doument", ".", "msExitFullscreen", "(", ")", ";", "}", "else", "if", "(", "_doument", ".", "mozCancelFullScreen", ")", "{", "_doument", ".", "mozCancelFullScreen", "(", ")", ";", "}", "else", "if", "(", "_doument", ".", "webkitExitFullscreen", ")", "{", "_doument", ".", "webkitExitFullscreen", "(", ")", ";", "}", "}" ]
exit fullscreen mode.
[ "exit", "fullscreen", "mode", "." ]
9bccd4fc00d829f747e1f8824b6753079068193e
https://github.com/shisama/toggle-fullscreen/blob/9bccd4fc00d829f747e1f8824b6753079068193e/lib/index.js#L62-L76
36,950
shisama/toggle-fullscreen
lib/index.js
isFullscreen
function isFullscreen() { var _document = document; if (!_document.fullscreenElement && !_document.mozFullScreenElement && !_document.webkitFullscreenElement && !_document.msFullscreenElement) { return false; } return true; }
javascript
function isFullscreen() { var _document = document; if (!_document.fullscreenElement && !_document.mozFullScreenElement && !_document.webkitFullscreenElement && !_document.msFullscreenElement) { return false; } return true; }
[ "function", "isFullscreen", "(", ")", "{", "var", "_document", "=", "document", ";", "if", "(", "!", "_document", ".", "fullscreenElement", "&&", "!", "_document", ".", "mozFullScreenElement", "&&", "!", "_document", ".", "webkitFullscreenElement", "&&", "!", "_document", ".", "msFullscreenElement", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
check if fullscreen or not. @returns {boolean}
[ "check", "if", "fullscreen", "or", "not", "." ]
9bccd4fc00d829f747e1f8824b6753079068193e
https://github.com/shisama/toggle-fullscreen/blob/9bccd4fc00d829f747e1f8824b6753079068193e/lib/index.js#L83-L92
36,951
shisama/toggle-fullscreen
lib/index.js
fullscreenChange
function fullscreenChange(callback) { var _document = document; return new Promise(function (resolve, reject) { if (document.fullscreenEnabled) { document.addEventListener('fullscreenchange', callback); } else if (_document.mozFullScreenEnabled) { _document.addEventListener('mozfullscreenchange', callback); } else if (_document.webkitFullscreenEnabled) { _document.addEventListener('webkitfullscreenchange', callback); //Safari _document.addEventListener('fullscreenChange', callback); // Edge } else if (_document.msFullscreenEnabled) { _document.addEventListener('MSFullscreenChange', callback); } else { reject(); } resolve(); }); }
javascript
function fullscreenChange(callback) { var _document = document; return new Promise(function (resolve, reject) { if (document.fullscreenEnabled) { document.addEventListener('fullscreenchange', callback); } else if (_document.mozFullScreenEnabled) { _document.addEventListener('mozfullscreenchange', callback); } else if (_document.webkitFullscreenEnabled) { _document.addEventListener('webkitfullscreenchange', callback); //Safari _document.addEventListener('fullscreenChange', callback); // Edge } else if (_document.msFullscreenEnabled) { _document.addEventListener('MSFullscreenChange', callback); } else { reject(); } resolve(); }); }
[ "function", "fullscreenChange", "(", "callback", ")", "{", "var", "_document", "=", "document", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "document", ".", "fullscreenEnabled", ")", "{", "document", ".", "addEventListener", "(", "'fullscreenchange'", ",", "callback", ")", ";", "}", "else", "if", "(", "_document", ".", "mozFullScreenEnabled", ")", "{", "_document", ".", "addEventListener", "(", "'mozfullscreenchange'", ",", "callback", ")", ";", "}", "else", "if", "(", "_document", ".", "webkitFullscreenEnabled", ")", "{", "_document", ".", "addEventListener", "(", "'webkitfullscreenchange'", ",", "callback", ")", ";", "//Safari", "_document", ".", "addEventListener", "(", "'fullscreenChange'", ",", "callback", ")", ";", "// Edge", "}", "else", "if", "(", "_document", ".", "msFullscreenEnabled", ")", "{", "_document", ".", "addEventListener", "(", "'MSFullscreenChange'", ",", "callback", ")", ";", "}", "else", "{", "reject", "(", ")", ";", "}", "resolve", "(", ")", ";", "}", ")", ";", "}" ]
add eventListener 'fullscreenchange' @param callback @return {Promise}
[ "add", "eventListener", "fullscreenchange" ]
9bccd4fc00d829f747e1f8824b6753079068193e
https://github.com/shisama/toggle-fullscreen/blob/9bccd4fc00d829f747e1f8824b6753079068193e/lib/index.js#L99-L120
36,952
evan-duncan/log-rotator
lib/logRotator.js
timeInMs
function timeInMs(time) { var HOUR_IN_MS = 3.6e+6, DAY_IN_MS = HOUR_IN_MS * 24, WK_IN_MS = DAY_IN_MS * 7, MS_DICTIONARY = { 'weeks': WK_IN_MS, 'week': WK_IN_MS, 'w': WK_IN_MS, 'days': DAY_IN_MS, 'day': DAY_IN_MS, 'd': DAY_IN_MS, 'hours': HOUR_IN_MS, 'hour': HOUR_IN_MS, 'h': HOUR_IN_MS }; var duration = parseInt(time, 10); var interval = time.replace(/\d*[\d]/, '').trim(); if (Object.keys(MS_DICTIONARY).indexOf(interval) < 0) { throw new Error('Interval is invalid. The ttl must be of weeks, days, or hours'); } return MS_DICTIONARY[interval] * duration; }
javascript
function timeInMs(time) { var HOUR_IN_MS = 3.6e+6, DAY_IN_MS = HOUR_IN_MS * 24, WK_IN_MS = DAY_IN_MS * 7, MS_DICTIONARY = { 'weeks': WK_IN_MS, 'week': WK_IN_MS, 'w': WK_IN_MS, 'days': DAY_IN_MS, 'day': DAY_IN_MS, 'd': DAY_IN_MS, 'hours': HOUR_IN_MS, 'hour': HOUR_IN_MS, 'h': HOUR_IN_MS }; var duration = parseInt(time, 10); var interval = time.replace(/\d*[\d]/, '').trim(); if (Object.keys(MS_DICTIONARY).indexOf(interval) < 0) { throw new Error('Interval is invalid. The ttl must be of weeks, days, or hours'); } return MS_DICTIONARY[interval] * duration; }
[ "function", "timeInMs", "(", "time", ")", "{", "var", "HOUR_IN_MS", "=", "3.6e+6", ",", "DAY_IN_MS", "=", "HOUR_IN_MS", "*", "24", ",", "WK_IN_MS", "=", "DAY_IN_MS", "*", "7", ",", "MS_DICTIONARY", "=", "{", "'weeks'", ":", "WK_IN_MS", ",", "'week'", ":", "WK_IN_MS", ",", "'w'", ":", "WK_IN_MS", ",", "'days'", ":", "DAY_IN_MS", ",", "'day'", ":", "DAY_IN_MS", ",", "'d'", ":", "DAY_IN_MS", ",", "'hours'", ":", "HOUR_IN_MS", ",", "'hour'", ":", "HOUR_IN_MS", ",", "'h'", ":", "HOUR_IN_MS", "}", ";", "var", "duration", "=", "parseInt", "(", "time", ",", "10", ")", ";", "var", "interval", "=", "time", ".", "replace", "(", "/", "\\d*[\\d]", "/", ",", "''", ")", ".", "trim", "(", ")", ";", "if", "(", "Object", ".", "keys", "(", "MS_DICTIONARY", ")", ".", "indexOf", "(", "interval", ")", "<", "0", ")", "{", "throw", "new", "Error", "(", "'Interval is invalid. The ttl must be of weeks, days, or hours'", ")", ";", "}", "return", "MS_DICTIONARY", "[", "interval", "]", "*", "duration", ";", "}" ]
Get the time in ms @param {String} time - The time as a string. @example timeInMs('24h'); // => 8.64e+7 @return {Number}
[ "Get", "the", "time", "in", "ms" ]
833f422f94caf1a2d2ceaf450c232480481cc1cc
https://github.com/evan-duncan/log-rotator/blob/833f422f94caf1a2d2ceaf450c232480481cc1cc/lib/logRotator.js#L95-L119
36,953
myrmex-org/myrmex
packages/api-gateway/src/index.js
loadApis
function loadApis() { // Shortcut if apis already have been loaded if (apis !== undefined) { return Promise.resolve(apis); } const apiSpecsPath = path.join(process.cwd(), plugin.config.apisPath); // This event allows to inject code before loading all APIs return plugin.myrmex.fire('beforeApisLoad') .then(() => { // Retrieve configuration path of all API specifications return Promise.promisify(fs.readdir)(apiSpecsPath); }) .then(subdirs => { // Load all the API specifications const apiPromises = []; _.forEach(subdirs, (subdir) => { const apiSpecPath = path.join(apiSpecsPath, subdir, 'spec'); // subdir is the identifier of the API, so we pass it as the second argument apiPromises.push(loadApi(apiSpecPath, subdir)); }); return Promise.all(apiPromises); }) .then(apis => { // This event allows to inject code to add or delete or alter API specifications return plugin.myrmex.fire('afterApisLoad', apis); }) .spread(loadedApis => { apis = loadedApis; return Promise.resolve(apis); }) .catch(e => { if (e.code === 'ENOENT' && path.basename(e.path) === path.basename(plugin.config.apisPath)) { return Promise.resolve([]); } return Promise.reject(e); }); }
javascript
function loadApis() { // Shortcut if apis already have been loaded if (apis !== undefined) { return Promise.resolve(apis); } const apiSpecsPath = path.join(process.cwd(), plugin.config.apisPath); // This event allows to inject code before loading all APIs return plugin.myrmex.fire('beforeApisLoad') .then(() => { // Retrieve configuration path of all API specifications return Promise.promisify(fs.readdir)(apiSpecsPath); }) .then(subdirs => { // Load all the API specifications const apiPromises = []; _.forEach(subdirs, (subdir) => { const apiSpecPath = path.join(apiSpecsPath, subdir, 'spec'); // subdir is the identifier of the API, so we pass it as the second argument apiPromises.push(loadApi(apiSpecPath, subdir)); }); return Promise.all(apiPromises); }) .then(apis => { // This event allows to inject code to add or delete or alter API specifications return plugin.myrmex.fire('afterApisLoad', apis); }) .spread(loadedApis => { apis = loadedApis; return Promise.resolve(apis); }) .catch(e => { if (e.code === 'ENOENT' && path.basename(e.path) === path.basename(plugin.config.apisPath)) { return Promise.resolve([]); } return Promise.reject(e); }); }
[ "function", "loadApis", "(", ")", "{", "// Shortcut if apis already have been loaded", "if", "(", "apis", "!==", "undefined", ")", "{", "return", "Promise", ".", "resolve", "(", "apis", ")", ";", "}", "const", "apiSpecsPath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "plugin", ".", "config", ".", "apisPath", ")", ";", "// This event allows to inject code before loading all APIs", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'beforeApisLoad'", ")", ".", "then", "(", "(", ")", "=>", "{", "// Retrieve configuration path of all API specifications", "return", "Promise", ".", "promisify", "(", "fs", ".", "readdir", ")", "(", "apiSpecsPath", ")", ";", "}", ")", ".", "then", "(", "subdirs", "=>", "{", "// Load all the API specifications", "const", "apiPromises", "=", "[", "]", ";", "_", ".", "forEach", "(", "subdirs", ",", "(", "subdir", ")", "=>", "{", "const", "apiSpecPath", "=", "path", ".", "join", "(", "apiSpecsPath", ",", "subdir", ",", "'spec'", ")", ";", "// subdir is the identifier of the API, so we pass it as the second argument", "apiPromises", ".", "push", "(", "loadApi", "(", "apiSpecPath", ",", "subdir", ")", ")", ";", "}", ")", ";", "return", "Promise", ".", "all", "(", "apiPromises", ")", ";", "}", ")", ".", "then", "(", "apis", "=>", "{", "// This event allows to inject code to add or delete or alter API specifications", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'afterApisLoad'", ",", "apis", ")", ";", "}", ")", ".", "spread", "(", "loadedApis", "=>", "{", "apis", "=", "loadedApis", ";", "return", "Promise", ".", "resolve", "(", "apis", ")", ";", "}", ")", ".", "catch", "(", "e", "=>", "{", "if", "(", "e", ".", "code", "===", "'ENOENT'", "&&", "path", ".", "basename", "(", "e", ".", "path", ")", "===", "path", ".", "basename", "(", "plugin", ".", "config", ".", "apisPath", ")", ")", "{", "return", "Promise", ".", "resolve", "(", "[", "]", ")", ";", "}", "return", "Promise", ".", "reject", "(", "e", ")", ";", "}", ")", ";", "}" ]
Load all API specifications @returns {Promise<[Api]>} - the promise of an array containing all APIs
[ "Load", "all", "API", "specifications" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/api-gateway/src/index.js#L17-L55
36,954
myrmex-org/myrmex
packages/api-gateway/src/index.js
loadApi
function loadApi(apiSpecPath, identifier) { return plugin.myrmex.fire('beforeApiLoad', apiSpecPath, identifier) .spread((apiSpecPath, identifier) => { // Because we use require() to get the spec, it could either be a JSON file // or the content exported by a node module // But because require() caches the content it loads, we clone the result to avoid bugs // if the function is called twice const apiSpec = _.cloneDeep(require(apiSpecPath)); apiSpec['x-myrmex'] = apiSpec['x-myrmex'] || {}; // Lasy loading because the plugin has to be registered in a Myrmex instance before requiring ./endpoint const Api = require('./api'); const api = new Api(apiSpec, identifier); // This event allows to inject code to alter the API specification return plugin.myrmex.fire('afterApiLoad', api); }) .spread(api => { return api.init(); }); }
javascript
function loadApi(apiSpecPath, identifier) { return plugin.myrmex.fire('beforeApiLoad', apiSpecPath, identifier) .spread((apiSpecPath, identifier) => { // Because we use require() to get the spec, it could either be a JSON file // or the content exported by a node module // But because require() caches the content it loads, we clone the result to avoid bugs // if the function is called twice const apiSpec = _.cloneDeep(require(apiSpecPath)); apiSpec['x-myrmex'] = apiSpec['x-myrmex'] || {}; // Lasy loading because the plugin has to be registered in a Myrmex instance before requiring ./endpoint const Api = require('./api'); const api = new Api(apiSpec, identifier); // This event allows to inject code to alter the API specification return plugin.myrmex.fire('afterApiLoad', api); }) .spread(api => { return api.init(); }); }
[ "function", "loadApi", "(", "apiSpecPath", ",", "identifier", ")", "{", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'beforeApiLoad'", ",", "apiSpecPath", ",", "identifier", ")", ".", "spread", "(", "(", "apiSpecPath", ",", "identifier", ")", "=>", "{", "// Because we use require() to get the spec, it could either be a JSON file", "// or the content exported by a node module", "// But because require() caches the content it loads, we clone the result to avoid bugs", "// if the function is called twice", "const", "apiSpec", "=", "_", ".", "cloneDeep", "(", "require", "(", "apiSpecPath", ")", ")", ";", "apiSpec", "[", "'x-myrmex'", "]", "=", "apiSpec", "[", "'x-myrmex'", "]", "||", "{", "}", ";", "// Lasy loading because the plugin has to be registered in a Myrmex instance before requiring ./endpoint", "const", "Api", "=", "require", "(", "'./api'", ")", ";", "const", "api", "=", "new", "Api", "(", "apiSpec", ",", "identifier", ")", ";", "// This event allows to inject code to alter the API specification", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'afterApiLoad'", ",", "api", ")", ";", "}", ")", ".", "spread", "(", "api", "=>", "{", "return", "api", ".", "init", "(", ")", ";", "}", ")", ";", "}" ]
Load an API specification @param {string} apiSpecPath - the full path to the specification file @param {string} OPTIONAL identifier - a human readable identifier, eventually configured in the specification file itself @returns {Promise<Api>} - the promise of an API instance
[ "Load", "an", "API", "specification" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/api-gateway/src/index.js#L64-L84
36,955
myrmex-org/myrmex
packages/api-gateway/src/index.js
loadEndpoints
function loadEndpoints() { // Shortcut if endpoints already have been loaded if (endpoints !== undefined) { return Promise.resolve(endpoints); } const endpointSpecsPath = path.join(process.cwd(), plugin.config.endpointsPath); return plugin.myrmex.fire('beforeEndpointsLoad') .spread(() => { const endpointPromises = []; file.walkSync(endpointSpecsPath, (dirPath, dirs, files) => { // We are looking for directories that have the name of an HTTP method const subPath = dirPath.substr(endpointSpecsPath.length); const resourcePathParts = subPath.split(path.sep); const method = resourcePathParts.pop(); if (plugin.httpMethods.indexOf(method) === -1) { return; } // We construct the path to the resource const resourcePath = resourcePathParts.join('/'); endpointPromises.push(loadEndpoint(endpointSpecsPath, resourcePath, method)); }); return Promise.all(endpointPromises); }) .then(endpoints => { return plugin.myrmex.fire('afterEndpointsLoad', endpoints); }) .spread(loadedEndpoints => { endpoints = loadedEndpoints; return Promise.resolve(endpoints); }) .catch(e => { if (e.code === 'ENOENT' && path.basename(e.path) === path.basename(plugin.config.endpointsPath)) { return Promise.resolve([]); } Promise.reject(e); }); }
javascript
function loadEndpoints() { // Shortcut if endpoints already have been loaded if (endpoints !== undefined) { return Promise.resolve(endpoints); } const endpointSpecsPath = path.join(process.cwd(), plugin.config.endpointsPath); return plugin.myrmex.fire('beforeEndpointsLoad') .spread(() => { const endpointPromises = []; file.walkSync(endpointSpecsPath, (dirPath, dirs, files) => { // We are looking for directories that have the name of an HTTP method const subPath = dirPath.substr(endpointSpecsPath.length); const resourcePathParts = subPath.split(path.sep); const method = resourcePathParts.pop(); if (plugin.httpMethods.indexOf(method) === -1) { return; } // We construct the path to the resource const resourcePath = resourcePathParts.join('/'); endpointPromises.push(loadEndpoint(endpointSpecsPath, resourcePath, method)); }); return Promise.all(endpointPromises); }) .then(endpoints => { return plugin.myrmex.fire('afterEndpointsLoad', endpoints); }) .spread(loadedEndpoints => { endpoints = loadedEndpoints; return Promise.resolve(endpoints); }) .catch(e => { if (e.code === 'ENOENT' && path.basename(e.path) === path.basename(plugin.config.endpointsPath)) { return Promise.resolve([]); } Promise.reject(e); }); }
[ "function", "loadEndpoints", "(", ")", "{", "// Shortcut if endpoints already have been loaded", "if", "(", "endpoints", "!==", "undefined", ")", "{", "return", "Promise", ".", "resolve", "(", "endpoints", ")", ";", "}", "const", "endpointSpecsPath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "plugin", ".", "config", ".", "endpointsPath", ")", ";", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'beforeEndpointsLoad'", ")", ".", "spread", "(", "(", ")", "=>", "{", "const", "endpointPromises", "=", "[", "]", ";", "file", ".", "walkSync", "(", "endpointSpecsPath", ",", "(", "dirPath", ",", "dirs", ",", "files", ")", "=>", "{", "// We are looking for directories that have the name of an HTTP method", "const", "subPath", "=", "dirPath", ".", "substr", "(", "endpointSpecsPath", ".", "length", ")", ";", "const", "resourcePathParts", "=", "subPath", ".", "split", "(", "path", ".", "sep", ")", ";", "const", "method", "=", "resourcePathParts", ".", "pop", "(", ")", ";", "if", "(", "plugin", ".", "httpMethods", ".", "indexOf", "(", "method", ")", "===", "-", "1", ")", "{", "return", ";", "}", "// We construct the path to the resource", "const", "resourcePath", "=", "resourcePathParts", ".", "join", "(", "'/'", ")", ";", "endpointPromises", ".", "push", "(", "loadEndpoint", "(", "endpointSpecsPath", ",", "resourcePath", ",", "method", ")", ")", ";", "}", ")", ";", "return", "Promise", ".", "all", "(", "endpointPromises", ")", ";", "}", ")", ".", "then", "(", "endpoints", "=>", "{", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'afterEndpointsLoad'", ",", "endpoints", ")", ";", "}", ")", ".", "spread", "(", "loadedEndpoints", "=>", "{", "endpoints", "=", "loadedEndpoints", ";", "return", "Promise", ".", "resolve", "(", "endpoints", ")", ";", "}", ")", ".", "catch", "(", "e", "=>", "{", "if", "(", "e", ".", "code", "===", "'ENOENT'", "&&", "path", ".", "basename", "(", "e", ".", "path", ")", "===", "path", ".", "basename", "(", "plugin", ".", "config", ".", "endpointsPath", ")", ")", "{", "return", "Promise", ".", "resolve", "(", "[", "]", ")", ";", "}", "Promise", ".", "reject", "(", "e", ")", ";", "}", ")", ";", "}" ]
Load all Endpoint specifications @returns {Promise<[Endpoints]>} - the promise of an array containing all endpoints
[ "Load", "all", "Endpoint", "specifications" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/api-gateway/src/index.js#L90-L128
36,956
myrmex-org/myrmex
packages/api-gateway/src/index.js
loadModels
function loadModels() { const modelSpecsPath = path.join(process.cwd(), plugin.config.modelsPath); return plugin.myrmex.fire('beforeModelsLoad') .spread(() => { return Promise.promisify(fs.readdir)(modelSpecsPath); }) .then(fileNames => { // Load all the model specifications return Promise.map(fileNames, fileName => { const modelSpecPath = path.join(modelSpecsPath, fileName); const modelName = path.parse(fileName).name; return loadModel(modelSpecPath, modelName); }); }) .then(models => { return plugin.myrmex.fire('afterModelsLoad', models); }) .spread(models => { return Promise.resolve(models); }) .catch(e => { if (e.code === 'ENOENT' && path.basename(e.path) === path.basename(plugin.config.modelsPath)) { return Promise.resolve([]); } Promise.reject(e); }); }
javascript
function loadModels() { const modelSpecsPath = path.join(process.cwd(), plugin.config.modelsPath); return plugin.myrmex.fire('beforeModelsLoad') .spread(() => { return Promise.promisify(fs.readdir)(modelSpecsPath); }) .then(fileNames => { // Load all the model specifications return Promise.map(fileNames, fileName => { const modelSpecPath = path.join(modelSpecsPath, fileName); const modelName = path.parse(fileName).name; return loadModel(modelSpecPath, modelName); }); }) .then(models => { return plugin.myrmex.fire('afterModelsLoad', models); }) .spread(models => { return Promise.resolve(models); }) .catch(e => { if (e.code === 'ENOENT' && path.basename(e.path) === path.basename(plugin.config.modelsPath)) { return Promise.resolve([]); } Promise.reject(e); }); }
[ "function", "loadModels", "(", ")", "{", "const", "modelSpecsPath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "plugin", ".", "config", ".", "modelsPath", ")", ";", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'beforeModelsLoad'", ")", ".", "spread", "(", "(", ")", "=>", "{", "return", "Promise", ".", "promisify", "(", "fs", ".", "readdir", ")", "(", "modelSpecsPath", ")", ";", "}", ")", ".", "then", "(", "fileNames", "=>", "{", "// Load all the model specifications", "return", "Promise", ".", "map", "(", "fileNames", ",", "fileName", "=>", "{", "const", "modelSpecPath", "=", "path", ".", "join", "(", "modelSpecsPath", ",", "fileName", ")", ";", "const", "modelName", "=", "path", ".", "parse", "(", "fileName", ")", ".", "name", ";", "return", "loadModel", "(", "modelSpecPath", ",", "modelName", ")", ";", "}", ")", ";", "}", ")", ".", "then", "(", "models", "=>", "{", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'afterModelsLoad'", ",", "models", ")", ";", "}", ")", ".", "spread", "(", "models", "=>", "{", "return", "Promise", ".", "resolve", "(", "models", ")", ";", "}", ")", ".", "catch", "(", "e", "=>", "{", "if", "(", "e", ".", "code", "===", "'ENOENT'", "&&", "path", ".", "basename", "(", "e", ".", "path", ")", "===", "path", ".", "basename", "(", "plugin", ".", "config", ".", "modelsPath", ")", ")", "{", "return", "Promise", ".", "resolve", "(", "[", "]", ")", ";", "}", "Promise", ".", "reject", "(", "e", ")", ";", "}", ")", ";", "}" ]
Load all Model specifications @returns {Promise<[Models]>} - the promise of an array containing all models
[ "Load", "all", "Model", "specifications" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/api-gateway/src/index.js#L177-L204
36,957
myrmex-org/myrmex
packages/api-gateway/src/index.js
loadModel
function loadModel(modelSpecPath, name) { return plugin.myrmex.fire('beforeModelLoad', modelSpecPath, name) .spread(() => { // Because we use require() to get the spec, it could either be a JSON file // or the content exported by a node module // But because require() caches the content it loads, we clone the result to avoid bugs // if the function is called twice const modelSpec = _.cloneDeep(require(modelSpecPath)); // Lasy loading because the plugin has to be registered in a Myrmex instance before requiring ./model const Model = require('./model'); return Promise.resolve(new Model(name, modelSpec)); }) .then(model => { // This event allows to inject code to alter the model specification return plugin.myrmex.fire('afterModelLoad', model); }) .spread((model) => { return Promise.resolve(model); }); }
javascript
function loadModel(modelSpecPath, name) { return plugin.myrmex.fire('beforeModelLoad', modelSpecPath, name) .spread(() => { // Because we use require() to get the spec, it could either be a JSON file // or the content exported by a node module // But because require() caches the content it loads, we clone the result to avoid bugs // if the function is called twice const modelSpec = _.cloneDeep(require(modelSpecPath)); // Lasy loading because the plugin has to be registered in a Myrmex instance before requiring ./model const Model = require('./model'); return Promise.resolve(new Model(name, modelSpec)); }) .then(model => { // This event allows to inject code to alter the model specification return plugin.myrmex.fire('afterModelLoad', model); }) .spread((model) => { return Promise.resolve(model); }); }
[ "function", "loadModel", "(", "modelSpecPath", ",", "name", ")", "{", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'beforeModelLoad'", ",", "modelSpecPath", ",", "name", ")", ".", "spread", "(", "(", ")", "=>", "{", "// Because we use require() to get the spec, it could either be a JSON file", "// or the content exported by a node module", "// But because require() caches the content it loads, we clone the result to avoid bugs", "// if the function is called twice", "const", "modelSpec", "=", "_", ".", "cloneDeep", "(", "require", "(", "modelSpecPath", ")", ")", ";", "// Lasy loading because the plugin has to be registered in a Myrmex instance before requiring ./model", "const", "Model", "=", "require", "(", "'./model'", ")", ";", "return", "Promise", ".", "resolve", "(", "new", "Model", "(", "name", ",", "modelSpec", ")", ")", ";", "}", ")", ".", "then", "(", "model", "=>", "{", "// This event allows to inject code to alter the model specification", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'afterModelLoad'", ",", "model", ")", ";", "}", ")", ".", "spread", "(", "(", "model", ")", "=>", "{", "return", "Promise", ".", "resolve", "(", "model", ")", ";", "}", ")", ";", "}" ]
Load an Model specification @param {string} modelSpecPath - the path to the the model specification @returns {Promise<Model>} - the promise of an model instance
[ "Load", "an", "Model", "specification" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/api-gateway/src/index.js#L211-L231
36,958
myrmex-org/myrmex
packages/api-gateway/src/index.js
loadIntegrations
function loadIntegrations(region, context, endpoints) { // The `deployIntegrations` hook takes four arguments // The region of the deployment // The "context" of the deployment // The list of endpoints that must be deployed // An array that will receive integration results const integrationDataInjectors = []; return plugin.myrmex.fire('loadIntegrations', region, context, endpoints, integrationDataInjectors) .spread((region, context, endpoints, integrationDataInjectors) => { // At this point, integration plugins returned their integrationDataInjectors return plugin.myrmex.fire('beforeAddIntegrationDataToEndpoints', endpoints, integrationDataInjectors); }) .spread((endpoints, integrationDataInjectors) => { return Promise.map(integrationDataInjectors, (integrationDataInjector) => { return Promise.map(endpoints, (endpoint) => { return integrationDataInjector.applyToEndpoint(endpoint); }); }) .then(() => { return plugin.myrmex.fire('afterAddIntegrationDataToEndpoints', endpoints, integrationDataInjectors); }); }) .spread((endpoints, integrationDataInjectors) => { return Promise.resolve(endpoints); }); }
javascript
function loadIntegrations(region, context, endpoints) { // The `deployIntegrations` hook takes four arguments // The region of the deployment // The "context" of the deployment // The list of endpoints that must be deployed // An array that will receive integration results const integrationDataInjectors = []; return plugin.myrmex.fire('loadIntegrations', region, context, endpoints, integrationDataInjectors) .spread((region, context, endpoints, integrationDataInjectors) => { // At this point, integration plugins returned their integrationDataInjectors return plugin.myrmex.fire('beforeAddIntegrationDataToEndpoints', endpoints, integrationDataInjectors); }) .spread((endpoints, integrationDataInjectors) => { return Promise.map(integrationDataInjectors, (integrationDataInjector) => { return Promise.map(endpoints, (endpoint) => { return integrationDataInjector.applyToEndpoint(endpoint); }); }) .then(() => { return plugin.myrmex.fire('afterAddIntegrationDataToEndpoints', endpoints, integrationDataInjectors); }); }) .spread((endpoints, integrationDataInjectors) => { return Promise.resolve(endpoints); }); }
[ "function", "loadIntegrations", "(", "region", ",", "context", ",", "endpoints", ")", "{", "// The `deployIntegrations` hook takes four arguments", "// The region of the deployment", "// The \"context\" of the deployment", "// The list of endpoints that must be deployed", "// An array that will receive integration results", "const", "integrationDataInjectors", "=", "[", "]", ";", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'loadIntegrations'", ",", "region", ",", "context", ",", "endpoints", ",", "integrationDataInjectors", ")", ".", "spread", "(", "(", "region", ",", "context", ",", "endpoints", ",", "integrationDataInjectors", ")", "=>", "{", "// At this point, integration plugins returned their integrationDataInjectors", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'beforeAddIntegrationDataToEndpoints'", ",", "endpoints", ",", "integrationDataInjectors", ")", ";", "}", ")", ".", "spread", "(", "(", "endpoints", ",", "integrationDataInjectors", ")", "=>", "{", "return", "Promise", ".", "map", "(", "integrationDataInjectors", ",", "(", "integrationDataInjector", ")", "=>", "{", "return", "Promise", ".", "map", "(", "endpoints", ",", "(", "endpoint", ")", "=>", "{", "return", "integrationDataInjector", ".", "applyToEndpoint", "(", "endpoint", ")", ";", "}", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'afterAddIntegrationDataToEndpoints'", ",", "endpoints", ",", "integrationDataInjectors", ")", ";", "}", ")", ";", "}", ")", ".", "spread", "(", "(", "endpoints", ",", "integrationDataInjectors", ")", "=>", "{", "return", "Promise", ".", "resolve", "(", "endpoints", ")", ";", "}", ")", ";", "}" ]
Update the configuration of endpoints with data returned by integration This data can come from the deployment of a lambda function, the configuration of an HTTP proxy, the generation of a mock etc ... @param {string} region - AWS region @param {string} stage - API stage @param {string} environment - environment identifier @returns {[IntegrationObject]} - an array of integrqtion objects
[ "Update", "the", "configuration", "of", "endpoints", "with", "data", "returned", "by", "integration", "This", "data", "can", "come", "from", "the", "deployment", "of", "a", "lambda", "function", "the", "configuration", "of", "an", "HTTP", "proxy", "the", "generation", "of", "a", "mock", "etc", "..." ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/api-gateway/src/index.js#L242-L267
36,959
myrmex-org/myrmex
packages/api-gateway/src/index.js
findApi
function findApi(identifier) { return loadApis() .then(apis => { const api = _.find(apis, (api) => { return api.getIdentifier() === identifier; }); if (!api) { return Promise.reject(new Error('Could not find the API "' + identifier + '" in the current project')); } return api; }); }
javascript
function findApi(identifier) { return loadApis() .then(apis => { const api = _.find(apis, (api) => { return api.getIdentifier() === identifier; }); if (!api) { return Promise.reject(new Error('Could not find the API "' + identifier + '" in the current project')); } return api; }); }
[ "function", "findApi", "(", "identifier", ")", "{", "return", "loadApis", "(", ")", ".", "then", "(", "apis", "=>", "{", "const", "api", "=", "_", ".", "find", "(", "apis", ",", "(", "api", ")", "=>", "{", "return", "api", ".", "getIdentifier", "(", ")", "===", "identifier", ";", "}", ")", ";", "if", "(", "!", "api", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "'Could not find the API \"'", "+", "identifier", "+", "'\" in the current project'", ")", ")", ";", "}", "return", "api", ";", "}", ")", ";", "}" ]
Find an APIs by its identifier and return it with its endpoints @param {string} identifier - the API identifier @returns {Api} - the API corresponding to the identifier
[ "Find", "an", "APIs", "by", "its", "identifier", "and", "return", "it", "with", "its", "endpoints" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/api-gateway/src/index.js#L274-L283
36,960
myrmex-org/myrmex
packages/api-gateway/src/index.js
findEndpoint
function findEndpoint(resourcePath, method) { return loadEndpoints() .then(endpoints => { const endpoint = _.find(endpoints, endpoint => { return endpoint.getResourcePath() === resourcePath && endpoint.getMethod() === method; }); if (!endpoint) { return Promise.reject(new Error('Could not find the endpoint "' + method + ' ' + resourcePath + '" in the current project')); } return endpoint; }); }
javascript
function findEndpoint(resourcePath, method) { return loadEndpoints() .then(endpoints => { const endpoint = _.find(endpoints, endpoint => { return endpoint.getResourcePath() === resourcePath && endpoint.getMethod() === method; }); if (!endpoint) { return Promise.reject(new Error('Could not find the endpoint "' + method + ' ' + resourcePath + '" in the current project')); } return endpoint; }); }
[ "function", "findEndpoint", "(", "resourcePath", ",", "method", ")", "{", "return", "loadEndpoints", "(", ")", ".", "then", "(", "endpoints", "=>", "{", "const", "endpoint", "=", "_", ".", "find", "(", "endpoints", ",", "endpoint", "=>", "{", "return", "endpoint", ".", "getResourcePath", "(", ")", "===", "resourcePath", "&&", "endpoint", ".", "getMethod", "(", ")", "===", "method", ";", "}", ")", ";", "if", "(", "!", "endpoint", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "'Could not find the endpoint \"'", "+", "method", "+", "' '", "+", "resourcePath", "+", "'\" in the current project'", ")", ")", ";", "}", "return", "endpoint", ";", "}", ")", ";", "}" ]
Find an endpoint by its resource path and HTTP method @param {string} resourcePath - the resource path of the endpoint @param {string} method - the HTTP method of the endpoint @returns {Endpoint} - the endpoint corresponding to the resource path and the HTTP method
[ "Find", "an", "endpoint", "by", "its", "resource", "path", "and", "HTTP", "method" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/api-gateway/src/index.js#L291-L300
36,961
myrmex-org/myrmex
packages/api-gateway/src/index.js
findModel
function findModel(name) { return loadModels() .then(models => { const model = _.find(models, model => { return model.getName('spec') === name; }); if (!model) { return Promise.reject(new Error('Could not find the model "' + name + '" in the current project')); } return model; }); }
javascript
function findModel(name) { return loadModels() .then(models => { const model = _.find(models, model => { return model.getName('spec') === name; }); if (!model) { return Promise.reject(new Error('Could not find the model "' + name + '" in the current project')); } return model; }); }
[ "function", "findModel", "(", "name", ")", "{", "return", "loadModels", "(", ")", ".", "then", "(", "models", "=>", "{", "const", "model", "=", "_", ".", "find", "(", "models", ",", "model", "=>", "{", "return", "model", ".", "getName", "(", "'spec'", ")", "===", "name", ";", "}", ")", ";", "if", "(", "!", "model", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "'Could not find the model \"'", "+", "name", "+", "'\" in the current project'", ")", ")", ";", "}", "return", "model", ";", "}", ")", ";", "}" ]
Find an model by its name @param {string} name - the name of the model @returns {Model} - the model corresponding to the resource path and the HTTP method
[ "Find", "an", "model", "by", "its", "name" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/api-gateway/src/index.js#L307-L316
36,962
myrmex-org/myrmex
packages/api-gateway/src/index.js
mergeSpecsFiles
function mergeSpecsFiles(beginPath, subPath) { // Initialise specification const spec = {}; // List all directories where we have to look for specifications const subDirs = subPath.split(path.sep); // Initialize the directory path for the do/while statement let searchSpecDir = beginPath; do { let subSpec = {}; const subDir = subDirs.shift(); searchSpecDir = path.join(searchSpecDir, subDir); try { // Try to load the definition and silently ignore the error if it does not exist // Because we use require() to get the config, it could either be a JSON file // or the content exported by a node module // But because require() caches the content it loads, we clone the result to avoid bugs // if the function is called twice subSpec = _.cloneDeep(require(searchSpecDir + path.sep + 'spec')); } catch (e) { // Silently ignore the error when calling require() on an unexisting spec.json file if (e.code !== 'MODULE_NOT_FOUND') { throw e; } } // Merge the spec eventually found _.merge(spec, subSpec); } while (subDirs.length); // return the result of the merges return spec; }
javascript
function mergeSpecsFiles(beginPath, subPath) { // Initialise specification const spec = {}; // List all directories where we have to look for specifications const subDirs = subPath.split(path.sep); // Initialize the directory path for the do/while statement let searchSpecDir = beginPath; do { let subSpec = {}; const subDir = subDirs.shift(); searchSpecDir = path.join(searchSpecDir, subDir); try { // Try to load the definition and silently ignore the error if it does not exist // Because we use require() to get the config, it could either be a JSON file // or the content exported by a node module // But because require() caches the content it loads, we clone the result to avoid bugs // if the function is called twice subSpec = _.cloneDeep(require(searchSpecDir + path.sep + 'spec')); } catch (e) { // Silently ignore the error when calling require() on an unexisting spec.json file if (e.code !== 'MODULE_NOT_FOUND') { throw e; } } // Merge the spec eventually found _.merge(spec, subSpec); } while (subDirs.length); // return the result of the merges return spec; }
[ "function", "mergeSpecsFiles", "(", "beginPath", ",", "subPath", ")", "{", "// Initialise specification", "const", "spec", "=", "{", "}", ";", "// List all directories where we have to look for specifications", "const", "subDirs", "=", "subPath", ".", "split", "(", "path", ".", "sep", ")", ";", "// Initialize the directory path for the do/while statement", "let", "searchSpecDir", "=", "beginPath", ";", "do", "{", "let", "subSpec", "=", "{", "}", ";", "const", "subDir", "=", "subDirs", ".", "shift", "(", ")", ";", "searchSpecDir", "=", "path", ".", "join", "(", "searchSpecDir", ",", "subDir", ")", ";", "try", "{", "// Try to load the definition and silently ignore the error if it does not exist", "// Because we use require() to get the config, it could either be a JSON file", "// or the content exported by a node module", "// But because require() caches the content it loads, we clone the result to avoid bugs", "// if the function is called twice", "subSpec", "=", "_", ".", "cloneDeep", "(", "require", "(", "searchSpecDir", "+", "path", ".", "sep", "+", "'spec'", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "// Silently ignore the error when calling require() on an unexisting spec.json file", "if", "(", "e", ".", "code", "!==", "'MODULE_NOT_FOUND'", ")", "{", "throw", "e", ";", "}", "}", "// Merge the spec eventually found", "_", ".", "merge", "(", "spec", ",", "subSpec", ")", ";", "}", "while", "(", "subDirs", ".", "length", ")", ";", "// return the result of the merges", "return", "spec", ";", "}" ]
Function that aggregates the specifications found in all spec.json|js files in a path @param {string} beginPath - path from which the function will look for swagger.json|js files @param {string} subPath - path until which the function will look for swagger.json|js files @returns {Object} - aggregation of specifications that have been found
[ "Function", "that", "aggregates", "the", "specifications", "found", "in", "all", "spec", ".", "json|js", "files", "in", "a", "path" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/api-gateway/src/index.js#L382-L415
36,963
jefersondaniel/dom-form-serializer
lib/InputReaders.js
getSelectValue
function getSelectValue (elem) { var value, option, i var options = elem.options var index = elem.selectedIndex var one = elem.type === 'select-one' var values = one ? null : [] var max = one ? index + 1 : options.length if (index < 0) { i = max } else { i = one ? index : 0 } // Loop through all the selected options for (; i < max; i++) { option = options[i] // Support: IE <=9 only // IE8-9 doesn't update selected after form reset if ((option.selected || i === index) && // Don't return options that are disabled or in a disabled optgroup !option.disabled && (!option.parentNode.disabled || option.parentNode.tagName.toLowerCase() === 'optgroup')) { // Get the specific value for the option value = option.value // We don't need an array for one selects if (one) { return value } // Multi-Selects return an array values.push(value) } } return values }
javascript
function getSelectValue (elem) { var value, option, i var options = elem.options var index = elem.selectedIndex var one = elem.type === 'select-one' var values = one ? null : [] var max = one ? index + 1 : options.length if (index < 0) { i = max } else { i = one ? index : 0 } // Loop through all the selected options for (; i < max; i++) { option = options[i] // Support: IE <=9 only // IE8-9 doesn't update selected after form reset if ((option.selected || i === index) && // Don't return options that are disabled or in a disabled optgroup !option.disabled && (!option.parentNode.disabled || option.parentNode.tagName.toLowerCase() === 'optgroup')) { // Get the specific value for the option value = option.value // We don't need an array for one selects if (one) { return value } // Multi-Selects return an array values.push(value) } } return values }
[ "function", "getSelectValue", "(", "elem", ")", "{", "var", "value", ",", "option", ",", "i", "var", "options", "=", "elem", ".", "options", "var", "index", "=", "elem", ".", "selectedIndex", "var", "one", "=", "elem", ".", "type", "===", "'select-one'", "var", "values", "=", "one", "?", "null", ":", "[", "]", "var", "max", "=", "one", "?", "index", "+", "1", ":", "options", ".", "length", "if", "(", "index", "<", "0", ")", "{", "i", "=", "max", "}", "else", "{", "i", "=", "one", "?", "index", ":", "0", "}", "// Loop through all the selected options", "for", "(", ";", "i", "<", "max", ";", "i", "++", ")", "{", "option", "=", "options", "[", "i", "]", "// Support: IE <=9 only", "// IE8-9 doesn't update selected after form reset", "if", "(", "(", "option", ".", "selected", "||", "i", "===", "index", ")", "&&", "// Don't return options that are disabled or in a disabled optgroup", "!", "option", ".", "disabled", "&&", "(", "!", "option", ".", "parentNode", ".", "disabled", "||", "option", ".", "parentNode", ".", "tagName", ".", "toLowerCase", "(", ")", "===", "'optgroup'", ")", ")", "{", "// Get the specific value for the option", "value", "=", "option", ".", "value", "// We don't need an array for one selects", "if", "(", "one", ")", "{", "return", "value", "}", "// Multi-Selects return an array", "values", ".", "push", "(", "value", ")", "}", "}", "return", "values", "}" ]
Read select values @see {@link https://github.com/jquery/jquery/blob/master/src/attributes/val.js|Github} @param {object} Select element @return {string|Array} Select value(s)
[ "Read", "select", "values" ]
97e0ebf0431b87e4a9b98d87b1d2d037d27c8af2
https://github.com/jefersondaniel/dom-form-serializer/blob/97e0ebf0431b87e4a9b98d87b1d2d037d27c8af2/lib/InputReaders.js#L19-L59
36,964
FocaBot/ffmpeg-downloader
downloader.js
updateBinary
function updateBinary (os = platform, arch = process.arch) { return new Promise((resolve, reject) => { if (platform === 'freebsd') return resolve(` There are no static ffmpeg builds for FreeBSD currently available. The module will try to use the system-wide installation. Install it by running "pkg install ffmpeg" or via ports. `) if (platform === 'openbsd') return resolve(` There are no static ffmpeg builds for OpenBSD currently available. The module will try to use the system-wide installation. Install it by running "pkg_add ffmpeg" or via ports. `) const dir = `bin/${os}/${arch}` const bin = `${dir}/ffmpeg${os === 'win32' ? '.exe' : ''}` const dest = path.join(__dirname, bin) const fname = `${os}-${arch}.tar.bz2` const tmp = path.join(__dirname, 'bin', fname) try { fs.mkdirSync(path.join(__dirname, 'bin')) } catch(e) {} let bar // Cleanup directory fs.emptyDirSync('bin') // Get the latest version const req = request.get(`https://github.com/FocaBot/ffmpeg-downloader/raw/master/bin/${fname}`) req.on('error', e => reject(e)) // Handle errors .on('data', c => { bar = bar || new ProgressBar(`${fname} [:bar] :percent (ETA: :etas)`, { complete: '=', incomplete: ' ', width: 25, total: parseInt(req.response.headers['content-length']) }) bar.tick(c.length) }) .on('end', () => setTimeout(() => { bar.tick(bar.total - bar.curr) console.log('Decompressing...') decompress(tmp, path.join(__dirname, 'bin')).then(f => { fs.unlinkSync(tmp) // Try to get the version number // Skip this if not the same arch/os as what launched it if (os === platform && arch === process.arch) { execFile(dest, ['-version'], (error, stdout, stderr) => { if (error || stderr.length) return reject(error || stderr) resolve(stdout) }) } else { resolve('Platform and arch are different than this system, cannot display ffmpeg version') } }) }, 1000)) .pipe(fs.createWriteStream(tmp, { mode: 0o755 })) }) }
javascript
function updateBinary (os = platform, arch = process.arch) { return new Promise((resolve, reject) => { if (platform === 'freebsd') return resolve(` There are no static ffmpeg builds for FreeBSD currently available. The module will try to use the system-wide installation. Install it by running "pkg install ffmpeg" or via ports. `) if (platform === 'openbsd') return resolve(` There are no static ffmpeg builds for OpenBSD currently available. The module will try to use the system-wide installation. Install it by running "pkg_add ffmpeg" or via ports. `) const dir = `bin/${os}/${arch}` const bin = `${dir}/ffmpeg${os === 'win32' ? '.exe' : ''}` const dest = path.join(__dirname, bin) const fname = `${os}-${arch}.tar.bz2` const tmp = path.join(__dirname, 'bin', fname) try { fs.mkdirSync(path.join(__dirname, 'bin')) } catch(e) {} let bar // Cleanup directory fs.emptyDirSync('bin') // Get the latest version const req = request.get(`https://github.com/FocaBot/ffmpeg-downloader/raw/master/bin/${fname}`) req.on('error', e => reject(e)) // Handle errors .on('data', c => { bar = bar || new ProgressBar(`${fname} [:bar] :percent (ETA: :etas)`, { complete: '=', incomplete: ' ', width: 25, total: parseInt(req.response.headers['content-length']) }) bar.tick(c.length) }) .on('end', () => setTimeout(() => { bar.tick(bar.total - bar.curr) console.log('Decompressing...') decompress(tmp, path.join(__dirname, 'bin')).then(f => { fs.unlinkSync(tmp) // Try to get the version number // Skip this if not the same arch/os as what launched it if (os === platform && arch === process.arch) { execFile(dest, ['-version'], (error, stdout, stderr) => { if (error || stderr.length) return reject(error || stderr) resolve(stdout) }) } else { resolve('Platform and arch are different than this system, cannot display ffmpeg version') } }) }, 1000)) .pipe(fs.createWriteStream(tmp, { mode: 0o755 })) }) }
[ "function", "updateBinary", "(", "os", "=", "platform", ",", "arch", "=", "process", ".", "arch", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "platform", "===", "'freebsd'", ")", "return", "resolve", "(", "`", "`", ")", "if", "(", "platform", "===", "'openbsd'", ")", "return", "resolve", "(", "`", "`", ")", "const", "dir", "=", "`", "${", "os", "}", "${", "arch", "}", "`", "const", "bin", "=", "`", "${", "dir", "}", "${", "os", "===", "'win32'", "?", "'.exe'", ":", "''", "}", "`", "const", "dest", "=", "path", ".", "join", "(", "__dirname", ",", "bin", ")", "const", "fname", "=", "`", "${", "os", "}", "${", "arch", "}", "`", "const", "tmp", "=", "path", ".", "join", "(", "__dirname", ",", "'bin'", ",", "fname", ")", "try", "{", "fs", ".", "mkdirSync", "(", "path", ".", "join", "(", "__dirname", ",", "'bin'", ")", ")", "}", "catch", "(", "e", ")", "{", "}", "let", "bar", "// Cleanup directory", "fs", ".", "emptyDirSync", "(", "'bin'", ")", "// Get the latest version", "const", "req", "=", "request", ".", "get", "(", "`", "${", "fname", "}", "`", ")", "req", ".", "on", "(", "'error'", ",", "e", "=>", "reject", "(", "e", ")", ")", "// Handle errors", ".", "on", "(", "'data'", ",", "c", "=>", "{", "bar", "=", "bar", "||", "new", "ProgressBar", "(", "`", "${", "fname", "}", "`", ",", "{", "complete", ":", "'='", ",", "incomplete", ":", "' '", ",", "width", ":", "25", ",", "total", ":", "parseInt", "(", "req", ".", "response", ".", "headers", "[", "'content-length'", "]", ")", "}", ")", "bar", ".", "tick", "(", "c", ".", "length", ")", "}", ")", ".", "on", "(", "'end'", ",", "(", ")", "=>", "setTimeout", "(", "(", ")", "=>", "{", "bar", ".", "tick", "(", "bar", ".", "total", "-", "bar", ".", "curr", ")", "console", ".", "log", "(", "'Decompressing...'", ")", "decompress", "(", "tmp", ",", "path", ".", "join", "(", "__dirname", ",", "'bin'", ")", ")", ".", "then", "(", "f", "=>", "{", "fs", ".", "unlinkSync", "(", "tmp", ")", "// Try to get the version number", "// Skip this if not the same arch/os as what launched it", "if", "(", "os", "===", "platform", "&&", "arch", "===", "process", ".", "arch", ")", "{", "execFile", "(", "dest", ",", "[", "'-version'", "]", ",", "(", "error", ",", "stdout", ",", "stderr", ")", "=>", "{", "if", "(", "error", "||", "stderr", ".", "length", ")", "return", "reject", "(", "error", "||", "stderr", ")", "resolve", "(", "stdout", ")", "}", ")", "}", "else", "{", "resolve", "(", "'Platform and arch are different than this system, cannot display ffmpeg version'", ")", "}", "}", ")", "}", ",", "1000", ")", ")", ".", "pipe", "(", "fs", ".", "createWriteStream", "(", "tmp", ",", "{", "mode", ":", "0o755", "}", ")", ")", "}", ")", "}" ]
Downloads the FFMPEG binary. @param {string} os - Target OS @param {string} arch - Target architecture @return {Promise<string>} - Output of ffmpeg -version
[ "Downloads", "the", "FFMPEG", "binary", "." ]
1e2998ee76d672857f205ba506f0568f7e4f97cb
https://github.com/FocaBot/ffmpeg-downloader/blob/1e2998ee76d672857f205ba506f0568f7e4f97cb/downloader.js#L17-L74
36,965
maierfelix/POGO-asset-downloader
index.js
sortArrayByIndex
function sortArrayByIndex(array) { let ii = 0; let length = array.length; let output = []; for (; ii < length; ++ii) { output[array[ii].index] = array[ii]; delete array[ii].index; }; return (output); }
javascript
function sortArrayByIndex(array) { let ii = 0; let length = array.length; let output = []; for (; ii < length; ++ii) { output[array[ii].index] = array[ii]; delete array[ii].index; }; return (output); }
[ "function", "sortArrayByIndex", "(", "array", ")", "{", "let", "ii", "=", "0", ";", "let", "length", "=", "array", ".", "length", ";", "let", "output", "=", "[", "]", ";", "for", "(", ";", "ii", "<", "length", ";", "++", "ii", ")", "{", "output", "[", "array", "[", "ii", "]", ".", "index", "]", "=", "array", "[", "ii", "]", ";", "delete", "array", "[", "ii", "]", ".", "index", ";", "}", ";", "return", "(", "output", ")", ";", "}" ]
Sort array back into correct call order @param {Array} array @return {Array}
[ "Sort", "array", "back", "into", "correct", "call", "order" ]
c26e011d28a85a07349195973597b2f98484ffc3
https://github.com/maierfelix/POGO-asset-downloader/blob/c26e011d28a85a07349195973597b2f98484ffc3/index.js#L180-L194
36,966
myrmex-org/myrmex
packages/api-gateway/src/endpoint.js
Endpoint
function Endpoint(spec, resourcePath, method) { this.method = method; this.resourcePath = resourcePath || '/'; this.spec = spec; }
javascript
function Endpoint(spec, resourcePath, method) { this.method = method; this.resourcePath = resourcePath || '/'; this.spec = spec; }
[ "function", "Endpoint", "(", "spec", ",", "resourcePath", ",", "method", ")", "{", "this", ".", "method", "=", "method", ";", "this", ".", "resourcePath", "=", "resourcePath", "||", "'/'", ";", "this", ".", "spec", "=", "spec", ";", "}" ]
The specification of an API endpoint @param {Object} spec - Swagger/OpenAPI specification of the endpoint @param {string} resourcePath - path of the endpoint @param {string} method - HTTP method of the endpoint @constructor
[ "The", "specification", "of", "an", "API", "endpoint" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/api-gateway/src/endpoint.js#L14-L18
36,967
auttoio/typeform-node
gulp/plumb.js
monkeyPatchPipe
function monkeyPatchPipe(stream) { while (!stream.hasOwnProperty('pipe')) { stream = Object.getPrototypeOf(stream) if (!stream) return null } let existingPipe = stream.pipe newPipe['$$monkey-patch'] = true return stream.pipe = newPipe /** Create new pipe copy of existing pipe */ function newPipe() { let result = existingPipe.apply(this, arguments) result.setMaxListeners(0) if (!result.pipe['$$monkey-patch']) { monkeyPatchPipe(result) } return result.on('error', function(err) { gutil.log(gutil.colors.yellow(err)) gutil.beep() this.emit('end') }) } }
javascript
function monkeyPatchPipe(stream) { while (!stream.hasOwnProperty('pipe')) { stream = Object.getPrototypeOf(stream) if (!stream) return null } let existingPipe = stream.pipe newPipe['$$monkey-patch'] = true return stream.pipe = newPipe /** Create new pipe copy of existing pipe */ function newPipe() { let result = existingPipe.apply(this, arguments) result.setMaxListeners(0) if (!result.pipe['$$monkey-patch']) { monkeyPatchPipe(result) } return result.on('error', function(err) { gutil.log(gutil.colors.yellow(err)) gutil.beep() this.emit('end') }) } }
[ "function", "monkeyPatchPipe", "(", "stream", ")", "{", "while", "(", "!", "stream", ".", "hasOwnProperty", "(", "'pipe'", ")", ")", "{", "stream", "=", "Object", ".", "getPrototypeOf", "(", "stream", ")", "if", "(", "!", "stream", ")", "return", "null", "}", "let", "existingPipe", "=", "stream", ".", "pipe", "newPipe", "[", "'$$monkey-patch'", "]", "=", "true", "return", "stream", ".", "pipe", "=", "newPipe", "/** Create new pipe copy of existing pipe */", "function", "newPipe", "(", ")", "{", "let", "result", "=", "existingPipe", ".", "apply", "(", "this", ",", "arguments", ")", "result", ".", "setMaxListeners", "(", "0", ")", "if", "(", "!", "result", ".", "pipe", "[", "'$$monkey-patch'", "]", ")", "{", "monkeyPatchPipe", "(", "result", ")", "}", "return", "result", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "gutil", ".", "log", "(", "gutil", ".", "colors", ".", "yellow", "(", "err", ")", ")", "gutil", ".", "beep", "(", ")", "this", ".", "emit", "(", "'end'", ")", "}", ")", "}", "}" ]
Monkey patch Gulp pipe to suppress errors in watch task @param {object} pipe Gulp stream
[ "Monkey", "patch", "Gulp", "pipe", "to", "suppress", "errors", "in", "watch", "task" ]
4ff186158b7031b570b2ba7507a9ff00e9e7e156
https://github.com/auttoio/typeform-node/blob/4ff186158b7031b570b2ba7507a9ff00e9e7e156/gulp/plumb.js#L18-L42
36,968
glayzzle/grafine
src/index.js
function(db, id) { this._db = db; this._id = id; this._index = new Map(); this._size = 0; this._changed = false; }
javascript
function(db, id) { this._db = db; this._id = id; this._index = new Map(); this._size = 0; this._changed = false; }
[ "function", "(", "db", ",", "id", ")", "{", "this", ".", "_db", "=", "db", ";", "this", ".", "_id", "=", "id", ";", "this", ".", "_index", "=", "new", "Map", "(", ")", ";", "this", ".", "_size", "=", "0", ";", "this", ".", "_changed", "=", "false", ";", "}" ]
An index storage @constructor Index
[ "An", "index", "storage" ]
616ff0a57806d6b809b69e81f3e5ff77919fc3cd
https://github.com/glayzzle/grafine/blob/616ff0a57806d6b809b69e81f3e5ff77919fc3cd/src/index.js#L14-L20
36,969
borela-tech/js-toolbox
src/configs/webpack/shared.js
configureBundleStats
function configureBundleStats(config) { // Interactive tree map of the bundle. if (interactiveBundleStats) config.plugins.push(new BundleAnalyzerPlugin) // JSON file containing the bundle stats. if (bundleStats) { config.plugins.push(new StatsWriterPlugin({ filename: 'bundle-stats.json', // Include everything. fields: null, })) } }
javascript
function configureBundleStats(config) { // Interactive tree map of the bundle. if (interactiveBundleStats) config.plugins.push(new BundleAnalyzerPlugin) // JSON file containing the bundle stats. if (bundleStats) { config.plugins.push(new StatsWriterPlugin({ filename: 'bundle-stats.json', // Include everything. fields: null, })) } }
[ "function", "configureBundleStats", "(", "config", ")", "{", "// Interactive tree map of the bundle.", "if", "(", "interactiveBundleStats", ")", "config", ".", "plugins", ".", "push", "(", "new", "BundleAnalyzerPlugin", ")", "// JSON file containing the bundle stats.", "if", "(", "bundleStats", ")", "{", "config", ".", "plugins", ".", "push", "(", "new", "StatsWriterPlugin", "(", "{", "filename", ":", "'bundle-stats.json'", ",", "// Include everything.", "fields", ":", "null", ",", "}", ")", ")", "}", "}" ]
Configure the stats generation.
[ "Configure", "the", "stats", "generation", "." ]
0ed75d373fa1573d64a3d715ee8e6e24852824e4
https://github.com/borela-tech/js-toolbox/blob/0ed75d373fa1573d64a3d715ee8e6e24852824e4/src/configs/webpack/shared.js#L55-L68
36,970
borela-tech/js-toolbox
src/configs/webpack/shared.js
configureJsMinification
function configureJsMinification(config) { if (!(minify || minifyJs)) return config.optimization.minimize = true config.optimization.minimizer = [new UglifyJsPlugin({ sourceMap: !disableSourceMaps, uglifyOptions: { output: { comments: false, }, }, })] }
javascript
function configureJsMinification(config) { if (!(minify || minifyJs)) return config.optimization.minimize = true config.optimization.minimizer = [new UglifyJsPlugin({ sourceMap: !disableSourceMaps, uglifyOptions: { output: { comments: false, }, }, })] }
[ "function", "configureJsMinification", "(", "config", ")", "{", "if", "(", "!", "(", "minify", "||", "minifyJs", ")", ")", "return", "config", ".", "optimization", ".", "minimize", "=", "true", "config", ".", "optimization", ".", "minimizer", "=", "[", "new", "UglifyJsPlugin", "(", "{", "sourceMap", ":", "!", "disableSourceMaps", ",", "uglifyOptions", ":", "{", "output", ":", "{", "comments", ":", "false", ",", "}", ",", "}", ",", "}", ")", "]", "}" ]
Configure the minifier to compress the final bundle.
[ "Configure", "the", "minifier", "to", "compress", "the", "final", "bundle", "." ]
0ed75d373fa1573d64a3d715ee8e6e24852824e4
https://github.com/borela-tech/js-toolbox/blob/0ed75d373fa1573d64a3d715ee8e6e24852824e4/src/configs/webpack/shared.js#L107-L119
36,971
MtnFranke/node-weka
lib/weka-lib.js
parseArffFile
function parseArffFile(arffObj, cb) { var arffFile = ''; arffFile += '@relation '; arffFile += arffObj.name; arffFile += '\n\n'; async.waterfall([ function (callback) { var i = 0; async.eachSeries(arffObj.data, function (obj, dataCb) { async.eachSeries(_.keys(obj), function (key, mapCb) { if (arffObj.types[key].type.indexOf('nominal') > -1 && !_.isString(arffObj.data[i][key])) { arffObj.data[i][key] = arffObj.types[key].oneof[arffObj.data[i][key]]; } mapCb(); }, function (err) { i++; dataCb(err); }); }, function (err) { callback(err); }); }, function (callback) { async.eachSeries(arffObj.attributes, function (obj, attrCb) { arffFile += '@attribute '; arffFile += obj; arffFile += ' '; if (arffObj.types[obj].type.indexOf('nominal') > -1) { arffFile += '{' + arffObj.types[obj].oneof + '}'; } else { arffFile += arffObj.types[obj].type; } arffFile += '\n'; attrCb(); }, function (err) { callback(err); }); }, function (callback) { arffFile += '\n'; arffFile += '@data'; arffFile += '\n'; async.eachSeries(arffObj.data, function (obj, dataCb) { arffFile += _.values(obj); arffFile += '\n'; dataCb(); }, function (err) { callback(err); }); } ], function (err, result) { var fileId = '/tmp/node-weka-' + _.random(0, 10000000) + '.arff'; // console.log(arffFile); fs.writeFile(fileId, arffFile, function (err) { cb(err, fileId); }); }); }
javascript
function parseArffFile(arffObj, cb) { var arffFile = ''; arffFile += '@relation '; arffFile += arffObj.name; arffFile += '\n\n'; async.waterfall([ function (callback) { var i = 0; async.eachSeries(arffObj.data, function (obj, dataCb) { async.eachSeries(_.keys(obj), function (key, mapCb) { if (arffObj.types[key].type.indexOf('nominal') > -1 && !_.isString(arffObj.data[i][key])) { arffObj.data[i][key] = arffObj.types[key].oneof[arffObj.data[i][key]]; } mapCb(); }, function (err) { i++; dataCb(err); }); }, function (err) { callback(err); }); }, function (callback) { async.eachSeries(arffObj.attributes, function (obj, attrCb) { arffFile += '@attribute '; arffFile += obj; arffFile += ' '; if (arffObj.types[obj].type.indexOf('nominal') > -1) { arffFile += '{' + arffObj.types[obj].oneof + '}'; } else { arffFile += arffObj.types[obj].type; } arffFile += '\n'; attrCb(); }, function (err) { callback(err); }); }, function (callback) { arffFile += '\n'; arffFile += '@data'; arffFile += '\n'; async.eachSeries(arffObj.data, function (obj, dataCb) { arffFile += _.values(obj); arffFile += '\n'; dataCb(); }, function (err) { callback(err); }); } ], function (err, result) { var fileId = '/tmp/node-weka-' + _.random(0, 10000000) + '.arff'; // console.log(arffFile); fs.writeFile(fileId, arffFile, function (err) { cb(err, fileId); }); }); }
[ "function", "parseArffFile", "(", "arffObj", ",", "cb", ")", "{", "var", "arffFile", "=", "''", ";", "arffFile", "+=", "'@relation '", ";", "arffFile", "+=", "arffObj", ".", "name", ";", "arffFile", "+=", "'\\n\\n'", ";", "async", ".", "waterfall", "(", "[", "function", "(", "callback", ")", "{", "var", "i", "=", "0", ";", "async", ".", "eachSeries", "(", "arffObj", ".", "data", ",", "function", "(", "obj", ",", "dataCb", ")", "{", "async", ".", "eachSeries", "(", "_", ".", "keys", "(", "obj", ")", ",", "function", "(", "key", ",", "mapCb", ")", "{", "if", "(", "arffObj", ".", "types", "[", "key", "]", ".", "type", ".", "indexOf", "(", "'nominal'", ")", ">", "-", "1", "&&", "!", "_", ".", "isString", "(", "arffObj", ".", "data", "[", "i", "]", "[", "key", "]", ")", ")", "{", "arffObj", ".", "data", "[", "i", "]", "[", "key", "]", "=", "arffObj", ".", "types", "[", "key", "]", ".", "oneof", "[", "arffObj", ".", "data", "[", "i", "]", "[", "key", "]", "]", ";", "}", "mapCb", "(", ")", ";", "}", ",", "function", "(", "err", ")", "{", "i", "++", ";", "dataCb", "(", "err", ")", ";", "}", ")", ";", "}", ",", "function", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "async", ".", "eachSeries", "(", "arffObj", ".", "attributes", ",", "function", "(", "obj", ",", "attrCb", ")", "{", "arffFile", "+=", "'@attribute '", ";", "arffFile", "+=", "obj", ";", "arffFile", "+=", "' '", ";", "if", "(", "arffObj", ".", "types", "[", "obj", "]", ".", "type", ".", "indexOf", "(", "'nominal'", ")", ">", "-", "1", ")", "{", "arffFile", "+=", "'{'", "+", "arffObj", ".", "types", "[", "obj", "]", ".", "oneof", "+", "'}'", ";", "}", "else", "{", "arffFile", "+=", "arffObj", ".", "types", "[", "obj", "]", ".", "type", ";", "}", "arffFile", "+=", "'\\n'", ";", "attrCb", "(", ")", ";", "}", ",", "function", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "arffFile", "+=", "'\\n'", ";", "arffFile", "+=", "'@data'", ";", "arffFile", "+=", "'\\n'", ";", "async", ".", "eachSeries", "(", "arffObj", ".", "data", ",", "function", "(", "obj", ",", "dataCb", ")", "{", "arffFile", "+=", "_", ".", "values", "(", "obj", ")", ";", "arffFile", "+=", "'\\n'", ";", "dataCb", "(", ")", ";", "}", ",", "function", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", ")", ";", "}", "]", ",", "function", "(", "err", ",", "result", ")", "{", "var", "fileId", "=", "'/tmp/node-weka-'", "+", "_", ".", "random", "(", "0", ",", "10000000", ")", "+", "'.arff'", ";", "// console.log(arffFile);", "fs", ".", "writeFile", "(", "fileId", ",", "arffFile", ",", "function", "(", "err", ")", "{", "cb", "(", "err", ",", "fileId", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
JS Arff format back to weka arff format
[ "JS", "Arff", "format", "back", "to", "weka", "arff", "format" ]
fadcc9db5da03e5c089139614905fc7d8325f9b3
https://github.com/MtnFranke/node-weka/blob/fadcc9db5da03e5c089139614905fc7d8325f9b3/lib/weka-lib.js#L75-L159
36,972
vail-systems/node-dct
src/dct.js
function(N) { cosMap = cosMap || {}; cosMap[N] = new Array(N*N); var PI_N = Math.PI / N; for (var k = 0; k < N; k++) { for (var n = 0; n < N; n++) { cosMap[N][n + (k * N)] = Math.cos(PI_N * (n + 0.5) * k); } } }
javascript
function(N) { cosMap = cosMap || {}; cosMap[N] = new Array(N*N); var PI_N = Math.PI / N; for (var k = 0; k < N; k++) { for (var n = 0; n < N; n++) { cosMap[N][n + (k * N)] = Math.cos(PI_N * (n + 0.5) * k); } } }
[ "function", "(", "N", ")", "{", "cosMap", "=", "cosMap", "||", "{", "}", ";", "cosMap", "[", "N", "]", "=", "new", "Array", "(", "N", "*", "N", ")", ";", "var", "PI_N", "=", "Math", ".", "PI", "/", "N", ";", "for", "(", "var", "k", "=", "0", ";", "k", "<", "N", ";", "k", "++", ")", "{", "for", "(", "var", "n", "=", "0", ";", "n", "<", "N", ";", "n", "++", ")", "{", "cosMap", "[", "N", "]", "[", "n", "+", "(", "k", "*", "N", ")", "]", "=", "Math", ".", "cos", "(", "PI_N", "*", "(", "n", "+", "0.5", ")", "*", "k", ")", ";", "}", "}", "}" ]
Builds a cosine map for the given input size. This allows multiple input sizes to be memoized automagically if you want to run the DCT over and over.
[ "Builds", "a", "cosine", "map", "for", "the", "given", "input", "size", ".", "This", "allows", "multiple", "input", "sizes", "to", "be", "memoized", "automagically", "if", "you", "want", "to", "run", "the", "DCT", "over", "and", "over", "." ]
a643a5d071a3a087e2f187c3a764b93568707be1
https://github.com/vail-systems/node-dct/blob/a643a5d071a3a087e2f187c3a764b93568707be1/src/dct.js#L14-L25
36,973
shakyShane/svg-sprite-data
lib/svg-obj.js
SVGObj
function SVGObj(file, svg, config) { this.file = file; this.id = path.basename(this.file, '.svg'); // this.newSVG = ; // this.newSVG = new dom().parseFromString('<book><title>Harry Potter</title></book>'); // this.newSVG = new dom().parseFromString(svg); // this.svg = libxmljs.parseXml(svg); this.svg = new XMLObject(svg); // console.log(this.svg); // console.log('-----------------------------------------'); // console.log('-----------------------------------------'); // console.log(this.newSVG); // // this.obj = new SVGToObject(svg); // res = this.obj.findAllNodes({name:'path'}); // res = this.obj.findNode({attributes:'width'}); // res = this.obj.findNode('@id'); // this.obj.log(); // var hans = obj.queryNode({name: 'path'}); // var hans = obj.queryNodeAll({name: 'path'}); // _.each(hans, function(node){ // console.log(obj.attribute(node, 'attributes')); // }) // console.log('######################################################'); // console.log('######################################################'); // console.log(); // console.log('hier', obj.queryNode('path')); // // // var select = xpath.useNamespaces({"svg": "http://www.w3.org/2000/svg"}); // var nodes = xpath.select("//title/text()", this.newSVG).toString(); // console.log('-----------------------------------------'); // console.log(select("//svg:title/text()", this.newSVG)[0].nodeValue); // console.log(select("//svg:@", this.newSVG)); // console.log(xpath.select("//svg", this.newSVG)); this._config = _.extend({ maxwidth : 1000, maxheight : 1000, padding : 0 }, config); this._config.maxwidth = Math.abs(parseInt(this._config.maxwidth || 0, 10)); this._config.maxheight = Math.abs(parseInt(this._config.maxheight || 0, 10)); this._config.padding = Math.abs(parseInt(this._config.padding, 10)); var width = this.svg.root().attr('width'), height = this.svg.root().attr('height'); this.width = width ? parseFloat(width, 10) : false; this.height = height ? parseFloat(height, 10) : false; // console.log('this.width',this.width); // console.log('this.height',this.height); // console.log('mywidth',parseFloat(this.obj.root().attr('width'),10)); // console.log('myheight',parseFloat(this.obj.root().attr('height'),10)); }
javascript
function SVGObj(file, svg, config) { this.file = file; this.id = path.basename(this.file, '.svg'); // this.newSVG = ; // this.newSVG = new dom().parseFromString('<book><title>Harry Potter</title></book>'); // this.newSVG = new dom().parseFromString(svg); // this.svg = libxmljs.parseXml(svg); this.svg = new XMLObject(svg); // console.log(this.svg); // console.log('-----------------------------------------'); // console.log('-----------------------------------------'); // console.log(this.newSVG); // // this.obj = new SVGToObject(svg); // res = this.obj.findAllNodes({name:'path'}); // res = this.obj.findNode({attributes:'width'}); // res = this.obj.findNode('@id'); // this.obj.log(); // var hans = obj.queryNode({name: 'path'}); // var hans = obj.queryNodeAll({name: 'path'}); // _.each(hans, function(node){ // console.log(obj.attribute(node, 'attributes')); // }) // console.log('######################################################'); // console.log('######################################################'); // console.log(); // console.log('hier', obj.queryNode('path')); // // // var select = xpath.useNamespaces({"svg": "http://www.w3.org/2000/svg"}); // var nodes = xpath.select("//title/text()", this.newSVG).toString(); // console.log('-----------------------------------------'); // console.log(select("//svg:title/text()", this.newSVG)[0].nodeValue); // console.log(select("//svg:@", this.newSVG)); // console.log(xpath.select("//svg", this.newSVG)); this._config = _.extend({ maxwidth : 1000, maxheight : 1000, padding : 0 }, config); this._config.maxwidth = Math.abs(parseInt(this._config.maxwidth || 0, 10)); this._config.maxheight = Math.abs(parseInt(this._config.maxheight || 0, 10)); this._config.padding = Math.abs(parseInt(this._config.padding, 10)); var width = this.svg.root().attr('width'), height = this.svg.root().attr('height'); this.width = width ? parseFloat(width, 10) : false; this.height = height ? parseFloat(height, 10) : false; // console.log('this.width',this.width); // console.log('this.height',this.height); // console.log('mywidth',parseFloat(this.obj.root().attr('width'),10)); // console.log('myheight',parseFloat(this.obj.root().attr('height'),10)); }
[ "function", "SVGObj", "(", "file", ",", "svg", ",", "config", ")", "{", "this", ".", "file", "=", "file", ";", "this", ".", "id", "=", "path", ".", "basename", "(", "this", ".", "file", ",", "'.svg'", ")", ";", "// this.newSVG = ;", "// this.newSVG = new dom().parseFromString('<book><title>Harry Potter</title></book>');", "// this.newSVG = new dom().parseFromString(svg);", "// this.svg = libxmljs.parseXml(svg);", "this", ".", "svg", "=", "new", "XMLObject", "(", "svg", ")", ";", "// console.log(this.svg);", "// console.log('-----------------------------------------');", "// console.log('-----------------------------------------');", "// console.log(this.newSVG);", "//", "// this.obj = new SVGToObject(svg);", "// res = this.obj.findAllNodes({name:'path'});", "// res = this.obj.findNode({attributes:'width'});", "// res = this.obj.findNode('@id');", "// this.obj.log();", "// var hans = obj.queryNode({name: 'path'});", "// var hans = obj.queryNodeAll({name: 'path'});", "// _.each(hans, function(node){", "// console.log(obj.attribute(node, 'attributes'));", "// })", "// console.log('######################################################');", "// console.log('######################################################');", "// console.log();", "// console.log('hier', obj.queryNode('path'));", "//", "//", "// var select = xpath.useNamespaces({\"svg\": \"http://www.w3.org/2000/svg\"});", "// var nodes = xpath.select(\"//title/text()\", this.newSVG).toString();", "// console.log('-----------------------------------------');", "// console.log(select(\"//svg:title/text()\", this.newSVG)[0].nodeValue);", "// console.log(select(\"//svg:@\", this.newSVG));", "// console.log(xpath.select(\"//svg\", this.newSVG));", "this", ".", "_config", "=", "_", ".", "extend", "(", "{", "maxwidth", ":", "1000", ",", "maxheight", ":", "1000", ",", "padding", ":", "0", "}", ",", "config", ")", ";", "this", ".", "_config", ".", "maxwidth", "=", "Math", ".", "abs", "(", "parseInt", "(", "this", ".", "_config", ".", "maxwidth", "||", "0", ",", "10", ")", ")", ";", "this", ".", "_config", ".", "maxheight", "=", "Math", ".", "abs", "(", "parseInt", "(", "this", ".", "_config", ".", "maxheight", "||", "0", ",", "10", ")", ")", ";", "this", ".", "_config", ".", "padding", "=", "Math", ".", "abs", "(", "parseInt", "(", "this", ".", "_config", ".", "padding", ",", "10", ")", ")", ";", "var", "width", "=", "this", ".", "svg", ".", "root", "(", ")", ".", "attr", "(", "'width'", ")", ",", "height", "=", "this", ".", "svg", ".", "root", "(", ")", ".", "attr", "(", "'height'", ")", ";", "this", ".", "width", "=", "width", "?", "parseFloat", "(", "width", ",", "10", ")", ":", "false", ";", "this", ".", "height", "=", "height", "?", "parseFloat", "(", "height", ",", "10", ")", ":", "false", ";", "// console.log('this.width',this.width);", "// console.log('this.height',this.height);", "// console.log('mywidth',parseFloat(this.obj.root().attr('width'),10));", "// console.log('myheight',parseFloat(this.obj.root().attr('height'),10));", "}" ]
SVG object constructor @param {String} file SVG file name @param {String} svg SVG XML @param {Object} config Configuration @return {SVGObj}
[ "SVG", "object", "constructor" ]
fa2bd9e68df3dd5906153333245aa06a5ac4b2b3
https://github.com/shakyShane/svg-sprite-data/blob/fa2bd9e68df3dd5906153333245aa06a5ac4b2b3/lib/svg-obj.js#L26-L91
36,974
robhicks/financejs
finance.js
dateLastPaymentShouldHaveBeenMade
function dateLastPaymentShouldHaveBeenMade(loan, cb) { var d = Q.defer(); var result; if (!loan || _.isEmpty(loan.amortizationTable)) { d.reject(new Error('required dateLastPaymentShouldHaveBeenMade not provided')); } else { var determinationDate = loan.determinationDate ? moment(loan.determinationDate) : moment(); var daysUntilLate = loan.daysUntilLate ? Number(loan.daysUntilLate) : 0; determinationDate.add('days', daysUntilLate); loan.amortizationTable.forEach(function (payment) { var paymentDate = moment(payment.date); if (paymentDate.isBefore(determinationDate)) result = paymentDate.toISOString(); }); loan.dateLastPaymentShouldHaveBeenMade = result; d.resolve(loan) } if (cb) return cb(loan); return d.promise; }
javascript
function dateLastPaymentShouldHaveBeenMade(loan, cb) { var d = Q.defer(); var result; if (!loan || _.isEmpty(loan.amortizationTable)) { d.reject(new Error('required dateLastPaymentShouldHaveBeenMade not provided')); } else { var determinationDate = loan.determinationDate ? moment(loan.determinationDate) : moment(); var daysUntilLate = loan.daysUntilLate ? Number(loan.daysUntilLate) : 0; determinationDate.add('days', daysUntilLate); loan.amortizationTable.forEach(function (payment) { var paymentDate = moment(payment.date); if (paymentDate.isBefore(determinationDate)) result = paymentDate.toISOString(); }); loan.dateLastPaymentShouldHaveBeenMade = result; d.resolve(loan) } if (cb) return cb(loan); return d.promise; }
[ "function", "dateLastPaymentShouldHaveBeenMade", "(", "loan", ",", "cb", ")", "{", "var", "d", "=", "Q", ".", "defer", "(", ")", ";", "var", "result", ";", "if", "(", "!", "loan", "||", "_", ".", "isEmpty", "(", "loan", ".", "amortizationTable", ")", ")", "{", "d", ".", "reject", "(", "new", "Error", "(", "'required dateLastPaymentShouldHaveBeenMade not provided'", ")", ")", ";", "}", "else", "{", "var", "determinationDate", "=", "loan", ".", "determinationDate", "?", "moment", "(", "loan", ".", "determinationDate", ")", ":", "moment", "(", ")", ";", "var", "daysUntilLate", "=", "loan", ".", "daysUntilLate", "?", "Number", "(", "loan", ".", "daysUntilLate", ")", ":", "0", ";", "determinationDate", ".", "add", "(", "'days'", ",", "daysUntilLate", ")", ";", "loan", ".", "amortizationTable", ".", "forEach", "(", "function", "(", "payment", ")", "{", "var", "paymentDate", "=", "moment", "(", "payment", ".", "date", ")", ";", "if", "(", "paymentDate", ".", "isBefore", "(", "determinationDate", ")", ")", "result", "=", "paymentDate", ".", "toISOString", "(", ")", ";", "}", ")", ";", "loan", ".", "dateLastPaymentShouldHaveBeenMade", "=", "result", ";", "d", ".", "resolve", "(", "loan", ")", "}", "if", "(", "cb", ")", "return", "cb", "(", "loan", ")", ";", "return", "d", ".", "promise", ";", "}" ]
Calculates the last date a payment should have been @param loan, which must include - amortizationTable - a loan amortization table with the expected payment dates - daysUntilLate (optional) - the grace days for the loan - defaults to 0 - determinationDate (optional) - the date the determination is made, defaults to today
[ "Calculates", "the", "last", "date", "a", "payment", "should", "have", "been" ]
dc9f0f63c8440a678f4d3598e1273c01f773cea3
https://github.com/robhicks/financejs/blob/dc9f0f63c8440a678f4d3598e1273c01f773cea3/finance.js#L544-L562
36,975
robhicks/financejs
finance.js
addLateFees
function addLateFees(loan, cb) { var d = Q.defer(); if (!loan || !loan.closingDate || !loan.loanAmount || !loan.interestRate || !loan.paymentAmount) { d.reject(new Error('required parameters for addLateFees not provided')); } else { var lateFee = calcLateFee(loan); var determinationDate = moment(); var txDate, pmtDate, graceDate, pmtTransactions, elapsedMonths, i; var lateFeeTxs = loan.transactions.filter(function (tx) { return tx.type === 'Late Fee'; }); //remove all existing late fees lateFeeTxs.forEach(function (tx) { loan.transactions.id(tx._id).remove(); }); pmtTransactions = loan.transactions.filter(function (tx) { return tx.type !== 'Late Fee'; }); //calculate the number of months that have lapsed starting with the first payment date //until the determination date elapsedMonths = determinationDate.diff(moment(loan.firstPaymentDate), 'months') + 1; for (i = 0; i < elapsedMonths; i++) { pmtDate = moment(loan.firstPaymentDate).add('months', i); graceDate = moment(loan.firstPaymentDate).add('months', i).add('days', loan.daysUntilLate); if (!paymentMadeOnTime(pmtTransactions, pmtDate, graceDate, loan.paymentAmount) && pmtDate.isBefore(determinationDate) && !lateFeeAppliedForDate(loan, graceDate)) { txDate = graceDate.toISOString(); console.log('loan balance in late fees: ', getLoanBalance(loan, txDate)); loan.transactions.push({ txDate: txDate, type: "Late Fee", amount: -1 * lateFee, comments: "Late fee imposed for failure to pay on time or to pay proper amount", loanBalance: getLoanBalance(loan, txDate) }); } } } console.log('addLateFees'); d.resolve(loan); if (cb) return cb(loan); return d.promise; }
javascript
function addLateFees(loan, cb) { var d = Q.defer(); if (!loan || !loan.closingDate || !loan.loanAmount || !loan.interestRate || !loan.paymentAmount) { d.reject(new Error('required parameters for addLateFees not provided')); } else { var lateFee = calcLateFee(loan); var determinationDate = moment(); var txDate, pmtDate, graceDate, pmtTransactions, elapsedMonths, i; var lateFeeTxs = loan.transactions.filter(function (tx) { return tx.type === 'Late Fee'; }); //remove all existing late fees lateFeeTxs.forEach(function (tx) { loan.transactions.id(tx._id).remove(); }); pmtTransactions = loan.transactions.filter(function (tx) { return tx.type !== 'Late Fee'; }); //calculate the number of months that have lapsed starting with the first payment date //until the determination date elapsedMonths = determinationDate.diff(moment(loan.firstPaymentDate), 'months') + 1; for (i = 0; i < elapsedMonths; i++) { pmtDate = moment(loan.firstPaymentDate).add('months', i); graceDate = moment(loan.firstPaymentDate).add('months', i).add('days', loan.daysUntilLate); if (!paymentMadeOnTime(pmtTransactions, pmtDate, graceDate, loan.paymentAmount) && pmtDate.isBefore(determinationDate) && !lateFeeAppliedForDate(loan, graceDate)) { txDate = graceDate.toISOString(); console.log('loan balance in late fees: ', getLoanBalance(loan, txDate)); loan.transactions.push({ txDate: txDate, type: "Late Fee", amount: -1 * lateFee, comments: "Late fee imposed for failure to pay on time or to pay proper amount", loanBalance: getLoanBalance(loan, txDate) }); } } } console.log('addLateFees'); d.resolve(loan); if (cb) return cb(loan); return d.promise; }
[ "function", "addLateFees", "(", "loan", ",", "cb", ")", "{", "var", "d", "=", "Q", ".", "defer", "(", ")", ";", "if", "(", "!", "loan", "||", "!", "loan", ".", "closingDate", "||", "!", "loan", ".", "loanAmount", "||", "!", "loan", ".", "interestRate", "||", "!", "loan", ".", "paymentAmount", ")", "{", "d", ".", "reject", "(", "new", "Error", "(", "'required parameters for addLateFees not provided'", ")", ")", ";", "}", "else", "{", "var", "lateFee", "=", "calcLateFee", "(", "loan", ")", ";", "var", "determinationDate", "=", "moment", "(", ")", ";", "var", "txDate", ",", "pmtDate", ",", "graceDate", ",", "pmtTransactions", ",", "elapsedMonths", ",", "i", ";", "var", "lateFeeTxs", "=", "loan", ".", "transactions", ".", "filter", "(", "function", "(", "tx", ")", "{", "return", "tx", ".", "type", "===", "'Late Fee'", ";", "}", ")", ";", "//remove all existing late fees", "lateFeeTxs", ".", "forEach", "(", "function", "(", "tx", ")", "{", "loan", ".", "transactions", ".", "id", "(", "tx", ".", "_id", ")", ".", "remove", "(", ")", ";", "}", ")", ";", "pmtTransactions", "=", "loan", ".", "transactions", ".", "filter", "(", "function", "(", "tx", ")", "{", "return", "tx", ".", "type", "!==", "'Late Fee'", ";", "}", ")", ";", "//calculate the number of months that have lapsed starting with the first payment date", "//until the determination date", "elapsedMonths", "=", "determinationDate", ".", "diff", "(", "moment", "(", "loan", ".", "firstPaymentDate", ")", ",", "'months'", ")", "+", "1", ";", "for", "(", "i", "=", "0", ";", "i", "<", "elapsedMonths", ";", "i", "++", ")", "{", "pmtDate", "=", "moment", "(", "loan", ".", "firstPaymentDate", ")", ".", "add", "(", "'months'", ",", "i", ")", ";", "graceDate", "=", "moment", "(", "loan", ".", "firstPaymentDate", ")", ".", "add", "(", "'months'", ",", "i", ")", ".", "add", "(", "'days'", ",", "loan", ".", "daysUntilLate", ")", ";", "if", "(", "!", "paymentMadeOnTime", "(", "pmtTransactions", ",", "pmtDate", ",", "graceDate", ",", "loan", ".", "paymentAmount", ")", "&&", "pmtDate", ".", "isBefore", "(", "determinationDate", ")", "&&", "!", "lateFeeAppliedForDate", "(", "loan", ",", "graceDate", ")", ")", "{", "txDate", "=", "graceDate", ".", "toISOString", "(", ")", ";", "console", ".", "log", "(", "'loan balance in late fees: '", ",", "getLoanBalance", "(", "loan", ",", "txDate", ")", ")", ";", "loan", ".", "transactions", ".", "push", "(", "{", "txDate", ":", "txDate", ",", "type", ":", "\"Late Fee\"", ",", "amount", ":", "-", "1", "*", "lateFee", ",", "comments", ":", "\"Late fee imposed for failure to pay on time or to pay proper amount\"", ",", "loanBalance", ":", "getLoanBalance", "(", "loan", ",", "txDate", ")", "}", ")", ";", "}", "}", "}", "console", ".", "log", "(", "'addLateFees'", ")", ";", "d", ".", "resolve", "(", "loan", ")", ";", "if", "(", "cb", ")", "return", "cb", "(", "loan", ")", ";", "return", "d", ".", "promise", ";", "}" ]
Add Late Fees @param loan @param cb @returns {*}
[ "Add", "Late", "Fees" ]
dc9f0f63c8440a678f4d3598e1273c01f773cea3
https://github.com/robhicks/financejs/blob/dc9f0f63c8440a678f4d3598e1273c01f773cea3/finance.js#L727-L774
36,976
sjkaliski/music
commands/play.js
SpotifySearch
function SpotifySearch (title) { /** * @public {Array} tracks. */ this.tracks = [] // Query spotify, parse xml response, display in terminal, // prompt user for track number, play track. this._query(title) .then(this._parseJSON.bind(this)) .then(this._printData.bind(this)) .then(this._promptUser.bind(this)) .then(this._playTrack.bind(this)) .fail(this._onError.bind(this)) }
javascript
function SpotifySearch (title) { /** * @public {Array} tracks. */ this.tracks = [] // Query spotify, parse xml response, display in terminal, // prompt user for track number, play track. this._query(title) .then(this._parseJSON.bind(this)) .then(this._printData.bind(this)) .then(this._promptUser.bind(this)) .then(this._playTrack.bind(this)) .fail(this._onError.bind(this)) }
[ "function", "SpotifySearch", "(", "title", ")", "{", "/**\n * @public {Array} tracks.\n */", "this", ".", "tracks", "=", "[", "]", "// Query spotify, parse xml response, display in terminal,", "// prompt user for track number, play track.", "this", ".", "_query", "(", "title", ")", ".", "then", "(", "this", ".", "_parseJSON", ".", "bind", "(", "this", ")", ")", ".", "then", "(", "this", ".", "_printData", ".", "bind", "(", "this", ")", ")", ".", "then", "(", "this", ".", "_promptUser", ".", "bind", "(", "this", ")", ")", ".", "then", "(", "this", ".", "_playTrack", ".", "bind", "(", "this", ")", ")", ".", "fail", "(", "this", ".", "_onError", ".", "bind", "(", "this", ")", ")", "}" ]
Spotify search client. @param {string} search query. @constructor
[ "Spotify", "search", "client", "." ]
cb56232204ce455590fc9a27eead22b3d7fd2172
https://github.com/sjkaliski/music/blob/cb56232204ce455590fc9a27eead22b3d7fd2172/commands/play.js#L45-L59
36,977
mozilla/MakeAPI
lib/middleware.js
function (modelName) { if (["make", "list"].indexOf(modelName) === -1) { throw new Error( "checkOwnerApp middleware can only be configured with 'make' or 'list'. You passed in: '" + modelName + "'" ); } return function (req, res, next) { // Don't enforce write permissions if not enabled. if (!ENFORCE_WRITE_PERMISSIONS) { return next(); } var model = req[modelName], user = req.credentials.user; // check if the authenticated application has admin permissions, or if it owns the make if (req.credentials.admin !== true && user !== model.ownerApp) { return hawkModule.respond(403, res, req.credentials, req.artifacts, { status: "failure", reason: "unauthorized" }, "application/json"); } next(); }; }
javascript
function (modelName) { if (["make", "list"].indexOf(modelName) === -1) { throw new Error( "checkOwnerApp middleware can only be configured with 'make' or 'list'. You passed in: '" + modelName + "'" ); } return function (req, res, next) { // Don't enforce write permissions if not enabled. if (!ENFORCE_WRITE_PERMISSIONS) { return next(); } var model = req[modelName], user = req.credentials.user; // check if the authenticated application has admin permissions, or if it owns the make if (req.credentials.admin !== true && user !== model.ownerApp) { return hawkModule.respond(403, res, req.credentials, req.artifacts, { status: "failure", reason: "unauthorized" }, "application/json"); } next(); }; }
[ "function", "(", "modelName", ")", "{", "if", "(", "[", "\"make\"", ",", "\"list\"", "]", ".", "indexOf", "(", "modelName", ")", "===", "-", "1", ")", "{", "throw", "new", "Error", "(", "\"checkOwnerApp middleware can only be configured with 'make' or 'list'. You passed in: '\"", "+", "modelName", "+", "\"'\"", ")", ";", "}", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "// Don't enforce write permissions if not enabled.", "if", "(", "!", "ENFORCE_WRITE_PERMISSIONS", ")", "{", "return", "next", "(", ")", ";", "}", "var", "model", "=", "req", "[", "modelName", "]", ",", "user", "=", "req", ".", "credentials", ".", "user", ";", "// check if the authenticated application has admin permissions, or if it owns the make", "if", "(", "req", ".", "credentials", ".", "admin", "!==", "true", "&&", "user", "!==", "model", ".", "ownerApp", ")", "{", "return", "hawkModule", ".", "respond", "(", "403", ",", "res", ",", "req", ".", "credentials", ",", "req", ".", "artifacts", ",", "{", "status", ":", "\"failure\"", ",", "reason", ":", "\"unauthorized\"", "}", ",", "\"application/json\"", ")", ";", "}", "next", "(", ")", ";", "}", ";", "}" ]
modelName must be "make" or "list" only
[ "modelName", "must", "be", "make", "or", "list", "only" ]
f2893cf6cb81cfed10252a83f721572a1bf2e7ce
https://github.com/mozilla/MakeAPI/blob/f2893cf6cb81cfed10252a83f721572a1bf2e7ce/lib/middleware.js#L311-L337
36,978
helion3/lodash-addons
src/getPrototype.js
getPrototype
function getPrototype(value) { let prototype; if (!_.isUndefined(value) && !_.isNull(value)) { if (!_.isObject(value)) { prototype = value.constructor.prototype; } else if (_.isFunction(value)) { prototype = value.prototype; } else { prototype = Object.getPrototypeOf(value); } } return prototype; }
javascript
function getPrototype(value) { let prototype; if (!_.isUndefined(value) && !_.isNull(value)) { if (!_.isObject(value)) { prototype = value.constructor.prototype; } else if (_.isFunction(value)) { prototype = value.prototype; } else { prototype = Object.getPrototypeOf(value); } } return prototype; }
[ "function", "getPrototype", "(", "value", ")", "{", "let", "prototype", ";", "if", "(", "!", "_", ".", "isUndefined", "(", "value", ")", "&&", "!", "_", ".", "isNull", "(", "value", ")", ")", "{", "if", "(", "!", "_", ".", "isObject", "(", "value", ")", ")", "{", "prototype", "=", "value", ".", "constructor", ".", "prototype", ";", "}", "else", "if", "(", "_", ".", "isFunction", "(", "value", ")", ")", "{", "prototype", "=", "value", ".", "prototype", ";", "}", "else", "{", "prototype", "=", "Object", ".", "getPrototypeOf", "(", "value", ")", ";", "}", "}", "return", "prototype", ";", "}" ]
Gets the prototype for the given value. @static @memberOf _ @category Util @param {*} value Source value @return {object} Found prototype or undefined. @example _.getPrototype(5); // => { toFixed: func(), ... }
[ "Gets", "the", "prototype", "for", "the", "given", "value", "." ]
83b5bf14258241e7ae35eef346151a332fdb6f50
https://github.com/helion3/lodash-addons/blob/83b5bf14258241e7ae35eef346151a332fdb6f50/src/getPrototype.js#L16-L32
36,979
helion3/lodash-addons
src/generateKey.js
generateKey
function generateKey(length) { const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const possibleLength = possible.length - 1; let text = ''; _.times(getNumber(length, 16), () => { text += possible.charAt(_.random(possibleLength)); }); return text; }
javascript
function generateKey(length) { const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const possibleLength = possible.length - 1; let text = ''; _.times(getNumber(length, 16), () => { text += possible.charAt(_.random(possibleLength)); }); return text; }
[ "function", "generateKey", "(", "length", ")", "{", "const", "possible", "=", "'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'", ";", "const", "possibleLength", "=", "possible", ".", "length", "-", "1", ";", "let", "text", "=", "''", ";", "_", ".", "times", "(", "getNumber", "(", "length", ",", "16", ")", ",", "(", ")", "=>", "{", "text", "+=", "possible", ".", "charAt", "(", "_", ".", "random", "(", "possibleLength", ")", ")", ";", "}", ")", ";", "return", "text", ";", "}" ]
Generates a random alphanumeric string with length n. @static @memberOf _ @category String @param {int} length Desired length. @return {string} String of random characters. @example _.generateKey(5); // => 'L7IpD'
[ "Generates", "a", "random", "alphanumeric", "string", "with", "length", "n", "." ]
83b5bf14258241e7ae35eef346151a332fdb6f50
https://github.com/helion3/lodash-addons/blob/83b5bf14258241e7ae35eef346151a332fdb6f50/src/generateKey.js#L17-L27
36,980
myrmex-org/myrmex
packages/api-gateway/src/cli/create-model.js
executeCommand
function executeCommand(parameters) { // If a name has been provided, we create the project directory const modelFilePath = path.join(process.cwd(), plugin.config.modelsPath); return mkdirpAsync(modelFilePath) .then(() => { const model = { type: 'object', properties: {} }; return fs.writeFileAsync(modelFilePath + path.sep + parameters.name + '.json', JSON.stringify(model, null, 2)); }) .then(() => { let msg = '\n A new model has been created!\n\n'; msg += ' Its Swagger specification is available in ' + icli.format.info(modelFilePath + path.sep + parameters.name + '.json') + '\n'; icli.print(msg); }); }
javascript
function executeCommand(parameters) { // If a name has been provided, we create the project directory const modelFilePath = path.join(process.cwd(), plugin.config.modelsPath); return mkdirpAsync(modelFilePath) .then(() => { const model = { type: 'object', properties: {} }; return fs.writeFileAsync(modelFilePath + path.sep + parameters.name + '.json', JSON.stringify(model, null, 2)); }) .then(() => { let msg = '\n A new model has been created!\n\n'; msg += ' Its Swagger specification is available in ' + icli.format.info(modelFilePath + path.sep + parameters.name + '.json') + '\n'; icli.print(msg); }); }
[ "function", "executeCommand", "(", "parameters", ")", "{", "// If a name has been provided, we create the project directory", "const", "modelFilePath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "plugin", ".", "config", ".", "modelsPath", ")", ";", "return", "mkdirpAsync", "(", "modelFilePath", ")", ".", "then", "(", "(", ")", "=>", "{", "const", "model", "=", "{", "type", ":", "'object'", ",", "properties", ":", "{", "}", "}", ";", "return", "fs", ".", "writeFileAsync", "(", "modelFilePath", "+", "path", ".", "sep", "+", "parameters", ".", "name", "+", "'.json'", ",", "JSON", ".", "stringify", "(", "model", ",", "null", ",", "2", ")", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "let", "msg", "=", "'\\n A new model has been created!\\n\\n'", ";", "msg", "+=", "' Its Swagger specification is available in '", "+", "icli", ".", "format", ".", "info", "(", "modelFilePath", "+", "path", ".", "sep", "+", "parameters", ".", "name", "+", "'.json'", ")", "+", "'\\n'", ";", "icli", ".", "print", "(", "msg", ")", ";", "}", ")", ";", "}" ]
Create the new model @param {Object} parameters - the parameters provided in the command and in the prompt @returns {Promise<null>} - The execution stops here
[ "Create", "the", "new", "model" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/api-gateway/src/cli/create-model.js#L42-L58
36,981
myrmex-org/myrmex
packages/iam/src/index.js
loadPolicies
function loadPolicies() { const policyConfigsPath = path.join(process.cwd(), plugin.config.policiesPath); // This event allows to inject code before loading all APIs return plugin.myrmex.fire('beforePoliciesLoad') .then(() => { // Retrieve configuration path of all API specifications return fs.readdirAsync(policyConfigsPath); }) .then(policyConfigFiles => { // Load all the policy configurations const policyPromises = []; _.forEach(policyConfigFiles, (filename) => { const policyConfigPath = path.join(policyConfigsPath, filename); const policyName = path.parse(filename).name; policyPromises.push(loadPolicy(policyConfigPath, policyName)); }); return Promise.all(policyPromises); }) .then(policies => { // This event allows to inject code to add or delete or alter policy configurations return plugin.myrmex.fire('afterPoliciesLoad', policies); }) .spread(policies => { return Promise.resolve(policies); }) .catch(e => { if (e.code === 'ENOENT' && path.basename(e.path) === 'policies') { return Promise.resolve([]); } return Promise.reject(e); }); }
javascript
function loadPolicies() { const policyConfigsPath = path.join(process.cwd(), plugin.config.policiesPath); // This event allows to inject code before loading all APIs return plugin.myrmex.fire('beforePoliciesLoad') .then(() => { // Retrieve configuration path of all API specifications return fs.readdirAsync(policyConfigsPath); }) .then(policyConfigFiles => { // Load all the policy configurations const policyPromises = []; _.forEach(policyConfigFiles, (filename) => { const policyConfigPath = path.join(policyConfigsPath, filename); const policyName = path.parse(filename).name; policyPromises.push(loadPolicy(policyConfigPath, policyName)); }); return Promise.all(policyPromises); }) .then(policies => { // This event allows to inject code to add or delete or alter policy configurations return plugin.myrmex.fire('afterPoliciesLoad', policies); }) .spread(policies => { return Promise.resolve(policies); }) .catch(e => { if (e.code === 'ENOENT' && path.basename(e.path) === 'policies') { return Promise.resolve([]); } return Promise.reject(e); }); }
[ "function", "loadPolicies", "(", ")", "{", "const", "policyConfigsPath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "plugin", ".", "config", ".", "policiesPath", ")", ";", "// This event allows to inject code before loading all APIs", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'beforePoliciesLoad'", ")", ".", "then", "(", "(", ")", "=>", "{", "// Retrieve configuration path of all API specifications", "return", "fs", ".", "readdirAsync", "(", "policyConfigsPath", ")", ";", "}", ")", ".", "then", "(", "policyConfigFiles", "=>", "{", "// Load all the policy configurations", "const", "policyPromises", "=", "[", "]", ";", "_", ".", "forEach", "(", "policyConfigFiles", ",", "(", "filename", ")", "=>", "{", "const", "policyConfigPath", "=", "path", ".", "join", "(", "policyConfigsPath", ",", "filename", ")", ";", "const", "policyName", "=", "path", ".", "parse", "(", "filename", ")", ".", "name", ";", "policyPromises", ".", "push", "(", "loadPolicy", "(", "policyConfigPath", ",", "policyName", ")", ")", ";", "}", ")", ";", "return", "Promise", ".", "all", "(", "policyPromises", ")", ";", "}", ")", ".", "then", "(", "policies", "=>", "{", "// This event allows to inject code to add or delete or alter policy configurations", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'afterPoliciesLoad'", ",", "policies", ")", ";", "}", ")", ".", "spread", "(", "policies", "=>", "{", "return", "Promise", ".", "resolve", "(", "policies", ")", ";", "}", ")", ".", "catch", "(", "e", "=>", "{", "if", "(", "e", ".", "code", "===", "'ENOENT'", "&&", "path", ".", "basename", "(", "e", ".", "path", ")", "===", "'policies'", ")", "{", "return", "Promise", ".", "resolve", "(", "[", "]", ")", ";", "}", "return", "Promise", ".", "reject", "(", "e", ")", ";", "}", ")", ";", "}" ]
Load all policy configurations @return {Promise<[Policy]>} - promise of an array of policies
[ "Load", "all", "policy", "configurations" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/iam/src/index.js#L14-L46
36,982
myrmex-org/myrmex
packages/iam/src/index.js
loadPolicy
function loadPolicy(documentPath, name) { return plugin.myrmex.fire('beforePolicyLoad', documentPath, name) .spread((documentPath, name) => { // Because we use require() to get the document, it could either be a JSON file // or the content exported by a node module // But because require() caches the content it loads, we clone the result to avoid bugs // if the function is called twice const document = _.cloneDeep(require(documentPath)); const Policy = require('./policy'); const policy = new Policy(document, name); // This event allows to inject code to alter the Lambda configuration return plugin.myrmex.fire('afterPolicyLoad', policy); }) .spread((policy) => { return Promise.resolve(policy); }); }
javascript
function loadPolicy(documentPath, name) { return plugin.myrmex.fire('beforePolicyLoad', documentPath, name) .spread((documentPath, name) => { // Because we use require() to get the document, it could either be a JSON file // or the content exported by a node module // But because require() caches the content it loads, we clone the result to avoid bugs // if the function is called twice const document = _.cloneDeep(require(documentPath)); const Policy = require('./policy'); const policy = new Policy(document, name); // This event allows to inject code to alter the Lambda configuration return plugin.myrmex.fire('afterPolicyLoad', policy); }) .spread((policy) => { return Promise.resolve(policy); }); }
[ "function", "loadPolicy", "(", "documentPath", ",", "name", ")", "{", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'beforePolicyLoad'", ",", "documentPath", ",", "name", ")", ".", "spread", "(", "(", "documentPath", ",", "name", ")", "=>", "{", "// Because we use require() to get the document, it could either be a JSON file", "// or the content exported by a node module", "// But because require() caches the content it loads, we clone the result to avoid bugs", "// if the function is called twice", "const", "document", "=", "_", ".", "cloneDeep", "(", "require", "(", "documentPath", ")", ")", ";", "const", "Policy", "=", "require", "(", "'./policy'", ")", ";", "const", "policy", "=", "new", "Policy", "(", "document", ",", "name", ")", ";", "// This event allows to inject code to alter the Lambda configuration", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'afterPolicyLoad'", ",", "policy", ")", ";", "}", ")", ".", "spread", "(", "(", "policy", ")", "=>", "{", "return", "Promise", ".", "resolve", "(", "policy", ")", ";", "}", ")", ";", "}" ]
Load a policy @param {string} documentPath - path to the document file @param {string} name - the policy name @returns {Promise<Policy>} - the promise of a policy
[ "Load", "a", "policy" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/iam/src/index.js#L54-L71
36,983
myrmex-org/myrmex
packages/iam/src/index.js
findPolicies
function findPolicies(identifiers) { return loadPolicies() .then((policies) => { return _.filter(policies, (policy) => { return identifiers.indexOf(policy.name) !== -1; }); }); }
javascript
function findPolicies(identifiers) { return loadPolicies() .then((policies) => { return _.filter(policies, (policy) => { return identifiers.indexOf(policy.name) !== -1; }); }); }
[ "function", "findPolicies", "(", "identifiers", ")", "{", "return", "loadPolicies", "(", ")", ".", "then", "(", "(", "policies", ")", "=>", "{", "return", "_", ".", "filter", "(", "policies", ",", "(", "policy", ")", "=>", "{", "return", "identifiers", ".", "indexOf", "(", "policy", ".", "name", ")", "!==", "-", "1", ";", "}", ")", ";", "}", ")", ";", "}" ]
Retrieve policies by their identifier @param {Array} identifiers - an array of policy identifiers @return {Promise<[Policy]>} - promise of an array of policies
[ "Retrieve", "policies", "by", "their", "identifier" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/iam/src/index.js#L78-L83
36,984
myrmex-org/myrmex
packages/iam/src/index.js
registerCommands
function registerCommands(icli) { return Promise.all([ require('./cli/create-policy')(icli), require('./cli/create-role')(icli), require('./cli/deploy-policies')(icli), require('./cli/deploy-roles')(icli) ]) .then(() => { return Promise.resolve([]); }); }
javascript
function registerCommands(icli) { return Promise.all([ require('./cli/create-policy')(icli), require('./cli/create-role')(icli), require('./cli/deploy-policies')(icli), require('./cli/deploy-roles')(icli) ]) .then(() => { return Promise.resolve([]); }); }
[ "function", "registerCommands", "(", "icli", ")", "{", "return", "Promise", ".", "all", "(", "[", "require", "(", "'./cli/create-policy'", ")", "(", "icli", ")", ",", "require", "(", "'./cli/create-role'", ")", "(", "icli", ")", ",", "require", "(", "'./cli/deploy-policies'", ")", "(", "icli", ")", ",", "require", "(", "'./cli/deploy-roles'", ")", "(", "icli", ")", "]", ")", ".", "then", "(", "(", ")", "=>", "{", "return", "Promise", ".", "resolve", "(", "[", "]", ")", ";", "}", ")", ";", "}" ]
Hooks that add new commands to the Myrmex CLI @returns {Promise}
[ "Hooks", "that", "add", "new", "commands", "to", "the", "Myrmex", "CLI" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/iam/src/index.js#L174-L184
36,985
helion3/lodash-addons
src/hasInOfType.js
hasInOfType
function hasInOfType(value, path, validator) { return _.hasIn(value, path) ? validator(_.get(value, path)) : false; }
javascript
function hasInOfType(value, path, validator) { return _.hasIn(value, path) ? validator(_.get(value, path)) : false; }
[ "function", "hasInOfType", "(", "value", ",", "path", ",", "validator", ")", "{", "return", "_", ".", "hasIn", "(", "value", ",", "path", ")", "?", "validator", "(", "_", ".", "get", "(", "value", ",", "path", ")", ")", ":", "false", ";", "}" ]
If _.hasIn returns true, run a validator on value. @static @memberOf _ @category Object @param {mixed} value Collection for _.hasIn @param {string|number} path Path. @param {function} validator Function to validate value. @return {boolean} Whether collection has the path and it passes validation
[ "If", "_", ".", "hasIn", "returns", "true", "run", "a", "validator", "on", "value", "." ]
83b5bf14258241e7ae35eef346151a332fdb6f50
https://github.com/helion3/lodash-addons/blob/83b5bf14258241e7ae35eef346151a332fdb6f50/src/hasInOfType.js#L14-L16
36,986
stanford-oval/thingpedia-api
lib/helpers/oauth2.js
rot13
function rot13(x) { return Array.prototype.map.call(x, (ch) => { var code = ch.charCodeAt(0); if (code >= 0x41 && code <= 0x5a) code = (((code - 0x41) + 13) % 26) + 0x41; else if (code >= 0x61 && code <= 0x7a) code = (((code - 0x61) + 13) % 26) + 0x61; return String.fromCharCode(code); }).join(''); }
javascript
function rot13(x) { return Array.prototype.map.call(x, (ch) => { var code = ch.charCodeAt(0); if (code >= 0x41 && code <= 0x5a) code = (((code - 0x41) + 13) % 26) + 0x41; else if (code >= 0x61 && code <= 0x7a) code = (((code - 0x61) + 13) % 26) + 0x61; return String.fromCharCode(code); }).join(''); }
[ "function", "rot13", "(", "x", ")", "{", "return", "Array", ".", "prototype", ".", "map", ".", "call", "(", "x", ",", "(", "ch", ")", "=>", "{", "var", "code", "=", "ch", ".", "charCodeAt", "(", "0", ")", ";", "if", "(", "code", ">=", "0x41", "&&", "code", "<=", "0x5a", ")", "code", "=", "(", "(", "(", "code", "-", "0x41", ")", "+", "13", ")", "%", "26", ")", "+", "0x41", ";", "else", "if", "(", "code", ">=", "0x61", "&&", "code", "<=", "0x7a", ")", "code", "=", "(", "(", "(", "code", "-", "0x61", ")", "+", "13", ")", "%", "26", ")", "+", "0x61", ";", "return", "String", ".", "fromCharCode", "(", "code", ")", ";", "}", ")", ".", "join", "(", "''", ")", ";", "}" ]
encryption ;)
[ "encryption", ";", ")" ]
a5e795ec5384b0ebce462793014643dd1c7dac36
https://github.com/stanford-oval/thingpedia-api/blob/a5e795ec5384b0ebce462793014643dd1c7dac36/lib/helpers/oauth2.js#L15-L25
36,987
nodetiles/nodetiles-core
lib/Map.js
function(options) { options = options || {}; this.datasources = []; this.styles = []; this.projection = DEFAULT_PROJECTION; this.assetsPath = "."; if (options.projection){ this.projection = projector.util.cleanProjString(options.projection); console.log(this.projection); } this.boundsBuffer = ("boundsBuffer" in options) ? options.boundsBuffer : BUFFER_RATIO; this._renderer = cartoRenderer; }
javascript
function(options) { options = options || {}; this.datasources = []; this.styles = []; this.projection = DEFAULT_PROJECTION; this.assetsPath = "."; if (options.projection){ this.projection = projector.util.cleanProjString(options.projection); console.log(this.projection); } this.boundsBuffer = ("boundsBuffer" in options) ? options.boundsBuffer : BUFFER_RATIO; this._renderer = cartoRenderer; }
[ "function", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "datasources", "=", "[", "]", ";", "this", ".", "styles", "=", "[", "]", ";", "this", ".", "projection", "=", "DEFAULT_PROJECTION", ";", "this", ".", "assetsPath", "=", "\".\"", ";", "if", "(", "options", ".", "projection", ")", "{", "this", ".", "projection", "=", "projector", ".", "util", ".", "cleanProjString", "(", "options", ".", "projection", ")", ";", "console", ".", "log", "(", "this", ".", "projection", ")", ";", "}", "this", ".", "boundsBuffer", "=", "(", "\"boundsBuffer\"", "in", "options", ")", "?", "options", ".", "boundsBuffer", ":", "BUFFER_RATIO", ";", "this", ".", "_renderer", "=", "cartoRenderer", ";", "}" ]
"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs";
[ "+", "proj", "=", "merc", "+", "a", "=", "6378137", "+", "b", "=", "6378137", "+", "lat_ts", "=", "0", ".", "0", "+", "lon_0", "=", "0", ".", "0", "+", "x_0", "=", "0", ".", "0", "+", "y_0", "=", "0", "+", "k", "=", "1", ".", "0", "+", "units", "=", "m", "+", "nadgrids", "=" ]
117853de6935081f7ebefb19c766ab6c1bded244
https://github.com/nodetiles/nodetiles-core/blob/117853de6935081f7ebefb19c766ab6c1bded244/lib/Map.js#L20-L37
36,988
nodetiles/nodetiles-core
lib/Map.js
function() { var projection = this.projection; this.datasources.forEach(function(datasource) { datasource.load && datasource.load(function(error) { datasource.project && datasource.project(projection); }); }); }
javascript
function() { var projection = this.projection; this.datasources.forEach(function(datasource) { datasource.load && datasource.load(function(error) { datasource.project && datasource.project(projection); }); }); }
[ "function", "(", ")", "{", "var", "projection", "=", "this", ".", "projection", ";", "this", ".", "datasources", ".", "forEach", "(", "function", "(", "datasource", ")", "{", "datasource", ".", "load", "&&", "datasource", ".", "load", "(", "function", "(", "error", ")", "{", "datasource", ".", "project", "&&", "datasource", ".", "project", "(", "projection", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Triggers all the map's datasources to prepare themselves. Usually this connecting to a database, loading and processing a file, etc. Calling this method is completely optional, but allows you to speed up rendering of the first tile.
[ "Triggers", "all", "the", "map", "s", "datasources", "to", "prepare", "themselves", ".", "Usually", "this", "connecting", "to", "a", "database", "loading", "and", "processing", "a", "file", "etc", ".", "Calling", "this", "method", "is", "completely", "optional", "but", "allows", "you", "to", "speed", "up", "rendering", "of", "the", "first", "tile", "." ]
117853de6935081f7ebefb19c766ab6c1bded244
https://github.com/nodetiles/nodetiles-core/blob/117853de6935081f7ebefb19c766ab6c1bded244/lib/Map.js#L196-L204
36,989
helion3/lodash-addons
src/differenceKeys.js
differenceKeys
function differenceKeys(first, second) { return filterKeys(first, function(val, key) { return val !== second[key]; }); }
javascript
function differenceKeys(first, second) { return filterKeys(first, function(val, key) { return val !== second[key]; }); }
[ "function", "differenceKeys", "(", "first", ",", "second", ")", "{", "return", "filterKeys", "(", "first", ",", "function", "(", "val", ",", "key", ")", "{", "return", "val", "!==", "second", "[", "key", "]", ";", "}", ")", ";", "}" ]
Gets indices for which elements differ between two arrays. @static @memberOf _ @category Collection @param {array} first First array @param {array} second Second array @return {array} Array of indices of differing elements @example _.differenceKeys([false, true], [false, false]); // => [1]
[ "Gets", "indices", "for", "which", "elements", "differ", "between", "two", "arrays", "." ]
83b5bf14258241e7ae35eef346151a332fdb6f50
https://github.com/helion3/lodash-addons/blob/83b5bf14258241e7ae35eef346151a332fdb6f50/src/differenceKeys.js#L17-L21
36,990
helion3/lodash-addons
src/slugify.js
slugify
function slugify(string) { return _.deburr(string).trim().toLowerCase().replace(/ /g, '-').replace(/([^a-zA-Z0-9\._-]+)/, ''); }
javascript
function slugify(string) { return _.deburr(string).trim().toLowerCase().replace(/ /g, '-').replace(/([^a-zA-Z0-9\._-]+)/, ''); }
[ "function", "slugify", "(", "string", ")", "{", "return", "_", ".", "deburr", "(", "string", ")", ".", "trim", "(", ")", ".", "toLowerCase", "(", ")", ".", "replace", "(", "/", " ", "/", "g", ",", "'-'", ")", ".", "replace", "(", "/", "([^a-zA-Z0-9\\._-]+)", "/", ",", "''", ")", ";", "}" ]
Generates a url-safe "slug" form of a string. @static @memberOf _ @category String @param {string} string String value. @return {string} URL-safe form of a string. @example _.slugify('A Test'); // => a-test
[ "Generates", "a", "url", "-", "safe", "slug", "form", "of", "a", "string", "." ]
83b5bf14258241e7ae35eef346151a332fdb6f50
https://github.com/helion3/lodash-addons/blob/83b5bf14258241e7ae35eef346151a332fdb6f50/src/slugify.js#L16-L18
36,991
helion3/lodash-addons
src/objectWith.js
objectWith
function objectWith() { const args = _.reverse(arguments); const [value, path] = _.take(args, 2); const object = _.nth(args, 2) || {}; return _.set(object, path, value); }
javascript
function objectWith() { const args = _.reverse(arguments); const [value, path] = _.take(args, 2); const object = _.nth(args, 2) || {}; return _.set(object, path, value); }
[ "function", "objectWith", "(", ")", "{", "const", "args", "=", "_", ".", "reverse", "(", "arguments", ")", ";", "const", "[", "value", ",", "path", "]", "=", "_", ".", "take", "(", "args", ",", "2", ")", ";", "const", "object", "=", "_", ".", "nth", "(", "args", ",", "2", ")", "||", "{", "}", ";", "return", "_", ".", "set", "(", "object", ",", "path", ",", "value", ")", ";", "}" ]
Shorthand object creation when sole property is a variable, or a path. @static @memberOf _ @category Object @param {[object]} object Existing object (optional) @param {string|number} path Property @param {mixed} value Value @return {object} Resulting object @example // To create a new object: _.objectWith('key', 'value'); // => { key: 'value' } _.objectWith('a.deep.path', 'value'); // => { a: { deep: { path: 'value' } } } // Using existing: _.objectWith({ a: 1 }, 'b', 2); // => { a: 1, b: 2 }
[ "Shorthand", "object", "creation", "when", "sole", "property", "is", "a", "variable", "or", "a", "path", "." ]
83b5bf14258241e7ae35eef346151a332fdb6f50
https://github.com/helion3/lodash-addons/blob/83b5bf14258241e7ae35eef346151a332fdb6f50/src/objectWith.js#L33-L39
36,992
myrmex-org/myrmex
packages/api-gateway/src/cli/create-api.js
executeCommand
function executeCommand(parameters) { // If a name has been provided, we create the project directory const specFilePath = path.join(process.cwd(), plugin.config.apisPath, parameters.apiIdentifier); return mkdirpAsync(specFilePath) .then(() => { const spec = { swagger: '2.0', info: { title: parameters.title, description: parameters.desc }, schemes: ['https'], host: 'API_ID.execute-api.REGION.amazonaws.com', consume: parameters.consume, produce: parameters.produce, paths: {}, definitions: {} }; return fs.writeFileAsync(specFilePath + path.sep + 'spec.json', JSON.stringify(spec, null, 2)); }) .then(() => { const msg = '\n The API "' + icli.format.info(parameters.apiIdentifier) + '" has been created\n\n' + ' Its Swagger specification is available in ' + icli.format.info(specFilePath + path.sep + 'spec.json') + '\n' + ' You can inspect it using the command ' + icli.format.cmd('myrmex inspect-api ' + parameters.apiIdentifier) + '\n'; icli.print(msg); }); }
javascript
function executeCommand(parameters) { // If a name has been provided, we create the project directory const specFilePath = path.join(process.cwd(), plugin.config.apisPath, parameters.apiIdentifier); return mkdirpAsync(specFilePath) .then(() => { const spec = { swagger: '2.0', info: { title: parameters.title, description: parameters.desc }, schemes: ['https'], host: 'API_ID.execute-api.REGION.amazonaws.com', consume: parameters.consume, produce: parameters.produce, paths: {}, definitions: {} }; return fs.writeFileAsync(specFilePath + path.sep + 'spec.json', JSON.stringify(spec, null, 2)); }) .then(() => { const msg = '\n The API "' + icli.format.info(parameters.apiIdentifier) + '" has been created\n\n' + ' Its Swagger specification is available in ' + icli.format.info(specFilePath + path.sep + 'spec.json') + '\n' + ' You can inspect it using the command ' + icli.format.cmd('myrmex inspect-api ' + parameters.apiIdentifier) + '\n'; icli.print(msg); }); }
[ "function", "executeCommand", "(", "parameters", ")", "{", "// If a name has been provided, we create the project directory", "const", "specFilePath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "plugin", ".", "config", ".", "apisPath", ",", "parameters", ".", "apiIdentifier", ")", ";", "return", "mkdirpAsync", "(", "specFilePath", ")", ".", "then", "(", "(", ")", "=>", "{", "const", "spec", "=", "{", "swagger", ":", "'2.0'", ",", "info", ":", "{", "title", ":", "parameters", ".", "title", ",", "description", ":", "parameters", ".", "desc", "}", ",", "schemes", ":", "[", "'https'", "]", ",", "host", ":", "'API_ID.execute-api.REGION.amazonaws.com'", ",", "consume", ":", "parameters", ".", "consume", ",", "produce", ":", "parameters", ".", "produce", ",", "paths", ":", "{", "}", ",", "definitions", ":", "{", "}", "}", ";", "return", "fs", ".", "writeFileAsync", "(", "specFilePath", "+", "path", ".", "sep", "+", "'spec.json'", ",", "JSON", ".", "stringify", "(", "spec", ",", "null", ",", "2", ")", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "const", "msg", "=", "'\\n The API \"'", "+", "icli", ".", "format", ".", "info", "(", "parameters", ".", "apiIdentifier", ")", "+", "'\" has been created\\n\\n'", "+", "' Its Swagger specification is available in '", "+", "icli", ".", "format", ".", "info", "(", "specFilePath", "+", "path", ".", "sep", "+", "'spec.json'", ")", "+", "'\\n'", "+", "' You can inspect it using the command '", "+", "icli", ".", "format", ".", "cmd", "(", "'myrmex inspect-api '", "+", "parameters", ".", "apiIdentifier", ")", "+", "'\\n'", ";", "icli", ".", "print", "(", "msg", ")", ";", "}", ")", ";", "}" ]
Create the new api @param {Object} parameters - the parameters provided in the command and in the prompt @returns {Promise<null>} - The execution stops here
[ "Create", "the", "new", "api" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/api-gateway/src/cli/create-api.js#L61-L87
36,993
Joe3Ray/vue-to-js
lib/index.js
generateCode
function generateCode(filepath) { var mode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'amd'; // support 4 types of output as follows: // amd/commonjs/global/umd var choice = { amd: { prefix: 'define([\'module\', \'exports\'], function (module, exports) {', suffix: '});' }, commonjs: { prefix: '', suffix: '' }, global: { prefix: '(function (module, exports) {', suffix: '})(this, this.exports = this.exports || {});' }, umd: { prefix: '\n (function (global, factory) {\n typeof exports === \'object\' && typeof module !== \'undefined\' ? factory(module, exports) :\n typeof define === \'function\' && define.amd ? define([\'module\', \'exports\'], factory) :\n (factory(global, global.exports = global.exports || {}));\n }(this, (function (module, exports) {\n ', suffix: '})));' } }; var _ref = choice[mode] || choice.amd, prefix = _ref.prefix, suffix = _ref.suffix; //const content = readFileSync(filepath, 'utf8'); //const result = parseComponent(content); var result = getBlocks(filepath); var templateCode = result.template.code; var styleCode = result.styles.map(function (style) { return (0, _style2.default)(style.code); }).join('\n'); var scriptCode = result.script.code; var code = '\n ' + prefix + '\n /* append style */\n ' + styleCode + '\n\n /* get render function */\n var _module1 = {\n exports: {}\n };\n (function (module, exports) {\n ' + (0, _template2.default)(templateCode) + '\n })(_module1, _module1.exports);\n\n /* get script output data */\n var _module2 = {\n exports: {}\n };\n (function (module, exports) {\n ' + (0, _script2.default)(scriptCode) + '\n })(_module2, _module2.exports);\n\n var obj = _module2.exports.default || _module2.exports;\n obj.render = _module1.exports.render;\n obj.staticRenderFns = _module1.exports.staticRenderFns;\n\n module.exports = obj;\n ' + suffix + '\n '; return (0, _jsBeautify.js_beautify)(code); }
javascript
function generateCode(filepath) { var mode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'amd'; // support 4 types of output as follows: // amd/commonjs/global/umd var choice = { amd: { prefix: 'define([\'module\', \'exports\'], function (module, exports) {', suffix: '});' }, commonjs: { prefix: '', suffix: '' }, global: { prefix: '(function (module, exports) {', suffix: '})(this, this.exports = this.exports || {});' }, umd: { prefix: '\n (function (global, factory) {\n typeof exports === \'object\' && typeof module !== \'undefined\' ? factory(module, exports) :\n typeof define === \'function\' && define.amd ? define([\'module\', \'exports\'], factory) :\n (factory(global, global.exports = global.exports || {}));\n }(this, (function (module, exports) {\n ', suffix: '})));' } }; var _ref = choice[mode] || choice.amd, prefix = _ref.prefix, suffix = _ref.suffix; //const content = readFileSync(filepath, 'utf8'); //const result = parseComponent(content); var result = getBlocks(filepath); var templateCode = result.template.code; var styleCode = result.styles.map(function (style) { return (0, _style2.default)(style.code); }).join('\n'); var scriptCode = result.script.code; var code = '\n ' + prefix + '\n /* append style */\n ' + styleCode + '\n\n /* get render function */\n var _module1 = {\n exports: {}\n };\n (function (module, exports) {\n ' + (0, _template2.default)(templateCode) + '\n })(_module1, _module1.exports);\n\n /* get script output data */\n var _module2 = {\n exports: {}\n };\n (function (module, exports) {\n ' + (0, _script2.default)(scriptCode) + '\n })(_module2, _module2.exports);\n\n var obj = _module2.exports.default || _module2.exports;\n obj.render = _module1.exports.render;\n obj.staticRenderFns = _module1.exports.staticRenderFns;\n\n module.exports = obj;\n ' + suffix + '\n '; return (0, _jsBeautify.js_beautify)(code); }
[ "function", "generateCode", "(", "filepath", ")", "{", "var", "mode", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "'amd'", ";", "// support 4 types of output as follows:", "// amd/commonjs/global/umd", "var", "choice", "=", "{", "amd", ":", "{", "prefix", ":", "'define([\\'module\\', \\'exports\\'], function (module, exports) {'", ",", "suffix", ":", "'});'", "}", ",", "commonjs", ":", "{", "prefix", ":", "''", ",", "suffix", ":", "''", "}", ",", "global", ":", "{", "prefix", ":", "'(function (module, exports) {'", ",", "suffix", ":", "'})(this, this.exports = this.exports || {});'", "}", ",", "umd", ":", "{", "prefix", ":", "'\\n (function (global, factory) {\\n typeof exports === \\'object\\' && typeof module !== \\'undefined\\' ? factory(module, exports) :\\n typeof define === \\'function\\' && define.amd ? define([\\'module\\', \\'exports\\'], factory) :\\n (factory(global, global.exports = global.exports || {}));\\n }(this, (function (module, exports) {\\n '", ",", "suffix", ":", "'})));'", "}", "}", ";", "var", "_ref", "=", "choice", "[", "mode", "]", "||", "choice", ".", "amd", ",", "prefix", "=", "_ref", ".", "prefix", ",", "suffix", "=", "_ref", ".", "suffix", ";", "//const content = readFileSync(filepath, 'utf8');", "//const result = parseComponent(content);", "var", "result", "=", "getBlocks", "(", "filepath", ")", ";", "var", "templateCode", "=", "result", ".", "template", ".", "code", ";", "var", "styleCode", "=", "result", ".", "styles", ".", "map", "(", "function", "(", "style", ")", "{", "return", "(", "0", ",", "_style2", ".", "default", ")", "(", "style", ".", "code", ")", ";", "}", ")", ".", "join", "(", "'\\n'", ")", ";", "var", "scriptCode", "=", "result", ".", "script", ".", "code", ";", "var", "code", "=", "'\\n '", "+", "prefix", "+", "'\\n /* append style */\\n '", "+", "styleCode", "+", "'\\n\\n /* get render function */\\n var _module1 = {\\n exports: {}\\n };\\n (function (module, exports) {\\n '", "+", "(", "0", ",", "_template2", ".", "default", ")", "(", "templateCode", ")", "+", "'\\n })(_module1, _module1.exports);\\n\\n /* get script output data */\\n var _module2 = {\\n exports: {}\\n };\\n (function (module, exports) {\\n '", "+", "(", "0", ",", "_script2", ".", "default", ")", "(", "scriptCode", ")", "+", "'\\n })(_module2, _module2.exports);\\n\\n var obj = _module2.exports.default || _module2.exports;\\n obj.render = _module1.exports.render;\\n obj.staticRenderFns = _module1.exports.staticRenderFns;\\n\\n module.exports = obj;\\n '", "+", "suffix", "+", "'\\n '", ";", "return", "(", "0", ",", "_jsBeautify", ".", "js_beautify", ")", "(", "code", ")", ";", "}" ]
compile vue file to js code @param {string} filepath the path of .vue file @param {string} mode the output mode, it should be one of amd/commonjs/global/umd @return {string} js code with appointed mode
[ "compile", "vue", "file", "to", "js", "code" ]
c98a09ed5c00998efab45e6c65c79bf480d1a67a
https://github.com/Joe3Ray/vue-to-js/blob/c98a09ed5c00998efab45e6c65c79bf480d1a67a/lib/index.js#L85-L128
36,994
Joe3Ray/vue-to-js
lib/index.js
compile
function compile(_ref2) { var resource = _ref2.resource, dest = _ref2.dest, mode = _ref2.mode; dest = dest || 'dest'; resource = resource || '*.vue'; mode = ['amd', 'commonjs', 'umd', 'global'].indexOf(mode) > -1 ? mode : 'amd'; if ((0, _fs.existsSync)(dest)) { if (!(0, _fs.statSync)(dest).isDirectory()) { throw new Error('the destination path is already exist and it is not a directory'); } } else { (0, _fs.mkdirSync)(dest); } var files = _glob2.default.sync(resource); files.forEach(function (file) { var name = (0, _path.parse)(file).name; try { var code = generateCode(file, mode); var outputPath = (0, _path.format)({ dir: dest, name: name, ext: '.js' }); (0, _fs.writeFileSync)(outputPath, code); } catch (e) { throw e; } }); }
javascript
function compile(_ref2) { var resource = _ref2.resource, dest = _ref2.dest, mode = _ref2.mode; dest = dest || 'dest'; resource = resource || '*.vue'; mode = ['amd', 'commonjs', 'umd', 'global'].indexOf(mode) > -1 ? mode : 'amd'; if ((0, _fs.existsSync)(dest)) { if (!(0, _fs.statSync)(dest).isDirectory()) { throw new Error('the destination path is already exist and it is not a directory'); } } else { (0, _fs.mkdirSync)(dest); } var files = _glob2.default.sync(resource); files.forEach(function (file) { var name = (0, _path.parse)(file).name; try { var code = generateCode(file, mode); var outputPath = (0, _path.format)({ dir: dest, name: name, ext: '.js' }); (0, _fs.writeFileSync)(outputPath, code); } catch (e) { throw e; } }); }
[ "function", "compile", "(", "_ref2", ")", "{", "var", "resource", "=", "_ref2", ".", "resource", ",", "dest", "=", "_ref2", ".", "dest", ",", "mode", "=", "_ref2", ".", "mode", ";", "dest", "=", "dest", "||", "'dest'", ";", "resource", "=", "resource", "||", "'*.vue'", ";", "mode", "=", "[", "'amd'", ",", "'commonjs'", ",", "'umd'", ",", "'global'", "]", ".", "indexOf", "(", "mode", ")", ">", "-", "1", "?", "mode", ":", "'amd'", ";", "if", "(", "(", "0", ",", "_fs", ".", "existsSync", ")", "(", "dest", ")", ")", "{", "if", "(", "!", "(", "0", ",", "_fs", ".", "statSync", ")", "(", "dest", ")", ".", "isDirectory", "(", ")", ")", "{", "throw", "new", "Error", "(", "'the destination path is already exist and it is not a directory'", ")", ";", "}", "}", "else", "{", "(", "0", ",", "_fs", ".", "mkdirSync", ")", "(", "dest", ")", ";", "}", "var", "files", "=", "_glob2", ".", "default", ".", "sync", "(", "resource", ")", ";", "files", ".", "forEach", "(", "function", "(", "file", ")", "{", "var", "name", "=", "(", "0", ",", "_path", ".", "parse", ")", "(", "file", ")", ".", "name", ";", "try", "{", "var", "code", "=", "generateCode", "(", "file", ",", "mode", ")", ";", "var", "outputPath", "=", "(", "0", ",", "_path", ".", "format", ")", "(", "{", "dir", ":", "dest", ",", "name", ":", "name", ",", "ext", ":", "'.js'", "}", ")", ";", "(", "0", ",", "_fs", ".", "writeFileSync", ")", "(", "outputPath", ",", "code", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "e", ";", "}", "}", ")", ";", "}" ]
compile .vue to .js with appointed destination directory @param {Object} options compile config info @param {string} options.resource glob pattern file path @param {string} options.dest output destination directory @param {string} options.mode one of amd/commonjs/umd/global
[ "compile", ".", "vue", "to", ".", "js", "with", "appointed", "destination", "directory" ]
c98a09ed5c00998efab45e6c65c79bf480d1a67a
https://github.com/Joe3Ray/vue-to-js/blob/c98a09ed5c00998efab45e6c65c79bf480d1a67a/lib/index.js#L138-L169
36,995
XadillaX/ez-upyun
lib/upyun.js
function(callback) { fs.exists(file, function(exists) { if(!exists) { rawData = file; if(typeof rawData === "string") rawData = new Buffer(file); return callback(); } fs.readFile(file, function(err, data) { if(err) return callback(err); rawData = data; return callback(); }); }); }
javascript
function(callback) { fs.exists(file, function(exists) { if(!exists) { rawData = file; if(typeof rawData === "string") rawData = new Buffer(file); return callback(); } fs.readFile(file, function(err, data) { if(err) return callback(err); rawData = data; return callback(); }); }); }
[ "function", "(", "callback", ")", "{", "fs", ".", "exists", "(", "file", ",", "function", "(", "exists", ")", "{", "if", "(", "!", "exists", ")", "{", "rawData", "=", "file", ";", "if", "(", "typeof", "rawData", "===", "\"string\"", ")", "rawData", "=", "new", "Buffer", "(", "file", ")", ";", "return", "callback", "(", ")", ";", "}", "fs", ".", "readFile", "(", "file", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "rawData", "=", "data", ";", "return", "callback", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
get the raw data @param callback
[ "get", "the", "raw", "data" ]
f6111bc855050f77d7d1abfb0dc651712774f984
https://github.com/XadillaX/ez-upyun/blob/f6111bc855050f77d7d1abfb0dc651712774f984/lib/upyun.js#L402-L416
36,996
XadillaX/ez-upyun
lib/upyun.js
function(callback) { spidex.put(self.baseUri + "/" + uploadFilename, { data: rawData, header: header, charset: "utf8" }, function(html, status, respHeader) { if(200 !== status && 201 !== status) { return callback(new Error(html.replace("</h1>", "</h1> ").stripTags())); } var result = {}; if(respHeader["x-upyun-width"] !== undefined) result.width = parseInt(respHeader["x-upyun-width"]); if(respHeader["x-upyun-height"] !== undefined) result.height = parseInt(respHeader["x-upyun-height"]); if(respHeader["x-upyun-frames"] !== undefined) result.frames = parseInt(respHeader["x-upyun-frames"]); if(respHeader["x-upyun-file-type"] !== undefined) result.type = respHeader["x-upyun-file-type"]; callback(undefined, result); }).on("error", callback); }
javascript
function(callback) { spidex.put(self.baseUri + "/" + uploadFilename, { data: rawData, header: header, charset: "utf8" }, function(html, status, respHeader) { if(200 !== status && 201 !== status) { return callback(new Error(html.replace("</h1>", "</h1> ").stripTags())); } var result = {}; if(respHeader["x-upyun-width"] !== undefined) result.width = parseInt(respHeader["x-upyun-width"]); if(respHeader["x-upyun-height"] !== undefined) result.height = parseInt(respHeader["x-upyun-height"]); if(respHeader["x-upyun-frames"] !== undefined) result.frames = parseInt(respHeader["x-upyun-frames"]); if(respHeader["x-upyun-file-type"] !== undefined) result.type = respHeader["x-upyun-file-type"]; callback(undefined, result); }).on("error", callback); }
[ "function", "(", "callback", ")", "{", "spidex", ".", "put", "(", "self", ".", "baseUri", "+", "\"/\"", "+", "uploadFilename", ",", "{", "data", ":", "rawData", ",", "header", ":", "header", ",", "charset", ":", "\"utf8\"", "}", ",", "function", "(", "html", ",", "status", ",", "respHeader", ")", "{", "if", "(", "200", "!==", "status", "&&", "201", "!==", "status", ")", "{", "return", "callback", "(", "new", "Error", "(", "html", ".", "replace", "(", "\"</h1>\"", ",", "\"</h1> \"", ")", ".", "stripTags", "(", ")", ")", ")", ";", "}", "var", "result", "=", "{", "}", ";", "if", "(", "respHeader", "[", "\"x-upyun-width\"", "]", "!==", "undefined", ")", "result", ".", "width", "=", "parseInt", "(", "respHeader", "[", "\"x-upyun-width\"", "]", ")", ";", "if", "(", "respHeader", "[", "\"x-upyun-height\"", "]", "!==", "undefined", ")", "result", ".", "height", "=", "parseInt", "(", "respHeader", "[", "\"x-upyun-height\"", "]", ")", ";", "if", "(", "respHeader", "[", "\"x-upyun-frames\"", "]", "!==", "undefined", ")", "result", ".", "frames", "=", "parseInt", "(", "respHeader", "[", "\"x-upyun-frames\"", "]", ")", ";", "if", "(", "respHeader", "[", "\"x-upyun-file-type\"", "]", "!==", "undefined", ")", "result", ".", "type", "=", "respHeader", "[", "\"x-upyun-file-type\"", "]", ";", "callback", "(", "undefined", ",", "result", ")", ";", "}", ")", ".", "on", "(", "\"error\"", ",", "callback", ")", ";", "}" ]
use upyun api to upload the file and get result @param callback
[ "use", "upyun", "api", "to", "upload", "the", "file", "and", "get", "result" ]
f6111bc855050f77d7d1abfb0dc651712774f984
https://github.com/XadillaX/ez-upyun/blob/f6111bc855050f77d7d1abfb0dc651712774f984/lib/upyun.js#L452-L470
36,997
myrmex-org/myrmex
packages/api-gateway/src/cli/create-endpoint.js
executeCommand
function executeCommand(parameters) { if (!parameters.role && parameters.roleManually) { parameters.role = parameters.roleManually; } if (parameters.resourcePath.charAt(0) !== '/') { parameters.resourcePath = '/' + parameters.resourcePath; } // We calculate the path where we will save the specification and create the directory // Destructuring parameters only available in node 6 :( // specFilePath = path.join(process.cwd(), 'endpoints', ...answers.resourcePath.split('/')); const pathParts = parameters.resourcePath.split('/'); pathParts.push(parameters.httpMethod); pathParts.unshift(path.join(process.cwd(), plugin.config.endpointsPath)); const specFilePath = path.join.apply(null, pathParts); return mkdirpAsync(specFilePath) .then(() => { // We create the endpoint Swagger/OpenAPI specification const spec = { 'x-myrmex': { 'apis': parameters.apis }, summary: parameters.summary, consume: parameters.consume, produce: parameters.produce, responses: { '200': {} }, 'x-amazon-apigateway-auth': { type: parameters.auth }, 'x-amazon-apigateway-integration': { credentials: parameters.role, responses: { default: { statusCode: 200 } } } }; switch (parameters.integration) { case 'lambda-proxy': spec['x-amazon-apigateway-integration'].type = 'aws_proxy'; spec['x-amazon-apigateway-integration'].contentHandling = 'CONVERT_TO_TEXT'; spec['x-amazon-apigateway-integration'].passthroughBehavior = 'when_no_match'; spec['x-amazon-apigateway-integration'].httpMethod = 'POST'; break; case 'mock': spec['x-amazon-apigateway-integration'].requestTemplates = { 'application/json': '{"statusCode": 200}' }; spec['x-amazon-apigateway-integration'].type = 'mock'; spec['x-amazon-apigateway-integration'].passthroughBehavior = 'when_no_match'; break; } config.specModifiers.forEach(fn => { fn(spec, parameters); }); // We save the specification in a json file return fs.writeFileAsync(path.join(specFilePath, 'spec.json'), JSON.stringify(spec, null, 2)); }) .then(() => { const msg = '\n The endpoint ' + icli.format.info(parameters.httpMethod + ' ' + parameters.resourcePath) + ' has been created\n\n' + ' Its OpenAPI specification is available in ' + icli.format.info(specFilePath + path.sep + 'spec.json') + '\n' + ' You can inspect it using the command ' + icli.format.cmd('myrmex inspect-endpoint ' + parameters.resourcePath + ' ' + parameters.httpMethod) + '\n'; icli.print(msg); }); }
javascript
function executeCommand(parameters) { if (!parameters.role && parameters.roleManually) { parameters.role = parameters.roleManually; } if (parameters.resourcePath.charAt(0) !== '/') { parameters.resourcePath = '/' + parameters.resourcePath; } // We calculate the path where we will save the specification and create the directory // Destructuring parameters only available in node 6 :( // specFilePath = path.join(process.cwd(), 'endpoints', ...answers.resourcePath.split('/')); const pathParts = parameters.resourcePath.split('/'); pathParts.push(parameters.httpMethod); pathParts.unshift(path.join(process.cwd(), plugin.config.endpointsPath)); const specFilePath = path.join.apply(null, pathParts); return mkdirpAsync(specFilePath) .then(() => { // We create the endpoint Swagger/OpenAPI specification const spec = { 'x-myrmex': { 'apis': parameters.apis }, summary: parameters.summary, consume: parameters.consume, produce: parameters.produce, responses: { '200': {} }, 'x-amazon-apigateway-auth': { type: parameters.auth }, 'x-amazon-apigateway-integration': { credentials: parameters.role, responses: { default: { statusCode: 200 } } } }; switch (parameters.integration) { case 'lambda-proxy': spec['x-amazon-apigateway-integration'].type = 'aws_proxy'; spec['x-amazon-apigateway-integration'].contentHandling = 'CONVERT_TO_TEXT'; spec['x-amazon-apigateway-integration'].passthroughBehavior = 'when_no_match'; spec['x-amazon-apigateway-integration'].httpMethod = 'POST'; break; case 'mock': spec['x-amazon-apigateway-integration'].requestTemplates = { 'application/json': '{"statusCode": 200}' }; spec['x-amazon-apigateway-integration'].type = 'mock'; spec['x-amazon-apigateway-integration'].passthroughBehavior = 'when_no_match'; break; } config.specModifiers.forEach(fn => { fn(spec, parameters); }); // We save the specification in a json file return fs.writeFileAsync(path.join(specFilePath, 'spec.json'), JSON.stringify(spec, null, 2)); }) .then(() => { const msg = '\n The endpoint ' + icli.format.info(parameters.httpMethod + ' ' + parameters.resourcePath) + ' has been created\n\n' + ' Its OpenAPI specification is available in ' + icli.format.info(specFilePath + path.sep + 'spec.json') + '\n' + ' You can inspect it using the command ' + icli.format.cmd('myrmex inspect-endpoint ' + parameters.resourcePath + ' ' + parameters.httpMethod) + '\n'; icli.print(msg); }); }
[ "function", "executeCommand", "(", "parameters", ")", "{", "if", "(", "!", "parameters", ".", "role", "&&", "parameters", ".", "roleManually", ")", "{", "parameters", ".", "role", "=", "parameters", ".", "roleManually", ";", "}", "if", "(", "parameters", ".", "resourcePath", ".", "charAt", "(", "0", ")", "!==", "'/'", ")", "{", "parameters", ".", "resourcePath", "=", "'/'", "+", "parameters", ".", "resourcePath", ";", "}", "// We calculate the path where we will save the specification and create the directory", "// Destructuring parameters only available in node 6 :(", "// specFilePath = path.join(process.cwd(), 'endpoints', ...answers.resourcePath.split('/'));", "const", "pathParts", "=", "parameters", ".", "resourcePath", ".", "split", "(", "'/'", ")", ";", "pathParts", ".", "push", "(", "parameters", ".", "httpMethod", ")", ";", "pathParts", ".", "unshift", "(", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "plugin", ".", "config", ".", "endpointsPath", ")", ")", ";", "const", "specFilePath", "=", "path", ".", "join", ".", "apply", "(", "null", ",", "pathParts", ")", ";", "return", "mkdirpAsync", "(", "specFilePath", ")", ".", "then", "(", "(", ")", "=>", "{", "// We create the endpoint Swagger/OpenAPI specification", "const", "spec", "=", "{", "'x-myrmex'", ":", "{", "'apis'", ":", "parameters", ".", "apis", "}", ",", "summary", ":", "parameters", ".", "summary", ",", "consume", ":", "parameters", ".", "consume", ",", "produce", ":", "parameters", ".", "produce", ",", "responses", ":", "{", "'200'", ":", "{", "}", "}", ",", "'x-amazon-apigateway-auth'", ":", "{", "type", ":", "parameters", ".", "auth", "}", ",", "'x-amazon-apigateway-integration'", ":", "{", "credentials", ":", "parameters", ".", "role", ",", "responses", ":", "{", "default", ":", "{", "statusCode", ":", "200", "}", "}", "}", "}", ";", "switch", "(", "parameters", ".", "integration", ")", "{", "case", "'lambda-proxy'", ":", "spec", "[", "'x-amazon-apigateway-integration'", "]", ".", "type", "=", "'aws_proxy'", ";", "spec", "[", "'x-amazon-apigateway-integration'", "]", ".", "contentHandling", "=", "'CONVERT_TO_TEXT'", ";", "spec", "[", "'x-amazon-apigateway-integration'", "]", ".", "passthroughBehavior", "=", "'when_no_match'", ";", "spec", "[", "'x-amazon-apigateway-integration'", "]", ".", "httpMethod", "=", "'POST'", ";", "break", ";", "case", "'mock'", ":", "spec", "[", "'x-amazon-apigateway-integration'", "]", ".", "requestTemplates", "=", "{", "'application/json'", ":", "'{\"statusCode\": 200}'", "}", ";", "spec", "[", "'x-amazon-apigateway-integration'", "]", ".", "type", "=", "'mock'", ";", "spec", "[", "'x-amazon-apigateway-integration'", "]", ".", "passthroughBehavior", "=", "'when_no_match'", ";", "break", ";", "}", "config", ".", "specModifiers", ".", "forEach", "(", "fn", "=>", "{", "fn", "(", "spec", ",", "parameters", ")", ";", "}", ")", ";", "// We save the specification in a json file", "return", "fs", ".", "writeFileAsync", "(", "path", ".", "join", "(", "specFilePath", ",", "'spec.json'", ")", ",", "JSON", ".", "stringify", "(", "spec", ",", "null", ",", "2", ")", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "const", "msg", "=", "'\\n The endpoint '", "+", "icli", ".", "format", ".", "info", "(", "parameters", ".", "httpMethod", "+", "' '", "+", "parameters", ".", "resourcePath", ")", "+", "' has been created\\n\\n'", "+", "' Its OpenAPI specification is available in '", "+", "icli", ".", "format", ".", "info", "(", "specFilePath", "+", "path", ".", "sep", "+", "'spec.json'", ")", "+", "'\\n'", "+", "' You can inspect it using the command '", "+", "icli", ".", "format", ".", "cmd", "(", "'myrmex inspect-endpoint '", "+", "parameters", ".", "resourcePath", "+", "' '", "+", "parameters", ".", "httpMethod", ")", "+", "'\\n'", ";", "icli", ".", "print", "(", "msg", ")", ";", "}", ")", ";", "}" ]
Create the new endpoint @param {Object} parameters - the parameters provided in the command and in the prompt @returns {Promise<null>} - The execution stops here
[ "Create", "the", "new", "endpoint" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/api-gateway/src/cli/create-endpoint.js#L207-L271
36,998
myrmex-org/myrmex
packages/iam/src/cli/create-policy.js
executeCommand
function executeCommand(parameters) { const configFilePath = path.join(process.cwd(), plugin.config.policiesPath); return mkdirpAsync(configFilePath) .then(() => { // We create the configuration file of the Lambda const document = { Version: '2012-10-17', Statement: [{ Effect: 'Deny', Action: ['*'], Resource: ['*'] }] }; // We save the specification in a json file return fs.writeFileAsync(configFilePath + path.sep + parameters.identifier + '.json', JSON.stringify(document, null, 2)); }) .then(() => { const msg = '\n The IAM policy ' + icli.format.info(parameters.identifier) + ' has been created in ' + icli.format.info(configFilePath + path.sep + parameters.identifier + '.json') + '\n\n'; icli.print(msg); }); }
javascript
function executeCommand(parameters) { const configFilePath = path.join(process.cwd(), plugin.config.policiesPath); return mkdirpAsync(configFilePath) .then(() => { // We create the configuration file of the Lambda const document = { Version: '2012-10-17', Statement: [{ Effect: 'Deny', Action: ['*'], Resource: ['*'] }] }; // We save the specification in a json file return fs.writeFileAsync(configFilePath + path.sep + parameters.identifier + '.json', JSON.stringify(document, null, 2)); }) .then(() => { const msg = '\n The IAM policy ' + icli.format.info(parameters.identifier) + ' has been created in ' + icli.format.info(configFilePath + path.sep + parameters.identifier + '.json') + '\n\n'; icli.print(msg); }); }
[ "function", "executeCommand", "(", "parameters", ")", "{", "const", "configFilePath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "plugin", ".", "config", ".", "policiesPath", ")", ";", "return", "mkdirpAsync", "(", "configFilePath", ")", ".", "then", "(", "(", ")", "=>", "{", "// We create the configuration file of the Lambda", "const", "document", "=", "{", "Version", ":", "'2012-10-17'", ",", "Statement", ":", "[", "{", "Effect", ":", "'Deny'", ",", "Action", ":", "[", "'*'", "]", ",", "Resource", ":", "[", "'*'", "]", "}", "]", "}", ";", "// We save the specification in a json file", "return", "fs", ".", "writeFileAsync", "(", "configFilePath", "+", "path", ".", "sep", "+", "parameters", ".", "identifier", "+", "'.json'", ",", "JSON", ".", "stringify", "(", "document", ",", "null", ",", "2", ")", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "const", "msg", "=", "'\\n The IAM policy '", "+", "icli", ".", "format", ".", "info", "(", "parameters", ".", "identifier", ")", "+", "' has been created in '", "+", "icli", ".", "format", ".", "info", "(", "configFilePath", "+", "path", ".", "sep", "+", "parameters", ".", "identifier", "+", "'.json'", ")", "+", "'\\n\\n'", ";", "icli", ".", "print", "(", "msg", ")", ";", "}", ")", ";", "}" ]
Create the new policy @param {Object} parameters - the parameters provided in the command and in the prompt @returns {Promise<null>} - The execution stops here
[ "Create", "the", "new", "policy" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/iam/src/cli/create-policy.js#L41-L63
36,999
helion3/lodash-addons
src/transformValueMap.js
transformValueMap
function transformValueMap(collection, path, transformer) { _.each(collection, (element) => { let val = _.get(element, path); if (!_.isUndefined(val)) { _.set(element, path, transformer(val)); } }); return collection; }
javascript
function transformValueMap(collection, path, transformer) { _.each(collection, (element) => { let val = _.get(element, path); if (!_.isUndefined(val)) { _.set(element, path, transformer(val)); } }); return collection; }
[ "function", "transformValueMap", "(", "collection", ",", "path", ",", "transformer", ")", "{", "_", ".", "each", "(", "collection", ",", "(", "element", ")", "=>", "{", "let", "val", "=", "_", ".", "get", "(", "element", ",", "path", ")", ";", "if", "(", "!", "_", ".", "isUndefined", "(", "val", ")", ")", "{", "_", ".", "set", "(", "element", ",", "path", ",", "transformer", "(", "val", ")", ")", ";", "}", "}", ")", ";", "return", "collection", ";", "}" ]
Transforms a value in each element of collection if the path is not undefined. @static @memberOf _ @category Array @param {Array} collection Array of objects @param {string} path The path of the value to transform @param {function} transformer Callback which returns the transformed value @return {Array} Returns the array of results.
[ "Transforms", "a", "value", "in", "each", "element", "of", "collection", "if", "the", "path", "is", "not", "undefined", "." ]
83b5bf14258241e7ae35eef346151a332fdb6f50
https://github.com/helion3/lodash-addons/blob/83b5bf14258241e7ae35eef346151a332fdb6f50/src/transformValueMap.js#L14-L24