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
40,200
jsdoc2md/ddata
lib/ddata.js
module
function module (options) { options.hash.kind = 'module' var result = _identifiers(options)[0] return result ? options.fn(result) : 'ERROR, Cannot find module.' }
javascript
function module (options) { options.hash.kind = 'module' var result = _identifiers(options)[0] return result ? options.fn(result) : 'ERROR, Cannot find module.' }
[ "function", "module", "(", "options", ")", "{", "options", ".", "hash", ".", "kind", "=", "'module'", "var", "result", "=", "_identifiers", "(", "options", ")", "[", "0", "]", "return", "result", "?", "options", ".", "fn", "(", "result", ")", ":", "'ERROR, Cannot find module.'", "}" ]
render the supplied block for the specified module @static @category Block helper: selector
[ "render", "the", "supplied", "block", "for", "the", "specified", "module" ]
f34be998eae49f13696ba056f264fd3acab089c9
https://github.com/jsdoc2md/ddata/blob/f34be998eae49f13696ba056f264fd3acab089c9/lib/ddata.js#L167-L171
40,201
jsdoc2md/ddata
lib/ddata.js
classes
function classes (options) { options.hash.kind = 'class' return handlebars.helpers.each(_identifiers(options), options) }
javascript
function classes (options) { options.hash.kind = 'class' return handlebars.helpers.each(_identifiers(options), options) }
[ "function", "classes", "(", "options", ")", "{", "options", ".", "hash", ".", "kind", "=", "'class'", "return", "handlebars", ".", "helpers", ".", "each", "(", "_identifiers", "(", "options", ")", ",", "options", ")", "}" ]
render the block for each class @static @category Block helper: selector
[ "render", "the", "block", "for", "each", "class" ]
f34be998eae49f13696ba056f264fd3acab089c9
https://github.com/jsdoc2md/ddata/blob/f34be998eae49f13696ba056f264fd3acab089c9/lib/ddata.js#L188-L191
40,202
jsdoc2md/ddata
lib/ddata.js
misc
function misc (options) { options.hash.scope = undefined options.hash['!kind'] = /module|constructor|external/ options.hash['!isExported'] = true return handlebars.helpers.each(_identifiers(options), options) }
javascript
function misc (options) { options.hash.scope = undefined options.hash['!kind'] = /module|constructor|external/ options.hash['!isExported'] = true return handlebars.helpers.each(_identifiers(options), options) }
[ "function", "misc", "(", "options", ")", "{", "options", ".", "hash", ".", "scope", "=", "undefined", "options", ".", "hash", "[", "'!kind'", "]", "=", "/", "module|constructor|external", "/", "options", ".", "hash", "[", "'!isExported'", "]", "=", "true", "return", "handlebars", ".", "helpers", ".", "each", "(", "_identifiers", "(", "options", ")", ",", "options", ")", "}" ]
render the supplied block for each orphan with no scope set @static @category Block helper: selector
[ "render", "the", "supplied", "block", "for", "each", "orphan", "with", "no", "scope", "set" ]
f34be998eae49f13696ba056f264fd3acab089c9
https://github.com/jsdoc2md/ddata/blob/f34be998eae49f13696ba056f264fd3acab089c9/lib/ddata.js#L253-L258
40,203
dreampiggy/functional.js
Retroactive/lib/data_structures/bst.js
BST
function BST(compareFn) { this.root = null; this._size = 0; /** * @var Comparator */ this._comparator = new Comparator(compareFn); /** * Read-only property for the size of the tree */ Object.defineProperty(this, 'size', { get: function () { return this._size; }.bind(this) }); }
javascript
function BST(compareFn) { this.root = null; this._size = 0; /** * @var Comparator */ this._comparator = new Comparator(compareFn); /** * Read-only property for the size of the tree */ Object.defineProperty(this, 'size', { get: function () { return this._size; }.bind(this) }); }
[ "function", "BST", "(", "compareFn", ")", "{", "this", ".", "root", "=", "null", ";", "this", ".", "_size", "=", "0", ";", "/**\n * @var Comparator\n */", "this", ".", "_comparator", "=", "new", "Comparator", "(", "compareFn", ")", ";", "/**\n * Read-only property for the size of the tree\n */", "Object", ".", "defineProperty", "(", "this", ",", "'size'", ",", "{", "get", ":", "function", "(", ")", "{", "return", "this", ".", "_size", ";", "}", ".", "bind", "(", "this", ")", "}", ")", ";", "}" ]
Binary Search Tree
[ "Binary", "Search", "Tree" ]
ec7b7213de7965659a8a1e8fa61438e3ae564260
https://github.com/dreampiggy/functional.js/blob/ec7b7213de7965659a8a1e8fa61438e3ae564260/Retroactive/lib/data_structures/bst.js#L7-L21
40,204
bootprint/bootprint-base
handlebars/helpers.js
function (value, options) { if (!value) { return value } var html = marked(value) // We strip the surrounding <p>-tag, if if (options.hash && options.hash.stripParagraph) { var $ = cheerio('<root>' + html + '</root>') // Only strip <p>-tags and only if there is just one of them. if ($.children().length === 1 && $.children('p').length === 1) { html = $.children('p').html() } } return new Handlebars.SafeString(html) }
javascript
function (value, options) { if (!value) { return value } var html = marked(value) // We strip the surrounding <p>-tag, if if (options.hash && options.hash.stripParagraph) { var $ = cheerio('<root>' + html + '</root>') // Only strip <p>-tags and only if there is just one of them. if ($.children().length === 1 && $.children('p').length === 1) { html = $.children('p').html() } } return new Handlebars.SafeString(html) }
[ "function", "(", "value", ",", "options", ")", "{", "if", "(", "!", "value", ")", "{", "return", "value", "}", "var", "html", "=", "marked", "(", "value", ")", "// We strip the surrounding <p>-tag, if", "if", "(", "options", ".", "hash", "&&", "options", ".", "hash", ".", "stripParagraph", ")", "{", "var", "$", "=", "cheerio", "(", "'<root>'", "+", "html", "+", "'</root>'", ")", "// Only strip <p>-tags and only if there is just one of them.", "if", "(", "$", ".", "children", "(", ")", ".", "length", "===", "1", "&&", "$", ".", "children", "(", "'p'", ")", ".", "length", "===", "1", ")", "{", "html", "=", "$", ".", "children", "(", "'p'", ")", ".", "html", "(", ")", "}", "}", "return", "new", "Handlebars", ".", "SafeString", "(", "html", ")", "}" ]
Render a markdown-formatted text as HTML. @param {string} `value` the markdown-formatted text @param {boolean} `options.hash.stripParagraph` the marked-md-renderer wraps generated HTML in a <p>-tag by default. If this options is set to true, the <p>-tag is stripped. @returns {Handlebars.SafeString} a Handlebars-SafeString containing the provieded markdown, rendered as HTML.
[ "Render", "a", "markdown", "-", "formatted", "text", "as", "HTML", "." ]
fdb843317d68f04eaf513e2cdda439774a7ca134
https://github.com/bootprint/bootprint-base/blob/fdb843317d68f04eaf513e2cdda439774a7ca134/handlebars/helpers.js#L119-L133
40,205
StirfireStudios/Jacquard-YarnParser
src/listener/util.js
dsStatement
function dsStatement(statement) { switch(statement.constructor) { case Statements.Blank: case Statements.Conditional: case Statements.DialogueSegment: case Statements.Evaluate: case Statements.Function: case Statements.Link: case Statements.Option: case Statements.OptionGroup: case Statements.Shortcut: case Statements.ShortcutGroup: return false; case Statements.Command: case Statements.LineGroup: case Statements.Text: case Statements.Hashtag: return true; default: console.warn(`Unrecognized statement type: ${statement.constructor.name}`); return false; } }
javascript
function dsStatement(statement) { switch(statement.constructor) { case Statements.Blank: case Statements.Conditional: case Statements.DialogueSegment: case Statements.Evaluate: case Statements.Function: case Statements.Link: case Statements.Option: case Statements.OptionGroup: case Statements.Shortcut: case Statements.ShortcutGroup: return false; case Statements.Command: case Statements.LineGroup: case Statements.Text: case Statements.Hashtag: return true; default: console.warn(`Unrecognized statement type: ${statement.constructor.name}`); return false; } }
[ "function", "dsStatement", "(", "statement", ")", "{", "switch", "(", "statement", ".", "constructor", ")", "{", "case", "Statements", ".", "Blank", ":", "case", "Statements", ".", "Conditional", ":", "case", "Statements", ".", "DialogueSegment", ":", "case", "Statements", ".", "Evaluate", ":", "case", "Statements", ".", "Function", ":", "case", "Statements", ".", "Link", ":", "case", "Statements", ".", "Option", ":", "case", "Statements", ".", "OptionGroup", ":", "case", "Statements", ".", "Shortcut", ":", "case", "Statements", ".", "ShortcutGroup", ":", "return", "false", ";", "case", "Statements", ".", "Command", ":", "case", "Statements", ".", "LineGroup", ":", "case", "Statements", ".", "Text", ":", "case", "Statements", ".", "Hashtag", ":", "return", "true", ";", "default", ":", "console", ".", "warn", "(", "`", "${", "statement", ".", "constructor", ".", "name", "}", "`", ")", ";", "return", "false", ";", "}", "}" ]
Dialog segment utils!
[ "Dialog", "segment", "utils!" ]
fd2d3e1b3a952d2b2502c16919eaf12f2b5764b8
https://github.com/StirfireStudios/Jacquard-YarnParser/blob/fd2d3e1b3a952d2b2502c16919eaf12f2b5764b8/src/listener/util.js#L52-L74
40,206
websemantics/svg-smart
smart.js
read
function read (filename) { var data = null try { data = readfile(filename) } catch (error) { if (error.code === 'MODULE_NOT_FOUND') { console.error('File ' + filename + ' is not found') } } return data }
javascript
function read (filename) { var data = null try { data = readfile(filename) } catch (error) { if (error.code === 'MODULE_NOT_FOUND') { console.error('File ' + filename + ' is not found') } } return data }
[ "function", "read", "(", "filename", ")", "{", "var", "data", "=", "null", "try", "{", "data", "=", "readfile", "(", "filename", ")", "}", "catch", "(", "error", ")", "{", "if", "(", "error", ".", "code", "===", "'MODULE_NOT_FOUND'", ")", "{", "console", ".", "error", "(", "'File '", "+", "filename", "+", "' is not found'", ")", "}", "}", "return", "data", "}" ]
Read a dot file, .. simple, huh .. @param {filename} string, json file @return object
[ "Read", "a", "dot", "file", "..", "simple", "huh", ".." ]
d4a81574b2ef10a0f44b81a02ee9c898e97b4604
https://github.com/websemantics/svg-smart/blob/d4a81574b2ef10a0f44b81a02ee9c898e97b4604/smart.js#L241-L251
40,207
websemantics/svg-smart
smart.js
function (smart_filename, package_filename) { var smart = read(smart_filename) var data = { global: hydrate(smart.global, smart.global), package: read(package_filename) } var dist = data.global.files.dist || 'dist' var res = resources(hydrate(smart.template, data), hydrate(smart.data, data), data.global.files.concatenator, dist) return { svg: res.svg, png: res.png, icon: res.icon, sprite: res.sprite, dist: dist, html: hydrate(smart.html, data) } }
javascript
function (smart_filename, package_filename) { var smart = read(smart_filename) var data = { global: hydrate(smart.global, smart.global), package: read(package_filename) } var dist = data.global.files.dist || 'dist' var res = resources(hydrate(smart.template, data), hydrate(smart.data, data), data.global.files.concatenator, dist) return { svg: res.svg, png: res.png, icon: res.icon, sprite: res.sprite, dist: dist, html: hydrate(smart.html, data) } }
[ "function", "(", "smart_filename", ",", "package_filename", ")", "{", "var", "smart", "=", "read", "(", "smart_filename", ")", "var", "data", "=", "{", "global", ":", "hydrate", "(", "smart", ".", "global", ",", "smart", ".", "global", ")", ",", "package", ":", "read", "(", "package_filename", ")", "}", "var", "dist", "=", "data", ".", "global", ".", "files", ".", "dist", "||", "'dist'", "var", "res", "=", "resources", "(", "hydrate", "(", "smart", ".", "template", ",", "data", ")", ",", "hydrate", "(", "smart", ".", "data", ",", "data", ")", ",", "data", ".", "global", ".", "files", ".", "concatenator", ",", "dist", ")", "return", "{", "svg", ":", "res", ".", "svg", ",", "png", ":", "res", ".", "png", ",", "icon", ":", "res", ".", "icon", ",", "sprite", ":", "res", ".", "sprite", ",", "dist", ":", "dist", ",", "html", ":", "hydrate", "(", "smart", ".", "html", ",", "data", ")", "}", "}" ]
Load and process the svg-smart json file @param {smart_filename} string, the svg-smart json file @param {package_filename} string, node.js package filename (reuse of information) @return object, a list of resources to be generated (svg, png, ico, sprite)
[ "Load", "and", "process", "the", "svg", "-", "smart", "json", "file" ]
d4a81574b2ef10a0f44b81a02ee9c898e97b4604
https://github.com/websemantics/svg-smart/blob/d4a81574b2ef10a0f44b81a02ee9c898e97b4604/smart.js#L270-L289
40,208
noderaider/repackage
jspm_packages/npm/[email protected]/lib/transformation/transformers/validation/react.js
check
function check(source, file) { if (t.isLiteral(source)) { var name = source.value; var lower = name.toLowerCase(); if (lower === "react" && name !== lower) { throw file.errorWithNode(source, messages.get("didYouMean", "react")); } } }
javascript
function check(source, file) { if (t.isLiteral(source)) { var name = source.value; var lower = name.toLowerCase(); if (lower === "react" && name !== lower) { throw file.errorWithNode(source, messages.get("didYouMean", "react")); } } }
[ "function", "check", "(", "source", ",", "file", ")", "{", "if", "(", "t", ".", "isLiteral", "(", "source", ")", ")", "{", "var", "name", "=", "source", ".", "value", ";", "var", "lower", "=", "name", ".", "toLowerCase", "(", ")", ";", "if", "(", "lower", "===", "\"react\"", "&&", "name", "!==", "lower", ")", "{", "throw", "file", ".", "errorWithNode", "(", "source", ",", "messages", ".", "get", "(", "\"didYouMean\"", ",", "\"react\"", ")", ")", ";", "}", "}", "}" ]
check if the input Literal `source` is an alternate casing of "react"
[ "check", "if", "the", "input", "Literal", "source", "is", "an", "alternate", "casing", "of", "react" ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/transformation/transformers/validation/react.js#L19-L28
40,209
emmetio/html-snippets-resolver
index.js
merge
function merge(from, to) { to.name = from.name; if (from.selfClosing) { to.selfClosing = true; } if (from.value != null) { to.value = from.value; } if (from.repeat) { to.repeat = Object.assign({}, from.repeat); } return mergeAttributes(from, to); }
javascript
function merge(from, to) { to.name = from.name; if (from.selfClosing) { to.selfClosing = true; } if (from.value != null) { to.value = from.value; } if (from.repeat) { to.repeat = Object.assign({}, from.repeat); } return mergeAttributes(from, to); }
[ "function", "merge", "(", "from", ",", "to", ")", "{", "to", ".", "name", "=", "from", ".", "name", ";", "if", "(", "from", ".", "selfClosing", ")", "{", "to", ".", "selfClosing", "=", "true", ";", "}", "if", "(", "from", ".", "value", "!=", "null", ")", "{", "to", ".", "value", "=", "from", ".", "value", ";", "}", "if", "(", "from", ".", "repeat", ")", "{", "to", ".", "repeat", "=", "Object", ".", "assign", "(", "{", "}", ",", "from", ".", "repeat", ")", ";", "}", "return", "mergeAttributes", "(", "from", ",", "to", ")", ";", "}" ]
Adds data from first node into second node and returns it @param {Node} from @param {Node} to @return {Node}
[ "Adds", "data", "from", "first", "node", "into", "second", "node", "and", "returns", "it" ]
a65d8f769af1ea12f8edc031bf37ddeb3383f9e8
https://github.com/emmetio/html-snippets-resolver/blob/a65d8f769af1ea12f8edc031bf37ddeb3383f9e8/index.js#L69-L85
40,210
emmetio/html-snippets-resolver
index.js
mergeClassNames
function mergeClassNames(from, to) { const classNames = from.classList; for (let i = 0; i < classNames.length; i++) { to.addClass(classNames[i]); } return to; }
javascript
function mergeClassNames(from, to) { const classNames = from.classList; for (let i = 0; i < classNames.length; i++) { to.addClass(classNames[i]); } return to; }
[ "function", "mergeClassNames", "(", "from", ",", "to", ")", "{", "const", "classNames", "=", "from", ".", "classList", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "classNames", ".", "length", ";", "i", "++", ")", "{", "to", ".", "addClass", "(", "classNames", "[", "i", "]", ")", ";", "}", "return", "to", ";", "}" ]
Adds class names from first node to second one @param {Node} from @param {Node} to @return {Node}
[ "Adds", "class", "names", "from", "first", "node", "to", "second", "one" ]
a65d8f769af1ea12f8edc031bf37ddeb3383f9e8
https://github.com/emmetio/html-snippets-resolver/blob/a65d8f769af1ea12f8edc031bf37ddeb3383f9e8/index.js#L140-L147
40,211
emmetio/html-snippets-resolver
index.js
findDeepestNode
function findDeepestNode(node) { while (node.children.length) { node = node.children[node.children.length - 1]; } return node; }
javascript
function findDeepestNode(node) { while (node.children.length) { node = node.children[node.children.length - 1]; } return node; }
[ "function", "findDeepestNode", "(", "node", ")", "{", "while", "(", "node", ".", "children", ".", "length", ")", "{", "node", "=", "node", ".", "children", "[", "node", ".", "children", ".", "length", "-", "1", "]", ";", "}", "return", "node", ";", "}" ]
Finds node which is the deepest for in current node or node itself. @param {Node} node @return {Node}
[ "Finds", "node", "which", "is", "the", "deepest", "for", "in", "current", "node", "or", "node", "itself", "." ]
a65d8f769af1ea12f8edc031bf37ddeb3383f9e8
https://github.com/emmetio/html-snippets-resolver/blob/a65d8f769af1ea12f8edc031bf37ddeb3383f9e8/index.js#L154-L160
40,212
skerit/protoblast
lib/request_browser.js
done
function done() { if (!error && xhr.status > 399) { error = new Error(xhr.statusText); error.status = error.number = xhr.status; } if (type && type.indexOf('json') > -1 && result) { result = Collection.JSON.undry(result); } if (error) { error.result = result; pledge.reject(error); that.error = error; } else { that.result = result; pledge.resolve(result); } }
javascript
function done() { if (!error && xhr.status > 399) { error = new Error(xhr.statusText); error.status = error.number = xhr.status; } if (type && type.indexOf('json') > -1 && result) { result = Collection.JSON.undry(result); } if (error) { error.result = result; pledge.reject(error); that.error = error; } else { that.result = result; pledge.resolve(result); } }
[ "function", "done", "(", ")", "{", "if", "(", "!", "error", "&&", "xhr", ".", "status", ">", "399", ")", "{", "error", "=", "new", "Error", "(", "xhr", ".", "statusText", ")", ";", "error", ".", "status", "=", "error", ".", "number", "=", "xhr", ".", "status", ";", "}", "if", "(", "type", "&&", "type", ".", "indexOf", "(", "'json'", ")", ">", "-", "1", "&&", "result", ")", "{", "result", "=", "Collection", ".", "JSON", ".", "undry", "(", "result", ")", ";", "}", "if", "(", "error", ")", "{", "error", ".", "result", "=", "result", ";", "pledge", ".", "reject", "(", "error", ")", ";", "that", ".", "error", "=", "error", ";", "}", "else", "{", "that", ".", "result", "=", "result", ";", "pledge", ".", "resolve", "(", "result", ")", ";", "}", "}" ]
Function that'll cleanup the request & resolve or reject the pledge
[ "Function", "that", "ll", "cleanup", "the", "request", "&", "resolve", "or", "reject", "the", "pledge" ]
22f35b05611bd507d380782023179a3f6ec383ae
https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/request_browser.js#L173-L192
40,213
M6Web/immutable-set
src/set.js
set
function set(base, path, value, { withArrays, sameValue }) { if (path.length === 0) { return value; } const [key, nextKey] = path; const isArrayKeys = Array.isArray(key); let currentBase = base; if (!base || typeof base !== 'object') { currentBase = (isArrayKeys && typeof key[0] === 'number') || (withArrays && typeof key === 'number') ? [] : {}; } if (isArrayKeys) { if (Array.isArray(currentBase)) { return reduceWithArray(set)(currentBase, path, key, nextKey, value, { withArrays, sameValue }, [...currentBase]); } return { ...currentBase, ...reduceWithObject(set)(currentBase, path, key, nextKey, value, { withArrays, sameValue }, {}), }; } if (Array.isArray(currentBase)) { return [ ...currentBase.slice(0, key), set(nextBase(currentBase, key, nextKey, withArrays), path.slice(1), value, { withArrays, sameValue }), ...currentBase.slice(key + 1), ]; } return { ...currentBase, [key]: set(nextBase(currentBase, key, nextKey, withArrays), path.slice(1), value, { withArrays, sameValue }), }; }
javascript
function set(base, path, value, { withArrays, sameValue }) { if (path.length === 0) { return value; } const [key, nextKey] = path; const isArrayKeys = Array.isArray(key); let currentBase = base; if (!base || typeof base !== 'object') { currentBase = (isArrayKeys && typeof key[0] === 'number') || (withArrays && typeof key === 'number') ? [] : {}; } if (isArrayKeys) { if (Array.isArray(currentBase)) { return reduceWithArray(set)(currentBase, path, key, nextKey, value, { withArrays, sameValue }, [...currentBase]); } return { ...currentBase, ...reduceWithObject(set)(currentBase, path, key, nextKey, value, { withArrays, sameValue }, {}), }; } if (Array.isArray(currentBase)) { return [ ...currentBase.slice(0, key), set(nextBase(currentBase, key, nextKey, withArrays), path.slice(1), value, { withArrays, sameValue }), ...currentBase.slice(key + 1), ]; } return { ...currentBase, [key]: set(nextBase(currentBase, key, nextKey, withArrays), path.slice(1), value, { withArrays, sameValue }), }; }
[ "function", "set", "(", "base", ",", "path", ",", "value", ",", "{", "withArrays", ",", "sameValue", "}", ")", "{", "if", "(", "path", ".", "length", "===", "0", ")", "{", "return", "value", ";", "}", "const", "[", "key", ",", "nextKey", "]", "=", "path", ";", "const", "isArrayKeys", "=", "Array", ".", "isArray", "(", "key", ")", ";", "let", "currentBase", "=", "base", ";", "if", "(", "!", "base", "||", "typeof", "base", "!==", "'object'", ")", "{", "currentBase", "=", "(", "isArrayKeys", "&&", "typeof", "key", "[", "0", "]", "===", "'number'", ")", "||", "(", "withArrays", "&&", "typeof", "key", "===", "'number'", ")", "?", "[", "]", ":", "{", "}", ";", "}", "if", "(", "isArrayKeys", ")", "{", "if", "(", "Array", ".", "isArray", "(", "currentBase", ")", ")", "{", "return", "reduceWithArray", "(", "set", ")", "(", "currentBase", ",", "path", ",", "key", ",", "nextKey", ",", "value", ",", "{", "withArrays", ",", "sameValue", "}", ",", "[", "...", "currentBase", "]", ")", ";", "}", "return", "{", "...", "currentBase", ",", "...", "reduceWithObject", "(", "set", ")", "(", "currentBase", ",", "path", ",", "key", ",", "nextKey", ",", "value", ",", "{", "withArrays", ",", "sameValue", "}", ",", "{", "}", ")", ",", "}", ";", "}", "if", "(", "Array", ".", "isArray", "(", "currentBase", ")", ")", "{", "return", "[", "...", "currentBase", ".", "slice", "(", "0", ",", "key", ")", ",", "set", "(", "nextBase", "(", "currentBase", ",", "key", ",", "nextKey", ",", "withArrays", ")", ",", "path", ".", "slice", "(", "1", ")", ",", "value", ",", "{", "withArrays", ",", "sameValue", "}", ")", ",", "...", "currentBase", ".", "slice", "(", "key", "+", "1", ")", ",", "]", ";", "}", "return", "{", "...", "currentBase", ",", "[", "key", "]", ":", "set", "(", "nextBase", "(", "currentBase", ",", "key", ",", "nextKey", ",", "withArrays", ")", ",", "path", ".", "slice", "(", "1", ")", ",", "value", ",", "{", "withArrays", ",", "sameValue", "}", ")", ",", "}", ";", "}" ]
Recursive immutable set @param base current base @param path current path @param value current value @param config - withArrays create arrays instead of object when nextKey is a number and key has no value in the current base - sameValue use the same value for each element @returns {*} a new instance of the given level
[ "Recursive", "immutable", "set" ]
8e096b74959abdd1a7489d51b76f989def02c7d8
https://github.com/M6Web/immutable-set/blob/8e096b74959abdd1a7489d51b76f989def02c7d8/src/set.js#L93-L129
40,214
NotNinja/node-blinkt
src/blinkt.js
show
function show() { if (dat == null && clk == null) { dat = new Gpio(23, 'out'); clk = new Gpio(24, 'out'); } sof(); var pixel; for (var i = 0, length = pixels.length; i < length; i++) { pixel = pixels[i]; writeByte(0xe0 | pixel[3]); writeByte(pixel[2]); writeByte(pixel[1]); writeByte(pixel[0]); } eof(); }
javascript
function show() { if (dat == null && clk == null) { dat = new Gpio(23, 'out'); clk = new Gpio(24, 'out'); } sof(); var pixel; for (var i = 0, length = pixels.length; i < length; i++) { pixel = pixels[i]; writeByte(0xe0 | pixel[3]); writeByte(pixel[2]); writeByte(pixel[1]); writeByte(pixel[0]); } eof(); }
[ "function", "show", "(", ")", "{", "if", "(", "dat", "==", "null", "&&", "clk", "==", "null", ")", "{", "dat", "=", "new", "Gpio", "(", "23", ",", "'out'", ")", ";", "clk", "=", "new", "Gpio", "(", "24", ",", "'out'", ")", ";", "}", "sof", "(", ")", ";", "var", "pixel", ";", "for", "(", "var", "i", "=", "0", ",", "length", "=", "pixels", ".", "length", ";", "i", "<", "length", ";", "i", "++", ")", "{", "pixel", "=", "pixels", "[", "i", "]", ";", "writeByte", "(", "0xe0", "|", "pixel", "[", "3", "]", ")", ";", "writeByte", "(", "pixel", "[", "2", "]", ")", ";", "writeByte", "(", "pixel", "[", "1", "]", ")", ";", "writeByte", "(", "pixel", "[", "0", "]", ")", ";", "}", "eof", "(", ")", ";", "}" ]
Outputs the buffer to Blinkt! @return {void} @public
[ "Outputs", "the", "buffer", "to", "Blinkt!" ]
95d85ea46901f3a90c63082fec1f974e04d23b50
https://github.com/NotNinja/node-blinkt/blob/95d85ea46901f3a90c63082fec1f974e04d23b50/src/blinkt.js#L166-L186
40,215
webgme/ui-replay
src/visualizers/widgets/UIReplay/UIReplayCommitBadge.js
function (containerEl, client, params) { var self = this, index = params.index; this._client = client; this._commitHash = params.id; if (typeof index === 'number') { // Add some margins just in case. this._n = index > 90 ? index + 20 : 100; } else { // Until webgme v2.18.0 look through 300 commits. this._n = 300; } this._destroyed = false; this.$el = $('<i>', { class: 'fa fa-video-camera ui-replay-commit-status-icon loading' }); $(containerEl).append(this.$el); RecordReplayControllers.getStatus(client.getActiveProjectId(), this._commitHash, function (err, status) { if (self._destroyed) { return; } self.$el.removeClass('loading'); if (err) { self.$el.addClass('error'); self.$el.attr('title', 'Errored'); } else if (status.exists === true) { self.$el.addClass('success'); self.$el.attr('title', 'Start playback to current commit from this commit'); self.$el.on('click', function () { self._showReplayDialog(); }); } else { self.$el.addClass('unavailable'); self.$el.attr('title', 'No recording available'); } }); }
javascript
function (containerEl, client, params) { var self = this, index = params.index; this._client = client; this._commitHash = params.id; if (typeof index === 'number') { // Add some margins just in case. this._n = index > 90 ? index + 20 : 100; } else { // Until webgme v2.18.0 look through 300 commits. this._n = 300; } this._destroyed = false; this.$el = $('<i>', { class: 'fa fa-video-camera ui-replay-commit-status-icon loading' }); $(containerEl).append(this.$el); RecordReplayControllers.getStatus(client.getActiveProjectId(), this._commitHash, function (err, status) { if (self._destroyed) { return; } self.$el.removeClass('loading'); if (err) { self.$el.addClass('error'); self.$el.attr('title', 'Errored'); } else if (status.exists === true) { self.$el.addClass('success'); self.$el.attr('title', 'Start playback to current commit from this commit'); self.$el.on('click', function () { self._showReplayDialog(); }); } else { self.$el.addClass('unavailable'); self.$el.attr('title', 'No recording available'); } }); }
[ "function", "(", "containerEl", ",", "client", ",", "params", ")", "{", "var", "self", "=", "this", ",", "index", "=", "params", ".", "index", ";", "this", ".", "_client", "=", "client", ";", "this", ".", "_commitHash", "=", "params", ".", "id", ";", "if", "(", "typeof", "index", "===", "'number'", ")", "{", "// Add some margins just in case.", "this", ".", "_n", "=", "index", ">", "90", "?", "index", "+", "20", ":", "100", ";", "}", "else", "{", "// Until webgme v2.18.0 look through 300 commits.", "this", ".", "_n", "=", "300", ";", "}", "this", ".", "_destroyed", "=", "false", ";", "this", ".", "$el", "=", "$", "(", "'<i>'", ",", "{", "class", ":", "'fa fa-video-camera ui-replay-commit-status-icon loading'", "}", ")", ";", "$", "(", "containerEl", ")", ".", "append", "(", "this", ".", "$el", ")", ";", "RecordReplayControllers", ".", "getStatus", "(", "client", ".", "getActiveProjectId", "(", ")", ",", "this", ".", "_commitHash", ",", "function", "(", "err", ",", "status", ")", "{", "if", "(", "self", ".", "_destroyed", ")", "{", "return", ";", "}", "self", ".", "$el", ".", "removeClass", "(", "'loading'", ")", ";", "if", "(", "err", ")", "{", "self", ".", "$el", ".", "addClass", "(", "'error'", ")", ";", "self", ".", "$el", ".", "attr", "(", "'title'", ",", "'Errored'", ")", ";", "}", "else", "if", "(", "status", ".", "exists", "===", "true", ")", "{", "self", ".", "$el", ".", "addClass", "(", "'success'", ")", ";", "self", ".", "$el", ".", "attr", "(", "'title'", ",", "'Start playback to current commit from this commit'", ")", ";", "self", ".", "$el", ".", "on", "(", "'click'", ",", "function", "(", ")", "{", "self", ".", "_showReplayDialog", "(", ")", ";", "}", ")", ";", "}", "else", "{", "self", ".", "$el", ".", "addClass", "(", "'unavailable'", ")", ";", "self", ".", "$el", ".", "attr", "(", "'title'", ",", "'No recording available'", ")", ";", "}", "}", ")", ";", "}" ]
var STATUS_CLASSES = 'loading success unavailable error';
[ "var", "STATUS_CLASSES", "=", "loading", "success", "unavailable", "error", ";" ]
0e0ad90b044d92cd508af03246ce0e9cbc382097
https://github.com/webgme/ui-replay/blob/0e0ad90b044d92cd508af03246ce0e9cbc382097/src/visualizers/widgets/UIReplay/UIReplayCommitBadge.js#L15-L58
40,216
seangenabe/copy-newer
src/copy.js
copyNewerSingle
async function copyNewerSingle(srcpath, destpath, opts) { let { interval = 1000, verbose = false } = opts let stat = await FS.stat(srcpath) // Stat and check the filesystem entry type. if (stat.isDirectory()) { // Directory, ensure destination exists and return. let made = await mkdirp(destpath) if (verbose && made) { console.log(`${made} - directory created`)} return 'dir' } else if (!stat.isFile()) { // Not a file. throw new Error("Not supported.") } let srcmtime = stat.mtime let destmtime try { // Stat destpath and get the mtime. destmtime = (await FS.stat(destpath)).mtime } catch (err) { // path does not exist } if (destmtime !== undefined && srcmtime - destmtime <= interval) { // destpath does not exist or mtime is equal, return. if (verbose) { console.log(`${srcpath} == ${destpath}`) } return false } // Ensure parent directory exists. await mkdirp(`${destpath}/..`) // Commence copying. let rs = FS.createReadStream(srcpath) let ws = FS.createWriteStream(destpath) rs.pipe(ws) await waitForStreamEnd(ws) // Set mtime to be equal to the source file. await FS.utimes(destpath, new Date(), stat.mtime) if (verbose) { console.log(`${srcpath} -> ${destpath}`) } return true }
javascript
async function copyNewerSingle(srcpath, destpath, opts) { let { interval = 1000, verbose = false } = opts let stat = await FS.stat(srcpath) // Stat and check the filesystem entry type. if (stat.isDirectory()) { // Directory, ensure destination exists and return. let made = await mkdirp(destpath) if (verbose && made) { console.log(`${made} - directory created`)} return 'dir' } else if (!stat.isFile()) { // Not a file. throw new Error("Not supported.") } let srcmtime = stat.mtime let destmtime try { // Stat destpath and get the mtime. destmtime = (await FS.stat(destpath)).mtime } catch (err) { // path does not exist } if (destmtime !== undefined && srcmtime - destmtime <= interval) { // destpath does not exist or mtime is equal, return. if (verbose) { console.log(`${srcpath} == ${destpath}`) } return false } // Ensure parent directory exists. await mkdirp(`${destpath}/..`) // Commence copying. let rs = FS.createReadStream(srcpath) let ws = FS.createWriteStream(destpath) rs.pipe(ws) await waitForStreamEnd(ws) // Set mtime to be equal to the source file. await FS.utimes(destpath, new Date(), stat.mtime) if (verbose) { console.log(`${srcpath} -> ${destpath}`) } return true }
[ "async", "function", "copyNewerSingle", "(", "srcpath", ",", "destpath", ",", "opts", ")", "{", "let", "{", "interval", "=", "1000", ",", "verbose", "=", "false", "}", "=", "opts", "let", "stat", "=", "await", "FS", ".", "stat", "(", "srcpath", ")", "// Stat and check the filesystem entry type.", "if", "(", "stat", ".", "isDirectory", "(", ")", ")", "{", "// Directory, ensure destination exists and return.", "let", "made", "=", "await", "mkdirp", "(", "destpath", ")", "if", "(", "verbose", "&&", "made", ")", "{", "console", ".", "log", "(", "`", "${", "made", "}", "`", ")", "}", "return", "'dir'", "}", "else", "if", "(", "!", "stat", ".", "isFile", "(", ")", ")", "{", "// Not a file.", "throw", "new", "Error", "(", "\"Not supported.\"", ")", "}", "let", "srcmtime", "=", "stat", ".", "mtime", "let", "destmtime", "try", "{", "// Stat destpath and get the mtime.", "destmtime", "=", "(", "await", "FS", ".", "stat", "(", "destpath", ")", ")", ".", "mtime", "}", "catch", "(", "err", ")", "{", "// path does not exist", "}", "if", "(", "destmtime", "!==", "undefined", "&&", "srcmtime", "-", "destmtime", "<=", "interval", ")", "{", "// destpath does not exist or mtime is equal, return.", "if", "(", "verbose", ")", "{", "console", ".", "log", "(", "`", "${", "srcpath", "}", "${", "destpath", "}", "`", ")", "}", "return", "false", "}", "// Ensure parent directory exists.", "await", "mkdirp", "(", "`", "${", "destpath", "}", "`", ")", "// Commence copying.", "let", "rs", "=", "FS", ".", "createReadStream", "(", "srcpath", ")", "let", "ws", "=", "FS", ".", "createWriteStream", "(", "destpath", ")", "rs", ".", "pipe", "(", "ws", ")", "await", "waitForStreamEnd", "(", "ws", ")", "// Set mtime to be equal to the source file.", "await", "FS", ".", "utimes", "(", "destpath", ",", "new", "Date", "(", ")", ",", "stat", ".", "mtime", ")", "if", "(", "verbose", ")", "{", "console", ".", "log", "(", "`", "${", "srcpath", "}", "${", "destpath", "}", "`", ")", "}", "return", "true", "}" ]
Copies a single file. Returns 'dir' if directory, true if successful, false if not. Throws Error if not a file and not a directory.
[ "Copies", "a", "single", "file", ".", "Returns", "dir", "if", "directory", "true", "if", "successful", "false", "if", "not", ".", "Throws", "Error", "if", "not", "a", "file", "and", "not", "a", "directory", "." ]
0be2dacc287ca9ccbd3bcd1049cdf0a86f2b3a1b
https://github.com/seangenabe/copy-newer/blob/0be2dacc287ca9ccbd3bcd1049cdf0a86f2b3a1b/src/copy.js#L33-L80
40,217
marshallswain/amity-mongodb
lib/amity-mongodb.js
function(database, callback){ var dbName = database.databaseName || database.name; var options = { name:dbName + '/_collections', service:feathersMongoColls(amityMongo.db.db(dbName)) }; amityMongo.amity_collManager.push(options); callback(); }
javascript
function(database, callback){ var dbName = database.databaseName || database.name; var options = { name:dbName + '/_collections', service:feathersMongoColls(amityMongo.db.db(dbName)) }; amityMongo.amity_collManager.push(options); callback(); }
[ "function", "(", "database", ",", "callback", ")", "{", "var", "dbName", "=", "database", ".", "databaseName", "||", "database", ".", "name", ";", "var", "options", "=", "{", "name", ":", "dbName", "+", "'/_collections'", ",", "service", ":", "feathersMongoColls", "(", "amityMongo", ".", "db", ".", "db", "(", "dbName", ")", ")", "}", ";", "amityMongo", ".", "amity_collManager", ".", "push", "(", "options", ")", ";", "callback", "(", ")", ";", "}" ]
Prepares a service to manage collections on the database. This service will be set up by the Amity server.
[ "Prepares", "a", "service", "to", "manage", "collections", "on", "the", "database", ".", "This", "service", "will", "be", "set", "up", "by", "the", "Amity", "server", "." ]
311b85b70ec126d70ce457eb21c7a492076a0b8c
https://github.com/marshallswain/amity-mongodb/blob/311b85b70ec126d70ce457eb21c7a492076a0b8c/lib/amity-mongodb.js#L132-L140
40,218
marshallswain/amity-mongodb
lib/amity-mongodb.js
function(collection, callback){ // Prep the collection name. var colName = collection.name.split('.'); var dbName = colName.shift(); colName = colName.join('.'); var database = amityMongo.db.db(dbName); var options = { name:dbName + '/' + colName, service:feathersMongo({collection:database.collection(collection.name)}) }; amityMongo.amity_collections.push(options); callback(); }
javascript
function(collection, callback){ // Prep the collection name. var colName = collection.name.split('.'); var dbName = colName.shift(); colName = colName.join('.'); var database = amityMongo.db.db(dbName); var options = { name:dbName + '/' + colName, service:feathersMongo({collection:database.collection(collection.name)}) }; amityMongo.amity_collections.push(options); callback(); }
[ "function", "(", "collection", ",", "callback", ")", "{", "// Prep the collection name.", "var", "colName", "=", "collection", ".", "name", ".", "split", "(", "'.'", ")", ";", "var", "dbName", "=", "colName", ".", "shift", "(", ")", ";", "colName", "=", "colName", ".", "join", "(", "'.'", ")", ";", "var", "database", "=", "amityMongo", ".", "db", ".", "db", "(", "dbName", ")", ";", "var", "options", "=", "{", "name", ":", "dbName", "+", "'/'", "+", "colName", ",", "service", ":", "feathersMongo", "(", "{", "collection", ":", "database", ".", "collection", "(", "collection", ".", "name", ")", "}", ")", "}", ";", "amityMongo", ".", "amity_collections", ".", "push", "(", "options", ")", ";", "callback", "(", ")", ";", "}" ]
Prepares a service to manage documents in the provided collection. This service will be set up by the Amity server.
[ "Prepares", "a", "service", "to", "manage", "documents", "in", "the", "provided", "collection", ".", "This", "service", "will", "be", "set", "up", "by", "the", "Amity", "server", "." ]
311b85b70ec126d70ce457eb21c7a492076a0b8c
https://github.com/marshallswain/amity-mongodb/blob/311b85b70ec126d70ce457eb21c7a492076a0b8c/lib/amity-mongodb.js#L144-L158
40,219
jffry/lb-include
src/index.js
loadFileContents
function loadFileContents(filePath, preloaded) { //use pre-supplied contents? if (typeof preloaded !== 'undefined' && preloaded !== null) { //return a promise which will get resolved with the preloaded value if (preloaded instanceof Buffer) { return promiseValue(preloaded.toString()); } else { return promiseValue(String(preloaded)); } } else { return Q.nfcall(fs.readFile, filePath).invoke('toString'); } }
javascript
function loadFileContents(filePath, preloaded) { //use pre-supplied contents? if (typeof preloaded !== 'undefined' && preloaded !== null) { //return a promise which will get resolved with the preloaded value if (preloaded instanceof Buffer) { return promiseValue(preloaded.toString()); } else { return promiseValue(String(preloaded)); } } else { return Q.nfcall(fs.readFile, filePath).invoke('toString'); } }
[ "function", "loadFileContents", "(", "filePath", ",", "preloaded", ")", "{", "//use pre-supplied contents?", "if", "(", "typeof", "preloaded", "!==", "'undefined'", "&&", "preloaded", "!==", "null", ")", "{", "//return a promise which will get resolved with the preloaded value", "if", "(", "preloaded", "instanceof", "Buffer", ")", "{", "return", "promiseValue", "(", "preloaded", ".", "toString", "(", ")", ")", ";", "}", "else", "{", "return", "promiseValue", "(", "String", "(", "preloaded", ")", ")", ";", "}", "}", "else", "{", "return", "Q", ".", "nfcall", "(", "fs", ".", "readFile", ",", "filePath", ")", ".", "invoke", "(", "'toString'", ")", ";", "}", "}" ]
helper function to load file; returns promise that's resolved with contents
[ "helper", "function", "to", "load", "file", ";", "returns", "promise", "that", "s", "resolved", "with", "contents" ]
049f3ff1a86604a43c51391fe273bc6ba02a594b
https://github.com/jffry/lb-include/blob/049f3ff1a86604a43c51391fe273bc6ba02a594b/src/index.js#L186-L205
40,220
viliam-jobko/swagger-client-sync
index.js
returnClient
function returnClient(options, ignoreCache) { if (typeof options === 'string') { options = { url: options, usePromise: true }; } if (ignoreCache === true) { return generateClient(options); } const optionsJSON = JSON.stringify(options); if (cachedClients[optionsJSON] instanceof Swagger) { return cachedClients[optionsJSON]; } else { cachedClients[optionsJSON] = generateClient(options); return cachedClients[optionsJSON]; } }
javascript
function returnClient(options, ignoreCache) { if (typeof options === 'string') { options = { url: options, usePromise: true }; } if (ignoreCache === true) { return generateClient(options); } const optionsJSON = JSON.stringify(options); if (cachedClients[optionsJSON] instanceof Swagger) { return cachedClients[optionsJSON]; } else { cachedClients[optionsJSON] = generateClient(options); return cachedClients[optionsJSON]; } }
[ "function", "returnClient", "(", "options", ",", "ignoreCache", ")", "{", "if", "(", "typeof", "options", "===", "'string'", ")", "{", "options", "=", "{", "url", ":", "options", ",", "usePromise", ":", "true", "}", ";", "}", "if", "(", "ignoreCache", "===", "true", ")", "{", "return", "generateClient", "(", "options", ")", ";", "}", "const", "optionsJSON", "=", "JSON", ".", "stringify", "(", "options", ")", ";", "if", "(", "cachedClients", "[", "optionsJSON", "]", "instanceof", "Swagger", ")", "{", "return", "cachedClients", "[", "optionsJSON", "]", ";", "}", "else", "{", "cachedClients", "[", "optionsJSON", "]", "=", "generateClient", "(", "options", ")", ";", "return", "cachedClients", "[", "optionsJSON", "]", ";", "}", "}" ]
Create a swagger-client synchronously. @param {String|Object} options URL to swagger specification or object with options that will be passed to swagger-client constructor. @param {Boolean=} ignoreCache Created new swagger-client and don't cache it (default: false).
[ "Create", "a", "swagger", "-", "client", "synchronously", "." ]
b59abf3e645596647c1a0a9d754ae0c2518b09ed
https://github.com/viliam-jobko/swagger-client-sync/blob/b59abf3e645596647c1a0a9d754ae0c2518b09ed/index.js#L24-L43
40,221
stezu/node-stream
lib/_utils/parse.js
parse
function parse(data, callback) { var parsed; try { parsed = JSON.parse(data); } catch (e) { return callback(e); } return callback(null, parsed); }
javascript
function parse(data, callback) { var parsed; try { parsed = JSON.parse(data); } catch (e) { return callback(e); } return callback(null, parsed); }
[ "function", "parse", "(", "data", ",", "callback", ")", "{", "var", "parsed", ";", "try", "{", "parsed", "=", "JSON", ".", "parse", "(", "data", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "callback", "(", "e", ")", ";", "}", "return", "callback", "(", "null", ",", "parsed", ")", ";", "}" ]
Parse the contents of a string as JSON. @private @static @since 1.3.0 @category Utilities @param {String} data - String you would like to parse as JSON. @param {Function} callback - Callback with an error or parsed JSON. @returns {undefined}
[ "Parse", "the", "contents", "of", "a", "string", "as", "JSON", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/_utils/parse.js#L13-L23
40,222
noderaider/repackage
jspm_packages/npm/[email protected]/lib/transformation/transformers/es6/parameters/rest.js
BindingIdentifier
function BindingIdentifier(node, parent, scope, state) { if (node.name === state.name) { state.deopted = true; } }
javascript
function BindingIdentifier(node, parent, scope, state) { if (node.name === state.name) { state.deopted = true; } }
[ "function", "BindingIdentifier", "(", "node", ",", "parent", ",", "scope", ",", "state", ")", "{", "if", "(", "node", ".", "name", "===", "state", ".", "name", ")", "{", "state", ".", "deopted", "=", "true", ";", "}", "}" ]
Deopt on use of a binding identifier with the same name as our rest param. See https://github.com/babel/babel/issues/2091
[ "Deopt", "on", "use", "of", "a", "binding", "identifier", "with", "the", "same", "name", "as", "our", "rest", "param", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/transformation/transformers/es6/parameters/rest.js#L103-L107
40,223
briancsparks/aws-json
lib/cf/subnet.js
function(name, zoneLetter, cf, vpc, routeTable) { var self = this; self.isPublic = false; base.Base.call(this, cf, 'EC2::Subnet', name); self.addProperty('VpcId', vpc.ref()); self.zone = self.addProperty('AvailabilityZone', vpc.az(zoneLetter)); self.cidrBlock = function(cidr) { self.cidr = vpc.mkSubnetCidrBlock(cidr); return self.addProperty('CidrBlock', self.cidr); }; self.mapPublicIpOnLaunch = function(value) { if (arguments.length === 0) { value = true; } return self.addProperty('MapPublicIpOnLaunch', !!value); }; var assocName = name+'RouteTableAssociation'; cf.data.Resources[assocName] = subnet.makeSubnetRouteTableAssociation(assocName, cf, self, routeTable); //self.output(name+"CidrBlock", self.getAtt("CidrBlock"), "Subnet "+name+"CIDR block"); /* Do not know why CidrBlock is not available */ }
javascript
function(name, zoneLetter, cf, vpc, routeTable) { var self = this; self.isPublic = false; base.Base.call(this, cf, 'EC2::Subnet', name); self.addProperty('VpcId', vpc.ref()); self.zone = self.addProperty('AvailabilityZone', vpc.az(zoneLetter)); self.cidrBlock = function(cidr) { self.cidr = vpc.mkSubnetCidrBlock(cidr); return self.addProperty('CidrBlock', self.cidr); }; self.mapPublicIpOnLaunch = function(value) { if (arguments.length === 0) { value = true; } return self.addProperty('MapPublicIpOnLaunch', !!value); }; var assocName = name+'RouteTableAssociation'; cf.data.Resources[assocName] = subnet.makeSubnetRouteTableAssociation(assocName, cf, self, routeTable); //self.output(name+"CidrBlock", self.getAtt("CidrBlock"), "Subnet "+name+"CIDR block"); /* Do not know why CidrBlock is not available */ }
[ "function", "(", "name", ",", "zoneLetter", ",", "cf", ",", "vpc", ",", "routeTable", ")", "{", "var", "self", "=", "this", ";", "self", ".", "isPublic", "=", "false", ";", "base", ".", "Base", ".", "call", "(", "this", ",", "cf", ",", "'EC2::Subnet'", ",", "name", ")", ";", "self", ".", "addProperty", "(", "'VpcId'", ",", "vpc", ".", "ref", "(", ")", ")", ";", "self", ".", "zone", "=", "self", ".", "addProperty", "(", "'AvailabilityZone'", ",", "vpc", ".", "az", "(", "zoneLetter", ")", ")", ";", "self", ".", "cidrBlock", "=", "function", "(", "cidr", ")", "{", "self", ".", "cidr", "=", "vpc", ".", "mkSubnetCidrBlock", "(", "cidr", ")", ";", "return", "self", ".", "addProperty", "(", "'CidrBlock'", ",", "self", ".", "cidr", ")", ";", "}", ";", "self", ".", "mapPublicIpOnLaunch", "=", "function", "(", "value", ")", "{", "if", "(", "arguments", ".", "length", "===", "0", ")", "{", "value", "=", "true", ";", "}", "return", "self", ".", "addProperty", "(", "'MapPublicIpOnLaunch'", ",", "!", "!", "value", ")", ";", "}", ";", "var", "assocName", "=", "name", "+", "'RouteTableAssociation'", ";", "cf", ".", "data", ".", "Resources", "[", "assocName", "]", "=", "subnet", ".", "makeSubnetRouteTableAssociation", "(", "assocName", ",", "cf", ",", "self", ",", "routeTable", ")", ";", "//self.output(name+\"CidrBlock\", self.getAtt(\"CidrBlock\"), \"Subnet \"+name+\"CIDR block\"); /* Do not know why CidrBlock is not available */", "}" ]
Base for subnet class.
[ "Base", "for", "subnet", "class", "." ]
df224093d0d5018834625f7a6fa640773814a311
https://github.com/briancsparks/aws-json/blob/df224093d0d5018834625f7a6fa640773814a311/lib/cf/subnet.js#L13-L37
40,224
preceptorjs/taxi
lib/connection.js
stringifyStackTrace
function stringifyStackTrace (stackTrace) { var i, len, result = []; for (i = 0, len = stackTrace.length; i < len; i++) { if (stackTrace[i]) { result.push(stackTrace[i].methodName + "::" + stackTrace[i].className + " (" + stackTrace[i].fileName + ":" + stackTrace[i].lineNumber + ")"); } } return result.join("\n"); }
javascript
function stringifyStackTrace (stackTrace) { var i, len, result = []; for (i = 0, len = stackTrace.length; i < len; i++) { if (stackTrace[i]) { result.push(stackTrace[i].methodName + "::" + stackTrace[i].className + " (" + stackTrace[i].fileName + ":" + stackTrace[i].lineNumber + ")"); } } return result.join("\n"); }
[ "function", "stringifyStackTrace", "(", "stackTrace", ")", "{", "var", "i", ",", "len", ",", "result", "=", "[", "]", ";", "for", "(", "i", "=", "0", ",", "len", "=", "stackTrace", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "stackTrace", "[", "i", "]", ")", "{", "result", ".", "push", "(", "stackTrace", "[", "i", "]", ".", "methodName", "+", "\"::\"", "+", "stackTrace", "[", "i", "]", ".", "className", "+", "\" (\"", "+", "stackTrace", "[", "i", "]", ".", "fileName", "+", "\":\"", "+", "stackTrace", "[", "i", "]", ".", "lineNumber", "+", "\")\"", ")", ";", "}", "}", "return", "result", ".", "join", "(", "\"\\n\"", ")", ";", "}" ]
Turns a selenium stack-trace into a string @param {Array.<Object>} stackTrace @return {String}
[ "Turns", "a", "selenium", "stack", "-", "trace", "into", "a", "string" ]
96ab5a5c5fa9dc50f325ba4de52dd90009073ca3
https://github.com/preceptorjs/taxi/blob/96ab5a5c5fa9dc50f325ba4de52dd90009073ca3/lib/connection.js#L248-L259
40,225
preceptorjs/taxi
lib/connection.js
createInternalConnection
function createInternalConnection (mode) { var result; switch (mode) { case 'async': result = require('then-request'); break; case 'sync': result = require('sync-req'); break; default: throw new Error('Expected options.mode to be "async" or "sync" but got ' + JSON.stringify(mode)); } return result; }
javascript
function createInternalConnection (mode) { var result; switch (mode) { case 'async': result = require('then-request'); break; case 'sync': result = require('sync-req'); break; default: throw new Error('Expected options.mode to be "async" or "sync" but got ' + JSON.stringify(mode)); } return result; }
[ "function", "createInternalConnection", "(", "mode", ")", "{", "var", "result", ";", "switch", "(", "mode", ")", "{", "case", "'async'", ":", "result", "=", "require", "(", "'then-request'", ")", ";", "break", ";", "case", "'sync'", ":", "result", "=", "require", "(", "'sync-req'", ")", ";", "break", ";", "default", ":", "throw", "new", "Error", "(", "'Expected options.mode to be \"async\" or \"sync\" but got '", "+", "JSON", ".", "stringify", "(", "mode", ")", ")", ";", "}", "return", "result", ";", "}" ]
Create connection object according to mode-type @param {String} mode (async|sync) @return {function}
[ "Create", "connection", "object", "according", "to", "mode", "-", "type" ]
96ab5a5c5fa9dc50f325ba4de52dd90009073ca3
https://github.com/preceptorjs/taxi/blob/96ab5a5c5fa9dc50f325ba4de52dd90009073ca3/lib/connection.js#L267-L283
40,226
Dacrol/node-current-branch
get-branch.js
branch
function branch () { const headpath = path.join(process.cwd(), '.git/HEAD') if (!fs.existsSync(headpath)) { console.warn('No HEAD found, aborting.') return null } const headcontent = fs.readFileSync(headpath, 'utf8') const branchRegex = /ref: refs\/heads\/(\S+)/ const branchname = branchRegex.exec(headcontent) return branchname && branchname[1] }
javascript
function branch () { const headpath = path.join(process.cwd(), '.git/HEAD') if (!fs.existsSync(headpath)) { console.warn('No HEAD found, aborting.') return null } const headcontent = fs.readFileSync(headpath, 'utf8') const branchRegex = /ref: refs\/heads\/(\S+)/ const branchname = branchRegex.exec(headcontent) return branchname && branchname[1] }
[ "function", "branch", "(", ")", "{", "const", "headpath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "'.git/HEAD'", ")", "if", "(", "!", "fs", ".", "existsSync", "(", "headpath", ")", ")", "{", "console", ".", "warn", "(", "'No HEAD found, aborting.'", ")", "return", "null", "}", "const", "headcontent", "=", "fs", ".", "readFileSync", "(", "headpath", ",", "'utf8'", ")", "const", "branchRegex", "=", "/", "ref: refs\\/heads\\/(\\S+)", "/", "const", "branchname", "=", "branchRegex", ".", "exec", "(", "headcontent", ")", "return", "branchname", "&&", "branchname", "[", "1", "]", "}" ]
Gets the current branch. @returns {string} Branch name
[ "Gets", "the", "current", "branch", "." ]
d1f76052cce7800cd3aafbbde75d526753240dc7
https://github.com/Dacrol/node-current-branch/blob/d1f76052cce7800cd3aafbbde75d526753240dc7/get-branch.js#L9-L19
40,227
WASdev/lib.rtcomm.node
lib/RtcConnector.js
function(topic, message) { /* * so should a filter manage the last message it has? and give it an ID and store it... * to prevent duplicates... * or should this filter do it... * this shold just execute 1 filter -- NO more than 1. But if a topic matches * multiple filters then we need to call one filter and mark it dirty or something * * maybe save the lastMessage w/ a timestamp and if it matches, then skip it... * * given topic A that matches 2 filters so there will be 2 messages... * * * return number of matches... * * */ for( var key in myFilters) { if (myFilters.hasOwnProperty(key)) { myFilters[key].doFilter(topic,message) ; } } // count is how many times filter ran... }
javascript
function(topic, message) { /* * so should a filter manage the last message it has? and give it an ID and store it... * to prevent duplicates... * or should this filter do it... * this shold just execute 1 filter -- NO more than 1. But if a topic matches * multiple filters then we need to call one filter and mark it dirty or something * * maybe save the lastMessage w/ a timestamp and if it matches, then skip it... * * given topic A that matches 2 filters so there will be 2 messages... * * * return number of matches... * * */ for( var key in myFilters) { if (myFilters.hasOwnProperty(key)) { myFilters[key].doFilter(topic,message) ; } } // count is how many times filter ran... }
[ "function", "(", "topic", ",", "message", ")", "{", "/*\r\n * so should a filter manage the last message it has? and give it an ID and store it... \r\n * to prevent duplicates...\r\n * or should this filter do it...\r\n * this shold just execute 1 filter -- NO more than 1. But if a topic matches\r\n * multiple filters then we need to call one filter and mark it dirty or something\r\n *\r\n * maybe save the lastMessage w/ a timestamp and if it matches, then skip it... \r\n *\r\n * given topic A that matches 2 filters so there will be 2 messages... \r\n *\r\n *\r\n * return number of matches...\r\n * \r\n *\r\n */", "for", "(", "var", "key", "in", "myFilters", ")", "{", "if", "(", "myFilters", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "myFilters", "[", "key", "]", ".", "doFilter", "(", "topic", ",", "message", ")", ";", "}", "}", "// count is how many times filter ran... \r", "}" ]
doFilter - Execute the filter callbacks for the topic passed @private @param {String} topic Topic name to filter @param {String} message Message to pass
[ "doFilter", "-", "Execute", "the", "filter", "callbacks", "for", "the", "topic", "passed" ]
bac07b57862a0f3c14538a863ae9e76baed894f3
https://github.com/WASdev/lib.rtcomm.node/blob/bac07b57862a0f3c14538a863ae9e76baed894f3/lib/RtcConnector.js#L296-L320
40,228
WASdev/lib.rtcomm.node
lib/RtcConnector.js
function(config) { var em = new RtcConnector(config); var unique = (config && config.unique) ? true : false; l('DEBUG') && console.log('createRtcConnector() config is: ',config); var key = em.key = createKey(em.config.user||null, em.config.password || null, em.config.server || null, em.config.port || null, em.config.eventPath || 'rtcomm'); var mon = find(key); // Monitors not requesting to be UNIQUE. var umon = []; mon.forEach(function(m){ !m.unique && umon.push(m); }); if (unique || umon.length === 0) { rtcConnectors[em.id] = em; return em; } // return first nonunique that matched the key return umon[0] || null; }
javascript
function(config) { var em = new RtcConnector(config); var unique = (config && config.unique) ? true : false; l('DEBUG') && console.log('createRtcConnector() config is: ',config); var key = em.key = createKey(em.config.user||null, em.config.password || null, em.config.server || null, em.config.port || null, em.config.eventPath || 'rtcomm'); var mon = find(key); // Monitors not requesting to be UNIQUE. var umon = []; mon.forEach(function(m){ !m.unique && umon.push(m); }); if (unique || umon.length === 0) { rtcConnectors[em.id] = em; return em; } // return first nonunique that matched the key return umon[0] || null; }
[ "function", "(", "config", ")", "{", "var", "em", "=", "new", "RtcConnector", "(", "config", ")", ";", "var", "unique", "=", "(", "config", "&&", "config", ".", "unique", ")", "?", "true", ":", "false", ";", "l", "(", "'DEBUG'", ")", "&&", "console", ".", "log", "(", "'createRtcConnector() config is: '", ",", "config", ")", ";", "var", "key", "=", "em", ".", "key", "=", "createKey", "(", "em", ".", "config", ".", "user", "||", "null", ",", "em", ".", "config", ".", "password", "||", "null", ",", "em", ".", "config", ".", "server", "||", "null", ",", "em", ".", "config", ".", "port", "||", "null", ",", "em", ".", "config", ".", "eventPath", "||", "'rtcomm'", ")", ";", "var", "mon", "=", "find", "(", "key", ")", ";", "// Monitors not requesting to be UNIQUE.\r", "var", "umon", "=", "[", "]", ";", "mon", ".", "forEach", "(", "function", "(", "m", ")", "{", "!", "m", ".", "unique", "&&", "umon", ".", "push", "(", "m", ")", ";", "}", ")", ";", "if", "(", "unique", "||", "umon", ".", "length", "===", "0", ")", "{", "rtcConnectors", "[", "em", ".", "id", "]", "=", "em", ";", "return", "em", ";", "}", "// return first nonunique that matched the key\r", "return", "umon", "[", "0", "]", "||", "null", ";", "}" ]
Create an RtcConnector and add it to the rtcConnectors pool
[ "Create", "an", "RtcConnector", "and", "add", "it", "to", "the", "rtcConnectors", "pool" ]
bac07b57862a0f3c14538a863ae9e76baed894f3
https://github.com/WASdev/lib.rtcomm.node/blob/bac07b57862a0f3c14538a863ae9e76baed894f3/lib/RtcConnector.js#L441-L457
40,229
stezu/node-stream
lib/modifiers/stringify.js
stringify
function stringify() { return map(function (chunk, next) { var stringified; try { stringified = JSON.stringify(chunk); } catch (e) { return next(e); } return next(null, stringified); }); }
javascript
function stringify() { return map(function (chunk, next) { var stringified; try { stringified = JSON.stringify(chunk); } catch (e) { return next(e); } return next(null, stringified); }); }
[ "function", "stringify", "(", ")", "{", "return", "map", "(", "function", "(", "chunk", ",", "next", ")", "{", "var", "stringified", ";", "try", "{", "stringified", "=", "JSON", ".", "stringify", "(", "chunk", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "next", "(", "e", ")", ";", "}", "return", "next", "(", "null", ",", "stringified", ")", ";", "}", ")", ";", "}" ]
Creates a new stream where every element in the source stream is converted to a string by using `JSON.stringify`. @static @since 1.1.0 @category Modifiers @returns {Stream.Transform} - Transform stream. @example // stringify every element in an object stream so it can be // piped to a non-object stream. objStream .pipe(nodeStream.stringify()) .pipe(process.stdout);
[ "Creates", "a", "new", "stream", "where", "every", "element", "in", "the", "source", "stream", "is", "converted", "to", "a", "string", "by", "using", "JSON", ".", "stringify", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/modifiers/stringify.js#L21-L34
40,230
codius-deprecated/codius-engine
lib/crypto.js
deriveSecret
function deriveSecret(parent_secret, child_name, hash_algorithm) { if (!hash_algorithm) { hash_algorithm = 'sha512'; } return crypto.createHmac(hash_algorithm, parent_secret).update(child_name).digest('hex'); }
javascript
function deriveSecret(parent_secret, child_name, hash_algorithm) { if (!hash_algorithm) { hash_algorithm = 'sha512'; } return crypto.createHmac(hash_algorithm, parent_secret).update(child_name).digest('hex'); }
[ "function", "deriveSecret", "(", "parent_secret", ",", "child_name", ",", "hash_algorithm", ")", "{", "if", "(", "!", "hash_algorithm", ")", "{", "hash_algorithm", "=", "'sha512'", ";", "}", "return", "crypto", ".", "createHmac", "(", "hash_algorithm", ",", "parent_secret", ")", ".", "update", "(", "child_name", ")", ".", "digest", "(", "'hex'", ")", ";", "}" ]
Derive a "child" secret from a "parent" one using HMAC. @param {String} parent_secret @param {String} child_name @param {String} ['sha512'] hash_algorithm @returns {String} Note that the number of bits depends on the hash algorithm used
[ "Derive", "a", "child", "secret", "from", "a", "parent", "one", "using", "HMAC", "." ]
48aaea3d1a0dd2cf755a1905ff040e1667e8d131
https://github.com/codius-deprecated/codius-engine/blob/48aaea3d1a0dd2cf755a1905ff040e1667e8d131/lib/crypto.js#L44-L50
40,231
codius-deprecated/codius-engine
lib/crypto.js
deriveKeypair
function deriveKeypair(parent_secret, child_name, signature_scheme) { if (!signature_scheme) { signature_scheme = 'ec_secp256k1'; } var pair = {}; if (signature_scheme === 'ec_secp256k1') { pair.private = deriveSecret(parent_secret, child_name, 'sha256'); // If the private key is greater than the curve modulus we // use a counter to get a new random secret var modulus = new BigInteger(ecurve.getCurveByName('secp256k1').n, 16); var counter = 1; while (!pair.private || modulus.compareTo(pair.private) < 0) { pair.private = deriveSecret(parent_secret, child_name + '_' + counter, 'sha256'); counter += 1; } pair.public = new bitcoinjs.ECKey(new BigInteger(pair.private, 16), false).pub.toHex(); } else { throw new Error('Signature scheme: ' + signature_scheme + ' not currently supported'); } return pair; }
javascript
function deriveKeypair(parent_secret, child_name, signature_scheme) { if (!signature_scheme) { signature_scheme = 'ec_secp256k1'; } var pair = {}; if (signature_scheme === 'ec_secp256k1') { pair.private = deriveSecret(parent_secret, child_name, 'sha256'); // If the private key is greater than the curve modulus we // use a counter to get a new random secret var modulus = new BigInteger(ecurve.getCurveByName('secp256k1').n, 16); var counter = 1; while (!pair.private || modulus.compareTo(pair.private) < 0) { pair.private = deriveSecret(parent_secret, child_name + '_' + counter, 'sha256'); counter += 1; } pair.public = new bitcoinjs.ECKey(new BigInteger(pair.private, 16), false).pub.toHex(); } else { throw new Error('Signature scheme: ' + signature_scheme + ' not currently supported'); } return pair; }
[ "function", "deriveKeypair", "(", "parent_secret", ",", "child_name", ",", "signature_scheme", ")", "{", "if", "(", "!", "signature_scheme", ")", "{", "signature_scheme", "=", "'ec_secp256k1'", ";", "}", "var", "pair", "=", "{", "}", ";", "if", "(", "signature_scheme", "===", "'ec_secp256k1'", ")", "{", "pair", ".", "private", "=", "deriveSecret", "(", "parent_secret", ",", "child_name", ",", "'sha256'", ")", ";", "// If the private key is greater than the curve modulus we", "// use a counter to get a new random secret", "var", "modulus", "=", "new", "BigInteger", "(", "ecurve", ".", "getCurveByName", "(", "'secp256k1'", ")", ".", "n", ",", "16", ")", ";", "var", "counter", "=", "1", ";", "while", "(", "!", "pair", ".", "private", "||", "modulus", ".", "compareTo", "(", "pair", ".", "private", ")", "<", "0", ")", "{", "pair", ".", "private", "=", "deriveSecret", "(", "parent_secret", ",", "child_name", "+", "'_'", "+", "counter", ",", "'sha256'", ")", ";", "counter", "+=", "1", ";", "}", "pair", ".", "public", "=", "new", "bitcoinjs", ".", "ECKey", "(", "new", "BigInteger", "(", "pair", ".", "private", ",", "16", ")", ",", "false", ")", ".", "pub", ".", "toHex", "(", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Signature scheme: '", "+", "signature_scheme", "+", "' not currently supported'", ")", ";", "}", "return", "pair", ";", "}" ]
Derive a public and private key from a "parent" secret. @param {String} parent_secret @param {String} child_name @param {String} ['secp256k1'] signature_scheme @returns {Object} Object with "public" and "private" fields
[ "Derive", "a", "public", "and", "private", "key", "from", "a", "parent", "secret", "." ]
48aaea3d1a0dd2cf755a1905ff040e1667e8d131
https://github.com/codius-deprecated/codius-engine/blob/48aaea3d1a0dd2cf755a1905ff040e1667e8d131/lib/crypto.js#L61-L90
40,232
codius-deprecated/codius-engine
lib/crypto.js
sign
function sign(private_key, data) { var key = new bitcoinjs.ECKey(new BigInteger(private_key, 16), false); var hash = bitcoinjs.crypto.hash256(new Buffer(data, 'hex')); return key.sign(hash).toDER().toString('hex'); }
javascript
function sign(private_key, data) { var key = new bitcoinjs.ECKey(new BigInteger(private_key, 16), false); var hash = bitcoinjs.crypto.hash256(new Buffer(data, 'hex')); return key.sign(hash).toDER().toString('hex'); }
[ "function", "sign", "(", "private_key", ",", "data", ")", "{", "var", "key", "=", "new", "bitcoinjs", ".", "ECKey", "(", "new", "BigInteger", "(", "private_key", ",", "16", ")", ",", "false", ")", ";", "var", "hash", "=", "bitcoinjs", ".", "crypto", ".", "hash256", "(", "new", "Buffer", "(", "data", ",", "'hex'", ")", ")", ";", "return", "key", ".", "sign", "(", "hash", ")", ".", "toDER", "(", ")", ".", "toString", "(", "'hex'", ")", ";", "}" ]
Sign the given data ** For now assumes ec_secp256k1 ** @param {String} private_key Hex-encoded private key @param {String} data Hex-encoded data
[ "Sign", "the", "given", "data" ]
48aaea3d1a0dd2cf755a1905ff040e1667e8d131
https://github.com/codius-deprecated/codius-engine/blob/48aaea3d1a0dd2cf755a1905ff040e1667e8d131/lib/crypto.js#L100-L104
40,233
codius-deprecated/codius-engine
lib/crypto.js
verify
function verify(public_key, data, signature) { var pubkey = bitcoinjs.ECPubKey.fromHex(public_key); var hash = bitcoinjs.crypto.hash256(new Buffer(data, 'hex')); var ecsignature = bitcoinjs.ECSignature.fromDER(new Buffer(signature, 'hex')); return pubkey.verify(hash, ecsignature); }
javascript
function verify(public_key, data, signature) { var pubkey = bitcoinjs.ECPubKey.fromHex(public_key); var hash = bitcoinjs.crypto.hash256(new Buffer(data, 'hex')); var ecsignature = bitcoinjs.ECSignature.fromDER(new Buffer(signature, 'hex')); return pubkey.verify(hash, ecsignature); }
[ "function", "verify", "(", "public_key", ",", "data", ",", "signature", ")", "{", "var", "pubkey", "=", "bitcoinjs", ".", "ECPubKey", ".", "fromHex", "(", "public_key", ")", ";", "var", "hash", "=", "bitcoinjs", ".", "crypto", ".", "hash256", "(", "new", "Buffer", "(", "data", ",", "'hex'", ")", ")", ";", "var", "ecsignature", "=", "bitcoinjs", ".", "ECSignature", ".", "fromDER", "(", "new", "Buffer", "(", "signature", ",", "'hex'", ")", ")", ";", "return", "pubkey", ".", "verify", "(", "hash", ",", "ecsignature", ")", ";", "}" ]
Verify a signature on the given data ** For now assumes ec_secp256k1 ** @param {String} public_key Hex-encoded public key @param {String} data Hex-encoded data @param {String} signature Hex-encoded signature
[ "Verify", "a", "signature", "on", "the", "given", "data" ]
48aaea3d1a0dd2cf755a1905ff040e1667e8d131
https://github.com/codius-deprecated/codius-engine/blob/48aaea3d1a0dd2cf755a1905ff040e1667e8d131/lib/crypto.js#L115-L120
40,234
jonkemp/style-selector
index.js
getSpecificity
function getSpecificity(text, parsed) { var expressions = parsed || parse(text), spec = [ 0, 0, 0, 0 ], nots = [], i, expression, pseudos, p, ii, not, jj; for (i = 0; i < expressions.length; i++) { expression = expressions[i]; pseudos = expression.pseudos; // id awards a point in the second column if (expression.id) { spec[1]++; } // classes and attributes award a point each in the third column if (expression.attributes) { spec[2] += expression.attributes.length; } if (expression.classList) { spec[2] += expression.classList.length; } // tag awards a point in the fourth column if (expression.tag && expression.tag !== '*') { spec[3]++; } // pseudos award a point each in the fourth column if (pseudos) { spec[3] += pseudos.length; for (p = 0; p < pseudos.length; p++) { if (pseudos[p].key === 'not') { nots.push(pseudos[p].value); spec[3]--; } } } } for (ii = nots.length; ii--;) { not = getSpecificity(nots[ii]); for (jj = 4; jj--;) { spec[jj] += not[jj]; } } return spec; }
javascript
function getSpecificity(text, parsed) { var expressions = parsed || parse(text), spec = [ 0, 0, 0, 0 ], nots = [], i, expression, pseudos, p, ii, not, jj; for (i = 0; i < expressions.length; i++) { expression = expressions[i]; pseudos = expression.pseudos; // id awards a point in the second column if (expression.id) { spec[1]++; } // classes and attributes award a point each in the third column if (expression.attributes) { spec[2] += expression.attributes.length; } if (expression.classList) { spec[2] += expression.classList.length; } // tag awards a point in the fourth column if (expression.tag && expression.tag !== '*') { spec[3]++; } // pseudos award a point each in the fourth column if (pseudos) { spec[3] += pseudos.length; for (p = 0; p < pseudos.length; p++) { if (pseudos[p].key === 'not') { nots.push(pseudos[p].value); spec[3]--; } } } } for (ii = nots.length; ii--;) { not = getSpecificity(nots[ii]); for (jj = 4; jj--;) { spec[jj] += not[jj]; } } return spec; }
[ "function", "getSpecificity", "(", "text", ",", "parsed", ")", "{", "var", "expressions", "=", "parsed", "||", "parse", "(", "text", ")", ",", "spec", "=", "[", "0", ",", "0", ",", "0", ",", "0", "]", ",", "nots", "=", "[", "]", ",", "i", ",", "expression", ",", "pseudos", ",", "p", ",", "ii", ",", "not", ",", "jj", ";", "for", "(", "i", "=", "0", ";", "i", "<", "expressions", ".", "length", ";", "i", "++", ")", "{", "expression", "=", "expressions", "[", "i", "]", ";", "pseudos", "=", "expression", ".", "pseudos", ";", "// id awards a point in the second column", "if", "(", "expression", ".", "id", ")", "{", "spec", "[", "1", "]", "++", ";", "}", "// classes and attributes award a point each in the third column", "if", "(", "expression", ".", "attributes", ")", "{", "spec", "[", "2", "]", "+=", "expression", ".", "attributes", ".", "length", ";", "}", "if", "(", "expression", ".", "classList", ")", "{", "spec", "[", "2", "]", "+=", "expression", ".", "classList", ".", "length", ";", "}", "// tag awards a point in the fourth column", "if", "(", "expression", ".", "tag", "&&", "expression", ".", "tag", "!==", "'*'", ")", "{", "spec", "[", "3", "]", "++", ";", "}", "// pseudos award a point each in the fourth column", "if", "(", "pseudos", ")", "{", "spec", "[", "3", "]", "+=", "pseudos", ".", "length", ";", "for", "(", "p", "=", "0", ";", "p", "<", "pseudos", ".", "length", ";", "p", "++", ")", "{", "if", "(", "pseudos", "[", "p", "]", ".", "key", "===", "'not'", ")", "{", "nots", ".", "push", "(", "pseudos", "[", "p", "]", ".", "value", ")", ";", "spec", "[", "3", "]", "--", ";", "}", "}", "}", "}", "for", "(", "ii", "=", "nots", ".", "length", ";", "ii", "--", ";", ")", "{", "not", "=", "getSpecificity", "(", "nots", "[", "ii", "]", ")", ";", "for", "(", "jj", "=", "4", ";", "jj", "--", ";", ")", "{", "spec", "[", "jj", "]", "+=", "not", "[", "jj", "]", ";", "}", "}", "return", "spec", ";", "}" ]
Returns specificity based on selector text and tokens. @param {String} selector @param {Array} tokens @api private.
[ "Returns", "specificity", "based", "on", "selector", "text", "and", "tokens", "." ]
2d6ddc06ffdc0030f8814cb682a79f914baa4097
https://github.com/jonkemp/style-selector/blob/2d6ddc06ffdc0030f8814cb682a79f914baa4097/index.js#L32-L87
40,235
stezu/node-stream
lib/consumers/selectVersion.js
selectVersion
function selectVersion(v1, v2) { return function (firstParam) { // the v1 API took a stream as the first argument if (firstParam instanceof stream.Stream) { return v1.apply(v1, arguments); } // the v2 API returns a stream for piping return v2.apply(v2, arguments); }; }
javascript
function selectVersion(v1, v2) { return function (firstParam) { // the v1 API took a stream as the first argument if (firstParam instanceof stream.Stream) { return v1.apply(v1, arguments); } // the v2 API returns a stream for piping return v2.apply(v2, arguments); }; }
[ "function", "selectVersion", "(", "v1", ",", "v2", ")", "{", "return", "function", "(", "firstParam", ")", "{", "// the v1 API took a stream as the first argument", "if", "(", "firstParam", "instanceof", "stream", ".", "Stream", ")", "{", "return", "v1", ".", "apply", "(", "v1", ",", "arguments", ")", ";", "}", "// the v2 API returns a stream for piping", "return", "v2", ".", "apply", "(", "v2", ",", "arguments", ")", ";", "}", ";", "}" ]
Determines which version of the API should be used for the given input. If a stream is provided as the first argument use the v1 API, otherwise use the v2 API. @private @param {Function} v1 - Function to call for a v1 API signature. @param {Function} v2 - Function to call for a v2 API signature. @returns {Function} - Function which allows either signature.
[ "Determines", "which", "version", "of", "the", "API", "should", "be", "used", "for", "the", "given", "input", ".", "If", "a", "stream", "is", "provided", "as", "the", "first", "argument", "use", "the", "v1", "API", "otherwise", "use", "the", "v2", "API", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/consumers/selectVersion.js#L13-L25
40,236
CTRLLA/ctrllr
lib/util.js
evalPromise
function evalPromise(promise) { // wrap in `countdown` exports.countdown(promise, timeout) .then(function(resolvedValue) { deferred.resolve(resolvedValue); }).fail(function(err) { deferred.reject(err); }); }
javascript
function evalPromise(promise) { // wrap in `countdown` exports.countdown(promise, timeout) .then(function(resolvedValue) { deferred.resolve(resolvedValue); }).fail(function(err) { deferred.reject(err); }); }
[ "function", "evalPromise", "(", "promise", ")", "{", "// wrap in `countdown`", "exports", ".", "countdown", "(", "promise", ",", "timeout", ")", ".", "then", "(", "function", "(", "resolvedValue", ")", "{", "deferred", ".", "resolve", "(", "resolvedValue", ")", ";", "}", ")", ".", "fail", "(", "function", "(", "err", ")", "{", "deferred", ".", "reject", "(", "err", ")", ";", "}", ")", ";", "}" ]
waits for a promise, resolves deferred when resolved @param promise
[ "waits", "for", "a", "promise", "resolves", "deferred", "when", "resolved" ]
bf7a58de221dd8a083a2c72b7aa14d1f05c8d350
https://github.com/CTRLLA/ctrllr/blob/bf7a58de221dd8a083a2c72b7aa14d1f05c8d350/lib/util.js#L255-L263
40,237
aliaksandr-master/node-verifier
lib/verifier.js
function (rules) { if (!_.isArray(rules)) { rules = [ rules ]; } var that = this; return _.map(rules, function (rule) { if (typeof rule === 'string') { return that._parseString(rule); } if (_.isPlainObject(rule)) { return that._parseObject(rule); } throw new Error('#V1: invalid rule type, must be string or plain object'); }); }
javascript
function (rules) { if (!_.isArray(rules)) { rules = [ rules ]; } var that = this; return _.map(rules, function (rule) { if (typeof rule === 'string') { return that._parseString(rule); } if (_.isPlainObject(rule)) { return that._parseObject(rule); } throw new Error('#V1: invalid rule type, must be string or plain object'); }); }
[ "function", "(", "rules", ")", "{", "if", "(", "!", "_", ".", "isArray", "(", "rules", ")", ")", "{", "rules", "=", "[", "rules", "]", ";", "}", "var", "that", "=", "this", ";", "return", "_", ".", "map", "(", "rules", ",", "function", "(", "rule", ")", "{", "if", "(", "typeof", "rule", "===", "'string'", ")", "{", "return", "that", ".", "_parseString", "(", "rule", ")", ";", "}", "if", "(", "_", ".", "isPlainObject", "(", "rule", ")", ")", "{", "return", "that", ".", "_parseObject", "(", "rule", ")", ";", "}", "throw", "new", "Error", "(", "'#V1: invalid rule type, must be string or plain object'", ")", ";", "}", ")", ";", "}" ]
convert raw rules array to Rule array @method @param {Array|String} rules - rules for parsing @this Verifier @returns {Rule[]}
[ "convert", "raw", "rules", "array", "to", "Rule", "array" ]
bc6ae67004be0849476490be9a87ddac22c34c1f
https://github.com/aliaksandr-master/node-verifier/blob/bc6ae67004be0849476490be9a87ddac22c34c1f/lib/verifier.js#L52-L70
40,238
aliaksandr-master/node-verifier
lib/verifier.js
function (ruleStr) { var name; var params = ''; ruleStr.replace(this._RULE_STRING_FORMAT, function ($0, _name, _params) { name = _name; params = _params.trim(); }); params = params.length ? this._parseParamsString(params) : null; return Rule.create(name, params); }
javascript
function (ruleStr) { var name; var params = ''; ruleStr.replace(this._RULE_STRING_FORMAT, function ($0, _name, _params) { name = _name; params = _params.trim(); }); params = params.length ? this._parseParamsString(params) : null; return Rule.create(name, params); }
[ "function", "(", "ruleStr", ")", "{", "var", "name", ";", "var", "params", "=", "''", ";", "ruleStr", ".", "replace", "(", "this", ".", "_RULE_STRING_FORMAT", ",", "function", "(", "$0", ",", "_name", ",", "_params", ")", "{", "name", "=", "_name", ";", "params", "=", "_params", ".", "trim", "(", ")", ";", "}", ")", ";", "params", "=", "params", ".", "length", "?", "this", ".", "_parseParamsString", "(", "params", ")", ":", "null", ";", "return", "Rule", ".", "create", "(", "name", ",", "params", ")", ";", "}" ]
convert string to Rule object @private @method @param {String} ruleStr - string for parsing @returns {Rule}
[ "convert", "string", "to", "Rule", "object" ]
bc6ae67004be0849476490be9a87ddac22c34c1f
https://github.com/aliaksandr-master/node-verifier/blob/bc6ae67004be0849476490be9a87ddac22c34c1f/lib/verifier.js#L100-L112
40,239
aliaksandr-master/node-verifier
lib/verifier.js
function (jsonSource) { var json = null; try { json = JSON.parse(jsonSource); } catch (err) { json = jsonSource; // string } return json; }
javascript
function (jsonSource) { var json = null; try { json = JSON.parse(jsonSource); } catch (err) { json = jsonSource; // string } return json; }
[ "function", "(", "jsonSource", ")", "{", "var", "json", "=", "null", ";", "try", "{", "json", "=", "JSON", ".", "parse", "(", "jsonSource", ")", ";", "}", "catch", "(", "err", ")", "{", "json", "=", "jsonSource", ";", "// string", "}", "return", "json", ";", "}" ]
parse json params @private @method @param {String} jsonSource - json object for parsing @returns {*}
[ "parse", "json", "params" ]
bc6ae67004be0849476490be9a87ddac22c34c1f
https://github.com/aliaksandr-master/node-verifier/blob/bc6ae67004be0849476490be9a87ddac22c34c1f/lib/verifier.js#L122-L132
40,240
Prestaul/listen-up
index.js
eventData
function eventData(emitter) { return emitter[eventEmitter.EVENT_DATA_PROPERTY] || Object.defineProperty(emitter, eventEmitter.EVENT_DATA_PROPERTY, { value: {}, enumerable: false })[eventEmitter.EVENT_DATA_PROPERTY]; }
javascript
function eventData(emitter) { return emitter[eventEmitter.EVENT_DATA_PROPERTY] || Object.defineProperty(emitter, eventEmitter.EVENT_DATA_PROPERTY, { value: {}, enumerable: false })[eventEmitter.EVENT_DATA_PROPERTY]; }
[ "function", "eventData", "(", "emitter", ")", "{", "return", "emitter", "[", "eventEmitter", ".", "EVENT_DATA_PROPERTY", "]", "||", "Object", ".", "defineProperty", "(", "emitter", ",", "eventEmitter", ".", "EVENT_DATA_PROPERTY", ",", "{", "value", ":", "{", "}", ",", "enumerable", ":", "false", "}", ")", "[", "eventEmitter", ".", "EVENT_DATA_PROPERTY", "]", ";", "}" ]
Get event data from an emitter. Lazily create it if it isn't there.
[ "Get", "event", "data", "from", "an", "emitter", ".", "Lazily", "create", "it", "if", "it", "isn", "t", "there", "." ]
5ea9b8d97e7140e3a8c7e3ebb9d6f2a2407665b8
https://github.com/Prestaul/listen-up/blob/5ea9b8d97e7140e3a8c7e3ebb9d6f2a2407665b8/index.js#L49-L54
40,241
KTH/kth-node-redis
index.js
_createClient
function _createClient (name, options, callback) { const log = logger.child({ redis: name }) log.debug('Redis creating client: ' + name) let isReady = false const config = {} deepAssign(config, _defaults, options) let client = redis.createClient(config) callback = _once(callback) _clients[ name ] = client _clients[ name ].log = log log.debug({ clients: Object.keys(_clients) }, 'Redis clients') client.on('error', function (err) { log.error({ err: err }, 'Redis client error') callback(err) }) client.on('warning', function (err) { log.warn({ err: err }, 'Redis client warning') }) client.on('connect', function () { log.debug('Redis connected: ' + name) }) client.on('ready', function () { log.debug('Redis client ready: ' + name) log.debug({ config: config }, 'Redis client config') log.debug(`Redis server version: ${safeGet(() => client.server_info.redis_version)}`) isReady = true callback(null, client) }) client.on('reconnecting', function () { log.debug('Redis client reconnecting: ' + name) }) client.on('end', function () { log.debug('Redis client end: ' + name) // Close the connection before removing reference. client.quit() client = null delete _clients[ name ] log.debug({ clients: Object.keys(_clients) }, 'Redis clients: ' + _clients.length) if (!isReady) { callback(new Error('Done - Failed to connect to Redis')) } }) }
javascript
function _createClient (name, options, callback) { const log = logger.child({ redis: name }) log.debug('Redis creating client: ' + name) let isReady = false const config = {} deepAssign(config, _defaults, options) let client = redis.createClient(config) callback = _once(callback) _clients[ name ] = client _clients[ name ].log = log log.debug({ clients: Object.keys(_clients) }, 'Redis clients') client.on('error', function (err) { log.error({ err: err }, 'Redis client error') callback(err) }) client.on('warning', function (err) { log.warn({ err: err }, 'Redis client warning') }) client.on('connect', function () { log.debug('Redis connected: ' + name) }) client.on('ready', function () { log.debug('Redis client ready: ' + name) log.debug({ config: config }, 'Redis client config') log.debug(`Redis server version: ${safeGet(() => client.server_info.redis_version)}`) isReady = true callback(null, client) }) client.on('reconnecting', function () { log.debug('Redis client reconnecting: ' + name) }) client.on('end', function () { log.debug('Redis client end: ' + name) // Close the connection before removing reference. client.quit() client = null delete _clients[ name ] log.debug({ clients: Object.keys(_clients) }, 'Redis clients: ' + _clients.length) if (!isReady) { callback(new Error('Done - Failed to connect to Redis')) } }) }
[ "function", "_createClient", "(", "name", ",", "options", ",", "callback", ")", "{", "const", "log", "=", "logger", ".", "child", "(", "{", "redis", ":", "name", "}", ")", "log", ".", "debug", "(", "'Redis creating client: '", "+", "name", ")", "let", "isReady", "=", "false", "const", "config", "=", "{", "}", "deepAssign", "(", "config", ",", "_defaults", ",", "options", ")", "let", "client", "=", "redis", ".", "createClient", "(", "config", ")", "callback", "=", "_once", "(", "callback", ")", "_clients", "[", "name", "]", "=", "client", "_clients", "[", "name", "]", ".", "log", "=", "log", "log", ".", "debug", "(", "{", "clients", ":", "Object", ".", "keys", "(", "_clients", ")", "}", ",", "'Redis clients'", ")", "client", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "log", ".", "error", "(", "{", "err", ":", "err", "}", ",", "'Redis client error'", ")", "callback", "(", "err", ")", "}", ")", "client", ".", "on", "(", "'warning'", ",", "function", "(", "err", ")", "{", "log", ".", "warn", "(", "{", "err", ":", "err", "}", ",", "'Redis client warning'", ")", "}", ")", "client", ".", "on", "(", "'connect'", ",", "function", "(", ")", "{", "log", ".", "debug", "(", "'Redis connected: '", "+", "name", ")", "}", ")", "client", ".", "on", "(", "'ready'", ",", "function", "(", ")", "{", "log", ".", "debug", "(", "'Redis client ready: '", "+", "name", ")", "log", ".", "debug", "(", "{", "config", ":", "config", "}", ",", "'Redis client config'", ")", "log", ".", "debug", "(", "`", "${", "safeGet", "(", "(", ")", "=>", "client", ".", "server_info", ".", "redis_version", ")", "}", "`", ")", "isReady", "=", "true", "callback", "(", "null", ",", "client", ")", "}", ")", "client", ".", "on", "(", "'reconnecting'", ",", "function", "(", ")", "{", "log", ".", "debug", "(", "'Redis client reconnecting: '", "+", "name", ")", "}", ")", "client", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "log", ".", "debug", "(", "'Redis client end: '", "+", "name", ")", "// Close the connection before removing reference.", "client", ".", "quit", "(", ")", "client", "=", "null", "delete", "_clients", "[", "name", "]", "log", ".", "debug", "(", "{", "clients", ":", "Object", ".", "keys", "(", "_clients", ")", "}", ",", "'Redis clients: '", "+", "_clients", ".", "length", ")", "if", "(", "!", "isReady", ")", "{", "callback", "(", "new", "Error", "(", "'Done - Failed to connect to Redis'", ")", ")", "}", "}", ")", "}" ]
Creates a Redis client based on the given name and options. @param {*} name the given name for the Redis client. @param {*} options the given options for the Redis client. @param {*} callback
[ "Creates", "a", "Redis", "client", "based", "on", "the", "given", "name", "and", "options", "." ]
4eabee3a6447ac9f34ca6a378aac397359250ac6
https://github.com/KTH/kth-node-redis/blob/4eabee3a6447ac9f34ca6a378aac397359250ac6/index.js#L56-L107
40,242
epii-io/epii-node-html5
lib/AssetRef.js
getFileMIME
function getFileMIME(file) { var idx = file.lastIndexOf('.') var ext = idx > -1 ? file.slice(idx) : null if (ext) ext = ext.toLowerCase().substring(1) return MIMES[ext] || MIMES.txt }
javascript
function getFileMIME(file) { var idx = file.lastIndexOf('.') var ext = idx > -1 ? file.slice(idx) : null if (ext) ext = ext.toLowerCase().substring(1) return MIMES[ext] || MIMES.txt }
[ "function", "getFileMIME", "(", "file", ")", "{", "var", "idx", "=", "file", ".", "lastIndexOf", "(", "'.'", ")", "var", "ext", "=", "idx", ">", "-", "1", "?", "file", ".", "slice", "(", "idx", ")", ":", "null", "if", "(", "ext", ")", "ext", "=", "ext", ".", "toLowerCase", "(", ")", ".", "substring", "(", "1", ")", "return", "MIMES", "[", "ext", "]", "||", "MIMES", ".", "txt", "}" ]
get MIME by file name @param {String} file @return {String}
[ "get", "MIME", "by", "file", "name" ]
69ea36c2be19ac95536925fde4eab9f0e1b16151
https://github.com/epii-io/epii-node-html5/blob/69ea36c2be19ac95536925fde4eab9f0e1b16151/lib/AssetRef.js#L24-L29
40,243
Kaniwani/KanaWana
src/packages/kanawana/utils/isCharEnglishPunctuation.js
isCharEnglishPunctuation
function isCharEnglishPunctuation(char = '') { if (isEmpty(char)) return false; return ENGLISH_PUNCTUATION_RANGES.some(([start, end]) => isCharInRange(char, start, end)); }
javascript
function isCharEnglishPunctuation(char = '') { if (isEmpty(char)) return false; return ENGLISH_PUNCTUATION_RANGES.some(([start, end]) => isCharInRange(char, start, end)); }
[ "function", "isCharEnglishPunctuation", "(", "char", "=", "''", ")", "{", "if", "(", "isEmpty", "(", "char", ")", ")", "return", "false", ";", "return", "ENGLISH_PUNCTUATION_RANGES", ".", "some", "(", "(", "[", "start", ",", "end", "]", ")", "=>", "isCharInRange", "(", "char", ",", "start", ",", "end", ")", ")", ";", "}" ]
Tests a character. Returns true if the character is considered English punctuation. @param {String} char character string to test @return {Boolean}
[ "Tests", "a", "character", ".", "Returns", "true", "if", "the", "character", "is", "considered", "English", "punctuation", "." ]
7084d6c50e68023c225f663f994544f693ff8d3a
https://github.com/Kaniwani/KanaWana/blob/7084d6c50e68023c225f663f994544f693ff8d3a/src/packages/kanawana/utils/isCharEnglishPunctuation.js#L10-L13
40,244
theprotein/shortcss
lib/index.js
expand
function expand(property, value, recurse) { ASSERT(arguments.length, 'property argument is required'); if (arguments.length < 3) { if (typeof value === 'boolean') { recurse = value; value = undefined; } else { recurse = true; } } var undefvalue = typeof value === 'undefined'; return undefvalue? expandAsArray(property, recurse) : expandAsObject(property, value, recurse); }
javascript
function expand(property, value, recurse) { ASSERT(arguments.length, 'property argument is required'); if (arguments.length < 3) { if (typeof value === 'boolean') { recurse = value; value = undefined; } else { recurse = true; } } var undefvalue = typeof value === 'undefined'; return undefvalue? expandAsArray(property, recurse) : expandAsObject(property, value, recurse); }
[ "function", "expand", "(", "property", ",", "value", ",", "recurse", ")", "{", "ASSERT", "(", "arguments", ".", "length", ",", "'property argument is required'", ")", ";", "if", "(", "arguments", ".", "length", "<", "3", ")", "{", "if", "(", "typeof", "value", "===", "'boolean'", ")", "{", "recurse", "=", "value", ";", "value", "=", "undefined", ";", "}", "else", "{", "recurse", "=", "true", ";", "}", "}", "var", "undefvalue", "=", "typeof", "value", "===", "'undefined'", ";", "return", "undefvalue", "?", "expandAsArray", "(", "property", ",", "recurse", ")", ":", "expandAsObject", "(", "property", ",", "value", ",", "recurse", ")", ";", "}" ]
Expand a property to an array of parts or property and value to object @param {string} property @param {?string} value @param {?boolean} recurse @returns {Array|Object}
[ "Expand", "a", "property", "to", "an", "array", "of", "parts", "or", "property", "and", "value", "to", "object" ]
8c727536eca12479d3ef428058d27b6604750bb7
https://github.com/theprotein/shortcss/blob/8c727536eca12479d3ef428058d27b6604750bb7/lib/index.js#L16-L33
40,245
dominicbarnes/node-siren-writer
index.js
normalizeEntity
function normalizeEntity(base, input) { if (!input) return {}; var result = Object.assign(clone(input), { class: normalizeClass(input.class), properties: normalizeProperties(input.properties), entities: normalizeEntities(base, input.entities), links: normalizeLinks(base, input.links), actions: normalizeActions(base, input.actions), title: input.title }); // strip undefined values from the result return filter(result, function (v) { return typeof v !== 'undefined'; }); }
javascript
function normalizeEntity(base, input) { if (!input) return {}; var result = Object.assign(clone(input), { class: normalizeClass(input.class), properties: normalizeProperties(input.properties), entities: normalizeEntities(base, input.entities), links: normalizeLinks(base, input.links), actions: normalizeActions(base, input.actions), title: input.title }); // strip undefined values from the result return filter(result, function (v) { return typeof v !== 'undefined'; }); }
[ "function", "normalizeEntity", "(", "base", ",", "input", ")", "{", "if", "(", "!", "input", ")", "return", "{", "}", ";", "var", "result", "=", "Object", ".", "assign", "(", "clone", "(", "input", ")", ",", "{", "class", ":", "normalizeClass", "(", "input", ".", "class", ")", ",", "properties", ":", "normalizeProperties", "(", "input", ".", "properties", ")", ",", "entities", ":", "normalizeEntities", "(", "base", ",", "input", ".", "entities", ")", ",", "links", ":", "normalizeLinks", "(", "base", ",", "input", ".", "links", ")", ",", "actions", ":", "normalizeActions", "(", "base", ",", "input", ".", "actions", ")", ",", "title", ":", "input", ".", "title", "}", ")", ";", "// strip undefined values from the result", "return", "filter", "(", "result", ",", "function", "(", "v", ")", "{", "return", "typeof", "v", "!==", "'undefined'", ";", "}", ")", ";", "}" ]
Takes the `input` entity object and normalizes it into a valid siren object. @param {String} base The base URL for this API. @param {Object} input The entity object to normalize. @return {Object}
[ "Takes", "the", "input", "entity", "object", "and", "normalizes", "it", "into", "a", "valid", "siren", "object", "." ]
d00b6b32bc8a755c3ae98a6382790d348c7aaffa
https://github.com/dominicbarnes/node-siren-writer/blob/d00b6b32bc8a755c3ae98a6382790d348c7aaffa/index.js#L32-L48
40,246
dominicbarnes/node-siren-writer
index.js
normalizeRel
function normalizeRel(base, input) { if (!input) return; if (!Array.isArray(input)) input = [ input ]; return flatten(input).map(function (rel) { return rel in iana ? rel : url.resolve(base, rel); }); }
javascript
function normalizeRel(base, input) { if (!input) return; if (!Array.isArray(input)) input = [ input ]; return flatten(input).map(function (rel) { return rel in iana ? rel : url.resolve(base, rel); }); }
[ "function", "normalizeRel", "(", "base", ",", "input", ")", "{", "if", "(", "!", "input", ")", "return", ";", "if", "(", "!", "Array", ".", "isArray", "(", "input", ")", ")", "input", "=", "[", "input", "]", ";", "return", "flatten", "(", "input", ")", ".", "map", "(", "function", "(", "rel", ")", "{", "return", "rel", "in", "iana", "?", "rel", ":", "url", ".", "resolve", "(", "base", ",", "rel", ")", ";", "}", ")", ";", "}" ]
Takes the `input` rel value and normalizes it into a valid array. @param {String} base The base URL for this API. @param {Mixed} input The rel value to normalize. @return {Array}
[ "Takes", "the", "input", "rel", "value", "and", "normalizes", "it", "into", "a", "valid", "array", "." ]
d00b6b32bc8a755c3ae98a6382790d348c7aaffa
https://github.com/dominicbarnes/node-siren-writer/blob/d00b6b32bc8a755c3ae98a6382790d348c7aaffa/index.js#L57-L64
40,247
dominicbarnes/node-siren-writer
index.js
normalizeProperties
function normalizeProperties(input) { if (!input) return; if (Array.isArray(input)) { return flatten(input).reduce(function (acc, o) { return Object.assign(acc, o); }, {}); } return clone(input); }
javascript
function normalizeProperties(input) { if (!input) return; if (Array.isArray(input)) { return flatten(input).reduce(function (acc, o) { return Object.assign(acc, o); }, {}); } return clone(input); }
[ "function", "normalizeProperties", "(", "input", ")", "{", "if", "(", "!", "input", ")", "return", ";", "if", "(", "Array", ".", "isArray", "(", "input", ")", ")", "{", "return", "flatten", "(", "input", ")", ".", "reduce", "(", "function", "(", "acc", ",", "o", ")", "{", "return", "Object", ".", "assign", "(", "acc", ",", "o", ")", ";", "}", ",", "{", "}", ")", ";", "}", "return", "clone", "(", "input", ")", ";", "}" ]
Takes the `input` properties value and normalizes it into a single object. @param {Mixed} input The properties value to normalize. @return {Object}
[ "Takes", "the", "input", "properties", "value", "and", "normalizes", "it", "into", "a", "single", "object", "." ]
d00b6b32bc8a755c3ae98a6382790d348c7aaffa
https://github.com/dominicbarnes/node-siren-writer/blob/d00b6b32bc8a755c3ae98a6382790d348c7aaffa/index.js#L95-L105
40,248
dominicbarnes/node-siren-writer
index.js
normalizeEntities
function normalizeEntities(base, input) { if (!input) return; if (!Array.isArray(input)) input = [ input ]; return flatten(input).filter(Boolean).map(function (entity) { assert(entity.rel, 'sub-entities must have a rel'); var ret = normalizeEntity(base, entity); ret.rel = normalizeRel(base, entity.rel); if (entity.href) ret.href = normalizeHref(base, entity.href); return ret; }); }
javascript
function normalizeEntities(base, input) { if (!input) return; if (!Array.isArray(input)) input = [ input ]; return flatten(input).filter(Boolean).map(function (entity) { assert(entity.rel, 'sub-entities must have a rel'); var ret = normalizeEntity(base, entity); ret.rel = normalizeRel(base, entity.rel); if (entity.href) ret.href = normalizeHref(base, entity.href); return ret; }); }
[ "function", "normalizeEntities", "(", "base", ",", "input", ")", "{", "if", "(", "!", "input", ")", "return", ";", "if", "(", "!", "Array", ".", "isArray", "(", "input", ")", ")", "input", "=", "[", "input", "]", ";", "return", "flatten", "(", "input", ")", ".", "filter", "(", "Boolean", ")", ".", "map", "(", "function", "(", "entity", ")", "{", "assert", "(", "entity", ".", "rel", ",", "'sub-entities must have a rel'", ")", ";", "var", "ret", "=", "normalizeEntity", "(", "base", ",", "entity", ")", ";", "ret", ".", "rel", "=", "normalizeRel", "(", "base", ",", "entity", ".", "rel", ")", ";", "if", "(", "entity", ".", "href", ")", "ret", ".", "href", "=", "normalizeHref", "(", "base", ",", "entity", ".", "href", ")", ";", "return", "ret", ";", "}", ")", ";", "}" ]
Takes the `input` entities value and normalizes it into a single array. @param {String} base The base URL for this API. @param {Mixed} input The entities value to normalize. @return {Array}
[ "Takes", "the", "input", "entities", "value", "and", "normalizes", "it", "into", "a", "single", "array", "." ]
d00b6b32bc8a755c3ae98a6382790d348c7aaffa
https://github.com/dominicbarnes/node-siren-writer/blob/d00b6b32bc8a755c3ae98a6382790d348c7aaffa/index.js#L114-L127
40,249
dominicbarnes/node-siren-writer
index.js
normalizeLinks
function normalizeLinks(base, input) { if (!input) return; if (!Array.isArray(input)) input = [ input ]; return flatten(input).filter(Boolean).map(function (link) { return normalizeLink(base, link); }); }
javascript
function normalizeLinks(base, input) { if (!input) return; if (!Array.isArray(input)) input = [ input ]; return flatten(input).filter(Boolean).map(function (link) { return normalizeLink(base, link); }); }
[ "function", "normalizeLinks", "(", "base", ",", "input", ")", "{", "if", "(", "!", "input", ")", "return", ";", "if", "(", "!", "Array", ".", "isArray", "(", "input", ")", ")", "input", "=", "[", "input", "]", ";", "return", "flatten", "(", "input", ")", ".", "filter", "(", "Boolean", ")", ".", "map", "(", "function", "(", "link", ")", "{", "return", "normalizeLink", "(", "base", ",", "link", ")", ";", "}", ")", ";", "}" ]
Takes the `input` links value and normalizes it into a single array. @param {String} base The base URL for this API. @param {Object} input The links value to normalize. @return {Array}
[ "Takes", "the", "input", "links", "value", "and", "normalizes", "it", "into", "a", "single", "array", "." ]
d00b6b32bc8a755c3ae98a6382790d348c7aaffa
https://github.com/dominicbarnes/node-siren-writer/blob/d00b6b32bc8a755c3ae98a6382790d348c7aaffa/index.js#L158-L165
40,250
dominicbarnes/node-siren-writer
index.js
normalizeAction
function normalizeAction(base, input) { assert(input.name, 'actions must have a name'); assert(input.href, 'actions must have an href'); var ret = clone(input); ret.href = normalizeHref(base, input.href); if (input.method) ret.method = normalizeMethod(input.method); var cls = normalizeClass(input.class); if (cls) ret.class = cls; var fields = normalizeFields(input.fields); if (fields) ret.fields = fields; return ret; }
javascript
function normalizeAction(base, input) { assert(input.name, 'actions must have a name'); assert(input.href, 'actions must have an href'); var ret = clone(input); ret.href = normalizeHref(base, input.href); if (input.method) ret.method = normalizeMethod(input.method); var cls = normalizeClass(input.class); if (cls) ret.class = cls; var fields = normalizeFields(input.fields); if (fields) ret.fields = fields; return ret; }
[ "function", "normalizeAction", "(", "base", ",", "input", ")", "{", "assert", "(", "input", ".", "name", ",", "'actions must have a name'", ")", ";", "assert", "(", "input", ".", "href", ",", "'actions must have an href'", ")", ";", "var", "ret", "=", "clone", "(", "input", ")", ";", "ret", ".", "href", "=", "normalizeHref", "(", "base", ",", "input", ".", "href", ")", ";", "if", "(", "input", ".", "method", ")", "ret", ".", "method", "=", "normalizeMethod", "(", "input", ".", "method", ")", ";", "var", "cls", "=", "normalizeClass", "(", "input", ".", "class", ")", ";", "if", "(", "cls", ")", "ret", ".", "class", "=", "cls", ";", "var", "fields", "=", "normalizeFields", "(", "input", ".", "fields", ")", ";", "if", "(", "fields", ")", "ret", ".", "fields", "=", "fields", ";", "return", "ret", ";", "}" ]
Takes the `input` action value and normalizes it into a single object. @param {String} base The base URL for this API. @param {Object} input The action value to normalize. @return {Object}
[ "Takes", "the", "input", "action", "value", "and", "normalizes", "it", "into", "a", "single", "object", "." ]
d00b6b32bc8a755c3ae98a6382790d348c7aaffa
https://github.com/dominicbarnes/node-siren-writer/blob/d00b6b32bc8a755c3ae98a6382790d348c7aaffa/index.js#L185-L201
40,251
dominicbarnes/node-siren-writer
index.js
normalizeActions
function normalizeActions(base, input) { if (!input) return; if (!Array.isArray(input)) input = [ input ]; return flatten(input).filter(Boolean).map(function (action) { return normalizeAction(base, action); }); }
javascript
function normalizeActions(base, input) { if (!input) return; if (!Array.isArray(input)) input = [ input ]; return flatten(input).filter(Boolean).map(function (action) { return normalizeAction(base, action); }); }
[ "function", "normalizeActions", "(", "base", ",", "input", ")", "{", "if", "(", "!", "input", ")", "return", ";", "if", "(", "!", "Array", ".", "isArray", "(", "input", ")", ")", "input", "=", "[", "input", "]", ";", "return", "flatten", "(", "input", ")", ".", "filter", "(", "Boolean", ")", ".", "map", "(", "function", "(", "action", ")", "{", "return", "normalizeAction", "(", "base", ",", "action", ")", ";", "}", ")", ";", "}" ]
Takes the `input` actions value and normalizes it into a single array. @param {String} base The base URL for this API. @param {Mixed} input The links value to normalize. @return {Array}
[ "Takes", "the", "input", "actions", "value", "and", "normalizes", "it", "into", "a", "single", "array", "." ]
d00b6b32bc8a755c3ae98a6382790d348c7aaffa
https://github.com/dominicbarnes/node-siren-writer/blob/d00b6b32bc8a755c3ae98a6382790d348c7aaffa/index.js#L210-L217
40,252
dominicbarnes/node-siren-writer
index.js
normalizeFields
function normalizeFields(input) { if (!input) return; if (!Array.isArray(input)) input = [ input ]; return flatten(input).filter(Boolean).map(normalizeField); }
javascript
function normalizeFields(input) { if (!input) return; if (!Array.isArray(input)) input = [ input ]; return flatten(input).filter(Boolean).map(normalizeField); }
[ "function", "normalizeFields", "(", "input", ")", "{", "if", "(", "!", "input", ")", "return", ";", "if", "(", "!", "Array", ".", "isArray", "(", "input", ")", ")", "input", "=", "[", "input", "]", ";", "return", "flatten", "(", "input", ")", ".", "filter", "(", "Boolean", ")", ".", "map", "(", "normalizeField", ")", ";", "}" ]
Takes the `input` fields value and normalizes it into a single array. @param {Mixed} input The links value to normalize. @return {Array}
[ "Takes", "the", "input", "fields", "value", "and", "normalizes", "it", "into", "a", "single", "array", "." ]
d00b6b32bc8a755c3ae98a6382790d348c7aaffa
https://github.com/dominicbarnes/node-siren-writer/blob/d00b6b32bc8a755c3ae98a6382790d348c7aaffa/index.js#L242-L247
40,253
EikosPartners/scalejs
dist/scalejs.core.js
registerExtension
function registerExtension(extension) { try { var ext; // Actual extension if (is(extension, 'buildCore', 'function')) { // If extension has buildCore function then give it an instance of the core. extension.buildCore(self); addOne(extensions, extension); return; // No need to extend as that will be handled in buildCore } if (is(extension, 'function')) { // If extension is a function then give it an instance of the core. ext = extension(self); } else if (has(extension, 'core')) { // If extension has `core` property then extend core with it. ext = extension.core; } else { // Otherwise extend core with the extension itself. ext = extension; } if (ext) { extend(self, ext); addOne(extensions, extension); } } catch (ex) { error('Fatal error during application initialization. ', 'Failed to build core with extension "', extension, 'See following exception for more details.', ex); } return extension; }
javascript
function registerExtension(extension) { try { var ext; // Actual extension if (is(extension, 'buildCore', 'function')) { // If extension has buildCore function then give it an instance of the core. extension.buildCore(self); addOne(extensions, extension); return; // No need to extend as that will be handled in buildCore } if (is(extension, 'function')) { // If extension is a function then give it an instance of the core. ext = extension(self); } else if (has(extension, 'core')) { // If extension has `core` property then extend core with it. ext = extension.core; } else { // Otherwise extend core with the extension itself. ext = extension; } if (ext) { extend(self, ext); addOne(extensions, extension); } } catch (ex) { error('Fatal error during application initialization. ', 'Failed to build core with extension "', extension, 'See following exception for more details.', ex); } return extension; }
[ "function", "registerExtension", "(", "extension", ")", "{", "try", "{", "var", "ext", ";", "// Actual extension", "if", "(", "is", "(", "extension", ",", "'buildCore'", ",", "'function'", ")", ")", "{", "// If extension has buildCore function then give it an instance of the core.", "extension", ".", "buildCore", "(", "self", ")", ";", "addOne", "(", "extensions", ",", "extension", ")", ";", "return", ";", "// No need to extend as that will be handled in buildCore", "}", "if", "(", "is", "(", "extension", ",", "'function'", ")", ")", "{", "// If extension is a function then give it an instance of the core.", "ext", "=", "extension", "(", "self", ")", ";", "}", "else", "if", "(", "has", "(", "extension", ",", "'core'", ")", ")", "{", "// If extension has `core` property then extend core with it.", "ext", "=", "extension", ".", "core", ";", "}", "else", "{", "// Otherwise extend core with the extension itself.", "ext", "=", "extension", ";", "}", "if", "(", "ext", ")", "{", "extend", "(", "self", ",", "ext", ")", ";", "addOne", "(", "extensions", ",", "extension", ")", ";", "}", "}", "catch", "(", "ex", ")", "{", "error", "(", "'Fatal error during application initialization. '", ",", "'Failed to build core with extension \"'", ",", "extension", ",", "'See following exception for more details.'", ",", "ex", ")", ";", "}", "return", "extension", ";", "}" ]
Registers an extension to the sandbox @param {Function|Object} extension function to create the extension or object representing the extension @memberOf core Provides core functionality of scalejs @namespace scalejs.core @module core /*global define
[ "Registers", "an", "extension", "to", "the", "sandbox" ]
115d0eac1a90aebb54f50485ed92de25165f9c30
https://github.com/EikosPartners/scalejs/blob/115d0eac1a90aebb54f50485ed92de25165f9c30/dist/scalejs.core.js#L71-L102
40,254
EikosPartners/scalejs
dist/scalejs.core.js
buildSandbox
function buildSandbox(id) { if (!has(id)) { throw new Error('Sandbox name is required to build a sandbox.'); } // Create module instance specific sandbox var sandbox = { type: self.type, object: self.object, array: self.array, log: self.log }; // Add extensions to sandbox extensions.forEach(function (extension) { try { // If extension has buildSandbox method use it to build sandbox if (is(extension, 'buildSandbox', 'function')) { extension.buildSandbox(sandbox); } // If extension has a sandbox object add it else if (has(extension, 'sandbox')) { extend(sandbox, extension.sandbox); } // Otherwise extend the sandbox with the extension else { extend(sandbox, extension); } } catch (ex) { error('Fatal error during application initialization. ', 'Failed to build sandbox with extension "', extension, 'See following exception for more details.', ex); throw ex; } }); return sandbox; }
javascript
function buildSandbox(id) { if (!has(id)) { throw new Error('Sandbox name is required to build a sandbox.'); } // Create module instance specific sandbox var sandbox = { type: self.type, object: self.object, array: self.array, log: self.log }; // Add extensions to sandbox extensions.forEach(function (extension) { try { // If extension has buildSandbox method use it to build sandbox if (is(extension, 'buildSandbox', 'function')) { extension.buildSandbox(sandbox); } // If extension has a sandbox object add it else if (has(extension, 'sandbox')) { extend(sandbox, extension.sandbox); } // Otherwise extend the sandbox with the extension else { extend(sandbox, extension); } } catch (ex) { error('Fatal error during application initialization. ', 'Failed to build sandbox with extension "', extension, 'See following exception for more details.', ex); throw ex; } }); return sandbox; }
[ "function", "buildSandbox", "(", "id", ")", "{", "if", "(", "!", "has", "(", "id", ")", ")", "{", "throw", "new", "Error", "(", "'Sandbox name is required to build a sandbox.'", ")", ";", "}", "// Create module instance specific sandbox", "var", "sandbox", "=", "{", "type", ":", "self", ".", "type", ",", "object", ":", "self", ".", "object", ",", "array", ":", "self", ".", "array", ",", "log", ":", "self", ".", "log", "}", ";", "// Add extensions to sandbox", "extensions", ".", "forEach", "(", "function", "(", "extension", ")", "{", "try", "{", "// If extension has buildSandbox method use it to build sandbox", "if", "(", "is", "(", "extension", ",", "'buildSandbox'", ",", "'function'", ")", ")", "{", "extension", ".", "buildSandbox", "(", "sandbox", ")", ";", "}", "// If extension has a sandbox object add it", "else", "if", "(", "has", "(", "extension", ",", "'sandbox'", ")", ")", "{", "extend", "(", "sandbox", ",", "extension", ".", "sandbox", ")", ";", "}", "// Otherwise extend the sandbox with the extension", "else", "{", "extend", "(", "sandbox", ",", "extension", ")", ";", "}", "}", "catch", "(", "ex", ")", "{", "error", "(", "'Fatal error during application initialization. '", ",", "'Failed to build sandbox with extension \"'", ",", "extension", ",", "'See following exception for more details.'", ",", "ex", ")", ";", "throw", "ex", ";", "}", "}", ")", ";", "return", "sandbox", ";", "}" ]
Builds a sandbox from the current list of extensions @param {String} id identifier for the sandbox @memberOf core @return {Object} object representing the built sandbox
[ "Builds", "a", "sandbox", "from", "the", "current", "list", "of", "extensions" ]
115d0eac1a90aebb54f50485ed92de25165f9c30
https://github.com/EikosPartners/scalejs/blob/115d0eac1a90aebb54f50485ed92de25165f9c30/dist/scalejs.core.js#L111-L149
40,255
Maples7/express-final-response
lib/index.js
handleErrorRequest
function handleErrorRequest(result, req, res) { const err = _.isError(result.msg) ? result.msg : result; const finalResp = STATUSES[result.status] || STATUSES[err.message] || STATUSES['error']; finalResp.msg = err.message; if (isDebug) finalResp.ext = err; logRequestError(err, req, finalResp); res.status(finalResp.statusCode); const view = result.view || errorView; if (view) { returnHTML(view, finalResp, res); } else { returnJSON(finalResp, res); } }
javascript
function handleErrorRequest(result, req, res) { const err = _.isError(result.msg) ? result.msg : result; const finalResp = STATUSES[result.status] || STATUSES[err.message] || STATUSES['error']; finalResp.msg = err.message; if (isDebug) finalResp.ext = err; logRequestError(err, req, finalResp); res.status(finalResp.statusCode); const view = result.view || errorView; if (view) { returnHTML(view, finalResp, res); } else { returnJSON(finalResp, res); } }
[ "function", "handleErrorRequest", "(", "result", ",", "req", ",", "res", ")", "{", "const", "err", "=", "_", ".", "isError", "(", "result", ".", "msg", ")", "?", "result", ".", "msg", ":", "result", ";", "const", "finalResp", "=", "STATUSES", "[", "result", ".", "status", "]", "||", "STATUSES", "[", "err", ".", "message", "]", "||", "STATUSES", "[", "'error'", "]", ";", "finalResp", ".", "msg", "=", "err", ".", "message", ";", "if", "(", "isDebug", ")", "finalResp", ".", "ext", "=", "err", ";", "logRequestError", "(", "err", ",", "req", ",", "finalResp", ")", ";", "res", ".", "status", "(", "finalResp", ".", "statusCode", ")", ";", "const", "view", "=", "result", ".", "view", "||", "errorView", ";", "if", "(", "view", ")", "{", "returnHTML", "(", "view", ",", "finalResp", ",", "res", ")", ";", "}", "else", "{", "returnJSON", "(", "finalResp", ",", "res", ")", ";", "}", "}" ]
handle result according to its type
[ "handle", "result", "according", "to", "its", "type" ]
fd4d413ba5254adc9bfa86ed4ee204374d5573a8
https://github.com/Maples7/express-final-response/blob/fd4d413ba5254adc9bfa86ed4ee204374d5573a8/lib/index.js#L84-L99
40,256
miniplug/plug-login
src/index.js
json
function json (opts) { return { ...opts, headers: { ...opts.headers, 'content-type': 'application/json' }, body: JSON.stringify(opts.body) } }
javascript
function json (opts) { return { ...opts, headers: { ...opts.headers, 'content-type': 'application/json' }, body: JSON.stringify(opts.body) } }
[ "function", "json", "(", "opts", ")", "{", "return", "{", "...", "opts", ",", "headers", ":", "{", "...", "opts", ".", "headers", ",", "'content-type'", ":", "'application/json'", "}", ",", "body", ":", "JSON", ".", "stringify", "(", "opts", ".", "body", ")", "}", "}" ]
Enhance a `fetch` options object to use a JSON body when sending data.
[ "Enhance", "a", "fetch", "options", "object", "to", "use", "a", "JSON", "body", "when", "sending", "data", "." ]
6568bca8daaabc385dce92d7e86086ae1c6a5b79
https://github.com/miniplug/plug-login/blob/6568bca8daaabc385dce92d7e86086ae1c6a5b79/src/index.js#L8-L17
40,257
miniplug/plug-login
src/index.js
error
function error (response, status, message) { let e = new Error(`${status}: ${message}`) e.response = response e.status = status return e }
javascript
function error (response, status, message) { let e = new Error(`${status}: ${message}`) e.response = response e.status = status return e }
[ "function", "error", "(", "response", ",", "status", ",", "message", ")", "{", "let", "e", "=", "new", "Error", "(", "`", "${", "status", "}", "${", "message", "}", "`", ")", "e", ".", "response", "=", "response", "e", ".", "status", "=", "status", "return", "e", "}" ]
Create an HTTP response error.
[ "Create", "an", "HTTP", "response", "error", "." ]
6568bca8daaabc385dce92d7e86086ae1c6a5b79
https://github.com/miniplug/plug-login/blob/6568bca8daaabc385dce92d7e86086ae1c6a5b79/src/index.js#L20-L25
40,258
miniplug/plug-login
src/index.js
getJSON
function getJSON (response) { return response.json().then((body) => { if (body.status !== 'ok') { throw error(response, body.status, body.data[0]) } return body }) }
javascript
function getJSON (response) { return response.json().then((body) => { if (body.status !== 'ok') { throw error(response, body.status, body.data[0]) } return body }) }
[ "function", "getJSON", "(", "response", ")", "{", "return", "response", ".", "json", "(", ")", ".", "then", "(", "(", "body", ")", "=>", "{", "if", "(", "body", ".", "status", "!==", "'ok'", ")", "{", "throw", "error", "(", "response", ",", "body", ".", "status", ",", "body", ".", "data", "[", "0", "]", ")", "}", "return", "body", "}", ")", "}" ]
Get the JSON response from the plug.dj API, throwing if it is an error response.
[ "Get", "the", "JSON", "response", "from", "the", "plug", ".", "dj", "API", "throwing", "if", "it", "is", "an", "error", "response", "." ]
6568bca8daaabc385dce92d7e86086ae1c6a5b79
https://github.com/miniplug/plug-login/blob/6568bca8daaabc385dce92d7e86086ae1c6a5b79/src/index.js#L28-L35
40,259
miniplug/plug-login
src/index.js
getSessionCookie
function getSessionCookie (headers) { if (!headers) return const cookie = parse(headers) if (cookie.session) return cookie.session }
javascript
function getSessionCookie (headers) { if (!headers) return const cookie = parse(headers) if (cookie.session) return cookie.session }
[ "function", "getSessionCookie", "(", "headers", ")", "{", "if", "(", "!", "headers", ")", "return", "const", "cookie", "=", "parse", "(", "headers", ")", "if", "(", "cookie", ".", "session", ")", "return", "cookie", ".", "session", "}" ]
Extract the session cookie value from an array of set-cookie headers.
[ "Extract", "the", "session", "cookie", "value", "from", "an", "array", "of", "set", "-", "cookie", "headers", "." ]
6568bca8daaabc385dce92d7e86086ae1c6a5b79
https://github.com/miniplug/plug-login/blob/6568bca8daaabc385dce92d7e86086ae1c6a5b79/src/index.js#L38-L42
40,260
miniplug/plug-login
src/index.js
getCsrf
function getCsrf (opts) { // for testing if (opts._simulateMaintenance) { return new Promise((resolve, reject) => { setTimeout(() => { reject(new Error('Could not find CSRF token')) }, 300) }) } return fetch(`${opts.host}/_/mobile/init`, json(opts)) .then((response) => props({ csrf: getJSON(response).then((body) => body.data[0].c), session: getSessionCookie(response.headers.get('set-cookie')) })) }
javascript
function getCsrf (opts) { // for testing if (opts._simulateMaintenance) { return new Promise((resolve, reject) => { setTimeout(() => { reject(new Error('Could not find CSRF token')) }, 300) }) } return fetch(`${opts.host}/_/mobile/init`, json(opts)) .then((response) => props({ csrf: getJSON(response).then((body) => body.data[0].c), session: getSessionCookie(response.headers.get('set-cookie')) })) }
[ "function", "getCsrf", "(", "opts", ")", "{", "// for testing", "if", "(", "opts", ".", "_simulateMaintenance", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "setTimeout", "(", "(", ")", "=>", "{", "reject", "(", "new", "Error", "(", "'Could not find CSRF token'", ")", ")", "}", ",", "300", ")", "}", ")", "}", "return", "fetch", "(", "`", "${", "opts", ".", "host", "}", "`", ",", "json", "(", "opts", ")", ")", ".", "then", "(", "(", "response", ")", "=>", "props", "(", "{", "csrf", ":", "getJSON", "(", "response", ")", ".", "then", "(", "(", "body", ")", "=>", "body", ".", "data", "[", "0", "]", ".", "c", ")", ",", "session", ":", "getSessionCookie", "(", "response", ".", "headers", ".", "get", "(", "'set-cookie'", ")", ")", "}", ")", ")", "}" ]
Get a CSRF token and session cookie for logging into plug.dj from their main page. Without the CSRF token, login requests will be rejected.
[ "Get", "a", "CSRF", "token", "and", "session", "cookie", "for", "logging", "into", "plug", ".", "dj", "from", "their", "main", "page", ".", "Without", "the", "CSRF", "token", "login", "requests", "will", "be", "rejected", "." ]
6568bca8daaabc385dce92d7e86086ae1c6a5b79
https://github.com/miniplug/plug-login/blob/6568bca8daaabc385dce92d7e86086ae1c6a5b79/src/index.js#L63-L78
40,261
miniplug/plug-login
src/index.js
doLogin
function doLogin (opts, csrf, email, password) { return fetch(`${opts.host}/_/auth/login`, json({ ...opts, method: 'post', body: { csrf, email, password } })).then((response) => props({ session: getSessionCookie(response.headers.get('set-cookie')), body: getJSON(response) })) }
javascript
function doLogin (opts, csrf, email, password) { return fetch(`${opts.host}/_/auth/login`, json({ ...opts, method: 'post', body: { csrf, email, password } })).then((response) => props({ session: getSessionCookie(response.headers.get('set-cookie')), body: getJSON(response) })) }
[ "function", "doLogin", "(", "opts", ",", "csrf", ",", "email", ",", "password", ")", "{", "return", "fetch", "(", "`", "${", "opts", ".", "host", "}", "`", ",", "json", "(", "{", "...", "opts", ",", "method", ":", "'post'", ",", "body", ":", "{", "csrf", ",", "email", ",", "password", "}", "}", ")", ")", ".", "then", "(", "(", "response", ")", "=>", "props", "(", "{", "session", ":", "getSessionCookie", "(", "response", ".", "headers", ".", "get", "(", "'set-cookie'", ")", ")", ",", "body", ":", "getJSON", "(", "response", ")", "}", ")", ")", "}" ]
Log in to plug.dj with an email address and password. `opts` must contain headers with a session cookie.
[ "Log", "in", "to", "plug", ".", "dj", "with", "an", "email", "address", "and", "password", ".", "opts", "must", "contain", "headers", "with", "a", "session", "cookie", "." ]
6568bca8daaabc385dce92d7e86086ae1c6a5b79
https://github.com/miniplug/plug-login/blob/6568bca8daaabc385dce92d7e86086ae1c6a5b79/src/index.js#L82-L91
40,262
jfrazx/mongoose-enumvalues
index.js
modifyProperties
function modifyProperties(schema, paths) { if (!paths.length) { return; } const options = paths[0].options; /** * Modify document enum (string) properties to an object, with (original) value and * values (enumValues) * */ function populatePropertyFor (documents, next) { if (this._mongooseOptions.lean) { asArray(documents).forEach(function(doc) { paths.forEach(function(path) { try { const splitted = path.path.split('.'); const key = splitted.shift(); const insert = { values: path.enumValues }; const value = doc[key]; insert.value = determineValue(splitted, value); doc[key] = nest(splitted, insert); } catch (error) { return next(error); } }); }); } next(); } /** * If a document is modified, this method will locate the value on updates and assign it to the * appropriate property, allowing for proper validations later. * @param <Function>: next - function that notifies mongoose this middleware is complete */ function reformatUpdateProperty(next) { const document = this._update['$set']; if (document) { paths.forEach(function(path) { try { const splitted = path.path.split('.'); const key = splitted.shift(); if (document[key] === undefined) { return; } const value = determineValue(splitted, document[key]); document[key] = nest(splitted, value); } catch (error) { return next(error); } }); } next(); } /** * If a document is modified, this method will locate the value before save/validation and assign it to the * appropriate property, allowing for proper validations later. * @param <Function>: next - function that notifies mongoose this middleware is complete */ function reformatProperty(next) { const self = this; paths.forEach(function(path) { try { const splitted = path.path.split('.'); const key = splitted.shift(); const value = determineValue(splitted, self[key]); self[key] = nest(splitted, value); } catch (error) { return next(error); } }); next(); } /** * Setup handlers for modifying properties -- ['find', 'findOne'] */ options.modify.on.forEach(function(on) { schema.post(on, populatePropertyFor); }); schema.pre((options.validateBeforeSave ? 'validate' : 'save'), reformatProperty); /* * Setup handlers for updating documents (there may be more to consider) */ ['update', 'findOneAndUpdate'].forEach(function(on) { schema.pre(on, reformatUpdateProperty); }); }
javascript
function modifyProperties(schema, paths) { if (!paths.length) { return; } const options = paths[0].options; /** * Modify document enum (string) properties to an object, with (original) value and * values (enumValues) * */ function populatePropertyFor (documents, next) { if (this._mongooseOptions.lean) { asArray(documents).forEach(function(doc) { paths.forEach(function(path) { try { const splitted = path.path.split('.'); const key = splitted.shift(); const insert = { values: path.enumValues }; const value = doc[key]; insert.value = determineValue(splitted, value); doc[key] = nest(splitted, insert); } catch (error) { return next(error); } }); }); } next(); } /** * If a document is modified, this method will locate the value on updates and assign it to the * appropriate property, allowing for proper validations later. * @param <Function>: next - function that notifies mongoose this middleware is complete */ function reformatUpdateProperty(next) { const document = this._update['$set']; if (document) { paths.forEach(function(path) { try { const splitted = path.path.split('.'); const key = splitted.shift(); if (document[key] === undefined) { return; } const value = determineValue(splitted, document[key]); document[key] = nest(splitted, value); } catch (error) { return next(error); } }); } next(); } /** * If a document is modified, this method will locate the value before save/validation and assign it to the * appropriate property, allowing for proper validations later. * @param <Function>: next - function that notifies mongoose this middleware is complete */ function reformatProperty(next) { const self = this; paths.forEach(function(path) { try { const splitted = path.path.split('.'); const key = splitted.shift(); const value = determineValue(splitted, self[key]); self[key] = nest(splitted, value); } catch (error) { return next(error); } }); next(); } /** * Setup handlers for modifying properties -- ['find', 'findOne'] */ options.modify.on.forEach(function(on) { schema.post(on, populatePropertyFor); }); schema.pre((options.validateBeforeSave ? 'validate' : 'save'), reformatProperty); /* * Setup handlers for updating documents (there may be more to consider) */ ['update', 'findOneAndUpdate'].forEach(function(on) { schema.pre(on, reformatUpdateProperty); }); }
[ "function", "modifyProperties", "(", "schema", ",", "paths", ")", "{", "if", "(", "!", "paths", ".", "length", ")", "{", "return", ";", "}", "const", "options", "=", "paths", "[", "0", "]", ".", "options", ";", "/**\n * Modify document enum (string) properties to an object, with (original) value and\n * values (enumValues)\n *\n */", "function", "populatePropertyFor", "(", "documents", ",", "next", ")", "{", "if", "(", "this", ".", "_mongooseOptions", ".", "lean", ")", "{", "asArray", "(", "documents", ")", ".", "forEach", "(", "function", "(", "doc", ")", "{", "paths", ".", "forEach", "(", "function", "(", "path", ")", "{", "try", "{", "const", "splitted", "=", "path", ".", "path", ".", "split", "(", "'.'", ")", ";", "const", "key", "=", "splitted", ".", "shift", "(", ")", ";", "const", "insert", "=", "{", "values", ":", "path", ".", "enumValues", "}", ";", "const", "value", "=", "doc", "[", "key", "]", ";", "insert", ".", "value", "=", "determineValue", "(", "splitted", ",", "value", ")", ";", "doc", "[", "key", "]", "=", "nest", "(", "splitted", ",", "insert", ")", ";", "}", "catch", "(", "error", ")", "{", "return", "next", "(", "error", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", "next", "(", ")", ";", "}", "/**\n * If a document is modified, this method will locate the value on updates and assign it to the\n * appropriate property, allowing for proper validations later.\n * @param <Function>: next - function that notifies mongoose this middleware is complete\n */", "function", "reformatUpdateProperty", "(", "next", ")", "{", "const", "document", "=", "this", ".", "_update", "[", "'$set'", "]", ";", "if", "(", "document", ")", "{", "paths", ".", "forEach", "(", "function", "(", "path", ")", "{", "try", "{", "const", "splitted", "=", "path", ".", "path", ".", "split", "(", "'.'", ")", ";", "const", "key", "=", "splitted", ".", "shift", "(", ")", ";", "if", "(", "document", "[", "key", "]", "===", "undefined", ")", "{", "return", ";", "}", "const", "value", "=", "determineValue", "(", "splitted", ",", "document", "[", "key", "]", ")", ";", "document", "[", "key", "]", "=", "nest", "(", "splitted", ",", "value", ")", ";", "}", "catch", "(", "error", ")", "{", "return", "next", "(", "error", ")", ";", "}", "}", ")", ";", "}", "next", "(", ")", ";", "}", "/**\n * If a document is modified, this method will locate the value before save/validation and assign it to the\n * appropriate property, allowing for proper validations later.\n * @param <Function>: next - function that notifies mongoose this middleware is complete\n */", "function", "reformatProperty", "(", "next", ")", "{", "const", "self", "=", "this", ";", "paths", ".", "forEach", "(", "function", "(", "path", ")", "{", "try", "{", "const", "splitted", "=", "path", ".", "path", ".", "split", "(", "'.'", ")", ";", "const", "key", "=", "splitted", ".", "shift", "(", ")", ";", "const", "value", "=", "determineValue", "(", "splitted", ",", "self", "[", "key", "]", ")", ";", "self", "[", "key", "]", "=", "nest", "(", "splitted", ",", "value", ")", ";", "}", "catch", "(", "error", ")", "{", "return", "next", "(", "error", ")", ";", "}", "}", ")", ";", "next", "(", ")", ";", "}", "/**\n * Setup handlers for modifying properties -- ['find', 'findOne']\n */", "options", ".", "modify", ".", "on", ".", "forEach", "(", "function", "(", "on", ")", "{", "schema", ".", "post", "(", "on", ",", "populatePropertyFor", ")", ";", "}", ")", ";", "schema", ".", "pre", "(", "(", "options", ".", "validateBeforeSave", "?", "'validate'", ":", "'save'", ")", ",", "reformatProperty", ")", ";", "/*\n * Setup handlers for updating documents (there may be more to consider)\n */", "[", "'update'", ",", "'findOneAndUpdate'", "]", ".", "forEach", "(", "function", "(", "on", ")", "{", "schema", ".", "pre", "(", "on", ",", "reformatUpdateProperty", ")", ";", "}", ")", ";", "}" ]
Setup handlers for modifying document properties, must be a `lean` object
[ "Setup", "handlers", "for", "modifying", "document", "properties", "must", "be", "a", "lean", "object" ]
589e792ba5cc39bbb4da9bc84814690f010b7cb2
https://github.com/jfrazx/mongoose-enumvalues/blob/589e792ba5cc39bbb4da9bc84814690f010b7cb2/index.js#L67-L158
40,263
jfrazx/mongoose-enumvalues
index.js
reformatUpdateProperty
function reformatUpdateProperty(next) { const document = this._update['$set']; if (document) { paths.forEach(function(path) { try { const splitted = path.path.split('.'); const key = splitted.shift(); if (document[key] === undefined) { return; } const value = determineValue(splitted, document[key]); document[key] = nest(splitted, value); } catch (error) { return next(error); } }); } next(); }
javascript
function reformatUpdateProperty(next) { const document = this._update['$set']; if (document) { paths.forEach(function(path) { try { const splitted = path.path.split('.'); const key = splitted.shift(); if (document[key] === undefined) { return; } const value = determineValue(splitted, document[key]); document[key] = nest(splitted, value); } catch (error) { return next(error); } }); } next(); }
[ "function", "reformatUpdateProperty", "(", "next", ")", "{", "const", "document", "=", "this", ".", "_update", "[", "'$set'", "]", ";", "if", "(", "document", ")", "{", "paths", ".", "forEach", "(", "function", "(", "path", ")", "{", "try", "{", "const", "splitted", "=", "path", ".", "path", ".", "split", "(", "'.'", ")", ";", "const", "key", "=", "splitted", ".", "shift", "(", ")", ";", "if", "(", "document", "[", "key", "]", "===", "undefined", ")", "{", "return", ";", "}", "const", "value", "=", "determineValue", "(", "splitted", ",", "document", "[", "key", "]", ")", ";", "document", "[", "key", "]", "=", "nest", "(", "splitted", ",", "value", ")", ";", "}", "catch", "(", "error", ")", "{", "return", "next", "(", "error", ")", ";", "}", "}", ")", ";", "}", "next", "(", ")", ";", "}" ]
If a document is modified, this method will locate the value on updates and assign it to the appropriate property, allowing for proper validations later. @param <Function>: next - function that notifies mongoose this middleware is complete
[ "If", "a", "document", "is", "modified", "this", "method", "will", "locate", "the", "value", "on", "updates", "and", "assign", "it", "to", "the", "appropriate", "property", "allowing", "for", "proper", "validations", "later", "." ]
589e792ba5cc39bbb4da9bc84814690f010b7cb2
https://github.com/jfrazx/mongoose-enumvalues/blob/589e792ba5cc39bbb4da9bc84814690f010b7cb2/index.js#L102-L121
40,264
jfrazx/mongoose-enumvalues
index.js
findPaths
function findPaths(schema, options) { const paths = []; schema.eachPath(function(path, type) { if (type.enumValues && type.enumValues.length) { paths.push( { path: path, enumValues: type.enumValues, options: options } ); } }); return filterPaths(paths, options); }
javascript
function findPaths(schema, options) { const paths = []; schema.eachPath(function(path, type) { if (type.enumValues && type.enumValues.length) { paths.push( { path: path, enumValues: type.enumValues, options: options } ); } }); return filterPaths(paths, options); }
[ "function", "findPaths", "(", "schema", ",", "options", ")", "{", "const", "paths", "=", "[", "]", ";", "schema", ".", "eachPath", "(", "function", "(", "path", ",", "type", ")", "{", "if", "(", "type", ".", "enumValues", "&&", "type", ".", "enumValues", ".", "length", ")", "{", "paths", ".", "push", "(", "{", "path", ":", "path", ",", "enumValues", ":", "type", ".", "enumValues", ",", "options", ":", "options", "}", ")", ";", "}", "}", ")", ";", "return", "filterPaths", "(", "paths", ",", "options", ")", ";", "}" ]
Locate schema paths that are enums @param
[ "Locate", "schema", "paths", "that", "are", "enums" ]
589e792ba5cc39bbb4da9bc84814690f010b7cb2
https://github.com/jfrazx/mongoose-enumvalues/blob/589e792ba5cc39bbb4da9bc84814690f010b7cb2/index.js#L164-L180
40,265
jfrazx/mongoose-enumvalues
index.js
setVirtuals
function setVirtuals(schema, paths) { paths.forEach(path => { const props = path.options.virtual.properties; if (props[path.path]) { schema.virtual(props[path.path]).get(function() { return path.enumValues; }); } }); }
javascript
function setVirtuals(schema, paths) { paths.forEach(path => { const props = path.options.virtual.properties; if (props[path.path]) { schema.virtual(props[path.path]).get(function() { return path.enumValues; }); } }); }
[ "function", "setVirtuals", "(", "schema", ",", "paths", ")", "{", "paths", ".", "forEach", "(", "path", "=>", "{", "const", "props", "=", "path", ".", "options", ".", "virtual", ".", "properties", ";", "if", "(", "props", "[", "path", ".", "path", "]", ")", "{", "schema", ".", "virtual", "(", "props", "[", "path", ".", "path", "]", ")", ".", "get", "(", "function", "(", ")", "{", "return", "path", ".", "enumValues", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
Setup virtual properties for the document
[ "Setup", "virtual", "properties", "for", "the", "document" ]
589e792ba5cc39bbb4da9bc84814690f010b7cb2
https://github.com/jfrazx/mongoose-enumvalues/blob/589e792ba5cc39bbb4da9bc84814690f010b7cb2/index.js#L221-L231
40,266
jfrazx/mongoose-enumvalues
index.js
attachProperties
function attachProperties(schema, paths) { paths.forEach(path => { const props = path.options.attach.properties; if (props[path.path]) { (props[path.path].on || []).forEach(on => { /** * Setup post callbacks */ schema.post(on, function(documents, next) { asArray(documents).forEach(function(doc) { paths.forEach(function(path) { doc[props[path.path].as] = path.enumValues; }); }); next(); }); }); } }); }
javascript
function attachProperties(schema, paths) { paths.forEach(path => { const props = path.options.attach.properties; if (props[path.path]) { (props[path.path].on || []).forEach(on => { /** * Setup post callbacks */ schema.post(on, function(documents, next) { asArray(documents).forEach(function(doc) { paths.forEach(function(path) { doc[props[path.path].as] = path.enumValues; }); }); next(); }); }); } }); }
[ "function", "attachProperties", "(", "schema", ",", "paths", ")", "{", "paths", ".", "forEach", "(", "path", "=>", "{", "const", "props", "=", "path", ".", "options", ".", "attach", ".", "properties", ";", "if", "(", "props", "[", "path", ".", "path", "]", ")", "{", "(", "props", "[", "path", ".", "path", "]", ".", "on", "||", "[", "]", ")", ".", "forEach", "(", "on", "=>", "{", "/**\n * Setup post callbacks\n */", "schema", ".", "post", "(", "on", ",", "function", "(", "documents", ",", "next", ")", "{", "asArray", "(", "documents", ")", ".", "forEach", "(", "function", "(", "doc", ")", "{", "paths", ".", "forEach", "(", "function", "(", "path", ")", "{", "doc", "[", "props", "[", "path", ".", "path", "]", ".", "as", "]", "=", "path", ".", "enumValues", ";", "}", ")", ";", "}", ")", ";", "next", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
Attach properties to the document
[ "Attach", "properties", "to", "the", "document" ]
589e792ba5cc39bbb4da9bc84814690f010b7cb2
https://github.com/jfrazx/mongoose-enumvalues/blob/589e792ba5cc39bbb4da9bc84814690f010b7cb2/index.js#L237-L259
40,267
jfrazx/mongoose-enumvalues
index.js
determineValue
function determineValue(keys, doc) { try { for (const key of keys) { doc = doc[key]; } /** the keys array should transition through any nesting, so any object is assumed to be enumValues: { value: 'string', enumValues: ['strings'] } */ return typeof doc === 'object' ? doc.value : doc; } catch (error) { return doc; } }
javascript
function determineValue(keys, doc) { try { for (const key of keys) { doc = doc[key]; } /** the keys array should transition through any nesting, so any object is assumed to be enumValues: { value: 'string', enumValues: ['strings'] } */ return typeof doc === 'object' ? doc.value : doc; } catch (error) { return doc; } }
[ "function", "determineValue", "(", "keys", ",", "doc", ")", "{", "try", "{", "for", "(", "const", "key", "of", "keys", ")", "{", "doc", "=", "doc", "[", "key", "]", ";", "}", "/**\n the keys array should transition through any nesting,\n so any object is assumed to be enumValues:\n { value: 'string', enumValues: ['strings'] }\n */", "return", "typeof", "doc", "===", "'object'", "?", "doc", ".", "value", ":", "doc", ";", "}", "catch", "(", "error", ")", "{", "return", "doc", ";", "}", "}" ]
Traverse the passed document, according to keys, appropriating the desired value @param [String]: keys -- an array of keys determining the path to value @param Object: doc -- the document that contains the value at keys path @return any: -- the value at the end of keys path in document
[ "Traverse", "the", "passed", "document", "according", "to", "keys", "appropriating", "the", "desired", "value" ]
589e792ba5cc39bbb4da9bc84814690f010b7cb2
https://github.com/jfrazx/mongoose-enumvalues/blob/589e792ba5cc39bbb4da9bc84814690f010b7cb2/index.js#L267-L280
40,268
jfrazx/mongoose-enumvalues
index.js
nest
function nest(array, insert) { let obj; array.reverse().forEach(key => { obj = { [key]: insert }; insert = obj; }); return insert; }
javascript
function nest(array, insert) { let obj; array.reverse().forEach(key => { obj = { [key]: insert }; insert = obj; }); return insert; }
[ "function", "nest", "(", "array", ",", "insert", ")", "{", "let", "obj", ";", "array", ".", "reverse", "(", ")", ".", "forEach", "(", "key", "=>", "{", "obj", "=", "{", "[", "key", "]", ":", "insert", "}", ";", "insert", "=", "obj", ";", "}", ")", ";", "return", "insert", ";", "}" ]
Nest the insert value into objects with keys from array
[ "Nest", "the", "insert", "value", "into", "objects", "with", "keys", "from", "array" ]
589e792ba5cc39bbb4da9bc84814690f010b7cb2
https://github.com/jfrazx/mongoose-enumvalues/blob/589e792ba5cc39bbb4da9bc84814690f010b7cb2/index.js#L286-L295
40,269
jfrazx/mongoose-enumvalues
index.js
setOptions
function setOptions(schema, options) { function setDefaults(array) { if (!array.length) { if (options.find) { array.push('find'); } if (options.findOne || !options.find) { array.push('findOne'); } } } options = options || {}; options.only = options.only || []; options.validateBeforeSave = options.validateBeforeSave === undefined ? schema.options.validateBeforeSave : Boolean(options.validateBeforeSave); ['virtual', 'attach', 'modify'].filter(prop => options[prop]) .forEach( prop => { if (typeof options[prop] !== 'object') { options[prop] = {}; } options[prop].properties = options[prop].properties || {}; options[prop].only = options[prop].only || Object.keys(options[prop].properties); } ); if (options.modify) { delete options.modify.properties; options.modify.on = options.modify.on || []; setDefaults(options.modify.on); } if (options.attach) { Object.keys(options.attach.properties).forEach(property => { options.attach.properties[property].on = options.attach.properties[property].on || []; setDefaults(options.attach.properties[property].on); }); } return options; }
javascript
function setOptions(schema, options) { function setDefaults(array) { if (!array.length) { if (options.find) { array.push('find'); } if (options.findOne || !options.find) { array.push('findOne'); } } } options = options || {}; options.only = options.only || []; options.validateBeforeSave = options.validateBeforeSave === undefined ? schema.options.validateBeforeSave : Boolean(options.validateBeforeSave); ['virtual', 'attach', 'modify'].filter(prop => options[prop]) .forEach( prop => { if (typeof options[prop] !== 'object') { options[prop] = {}; } options[prop].properties = options[prop].properties || {}; options[prop].only = options[prop].only || Object.keys(options[prop].properties); } ); if (options.modify) { delete options.modify.properties; options.modify.on = options.modify.on || []; setDefaults(options.modify.on); } if (options.attach) { Object.keys(options.attach.properties).forEach(property => { options.attach.properties[property].on = options.attach.properties[property].on || []; setDefaults(options.attach.properties[property].on); }); } return options; }
[ "function", "setOptions", "(", "schema", ",", "options", ")", "{", "function", "setDefaults", "(", "array", ")", "{", "if", "(", "!", "array", ".", "length", ")", "{", "if", "(", "options", ".", "find", ")", "{", "array", ".", "push", "(", "'find'", ")", ";", "}", "if", "(", "options", ".", "findOne", "||", "!", "options", ".", "find", ")", "{", "array", ".", "push", "(", "'findOne'", ")", ";", "}", "}", "}", "options", "=", "options", "||", "{", "}", ";", "options", ".", "only", "=", "options", ".", "only", "||", "[", "]", ";", "options", ".", "validateBeforeSave", "=", "options", ".", "validateBeforeSave", "===", "undefined", "?", "schema", ".", "options", ".", "validateBeforeSave", ":", "Boolean", "(", "options", ".", "validateBeforeSave", ")", ";", "[", "'virtual'", ",", "'attach'", ",", "'modify'", "]", ".", "filter", "(", "prop", "=>", "options", "[", "prop", "]", ")", ".", "forEach", "(", "prop", "=>", "{", "if", "(", "typeof", "options", "[", "prop", "]", "!==", "'object'", ")", "{", "options", "[", "prop", "]", "=", "{", "}", ";", "}", "options", "[", "prop", "]", ".", "properties", "=", "options", "[", "prop", "]", ".", "properties", "||", "{", "}", ";", "options", "[", "prop", "]", ".", "only", "=", "options", "[", "prop", "]", ".", "only", "||", "Object", ".", "keys", "(", "options", "[", "prop", "]", ".", "properties", ")", ";", "}", ")", ";", "if", "(", "options", ".", "modify", ")", "{", "delete", "options", ".", "modify", ".", "properties", ";", "options", ".", "modify", ".", "on", "=", "options", ".", "modify", ".", "on", "||", "[", "]", ";", "setDefaults", "(", "options", ".", "modify", ".", "on", ")", ";", "}", "if", "(", "options", ".", "attach", ")", "{", "Object", ".", "keys", "(", "options", ".", "attach", ".", "properties", ")", ".", "forEach", "(", "property", "=>", "{", "options", ".", "attach", ".", "properties", "[", "property", "]", ".", "on", "=", "options", ".", "attach", ".", "properties", "[", "property", "]", ".", "on", "||", "[", "]", ";", "setDefaults", "(", "options", ".", "attach", ".", "properties", "[", "property", "]", ".", "on", ")", ";", "}", ")", ";", "}", "return", "options", ";", "}" ]
Setup options and defaults
[ "Setup", "options", "and", "defaults" ]
589e792ba5cc39bbb4da9bc84814690f010b7cb2
https://github.com/jfrazx/mongoose-enumvalues/blob/589e792ba5cc39bbb4da9bc84814690f010b7cb2/index.js#L301-L340
40,270
stezu/node-stream
lib/modifiers/parse.js
parse
function parse(options) { var settings = _.extend({ error: true }, options); return map(function (chunk, next) { var parsed; try { parsed = JSON.parse(chunk); } catch (e) { if (settings.error === true) { return next(e); } return next(); } return next(null, parsed); }); }
javascript
function parse(options) { var settings = _.extend({ error: true }, options); return map(function (chunk, next) { var parsed; try { parsed = JSON.parse(chunk); } catch (e) { if (settings.error === true) { return next(e); } return next(); } return next(null, parsed); }); }
[ "function", "parse", "(", "options", ")", "{", "var", "settings", "=", "_", ".", "extend", "(", "{", "error", ":", "true", "}", ",", "options", ")", ";", "return", "map", "(", "function", "(", "chunk", ",", "next", ")", "{", "var", "parsed", ";", "try", "{", "parsed", "=", "JSON", ".", "parse", "(", "chunk", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "settings", ".", "error", "===", "true", ")", "{", "return", "next", "(", "e", ")", ";", "}", "return", "next", "(", ")", ";", "}", "return", "next", "(", "null", ",", "parsed", ")", ";", "}", ")", ";", "}" ]
Creates a new stream where every element in the source stream is parsed as JSON. @static @since 1.1.0 @category Modifiers @param {Object} [options] - Options to use when parsing items in the stream. @param {Boolean} [options.error = true] - If true, an error caught when parsing JSON will be emitted on the stream. If false, the unparseable item will be removed from the stream without error. @returns {Stream.Transform} - Transform stream. @example // parse a newline-separated JSON file fs.createReadStream('example.log') .pipe(nodeStream.split()) .pipe(nodeStream.parse()); @example // parse a large JSON file fs.createReadStream('warandpeace.json') .pipe(nodeStream.wait()) .pipe(nodeStream.parse());
[ "Creates", "a", "new", "stream", "where", "every", "element", "in", "the", "source", "stream", "is", "parsed", "as", "JSON", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/modifiers/parse.js#L34-L55
40,271
gabegorelick/hidalgo-cusum-pvalue
index.js
lerp
function lerp (vX, vY, x) { if (x < vX[0]) { // Don't interpolate leftward, Cuellar says this is done on purpose return vY[0]; } var i = search(vX, x, function (a, b) {return a - b;}); if (i >= 0) { // found exact match, no need to interpolate return vY[i]; } else { // when not found, binary-search returns the -(index_x_should_be + 1), // see https://github.com/darkskyapp/binary-search/issues/1 i = Math.abs(i + 1); if (i >= vX.length) { // extrapolate using last 2 values i = vX.length - 1; } var y0 = vY[i - 1]; var y1 = vY[i]; var x0 = vX[i - 1]; var x1 = vX[i]; return y0 + (y1 - y0) * (x - x0) / (x1 - x0); } }
javascript
function lerp (vX, vY, x) { if (x < vX[0]) { // Don't interpolate leftward, Cuellar says this is done on purpose return vY[0]; } var i = search(vX, x, function (a, b) {return a - b;}); if (i >= 0) { // found exact match, no need to interpolate return vY[i]; } else { // when not found, binary-search returns the -(index_x_should_be + 1), // see https://github.com/darkskyapp/binary-search/issues/1 i = Math.abs(i + 1); if (i >= vX.length) { // extrapolate using last 2 values i = vX.length - 1; } var y0 = vY[i - 1]; var y1 = vY[i]; var x0 = vX[i - 1]; var x1 = vX[i]; return y0 + (y1 - y0) * (x - x0) / (x1 - x0); } }
[ "function", "lerp", "(", "vX", ",", "vY", ",", "x", ")", "{", "if", "(", "x", "<", "vX", "[", "0", "]", ")", "{", "// Don't interpolate leftward, Cuellar says this is done on purpose", "return", "vY", "[", "0", "]", ";", "}", "var", "i", "=", "search", "(", "vX", ",", "x", ",", "function", "(", "a", ",", "b", ")", "{", "return", "a", "-", "b", ";", "}", ")", ";", "if", "(", "i", ">=", "0", ")", "{", "// found exact match, no need to interpolate", "return", "vY", "[", "i", "]", ";", "}", "else", "{", "// when not found, binary-search returns the -(index_x_should_be + 1),", "// see https://github.com/darkskyapp/binary-search/issues/1", "i", "=", "Math", ".", "abs", "(", "i", "+", "1", ")", ";", "if", "(", "i", ">=", "vX", ".", "length", ")", "{", "// extrapolate using last 2 values", "i", "=", "vX", ".", "length", "-", "1", ";", "}", "var", "y0", "=", "vY", "[", "i", "-", "1", "]", ";", "var", "y1", "=", "vY", "[", "i", "]", ";", "var", "x0", "=", "vX", "[", "i", "-", "1", "]", ";", "var", "x1", "=", "vX", "[", "i", "]", ";", "return", "y0", "+", "(", "y1", "-", "y0", ")", "*", "(", "x", "-", "x0", ")", "/", "(", "x1", "-", "x0", ")", ";", "}", "}" ]
Linear interpolation with some eccentricities. @param {number[]} vX - array (vector in math speak) of x values @param {number[]} vY - array (vector in math speak) of y values @param {number} x - value to interpolate @returns {number} interpolated value
[ "Linear", "interpolation", "with", "some", "eccentricities", "." ]
ccdc1a8a2c5068ed244884d7c91bc6f39bfd1974
https://github.com/gabegorelick/hidalgo-cusum-pvalue/blob/ccdc1a8a2c5068ed244884d7c91bc6f39bfd1974/index.js#L13-L39
40,272
terkelg/eliminate
src/index.js
eliminate
async function eliminate(dir) { const stat = await lstat(dir); if (!stat.isDirectory()) { await unlink(dir); return; } const files = await readdir(dir); for (const file of files) { const path = join(dir, file); if (fs.existsSync(path)) { await eliminate(path); } else { await unlink(path); } } await rmdir(dir); }
javascript
async function eliminate(dir) { const stat = await lstat(dir); if (!stat.isDirectory()) { await unlink(dir); return; } const files = await readdir(dir); for (const file of files) { const path = join(dir, file); if (fs.existsSync(path)) { await eliminate(path); } else { await unlink(path); } } await rmdir(dir); }
[ "async", "function", "eliminate", "(", "dir", ")", "{", "const", "stat", "=", "await", "lstat", "(", "dir", ")", ";", "if", "(", "!", "stat", ".", "isDirectory", "(", ")", ")", "{", "await", "unlink", "(", "dir", ")", ";", "return", ";", "}", "const", "files", "=", "await", "readdir", "(", "dir", ")", ";", "for", "(", "const", "file", "of", "files", ")", "{", "const", "path", "=", "join", "(", "dir", ",", "file", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "path", ")", ")", "{", "await", "eliminate", "(", "path", ")", ";", "}", "else", "{", "await", "unlink", "(", "path", ")", ";", "}", "}", "await", "rmdir", "(", "dir", ")", ";", "}" ]
Delete directory or file @param {String} dir The path/file to delete
[ "Delete", "directory", "or", "file" ]
1d00e99bea6c1ed978d4e89fb14c24b0a157d5ce
https://github.com/terkelg/eliminate/blob/1d00e99bea6c1ed978d4e89fb14c24b0a157d5ce/src/index.js#L14-L30
40,273
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/generators/jsx.js
JSXAttribute
function JSXAttribute(node, print) { print.plain(node.name); if (node.value) { this.push("="); print.plain(node.value); } }
javascript
function JSXAttribute(node, print) { print.plain(node.name); if (node.value) { this.push("="); print.plain(node.value); } }
[ "function", "JSXAttribute", "(", "node", ",", "print", ")", "{", "print", ".", "plain", "(", "node", ".", "name", ")", ";", "if", "(", "node", ".", "value", ")", "{", "this", ".", "push", "(", "\"=\"", ")", ";", "print", ".", "plain", "(", "node", ".", "value", ")", ";", "}", "}" ]
Prints JSXAttribute, prints name and value.
[ "Prints", "JSXAttribute", "prints", "name", "and", "value", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/generators/jsx.js#L28-L34
40,274
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/generators/jsx.js
JSXElement
function JSXElement(node, print) { var open = node.openingElement; print.plain(open); if (open.selfClosing) return; this.indent(); var _arr = node.children; for (var _i = 0; _i < _arr.length; _i++) { var child = _arr[_i]; if (t.isLiteral(child)) { this.push(child.value, true); } else { print.plain(child); } } this.dedent(); print.plain(node.closingElement); }
javascript
function JSXElement(node, print) { var open = node.openingElement; print.plain(open); if (open.selfClosing) return; this.indent(); var _arr = node.children; for (var _i = 0; _i < _arr.length; _i++) { var child = _arr[_i]; if (t.isLiteral(child)) { this.push(child.value, true); } else { print.plain(child); } } this.dedent(); print.plain(node.closingElement); }
[ "function", "JSXElement", "(", "node", ",", "print", ")", "{", "var", "open", "=", "node", ".", "openingElement", ";", "print", ".", "plain", "(", "open", ")", ";", "if", "(", "open", ".", "selfClosing", ")", "return", ";", "this", ".", "indent", "(", ")", ";", "var", "_arr", "=", "node", ".", "children", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "_arr", ".", "length", ";", "_i", "++", ")", "{", "var", "child", "=", "_arr", "[", "_i", "]", ";", "if", "(", "t", ".", "isLiteral", "(", "child", ")", ")", "{", "this", ".", "push", "(", "child", ".", "value", ",", "true", ")", ";", "}", "else", "{", "print", ".", "plain", "(", "child", ")", ";", "}", "}", "this", ".", "dedent", "(", ")", ";", "print", ".", "plain", "(", "node", ".", "closingElement", ")", ";", "}" ]
Prints JSXElement, prints openingElement, children, and closingElement.
[ "Prints", "JSXElement", "prints", "openingElement", "children", "and", "closingElement", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/generators/jsx.js#L88-L106
40,275
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/generators/jsx.js
JSXOpeningElement
function JSXOpeningElement(node, print) { this.push("<"); print.plain(node.name); if (node.attributes.length > 0) { this.push(" "); print.join(node.attributes, { separator: " " }); } this.push(node.selfClosing ? " />" : ">"); }
javascript
function JSXOpeningElement(node, print) { this.push("<"); print.plain(node.name); if (node.attributes.length > 0) { this.push(" "); print.join(node.attributes, { separator: " " }); } this.push(node.selfClosing ? " />" : ">"); }
[ "function", "JSXOpeningElement", "(", "node", ",", "print", ")", "{", "this", ".", "push", "(", "\"<\"", ")", ";", "print", ".", "plain", "(", "node", ".", "name", ")", ";", "if", "(", "node", ".", "attributes", ".", "length", ">", "0", ")", "{", "this", ".", "push", "(", "\" \"", ")", ";", "print", ".", "join", "(", "node", ".", "attributes", ",", "{", "separator", ":", "\" \"", "}", ")", ";", "}", "this", ".", "push", "(", "node", ".", "selfClosing", "?", "\" />\"", ":", "\">\"", ")", ";", "}" ]
Prints JSXOpeningElement, prints name and attributes, handles selfClosing.
[ "Prints", "JSXOpeningElement", "prints", "name", "and", "attributes", "handles", "selfClosing", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/generators/jsx.js#L112-L120
40,276
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/generators/base.js
BlockStatement
function BlockStatement(node, print) { this.push("{"); if (node.body.length) { this.newline(); print.sequence(node.body, { indent: true }); if (!this.format.retainLines) this.removeLast("\n"); this.rightBrace(); } else { print.printInnerComments(); this.push("}"); } }
javascript
function BlockStatement(node, print) { this.push("{"); if (node.body.length) { this.newline(); print.sequence(node.body, { indent: true }); if (!this.format.retainLines) this.removeLast("\n"); this.rightBrace(); } else { print.printInnerComments(); this.push("}"); } }
[ "function", "BlockStatement", "(", "node", ",", "print", ")", "{", "this", ".", "push", "(", "\"{\"", ")", ";", "if", "(", "node", ".", "body", ".", "length", ")", "{", "this", ".", "newline", "(", ")", ";", "print", ".", "sequence", "(", "node", ".", "body", ",", "{", "indent", ":", "true", "}", ")", ";", "if", "(", "!", "this", ".", "format", ".", "retainLines", ")", "this", ".", "removeLast", "(", "\"\\n\"", ")", ";", "this", ".", "rightBrace", "(", ")", ";", "}", "else", "{", "print", ".", "printInnerComments", "(", ")", ";", "this", ".", "push", "(", "\"}\"", ")", ";", "}", "}" ]
Print BlockStatement, collapses empty blocks, prints body.
[ "Print", "BlockStatement", "collapses", "empty", "blocks", "prints", "body", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/generators/base.js#L31-L42
40,277
RobLoach/metalsmith-jstransformer-partials
index.js
getTransformer
function getTransformer(name) { if (name in transformers) { return transformers[name] } const transformer = toTransformer(name) transformers[name] = transformer ? jstransformer(transformer) : false return transformers[name] }
javascript
function getTransformer(name) { if (name in transformers) { return transformers[name] } const transformer = toTransformer(name) transformers[name] = transformer ? jstransformer(transformer) : false return transformers[name] }
[ "function", "getTransformer", "(", "name", ")", "{", "if", "(", "name", "in", "transformers", ")", "{", "return", "transformers", "[", "name", "]", "}", "const", "transformer", "=", "toTransformer", "(", "name", ")", "transformers", "[", "name", "]", "=", "transformer", "?", "jstransformer", "(", "transformer", ")", ":", "false", "return", "transformers", "[", "name", "]", "}" ]
Get the transformer from the given name. @return The JSTransformer; null if it doesn't exist.
[ "Get", "the", "transformer", "from", "the", "given", "name", "." ]
f164b32438e05701837e13fa7852cc909470c321
https://github.com/RobLoach/metalsmith-jstransformer-partials/blob/f164b32438e05701837e13fa7852cc909470c321/index.js#L29-L36
40,278
RobLoach/metalsmith-jstransformer-partials
index.js
renderPartial
function renderPartial(name) { // The name is a required input. if (!name) { throw new Error('When calling .partial(), name is required.') } // Ensure the partial is available in the metadata. if (!(name in metalsmith.metadata().partials)) { throw new Error('The partial "' + name + '" was not found.') } // Construct the partial function arguments. const fnarray = [] for (let i = 1; i < arguments.length; i++) { fnarray.push(arguments[i]) } // Call the partial function with the given array arguments. return metalsmith.metadata().partials[name].apply(metalsmith.metadata(), fnarray) }
javascript
function renderPartial(name) { // The name is a required input. if (!name) { throw new Error('When calling .partial(), name is required.') } // Ensure the partial is available in the metadata. if (!(name in metalsmith.metadata().partials)) { throw new Error('The partial "' + name + '" was not found.') } // Construct the partial function arguments. const fnarray = [] for (let i = 1; i < arguments.length; i++) { fnarray.push(arguments[i]) } // Call the partial function with the given array arguments. return metalsmith.metadata().partials[name].apply(metalsmith.metadata(), fnarray) }
[ "function", "renderPartial", "(", "name", ")", "{", "// The name is a required input.", "if", "(", "!", "name", ")", "{", "throw", "new", "Error", "(", "'When calling .partial(), name is required.'", ")", "}", "// Ensure the partial is available in the metadata.", "if", "(", "!", "(", "name", "in", "metalsmith", ".", "metadata", "(", ")", ".", "partials", ")", ")", "{", "throw", "new", "Error", "(", "'The partial \"'", "+", "name", "+", "'\" was not found.'", ")", "}", "// Construct the partial function arguments.", "const", "fnarray", "=", "[", "]", "for", "(", "let", "i", "=", "1", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "fnarray", ".", "push", "(", "arguments", "[", "i", "]", ")", "}", "// Call the partial function with the given array arguments.", "return", "metalsmith", ".", "metadata", "(", ")", ".", "partials", "[", "name", "]", ".", "apply", "(", "metalsmith", ".", "metadata", "(", ")", ",", "fnarray", ")", "}" ]
Renders a partial from the given name.
[ "Renders", "a", "partial", "from", "the", "given", "name", "." ]
f164b32438e05701837e13fa7852cc909470c321
https://github.com/RobLoach/metalsmith-jstransformer-partials/blob/f164b32438e05701837e13fa7852cc909470c321/index.js#L46-L65
40,279
RobLoach/metalsmith-jstransformer-partials
index.js
filterFile
function filterFile(file, done) { if (files[file].partial) { // Discover whether it is explicitly declared as a partial. return done(null, files[file].partial) } else if (opts.pattern) { // Check if it matches the partial pattern. return done(null, minimatch(file, opts.pattern)) } // The file is not a partial. done(null, false) }
javascript
function filterFile(file, done) { if (files[file].partial) { // Discover whether it is explicitly declared as a partial. return done(null, files[file].partial) } else if (opts.pattern) { // Check if it matches the partial pattern. return done(null, minimatch(file, opts.pattern)) } // The file is not a partial. done(null, false) }
[ "function", "filterFile", "(", "file", ",", "done", ")", "{", "if", "(", "files", "[", "file", "]", ".", "partial", ")", "{", "// Discover whether it is explicitly declared as a partial.", "return", "done", "(", "null", ",", "files", "[", "file", "]", ".", "partial", ")", "}", "else", "if", "(", "opts", ".", "pattern", ")", "{", "// Check if it matches the partial pattern.", "return", "done", "(", "null", ",", "minimatch", "(", "file", ",", "opts", ".", "pattern", ")", ")", "}", "// The file is not a partial.", "done", "(", "null", ",", "false", ")", "}" ]
Filter out all partials
[ "Filter", "out", "all", "partials" ]
f164b32438e05701837e13fa7852cc909470c321
https://github.com/RobLoach/metalsmith-jstransformer-partials/blob/f164b32438e05701837e13fa7852cc909470c321/index.js#L77-L87
40,280
RobLoach/metalsmith-jstransformer-partials
index.js
addPartial
function addPartial(filename, done) { // Create a copy of the file and delete it from the database. const file = clone(files[filename]) delete files[filename] // Compile the partial. const info = path.parse(filename) const transform = info.ext ? info.ext.substring(1) : null const transformer = getTransformer(transform) if (transformer) { // Construct the options. const options = extend({}, metalsmith.metadata(), file, { filename: path.join(metalsmith.source(), filename) }) // Compile the partial. transformer.compileAsync(file.contents.toString(), options).then(template => { /** * Define the partial as a function. */ metalsmith.metadata().partials[info.name] = locals => { const opt = extend({}, options, locals) return template.fn.apply(file, [opt]) } metalsmith.metadata().partials[info.name].file = file done() }, done) } else { // Do not error out when the Transformer is not found. done() } }
javascript
function addPartial(filename, done) { // Create a copy of the file and delete it from the database. const file = clone(files[filename]) delete files[filename] // Compile the partial. const info = path.parse(filename) const transform = info.ext ? info.ext.substring(1) : null const transformer = getTransformer(transform) if (transformer) { // Construct the options. const options = extend({}, metalsmith.metadata(), file, { filename: path.join(metalsmith.source(), filename) }) // Compile the partial. transformer.compileAsync(file.contents.toString(), options).then(template => { /** * Define the partial as a function. */ metalsmith.metadata().partials[info.name] = locals => { const opt = extend({}, options, locals) return template.fn.apply(file, [opt]) } metalsmith.metadata().partials[info.name].file = file done() }, done) } else { // Do not error out when the Transformer is not found. done() } }
[ "function", "addPartial", "(", "filename", ",", "done", ")", "{", "// Create a copy of the file and delete it from the database.", "const", "file", "=", "clone", "(", "files", "[", "filename", "]", ")", "delete", "files", "[", "filename", "]", "// Compile the partial.", "const", "info", "=", "path", ".", "parse", "(", "filename", ")", "const", "transform", "=", "info", ".", "ext", "?", "info", ".", "ext", ".", "substring", "(", "1", ")", ":", "null", "const", "transformer", "=", "getTransformer", "(", "transform", ")", "if", "(", "transformer", ")", "{", "// Construct the options.", "const", "options", "=", "extend", "(", "{", "}", ",", "metalsmith", ".", "metadata", "(", ")", ",", "file", ",", "{", "filename", ":", "path", ".", "join", "(", "metalsmith", ".", "source", "(", ")", ",", "filename", ")", "}", ")", "// Compile the partial.", "transformer", ".", "compileAsync", "(", "file", ".", "contents", ".", "toString", "(", ")", ",", "options", ")", ".", "then", "(", "template", "=>", "{", "/**\n * Define the partial as a function.\n */", "metalsmith", ".", "metadata", "(", ")", ".", "partials", "[", "info", ".", "name", "]", "=", "locals", "=>", "{", "const", "opt", "=", "extend", "(", "{", "}", ",", "options", ",", "locals", ")", "return", "template", ".", "fn", ".", "apply", "(", "file", ",", "[", "opt", "]", ")", "}", "metalsmith", ".", "metadata", "(", ")", ".", "partials", "[", "info", ".", "name", "]", ".", "file", "=", "file", "done", "(", ")", "}", ",", "done", ")", "}", "else", "{", "// Do not error out when the Transformer is not found.", "done", "(", ")", "}", "}" ]
Add the given file in as a partial.
[ "Add", "the", "given", "file", "in", "as", "a", "partial", "." ]
f164b32438e05701837e13fa7852cc909470c321
https://github.com/RobLoach/metalsmith-jstransformer-partials/blob/f164b32438e05701837e13fa7852cc909470c321/index.js#L92-L123
40,281
sumeetdas/Meow
lib/jobs.js
publishRobotsTxt
function publishRobotsTxt () { var path = 'robots.txt'; return fs .statAsync(path) .then(function (pStat) { if (!pStat.isFile()) { // go to our default course of action, that is create robots.txt file throw new Error (); } }) .catch(Error, function () { return fs .openAsync(path, 'w') .then(function () { return fs.writeFileAsync(path, 'User-agent: *\nSitemap: ' + config.siteUrl + '/sitemap.xml'); }) .catch(function (pErr) { log.error(pErr); }); }); }
javascript
function publishRobotsTxt () { var path = 'robots.txt'; return fs .statAsync(path) .then(function (pStat) { if (!pStat.isFile()) { // go to our default course of action, that is create robots.txt file throw new Error (); } }) .catch(Error, function () { return fs .openAsync(path, 'w') .then(function () { return fs.writeFileAsync(path, 'User-agent: *\nSitemap: ' + config.siteUrl + '/sitemap.xml'); }) .catch(function (pErr) { log.error(pErr); }); }); }
[ "function", "publishRobotsTxt", "(", ")", "{", "var", "path", "=", "'robots.txt'", ";", "return", "fs", ".", "statAsync", "(", "path", ")", ".", "then", "(", "function", "(", "pStat", ")", "{", "if", "(", "!", "pStat", ".", "isFile", "(", ")", ")", "{", "// go to our default course of action, that is create robots.txt file", "throw", "new", "Error", "(", ")", ";", "}", "}", ")", ".", "catch", "(", "Error", ",", "function", "(", ")", "{", "return", "fs", ".", "openAsync", "(", "path", ",", "'w'", ")", ".", "then", "(", "function", "(", ")", "{", "return", "fs", ".", "writeFileAsync", "(", "path", ",", "'User-agent: *\\nSitemap: '", "+", "config", ".", "siteUrl", "+", "'/sitemap.xml'", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "pErr", ")", "{", "log", ".", "error", "(", "pErr", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Creates a default robots.txt file if it does not exist @returns {*}
[ "Creates", "a", "default", "robots", ".", "txt", "file", "if", "it", "does", "not", "exist" ]
965cd8a966aed9fe2fb271bf9a1ba9692eb2f3a9
https://github.com/sumeetdas/Meow/blob/965cd8a966aed9fe2fb271bf9a1ba9692eb2f3a9/lib/jobs.js#L129-L149
40,282
divshot/ask
lib/mock-request-response.js
function () { var self = this; return function () { var status = self.statusCode; if (status === 0 || (status >= 400 && status < 600)) { return context.asRejectedPromise(self); } return context.asPromise(self); }; }
javascript
function () { var self = this; return function () { var status = self.statusCode; if (status === 0 || (status >= 400 && status < 600)) { return context.asRejectedPromise(self); } return context.asPromise(self); }; }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "return", "function", "(", ")", "{", "var", "status", "=", "self", ".", "statusCode", ";", "if", "(", "status", "===", "0", "||", "(", "status", ">=", "400", "&&", "status", "<", "600", ")", ")", "{", "return", "context", ".", "asRejectedPromise", "(", "self", ")", ";", "}", "return", "context", ".", "asPromise", "(", "self", ")", ";", "}", ";", "}" ]
Custom function to return when a mock is present
[ "Custom", "function", "to", "return", "when", "a", "mock", "is", "present" ]
bd37e5654374c98d48e9d37c65984579d3bda445
https://github.com/divshot/ask/blob/bd37e5654374c98d48e9d37c65984579d3bda445/lib/mock-request-response.js#L29-L40
40,283
keqingrong/is-same-origin
src/index.js
parseURL
function parseURL(s) { var url = null; try { url = new URL(s); } catch (error) { console.error(error); } return url; }
javascript
function parseURL(s) { var url = null; try { url = new URL(s); } catch (error) { console.error(error); } return url; }
[ "function", "parseURL", "(", "s", ")", "{", "var", "url", "=", "null", ";", "try", "{", "url", "=", "new", "URL", "(", "s", ")", ";", "}", "catch", "(", "error", ")", "{", "console", ".", "error", "(", "error", ")", ";", "}", "return", "url", ";", "}" ]
Parse the URL string @param {string} s - URL string @returns {URL|null}
[ "Parse", "the", "URL", "string" ]
5891c5d3a98f9436c16c9d992c710fc1938b05c4
https://github.com/keqingrong/is-same-origin/blob/5891c5d3a98f9436c16c9d992c710fc1938b05c4/src/index.js#L34-L42
40,284
stezu/node-stream
lib/consumers/v1/first.js
firstObj
function firstObj(stream, onEnd) { var data; /** * Send the correct data to the onEnd callback. * * @private * @param {Error} [err] - Optional error. * @returns {undefined} */ var done = _.once(function (err) { if (err) { return onEnd(err); } return onEnd(null, data); }); stream.once('data', function (chunk) { data = chunk; }); stream.on('error', done); stream.on('end', done); }
javascript
function firstObj(stream, onEnd) { var data; /** * Send the correct data to the onEnd callback. * * @private * @param {Error} [err] - Optional error. * @returns {undefined} */ var done = _.once(function (err) { if (err) { return onEnd(err); } return onEnd(null, data); }); stream.once('data', function (chunk) { data = chunk; }); stream.on('error', done); stream.on('end', done); }
[ "function", "firstObj", "(", "stream", ",", "onEnd", ")", "{", "var", "data", ";", "/**\n * Send the correct data to the onEnd callback.\n *\n * @private\n * @param {Error} [err] - Optional error.\n * @returns {undefined}\n */", "var", "done", "=", "_", ".", "once", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "onEnd", "(", "err", ")", ";", "}", "return", "onEnd", "(", "null", ",", "data", ")", ";", "}", ")", ";", "stream", ".", "once", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "data", "=", "chunk", ";", "}", ")", ";", "stream", ".", "on", "(", "'error'", ",", "done", ")", ";", "stream", ".", "on", "(", "'end'", ",", "done", ")", ";", "}" ]
Get the first item in a stream. @private @deprecated @static @since 0.0.4 @category Consumers @param {Stream} stream - Stream that will be read for this function. @param {Function} onEnd - Callback when the stream has been read completely. @returns {undefined}
[ "Get", "the", "first", "item", "in", "a", "stream", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/consumers/v1/first.js#L18-L42
40,285
stezu/node-stream
lib/consumers/v1/first.js
first
function first(stream, onEnd) { firstObj(stream, function (err, data) { if (err) { return onEnd(err); } return onEnd(null, new Buffer(data)); }); }
javascript
function first(stream, onEnd) { firstObj(stream, function (err, data) { if (err) { return onEnd(err); } return onEnd(null, new Buffer(data)); }); }
[ "function", "first", "(", "stream", ",", "onEnd", ")", "{", "firstObj", "(", "stream", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "return", "onEnd", "(", "err", ")", ";", "}", "return", "onEnd", "(", "null", ",", "new", "Buffer", "(", "data", ")", ")", ";", "}", ")", ";", "}" ]
Get the first item in a stream and convert to a buffer. @private @deprecated @static @since 0.0.4 @category Consumers @param {Stream} stream - Stream that will be read for this function. @param {Function} onEnd - Callback when the stream has been read completely. @returns {undefined}
[ "Get", "the", "first", "item", "in", "a", "stream", "and", "convert", "to", "a", "buffer", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/consumers/v1/first.js#L57-L67
40,286
stezu/node-stream
lib/consumers/v1/first.js
firstJson
function firstJson(stream, onEnd) { first(stream, function (err, data) { if (err) { return onEnd(err); } return parse(data, onEnd); }); }
javascript
function firstJson(stream, onEnd) { first(stream, function (err, data) { if (err) { return onEnd(err); } return parse(data, onEnd); }); }
[ "function", "firstJson", "(", "stream", ",", "onEnd", ")", "{", "first", "(", "stream", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "return", "onEnd", "(", "err", ")", ";", "}", "return", "parse", "(", "data", ",", "onEnd", ")", ";", "}", ")", ";", "}" ]
Get the first item in a stream and parse it for JSON. @private @deprecated @static @since 0.0.4 @category Consumers @param {Stream} stream - Stream that will be read for this function. @param {Function} onEnd - Callback when the stream has been read completely. @returns {undefined}
[ "Get", "the", "first", "item", "in", "a", "stream", "and", "parse", "it", "for", "JSON", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/consumers/v1/first.js#L82-L92
40,287
queicherius/promise-control-flow
src/index.js
parallel
function parallel (promiseFunctions, limit = Infinity, silenceErrors = false) { const contraMethod = (tasks, callback) => concurrent(tasks, limit, callback) return generatePromise(promiseFunctions, contraMethod, silenceErrors) }
javascript
function parallel (promiseFunctions, limit = Infinity, silenceErrors = false) { const contraMethod = (tasks, callback) => concurrent(tasks, limit, callback) return generatePromise(promiseFunctions, contraMethod, silenceErrors) }
[ "function", "parallel", "(", "promiseFunctions", ",", "limit", "=", "Infinity", ",", "silenceErrors", "=", "false", ")", "{", "const", "contraMethod", "=", "(", "tasks", ",", "callback", ")", "=>", "concurrent", "(", "tasks", ",", "limit", ",", "callback", ")", "return", "generatePromise", "(", "promiseFunctions", ",", "contraMethod", ",", "silenceErrors", ")", "}" ]
Work on the tasks in parallel, with a optional concurrency limit
[ "Work", "on", "the", "tasks", "in", "parallel", "with", "a", "optional", "concurrency", "limit" ]
19552ffe90e2f329271b830808393ee6499f4f68
https://github.com/queicherius/promise-control-flow/blob/19552ffe90e2f329271b830808393ee6499f4f68/src/index.js#L12-L15
40,288
queicherius/promise-control-flow
src/index.js
generatePromise
function generatePromise (promiseFunctions, contraMethod, silenceErrors) { return new Promise((resolve, reject) => { // Generate a function that executes the promise function and // calls back in a way that the contra library requires for (let i in promiseFunctions) { let promiseFunction = promiseFunctions[i] if (!isFunction(promiseFunction)) { return reject(new Error('One of the supplied promise functions is not a function')) } promiseFunctions[i] = (contraCallback) => { promiseFunction() .then(data => contraCallback(null, data)) .catch(err => silenceErrors ? contraCallback(null, null) : contraCallback(err)) } } contraMethod(promiseFunctions, (err, results) => { if (err) return reject(err) resolve(results) }) }) }
javascript
function generatePromise (promiseFunctions, contraMethod, silenceErrors) { return new Promise((resolve, reject) => { // Generate a function that executes the promise function and // calls back in a way that the contra library requires for (let i in promiseFunctions) { let promiseFunction = promiseFunctions[i] if (!isFunction(promiseFunction)) { return reject(new Error('One of the supplied promise functions is not a function')) } promiseFunctions[i] = (contraCallback) => { promiseFunction() .then(data => contraCallback(null, data)) .catch(err => silenceErrors ? contraCallback(null, null) : contraCallback(err)) } } contraMethod(promiseFunctions, (err, results) => { if (err) return reject(err) resolve(results) }) }) }
[ "function", "generatePromise", "(", "promiseFunctions", ",", "contraMethod", ",", "silenceErrors", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "// Generate a function that executes the promise function and", "// calls back in a way that the contra library requires", "for", "(", "let", "i", "in", "promiseFunctions", ")", "{", "let", "promiseFunction", "=", "promiseFunctions", "[", "i", "]", "if", "(", "!", "isFunction", "(", "promiseFunction", ")", ")", "{", "return", "reject", "(", "new", "Error", "(", "'One of the supplied promise functions is not a function'", ")", ")", "}", "promiseFunctions", "[", "i", "]", "=", "(", "contraCallback", ")", "=>", "{", "promiseFunction", "(", ")", ".", "then", "(", "data", "=>", "contraCallback", "(", "null", ",", "data", ")", ")", ".", "catch", "(", "err", "=>", "silenceErrors", "?", "contraCallback", "(", "null", ",", "null", ")", ":", "contraCallback", "(", "err", ")", ")", "}", "}", "contraMethod", "(", "promiseFunctions", ",", "(", "err", ",", "results", ")", "=>", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", "resolve", "(", "results", ")", "}", ")", "}", ")", "}" ]
Wrap the contra library with a promise, and convert the promise functions into callbacks
[ "Wrap", "the", "contra", "library", "with", "a", "promise", "and", "convert", "the", "promise", "functions", "into", "callbacks" ]
19552ffe90e2f329271b830808393ee6499f4f68
https://github.com/queicherius/promise-control-flow/blob/19552ffe90e2f329271b830808393ee6499f4f68/src/index.js#L18-L41
40,289
dominictarr/bipf
index.js
createSeekPathSrc
function createSeekPathSrc(target) { return ( '"use strict";\n' + //go fast sauce! target.map(function (e, i) { return ' var k'+i+' = Buffer.from('+ JSON.stringify(e) +');' //strings only! }).join('\n') + '\n'+ " return function (buffer, start) {\n"+ target.map(function (_, i) { return " start = seekKey(buffer, start, k"+i+")" }).join('\n') + '\n' + ' return start;\n'+ '}\n' ) }
javascript
function createSeekPathSrc(target) { return ( '"use strict";\n' + //go fast sauce! target.map(function (e, i) { return ' var k'+i+' = Buffer.from('+ JSON.stringify(e) +');' //strings only! }).join('\n') + '\n'+ " return function (buffer, start) {\n"+ target.map(function (_, i) { return " start = seekKey(buffer, start, k"+i+")" }).join('\n') + '\n' + ' return start;\n'+ '}\n' ) }
[ "function", "createSeekPathSrc", "(", "target", ")", "{", "return", "(", "'\"use strict\";\\n'", "+", "//go fast sauce!", "target", ".", "map", "(", "function", "(", "e", ",", "i", ")", "{", "return", "' var k'", "+", "i", "+", "' = Buffer.from('", "+", "JSON", ".", "stringify", "(", "e", ")", "+", "');'", "//strings only!", "}", ")", ".", "join", "(", "'\\n'", ")", "+", "'\\n'", "+", "\" return function (buffer, start) {\\n\"", "+", "target", ".", "map", "(", "function", "(", "_", ",", "i", ")", "{", "return", "\" start = seekKey(buffer, start, k\"", "+", "i", "+", "\")\"", "}", ")", ".", "join", "(", "'\\n'", ")", "+", "'\\n'", "+", "' return start;\\n'", "+", "'}\\n'", ")", "}" ]
for some reason, seek path
[ "for", "some", "reason", "seek", "path" ]
aca01838b706673cd7e64961466232fa8b97fc1c
https://github.com/dominictarr/bipf/blob/aca01838b706673cd7e64961466232fa8b97fc1c/index.js#L269-L282
40,290
ecomfe/edp-module-compiler
src/module.js
Module
function Module(moduleId, ctx, combineConfig) { this.moduleId = moduleId; this.compiler = ctx; this.combineConfig = combineConfig || ctx.getCombineConfig(moduleId); this.definition = null; this.prepare(); }
javascript
function Module(moduleId, ctx, combineConfig) { this.moduleId = moduleId; this.compiler = ctx; this.combineConfig = combineConfig || ctx.getCombineConfig(moduleId); this.definition = null; this.prepare(); }
[ "function", "Module", "(", "moduleId", ",", "ctx", ",", "combineConfig", ")", "{", "this", ".", "moduleId", "=", "moduleId", ";", "this", ".", "compiler", "=", "ctx", ";", "this", ".", "combineConfig", "=", "combineConfig", "||", "ctx", ".", "getCombineConfig", "(", "moduleId", ")", ";", "this", ".", "definition", "=", "null", ";", "this", ".", "prepare", "(", ")", ";", "}" ]
The module constructor @constructor @param {string} moduleId 模块的Id. @param {Compiler} ctx 整个Compiler的上下文环境,提供必要的api和保存一些全局的数据. @param {CombineConfig=} combineConfig combine配置信息.
[ "The", "module", "constructor" ]
4fa03db7bd7a059482d39af079b21bf7d47dc551
https://github.com/ecomfe/edp-module-compiler/blob/4fa03db7bd7a059482d39af079b21bf7d47dc551/src/module.js#L16-L22
40,291
bitbinio/bitbin
src/manifest.js
function(files) { var collection = {}; files.forEach(function(file) { var filename = file.name; if (!collection.hasOwnProperty(filename) || collection[filename].version < file.version) { collection[filename] = file; } }); return Object.keys(collection).map(function(name) { return collection[name]; }); }
javascript
function(files) { var collection = {}; files.forEach(function(file) { var filename = file.name; if (!collection.hasOwnProperty(filename) || collection[filename].version < file.version) { collection[filename] = file; } }); return Object.keys(collection).map(function(name) { return collection[name]; }); }
[ "function", "(", "files", ")", "{", "var", "collection", "=", "{", "}", ";", "files", ".", "forEach", "(", "function", "(", "file", ")", "{", "var", "filename", "=", "file", ".", "name", ";", "if", "(", "!", "collection", ".", "hasOwnProperty", "(", "filename", ")", "||", "collection", "[", "filename", "]", ".", "version", "<", "file", ".", "version", ")", "{", "collection", "[", "filename", "]", "=", "file", ";", "}", "}", ")", ";", "return", "Object", ".", "keys", "(", "collection", ")", ".", "map", "(", "function", "(", "name", ")", "{", "return", "collection", "[", "name", "]", ";", "}", ")", ";", "}" ]
Deduplicate the list of files. Only keep the most recent file versions. @param array files @return array
[ "Deduplicate", "the", "list", "of", "files", "." ]
fdb1734f9fd47234eec96d9e61a28e8cb3820e63
https://github.com/bitbinio/bitbin/blob/fdb1734f9fd47234eec96d9e61a28e8cb3820e63/src/manifest.js#L133-L144
40,292
damnit/metalsmith-htmlescape
lib/index.js
plugin
function plugin(options) { return function(files, metalsmith, done) { Object.keys(files).forEach(function(file) { var data = files[file]; data.contents = new Buffer(special(data.contents.toString())); }); done(); } }
javascript
function plugin(options) { return function(files, metalsmith, done) { Object.keys(files).forEach(function(file) { var data = files[file]; data.contents = new Buffer(special(data.contents.toString())); }); done(); } }
[ "function", "plugin", "(", "options", ")", "{", "return", "function", "(", "files", ",", "metalsmith", ",", "done", ")", "{", "Object", ".", "keys", "(", "files", ")", ".", "forEach", "(", "function", "(", "file", ")", "{", "var", "data", "=", "files", "[", "file", "]", ";", "data", ".", "contents", "=", "new", "Buffer", "(", "special", "(", "data", ".", "contents", ".", "toString", "(", ")", ")", ")", ";", "}", ")", ";", "done", "(", ")", ";", "}", "}" ]
Metalsmith plugin to sanitize special unicode chars in html @param {Object or String} options (optional) @return {Function}
[ "Metalsmith", "plugin", "to", "sanitize", "special", "unicode", "chars", "in", "html" ]
d0581c95dc21520b28f6884a8b52e8601998eeb6
https://github.com/damnit/metalsmith-htmlescape/blob/d0581c95dc21520b28f6884a8b52e8601998eeb6/lib/index.js#L17-L27
40,293
kevoree/kevoree-js
core/kevoree-core/kevoree-core.js
KevoreeCore
function KevoreeCore(resolver, kevscript, loggerFactory) { if (!resolver || !kevscript || !loggerFactory) { throw new Error('KevoreeCore constructor needs: Resolver, KevScript engine and a LoggerFactory'); } this.resolver = resolver; this.loggerFactory = loggerFactory; this.log = loggerFactory.create('Core'); this.kevs = kevscript; this.stopping = false; this.currentModel = null; this.deployModel = null; this.nodeName = null; this.nodeInstance = null; this.firstBoot = true; this.scriptQueue = []; this.emitter = new EventEmitter(); }
javascript
function KevoreeCore(resolver, kevscript, loggerFactory) { if (!resolver || !kevscript || !loggerFactory) { throw new Error('KevoreeCore constructor needs: Resolver, KevScript engine and a LoggerFactory'); } this.resolver = resolver; this.loggerFactory = loggerFactory; this.log = loggerFactory.create('Core'); this.kevs = kevscript; this.stopping = false; this.currentModel = null; this.deployModel = null; this.nodeName = null; this.nodeInstance = null; this.firstBoot = true; this.scriptQueue = []; this.emitter = new EventEmitter(); }
[ "function", "KevoreeCore", "(", "resolver", ",", "kevscript", ",", "loggerFactory", ")", "{", "if", "(", "!", "resolver", "||", "!", "kevscript", "||", "!", "loggerFactory", ")", "{", "throw", "new", "Error", "(", "'KevoreeCore constructor needs: Resolver, KevScript engine and a LoggerFactory'", ")", ";", "}", "this", ".", "resolver", "=", "resolver", ";", "this", ".", "loggerFactory", "=", "loggerFactory", ";", "this", ".", "log", "=", "loggerFactory", ".", "create", "(", "'Core'", ")", ";", "this", ".", "kevs", "=", "kevscript", ";", "this", ".", "stopping", "=", "false", ";", "this", ".", "currentModel", "=", "null", ";", "this", ".", "deployModel", "=", "null", ";", "this", ".", "nodeName", "=", "null", ";", "this", ".", "nodeInstance", "=", "null", ";", "this", ".", "firstBoot", "=", "true", ";", "this", ".", "scriptQueue", "=", "[", "]", ";", "this", ".", "emitter", "=", "new", "EventEmitter", "(", ")", ";", "}" ]
KevoreeCore is the kernel of the Kevoree JavaScript runtime @param {Resolver} resolver service to download the DeployUnits @param {KevScript} kevscript service to interpret the KevScript @param {LoggerFactory} loggerFactory service to create loggers @throws {Error} undefined constructor params @constructor
[ "KevoreeCore", "is", "the", "kernel", "of", "the", "Kevoree", "JavaScript", "runtime" ]
7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd
https://github.com/kevoree/kevoree-js/blob/7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd/core/kevoree-core/kevoree-core.js#L16-L33
40,294
stezu/node-stream
lib/modifiers/filter.js
filter
function filter(condition) { var cb = makeAsync(condition, 2); return through.obj(function (chunk, enc, next) { cb(chunk, function (err, keep) { if (err) { return next(err); } if (keep) { return next(null, chunk); } return next(); }); }); }
javascript
function filter(condition) { var cb = makeAsync(condition, 2); return through.obj(function (chunk, enc, next) { cb(chunk, function (err, keep) { if (err) { return next(err); } if (keep) { return next(null, chunk); } return next(); }); }); }
[ "function", "filter", "(", "condition", ")", "{", "var", "cb", "=", "makeAsync", "(", "condition", ",", "2", ")", ";", "return", "through", ".", "obj", "(", "function", "(", "chunk", ",", "enc", ",", "next", ")", "{", "cb", "(", "chunk", ",", "function", "(", "err", ",", "keep", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", ";", "}", "if", "(", "keep", ")", "{", "return", "next", "(", "null", ",", "chunk", ")", ";", "}", "return", "next", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Creates a new stream with all elements that pass the test implemented by the provided function. Similar to Array.filter... but on a stream. @static @since 1.0.0 @category Modifiers @param {Function} condition - Function that filters elements on the stream. Takes one argument, the value of the item at this position in the stream. @returns {Stream.Transform} - A transform stream with the filtered values. @example // If you wanted to create a new stream whose values all passed a certain criteria, // you could do something like the following. Assuming "test-scores.txt" is a file // containing the following data: // Sally...90 // Tommy...94 // Jimmy...12 // Sarah...82 // Jonny...64 // We can write a function that returns the students who are failing: fs.createReadStream('test-scores.txt') .pipe(nodeStream.split()) // split on new lines .pipe(nodeStream.filter(value => { const [student, testScore] = value.toString().split('...'); return Number(testScore) < 70; })); // The resulting stream would have the following data: // Jimmy...12 // Jonny...64 @example // It is also possible to filter a stream asynchronously for more complex actions. // Note: The signature of the function that you pass as the callback is important. It // MUST have *two* parameters. // Assuming "filenames.txt" is a newline-separated list of file names, you could // create a new stream with only valid names by doing something like the following: fs.createReadStream('filenames.txt') .pipe(nodeStream.split()) // split on new lines .pipe(nodeStream.filter((value, next) => { fs.stat(value, (err, stats) => { // Error the stream since this file is not valid if (err) { return next(err); } next(null, stats.isFile()); }); })); // The resulting stream will contain the filenames that passed the test. Note: If `next` // is called with an error as the first argument, the stream will error. This is typical // behavior for node callbacks.
[ "Creates", "a", "new", "stream", "with", "all", "elements", "that", "pass", "the", "test", "implemented", "by", "the", "provided", "function", ".", "Similar", "to", "Array", ".", "filter", "...", "but", "on", "a", "stream", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/modifiers/filter.js#L68-L86
40,295
stezu/node-stream
lib/creators/fromArray.js
fromArray
function fromArray(source) { var data; if (!Array.isArray(source)) { throw new TypeError('Expected `source` to be an array.'); } // Copy the source array so we can modify it at will data = source.slice(); return new Readable({ objectMode: true, read: function () { if (data.length > 0) { this.push(data.shift()); } else { this.push(null); } } }); }
javascript
function fromArray(source) { var data; if (!Array.isArray(source)) { throw new TypeError('Expected `source` to be an array.'); } // Copy the source array so we can modify it at will data = source.slice(); return new Readable({ objectMode: true, read: function () { if (data.length > 0) { this.push(data.shift()); } else { this.push(null); } } }); }
[ "function", "fromArray", "(", "source", ")", "{", "var", "data", ";", "if", "(", "!", "Array", ".", "isArray", "(", "source", ")", ")", "{", "throw", "new", "TypeError", "(", "'Expected `source` to be an array.'", ")", ";", "}", "// Copy the source array so we can modify it at will", "data", "=", "source", ".", "slice", "(", ")", ";", "return", "new", "Readable", "(", "{", "objectMode", ":", "true", ",", "read", ":", "function", "(", ")", "{", "if", "(", "data", ".", "length", ">", "0", ")", "{", "this", ".", "push", "(", "data", ".", "shift", "(", ")", ")", ";", "}", "else", "{", "this", ".", "push", "(", "null", ")", ";", "}", "}", "}", ")", ";", "}" ]
Creates a new readable stream from an array. This is primarily useful for piping into additional node-stream methods like map, reduce and filter. @static @since 1.6.0 @category Creators @param {Array} source - An array which will be converted to a stream. If an item in the array is `null` the stream will end early. Every other data type is allowed and valid. @returns {Stream.Readable} - Readable stream. @throws {TypeError} - If `source` is not an array. @example // Create a stream from an array which is then piped to another node-stream method nodeStream.fromArray(['file1.txt', 'file2.txt', 'file3.txt']) .pipe(nodeStream.map(fs.readFile)); // => ['contents of file1.txt', 'contents of file2.txt', 'contents of file3.txt']
[ "Creates", "a", "new", "readable", "stream", "from", "an", "array", ".", "This", "is", "primarily", "useful", "for", "piping", "into", "additional", "node", "-", "stream", "methods", "like", "map", "reduce", "and", "filter", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/creators/fromArray.js#L25-L46
40,296
joeyespo/gesso.js
client/delegate.js
Delegate
function Delegate(subscribed, unsubscribed) { var handlers = []; function callable(handler) { if (arguments.length !== 1) { throw new Error('Delegate takes exactly 1 argument (' + arguments.length + ' given)'); } else if (typeof handler !== 'function') { throw new Error('Delegate argument must be a Function object (got ' + typeof handler + ')'); } // Add the handler handlers.push(handler); // Allow custom logic on subscribe, passing in the handler var subscribedResult; if (subscribed) { subscribedResult = subscribed(handler); } // Return the unsubscribe function return function unsubscribe() { var initialHandler = util.removeLast(handlers, handler); // Allow custom logic on unsubscribe, passing in the original handler if (unsubscribed) { unsubscribed(initialHandler, subscribedResult); } // Return the original handler return initialHandler; }; } callable.invoke = function invoke() { var args = arguments; util.forEach(handlers, function (handler) { handler.apply(null, args); }); }; // Expose handlers for inspection callable.handlers = handlers; return callable; }
javascript
function Delegate(subscribed, unsubscribed) { var handlers = []; function callable(handler) { if (arguments.length !== 1) { throw new Error('Delegate takes exactly 1 argument (' + arguments.length + ' given)'); } else if (typeof handler !== 'function') { throw new Error('Delegate argument must be a Function object (got ' + typeof handler + ')'); } // Add the handler handlers.push(handler); // Allow custom logic on subscribe, passing in the handler var subscribedResult; if (subscribed) { subscribedResult = subscribed(handler); } // Return the unsubscribe function return function unsubscribe() { var initialHandler = util.removeLast(handlers, handler); // Allow custom logic on unsubscribe, passing in the original handler if (unsubscribed) { unsubscribed(initialHandler, subscribedResult); } // Return the original handler return initialHandler; }; } callable.invoke = function invoke() { var args = arguments; util.forEach(handlers, function (handler) { handler.apply(null, args); }); }; // Expose handlers for inspection callable.handlers = handlers; return callable; }
[ "function", "Delegate", "(", "subscribed", ",", "unsubscribed", ")", "{", "var", "handlers", "=", "[", "]", ";", "function", "callable", "(", "handler", ")", "{", "if", "(", "arguments", ".", "length", "!==", "1", ")", "{", "throw", "new", "Error", "(", "'Delegate takes exactly 1 argument ('", "+", "arguments", ".", "length", "+", "' given)'", ")", ";", "}", "else", "if", "(", "typeof", "handler", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "'Delegate argument must be a Function object (got '", "+", "typeof", "handler", "+", "')'", ")", ";", "}", "// Add the handler", "handlers", ".", "push", "(", "handler", ")", ";", "// Allow custom logic on subscribe, passing in the handler", "var", "subscribedResult", ";", "if", "(", "subscribed", ")", "{", "subscribedResult", "=", "subscribed", "(", "handler", ")", ";", "}", "// Return the unsubscribe function", "return", "function", "unsubscribe", "(", ")", "{", "var", "initialHandler", "=", "util", ".", "removeLast", "(", "handlers", ",", "handler", ")", ";", "// Allow custom logic on unsubscribe, passing in the original handler", "if", "(", "unsubscribed", ")", "{", "unsubscribed", "(", "initialHandler", ",", "subscribedResult", ")", ";", "}", "// Return the original handler", "return", "initialHandler", ";", "}", ";", "}", "callable", ".", "invoke", "=", "function", "invoke", "(", ")", "{", "var", "args", "=", "arguments", ";", "util", ".", "forEach", "(", "handlers", ",", "function", "(", "handler", ")", "{", "handler", ".", "apply", "(", "null", ",", "args", ")", ";", "}", ")", ";", "}", ";", "// Expose handlers for inspection", "callable", ".", "handlers", "=", "handlers", ";", "return", "callable", ";", "}" ]
Returns a callable object that, when called with a function, subscribes to the delegate. Call invoke on this object to invoke each handler.
[ "Returns", "a", "callable", "object", "that", "when", "called", "with", "a", "function", "subscribes", "to", "the", "delegate", ".", "Call", "invoke", "on", "this", "object", "to", "invoke", "each", "handler", "." ]
b4858dfc607aab13342474930c174b5b82f98267
https://github.com/joeyespo/gesso.js/blob/b4858dfc607aab13342474930c174b5b82f98267/client/delegate.js#L5-L42
40,297
wanderview/node-netbios-name
name.js
_decompressName
function _decompressName(buf, offset) { var name = ''; var bytes = 0; var octet = buf.readUInt8(offset + bytes); bytes += 1; // The name is made up of a variable number of labels. Each label begins // with a length octet. The string of labels is ended by a zero length octet. while (octet) { var label = null; // The first 2-bits of the octet are flags indicating if this is a length // value or a label pointer to elsewhere in the packet. var flags = octet & 0xc0; // If both the top 2-bits of the octet are set, then this is an offset pointer. if (flags === 0xc0) { // NOTE: The number of bytes parsed was already incremented. We need // to re-read that first byte to incorporate it into our pointer // value. Therefore subtract one from the offset and only add // one additional byte to the parsed count. var pointer = buf.readUInt16BE(offset + bytes - 1) & 0x3fff; bytes += 1; // NOTE: This will only work if the start of the buffer corresponds to // the start of the packet. If the packet is embedded in a larger // buffer then we need to pass through the offset to the start of // the packet. var res = _decompressName(buf, pointer); if (res.error) { return res; } label = res.name; if (!label) { return {bytesRead: bytes, name: name} } // Once a pointer is used the name section is complete. We do not need // to keep looking for a zero length octet. Note there is some logic at // the end of the loop we still want to execute, so simply set octet to // zero to terminate the loop instead of breaking. octet = 0; // If neither of the bits are set then the name is stored inline in the // following bytes. The name length is defined by the lower 6-bits of the // octet. } else if (flags === 0) { var length = octet & 0x3f; if (offset + bytes + length > buf.length) { return { error: new Error('Name label too large to fit in remaining packet ' + 'bytes.') }; } label = buf.toString('ascii', offset + bytes, offset + bytes + length); bytes += length; // Look for the next label's length octet octet = buf.readUInt8(offset + bytes); bytes += 1; // Any other values are undefined, so throw an error. } else { return { error: new Error('Label length octet at offset [' + (offset + bytes - 1) + '] has unexpected top 2-bits ' + 'of [' + flags + ']; should be [' + 0xc0 + '] or ' + '[0].') }; } // Append to the last parsed label to the name. Separate labels with // periods. if (name.length > 0) { name += '.'; } name += label; } return {bytesRead: bytes, name: name}; }
javascript
function _decompressName(buf, offset) { var name = ''; var bytes = 0; var octet = buf.readUInt8(offset + bytes); bytes += 1; // The name is made up of a variable number of labels. Each label begins // with a length octet. The string of labels is ended by a zero length octet. while (octet) { var label = null; // The first 2-bits of the octet are flags indicating if this is a length // value or a label pointer to elsewhere in the packet. var flags = octet & 0xc0; // If both the top 2-bits of the octet are set, then this is an offset pointer. if (flags === 0xc0) { // NOTE: The number of bytes parsed was already incremented. We need // to re-read that first byte to incorporate it into our pointer // value. Therefore subtract one from the offset and only add // one additional byte to the parsed count. var pointer = buf.readUInt16BE(offset + bytes - 1) & 0x3fff; bytes += 1; // NOTE: This will only work if the start of the buffer corresponds to // the start of the packet. If the packet is embedded in a larger // buffer then we need to pass through the offset to the start of // the packet. var res = _decompressName(buf, pointer); if (res.error) { return res; } label = res.name; if (!label) { return {bytesRead: bytes, name: name} } // Once a pointer is used the name section is complete. We do not need // to keep looking for a zero length octet. Note there is some logic at // the end of the loop we still want to execute, so simply set octet to // zero to terminate the loop instead of breaking. octet = 0; // If neither of the bits are set then the name is stored inline in the // following bytes. The name length is defined by the lower 6-bits of the // octet. } else if (flags === 0) { var length = octet & 0x3f; if (offset + bytes + length > buf.length) { return { error: new Error('Name label too large to fit in remaining packet ' + 'bytes.') }; } label = buf.toString('ascii', offset + bytes, offset + bytes + length); bytes += length; // Look for the next label's length octet octet = buf.readUInt8(offset + bytes); bytes += 1; // Any other values are undefined, so throw an error. } else { return { error: new Error('Label length octet at offset [' + (offset + bytes - 1) + '] has unexpected top 2-bits ' + 'of [' + flags + ']; should be [' + 0xc0 + '] or ' + '[0].') }; } // Append to the last parsed label to the name. Separate labels with // periods. if (name.length > 0) { name += '.'; } name += label; } return {bytesRead: bytes, name: name}; }
[ "function", "_decompressName", "(", "buf", ",", "offset", ")", "{", "var", "name", "=", "''", ";", "var", "bytes", "=", "0", ";", "var", "octet", "=", "buf", ".", "readUInt8", "(", "offset", "+", "bytes", ")", ";", "bytes", "+=", "1", ";", "// The name is made up of a variable number of labels. Each label begins", "// with a length octet. The string of labels is ended by a zero length octet.", "while", "(", "octet", ")", "{", "var", "label", "=", "null", ";", "// The first 2-bits of the octet are flags indicating if this is a length", "// value or a label pointer to elsewhere in the packet.", "var", "flags", "=", "octet", "&", "0xc0", ";", "// If both the top 2-bits of the octet are set, then this is an offset pointer.", "if", "(", "flags", "===", "0xc0", ")", "{", "// NOTE: The number of bytes parsed was already incremented. We need", "// to re-read that first byte to incorporate it into our pointer", "// value. Therefore subtract one from the offset and only add", "// one additional byte to the parsed count.", "var", "pointer", "=", "buf", ".", "readUInt16BE", "(", "offset", "+", "bytes", "-", "1", ")", "&", "0x3fff", ";", "bytes", "+=", "1", ";", "// NOTE: This will only work if the start of the buffer corresponds to", "// the start of the packet. If the packet is embedded in a larger", "// buffer then we need to pass through the offset to the start of", "// the packet.", "var", "res", "=", "_decompressName", "(", "buf", ",", "pointer", ")", ";", "if", "(", "res", ".", "error", ")", "{", "return", "res", ";", "}", "label", "=", "res", ".", "name", ";", "if", "(", "!", "label", ")", "{", "return", "{", "bytesRead", ":", "bytes", ",", "name", ":", "name", "}", "}", "// Once a pointer is used the name section is complete. We do not need", "// to keep looking for a zero length octet. Note there is some logic at", "// the end of the loop we still want to execute, so simply set octet to", "// zero to terminate the loop instead of breaking.", "octet", "=", "0", ";", "// If neither of the bits are set then the name is stored inline in the", "// following bytes. The name length is defined by the lower 6-bits of the", "// octet.", "}", "else", "if", "(", "flags", "===", "0", ")", "{", "var", "length", "=", "octet", "&", "0x3f", ";", "if", "(", "offset", "+", "bytes", "+", "length", ">", "buf", ".", "length", ")", "{", "return", "{", "error", ":", "new", "Error", "(", "'Name label too large to fit in remaining packet '", "+", "'bytes.'", ")", "}", ";", "}", "label", "=", "buf", ".", "toString", "(", "'ascii'", ",", "offset", "+", "bytes", ",", "offset", "+", "bytes", "+", "length", ")", ";", "bytes", "+=", "length", ";", "// Look for the next label's length octet", "octet", "=", "buf", ".", "readUInt8", "(", "offset", "+", "bytes", ")", ";", "bytes", "+=", "1", ";", "// Any other values are undefined, so throw an error.", "}", "else", "{", "return", "{", "error", ":", "new", "Error", "(", "'Label length octet at offset ['", "+", "(", "offset", "+", "bytes", "-", "1", ")", "+", "'] has unexpected top 2-bits '", "+", "'of ['", "+", "flags", "+", "']; should be ['", "+", "0xc0", "+", "'] or '", "+", "'[0].'", ")", "}", ";", "}", "// Append to the last parsed label to the name. Separate labels with", "// periods.", "if", "(", "name", ".", "length", ">", "0", ")", "{", "name", "+=", "'.'", ";", "}", "name", "+=", "label", ";", "}", "return", "{", "bytesRead", ":", "bytes", ",", "name", ":", "name", "}", ";", "}" ]
Decompress the name from the packet. The compression scheme is defined in RFC 883 and is the same method used in DNS packets. Essentially, names are stored in parts called labels. Each label is preceded by a 2-bit flag field and 6-bit length field. In the common case the 2-bits are zero and the length indicates how many bytes are in that label. The parsing process is terminated by a zero length label. Alternatively, a the 2-bit flags can both be set indicating a label pointer. In that case the following 14-bits indicate an offset into the packet from which to read the remaining labels for the name.
[ "Decompress", "the", "name", "from", "the", "packet", ".", "The", "compression", "scheme", "is", "defined", "in", "RFC", "883", "and", "is", "the", "same", "method", "used", "in", "DNS", "packets", ".", "Essentially", "names", "are", "stored", "in", "parts", "called", "labels", ".", "Each", "label", "is", "preceded", "by", "a", "2", "-", "bit", "flag", "field", "and", "6", "-", "bit", "length", "field", ".", "In", "the", "common", "case", "the", "2", "-", "bits", "are", "zero", "and", "the", "length", "indicates", "how", "many", "bytes", "are", "in", "that", "label", ".", "The", "parsing", "process", "is", "terminated", "by", "a", "zero", "length", "label", ".", "Alternatively", "a", "the", "2", "-", "bit", "flags", "can", "both", "be", "set", "indicating", "a", "label", "pointer", ".", "In", "that", "case", "the", "following", "14", "-", "bits", "indicate", "an", "offset", "into", "the", "packet", "from", "which", "to", "read", "the", "remaining", "labels", "for", "the", "name", "." ]
d803bedf260e572ab3470a36d4ddef8ce5bc3d45
https://github.com/wanderview/node-netbios-name/blob/d803bedf260e572ab3470a36d4ddef8ce5bc3d45/name.js#L187-L272
40,298
wanderview/node-netbios-name
name.js
_decodeName
function _decodeName (name) { var encoded = name; var periodIndex = name.indexOf('.'); if (periodIndex > -1) { encoded = name.slice(0, periodIndex); } var decoded = ''; var suffix = 0; var charValue = 0;; for (var i = 0, n = encoded.length; i < n; ++i) { // decode char to first nibble if (i % 2 === 0) { charValue = (encoded.charCodeAt(i) - 'A'.charCodeAt(0)) << 4; // decore char to second nibble and then combine with first nibble } else { charValue += encoded.charCodeAt(i) - 'A'.charCodeAt(0); // Append the newly decoded character for the first 15 bytes if (i < (encoded.length - 1)) { decoded += String.fromCharCode(charValue); // The last byte is reserved by convention as the suffix or type } else { suffix = charValue; } } } // NetBIOS names are always space padded out to 15 characters decoded = decoded.trim(); // If there was a scope identifier (domain name) after the NetBIOS name // then re-append it to the newly decoded name. if (periodIndex > -1) { decoded += name.slice(periodIndex); } return {fqdn: decoded, suffix: suffix}; }
javascript
function _decodeName (name) { var encoded = name; var periodIndex = name.indexOf('.'); if (periodIndex > -1) { encoded = name.slice(0, periodIndex); } var decoded = ''; var suffix = 0; var charValue = 0;; for (var i = 0, n = encoded.length; i < n; ++i) { // decode char to first nibble if (i % 2 === 0) { charValue = (encoded.charCodeAt(i) - 'A'.charCodeAt(0)) << 4; // decore char to second nibble and then combine with first nibble } else { charValue += encoded.charCodeAt(i) - 'A'.charCodeAt(0); // Append the newly decoded character for the first 15 bytes if (i < (encoded.length - 1)) { decoded += String.fromCharCode(charValue); // The last byte is reserved by convention as the suffix or type } else { suffix = charValue; } } } // NetBIOS names are always space padded out to 15 characters decoded = decoded.trim(); // If there was a scope identifier (domain name) after the NetBIOS name // then re-append it to the newly decoded name. if (periodIndex > -1) { decoded += name.slice(periodIndex); } return {fqdn: decoded, suffix: suffix}; }
[ "function", "_decodeName", "(", "name", ")", "{", "var", "encoded", "=", "name", ";", "var", "periodIndex", "=", "name", ".", "indexOf", "(", "'.'", ")", ";", "if", "(", "periodIndex", ">", "-", "1", ")", "{", "encoded", "=", "name", ".", "slice", "(", "0", ",", "periodIndex", ")", ";", "}", "var", "decoded", "=", "''", ";", "var", "suffix", "=", "0", ";", "var", "charValue", "=", "0", ";", ";", "for", "(", "var", "i", "=", "0", ",", "n", "=", "encoded", ".", "length", ";", "i", "<", "n", ";", "++", "i", ")", "{", "// decode char to first nibble", "if", "(", "i", "%", "2", "===", "0", ")", "{", "charValue", "=", "(", "encoded", ".", "charCodeAt", "(", "i", ")", "-", "'A'", ".", "charCodeAt", "(", "0", ")", ")", "<<", "4", ";", "// decore char to second nibble and then combine with first nibble", "}", "else", "{", "charValue", "+=", "encoded", ".", "charCodeAt", "(", "i", ")", "-", "'A'", ".", "charCodeAt", "(", "0", ")", ";", "// Append the newly decoded character for the first 15 bytes", "if", "(", "i", "<", "(", "encoded", ".", "length", "-", "1", ")", ")", "{", "decoded", "+=", "String", ".", "fromCharCode", "(", "charValue", ")", ";", "// The last byte is reserved by convention as the suffix or type", "}", "else", "{", "suffix", "=", "charValue", ";", "}", "}", "}", "// NetBIOS names are always space padded out to 15 characters", "decoded", "=", "decoded", ".", "trim", "(", ")", ";", "// If there was a scope identifier (domain name) after the NetBIOS name", "// then re-append it to the newly decoded name.", "if", "(", "periodIndex", ">", "-", "1", ")", "{", "decoded", "+=", "name", ".", "slice", "(", "periodIndex", ")", ";", "}", "return", "{", "fqdn", ":", "decoded", ",", "suffix", ":", "suffix", "}", ";", "}" ]
Decode the NetBIOS name after it has been decompressed. The NetBIOS name is represented as the first part of the FQDN. See page 26 of RFC 1001 for full details on the encoding algorithm. In short, each byte of the original NetBIOS name is split into two nibbles. Each nibble is then encoded as a separate byte by adding the ASCII value for 'A'. In order to decode we therefore must reverse this logic.
[ "Decode", "the", "NetBIOS", "name", "after", "it", "has", "been", "decompressed", ".", "The", "NetBIOS", "name", "is", "represented", "as", "the", "first", "part", "of", "the", "FQDN", ".", "See", "page", "26", "of", "RFC", "1001", "for", "full", "details", "on", "the", "encoding", "algorithm", ".", "In", "short", "each", "byte", "of", "the", "original", "NetBIOS", "name", "is", "split", "into", "two", "nibbles", ".", "Each", "nibble", "is", "then", "encoded", "as", "a", "separate", "byte", "by", "adding", "the", "ASCII", "value", "for", "A", ".", "In", "order", "to", "decode", "we", "therefore", "must", "reverse", "this", "logic", "." ]
d803bedf260e572ab3470a36d4ddef8ce5bc3d45
https://github.com/wanderview/node-netbios-name/blob/d803bedf260e572ab3470a36d4ddef8ce5bc3d45/name.js#L280-L322
40,299
stezu/node-stream
lib/creators/fromPromise.js
fromPromise
function fromPromise(source) { var callCount = 0; // Throw an error if the source is not a promise if ( typeof source !== 'object' || source === null || typeof source.then !== 'function' ) { throw new TypeError('Expected `source` to be a promise.'); } return new Readable({ objectMode: true, read: function () { var self = this; // Increment the number of calls so we know when to push null callCount += 1; // Listen to the promise and push results if this is the first call if (callCount === 1) { source.then( function onResolve(data) { self.push(data); }, function onReject(err) { process.nextTick(function () { self.emit('error', err); }); } ); return; } // End the stream self.push(null); } }); }
javascript
function fromPromise(source) { var callCount = 0; // Throw an error if the source is not a promise if ( typeof source !== 'object' || source === null || typeof source.then !== 'function' ) { throw new TypeError('Expected `source` to be a promise.'); } return new Readable({ objectMode: true, read: function () { var self = this; // Increment the number of calls so we know when to push null callCount += 1; // Listen to the promise and push results if this is the first call if (callCount === 1) { source.then( function onResolve(data) { self.push(data); }, function onReject(err) { process.nextTick(function () { self.emit('error', err); }); } ); return; } // End the stream self.push(null); } }); }
[ "function", "fromPromise", "(", "source", ")", "{", "var", "callCount", "=", "0", ";", "// Throw an error if the source is not a promise", "if", "(", "typeof", "source", "!==", "'object'", "||", "source", "===", "null", "||", "typeof", "source", ".", "then", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", "'Expected `source` to be a promise.'", ")", ";", "}", "return", "new", "Readable", "(", "{", "objectMode", ":", "true", ",", "read", ":", "function", "(", ")", "{", "var", "self", "=", "this", ";", "// Increment the number of calls so we know when to push null", "callCount", "+=", "1", ";", "// Listen to the promise and push results if this is the first call", "if", "(", "callCount", "===", "1", ")", "{", "source", ".", "then", "(", "function", "onResolve", "(", "data", ")", "{", "self", ".", "push", "(", "data", ")", ";", "}", ",", "function", "onReject", "(", "err", ")", "{", "process", ".", "nextTick", "(", "function", "(", ")", "{", "self", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", ")", ";", "}", ")", ";", "return", ";", "}", "// End the stream", "self", ".", "push", "(", "null", ")", ";", "}", "}", ")", ";", "}" ]
Creates a new readable stream from a promise. This is primarily useful for piping into additional node-stream methods like map, reduce and filter. @static @since 1.6.0 @category Creators @param {Promise} source - A promise which will be converted to a stream. If the promise resolves, each argument becomes a discrete item in the stream. If the promise rejects, the stream will emit an "error" event. @returns {Stream.Readable} - Readable stream. @throws {TypeError} - If `source` is not a promise. @example // Create a stream from a promise nodeStream.fromPromise(globby('*.js')) .pipe(nodeStream.map(fs.readFile)); // => ['contents of file1.js', 'contents of file2.js', 'contents of file3.js']
[ "Creates", "a", "new", "readable", "stream", "from", "a", "promise", ".", "This", "is", "primarily", "useful", "for", "piping", "into", "additional", "node", "-", "stream", "methods", "like", "map", "reduce", "and", "filter", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/creators/fromPromise.js#L25-L66