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
partition
stringclasses
1 value
switer/Zect
lib/zect.js
getComponent
function getComponent(tn) { var cid = tn.toLowerCase() var compDef components.some(function (comp) { if (comp.hasOwnProperty(cid)) { compDef = comp[cid] return true } }) return compDef }
javascript
function getComponent(tn) { var cid = tn.toLowerCase() var compDef components.some(function (comp) { if (comp.hasOwnProperty(cid)) { compDef = comp[cid] return true } }) return compDef }
[ "function", "getComponent", "(", "tn", ")", "{", "var", "cid", "=", "tn", ".", "toLowerCase", "(", ")", "var", "compDef", "components", ".", "some", "(", "function", "(", "comp", ")", "{", "if", "(", "comp", ".", "hasOwnProperty", "(", "cid", ")", ")", "{", "compDef", "=", "comp", "[", "cid", "]", "return", "true", "}", "}", ")", "return", "compDef", "}" ]
Reverse component Constructor by tagName
[ "Reverse", "component", "Constructor", "by", "tagName" ]
88b92d62d5000d999c3043e6379790f79608bdfa
https://github.com/switer/Zect/blob/88b92d62d5000d999c3043e6379790f79608bdfa/lib/zect.js#L399-L409
train
switer/Zect
lib/zect.js
compileElement
function compileElement(node, scope, isRoot) { var tagName = node.tagName var inst switch(true) { /** * <*-if></*-if> */ case is.IfElement(tagName): var children = _slice(node.children) var exprs = [$(node).attr('is')] children.forEach(function(c) { if (is.ElseElement(c)) { exprs.push($(c).attr(conf.namespace + 'else') || '') } }) inst = new ElementDirective( vm, scope, node, elements['if'], NS + 'if', exprs ) if (!isRoot) { inst.$mount(node) } // save elements refs _directives.push(inst) // save bindins to scope _setBindings2Scope(scope, inst) return inst /** * <*-repeat></*-repeat> */ case is.RepeatElement(tagName): inst = new ElementDirective( vm, scope, node, elements.repeat, NS + 'repeat', $(node).attr('items') ) if (!isRoot) { inst.$mount(node) } _directives.push(inst) _setBindings2Scope(scope, inst) return inst } }
javascript
function compileElement(node, scope, isRoot) { var tagName = node.tagName var inst switch(true) { /** * <*-if></*-if> */ case is.IfElement(tagName): var children = _slice(node.children) var exprs = [$(node).attr('is')] children.forEach(function(c) { if (is.ElseElement(c)) { exprs.push($(c).attr(conf.namespace + 'else') || '') } }) inst = new ElementDirective( vm, scope, node, elements['if'], NS + 'if', exprs ) if (!isRoot) { inst.$mount(node) } // save elements refs _directives.push(inst) // save bindins to scope _setBindings2Scope(scope, inst) return inst /** * <*-repeat></*-repeat> */ case is.RepeatElement(tagName): inst = new ElementDirective( vm, scope, node, elements.repeat, NS + 'repeat', $(node).attr('items') ) if (!isRoot) { inst.$mount(node) } _directives.push(inst) _setBindings2Scope(scope, inst) return inst } }
[ "function", "compileElement", "(", "node", ",", "scope", ",", "isRoot", ")", "{", "var", "tagName", "=", "node", ".", "tagName", "var", "inst", "switch", "(", "true", ")", "{", "case", "is", ".", "IfElement", "(", "tagName", ")", ":", "var", "children", "=", "_slice", "(", "node", ".", "children", ")", "var", "exprs", "=", "[", "$", "(", "node", ")", ".", "attr", "(", "'is'", ")", "]", "children", ".", "forEach", "(", "function", "(", "c", ")", "{", "if", "(", "is", ".", "ElseElement", "(", "c", ")", ")", "{", "exprs", ".", "push", "(", "$", "(", "c", ")", ".", "attr", "(", "conf", ".", "namespace", "+", "'else'", ")", "||", "''", ")", "}", "}", ")", "inst", "=", "new", "ElementDirective", "(", "vm", ",", "scope", ",", "node", ",", "elements", "[", "'if'", "]", ",", "NS", "+", "'if'", ",", "exprs", ")", "if", "(", "!", "isRoot", ")", "{", "inst", ".", "$mount", "(", "node", ")", "}", "_directives", ".", "push", "(", "inst", ")", "_setBindings2Scope", "(", "scope", ",", "inst", ")", "return", "inst", "case", "is", ".", "RepeatElement", "(", "tagName", ")", ":", "inst", "=", "new", "ElementDirective", "(", "vm", ",", "scope", ",", "node", ",", "elements", ".", "repeat", ",", "NS", "+", "'repeat'", ",", "$", "(", "node", ")", ".", "attr", "(", "'items'", ")", ")", "if", "(", "!", "isRoot", ")", "{", "inst", ".", "$mount", "(", "node", ")", "}", "_directives", ".", "push", "(", "inst", ")", "_setBindings2Scope", "(", "scope", ",", "inst", ")", "return", "inst", "}", "}" ]
Compile element for block syntax handling
[ "Compile", "element", "for", "block", "syntax", "handling" ]
88b92d62d5000d999c3043e6379790f79608bdfa
https://github.com/switer/Zect/blob/88b92d62d5000d999c3043e6379790f79608bdfa/lib/zect.js#L413-L463
train
switer/Zect
lib/zect.js
compileDirective
function compileDirective (node, scope) { var ast = { attrs: {}, dires: {} } var dirtDefs = _getAllDirts() /** * attributes walk */ _slice(node.attributes).forEach(function(att) { var aname = att.name var v = att.value // parse att if (~componentProps.indexOf(aname)) { return } else if (_isExpr(aname)) { // variable attribute name ast.attrs[aname] = v } else if (aname.indexOf(NS) === 0) { var def = dirtDefs[aname] if (def) { // directive ast.dires[aname] = { def: def, expr: v } } else { return } } else if (_isExpr(v.trim())) { // named attribute with expression ast.attrs[aname] = v } else { return } node.removeAttribute(aname) }) /** * Attributes binding */ util.objEach(ast.attrs, function(name, value) { var attd = new AttributeDirective(vm, scope, node, name, value) _directives.push(attd) _setBindings2Scope(scope, attd) }) /** * Directives binding */ util.objEach(ast.dires, function(dname, spec) { var def = spec.def var expr = spec.expr var sep = ';' var d // multiple defines expression parse if (def.multi && expr.match(sep)) { Expression.strip(expr) .split(sep) .forEach(function(item) { // discard empty expression if (!item.trim()) return d = new Directive(vm, scope, node, def, dname, '{' + item + '}') _directives.push(d) _setBindings2Scope(scope, d) }) } else { d = new Directive(vm, scope, node, def, dname, expr) _directives.push(d) _setBindings2Scope(scope, d) } }) }
javascript
function compileDirective (node, scope) { var ast = { attrs: {}, dires: {} } var dirtDefs = _getAllDirts() /** * attributes walk */ _slice(node.attributes).forEach(function(att) { var aname = att.name var v = att.value // parse att if (~componentProps.indexOf(aname)) { return } else if (_isExpr(aname)) { // variable attribute name ast.attrs[aname] = v } else if (aname.indexOf(NS) === 0) { var def = dirtDefs[aname] if (def) { // directive ast.dires[aname] = { def: def, expr: v } } else { return } } else if (_isExpr(v.trim())) { // named attribute with expression ast.attrs[aname] = v } else { return } node.removeAttribute(aname) }) /** * Attributes binding */ util.objEach(ast.attrs, function(name, value) { var attd = new AttributeDirective(vm, scope, node, name, value) _directives.push(attd) _setBindings2Scope(scope, attd) }) /** * Directives binding */ util.objEach(ast.dires, function(dname, spec) { var def = spec.def var expr = spec.expr var sep = ';' var d // multiple defines expression parse if (def.multi && expr.match(sep)) { Expression.strip(expr) .split(sep) .forEach(function(item) { // discard empty expression if (!item.trim()) return d = new Directive(vm, scope, node, def, dname, '{' + item + '}') _directives.push(d) _setBindings2Scope(scope, d) }) } else { d = new Directive(vm, scope, node, def, dname, expr) _directives.push(d) _setBindings2Scope(scope, d) } }) }
[ "function", "compileDirective", "(", "node", ",", "scope", ")", "{", "var", "ast", "=", "{", "attrs", ":", "{", "}", ",", "dires", ":", "{", "}", "}", "var", "dirtDefs", "=", "_getAllDirts", "(", ")", "_slice", "(", "node", ".", "attributes", ")", ".", "forEach", "(", "function", "(", "att", ")", "{", "var", "aname", "=", "att", ".", "name", "var", "v", "=", "att", ".", "value", "if", "(", "~", "componentProps", ".", "indexOf", "(", "aname", ")", ")", "{", "return", "}", "else", "if", "(", "_isExpr", "(", "aname", ")", ")", "{", "ast", ".", "attrs", "[", "aname", "]", "=", "v", "}", "else", "if", "(", "aname", ".", "indexOf", "(", "NS", ")", "===", "0", ")", "{", "var", "def", "=", "dirtDefs", "[", "aname", "]", "if", "(", "def", ")", "{", "ast", ".", "dires", "[", "aname", "]", "=", "{", "def", ":", "def", ",", "expr", ":", "v", "}", "}", "else", "{", "return", "}", "}", "else", "if", "(", "_isExpr", "(", "v", ".", "trim", "(", ")", ")", ")", "{", "ast", ".", "attrs", "[", "aname", "]", "=", "v", "}", "else", "{", "return", "}", "node", ".", "removeAttribute", "(", "aname", ")", "}", ")", "util", ".", "objEach", "(", "ast", ".", "attrs", ",", "function", "(", "name", ",", "value", ")", "{", "var", "attd", "=", "new", "AttributeDirective", "(", "vm", ",", "scope", ",", "node", ",", "name", ",", "value", ")", "_directives", ".", "push", "(", "attd", ")", "_setBindings2Scope", "(", "scope", ",", "attd", ")", "}", ")", "util", ".", "objEach", "(", "ast", ".", "dires", ",", "function", "(", "dname", ",", "spec", ")", "{", "var", "def", "=", "spec", ".", "def", "var", "expr", "=", "spec", ".", "expr", "var", "sep", "=", "';'", "var", "d", "if", "(", "def", ".", "multi", "&&", "expr", ".", "match", "(", "sep", ")", ")", "{", "Expression", ".", "strip", "(", "expr", ")", ".", "split", "(", "sep", ")", ".", "forEach", "(", "function", "(", "item", ")", "{", "if", "(", "!", "item", ".", "trim", "(", ")", ")", "return", "d", "=", "new", "Directive", "(", "vm", ",", "scope", ",", "node", ",", "def", ",", "dname", ",", "'{'", "+", "item", "+", "'}'", ")", "_directives", ".", "push", "(", "d", ")", "_setBindings2Scope", "(", "scope", ",", "d", ")", "}", ")", "}", "else", "{", "d", "=", "new", "Directive", "(", "vm", ",", "scope", ",", "node", ",", "def", ",", "dname", ",", "expr", ")", "_directives", ".", "push", "(", "d", ")", "_setBindings2Scope", "(", "scope", ",", "d", ")", "}", "}", ")", "}" ]
Compile attributes to directive
[ "Compile", "attributes", "to", "directive" ]
88b92d62d5000d999c3043e6379790f79608bdfa
https://github.com/switer/Zect/blob/88b92d62d5000d999c3043e6379790f79608bdfa/lib/zect.js#L587-L660
train
bodyno/nunjucks-volt
src/parser.js
function(){ var node = this.parseAdd(); while(this.skipValue(lexer.TOKEN_TILDE, '~')) { var node2 = this.parseAdd(); node = new nodes.Concat(node.lineno, node.colno, node, node2); } return node; }
javascript
function(){ var node = this.parseAdd(); while(this.skipValue(lexer.TOKEN_TILDE, '~')) { var node2 = this.parseAdd(); node = new nodes.Concat(node.lineno, node.colno, node, node2); } return node; }
[ "function", "(", ")", "{", "var", "node", "=", "this", ".", "parseAdd", "(", ")", ";", "while", "(", "this", ".", "skipValue", "(", "lexer", ".", "TOKEN_TILDE", ",", "'~'", ")", ")", "{", "var", "node2", "=", "this", ".", "parseAdd", "(", ")", ";", "node", "=", "new", "nodes", ".", "Concat", "(", "node", ".", "lineno", ",", "node", ".", "colno", ",", "node", ",", "node2", ")", ";", "}", "return", "node", ";", "}" ]
finds the '~' for string concatenation
[ "finds", "the", "~", "for", "string", "concatenation" ]
a7c0908bf98acc2af497069d7d2701bb880d3323
https://github.com/bodyno/nunjucks-volt/blob/a7c0908bf98acc2af497069d7d2701bb880d3323/src/parser.js#L797-L807
train
billstron/passwordless-mysql
lib/mysql-store.js
Store
function Store(conString, options) { var self = this; this._table = "passwordless"; this._client = mysql.createPool(conString); this._client.query("CREATE TABLE IF NOT EXISTS " + this._table + " " + "( id serial NOT NULL, uid character varying(160), token character varying(60) NOT NULL, origin text, ttl bigint, " + "CONSTRAINT passwordless_pkey PRIMARY KEY (id), CONSTRAINT passwordless_token_key UNIQUE (token), CONSTRAINT passwordless_uid_key UNIQUE (uid) )"); }
javascript
function Store(conString, options) { var self = this; this._table = "passwordless"; this._client = mysql.createPool(conString); this._client.query("CREATE TABLE IF NOT EXISTS " + this._table + " " + "( id serial NOT NULL, uid character varying(160), token character varying(60) NOT NULL, origin text, ttl bigint, " + "CONSTRAINT passwordless_pkey PRIMARY KEY (id), CONSTRAINT passwordless_token_key UNIQUE (token), CONSTRAINT passwordless_uid_key UNIQUE (uid) )"); }
[ "function", "Store", "(", "conString", ",", "options", ")", "{", "var", "self", "=", "this", ";", "this", ".", "_table", "=", "\"passwordless\"", ";", "this", ".", "_client", "=", "mysql", ".", "createPool", "(", "conString", ")", ";", "this", ".", "_client", ".", "query", "(", "\"CREATE TABLE IF NOT EXISTS \"", "+", "this", ".", "_table", "+", "\" \"", "+", "\"( id serial NOT NULL, uid character varying(160), token character varying(60) NOT NULL, origin text, ttl bigint, \"", "+", "\"CONSTRAINT passwordless_pkey PRIMARY KEY (id), CONSTRAINT passwordless_token_key UNIQUE (token), CONSTRAINT passwordless_uid_key UNIQUE (uid) )\"", ")", ";", "}" ]
Constructor of Store @param {String} conString URI as defined by the MySQL specification. @param {Object} [options] Combines both the options for the MySQL Client as well as the options for Store. For the MySQL Client options please refer back to the documentation. @constructor
[ "Constructor", "of", "Store" ]
d298078977dffc997c9cb96342bdf7304b1f23d1
https://github.com/billstron/passwordless-mysql/blob/d298078977dffc997c9cb96342bdf7304b1f23d1/lib/mysql-store.js#L14-L21
train
seancheung/kuconfig
lib/object.js
$merge
function $merge(params, fn) { if ( Array.isArray(params) && params.length === 2 && params.every(p => typeof p === 'object') ) { return fn.merge(params[0], params[1]); } throw new Error('$merge expects an array of two objects'); }
javascript
function $merge(params, fn) { if ( Array.isArray(params) && params.length === 2 && params.every(p => typeof p === 'object') ) { return fn.merge(params[0], params[1]); } throw new Error('$merge expects an array of two objects'); }
[ "function", "$merge", "(", "params", ",", "fn", ")", "{", "if", "(", "Array", ".", "isArray", "(", "params", ")", "&&", "params", ".", "length", "===", "2", "&&", "params", ".", "every", "(", "p", "=>", "typeof", "p", "===", "'object'", ")", ")", "{", "return", "fn", ".", "merge", "(", "params", "[", "0", "]", ",", "params", "[", "1", "]", ")", ";", "}", "throw", "new", "Error", "(", "'$merge expects an array of two objects'", ")", ";", "}" ]
Return the merge of two objects @param {[any, any]} params @returns {any}
[ "Return", "the", "merge", "of", "two", "objects" ]
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/object.js#L7-L16
train
seancheung/kuconfig
lib/object.js
$keys
function $keys(params) { if (params == null) { return params; } if (params != null && typeof params === 'object') { return Object.keys(params); } throw new Error('$keys expects object'); }
javascript
function $keys(params) { if (params == null) { return params; } if (params != null && typeof params === 'object') { return Object.keys(params); } throw new Error('$keys expects object'); }
[ "function", "$keys", "(", "params", ")", "{", "if", "(", "params", "==", "null", ")", "{", "return", "params", ";", "}", "if", "(", "params", "!=", "null", "&&", "typeof", "params", "===", "'object'", ")", "{", "return", "Object", ".", "keys", "(", "params", ")", ";", "}", "throw", "new", "Error", "(", "'$keys expects object'", ")", ";", "}" ]
Return the keys of an object @param {any} params @returns {string[]}
[ "Return", "the", "keys", "of", "an", "object" ]
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/object.js#L24-L32
train
seancheung/kuconfig
lib/object.js
$vals
function $vals(params) { if (params == null) { return params; } if (params != null && typeof params === 'object') { return Object.keys(params).map(k => params[k]); } throw new Error('$vals expects object'); }
javascript
function $vals(params) { if (params == null) { return params; } if (params != null && typeof params === 'object') { return Object.keys(params).map(k => params[k]); } throw new Error('$vals expects object'); }
[ "function", "$vals", "(", "params", ")", "{", "if", "(", "params", "==", "null", ")", "{", "return", "params", ";", "}", "if", "(", "params", "!=", "null", "&&", "typeof", "params", "===", "'object'", ")", "{", "return", "Object", ".", "keys", "(", "params", ")", ".", "map", "(", "k", "=>", "params", "[", "k", "]", ")", ";", "}", "throw", "new", "Error", "(", "'$vals expects object'", ")", ";", "}" ]
Return the values of an object @param {any} params @returns {any[]}
[ "Return", "the", "values", "of", "an", "object" ]
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/object.js#L40-L48
train
seancheung/kuconfig
lib/object.js
$zip
function $zip(params) { if ( Array.isArray(params) && params.every(p => Array.isArray(p) && p.length === 2) ) { return params.reduce((o, p) => Object.assign(o, { [p[0]]: p[1] }), {}); } throw new Error('$zip expects an array of two-element-array'); }
javascript
function $zip(params) { if ( Array.isArray(params) && params.every(p => Array.isArray(p) && p.length === 2) ) { return params.reduce((o, p) => Object.assign(o, { [p[0]]: p[1] }), {}); } throw new Error('$zip expects an array of two-element-array'); }
[ "function", "$zip", "(", "params", ")", "{", "if", "(", "Array", ".", "isArray", "(", "params", ")", "&&", "params", ".", "every", "(", "p", "=>", "Array", ".", "isArray", "(", "p", ")", "&&", "p", ".", "length", "===", "2", ")", ")", "{", "return", "params", ".", "reduce", "(", "(", "o", ",", "p", ")", "=>", "Object", ".", "assign", "(", "o", ",", "{", "[", "p", "[", "0", "]", "]", ":", "p", "[", "1", "]", "}", ")", ",", "{", "}", ")", ";", "}", "throw", "new", "Error", "(", "'$zip expects an array of two-element-array'", ")", ";", "}" ]
Merge a series of key-value pairs into an object @param {[any, any][]} params @returns {any}
[ "Merge", "a", "series", "of", "key", "-", "value", "pairs", "into", "an", "object" ]
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/object.js#L56-L64
train
nknapp/thought
lib/utils/resolve-package-root.js
resolvePackageRoot
function resolvePackageRoot (file) { try { const fullPath = path.resolve(file) for (let lead = fullPath; path.dirname(lead) !== lead; lead = path.dirname(lead)) { debug('Looking for package.json in ' + lead) let packagePath = path.join(lead, 'package.json') try { if (fs.statSync(packagePath).isFile()) { return fs.readFile(packagePath, 'utf-8') .then(JSON.parse) .then(packageJson => { return { packageRoot: path.relative(process.cwd(), lead) || '.', relativeFile: path.relative(lead, fullPath), packageJson } }) } } catch (e) { /* istanbul ignore else */ switch (e.code) { case 'ENOTDIR': case 'ENOENT': continue default: throw e } } } } catch (e) { return Promise.reject(e) } }
javascript
function resolvePackageRoot (file) { try { const fullPath = path.resolve(file) for (let lead = fullPath; path.dirname(lead) !== lead; lead = path.dirname(lead)) { debug('Looking for package.json in ' + lead) let packagePath = path.join(lead, 'package.json') try { if (fs.statSync(packagePath).isFile()) { return fs.readFile(packagePath, 'utf-8') .then(JSON.parse) .then(packageJson => { return { packageRoot: path.relative(process.cwd(), lead) || '.', relativeFile: path.relative(lead, fullPath), packageJson } }) } } catch (e) { /* istanbul ignore else */ switch (e.code) { case 'ENOTDIR': case 'ENOENT': continue default: throw e } } } } catch (e) { return Promise.reject(e) } }
[ "function", "resolvePackageRoot", "(", "file", ")", "{", "try", "{", "const", "fullPath", "=", "path", ".", "resolve", "(", "file", ")", "for", "(", "let", "lead", "=", "fullPath", ";", "path", ".", "dirname", "(", "lead", ")", "!==", "lead", ";", "lead", "=", "path", ".", "dirname", "(", "lead", ")", ")", "{", "debug", "(", "'Looking for package.json in '", "+", "lead", ")", "let", "packagePath", "=", "path", ".", "join", "(", "lead", ",", "'package.json'", ")", "try", "{", "if", "(", "fs", ".", "statSync", "(", "packagePath", ")", ".", "isFile", "(", ")", ")", "{", "return", "fs", ".", "readFile", "(", "packagePath", ",", "'utf-8'", ")", ".", "then", "(", "JSON", ".", "parse", ")", ".", "then", "(", "packageJson", "=>", "{", "return", "{", "packageRoot", ":", "path", ".", "relative", "(", "process", ".", "cwd", "(", ")", ",", "lead", ")", "||", "'.'", ",", "relativeFile", ":", "path", ".", "relative", "(", "lead", ",", "fullPath", ")", ",", "packageJson", "}", "}", ")", "}", "}", "catch", "(", "e", ")", "{", "switch", "(", "e", ".", "code", ")", "{", "case", "'ENOTDIR'", ":", "case", "'ENOENT'", ":", "continue", "default", ":", "throw", "e", "}", "}", "}", "}", "catch", "(", "e", ")", "{", "return", "Promise", ".", "reject", "(", "e", ")", "}", "}" ]
Find the `package.json` by walking up from a given file. The result contains the following properties * **packageRoot**: The base-directory of the package containing the file (i.e. the parent of the `package.json` * **relativeFile**: The path of "file" relative to the packageRoot * **packageJson**: The required package.json @param file @return {{packageRoot: string, packageJson: object, relativeFile: string}} the path to the package.json
[ "Find", "the", "package", ".", "json", "by", "walking", "up", "from", "a", "given", "file", ".", "The", "result", "contains", "the", "following", "properties" ]
2ae991f2d3065ff4eae4df544d20787b07be5116
https://github.com/nknapp/thought/blob/2ae991f2d3065ff4eae4df544d20787b07be5116/lib/utils/resolve-package-root.js#L18-L50
train
tarquas/mongoose-hook
lib/v0/mongoose-hook.js
function(pluginIdx) { if (pluginIdx >= plugins.length) return callback(hooks.collectionHook); var plugin = plugins[pluginIdx]; var next = function() {iterPlugins(pluginIdx + 1);}; var func = plugin[stage]; // call the plugin's stage hook, if defined if (func) { // T is database operation object func.call(plugin, T, next); } else next(); }
javascript
function(pluginIdx) { if (pluginIdx >= plugins.length) return callback(hooks.collectionHook); var plugin = plugins[pluginIdx]; var next = function() {iterPlugins(pluginIdx + 1);}; var func = plugin[stage]; // call the plugin's stage hook, if defined if (func) { // T is database operation object func.call(plugin, T, next); } else next(); }
[ "function", "(", "pluginIdx", ")", "{", "if", "(", "pluginIdx", ">=", "plugins", ".", "length", ")", "return", "callback", "(", "hooks", ".", "collectionHook", ")", ";", "var", "plugin", "=", "plugins", "[", "pluginIdx", "]", ";", "var", "next", "=", "function", "(", ")", "{", "iterPlugins", "(", "pluginIdx", "+", "1", ")", ";", "}", ";", "var", "func", "=", "plugin", "[", "stage", "]", ";", "if", "(", "func", ")", "{", "func", ".", "call", "(", "plugin", ",", "T", ",", "next", ")", ";", "}", "else", "next", "(", ")", ";", "}" ]
iterate through the hook-based plugins
[ "iterate", "through", "the", "hook", "-", "based", "plugins" ]
f9bf74886fe0145efaa5a3591deeae3163e116b7
https://github.com/tarquas/mongoose-hook/blob/f9bf74886fe0145efaa5a3591deeae3163e116b7/lib/v0/mongoose-hook.js#L146-L158
train
nknapp/thought
handlebars/helpers/index.js
include
function include (filename, language) { return fs.readFile(filename, 'utf-8').then(function (contents) { return '```' + (typeof language === 'string' ? language : path.extname(filename).substr(1)) + '\n' + contents + '\n```\n' }) }
javascript
function include (filename, language) { return fs.readFile(filename, 'utf-8').then(function (contents) { return '```' + (typeof language === 'string' ? language : path.extname(filename).substr(1)) + '\n' + contents + '\n```\n' }) }
[ "function", "include", "(", "filename", ",", "language", ")", "{", "return", "fs", ".", "readFile", "(", "filename", ",", "'utf-8'", ")", ".", "then", "(", "function", "(", "contents", ")", "{", "return", "'```'", "+", "(", "typeof", "language", "===", "'string'", "?", "language", ":", "path", ".", "extname", "(", "filename", ")", ".", "substr", "(", "1", ")", ")", "+", "'\\n'", "+", "\\n", "+", "contents", "}", ")", "}" ]
Include a file into a markdown code-block @param filename @param language the programming language used for the code-block @returns {string} @access public @memberOf helpers
[ "Include", "a", "file", "into", "a", "markdown", "code", "-", "block" ]
2ae991f2d3065ff4eae4df544d20787b07be5116
https://github.com/nknapp/thought/blob/2ae991f2d3065ff4eae4df544d20787b07be5116/handlebars/helpers/index.js#L59-L67
train
nknapp/thought
handlebars/helpers/index.js
exec
function exec (command, options) { let start let end const lang = options.hash && options.hash.lang switch (lang) { case 'raw': start = end = '' break case 'inline': start = end = '`' break default: const fenceLanguage = lang || '' start = '```' + fenceLanguage + '\n' end = '\n```' } const output = cp.execSync(command, { encoding: 'utf8', cwd: options.hash && options.hash.cwd }) return start + output.trim() + end }
javascript
function exec (command, options) { let start let end const lang = options.hash && options.hash.lang switch (lang) { case 'raw': start = end = '' break case 'inline': start = end = '`' break default: const fenceLanguage = lang || '' start = '```' + fenceLanguage + '\n' end = '\n```' } const output = cp.execSync(command, { encoding: 'utf8', cwd: options.hash && options.hash.cwd }) return start + output.trim() + end }
[ "function", "exec", "(", "command", ",", "options", ")", "{", "let", "start", "let", "end", "const", "lang", "=", "options", ".", "hash", "&&", "options", ".", "hash", ".", "lang", "switch", "(", "lang", ")", "{", "case", "'raw'", ":", "start", "=", "end", "=", "''", "break", "case", "'inline'", ":", "start", "=", "end", "=", "'`'", "break", "default", ":", "const", "fenceLanguage", "=", "lang", "||", "''", "start", "=", "'```'", "+", "fenceLanguage", "+", "'\\n'", "\\n", "}", "end", "=", "'\\n```'", "\\n", "}" ]
Execute a command and include the output in a fenced code-block. @param {string} command the command, passed to `child-process#execSync()` @param {object} options optional arguments and Handlebars internal args. @param {string} options.hash.lang the language tag that should be attached to the fence (like `js` or `bash`). If this is set to `raw`, the output is included as-is, without fences. @param {string} options.hash.cwd the current working directory of the example process @returns {string} the output of `execSync`, enclosed in fences. @access public @memberOf helpers
[ "Execute", "a", "command", "and", "include", "the", "output", "in", "a", "fenced", "code", "-", "block", "." ]
2ae991f2d3065ff4eae4df544d20787b07be5116
https://github.com/nknapp/thought/blob/2ae991f2d3065ff4eae4df544d20787b07be5116/handlebars/helpers/index.js#L147-L168
train
nknapp/thought
handlebars/helpers/index.js
renderTree
function renderTree (object, options) { const tree = require('archy')(transformTree(object, options.fn)) return '<pre><code>\n' + tree + '</code></pre>' }
javascript
function renderTree (object, options) { const tree = require('archy')(transformTree(object, options.fn)) return '<pre><code>\n' + tree + '</code></pre>' }
[ "function", "renderTree", "(", "object", ",", "options", ")", "{", "const", "tree", "=", "require", "(", "'archy'", ")", "(", "transformTree", "(", "object", ",", "options", ".", "fn", ")", ")", "return", "'<pre><code>\\n'", "+", "\\n", "+", "tree", "}" ]
Render an object hierarchy. The expected input is of the form ``` { prop1: 'value', prop2: 'value', ..., children: [ { prop1: 'value', propt2: 'value', ..., children: ... } ] } ``` The tree is transformed and rendered using [archy](https://www.npmjs.com/package/archy) @param object @param options @param {function} options.fn computes the label for a node based on the node itself @returns {string} @access public @memberOf helpers
[ "Render", "an", "object", "hierarchy", "." ]
2ae991f2d3065ff4eae4df544d20787b07be5116
https://github.com/nknapp/thought/blob/2ae991f2d3065ff4eae4df544d20787b07be5116/handlebars/helpers/index.js#L200-L203
train
nknapp/thought
handlebars/helpers/index.js
transformTree
function transformTree (object, fn) { const label = fn(object).trim() if (object.children) { return { label: label, nodes: object.children.map(function (child) { return transformTree(child, fn) }) } } else { return label } }
javascript
function transformTree (object, fn) { const label = fn(object).trim() if (object.children) { return { label: label, nodes: object.children.map(function (child) { return transformTree(child, fn) }) } } else { return label } }
[ "function", "transformTree", "(", "object", ",", "fn", ")", "{", "const", "label", "=", "fn", "(", "object", ")", ".", "trim", "(", ")", "if", "(", "object", ".", "children", ")", "{", "return", "{", "label", ":", "label", ",", "nodes", ":", "object", ".", "children", ".", "map", "(", "function", "(", "child", ")", "{", "return", "transformTree", "(", "child", ",", "fn", ")", "}", ")", "}", "}", "else", "{", "return", "label", "}", "}" ]
Transfrom an object hierarchy into `archy`'s format Transform a tree-structure of the form ``` { prop1: 'value', prop2: 'value', ..., children: [ { prop1: 'value', propt2: 'value', ..., children: ... } ] } ``` Into an [archy](https://www.npmjs.com/package/archy)-compatible format, by passing each node to a block-helper function. The result of the function should be a string which is then used as label for the node. @param {object} object the tree data @param fn the block-helper function (options.fn) of Handlebars (http://handlebarsjs.com/block_helpers.html) @access private
[ "Transfrom", "an", "object", "hierarchy", "into", "archy", "s", "format" ]
2ae991f2d3065ff4eae4df544d20787b07be5116
https://github.com/nknapp/thought/blob/2ae991f2d3065ff4eae4df544d20787b07be5116/handlebars/helpers/index.js#L384-L396
train
nknapp/thought
handlebars/helpers/index.js
repoWebUrl
function repoWebUrl (gitUrl) { if (!gitUrl) { return undefined } const orgRepo = _githubOrgRepo(gitUrl) if (orgRepo) { return 'https://github.com/' + orgRepo } else { return null } }
javascript
function repoWebUrl (gitUrl) { if (!gitUrl) { return undefined } const orgRepo = _githubOrgRepo(gitUrl) if (orgRepo) { return 'https://github.com/' + orgRepo } else { return null } }
[ "function", "repoWebUrl", "(", "gitUrl", ")", "{", "if", "(", "!", "gitUrl", ")", "{", "return", "undefined", "}", "const", "orgRepo", "=", "_githubOrgRepo", "(", "gitUrl", ")", "if", "(", "orgRepo", ")", "{", "return", "'https://github.com/'", "+", "orgRepo", "}", "else", "{", "return", "null", "}", "}" ]
Returns the http-url for viewing a git-repository in the browser given a repo-url from the package.json Currently, only github urls are supported @param {string} gitUrl the git url from the repository.url-property of package.json @access public @memberOf helpers
[ "Returns", "the", "http", "-", "url", "for", "viewing", "a", "git", "-", "repository", "in", "the", "browser", "given", "a", "repo", "-", "url", "from", "the", "package", ".", "json", "Currently", "only", "github", "urls", "are", "supported" ]
2ae991f2d3065ff4eae4df544d20787b07be5116
https://github.com/nknapp/thought/blob/2ae991f2d3065ff4eae4df544d20787b07be5116/handlebars/helpers/index.js#L421-L431
train
nknapp/thought
handlebars/helpers/index.js
regex
function regex (strings, ...args) { return String.raw(strings, ...args.map(_.escapeRegExp)) }
javascript
function regex (strings, ...args) { return String.raw(strings, ...args.map(_.escapeRegExp)) }
[ "function", "regex", "(", "strings", ",", "...", "args", ")", "{", "return", "String", ".", "raw", "(", "strings", ",", "...", "args", ".", "map", "(", "_", ".", "escapeRegExp", ")", ")", "}" ]
Helper function for composing template-literals to properly escaped regexes @param strings @param args @returns {string} @access private
[ "Helper", "function", "for", "composing", "template", "-", "literals", "to", "properly", "escaped", "regexes" ]
2ae991f2d3065ff4eae4df544d20787b07be5116
https://github.com/nknapp/thought/blob/2ae991f2d3065ff4eae4df544d20787b07be5116/handlebars/helpers/index.js#L462-L464
train
nknapp/thought
handlebars/helpers/index.js
_rawGithubUrl
function _rawGithubUrl (resolvedPackageRoot) { var { packageJson, relativeFile } = resolvedPackageRoot const orgRepo = _githubOrgRepo(packageJson && packageJson.repository && packageJson.repository.url) if (orgRepo) { return `https://raw.githubusercontent.com/${orgRepo}/v${packageJson.version}/${relativeFile}` } }
javascript
function _rawGithubUrl (resolvedPackageRoot) { var { packageJson, relativeFile } = resolvedPackageRoot const orgRepo = _githubOrgRepo(packageJson && packageJson.repository && packageJson.repository.url) if (orgRepo) { return `https://raw.githubusercontent.com/${orgRepo}/v${packageJson.version}/${relativeFile}` } }
[ "function", "_rawGithubUrl", "(", "resolvedPackageRoot", ")", "{", "var", "{", "packageJson", ",", "relativeFile", "}", "=", "resolvedPackageRoot", "const", "orgRepo", "=", "_githubOrgRepo", "(", "packageJson", "&&", "packageJson", ".", "repository", "&&", "packageJson", ".", "repository", ".", "url", ")", "if", "(", "orgRepo", ")", "{", "return", "`", "${", "orgRepo", "}", "${", "packageJson", ".", "version", "}", "${", "relativeFile", "}", "`", "}", "}" ]
Return the raw url of a file in a githb repository @private
[ "Return", "the", "raw", "url", "of", "a", "file", "in", "a", "githb", "repository" ]
2ae991f2d3065ff4eae4df544d20787b07be5116
https://github.com/nknapp/thought/blob/2ae991f2d3065ff4eae4df544d20787b07be5116/handlebars/helpers/index.js#L499-L505
train
solid/issue-pane
issuePane.js
function (subject) { var kb = UI.store var t = kb.findTypeURIs(subject) if (t['http://www.w3.org/2005/01/wf/flow#Task'] || kb.holds(subject, UI.ns.wf('tracker'))) return 'issue' // in case ontology not available if (t['http://www.w3.org/2005/01/wf/flow#Tracker']) return 'tracker' // Later: Person. For a list of things assigned to them, // open bugs on projects they are developer on, etc return null // No under other circumstances (while testing at least!) }
javascript
function (subject) { var kb = UI.store var t = kb.findTypeURIs(subject) if (t['http://www.w3.org/2005/01/wf/flow#Task'] || kb.holds(subject, UI.ns.wf('tracker'))) return 'issue' // in case ontology not available if (t['http://www.w3.org/2005/01/wf/flow#Tracker']) return 'tracker' // Later: Person. For a list of things assigned to them, // open bugs on projects they are developer on, etc return null // No under other circumstances (while testing at least!) }
[ "function", "(", "subject", ")", "{", "var", "kb", "=", "UI", ".", "store", "var", "t", "=", "kb", ".", "findTypeURIs", "(", "subject", ")", "if", "(", "t", "[", "'http://www.w3.org/2005/01/wf/flow#Task'", "]", "||", "kb", ".", "holds", "(", "subject", ",", "UI", ".", "ns", ".", "wf", "(", "'tracker'", ")", ")", ")", "return", "'issue'", "if", "(", "t", "[", "'http://www.w3.org/2005/01/wf/flow#Tracker'", "]", ")", "return", "'tracker'", "return", "null", "}" ]
Does the subject deserve an issue pane?
[ "Does", "the", "subject", "deserve", "an", "issue", "pane?" ]
e14bd32ec5629b6cd09899ab8c1e38989a3c8d58
https://github.com/solid/issue-pane/blob/e14bd32ec5629b6cd09899ab8c1e38989a3c8d58/issuePane.js#L25-L34
train
solid/issue-pane
issuePane.js
function (root) { if (root.refresh) { root.refresh() return } for (var i = 0; i < root.children.length; i++) { refreshTree(root.children[i]) } }
javascript
function (root) { if (root.refresh) { root.refresh() return } for (var i = 0; i < root.children.length; i++) { refreshTree(root.children[i]) } }
[ "function", "(", "root", ")", "{", "if", "(", "root", ".", "refresh", ")", "{", "root", ".", "refresh", "(", ")", "return", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "root", ".", "children", ".", "length", ";", "i", "++", ")", "{", "refreshTree", "(", "root", ".", "children", "[", "i", "]", ")", "}", "}" ]
Refresh the DOM tree
[ "Refresh", "the", "DOM", "tree" ]
e14bd32ec5629b6cd09899ab8c1e38989a3c8d58
https://github.com/solid/issue-pane/blob/e14bd32ec5629b6cd09899ab8c1e38989a3c8d58/issuePane.js#L278-L286
train
solid/issue-pane
issuePane.js
getPossibleAssignees
async function getPossibleAssignees () { var devs = [] var devGroups = kb.each(subject, ns.wf('assigneeGroup')) for (let i = 0; i < devGroups.length; i++) { let group = devGroups[i] await kb.fetcher.load() devs = devs.concat(kb.each(group, ns.vcard('member'))) } // Anyone who is a developer of any project which uses this tracker var proj = kb.any(null, ns.doap('bug-database'), tracker) // What project? if (proj) { await kb.fetcher.load(proj) devs = devs.concat(kb.each(proj, ns.doap('developer'))) } return devs }
javascript
async function getPossibleAssignees () { var devs = [] var devGroups = kb.each(subject, ns.wf('assigneeGroup')) for (let i = 0; i < devGroups.length; i++) { let group = devGroups[i] await kb.fetcher.load() devs = devs.concat(kb.each(group, ns.vcard('member'))) } // Anyone who is a developer of any project which uses this tracker var proj = kb.any(null, ns.doap('bug-database'), tracker) // What project? if (proj) { await kb.fetcher.load(proj) devs = devs.concat(kb.each(proj, ns.doap('developer'))) } return devs }
[ "async", "function", "getPossibleAssignees", "(", ")", "{", "var", "devs", "=", "[", "]", "var", "devGroups", "=", "kb", ".", "each", "(", "subject", ",", "ns", ".", "wf", "(", "'assigneeGroup'", ")", ")", "for", "(", "let", "i", "=", "0", ";", "i", "<", "devGroups", ".", "length", ";", "i", "++", ")", "{", "let", "group", "=", "devGroups", "[", "i", "]", "await", "kb", ".", "fetcher", ".", "load", "(", ")", "devs", "=", "devs", ".", "concat", "(", "kb", ".", "each", "(", "group", ",", "ns", ".", "vcard", "(", "'member'", ")", ")", ")", "}", "var", "proj", "=", "kb", ".", "any", "(", "null", ",", "ns", ".", "doap", "(", "'bug-database'", ")", ",", "tracker", ")", "if", "(", "proj", ")", "{", "await", "kb", ".", "fetcher", ".", "load", "(", "proj", ")", "devs", "=", "devs", ".", "concat", "(", "kb", ".", "each", "(", "proj", ",", "ns", ".", "doap", "(", "'developer'", ")", ")", ")", "}", "return", "devs", "}" ]
Who could be assigned to this? Anyone assigned to any issue we know about
[ "Who", "could", "be", "assigned", "to", "this?", "Anyone", "assigned", "to", "any", "issue", "we", "know", "about" ]
e14bd32ec5629b6cd09899ab8c1e38989a3c8d58
https://github.com/solid/issue-pane/blob/e14bd32ec5629b6cd09899ab8c1e38989a3c8d58/issuePane.js#L377-L392
train
seancheung/kuconfig
utils/index.js
merge
function merge(source, target) { if (target == null) { return clone(source); } if (source == null) { return clone(target); } if (typeof source !== 'object' || typeof target !== 'object') { return clone(target); } const merge = (source, target) => { Object.keys(target).forEach(key => { if (source[key] == null) { source[key] = target[key]; } else if (typeof source[key] === 'object') { if (typeof target[key] === 'object') { merge(source[key], target[key]); } else { source[key] = target[key]; } } else { source[key] = target[key]; } }); return source; }; return merge(clone(source), clone(target)); }
javascript
function merge(source, target) { if (target == null) { return clone(source); } if (source == null) { return clone(target); } if (typeof source !== 'object' || typeof target !== 'object') { return clone(target); } const merge = (source, target) => { Object.keys(target).forEach(key => { if (source[key] == null) { source[key] = target[key]; } else if (typeof source[key] === 'object') { if (typeof target[key] === 'object') { merge(source[key], target[key]); } else { source[key] = target[key]; } } else { source[key] = target[key]; } }); return source; }; return merge(clone(source), clone(target)); }
[ "function", "merge", "(", "source", ",", "target", ")", "{", "if", "(", "target", "==", "null", ")", "{", "return", "clone", "(", "source", ")", ";", "}", "if", "(", "source", "==", "null", ")", "{", "return", "clone", "(", "target", ")", ";", "}", "if", "(", "typeof", "source", "!==", "'object'", "||", "typeof", "target", "!==", "'object'", ")", "{", "return", "clone", "(", "target", ")", ";", "}", "const", "merge", "=", "(", "source", ",", "target", ")", "=>", "{", "Object", ".", "keys", "(", "target", ")", ".", "forEach", "(", "key", "=>", "{", "if", "(", "source", "[", "key", "]", "==", "null", ")", "{", "source", "[", "key", "]", "=", "target", "[", "key", "]", ";", "}", "else", "if", "(", "typeof", "source", "[", "key", "]", "===", "'object'", ")", "{", "if", "(", "typeof", "target", "[", "key", "]", "===", "'object'", ")", "{", "merge", "(", "source", "[", "key", "]", ",", "target", "[", "key", "]", ")", ";", "}", "else", "{", "source", "[", "key", "]", "=", "target", "[", "key", "]", ";", "}", "}", "else", "{", "source", "[", "key", "]", "=", "target", "[", "key", "]", ";", "}", "}", ")", ";", "return", "source", ";", "}", ";", "return", "merge", "(", "clone", "(", "source", ")", ",", "clone", "(", "target", ")", ")", ";", "}" ]
Make clones of two objects then merge the second one into the first one and returns the merged object @param {any} source @param {any} target @returns {any}
[ "Make", "clones", "of", "two", "objects", "then", "merge", "the", "second", "one", "into", "the", "first", "one", "and", "returns", "the", "merged", "object" ]
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/utils/index.js#L34-L63
train
seancheung/kuconfig
utils/index.js
env
function env(file, inject) { const envs = {}; if (!path.isAbsolute(file)) { file = path.resolve(process.cwd(), file); } if (fs.existsSync(file) && fs.lstatSync(file).isFile()) { const content = fs.readFileSync(file, 'utf8'); content.split('\n').forEach(line => { const kv = line.match(/^\s*([\w.-]+)\s*=\s*(.*)?\s*$/); if (kv) { const k = kv[1]; let v = kv[2] || ''; if ( v && v.length > 0 && v.charAt(0) === '"' && v.charAt(v.length - 1) === '"' ) { v = v.replace(/\\n/gm, '\n'); } v = v.replace(/(^['"]|['"]$)/g, '').trim(); envs[k] = v; } }); } if (inject) { Object.keys(envs).forEach(k => { if (!(k in process.env)) { process.env[k] = envs[k]; } }); } return envs; }
javascript
function env(file, inject) { const envs = {}; if (!path.isAbsolute(file)) { file = path.resolve(process.cwd(), file); } if (fs.existsSync(file) && fs.lstatSync(file).isFile()) { const content = fs.readFileSync(file, 'utf8'); content.split('\n').forEach(line => { const kv = line.match(/^\s*([\w.-]+)\s*=\s*(.*)?\s*$/); if (kv) { const k = kv[1]; let v = kv[2] || ''; if ( v && v.length > 0 && v.charAt(0) === '"' && v.charAt(v.length - 1) === '"' ) { v = v.replace(/\\n/gm, '\n'); } v = v.replace(/(^['"]|['"]$)/g, '').trim(); envs[k] = v; } }); } if (inject) { Object.keys(envs).forEach(k => { if (!(k in process.env)) { process.env[k] = envs[k]; } }); } return envs; }
[ "function", "env", "(", "file", ",", "inject", ")", "{", "const", "envs", "=", "{", "}", ";", "if", "(", "!", "path", ".", "isAbsolute", "(", "file", ")", ")", "{", "file", "=", "path", ".", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "file", ")", ";", "}", "if", "(", "fs", ".", "existsSync", "(", "file", ")", "&&", "fs", ".", "lstatSync", "(", "file", ")", ".", "isFile", "(", ")", ")", "{", "const", "content", "=", "fs", ".", "readFileSync", "(", "file", ",", "'utf8'", ")", ";", "content", ".", "split", "(", "'\\n'", ")", ".", "\\n", "forEach", ";", "}", "(", "line", "=>", "{", "const", "kv", "=", "line", ".", "match", "(", "/", "^\\s*([\\w.-]+)\\s*=\\s*(.*)?\\s*$", "/", ")", ";", "if", "(", "kv", ")", "{", "const", "k", "=", "kv", "[", "1", "]", ";", "let", "v", "=", "kv", "[", "2", "]", "||", "''", ";", "if", "(", "v", "&&", "v", ".", "length", ">", "0", "&&", "v", ".", "charAt", "(", "0", ")", "===", "'\"'", "&&", "v", ".", "charAt", "(", "v", ".", "length", "-", "1", ")", "===", "'\"'", ")", "{", "v", "=", "v", ".", "replace", "(", "/", "\\\\n", "/", "gm", ",", "'\\n'", ")", ";", "}", "\\n", "v", "=", "v", ".", "replace", "(", "/", "(^['\"]|['\"]$)", "/", "g", ",", "''", ")", ".", "trim", "(", ")", ";", "}", "}", ")", "envs", "[", "k", "]", "=", "v", ";", "}" ]
Read envs from file path @param {string} file @param {boolean} [inject] @returns {{[x: string]: string}}
[ "Read", "envs", "from", "file", "path" ]
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/utils/index.js#L72-L107
train
RideAmigosCorp/grandfatherson
index.js
toDelete
function toDelete(datetimes, options) { // We can't just a function like _.difference, because moment objects can't be compared that simply // and the incoming values might not already be moment objects var seenSurvivors = {}; toKeep(datetimes, options).map(function (dt) { seenSurvivors[dt.toISOString()] = true; }) datetimes = datetimes.map(function (dt) { return moment.utc(dt) }); // The dates to delete are the ones not returned by toKeep return _.filter(datetimes, function (dt) { return !seenSurvivors[ dt.toISOString() ] }); }
javascript
function toDelete(datetimes, options) { // We can't just a function like _.difference, because moment objects can't be compared that simply // and the incoming values might not already be moment objects var seenSurvivors = {}; toKeep(datetimes, options).map(function (dt) { seenSurvivors[dt.toISOString()] = true; }) datetimes = datetimes.map(function (dt) { return moment.utc(dt) }); // The dates to delete are the ones not returned by toKeep return _.filter(datetimes, function (dt) { return !seenSurvivors[ dt.toISOString() ] }); }
[ "function", "toDelete", "(", "datetimes", ",", "options", ")", "{", "var", "seenSurvivors", "=", "{", "}", ";", "toKeep", "(", "datetimes", ",", "options", ")", ".", "map", "(", "function", "(", "dt", ")", "{", "seenSurvivors", "[", "dt", ".", "toISOString", "(", ")", "]", "=", "true", ";", "}", ")", "datetimes", "=", "datetimes", ".", "map", "(", "function", "(", "dt", ")", "{", "return", "moment", ".", "utc", "(", "dt", ")", "}", ")", ";", "return", "_", ".", "filter", "(", "datetimes", ",", "function", "(", "dt", ")", "{", "return", "!", "seenSurvivors", "[", "dt", ".", "toISOString", "(", ")", "]", "}", ")", ";", "}" ]
Return a set of datetimes that should be deleted, out of 'datetimes`
[ "Return", "a", "set", "of", "datetimes", "that", "should", "be", "deleted", "out", "of", "datetimes" ]
5fcd39ee260523db45c25fb3cba6c1f0e02b3400
https://github.com/RideAmigosCorp/grandfatherson/blob/5fcd39ee260523db45c25fb3cba6c1f0e02b3400/index.js#L64-L78
train
NotNinja/nevis
src/equals/context.js
EqualsContext
function EqualsContext(value, other, equals, options) { if (options == null) { options = {}; } /** * A reference to {@link Nevis.equals} which can be called within an {@link EqualsComparator}. * * @private * @type {Function} */ this._equals = equals; /** * The options to be used to test equality for both of the values. * * @public * @type {Nevis~EqualsOptions} */ this.options = { filterProperty: options.filterProperty != null ? options.filterProperty : function() { return true; }, ignoreCase: Boolean(options.ignoreCase), ignoreEquals: Boolean(options.ignoreEquals), ignoreInherited: Boolean(options.ignoreInherited), ignoreMethods: Boolean(options.ignoreMethods) }; /** * The other value to be checked against the <code>value</code>. * * @public * @type {*} */ this.other = other; /** * The string representation of the values to be tested for equality. * * This is generated using <code>Object.prototype.toString</code> and is intended to be primarily used for more * specific type-checking. * * @public * @type {string} */ this.string = Object.prototype.toString.call(value); /** * The type of the values to be tested for equality. * * This is generated using <code>typeof</code> and is intended to be primarily used for simple type-checking. * * @public * @type {string} */ this.type = typeof value; /** * The value to be checked against the <code>other</code>. * * @public * @type {*} */ this.value = value; }
javascript
function EqualsContext(value, other, equals, options) { if (options == null) { options = {}; } /** * A reference to {@link Nevis.equals} which can be called within an {@link EqualsComparator}. * * @private * @type {Function} */ this._equals = equals; /** * The options to be used to test equality for both of the values. * * @public * @type {Nevis~EqualsOptions} */ this.options = { filterProperty: options.filterProperty != null ? options.filterProperty : function() { return true; }, ignoreCase: Boolean(options.ignoreCase), ignoreEquals: Boolean(options.ignoreEquals), ignoreInherited: Boolean(options.ignoreInherited), ignoreMethods: Boolean(options.ignoreMethods) }; /** * The other value to be checked against the <code>value</code>. * * @public * @type {*} */ this.other = other; /** * The string representation of the values to be tested for equality. * * This is generated using <code>Object.prototype.toString</code> and is intended to be primarily used for more * specific type-checking. * * @public * @type {string} */ this.string = Object.prototype.toString.call(value); /** * The type of the values to be tested for equality. * * This is generated using <code>typeof</code> and is intended to be primarily used for simple type-checking. * * @public * @type {string} */ this.type = typeof value; /** * The value to be checked against the <code>other</code>. * * @public * @type {*} */ this.value = value; }
[ "function", "EqualsContext", "(", "value", ",", "other", ",", "equals", ",", "options", ")", "{", "if", "(", "options", "==", "null", ")", "{", "options", "=", "{", "}", ";", "}", "this", ".", "_equals", "=", "equals", ";", "this", ".", "options", "=", "{", "filterProperty", ":", "options", ".", "filterProperty", "!=", "null", "?", "options", ".", "filterProperty", ":", "function", "(", ")", "{", "return", "true", ";", "}", ",", "ignoreCase", ":", "Boolean", "(", "options", ".", "ignoreCase", ")", ",", "ignoreEquals", ":", "Boolean", "(", "options", ".", "ignoreEquals", ")", ",", "ignoreInherited", ":", "Boolean", "(", "options", ".", "ignoreInherited", ")", ",", "ignoreMethods", ":", "Boolean", "(", "options", ".", "ignoreMethods", ")", "}", ";", "this", ".", "other", "=", "other", ";", "this", ".", "string", "=", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "value", ")", ";", "this", ".", "type", "=", "typeof", "value", ";", "this", ".", "value", "=", "value", ";", "}" ]
Contains the values whose equality is to be tested as well as the string representation and type for the value which can be checked elsewhere for type-checking etc. A <code>EqualsContext</code> is <b>only</b> created once it has been determined that both values not exactly equal and neither are <code>null</code>. Once instantiated, {@link EqualsContext#validate} should be called to ensure that both values share the same type. @param {*} value - the value to be checked against <code>other</code> @param {*} other - the other value to be checked against <code>value</code> @param {Function} equals - a reference to {@link Nevis.equals} which can be called within an {@link EqualsComparator} @param {?Nevis~EqualsOptions} options - the options to be used (may be <code>null</code>) @public @constructor
[ "Contains", "the", "values", "whose", "equality", "is", "to", "be", "tested", "as", "well", "as", "the", "string", "representation", "and", "type", "for", "the", "value", "which", "can", "be", "checked", "elsewhere", "for", "type", "-", "checking", "etc", "." ]
1885e154e6e52d8d3eb307da9f27ed591bac455c
https://github.com/NotNinja/nevis/blob/1885e154e6e52d8d3eb307da9f27ed591bac455c/src/equals/context.js#L40-L105
train
jsalis/video-fullscreen
src/fullscreen.js
findSupported
function findSupported(apiList, document) { let standardApi = apiList[0]; let supportedApi = null; for (let i = 0, len = apiList.length; i < len; i++) { let api = apiList[ i ]; if (api[1] in document) { supportedApi = api; break; } } if (Array.isArray(supportedApi)) { return supportedApi.reduce((result, funcName, i) => { result[ standardApi[ i ] ] = funcName; return result; }, {}); } else { return null; } }
javascript
function findSupported(apiList, document) { let standardApi = apiList[0]; let supportedApi = null; for (let i = 0, len = apiList.length; i < len; i++) { let api = apiList[ i ]; if (api[1] in document) { supportedApi = api; break; } } if (Array.isArray(supportedApi)) { return supportedApi.reduce((result, funcName, i) => { result[ standardApi[ i ] ] = funcName; return result; }, {}); } else { return null; } }
[ "function", "findSupported", "(", "apiList", ",", "document", ")", "{", "let", "standardApi", "=", "apiList", "[", "0", "]", ";", "let", "supportedApi", "=", "null", ";", "for", "(", "let", "i", "=", "0", ",", "len", "=", "apiList", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "let", "api", "=", "apiList", "[", "i", "]", ";", "if", "(", "api", "[", "1", "]", "in", "document", ")", "{", "supportedApi", "=", "api", ";", "break", ";", "}", "}", "if", "(", "Array", ".", "isArray", "(", "supportedApi", ")", ")", "{", "return", "supportedApi", ".", "reduce", "(", "(", "result", ",", "funcName", ",", "i", ")", "=>", "{", "result", "[", "standardApi", "[", "i", "]", "]", "=", "funcName", ";", "return", "result", ";", "}", ",", "{", "}", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Finds a supported fullscreen API. @param {Array} apiList The list of possible fullscreen APIs. @param {Document} document The source of the fullscreen interface. @returns {Object}
[ "Finds", "a", "supported", "fullscreen", "API", "." ]
5654cc911f1d6e598b9eb221bc131a533f2862b1
https://github.com/jsalis/video-fullscreen/blob/5654cc911f1d6e598b9eb221bc131a533f2862b1/src/fullscreen.js#L51-L77
train
NotNinja/nevis
src/hash-code/builder.js
HashCodeBuilder
function HashCodeBuilder(initial, multiplier) { if (initial == null) { initial = HashCodeBuilder.DEFAULT_INITIAL_VALUE; } else if (initial % 2 === 0) { throw new Error('initial must be an odd number'); } if (multiplier == null) { multiplier = HashCodeBuilder.DEFAULT_MULTIPLIER_VALUE; } else if (multiplier % 2 === 0) { throw new Error('multiplier must be an odd number'); } /** * The current hash code for this {@link HashCodeBuilder}. * * @private * @type {number} */ this._hash = initial; /** * The multiplier to be used by this {@link HashCodeBuilder}. * * @private * @type {number} */ this._multiplier = multiplier; }
javascript
function HashCodeBuilder(initial, multiplier) { if (initial == null) { initial = HashCodeBuilder.DEFAULT_INITIAL_VALUE; } else if (initial % 2 === 0) { throw new Error('initial must be an odd number'); } if (multiplier == null) { multiplier = HashCodeBuilder.DEFAULT_MULTIPLIER_VALUE; } else if (multiplier % 2 === 0) { throw new Error('multiplier must be an odd number'); } /** * The current hash code for this {@link HashCodeBuilder}. * * @private * @type {number} */ this._hash = initial; /** * The multiplier to be used by this {@link HashCodeBuilder}. * * @private * @type {number} */ this._multiplier = multiplier; }
[ "function", "HashCodeBuilder", "(", "initial", ",", "multiplier", ")", "{", "if", "(", "initial", "==", "null", ")", "{", "initial", "=", "HashCodeBuilder", ".", "DEFAULT_INITIAL_VALUE", ";", "}", "else", "if", "(", "initial", "%", "2", "===", "0", ")", "{", "throw", "new", "Error", "(", "'initial must be an odd number'", ")", ";", "}", "if", "(", "multiplier", "==", "null", ")", "{", "multiplier", "=", "HashCodeBuilder", ".", "DEFAULT_MULTIPLIER_VALUE", ";", "}", "else", "if", "(", "multiplier", "%", "2", "===", "0", ")", "{", "throw", "new", "Error", "(", "'multiplier must be an odd number'", ")", ";", "}", "this", ".", "_hash", "=", "initial", ";", "this", ".", "_multiplier", "=", "multiplier", ";", "}" ]
Assists in building hash codes for complex classes. Ideally the <code>initial</code> value and <code>multiplier</code> should be different for each class, however, this is not vital. Prime numbers are preferred, especially for <code>multiplier</code>. @param {number} [initial=HashCodeBuilder.DEFAULT_INITIAL_VALUE] - the initial value to be used (may be <code>null</code> but cannot be even) @param {number} [multiplier=HashCodeBuilder.DEFAULT_MULTIPLIER_VALUE] - the multiplier to be used (may be <code>null</code> but cannot be even) @throws {Error} If either <code>initial</code> or <code>multiplier</code> are even numbers. @public @constructor
[ "Assists", "in", "building", "hash", "codes", "for", "complex", "classes", "." ]
1885e154e6e52d8d3eb307da9f27ed591bac455c
https://github.com/NotNinja/nevis/blob/1885e154e6e52d8d3eb307da9f27ed591bac455c/src/hash-code/builder.js#L41-L69
train
Doodle3D/connman-simplified
lib/WiFi.js
function(next) { // already connected to service? stop if (targetServiceProperties.state === STATES.READY || targetServiceProperties.state === STATES.ONLINE) { debug('already connected'); if (callback) callback(); _lockJoin = false; return; } else { next(); } }
javascript
function(next) { // already connected to service? stop if (targetServiceProperties.state === STATES.READY || targetServiceProperties.state === STATES.ONLINE) { debug('already connected'); if (callback) callback(); _lockJoin = false; return; } else { next(); } }
[ "function", "(", "next", ")", "{", "if", "(", "targetServiceProperties", ".", "state", "===", "STATES", ".", "READY", "||", "targetServiceProperties", ".", "state", "===", "STATES", ".", "ONLINE", ")", "{", "debug", "(", "'already connected'", ")", ";", "if", "(", "callback", ")", "callback", "(", ")", ";", "_lockJoin", "=", "false", ";", "return", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}" ]
check current state
[ "check", "current", "state" ]
9dd9109660baa4673ff77d52bca1b630a2f756f1
https://github.com/Doodle3D/connman-simplified/blob/9dd9109660baa4673ff77d52bca1b630a2f756f1/lib/WiFi.js#L190-L201
train
Doodle3D/connman-simplified
lib/WiFi.js
function(next) { function finishJoining(err) { targetService.removeListener('PropertyChanged', onChange); if (typeof(passphraseSender) == 'function') { self.connman.Agent.removeListener('RequestInput', passphraseSender); passphraseSender = null } next(err); } function onChange(type, value) { if (type !== 'State') return; debug('service State: ', value); switch (value) { // when wifi ready and online case STATES.READY: case STATES.ONLINE: clearTimeout(timeout); finishJoining() break; case STATES.DISCONNECT: case STATES.FAILURE: clearTimeout(timeout); var err = new Error('Joining network failed (wrong password?)'); finishJoining(err); // ToDo include error... (sometimes there is a Error property change, with a value like 'invalid-key') break; } } timeout = setTimeout(function(){ var err = new Error('Joining network failed (Timeout)'); finishJoining(err); }, _timeoutJoin); targetService.on('PropertyChanged', onChange); }
javascript
function(next) { function finishJoining(err) { targetService.removeListener('PropertyChanged', onChange); if (typeof(passphraseSender) == 'function') { self.connman.Agent.removeListener('RequestInput', passphraseSender); passphraseSender = null } next(err); } function onChange(type, value) { if (type !== 'State') return; debug('service State: ', value); switch (value) { // when wifi ready and online case STATES.READY: case STATES.ONLINE: clearTimeout(timeout); finishJoining() break; case STATES.DISCONNECT: case STATES.FAILURE: clearTimeout(timeout); var err = new Error('Joining network failed (wrong password?)'); finishJoining(err); // ToDo include error... (sometimes there is a Error property change, with a value like 'invalid-key') break; } } timeout = setTimeout(function(){ var err = new Error('Joining network failed (Timeout)'); finishJoining(err); }, _timeoutJoin); targetService.on('PropertyChanged', onChange); }
[ "function", "(", "next", ")", "{", "function", "finishJoining", "(", "err", ")", "{", "targetService", ".", "removeListener", "(", "'PropertyChanged'", ",", "onChange", ")", ";", "if", "(", "typeof", "(", "passphraseSender", ")", "==", "'function'", ")", "{", "self", ".", "connman", ".", "Agent", ".", "removeListener", "(", "'RequestInput'", ",", "passphraseSender", ")", ";", "passphraseSender", "=", "null", "}", "next", "(", "err", ")", ";", "}", "function", "onChange", "(", "type", ",", "value", ")", "{", "if", "(", "type", "!==", "'State'", ")", "return", ";", "debug", "(", "'service State: '", ",", "value", ")", ";", "switch", "(", "value", ")", "{", "case", "STATES", ".", "READY", ":", "case", "STATES", ".", "ONLINE", ":", "clearTimeout", "(", "timeout", ")", ";", "finishJoining", "(", ")", "break", ";", "case", "STATES", ".", "DISCONNECT", ":", "case", "STATES", ".", "FAILURE", ":", "clearTimeout", "(", "timeout", ")", ";", "var", "err", "=", "new", "Error", "(", "'Joining network failed (wrong password?)'", ")", ";", "finishJoining", "(", "err", ")", ";", "break", ";", "}", "}", "timeout", "=", "setTimeout", "(", "function", "(", ")", "{", "var", "err", "=", "new", "Error", "(", "'Joining network failed (Timeout)'", ")", ";", "finishJoining", "(", "err", ")", ";", "}", ",", "_timeoutJoin", ")", ";", "targetService", ".", "on", "(", "'PropertyChanged'", ",", "onChange", ")", ";", "}" ]
listen to state
[ "listen", "to", "state" ]
9dd9109660baa4673ff77d52bca1b630a2f756f1
https://github.com/Doodle3D/connman-simplified/blob/9dd9109660baa4673ff77d52bca1b630a2f756f1/lib/WiFi.js#L234-L267
train
adrai/devicestack
lib/serial/deviceloader.js
SerialDeviceLoader
function SerialDeviceLoader(Device, useGlobal) { // call super class DeviceLoader.call(this); this.Device = Device; this.useGlobal = (useGlobal === undefined || useGlobal === null) ? true : useGlobal; if (this.useGlobal) { this.globalSerialDeviceLoader = globalSerialDeviceLoader.create(Device, this.filter); } }
javascript
function SerialDeviceLoader(Device, useGlobal) { // call super class DeviceLoader.call(this); this.Device = Device; this.useGlobal = (useGlobal === undefined || useGlobal === null) ? true : useGlobal; if (this.useGlobal) { this.globalSerialDeviceLoader = globalSerialDeviceLoader.create(Device, this.filter); } }
[ "function", "SerialDeviceLoader", "(", "Device", ",", "useGlobal", ")", "{", "DeviceLoader", ".", "call", "(", "this", ")", ";", "this", ".", "Device", "=", "Device", ";", "this", ".", "useGlobal", "=", "(", "useGlobal", "===", "undefined", "||", "useGlobal", "===", "null", ")", "?", "true", ":", "useGlobal", ";", "if", "(", "this", ".", "useGlobal", ")", "{", "this", ".", "globalSerialDeviceLoader", "=", "globalSerialDeviceLoader", ".", "create", "(", "Device", ",", "this", ".", "filter", ")", ";", "}", "}" ]
A serialdeviceloader can check if there are available some serial devices. @param {Object} Device The constructor function of the device.
[ "A", "serialdeviceloader", "can", "check", "if", "there", "are", "available", "some", "serial", "devices", "." ]
c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76
https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/serial/deviceloader.js#L11-L23
train
crysalead-js/dom-layer
src/tree/patch.js
keysIndexes
function keysIndexes(children, startIndex, endIndex) { var i, keys = Object.create(null), key; for (i = startIndex; i <= endIndex; ++i) { if (children[i]) { key = children[i].key; if (key !== undefined) { keys[key] = i; } } } return keys; }
javascript
function keysIndexes(children, startIndex, endIndex) { var i, keys = Object.create(null), key; for (i = startIndex; i <= endIndex; ++i) { if (children[i]) { key = children[i].key; if (key !== undefined) { keys[key] = i; } } } return keys; }
[ "function", "keysIndexes", "(", "children", ",", "startIndex", ",", "endIndex", ")", "{", "var", "i", ",", "keys", "=", "Object", ".", "create", "(", "null", ")", ",", "key", ";", "for", "(", "i", "=", "startIndex", ";", "i", "<=", "endIndex", ";", "++", "i", ")", "{", "if", "(", "children", "[", "i", "]", ")", "{", "key", "=", "children", "[", "i", "]", ".", "key", ";", "if", "(", "key", "!==", "undefined", ")", "{", "keys", "[", "key", "]", "=", "i", ";", "}", "}", "}", "return", "keys", ";", "}" ]
Returns indexes of keyed nodes. @param Array children An array of nodes. @return Object An object of keyed nodes indexes.
[ "Returns", "indexes", "of", "keyed", "nodes", "." ]
0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2
https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/src/tree/patch.js#L99-L110
train
crysalead-js/dom-layer
src/node/patcher/dataset.js
patch
function patch(element, previous, dataset) { if (!previous && !dataset) { return dataset; } var name; previous = previous || {}; dataset = dataset || {}; for (name in previous) { if (dataset[name] === undefined) { delete element.dataset[name]; } } for (name in dataset) { if (previous[name] === dataset[name]) { continue; } element.dataset[name] = dataset[name]; } return dataset; }
javascript
function patch(element, previous, dataset) { if (!previous && !dataset) { return dataset; } var name; previous = previous || {}; dataset = dataset || {}; for (name in previous) { if (dataset[name] === undefined) { delete element.dataset[name]; } } for (name in dataset) { if (previous[name] === dataset[name]) { continue; } element.dataset[name] = dataset[name]; } return dataset; }
[ "function", "patch", "(", "element", ",", "previous", ",", "dataset", ")", "{", "if", "(", "!", "previous", "&&", "!", "dataset", ")", "{", "return", "dataset", ";", "}", "var", "name", ";", "previous", "=", "previous", "||", "{", "}", ";", "dataset", "=", "dataset", "||", "{", "}", ";", "for", "(", "name", "in", "previous", ")", "{", "if", "(", "dataset", "[", "name", "]", "===", "undefined", ")", "{", "delete", "element", ".", "dataset", "[", "name", "]", ";", "}", "}", "for", "(", "name", "in", "dataset", ")", "{", "if", "(", "previous", "[", "name", "]", "===", "dataset", "[", "name", "]", ")", "{", "continue", ";", "}", "element", ".", "dataset", "[", "name", "]", "=", "dataset", "[", "name", "]", ";", "}", "return", "dataset", ";", "}" ]
Maintains state of element dataset. @param Object element A DOM element. @param Object previous The previous state of dataset. @param Object dataset The dataset to match on. @return Object dataset The element dataset state.
[ "Maintains", "state", "of", "element", "dataset", "." ]
0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2
https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/src/node/patcher/dataset.js#L9-L31
train
CSTARS/poplar-3pg-model
lib/fn.js
function(stem, p) { var avDOB = Math.pow( ( stem / p.stemCnt / p.stemC) , (1 / p.stemP) ); var ppfs= p.pfsC * Math.pow(avDOB , p.pfsP); return Math.min(p.pfsMx,ppfs); }
javascript
function(stem, p) { var avDOB = Math.pow( ( stem / p.stemCnt / p.stemC) , (1 / p.stemP) ); var ppfs= p.pfsC * Math.pow(avDOB , p.pfsP); return Math.min(p.pfsMx,ppfs); }
[ "function", "(", "stem", ",", "p", ")", "{", "var", "avDOB", "=", "Math", ".", "pow", "(", "(", "stem", "/", "p", ".", "stemCnt", "/", "p", ".", "stemC", ")", ",", "(", "1", "/", "p", ".", "stemP", ")", ")", ";", "var", "ppfs", "=", "p", ".", "pfsC", "*", "Math", ".", "pow", "(", "avDOB", ",", "p", ".", "pfsP", ")", ";", "return", "Math", ".", "min", "(", "p", ".", "pfsMx", ",", "ppfs", ")", ";", "}" ]
Coppice Functions are based on Diameter on Stump, NOT DBH. Calculates the pfs based on the stem weight in KG
[ "Coppice", "Functions", "are", "based", "on", "Diameter", "on", "Stump", "NOT", "DBH", ".", "Calculates", "the", "pfs", "based", "on", "the", "stem", "weight", "in", "KG" ]
3d8c330b9d7f760611be4532204f7742096e165c
https://github.com/CSTARS/poplar-3pg-model/blob/3d8c330b9d7f760611be4532204f7742096e165c/lib/fn.js#L380-L385
train
CSTARS/poplar-3pg-model
lib/fn.js
function (stemG, wsVI, laVI, SLA) { if (stemG < 10) { stemG=10; } var VI = Math.pow( (stemG / wsVI.stems_per_stump / wsVI.constant),(1 / wsVI.power) ); // Add up for all stems var la = laVI.constant * Math.pow(VI,laVI.power) * wsVI.stems_per_stump; var wf = 1000 * (la / SLA); // Foilage Weight in g; var pfs = wf/stemG; return pfs; }
javascript
function (stemG, wsVI, laVI, SLA) { if (stemG < 10) { stemG=10; } var VI = Math.pow( (stemG / wsVI.stems_per_stump / wsVI.constant),(1 / wsVI.power) ); // Add up for all stems var la = laVI.constant * Math.pow(VI,laVI.power) * wsVI.stems_per_stump; var wf = 1000 * (la / SLA); // Foilage Weight in g; var pfs = wf/stemG; return pfs; }
[ "function", "(", "stemG", ",", "wsVI", ",", "laVI", ",", "SLA", ")", "{", "if", "(", "stemG", "<", "10", ")", "{", "stemG", "=", "10", ";", "}", "var", "VI", "=", "Math", ".", "pow", "(", "(", "stemG", "/", "wsVI", ".", "stems_per_stump", "/", "wsVI", ".", "constant", ")", ",", "(", "1", "/", "wsVI", ".", "power", ")", ")", ";", "var", "la", "=", "laVI", ".", "constant", "*", "Math", ".", "pow", "(", "VI", ",", "laVI", ".", "power", ")", "*", "wsVI", ".", "stems_per_stump", ";", "var", "wf", "=", "1000", "*", "(", "la", "/", "SLA", ")", ";", "var", "pfs", "=", "wf", "/", "stemG", ";", "return", "pfs", ";", "}" ]
Calculates the pfs based on stem with in G. Uses volume Index as guide
[ "Calculates", "the", "pfs", "based", "on", "stem", "with", "in", "G", ".", "Uses", "volume", "Index", "as", "guide" ]
3d8c330b9d7f760611be4532204f7742096e165c
https://github.com/CSTARS/poplar-3pg-model/blob/3d8c330b9d7f760611be4532204f7742096e165c/lib/fn.js#L388-L399
train
bodyno/nunjucks-volt
src/globals.js
globals
function globals() { return { range: function(start, stop, step) { if(typeof stop === 'undefined') { stop = start; start = 0; step = 1; } else if(!step) { step = 1; } var arr = []; var i; if (step > 0) { for (i=start; i<stop; i+=step) { arr.push(i); } } else { for (i=start; i>stop; i+=step) { arr.push(i); } } return arr; }, // lipsum: function(n, html, min, max) { // }, cycler: function() { return cycler(Array.prototype.slice.call(arguments)); }, joiner: function(sep) { return joiner(sep); } }; }
javascript
function globals() { return { range: function(start, stop, step) { if(typeof stop === 'undefined') { stop = start; start = 0; step = 1; } else if(!step) { step = 1; } var arr = []; var i; if (step > 0) { for (i=start; i<stop; i+=step) { arr.push(i); } } else { for (i=start; i>stop; i+=step) { arr.push(i); } } return arr; }, // lipsum: function(n, html, min, max) { // }, cycler: function() { return cycler(Array.prototype.slice.call(arguments)); }, joiner: function(sep) { return joiner(sep); } }; }
[ "function", "globals", "(", ")", "{", "return", "{", "range", ":", "function", "(", "start", ",", "stop", ",", "step", ")", "{", "if", "(", "typeof", "stop", "===", "'undefined'", ")", "{", "stop", "=", "start", ";", "start", "=", "0", ";", "step", "=", "1", ";", "}", "else", "if", "(", "!", "step", ")", "{", "step", "=", "1", ";", "}", "var", "arr", "=", "[", "]", ";", "var", "i", ";", "if", "(", "step", ">", "0", ")", "{", "for", "(", "i", "=", "start", ";", "i", "<", "stop", ";", "i", "+=", "step", ")", "{", "arr", ".", "push", "(", "i", ")", ";", "}", "}", "else", "{", "for", "(", "i", "=", "start", ";", "i", ">", "stop", ";", "i", "+=", "step", ")", "{", "arr", ".", "push", "(", "i", ")", ";", "}", "}", "return", "arr", ";", "}", ",", "cycler", ":", "function", "(", ")", "{", "return", "cycler", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ")", ";", "}", ",", "joiner", ":", "function", "(", "sep", ")", "{", "return", "joiner", "(", "sep", ")", ";", "}", "}", ";", "}" ]
Making this a function instead so it returns a new object each time it's called. That way, if something like an environment uses it, they will each have their own copy.
[ "Making", "this", "a", "function", "instead", "so", "it", "returns", "a", "new", "object", "each", "time", "it", "s", "called", ".", "That", "way", "if", "something", "like", "an", "environment", "uses", "it", "they", "will", "each", "have", "their", "own", "copy", "." ]
a7c0908bf98acc2af497069d7d2701bb880d3323
https://github.com/bodyno/nunjucks-volt/blob/a7c0908bf98acc2af497069d7d2701bb880d3323/src/globals.js#L40-L77
train
iammapping/githooks
githooks.js
filterFiles
function filterFiles(files, check) { return files.filter(function(file) { if (typeof check == 'string') { // ignore typecase equal return check.toLowerCase() === file.toLowerCase(); } else if (Util.isRegExp(check)) { // regexp test return check.test(file); } else if (typeof check == 'function') { // function callback return check(file); } }); }
javascript
function filterFiles(files, check) { return files.filter(function(file) { if (typeof check == 'string') { // ignore typecase equal return check.toLowerCase() === file.toLowerCase(); } else if (Util.isRegExp(check)) { // regexp test return check.test(file); } else if (typeof check == 'function') { // function callback return check(file); } }); }
[ "function", "filterFiles", "(", "files", ",", "check", ")", "{", "return", "files", ".", "filter", "(", "function", "(", "file", ")", "{", "if", "(", "typeof", "check", "==", "'string'", ")", "{", "return", "check", ".", "toLowerCase", "(", ")", "===", "file", ".", "toLowerCase", "(", ")", ";", "}", "else", "if", "(", "Util", ".", "isRegExp", "(", "check", ")", ")", "{", "return", "check", ".", "test", "(", "file", ")", ";", "}", "else", "if", "(", "typeof", "check", "==", "'function'", ")", "{", "return", "check", "(", "file", ")", ";", "}", "}", ")", ";", "}" ]
filter files array @param {Array} files @param {String|RegExp|Function} check @return {Array}
[ "filter", "files", "array" ]
91fdb886c59840a0d210575684292fa022f339ed
https://github.com/iammapping/githooks/blob/91fdb886c59840a0d210575684292fa022f339ed/githooks.js#L162-L175
train
iammapping/githooks
githooks.js
function() { var hooks = {}; return { // ignore hook error ignore: false, // provide async api async: async, /** * add a new hook * @param {String} hook [hook name] * @param {Object} rules [hook trigger rules] * @return Githook */ hook: function(hook, rules) { if (cfg.AVAILABLE_HOOKS.indexOf(hook) < 0 && !this.ignore) { this.error('hook "' + hook + '" not support'); } if (!hooks[hook]) { hooks[hook] = new Githook(rules); } return hooks[hook]; }, /** * remove hook * @param {String} hook [hook name] */ removeHook: function(hook) { if (hooks[hook]) { delete hooks[hook]; } }, /** * return all pending hooks * @return {Array} hook names */ pendingHooks: function() { return Object.keys(hooks); }, /** * trigger Githook * @param {String} hook [hook name] */ trigger: function(hook) { hooks[hook] && hooks[hook].trigger.apply(hooks[hook], Array.prototype.slice.call(arguments, 1)); }, /** * output error message and exit with ERROR_EXIT * @param {String|Error} error */ error: function(error) { if (error) { console.error(error.toString()); } process.exit(cfg.ERROR_EXIT); }, /** * pass immediately * output notice message and exit with SUCCESS_EXIT * @param {[type]} notice [description] * @return {[type]} [description] */ pass: function(notice) { if (notice) { console.log('Notice: ' + notice); } process.exit(cfg.SUCCESS_EXIT); } } }
javascript
function() { var hooks = {}; return { // ignore hook error ignore: false, // provide async api async: async, /** * add a new hook * @param {String} hook [hook name] * @param {Object} rules [hook trigger rules] * @return Githook */ hook: function(hook, rules) { if (cfg.AVAILABLE_HOOKS.indexOf(hook) < 0 && !this.ignore) { this.error('hook "' + hook + '" not support'); } if (!hooks[hook]) { hooks[hook] = new Githook(rules); } return hooks[hook]; }, /** * remove hook * @param {String} hook [hook name] */ removeHook: function(hook) { if (hooks[hook]) { delete hooks[hook]; } }, /** * return all pending hooks * @return {Array} hook names */ pendingHooks: function() { return Object.keys(hooks); }, /** * trigger Githook * @param {String} hook [hook name] */ trigger: function(hook) { hooks[hook] && hooks[hook].trigger.apply(hooks[hook], Array.prototype.slice.call(arguments, 1)); }, /** * output error message and exit with ERROR_EXIT * @param {String|Error} error */ error: function(error) { if (error) { console.error(error.toString()); } process.exit(cfg.ERROR_EXIT); }, /** * pass immediately * output notice message and exit with SUCCESS_EXIT * @param {[type]} notice [description] * @return {[type]} [description] */ pass: function(notice) { if (notice) { console.log('Notice: ' + notice); } process.exit(cfg.SUCCESS_EXIT); } } }
[ "function", "(", ")", "{", "var", "hooks", "=", "{", "}", ";", "return", "{", "ignore", ":", "false", ",", "async", ":", "async", ",", "hook", ":", "function", "(", "hook", ",", "rules", ")", "{", "if", "(", "cfg", ".", "AVAILABLE_HOOKS", ".", "indexOf", "(", "hook", ")", "<", "0", "&&", "!", "this", ".", "ignore", ")", "{", "this", ".", "error", "(", "'hook \"'", "+", "hook", "+", "'\" not support'", ")", ";", "}", "if", "(", "!", "hooks", "[", "hook", "]", ")", "{", "hooks", "[", "hook", "]", "=", "new", "Githook", "(", "rules", ")", ";", "}", "return", "hooks", "[", "hook", "]", ";", "}", ",", "removeHook", ":", "function", "(", "hook", ")", "{", "if", "(", "hooks", "[", "hook", "]", ")", "{", "delete", "hooks", "[", "hook", "]", ";", "}", "}", ",", "pendingHooks", ":", "function", "(", ")", "{", "return", "Object", ".", "keys", "(", "hooks", ")", ";", "}", ",", "trigger", ":", "function", "(", "hook", ")", "{", "hooks", "[", "hook", "]", "&&", "hooks", "[", "hook", "]", ".", "trigger", ".", "apply", "(", "hooks", "[", "hook", "]", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ")", ";", "}", ",", "error", ":", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "console", ".", "error", "(", "error", ".", "toString", "(", ")", ")", ";", "}", "process", ".", "exit", "(", "cfg", ".", "ERROR_EXIT", ")", ";", "}", ",", "pass", ":", "function", "(", "notice", ")", "{", "if", "(", "notice", ")", "{", "console", ".", "log", "(", "'Notice: '", "+", "notice", ")", ";", "}", "process", ".", "exit", "(", "cfg", ".", "SUCCESS_EXIT", ")", ";", "}", "}", "}" ]
set of Githook
[ "set", "of", "Githook" ]
91fdb886c59840a0d210575684292fa022f339ed
https://github.com/iammapping/githooks/blob/91fdb886c59840a0d210575684292fa022f339ed/githooks.js#L180-L249
train
iammapping/githooks
githooks.js
function(hook, rules) { if (cfg.AVAILABLE_HOOKS.indexOf(hook) < 0 && !this.ignore) { this.error('hook "' + hook + '" not support'); } if (!hooks[hook]) { hooks[hook] = new Githook(rules); } return hooks[hook]; }
javascript
function(hook, rules) { if (cfg.AVAILABLE_HOOKS.indexOf(hook) < 0 && !this.ignore) { this.error('hook "' + hook + '" not support'); } if (!hooks[hook]) { hooks[hook] = new Githook(rules); } return hooks[hook]; }
[ "function", "(", "hook", ",", "rules", ")", "{", "if", "(", "cfg", ".", "AVAILABLE_HOOKS", ".", "indexOf", "(", "hook", ")", "<", "0", "&&", "!", "this", ".", "ignore", ")", "{", "this", ".", "error", "(", "'hook \"'", "+", "hook", "+", "'\" not support'", ")", ";", "}", "if", "(", "!", "hooks", "[", "hook", "]", ")", "{", "hooks", "[", "hook", "]", "=", "new", "Githook", "(", "rules", ")", ";", "}", "return", "hooks", "[", "hook", "]", ";", "}" ]
add a new hook @param {String} hook [hook name] @param {Object} rules [hook trigger rules] @return Githook
[ "add", "a", "new", "hook" ]
91fdb886c59840a0d210575684292fa022f339ed
https://github.com/iammapping/githooks/blob/91fdb886c59840a0d210575684292fa022f339ed/githooks.js#L193-L202
train
iammapping/githooks
githooks.js
function(error) { if (error) { console.error(error.toString()); } process.exit(cfg.ERROR_EXIT); }
javascript
function(error) { if (error) { console.error(error.toString()); } process.exit(cfg.ERROR_EXIT); }
[ "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "console", ".", "error", "(", "error", ".", "toString", "(", ")", ")", ";", "}", "process", ".", "exit", "(", "cfg", ".", "ERROR_EXIT", ")", ";", "}" ]
output error message and exit with ERROR_EXIT @param {String|Error} error
[ "output", "error", "message", "and", "exit", "with", "ERROR_EXIT" ]
91fdb886c59840a0d210575684292fa022f339ed
https://github.com/iammapping/githooks/blob/91fdb886c59840a0d210575684292fa022f339ed/githooks.js#L230-L235
train
MarcDiethelm/xtc
lib/configure.js
configurePaths
function configurePaths(cfg) { var sourcesBasePath = path.resolve(appPath, cfg.get('sourcesBasePath')) ,sources = cfg.get('sources') ,build = cfg.get('build') ,buildBaseUri ,buildDir = nodeEnv == 'development' ? build.baseDirNameDev : build.baseDirNameDist ,buildPath = path.join( path.resolve(appPath, cfg.get('buildBasePath')), buildDir) ,keys, key ,i ; buildBaseUri = cfg.get('staticBaseUri') + '/' + buildDir +'/'; cfg.set('buildBaseUri', buildBaseUri); cfg.set('cssUri', buildBaseUri + build.css.dirName + build.css.external[nodeEnv]); cfg.set('jsUri', buildBaseUri + build.js.dirName + build.js.external[nodeEnv]); cfg.set('testUri', buildBaseUri + build.js.dirName + 'test.js'); // Resolve absolute paths from relative paths in config files cfg.set('staticPath', path.resolve(appPath, cfg.get('staticPath'))); cfg.set('routesPath', path.resolve(appPath, cfg.get('routesPath'))); cfg.set('buildBasePath', path.resolve(appPath, cfg.get('buildBasePath'))); cfg.set('helpersPath', path.resolve(appPath, cfg.get('helpersPath'))); cfg.set('handlebarsHelpersPath', path.resolve(appPath, cfg.get('handlebarsHelpersPath'))); cfg.set('repoWebViewBaseUri', cfg.get('repository').replace('.git', '/') ); keys = Object.keys(sources); for (i = 0; i < keys.length; i++) { key = keys[i]; cfg.set( 'sources.'+key, path.resolve( sourcesBasePath, sources[key]) ); } build.css.inline[nodeEnv] && cfg.set('build.css.inline', path.resolve( buildPath, build.css.inline[nodeEnv] )); build.css.external[nodeEnv] && cfg.set('build.css.external', path.resolve( buildPath, build.css.external[nodeEnv] )); build.js.inline[nodeEnv] && cfg.set('build.js.inline', path.resolve( buildPath, build.js.inline[nodeEnv] )); build.js.external[nodeEnv] && cfg.set('build.js.external', path.resolve( buildPath, build.js.external[nodeEnv] )); cfg.set('build.spritesheets', path.resolve( buildPath, build.spriteSheets.dirName )); return cfg; }
javascript
function configurePaths(cfg) { var sourcesBasePath = path.resolve(appPath, cfg.get('sourcesBasePath')) ,sources = cfg.get('sources') ,build = cfg.get('build') ,buildBaseUri ,buildDir = nodeEnv == 'development' ? build.baseDirNameDev : build.baseDirNameDist ,buildPath = path.join( path.resolve(appPath, cfg.get('buildBasePath')), buildDir) ,keys, key ,i ; buildBaseUri = cfg.get('staticBaseUri') + '/' + buildDir +'/'; cfg.set('buildBaseUri', buildBaseUri); cfg.set('cssUri', buildBaseUri + build.css.dirName + build.css.external[nodeEnv]); cfg.set('jsUri', buildBaseUri + build.js.dirName + build.js.external[nodeEnv]); cfg.set('testUri', buildBaseUri + build.js.dirName + 'test.js'); // Resolve absolute paths from relative paths in config files cfg.set('staticPath', path.resolve(appPath, cfg.get('staticPath'))); cfg.set('routesPath', path.resolve(appPath, cfg.get('routesPath'))); cfg.set('buildBasePath', path.resolve(appPath, cfg.get('buildBasePath'))); cfg.set('helpersPath', path.resolve(appPath, cfg.get('helpersPath'))); cfg.set('handlebarsHelpersPath', path.resolve(appPath, cfg.get('handlebarsHelpersPath'))); cfg.set('repoWebViewBaseUri', cfg.get('repository').replace('.git', '/') ); keys = Object.keys(sources); for (i = 0; i < keys.length; i++) { key = keys[i]; cfg.set( 'sources.'+key, path.resolve( sourcesBasePath, sources[key]) ); } build.css.inline[nodeEnv] && cfg.set('build.css.inline', path.resolve( buildPath, build.css.inline[nodeEnv] )); build.css.external[nodeEnv] && cfg.set('build.css.external', path.resolve( buildPath, build.css.external[nodeEnv] )); build.js.inline[nodeEnv] && cfg.set('build.js.inline', path.resolve( buildPath, build.js.inline[nodeEnv] )); build.js.external[nodeEnv] && cfg.set('build.js.external', path.resolve( buildPath, build.js.external[nodeEnv] )); cfg.set('build.spritesheets', path.resolve( buildPath, build.spriteSheets.dirName )); return cfg; }
[ "function", "configurePaths", "(", "cfg", ")", "{", "var", "sourcesBasePath", "=", "path", ".", "resolve", "(", "appPath", ",", "cfg", ".", "get", "(", "'sourcesBasePath'", ")", ")", ",", "sources", "=", "cfg", ".", "get", "(", "'sources'", ")", ",", "build", "=", "cfg", ".", "get", "(", "'build'", ")", ",", "buildBaseUri", ",", "buildDir", "=", "nodeEnv", "==", "'development'", "?", "build", ".", "baseDirNameDev", ":", "build", ".", "baseDirNameDist", ",", "buildPath", "=", "path", ".", "join", "(", "path", ".", "resolve", "(", "appPath", ",", "cfg", ".", "get", "(", "'buildBasePath'", ")", ")", ",", "buildDir", ")", ",", "keys", ",", "key", ",", "i", ";", "buildBaseUri", "=", "cfg", ".", "get", "(", "'staticBaseUri'", ")", "+", "'/'", "+", "buildDir", "+", "'/'", ";", "cfg", ".", "set", "(", "'buildBaseUri'", ",", "buildBaseUri", ")", ";", "cfg", ".", "set", "(", "'cssUri'", ",", "buildBaseUri", "+", "build", ".", "css", ".", "dirName", "+", "build", ".", "css", ".", "external", "[", "nodeEnv", "]", ")", ";", "cfg", ".", "set", "(", "'jsUri'", ",", "buildBaseUri", "+", "build", ".", "js", ".", "dirName", "+", "build", ".", "js", ".", "external", "[", "nodeEnv", "]", ")", ";", "cfg", ".", "set", "(", "'testUri'", ",", "buildBaseUri", "+", "build", ".", "js", ".", "dirName", "+", "'test.js'", ")", ";", "cfg", ".", "set", "(", "'staticPath'", ",", "path", ".", "resolve", "(", "appPath", ",", "cfg", ".", "get", "(", "'staticPath'", ")", ")", ")", ";", "cfg", ".", "set", "(", "'routesPath'", ",", "path", ".", "resolve", "(", "appPath", ",", "cfg", ".", "get", "(", "'routesPath'", ")", ")", ")", ";", "cfg", ".", "set", "(", "'buildBasePath'", ",", "path", ".", "resolve", "(", "appPath", ",", "cfg", ".", "get", "(", "'buildBasePath'", ")", ")", ")", ";", "cfg", ".", "set", "(", "'helpersPath'", ",", "path", ".", "resolve", "(", "appPath", ",", "cfg", ".", "get", "(", "'helpersPath'", ")", ")", ")", ";", "cfg", ".", "set", "(", "'handlebarsHelpersPath'", ",", "path", ".", "resolve", "(", "appPath", ",", "cfg", ".", "get", "(", "'handlebarsHelpersPath'", ")", ")", ")", ";", "cfg", ".", "set", "(", "'repoWebViewBaseUri'", ",", "cfg", ".", "get", "(", "'repository'", ")", ".", "replace", "(", "'.git'", ",", "'/'", ")", ")", ";", "keys", "=", "Object", ".", "keys", "(", "sources", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "key", "=", "keys", "[", "i", "]", ";", "cfg", ".", "set", "(", "'sources.'", "+", "key", ",", "path", ".", "resolve", "(", "sourcesBasePath", ",", "sources", "[", "key", "]", ")", ")", ";", "}", "build", ".", "css", ".", "inline", "[", "nodeEnv", "]", "&&", "cfg", ".", "set", "(", "'build.css.inline'", ",", "path", ".", "resolve", "(", "buildPath", ",", "build", ".", "css", ".", "inline", "[", "nodeEnv", "]", ")", ")", ";", "build", ".", "css", ".", "external", "[", "nodeEnv", "]", "&&", "cfg", ".", "set", "(", "'build.css.external'", ",", "path", ".", "resolve", "(", "buildPath", ",", "build", ".", "css", ".", "external", "[", "nodeEnv", "]", ")", ")", ";", "build", ".", "js", ".", "inline", "[", "nodeEnv", "]", "&&", "cfg", ".", "set", "(", "'build.js.inline'", ",", "path", ".", "resolve", "(", "buildPath", ",", "build", ".", "js", ".", "inline", "[", "nodeEnv", "]", ")", ")", ";", "build", ".", "js", ".", "external", "[", "nodeEnv", "]", "&&", "cfg", ".", "set", "(", "'build.js.external'", ",", "path", ".", "resolve", "(", "buildPath", ",", "build", ".", "js", ".", "external", "[", "nodeEnv", "]", ")", ")", ";", "cfg", ".", "set", "(", "'build.spritesheets'", ",", "path", ".", "resolve", "(", "buildPath", ",", "build", ".", "spriteSheets", ".", "dirName", ")", ")", ";", "return", "cfg", ";", "}" ]
Build some paths and create absolute paths from the cfg.sources using our base path
[ "Build", "some", "paths", "and", "create", "absolute", "paths", "from", "the", "cfg", ".", "sources", "using", "our", "base", "path" ]
dd422136b27ca52b17255d4e8778ca30a70e987b
https://github.com/MarcDiethelm/xtc/blob/dd422136b27ca52b17255d4e8778ca30a70e987b/lib/configure.js#L103-L151
train
edjafarov/PromisePipe
example/connectors/HTTPDuplexStream.js
ServerClientStream
function ServerClientStream(app){ var StreamHandler; app.use(function(req, res, next){ if(req.originalUrl == '/promise-pipe-connector' && req.method=='POST'){ var message = req.body; message._response = res; StreamHandler(message) } else { return next(); } }); return { send: function(message){ if(!message._response) throw Error("no response defined"); var res = message._response; message._response = undefined; res.json(message); }, listen: function(handler){ StreamHandler = handler; } } }
javascript
function ServerClientStream(app){ var StreamHandler; app.use(function(req, res, next){ if(req.originalUrl == '/promise-pipe-connector' && req.method=='POST'){ var message = req.body; message._response = res; StreamHandler(message) } else { return next(); } }); return { send: function(message){ if(!message._response) throw Error("no response defined"); var res = message._response; message._response = undefined; res.json(message); }, listen: function(handler){ StreamHandler = handler; } } }
[ "function", "ServerClientStream", "(", "app", ")", "{", "var", "StreamHandler", ";", "app", ".", "use", "(", "function", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "req", ".", "originalUrl", "==", "'/promise-pipe-connector'", "&&", "req", ".", "method", "==", "'POST'", ")", "{", "var", "message", "=", "req", ".", "body", ";", "message", ".", "_response", "=", "res", ";", "StreamHandler", "(", "message", ")", "}", "else", "{", "return", "next", "(", ")", ";", "}", "}", ")", ";", "return", "{", "send", ":", "function", "(", "message", ")", "{", "if", "(", "!", "message", ".", "_response", ")", "throw", "Error", "(", "\"no response defined\"", ")", ";", "var", "res", "=", "message", ".", "_response", ";", "message", ".", "_response", "=", "undefined", ";", "res", ".", "json", "(", "message", ")", ";", "}", ",", "listen", ":", "function", "(", "handler", ")", "{", "StreamHandler", "=", "handler", ";", "}", "}", "}" ]
express app highly experimental
[ "express", "app", "highly", "experimental" ]
ec37d5eaab57feadc2e1f5a9f9e7306e32565143
https://github.com/edjafarov/PromisePipe/blob/ec37d5eaab57feadc2e1f5a9f9e7306e32565143/example/connectors/HTTPDuplexStream.js#L29-L51
train
chjj/node-pingback
lib/pingback.js
function(url, body, func) { if (typeof url !== 'object') { url = parse(url); } if (!func) { func = body; body = undefined; } var opt = { host: url.hostname, port: url.port || 80, path: url.pathname //agent: false }; if (body) { opt.headers = { 'Content-Type': 'application/xml; charset=utf-8', 'Content-Length': Buffer.byteLength(body), 'Range': 'bytes=0-5120' }; opt.method = 'POST'; } else { opt.method = 'GET'; } var req = http.request(opt); req.on('response', function(res) { var decoder = new StringDecoder('utf8') , total = 0 , body = '' , done = false; var end = function() { if (done) return; done = true; res.body = body; func(null, res); }; res.on('data', function(data) { total += data.length; body += decoder.write(data); if (total > 5120) { res.destroy(); end(); } }).on('error', function(err) { res.destroy(); func(err); }); res.on('end', end); // an agent socket's `end` sometimes // wont be emitted on the response res.socket.on('end', end); }); req.end(body); }
javascript
function(url, body, func) { if (typeof url !== 'object') { url = parse(url); } if (!func) { func = body; body = undefined; } var opt = { host: url.hostname, port: url.port || 80, path: url.pathname //agent: false }; if (body) { opt.headers = { 'Content-Type': 'application/xml; charset=utf-8', 'Content-Length': Buffer.byteLength(body), 'Range': 'bytes=0-5120' }; opt.method = 'POST'; } else { opt.method = 'GET'; } var req = http.request(opt); req.on('response', function(res) { var decoder = new StringDecoder('utf8') , total = 0 , body = '' , done = false; var end = function() { if (done) return; done = true; res.body = body; func(null, res); }; res.on('data', function(data) { total += data.length; body += decoder.write(data); if (total > 5120) { res.destroy(); end(); } }).on('error', function(err) { res.destroy(); func(err); }); res.on('end', end); // an agent socket's `end` sometimes // wont be emitted on the response res.socket.on('end', end); }); req.end(body); }
[ "function", "(", "url", ",", "body", ",", "func", ")", "{", "if", "(", "typeof", "url", "!==", "'object'", ")", "{", "url", "=", "parse", "(", "url", ")", ";", "}", "if", "(", "!", "func", ")", "{", "func", "=", "body", ";", "body", "=", "undefined", ";", "}", "var", "opt", "=", "{", "host", ":", "url", ".", "hostname", ",", "port", ":", "url", ".", "port", "||", "80", ",", "path", ":", "url", ".", "pathname", "}", ";", "if", "(", "body", ")", "{", "opt", ".", "headers", "=", "{", "'Content-Type'", ":", "'application/xml; charset=utf-8'", ",", "'Content-Length'", ":", "Buffer", ".", "byteLength", "(", "body", ")", ",", "'Range'", ":", "'bytes=0-5120'", "}", ";", "opt", ".", "method", "=", "'POST'", ";", "}", "else", "{", "opt", ".", "method", "=", "'GET'", ";", "}", "var", "req", "=", "http", ".", "request", "(", "opt", ")", ";", "req", ".", "on", "(", "'response'", ",", "function", "(", "res", ")", "{", "var", "decoder", "=", "new", "StringDecoder", "(", "'utf8'", ")", ",", "total", "=", "0", ",", "body", "=", "''", ",", "done", "=", "false", ";", "var", "end", "=", "function", "(", ")", "{", "if", "(", "done", ")", "return", ";", "done", "=", "true", ";", "res", ".", "body", "=", "body", ";", "func", "(", "null", ",", "res", ")", ";", "}", ";", "res", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "total", "+=", "data", ".", "length", ";", "body", "+=", "decoder", ".", "write", "(", "data", ")", ";", "if", "(", "total", ">", "5120", ")", "{", "res", ".", "destroy", "(", ")", ";", "end", "(", ")", ";", "}", "}", ")", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "res", ".", "destroy", "(", ")", ";", "func", "(", "err", ")", ";", "}", ")", ";", "res", ".", "on", "(", "'end'", ",", "end", ")", ";", "res", ".", "socket", ".", "on", "(", "'end'", ",", "end", ")", ";", "}", ")", ";", "req", ".", "end", "(", "body", ")", ";", "}" ]
HTTP Request make an http request
[ "HTTP", "Request", "make", "an", "http", "request" ]
4f2fa8847c7657e495a1065d5013eda0c4f16fee
https://github.com/chjj/node-pingback/blob/4f2fa8847c7657e495a1065d5013eda0c4f16fee/lib/pingback.js#L428-L489
train
jasonkneen/TiCh
bin/tich.js
status
function status() { console.log('\n'); console.log('Name: ' + chalk.cyan(tiapp.name)); console.log('AppId: ' + chalk.cyan(tiapp.id)); console.log('Version: ' + chalk.cyan(tiapp.version)); console.log('GUID: ' + chalk.cyan(tiapp.guid)); console.log('\n'); }
javascript
function status() { console.log('\n'); console.log('Name: ' + chalk.cyan(tiapp.name)); console.log('AppId: ' + chalk.cyan(tiapp.id)); console.log('Version: ' + chalk.cyan(tiapp.version)); console.log('GUID: ' + chalk.cyan(tiapp.guid)); console.log('\n'); }
[ "function", "status", "(", ")", "{", "console", ".", "log", "(", "'\\n'", ")", ";", "\\n", "console", ".", "log", "(", "'Name: '", "+", "chalk", ".", "cyan", "(", "tiapp", ".", "name", ")", ")", ";", "console", ".", "log", "(", "'AppId: '", "+", "chalk", ".", "cyan", "(", "tiapp", ".", "id", ")", ")", ";", "console", ".", "log", "(", "'Version: '", "+", "chalk", ".", "cyan", "(", "tiapp", ".", "version", ")", ")", ";", "console", ".", "log", "(", "'GUID: '", "+", "chalk", ".", "cyan", "(", "tiapp", ".", "guid", ")", ")", ";", "}" ]
status command, shows the current config
[ "status", "command", "shows", "the", "current", "config" ]
a7d7e36a73d591d2aa3ae0df9c6b3a3b2b8b3500
https://github.com/jasonkneen/TiCh/blob/a7d7e36a73d591d2aa3ae0df9c6b3a3b2b8b3500/bin/tich.js#L23-L30
train
jasonkneen/TiCh
bin/tich.js
select
function select(name, outfilename) { var regex = /\$tiapp\.(.*)\$/; if (!name) { if (fs.existsSync('./app/config.json')) { var alloyCfg = JSON.parse(fs.readFileSync("./app/config.json", "utf-8")); if (alloyCfg.global.theme) { console.log('\nFound a theme in config.json, trying ' + chalk.cyan(alloyCfg.global.theme)); select(alloyCfg.global.theme); } else { status(); } } } else { // find the config name specified cfg.configs.forEach(function(config) { if (config.name === name) { console.log('\nFound a config for ' + chalk.cyan(config.name) + '\n'); if (fs.existsSync('./app/config.json')) { var alloyCfg = JSON.parse(fs.readFileSync("./app/config.json", "utf-8")); if (alloyCfg.global.theme) { var original = alloyCfg.global.theme; alloyCfg.global.theme = name; fs.writeFile("./app/config.json", JSON.stringify(alloyCfg, null, 2), function (err) { if (err) return console.log(err); console.log('\nChanging theme value in config.json from ' + chalk.cyan(original) + ' to ' + chalk.cyan(name)); }); } } for (var setting in config.settings) { if (!config.settings.hasOwnProperty(setting)) continue; if (setting != "properties" && setting != "raw") { var now = new Date(); var replaceWith = config.settings[setting] .replace('$DATE$', now.toLocaleDateString()) .replace('$TIME$', now.toLocaleTimeString()) .replace('$DATETIME$', now.toLocaleString()) .replace('$TIME_EPOCH$', now.getTime().toString()); var matches = regex.exec(replaceWith); if (matches && matches[1]) { var propName = matches[1]; replaceWith = replaceWith.replace(regex, tiapp[propName]); } tiapp[setting] = replaceWith; console.log('Changing ' + chalk.cyan(setting) + ' to ' + chalk.yellow(replaceWith)); } } if (config.settings.properties) { for (var property in config.settings.properties) { if (!config.settings.properties.hasOwnProperty(property)) continue; var replaceWith = config.settings.properties[property] .replace('$DATE$', new Date().toLocaleDateString()) .replace('$TIME$', new Date().toLocaleTimeString()) .replace('$DATETIME$', new Date().toLocaleString()) .replace('$TIME_EPOCH$', new Date().getTime().toString()); var matches = regex.exec(replaceWith); if (matches && matches[1]) { var propName = matches[1]; replaceWith = replaceWith.replace(regex, tiapp[propName]); } tiapp.setProperty(property, replaceWith); console.log('Changing App property ' + chalk.cyan(property) + ' to ' + chalk.yellow(replaceWith)); } } if (config.settings.raw) { var doc = tiapp.doc; var select = xpath.useNamespaces({ "ti": "http://ti.appcelerator.org", "android": "http://schemas.android.com/apk/res/android" }); for (var path in config.settings.raw) { if (!config.settings.raw.hasOwnProperty(path)) continue; var node = select(path, doc, true); if (!node) { console.log(chalk.yellow('Could not find ' + path + ", skipping")); continue; } var replaceWith = config.settings.raw[path] .replace('$DATE$', new Date().toLocaleDateString()) .replace('$TIME$', new Date().toLocaleTimeString()) .replace('$DATETIME$', new Date().toLocaleString()) .replace('$TIME_EPOCH$', new Date().getTime().toString()); var matches = regex.exec(replaceWith); if (matches && matches[1]) { var propName = matches[1]; replaceWith = replaceWith.replace(regex, tiapp[propName]); } if (typeof(node.value) === 'undefined'){ node.firstChild.data = replaceWith; } else{ node.value = replaceWith; } console.log('Changing Raw property ' + chalk.cyan(path) + ' to ' + chalk.yellow(replaceWith)); } } if (fs.existsSync("./app/themes/" + name + "/assets/iphone/DefaultIcon.png")) { // if it exists in the themes folder, in a platform subfolder console.log(chalk.blue('Found a DefaultIcon.png in the theme\'s assets/iphone folder\n')); copyFile("./app/themes/" + name + "/assets/iphone/DefaultIcon.png", "./DefaultIcon.png") } else if (fs.existsSync("./app/themes/" + name + "/DefaultIcon.png")) { // if it exists in the top level theme folder console.log(chalk.blue('Found a DefaultIcon.png in the theme folder\n')); copyFile("./app/themes/" + name + "/" + "/DefaultIcon.png", "./DefaultIcon.png") } console.log(chalk.green('\n' + outfilename + ' updated\n')); tiapp.write(outfilename); } }); //console.log(chalk.red('\nCouldn\'t find a config called: ' + name + '\n')); } }
javascript
function select(name, outfilename) { var regex = /\$tiapp\.(.*)\$/; if (!name) { if (fs.existsSync('./app/config.json')) { var alloyCfg = JSON.parse(fs.readFileSync("./app/config.json", "utf-8")); if (alloyCfg.global.theme) { console.log('\nFound a theme in config.json, trying ' + chalk.cyan(alloyCfg.global.theme)); select(alloyCfg.global.theme); } else { status(); } } } else { // find the config name specified cfg.configs.forEach(function(config) { if (config.name === name) { console.log('\nFound a config for ' + chalk.cyan(config.name) + '\n'); if (fs.existsSync('./app/config.json')) { var alloyCfg = JSON.parse(fs.readFileSync("./app/config.json", "utf-8")); if (alloyCfg.global.theme) { var original = alloyCfg.global.theme; alloyCfg.global.theme = name; fs.writeFile("./app/config.json", JSON.stringify(alloyCfg, null, 2), function (err) { if (err) return console.log(err); console.log('\nChanging theme value in config.json from ' + chalk.cyan(original) + ' to ' + chalk.cyan(name)); }); } } for (var setting in config.settings) { if (!config.settings.hasOwnProperty(setting)) continue; if (setting != "properties" && setting != "raw") { var now = new Date(); var replaceWith = config.settings[setting] .replace('$DATE$', now.toLocaleDateString()) .replace('$TIME$', now.toLocaleTimeString()) .replace('$DATETIME$', now.toLocaleString()) .replace('$TIME_EPOCH$', now.getTime().toString()); var matches = regex.exec(replaceWith); if (matches && matches[1]) { var propName = matches[1]; replaceWith = replaceWith.replace(regex, tiapp[propName]); } tiapp[setting] = replaceWith; console.log('Changing ' + chalk.cyan(setting) + ' to ' + chalk.yellow(replaceWith)); } } if (config.settings.properties) { for (var property in config.settings.properties) { if (!config.settings.properties.hasOwnProperty(property)) continue; var replaceWith = config.settings.properties[property] .replace('$DATE$', new Date().toLocaleDateString()) .replace('$TIME$', new Date().toLocaleTimeString()) .replace('$DATETIME$', new Date().toLocaleString()) .replace('$TIME_EPOCH$', new Date().getTime().toString()); var matches = regex.exec(replaceWith); if (matches && matches[1]) { var propName = matches[1]; replaceWith = replaceWith.replace(regex, tiapp[propName]); } tiapp.setProperty(property, replaceWith); console.log('Changing App property ' + chalk.cyan(property) + ' to ' + chalk.yellow(replaceWith)); } } if (config.settings.raw) { var doc = tiapp.doc; var select = xpath.useNamespaces({ "ti": "http://ti.appcelerator.org", "android": "http://schemas.android.com/apk/res/android" }); for (var path in config.settings.raw) { if (!config.settings.raw.hasOwnProperty(path)) continue; var node = select(path, doc, true); if (!node) { console.log(chalk.yellow('Could not find ' + path + ", skipping")); continue; } var replaceWith = config.settings.raw[path] .replace('$DATE$', new Date().toLocaleDateString()) .replace('$TIME$', new Date().toLocaleTimeString()) .replace('$DATETIME$', new Date().toLocaleString()) .replace('$TIME_EPOCH$', new Date().getTime().toString()); var matches = regex.exec(replaceWith); if (matches && matches[1]) { var propName = matches[1]; replaceWith = replaceWith.replace(regex, tiapp[propName]); } if (typeof(node.value) === 'undefined'){ node.firstChild.data = replaceWith; } else{ node.value = replaceWith; } console.log('Changing Raw property ' + chalk.cyan(path) + ' to ' + chalk.yellow(replaceWith)); } } if (fs.existsSync("./app/themes/" + name + "/assets/iphone/DefaultIcon.png")) { // if it exists in the themes folder, in a platform subfolder console.log(chalk.blue('Found a DefaultIcon.png in the theme\'s assets/iphone folder\n')); copyFile("./app/themes/" + name + "/assets/iphone/DefaultIcon.png", "./DefaultIcon.png") } else if (fs.existsSync("./app/themes/" + name + "/DefaultIcon.png")) { // if it exists in the top level theme folder console.log(chalk.blue('Found a DefaultIcon.png in the theme folder\n')); copyFile("./app/themes/" + name + "/" + "/DefaultIcon.png", "./DefaultIcon.png") } console.log(chalk.green('\n' + outfilename + ' updated\n')); tiapp.write(outfilename); } }); //console.log(chalk.red('\nCouldn\'t find a config called: ' + name + '\n')); } }
[ "function", "select", "(", "name", ",", "outfilename", ")", "{", "var", "regex", "=", "/", "\\$tiapp\\.(.*)\\$", "/", ";", "if", "(", "!", "name", ")", "{", "if", "(", "fs", ".", "existsSync", "(", "'./app/config.json'", ")", ")", "{", "var", "alloyCfg", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "\"./app/config.json\"", ",", "\"utf-8\"", ")", ")", ";", "if", "(", "alloyCfg", ".", "global", ".", "theme", ")", "{", "console", ".", "log", "(", "'\\nFound a theme in config.json, trying '", "+", "\\n", ")", ";", "chalk", ".", "cyan", "(", "alloyCfg", ".", "global", ".", "theme", ")", "}", "else", "select", "(", "alloyCfg", ".", "global", ".", "theme", ")", ";", "}", "}", "else", "{", "status", "(", ")", ";", "}", "}" ]
select a new config by name
[ "select", "a", "new", "config", "by", "name" ]
a7d7e36a73d591d2aa3ae0df9c6b3a3b2b8b3500
https://github.com/jasonkneen/TiCh/blob/a7d7e36a73d591d2aa3ae0df9c6b3a3b2b8b3500/bin/tich.js#L33-L179
train
seancheung/kuconfig
lib/accumulator.js
$max
function $max(params) { if (Array.isArray(params) && params.every(p => typeof p === 'number')) { return Math.max(...params); } throw new Error('$max expects an array of number'); }
javascript
function $max(params) { if (Array.isArray(params) && params.every(p => typeof p === 'number')) { return Math.max(...params); } throw new Error('$max expects an array of number'); }
[ "function", "$max", "(", "params", ")", "{", "if", "(", "Array", ".", "isArray", "(", "params", ")", "&&", "params", ".", "every", "(", "p", "=>", "typeof", "p", "===", "'number'", ")", ")", "{", "return", "Math", ".", "max", "(", "...", "params", ")", ";", "}", "throw", "new", "Error", "(", "'$max expects an array of number'", ")", ";", "}" ]
Return the max number in the array @param {number[]} params @returns {number}
[ "Return", "the", "max", "number", "in", "the", "array" ]
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/accumulator.js#L7-L12
train
seancheung/kuconfig
lib/accumulator.js
$min
function $min(params) { if (Array.isArray(params) && params.every(p => typeof p === 'number')) { return Math.min(...params); } throw new Error('$min expects an array of number'); }
javascript
function $min(params) { if (Array.isArray(params) && params.every(p => typeof p === 'number')) { return Math.min(...params); } throw new Error('$min expects an array of number'); }
[ "function", "$min", "(", "params", ")", "{", "if", "(", "Array", ".", "isArray", "(", "params", ")", "&&", "params", ".", "every", "(", "p", "=>", "typeof", "p", "===", "'number'", ")", ")", "{", "return", "Math", ".", "min", "(", "...", "params", ")", ";", "}", "throw", "new", "Error", "(", "'$min expects an array of number'", ")", ";", "}" ]
Return the min number in the array @param {number[]} params @returns {number}
[ "Return", "the", "min", "number", "in", "the", "array" ]
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/accumulator.js#L20-L25
train
seancheung/kuconfig
lib/accumulator.js
$sum
function $sum(params) { if (Array.isArray(params) && params.every(p => typeof p === 'number')) { return params.reduce((t, n) => t + n, 0); } throw new Error('$sum expects an array of number'); }
javascript
function $sum(params) { if (Array.isArray(params) && params.every(p => typeof p === 'number')) { return params.reduce((t, n) => t + n, 0); } throw new Error('$sum expects an array of number'); }
[ "function", "$sum", "(", "params", ")", "{", "if", "(", "Array", ".", "isArray", "(", "params", ")", "&&", "params", ".", "every", "(", "p", "=>", "typeof", "p", "===", "'number'", ")", ")", "{", "return", "params", ".", "reduce", "(", "(", "t", ",", "n", ")", "=>", "t", "+", "n", ",", "0", ")", ";", "}", "throw", "new", "Error", "(", "'$sum expects an array of number'", ")", ";", "}" ]
Sum the numbers in the array @param {number[]} params @returns {number}
[ "Sum", "the", "numbers", "in", "the", "array" ]
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/accumulator.js#L33-L38
train
seancheung/kuconfig
lib/accumulator.js
$concat
function $concat(params) { if ( Array.isArray(params) && (params.every(p => typeof p === 'string') || params.every(p => Array.isArray(p))) ) { return params[0].concat(...params.slice(1)); } throw new Error('$concat expects an array of array or string'); }
javascript
function $concat(params) { if ( Array.isArray(params) && (params.every(p => typeof p === 'string') || params.every(p => Array.isArray(p))) ) { return params[0].concat(...params.slice(1)); } throw new Error('$concat expects an array of array or string'); }
[ "function", "$concat", "(", "params", ")", "{", "if", "(", "Array", ".", "isArray", "(", "params", ")", "&&", "(", "params", ".", "every", "(", "p", "=>", "typeof", "p", "===", "'string'", ")", "||", "params", ".", "every", "(", "p", "=>", "Array", ".", "isArray", "(", "p", ")", ")", ")", ")", "{", "return", "params", "[", "0", "]", ".", "concat", "(", "...", "params", ".", "slice", "(", "1", ")", ")", ";", "}", "throw", "new", "Error", "(", "'$concat expects an array of array or string'", ")", ";", "}" ]
Concat strings or arrays @param {string[]|[][]} params @returns {string|any[]}
[ "Concat", "strings", "or", "arrays" ]
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/accumulator.js#L105-L114
train
johnturingan/gulp-html-to-json
index.js
htmlToJsonController
function htmlToJsonController (fileContents, filePath, output, p) { var matches; var includePaths = false; while (matches = _DIRECTIVE_REGEX.exec(fileContents)) { var relPath = path.dirname(filePath), fullPath = path.join(relPath, matches[3].replace(/['"]/g, '')).trim(), jsonVar = matches[2], extension = matches[3].split('.').pop(); var fileMatches = []; if (p.includePaths) { if (typeof p.includePaths == "string") { // Arrayify the string includePaths = [params.includePaths]; }else if (Array.isArray(p.includePaths)) { // Set this array to the includepaths includePaths = p.includePaths; } var includePath = ''; for (var y = 0; y < includePaths.length; y++) { includePath = path.join(includePaths[y], matches[3].replace(/['"]/g, '')).trim(); if (fs.existsSync(includePath)) { var globResults = glob.sync(includePath, {mark: true}); fileMatches = fileMatches.concat(globResults); } } } else { var globResults = glob.sync(fullPath, {mark: true}); fileMatches = fileMatches.concat(globResults); } try { fileMatches.forEach(function(value){ var _inc = _parse(value); if (_inc.length > 0) { var ind = (jsonVar.trim() == '*') ? indName(value) : jsonVar; output[ind] = _inc; } }) } catch (err) { console.log(err) } } }
javascript
function htmlToJsonController (fileContents, filePath, output, p) { var matches; var includePaths = false; while (matches = _DIRECTIVE_REGEX.exec(fileContents)) { var relPath = path.dirname(filePath), fullPath = path.join(relPath, matches[3].replace(/['"]/g, '')).trim(), jsonVar = matches[2], extension = matches[3].split('.').pop(); var fileMatches = []; if (p.includePaths) { if (typeof p.includePaths == "string") { // Arrayify the string includePaths = [params.includePaths]; }else if (Array.isArray(p.includePaths)) { // Set this array to the includepaths includePaths = p.includePaths; } var includePath = ''; for (var y = 0; y < includePaths.length; y++) { includePath = path.join(includePaths[y], matches[3].replace(/['"]/g, '')).trim(); if (fs.existsSync(includePath)) { var globResults = glob.sync(includePath, {mark: true}); fileMatches = fileMatches.concat(globResults); } } } else { var globResults = glob.sync(fullPath, {mark: true}); fileMatches = fileMatches.concat(globResults); } try { fileMatches.forEach(function(value){ var _inc = _parse(value); if (_inc.length > 0) { var ind = (jsonVar.trim() == '*') ? indName(value) : jsonVar; output[ind] = _inc; } }) } catch (err) { console.log(err) } } }
[ "function", "htmlToJsonController", "(", "fileContents", ",", "filePath", ",", "output", ",", "p", ")", "{", "var", "matches", ";", "var", "includePaths", "=", "false", ";", "while", "(", "matches", "=", "_DIRECTIVE_REGEX", ".", "exec", "(", "fileContents", ")", ")", "{", "var", "relPath", "=", "path", ".", "dirname", "(", "filePath", ")", ",", "fullPath", "=", "path", ".", "join", "(", "relPath", ",", "matches", "[", "3", "]", ".", "replace", "(", "/", "['\"]", "/", "g", ",", "''", ")", ")", ".", "trim", "(", ")", ",", "jsonVar", "=", "matches", "[", "2", "]", ",", "extension", "=", "matches", "[", "3", "]", ".", "split", "(", "'.'", ")", ".", "pop", "(", ")", ";", "var", "fileMatches", "=", "[", "]", ";", "if", "(", "p", ".", "includePaths", ")", "{", "if", "(", "typeof", "p", ".", "includePaths", "==", "\"string\"", ")", "{", "includePaths", "=", "[", "params", ".", "includePaths", "]", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "p", ".", "includePaths", ")", ")", "{", "includePaths", "=", "p", ".", "includePaths", ";", "}", "var", "includePath", "=", "''", ";", "for", "(", "var", "y", "=", "0", ";", "y", "<", "includePaths", ".", "length", ";", "y", "++", ")", "{", "includePath", "=", "path", ".", "join", "(", "includePaths", "[", "y", "]", ",", "matches", "[", "3", "]", ".", "replace", "(", "/", "['\"]", "/", "g", ",", "''", ")", ")", ".", "trim", "(", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "includePath", ")", ")", "{", "var", "globResults", "=", "glob", ".", "sync", "(", "includePath", ",", "{", "mark", ":", "true", "}", ")", ";", "fileMatches", "=", "fileMatches", ".", "concat", "(", "globResults", ")", ";", "}", "}", "}", "else", "{", "var", "globResults", "=", "glob", ".", "sync", "(", "fullPath", ",", "{", "mark", ":", "true", "}", ")", ";", "fileMatches", "=", "fileMatches", ".", "concat", "(", "globResults", ")", ";", "}", "try", "{", "fileMatches", ".", "forEach", "(", "function", "(", "value", ")", "{", "var", "_inc", "=", "_parse", "(", "value", ")", ";", "if", "(", "_inc", ".", "length", ">", "0", ")", "{", "var", "ind", "=", "(", "jsonVar", ".", "trim", "(", ")", "==", "'*'", ")", "?", "indName", "(", "value", ")", ":", "jsonVar", ";", "output", "[", "ind", "]", "=", "_inc", ";", "}", "}", ")", "}", "catch", "(", "err", ")", "{", "console", ".", "log", "(", "err", ")", "}", "}", "}" ]
Control HTML to JSON @param fileContents @param filePath @param output @param p
[ "Control", "HTML", "to", "JSON" ]
c5b6d01ef57de59d985662dd9dd7f31e188a8b57
https://github.com/johnturingan/gulp-html-to-json/blob/c5b6d01ef57de59d985662dd9dd7f31e188a8b57/index.js#L117-L181
train
johnturingan/gulp-html-to-json
index.js
angularTemplate
function angularTemplate (p, json) { var prefix = (p.prefix !== "") ? p.prefix + "." : "", tpl = 'angular.module("'+ prefix + p.filename +'",["ng"]).run(["$templateCache",'; tpl += 'function($templateCache) {'; for (var key in json) { if (json.hasOwnProperty(key)) { tpl += '$templateCache.put("'+ key +'",'; tpl += JSON.stringify(json[key]); tpl += ');' } } tpl += '}])'; return tpl; }
javascript
function angularTemplate (p, json) { var prefix = (p.prefix !== "") ? p.prefix + "." : "", tpl = 'angular.module("'+ prefix + p.filename +'",["ng"]).run(["$templateCache",'; tpl += 'function($templateCache) {'; for (var key in json) { if (json.hasOwnProperty(key)) { tpl += '$templateCache.put("'+ key +'",'; tpl += JSON.stringify(json[key]); tpl += ');' } } tpl += '}])'; return tpl; }
[ "function", "angularTemplate", "(", "p", ",", "json", ")", "{", "var", "prefix", "=", "(", "p", ".", "prefix", "!==", "\"\"", ")", "?", "p", ".", "prefix", "+", "\".\"", ":", "\"\"", ",", "tpl", "=", "'angular.module(\"'", "+", "prefix", "+", "p", ".", "filename", "+", "'\",[\"ng\"]).run([\"$templateCache\",'", ";", "tpl", "+=", "'function($templateCache) {'", ";", "for", "(", "var", "key", "in", "json", ")", "{", "if", "(", "json", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "tpl", "+=", "'$templateCache.put(\"'", "+", "key", "+", "'\",'", ";", "tpl", "+=", "JSON", ".", "stringify", "(", "json", "[", "key", "]", ")", ";", "tpl", "+=", "');'", "}", "}", "tpl", "+=", "'}])'", ";", "return", "tpl", ";", "}" ]
Make Angular Template @param p @param json @returns {string}
[ "Make", "Angular", "Template" ]
c5b6d01ef57de59d985662dd9dd7f31e188a8b57
https://github.com/johnturingan/gulp-html-to-json/blob/c5b6d01ef57de59d985662dd9dd7f31e188a8b57/index.js#L189-L207
train
sliptype/sass-shake
src/sass-shake.js
getDependencies
async function getDependencies(includePaths, file) { const result = await util.promisify(sass.render)({ includePaths, file }); return result.stats.includedFiles.map(path.normalize); }
javascript
async function getDependencies(includePaths, file) { const result = await util.promisify(sass.render)({ includePaths, file }); return result.stats.includedFiles.map(path.normalize); }
[ "async", "function", "getDependencies", "(", "includePaths", ",", "file", ")", "{", "const", "result", "=", "await", "util", ".", "promisify", "(", "sass", ".", "render", ")", "(", "{", "includePaths", ",", "file", "}", ")", ";", "return", "result", ".", "stats", ".", "includedFiles", ".", "map", "(", "path", ".", "normalize", ")", ";", "}" ]
Gather a list of dependencies from a single sass tree @param { String } file @returns { Array } dependencies
[ "Gather", "a", "list", "of", "dependencies", "from", "a", "single", "sass", "tree" ]
dfd43f181a969b0e26d7e5f2b7e6dad6fba05405
https://github.com/sliptype/sass-shake/blob/dfd43f181a969b0e26d7e5f2b7e6dad6fba05405/src/sass-shake.js#L40-L43
train
sliptype/sass-shake
src/sass-shake.js
reduceEntryPointsToDependencies
async function reduceEntryPointsToDependencies(includePaths, entryPoints) { return await entryPoints.reduce(async function (allDeps, entry) { const resolvedDeps = await allDeps.then(); const newDeps = await getDependencies(includePaths, entry); return Promise.resolve([ ...resolvedDeps, ...newDeps ]); }, Promise.resolve([])); }
javascript
async function reduceEntryPointsToDependencies(includePaths, entryPoints) { return await entryPoints.reduce(async function (allDeps, entry) { const resolvedDeps = await allDeps.then(); const newDeps = await getDependencies(includePaths, entry); return Promise.resolve([ ...resolvedDeps, ...newDeps ]); }, Promise.resolve([])); }
[ "async", "function", "reduceEntryPointsToDependencies", "(", "includePaths", ",", "entryPoints", ")", "{", "return", "await", "entryPoints", ".", "reduce", "(", "async", "function", "(", "allDeps", ",", "entry", ")", "{", "const", "resolvedDeps", "=", "await", "allDeps", ".", "then", "(", ")", ";", "const", "newDeps", "=", "await", "getDependencies", "(", "includePaths", ",", "entry", ")", ";", "return", "Promise", ".", "resolve", "(", "[", "...", "resolvedDeps", ",", "...", "newDeps", "]", ")", ";", "}", ",", "Promise", ".", "resolve", "(", "[", "]", ")", ")", ";", "}" ]
Transform a list of entry points into a list of all dependencies @param { Array } entryPoints @returns { Array } dependencies
[ "Transform", "a", "list", "of", "entry", "points", "into", "a", "list", "of", "all", "dependencies" ]
dfd43f181a969b0e26d7e5f2b7e6dad6fba05405
https://github.com/sliptype/sass-shake/blob/dfd43f181a969b0e26d7e5f2b7e6dad6fba05405/src/sass-shake.js#L50-L59
train
sliptype/sass-shake
src/sass-shake.js
async function (directory, filesInSassTree, exclusions) { const filesInDirectory = (await recursive(directory)); const unusedFiles = filesInDirectory .filter((file) => isUnused(file, filesInSassTree, exclusions)); return unusedFiles; }
javascript
async function (directory, filesInSassTree, exclusions) { const filesInDirectory = (await recursive(directory)); const unusedFiles = filesInDirectory .filter((file) => isUnused(file, filesInSassTree, exclusions)); return unusedFiles; }
[ "async", "function", "(", "directory", ",", "filesInSassTree", ",", "exclusions", ")", "{", "const", "filesInDirectory", "=", "(", "await", "recursive", "(", "directory", ")", ")", ";", "const", "unusedFiles", "=", "filesInDirectory", ".", "filter", "(", "(", "file", ")", "=>", "isUnused", "(", "file", ",", "filesInSassTree", ",", "exclusions", ")", ")", ";", "return", "unusedFiles", ";", "}" ]
Compare directory contents with a list of files that are in use @param { String } directory @param { Array } filesInSassTree @param { Array } exclusions @returns { Array } files that are unused
[ "Compare", "directory", "contents", "with", "a", "list", "of", "files", "that", "are", "in", "use" ]
dfd43f181a969b0e26d7e5f2b7e6dad6fba05405
https://github.com/sliptype/sass-shake/blob/dfd43f181a969b0e26d7e5f2b7e6dad6fba05405/src/sass-shake.js#L91-L98
train
s1gtrap/node-binary-vdf
index.js
readIntoBuf
function readIntoBuf(stream) { return new Promise((resolve, reject) => { const chunks = [] stream.on('data', chunk => { chunks.push(chunk) }) stream.on('error', err => { reject(err) }) stream.on('end', () => { resolve(Buffer.concat(chunks)) }) }) }
javascript
function readIntoBuf(stream) { return new Promise((resolve, reject) => { const chunks = [] stream.on('data', chunk => { chunks.push(chunk) }) stream.on('error', err => { reject(err) }) stream.on('end', () => { resolve(Buffer.concat(chunks)) }) }) }
[ "function", "readIntoBuf", "(", "stream", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "chunks", "=", "[", "]", "stream", ".", "on", "(", "'data'", ",", "chunk", "=>", "{", "chunks", ".", "push", "(", "chunk", ")", "}", ")", "stream", ".", "on", "(", "'error'", ",", "err", "=>", "{", "reject", "(", "err", ")", "}", ")", "stream", ".", "on", "(", "'end'", ",", "(", ")", "=>", "{", "resolve", "(", "Buffer", ".", "concat", "(", "chunks", ")", ")", "}", ")", "}", ")", "}" ]
Produces a Promise that consumes a Readable entirely into a Buffer
[ "Produces", "a", "Promise", "that", "consumes", "a", "Readable", "entirely", "into", "a", "Buffer" ]
6d503bcc2053293d6aff3e0d85571404f1bdc1d7
https://github.com/s1gtrap/node-binary-vdf/blob/6d503bcc2053293d6aff3e0d85571404f1bdc1d7/index.js#L2-L18
train
s1gtrap/node-binary-vdf
index.js
readStr
function readStr(buf) { let size = 0 while (buf.readUInt8(size++) != 0x00) continue let str = buf.toString('utf8', 0, size - 1) return [str, size] }
javascript
function readStr(buf) { let size = 0 while (buf.readUInt8(size++) != 0x00) continue let str = buf.toString('utf8', 0, size - 1) return [str, size] }
[ "function", "readStr", "(", "buf", ")", "{", "let", "size", "=", "0", "while", "(", "buf", ".", "readUInt8", "(", "size", "++", ")", "!=", "0x00", ")", "continue", "let", "str", "=", "buf", ".", "toString", "(", "'utf8'", ",", "0", ",", "size", "-", "1", ")", "return", "[", "str", ",", "size", "]", "}" ]
Read a null-terminated UTF-8 string from a Buffer, returning the string and the number of bytes read
[ "Read", "a", "null", "-", "terminated", "UTF", "-", "8", "string", "from", "a", "Buffer", "returning", "the", "string", "and", "the", "number", "of", "bytes", "read" ]
6d503bcc2053293d6aff3e0d85571404f1bdc1d7
https://github.com/s1gtrap/node-binary-vdf/blob/6d503bcc2053293d6aff3e0d85571404f1bdc1d7/index.js#L22-L30
train
s1gtrap/node-binary-vdf
index.js
readAppInfo
function readAppInfo(buf) { // First byte varies across installs, only the 2nd and 3rd seem consistent if (buf.readUInt8(1) != 0x44 || buf.readUInt8(2) != 0x56) throw new Error('Invalid file signature') return readAppEntries(buf.slice(8)) }
javascript
function readAppInfo(buf) { // First byte varies across installs, only the 2nd and 3rd seem consistent if (buf.readUInt8(1) != 0x44 || buf.readUInt8(2) != 0x56) throw new Error('Invalid file signature') return readAppEntries(buf.slice(8)) }
[ "function", "readAppInfo", "(", "buf", ")", "{", "if", "(", "buf", ".", "readUInt8", "(", "1", ")", "!=", "0x44", "||", "buf", ".", "readUInt8", "(", "2", ")", "!=", "0x56", ")", "throw", "new", "Error", "(", "'Invalid file signature'", ")", "return", "readAppEntries", "(", "buf", ".", "slice", "(", "8", ")", ")", "}" ]
Read header and app entries from binary VDF Buffer
[ "Read", "header", "and", "app", "entries", "from", "binary", "VDF", "Buffer" ]
6d503bcc2053293d6aff3e0d85571404f1bdc1d7
https://github.com/s1gtrap/node-binary-vdf/blob/6d503bcc2053293d6aff3e0d85571404f1bdc1d7/index.js#L33-L39
train
s1gtrap/node-binary-vdf
index.js
readAppEntries
function readAppEntries(buf) { const entries = [] // App entry collection is terminated by null dword for (let off = 0; buf.readUInt32LE(off) != 0x00000000; ++off) { let [entry, size] = readAppEntry(buf.slice(off)) entries.push(entry) off += size } return entries }
javascript
function readAppEntries(buf) { const entries = [] // App entry collection is terminated by null dword for (let off = 0; buf.readUInt32LE(off) != 0x00000000; ++off) { let [entry, size] = readAppEntry(buf.slice(off)) entries.push(entry) off += size } return entries }
[ "function", "readAppEntries", "(", "buf", ")", "{", "const", "entries", "=", "[", "]", "for", "(", "let", "off", "=", "0", ";", "buf", ".", "readUInt32LE", "(", "off", ")", "!=", "0x00000000", ";", "++", "off", ")", "{", "let", "[", "entry", ",", "size", "]", "=", "readAppEntry", "(", "buf", ".", "slice", "(", "off", ")", ")", "entries", ".", "push", "(", "entry", ")", "off", "+=", "size", "}", "return", "entries", "}" ]
Read a collection of app entries
[ "Read", "a", "collection", "of", "app", "entries" ]
6d503bcc2053293d6aff3e0d85571404f1bdc1d7
https://github.com/s1gtrap/node-binary-vdf/blob/6d503bcc2053293d6aff3e0d85571404f1bdc1d7/index.js#L42-L55
train
s1gtrap/node-binary-vdf
index.js
readAppEntry
function readAppEntry(buf) { let off = 0 const id = buf.readUInt32LE(off) off += 49 // Skip a bunch of fields we don't care about const [name, nameSize] = readStr(buf.slice(off)) off += nameSize const [entries, entriesSize] = readEntries(buf.slice(off)) off += entriesSize return [{id, name, entries}, off] }
javascript
function readAppEntry(buf) { let off = 0 const id = buf.readUInt32LE(off) off += 49 // Skip a bunch of fields we don't care about const [name, nameSize] = readStr(buf.slice(off)) off += nameSize const [entries, entriesSize] = readEntries(buf.slice(off)) off += entriesSize return [{id, name, entries}, off] }
[ "function", "readAppEntry", "(", "buf", ")", "{", "let", "off", "=", "0", "const", "id", "=", "buf", ".", "readUInt32LE", "(", "off", ")", "off", "+=", "49", "const", "[", "name", ",", "nameSize", "]", "=", "readStr", "(", "buf", ".", "slice", "(", "off", ")", ")", "off", "+=", "nameSize", "const", "[", "entries", ",", "entriesSize", "]", "=", "readEntries", "(", "buf", ".", "slice", "(", "off", ")", ")", "off", "+=", "entriesSize", "return", "[", "{", "id", ",", "name", ",", "entries", "}", ",", "off", "]", "}" ]
Read a single app entry, returning its id, name and key-value entries
[ "Read", "a", "single", "app", "entry", "returning", "its", "id", "name", "and", "key", "-", "value", "entries" ]
6d503bcc2053293d6aff3e0d85571404f1bdc1d7
https://github.com/s1gtrap/node-binary-vdf/blob/6d503bcc2053293d6aff3e0d85571404f1bdc1d7/index.js#L58-L74
train
s1gtrap/node-binary-vdf
index.js
readEntries
function readEntries(buf) { const entries = {} let off = 0 // Entry collection is terminated by 0x08 byte for (; buf.readUInt8(off) != 0x08;) { let [key, val, size] = readEntry(buf.slice(off)) entries[key] = val off += size } return [entries, off + 1] }
javascript
function readEntries(buf) { const entries = {} let off = 0 // Entry collection is terminated by 0x08 byte for (; buf.readUInt8(off) != 0x08;) { let [key, val, size] = readEntry(buf.slice(off)) entries[key] = val off += size } return [entries, off + 1] }
[ "function", "readEntries", "(", "buf", ")", "{", "const", "entries", "=", "{", "}", "let", "off", "=", "0", "for", "(", ";", "buf", ".", "readUInt8", "(", "off", ")", "!=", "0x08", ";", ")", "{", "let", "[", "key", ",", "val", ",", "size", "]", "=", "readEntry", "(", "buf", ".", "slice", "(", "off", ")", ")", "entries", "[", "key", "]", "=", "val", "off", "+=", "size", "}", "return", "[", "entries", ",", "off", "+", "1", "]", "}" ]
Read a collection of key-value entries, returning the collection and bytes read
[ "Read", "a", "collection", "of", "key", "-", "value", "entries", "returning", "the", "collection", "and", "bytes", "read" ]
6d503bcc2053293d6aff3e0d85571404f1bdc1d7
https://github.com/s1gtrap/node-binary-vdf/blob/6d503bcc2053293d6aff3e0d85571404f1bdc1d7/index.js#L78-L93
train
s1gtrap/node-binary-vdf
index.js
readEntry
function readEntry(buf) { let off = 0 let type = buf.readUInt8(off) off += 1 let [key, keySize] = readStr(buf.slice(off)) off += keySize switch (type) { case 0x00: // Nested entries let [kvs, kvsSize] = readEntries(buf.slice(off)) return [key, kvs, off + kvsSize] case 0x01: // String let [str, strSize] = readStr(buf.slice(off)) return [key, str, off + strSize] case 0x02: // Int return [key, buf.readUInt32LE(off), off + 4] default: throw new Error(`Unhandled entry type: ${type}`) } }
javascript
function readEntry(buf) { let off = 0 let type = buf.readUInt8(off) off += 1 let [key, keySize] = readStr(buf.slice(off)) off += keySize switch (type) { case 0x00: // Nested entries let [kvs, kvsSize] = readEntries(buf.slice(off)) return [key, kvs, off + kvsSize] case 0x01: // String let [str, strSize] = readStr(buf.slice(off)) return [key, str, off + strSize] case 0x02: // Int return [key, buf.readUInt32LE(off), off + 4] default: throw new Error(`Unhandled entry type: ${type}`) } }
[ "function", "readEntry", "(", "buf", ")", "{", "let", "off", "=", "0", "let", "type", "=", "buf", ".", "readUInt8", "(", "off", ")", "off", "+=", "1", "let", "[", "key", ",", "keySize", "]", "=", "readStr", "(", "buf", ".", "slice", "(", "off", ")", ")", "off", "+=", "keySize", "switch", "(", "type", ")", "{", "case", "0x00", ":", "let", "[", "kvs", ",", "kvsSize", "]", "=", "readEntries", "(", "buf", ".", "slice", "(", "off", ")", ")", "return", "[", "key", ",", "kvs", ",", "off", "+", "kvsSize", "]", "case", "0x01", ":", "let", "[", "str", ",", "strSize", "]", "=", "readStr", "(", "buf", ".", "slice", "(", "off", ")", ")", "return", "[", "key", ",", "str", ",", "off", "+", "strSize", "]", "case", "0x02", ":", "return", "[", "key", ",", "buf", ".", "readUInt32LE", "(", "off", ")", ",", "off", "+", "4", "]", "default", ":", "throw", "new", "Error", "(", "`", "${", "type", "}", "`", ")", "}", "}" ]
Read a single entry, returning the key-value pair and bytes read
[ "Read", "a", "single", "entry", "returning", "the", "key", "-", "value", "pair", "and", "bytes", "read" ]
6d503bcc2053293d6aff3e0d85571404f1bdc1d7
https://github.com/s1gtrap/node-binary-vdf/blob/6d503bcc2053293d6aff3e0d85571404f1bdc1d7/index.js#L96-L124
train
MarcDiethelm/xtc
lib/mod-render.js
renderModule
function renderModule(context, options) { var cacheKey ,modSourceTemplate ,mergedData ,html ; // this check is used when rendering isolated modules or views for development and testing (in the default layout!). // skip any modules that are not THE module or THE view. // view: skip all modules that have the attribute _isLayout="true" // module: skip all other modules if ( context.skipModules === true || // case: module context.skipModules == 'layout' && options._isLayout // case: view ) { return ''; } options.template = options.template || options.name; options.tag = options.tag || defaults.tag; options.data = options.data || {}; options.data.moduleNestingLevel = typeof context.moduleNestingLevel === 'undefined' ? 0 : context.moduleNestingLevel + 1; autoIncrementIndent = options.data.moduleNestingLevel > 0 ? 1 : false; options.data.indent = options.indent || autoIncrementIndent || context.indent || 0; // merge the request context and data in the module include, with the latter trumping the former. mergedData = _.merge({}, context, options.data); // create a unique identifier for the module/template combination cacheKey = options.name + ' ' + options.template; // If addTest exists it means we should pass module options into it for later client-side module testing. context._locals && context._locals.addTest && context._locals.addTest(options); // force reading from disk in development mode NODE_ENV == 'development' && (cache[cacheKey] = null); // if the module/template combination is cached use it, else read from disk and cache it. modSourceTemplate = cache[cacheKey] || (cache[cacheKey] = getModTemplate(options)); // render the module source in the locally merged context // moduleSrc is a {{variable}} in the moduleWrapper template try { options.moduleSrc = modSourceTemplate.fn(mergedData); } catch (e) { if (process.env.NODE_ENV != 'test') { if (e instanceof RenderError) // if this is our error from a nested template rethrow it. throw e; else // if this is the original Handlebars error, make it useful throw new RenderError('Module: ' + options.name + ', Template: ' + options.template + cfg.templateExtension +'\n'+ e.toString().replace(/^Error/, 'Reason')); } } if (options.noWrapper) { html = options.moduleSrc; } else { // if we have a persisted read error, add the error class to the module. modSourceTemplate.err && (options.classes = options.classes ? options.classes + ' xtc-error' : 'xtc-error'); if (annotateModules) { options._module = modSourceTemplate.name; options._file = modSourceTemplate.file; options._path = modSourceTemplate.path; options._repository = modSourceTemplate.repository; } // render the wrapper template html = wrapperFn(options); } // manage indentation if (mergedData.indent) { html = utils.indent(html, mergedData.indent, cfg.indentString); } return html; }
javascript
function renderModule(context, options) { var cacheKey ,modSourceTemplate ,mergedData ,html ; // this check is used when rendering isolated modules or views for development and testing (in the default layout!). // skip any modules that are not THE module or THE view. // view: skip all modules that have the attribute _isLayout="true" // module: skip all other modules if ( context.skipModules === true || // case: module context.skipModules == 'layout' && options._isLayout // case: view ) { return ''; } options.template = options.template || options.name; options.tag = options.tag || defaults.tag; options.data = options.data || {}; options.data.moduleNestingLevel = typeof context.moduleNestingLevel === 'undefined' ? 0 : context.moduleNestingLevel + 1; autoIncrementIndent = options.data.moduleNestingLevel > 0 ? 1 : false; options.data.indent = options.indent || autoIncrementIndent || context.indent || 0; // merge the request context and data in the module include, with the latter trumping the former. mergedData = _.merge({}, context, options.data); // create a unique identifier for the module/template combination cacheKey = options.name + ' ' + options.template; // If addTest exists it means we should pass module options into it for later client-side module testing. context._locals && context._locals.addTest && context._locals.addTest(options); // force reading from disk in development mode NODE_ENV == 'development' && (cache[cacheKey] = null); // if the module/template combination is cached use it, else read from disk and cache it. modSourceTemplate = cache[cacheKey] || (cache[cacheKey] = getModTemplate(options)); // render the module source in the locally merged context // moduleSrc is a {{variable}} in the moduleWrapper template try { options.moduleSrc = modSourceTemplate.fn(mergedData); } catch (e) { if (process.env.NODE_ENV != 'test') { if (e instanceof RenderError) // if this is our error from a nested template rethrow it. throw e; else // if this is the original Handlebars error, make it useful throw new RenderError('Module: ' + options.name + ', Template: ' + options.template + cfg.templateExtension +'\n'+ e.toString().replace(/^Error/, 'Reason')); } } if (options.noWrapper) { html = options.moduleSrc; } else { // if we have a persisted read error, add the error class to the module. modSourceTemplate.err && (options.classes = options.classes ? options.classes + ' xtc-error' : 'xtc-error'); if (annotateModules) { options._module = modSourceTemplate.name; options._file = modSourceTemplate.file; options._path = modSourceTemplate.path; options._repository = modSourceTemplate.repository; } // render the wrapper template html = wrapperFn(options); } // manage indentation if (mergedData.indent) { html = utils.indent(html, mergedData.indent, cfg.indentString); } return html; }
[ "function", "renderModule", "(", "context", ",", "options", ")", "{", "var", "cacheKey", ",", "modSourceTemplate", ",", "mergedData", ",", "html", ";", "if", "(", "context", ".", "skipModules", "===", "true", "||", "context", ".", "skipModules", "==", "'layout'", "&&", "options", ".", "_isLayout", ")", "{", "return", "''", ";", "}", "options", ".", "template", "=", "options", ".", "template", "||", "options", ".", "name", ";", "options", ".", "tag", "=", "options", ".", "tag", "||", "defaults", ".", "tag", ";", "options", ".", "data", "=", "options", ".", "data", "||", "{", "}", ";", "options", ".", "data", ".", "moduleNestingLevel", "=", "typeof", "context", ".", "moduleNestingLevel", "===", "'undefined'", "?", "0", ":", "context", ".", "moduleNestingLevel", "+", "1", ";", "autoIncrementIndent", "=", "options", ".", "data", ".", "moduleNestingLevel", ">", "0", "?", "1", ":", "false", ";", "options", ".", "data", ".", "indent", "=", "options", ".", "indent", "||", "autoIncrementIndent", "||", "context", ".", "indent", "||", "0", ";", "mergedData", "=", "_", ".", "merge", "(", "{", "}", ",", "context", ",", "options", ".", "data", ")", ";", "cacheKey", "=", "options", ".", "name", "+", "' '", "+", "options", ".", "template", ";", "context", ".", "_locals", "&&", "context", ".", "_locals", ".", "addTest", "&&", "context", ".", "_locals", ".", "addTest", "(", "options", ")", ";", "NODE_ENV", "==", "'development'", "&&", "(", "cache", "[", "cacheKey", "]", "=", "null", ")", ";", "modSourceTemplate", "=", "cache", "[", "cacheKey", "]", "||", "(", "cache", "[", "cacheKey", "]", "=", "getModTemplate", "(", "options", ")", ")", ";", "try", "{", "options", ".", "moduleSrc", "=", "modSourceTemplate", ".", "fn", "(", "mergedData", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "process", ".", "env", ".", "NODE_ENV", "!=", "'test'", ")", "{", "if", "(", "e", "instanceof", "RenderError", ")", "throw", "e", ";", "else", "throw", "new", "RenderError", "(", "'Module: '", "+", "options", ".", "name", "+", "', Template: '", "+", "options", ".", "template", "+", "cfg", ".", "templateExtension", "+", "'\\n'", "+", "\\n", ")", ";", "}", "}", "e", ".", "toString", "(", ")", ".", "replace", "(", "/", "^Error", "/", ",", "'Reason'", ")", "if", "(", "options", ".", "noWrapper", ")", "{", "html", "=", "options", ".", "moduleSrc", ";", "}", "else", "{", "modSourceTemplate", ".", "err", "&&", "(", "options", ".", "classes", "=", "options", ".", "classes", "?", "options", ".", "classes", "+", "' xtc-error'", ":", "'xtc-error'", ")", ";", "if", "(", "annotateModules", ")", "{", "options", ".", "_module", "=", "modSourceTemplate", ".", "name", ";", "options", ".", "_file", "=", "modSourceTemplate", ".", "file", ";", "options", ".", "_path", "=", "modSourceTemplate", ".", "path", ";", "options", ".", "_repository", "=", "modSourceTemplate", ".", "repository", ";", "}", "html", "=", "wrapperFn", "(", "options", ")", ";", "}", "if", "(", "mergedData", ".", "indent", ")", "{", "html", "=", "utils", ".", "indent", "(", "html", ",", "mergedData", ".", "indent", ",", "cfg", ".", "indentString", ")", ";", "}", "}" ]
Render a Terrific markup module @param {Object} context @param {{name: String}} options @returns {String} – Module HTML
[ "Render", "a", "Terrific", "markup", "module" ]
dd422136b27ca52b17255d4e8778ca30a70e987b
https://github.com/MarcDiethelm/xtc/blob/dd422136b27ca52b17255d4e8778ca30a70e987b/lib/mod-render.js#L55-L133
train
henrytseng/hostr
lib/watch.js
_recurseFolder
function _recurseFolder(src) { // Ignore var relativeSrc = path.relative(process.cwd(), src); if(_isIgnored(relativeSrc)) return; // Process fs.readdir(src, function(err, files) { files.forEach(function(filename) { fs.stat(src+path.sep+filename, function(err, stat) { if(stat && stat.isDirectory()) { _recurseFolder(src+path.sep+filename); } }); }); }); // Watch current folder _track(src); }
javascript
function _recurseFolder(src) { // Ignore var relativeSrc = path.relative(process.cwd(), src); if(_isIgnored(relativeSrc)) return; // Process fs.readdir(src, function(err, files) { files.forEach(function(filename) { fs.stat(src+path.sep+filename, function(err, stat) { if(stat && stat.isDirectory()) { _recurseFolder(src+path.sep+filename); } }); }); }); // Watch current folder _track(src); }
[ "function", "_recurseFolder", "(", "src", ")", "{", "var", "relativeSrc", "=", "path", ".", "relative", "(", "process", ".", "cwd", "(", ")", ",", "src", ")", ";", "if", "(", "_isIgnored", "(", "relativeSrc", ")", ")", "return", ";", "fs", ".", "readdir", "(", "src", ",", "function", "(", "err", ",", "files", ")", "{", "files", ".", "forEach", "(", "function", "(", "filename", ")", "{", "fs", ".", "stat", "(", "src", "+", "path", ".", "sep", "+", "filename", ",", "function", "(", "err", ",", "stat", ")", "{", "if", "(", "stat", "&&", "stat", ".", "isDirectory", "(", ")", ")", "{", "_recurseFolder", "(", "src", "+", "path", ".", "sep", "+", "filename", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", ")", ";", "_track", "(", "src", ")", ";", "}" ]
Internal method to watch folders recursively @param {String} src A path to start from
[ "Internal", "method", "to", "watch", "folders", "recursively" ]
8ef1ec59d2acdd135eafb19d439519a8d87ff21a
https://github.com/henrytseng/hostr/blob/8ef1ec59d2acdd135eafb19d439519a8d87ff21a/lib/watch.js#L85-L103
train
roboncode/tang
lib/factory.js
factory
function factory(name, schema = {}, options = {}) { class TangModel extends Model { constructor(data) { super(data, schema, options) } } TangModel.options = options TangModel.schema = schema Object.defineProperty(TangModel, 'name', { value: name }) for (let name in schema.statics) { TangModel[name] = function() { return schema.statics[name].apply(TangModel, arguments) } } return TangModel }
javascript
function factory(name, schema = {}, options = {}) { class TangModel extends Model { constructor(data) { super(data, schema, options) } } TangModel.options = options TangModel.schema = schema Object.defineProperty(TangModel, 'name', { value: name }) for (let name in schema.statics) { TangModel[name] = function() { return schema.statics[name].apply(TangModel, arguments) } } return TangModel }
[ "function", "factory", "(", "name", ",", "schema", "=", "{", "}", ",", "options", "=", "{", "}", ")", "{", "class", "TangModel", "extends", "Model", "{", "constructor", "(", "data", ")", "{", "super", "(", "data", ",", "schema", ",", "options", ")", "}", "}", "TangModel", ".", "options", "=", "options", "TangModel", ".", "schema", "=", "schema", "Object", ".", "defineProperty", "(", "TangModel", ",", "'name'", ",", "{", "value", ":", "name", "}", ")", "for", "(", "let", "name", "in", "schema", ".", "statics", ")", "{", "TangModel", "[", "name", "]", "=", "function", "(", ")", "{", "return", "schema", ".", "statics", "[", "name", "]", ".", "apply", "(", "TangModel", ",", "arguments", ")", "}", "}", "return", "TangModel", "}" ]
Constructs a Model class @param {*} name @param {*} schema @param {*} options
[ "Constructs", "a", "Model", "class" ]
3e3826be0e1a621faf3eeea8c769dd28343fb326
https://github.com/roboncode/tang/blob/3e3826be0e1a621faf3eeea8c769dd28343fb326/lib/factory.js#L8-L27
train
adrai/devicestack
lib/usb/deviceloader.js
UsbDeviceLoader
function UsbDeviceLoader(Device, vendorId, productId) { // call super class DeviceLoader.call(this); this.Device = Device; this.vidPidPairs = []; if (!productId && _.isArray(vendorId)) { this.vidPidPairs = vendorId; } else { this.vidPidPairs = [{vendorId: vendorId, productId: productId}]; } }
javascript
function UsbDeviceLoader(Device, vendorId, productId) { // call super class DeviceLoader.call(this); this.Device = Device; this.vidPidPairs = []; if (!productId && _.isArray(vendorId)) { this.vidPidPairs = vendorId; } else { this.vidPidPairs = [{vendorId: vendorId, productId: productId}]; } }
[ "function", "UsbDeviceLoader", "(", "Device", ",", "vendorId", ",", "productId", ")", "{", "DeviceLoader", ".", "call", "(", "this", ")", ";", "this", ".", "Device", "=", "Device", ";", "this", ".", "vidPidPairs", "=", "[", "]", ";", "if", "(", "!", "productId", "&&", "_", ".", "isArray", "(", "vendorId", ")", ")", "{", "this", ".", "vidPidPairs", "=", "vendorId", ";", "}", "else", "{", "this", ".", "vidPidPairs", "=", "[", "{", "vendorId", ":", "vendorId", ",", "productId", ":", "productId", "}", "]", ";", "}", "}" ]
A usbdeviceloader can check if there are available some serial devices. @param {Object} Device Device The constructor function of the device. @param {Number || Array} vendorId The vendor id or an array of vid/pid pairs. @param {Number} productId The product id or optional.
[ "A", "usbdeviceloader", "can", "check", "if", "there", "are", "available", "some", "serial", "devices", "." ]
c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76
https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/usb/deviceloader.js#L13-L27
train
mkloubert/nativescript-xmlobjects
plugin/index.js
function () { var childNodes = this.nodes(); if (childNodes.length < 1) { return null; } var elementValue = ''; for (var i = 0; i < childNodes.length; i++) { var node = childNodes[i]; var valueToAdd; if (!TypeUtils.isNullOrUndefined(node.value)) { valueToAdd = node.value; } else { valueToAdd = node.toString(); } if (!TypeUtils.isNullOrUndefined(valueToAdd)) { elementValue += valueToAdd; } } return elementValue; }
javascript
function () { var childNodes = this.nodes(); if (childNodes.length < 1) { return null; } var elementValue = ''; for (var i = 0; i < childNodes.length; i++) { var node = childNodes[i]; var valueToAdd; if (!TypeUtils.isNullOrUndefined(node.value)) { valueToAdd = node.value; } else { valueToAdd = node.toString(); } if (!TypeUtils.isNullOrUndefined(valueToAdd)) { elementValue += valueToAdd; } } return elementValue; }
[ "function", "(", ")", "{", "var", "childNodes", "=", "this", ".", "nodes", "(", ")", ";", "if", "(", "childNodes", ".", "length", "<", "1", ")", "{", "return", "null", ";", "}", "var", "elementValue", "=", "''", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "childNodes", ".", "length", ";", "i", "++", ")", "{", "var", "node", "=", "childNodes", "[", "i", "]", ";", "var", "valueToAdd", ";", "if", "(", "!", "TypeUtils", ".", "isNullOrUndefined", "(", "node", ".", "value", ")", ")", "{", "valueToAdd", "=", "node", ".", "value", ";", "}", "else", "{", "valueToAdd", "=", "node", ".", "toString", "(", ")", ";", "}", "if", "(", "!", "TypeUtils", ".", "isNullOrUndefined", "(", "valueToAdd", ")", ")", "{", "elementValue", "+=", "valueToAdd", ";", "}", "}", "return", "elementValue", ";", "}" ]
Gets the value of that element. @return {any} The value.
[ "Gets", "the", "value", "of", "that", "element", "." ]
8e75f9b4a28d0ac3a737021ade03130c9448a2fc
https://github.com/mkloubert/nativescript-xmlobjects/blob/8e75f9b4a28d0ac3a737021ade03130c9448a2fc/plugin/index.js#L485-L505
train
mkloubert/nativescript-xmlobjects
plugin/index.js
parse
function parse(xml, processNamespaces, angularSyntax) { var doc = new XDocument(); var errors = []; var elementStack = []; var currentContainer = function () { return elementStack.length > 0 ? elementStack[elementStack.length - 1] : doc; }; var xParser = new Xml.XmlParser(function (e) { var c = currentContainer(); if (e.eventType === Xml.ParserEventType.StartElement) { var newElement = new XElement(e.elementName); newElement.add(e.data); var attribs = getOwnProperties(e.attributes); if (!TypeUtils.isNullOrUndefined(attribs)) { for (var p in attribs) { var a = new XAttribute(p); a.value = attribs[p]; newElement.add(a); } } currentContainer().add(newElement); elementStack.push(newElement); } else if (e.eventType === Xml.ParserEventType.Text) { var newText = new XText(); newText.value = e.data; currentContainer().add(newText); } else if (e.eventType === Xml.ParserEventType.CDATA) { var newCData = new XCData(); newCData.value = e.data; currentContainer().add(newCData); } else if (e.eventType === Xml.ParserEventType.Comment) { var newComment = new XComment(); newComment.value = e.data; currentContainer().add(newComment); } else if (e.eventType === Xml.ParserEventType.EndElement) { elementStack.pop(); } }, function (error, position) { errors.push([error, position]); }, processNamespaces, angularSyntax); xParser.parse(xml); if (errors.length > 0) { // collect errors and throw var exceptionMsg = 'XML parse error:'; for (var i = 0; i < errors.length; i++) { var err = errors[i][0]; var pos = errors[i][1]; exceptionMsg += "\n(" + pos.column + "," + pos.line + "): [" + err.name + "] " + err.message; } throw exceptionMsg; } return doc; }
javascript
function parse(xml, processNamespaces, angularSyntax) { var doc = new XDocument(); var errors = []; var elementStack = []; var currentContainer = function () { return elementStack.length > 0 ? elementStack[elementStack.length - 1] : doc; }; var xParser = new Xml.XmlParser(function (e) { var c = currentContainer(); if (e.eventType === Xml.ParserEventType.StartElement) { var newElement = new XElement(e.elementName); newElement.add(e.data); var attribs = getOwnProperties(e.attributes); if (!TypeUtils.isNullOrUndefined(attribs)) { for (var p in attribs) { var a = new XAttribute(p); a.value = attribs[p]; newElement.add(a); } } currentContainer().add(newElement); elementStack.push(newElement); } else if (e.eventType === Xml.ParserEventType.Text) { var newText = new XText(); newText.value = e.data; currentContainer().add(newText); } else if (e.eventType === Xml.ParserEventType.CDATA) { var newCData = new XCData(); newCData.value = e.data; currentContainer().add(newCData); } else if (e.eventType === Xml.ParserEventType.Comment) { var newComment = new XComment(); newComment.value = e.data; currentContainer().add(newComment); } else if (e.eventType === Xml.ParserEventType.EndElement) { elementStack.pop(); } }, function (error, position) { errors.push([error, position]); }, processNamespaces, angularSyntax); xParser.parse(xml); if (errors.length > 0) { // collect errors and throw var exceptionMsg = 'XML parse error:'; for (var i = 0; i < errors.length; i++) { var err = errors[i][0]; var pos = errors[i][1]; exceptionMsg += "\n(" + pos.column + "," + pos.line + "): [" + err.name + "] " + err.message; } throw exceptionMsg; } return doc; }
[ "function", "parse", "(", "xml", ",", "processNamespaces", ",", "angularSyntax", ")", "{", "var", "doc", "=", "new", "XDocument", "(", ")", ";", "var", "errors", "=", "[", "]", ";", "var", "elementStack", "=", "[", "]", ";", "var", "currentContainer", "=", "function", "(", ")", "{", "return", "elementStack", ".", "length", ">", "0", "?", "elementStack", "[", "elementStack", ".", "length", "-", "1", "]", ":", "doc", ";", "}", ";", "var", "xParser", "=", "new", "Xml", ".", "XmlParser", "(", "function", "(", "e", ")", "{", "var", "c", "=", "currentContainer", "(", ")", ";", "if", "(", "e", ".", "eventType", "===", "Xml", ".", "ParserEventType", ".", "StartElement", ")", "{", "var", "newElement", "=", "new", "XElement", "(", "e", ".", "elementName", ")", ";", "newElement", ".", "add", "(", "e", ".", "data", ")", ";", "var", "attribs", "=", "getOwnProperties", "(", "e", ".", "attributes", ")", ";", "if", "(", "!", "TypeUtils", ".", "isNullOrUndefined", "(", "attribs", ")", ")", "{", "for", "(", "var", "p", "in", "attribs", ")", "{", "var", "a", "=", "new", "XAttribute", "(", "p", ")", ";", "a", ".", "value", "=", "attribs", "[", "p", "]", ";", "newElement", ".", "add", "(", "a", ")", ";", "}", "}", "currentContainer", "(", ")", ".", "add", "(", "newElement", ")", ";", "elementStack", ".", "push", "(", "newElement", ")", ";", "}", "else", "if", "(", "e", ".", "eventType", "===", "Xml", ".", "ParserEventType", ".", "Text", ")", "{", "var", "newText", "=", "new", "XText", "(", ")", ";", "newText", ".", "value", "=", "e", ".", "data", ";", "currentContainer", "(", ")", ".", "add", "(", "newText", ")", ";", "}", "else", "if", "(", "e", ".", "eventType", "===", "Xml", ".", "ParserEventType", ".", "CDATA", ")", "{", "var", "newCData", "=", "new", "XCData", "(", ")", ";", "newCData", ".", "value", "=", "e", ".", "data", ";", "currentContainer", "(", ")", ".", "add", "(", "newCData", ")", ";", "}", "else", "if", "(", "e", ".", "eventType", "===", "Xml", ".", "ParserEventType", ".", "Comment", ")", "{", "var", "newComment", "=", "new", "XComment", "(", ")", ";", "newComment", ".", "value", "=", "e", ".", "data", ";", "currentContainer", "(", ")", ".", "add", "(", "newComment", ")", ";", "}", "else", "if", "(", "e", ".", "eventType", "===", "Xml", ".", "ParserEventType", ".", "EndElement", ")", "{", "elementStack", ".", "pop", "(", ")", ";", "}", "}", ",", "function", "(", "error", ",", "position", ")", "{", "errors", ".", "push", "(", "[", "error", ",", "position", "]", ")", ";", "}", ",", "processNamespaces", ",", "angularSyntax", ")", ";", "xParser", ".", "parse", "(", "xml", ")", ";", "if", "(", "errors", ".", "length", ">", "0", ")", "{", "var", "exceptionMsg", "=", "'XML parse error:'", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "errors", ".", "length", ";", "i", "++", ")", "{", "var", "err", "=", "errors", "[", "i", "]", "[", "0", "]", ";", "var", "pos", "=", "errors", "[", "i", "]", "[", "1", "]", ";", "exceptionMsg", "+=", "\"\\n(\"", "+", "\\n", "+", "pos", ".", "column", "+", "\",\"", "+", "pos", ".", "line", "+", "\"): [\"", "+", "err", ".", "name", "+", "\"] \"", ";", "}", "err", ".", "message", "}", "throw", "exceptionMsg", ";", "}" ]
Parses an XML string. @param {String} xml The string to parse. @param {Boolean} [processNamespaces] Process namespaces or not. @param {Boolean} [angularSyntax] Handle Angular syntax or not. @return {XDocument} The new document. @throws Parse error.
[ "Parses", "an", "XML", "string", "." ]
8e75f9b4a28d0ac3a737021ade03130c9448a2fc
https://github.com/mkloubert/nativescript-xmlobjects/blob/8e75f9b4a28d0ac3a737021ade03130c9448a2fc/plugin/index.js#L583-L637
train
Losant/bravado-core
lib/entity.js
function(options) { options = options || {}; this.type = options.type; this.body = options.body; this.actions = options.actions; this.links = options.links; this.embedded = options.embedded; }
javascript
function(options) { options = options || {}; this.type = options.type; this.body = options.body; this.actions = options.actions; this.links = options.links; this.embedded = options.embedded; }
[ "function", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "type", "=", "options", ".", "type", ";", "this", ".", "body", "=", "options", ".", "body", ";", "this", ".", "actions", "=", "options", ".", "actions", ";", "this", ".", "links", "=", "options", ".", "links", ";", "this", ".", "embedded", "=", "options", ".", "embedded", ";", "}" ]
Object that represents an entity returned by a resource's action
[ "Object", "that", "represents", "an", "entity", "returned", "by", "a", "resource", "s", "action" ]
df152017e0aff9e575c1f7beaf4ddbb9cd346a7c
https://github.com/Losant/bravado-core/blob/df152017e0aff9e575c1f7beaf4ddbb9cd346a7c/lib/entity.js#L33-L40
train
ibm-watson-data-lab/--deprecated--pipes-sdk
lib/storage/pipeStorage.js
outboundPayload
function outboundPayload( pipe ){ //Clone first var result = JSON.parse(JSON.stringify( pipe ) ); if ( result.hasOwnProperty("tables")){ //Filtered down the table object as the info it contains is too big to be transported back and forth result.tables = _.map( result.tables, function( table ){ var ret = { name: table.name, label: table.label, labelPlural: table.labelPlural }; //Check for field that start with prefix CLIENT_ which means that the connector expects the value to be sent to client _.map(table, function(value, key){ if ( _.startsWith(key, "CLIENT_")){ ret[key] = value; } }); return ret; }); } if ( result.hasOwnProperty( "sf") ){ delete result.sf; } return result; }
javascript
function outboundPayload( pipe ){ //Clone first var result = JSON.parse(JSON.stringify( pipe ) ); if ( result.hasOwnProperty("tables")){ //Filtered down the table object as the info it contains is too big to be transported back and forth result.tables = _.map( result.tables, function( table ){ var ret = { name: table.name, label: table.label, labelPlural: table.labelPlural }; //Check for field that start with prefix CLIENT_ which means that the connector expects the value to be sent to client _.map(table, function(value, key){ if ( _.startsWith(key, "CLIENT_")){ ret[key] = value; } }); return ret; }); } if ( result.hasOwnProperty( "sf") ){ delete result.sf; } return result; }
[ "function", "outboundPayload", "(", "pipe", ")", "{", "var", "result", "=", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "pipe", ")", ")", ";", "if", "(", "result", ".", "hasOwnProperty", "(", "\"tables\"", ")", ")", "{", "result", ".", "tables", "=", "_", ".", "map", "(", "result", ".", "tables", ",", "function", "(", "table", ")", "{", "var", "ret", "=", "{", "name", ":", "table", ".", "name", ",", "label", ":", "table", ".", "label", ",", "labelPlural", ":", "table", ".", "labelPlural", "}", ";", "_", ".", "map", "(", "table", ",", "function", "(", "value", ",", "key", ")", "{", "if", "(", "_", ".", "startsWith", "(", "key", ",", "\"CLIENT_\"", ")", ")", "{", "ret", "[", "key", "]", "=", "value", ";", "}", "}", ")", ";", "return", "ret", ";", "}", ")", ";", "}", "if", "(", "result", ".", "hasOwnProperty", "(", "\"sf\"", ")", ")", "{", "delete", "result", ".", "sf", ";", "}", "return", "result", ";", "}" ]
Return a filtered down version of the pipe for outbound purposes @param pipe
[ "Return", "a", "filtered", "down", "version", "of", "the", "pipe", "for", "outbound", "purposes" ]
b5cbf238d8d2c6a852f1712eed7dcfabeebfdb25
https://github.com/ibm-watson-data-lab/--deprecated--pipes-sdk/blob/b5cbf238d8d2c6a852f1712eed7dcfabeebfdb25/lib/storage/pipeStorage.js#L204-L225
train
ibm-watson-data-lab/--deprecated--pipes-sdk
lib/storage/pipeStorage.js
inboundPayload
function inboundPayload( storedPipe, pipe ){ if ( storedPipe && storedPipe.hasOwnProperty( "tables" ) ){ pipe.tables = storedPipe.tables; } if ( !pipe.hasOwnProperty("sf") ){ if ( storedPipe && storedPipe.hasOwnProperty( "sf" ) ){ pipe.sf = storedPipe.sf; } } return pipe; }
javascript
function inboundPayload( storedPipe, pipe ){ if ( storedPipe && storedPipe.hasOwnProperty( "tables" ) ){ pipe.tables = storedPipe.tables; } if ( !pipe.hasOwnProperty("sf") ){ if ( storedPipe && storedPipe.hasOwnProperty( "sf" ) ){ pipe.sf = storedPipe.sf; } } return pipe; }
[ "function", "inboundPayload", "(", "storedPipe", ",", "pipe", ")", "{", "if", "(", "storedPipe", "&&", "storedPipe", ".", "hasOwnProperty", "(", "\"tables\"", ")", ")", "{", "pipe", ".", "tables", "=", "storedPipe", ".", "tables", ";", "}", "if", "(", "!", "pipe", ".", "hasOwnProperty", "(", "\"sf\"", ")", ")", "{", "if", "(", "storedPipe", "&&", "storedPipe", ".", "hasOwnProperty", "(", "\"sf\"", ")", ")", "{", "pipe", ".", "sf", "=", "storedPipe", ".", "sf", ";", "}", "}", "return", "pipe", ";", "}" ]
Merge the pipe with the stored value, restoring any fields that have been filtered during outbound
[ "Merge", "the", "pipe", "with", "the", "stored", "value", "restoring", "any", "fields", "that", "have", "been", "filtered", "during", "outbound" ]
b5cbf238d8d2c6a852f1712eed7dcfabeebfdb25
https://github.com/ibm-watson-data-lab/--deprecated--pipes-sdk/blob/b5cbf238d8d2c6a852f1712eed7dcfabeebfdb25/lib/storage/pipeStorage.js#L230-L241
train
fuzhenn/maptalks-jsdoc
publish.js
mergeClassOptions
function mergeClassOptions(classes, clazz) { if (!clazz || !clazz.length) { return; } clazz = clazz[0]; var merged = []; var propChecked = {}; var clazzChecking = clazz; while (clazzChecking) { //find class's options var filtered = find({kind: 'member', memberof: clazzChecking.longname, name : 'options'}); if (filtered) { var properties = filtered.length ? filtered[0].properties : null; if (properties) { properties.forEach(function (prop) { //append 'options.' at the head of the property name if (prop.name.indexOf('options') < 0) { prop.name = 'options.' + prop.name; } if (!propChecked[prop.name]) { merged.push(prop); propChecked[prop.name] = 1; } }); } } //find class's parent class var parents = clazzChecking.augments ? helper.find(classes, {longname: clazzChecking.augments[0]}) : null; if (!parents || !parents.length) { break; } clazzChecking = parents[0]; } var toMerge = find({kind: 'member', memberof: clazz.longname, name : 'options'}); if (toMerge.length) { toMerge[0].properties = merged; } }
javascript
function mergeClassOptions(classes, clazz) { if (!clazz || !clazz.length) { return; } clazz = clazz[0]; var merged = []; var propChecked = {}; var clazzChecking = clazz; while (clazzChecking) { //find class's options var filtered = find({kind: 'member', memberof: clazzChecking.longname, name : 'options'}); if (filtered) { var properties = filtered.length ? filtered[0].properties : null; if (properties) { properties.forEach(function (prop) { //append 'options.' at the head of the property name if (prop.name.indexOf('options') < 0) { prop.name = 'options.' + prop.name; } if (!propChecked[prop.name]) { merged.push(prop); propChecked[prop.name] = 1; } }); } } //find class's parent class var parents = clazzChecking.augments ? helper.find(classes, {longname: clazzChecking.augments[0]}) : null; if (!parents || !parents.length) { break; } clazzChecking = parents[0]; } var toMerge = find({kind: 'member', memberof: clazz.longname, name : 'options'}); if (toMerge.length) { toMerge[0].properties = merged; } }
[ "function", "mergeClassOptions", "(", "classes", ",", "clazz", ")", "{", "if", "(", "!", "clazz", "||", "!", "clazz", ".", "length", ")", "{", "return", ";", "}", "clazz", "=", "clazz", "[", "0", "]", ";", "var", "merged", "=", "[", "]", ";", "var", "propChecked", "=", "{", "}", ";", "var", "clazzChecking", "=", "clazz", ";", "while", "(", "clazzChecking", ")", "{", "var", "filtered", "=", "find", "(", "{", "kind", ":", "'member'", ",", "memberof", ":", "clazzChecking", ".", "longname", ",", "name", ":", "'options'", "}", ")", ";", "if", "(", "filtered", ")", "{", "var", "properties", "=", "filtered", ".", "length", "?", "filtered", "[", "0", "]", ".", "properties", ":", "null", ";", "if", "(", "properties", ")", "{", "properties", ".", "forEach", "(", "function", "(", "prop", ")", "{", "if", "(", "prop", ".", "name", ".", "indexOf", "(", "'options'", ")", "<", "0", ")", "{", "prop", ".", "name", "=", "'options.'", "+", "prop", ".", "name", ";", "}", "if", "(", "!", "propChecked", "[", "prop", ".", "name", "]", ")", "{", "merged", ".", "push", "(", "prop", ")", ";", "propChecked", "[", "prop", ".", "name", "]", "=", "1", ";", "}", "}", ")", ";", "}", "}", "var", "parents", "=", "clazzChecking", ".", "augments", "?", "helper", ".", "find", "(", "classes", ",", "{", "longname", ":", "clazzChecking", ".", "augments", "[", "0", "]", "}", ")", ":", "null", ";", "if", "(", "!", "parents", "||", "!", "parents", ".", "length", ")", "{", "break", ";", "}", "clazzChecking", "=", "parents", "[", "0", "]", ";", "}", "var", "toMerge", "=", "find", "(", "{", "kind", ":", "'member'", ",", "memberof", ":", "clazz", ".", "longname", ",", "name", ":", "'options'", "}", ")", ";", "if", "(", "toMerge", ".", "length", ")", "{", "toMerge", "[", "0", "]", ".", "properties", "=", "merged", ";", "}", "}" ]
merge class's options with its parent classes recursively
[ "merge", "class", "s", "options", "with", "its", "parent", "classes", "recursively" ]
a3a6adfcaa77ee2eaeb2cbc063b1ad6545a8b5ea
https://github.com/fuzhenn/maptalks-jsdoc/blob/a3a6adfcaa77ee2eaeb2cbc063b1ad6545a8b5ea/publish.js#L740-L780
train
adrai/devicestack
lib/serial/device.js
SerialDevice
function SerialDevice(port, settings, Connection) { // call super class Device.call(this, Connection); this.set('portName', port); this.set('settings', settings); this.set('state', 'close'); }
javascript
function SerialDevice(port, settings, Connection) { // call super class Device.call(this, Connection); this.set('portName', port); this.set('settings', settings); this.set('state', 'close'); }
[ "function", "SerialDevice", "(", "port", ",", "settings", ",", "Connection", ")", "{", "Device", ".", "call", "(", "this", ",", "Connection", ")", ";", "this", ".", "set", "(", "'portName'", ",", "port", ")", ";", "this", ".", "set", "(", "'settings'", ",", "settings", ")", ";", "this", ".", "set", "(", "'state'", ",", "'close'", ")", ";", "}" ]
SerialDevice represents your physical device. Extends Device. @param {string} port The Com Port path or name for Windows. @param {Object} settings The Com Port Settings. @param {Object} Connection The constructor function of the connection.
[ "SerialDevice", "represents", "your", "physical", "device", ".", "Extends", "Device", "." ]
c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76
https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/serial/device.js#L15-L24
train
marcello3d/node-safestart
git_dependency_match.js
dependencyMatch
function dependencyMatch (expected, actual) { // expand github:user/repo#hash to git://github.com/... if (expected.indexOf('github:') === 0) { expected = expected.replace(/^github:/, 'git://github.com/') var parsed = url.parse(expected) parsed.pathname += '.git' expected = url.format(parsed) } // normalize git+https prefix actual = actual.replace(/^git\+https/, 'git') expected = expected.replace(/^git\+https/, 'git') expected = ngu(expected) actual = ngu(actual) expected.url = expected.url.replace('https://', 'git://') actual.url = actual.url.replace('https://', 'git://') if (expected.url !== actual.url) { return false } if (actual.branch && actual.branch.indexOf(expected.branch) !== 0) { return false } return true }
javascript
function dependencyMatch (expected, actual) { // expand github:user/repo#hash to git://github.com/... if (expected.indexOf('github:') === 0) { expected = expected.replace(/^github:/, 'git://github.com/') var parsed = url.parse(expected) parsed.pathname += '.git' expected = url.format(parsed) } // normalize git+https prefix actual = actual.replace(/^git\+https/, 'git') expected = expected.replace(/^git\+https/, 'git') expected = ngu(expected) actual = ngu(actual) expected.url = expected.url.replace('https://', 'git://') actual.url = actual.url.replace('https://', 'git://') if (expected.url !== actual.url) { return false } if (actual.branch && actual.branch.indexOf(expected.branch) !== 0) { return false } return true }
[ "function", "dependencyMatch", "(", "expected", ",", "actual", ")", "{", "if", "(", "expected", ".", "indexOf", "(", "'github:'", ")", "===", "0", ")", "{", "expected", "=", "expected", ".", "replace", "(", "/", "^github:", "/", ",", "'git://github.com/'", ")", "var", "parsed", "=", "url", ".", "parse", "(", "expected", ")", "parsed", ".", "pathname", "+=", "'.git'", "expected", "=", "url", ".", "format", "(", "parsed", ")", "}", "actual", "=", "actual", ".", "replace", "(", "/", "^git\\+https", "/", ",", "'git'", ")", "expected", "=", "expected", ".", "replace", "(", "/", "^git\\+https", "/", ",", "'git'", ")", "expected", "=", "ngu", "(", "expected", ")", "actual", "=", "ngu", "(", "actual", ")", "expected", ".", "url", "=", "expected", ".", "url", ".", "replace", "(", "'https://'", ",", "'git://'", ")", "actual", ".", "url", "=", "actual", ".", "url", ".", "replace", "(", "'https://'", ",", "'git://'", ")", "if", "(", "expected", ".", "url", "!==", "actual", ".", "url", ")", "{", "return", "false", "}", "if", "(", "actual", ".", "branch", "&&", "actual", ".", "branch", ".", "indexOf", "(", "expected", ".", "branch", ")", "!==", "0", ")", "{", "return", "false", "}", "return", "true", "}" ]
dependency match git urls
[ "dependency", "match", "git", "urls" ]
357b95a6ce73d0da3f65caddda633d56df11621c
https://github.com/marcello3d/node-safestart/blob/357b95a6ce73d0da3f65caddda633d56df11621c/git_dependency_match.js#L5-L33
train
switer/Zect
lib/compiler.js
_watch
function _watch(vm, vars, update) { var watchKeys = [] function _handler (kp) { if (watchKeys.some(function(key) { if (_relative(kp, key)) { return true } })) update.apply(null, arguments) } if (vars && vars.length) { vars.forEach(function (k) { if (~keywords.indexOf(k)) return while (k) { if (!~watchKeys.indexOf(k)) watchKeys.push(k) k = util.digest(k) } }) if (!watchKeys.length) return noop return vm.$watch(_handler) } return noop }
javascript
function _watch(vm, vars, update) { var watchKeys = [] function _handler (kp) { if (watchKeys.some(function(key) { if (_relative(kp, key)) { return true } })) update.apply(null, arguments) } if (vars && vars.length) { vars.forEach(function (k) { if (~keywords.indexOf(k)) return while (k) { if (!~watchKeys.indexOf(k)) watchKeys.push(k) k = util.digest(k) } }) if (!watchKeys.length) return noop return vm.$watch(_handler) } return noop }
[ "function", "_watch", "(", "vm", ",", "vars", ",", "update", ")", "{", "var", "watchKeys", "=", "[", "]", "function", "_handler", "(", "kp", ")", "{", "if", "(", "watchKeys", ".", "some", "(", "function", "(", "key", ")", "{", "if", "(", "_relative", "(", "kp", ",", "key", ")", ")", "{", "return", "true", "}", "}", ")", ")", "update", ".", "apply", "(", "null", ",", "arguments", ")", "}", "if", "(", "vars", "&&", "vars", ".", "length", ")", "{", "vars", ".", "forEach", "(", "function", "(", "k", ")", "{", "if", "(", "~", "keywords", ".", "indexOf", "(", "k", ")", ")", "return", "while", "(", "k", ")", "{", "if", "(", "!", "~", "watchKeys", ".", "indexOf", "(", "k", ")", ")", "watchKeys", ".", "push", "(", "k", ")", "k", "=", "util", ".", "digest", "(", "k", ")", "}", "}", ")", "if", "(", "!", "watchKeys", ".", "length", ")", "return", "noop", "return", "vm", ".", "$watch", "(", "_handler", ")", "}", "return", "noop", "}" ]
watch changes of variable-name of keypath @return <Function> unwatch
[ "watch", "changes", "of", "variable", "-", "name", "of", "keypath" ]
88b92d62d5000d999c3043e6379790f79608bdfa
https://github.com/switer/Zect/blob/88b92d62d5000d999c3043e6379790f79608bdfa/lib/compiler.js#L24-L46
train
seancheung/kuconfig
lib/array.js
$asce
function $asce(params) { if (Array.isArray(params) && params.every(p => typeof p === 'number')) { return params.sort((a, b) => a - b); } throw new Error('$asce expects an array of number'); }
javascript
function $asce(params) { if (Array.isArray(params) && params.every(p => typeof p === 'number')) { return params.sort((a, b) => a - b); } throw new Error('$asce expects an array of number'); }
[ "function", "$asce", "(", "params", ")", "{", "if", "(", "Array", ".", "isArray", "(", "params", ")", "&&", "params", ".", "every", "(", "p", "=>", "typeof", "p", "===", "'number'", ")", ")", "{", "return", "params", ".", "sort", "(", "(", "a", ",", "b", ")", "=>", "a", "-", "b", ")", ";", "}", "throw", "new", "Error", "(", "'$asce expects an array of number'", ")", ";", "}" ]
Sort the numbers in ascending order @param {number[]} params @returns {number[]}
[ "Sort", "the", "numbers", "in", "ascending", "order" ]
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/array.js#L7-L12
train
seancheung/kuconfig
lib/array.js
$rand
function $rand(params) { if (Array.isArray(params)) { return params[Math.floor(Math.random() * params.length)]; } throw new Error('$rand expects an array'); }
javascript
function $rand(params) { if (Array.isArray(params)) { return params[Math.floor(Math.random() * params.length)]; } throw new Error('$rand expects an array'); }
[ "function", "$rand", "(", "params", ")", "{", "if", "(", "Array", ".", "isArray", "(", "params", ")", ")", "{", "return", "params", "[", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "params", ".", "length", ")", "]", ";", "}", "throw", "new", "Error", "(", "'$rand expects an array'", ")", ";", "}" ]
Return an element at random index @param {any[]} params @returns {any}
[ "Return", "an", "element", "at", "random", "index" ]
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/array.js#L33-L38
train
seancheung/kuconfig
lib/array.js
$rands
function $rands(params) { if ( Array.isArray(params) && params.length === 2 && Array.isArray(params[0]) && typeof params[1] === 'number' ) { return Array(params[1]) .fill() .map(() => params[0].splice( Math.floor(Math.random() * params[0].length), 1 ) )[0]; } throw new Error( '$rands expects an array of two elements of which the first must be an array and the second be a number' ); }
javascript
function $rands(params) { if ( Array.isArray(params) && params.length === 2 && Array.isArray(params[0]) && typeof params[1] === 'number' ) { return Array(params[1]) .fill() .map(() => params[0].splice( Math.floor(Math.random() * params[0].length), 1 ) )[0]; } throw new Error( '$rands expects an array of two elements of which the first must be an array and the second be a number' ); }
[ "function", "$rands", "(", "params", ")", "{", "if", "(", "Array", ".", "isArray", "(", "params", ")", "&&", "params", ".", "length", "===", "2", "&&", "Array", ".", "isArray", "(", "params", "[", "0", "]", ")", "&&", "typeof", "params", "[", "1", "]", "===", "'number'", ")", "{", "return", "Array", "(", "params", "[", "1", "]", ")", ".", "fill", "(", ")", ".", "map", "(", "(", ")", "=>", "params", "[", "0", "]", ".", "splice", "(", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "params", "[", "0", "]", ".", "length", ")", ",", "1", ")", ")", "[", "0", "]", ";", "}", "throw", "new", "Error", "(", "'$rands expects an array of two elements of which the first must be an array and the second be a number'", ")", ";", "}" ]
Return the given amount of elements at random indices @param {[any[], number]} params @returns {any[]}
[ "Return", "the", "given", "amount", "of", "elements", "at", "random", "indices" ]
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/array.js#L46-L65
train
seancheung/kuconfig
lib/array.js
$slice
function $slice(params) { if ( Array.isArray(params) && (params.length === 2 || params.length === 3) && Array.isArray(params[0]) && typeof params[1] === 'number' && (params[2] === undefined || typeof params[2] === 'number') ) { return params[0].slice(params[1], params[2]); } throw new Error( '$slice expects an array of two or three elements of which the first must be an array and the second/third be a number' ); }
javascript
function $slice(params) { if ( Array.isArray(params) && (params.length === 2 || params.length === 3) && Array.isArray(params[0]) && typeof params[1] === 'number' && (params[2] === undefined || typeof params[2] === 'number') ) { return params[0].slice(params[1], params[2]); } throw new Error( '$slice expects an array of two or three elements of which the first must be an array and the second/third be a number' ); }
[ "function", "$slice", "(", "params", ")", "{", "if", "(", "Array", ".", "isArray", "(", "params", ")", "&&", "(", "params", ".", "length", "===", "2", "||", "params", ".", "length", "===", "3", ")", "&&", "Array", ".", "isArray", "(", "params", "[", "0", "]", ")", "&&", "typeof", "params", "[", "1", "]", "===", "'number'", "&&", "(", "params", "[", "2", "]", "===", "undefined", "||", "typeof", "params", "[", "2", "]", "===", "'number'", ")", ")", "{", "return", "params", "[", "0", "]", ".", "slice", "(", "params", "[", "1", "]", ",", "params", "[", "2", "]", ")", ";", "}", "throw", "new", "Error", "(", "'$slice expects an array of two or three elements of which the first must be an array and the second/third be a number'", ")", ";", "}" ]
Slice an array from the given index to an optional end index @param {[any[], number]|[any[], number, number]} params @returns {any[]}
[ "Slice", "an", "array", "from", "the", "given", "index", "to", "an", "optional", "end", "index" ]
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/array.js#L86-L99
train
amida-tech/blue-button-cms
lib/sections/vitals.js
getVitalUnits
function getVitalUnits(vitalType) { /*for height and weight, you need some kind of realistic numberical evaluator to determine the weight and height units */ if (vitalType.toLowerCase() === 'blood pressure') { return 'mm[Hg]'; } else if (vitalType.toLowerCase().indexOf('glucose') >= 0) { return 'mg/dL'; } else if (vitalType.toLowerCase().indexOf('height') >= 0) { return 'cm'; } else if (vitalType.toLowerCase().indexOf('weight') >= 0) { return 'kg'; } return null; }
javascript
function getVitalUnits(vitalType) { /*for height and weight, you need some kind of realistic numberical evaluator to determine the weight and height units */ if (vitalType.toLowerCase() === 'blood pressure') { return 'mm[Hg]'; } else if (vitalType.toLowerCase().indexOf('glucose') >= 0) { return 'mg/dL'; } else if (vitalType.toLowerCase().indexOf('height') >= 0) { return 'cm'; } else if (vitalType.toLowerCase().indexOf('weight') >= 0) { return 'kg'; } return null; }
[ "function", "getVitalUnits", "(", "vitalType", ")", "{", "if", "(", "vitalType", ".", "toLowerCase", "(", ")", "===", "'blood pressure'", ")", "{", "return", "'mm[Hg]'", ";", "}", "else", "if", "(", "vitalType", ".", "toLowerCase", "(", ")", ".", "indexOf", "(", "'glucose'", ")", ">=", "0", ")", "{", "return", "'mg/dL'", ";", "}", "else", "if", "(", "vitalType", ".", "toLowerCase", "(", ")", ".", "indexOf", "(", "'height'", ")", ">=", "0", ")", "{", "return", "'cm'", ";", "}", "else", "if", "(", "vitalType", ".", "toLowerCase", "(", ")", ".", "indexOf", "(", "'weight'", ")", ">=", "0", ")", "{", "return", "'kg'", ";", "}", "return", "null", ";", "}" ]
this needs to be a more complex function that can correctly analyze what type of units it is. Also should be given the value as well later.
[ "this", "needs", "to", "be", "a", "more", "complex", "function", "that", "can", "correctly", "analyze", "what", "type", "of", "units", "it", "is", ".", "Also", "should", "be", "given", "the", "value", "as", "well", "later", "." ]
749b8cf071910b22f8176a9ed8fc3b05062e1aad
https://github.com/amida-tech/blue-button-cms/blob/749b8cf071910b22f8176a9ed8fc3b05062e1aad/lib/sections/vitals.js#L10-L24
train
chemicstry/modular-json-rpc
dist/RPCNode.js
applyMixins
function applyMixins(derivedCtor, baseCtors) { baseCtors.forEach(baseCtor => { Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => { if (name !== 'constructor') { derivedCtor.prototype[name] = baseCtor.prototype[name]; } }); }); }
javascript
function applyMixins(derivedCtor, baseCtors) { baseCtors.forEach(baseCtor => { Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => { if (name !== 'constructor') { derivedCtor.prototype[name] = baseCtor.prototype[name]; } }); }); }
[ "function", "applyMixins", "(", "derivedCtor", ",", "baseCtors", ")", "{", "baseCtors", ".", "forEach", "(", "baseCtor", "=>", "{", "Object", ".", "getOwnPropertyNames", "(", "baseCtor", ".", "prototype", ")", ".", "forEach", "(", "name", "=>", "{", "if", "(", "name", "!==", "'constructor'", ")", "{", "derivedCtor", ".", "prototype", "[", "name", "]", "=", "baseCtor", ".", "prototype", "[", "name", "]", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Hack for multiple inheritance
[ "Hack", "for", "multiple", "inheritance" ]
7ffa945fbc3a508df39e160a0342911b2a260d8c
https://github.com/chemicstry/modular-json-rpc/blob/7ffa945fbc3a508df39e160a0342911b2a260d8c/dist/RPCNode.js#L17-L25
train
jonschlinkert/file-stat
index.js
stat
function stat(file, cb) { utils.fileExists(file); utils.fs.stat(file.path, function(err, stat) { if (err) { file.stat = null; cb(err, file); return; } file.stat = stat; cb(null, file); }); }
javascript
function stat(file, cb) { utils.fileExists(file); utils.fs.stat(file.path, function(err, stat) { if (err) { file.stat = null; cb(err, file); return; } file.stat = stat; cb(null, file); }); }
[ "function", "stat", "(", "file", ",", "cb", ")", "{", "utils", ".", "fileExists", "(", "file", ")", ";", "utils", ".", "fs", ".", "stat", "(", "file", ".", "path", ",", "function", "(", "err", ",", "stat", ")", "{", "if", "(", "err", ")", "{", "file", ".", "stat", "=", "null", ";", "cb", "(", "err", ",", "file", ")", ";", "return", ";", "}", "file", ".", "stat", "=", "stat", ";", "cb", "(", "null", ",", "file", ")", ";", "}", ")", ";", "}" ]
Asynchronously add a `stat` property from `fs.stat` to the given file object. ```js var File = require('vinyl'); var stats = require('{%= name %}'); stats.stat(new File({path: 'README.md'}), function(err, file) { console.log(file.stat.isFile()); //=> true }); ``` @name .stat @param {Object} `file` File object @param {Function} `cb` @api public
[ "Asynchronously", "add", "a", "stat", "property", "from", "fs", ".", "stat", "to", "the", "given", "file", "object", "." ]
d10c0d7cddd5af5edbbeb740fd5cf3cab4dd3688
https://github.com/jonschlinkert/file-stat/blob/d10c0d7cddd5af5edbbeb740fd5cf3cab4dd3688/index.js#L28-L39
train
jonschlinkert/file-stat
index.js
statSync
function statSync(file) { utils.fileExists(file); Object.defineProperty(file, 'stat', { configurable: true, set: function(val) { file._stat = val; }, get: function() { if (file._stat) { return file._stat; } if (this.exists) { file._stat = utils.fs.statSync(this.path); return file._stat; } return null; } }); }
javascript
function statSync(file) { utils.fileExists(file); Object.defineProperty(file, 'stat', { configurable: true, set: function(val) { file._stat = val; }, get: function() { if (file._stat) { return file._stat; } if (this.exists) { file._stat = utils.fs.statSync(this.path); return file._stat; } return null; } }); }
[ "function", "statSync", "(", "file", ")", "{", "utils", ".", "fileExists", "(", "file", ")", ";", "Object", ".", "defineProperty", "(", "file", ",", "'stat'", ",", "{", "configurable", ":", "true", ",", "set", ":", "function", "(", "val", ")", "{", "file", ".", "_stat", "=", "val", ";", "}", ",", "get", ":", "function", "(", ")", "{", "if", "(", "file", ".", "_stat", ")", "{", "return", "file", ".", "_stat", ";", "}", "if", "(", "this", ".", "exists", ")", "{", "file", ".", "_stat", "=", "utils", ".", "fs", ".", "statSync", "(", "this", ".", "path", ")", ";", "return", "file", ".", "_stat", ";", "}", "return", "null", ";", "}", "}", ")", ";", "}" ]
Synchronously add a `stat` property from `fs.stat` to the given file object. ```js var File = require('vinyl'); var stats = require('{%= name %}'); var file = new File({path: 'README.md'}); stats.statSync(file); console.log(file.stat.isFile()); //=> true ``` @name .statSync @param {Object} `file` File object @param {Function} `cb` @api public
[ "Synchronously", "add", "a", "stat", "property", "from", "fs", ".", "stat", "to", "the", "given", "file", "object", "." ]
d10c0d7cddd5af5edbbeb740fd5cf3cab4dd3688
https://github.com/jonschlinkert/file-stat/blob/d10c0d7cddd5af5edbbeb740fd5cf3cab4dd3688/index.js#L90-L108
train
jonschlinkert/file-stat
index.js
lstatSync
function lstatSync(file) { utils.fileExists(file); Object.defineProperty(file, 'lstat', { configurable: true, set: function(val) { file._lstat = val; }, get: function() { if (file._lstat) { return file._lstat; } if (this.exists) { file._lstat = utils.fs.lstatSync(this.path); return file._lstat; } return null; } }); }
javascript
function lstatSync(file) { utils.fileExists(file); Object.defineProperty(file, 'lstat', { configurable: true, set: function(val) { file._lstat = val; }, get: function() { if (file._lstat) { return file._lstat; } if (this.exists) { file._lstat = utils.fs.lstatSync(this.path); return file._lstat; } return null; } }); }
[ "function", "lstatSync", "(", "file", ")", "{", "utils", ".", "fileExists", "(", "file", ")", ";", "Object", ".", "defineProperty", "(", "file", ",", "'lstat'", ",", "{", "configurable", ":", "true", ",", "set", ":", "function", "(", "val", ")", "{", "file", ".", "_lstat", "=", "val", ";", "}", ",", "get", ":", "function", "(", ")", "{", "if", "(", "file", ".", "_lstat", ")", "{", "return", "file", ".", "_lstat", ";", "}", "if", "(", "this", ".", "exists", ")", "{", "file", ".", "_lstat", "=", "utils", ".", "fs", ".", "lstatSync", "(", "this", ".", "path", ")", ";", "return", "file", ".", "_lstat", ";", "}", "return", "null", ";", "}", "}", ")", ";", "}" ]
Synchronously add a `lstat` property from `fs.lstat` to the given file object. ```js var File = require('vinyl'); var stats = require('{%= name %}'); var file = new File({path: 'README.md'}); stats.statSync(file); console.log(file.lstat.isFile()); //=> true ``` @name .lstatSync @param {Object} `file` File object @param {Function} `cb` @api public
[ "Synchronously", "add", "a", "lstat", "property", "from", "fs", ".", "lstat", "to", "the", "given", "file", "object", "." ]
d10c0d7cddd5af5edbbeb740fd5cf3cab4dd3688
https://github.com/jonschlinkert/file-stat/blob/d10c0d7cddd5af5edbbeb740fd5cf3cab4dd3688/index.js#L127-L145
train
amida-tech/blue-button-cms
lib/cmsObjConverter.js
cleanUpModel
function cleanUpModel(bbDocumentModel) { var x; for (x in bbDocumentModel) { if (Object.keys(bbDocumentModel[x]).length === 0) { delete bbDocumentModel[x]; } } var data = bbDocumentModel.data; for (x in data) { if (Object.keys(data[x]).length === 0) { delete data[x]; } } }
javascript
function cleanUpModel(bbDocumentModel) { var x; for (x in bbDocumentModel) { if (Object.keys(bbDocumentModel[x]).length === 0) { delete bbDocumentModel[x]; } } var data = bbDocumentModel.data; for (x in data) { if (Object.keys(data[x]).length === 0) { delete data[x]; } } }
[ "function", "cleanUpModel", "(", "bbDocumentModel", ")", "{", "var", "x", ";", "for", "(", "x", "in", "bbDocumentModel", ")", "{", "if", "(", "Object", ".", "keys", "(", "bbDocumentModel", "[", "x", "]", ")", ".", "length", "===", "0", ")", "{", "delete", "bbDocumentModel", "[", "x", "]", ";", "}", "}", "var", "data", "=", "bbDocumentModel", ".", "data", ";", "for", "(", "x", "in", "data", ")", "{", "if", "(", "Object", ".", "keys", "(", "data", "[", "x", "]", ")", ".", "length", "===", "0", ")", "{", "delete", "data", "[", "x", "]", ";", "}", "}", "}" ]
Intermediate JSON is the initially converted JSON model from raw data, convert model based on
[ "Intermediate", "JSON", "is", "the", "initially", "converted", "JSON", "model", "from", "raw", "data", "convert", "model", "based", "on" ]
749b8cf071910b22f8176a9ed8fc3b05062e1aad
https://github.com/amida-tech/blue-button-cms/blob/749b8cf071910b22f8176a9ed8fc3b05062e1aad/lib/cmsObjConverter.js#L52-L65
train
crysalead-js/dom-layer
src/node/tag.js
Tag
function Tag(tagName, config, children) { this.tagName = tagName || 'div'; config = config || {}; this.children = children || []; this.props = config.props; this.attrs = config.attrs; this.attrsNS = config.attrsNS; this.events = config.events; this.hooks = config.hooks; this.data = config.data; this.params = config.params; this.element = undefined; this.parent = undefined; this.key = config.key != null ? config.key : undefined; this.namespace = config.attrs && config.attrs.xmlns || null; this.is = config.attrs && config.attrs.is || null; }
javascript
function Tag(tagName, config, children) { this.tagName = tagName || 'div'; config = config || {}; this.children = children || []; this.props = config.props; this.attrs = config.attrs; this.attrsNS = config.attrsNS; this.events = config.events; this.hooks = config.hooks; this.data = config.data; this.params = config.params; this.element = undefined; this.parent = undefined; this.key = config.key != null ? config.key : undefined; this.namespace = config.attrs && config.attrs.xmlns || null; this.is = config.attrs && config.attrs.is || null; }
[ "function", "Tag", "(", "tagName", ",", "config", ",", "children", ")", "{", "this", ".", "tagName", "=", "tagName", "||", "'div'", ";", "config", "=", "config", "||", "{", "}", ";", "this", ".", "children", "=", "children", "||", "[", "]", ";", "this", ".", "props", "=", "config", ".", "props", ";", "this", ".", "attrs", "=", "config", ".", "attrs", ";", "this", ".", "attrsNS", "=", "config", ".", "attrsNS", ";", "this", ".", "events", "=", "config", ".", "events", ";", "this", ".", "hooks", "=", "config", ".", "hooks", ";", "this", ".", "data", "=", "config", ".", "data", ";", "this", ".", "params", "=", "config", ".", "params", ";", "this", ".", "element", "=", "undefined", ";", "this", ".", "parent", "=", "undefined", ";", "this", ".", "key", "=", "config", ".", "key", "!=", "null", "?", "config", ".", "key", ":", "undefined", ";", "this", ".", "namespace", "=", "config", ".", "attrs", "&&", "config", ".", "attrs", ".", "xmlns", "||", "null", ";", "this", ".", "is", "=", "config", ".", "attrs", "&&", "config", ".", "attrs", ".", "is", "||", "null", ";", "}" ]
The Virtual Tag constructor. @param String tagName The tag name. @param Object config The virtual node definition. @param Array children An array for children.
[ "The", "Virtual", "Tag", "constructor", "." ]
0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2
https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/src/node/tag.js#L19-L37
train
crysalead-js/dom-layer
src/node/tag.js
broadcastRemove
function broadcastRemove(node) { if (node.children) { for (var i = 0, len = node.children.length; i < len; i++) { if (node.children[i]) { broadcastRemove(node.children[i]); } } } if (node.hooks && node.hooks.remove) { node.hooks.remove(node, node.element); } }
javascript
function broadcastRemove(node) { if (node.children) { for (var i = 0, len = node.children.length; i < len; i++) { if (node.children[i]) { broadcastRemove(node.children[i]); } } } if (node.hooks && node.hooks.remove) { node.hooks.remove(node, node.element); } }
[ "function", "broadcastRemove", "(", "node", ")", "{", "if", "(", "node", ".", "children", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "node", ".", "children", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "node", ".", "children", "[", "i", "]", ")", "{", "broadcastRemove", "(", "node", ".", "children", "[", "i", "]", ")", ";", "}", "}", "}", "if", "(", "node", ".", "hooks", "&&", "node", ".", "hooks", ".", "remove", ")", "{", "node", ".", "hooks", ".", "remove", "(", "node", ",", "node", ".", "element", ")", ";", "}", "}" ]
Broadcasts the remove 'event'.
[ "Broadcasts", "the", "remove", "event", "." ]
0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2
https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/src/node/tag.js#L248-L259
train
seancheung/kuconfig
lib/string.js
$split
function $split(params) { if (typeof params === 'string') { return params.split(/\s+/); } if ( Array.isArray(params) && (params.length === 2 || params.length === 3) && typeof params[0] === 'string' && typeof params[1] === 'string' && (params[3] == null || typeof params[3] === 'number') ) { return params[0].split(params[1], params[2]); } throw new Error( '$split expects an array of two string elements with an additional number element' ); }
javascript
function $split(params) { if (typeof params === 'string') { return params.split(/\s+/); } if ( Array.isArray(params) && (params.length === 2 || params.length === 3) && typeof params[0] === 'string' && typeof params[1] === 'string' && (params[3] == null || typeof params[3] === 'number') ) { return params[0].split(params[1], params[2]); } throw new Error( '$split expects an array of two string elements with an additional number element' ); }
[ "function", "$split", "(", "params", ")", "{", "if", "(", "typeof", "params", "===", "'string'", ")", "{", "return", "params", ".", "split", "(", "/", "\\s+", "/", ")", ";", "}", "if", "(", "Array", ".", "isArray", "(", "params", ")", "&&", "(", "params", ".", "length", "===", "2", "||", "params", ".", "length", "===", "3", ")", "&&", "typeof", "params", "[", "0", "]", "===", "'string'", "&&", "typeof", "params", "[", "1", "]", "===", "'string'", "&&", "(", "params", "[", "3", "]", "==", "null", "||", "typeof", "params", "[", "3", "]", "===", "'number'", ")", ")", "{", "return", "params", "[", "0", "]", ".", "split", "(", "params", "[", "1", "]", ",", "params", "[", "2", "]", ")", ";", "}", "throw", "new", "Error", "(", "'$split expects an array of two string elements with an additional number element'", ")", ";", "}" ]
Split input string into an array @param {string|[string, string]|[string, string, number]} params @returns {number[]}
[ "Split", "input", "string", "into", "an", "array" ]
eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead
https://github.com/seancheung/kuconfig/blob/eb0de1920c8fcc7b9a28dceceadc87ecaa5a2ead/lib/string.js#L39-L55
train
davidfig/rendersheet
docs/code.js
triangleDraw
function triangleDraw(c, params) { const size = params.size const half = params.size / 2 c.beginPath() c.fillStyle = '#' + params.color.toString(16) c.moveTo(half, 0) c.lineTo(0, size) c.lineTo(size, size) c.closePath() c.fill() c.fillStyle = 'white' c.font = '40px Arial' const measure = c.measureText(n) c.fillText(n++, size / 2 - measure.width / 2, size / 2 + 10) }
javascript
function triangleDraw(c, params) { const size = params.size const half = params.size / 2 c.beginPath() c.fillStyle = '#' + params.color.toString(16) c.moveTo(half, 0) c.lineTo(0, size) c.lineTo(size, size) c.closePath() c.fill() c.fillStyle = 'white' c.font = '40px Arial' const measure = c.measureText(n) c.fillText(n++, size / 2 - measure.width / 2, size / 2 + 10) }
[ "function", "triangleDraw", "(", "c", ",", "params", ")", "{", "const", "size", "=", "params", ".", "size", "const", "half", "=", "params", ".", "size", "/", "2", "c", ".", "beginPath", "(", ")", "c", ".", "fillStyle", "=", "'#'", "+", "params", ".", "color", ".", "toString", "(", "16", ")", "c", ".", "moveTo", "(", "half", ",", "0", ")", "c", ".", "lineTo", "(", "0", ",", "size", ")", "c", ".", "lineTo", "(", "size", ",", "size", ")", "c", ".", "closePath", "(", ")", "c", ".", "fill", "(", ")", "c", ".", "fillStyle", "=", "'white'", "c", ".", "font", "=", "'40px Arial'", "const", "measure", "=", "c", ".", "measureText", "(", "n", ")", "c", ".", "fillText", "(", "n", "++", ",", "size", "/", "2", "-", "measure", ".", "width", "/", "2", ",", "size", "/", "2", "+", "10", ")", "}" ]
draw a triangle to the render sheet using canvas
[ "draw", "a", "triangle", "to", "the", "render", "sheet", "using", "canvas" ]
a5b42d1dfece524d36186b308b8aefbd31921bb3
https://github.com/davidfig/rendersheet/blob/a5b42d1dfece524d36186b308b8aefbd31921bb3/docs/code.js#L85-L100
train
vfile/vfile-find-down
index.js
visit
function visit(state, filePath, one, done) { var file // Don’t walk into places multiple times. if (own.call(state.checked, filePath)) { done([]) return } state.checked[filePath] = true file = vfile(filePath) stat(resolve(filePath), onstat) function onstat(error, stats) { var real = Boolean(stats) var results = [] var result if (state.broken || !real) { done([]) } else { result = state.test(file, stats) if (mask(result, INCLUDE)) { results.push(file) if (one) { state.broken = true return done(results) } } if (mask(result, BREAK)) { state.broken = true } if (state.broken || !stats.isDirectory() || mask(result, SKIP)) { return done(results) } readdir(filePath, onread) } function onread(error, entries) { visitAll(state, entries, filePath, one, onvisit) } function onvisit(files) { done(results.concat(files)) } } }
javascript
function visit(state, filePath, one, done) { var file // Don’t walk into places multiple times. if (own.call(state.checked, filePath)) { done([]) return } state.checked[filePath] = true file = vfile(filePath) stat(resolve(filePath), onstat) function onstat(error, stats) { var real = Boolean(stats) var results = [] var result if (state.broken || !real) { done([]) } else { result = state.test(file, stats) if (mask(result, INCLUDE)) { results.push(file) if (one) { state.broken = true return done(results) } } if (mask(result, BREAK)) { state.broken = true } if (state.broken || !stats.isDirectory() || mask(result, SKIP)) { return done(results) } readdir(filePath, onread) } function onread(error, entries) { visitAll(state, entries, filePath, one, onvisit) } function onvisit(files) { done(results.concat(files)) } } }
[ "function", "visit", "(", "state", ",", "filePath", ",", "one", ",", "done", ")", "{", "var", "file", "if", "(", "own", ".", "call", "(", "state", ".", "checked", ",", "filePath", ")", ")", "{", "done", "(", "[", "]", ")", "return", "}", "state", ".", "checked", "[", "filePath", "]", "=", "true", "file", "=", "vfile", "(", "filePath", ")", "stat", "(", "resolve", "(", "filePath", ")", ",", "onstat", ")", "function", "onstat", "(", "error", ",", "stats", ")", "{", "var", "real", "=", "Boolean", "(", "stats", ")", "var", "results", "=", "[", "]", "var", "result", "if", "(", "state", ".", "broken", "||", "!", "real", ")", "{", "done", "(", "[", "]", ")", "}", "else", "{", "result", "=", "state", ".", "test", "(", "file", ",", "stats", ")", "if", "(", "mask", "(", "result", ",", "INCLUDE", ")", ")", "{", "results", ".", "push", "(", "file", ")", "if", "(", "one", ")", "{", "state", ".", "broken", "=", "true", "return", "done", "(", "results", ")", "}", "}", "if", "(", "mask", "(", "result", ",", "BREAK", ")", ")", "{", "state", ".", "broken", "=", "true", "}", "if", "(", "state", ".", "broken", "||", "!", "stats", ".", "isDirectory", "(", ")", "||", "mask", "(", "result", ",", "SKIP", ")", ")", "{", "return", "done", "(", "results", ")", "}", "readdir", "(", "filePath", ",", "onread", ")", "}", "function", "onread", "(", "error", ",", "entries", ")", "{", "visitAll", "(", "state", ",", "entries", ",", "filePath", ",", "one", ",", "onvisit", ")", "}", "function", "onvisit", "(", "files", ")", "{", "done", "(", "results", ".", "concat", "(", "files", ")", ")", "}", "}", "}" ]
Find files in `filePath`.
[ "Find", "files", "in", "filePath", "." ]
0c589eebc1d52d40fcf833c8a3f5fae55c068c84
https://github.com/vfile/vfile-find-down/blob/0c589eebc1d52d40fcf833c8a3f5fae55c068c84/index.js#L58-L111
train
vfile/vfile-find-down
index.js
visitAll
function visitAll(state, paths, cwd, one, done) { var expected = paths.length var actual = -1 var result = [] paths.forEach(each) next() function each(filePath) { visit(state, join(cwd || '', filePath), one, onvisit) } function onvisit(files) { result = result.concat(files) next() } function next() { actual++ if (actual === expected) { done(result) } } }
javascript
function visitAll(state, paths, cwd, one, done) { var expected = paths.length var actual = -1 var result = [] paths.forEach(each) next() function each(filePath) { visit(state, join(cwd || '', filePath), one, onvisit) } function onvisit(files) { result = result.concat(files) next() } function next() { actual++ if (actual === expected) { done(result) } } }
[ "function", "visitAll", "(", "state", ",", "paths", ",", "cwd", ",", "one", ",", "done", ")", "{", "var", "expected", "=", "paths", ".", "length", "var", "actual", "=", "-", "1", "var", "result", "=", "[", "]", "paths", ".", "forEach", "(", "each", ")", "next", "(", ")", "function", "each", "(", "filePath", ")", "{", "visit", "(", "state", ",", "join", "(", "cwd", "||", "''", ",", "filePath", ")", ",", "one", ",", "onvisit", ")", "}", "function", "onvisit", "(", "files", ")", "{", "result", "=", "result", ".", "concat", "(", "files", ")", "next", "(", ")", "}", "function", "next", "(", ")", "{", "actual", "++", "if", "(", "actual", "===", "expected", ")", "{", "done", "(", "result", ")", "}", "}", "}" ]
Find files in `paths`. Returns a list of applicable files.
[ "Find", "files", "in", "paths", ".", "Returns", "a", "list", "of", "applicable", "files", "." ]
0c589eebc1d52d40fcf833c8a3f5fae55c068c84
https://github.com/vfile/vfile-find-down/blob/0c589eebc1d52d40fcf833c8a3f5fae55c068c84/index.js#L114-L139
train
littlstar/stardux
src/index.js
isArrayLike
function isArrayLike (a) { if ('object' != typeof a) return false else if (null == a) return false else return Boolean( Array.isArray(a) || null != a.length || a[0] ) }
javascript
function isArrayLike (a) { if ('object' != typeof a) return false else if (null == a) return false else return Boolean( Array.isArray(a) || null != a.length || a[0] ) }
[ "function", "isArrayLike", "(", "a", ")", "{", "if", "(", "'object'", "!=", "typeof", "a", ")", "return", "false", "else", "if", "(", "null", "==", "a", ")", "return", "false", "else", "return", "Boolean", "(", "Array", ".", "isArray", "(", "a", ")", "||", "null", "!=", "a", ".", "length", "||", "a", "[", "0", "]", ")", "}" ]
Detects if input is "like" an array. @private @param {Mixed} a @return {Boolean}
[ "Detects", "if", "input", "is", "like", "an", "array", "." ]
88c4bd05e2c2755636590927e102e1303acb0038
https://github.com/littlstar/stardux/blob/88c4bd05e2c2755636590927e102e1303acb0038/src/index.js#L79-L88
train
littlstar/stardux
src/index.js
mkdux
function mkdux (node, data = {}) { if (node instanceof Container) node = node.domElement node[STARDUX_PRIVATE_ATTR] = ( node[STARDUX_PRIVATE_ATTR] || data ) return node[STARDUX_PRIVATE_ATTR] }
javascript
function mkdux (node, data = {}) { if (node instanceof Container) node = node.domElement node[STARDUX_PRIVATE_ATTR] = ( node[STARDUX_PRIVATE_ATTR] || data ) return node[STARDUX_PRIVATE_ATTR] }
[ "function", "mkdux", "(", "node", ",", "data", "=", "{", "}", ")", "{", "if", "(", "node", "instanceof", "Container", ")", "node", "=", "node", ".", "domElement", "node", "[", "STARDUX_PRIVATE_ATTR", "]", "=", "(", "node", "[", "STARDUX_PRIVATE_ATTR", "]", "||", "data", ")", "return", "node", "[", "STARDUX_PRIVATE_ATTR", "]", "}" ]
Make stardux data object on a node if not already there. @private @param {Object} node @param {Object} [data = {}] @return {Object}
[ "Make", "stardux", "data", "object", "on", "a", "node", "if", "not", "already", "there", "." ]
88c4bd05e2c2755636590927e102e1303acb0038
https://github.com/littlstar/stardux/blob/88c4bd05e2c2755636590927e102e1303acb0038/src/index.js#L100-L105
train
littlstar/stardux
src/index.js
rmdux
function rmdux (node) { if (null == node) return if (node instanceof Container) node = node.domElement delete node[STARDUX_PRIVATE_ATTR] }
javascript
function rmdux (node) { if (null == node) return if (node instanceof Container) node = node.domElement delete node[STARDUX_PRIVATE_ATTR] }
[ "function", "rmdux", "(", "node", ")", "{", "if", "(", "null", "==", "node", ")", "return", "if", "(", "node", "instanceof", "Container", ")", "node", "=", "node", ".", "domElement", "delete", "node", "[", "STARDUX_PRIVATE_ATTR", "]", "}" ]
Remove stardux data object. @private @param {Object} node
[ "Remove", "stardux", "data", "object", "." ]
88c4bd05e2c2755636590927e102e1303acb0038
https://github.com/littlstar/stardux/blob/88c4bd05e2c2755636590927e102e1303acb0038/src/index.js#L114-L119
train
littlstar/stardux
src/index.js
getTokens
function getTokens (string) { let tokens = null try { tokens = esprima.tokenize('`'+ string +'`') } catch (e) { tokens = [] } return tokens }
javascript
function getTokens (string) { let tokens = null try { tokens = esprima.tokenize('`'+ string +'`') } catch (e) { tokens = [] } return tokens }
[ "function", "getTokens", "(", "string", ")", "{", "let", "tokens", "=", "null", "try", "{", "tokens", "=", "esprima", ".", "tokenize", "(", "'`'", "+", "string", "+", "'`'", ")", "}", "catch", "(", "e", ")", "{", "tokens", "=", "[", "]", "}", "return", "tokens", "}" ]
Returns an array of known tokens in a javascript string. @private @param {String} string @return {Array}
[ "Returns", "an", "array", "of", "known", "tokens", "in", "a", "javascript", "string", "." ]
88c4bd05e2c2755636590927e102e1303acb0038
https://github.com/littlstar/stardux/blob/88c4bd05e2c2755636590927e102e1303acb0038/src/index.js#L130-L135
train
littlstar/stardux
src/index.js
getIdentifiersFromTokens
function getIdentifiersFromTokens (tokens) { const identifiers = {} /** * Predicate to determine if token is an identifier. * * @private * @param {Object} token * @return {Boolean} */ const isIdentifier = token => 'Identifier' == token.type /** * Mark token as a function identifier. * * @private * @param {Object} token * @param {Number} index * @return {Object} token */ const markFunction = (token, index) => { const next = tokens[index + 1] || null token.isFunction = ( 'Identifier' == token.type && 'object' == typeof next && next && 'Punctuator' == next.type && '(' == next.value ? true : false ) return token } /** * Mark token as a object identifier. * * @private * @param {Object} token * @param {Number} index * @return {Object} token */ const markObject = (token, index) => { const next = tokens[index + 1] || null token.isObject = ( 'Identifier' == token.type && 'object' == typeof next && next && 'Punctuator' == next.type && '.' == next.value ? true : false ) return token } /** * Assign token value to identifierss map. * * @private * @param {Object} map * @param {Object} token * @return {Object} map */ const assign = (map, token) => { const value = token.value if (token.isFunction) map[value] = _ => '' else if (token.isObject) map[value] = {} else map[value] = '' return map } // resolve identifierss and return map return ( tokens .map((t, i) => markFunction(t, i)) .map((t, i) => markObject(t, i)) .filter(t => isIdentifier(t)) .reduce((map, t) => assign(map, t), identifiers) ) }
javascript
function getIdentifiersFromTokens (tokens) { const identifiers = {} /** * Predicate to determine if token is an identifier. * * @private * @param {Object} token * @return {Boolean} */ const isIdentifier = token => 'Identifier' == token.type /** * Mark token as a function identifier. * * @private * @param {Object} token * @param {Number} index * @return {Object} token */ const markFunction = (token, index) => { const next = tokens[index + 1] || null token.isFunction = ( 'Identifier' == token.type && 'object' == typeof next && next && 'Punctuator' == next.type && '(' == next.value ? true : false ) return token } /** * Mark token as a object identifier. * * @private * @param {Object} token * @param {Number} index * @return {Object} token */ const markObject = (token, index) => { const next = tokens[index + 1] || null token.isObject = ( 'Identifier' == token.type && 'object' == typeof next && next && 'Punctuator' == next.type && '.' == next.value ? true : false ) return token } /** * Assign token value to identifierss map. * * @private * @param {Object} map * @param {Object} token * @return {Object} map */ const assign = (map, token) => { const value = token.value if (token.isFunction) map[value] = _ => '' else if (token.isObject) map[value] = {} else map[value] = '' return map } // resolve identifierss and return map return ( tokens .map((t, i) => markFunction(t, i)) .map((t, i) => markObject(t, i)) .filter(t => isIdentifier(t)) .reduce((map, t) => assign(map, t), identifiers) ) }
[ "function", "getIdentifiersFromTokens", "(", "tokens", ")", "{", "const", "identifiers", "=", "{", "}", "const", "isIdentifier", "=", "token", "=>", "'Identifier'", "==", "token", ".", "type", "const", "markFunction", "=", "(", "token", ",", "index", ")", "=>", "{", "const", "next", "=", "tokens", "[", "index", "+", "1", "]", "||", "null", "token", ".", "isFunction", "=", "(", "'Identifier'", "==", "token", ".", "type", "&&", "'object'", "==", "typeof", "next", "&&", "next", "&&", "'Punctuator'", "==", "next", ".", "type", "&&", "'('", "==", "next", ".", "value", "?", "true", ":", "false", ")", "return", "token", "}", "const", "markObject", "=", "(", "token", ",", "index", ")", "=>", "{", "const", "next", "=", "tokens", "[", "index", "+", "1", "]", "||", "null", "token", ".", "isObject", "=", "(", "'Identifier'", "==", "token", ".", "type", "&&", "'object'", "==", "typeof", "next", "&&", "next", "&&", "'Punctuator'", "==", "next", ".", "type", "&&", "'.'", "==", "next", ".", "value", "?", "true", ":", "false", ")", "return", "token", "}", "const", "assign", "=", "(", "map", ",", "token", ")", "=>", "{", "const", "value", "=", "token", ".", "value", "if", "(", "token", ".", "isFunction", ")", "map", "[", "value", "]", "=", "_", "=>", "''", "else", "if", "(", "token", ".", "isObject", ")", "map", "[", "value", "]", "=", "{", "}", "else", "map", "[", "value", "]", "=", "''", "return", "map", "}", "return", "(", "tokens", ".", "map", "(", "(", "t", ",", "i", ")", "=>", "markFunction", "(", "t", ",", "i", ")", ")", ".", "map", "(", "(", "t", ",", "i", ")", "=>", "markObject", "(", "t", ",", "i", ")", ")", ".", "filter", "(", "t", "=>", "isIdentifier", "(", "t", ")", ")", ".", "reduce", "(", "(", "map", ",", "t", ")", "=>", "assign", "(", "map", ",", "t", ")", ",", "identifiers", ")", ")", "}" ]
Returns an object of identifiers with empty string or NO-OP function values. @private @param {Array} tokens @return {Object}
[ "Returns", "an", "object", "of", "identifiers", "with", "empty", "string", "or", "NO", "-", "OP", "function", "values", "." ]
88c4bd05e2c2755636590927e102e1303acb0038
https://github.com/littlstar/stardux/blob/88c4bd05e2c2755636590927e102e1303acb0038/src/index.js#L147-L224
train
littlstar/stardux
src/index.js
ensureDOMElement
function ensureDOMElement (input) { let domElement = null let tmp = null if (input instanceof Element) { return input } else if ('string' == typeof input) { tmp = document.createElement('div') tmp.innerHTML = input domElement = tmp.innerHTML.length ? tmp.children[0] : new Template(input) } else { domElement = document.createElement('div') } return domElement }
javascript
function ensureDOMElement (input) { let domElement = null let tmp = null if (input instanceof Element) { return input } else if ('string' == typeof input) { tmp = document.createElement('div') tmp.innerHTML = input domElement = tmp.innerHTML.length ? tmp.children[0] : new Template(input) } else { domElement = document.createElement('div') } return domElement }
[ "function", "ensureDOMElement", "(", "input", ")", "{", "let", "domElement", "=", "null", "let", "tmp", "=", "null", "if", "(", "input", "instanceof", "Element", ")", "{", "return", "input", "}", "else", "if", "(", "'string'", "==", "typeof", "input", ")", "{", "tmp", "=", "document", ".", "createElement", "(", "'div'", ")", "tmp", ".", "innerHTML", "=", "input", "domElement", "=", "tmp", ".", "innerHTML", ".", "length", "?", "tmp", ".", "children", "[", "0", "]", ":", "new", "Template", "(", "input", ")", "}", "else", "{", "domElement", "=", "document", ".", "createElement", "(", "'div'", ")", "}", "return", "domElement", "}" ]
Ensure DOM element. @private @param {Mixed} input @return {Element}
[ "Ensure", "DOM", "element", "." ]
88c4bd05e2c2755636590927e102e1303acb0038
https://github.com/littlstar/stardux/blob/88c4bd05e2c2755636590927e102e1303acb0038/src/index.js#L247-L260
train
littlstar/stardux
src/index.js
getTemplateFromDomElement
function getTemplateFromDomElement (domElement) { let data = {} let src = null if (domElement && domElement[STARDUX_PRIVATE_ATTR]) data = mkdux(domElement) if ('string' == typeof domElement) src = domElement else if (data.src) src = data.src else if (domElement.children && 0 == domElement.children.length) src = ensureDOMString(domElement.textContent) else if (domElement.firstChild instanceof Text) src = ensureDOMString(domElement.innerHTML) else if (domElement instanceof Text) src = ensureDOMString(domElement.textContent) else if (domElement) src = domElement.innerHTML || domElement.textContent return src }
javascript
function getTemplateFromDomElement (domElement) { let data = {} let src = null if (domElement && domElement[STARDUX_PRIVATE_ATTR]) data = mkdux(domElement) if ('string' == typeof domElement) src = domElement else if (data.src) src = data.src else if (domElement.children && 0 == domElement.children.length) src = ensureDOMString(domElement.textContent) else if (domElement.firstChild instanceof Text) src = ensureDOMString(domElement.innerHTML) else if (domElement instanceof Text) src = ensureDOMString(domElement.textContent) else if (domElement) src = domElement.innerHTML || domElement.textContent return src }
[ "function", "getTemplateFromDomElement", "(", "domElement", ")", "{", "let", "data", "=", "{", "}", "let", "src", "=", "null", "if", "(", "domElement", "&&", "domElement", "[", "STARDUX_PRIVATE_ATTR", "]", ")", "data", "=", "mkdux", "(", "domElement", ")", "if", "(", "'string'", "==", "typeof", "domElement", ")", "src", "=", "domElement", "else", "if", "(", "data", ".", "src", ")", "src", "=", "data", ".", "src", "else", "if", "(", "domElement", ".", "children", "&&", "0", "==", "domElement", ".", "children", ".", "length", ")", "src", "=", "ensureDOMString", "(", "domElement", ".", "textContent", ")", "else", "if", "(", "domElement", ".", "firstChild", "instanceof", "Text", ")", "src", "=", "ensureDOMString", "(", "domElement", ".", "innerHTML", ")", "else", "if", "(", "domElement", "instanceof", "Text", ")", "src", "=", "ensureDOMString", "(", "domElement", ".", "textContent", ")", "else", "if", "(", "domElement", ")", "src", "=", "domElement", ".", "innerHTML", "||", "domElement", ".", "textContent", "return", "src", "}" ]
Returns a template tring from a given DOM Element. If the DOM Element given is a string then it is simply returned. @public @param {Element|String} domElement @return {String}
[ "Returns", "a", "template", "tring", "from", "a", "given", "DOM", "Element", ".", "If", "the", "DOM", "Element", "given", "is", "a", "string", "then", "it", "is", "simply", "returned", "." ]
88c4bd05e2c2755636590927e102e1303acb0038
https://github.com/littlstar/stardux/blob/88c4bd05e2c2755636590927e102e1303acb0038/src/index.js#L272-L293
train
littlstar/stardux
src/index.js
createRootReducer
function createRootReducer (container, ...reducers) { return (state = {}, action = {}) => { const identifiers = ensureContainerStateIdentifiers(container) const domElement = container[$domElement] const template = getTemplateFromDomElement(domElement) const middleware = container[$middleware].entries() const isBody = domElement == document.body if (action.data) { state = extend(state, action.data) } /** * Loops over each pipe function * providing state and action values * given to use from redux. * * @private */ const reducerSet = new Set([ ...reducers ]) const reducerEntires = reducerSet.entries() reduce() function reduce () { const step = reducerEntires.next() const done = step.done const reducer = step.value ? step.value[1] : null if (done) return const newState = reducer(state, action) if (null != newState) state = newState reduce() } if ($UPDATE_ACTION == action.type) { /** * Loops over each middleware function * providing state and action values * given to use from redux. * * @private */ void function next () { const step = middleware.next() const done = step.done const reducer = step.value ? step.value[0] : null if (done) return else if (null == reducer) next() else if (false === reducer(state, action)) return else next() }() container.define(state) if (!isBody && identifiers) { const parser = new Parser() const partial = new Template(template) const src = partial.render(container.state, container) const patch = parser.createPatch(src) patch(domElement) } } return state } }
javascript
function createRootReducer (container, ...reducers) { return (state = {}, action = {}) => { const identifiers = ensureContainerStateIdentifiers(container) const domElement = container[$domElement] const template = getTemplateFromDomElement(domElement) const middleware = container[$middleware].entries() const isBody = domElement == document.body if (action.data) { state = extend(state, action.data) } /** * Loops over each pipe function * providing state and action values * given to use from redux. * * @private */ const reducerSet = new Set([ ...reducers ]) const reducerEntires = reducerSet.entries() reduce() function reduce () { const step = reducerEntires.next() const done = step.done const reducer = step.value ? step.value[1] : null if (done) return const newState = reducer(state, action) if (null != newState) state = newState reduce() } if ($UPDATE_ACTION == action.type) { /** * Loops over each middleware function * providing state and action values * given to use from redux. * * @private */ void function next () { const step = middleware.next() const done = step.done const reducer = step.value ? step.value[0] : null if (done) return else if (null == reducer) next() else if (false === reducer(state, action)) return else next() }() container.define(state) if (!isBody && identifiers) { const parser = new Parser() const partial = new Template(template) const src = partial.render(container.state, container) const patch = parser.createPatch(src) patch(domElement) } } return state } }
[ "function", "createRootReducer", "(", "container", ",", "...", "reducers", ")", "{", "return", "(", "state", "=", "{", "}", ",", "action", "=", "{", "}", ")", "=>", "{", "const", "identifiers", "=", "ensureContainerStateIdentifiers", "(", "container", ")", "const", "domElement", "=", "container", "[", "$domElement", "]", "const", "template", "=", "getTemplateFromDomElement", "(", "domElement", ")", "const", "middleware", "=", "container", "[", "$middleware", "]", ".", "entries", "(", ")", "const", "isBody", "=", "domElement", "==", "document", ".", "body", "if", "(", "action", ".", "data", ")", "{", "state", "=", "extend", "(", "state", ",", "action", ".", "data", ")", "}", "const", "reducerSet", "=", "new", "Set", "(", "[", "...", "reducers", "]", ")", "const", "reducerEntires", "=", "reducerSet", ".", "entries", "(", ")", "reduce", "(", ")", "function", "reduce", "(", ")", "{", "const", "step", "=", "reducerEntires", ".", "next", "(", ")", "const", "done", "=", "step", ".", "done", "const", "reducer", "=", "step", ".", "value", "?", "step", ".", "value", "[", "1", "]", ":", "null", "if", "(", "done", ")", "return", "const", "newState", "=", "reducer", "(", "state", ",", "action", ")", "if", "(", "null", "!=", "newState", ")", "state", "=", "newState", "reduce", "(", ")", "}", "if", "(", "$UPDATE_ACTION", "==", "action", ".", "type", ")", "{", "void", "function", "next", "(", ")", "{", "const", "step", "=", "middleware", ".", "next", "(", ")", "const", "done", "=", "step", ".", "done", "const", "reducer", "=", "step", ".", "value", "?", "step", ".", "value", "[", "0", "]", ":", "null", "if", "(", "done", ")", "return", "else", "if", "(", "null", "==", "reducer", ")", "next", "(", ")", "else", "if", "(", "false", "===", "reducer", "(", "state", ",", "action", ")", ")", "return", "else", "next", "(", ")", "}", "(", ")", "container", ".", "define", "(", "state", ")", "if", "(", "!", "isBody", "&&", "identifiers", ")", "{", "const", "parser", "=", "new", "Parser", "(", ")", "const", "partial", "=", "new", "Template", "(", "template", ")", "const", "src", "=", "partial", ".", "render", "(", "container", ".", "state", ",", "container", ")", "const", "patch", "=", "parser", ".", "createPatch", "(", "src", ")", "patch", "(", "domElement", ")", "}", "}", "return", "state", "}", "}" ]
Creates a root reducer for a Container instance. @private @param {Container} container @return {Function}
[ "Creates", "a", "root", "reducer", "for", "a", "Container", "instance", "." ]
88c4bd05e2c2755636590927e102e1303acb0038
https://github.com/littlstar/stardux/blob/88c4bd05e2c2755636590927e102e1303acb0038/src/index.js#L334-L401
train
littlstar/stardux
src/index.js
createPipeReducer
function createPipeReducer (container) { return (state, action = {data: {}}) => { const pipes = container[$pipes].entries() reduce() return state /** * Loops over each pipe function * providing state and action values * given to use from redux. * * @private */ function reduce () { const step = pipes.next() const done = step.done const pipe = step.value ? step.value[1] : null if (done) return else if (false === pipe(state, action)) return else return reduce() } } }
javascript
function createPipeReducer (container) { return (state, action = {data: {}}) => { const pipes = container[$pipes].entries() reduce() return state /** * Loops over each pipe function * providing state and action values * given to use from redux. * * @private */ function reduce () { const step = pipes.next() const done = step.done const pipe = step.value ? step.value[1] : null if (done) return else if (false === pipe(state, action)) return else return reduce() } } }
[ "function", "createPipeReducer", "(", "container", ")", "{", "return", "(", "state", ",", "action", "=", "{", "data", ":", "{", "}", "}", ")", "=>", "{", "const", "pipes", "=", "container", "[", "$pipes", "]", ".", "entries", "(", ")", "reduce", "(", ")", "return", "state", "function", "reduce", "(", ")", "{", "const", "step", "=", "pipes", ".", "next", "(", ")", "const", "done", "=", "step", ".", "done", "const", "pipe", "=", "step", ".", "value", "?", "step", ".", "value", "[", "1", "]", ":", "null", "if", "(", "done", ")", "return", "else", "if", "(", "false", "===", "pipe", "(", "state", ",", "action", ")", ")", "return", "else", "return", "reduce", "(", ")", "}", "}", "}" ]
Creates a pipe reducer for a Container instance. @private @param {Container} container @return {Function}
[ "Creates", "a", "pipe", "reducer", "for", "a", "Container", "instance", "." ]
88c4bd05e2c2755636590927e102e1303acb0038
https://github.com/littlstar/stardux/blob/88c4bd05e2c2755636590927e102e1303acb0038/src/index.js#L412-L435
train
littlstar/stardux
src/index.js
reduce
function reduce () { const step = pipes.next() const done = step.done const pipe = step.value ? step.value[1] : null if (done) return else if (false === pipe(state, action)) return else return reduce() }
javascript
function reduce () { const step = pipes.next() const done = step.done const pipe = step.value ? step.value[1] : null if (done) return else if (false === pipe(state, action)) return else return reduce() }
[ "function", "reduce", "(", ")", "{", "const", "step", "=", "pipes", ".", "next", "(", ")", "const", "done", "=", "step", ".", "done", "const", "pipe", "=", "step", ".", "value", "?", "step", ".", "value", "[", "1", "]", ":", "null", "if", "(", "done", ")", "return", "else", "if", "(", "false", "===", "pipe", "(", "state", ",", "action", ")", ")", "return", "else", "return", "reduce", "(", ")", "}" ]
Loops over each pipe function providing state and action values given to use from redux. @private
[ "Loops", "over", "each", "pipe", "function", "providing", "state", "and", "action", "values", "given", "to", "use", "from", "redux", "." ]
88c4bd05e2c2755636590927e102e1303acb0038
https://github.com/littlstar/stardux/blob/88c4bd05e2c2755636590927e102e1303acb0038/src/index.js#L426-L433
train
littlstar/stardux
src/index.js
orphanContainerChildren
function orphanContainerChildren (container, rouge = false) { container = fetchContainer(container) const children = container.children if (null == container) throw new TypeError( "orphanContainerChildren() Expecting a container " ) for (let child of children) { container.removeChild(child) if (true === rouge) { orphanContainerChildren(child, true) CONTAINERS.delete(child.id) } } }
javascript
function orphanContainerChildren (container, rouge = false) { container = fetchContainer(container) const children = container.children if (null == container) throw new TypeError( "orphanContainerChildren() Expecting a container " ) for (let child of children) { container.removeChild(child) if (true === rouge) { orphanContainerChildren(child, true) CONTAINERS.delete(child.id) } } }
[ "function", "orphanContainerChildren", "(", "container", ",", "rouge", "=", "false", ")", "{", "container", "=", "fetchContainer", "(", "container", ")", "const", "children", "=", "container", ".", "children", "if", "(", "null", "==", "container", ")", "throw", "new", "TypeError", "(", "\"orphanContainerChildren() Expecting a container \"", ")", "for", "(", "let", "child", "of", "children", ")", "{", "container", ".", "removeChild", "(", "child", ")", "if", "(", "true", "===", "rouge", ")", "{", "orphanContainerChildren", "(", "child", ",", "true", ")", "CONTAINERS", ".", "delete", "(", "child", ".", "id", ")", "}", "}", "}" ]
Orphan container. @private @param {Container} container @param {Boolean} [rouge]
[ "Orphan", "container", "." ]
88c4bd05e2c2755636590927e102e1303acb0038
https://github.com/littlstar/stardux/blob/88c4bd05e2c2755636590927e102e1303acb0038/src/index.js#L445-L460
train