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
hash-bang/compare-names
index.js
compareNames
function compareNames(a, b) { if (!isArray(a)) a = splitAuthorString(a); if (!isArray(b)) b = splitAuthorString(b); var aPos = 0, bPos = 0; var authorLimit = Math.min(a.length, b.length); var failed = false; while (aPos < authorLimit && bPos < authorLimit) { if (fuzzyStringCompare(a[aPos], b[bPos])) { // Direct or fuzzy matching of entire strings aPos++; bPos++; } else { var aAuth = splitAuthor(a[aPos]); var bAuth = splitAuthor(b[bPos]); var nameLimit = Math.min(aAuth.length, bAuth.length); var nameMatches = 0; for (var n = 0; n < nameLimit; n++) { if ( aAuth[n] == bAuth[n] || // Direct match aAuth[n].length == 1 && bAuth[n].substr(0, 1) || // A is initial and B is full name bAuth[n].length == 1 && aAuth[n].substr(0, 1) || (aAuth[n].length > 1 && bAuth[n].length > 1 && fuzzyStringCompare(aAuth[n], bAuth[n], 3)) ) { nameMatches++; } } if (nameMatches >= nameLimit) { aPos++; bPos++; } else { failed = true; } break; } } return !failed; }
javascript
function compareNames(a, b) { if (!isArray(a)) a = splitAuthorString(a); if (!isArray(b)) b = splitAuthorString(b); var aPos = 0, bPos = 0; var authorLimit = Math.min(a.length, b.length); var failed = false; while (aPos < authorLimit && bPos < authorLimit) { if (fuzzyStringCompare(a[aPos], b[bPos])) { // Direct or fuzzy matching of entire strings aPos++; bPos++; } else { var aAuth = splitAuthor(a[aPos]); var bAuth = splitAuthor(b[bPos]); var nameLimit = Math.min(aAuth.length, bAuth.length); var nameMatches = 0; for (var n = 0; n < nameLimit; n++) { if ( aAuth[n] == bAuth[n] || // Direct match aAuth[n].length == 1 && bAuth[n].substr(0, 1) || // A is initial and B is full name bAuth[n].length == 1 && aAuth[n].substr(0, 1) || (aAuth[n].length > 1 && bAuth[n].length > 1 && fuzzyStringCompare(aAuth[n], bAuth[n], 3)) ) { nameMatches++; } } if (nameMatches >= nameLimit) { aPos++; bPos++; } else { failed = true; } break; } } return !failed; }
[ "function", "compareNames", "(", "a", ",", "b", ")", "{", "if", "(", "!", "isArray", "(", "a", ")", ")", "a", "=", "splitAuthorString", "(", "a", ")", ";", "if", "(", "!", "isArray", "(", "b", ")", ")", "b", "=", "splitAuthorString", "(", "b", ")", ";", "var", "aPos", "=", "0", ",", "bPos", "=", "0", ";", "var", "authorLimit", "=", "Math", ".", "min", "(", "a", ".", "length", ",", "b", ".", "length", ")", ";", "var", "failed", "=", "false", ";", "while", "(", "aPos", "<", "authorLimit", "&&", "bPos", "<", "authorLimit", ")", "{", "if", "(", "fuzzyStringCompare", "(", "a", "[", "aPos", "]", ",", "b", "[", "bPos", "]", ")", ")", "{", "aPos", "++", ";", "bPos", "++", ";", "}", "else", "{", "var", "aAuth", "=", "splitAuthor", "(", "a", "[", "aPos", "]", ")", ";", "var", "bAuth", "=", "splitAuthor", "(", "b", "[", "bPos", "]", ")", ";", "var", "nameLimit", "=", "Math", ".", "min", "(", "aAuth", ".", "length", ",", "bAuth", ".", "length", ")", ";", "var", "nameMatches", "=", "0", ";", "for", "(", "var", "n", "=", "0", ";", "n", "<", "nameLimit", ";", "n", "++", ")", "{", "if", "(", "aAuth", "[", "n", "]", "==", "bAuth", "[", "n", "]", "||", "aAuth", "[", "n", "]", ".", "length", "==", "1", "&&", "bAuth", "[", "n", "]", ".", "substr", "(", "0", ",", "1", ")", "||", "bAuth", "[", "n", "]", ".", "length", "==", "1", "&&", "aAuth", "[", "n", "]", ".", "substr", "(", "0", ",", "1", ")", "||", "(", "aAuth", "[", "n", "]", ".", "length", ">", "1", "&&", "bAuth", "[", "n", "]", ".", "length", ">", "1", "&&", "fuzzyStringCompare", "(", "aAuth", "[", "n", "]", ",", "bAuth", "[", "n", "]", ",", "3", ")", ")", ")", "{", "nameMatches", "++", ";", "}", "}", "if", "(", "nameMatches", ">=", "nameLimit", ")", "{", "aPos", "++", ";", "bPos", "++", ";", "}", "else", "{", "failed", "=", "true", ";", "}", "break", ";", "}", "}", "return", "!", "failed", ";", "}" ]
Compare an array of authors against a second array @param array a The first array of authors @param array b The second array of authors @return bolean True if a ≈ b
[ "Compare", "an", "array", "of", "authors", "against", "a", "second", "array" ]
19a15a8410f05b94b7fd191874c1f5af3ef5cd51
https://github.com/hash-bang/compare-names/blob/19a15a8410f05b94b7fd191874c1f5af3ef5cd51/index.js#L67-L105
train
mjaczynski/docloud-api
index.js
function(call, error, response, body, codes, reject) { if (error) { if (typeof error == 'string') { var message = util.format("Unexpected error on %s %s, reason : %s", call.method, call.uri, error); util.log(message); var exception = new Error(message); exception.call = call; reject(exception); } else { util.log(error); reject(error); } return true; } else if (codes.indexOf(response.statusCode) <0 ) { var message; if (body.message){ message = util.format("Unexpected response code %s on %s %s, reason : %s", response.statusCode, call.method, call.uri, body.message); } else { message = util.format("Unexpected response code %s on %s %s", response.statusCode, call.method, call.uri); } util.log(message); var exception = new Error(message); exception.call = call; exception.reason = body; reject(exception); return true; } return false; }
javascript
function(call, error, response, body, codes, reject) { if (error) { if (typeof error == 'string') { var message = util.format("Unexpected error on %s %s, reason : %s", call.method, call.uri, error); util.log(message); var exception = new Error(message); exception.call = call; reject(exception); } else { util.log(error); reject(error); } return true; } else if (codes.indexOf(response.statusCode) <0 ) { var message; if (body.message){ message = util.format("Unexpected response code %s on %s %s, reason : %s", response.statusCode, call.method, call.uri, body.message); } else { message = util.format("Unexpected response code %s on %s %s", response.statusCode, call.method, call.uri); } util.log(message); var exception = new Error(message); exception.call = call; exception.reason = body; reject(exception); return true; } return false; }
[ "function", "(", "call", ",", "error", ",", "response", ",", "body", ",", "codes", ",", "reject", ")", "{", "if", "(", "error", ")", "{", "if", "(", "typeof", "error", "==", "'string'", ")", "{", "var", "message", "=", "util", ".", "format", "(", "\"Unexpected error on %s %s, reason : %s\"", ",", "call", ".", "method", ",", "call", ".", "uri", ",", "error", ")", ";", "util", ".", "log", "(", "message", ")", ";", "var", "exception", "=", "new", "Error", "(", "message", ")", ";", "exception", ".", "call", "=", "call", ";", "reject", "(", "exception", ")", ";", "}", "else", "{", "util", ".", "log", "(", "error", ")", ";", "reject", "(", "error", ")", ";", "}", "return", "true", ";", "}", "else", "if", "(", "codes", ".", "indexOf", "(", "response", ".", "statusCode", ")", "<", "0", ")", "{", "var", "message", ";", "if", "(", "body", ".", "message", ")", "{", "message", "=", "util", ".", "format", "(", "\"Unexpected response code %s on %s %s, reason : %s\"", ",", "response", ".", "statusCode", ",", "call", ".", "method", ",", "call", ".", "uri", ",", "body", ".", "message", ")", ";", "}", "else", "{", "message", "=", "util", ".", "format", "(", "\"Unexpected response code %s on %s %s\"", ",", "response", ".", "statusCode", ",", "call", ".", "method", ",", "call", ".", "uri", ")", ";", "}", "util", ".", "log", "(", "message", ")", ";", "var", "exception", "=", "new", "Error", "(", "message", ")", ";", "exception", ".", "call", "=", "call", ";", "exception", ".", "reason", "=", "body", ";", "reject", "(", "exception", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Check for an error after calling an HTTP request. @param call the call data @param error the error info passed to the callback @param response the HTTP response @param body the HTTP body @param codes the array of accepted response code @param reject the promise reject call back to call in case of error
[ "Check", "for", "an", "error", "after", "calling", "an", "HTTP", "request", "." ]
10e2afb7cab0f66f5a02dc943e79d45b86817b9c
https://github.com/mjaczynski/docloud-api/blob/10e2afb7cab0f66f5a02dc943e79d45b86817b9c/index.js#L20-L51
train
preceptorjs/taxi
lib/element.js
Element
function Element (driver, parent, selector, id) { this._driver = driver; this._parent = parent; this._selector = selector; this._id = id; }
javascript
function Element (driver, parent, selector, id) { this._driver = driver; this._parent = parent; this._selector = selector; this._id = id; }
[ "function", "Element", "(", "driver", ",", "parent", ",", "selector", ",", "id", ")", "{", "this", ".", "_driver", "=", "driver", ";", "this", ".", "_parent", "=", "parent", ";", "this", ".", "_selector", "=", "selector", ";", "this", ".", "_id", "=", "id", ";", "}" ]
Object representing a DOM-Element @constructor @class Element @module WebDriver @submodule Core @param {Driver} driver @param {Browser|Element} parent @param {String} selector @param {String} id
[ "Object", "representing", "a", "DOM", "-", "Element" ]
96ab5a5c5fa9dc50f325ba4de52dd90009073ca3
https://github.com/preceptorjs/taxi/blob/96ab5a5c5fa9dc50f325ba4de52dd90009073ca3/lib/element.js#L26-L31
train
penartur/node-benchmark-pages
lib/benchmark-context.js
function (benchmark, simultaneousRequests, done) { var pageName, engineName; this.benchmark = benchmark; this.simultaneousRequests = simultaneousRequests; this.done = done; if (typeof simultaneousRequests !== "number") { throw new Error("simultaneousRequests must be an integer; " + (typeof simultaneousRequests) + " passed"); } if (simultaneousRequests < 1) { throw new Error("simultaneousRequests must be at least 1; " + simultaneousRequests + " passed"); } this.responseTimes = {}; for (pageName in this.benchmark.pages) { this.responseTimes[pageName] = {}; for (engineName in this.benchmark.engines) { this.responseTimes[pageName][engineName] = []; } } this.totals = {}; }
javascript
function (benchmark, simultaneousRequests, done) { var pageName, engineName; this.benchmark = benchmark; this.simultaneousRequests = simultaneousRequests; this.done = done; if (typeof simultaneousRequests !== "number") { throw new Error("simultaneousRequests must be an integer; " + (typeof simultaneousRequests) + " passed"); } if (simultaneousRequests < 1) { throw new Error("simultaneousRequests must be at least 1; " + simultaneousRequests + " passed"); } this.responseTimes = {}; for (pageName in this.benchmark.pages) { this.responseTimes[pageName] = {}; for (engineName in this.benchmark.engines) { this.responseTimes[pageName][engineName] = []; } } this.totals = {}; }
[ "function", "(", "benchmark", ",", "simultaneousRequests", ",", "done", ")", "{", "var", "pageName", ",", "engineName", ";", "this", ".", "benchmark", "=", "benchmark", ";", "this", ".", "simultaneousRequests", "=", "simultaneousRequests", ";", "this", ".", "done", "=", "done", ";", "if", "(", "typeof", "simultaneousRequests", "!==", "\"number\"", ")", "{", "throw", "new", "Error", "(", "\"simultaneousRequests must be an integer; \"", "+", "(", "typeof", "simultaneousRequests", ")", "+", "\" passed\"", ")", ";", "}", "if", "(", "simultaneousRequests", "<", "1", ")", "{", "throw", "new", "Error", "(", "\"simultaneousRequests must be at least 1; \"", "+", "simultaneousRequests", "+", "\" passed\"", ")", ";", "}", "this", ".", "responseTimes", "=", "{", "}", ";", "for", "(", "pageName", "in", "this", ".", "benchmark", ".", "pages", ")", "{", "this", ".", "responseTimes", "[", "pageName", "]", "=", "{", "}", ";", "for", "(", "engineName", "in", "this", ".", "benchmark", ".", "engines", ")", "{", "this", ".", "responseTimes", "[", "pageName", "]", "[", "engineName", "]", "=", "[", "]", ";", "}", "}", "this", ".", "totals", "=", "{", "}", ";", "}" ]
Instances of BenchmarkContext are one-time only
[ "Instances", "of", "BenchmarkContext", "are", "one", "-", "time", "only" ]
c8ad235b14427d9d4762c67b125b5ea258b32e91
https://github.com/penartur/node-benchmark-pages/blob/c8ad235b14427d9d4762c67b125b5ea258b32e91/lib/benchmark-context.js#L11-L35
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/traversal/path/context.js
visit
function visit() { if (this.isBlacklisted()) return false; if (this.opts.shouldSkip && this.opts.shouldSkip(this)) return false; this.call("enter"); if (this.shouldSkip) { return this.shouldStop; } var node = this.node; var opts = this.opts; if (node) { if (Array.isArray(node)) { // traverse over these replacement nodes we purposely don't call exitNode // as the original node has been destroyed for (var i = 0; i < node.length; i++) { _index2["default"].node(node[i], opts, this.scope, this.state, this, this.skipKeys); } } else { _index2["default"].node(node, opts, this.scope, this.state, this, this.skipKeys); this.call("exit"); } } return this.shouldStop; }
javascript
function visit() { if (this.isBlacklisted()) return false; if (this.opts.shouldSkip && this.opts.shouldSkip(this)) return false; this.call("enter"); if (this.shouldSkip) { return this.shouldStop; } var node = this.node; var opts = this.opts; if (node) { if (Array.isArray(node)) { // traverse over these replacement nodes we purposely don't call exitNode // as the original node has been destroyed for (var i = 0; i < node.length; i++) { _index2["default"].node(node[i], opts, this.scope, this.state, this, this.skipKeys); } } else { _index2["default"].node(node, opts, this.scope, this.state, this, this.skipKeys); this.call("exit"); } } return this.shouldStop; }
[ "function", "visit", "(", ")", "{", "if", "(", "this", ".", "isBlacklisted", "(", ")", ")", "return", "false", ";", "if", "(", "this", ".", "opts", ".", "shouldSkip", "&&", "this", ".", "opts", ".", "shouldSkip", "(", "this", ")", ")", "return", "false", ";", "this", ".", "call", "(", "\"enter\"", ")", ";", "if", "(", "this", ".", "shouldSkip", ")", "{", "return", "this", ".", "shouldStop", ";", "}", "var", "node", "=", "this", ".", "node", ";", "var", "opts", "=", "this", ".", "opts", ";", "if", "(", "node", ")", "{", "if", "(", "Array", ".", "isArray", "(", "node", ")", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "node", ".", "length", ";", "i", "++", ")", "{", "_index2", "[", "\"default\"", "]", ".", "node", "(", "node", "[", "i", "]", ",", "opts", ",", "this", ".", "scope", ",", "this", ".", "state", ",", "this", ",", "this", ".", "skipKeys", ")", ";", "}", "}", "else", "{", "_index2", "[", "\"default\"", "]", ".", "node", "(", "node", ",", "opts", ",", "this", ".", "scope", ",", "this", ".", "state", ",", "this", ",", "this", ".", "skipKeys", ")", ";", "this", ".", "call", "(", "\"exit\"", ")", ";", "}", "}", "return", "this", ".", "shouldStop", ";", "}" ]
Visits a node and calls appropriate enter and exit callbacks as required.
[ "Visits", "a", "node", "and", "calls", "appropriate", "enter", "and", "exit", "callbacks", "as", "required", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/traversal/path/context.js#L88-L115
train
skerit/protoblast
lib/jsonpath.js
JSONPath
function JSONPath(expression, options) { if (!options || typeof options != 'object') { options = {}; } if (!options.resultType) { options.resultType = 'value'; } if (typeof options.flatten == 'undefined') { options.flatten = false; } if (typeof options.wrap == 'undefined') { options.wrap = true; } if (typeof options.sandbox == 'undefined') { options.sandbox = {}; } this.expression = expression; this.options = options; this.resultType = options.resultType; }
javascript
function JSONPath(expression, options) { if (!options || typeof options != 'object') { options = {}; } if (!options.resultType) { options.resultType = 'value'; } if (typeof options.flatten == 'undefined') { options.flatten = false; } if (typeof options.wrap == 'undefined') { options.wrap = true; } if (typeof options.sandbox == 'undefined') { options.sandbox = {}; } this.expression = expression; this.options = options; this.resultType = options.resultType; }
[ "function", "JSONPath", "(", "expression", ",", "options", ")", "{", "if", "(", "!", "options", "||", "typeof", "options", "!=", "'object'", ")", "{", "options", "=", "{", "}", ";", "}", "if", "(", "!", "options", ".", "resultType", ")", "{", "options", ".", "resultType", "=", "'value'", ";", "}", "if", "(", "typeof", "options", ".", "flatten", "==", "'undefined'", ")", "{", "options", ".", "flatten", "=", "false", ";", "}", "if", "(", "typeof", "options", ".", "wrap", "==", "'undefined'", ")", "{", "options", ".", "wrap", "=", "true", ";", "}", "if", "(", "typeof", "options", ".", "sandbox", "==", "'undefined'", ")", "{", "options", ".", "sandbox", "=", "{", "}", ";", "}", "this", ".", "expression", "=", "expression", ";", "this", ".", "options", "=", "options", ";", "this", ".", "resultType", "=", "options", ".", "resultType", ";", "}" ]
Extract data from objects using JSONPath @author Stefan Goessner <goessner.net> @author Jelle De Loecker <[email protected]> @since 0.1.0 @version 0.1.0 @param {String} expr The string expression
[ "Extract", "data", "from", "objects", "using", "JSONPath" ]
22f35b05611bd507d380782023179a3f6ec383ae
https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/jsonpath.js#L27-L52
train
stdarg/property-path
index.js
getParentPath
function getParentPath(path, sep) { if (!is.nonEmptyStr(path)) return false; if (!is.nonEmptyStr(sep)) sep = defaultSepChar; // create new path and remove leading and trailing sep chars var properties = filter(path.split(sep), function(elem) { return is.str(elem) && elem.length; }); // create a parent path var parentPath = ''; for (var i=0; i<properties.length-1; i++) { parentPath += properties[i]; parentPath += (i < properties.length-2) ? sep : ''; } return parentPath.length ? parentPath : false; }
javascript
function getParentPath(path, sep) { if (!is.nonEmptyStr(path)) return false; if (!is.nonEmptyStr(sep)) sep = defaultSepChar; // create new path and remove leading and trailing sep chars var properties = filter(path.split(sep), function(elem) { return is.str(elem) && elem.length; }); // create a parent path var parentPath = ''; for (var i=0; i<properties.length-1; i++) { parentPath += properties[i]; parentPath += (i < properties.length-2) ? sep : ''; } return parentPath.length ? parentPath : false; }
[ "function", "getParentPath", "(", "path", ",", "sep", ")", "{", "if", "(", "!", "is", ".", "nonEmptyStr", "(", "path", ")", ")", "return", "false", ";", "if", "(", "!", "is", ".", "nonEmptyStr", "(", "sep", ")", ")", "sep", "=", "defaultSepChar", ";", "var", "properties", "=", "filter", "(", "path", ".", "split", "(", "sep", ")", ",", "function", "(", "elem", ")", "{", "return", "is", ".", "str", "(", "elem", ")", "&&", "elem", ".", "length", ";", "}", ")", ";", "var", "parentPath", "=", "''", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "properties", ".", "length", "-", "1", ";", "i", "++", ")", "{", "parentPath", "+=", "properties", "[", "i", "]", ";", "parentPath", "+=", "(", "i", "<", "properties", ".", "length", "-", "2", ")", "?", "sep", ":", "''", ";", "}", "return", "parentPath", ".", "length", "?", "parentPath", ":", "false", ";", "}" ]
Given a char separated object path, return the parent part of the path. Given a path, return the parent path, for '1.2.3.4', the parent path would be '1.2.3'. @param {String} path The path for which which we want the parent. @param {String} sep The separator character to separate path elements. @return {String|Boolean} The parent to the path input parameter or false if there is no parent path.
[ "Given", "a", "char", "separated", "object", "path", "return", "the", "parent", "part", "of", "the", "path", ".", "Given", "a", "path", "return", "the", "parent", "path", "for", "1", ".", "2", ".", "3", ".", "4", "the", "parent", "path", "would", "be", "1", ".", "2", ".", "3", "." ]
9b48457673c97bd3133c3fec57ff69c15b621251
https://github.com/stdarg/property-path/blob/9b48457673c97bd3133c3fec57ff69c15b621251/index.js#L62-L79
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/types/flow.js
createUnionTypeAnnotation
function createUnionTypeAnnotation(types) { var flattened = removeTypeDuplicates(types); if (flattened.length === 1) { return flattened[0]; } else { return t.unionTypeAnnotation(flattened); } }
javascript
function createUnionTypeAnnotation(types) { var flattened = removeTypeDuplicates(types); if (flattened.length === 1) { return flattened[0]; } else { return t.unionTypeAnnotation(flattened); } }
[ "function", "createUnionTypeAnnotation", "(", "types", ")", "{", "var", "flattened", "=", "removeTypeDuplicates", "(", "types", ")", ";", "if", "(", "flattened", ".", "length", "===", "1", ")", "{", "return", "flattened", "[", "0", "]", ";", "}", "else", "{", "return", "t", ".", "unionTypeAnnotation", "(", "flattened", ")", ";", "}", "}" ]
Takes an array of `types` and flattens them, removing duplicates and returns a `UnionTypeAnnotation` node containg them.
[ "Takes", "an", "array", "of", "types", "and", "flattens", "them", "removing", "duplicates", "and", "returns", "a", "UnionTypeAnnotation", "node", "containg", "them", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/types/flow.js#L22-L30
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/types/flow.js
removeTypeDuplicates
function removeTypeDuplicates(nodes) { var generics = {}; var bases = {}; // store union type groups to circular references var typeGroups = []; var types = []; for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; if (!node) continue; // detect duplicates if (types.indexOf(node) >= 0) { continue; } // this type matches anything if (t.isAnyTypeAnnotation(node)) { return [node]; } // if (t.isFlowBaseAnnotation(node)) { bases[node.type] = node; continue; } // if (t.isUnionTypeAnnotation(node)) { if (typeGroups.indexOf(node.types) < 0) { nodes = nodes.concat(node.types); typeGroups.push(node.types); } continue; } // find a matching generic type and merge and deduplicate the type parameters if (t.isGenericTypeAnnotation(node)) { var _name = node.id.name; if (generics[_name]) { var existing = generics[_name]; if (existing.typeParameters) { if (node.typeParameters) { existing.typeParameters.params = removeTypeDuplicates(existing.typeParameters.params.concat(node.typeParameters.params)); } } else { existing = node.typeParameters; } } else { generics[_name] = node; } continue; } types.push(node); } // add back in bases for (var type in bases) { types.push(bases[type]); } // add back in generics for (var _name2 in generics) { types.push(generics[_name2]); } return types; }
javascript
function removeTypeDuplicates(nodes) { var generics = {}; var bases = {}; // store union type groups to circular references var typeGroups = []; var types = []; for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; if (!node) continue; // detect duplicates if (types.indexOf(node) >= 0) { continue; } // this type matches anything if (t.isAnyTypeAnnotation(node)) { return [node]; } // if (t.isFlowBaseAnnotation(node)) { bases[node.type] = node; continue; } // if (t.isUnionTypeAnnotation(node)) { if (typeGroups.indexOf(node.types) < 0) { nodes = nodes.concat(node.types); typeGroups.push(node.types); } continue; } // find a matching generic type and merge and deduplicate the type parameters if (t.isGenericTypeAnnotation(node)) { var _name = node.id.name; if (generics[_name]) { var existing = generics[_name]; if (existing.typeParameters) { if (node.typeParameters) { existing.typeParameters.params = removeTypeDuplicates(existing.typeParameters.params.concat(node.typeParameters.params)); } } else { existing = node.typeParameters; } } else { generics[_name] = node; } continue; } types.push(node); } // add back in bases for (var type in bases) { types.push(bases[type]); } // add back in generics for (var _name2 in generics) { types.push(generics[_name2]); } return types; }
[ "function", "removeTypeDuplicates", "(", "nodes", ")", "{", "var", "generics", "=", "{", "}", ";", "var", "bases", "=", "{", "}", ";", "var", "typeGroups", "=", "[", "]", ";", "var", "types", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "nodes", ".", "length", ";", "i", "++", ")", "{", "var", "node", "=", "nodes", "[", "i", "]", ";", "if", "(", "!", "node", ")", "continue", ";", "if", "(", "types", ".", "indexOf", "(", "node", ")", ">=", "0", ")", "{", "continue", ";", "}", "if", "(", "t", ".", "isAnyTypeAnnotation", "(", "node", ")", ")", "{", "return", "[", "node", "]", ";", "}", "if", "(", "t", ".", "isFlowBaseAnnotation", "(", "node", ")", ")", "{", "bases", "[", "node", ".", "type", "]", "=", "node", ";", "continue", ";", "}", "if", "(", "t", ".", "isUnionTypeAnnotation", "(", "node", ")", ")", "{", "if", "(", "typeGroups", ".", "indexOf", "(", "node", ".", "types", ")", "<", "0", ")", "{", "nodes", "=", "nodes", ".", "concat", "(", "node", ".", "types", ")", ";", "typeGroups", ".", "push", "(", "node", ".", "types", ")", ";", "}", "continue", ";", "}", "if", "(", "t", ".", "isGenericTypeAnnotation", "(", "node", ")", ")", "{", "var", "_name", "=", "node", ".", "id", ".", "name", ";", "if", "(", "generics", "[", "_name", "]", ")", "{", "var", "existing", "=", "generics", "[", "_name", "]", ";", "if", "(", "existing", ".", "typeParameters", ")", "{", "if", "(", "node", ".", "typeParameters", ")", "{", "existing", ".", "typeParameters", ".", "params", "=", "removeTypeDuplicates", "(", "existing", ".", "typeParameters", ".", "params", ".", "concat", "(", "node", ".", "typeParameters", ".", "params", ")", ")", ";", "}", "}", "else", "{", "existing", "=", "node", ".", "typeParameters", ";", "}", "}", "else", "{", "generics", "[", "_name", "]", "=", "node", ";", "}", "continue", ";", "}", "types", ".", "push", "(", "node", ")", ";", "}", "for", "(", "var", "type", "in", "bases", ")", "{", "types", ".", "push", "(", "bases", "[", "type", "]", ")", ";", "}", "for", "(", "var", "_name2", "in", "generics", ")", "{", "types", ".", "push", "(", "generics", "[", "_name2", "]", ")", ";", "}", "return", "types", ";", "}" ]
Dedupe type annotations.
[ "Dedupe", "type", "annotations", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/types/flow.js#L36-L108
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/types/flow.js
createTypeAnnotationBasedOnTypeof
function createTypeAnnotationBasedOnTypeof(type) { if (type === "string") { return t.stringTypeAnnotation(); } else if (type === "number") { return t.numberTypeAnnotation(); } else if (type === "undefined") { return t.voidTypeAnnotation(); } else if (type === "boolean") { return t.booleanTypeAnnotation(); } else if (type === "function") { return t.genericTypeAnnotation(t.identifier("Function")); } else if (type === "object") { return t.genericTypeAnnotation(t.identifier("Object")); } else if (type === "symbol") { return t.genericTypeAnnotation(t.identifier("Symbol")); } else { throw new Error("Invalid typeof value"); } }
javascript
function createTypeAnnotationBasedOnTypeof(type) { if (type === "string") { return t.stringTypeAnnotation(); } else if (type === "number") { return t.numberTypeAnnotation(); } else if (type === "undefined") { return t.voidTypeAnnotation(); } else if (type === "boolean") { return t.booleanTypeAnnotation(); } else if (type === "function") { return t.genericTypeAnnotation(t.identifier("Function")); } else if (type === "object") { return t.genericTypeAnnotation(t.identifier("Object")); } else if (type === "symbol") { return t.genericTypeAnnotation(t.identifier("Symbol")); } else { throw new Error("Invalid typeof value"); } }
[ "function", "createTypeAnnotationBasedOnTypeof", "(", "type", ")", "{", "if", "(", "type", "===", "\"string\"", ")", "{", "return", "t", ".", "stringTypeAnnotation", "(", ")", ";", "}", "else", "if", "(", "type", "===", "\"number\"", ")", "{", "return", "t", ".", "numberTypeAnnotation", "(", ")", ";", "}", "else", "if", "(", "type", "===", "\"undefined\"", ")", "{", "return", "t", ".", "voidTypeAnnotation", "(", ")", ";", "}", "else", "if", "(", "type", "===", "\"boolean\"", ")", "{", "return", "t", ".", "booleanTypeAnnotation", "(", ")", ";", "}", "else", "if", "(", "type", "===", "\"function\"", ")", "{", "return", "t", ".", "genericTypeAnnotation", "(", "t", ".", "identifier", "(", "\"Function\"", ")", ")", ";", "}", "else", "if", "(", "type", "===", "\"object\"", ")", "{", "return", "t", ".", "genericTypeAnnotation", "(", "t", ".", "identifier", "(", "\"Object\"", ")", ")", ";", "}", "else", "if", "(", "type", "===", "\"symbol\"", ")", "{", "return", "t", ".", "genericTypeAnnotation", "(", "t", ".", "identifier", "(", "\"Symbol\"", ")", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"Invalid typeof value\"", ")", ";", "}", "}" ]
Create a type anotation based on typeof expression.
[ "Create", "a", "type", "anotation", "based", "on", "typeof", "expression", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/types/flow.js#L114-L132
train
zipscene/objtools
lib/index.js
deepEquals
function deepEquals(a, b) { var i, key; if (isScalar(a) && isScalar(b)) { return scalarEquals(a, b); } if (a === null || b === null || a === undefined || b === undefined) return a === b; if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) return false; for (i = 0; i < a.length; i++) { if (!deepEquals(a[i], b[i])) return false; } return true; } else if (!Array.isArray(a) && !Array.isArray(b)) { for (key in a) { if (!deepEquals(a[key], b[key])) return false; } for (key in b) { if (!deepEquals(a[key], b[key])) return false; } return true; } else { return false; } }
javascript
function deepEquals(a, b) { var i, key; if (isScalar(a) && isScalar(b)) { return scalarEquals(a, b); } if (a === null || b === null || a === undefined || b === undefined) return a === b; if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) return false; for (i = 0; i < a.length; i++) { if (!deepEquals(a[i], b[i])) return false; } return true; } else if (!Array.isArray(a) && !Array.isArray(b)) { for (key in a) { if (!deepEquals(a[key], b[key])) return false; } for (key in b) { if (!deepEquals(a[key], b[key])) return false; } return true; } else { return false; } }
[ "function", "deepEquals", "(", "a", ",", "b", ")", "{", "var", "i", ",", "key", ";", "if", "(", "isScalar", "(", "a", ")", "&&", "isScalar", "(", "b", ")", ")", "{", "return", "scalarEquals", "(", "a", ",", "b", ")", ";", "}", "if", "(", "a", "===", "null", "||", "b", "===", "null", "||", "a", "===", "undefined", "||", "b", "===", "undefined", ")", "return", "a", "===", "b", ";", "if", "(", "Array", ".", "isArray", "(", "a", ")", "&&", "Array", ".", "isArray", "(", "b", ")", ")", "{", "if", "(", "a", ".", "length", "!==", "b", ".", "length", ")", "return", "false", ";", "for", "(", "i", "=", "0", ";", "i", "<", "a", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "deepEquals", "(", "a", "[", "i", "]", ",", "b", "[", "i", "]", ")", ")", "return", "false", ";", "}", "return", "true", ";", "}", "else", "if", "(", "!", "Array", ".", "isArray", "(", "a", ")", "&&", "!", "Array", ".", "isArray", "(", "b", ")", ")", "{", "for", "(", "key", "in", "a", ")", "{", "if", "(", "!", "deepEquals", "(", "a", "[", "key", "]", ",", "b", "[", "key", "]", ")", ")", "return", "false", ";", "}", "for", "(", "key", "in", "b", ")", "{", "if", "(", "!", "deepEquals", "(", "a", "[", "key", "]", ",", "b", "[", "key", "]", ")", ")", "return", "false", ";", "}", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Checks for deep equality between two object or values. @method deepEquals @static @param {Mixed} a @param {Mixed} b @return {Boolean}
[ "Checks", "for", "deep", "equality", "between", "two", "object", "or", "values", "." ]
24b5ddf1a079561b978e9e131e14fa8bec19f9ae
https://github.com/zipscene/objtools/blob/24b5ddf1a079561b978e9e131e14fa8bec19f9ae/lib/index.js#L59-L82
train
zipscene/objtools
lib/index.js
deepCopy
function deepCopy(obj) { var res; var i; var key; if (isTerminal(obj)) { res = obj; } else if (Array.isArray(obj)) { res = Array(obj.length); for (i = 0; i < obj.length; i++) { res[i] = deepCopy(obj[i]); } } else { res = {}; for (key in obj) { res[key] = deepCopy(obj[key]); } } return res; }
javascript
function deepCopy(obj) { var res; var i; var key; if (isTerminal(obj)) { res = obj; } else if (Array.isArray(obj)) { res = Array(obj.length); for (i = 0; i < obj.length; i++) { res[i] = deepCopy(obj[i]); } } else { res = {}; for (key in obj) { res[key] = deepCopy(obj[key]); } } return res; }
[ "function", "deepCopy", "(", "obj", ")", "{", "var", "res", ";", "var", "i", ";", "var", "key", ";", "if", "(", "isTerminal", "(", "obj", ")", ")", "{", "res", "=", "obj", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "obj", ")", ")", "{", "res", "=", "Array", "(", "obj", ".", "length", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "obj", ".", "length", ";", "i", "++", ")", "{", "res", "[", "i", "]", "=", "deepCopy", "(", "obj", "[", "i", "]", ")", ";", "}", "}", "else", "{", "res", "=", "{", "}", ";", "for", "(", "key", "in", "obj", ")", "{", "res", "[", "key", "]", "=", "deepCopy", "(", "obj", "[", "key", "]", ")", ";", "}", "}", "return", "res", ";", "}" ]
Returns a deep copy of the given value such that entities are not passed by reference. @method deepCopy @static @param {Mixed} obj - The object or value to copy @return {Mixed}
[ "Returns", "a", "deep", "copy", "of", "the", "given", "value", "such", "that", "entities", "are", "not", "passed", "by", "reference", "." ]
24b5ddf1a079561b978e9e131e14fa8bec19f9ae
https://github.com/zipscene/objtools/blob/24b5ddf1a079561b978e9e131e14fa8bec19f9ae/lib/index.js#L109-L127
train
zipscene/objtools
lib/index.js
setPath
function setPath(obj, path, value) { var cur = obj; var parts = path.split('.'); var i; for (i = 0; i < parts.length; i++) { if (i === parts.length - 1) { cur[parts[i]] = value; } else { if (isScalar(cur[parts[i]])) cur[parts[i]] = {}; cur = cur[parts[i]]; } } return obj; }
javascript
function setPath(obj, path, value) { var cur = obj; var parts = path.split('.'); var i; for (i = 0; i < parts.length; i++) { if (i === parts.length - 1) { cur[parts[i]] = value; } else { if (isScalar(cur[parts[i]])) cur[parts[i]] = {}; cur = cur[parts[i]]; } } return obj; }
[ "function", "setPath", "(", "obj", ",", "path", ",", "value", ")", "{", "var", "cur", "=", "obj", ";", "var", "parts", "=", "path", ".", "split", "(", "'.'", ")", ";", "var", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "if", "(", "i", "===", "parts", ".", "length", "-", "1", ")", "{", "cur", "[", "parts", "[", "i", "]", "]", "=", "value", ";", "}", "else", "{", "if", "(", "isScalar", "(", "cur", "[", "parts", "[", "i", "]", "]", ")", ")", "cur", "[", "parts", "[", "i", "]", "]", "=", "{", "}", ";", "cur", "=", "cur", "[", "parts", "[", "i", "]", "]", ";", "}", "}", "return", "obj", ";", "}" ]
Sets the value at a given path in an object. @method setPath @static @param {Object} obj - The object @param {String} path - The path, dot-separated @param {Mixed} value - Value to set @return {Object} - The same object
[ "Sets", "the", "value", "at", "a", "given", "path", "in", "an", "object", "." ]
24b5ddf1a079561b978e9e131e14fa8bec19f9ae
https://github.com/zipscene/objtools/blob/24b5ddf1a079561b978e9e131e14fa8bec19f9ae/lib/index.js#L343-L356
train
zipscene/objtools
lib/index.js
deletePath
function deletePath(obj, path) { var cur = obj; var parts = path.split('.'); var i; for (i = 0; i < parts.length; i++) { if (i === parts.length - 1) { delete cur[parts[i]]; } else { if (isScalar(cur[parts[i]])) { return obj; } cur = cur[parts[i]]; } } return obj; }
javascript
function deletePath(obj, path) { var cur = obj; var parts = path.split('.'); var i; for (i = 0; i < parts.length; i++) { if (i === parts.length - 1) { delete cur[parts[i]]; } else { if (isScalar(cur[parts[i]])) { return obj; } cur = cur[parts[i]]; } } return obj; }
[ "function", "deletePath", "(", "obj", ",", "path", ")", "{", "var", "cur", "=", "obj", ";", "var", "parts", "=", "path", ".", "split", "(", "'.'", ")", ";", "var", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "if", "(", "i", "===", "parts", ".", "length", "-", "1", ")", "{", "delete", "cur", "[", "parts", "[", "i", "]", "]", ";", "}", "else", "{", "if", "(", "isScalar", "(", "cur", "[", "parts", "[", "i", "]", "]", ")", ")", "{", "return", "obj", ";", "}", "cur", "=", "cur", "[", "parts", "[", "i", "]", "]", ";", "}", "}", "return", "obj", ";", "}" ]
Deletes the value at a given path in an object. @method deletePath @static @param {Object} obj @param {String} path @return {Object} - The object that was passed in
[ "Deletes", "the", "value", "at", "a", "given", "path", "in", "an", "object", "." ]
24b5ddf1a079561b978e9e131e14fa8bec19f9ae
https://github.com/zipscene/objtools/blob/24b5ddf1a079561b978e9e131e14fa8bec19f9ae/lib/index.js#L368-L383
train
zipscene/objtools
lib/index.js
getPath
function getPath(obj, path, allowSkipArrays) { if (path === null || path === undefined) return obj; var cur = obj; var parts = path.split('.'); var i; for (i = 0; i < parts.length; i++) { if (isScalar(cur)) return undefined; if (Array.isArray(cur) && allowSkipArrays && !(/^[0-9]+$/.test(parts[i])) && cur.length === 1) { cur = cur[0]; i--; } else { cur = cur[parts[i]]; } } return cur; }
javascript
function getPath(obj, path, allowSkipArrays) { if (path === null || path === undefined) return obj; var cur = obj; var parts = path.split('.'); var i; for (i = 0; i < parts.length; i++) { if (isScalar(cur)) return undefined; if (Array.isArray(cur) && allowSkipArrays && !(/^[0-9]+$/.test(parts[i])) && cur.length === 1) { cur = cur[0]; i--; } else { cur = cur[parts[i]]; } } return cur; }
[ "function", "getPath", "(", "obj", ",", "path", ",", "allowSkipArrays", ")", "{", "if", "(", "path", "===", "null", "||", "path", "===", "undefined", ")", "return", "obj", ";", "var", "cur", "=", "obj", ";", "var", "parts", "=", "path", ".", "split", "(", "'.'", ")", ";", "var", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "if", "(", "isScalar", "(", "cur", ")", ")", "return", "undefined", ";", "if", "(", "Array", ".", "isArray", "(", "cur", ")", "&&", "allowSkipArrays", "&&", "!", "(", "/", "^[0-9]+$", "/", ".", "test", "(", "parts", "[", "i", "]", ")", ")", "&&", "cur", ".", "length", "===", "1", ")", "{", "cur", "=", "cur", "[", "0", "]", ";", "i", "--", ";", "}", "else", "{", "cur", "=", "cur", "[", "parts", "[", "i", "]", "]", ";", "}", "}", "return", "cur", ";", "}" ]
Gets the value at a given path in an object. @method getPath @static @param {Object} obj - The object @param {String} path - The path, dot-separated @param {Boolean} allowSkipArrays - If true: If a field in an object is an array and the path key is non-numeric, and the array has exactly 1 element, then the first element of the array is used. @return {Mixed} - The value at the path
[ "Gets", "the", "value", "at", "a", "given", "path", "in", "an", "object", "." ]
24b5ddf1a079561b978e9e131e14fa8bec19f9ae
https://github.com/zipscene/objtools/blob/24b5ddf1a079561b978e9e131e14fa8bec19f9ae/lib/index.js#L398-L413
train
zipscene/objtools
lib/index.js
merge
function merge(/* object, sources */) { var lastSource = arguments[arguments.length - 1]; if ( typeof lastSource === 'function' || ( arguments.length > 2 && Array.isArray(lastSource) && lastSource.indexOf(arguments[1]) >= 0 ) ) { return mergeHeavy.apply(null, arguments); } else { return mergeLight.apply(null, arguments); } }
javascript
function merge(/* object, sources */) { var lastSource = arguments[arguments.length - 1]; if ( typeof lastSource === 'function' || ( arguments.length > 2 && Array.isArray(lastSource) && lastSource.indexOf(arguments[1]) >= 0 ) ) { return mergeHeavy.apply(null, arguments); } else { return mergeLight.apply(null, arguments); } }
[ "function", "merge", "(", ")", "{", "var", "lastSource", "=", "arguments", "[", "arguments", ".", "length", "-", "1", "]", ";", "if", "(", "typeof", "lastSource", "===", "'function'", "||", "(", "arguments", ".", "length", ">", "2", "&&", "Array", ".", "isArray", "(", "lastSource", ")", "&&", "lastSource", ".", "indexOf", "(", "arguments", "[", "1", "]", ")", ">=", "0", ")", ")", "{", "return", "mergeHeavy", ".", "apply", "(", "null", ",", "arguments", ")", ";", "}", "else", "{", "return", "mergeLight", ".", "apply", "(", "null", ",", "arguments", ")", ";", "}", "}" ]
Merges n objects together. @method merge @static @param {Object} object - the destination object @param {Object} sources - the source object @param {Function} customizer - the function to customize merging properties If provided, customizer is invoked to produce the merged values of the destination and source properties. If customizer returns undefined, merging is handled by the method instead. @param {Mixed} customizer.objectValue - the value at `key` in the base object @param {Mixed} customizer.sourceValue - the value at `key` in the source object @param {Mixed} customizer.key - the key currently being merged @param {Mixed} customizer.object - the base object @param {Mixed} customizer.source - the source object @return {Object} - the merged object
[ "Merges", "n", "objects", "together", "." ]
24b5ddf1a079561b978e9e131e14fa8bec19f9ae
https://github.com/zipscene/objtools/blob/24b5ddf1a079561b978e9e131e14fa8bec19f9ae/lib/index.js#L465-L479
train
zipscene/objtools
lib/index.js
dottedDiff
function dottedDiff(val1, val2) { if (isScalar(val1) && isScalar(val2)) { return val1 === val2 ? [] : ''; } else { return Object.keys(addDottedDiffFieldsToSet({}, '', val1, val2)); } }
javascript
function dottedDiff(val1, val2) { if (isScalar(val1) && isScalar(val2)) { return val1 === val2 ? [] : ''; } else { return Object.keys(addDottedDiffFieldsToSet({}, '', val1, val2)); } }
[ "function", "dottedDiff", "(", "val1", ",", "val2", ")", "{", "if", "(", "isScalar", "(", "val1", ")", "&&", "isScalar", "(", "val2", ")", ")", "{", "return", "val1", "===", "val2", "?", "[", "]", ":", "''", ";", "}", "else", "{", "return", "Object", ".", "keys", "(", "addDottedDiffFieldsToSet", "(", "{", "}", ",", "''", ",", "val1", ",", "val2", ")", ")", ";", "}", "}" ]
Diffs two objects @method dottedDiff @static @param {Mixed} val1 - the first value to diff @param {Mixed} val2 - the second value to diff @return {String[]} - an array of dot-separated paths to the shallowest branches present in both objects from which there are no identical scalar values.
[ "Diffs", "two", "objects" ]
24b5ddf1a079561b978e9e131e14fa8bec19f9ae
https://github.com/zipscene/objtools/blob/24b5ddf1a079561b978e9e131e14fa8bec19f9ae/lib/index.js#L660-L666
train
zipscene/objtools
lib/index.js
objectHash
function objectHash(obj) { var hash = crypto.createHash('md5'); hash.update(makeHashKey(obj)); return hash.digest('hex'); }
javascript
function objectHash(obj) { var hash = crypto.createHash('md5'); hash.update(makeHashKey(obj)); return hash.digest('hex'); }
[ "function", "objectHash", "(", "obj", ")", "{", "var", "hash", "=", "crypto", ".", "createHash", "(", "'md5'", ")", ";", "hash", ".", "update", "(", "makeHashKey", "(", "obj", ")", ")", ";", "return", "hash", ".", "digest", "(", "'hex'", ")", ";", "}" ]
Construct a consistent hash of an object, array, or other Javascript entity. @method objectHash @static @param {Mixed} obj - The object to hash. @return {String} - The hash string. Long enough so collisions are extremely unlikely.
[ "Construct", "a", "consistent", "hash", "of", "an", "object", "array", "or", "other", "Javascript", "entity", "." ]
24b5ddf1a079561b978e9e131e14fa8bec19f9ae
https://github.com/zipscene/objtools/blob/24b5ddf1a079561b978e9e131e14fa8bec19f9ae/lib/index.js#L700-L704
train
zipscene/objtools
lib/index.js
sanitizeDate
function sanitizeDate(val) { if (!val) return null; if (_.isDate(val)) return val; if (_.isString(val)) return new Date(Date.parse(val)); if (_.isNumber(val)) return new Date(val); if (_.isObject(val) && val.date) return sanitizeDate(val.date); return null; }
javascript
function sanitizeDate(val) { if (!val) return null; if (_.isDate(val)) return val; if (_.isString(val)) return new Date(Date.parse(val)); if (_.isNumber(val)) return new Date(val); if (_.isObject(val) && val.date) return sanitizeDate(val.date); return null; }
[ "function", "sanitizeDate", "(", "val", ")", "{", "if", "(", "!", "val", ")", "return", "null", ";", "if", "(", "_", ".", "isDate", "(", "val", ")", ")", "return", "val", ";", "if", "(", "_", ".", "isString", "(", "val", ")", ")", "return", "new", "Date", "(", "Date", ".", "parse", "(", "val", ")", ")", ";", "if", "(", "_", ".", "isNumber", "(", "val", ")", ")", "return", "new", "Date", "(", "val", ")", ";", "if", "(", "_", ".", "isObject", "(", "val", ")", "&&", "val", ".", "date", ")", "return", "sanitizeDate", "(", "val", ".", "date", ")", ";", "return", "null", ";", "}" ]
Converts a date string, number of miliseconds or object with a date field into an instance of Date. It will return the same instance if a Date instance is passed in. @method sanitizeDate @parse {String|Number|Object} - the value to convert @return {Date} - returns the converted Date instance
[ "Converts", "a", "date", "string", "number", "of", "miliseconds", "or", "object", "with", "a", "date", "field", "into", "an", "instance", "of", "Date", ".", "It", "will", "return", "the", "same", "instance", "if", "a", "Date", "instance", "is", "passed", "in", "." ]
24b5ddf1a079561b978e9e131e14fa8bec19f9ae
https://github.com/zipscene/objtools/blob/24b5ddf1a079561b978e9e131e14fa8bec19f9ae/lib/index.js#L745-L752
train
zyw327/okgoes
lib/view/render.js
render
async function render(view, options) { view += settings.viewExt; const viewPath = path.join(settings.root, view); debug(`render: ${viewPath}`); // get from cache if (settings.cache && cache[viewPath]) { return cache[viewPath].call(options.scope, options); } const tpl = await fs.readFile(viewPath, 'utf8'); // override `ejs` node_module `resolveInclude` function ejs.resolveInclude = function(name, filename, isDir) { if (!path.extname(name)) { name += settings.viewExt; } return parentResolveInclude(name, filename, isDir); } const fn = ejs.compile(tpl, { filename: viewPath, _with: settings._with, compileDebug: settings.debug && settings.compileDebug, debug: settings.debug, delimiter: settings.delimiter }); if (settings.cache) { cache[viewPath] = fn; } return fn.call(options.scope, options); }
javascript
async function render(view, options) { view += settings.viewExt; const viewPath = path.join(settings.root, view); debug(`render: ${viewPath}`); // get from cache if (settings.cache && cache[viewPath]) { return cache[viewPath].call(options.scope, options); } const tpl = await fs.readFile(viewPath, 'utf8'); // override `ejs` node_module `resolveInclude` function ejs.resolveInclude = function(name, filename, isDir) { if (!path.extname(name)) { name += settings.viewExt; } return parentResolveInclude(name, filename, isDir); } const fn = ejs.compile(tpl, { filename: viewPath, _with: settings._with, compileDebug: settings.debug && settings.compileDebug, debug: settings.debug, delimiter: settings.delimiter }); if (settings.cache) { cache[viewPath] = fn; } return fn.call(options.scope, options); }
[ "async", "function", "render", "(", "view", ",", "options", ")", "{", "view", "+=", "settings", ".", "viewExt", ";", "const", "viewPath", "=", "path", ".", "join", "(", "settings", ".", "root", ",", "view", ")", ";", "debug", "(", "`", "${", "viewPath", "}", "`", ")", ";", "if", "(", "settings", ".", "cache", "&&", "cache", "[", "viewPath", "]", ")", "{", "return", "cache", "[", "viewPath", "]", ".", "call", "(", "options", ".", "scope", ",", "options", ")", ";", "}", "const", "tpl", "=", "await", "fs", ".", "readFile", "(", "viewPath", ",", "'utf8'", ")", ";", "ejs", ".", "resolveInclude", "=", "function", "(", "name", ",", "filename", ",", "isDir", ")", "{", "if", "(", "!", "path", ".", "extname", "(", "name", ")", ")", "{", "name", "+=", "settings", ".", "viewExt", ";", "}", "return", "parentResolveInclude", "(", "name", ",", "filename", ",", "isDir", ")", ";", "}", "const", "fn", "=", "ejs", ".", "compile", "(", "tpl", ",", "{", "filename", ":", "viewPath", ",", "_with", ":", "settings", ".", "_with", ",", "compileDebug", ":", "settings", ".", "debug", "&&", "settings", ".", "compileDebug", ",", "debug", ":", "settings", ".", "debug", ",", "delimiter", ":", "settings", ".", "delimiter", "}", ")", ";", "if", "(", "settings", ".", "cache", ")", "{", "cache", "[", "viewPath", "]", "=", "fn", ";", "}", "return", "fn", ".", "call", "(", "options", ".", "scope", ",", "options", ")", ";", "}" ]
generate html with view name and options @param {String} view @param {Object} options @return {String} html
[ "generate", "html", "with", "view", "name", "and", "options" ]
d3cc0e1a426aae0c39dbed834e9c15a25c43628e
https://github.com/zyw327/okgoes/blob/d3cc0e1a426aae0c39dbed834e9c15a25c43628e/lib/view/render.js#L76-L107
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/api/node.js
parse
function parse(code) { var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; opts.allowHashBang = true; opts.sourceType = "module"; opts.ecmaVersion = Infinity; opts.plugins = { jsx: true, flow: true }; opts.features = {}; for (var key in _transformation2["default"].pipeline.transformers) { opts.features[key] = true; } var ast = babylon.parse(code, opts); if (opts.onToken) { // istanbul ignore next var _opts$onToken; (_opts$onToken = opts.onToken).push.apply(_opts$onToken, ast.tokens); } if (opts.onComment) { // istanbul ignore next var _opts$onComment; (_opts$onComment = opts.onComment).push.apply(_opts$onComment, ast.comments); } return ast.program; }
javascript
function parse(code) { var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; opts.allowHashBang = true; opts.sourceType = "module"; opts.ecmaVersion = Infinity; opts.plugins = { jsx: true, flow: true }; opts.features = {}; for (var key in _transformation2["default"].pipeline.transformers) { opts.features[key] = true; } var ast = babylon.parse(code, opts); if (opts.onToken) { // istanbul ignore next var _opts$onToken; (_opts$onToken = opts.onToken).push.apply(_opts$onToken, ast.tokens); } if (opts.onComment) { // istanbul ignore next var _opts$onComment; (_opts$onComment = opts.onComment).push.apply(_opts$onComment, ast.comments); } return ast.program; }
[ "function", "parse", "(", "code", ")", "{", "var", "opts", "=", "arguments", ".", "length", "<=", "1", "||", "arguments", "[", "1", "]", "===", "undefined", "?", "{", "}", ":", "arguments", "[", "1", "]", ";", "opts", ".", "allowHashBang", "=", "true", ";", "opts", ".", "sourceType", "=", "\"module\"", ";", "opts", ".", "ecmaVersion", "=", "Infinity", ";", "opts", ".", "plugins", "=", "{", "jsx", ":", "true", ",", "flow", ":", "true", "}", ";", "opts", ".", "features", "=", "{", "}", ";", "for", "(", "var", "key", "in", "_transformation2", "[", "\"default\"", "]", ".", "pipeline", ".", "transformers", ")", "{", "opts", ".", "features", "[", "key", "]", "=", "true", ";", "}", "var", "ast", "=", "babylon", ".", "parse", "(", "code", ",", "opts", ")", ";", "if", "(", "opts", ".", "onToken", ")", "{", "var", "_opts$onToken", ";", "(", "_opts$onToken", "=", "opts", ".", "onToken", ")", ".", "push", ".", "apply", "(", "_opts$onToken", ",", "ast", ".", "tokens", ")", ";", "}", "if", "(", "opts", ".", "onComment", ")", "{", "var", "_opts$onComment", ";", "(", "_opts$onComment", "=", "opts", ".", "onComment", ")", ".", "push", ".", "apply", "(", "_opts$onComment", ",", "ast", ".", "comments", ")", ";", "}", "return", "ast", ".", "program", ";", "}" ]
Parse script with Babel's parser.
[ "Parse", "script", "with", "Babel", "s", "parser", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/api/node.js#L146-L181
train
epii-io/epii-node-html5
lib/renderer.js
renderToString
function renderToString(meta) { if (meta.html) return meta.html.source var output = [ '<!DOCTYPE html>', '<html>', '<head>', '<meta charset="utf8" />' ] var { head, body } = meta head.metas.forEach(e => output.push(renderMeta(e.name, e.http, e.content))) head.styles.forEach(e => output.push(renderStyle(e.type, e.src, e.source))) head.scripts.forEach(e => output.push(renderScript(e.type, e.src, e.source))) if (head.title) output.push(`<title>${head.title}</title>`) if (head.icon) output.push(renderIcon(head.icon.type, head.icon.src)) output.push('</head>', '<body>') if (body.holder) output.push(body.holder.source) body.injectA.forEach(e => output.push(renderScript(e.type, e.src, e.source))) body.scripts.forEach(e => output.push(renderScript(e.type, e.src, e.source))) body.injectB.forEach(e => output.push(renderScript(e.type, e.src, e.source))) output.push('</body>', '</html>') return concatString(output) }
javascript
function renderToString(meta) { if (meta.html) return meta.html.source var output = [ '<!DOCTYPE html>', '<html>', '<head>', '<meta charset="utf8" />' ] var { head, body } = meta head.metas.forEach(e => output.push(renderMeta(e.name, e.http, e.content))) head.styles.forEach(e => output.push(renderStyle(e.type, e.src, e.source))) head.scripts.forEach(e => output.push(renderScript(e.type, e.src, e.source))) if (head.title) output.push(`<title>${head.title}</title>`) if (head.icon) output.push(renderIcon(head.icon.type, head.icon.src)) output.push('</head>', '<body>') if (body.holder) output.push(body.holder.source) body.injectA.forEach(e => output.push(renderScript(e.type, e.src, e.source))) body.scripts.forEach(e => output.push(renderScript(e.type, e.src, e.source))) body.injectB.forEach(e => output.push(renderScript(e.type, e.src, e.source))) output.push('</body>', '</html>') return concatString(output) }
[ "function", "renderToString", "(", "meta", ")", "{", "if", "(", "meta", ".", "html", ")", "return", "meta", ".", "html", ".", "source", "var", "output", "=", "[", "'<!DOCTYPE html>'", ",", "'<html>'", ",", "'<head>'", ",", "'<meta charset=\"utf8\" />'", "]", "var", "{", "head", ",", "body", "}", "=", "meta", "head", ".", "metas", ".", "forEach", "(", "e", "=>", "output", ".", "push", "(", "renderMeta", "(", "e", ".", "name", ",", "e", ".", "http", ",", "e", ".", "content", ")", ")", ")", "head", ".", "styles", ".", "forEach", "(", "e", "=>", "output", ".", "push", "(", "renderStyle", "(", "e", ".", "type", ",", "e", ".", "src", ",", "e", ".", "source", ")", ")", ")", "head", ".", "scripts", ".", "forEach", "(", "e", "=>", "output", ".", "push", "(", "renderScript", "(", "e", ".", "type", ",", "e", ".", "src", ",", "e", ".", "source", ")", ")", ")", "if", "(", "head", ".", "title", ")", "output", ".", "push", "(", "`", "${", "head", ".", "title", "}", "`", ")", "if", "(", "head", ".", "icon", ")", "output", ".", "push", "(", "renderIcon", "(", "head", ".", "icon", ".", "type", ",", "head", ".", "icon", ".", "src", ")", ")", "output", ".", "push", "(", "'</head>'", ",", "'<body>'", ")", "if", "(", "body", ".", "holder", ")", "output", ".", "push", "(", "body", ".", "holder", ".", "source", ")", "body", ".", "injectA", ".", "forEach", "(", "e", "=>", "output", ".", "push", "(", "renderScript", "(", "e", ".", "type", ",", "e", ".", "src", ",", "e", ".", "source", ")", ")", ")", "body", ".", "scripts", ".", "forEach", "(", "e", "=>", "output", ".", "push", "(", "renderScript", "(", "e", ".", "type", ",", "e", ".", "src", ",", "e", ".", "source", ")", ")", ")", "body", ".", "injectB", ".", "forEach", "(", "e", "=>", "output", ".", "push", "(", "renderScript", "(", "e", ".", "type", ",", "e", ".", "src", ",", "e", ".", "source", ")", ")", ")", "output", ".", "push", "(", "'</body>'", ",", "'</html>'", ")", "return", "concatString", "(", "output", ")", "}" ]
render view to HTML5 @return {ViewMeta}
[ "render", "view", "to", "HTML5" ]
69ea36c2be19ac95536925fde4eab9f0e1b16151
https://github.com/epii-io/epii-node-html5/blob/69ea36c2be19ac95536925fde4eab9f0e1b16151/lib/renderer.js#L76-L94
train
jetebusiness/jetRoute
dist/jquery.jetroute.js
getRoute
function getRoute(route) { for (var key in settings.routes) { if (key === route) { return settings.routes[key]; } } }
javascript
function getRoute(route) { for (var key in settings.routes) { if (key === route) { return settings.routes[key]; } } }
[ "function", "getRoute", "(", "route", ")", "{", "for", "(", "var", "key", "in", "settings", ".", "routes", ")", "{", "if", "(", "key", "===", "route", ")", "{", "return", "settings", ".", "routes", "[", "key", "]", ";", "}", "}", "}" ]
Return the URI of the called initial route. @param route @returns {*}
[ "Return", "the", "URI", "of", "the", "called", "initial", "route", "." ]
02a8a926b68e250e3a8328f175555204ed39f143
https://github.com/jetebusiness/jetRoute/blob/02a8a926b68e250e3a8328f175555204ed39f143/dist/jquery.jetroute.js#L53-L59
train
jetebusiness/jetRoute
dist/jquery.jetroute.js
compareUrlRoute
function compareUrlRoute(currentURL, currentRoute) { var regex = /\{(.*)\}/i; var arraySize = currentRoute.length, testValue = false; for (var i = 0; i < arraySize; i++) { var dynamic = regex.exec(currentRoute[i]); if (dynamic) { document.routeParams[dynamic[1]] = currentURL[i]; } else { if (currentRoute[i] === currentURL[i]) { testValue = true; } } } return testValue; }
javascript
function compareUrlRoute(currentURL, currentRoute) { var regex = /\{(.*)\}/i; var arraySize = currentRoute.length, testValue = false; for (var i = 0; i < arraySize; i++) { var dynamic = regex.exec(currentRoute[i]); if (dynamic) { document.routeParams[dynamic[1]] = currentURL[i]; } else { if (currentRoute[i] === currentURL[i]) { testValue = true; } } } return testValue; }
[ "function", "compareUrlRoute", "(", "currentURL", ",", "currentRoute", ")", "{", "var", "regex", "=", "/", "\\{(.*)\\}", "/", "i", ";", "var", "arraySize", "=", "currentRoute", ".", "length", ",", "testValue", "=", "false", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arraySize", ";", "i", "++", ")", "{", "var", "dynamic", "=", "regex", ".", "exec", "(", "currentRoute", "[", "i", "]", ")", ";", "if", "(", "dynamic", ")", "{", "document", ".", "routeParams", "[", "dynamic", "[", "1", "]", "]", "=", "currentURL", "[", "i", "]", ";", "}", "else", "{", "if", "(", "currentRoute", "[", "i", "]", "===", "currentURL", "[", "i", "]", ")", "{", "testValue", "=", "true", ";", "}", "}", "}", "return", "testValue", ";", "}" ]
Route Compare and Dynamic Route Atributes @param currentURL @param currentRoute @returns {boolean}
[ "Route", "Compare", "and", "Dynamic", "Route", "Atributes" ]
02a8a926b68e250e3a8328f175555204ed39f143
https://github.com/jetebusiness/jetRoute/blob/02a8a926b68e250e3a8328f175555204ed39f143/dist/jquery.jetroute.js#L70-L86
train
VividCortex/grunt-circleci
tasks/lib/status.js
function (commit, until) { var checker = this; until = !isNaN(until) ? until : (new Date()).getTime() + (this.getOption('timeout')); if ((new Date()).getTime() > until) { return this.handleError('Timeout'); } return this.getBuilds() .then(function (builds) { if (undefined !== builds.message) { return checker.handleError(builds.message); } var finder = new BuildFinder(builds), builds = finder.findByCommit(commit); if (null === builds) { return checker.handleError('Build not found'); } return builds; }, this.handleError) .then(function (builds) { var successfulBuilds = 0; for (var i = 0; i < builds.length; i++) { if (builds[i].isSuccess()) { successfulBuilds++; } else if (builds[i].isFailure() || !checker.getOption('retryOnRunning')) { return checker.handleError('Invalid status for CircleCI build: "' + builds[i].getStatus() + '"') } } if (successfulBuilds === builds.length) { return true; } // Sleep for 10 seconds by default var promise = sleep(checker.getOption('retryAfter')); return promise.then(function () { return checker.checkCommit(commit, until); }); }, this.handleError); }
javascript
function (commit, until) { var checker = this; until = !isNaN(until) ? until : (new Date()).getTime() + (this.getOption('timeout')); if ((new Date()).getTime() > until) { return this.handleError('Timeout'); } return this.getBuilds() .then(function (builds) { if (undefined !== builds.message) { return checker.handleError(builds.message); } var finder = new BuildFinder(builds), builds = finder.findByCommit(commit); if (null === builds) { return checker.handleError('Build not found'); } return builds; }, this.handleError) .then(function (builds) { var successfulBuilds = 0; for (var i = 0; i < builds.length; i++) { if (builds[i].isSuccess()) { successfulBuilds++; } else if (builds[i].isFailure() || !checker.getOption('retryOnRunning')) { return checker.handleError('Invalid status for CircleCI build: "' + builds[i].getStatus() + '"') } } if (successfulBuilds === builds.length) { return true; } // Sleep for 10 seconds by default var promise = sleep(checker.getOption('retryAfter')); return promise.then(function () { return checker.checkCommit(commit, until); }); }, this.handleError); }
[ "function", "(", "commit", ",", "until", ")", "{", "var", "checker", "=", "this", ";", "until", "=", "!", "isNaN", "(", "until", ")", "?", "until", ":", "(", "new", "Date", "(", ")", ")", ".", "getTime", "(", ")", "+", "(", "this", ".", "getOption", "(", "'timeout'", ")", ")", ";", "if", "(", "(", "new", "Date", "(", ")", ")", ".", "getTime", "(", ")", ">", "until", ")", "{", "return", "this", ".", "handleError", "(", "'Timeout'", ")", ";", "}", "return", "this", ".", "getBuilds", "(", ")", ".", "then", "(", "function", "(", "builds", ")", "{", "if", "(", "undefined", "!==", "builds", ".", "message", ")", "{", "return", "checker", ".", "handleError", "(", "builds", ".", "message", ")", ";", "}", "var", "finder", "=", "new", "BuildFinder", "(", "builds", ")", ",", "builds", "=", "finder", ".", "findByCommit", "(", "commit", ")", ";", "if", "(", "null", "===", "builds", ")", "{", "return", "checker", ".", "handleError", "(", "'Build not found'", ")", ";", "}", "return", "builds", ";", "}", ",", "this", ".", "handleError", ")", ".", "then", "(", "function", "(", "builds", ")", "{", "var", "successfulBuilds", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "builds", ".", "length", ";", "i", "++", ")", "{", "if", "(", "builds", "[", "i", "]", ".", "isSuccess", "(", ")", ")", "{", "successfulBuilds", "++", ";", "}", "else", "if", "(", "builds", "[", "i", "]", ".", "isFailure", "(", ")", "||", "!", "checker", ".", "getOption", "(", "'retryOnRunning'", ")", ")", "{", "return", "checker", ".", "handleError", "(", "'Invalid status for CircleCI build: \"'", "+", "builds", "[", "i", "]", ".", "getStatus", "(", ")", "+", "'\"'", ")", "}", "}", "if", "(", "successfulBuilds", "===", "builds", ".", "length", ")", "{", "return", "true", ";", "}", "var", "promise", "=", "sleep", "(", "checker", ".", "getOption", "(", "'retryAfter'", ")", ")", ";", "return", "promise", ".", "then", "(", "function", "(", ")", "{", "return", "checker", ".", "checkCommit", "(", "commit", ",", "until", ")", ";", "}", ")", ";", "}", ",", "this", ".", "handleError", ")", ";", "}" ]
Checks the build status of a commit @param {String} commit The commit hash @param {Number} [until] For how long should be check if the build is still running @returns {*|!Promise}
[ "Checks", "the", "build", "status", "of", "a", "commit" ]
a6049fdaffe628f8350c0edcb7528522a4e1e9cc
https://github.com/VividCortex/grunt-circleci/blob/a6049fdaffe628f8350c0edcb7528522a4e1e9cc/tasks/lib/status.js#L84-L131
train
Wandalen/wConsequence
sample/SleepingBarber/Problem.js
clientsGenerator
function clientsGenerator() { var i = 0, len = clientsList.length; for( ; i < len; i++ ) { var client = { name : clientsList[ i ].name }; var time = _.timeNow(); setTimeout(( function( client, time ) { /* sending clients to shop */ this.barberShopArrive( client, time ); }).bind( this, client, time ), clientsList[ i ].arrivedTime ); } }
javascript
function clientsGenerator() { var i = 0, len = clientsList.length; for( ; i < len; i++ ) { var client = { name : clientsList[ i ].name }; var time = _.timeNow(); setTimeout(( function( client, time ) { /* sending clients to shop */ this.barberShopArrive( client, time ); }).bind( this, client, time ), clientsList[ i ].arrivedTime ); } }
[ "function", "clientsGenerator", "(", ")", "{", "var", "i", "=", "0", ",", "len", "=", "clientsList", ".", "length", ";", "for", "(", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "client", "=", "{", "name", ":", "clientsList", "[", "i", "]", ".", "name", "}", ";", "var", "time", "=", "_", ".", "timeNow", "(", ")", ";", "setTimeout", "(", "(", "function", "(", "client", ",", "time", ")", "{", "this", ".", "barberShopArrive", "(", "client", ",", "time", ")", ";", "}", ")", ".", "bind", "(", "this", ",", "client", ",", "time", ")", ",", "clientsList", "[", "i", "]", ".", "arrivedTime", ")", ";", "}", "}" ]
Used to simulate clients visiting hairdresser @param {wConsequence} con - this parameter represent sequence of clients that go to barber shop @returns {wConsequence}
[ "Used", "to", "simulate", "clients", "visiting", "hairdresser" ]
c26863e010ad6f8fdf267f94702f36ad2f05917d
https://github.com/Wandalen/wConsequence/blob/c26863e010ad6f8fdf267f94702f36ad2f05917d/sample/SleepingBarber/Problem.js#L32-L47
train
skerit/protoblast
lib/string_entities.js
loadEntities
function loadEntities() { // Uncompress the base charmap charMap = require('./string_entities_map.js'); HTMLEntities = {}; for (key in charMap) { for (i = 0; i < charMap[key].length; i++) { HTMLEntities[charMap[key][i]] = key; } } }
javascript
function loadEntities() { // Uncompress the base charmap charMap = require('./string_entities_map.js'); HTMLEntities = {}; for (key in charMap) { for (i = 0; i < charMap[key].length; i++) { HTMLEntities[charMap[key][i]] = key; } } }
[ "function", "loadEntities", "(", ")", "{", "charMap", "=", "require", "(", "'./string_entities_map.js'", ")", ";", "HTMLEntities", "=", "{", "}", ";", "for", "(", "key", "in", "charMap", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "charMap", "[", "key", "]", ".", "length", ";", "i", "++", ")", "{", "HTMLEntities", "[", "charMap", "[", "key", "]", "[", "i", "]", "]", "=", "key", ";", "}", "}", "}" ]
Populate HTMLEntities variable with entities @author Jelle De Loecker <[email protected]> @since 0.3.2 @version 0.4.1 @param {String} character The single character to encode @return {String} The encoded char
[ "Populate", "HTMLEntities", "variable", "with", "entities" ]
22f35b05611bd507d380782023179a3f6ec383ae
https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/string_entities.js#L114-L125
train
Kaniwani/KanaWana
src/packages/kanawana/utils/isCharVowel.js
isCharVowel
function isCharVowel(char = '', includeY = true) { if (isEmpty(char)) return false; const regexp = includeY ? /[aeiouy]/ : /[aeiou]/; return char.toLowerCase().charAt(0).search(regexp) !== -1; }
javascript
function isCharVowel(char = '', includeY = true) { if (isEmpty(char)) return false; const regexp = includeY ? /[aeiouy]/ : /[aeiou]/; return char.toLowerCase().charAt(0).search(regexp) !== -1; }
[ "function", "isCharVowel", "(", "char", "=", "''", ",", "includeY", "=", "true", ")", "{", "if", "(", "isEmpty", "(", "char", ")", ")", "return", "false", ";", "const", "regexp", "=", "includeY", "?", "/", "[aeiouy]", "/", ":", "/", "[aeiou]", "/", ";", "return", "char", ".", "toLowerCase", "(", ")", ".", "charAt", "(", "0", ")", ".", "search", "(", "regexp", ")", "!==", "-", "1", ";", "}" ]
Tests a character and an english vowel. Returns true if the char is a vowel. @param {String} char @param {Boolean} [includeY=true] Optional parameter to include y as a vowel in test @return {Boolean}
[ "Tests", "a", "character", "and", "an", "english", "vowel", ".", "Returns", "true", "if", "the", "char", "is", "a", "vowel", "." ]
7084d6c50e68023c225f663f994544f693ff8d3a
https://github.com/Kaniwani/KanaWana/blob/7084d6c50e68023c225f663f994544f693ff8d3a/src/packages/kanawana/utils/isCharVowel.js#L9-L13
train
Kaniwani/KanaWana
src/packages/kanawana/utils/convertFullwidthCharsToASCII.js
convertFullwidthCharsToASCII
function convertFullwidthCharsToASCII(text = '') { const asciiChars = [...text].map((char, index) => { const code = char.charCodeAt(0); const lower = isCharInRange(char, LOWERCASE_FULLWIDTH_START, LOWERCASE_FULLWIDTH_END); const upper = isCharInRange(char, UPPERCASE_FULLWIDTH_START, UPPERCASE_FULLWIDTH_END); if (lower) { return String.fromCharCode((code - LOWERCASE_FULLWIDTH_START) + LOWERCASE_START); } else if (upper) { return String.fromCharCode((code - UPPERCASE_FULLWIDTH_START) + UPPERCASE_START); } return char; }); return asciiChars.join(''); }
javascript
function convertFullwidthCharsToASCII(text = '') { const asciiChars = [...text].map((char, index) => { const code = char.charCodeAt(0); const lower = isCharInRange(char, LOWERCASE_FULLWIDTH_START, LOWERCASE_FULLWIDTH_END); const upper = isCharInRange(char, UPPERCASE_FULLWIDTH_START, UPPERCASE_FULLWIDTH_END); if (lower) { return String.fromCharCode((code - LOWERCASE_FULLWIDTH_START) + LOWERCASE_START); } else if (upper) { return String.fromCharCode((code - UPPERCASE_FULLWIDTH_START) + UPPERCASE_START); } return char; }); return asciiChars.join(''); }
[ "function", "convertFullwidthCharsToASCII", "(", "text", "=", "''", ")", "{", "const", "asciiChars", "=", "[", "...", "text", "]", ".", "map", "(", "(", "char", ",", "index", ")", "=>", "{", "const", "code", "=", "char", ".", "charCodeAt", "(", "0", ")", ";", "const", "lower", "=", "isCharInRange", "(", "char", ",", "LOWERCASE_FULLWIDTH_START", ",", "LOWERCASE_FULLWIDTH_END", ")", ";", "const", "upper", "=", "isCharInRange", "(", "char", ",", "UPPERCASE_FULLWIDTH_START", ",", "UPPERCASE_FULLWIDTH_END", ")", ";", "if", "(", "lower", ")", "{", "return", "String", ".", "fromCharCode", "(", "(", "code", "-", "LOWERCASE_FULLWIDTH_START", ")", "+", "LOWERCASE_START", ")", ";", "}", "else", "if", "(", "upper", ")", "{", "return", "String", ".", "fromCharCode", "(", "(", "code", "-", "UPPERCASE_FULLWIDTH_START", ")", "+", "UPPERCASE_START", ")", ";", "}", "return", "char", ";", "}", ")", ";", "return", "asciiChars", ".", "join", "(", "''", ")", ";", "}" ]
Converts all fullwidth roman letters in string to proper ASCII @param {String} text Full Width roman letters @return {String} ASCII
[ "Converts", "all", "fullwidth", "roman", "letters", "in", "string", "to", "proper", "ASCII" ]
7084d6c50e68023c225f663f994544f693ff8d3a
https://github.com/Kaniwani/KanaWana/blob/7084d6c50e68023c225f663f994544f693ff8d3a/src/packages/kanawana/utils/convertFullwidthCharsToASCII.js#L17-L30
train
juanprietob/clusterpost
src/clusterpost-provider/cronprovider.js
function(){ var view = "_design/searchJob/_view/jobstatus?key=" + JSON.stringify('UPLOADING'); return server.methods.clusterprovider.getView(view) .then(function(docs){ return Promise.map(_.pluck(docs, "value"), server.methods.cronprovider.addJobToUpdateQueue); }) .catch(console.error); }
javascript
function(){ var view = "_design/searchJob/_view/jobstatus?key=" + JSON.stringify('UPLOADING'); return server.methods.clusterprovider.getView(view) .then(function(docs){ return Promise.map(_.pluck(docs, "value"), server.methods.cronprovider.addJobToUpdateQueue); }) .catch(console.error); }
[ "function", "(", ")", "{", "var", "view", "=", "\"_design/searchJob/_view/jobstatus?key=\"", "+", "JSON", ".", "stringify", "(", "'UPLOADING'", ")", ";", "return", "server", ".", "methods", ".", "clusterprovider", ".", "getView", "(", "view", ")", ".", "then", "(", "function", "(", "docs", ")", "{", "return", "Promise", ".", "map", "(", "_", ".", "pluck", "(", "docs", ",", "\"value\"", ")", ",", "server", ".", "methods", ".", "cronprovider", ".", "addJobToUpdateQueue", ")", ";", "}", ")", ".", "catch", "(", "console", ".", "error", ")", ";", "}" ]
Checks for stalled uploading tasks.
[ "Checks", "for", "stalled", "uploading", "tasks", "." ]
5893d83d4f03f35e475b36cdcc975fb5154d12f5
https://github.com/juanprietob/clusterpost/blob/5893d83d4f03f35e475b36cdcc975fb5154d12f5/src/clusterpost-provider/cronprovider.js#L302-L311
train
oortcloud/ddp-srp
srp.js
function (options) { if (!options) // fast path return _defaults; var ret = _.extend({}, _defaults); _.each(['N', 'g', 'k'], function (p) { if (options[p]) { if (typeof options[p] === "string") ret[p] = new BigInteger(options[p], 16); else if (options[p] instanceof BigInteger) ret[p] = options[p]; else throw new Error("Invalid parameter: " + p); } }); if (options.hash) ret.hash = function (x) { return options.hash(x).toLowerCase(); }; if (!options.k && (options.N || options.g || options.hash)) { ret.k = ret.hash(ret.N.toString(16) + ret.g.toString(16)); } return ret; }
javascript
function (options) { if (!options) // fast path return _defaults; var ret = _.extend({}, _defaults); _.each(['N', 'g', 'k'], function (p) { if (options[p]) { if (typeof options[p] === "string") ret[p] = new BigInteger(options[p], 16); else if (options[p] instanceof BigInteger) ret[p] = options[p]; else throw new Error("Invalid parameter: " + p); } }); if (options.hash) ret.hash = function (x) { return options.hash(x).toLowerCase(); }; if (!options.k && (options.N || options.g || options.hash)) { ret.k = ret.hash(ret.N.toString(16) + ret.g.toString(16)); } return ret; }
[ "function", "(", "options", ")", "{", "if", "(", "!", "options", ")", "return", "_defaults", ";", "var", "ret", "=", "_", ".", "extend", "(", "{", "}", ",", "_defaults", ")", ";", "_", ".", "each", "(", "[", "'N'", ",", "'g'", ",", "'k'", "]", ",", "function", "(", "p", ")", "{", "if", "(", "options", "[", "p", "]", ")", "{", "if", "(", "typeof", "options", "[", "p", "]", "===", "\"string\"", ")", "ret", "[", "p", "]", "=", "new", "BigInteger", "(", "options", "[", "p", "]", ",", "16", ")", ";", "else", "if", "(", "options", "[", "p", "]", "instanceof", "BigInteger", ")", "ret", "[", "p", "]", "=", "options", "[", "p", "]", ";", "else", "throw", "new", "Error", "(", "\"Invalid parameter: \"", "+", "p", ")", ";", "}", "}", ")", ";", "if", "(", "options", ".", "hash", ")", "ret", ".", "hash", "=", "function", "(", "x", ")", "{", "return", "options", ".", "hash", "(", "x", ")", ".", "toLowerCase", "(", ")", ";", "}", ";", "if", "(", "!", "options", ".", "k", "&&", "(", "options", ".", "N", "||", "options", ".", "g", "||", "options", ".", "hash", ")", ")", "{", "ret", ".", "k", "=", "ret", ".", "hash", "(", "ret", ".", "N", ".", "toString", "(", "16", ")", "+", "ret", ".", "g", ".", "toString", "(", "16", ")", ")", ";", "}", "return", "ret", ";", "}" ]
Process an options hash to create SRP parameters. Options can include: - hash: Function. Defaults to SHA256. - N: String or BigInteger. Defaults to 1024 bit value from RFC 5054 - g: String or BigInteger. Defaults to 2. - k: String or BigInteger. Defaults to hash(N, g)
[ "Process", "an", "options", "hash", "to", "create", "SRP", "parameters", "." ]
3cb103387cae75abfc2e9a2fb0a66da21efb1244
https://github.com/oortcloud/ddp-srp/blob/3cb103387cae75abfc2e9a2fb0a66da21efb1244/srp.js#L313-L338
train
skerit/protoblast
lib/function_inheritance.js
doMultipleInheritance
function doMultipleInheritance(new_constructor, parent_constructor, proto) { var more; if (proto == null) { proto = Object.create(new_constructor.prototype); } // See if this goes even deeper FIRST // (older properties could get overwritten) more = Object.getPrototypeOf(parent_constructor.prototype); if (more.constructor !== Object) { // Recurse with the earlier constructor doMultipleInheritance(new_constructor, more.constructor, proto); } // Inject the enumerable and non-enumerable properties of the parent Collection.Object.inject(proto, parent_constructor.prototype); return proto; }
javascript
function doMultipleInheritance(new_constructor, parent_constructor, proto) { var more; if (proto == null) { proto = Object.create(new_constructor.prototype); } // See if this goes even deeper FIRST // (older properties could get overwritten) more = Object.getPrototypeOf(parent_constructor.prototype); if (more.constructor !== Object) { // Recurse with the earlier constructor doMultipleInheritance(new_constructor, more.constructor, proto); } // Inject the enumerable and non-enumerable properties of the parent Collection.Object.inject(proto, parent_constructor.prototype); return proto; }
[ "function", "doMultipleInheritance", "(", "new_constructor", ",", "parent_constructor", ",", "proto", ")", "{", "var", "more", ";", "if", "(", "proto", "==", "null", ")", "{", "proto", "=", "Object", ".", "create", "(", "new_constructor", ".", "prototype", ")", ";", "}", "more", "=", "Object", ".", "getPrototypeOf", "(", "parent_constructor", ".", "prototype", ")", ";", "if", "(", "more", ".", "constructor", "!==", "Object", ")", "{", "doMultipleInheritance", "(", "new_constructor", ",", "more", ".", "constructor", ",", "proto", ")", ";", "}", "Collection", ".", "Object", ".", "inject", "(", "proto", ",", "parent_constructor", ".", "prototype", ")", ";", "return", "proto", ";", "}" ]
Do multiple inheritance @author Jelle De Loecker <[email protected]> @since 0.3.6 @version 0.3.6 @param {Function} new_constructor @param {Function} parent_constructor @param {Object} proto
[ "Do", "multiple", "inheritance" ]
22f35b05611bd507d380782023179a3f6ec383ae
https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/function_inheritance.js#L99-L120
train
skerit/protoblast
lib/function_inheritance.js
getNamespace
function getNamespace(namespace) { var result, name, data; // Try getting the namespace if (!namespace) { result = Blast.Classes; } else { result = Obj.path(Blast.Classes, namespace); } if (result == null) { name = namespace.split('.'); name = name[name.length - 1]; result = Collection.Function.create(name, function() { var instance; if (!result[name]) { throw new Error('Could not find class "' + name + '" in namespace "' + namespace + '"'); } // Create the object instance instance = Object.create(result[name].prototype); // Apply the constructor result[name].apply(instance, arguments); return instance; }); // Add a getter to get the main class of this namespace Blast.defineGet(result, 'main_class', function getMainClass() { return result[name]; }); // Remember this is a namespace result.is_namespace = true; // Create the namespace object Obj.setPath(Blast.Classes, namespace, result); // Emit the creation of this namespace if (Blast.emit) { data = { type : 'namespace', namespace : namespace }; Blast.emit(data, namespace); } } return result; }
javascript
function getNamespace(namespace) { var result, name, data; // Try getting the namespace if (!namespace) { result = Blast.Classes; } else { result = Obj.path(Blast.Classes, namespace); } if (result == null) { name = namespace.split('.'); name = name[name.length - 1]; result = Collection.Function.create(name, function() { var instance; if (!result[name]) { throw new Error('Could not find class "' + name + '" in namespace "' + namespace + '"'); } // Create the object instance instance = Object.create(result[name].prototype); // Apply the constructor result[name].apply(instance, arguments); return instance; }); // Add a getter to get the main class of this namespace Blast.defineGet(result, 'main_class', function getMainClass() { return result[name]; }); // Remember this is a namespace result.is_namespace = true; // Create the namespace object Obj.setPath(Blast.Classes, namespace, result); // Emit the creation of this namespace if (Blast.emit) { data = { type : 'namespace', namespace : namespace }; Blast.emit(data, namespace); } } return result; }
[ "function", "getNamespace", "(", "namespace", ")", "{", "var", "result", ",", "name", ",", "data", ";", "if", "(", "!", "namespace", ")", "{", "result", "=", "Blast", ".", "Classes", ";", "}", "else", "{", "result", "=", "Obj", ".", "path", "(", "Blast", ".", "Classes", ",", "namespace", ")", ";", "}", "if", "(", "result", "==", "null", ")", "{", "name", "=", "namespace", ".", "split", "(", "'.'", ")", ";", "name", "=", "name", "[", "name", ".", "length", "-", "1", "]", ";", "result", "=", "Collection", ".", "Function", ".", "create", "(", "name", ",", "function", "(", ")", "{", "var", "instance", ";", "if", "(", "!", "result", "[", "name", "]", ")", "{", "throw", "new", "Error", "(", "'Could not find class \"'", "+", "name", "+", "'\" in namespace \"'", "+", "namespace", "+", "'\"'", ")", ";", "}", "instance", "=", "Object", ".", "create", "(", "result", "[", "name", "]", ".", "prototype", ")", ";", "result", "[", "name", "]", ".", "apply", "(", "instance", ",", "arguments", ")", ";", "return", "instance", ";", "}", ")", ";", "Blast", ".", "defineGet", "(", "result", ",", "'main_class'", ",", "function", "getMainClass", "(", ")", "{", "return", "result", "[", "name", "]", ";", "}", ")", ";", "result", ".", "is_namespace", "=", "true", ";", "Obj", ".", "setPath", "(", "Blast", ".", "Classes", ",", "namespace", ",", "result", ")", ";", "if", "(", "Blast", ".", "emit", ")", "{", "data", "=", "{", "type", ":", "'namespace'", ",", "namespace", ":", "namespace", "}", ";", "Blast", ".", "emit", "(", "data", ",", "namespace", ")", ";", "}", "}", "return", "result", ";", "}" ]
Get a namespace object, or create it if it doesn't exist @author Jelle De Loecker <[email protected]> @since 0.2.1 @version 0.6.5 @param {String} namespace @return {Object}
[ "Get", "a", "namespace", "object", "or", "create", "it", "if", "it", "doesn", "t", "exist" ]
22f35b05611bd507d380782023179a3f6ec383ae
https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/function_inheritance.js#L133-L189
train
skerit/protoblast
lib/function_inheritance.js
getClass
function getClass(path) { var pieces = path.split('.'), result; result = Obj.path(Blast.Classes, path); if (typeof result == 'function') { if (result.is_namespace) { result = result[result.name]; } return result; } result = Obj.path(Blast.Globals, path); if (typeof result == 'function') { if (result.is_namespace) { result = result[result.name]; } return result; } }
javascript
function getClass(path) { var pieces = path.split('.'), result; result = Obj.path(Blast.Classes, path); if (typeof result == 'function') { if (result.is_namespace) { result = result[result.name]; } return result; } result = Obj.path(Blast.Globals, path); if (typeof result == 'function') { if (result.is_namespace) { result = result[result.name]; } return result; } }
[ "function", "getClass", "(", "path", ")", "{", "var", "pieces", "=", "path", ".", "split", "(", "'.'", ")", ",", "result", ";", "result", "=", "Obj", ".", "path", "(", "Blast", ".", "Classes", ",", "path", ")", ";", "if", "(", "typeof", "result", "==", "'function'", ")", "{", "if", "(", "result", ".", "is_namespace", ")", "{", "result", "=", "result", "[", "result", ".", "name", "]", ";", "}", "return", "result", ";", "}", "result", "=", "Obj", ".", "path", "(", "Blast", ".", "Globals", ",", "path", ")", ";", "if", "(", "typeof", "result", "==", "'function'", ")", "{", "if", "(", "result", ".", "is_namespace", ")", "{", "result", "=", "result", "[", "result", ".", "name", "]", ";", "}", "return", "result", ";", "}", "}" ]
Get a class @author Jelle De Loecker <[email protected]> @since 0.5.0 @version 0.5.0 @param {String} path @return {Function}
[ "Get", "a", "class" ]
22f35b05611bd507d380782023179a3f6ec383ae
https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/function_inheritance.js#L204-L228
train
skerit/protoblast
lib/function_inheritance.js
getClassPathInfo
function getClassPathInfo(path) { var result = {}, namespace, name, temp; // See what's there temp = Obj.path(Blast.Classes, path); // Is there nothing at the current path? if (!temp) { if (path.indexOf('.') > -1) { // Split the path temp = path.split('.'); // The last part is actually the name of the class name = temp.pop(); // The namespace is what's left over namespace = temp.join('.'); } else { // There is no real "path", it's just the name name = path; // So there is no namespace namespace = ''; } } else { // Is the found function a namespace if (temp && temp.is_namespace) { // The name of the class is the same as the namespace name = temp.name; // The namespace path is the entire path namespace = path; // The full path actually needs the name again path = path + '.' + name; } else if (temp) { // We found a class function // The namespace should be on this class namespace = temp.namespace || ''; // The name is the name of the found class name = temp.name; } else { namespace = ''; name = path; } } result.name = name; result.namespace = namespace; result.path = path; result.class = Obj.path(Blast.Classes, path); result.namespace_wrapper = Obj.path(Blast.Classes, namespace); if (!namespace && !result.class && typeof Blast.Globals[name] == 'function') { result.class = Blast.Globals[name]; } if (!result.namespace_wrapper) { result.namespace_wrapper = getNamespace(namespace); } return result; }
javascript
function getClassPathInfo(path) { var result = {}, namespace, name, temp; // See what's there temp = Obj.path(Blast.Classes, path); // Is there nothing at the current path? if (!temp) { if (path.indexOf('.') > -1) { // Split the path temp = path.split('.'); // The last part is actually the name of the class name = temp.pop(); // The namespace is what's left over namespace = temp.join('.'); } else { // There is no real "path", it's just the name name = path; // So there is no namespace namespace = ''; } } else { // Is the found function a namespace if (temp && temp.is_namespace) { // The name of the class is the same as the namespace name = temp.name; // The namespace path is the entire path namespace = path; // The full path actually needs the name again path = path + '.' + name; } else if (temp) { // We found a class function // The namespace should be on this class namespace = temp.namespace || ''; // The name is the name of the found class name = temp.name; } else { namespace = ''; name = path; } } result.name = name; result.namespace = namespace; result.path = path; result.class = Obj.path(Blast.Classes, path); result.namespace_wrapper = Obj.path(Blast.Classes, namespace); if (!namespace && !result.class && typeof Blast.Globals[name] == 'function') { result.class = Blast.Globals[name]; } if (!result.namespace_wrapper) { result.namespace_wrapper = getNamespace(namespace); } return result; }
[ "function", "getClassPathInfo", "(", "path", ")", "{", "var", "result", "=", "{", "}", ",", "namespace", ",", "name", ",", "temp", ";", "temp", "=", "Obj", ".", "path", "(", "Blast", ".", "Classes", ",", "path", ")", ";", "if", "(", "!", "temp", ")", "{", "if", "(", "path", ".", "indexOf", "(", "'.'", ")", ">", "-", "1", ")", "{", "temp", "=", "path", ".", "split", "(", "'.'", ")", ";", "name", "=", "temp", ".", "pop", "(", ")", ";", "namespace", "=", "temp", ".", "join", "(", "'.'", ")", ";", "}", "else", "{", "name", "=", "path", ";", "namespace", "=", "''", ";", "}", "}", "else", "{", "if", "(", "temp", "&&", "temp", ".", "is_namespace", ")", "{", "name", "=", "temp", ".", "name", ";", "namespace", "=", "path", ";", "path", "=", "path", "+", "'.'", "+", "name", ";", "}", "else", "if", "(", "temp", ")", "{", "namespace", "=", "temp", ".", "namespace", "||", "''", ";", "name", "=", "temp", ".", "name", ";", "}", "else", "{", "namespace", "=", "''", ";", "name", "=", "path", ";", "}", "}", "result", ".", "name", "=", "name", ";", "result", ".", "namespace", "=", "namespace", ";", "result", ".", "path", "=", "path", ";", "result", ".", "class", "=", "Obj", ".", "path", "(", "Blast", ".", "Classes", ",", "path", ")", ";", "result", ".", "namespace_wrapper", "=", "Obj", ".", "path", "(", "Blast", ".", "Classes", ",", "namespace", ")", ";", "if", "(", "!", "namespace", "&&", "!", "result", ".", "class", "&&", "typeof", "Blast", ".", "Globals", "[", "name", "]", "==", "'function'", ")", "{", "result", ".", "class", "=", "Blast", ".", "Globals", "[", "name", "]", ";", "}", "if", "(", "!", "result", ".", "namespace_wrapper", ")", "{", "result", ".", "namespace_wrapper", "=", "getNamespace", "(", "namespace", ")", ";", "}", "return", "result", ";", "}" ]
Get path information @author Jelle De Loecker <[email protected]> @since 0.5.0 @version 0.5.0 @param {String} path @return {Object}
[ "Get", "path", "information" ]
22f35b05611bd507d380782023179a3f6ec383ae
https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/function_inheritance.js#L241-L311
train
skerit/protoblast
lib/function_inheritance.js
doConstitutors
function doConstitutors(constructor) { var waiting, tasks, i; if (has_constituted.get(constructor)) { return; } has_constituted.set(constructor, true); tasks = constructor.constitutors; if (tasks) { for (i = 0; i < tasks.length; i++) { doConstructorTask(constructor, tasks[i]); } } waiting = waiting_children.get(constructor); if (!waiting || !waiting.length) { return; } for (i = 0; i < waiting.length; i++) { doConstitutors(waiting[i]); } }
javascript
function doConstitutors(constructor) { var waiting, tasks, i; if (has_constituted.get(constructor)) { return; } has_constituted.set(constructor, true); tasks = constructor.constitutors; if (tasks) { for (i = 0; i < tasks.length; i++) { doConstructorTask(constructor, tasks[i]); } } waiting = waiting_children.get(constructor); if (!waiting || !waiting.length) { return; } for (i = 0; i < waiting.length; i++) { doConstitutors(waiting[i]); } }
[ "function", "doConstitutors", "(", "constructor", ")", "{", "var", "waiting", ",", "tasks", ",", "i", ";", "if", "(", "has_constituted", ".", "get", "(", "constructor", ")", ")", "{", "return", ";", "}", "has_constituted", ".", "set", "(", "constructor", ",", "true", ")", ";", "tasks", "=", "constructor", ".", "constitutors", ";", "if", "(", "tasks", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "tasks", ".", "length", ";", "i", "++", ")", "{", "doConstructorTask", "(", "constructor", ",", "tasks", "[", "i", "]", ")", ";", "}", "}", "waiting", "=", "waiting_children", ".", "get", "(", "constructor", ")", ";", "if", "(", "!", "waiting", "||", "!", "waiting", ".", "length", ")", "{", "return", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "waiting", ".", "length", ";", "i", "++", ")", "{", "doConstitutors", "(", "waiting", "[", "i", "]", ")", ";", "}", "}" ]
Do the constitutors for the given constructor @author Jelle De Loecker <[email protected]> @since 0.3.6 @version 0.3.6 @param {Function} constructor
[ "Do", "the", "constitutors", "for", "the", "given", "constructor" ]
22f35b05611bd507d380782023179a3f6ec383ae
https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/function_inheritance.js#L667-L696
train
skerit/protoblast
lib/function_inheritance.js
doConstructorTask
function doConstructorTask(constructor, task) { var finished; finished = finished_constitutors.get(constructor); if (!finished) { finished = []; finished_constitutors.set(constructor, finished); } if (finished.indexOf(task) == -1) { task.call(constructor); finished.push(task); } }
javascript
function doConstructorTask(constructor, task) { var finished; finished = finished_constitutors.get(constructor); if (!finished) { finished = []; finished_constitutors.set(constructor, finished); } if (finished.indexOf(task) == -1) { task.call(constructor); finished.push(task); } }
[ "function", "doConstructorTask", "(", "constructor", ",", "task", ")", "{", "var", "finished", ";", "finished", "=", "finished_constitutors", ".", "get", "(", "constructor", ")", ";", "if", "(", "!", "finished", ")", "{", "finished", "=", "[", "]", ";", "finished_constitutors", ".", "set", "(", "constructor", ",", "finished", ")", ";", "}", "if", "(", "finished", ".", "indexOf", "(", "task", ")", "==", "-", "1", ")", "{", "task", ".", "call", "(", "constructor", ")", ";", "finished", ".", "push", "(", "task", ")", ";", "}", "}" ]
Do the given task for a given constructor @author Jelle De Loecker <[email protected]> @since 0.3.6 @version 0.3.6 @param {Function} constructor @param {Function} task
[ "Do", "the", "given", "task", "for", "a", "given", "constructor" ]
22f35b05611bd507d380782023179a3f6ec383ae
https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/function_inheritance.js#L719-L734
train
skerit/protoblast
lib/function_inheritance.js
applyDecoration
function applyDecoration(constructor, key, options) { if (options.kind == 'method') { return Fn.setMethod(constructor, key, options.descriptor); } throw new Error('Decorating ' + options.kind + ' is not yet implemented'); }
javascript
function applyDecoration(constructor, key, options) { if (options.kind == 'method') { return Fn.setMethod(constructor, key, options.descriptor); } throw new Error('Decorating ' + options.kind + ' is not yet implemented'); }
[ "function", "applyDecoration", "(", "constructor", ",", "key", ",", "options", ")", "{", "if", "(", "options", ".", "kind", "==", "'method'", ")", "{", "return", "Fn", ".", "setMethod", "(", "constructor", ",", "key", ",", "options", ".", "descriptor", ")", ";", "}", "throw", "new", "Error", "(", "'Decorating '", "+", "options", ".", "kind", "+", "' is not yet implemented'", ")", ";", "}" ]
Apply a decoration object @author Jelle De Loecker <[email protected]> @since 0.6.0 @version 0.6.0 @param {Function} constructor @param {String|Symbol} key @param {Object} options
[ "Apply", "a", "decoration", "object" ]
22f35b05611bd507d380782023179a3f6ec383ae
https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/function_inheritance.js#L1170-L1177
train
skerit/protoblast
lib/function_inheritance.js
setStaticProperty
function setStaticProperty(key, getter, setter, inherit) { return Fn.setStaticProperty(this, key, getter, setter, inherit); }
javascript
function setStaticProperty(key, getter, setter, inherit) { return Fn.setStaticProperty(this, key, getter, setter, inherit); }
[ "function", "setStaticProperty", "(", "key", ",", "getter", ",", "setter", ",", "inherit", ")", "{", "return", "Fn", ".", "setStaticProperty", "(", "this", ",", "key", ",", "getter", ",", "setter", ",", "inherit", ")", ";", "}" ]
Set a static getter property @author Jelle De Loecker <[email protected]> @since 0.1.4 @version 0.1.4 @param {String} key Name to use (defaults to method name) @param {Function} getter Function that returns a value OR value @param {Function} setter Function that sets the value @param {Boolean} inherit Let children inherit this (true)
[ "Set", "a", "static", "getter", "property" ]
22f35b05611bd507d380782023179a3f6ec383ae
https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/function_inheritance.js#L1501-L1503
train
skerit/protoblast
lib/function_inheritance.js
compose
function compose(key, compositor, traits) { return Fn.compose(this.prototype, key, compositor, traits); }
javascript
function compose(key, compositor, traits) { return Fn.compose(this.prototype, key, compositor, traits); }
[ "function", "compose", "(", "key", ",", "compositor", ",", "traits", ")", "{", "return", "Fn", ".", "compose", "(", "this", ".", "prototype", ",", "key", ",", "compositor", ",", "traits", ")", ";", "}" ]
Compose a class as a property @author Jelle De Loecker <[email protected]> @since 0.1.4 @version 0.1.4 @param {String} key Name to use @param {Function} compositor @param {Object} traits
[ "Compose", "a", "class", "as", "a", "property" ]
22f35b05611bd507d380782023179a3f6ec383ae
https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/function_inheritance.js#L1605-L1607
train
skerit/protoblast
lib/function_inheritance.js
ensureConstructorStaticMethods
function ensureConstructorStaticMethods(newConstructor) { if (typeof newConstructor.setMethod !== 'function') { Blast.defineValue(newConstructor, protoPrepareStaticProperty); Blast.defineValue(newConstructor, protoSetStaticProperty); Blast.defineValue(newConstructor, protoPrepareProperty); Blast.defineValue(newConstructor, protoEnforceProperty); Blast.defineValue(newConstructor, protoDecorateMethod); Blast.defineValue(newConstructor, protoStaticCompose); Blast.defineValue(newConstructor, protoGetChildren); Blast.defineValue(newConstructor, protoSetProperty); Blast.defineValue(newConstructor, protoConstitute); Blast.defineValue(newConstructor, protoSetStatic); Blast.defineValue(newConstructor, protoSetMethod); Blast.defineValue(newConstructor, protoCompose); if (newConstructor.extend == null) { Blast.defineValue(newConstructor, 'extend', protoExtend); } } }
javascript
function ensureConstructorStaticMethods(newConstructor) { if (typeof newConstructor.setMethod !== 'function') { Blast.defineValue(newConstructor, protoPrepareStaticProperty); Blast.defineValue(newConstructor, protoSetStaticProperty); Blast.defineValue(newConstructor, protoPrepareProperty); Blast.defineValue(newConstructor, protoEnforceProperty); Blast.defineValue(newConstructor, protoDecorateMethod); Blast.defineValue(newConstructor, protoStaticCompose); Blast.defineValue(newConstructor, protoGetChildren); Blast.defineValue(newConstructor, protoSetProperty); Blast.defineValue(newConstructor, protoConstitute); Blast.defineValue(newConstructor, protoSetStatic); Blast.defineValue(newConstructor, protoSetMethod); Blast.defineValue(newConstructor, protoCompose); if (newConstructor.extend == null) { Blast.defineValue(newConstructor, 'extend', protoExtend); } } }
[ "function", "ensureConstructorStaticMethods", "(", "newConstructor", ")", "{", "if", "(", "typeof", "newConstructor", ".", "setMethod", "!==", "'function'", ")", "{", "Blast", ".", "defineValue", "(", "newConstructor", ",", "protoPrepareStaticProperty", ")", ";", "Blast", ".", "defineValue", "(", "newConstructor", ",", "protoSetStaticProperty", ")", ";", "Blast", ".", "defineValue", "(", "newConstructor", ",", "protoPrepareProperty", ")", ";", "Blast", ".", "defineValue", "(", "newConstructor", ",", "protoEnforceProperty", ")", ";", "Blast", ".", "defineValue", "(", "newConstructor", ",", "protoDecorateMethod", ")", ";", "Blast", ".", "defineValue", "(", "newConstructor", ",", "protoStaticCompose", ")", ";", "Blast", ".", "defineValue", "(", "newConstructor", ",", "protoGetChildren", ")", ";", "Blast", ".", "defineValue", "(", "newConstructor", ",", "protoSetProperty", ")", ";", "Blast", ".", "defineValue", "(", "newConstructor", ",", "protoConstitute", ")", ";", "Blast", ".", "defineValue", "(", "newConstructor", ",", "protoSetStatic", ")", ";", "Blast", ".", "defineValue", "(", "newConstructor", ",", "protoSetMethod", ")", ";", "Blast", ".", "defineValue", "(", "newConstructor", ",", "protoCompose", ")", ";", "if", "(", "newConstructor", ".", "extend", "==", "null", ")", "{", "Blast", ".", "defineValue", "(", "newConstructor", ",", "'extend'", ",", "protoExtend", ")", ";", "}", "}", "}" ]
Ensure a constructor has the required static methods @author Jelle De Loecker <[email protected]> @since 0.3.4 @version 0.3.4 @param {Function} newConstructor
[ "Ensure", "a", "constructor", "has", "the", "required", "static", "methods" ]
22f35b05611bd507d380782023179a3f6ec383ae
https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/function_inheritance.js#L1661-L1681
train
stezu/node-stream
lib/modifiers/map.js
map
function map(transform) { var cb = makeAsync(transform, 2); return through.obj(function (value, enc, next) { cb(value, next); }); }
javascript
function map(transform) { var cb = makeAsync(transform, 2); return through.obj(function (value, enc, next) { cb(value, next); }); }
[ "function", "map", "(", "transform", ")", "{", "var", "cb", "=", "makeAsync", "(", "transform", ",", "2", ")", ";", "return", "through", ".", "obj", "(", "function", "(", "value", ",", "enc", ",", "next", ")", "{", "cb", "(", "value", ",", "next", ")", ";", "}", ")", ";", "}" ]
Creates a new stream with the results of calling the provided function on every item in the stream. Similar to Array.map... but on a stream. @static @since 1.0.0 @category Modifiers @param {Function} transform - Function that returns a new element on the stream. Takes one argument, the value of the item at this position in the stream. @returns {Stream.Transform} - A transform stream with the modified values. @example // For a simple find/replace, you could do something like the following. Assuming // "example.txt" is a file with the text "the text has periods. because, english.", // you could replace each period with a comma like so: fs.createReadStream('example.txt') .pipe(nodeStream.map(value => value.toString().replace('.', ','))); // The resulting stream will have the value "the text has periods, because, english,". @example // It is also possible to transform a stream asynchronously for more complex actions. // Note: The signature of the function that you pass as the callback is important. It // MUST have *two* parameters. // Assuming "filenames.txt" is a newline-separated list of file names, you could // create a new stream with their contents by doing something like the following: fs.createReadStream('filenames.txt') .pipe(nodeStream.split()) // split on new lines .pipe(nodeStream.map((value, next) => { fs.readFile(value, next); })); // The resulting stream will contain the text of each file. Note: If `next` is called // with an error as the first argument, the stream will error. This is typical behavior // for node callbacks.
[ "Creates", "a", "new", "stream", "with", "the", "results", "of", "calling", "the", "provided", "function", "on", "every", "item", "in", "the", "stream", ".", "Similar", "to", "Array", ".", "map", "...", "but", "on", "a", "stream", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/modifiers/map.js#L46-L52
train
stezu/node-stream
lib/modifiers/reduce.js
reduce
function reduce(reducer, initialValue) { var accumulator = initialValue; var cb = makeAsync(reducer, 3); return through.obj( function transform(chunk, enc, next) { cb(accumulator, chunk, function (err, result) { accumulator = result; next(err); }); }, function Flush(next) { this.push(accumulator); next(); } ); }
javascript
function reduce(reducer, initialValue) { var accumulator = initialValue; var cb = makeAsync(reducer, 3); return through.obj( function transform(chunk, enc, next) { cb(accumulator, chunk, function (err, result) { accumulator = result; next(err); }); }, function Flush(next) { this.push(accumulator); next(); } ); }
[ "function", "reduce", "(", "reducer", ",", "initialValue", ")", "{", "var", "accumulator", "=", "initialValue", ";", "var", "cb", "=", "makeAsync", "(", "reducer", ",", "3", ")", ";", "return", "through", ".", "obj", "(", "function", "transform", "(", "chunk", ",", "enc", ",", "next", ")", "{", "cb", "(", "accumulator", ",", "chunk", ",", "function", "(", "err", ",", "result", ")", "{", "accumulator", "=", "result", ";", "next", "(", "err", ")", ";", "}", ")", ";", "}", ",", "function", "Flush", "(", "next", ")", "{", "this", ".", "push", "(", "accumulator", ")", ";", "next", "(", ")", ";", "}", ")", ";", "}" ]
Creates a new stream with a single item that's produced by calling a reducer with each item of the original stream. Similar to Array.reduce... but on a stream. @static @since 1.0.0 @category Modifiers @param {Function} reducer - Function that reduces items in the stream. Takes two arguments: the current value of the reduction, and the value of the item at this position in the stream. @param {*} [initialValue] - Value to use as the first argument to the first call of the `reducer`. @returns {Stream.Transform} - A transform stream that results from the reduction. @example // If you wanted to determine the content-length of a stream, you could do something like // the following. Assuming "example.txt" is a large file, you could determine it's length // by doing the following: fs.createReadStream('example.txt') .pipe(nodeStream.reduce((length, value) => length + value.length), 0); // The resulting stream will have an integer value representing the length of "example.txt". @example // It is also possible to reduce a stream asynchronously for more complex actions. // Note: The signature of the function that you pass as the callback is important. It // MUST have *three* parameters. // Assuming "twitterers.txt" is a newline-separated list of your favorite tweeters, you // could identify which is the most recently active by using the Twitter API: fs.createReadStream('twitterers.txt') .pipe(nodeStream.split()) // split on new lines .pipe(nodeStream.reduce((memo, user, next) => { twit.get('search/tweets', { q: `from:${user}`, count: 1 }, (err, data) => { // Error the stream since this request failed if (err) { return next(err); } // This is the first iteration of the reduction, so we automatically save the tweet if (!memo) { return next(null, data); } // This tweet is the most recent so far, save it for later if (new Date(data.statuses.created_at) > new Date(memo.statuses.created_at)) { return next(null, data); } // The tweet we have saved is still the most recent next(null, memo); }); })); // The resulting stream will contain the most recent tweet of the users in the list. // Note: If `next` is called with an error as the first argument, the stream will error. // This is typical behavior for node callbacks.
[ "Creates", "a", "new", "stream", "with", "a", "single", "item", "that", "s", "produced", "by", "calling", "a", "reducer", "with", "each", "item", "of", "the", "original", "stream", ".", "Similar", "to", "Array", ".", "reduce", "...", "but", "on", "a", "stream", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/modifiers/reduce.js#L68-L85
train
nodesource/ah-deep-clone
ah-deep-clone.js
copy
function copy(acc, k) { const val = x[k] let cpy if (Array.isArray(val)) { cpy = val.slice(0) } else { cpy = val } acc[k] = cpy return acc }
javascript
function copy(acc, k) { const val = x[k] let cpy if (Array.isArray(val)) { cpy = val.slice(0) } else { cpy = val } acc[k] = cpy return acc }
[ "function", "copy", "(", "acc", ",", "k", ")", "{", "const", "val", "=", "x", "[", "k", "]", "let", "cpy", "if", "(", "Array", ".", "isArray", "(", "val", ")", ")", "{", "cpy", "=", "val", ".", "slice", "(", "0", ")", "}", "else", "{", "cpy", "=", "val", "}", "acc", "[", "k", "]", "=", "cpy", "return", "acc", "}" ]
so far we only expect to deal with the following property types shallow Array, String, Number
[ "so", "far", "we", "only", "expect", "to", "deal", "with", "the", "following", "property", "types", "shallow", "Array", "String", "Number" ]
c532d41b9076582e6f91b415e629c90a6acce531
https://github.com/nodesource/ah-deep-clone/blob/c532d41b9076582e6f91b415e629c90a6acce531/ah-deep-clone.js#L4-L14
train
NogsMPLS/react-component-styleguide
lib/rcs.js
RCS
function RCS (input, opts) { opts = opts || {} this.log = require('./logger')('rcs-lib', {debug: opts.verbose || false}) var config // If feeding in a direct config object if (opts.config !== null && typeof opts.config === 'object') { config = opts.config } else { config = this.readConfig(opts.config) } opts = assign(config, opts) opts.output = path.resolve(process.cwd(), (opts.output || 'styleguide').replace(/\/+$/, '')) opts.title = opts.title || 'Style Guide' opts.root = opts.root ? path.normalize('/' + opts.root.replace(/\/+$/, '')) : null opts.pushstate = opts.pushstate || false opts.files = opts.files || [] opts.babelConfig = opts.babelConfig || null opts.webpackConfig = opts.webpackConfig || {} // Run on port 3000 if mode enabled but port not specified if (opts.dev && opts.dev === true) { opts.dev = 3000 } else if (!opts.dev) { opts.dev = false } var globOptions = opts.ignore ? {realpath: true, ignore: opts.ignore } : {realpath: true}; opts.styleComponents = opts.styleComponents ? glob.sync(opts.styleComponents, globOptions) : false; this.input = glob .sync(input, {realpath: true}) .filter(function (file) { var readFile = fs.readFileSync(file); try { if (reactDocGenModule.parse(readFile)) { return true } } catch (e) { return false } }); opts['reactDocgen'] = opts['reactDocgen'] || {} if (!opts['reactDocgen'].files) { opts['reactDocgen'].files = [input] } this.opts = opts // files to parse for react-docgen this.reactDocGenFiles = this.getReactPropDocFiles() // Cached files to include into the styleguide app this.cssFiles = this.extractFiles('.css') this.jsFiles = this.extractFiles('.js') this.appTemplate = fs.readFileSync(path.resolve(__dirname, './fixtures/index.html.mustache'), 'utf-8') this.stageDir = path.resolve(__dirname, '../rcs-tmp') }
javascript
function RCS (input, opts) { opts = opts || {} this.log = require('./logger')('rcs-lib', {debug: opts.verbose || false}) var config // If feeding in a direct config object if (opts.config !== null && typeof opts.config === 'object') { config = opts.config } else { config = this.readConfig(opts.config) } opts = assign(config, opts) opts.output = path.resolve(process.cwd(), (opts.output || 'styleguide').replace(/\/+$/, '')) opts.title = opts.title || 'Style Guide' opts.root = opts.root ? path.normalize('/' + opts.root.replace(/\/+$/, '')) : null opts.pushstate = opts.pushstate || false opts.files = opts.files || [] opts.babelConfig = opts.babelConfig || null opts.webpackConfig = opts.webpackConfig || {} // Run on port 3000 if mode enabled but port not specified if (opts.dev && opts.dev === true) { opts.dev = 3000 } else if (!opts.dev) { opts.dev = false } var globOptions = opts.ignore ? {realpath: true, ignore: opts.ignore } : {realpath: true}; opts.styleComponents = opts.styleComponents ? glob.sync(opts.styleComponents, globOptions) : false; this.input = glob .sync(input, {realpath: true}) .filter(function (file) { var readFile = fs.readFileSync(file); try { if (reactDocGenModule.parse(readFile)) { return true } } catch (e) { return false } }); opts['reactDocgen'] = opts['reactDocgen'] || {} if (!opts['reactDocgen'].files) { opts['reactDocgen'].files = [input] } this.opts = opts // files to parse for react-docgen this.reactDocGenFiles = this.getReactPropDocFiles() // Cached files to include into the styleguide app this.cssFiles = this.extractFiles('.css') this.jsFiles = this.extractFiles('.js') this.appTemplate = fs.readFileSync(path.resolve(__dirname, './fixtures/index.html.mustache'), 'utf-8') this.stageDir = path.resolve(__dirname, '../rcs-tmp') }
[ "function", "RCS", "(", "input", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", "this", ".", "log", "=", "require", "(", "'./logger'", ")", "(", "'rcs-lib'", ",", "{", "debug", ":", "opts", ".", "verbose", "||", "false", "}", ")", "var", "config", "if", "(", "opts", ".", "config", "!==", "null", "&&", "typeof", "opts", ".", "config", "===", "'object'", ")", "{", "config", "=", "opts", ".", "config", "}", "else", "{", "config", "=", "this", ".", "readConfig", "(", "opts", ".", "config", ")", "}", "opts", "=", "assign", "(", "config", ",", "opts", ")", "opts", ".", "output", "=", "path", ".", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "(", "opts", ".", "output", "||", "'styleguide'", ")", ".", "replace", "(", "/", "\\/+$", "/", ",", "''", ")", ")", "opts", ".", "title", "=", "opts", ".", "title", "||", "'Style Guide'", "opts", ".", "root", "=", "opts", ".", "root", "?", "path", ".", "normalize", "(", "'/'", "+", "opts", ".", "root", ".", "replace", "(", "/", "\\/+$", "/", ",", "''", ")", ")", ":", "null", "opts", ".", "pushstate", "=", "opts", ".", "pushstate", "||", "false", "opts", ".", "files", "=", "opts", ".", "files", "||", "[", "]", "opts", ".", "babelConfig", "=", "opts", ".", "babelConfig", "||", "null", "opts", ".", "webpackConfig", "=", "opts", ".", "webpackConfig", "||", "{", "}", "if", "(", "opts", ".", "dev", "&&", "opts", ".", "dev", "===", "true", ")", "{", "opts", ".", "dev", "=", "3000", "}", "else", "if", "(", "!", "opts", ".", "dev", ")", "{", "opts", ".", "dev", "=", "false", "}", "var", "globOptions", "=", "opts", ".", "ignore", "?", "{", "realpath", ":", "true", ",", "ignore", ":", "opts", ".", "ignore", "}", ":", "{", "realpath", ":", "true", "}", ";", "opts", ".", "styleComponents", "=", "opts", ".", "styleComponents", "?", "glob", ".", "sync", "(", "opts", ".", "styleComponents", ",", "globOptions", ")", ":", "false", ";", "this", ".", "input", "=", "glob", ".", "sync", "(", "input", ",", "{", "realpath", ":", "true", "}", ")", ".", "filter", "(", "function", "(", "file", ")", "{", "var", "readFile", "=", "fs", ".", "readFileSync", "(", "file", ")", ";", "try", "{", "if", "(", "reactDocGenModule", ".", "parse", "(", "readFile", ")", ")", "{", "return", "true", "}", "}", "catch", "(", "e", ")", "{", "return", "false", "}", "}", ")", ";", "opts", "[", "'reactDocgen'", "]", "=", "opts", "[", "'reactDocgen'", "]", "||", "{", "}", "if", "(", "!", "opts", "[", "'reactDocgen'", "]", ".", "files", ")", "{", "opts", "[", "'reactDocgen'", "]", ".", "files", "=", "[", "input", "]", "}", "this", ".", "opts", "=", "opts", "this", ".", "reactDocGenFiles", "=", "this", ".", "getReactPropDocFiles", "(", ")", "this", ".", "cssFiles", "=", "this", ".", "extractFiles", "(", "'.css'", ")", "this", ".", "jsFiles", "=", "this", ".", "extractFiles", "(", "'.js'", ")", "this", ".", "appTemplate", "=", "fs", ".", "readFileSync", "(", "path", ".", "resolve", "(", "__dirname", ",", "'./fixtures/index.html.mustache'", ")", ",", "'utf-8'", ")", "this", ".", "stageDir", "=", "path", ".", "resolve", "(", "__dirname", ",", "'../rcs-tmp'", ")", "}" ]
React Styleguide Generator @class @param {string} input @param {Object} opts @param {string} opts.output @param {string} opts.title @param {string|Object} opts.config @param {string} opts.root @param {boolean} opts.pushstate @param {string[]} opts.files @param {Object} opts.babelConfig @param {Object} opts.webpackConfig @param {Object} opts.reactDocgen
[ "React", "Styleguide", "Generator" ]
2974304ea50abc66a0238ca10c5e219c947d6cfa
https://github.com/NogsMPLS/react-component-styleguide/blob/2974304ea50abc66a0238ca10c5e219c947d6cfa/lib/rcs.js#L54-L118
train
bBlocks/component
component.js
function (obj, eventType, eventHandler) { if (!obj.eventHandlers) { obj.eventHandlers = {}; } if (!obj.eventHandlers[eventType]) { obj.eventHandlers[eventType] = []; } if (eventHandler) { obj.eventHandlers[eventType].push(eventHandler); } return obj.eventHandlers[eventType]; }
javascript
function (obj, eventType, eventHandler) { if (!obj.eventHandlers) { obj.eventHandlers = {}; } if (!obj.eventHandlers[eventType]) { obj.eventHandlers[eventType] = []; } if (eventHandler) { obj.eventHandlers[eventType].push(eventHandler); } return obj.eventHandlers[eventType]; }
[ "function", "(", "obj", ",", "eventType", ",", "eventHandler", ")", "{", "if", "(", "!", "obj", ".", "eventHandlers", ")", "{", "obj", ".", "eventHandlers", "=", "{", "}", ";", "}", "if", "(", "!", "obj", ".", "eventHandlers", "[", "eventType", "]", ")", "{", "obj", ".", "eventHandlers", "[", "eventType", "]", "=", "[", "]", ";", "}", "if", "(", "eventHandler", ")", "{", "obj", ".", "eventHandlers", "[", "eventType", "]", ".", "push", "(", "eventHandler", ")", ";", "}", "return", "obj", ".", "eventHandlers", "[", "eventType", "]", ";", "}" ]
Adds an event handler to a componet @param {object} obj - Target object @param {string} eventType - Name of the event @param {function} eventHandler - Event handler @return {object} - Object with a list of defined event handlers
[ "Adds", "an", "event", "handler", "to", "a", "componet" ]
7dcccf1861d66f2c915c97900630b0b4a9d072e2
https://github.com/bBlocks/component/blob/7dcccf1861d66f2c915c97900630b0b4a9d072e2/component.js#L29-L38
train
bBlocks/component
component.js
function(parentClass, isWhat, tag, features) { // v0 spec implementation using https://github.com/WebReflection/document-register-element var elementClass = Object.create(parentClass.prototype); // Clone event handlers if (elementClass.eventHandlers) { var clonedHandlers = {}; for (var i in elementClass.eventHandlers) { var handlers = elementClass.eventHandlers[i]; clonedHandlers[i] = handlers.slice(0); // Clone array of listeners; } elementClass.eventHandlers = clonedHandlers; } // Lifecycle elementClass.createdCallback = function () { // Add event listeners for (var i in this.eventHandlers) { var event = new CustomEvent(i); for (var j in this.eventHandlers[i]) { this.addEventListener(event.type, this.eventHandlers[i][j]); } } // Trigger create var event = new CustomEvent('create'); this.dispatchEvent(event); }; elementClass.attachedCallback = function () { var event = new CustomEvent('attach'); this.dispatchEvent(event); }; elementClass.detachedCallback = function () { var event = new CustomEvent('detach'); this.dispatchEvent(event); }; elementClass.attributeChangedCallback = function (attributeName) { var event = new CustomEvent('attributeChange', { detail: { attributeName: attributeName } }); this.dispatchEvent(event); }; // Attach features if (features) { if (!features.length) { // Can't use Array.isArray features = [features]; } for (var i=0;i<features.length;i++) { utils.addFeature(elementClass, features[i]); } } var params = { prototype: elementClass }; if (tag) { params.extends = tag; } var elementConstructor = document.registerElement(isWhat, params); // v0 syntax return elementConstructor; }
javascript
function(parentClass, isWhat, tag, features) { // v0 spec implementation using https://github.com/WebReflection/document-register-element var elementClass = Object.create(parentClass.prototype); // Clone event handlers if (elementClass.eventHandlers) { var clonedHandlers = {}; for (var i in elementClass.eventHandlers) { var handlers = elementClass.eventHandlers[i]; clonedHandlers[i] = handlers.slice(0); // Clone array of listeners; } elementClass.eventHandlers = clonedHandlers; } // Lifecycle elementClass.createdCallback = function () { // Add event listeners for (var i in this.eventHandlers) { var event = new CustomEvent(i); for (var j in this.eventHandlers[i]) { this.addEventListener(event.type, this.eventHandlers[i][j]); } } // Trigger create var event = new CustomEvent('create'); this.dispatchEvent(event); }; elementClass.attachedCallback = function () { var event = new CustomEvent('attach'); this.dispatchEvent(event); }; elementClass.detachedCallback = function () { var event = new CustomEvent('detach'); this.dispatchEvent(event); }; elementClass.attributeChangedCallback = function (attributeName) { var event = new CustomEvent('attributeChange', { detail: { attributeName: attributeName } }); this.dispatchEvent(event); }; // Attach features if (features) { if (!features.length) { // Can't use Array.isArray features = [features]; } for (var i=0;i<features.length;i++) { utils.addFeature(elementClass, features[i]); } } var params = { prototype: elementClass }; if (tag) { params.extends = tag; } var elementConstructor = document.registerElement(isWhat, params); // v0 syntax return elementConstructor; }
[ "function", "(", "parentClass", ",", "isWhat", ",", "tag", ",", "features", ")", "{", "var", "elementClass", "=", "Object", ".", "create", "(", "parentClass", ".", "prototype", ")", ";", "if", "(", "elementClass", ".", "eventHandlers", ")", "{", "var", "clonedHandlers", "=", "{", "}", ";", "for", "(", "var", "i", "in", "elementClass", ".", "eventHandlers", ")", "{", "var", "handlers", "=", "elementClass", ".", "eventHandlers", "[", "i", "]", ";", "clonedHandlers", "[", "i", "]", "=", "handlers", ".", "slice", "(", "0", ")", ";", "}", "elementClass", ".", "eventHandlers", "=", "clonedHandlers", ";", "}", "elementClass", ".", "createdCallback", "=", "function", "(", ")", "{", "for", "(", "var", "i", "in", "this", ".", "eventHandlers", ")", "{", "var", "event", "=", "new", "CustomEvent", "(", "i", ")", ";", "for", "(", "var", "j", "in", "this", ".", "eventHandlers", "[", "i", "]", ")", "{", "this", ".", "addEventListener", "(", "event", ".", "type", ",", "this", ".", "eventHandlers", "[", "i", "]", "[", "j", "]", ")", ";", "}", "}", "var", "event", "=", "new", "CustomEvent", "(", "'create'", ")", ";", "this", ".", "dispatchEvent", "(", "event", ")", ";", "}", ";", "elementClass", ".", "attachedCallback", "=", "function", "(", ")", "{", "var", "event", "=", "new", "CustomEvent", "(", "'attach'", ")", ";", "this", ".", "dispatchEvent", "(", "event", ")", ";", "}", ";", "elementClass", ".", "detachedCallback", "=", "function", "(", ")", "{", "var", "event", "=", "new", "CustomEvent", "(", "'detach'", ")", ";", "this", ".", "dispatchEvent", "(", "event", ")", ";", "}", ";", "elementClass", ".", "attributeChangedCallback", "=", "function", "(", "attributeName", ")", "{", "var", "event", "=", "new", "CustomEvent", "(", "'attributeChange'", ",", "{", "detail", ":", "{", "attributeName", ":", "attributeName", "}", "}", ")", ";", "this", ".", "dispatchEvent", "(", "event", ")", ";", "}", ";", "if", "(", "features", ")", "{", "if", "(", "!", "features", ".", "length", ")", "{", "features", "=", "[", "features", "]", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "features", ".", "length", ";", "i", "++", ")", "{", "utils", ".", "addFeature", "(", "elementClass", ",", "features", "[", "i", "]", ")", ";", "}", "}", "var", "params", "=", "{", "prototype", ":", "elementClass", "}", ";", "if", "(", "tag", ")", "{", "params", ".", "extends", "=", "tag", ";", "}", "var", "elementConstructor", "=", "document", ".", "registerElement", "(", "isWhat", ",", "params", ")", ";", "return", "elementConstructor", ";", "}" ]
Register custom element in the DOM using spec v0 @param {function} [HTMLElement] prarentClass - Constructor or class of the element @param {string} isWhat - Name for the component. Could be used as tag name or "is" attribute @param {string=} tag - Tag name of the element. Required when extending native elements @param {object|array} feature - One or more features to have @return {function} - Constructor of registered element
[ "Register", "custom", "element", "in", "the", "DOM", "using", "spec", "v0" ]
7dcccf1861d66f2c915c97900630b0b4a9d072e2
https://github.com/bBlocks/component/blob/7dcccf1861d66f2c915c97900630b0b4a9d072e2/component.js#L48-L109
train
bBlocks/component
component.js
function (obj, properties) { var events, propertyDescriptors, i; if (!properties) { return; } // Clone events if (properties.on) { events = Object.assign({}, properties.on); } Object.assign(obj, properties); // IE11 need a polyfill // Handle events if (events) { for (i in events) { this.addCustomEvent(obj, i, events[i]); } delete obj.on; } // Handle observed attributes if (properties.observedAttributes) { if (!obj.observedAttributesList) { obj.observedAttributesList = []; } Array.prototype.push.apply(obj.observedAttributesList,properties.observedAttributes); } // Handle properties getters and setters if (properties.define) { propertyDescriptors = Object.assign({}, properties.define); Object.defineProperties(obj, propertyDescriptors); } }
javascript
function (obj, properties) { var events, propertyDescriptors, i; if (!properties) { return; } // Clone events if (properties.on) { events = Object.assign({}, properties.on); } Object.assign(obj, properties); // IE11 need a polyfill // Handle events if (events) { for (i in events) { this.addCustomEvent(obj, i, events[i]); } delete obj.on; } // Handle observed attributes if (properties.observedAttributes) { if (!obj.observedAttributesList) { obj.observedAttributesList = []; } Array.prototype.push.apply(obj.observedAttributesList,properties.observedAttributes); } // Handle properties getters and setters if (properties.define) { propertyDescriptors = Object.assign({}, properties.define); Object.defineProperties(obj, propertyDescriptors); } }
[ "function", "(", "obj", ",", "properties", ")", "{", "var", "events", ",", "propertyDescriptors", ",", "i", ";", "if", "(", "!", "properties", ")", "{", "return", ";", "}", "if", "(", "properties", ".", "on", ")", "{", "events", "=", "Object", ".", "assign", "(", "{", "}", ",", "properties", ".", "on", ")", ";", "}", "Object", ".", "assign", "(", "obj", ",", "properties", ")", ";", "if", "(", "events", ")", "{", "for", "(", "i", "in", "events", ")", "{", "this", ".", "addCustomEvent", "(", "obj", ",", "i", ",", "events", "[", "i", "]", ")", ";", "}", "delete", "obj", ".", "on", ";", "}", "if", "(", "properties", ".", "observedAttributes", ")", "{", "if", "(", "!", "obj", ".", "observedAttributesList", ")", "{", "obj", ".", "observedAttributesList", "=", "[", "]", ";", "}", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "obj", ".", "observedAttributesList", ",", "properties", ".", "observedAttributes", ")", ";", "}", "if", "(", "properties", ".", "define", ")", "{", "propertyDescriptors", "=", "Object", ".", "assign", "(", "{", "}", ",", "properties", ".", "define", ")", ";", "Object", ".", "defineProperties", "(", "obj", ",", "propertyDescriptors", ")", ";", "}", "}" ]
Adds a feature to the component @param {object} obj - Target object. Usually a prototype of a component. Properties "on", "define", "observedAttribute" will be stacked.
[ "Adds", "a", "feature", "to", "the", "component" ]
7dcccf1861d66f2c915c97900630b0b4a9d072e2
https://github.com/bBlocks/component/blob/7dcccf1861d66f2c915c97900630b0b4a9d072e2/component.js#L220-L252
train
bBlocks/component
component.js
function() { 'use strict'; var features = arguments; if (!features.length) { return; } // Detect isWhat, tag and parent class var props = feature.apply(null, arguments); var isWhat = props.is; var tag = props.tag; var parentClass = props.extends; if (!parentClass) {parentClass = HTMLElement;} if (tag && !isWhat) {isWhat = tag; tag = null;}; if (!tag && !isWhat) {utils.warn('Name not specified'); return;} if (props.polyfill == 'v0') { return utils.registerElement(parentClass, isWhat, tag, arguments); } else { return utils.defineElement(parentClass, isWhat, tag, arguments); } }
javascript
function() { 'use strict'; var features = arguments; if (!features.length) { return; } // Detect isWhat, tag and parent class var props = feature.apply(null, arguments); var isWhat = props.is; var tag = props.tag; var parentClass = props.extends; if (!parentClass) {parentClass = HTMLElement;} if (tag && !isWhat) {isWhat = tag; tag = null;}; if (!tag && !isWhat) {utils.warn('Name not specified'); return;} if (props.polyfill == 'v0') { return utils.registerElement(parentClass, isWhat, tag, arguments); } else { return utils.defineElement(parentClass, isWhat, tag, arguments); } }
[ "function", "(", ")", "{", "'use strict'", ";", "var", "features", "=", "arguments", ";", "if", "(", "!", "features", ".", "length", ")", "{", "return", ";", "}", "var", "props", "=", "feature", ".", "apply", "(", "null", ",", "arguments", ")", ";", "var", "isWhat", "=", "props", ".", "is", ";", "var", "tag", "=", "props", ".", "tag", ";", "var", "parentClass", "=", "props", ".", "extends", ";", "if", "(", "!", "parentClass", ")", "{", "parentClass", "=", "HTMLElement", ";", "}", "if", "(", "tag", "&&", "!", "isWhat", ")", "{", "isWhat", "=", "tag", ";", "tag", "=", "null", ";", "}", ";", "if", "(", "!", "tag", "&&", "!", "isWhat", ")", "{", "utils", ".", "warn", "(", "'Name not specified'", ")", ";", "return", ";", "}", "if", "(", "props", ".", "polyfill", "==", "'v0'", ")", "{", "return", "utils", ".", "registerElement", "(", "parentClass", ",", "isWhat", ",", "tag", ",", "arguments", ")", ";", "}", "else", "{", "return", "utils", ".", "defineElement", "(", "parentClass", ",", "isWhat", ",", "tag", ",", "arguments", ")", ";", "}", "}" ]
Define a component and register in the DOM @memberof bb @param {object} [...] One or more features to have in the component. Features will be mixed. At least one of the features needs to have "is" proeprty defined. @return {function} Constructor for elements
[ "Define", "a", "component", "and", "register", "in", "the", "DOM" ]
7dcccf1861d66f2c915c97900630b0b4a9d072e2
https://github.com/bBlocks/component/blob/7dcccf1861d66f2c915c97900630b0b4a9d072e2/component.js#L271-L294
train
bBlocks/component
component.js
function() { 'use strict'; var self = this || {}; if (arguments.length) { for (var i = 0; i<arguments.length; i++) { if (typeof arguments[i] != 'object') {utils.warn('Expected object in argument #' + i); continue;} Object.assign(self, arguments[i]); } } return self; }
javascript
function() { 'use strict'; var self = this || {}; if (arguments.length) { for (var i = 0; i<arguments.length; i++) { if (typeof arguments[i] != 'object') {utils.warn('Expected object in argument #' + i); continue;} Object.assign(self, arguments[i]); } } return self; }
[ "function", "(", ")", "{", "'use strict'", ";", "var", "self", "=", "this", "||", "{", "}", ";", "if", "(", "arguments", ".", "length", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "if", "(", "typeof", "arguments", "[", "i", "]", "!=", "'object'", ")", "{", "utils", ".", "warn", "(", "'Expected object in argument #'", "+", "i", ")", ";", "continue", ";", "}", "Object", ".", "assign", "(", "self", ",", "arguments", "[", "i", "]", ")", ";", "}", "}", "return", "self", ";", "}" ]
Created a feature from one or more objects @constructor @memberof bb @param {object} [...] @return {object} Created feature. Each feature could have special properties like "is", "tag", "extends", "observedAttributes", "on", "define" used to define components
[ "Created", "a", "feature", "from", "one", "or", "more", "objects" ]
7dcccf1861d66f2c915c97900630b0b4a9d072e2
https://github.com/bBlocks/component/blob/7dcccf1861d66f2c915c97900630b0b4a9d072e2/component.js#L304-L314
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/generators/types.js
Property
function Property(node, print) { print.list(node.decorators, { separator: "" }); if (node.method || node.kind === "get" || node.kind === "set") { this._method(node, print); } else { if (node.computed) { this.push("["); print.plain(node.key); this.push("]"); } else { // print `({ foo: foo = 5 } = {})` as `({ foo = 5 } = {});` if (t.isAssignmentPattern(node.value) && t.isIdentifier(node.key) && node.key.name === node.value.left.name) { print.plain(node.value); return; } print.plain(node.key); // shorthand! if (node.shorthand && t.isIdentifier(node.key) && t.isIdentifier(node.value) && node.key.name === node.value.name) { return; } } this.push(":"); this.space(); print.plain(node.value); } }
javascript
function Property(node, print) { print.list(node.decorators, { separator: "" }); if (node.method || node.kind === "get" || node.kind === "set") { this._method(node, print); } else { if (node.computed) { this.push("["); print.plain(node.key); this.push("]"); } else { // print `({ foo: foo = 5 } = {})` as `({ foo = 5 } = {});` if (t.isAssignmentPattern(node.value) && t.isIdentifier(node.key) && node.key.name === node.value.left.name) { print.plain(node.value); return; } print.plain(node.key); // shorthand! if (node.shorthand && t.isIdentifier(node.key) && t.isIdentifier(node.value) && node.key.name === node.value.name) { return; } } this.push(":"); this.space(); print.plain(node.value); } }
[ "function", "Property", "(", "node", ",", "print", ")", "{", "print", ".", "list", "(", "node", ".", "decorators", ",", "{", "separator", ":", "\"\"", "}", ")", ";", "if", "(", "node", ".", "method", "||", "node", ".", "kind", "===", "\"get\"", "||", "node", ".", "kind", "===", "\"set\"", ")", "{", "this", ".", "_method", "(", "node", ",", "print", ")", ";", "}", "else", "{", "if", "(", "node", ".", "computed", ")", "{", "this", ".", "push", "(", "\"[\"", ")", ";", "print", ".", "plain", "(", "node", ".", "key", ")", ";", "this", ".", "push", "(", "\"]\"", ")", ";", "}", "else", "{", "if", "(", "t", ".", "isAssignmentPattern", "(", "node", ".", "value", ")", "&&", "t", ".", "isIdentifier", "(", "node", ".", "key", ")", "&&", "node", ".", "key", ".", "name", "===", "node", ".", "value", ".", "left", ".", "name", ")", "{", "print", ".", "plain", "(", "node", ".", "value", ")", ";", "return", ";", "}", "print", ".", "plain", "(", "node", ".", "key", ")", ";", "if", "(", "node", ".", "shorthand", "&&", "t", ".", "isIdentifier", "(", "node", ".", "key", ")", "&&", "t", ".", "isIdentifier", "(", "node", ".", "value", ")", "&&", "node", ".", "key", ".", "name", "===", "node", ".", "value", ".", "name", ")", "{", "return", ";", "}", "}", "this", ".", "push", "(", "\":\"", ")", ";", "this", ".", "space", "(", ")", ";", "print", ".", "plain", "(", "node", ".", "value", ")", ";", "}", "}" ]
Prints Property, prints decorators, key, and value, handles kind, computed, and shorthand.
[ "Prints", "Property", "prints", "decorators", "key", "and", "value", "handles", "kind", "computed", "and", "shorthand", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/generators/types.js#L78-L107
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/generators/types.js
ArrayExpression
function ArrayExpression(node, print) { var elems = node.elements; var len = elems.length; this.push("["); print.printInnerComments(); for (var i = 0; i < elems.length; i++) { var elem = elems[i]; if (elem) { if (i > 0) this.space(); print.plain(elem); if (i < len - 1) this.push(","); } else { // If the array expression ends with a hole, that hole // will be ignored by the interpreter, but if it ends with // two (or more) holes, we need to write out two (or more) // commas so that the resulting code is interpreted with // both (all) of the holes. this.push(","); } } this.push("]"); }
javascript
function ArrayExpression(node, print) { var elems = node.elements; var len = elems.length; this.push("["); print.printInnerComments(); for (var i = 0; i < elems.length; i++) { var elem = elems[i]; if (elem) { if (i > 0) this.space(); print.plain(elem); if (i < len - 1) this.push(","); } else { // If the array expression ends with a hole, that hole // will be ignored by the interpreter, but if it ends with // two (or more) holes, we need to write out two (or more) // commas so that the resulting code is interpreted with // both (all) of the holes. this.push(","); } } this.push("]"); }
[ "function", "ArrayExpression", "(", "node", ",", "print", ")", "{", "var", "elems", "=", "node", ".", "elements", ";", "var", "len", "=", "elems", ".", "length", ";", "this", ".", "push", "(", "\"[\"", ")", ";", "print", ".", "printInnerComments", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "elems", ".", "length", ";", "i", "++", ")", "{", "var", "elem", "=", "elems", "[", "i", "]", ";", "if", "(", "elem", ")", "{", "if", "(", "i", ">", "0", ")", "this", ".", "space", "(", ")", ";", "print", ".", "plain", "(", "elem", ")", ";", "if", "(", "i", "<", "len", "-", "1", ")", "this", ".", "push", "(", "\",\"", ")", ";", "}", "else", "{", "this", ".", "push", "(", "\",\"", ")", ";", "}", "}", "this", ".", "push", "(", "\"]\"", ")", ";", "}" ]
Prints ArrayExpression, prints elements.
[ "Prints", "ArrayExpression", "prints", "elements", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/generators/types.js#L113-L137
train
zipscene/human-readable-id-gen
Brocfile.js
getSourceTrees
function getSourceTrees(pathsToSearch) { return { read: function(readTree) { var promises = _.map(pathsToSearch, function(path) { return new Promise(function(resolve) { fs.exists(path, function(exists) { resolve((exists) ? path : null); }); }); }); return Promise.all(promises) .then(function(paths) { paths = _.filter(paths); if (paths.length === 0) throw new Error('No source paths found'); return paths; }) .then(function(paths) { console.log('Found source paths: ' + paths.join(', ')); var pathTrees = _.map(paths, function(path) { return new Funnel(path, { srcDir: '.', destDir: path }); }); return readTree(mergeTrees(pathTrees)); }); }, cleanup: function() {} }; }
javascript
function getSourceTrees(pathsToSearch) { return { read: function(readTree) { var promises = _.map(pathsToSearch, function(path) { return new Promise(function(resolve) { fs.exists(path, function(exists) { resolve((exists) ? path : null); }); }); }); return Promise.all(promises) .then(function(paths) { paths = _.filter(paths); if (paths.length === 0) throw new Error('No source paths found'); return paths; }) .then(function(paths) { console.log('Found source paths: ' + paths.join(', ')); var pathTrees = _.map(paths, function(path) { return new Funnel(path, { srcDir: '.', destDir: path }); }); return readTree(mergeTrees(pathTrees)); }); }, cleanup: function() {} }; }
[ "function", "getSourceTrees", "(", "pathsToSearch", ")", "{", "return", "{", "read", ":", "function", "(", "readTree", ")", "{", "var", "promises", "=", "_", ".", "map", "(", "pathsToSearch", ",", "function", "(", "path", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "fs", ".", "exists", "(", "path", ",", "function", "(", "exists", ")", "{", "resolve", "(", "(", "exists", ")", "?", "path", ":", "null", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "return", "Promise", ".", "all", "(", "promises", ")", ".", "then", "(", "function", "(", "paths", ")", "{", "paths", "=", "_", ".", "filter", "(", "paths", ")", ";", "if", "(", "paths", ".", "length", "===", "0", ")", "throw", "new", "Error", "(", "'No source paths found'", ")", ";", "return", "paths", ";", "}", ")", ".", "then", "(", "function", "(", "paths", ")", "{", "console", ".", "log", "(", "'Found source paths: '", "+", "paths", ".", "join", "(", "', '", ")", ")", ";", "var", "pathTrees", "=", "_", ".", "map", "(", "paths", ",", "function", "(", "path", ")", "{", "return", "new", "Funnel", "(", "path", ",", "{", "srcDir", ":", "'.'", ",", "destDir", ":", "path", "}", ")", ";", "}", ")", ";", "return", "readTree", "(", "mergeTrees", "(", "pathTrees", ")", ")", ";", "}", ")", ";", "}", ",", "cleanup", ":", "function", "(", ")", "{", "}", "}", ";", "}" ]
Returns a broc tree corresponding to the original source files
[ "Returns", "a", "broc", "tree", "corresponding", "to", "the", "original", "source", "files" ]
5e7128c3baa86266b5110a4e93a650bc9a08aaa5
https://github.com/zipscene/human-readable-id-gen/blob/5e7128c3baa86266b5110a4e93a650bc9a08aaa5/Brocfile.js#L14-L44
train
MaximeMaillet/dtorrent
src/manager.js
checkTorrentIntegrity
async function checkTorrentIntegrity(torrentFile, dataFile) { const _ntRead = promisify(nt.read); return _ntRead(torrentFile) .then((torrent) => { return new Promise((resolve, reject) => { torrent.metadata.info.name = path.basename(dataFile); const hasher = torrent.hashCheck(path.dirname(dataFile)); let percentMatch = 0; const errors = []; hasher.on('match', (i, hash, percent) => { percentMatch = percent; }); hasher.on('error', (err) => { errors.push(err.message); }); hasher.on('end', () => { if(errors.length > 0) { reject(errors); } else { resolve({ 'success': percentMatch === 100, 'hash': torrent.infoHash() }); } }); }); }); }
javascript
async function checkTorrentIntegrity(torrentFile, dataFile) { const _ntRead = promisify(nt.read); return _ntRead(torrentFile) .then((torrent) => { return new Promise((resolve, reject) => { torrent.metadata.info.name = path.basename(dataFile); const hasher = torrent.hashCheck(path.dirname(dataFile)); let percentMatch = 0; const errors = []; hasher.on('match', (i, hash, percent) => { percentMatch = percent; }); hasher.on('error', (err) => { errors.push(err.message); }); hasher.on('end', () => { if(errors.length > 0) { reject(errors); } else { resolve({ 'success': percentMatch === 100, 'hash': torrent.infoHash() }); } }); }); }); }
[ "async", "function", "checkTorrentIntegrity", "(", "torrentFile", ",", "dataFile", ")", "{", "const", "_ntRead", "=", "promisify", "(", "nt", ".", "read", ")", ";", "return", "_ntRead", "(", "torrentFile", ")", ".", "then", "(", "(", "torrent", ")", "=>", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "torrent", ".", "metadata", ".", "info", ".", "name", "=", "path", ".", "basename", "(", "dataFile", ")", ";", "const", "hasher", "=", "torrent", ".", "hashCheck", "(", "path", ".", "dirname", "(", "dataFile", ")", ")", ";", "let", "percentMatch", "=", "0", ";", "const", "errors", "=", "[", "]", ";", "hasher", ".", "on", "(", "'match'", ",", "(", "i", ",", "hash", ",", "percent", ")", "=>", "{", "percentMatch", "=", "percent", ";", "}", ")", ";", "hasher", ".", "on", "(", "'error'", ",", "(", "err", ")", "=>", "{", "errors", ".", "push", "(", "err", ".", "message", ")", ";", "}", ")", ";", "hasher", ".", "on", "(", "'end'", ",", "(", ")", "=>", "{", "if", "(", "errors", ".", "length", ">", "0", ")", "{", "reject", "(", "errors", ")", ";", "}", "else", "{", "resolve", "(", "{", "'success'", ":", "percentMatch", "===", "100", ",", "'hash'", ":", "torrent", ".", "infoHash", "(", ")", "}", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Check integrity between torrent and data @param torrentFile @param dataFile @return {Promise.<TResult>|*}
[ "Check", "integrity", "between", "torrent", "and", "data" ]
ed7fdd8e8959a4f30f9a2f1afa3ec17c64bc5535
https://github.com/MaximeMaillet/dtorrent/blob/ed7fdd8e8959a4f30f9a2f1afa3ec17c64bc5535/src/manager.js#L304-L335
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/util.js
canCompile
function canCompile(filename, altExts) { var exts = altExts || canCompile.EXTENSIONS; var ext = _path2["default"].extname(filename); return _lodashCollectionContains2["default"](exts, ext); }
javascript
function canCompile(filename, altExts) { var exts = altExts || canCompile.EXTENSIONS; var ext = _path2["default"].extname(filename); return _lodashCollectionContains2["default"](exts, ext); }
[ "function", "canCompile", "(", "filename", ",", "altExts", ")", "{", "var", "exts", "=", "altExts", "||", "canCompile", ".", "EXTENSIONS", ";", "var", "ext", "=", "_path2", "[", "\"default\"", "]", ".", "extname", "(", "filename", ")", ";", "return", "_lodashCollectionContains2", "[", "\"default\"", "]", "(", "exts", ",", "ext", ")", ";", "}" ]
Test if a filename ends with a compilable extension.
[ "Test", "if", "a", "filename", "ends", "with", "a", "compilable", "extension", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/util.js#L103-L107
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/util.js
list
function list(val) { if (!val) { return []; } else if (Array.isArray(val)) { return val; } else if (typeof val === "string") { return val.split(","); } else { return [val]; } }
javascript
function list(val) { if (!val) { return []; } else if (Array.isArray(val)) { return val; } else if (typeof val === "string") { return val.split(","); } else { return [val]; } }
[ "function", "list", "(", "val", ")", "{", "if", "(", "!", "val", ")", "{", "return", "[", "]", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "val", ")", ")", "{", "return", "val", ";", "}", "else", "if", "(", "typeof", "val", "===", "\"string\"", ")", "{", "return", "val", ".", "split", "(", "\",\"", ")", ";", "}", "else", "{", "return", "[", "val", "]", ";", "}", "}" ]
Create an array from any value, splitting strings by ",".
[ "Create", "an", "array", "from", "any", "value", "splitting", "strings", "by", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/util.js#L119-L129
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/util.js
regexify
function regexify(val) { if (!val) return new RegExp(/.^/); if (Array.isArray(val)) val = new RegExp(val.map(_lodashStringEscapeRegExp2["default"]).join("|"), "i"); if (_lodashLangIsString2["default"](val)) { // normalise path separators val = _slash2["default"](val); // remove starting wildcards or relative separator if present if (_lodashStringStartsWith2["default"](val, "./") || _lodashStringStartsWith2["default"](val, "*/")) val = val.slice(2); if (_lodashStringStartsWith2["default"](val, "**/")) val = val.slice(3); var regex = _minimatch2["default"].makeRe(val, { nocase: true }); return new RegExp(regex.source.slice(1, -1), "i"); } if (_lodashLangIsRegExp2["default"](val)) return val; throw new TypeError("illegal type for regexify"); }
javascript
function regexify(val) { if (!val) return new RegExp(/.^/); if (Array.isArray(val)) val = new RegExp(val.map(_lodashStringEscapeRegExp2["default"]).join("|"), "i"); if (_lodashLangIsString2["default"](val)) { // normalise path separators val = _slash2["default"](val); // remove starting wildcards or relative separator if present if (_lodashStringStartsWith2["default"](val, "./") || _lodashStringStartsWith2["default"](val, "*/")) val = val.slice(2); if (_lodashStringStartsWith2["default"](val, "**/")) val = val.slice(3); var regex = _minimatch2["default"].makeRe(val, { nocase: true }); return new RegExp(regex.source.slice(1, -1), "i"); } if (_lodashLangIsRegExp2["default"](val)) return val; throw new TypeError("illegal type for regexify"); }
[ "function", "regexify", "(", "val", ")", "{", "if", "(", "!", "val", ")", "return", "new", "RegExp", "(", "/", ".^", "/", ")", ";", "if", "(", "Array", ".", "isArray", "(", "val", ")", ")", "val", "=", "new", "RegExp", "(", "val", ".", "map", "(", "_lodashStringEscapeRegExp2", "[", "\"default\"", "]", ")", ".", "join", "(", "\"|\"", ")", ",", "\"i\"", ")", ";", "if", "(", "_lodashLangIsString2", "[", "\"default\"", "]", "(", "val", ")", ")", "{", "val", "=", "_slash2", "[", "\"default\"", "]", "(", "val", ")", ";", "if", "(", "_lodashStringStartsWith2", "[", "\"default\"", "]", "(", "val", ",", "\"./\"", ")", "||", "_lodashStringStartsWith2", "[", "\"default\"", "]", "(", "val", ",", "\"*/\"", ")", ")", "val", "=", "val", ".", "slice", "(", "2", ")", ";", "if", "(", "_lodashStringStartsWith2", "[", "\"default\"", "]", "(", "val", ",", "\"**/\"", ")", ")", "val", "=", "val", ".", "slice", "(", "3", ")", ";", "var", "regex", "=", "_minimatch2", "[", "\"default\"", "]", ".", "makeRe", "(", "val", ",", "{", "nocase", ":", "true", "}", ")", ";", "return", "new", "RegExp", "(", "regex", ".", "source", ".", "slice", "(", "1", ",", "-", "1", ")", ",", "\"i\"", ")", ";", "}", "if", "(", "_lodashLangIsRegExp2", "[", "\"default\"", "]", "(", "val", ")", ")", "return", "val", ";", "throw", "new", "TypeError", "(", "\"illegal type for regexify\"", ")", ";", "}" ]
Create a RegExp from a string, array, or regexp.
[ "Create", "a", "RegExp", "from", "a", "string", "array", "or", "regexp", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/util.js#L135-L155
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/util.js
shouldIgnore
function shouldIgnore(filename, ignore, only) { filename = _slash2["default"](filename); if (only) { var _arr = only; for (var _i = 0; _i < _arr.length; _i++) { var pattern = _arr[_i]; if (_shouldIgnore(pattern, filename)) return false; } return true; } else if (ignore.length) { var _arr2 = ignore; for (var _i2 = 0; _i2 < _arr2.length; _i2++) { var pattern = _arr2[_i2]; if (_shouldIgnore(pattern, filename)) return true; } } return false; }
javascript
function shouldIgnore(filename, ignore, only) { filename = _slash2["default"](filename); if (only) { var _arr = only; for (var _i = 0; _i < _arr.length; _i++) { var pattern = _arr[_i]; if (_shouldIgnore(pattern, filename)) return false; } return true; } else if (ignore.length) { var _arr2 = ignore; for (var _i2 = 0; _i2 < _arr2.length; _i2++) { var pattern = _arr2[_i2]; if (_shouldIgnore(pattern, filename)) return true; } } return false; }
[ "function", "shouldIgnore", "(", "filename", ",", "ignore", ",", "only", ")", "{", "filename", "=", "_slash2", "[", "\"default\"", "]", "(", "filename", ")", ";", "if", "(", "only", ")", "{", "var", "_arr", "=", "only", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "_arr", ".", "length", ";", "_i", "++", ")", "{", "var", "pattern", "=", "_arr", "[", "_i", "]", ";", "if", "(", "_shouldIgnore", "(", "pattern", ",", "filename", ")", ")", "return", "false", ";", "}", "return", "true", ";", "}", "else", "if", "(", "ignore", ".", "length", ")", "{", "var", "_arr2", "=", "ignore", ";", "for", "(", "var", "_i2", "=", "0", ";", "_i2", "<", "_arr2", ".", "length", ";", "_i2", "++", ")", "{", "var", "pattern", "=", "_arr2", "[", "_i2", "]", ";", "if", "(", "_shouldIgnore", "(", "pattern", ",", "filename", ")", ")", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Tests if a filename should be ignored based on "ignore" and "only" options.
[ "Tests", "if", "a", "filename", "should", "be", "ignored", "based", "on", "ignore", "and", "only", "options", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/util.js#L188-L209
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/util.js
parseTemplate
function parseTemplate(loc, code) { var ast = _helpersParse2["default"](code, { filename: loc, looseModules: true }).program; ast = _traversal2["default"].removeProperties(ast); return ast; }
javascript
function parseTemplate(loc, code) { var ast = _helpersParse2["default"](code, { filename: loc, looseModules: true }).program; ast = _traversal2["default"].removeProperties(ast); return ast; }
[ "function", "parseTemplate", "(", "loc", ",", "code", ")", "{", "var", "ast", "=", "_helpersParse2", "[", "\"default\"", "]", "(", "code", ",", "{", "filename", ":", "loc", ",", "looseModules", ":", "true", "}", ")", ".", "program", ";", "ast", "=", "_traversal2", "[", "\"default\"", "]", ".", "removeProperties", "(", "ast", ")", ";", "return", "ast", ";", "}" ]
Parse a template.
[ "Parse", "a", "template", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/util.js#L285-L289
train
kubosho/kotori
src/build.js
activatePostCSSPlugins
function activatePostCSSPlugins(config) { const plugins = []; if (config.lintRules || config.lintRules !== "") { // TODO: Throw easy-to-understand error message // incorrect path? (ex. "lintRules": "aaa") // typo? (ex. "lintRules": "stylelint-config-suitcs") const lintRules = require(config.lintRules); if (lintRules.rules) { plugins.push(stylelint(lintRules)); } else { throw new Error("Illegal lint rule: \"rules\" property is not found."); } } if (config.browsers && config.browsers !== "") { plugins.push(autoprefixer(config.browsers)); } plugins.push(cssfmt); plugins.push(reporter); return plugins; }
javascript
function activatePostCSSPlugins(config) { const plugins = []; if (config.lintRules || config.lintRules !== "") { // TODO: Throw easy-to-understand error message // incorrect path? (ex. "lintRules": "aaa") // typo? (ex. "lintRules": "stylelint-config-suitcs") const lintRules = require(config.lintRules); if (lintRules.rules) { plugins.push(stylelint(lintRules)); } else { throw new Error("Illegal lint rule: \"rules\" property is not found."); } } if (config.browsers && config.browsers !== "") { plugins.push(autoprefixer(config.browsers)); } plugins.push(cssfmt); plugins.push(reporter); return plugins; }
[ "function", "activatePostCSSPlugins", "(", "config", ")", "{", "const", "plugins", "=", "[", "]", ";", "if", "(", "config", ".", "lintRules", "||", "config", ".", "lintRules", "!==", "\"\"", ")", "{", "const", "lintRules", "=", "require", "(", "config", ".", "lintRules", ")", ";", "if", "(", "lintRules", ".", "rules", ")", "{", "plugins", ".", "push", "(", "stylelint", "(", "lintRules", ")", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"Illegal lint rule: \\\"rules\\\" property is not found.\"", ")", ";", "}", "}", "\\\"", "\\\"", "if", "(", "config", ".", "browsers", "&&", "config", ".", "browsers", "!==", "\"\"", ")", "{", "plugins", ".", "push", "(", "autoprefixer", "(", "config", ".", "browsers", ")", ")", ";", "}", "plugins", ".", "push", "(", "cssfmt", ")", ";", "}" ]
Activating PostCSS plugins @param {Object} config - Kotori config object @returns {Function[]} PostCSS plugins list @private
[ "Activating", "PostCSS", "plugins" ]
4a869d470408db17733caf9dabe67ecaa20cf4b7
https://github.com/kubosho/kotori/blob/4a869d470408db17733caf9dabe67ecaa20cf4b7/src/build.js#L103-L127
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/generation/generators/modules.js
ImportSpecifier
function ImportSpecifier(node, print) { print.plain(node.imported); if (node.local && node.local.name !== node.imported.name) { this.push(" as "); print.plain(node.local); } }
javascript
function ImportSpecifier(node, print) { print.plain(node.imported); if (node.local && node.local.name !== node.imported.name) { this.push(" as "); print.plain(node.local); } }
[ "function", "ImportSpecifier", "(", "node", ",", "print", ")", "{", "print", ".", "plain", "(", "node", ".", "imported", ")", ";", "if", "(", "node", ".", "local", "&&", "node", ".", "local", ".", "name", "!==", "node", ".", "imported", ".", "name", ")", "{", "this", ".", "push", "(", "\" as \"", ")", ";", "print", ".", "plain", "(", "node", ".", "local", ")", ";", "}", "}" ]
Prints ImportSpecifier, prints imported and local.
[ "Prints", "ImportSpecifier", "prints", "imported", "and", "local", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/generators/modules.js#L28-L34
train
manvalls/wapp
utils/buildScripts.js
es5Plugins
function es5Plugins(){ return [ require('babel-plugin-check-es2015-constants'), require('babel-plugin-transform-es2015-arrow-functions'), require('babel-plugin-transform-es2015-block-scoped-functions'), require('babel-plugin-transform-es2015-block-scoping'), require('babel-plugin-transform-es2015-classes'), require('babel-plugin-transform-es2015-computed-properties'), require('babel-plugin-transform-es2015-destructuring'), require('babel-plugin-transform-es2015-duplicate-keys'), require('babel-plugin-transform-es2015-for-of'), require('babel-plugin-transform-es2015-function-name'), require('babel-plugin-transform-es2015-literals'), require('babel-plugin-transform-es2015-object-super'), require('babel-plugin-transform-es2015-parameters'), require('babel-plugin-transform-es2015-shorthand-properties'), require('babel-plugin-transform-es2015-spread'), require('babel-plugin-transform-es2015-sticky-regex'), require('babel-plugin-transform-es2015-template-literals'), require('babel-plugin-transform-es2015-typeof-symbol'), require('babel-plugin-transform-es2015-unicode-regex'), require('babel-plugin-transform-async-to-generator'), require('babel-plugin-transform-exponentiation-operator'), require('babel-plugin-transform-regenerator') ]; }
javascript
function es5Plugins(){ return [ require('babel-plugin-check-es2015-constants'), require('babel-plugin-transform-es2015-arrow-functions'), require('babel-plugin-transform-es2015-block-scoped-functions'), require('babel-plugin-transform-es2015-block-scoping'), require('babel-plugin-transform-es2015-classes'), require('babel-plugin-transform-es2015-computed-properties'), require('babel-plugin-transform-es2015-destructuring'), require('babel-plugin-transform-es2015-duplicate-keys'), require('babel-plugin-transform-es2015-for-of'), require('babel-plugin-transform-es2015-function-name'), require('babel-plugin-transform-es2015-literals'), require('babel-plugin-transform-es2015-object-super'), require('babel-plugin-transform-es2015-parameters'), require('babel-plugin-transform-es2015-shorthand-properties'), require('babel-plugin-transform-es2015-spread'), require('babel-plugin-transform-es2015-sticky-regex'), require('babel-plugin-transform-es2015-template-literals'), require('babel-plugin-transform-es2015-typeof-symbol'), require('babel-plugin-transform-es2015-unicode-regex'), require('babel-plugin-transform-async-to-generator'), require('babel-plugin-transform-exponentiation-operator'), require('babel-plugin-transform-regenerator') ]; }
[ "function", "es5Plugins", "(", ")", "{", "return", "[", "require", "(", "'babel-plugin-check-es2015-constants'", ")", ",", "require", "(", "'babel-plugin-transform-es2015-arrow-functions'", ")", ",", "require", "(", "'babel-plugin-transform-es2015-block-scoped-functions'", ")", ",", "require", "(", "'babel-plugin-transform-es2015-block-scoping'", ")", ",", "require", "(", "'babel-plugin-transform-es2015-classes'", ")", ",", "require", "(", "'babel-plugin-transform-es2015-computed-properties'", ")", ",", "require", "(", "'babel-plugin-transform-es2015-destructuring'", ")", ",", "require", "(", "'babel-plugin-transform-es2015-duplicate-keys'", ")", ",", "require", "(", "'babel-plugin-transform-es2015-for-of'", ")", ",", "require", "(", "'babel-plugin-transform-es2015-function-name'", ")", ",", "require", "(", "'babel-plugin-transform-es2015-literals'", ")", ",", "require", "(", "'babel-plugin-transform-es2015-object-super'", ")", ",", "require", "(", "'babel-plugin-transform-es2015-parameters'", ")", ",", "require", "(", "'babel-plugin-transform-es2015-shorthand-properties'", ")", ",", "require", "(", "'babel-plugin-transform-es2015-spread'", ")", ",", "require", "(", "'babel-plugin-transform-es2015-sticky-regex'", ")", ",", "require", "(", "'babel-plugin-transform-es2015-template-literals'", ")", ",", "require", "(", "'babel-plugin-transform-es2015-typeof-symbol'", ")", ",", "require", "(", "'babel-plugin-transform-es2015-unicode-regex'", ")", ",", "require", "(", "'babel-plugin-transform-async-to-generator'", ")", ",", "require", "(", "'babel-plugin-transform-exponentiation-operator'", ")", ",", "require", "(", "'babel-plugin-transform-regenerator'", ")", "]", ";", "}" ]
Add default transformations
[ "Add", "default", "transformations" ]
fe3a2b9abcdb390805581f6db05f52ae322523b5
https://github.com/manvalls/wapp/blob/fe3a2b9abcdb390805581f6db05f52ae322523b5/utils/buildScripts.js#L95-L120
train
jmjuanes/get-args
index.js
function(obj, key, value) { if(typeof obj[key] === "undefined") { obj[key] = value; } else { //Check if the current option is not an array if(Array.isArray(obj[key]) === false) { obj[key] = [obj[key]]; } obj[key].push(value); } }
javascript
function(obj, key, value) { if(typeof obj[key] === "undefined") { obj[key] = value; } else { //Check if the current option is not an array if(Array.isArray(obj[key]) === false) { obj[key] = [obj[key]]; } obj[key].push(value); } }
[ "function", "(", "obj", ",", "key", ",", "value", ")", "{", "if", "(", "typeof", "obj", "[", "key", "]", "===", "\"undefined\"", ")", "{", "obj", "[", "key", "]", "=", "value", ";", "}", "else", "{", "if", "(", "Array", ".", "isArray", "(", "obj", "[", "key", "]", ")", "===", "false", ")", "{", "obj", "[", "key", "]", "=", "[", "obj", "[", "key", "]", "]", ";", "}", "obj", "[", "key", "]", ".", "push", "(", "value", ")", ";", "}", "}" ]
Save an option
[ "Save", "an", "option" ]
571850e9d71f02989beba3be778c23ecd495a93f
https://github.com/jmjuanes/get-args/blob/571850e9d71f02989beba3be778c23ecd495a93f/index.js#L2-L13
train
dreampiggy/functional.js
Retroactive/lib/data_structures/priority_queue.js
PriorityQueue
function PriorityQueue(initialItems) { var self = this; MinHeap.call(this, function (a, b) { return self.priority(a) < self.priority(b) ? -1 : 1; }); this._priority = {}; initialItems = initialItems || {}; Object.keys(initialItems).forEach(function (item) { self.insert(item, initialItems[item]); }); }
javascript
function PriorityQueue(initialItems) { var self = this; MinHeap.call(this, function (a, b) { return self.priority(a) < self.priority(b) ? -1 : 1; }); this._priority = {}; initialItems = initialItems || {}; Object.keys(initialItems).forEach(function (item) { self.insert(item, initialItems[item]); }); }
[ "function", "PriorityQueue", "(", "initialItems", ")", "{", "var", "self", "=", "this", ";", "MinHeap", ".", "call", "(", "this", ",", "function", "(", "a", ",", "b", ")", "{", "return", "self", ".", "priority", "(", "a", ")", "<", "self", ".", "priority", "(", "b", ")", "?", "-", "1", ":", "1", ";", "}", ")", ";", "this", ".", "_priority", "=", "{", "}", ";", "initialItems", "=", "initialItems", "||", "{", "}", ";", "Object", ".", "keys", "(", "initialItems", ")", ".", "forEach", "(", "function", "(", "item", ")", "{", "self", ".", "insert", "(", "item", ",", "initialItems", "[", "item", "]", ")", ";", "}", ")", ";", "}" ]
Extends the MinHeap with the only difference that the heap operations are performed based on the priority of the element and not on the element itself
[ "Extends", "the", "MinHeap", "with", "the", "only", "difference", "that", "the", "heap", "operations", "are", "performed", "based", "on", "the", "priority", "of", "the", "element", "and", "not", "on", "the", "element", "itself" ]
ec7b7213de7965659a8a1e8fa61438e3ae564260
https://github.com/dreampiggy/functional.js/blob/ec7b7213de7965659a8a1e8fa61438e3ae564260/Retroactive/lib/data_structures/priority_queue.js#L10-L23
train
KenanY/create-event
index.js
clean
function clean(type, options) { options = assign({}, defaults, options); if (type === 'dblclick') { options.detail = 2; } if (isString(options.key)) { options.key = keycode(options.key); } return options; }
javascript
function clean(type, options) { options = assign({}, defaults, options); if (type === 'dblclick') { options.detail = 2; } if (isString(options.key)) { options.key = keycode(options.key); } return options; }
[ "function", "clean", "(", "type", ",", "options", ")", "{", "options", "=", "assign", "(", "{", "}", ",", "defaults", ",", "options", ")", ";", "if", "(", "type", "===", "'dblclick'", ")", "{", "options", ".", "detail", "=", "2", ";", "}", "if", "(", "isString", "(", "options", ".", "key", ")", ")", "{", "options", ".", "key", "=", "keycode", "(", "options", ".", "key", ")", ";", "}", "return", "options", ";", "}" ]
Back an `options` object by defaults, and convert some convenience features. @param {String} type @param {Object} options @return {Object} [description]
[ "Back", "an", "options", "object", "by", "defaults", "and", "convert", "some", "convenience", "features", "." ]
82ceed57831f661261764612c9487d1d7386e1a0
https://github.com/KenanY/create-event/blob/82ceed57831f661261764612c9487d1d7386e1a0/index.js#L32-L41
train
KenanY/create-event
index.js
createMouseEvent
function createMouseEvent(type, options) { options = clean(type, options); var e = document.createEvent('MouseEvent'); e.initMouseEvent( type, options.bubbles, options.cancelable, options.view, options.detail, options.screenX, options.screenY, options.clientX, options.clientY, options.ctrl, options.alt, options.shift, options.meta, options.button, options.relatedTarget ); return e; }
javascript
function createMouseEvent(type, options) { options = clean(type, options); var e = document.createEvent('MouseEvent'); e.initMouseEvent( type, options.bubbles, options.cancelable, options.view, options.detail, options.screenX, options.screenY, options.clientX, options.clientY, options.ctrl, options.alt, options.shift, options.meta, options.button, options.relatedTarget ); return e; }
[ "function", "createMouseEvent", "(", "type", ",", "options", ")", "{", "options", "=", "clean", "(", "type", ",", "options", ")", ";", "var", "e", "=", "document", ".", "createEvent", "(", "'MouseEvent'", ")", ";", "e", ".", "initMouseEvent", "(", "type", ",", "options", ".", "bubbles", ",", "options", ".", "cancelable", ",", "options", ".", "view", ",", "options", ".", "detail", ",", "options", ".", "screenX", ",", "options", ".", "screenY", ",", "options", ".", "clientX", ",", "options", ".", "clientY", ",", "options", ".", "ctrl", ",", "options", ".", "alt", ",", "options", ".", "shift", ",", "options", ".", "meta", ",", "options", ".", "button", ",", "options", ".", "relatedTarget", ")", ";", "return", "e", ";", "}" ]
Create a non-IE mouse event. @param {String} type @param {Object} options
[ "Create", "a", "non", "-", "IE", "mouse", "event", "." ]
82ceed57831f661261764612c9487d1d7386e1a0
https://github.com/KenanY/create-event/blob/82ceed57831f661261764612c9487d1d7386e1a0/index.js#L49-L70
train
KenanY/create-event
index.js
createKeyboardEvent
function createKeyboardEvent(type, options) { options = clean(type, options); var e = document.createEvent('KeyboardEvent'); (e.initKeyEvent || e.initKeyboardEvent).call( e, type, options.bubbles, options.cancelable, options.view, options.ctrl, options.alt, options.shift, options.meta, options.key, options.key ); // http://stackoverflow.com/a/10520017 if (e.keyCode !== options.key) { Object.defineProperty(e, 'keyCode', { get: function() { return options.key; } }); Object.defineProperty(e, 'charCode', { get: function() { return options.key; } }); Object.defineProperty(e, 'which', { get: function() { return options.key; } }); Object.defineProperty(e, 'shiftKey', { get: function() { return options.shift; } }); } return e; }
javascript
function createKeyboardEvent(type, options) { options = clean(type, options); var e = document.createEvent('KeyboardEvent'); (e.initKeyEvent || e.initKeyboardEvent).call( e, type, options.bubbles, options.cancelable, options.view, options.ctrl, options.alt, options.shift, options.meta, options.key, options.key ); // http://stackoverflow.com/a/10520017 if (e.keyCode !== options.key) { Object.defineProperty(e, 'keyCode', { get: function() { return options.key; } }); Object.defineProperty(e, 'charCode', { get: function() { return options.key; } }); Object.defineProperty(e, 'which', { get: function() { return options.key; } }); Object.defineProperty(e, 'shiftKey', { get: function() { return options.shift; } }); } return e; }
[ "function", "createKeyboardEvent", "(", "type", ",", "options", ")", "{", "options", "=", "clean", "(", "type", ",", "options", ")", ";", "var", "e", "=", "document", ".", "createEvent", "(", "'KeyboardEvent'", ")", ";", "(", "e", ".", "initKeyEvent", "||", "e", ".", "initKeyboardEvent", ")", ".", "call", "(", "e", ",", "type", ",", "options", ".", "bubbles", ",", "options", ".", "cancelable", ",", "options", ".", "view", ",", "options", ".", "ctrl", ",", "options", ".", "alt", ",", "options", ".", "shift", ",", "options", ".", "meta", ",", "options", ".", "key", ",", "options", ".", "key", ")", ";", "if", "(", "e", ".", "keyCode", "!==", "options", ".", "key", ")", "{", "Object", ".", "defineProperty", "(", "e", ",", "'keyCode'", ",", "{", "get", ":", "function", "(", ")", "{", "return", "options", ".", "key", ";", "}", "}", ")", ";", "Object", ".", "defineProperty", "(", "e", ",", "'charCode'", ",", "{", "get", ":", "function", "(", ")", "{", "return", "options", ".", "key", ";", "}", "}", ")", ";", "Object", ".", "defineProperty", "(", "e", ",", "'which'", ",", "{", "get", ":", "function", "(", ")", "{", "return", "options", ".", "key", ";", "}", "}", ")", ";", "Object", ".", "defineProperty", "(", "e", ",", "'shiftKey'", ",", "{", "get", ":", "function", "(", ")", "{", "return", "options", ".", "shift", ";", "}", "}", ")", ";", "}", "return", "e", ";", "}" ]
Create a non-IE keyboard event. @param {String} type @param {Object} options
[ "Create", "a", "non", "-", "IE", "keyboard", "event", "." ]
82ceed57831f661261764612c9487d1d7386e1a0
https://github.com/KenanY/create-event/blob/82ceed57831f661261764612c9487d1d7386e1a0/index.js#L78-L112
train
KenanY/create-event
index.js
createEvent
function createEvent(type, options) { switch (type) { case 'dblclick': case 'click': return createMouseEvent(type, options); case 'keydown': case 'keyup': return createKeyboardEvent(type, options); } }
javascript
function createEvent(type, options) { switch (type) { case 'dblclick': case 'click': return createMouseEvent(type, options); case 'keydown': case 'keyup': return createKeyboardEvent(type, options); } }
[ "function", "createEvent", "(", "type", ",", "options", ")", "{", "switch", "(", "type", ")", "{", "case", "'dblclick'", ":", "case", "'click'", ":", "return", "createMouseEvent", "(", "type", ",", "options", ")", ";", "case", "'keydown'", ":", "case", "'keyup'", ":", "return", "createKeyboardEvent", "(", "type", ",", "options", ")", ";", "}", "}" ]
Create a non-IE event object. @param {String} type @param {Object} options
[ "Create", "a", "non", "-", "IE", "event", "object", "." ]
82ceed57831f661261764612c9487d1d7386e1a0
https://github.com/KenanY/create-event/blob/82ceed57831f661261764612c9487d1d7386e1a0/index.js#L120-L129
train
KenanY/create-event
index.js
createIeEvent
function createIeEvent(type, options) { options = clean(type, options); var e = document.createEventObject(); e.altKey = options.alt; e.bubbles = options.bubbles; e.button = options.button; e.cancelable = options.cancelable; e.clientX = options.clientX; e.clientY = options.clientY; e.ctrlKey = options.ctrl; e.detail = options.detail; e.metaKey = options.meta; e.screenX = options.screenX; e.screenY = options.screenY; e.shiftKey = options.shift; e.keyCode = options.key; e.charCode = options.key; e.view = options.view; return e; }
javascript
function createIeEvent(type, options) { options = clean(type, options); var e = document.createEventObject(); e.altKey = options.alt; e.bubbles = options.bubbles; e.button = options.button; e.cancelable = options.cancelable; e.clientX = options.clientX; e.clientY = options.clientY; e.ctrlKey = options.ctrl; e.detail = options.detail; e.metaKey = options.meta; e.screenX = options.screenX; e.screenY = options.screenY; e.shiftKey = options.shift; e.keyCode = options.key; e.charCode = options.key; e.view = options.view; return e; }
[ "function", "createIeEvent", "(", "type", ",", "options", ")", "{", "options", "=", "clean", "(", "type", ",", "options", ")", ";", "var", "e", "=", "document", ".", "createEventObject", "(", ")", ";", "e", ".", "altKey", "=", "options", ".", "alt", ";", "e", ".", "bubbles", "=", "options", ".", "bubbles", ";", "e", ".", "button", "=", "options", ".", "button", ";", "e", ".", "cancelable", "=", "options", ".", "cancelable", ";", "e", ".", "clientX", "=", "options", ".", "clientX", ";", "e", ".", "clientY", "=", "options", ".", "clientY", ";", "e", ".", "ctrlKey", "=", "options", ".", "ctrl", ";", "e", ".", "detail", "=", "options", ".", "detail", ";", "e", ".", "metaKey", "=", "options", ".", "meta", ";", "e", ".", "screenX", "=", "options", ".", "screenX", ";", "e", ".", "screenY", "=", "options", ".", "screenY", ";", "e", ".", "shiftKey", "=", "options", ".", "shift", ";", "e", ".", "keyCode", "=", "options", ".", "key", ";", "e", ".", "charCode", "=", "options", ".", "key", ";", "e", ".", "view", "=", "options", ".", "view", ";", "return", "e", ";", "}" ]
Create an IE event. @param {String} type @param {Object} options
[ "Create", "an", "IE", "event", "." ]
82ceed57831f661261764612c9487d1d7386e1a0
https://github.com/KenanY/create-event/blob/82ceed57831f661261764612c9487d1d7386e1a0/index.js#L137-L156
train
kltm/pup-tent
npm/pup-tent/pup-tent.js
_check_and_save
function _check_and_save(path){ //console.log('l@: ' + path); if( afs.exists_p(path) ){ if( afs.file_p(path) ){ //console.log('found file: ' + path); // Break into parts for saving if it is a full file. var filename = path; var slash_loc = path.lastIndexOf('/') + 1; if( slash_loc != 0 ){ filename = path.substr(slash_loc, path.length); } // Capture full path. path_cache[path] = path; zcache[path] = afs.read_file(path); // Capture flattened name. path_cache[filename] = path; zcache[filename] = afs.read_file(path); // Capture which is which. ns_cache_flat[filename] = true; ns_cache_full[path] = true; } } }
javascript
function _check_and_save(path){ //console.log('l@: ' + path); if( afs.exists_p(path) ){ if( afs.file_p(path) ){ //console.log('found file: ' + path); // Break into parts for saving if it is a full file. var filename = path; var slash_loc = path.lastIndexOf('/') + 1; if( slash_loc != 0 ){ filename = path.substr(slash_loc, path.length); } // Capture full path. path_cache[path] = path; zcache[path] = afs.read_file(path); // Capture flattened name. path_cache[filename] = path; zcache[filename] = afs.read_file(path); // Capture which is which. ns_cache_flat[filename] = true; ns_cache_full[path] = true; } } }
[ "function", "_check_and_save", "(", "path", ")", "{", "if", "(", "afs", ".", "exists_p", "(", "path", ")", ")", "{", "if", "(", "afs", ".", "file_p", "(", "path", ")", ")", "{", "var", "filename", "=", "path", ";", "var", "slash_loc", "=", "path", ".", "lastIndexOf", "(", "'/'", ")", "+", "1", ";", "if", "(", "slash_loc", "!=", "0", ")", "{", "filename", "=", "path", ".", "substr", "(", "slash_loc", ",", "path", ".", "length", ")", ";", "}", "path_cache", "[", "path", "]", "=", "path", ";", "zcache", "[", "path", "]", "=", "afs", ".", "read_file", "(", "path", ")", ";", "path_cache", "[", "filename", "]", "=", "path", ";", "zcache", "[", "filename", "]", "=", "afs", ".", "read_file", "(", "path", ")", ";", "ns_cache_flat", "[", "filename", "]", "=", "true", ";", "ns_cache_full", "[", "path", "]", "=", "true", ";", "}", "}", "}" ]
Make sure the file is there, then save it to the appropriate caches.
[ "Make", "sure", "the", "file", "is", "there", "then", "save", "it", "to", "the", "appropriate", "caches", "." ]
05e6b7761f2255fa6c8756c50c408514ec670b83
https://github.com/kltm/pup-tent/blob/05e6b7761f2255fa6c8756c50c408514ec670b83/npm/pup-tent/pup-tent.js#L225-L251
train
kltm/pup-tent
npm/pup-tent/pup-tent.js
_add_permanently_to
function _add_permanently_to(stack, item_or_list){ if( item_or_list && tcache[stack] ){ if( ! us.isArray(item_or_list) ){ // atom tcache[stack].push(item_or_list); }else{ // list tcache[stack] = tcache[stack].concat(item_or_list); } } return tcache[stack]; }
javascript
function _add_permanently_to(stack, item_or_list){ if( item_or_list && tcache[stack] ){ if( ! us.isArray(item_or_list) ){ // atom tcache[stack].push(item_or_list); }else{ // list tcache[stack] = tcache[stack].concat(item_or_list); } } return tcache[stack]; }
[ "function", "_add_permanently_to", "(", "stack", ",", "item_or_list", ")", "{", "if", "(", "item_or_list", "&&", "tcache", "[", "stack", "]", ")", "{", "if", "(", "!", "us", ".", "isArray", "(", "item_or_list", ")", ")", "{", "tcache", "[", "stack", "]", ".", "push", "(", "item_or_list", ")", ";", "}", "else", "{", "tcache", "[", "stack", "]", "=", "tcache", "[", "stack", "]", ".", "concat", "(", "item_or_list", ")", ";", "}", "}", "return", "tcache", "[", "stack", "]", ";", "}" ]
Permanently push an item or a list onto the internal list structure. Changes structure.
[ "Permanently", "push", "an", "item", "or", "a", "list", "onto", "the", "internal", "list", "structure", ".", "Changes", "structure", "." ]
05e6b7761f2255fa6c8756c50c408514ec670b83
https://github.com/kltm/pup-tent/blob/05e6b7761f2255fa6c8756c50c408514ec670b83/npm/pup-tent/pup-tent.js#L307-L316
train
kltm/pup-tent
npm/pup-tent/pup-tent.js
_set_common
function _set_common(stack_name, thing){ var ret = null; if( stack_name == 'css_libs' || stack_name == 'js_libs' || stack_name == 'js_vars' ){ _add_permanently_to(stack_name, thing); ret = thing; } //console.log('added ' + thing.length + ' to ' + stack_name); return ret; }
javascript
function _set_common(stack_name, thing){ var ret = null; if( stack_name == 'css_libs' || stack_name == 'js_libs' || stack_name == 'js_vars' ){ _add_permanently_to(stack_name, thing); ret = thing; } //console.log('added ' + thing.length + ' to ' + stack_name); return ret; }
[ "function", "_set_common", "(", "stack_name", ",", "thing", ")", "{", "var", "ret", "=", "null", ";", "if", "(", "stack_name", "==", "'css_libs'", "||", "stack_name", "==", "'js_libs'", "||", "stack_name", "==", "'js_vars'", ")", "{", "_add_permanently_to", "(", "stack_name", ",", "thing", ")", ";", "ret", "=", "thing", ";", "}", "return", "ret", ";", "}" ]
Permanently push an item or a list onto an internal list. Meant for all common variables across pup tent renderings.
[ "Permanently", "push", "an", "item", "or", "a", "list", "onto", "an", "internal", "list", ".", "Meant", "for", "all", "common", "variables", "across", "pup", "tent", "renderings", "." ]
05e6b7761f2255fa6c8756c50c408514ec670b83
https://github.com/kltm/pup-tent/blob/05e6b7761f2255fa6c8756c50c408514ec670b83/npm/pup-tent/pup-tent.js#L320-L331
train
kltm/pup-tent
npm/pup-tent/pup-tent.js
_use_zcache_p
function _use_zcache_p(yes_no){ if( yes_no == true ){ use_zcache_p = true; }else if( yes_no == false ){ use_zcache_p = false; } return use_zcache_p; }
javascript
function _use_zcache_p(yes_no){ if( yes_no == true ){ use_zcache_p = true; }else if( yes_no == false ){ use_zcache_p = false; } return use_zcache_p; }
[ "function", "_use_zcache_p", "(", "yes_no", ")", "{", "if", "(", "yes_no", "==", "true", ")", "{", "use_zcache_p", "=", "true", ";", "}", "else", "if", "(", "yes_no", "==", "false", ")", "{", "use_zcache_p", "=", "false", ";", "}", "return", "use_zcache_p", ";", "}" ]
Play with whether to use the cache or not.
[ "Play", "with", "whether", "to", "use", "the", "cache", "or", "not", "." ]
05e6b7761f2255fa6c8756c50c408514ec670b83
https://github.com/kltm/pup-tent/blob/05e6b7761f2255fa6c8756c50c408514ec670b83/npm/pup-tent/pup-tent.js#L334-L341
train
kltm/pup-tent
npm/pup-tent/pup-tent.js
_get
function _get(key){ var ret = null; // Pull from cache or re-read from fs. //console.log('key: ' + key) //console.log('use_zcache_p: ' + use_zcache_p) if( use_zcache_p ){ ret = zcache[key]; }else{ ret = afs.read_file(path_cache[key]); } return ret; }
javascript
function _get(key){ var ret = null; // Pull from cache or re-read from fs. //console.log('key: ' + key) //console.log('use_zcache_p: ' + use_zcache_p) if( use_zcache_p ){ ret = zcache[key]; }else{ ret = afs.read_file(path_cache[key]); } return ret; }
[ "function", "_get", "(", "key", ")", "{", "var", "ret", "=", "null", ";", "if", "(", "use_zcache_p", ")", "{", "ret", "=", "zcache", "[", "key", "]", ";", "}", "else", "{", "ret", "=", "afs", ".", "read_file", "(", "path_cache", "[", "key", "]", ")", ";", "}", "return", "ret", ";", "}" ]
Get a file, as string, from the cache by key; null otherwise.
[ "Get", "a", "file", "as", "string", "from", "the", "cache", "by", "key", ";", "null", "otherwise", "." ]
05e6b7761f2255fa6c8756c50c408514ec670b83
https://github.com/kltm/pup-tent/blob/05e6b7761f2255fa6c8756c50c408514ec670b83/npm/pup-tent/pup-tent.js#L344-L357
train
kltm/pup-tent
npm/pup-tent/pup-tent.js
_apply
function _apply (tmpl_name, tmpl_args){ var ret = null; var tmpl = _get(tmpl_name); if( tmpl ){ ret = mustache.render(tmpl, tmpl_args); } // if( tmpl ){ console.log('rendered string length: ' + ret.length); } return ret; }
javascript
function _apply (tmpl_name, tmpl_args){ var ret = null; var tmpl = _get(tmpl_name); if( tmpl ){ ret = mustache.render(tmpl, tmpl_args); } // if( tmpl ){ console.log('rendered string length: ' + ret.length); } return ret; }
[ "function", "_apply", "(", "tmpl_name", ",", "tmpl_args", ")", "{", "var", "ret", "=", "null", ";", "var", "tmpl", "=", "_get", "(", "tmpl_name", ")", ";", "if", "(", "tmpl", ")", "{", "ret", "=", "mustache", ".", "render", "(", "tmpl", ",", "tmpl_args", ")", ";", "}", "return", "ret", ";", "}" ]
Get a string from a named mustache template, with optional args.
[ "Get", "a", "string", "from", "a", "named", "mustache", "template", "with", "optional", "args", "." ]
05e6b7761f2255fa6c8756c50c408514ec670b83
https://github.com/kltm/pup-tent/blob/05e6b7761f2255fa6c8756c50c408514ec670b83/npm/pup-tent/pup-tent.js#L361-L372
train
skerit/protoblast
lib/diacritics.js
replaceSensitive
function replaceSensitive(chr, dbl) { var result, dbl_result; if (typeof baseDiacriticsMap[chr] === 'undefined') { return chr; } result = '[' + chr result += baseDiacriticsMap[chr]; result += ']'; if (dbl && baseDiacriticsMap[dbl]) { dbl_result = baseDiacriticsMap[dbl]; // Make the previous group optional, // but do require one of these groups then result = '?(?:' + result + '|[' + dbl_result + '])'; } return result; }
javascript
function replaceSensitive(chr, dbl) { var result, dbl_result; if (typeof baseDiacriticsMap[chr] === 'undefined') { return chr; } result = '[' + chr result += baseDiacriticsMap[chr]; result += ']'; if (dbl && baseDiacriticsMap[dbl]) { dbl_result = baseDiacriticsMap[dbl]; // Make the previous group optional, // but do require one of these groups then result = '?(?:' + result + '|[' + dbl_result + '])'; } return result; }
[ "function", "replaceSensitive", "(", "chr", ",", "dbl", ")", "{", "var", "result", ",", "dbl_result", ";", "if", "(", "typeof", "baseDiacriticsMap", "[", "chr", "]", "===", "'undefined'", ")", "{", "return", "chr", ";", "}", "result", "=", "'['", "+", "chr", "result", "+=", "baseDiacriticsMap", "[", "chr", "]", ";", "result", "+=", "']'", ";", "if", "(", "dbl", "&&", "baseDiacriticsMap", "[", "dbl", "]", ")", "{", "dbl_result", "=", "baseDiacriticsMap", "[", "dbl", "]", ";", "result", "=", "'?(?:'", "+", "result", "+", "'|['", "+", "dbl_result", "+", "'])'", ";", "}", "return", "result", ";", "}" ]
Replace the given character, but remain case sensitive @author Jelle De Loecker <[email protected]> @since 0.0.1 @version 0.6.4
[ "Replace", "the", "given", "character", "but", "remain", "case", "sensitive" ]
22f35b05611bd507d380782023179a3f6ec383ae
https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/diacritics.js#L169-L191
train
skerit/protoblast
lib/diacritics.js
replaceInsensitive
function replaceInsensitive(chr, dbl) { var lower = chr.toLowerCase(), upper = chr.toUpperCase(), result, dbl_result; if (lower == upper) { return chr; } result = '[' + lower + upper; result += (baseDiacriticsMap[lower]||''); result += (baseDiacriticsMap[upper]||''); result += ']'; if (dbl) { lower = dbl.toLowerCase(); upper = dbl.toUpperCase(); dbl_result = baseDiacriticsMap[lower] || ''; dbl_result += baseDiacriticsMap[upper] || ''; if (dbl_result) { // Make the previous group optional, // but do require one of these groups then result = '?(?:' + result + '|[' + dbl_result + '])'; } } return result; }
javascript
function replaceInsensitive(chr, dbl) { var lower = chr.toLowerCase(), upper = chr.toUpperCase(), result, dbl_result; if (lower == upper) { return chr; } result = '[' + lower + upper; result += (baseDiacriticsMap[lower]||''); result += (baseDiacriticsMap[upper]||''); result += ']'; if (dbl) { lower = dbl.toLowerCase(); upper = dbl.toUpperCase(); dbl_result = baseDiacriticsMap[lower] || ''; dbl_result += baseDiacriticsMap[upper] || ''; if (dbl_result) { // Make the previous group optional, // but do require one of these groups then result = '?(?:' + result + '|[' + dbl_result + '])'; } } return result; }
[ "function", "replaceInsensitive", "(", "chr", ",", "dbl", ")", "{", "var", "lower", "=", "chr", ".", "toLowerCase", "(", ")", ",", "upper", "=", "chr", ".", "toUpperCase", "(", ")", ",", "result", ",", "dbl_result", ";", "if", "(", "lower", "==", "upper", ")", "{", "return", "chr", ";", "}", "result", "=", "'['", "+", "lower", "+", "upper", ";", "result", "+=", "(", "baseDiacriticsMap", "[", "lower", "]", "||", "''", ")", ";", "result", "+=", "(", "baseDiacriticsMap", "[", "upper", "]", "||", "''", ")", ";", "result", "+=", "']'", ";", "if", "(", "dbl", ")", "{", "lower", "=", "dbl", ".", "toLowerCase", "(", ")", ";", "upper", "=", "dbl", ".", "toUpperCase", "(", ")", ";", "dbl_result", "=", "baseDiacriticsMap", "[", "lower", "]", "||", "''", ";", "dbl_result", "+=", "baseDiacriticsMap", "[", "upper", "]", "||", "''", ";", "if", "(", "dbl_result", ")", "{", "result", "=", "'?(?:'", "+", "result", "+", "'|['", "+", "dbl_result", "+", "'])'", ";", "}", "}", "return", "result", ";", "}" ]
Replace the given character without caring about the case @author Jelle De Loecker <[email protected]> @since 0.0.1 @version 0.6.4
[ "Replace", "the", "given", "character", "without", "caring", "about", "the", "case" ]
22f35b05611bd507d380782023179a3f6ec383ae
https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/diacritics.js#L200-L233
train
ericwooley/thewooleyway
packages/config/config.js
resolveConfig
function resolveConfig (fileName, options) { options = options || {} var schema = options.schema var resolvePackageJson = options.resolvePackageJson || false var fileNames = [fileName, resolvePackageJson ? 'package.json' : null].filter( item => !!item ) const results = upResolve(fileNames) return Promise.all(results.map(readFileAsync)) .then(parseFiles(options)) .then(validateSchema(schema)) .then(reduceConfigs) }
javascript
function resolveConfig (fileName, options) { options = options || {} var schema = options.schema var resolvePackageJson = options.resolvePackageJson || false var fileNames = [fileName, resolvePackageJson ? 'package.json' : null].filter( item => !!item ) const results = upResolve(fileNames) return Promise.all(results.map(readFileAsync)) .then(parseFiles(options)) .then(validateSchema(schema)) .then(reduceConfigs) }
[ "function", "resolveConfig", "(", "fileName", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", "var", "schema", "=", "options", ".", "schema", "var", "resolvePackageJson", "=", "options", ".", "resolvePackageJson", "||", "false", "var", "fileNames", "=", "[", "fileName", ",", "resolvePackageJson", "?", "'package.json'", ":", "null", "]", ".", "filter", "(", "item", "=>", "!", "!", "item", ")", "const", "results", "=", "upResolve", "(", "fileNames", ")", "return", "Promise", ".", "all", "(", "results", ".", "map", "(", "readFileAsync", ")", ")", ".", "then", "(", "parseFiles", "(", "options", ")", ")", ".", "then", "(", "validateSchema", "(", "schema", ")", ")", ".", "then", "(", "reduceConfigs", ")", "}" ]
Resolves config files, parses and combines them with priority to the nearest file @param {String} fileName @param {Object} options @param {Object} options.schema - validation options, see https://www.npmjs.com/package/jsonschema @param {boolean} options.resolvePackageJson - also include config from package.json @param {String} options.packageJsonKey - key to extract config from package json. eg {version: "0.0.1", deps: {...}, myConfg: {...}} => myConfig
[ "Resolves", "config", "files", "parses", "and", "combines", "them", "with", "priority", "to", "the", "nearest", "file" ]
2b4c13957fa2dd7f07d38b728b25ae0e26f7f68f
https://github.com/ericwooley/thewooleyway/blob/2b4c13957fa2dd7f07d38b728b25ae0e26f7f68f/packages/config/config.js#L14-L26
train
MaximeMaillet/dtorrent
src/workers/list.js
list
async function list(torrentHandler, config) { try { const list = await clientTorrent.list(config.pid); for(const i in list) { torrentHandler.handle(list[i], config.pid); } torrentHandler.checkState(list, config.pid); } catch (error) { lError(`Exception ${error}`); } }
javascript
async function list(torrentHandler, config) { try { const list = await clientTorrent.list(config.pid); for(const i in list) { torrentHandler.handle(list[i], config.pid); } torrentHandler.checkState(list, config.pid); } catch (error) { lError(`Exception ${error}`); } }
[ "async", "function", "list", "(", "torrentHandler", ",", "config", ")", "{", "try", "{", "const", "list", "=", "await", "clientTorrent", ".", "list", "(", "config", ".", "pid", ")", ";", "for", "(", "const", "i", "in", "list", ")", "{", "torrentHandler", ".", "handle", "(", "list", "[", "i", "]", ",", "config", ".", "pid", ")", ";", "}", "torrentHandler", ".", "checkState", "(", "list", ",", "config", ".", "pid", ")", ";", "}", "catch", "(", "error", ")", "{", "lError", "(", "`", "${", "error", "}", "`", ")", ";", "}", "}" ]
List all torrents @return {Promise.<void>}
[ "List", "all", "torrents" ]
ed7fdd8e8959a4f30f9a2f1afa3ec17c64bc5535
https://github.com/MaximeMaillet/dtorrent/blob/ed7fdd8e8959a4f30f9a2f1afa3ec17c64bc5535/src/workers/list.js#L27-L37
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/api/register/cache.js
load
function load() { if (process.env.BABEL_DISABLE_CACHE) return; process.on("exit", save); process.nextTick(save); if (!_pathExists2["default"].sync(FILENAME)) return; try { data = JSON.parse(_fs2["default"].readFileSync(FILENAME)); } catch (err) { return; } }
javascript
function load() { if (process.env.BABEL_DISABLE_CACHE) return; process.on("exit", save); process.nextTick(save); if (!_pathExists2["default"].sync(FILENAME)) return; try { data = JSON.parse(_fs2["default"].readFileSync(FILENAME)); } catch (err) { return; } }
[ "function", "load", "(", ")", "{", "if", "(", "process", ".", "env", ".", "BABEL_DISABLE_CACHE", ")", "return", ";", "process", ".", "on", "(", "\"exit\"", ",", "save", ")", ";", "process", ".", "nextTick", "(", "save", ")", ";", "if", "(", "!", "_pathExists2", "[", "\"default\"", "]", ".", "sync", "(", "FILENAME", ")", ")", "return", ";", "try", "{", "data", "=", "JSON", ".", "parse", "(", "_fs2", "[", "\"default\"", "]", ".", "readFileSync", "(", "FILENAME", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "return", ";", "}", "}" ]
Load cache from disk and parse.
[ "Load", "cache", "from", "disk", "and", "parse", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/api/register/cache.js#L44-L57
train
soup-js/omnistream
src/reactiveComponent.js
makeReactive
function makeReactive(componentDefinition, renderFn, ...stateStreamNames) { class ReactiveComponent extends PureComponent { constructor(props, context) { super(props, context); this.state = { childProps: {} } this.omnistream = this.context.omnistream; // Make the dispatch function accessible to be passed as a prop to child components. this.dispatch = this.omnistream.dispatch.bind(context.omnistream); this.dispatchObservableFn = this.omnistream.dispatchObservableFn.bind(context.omnistream); } componentDidMount() { // Creates a new substream for each action type based on the provided "streamNames" const stateStreams = stateStreamNames.map(name => this.omnistream.store[name]); const state$ = combineStreamsToState(stateStreams); // Subscribes to the props stream. This will trigger a re-render whenever a new action has been dispatched to // any filtered stream passed down as props to a component. this.subscription = state$.subscribe((props) => { this.setState({ childProps: Object.assign({}, this.props, props) }); }); } componentWillUnmount() { this.subscription.unsubscribe(); } render() { return renderFn.call(this, componentDefinition); } } ReactiveComponent.contextTypes = { omnistream: React.PropTypes.object.isRequired } return ReactiveComponent; }
javascript
function makeReactive(componentDefinition, renderFn, ...stateStreamNames) { class ReactiveComponent extends PureComponent { constructor(props, context) { super(props, context); this.state = { childProps: {} } this.omnistream = this.context.omnistream; // Make the dispatch function accessible to be passed as a prop to child components. this.dispatch = this.omnistream.dispatch.bind(context.omnistream); this.dispatchObservableFn = this.omnistream.dispatchObservableFn.bind(context.omnistream); } componentDidMount() { // Creates a new substream for each action type based on the provided "streamNames" const stateStreams = stateStreamNames.map(name => this.omnistream.store[name]); const state$ = combineStreamsToState(stateStreams); // Subscribes to the props stream. This will trigger a re-render whenever a new action has been dispatched to // any filtered stream passed down as props to a component. this.subscription = state$.subscribe((props) => { this.setState({ childProps: Object.assign({}, this.props, props) }); }); } componentWillUnmount() { this.subscription.unsubscribe(); } render() { return renderFn.call(this, componentDefinition); } } ReactiveComponent.contextTypes = { omnistream: React.PropTypes.object.isRequired } return ReactiveComponent; }
[ "function", "makeReactive", "(", "componentDefinition", ",", "renderFn", ",", "...", "stateStreamNames", ")", "{", "class", "ReactiveComponent", "extends", "PureComponent", "{", "constructor", "(", "props", ",", "context", ")", "{", "super", "(", "props", ",", "context", ")", ";", "this", ".", "state", "=", "{", "childProps", ":", "{", "}", "}", "this", ".", "omnistream", "=", "this", ".", "context", ".", "omnistream", ";", "this", ".", "dispatch", "=", "this", ".", "omnistream", ".", "dispatch", ".", "bind", "(", "context", ".", "omnistream", ")", ";", "this", ".", "dispatchObservableFn", "=", "this", ".", "omnistream", ".", "dispatchObservableFn", ".", "bind", "(", "context", ".", "omnistream", ")", ";", "}", "componentDidMount", "(", ")", "{", "const", "stateStreams", "=", "stateStreamNames", ".", "map", "(", "name", "=>", "this", ".", "omnistream", ".", "store", "[", "name", "]", ")", ";", "const", "state$", "=", "combineStreamsToState", "(", "stateStreams", ")", ";", "this", ".", "subscription", "=", "state$", ".", "subscribe", "(", "(", "props", ")", "=>", "{", "this", ".", "setState", "(", "{", "childProps", ":", "Object", ".", "assign", "(", "{", "}", ",", "this", ".", "props", ",", "props", ")", "}", ")", ";", "}", ")", ";", "}", "componentWillUnmount", "(", ")", "{", "this", ".", "subscription", ".", "unsubscribe", "(", ")", ";", "}", "render", "(", ")", "{", "return", "renderFn", ".", "call", "(", "this", ",", "componentDefinition", ")", ";", "}", "}", "ReactiveComponent", ".", "contextTypes", "=", "{", "omnistream", ":", "React", ".", "PropTypes", ".", "object", ".", "isRequired", "}", "return", "ReactiveComponent", ";", "}" ]
ReactiveComponent subscribes to a stream and re-renders when it receives new data.
[ "ReactiveComponent", "subscribes", "to", "a", "stream", "and", "re", "-", "renders", "when", "it", "receives", "new", "data", "." ]
8bec75ce4c6968e18e0736f6e4ce988312c130fc
https://github.com/soup-js/omnistream/blob/8bec75ce4c6968e18e0736f6e4ce988312c130fc/src/reactiveComponent.js#L15-L48
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/traversal/path/ancestry.js
getStatementParent
function getStatementParent() { var path = this; do { if (Array.isArray(path.container)) { return path; } } while (path = path.parentPath); }
javascript
function getStatementParent() { var path = this; do { if (Array.isArray(path.container)) { return path; } } while (path = path.parentPath); }
[ "function", "getStatementParent", "(", ")", "{", "var", "path", "=", "this", ";", "do", "{", "if", "(", "Array", ".", "isArray", "(", "path", ".", "container", ")", ")", "{", "return", "path", ";", "}", "}", "while", "(", "path", "=", "path", ".", "parentPath", ")", ";", "}" ]
Walk up the tree until we hit a parent node path in a list.
[ "Walk", "up", "the", "tree", "until", "we", "hit", "a", "parent", "node", "path", "in", "a", "list", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/traversal/path/ancestry.js#L57-L64
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/traversal/path/ancestry.js
getDeepestCommonAncestorFrom
function getDeepestCommonAncestorFrom(paths, filter) { // istanbul ignore next var _this = this; if (!paths.length) { return this; } if (paths.length === 1) { return paths[0]; } // minimum depth of the tree so we know the highest node var minDepth = Infinity; // last common ancestor var lastCommonIndex, lastCommon; // get the ancestors of the path, breaking when the parent exceeds ourselves var ancestries = paths.map(function (path) { var ancestry = []; do { ancestry.unshift(path); } while ((path = path.parentPath) && path !== _this); // save min depth to avoid going too far in if (ancestry.length < minDepth) { minDepth = ancestry.length; } return ancestry; }); // get the first ancestry so we have a seed to assess all other ancestries with var first = ancestries[0]; // check ancestor equality depthLoop: for (var i = 0; i < minDepth; i++) { var shouldMatch = first[i]; var _arr2 = ancestries; for (var _i2 = 0; _i2 < _arr2.length; _i2++) { var ancestry = _arr2[_i2]; if (ancestry[i] !== shouldMatch) { // we've hit a snag break depthLoop; } } // next iteration may break so store these so they can be returned lastCommonIndex = i; lastCommon = shouldMatch; } if (lastCommon) { if (filter) { return filter(lastCommon, lastCommonIndex, ancestries); } else { return lastCommon; } } else { throw new Error("Couldn't find intersection"); } }
javascript
function getDeepestCommonAncestorFrom(paths, filter) { // istanbul ignore next var _this = this; if (!paths.length) { return this; } if (paths.length === 1) { return paths[0]; } // minimum depth of the tree so we know the highest node var minDepth = Infinity; // last common ancestor var lastCommonIndex, lastCommon; // get the ancestors of the path, breaking when the parent exceeds ourselves var ancestries = paths.map(function (path) { var ancestry = []; do { ancestry.unshift(path); } while ((path = path.parentPath) && path !== _this); // save min depth to avoid going too far in if (ancestry.length < minDepth) { minDepth = ancestry.length; } return ancestry; }); // get the first ancestry so we have a seed to assess all other ancestries with var first = ancestries[0]; // check ancestor equality depthLoop: for (var i = 0; i < minDepth; i++) { var shouldMatch = first[i]; var _arr2 = ancestries; for (var _i2 = 0; _i2 < _arr2.length; _i2++) { var ancestry = _arr2[_i2]; if (ancestry[i] !== shouldMatch) { // we've hit a snag break depthLoop; } } // next iteration may break so store these so they can be returned lastCommonIndex = i; lastCommon = shouldMatch; } if (lastCommon) { if (filter) { return filter(lastCommon, lastCommonIndex, ancestries); } else { return lastCommon; } } else { throw new Error("Couldn't find intersection"); } }
[ "function", "getDeepestCommonAncestorFrom", "(", "paths", ",", "filter", ")", "{", "var", "_this", "=", "this", ";", "if", "(", "!", "paths", ".", "length", ")", "{", "return", "this", ";", "}", "if", "(", "paths", ".", "length", "===", "1", ")", "{", "return", "paths", "[", "0", "]", ";", "}", "var", "minDepth", "=", "Infinity", ";", "var", "lastCommonIndex", ",", "lastCommon", ";", "var", "ancestries", "=", "paths", ".", "map", "(", "function", "(", "path", ")", "{", "var", "ancestry", "=", "[", "]", ";", "do", "{", "ancestry", ".", "unshift", "(", "path", ")", ";", "}", "while", "(", "(", "path", "=", "path", ".", "parentPath", ")", "&&", "path", "!==", "_this", ")", ";", "if", "(", "ancestry", ".", "length", "<", "minDepth", ")", "{", "minDepth", "=", "ancestry", ".", "length", ";", "}", "return", "ancestry", ";", "}", ")", ";", "var", "first", "=", "ancestries", "[", "0", "]", ";", "depthLoop", ":", "for", "(", "var", "i", "=", "0", ";", "i", "<", "minDepth", ";", "i", "++", ")", "{", "var", "shouldMatch", "=", "first", "[", "i", "]", ";", "var", "_arr2", "=", "ancestries", ";", "for", "(", "var", "_i2", "=", "0", ";", "_i2", "<", "_arr2", ".", "length", ";", "_i2", "++", ")", "{", "var", "ancestry", "=", "_arr2", "[", "_i2", "]", ";", "if", "(", "ancestry", "[", "i", "]", "!==", "shouldMatch", ")", "{", "break", "depthLoop", ";", "}", "}", "lastCommonIndex", "=", "i", ";", "lastCommon", "=", "shouldMatch", ";", "}", "if", "(", "lastCommon", ")", "{", "if", "(", "filter", ")", "{", "return", "filter", "(", "lastCommon", ",", "lastCommonIndex", ",", "ancestries", ")", ";", "}", "else", "{", "return", "lastCommon", ";", "}", "}", "else", "{", "throw", "new", "Error", "(", "\"Couldn't find intersection\"", ")", ";", "}", "}" ]
Get the earliest path in the tree where the provided `paths` intersect. TODO: Possible optimisation target.
[ "Get", "the", "earliest", "path", "in", "the", "tree", "where", "the", "provided", "paths", "intersect", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/traversal/path/ancestry.js#L118-L183
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/traversal/path/ancestry.js
getAncestry
function getAncestry() { var path = this; var paths = []; do { paths.push(path); } while (path = path.parentPath); return paths; }
javascript
function getAncestry() { var path = this; var paths = []; do { paths.push(path); } while (path = path.parentPath); return paths; }
[ "function", "getAncestry", "(", ")", "{", "var", "path", "=", "this", ";", "var", "paths", "=", "[", "]", ";", "do", "{", "paths", ".", "push", "(", "path", ")", ";", "}", "while", "(", "path", "=", "path", ".", "parentPath", ")", ";", "return", "paths", ";", "}" ]
Build an array of node paths containing the entire ancestry of the current node path. NOTE: The current node path is included in this.
[ "Build", "an", "array", "of", "node", "paths", "containing", "the", "entire", "ancestry", "of", "the", "current", "node", "path", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/traversal/path/ancestry.js#L191-L198
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/traversal/path/ancestry.js
inShadow
function inShadow(key) { var path = this; do { if (path.isFunction()) { var shadow = path.node.shadow; if (shadow) { // this is because sometimes we may have a `shadow` value of: // // { this: false } // // we need to catch this case if `inShadow` has been passed a `key` if (!key || shadow[key] !== false) { return path; } } else if (path.isArrowFunctionExpression()) { return path; } // normal function, we've found our function context return null; } } while (path = path.parentPath); return null; }
javascript
function inShadow(key) { var path = this; do { if (path.isFunction()) { var shadow = path.node.shadow; if (shadow) { // this is because sometimes we may have a `shadow` value of: // // { this: false } // // we need to catch this case if `inShadow` has been passed a `key` if (!key || shadow[key] !== false) { return path; } } else if (path.isArrowFunctionExpression()) { return path; } // normal function, we've found our function context return null; } } while (path = path.parentPath); return null; }
[ "function", "inShadow", "(", "key", ")", "{", "var", "path", "=", "this", ";", "do", "{", "if", "(", "path", ".", "isFunction", "(", ")", ")", "{", "var", "shadow", "=", "path", ".", "node", ".", "shadow", ";", "if", "(", "shadow", ")", "{", "if", "(", "!", "key", "||", "shadow", "[", "key", "]", "!==", "false", ")", "{", "return", "path", ";", "}", "}", "else", "if", "(", "path", ".", "isArrowFunctionExpression", "(", ")", ")", "{", "return", "path", ";", "}", "return", "null", ";", "}", "}", "while", "(", "path", "=", "path", ".", "parentPath", ")", ";", "return", "null", ";", "}" ]
Check if we're inside a shadowed function.
[ "Check", "if", "we", "re", "inside", "a", "shadowed", "function", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/traversal/path/ancestry.js#L223-L246
train
Kronos-Integration/kronos-interceptor-line-header
src/line-header.js
getRealHeaderCheck
function getRealHeaderCheck(expectedHeader, caseSensitive, fieldNames) { return function (content) { let actualHeader; if (caseSensitive) { actualHeader = content; } else { actualHeader = arrayToUpperCase(content); expectedHeader = arrayToUpperCase(expectedHeader); } // the header must have all the expected columns but may have more return _getRealHeader(expectedHeader, actualHeader, fieldNames); }; }
javascript
function getRealHeaderCheck(expectedHeader, caseSensitive, fieldNames) { return function (content) { let actualHeader; if (caseSensitive) { actualHeader = content; } else { actualHeader = arrayToUpperCase(content); expectedHeader = arrayToUpperCase(expectedHeader); } // the header must have all the expected columns but may have more return _getRealHeader(expectedHeader, actualHeader, fieldNames); }; }
[ "function", "getRealHeaderCheck", "(", "expectedHeader", ",", "caseSensitive", ",", "fieldNames", ")", "{", "return", "function", "(", "content", ")", "{", "let", "actualHeader", ";", "if", "(", "caseSensitive", ")", "{", "actualHeader", "=", "content", ";", "}", "else", "{", "actualHeader", "=", "arrayToUpperCase", "(", "content", ")", ";", "expectedHeader", "=", "arrayToUpperCase", "(", "expectedHeader", ")", ";", "}", "return", "_getRealHeader", "(", "expectedHeader", ",", "actualHeader", ",", "fieldNames", ")", ";", "}", ";", "}" ]
Creates a check which will match the future columns names to there real position @param expectedHeader The expected header @param caseSensitive Is the header case sensitive @param fieldNames The fieldNames to use for each field. @return fieldMap This maps the fieldNames to the position in the array.
[ "Creates", "a", "check", "which", "will", "match", "the", "future", "columns", "names", "to", "there", "real", "position" ]
4baadc7782b94986abf947267a79d7328aebba18
https://github.com/Kronos-Integration/kronos-interceptor-line-header/blob/4baadc7782b94986abf947267a79d7328aebba18/src/line-header.js#L158-L172
train
Kronos-Integration/kronos-interceptor-line-header
src/line-header.js
getStrictCheck
function getStrictCheck(expectedHeader, caseSensitive, severity) { return function (content) { let actualHeader; if (caseSensitive) { actualHeader = content; } else { actualHeader = arrayToUpperCase(content); expectedHeader = arrayToUpperCase(expectedHeader); } if (expectedHeader.length !== actualHeader.length) { // If the length is different, it could not be the same return { errorCode: 'CHECK_HEADER_NO_STRICT_MATCH', severity: severity, message: 'The expected header [' + expectedHeader + '] has a different column count to the actual header [' + actualHeader + ']' }; } else { // no we need to compare field by field because the expected array could be an array of arrays // The expected header may contain alternative names for one column. for (let i = 0; i < expectedHeader.length; i++) { let match = false; const actualVal = actualHeader[i]; let expectedVal = expectedHeader[i]; if (Array.isArray(expectedVal)) { for (let j = 0; j < expectedVal.length; j++) { if (actualVal === expectedVal[j]) { match = true; } } } else { if (actualVal === expectedVal) { match = true; } } if (!match) { return { errorCode: 'CHECK_HEADER_NO_STRICT_MATCH', severity: severity, message: 'The expected header [' + expectedHeader + '] does not match the actual header [' + actualHeader + ']' }; } } } }; }
javascript
function getStrictCheck(expectedHeader, caseSensitive, severity) { return function (content) { let actualHeader; if (caseSensitive) { actualHeader = content; } else { actualHeader = arrayToUpperCase(content); expectedHeader = arrayToUpperCase(expectedHeader); } if (expectedHeader.length !== actualHeader.length) { // If the length is different, it could not be the same return { errorCode: 'CHECK_HEADER_NO_STRICT_MATCH', severity: severity, message: 'The expected header [' + expectedHeader + '] has a different column count to the actual header [' + actualHeader + ']' }; } else { // no we need to compare field by field because the expected array could be an array of arrays // The expected header may contain alternative names for one column. for (let i = 0; i < expectedHeader.length; i++) { let match = false; const actualVal = actualHeader[i]; let expectedVal = expectedHeader[i]; if (Array.isArray(expectedVal)) { for (let j = 0; j < expectedVal.length; j++) { if (actualVal === expectedVal[j]) { match = true; } } } else { if (actualVal === expectedVal) { match = true; } } if (!match) { return { errorCode: 'CHECK_HEADER_NO_STRICT_MATCH', severity: severity, message: 'The expected header [' + expectedHeader + '] does not match the actual header [' + actualHeader + ']' }; } } } }; }
[ "function", "getStrictCheck", "(", "expectedHeader", ",", "caseSensitive", ",", "severity", ")", "{", "return", "function", "(", "content", ")", "{", "let", "actualHeader", ";", "if", "(", "caseSensitive", ")", "{", "actualHeader", "=", "content", ";", "}", "else", "{", "actualHeader", "=", "arrayToUpperCase", "(", "content", ")", ";", "expectedHeader", "=", "arrayToUpperCase", "(", "expectedHeader", ")", ";", "}", "if", "(", "expectedHeader", ".", "length", "!==", "actualHeader", ".", "length", ")", "{", "return", "{", "errorCode", ":", "'CHECK_HEADER_NO_STRICT_MATCH'", ",", "severity", ":", "severity", ",", "message", ":", "'The expected header ['", "+", "expectedHeader", "+", "'] has a different column count to the actual header ['", "+", "actualHeader", "+", "']'", "}", ";", "}", "else", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "expectedHeader", ".", "length", ";", "i", "++", ")", "{", "let", "match", "=", "false", ";", "const", "actualVal", "=", "actualHeader", "[", "i", "]", ";", "let", "expectedVal", "=", "expectedHeader", "[", "i", "]", ";", "if", "(", "Array", ".", "isArray", "(", "expectedVal", ")", ")", "{", "for", "(", "let", "j", "=", "0", ";", "j", "<", "expectedVal", ".", "length", ";", "j", "++", ")", "{", "if", "(", "actualVal", "===", "expectedVal", "[", "j", "]", ")", "{", "match", "=", "true", ";", "}", "}", "}", "else", "{", "if", "(", "actualVal", "===", "expectedVal", ")", "{", "match", "=", "true", ";", "}", "}", "if", "(", "!", "match", ")", "{", "return", "{", "errorCode", ":", "'CHECK_HEADER_NO_STRICT_MATCH'", ",", "severity", ":", "severity", ",", "message", ":", "'The expected header ['", "+", "expectedHeader", "+", "'] does not match the actual header ['", "+", "actualHeader", "+", "']'", "}", ";", "}", "}", "}", "}", ";", "}" ]
returns the Strict header check @param expectedHeader The expected header
[ "returns", "the", "Strict", "header", "check" ]
4baadc7782b94986abf947267a79d7328aebba18
https://github.com/Kronos-Integration/kronos-interceptor-line-header/blob/4baadc7782b94986abf947267a79d7328aebba18/src/line-header.js#L277-L328
train
Kronos-Integration/kronos-interceptor-line-header
src/line-header.js
getMissingColumnCheck
function getMissingColumnCheck(expectedHeader, caseSensitive, severity) { return function (content) { let actualHeader; if (caseSensitive) { actualHeader = content; } else { actualHeader = arrayToUpperCase(content); expectedHeader = arrayToUpperCase(expectedHeader); } // the header must have all the expected columns but may have more let err = _missingColumns(expectedHeader, actualHeader); if (err) { return { errorCode: 'CHECK_HEADER_MISSING_COLUMNS', severity: severity, message: 'The following columns are missing in the header: [' + err.join() + ']' }; } }; }
javascript
function getMissingColumnCheck(expectedHeader, caseSensitive, severity) { return function (content) { let actualHeader; if (caseSensitive) { actualHeader = content; } else { actualHeader = arrayToUpperCase(content); expectedHeader = arrayToUpperCase(expectedHeader); } // the header must have all the expected columns but may have more let err = _missingColumns(expectedHeader, actualHeader); if (err) { return { errorCode: 'CHECK_HEADER_MISSING_COLUMNS', severity: severity, message: 'The following columns are missing in the header: [' + err.join() + ']' }; } }; }
[ "function", "getMissingColumnCheck", "(", "expectedHeader", ",", "caseSensitive", ",", "severity", ")", "{", "return", "function", "(", "content", ")", "{", "let", "actualHeader", ";", "if", "(", "caseSensitive", ")", "{", "actualHeader", "=", "content", ";", "}", "else", "{", "actualHeader", "=", "arrayToUpperCase", "(", "content", ")", ";", "expectedHeader", "=", "arrayToUpperCase", "(", "expectedHeader", ")", ";", "}", "let", "err", "=", "_missingColumns", "(", "expectedHeader", ",", "actualHeader", ")", ";", "if", "(", "err", ")", "{", "return", "{", "errorCode", ":", "'CHECK_HEADER_MISSING_COLUMNS'", ",", "severity", ":", "severity", ",", "message", ":", "'The following columns are missing in the header: ['", "+", "err", ".", "join", "(", ")", "+", "']'", "}", ";", "}", "}", ";", "}" ]
Creates the missing column check @param expectedHeader The expected header @param caseSensitive Is the header case sensitive @param severity The severity if the check fails
[ "Creates", "the", "missing", "column", "check" ]
4baadc7782b94986abf947267a79d7328aebba18
https://github.com/Kronos-Integration/kronos-interceptor-line-header/blob/4baadc7782b94986abf947267a79d7328aebba18/src/line-header.js#L420-L441
train
Kronos-Integration/kronos-interceptor-line-header
src/line-header.js
getMandatoryColumnCheck
function getMandatoryColumnCheck(mandatoryColumns, severity) { /** * @param the coluns found and matched. */ return function (foundColumns) { // the header must have all the expected columns but may have more let err = _missingColumns(mandatoryColumns, foundColumns); if (err) { return { errorCode: 'CHECK_HEADER_MANDATORY_COLUMNS', severity: severity, message: 'The following columns are missing in the header and are mandatory: [' + err.join() + ']' }; } }; }
javascript
function getMandatoryColumnCheck(mandatoryColumns, severity) { /** * @param the coluns found and matched. */ return function (foundColumns) { // the header must have all the expected columns but may have more let err = _missingColumns(mandatoryColumns, foundColumns); if (err) { return { errorCode: 'CHECK_HEADER_MANDATORY_COLUMNS', severity: severity, message: 'The following columns are missing in the header and are mandatory: [' + err.join() + ']' }; } }; }
[ "function", "getMandatoryColumnCheck", "(", "mandatoryColumns", ",", "severity", ")", "{", "return", "function", "(", "foundColumns", ")", "{", "let", "err", "=", "_missingColumns", "(", "mandatoryColumns", ",", "foundColumns", ")", ";", "if", "(", "err", ")", "{", "return", "{", "errorCode", ":", "'CHECK_HEADER_MANDATORY_COLUMNS'", ",", "severity", ":", "severity", ",", "message", ":", "'The following columns are missing in the header and are mandatory: ['", "+", "err", ".", "join", "(", ")", "+", "']'", "}", ";", "}", "}", ";", "}" ]
Creates the mandatory column check. This is every time case sensitive as we used the associated column names. @param mandatoryColumns The mandatory columns. BUT these are the associated fieldnames, not the original column names @param severity The severity if the check fails
[ "Creates", "the", "mandatory", "column", "check", ".", "This", "is", "every", "time", "case", "sensitive", "as", "we", "used", "the", "associated", "column", "names", "." ]
4baadc7782b94986abf947267a79d7328aebba18
https://github.com/Kronos-Integration/kronos-interceptor-line-header/blob/4baadc7782b94986abf947267a79d7328aebba18/src/line-header.js#L449-L466
train
panta82/readdir-plus
lib/vars.js
ReaddirPlusFile
function ReaddirPlusFile(source) { /** * File name. Eg. "file.txt" * @type {string} */ this.name = null; /** * Full path. Eg. "/home/myname/path/to/directory/subdir/file.txt" * @type {string} */ this.path = null; /** * Relative path, based on the directory you submitted to readdir. Eg. "subdir/file.txt" * @type {string} */ this.relativePath = null; /** * File name without extension. Eg. "file" * @type {string} */ this.basename = null; /** * Extension with leading dot. Eg. ".txt" * @type {string} */ this.extension = null; /** * One of vars.FILE_TYPES * @type {FILE_TYPES} */ this.type = null; /** * File or directory stats * @type {fs.Stats} */ this.stat = null; Object.assign(this, source); }
javascript
function ReaddirPlusFile(source) { /** * File name. Eg. "file.txt" * @type {string} */ this.name = null; /** * Full path. Eg. "/home/myname/path/to/directory/subdir/file.txt" * @type {string} */ this.path = null; /** * Relative path, based on the directory you submitted to readdir. Eg. "subdir/file.txt" * @type {string} */ this.relativePath = null; /** * File name without extension. Eg. "file" * @type {string} */ this.basename = null; /** * Extension with leading dot. Eg. ".txt" * @type {string} */ this.extension = null; /** * One of vars.FILE_TYPES * @type {FILE_TYPES} */ this.type = null; /** * File or directory stats * @type {fs.Stats} */ this.stat = null; Object.assign(this, source); }
[ "function", "ReaddirPlusFile", "(", "source", ")", "{", "this", ".", "name", "=", "null", ";", "this", ".", "path", "=", "null", ";", "this", ".", "relativePath", "=", "null", ";", "this", ".", "basename", "=", "null", ";", "this", ".", "extension", "=", "null", ";", "this", ".", "type", "=", "null", ";", "this", ".", "stat", "=", "null", ";", "Object", ".", "assign", "(", "this", ",", "source", ")", ";", "}" ]
File data returned by readdirPlus @param source
[ "File", "data", "returned", "by", "readdirPlus" ]
a3c0dc9356ebbcdfebf7565286709984b0770720
https://github.com/panta82/readdir-plus/blob/a3c0dc9356ebbcdfebf7565286709984b0770720/lib/vars.js#L225-L269
train
jonschlinkert/to-exports
index.js
toExports
function toExports(dir, patterns, recurse, options, fn) { if (arguments.length === 1 && !isGlob(dir)) { var key = 'toExports:' + dir; if (cache.hasOwnProperty(key)) { return cache[key]; } var result = lookup(dir, false, {}).reduce(function (res, fp) { if (filter(fp, fn)) { res[basename(fp)] = read(fp, fn); } return res; }, {}); return (cache[key] = result); } return explode.apply(explode, arguments); }
javascript
function toExports(dir, patterns, recurse, options, fn) { if (arguments.length === 1 && !isGlob(dir)) { var key = 'toExports:' + dir; if (cache.hasOwnProperty(key)) { return cache[key]; } var result = lookup(dir, false, {}).reduce(function (res, fp) { if (filter(fp, fn)) { res[basename(fp)] = read(fp, fn); } return res; }, {}); return (cache[key] = result); } return explode.apply(explode, arguments); }
[ "function", "toExports", "(", "dir", ",", "patterns", ",", "recurse", ",", "options", ",", "fn", ")", "{", "if", "(", "arguments", ".", "length", "===", "1", "&&", "!", "isGlob", "(", "dir", ")", ")", "{", "var", "key", "=", "'toExports:'", "+", "dir", ";", "if", "(", "cache", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "return", "cache", "[", "key", "]", ";", "}", "var", "result", "=", "lookup", "(", "dir", ",", "false", ",", "{", "}", ")", ".", "reduce", "(", "function", "(", "res", ",", "fp", ")", "{", "if", "(", "filter", "(", "fp", ",", "fn", ")", ")", "{", "res", "[", "basename", "(", "fp", ")", "]", "=", "read", "(", "fp", ",", "fn", ")", ";", "}", "return", "res", ";", "}", ",", "{", "}", ")", ";", "return", "(", "cache", "[", "key", "]", "=", "result", ")", ";", "}", "return", "explode", ".", "apply", "(", "explode", ",", "arguments", ")", ";", "}" ]
Export files from the give `directory` filtering the results with @param {String} `directory` Use `__dirname` for the immediate directory. @param {String|Array} `patterns` Glob patterns to use for matching. @param {Boolean} `recurse` Pass `true` to recurse deeper than the current directory. @param {String} `options` @param {Function} `fn` Callback for filtering. @return {String}
[ "Export", "files", "from", "the", "give", "directory", "filtering", "the", "results", "with" ]
93471d63094718ca5fd32d99a9abada8008f1d73
https://github.com/jonschlinkert/to-exports/blob/93471d63094718ca5fd32d99a9abada8008f1d73/index.js#L36-L53
train
jonschlinkert/to-exports
index.js
lookup
function lookup(dir, recurse) { if (typeof dir !== 'string') { throw new Error('export-files expects a string as the first argument.'); } var key = 'lookup:' + dir + ('' + recurse); if (cache.hasOwnProperty(key)) { return cache[key]; } var files = fs.readdirSync(dir); var len = files.length; var res = []; if (recurse === false) return map(files, resolve(dir)); while (len--) { var fp = path.resolve(dir, files[len]); if (isDir(fp)) { res.push.apply(res, lookup(fp, recurse)); } else { res.push(fp); } } return (cache[key] = res); }
javascript
function lookup(dir, recurse) { if (typeof dir !== 'string') { throw new Error('export-files expects a string as the first argument.'); } var key = 'lookup:' + dir + ('' + recurse); if (cache.hasOwnProperty(key)) { return cache[key]; } var files = fs.readdirSync(dir); var len = files.length; var res = []; if (recurse === false) return map(files, resolve(dir)); while (len--) { var fp = path.resolve(dir, files[len]); if (isDir(fp)) { res.push.apply(res, lookup(fp, recurse)); } else { res.push(fp); } } return (cache[key] = res); }
[ "function", "lookup", "(", "dir", ",", "recurse", ")", "{", "if", "(", "typeof", "dir", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'export-files expects a string as the first argument.'", ")", ";", "}", "var", "key", "=", "'lookup:'", "+", "dir", "+", "(", "''", "+", "recurse", ")", ";", "if", "(", "cache", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "return", "cache", "[", "key", "]", ";", "}", "var", "files", "=", "fs", ".", "readdirSync", "(", "dir", ")", ";", "var", "len", "=", "files", ".", "length", ";", "var", "res", "=", "[", "]", ";", "if", "(", "recurse", "===", "false", ")", "return", "map", "(", "files", ",", "resolve", "(", "dir", ")", ")", ";", "while", "(", "len", "--", ")", "{", "var", "fp", "=", "path", ".", "resolve", "(", "dir", ",", "files", "[", "len", "]", ")", ";", "if", "(", "isDir", "(", "fp", ")", ")", "{", "res", ".", "push", ".", "apply", "(", "res", ",", "lookup", "(", "fp", ",", "recurse", ")", ")", ";", "}", "else", "{", "res", ".", "push", "(", "fp", ")", ";", "}", "}", "return", "(", "cache", "[", "key", "]", "=", "res", ")", ";", "}" ]
Recursively read directories, starting with the given `dir`. @param {String} `dir` @param {Boolean} `recurse` Should the function recurse? @return {Array} Returns an array of files.
[ "Recursively", "read", "directories", "starting", "with", "the", "given", "dir", "." ]
93471d63094718ca5fd32d99a9abada8008f1d73
https://github.com/jonschlinkert/to-exports/blob/93471d63094718ca5fd32d99a9abada8008f1d73/index.js#L94-L119
train
jonschlinkert/to-exports
index.js
renameKey
function renameKey(fp, opts) { if (opts && opts.renameKey) { return opts.renameKey(fp, opts); } return basename(fp); }
javascript
function renameKey(fp, opts) { if (opts && opts.renameKey) { return opts.renameKey(fp, opts); } return basename(fp); }
[ "function", "renameKey", "(", "fp", ",", "opts", ")", "{", "if", "(", "opts", "&&", "opts", ".", "renameKey", ")", "{", "return", "opts", ".", "renameKey", "(", "fp", ",", "opts", ")", ";", "}", "return", "basename", "(", "fp", ")", ";", "}" ]
Rename object keys with a custom function. If no function is passed, the basname is returned.
[ "Rename", "object", "keys", "with", "a", "custom", "function", ".", "If", "no", "function", "is", "passed", "the", "basname", "is", "returned", "." ]
93471d63094718ca5fd32d99a9abada8008f1d73
https://github.com/jonschlinkert/to-exports/blob/93471d63094718ca5fd32d99a9abada8008f1d73/index.js#L127-L132
train
jonschlinkert/to-exports
index.js
read
function read(fp, opts, fn) { opts = opts || {}; opts.encoding = opts.encoding || 'utf8'; if (opts.read) { return opts.read(fp, opts); } else if (fn) { return fn(fp, opts); } if (endsWith(fp, '.js')) { return tryRequire(fp); } else { var str = tryCatch(fs.readFileSync, fp, opts); if (endsWith(fp, '.json')) { return tryCatch(JSON.parse, str); } return str; } }
javascript
function read(fp, opts, fn) { opts = opts || {}; opts.encoding = opts.encoding || 'utf8'; if (opts.read) { return opts.read(fp, opts); } else if (fn) { return fn(fp, opts); } if (endsWith(fp, '.js')) { return tryRequire(fp); } else { var str = tryCatch(fs.readFileSync, fp, opts); if (endsWith(fp, '.json')) { return tryCatch(JSON.parse, str); } return str; } }
[ "function", "read", "(", "fp", ",", "opts", ",", "fn", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "opts", ".", "encoding", "=", "opts", ".", "encoding", "||", "'utf8'", ";", "if", "(", "opts", ".", "read", ")", "{", "return", "opts", ".", "read", "(", "fp", ",", "opts", ")", ";", "}", "else", "if", "(", "fn", ")", "{", "return", "fn", "(", "fp", ",", "opts", ")", ";", "}", "if", "(", "endsWith", "(", "fp", ",", "'.js'", ")", ")", "{", "return", "tryRequire", "(", "fp", ")", ";", "}", "else", "{", "var", "str", "=", "tryCatch", "(", "fs", ".", "readFileSync", ",", "fp", ",", "opts", ")", ";", "if", "(", "endsWith", "(", "fp", ",", "'.json'", ")", ")", "{", "return", "tryCatch", "(", "JSON", ".", "parse", ",", "str", ")", ";", "}", "return", "str", ";", "}", "}" ]
Read or require the given file with `opts`
[ "Read", "or", "require", "the", "given", "file", "with", "opts" ]
93471d63094718ca5fd32d99a9abada8008f1d73
https://github.com/jonschlinkert/to-exports/blob/93471d63094718ca5fd32d99a9abada8008f1d73/index.js#L146-L165
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/types/validators.js
isBinding
function isBinding(node, parent) { var keys = _retrievers.getBindingIdentifiers.keys[parent.type]; if (keys) { for (var i = 0; i < keys.length; i++) { var key = keys[i]; var val = parent[key]; if (Array.isArray(val)) { if (val.indexOf(node) >= 0) return true; } else { if (val === node) return true; } } } return false; }
javascript
function isBinding(node, parent) { var keys = _retrievers.getBindingIdentifiers.keys[parent.type]; if (keys) { for (var i = 0; i < keys.length; i++) { var key = keys[i]; var val = parent[key]; if (Array.isArray(val)) { if (val.indexOf(node) >= 0) return true; } else { if (val === node) return true; } } } return false; }
[ "function", "isBinding", "(", "node", ",", "parent", ")", "{", "var", "keys", "=", "_retrievers", ".", "getBindingIdentifiers", ".", "keys", "[", "parent", ".", "type", "]", ";", "if", "(", "keys", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "var", "key", "=", "keys", "[", "i", "]", ";", "var", "val", "=", "parent", "[", "key", "]", ";", "if", "(", "Array", ".", "isArray", "(", "val", ")", ")", "{", "if", "(", "val", ".", "indexOf", "(", "node", ")", ">=", "0", ")", "return", "true", ";", "}", "else", "{", "if", "(", "val", "===", "node", ")", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
Check if the input `node` is a binding identifier.
[ "Check", "if", "the", "input", "node", "is", "a", "binding", "identifier", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/types/validators.js#L37-L52
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/types/validators.js
isSpecifierDefault
function isSpecifierDefault(specifier) { return t.isImportDefaultSpecifier(specifier) || t.isIdentifier(specifier.imported || specifier.exported, { name: "default" }); }
javascript
function isSpecifierDefault(specifier) { return t.isImportDefaultSpecifier(specifier) || t.isIdentifier(specifier.imported || specifier.exported, { name: "default" }); }
[ "function", "isSpecifierDefault", "(", "specifier", ")", "{", "return", "t", ".", "isImportDefaultSpecifier", "(", "specifier", ")", "||", "t", ".", "isIdentifier", "(", "specifier", ".", "imported", "||", "specifier", ".", "exported", ",", "{", "name", ":", "\"default\"", "}", ")", ";", "}" ]
Check if the input `specifier` is a `default` import or export.
[ "Check", "if", "the", "input", "specifier", "is", "a", "default", "import", "or", "export", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/types/validators.js#L216-L218
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/types/validators.js
isScope
function isScope(node, parent) { if (t.isBlockStatement(node) && t.isFunction(parent, { body: node })) { return false; } return t.isScopable(node); }
javascript
function isScope(node, parent) { if (t.isBlockStatement(node) && t.isFunction(parent, { body: node })) { return false; } return t.isScopable(node); }
[ "function", "isScope", "(", "node", ",", "parent", ")", "{", "if", "(", "t", ".", "isBlockStatement", "(", "node", ")", "&&", "t", ".", "isFunction", "(", "parent", ",", "{", "body", ":", "node", "}", ")", ")", "{", "return", "false", ";", "}", "return", "t", ".", "isScopable", "(", "node", ")", ";", "}" ]
Check if the input `node` is a scope.
[ "Check", "if", "the", "input", "node", "is", "a", "scope", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/types/validators.js#L224-L230
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/types/validators.js
isImmutable
function isImmutable(node) { if (t.isType(node.type, "Immutable")) return true; if (t.isLiteral(node)) { if (node.regex) { // regexs are mutable return false; } else { // immutable! return true; } } else if (t.isIdentifier(node)) { if (node.name === "undefined") { // immutable! return true; } else { // no idea... return false; } } return false; }
javascript
function isImmutable(node) { if (t.isType(node.type, "Immutable")) return true; if (t.isLiteral(node)) { if (node.regex) { // regexs are mutable return false; } else { // immutable! return true; } } else if (t.isIdentifier(node)) { if (node.name === "undefined") { // immutable! return true; } else { // no idea... return false; } } return false; }
[ "function", "isImmutable", "(", "node", ")", "{", "if", "(", "t", ".", "isType", "(", "node", ".", "type", ",", "\"Immutable\"", ")", ")", "return", "true", ";", "if", "(", "t", ".", "isLiteral", "(", "node", ")", ")", "{", "if", "(", "node", ".", "regex", ")", "{", "return", "false", ";", "}", "else", "{", "return", "true", ";", "}", "}", "else", "if", "(", "t", ".", "isIdentifier", "(", "node", ")", ")", "{", "if", "(", "node", ".", "name", "===", "\"undefined\"", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}", "return", "false", ";", "}" ]
Check if the input `node` is definitely immutable.
[ "Check", "if", "the", "input", "node", "is", "definitely", "immutable", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/types/validators.js#L236-L258
train
kevoree/kevoree-js
tools/kevoree-kevscript/lib/KevScript.js
function (data, ctxModel, ctxVars) { const options = xtend(this.options, { ctxVars, logger: this.logger }); const parser = new kevs.Parser(); const ast = parser.parse(data); if (ast.type !== 'kevScript') { const err = new Error('Unable to parse script'); err.parser = ast; err.warnings = options.warnings || []; return Promise.reject(err); } else { return interpreter(ast, ctxModel, options) .then(({ error, warnings, model }) => { if (error) { error.warnings = warnings; throw error; } else { return { model, warnings }; } }); } }
javascript
function (data, ctxModel, ctxVars) { const options = xtend(this.options, { ctxVars, logger: this.logger }); const parser = new kevs.Parser(); const ast = parser.parse(data); if (ast.type !== 'kevScript') { const err = new Error('Unable to parse script'); err.parser = ast; err.warnings = options.warnings || []; return Promise.reject(err); } else { return interpreter(ast, ctxModel, options) .then(({ error, warnings, model }) => { if (error) { error.warnings = warnings; throw error; } else { return { model, warnings }; } }); } }
[ "function", "(", "data", ",", "ctxModel", ",", "ctxVars", ")", "{", "const", "options", "=", "xtend", "(", "this", ".", "options", ",", "{", "ctxVars", ",", "logger", ":", "this", ".", "logger", "}", ")", ";", "const", "parser", "=", "new", "kevs", ".", "Parser", "(", ")", ";", "const", "ast", "=", "parser", ".", "parse", "(", "data", ")", ";", "if", "(", "ast", ".", "type", "!==", "'kevScript'", ")", "{", "const", "err", "=", "new", "Error", "(", "'Unable to parse script'", ")", ";", "err", ".", "parser", "=", "ast", ";", "err", ".", "warnings", "=", "options", ".", "warnings", "||", "[", "]", ";", "return", "Promise", ".", "reject", "(", "err", ")", ";", "}", "else", "{", "return", "interpreter", "(", "ast", ",", "ctxModel", ",", "options", ")", ".", "then", "(", "(", "{", "error", ",", "warnings", ",", "model", "}", ")", "=>", "{", "if", "(", "error", ")", "{", "error", ".", "warnings", "=", "warnings", ";", "throw", "error", ";", "}", "else", "{", "return", "{", "model", ",", "warnings", "}", ";", "}", "}", ")", ";", "}", "}" ]
Parses given KevScript source-code in parameter 'data' and returns a ContainerRoot. @param {String} data string @param {Object|Function} [ctxModel] a model to "start" on (in order not to create a model from scratch) @param {Object|Function} [ctxVars] context variables to be accessible from the KevScript @returns {Promise<{ ContainerRoot, Array<Warning>}} promise @throws Error on SyntaxError and on source code validity and such
[ "Parses", "given", "KevScript", "source", "-", "code", "in", "parameter", "data", "and", "returns", "a", "ContainerRoot", "." ]
7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd
https://github.com/kevoree/kevoree-js/blob/7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd/tools/kevoree-kevscript/lib/KevScript.js#L36-L57
train
sumeetdas/Meow
lib/utils.js
setPropertyVal
function setPropertyVal (pObj, pProp, pNewVal) { if (typeof pProp === 'string') { pProp = pProp || ''; pProp = pProp.split('.'); } if (pProp.length > 1) { var prop = pProp.shift(); pObj[prop] = (typeof pObj[prop] !== 'undefined' || typeof pObj[prop] !== 'null') ? pObj[prop] : {}; setPropertyVal(pObj[prop], pProp, pNewVal); } else { pObj[ pProp[0] ] = pNewVal; } }
javascript
function setPropertyVal (pObj, pProp, pNewVal) { if (typeof pProp === 'string') { pProp = pProp || ''; pProp = pProp.split('.'); } if (pProp.length > 1) { var prop = pProp.shift(); pObj[prop] = (typeof pObj[prop] !== 'undefined' || typeof pObj[prop] !== 'null') ? pObj[prop] : {}; setPropertyVal(pObj[prop], pProp, pNewVal); } else { pObj[ pProp[0] ] = pNewVal; } }
[ "function", "setPropertyVal", "(", "pObj", ",", "pProp", ",", "pNewVal", ")", "{", "if", "(", "typeof", "pProp", "===", "'string'", ")", "{", "pProp", "=", "pProp", "||", "''", ";", "pProp", "=", "pProp", ".", "split", "(", "'.'", ")", ";", "}", "if", "(", "pProp", ".", "length", ">", "1", ")", "{", "var", "prop", "=", "pProp", ".", "shift", "(", ")", ";", "pObj", "[", "prop", "]", "=", "(", "typeof", "pObj", "[", "prop", "]", "!==", "'undefined'", "||", "typeof", "pObj", "[", "prop", "]", "!==", "'null'", ")", "?", "pObj", "[", "prop", "]", ":", "{", "}", ";", "setPropertyVal", "(", "pObj", "[", "prop", "]", ",", "pProp", ",", "pNewVal", ")", ";", "}", "else", "{", "pObj", "[", "pProp", "[", "0", "]", "]", "=", "pNewVal", ";", "}", "}" ]
Utility method to set property value of an object by using the dot notation of the affected property For instance, for the following object: var someObject = { animals: { cow: true, cat: false } }; If we want to change the property val of 'cat', we can use this function to do so: setPropertyVal (someObject, 'animals.cat', true); @param pObj Object whose property value needs to be updated @param pProp dot notation property value, e.g. 'animal.cat' @param pNewVal new value with which the property @param pProp will be updated with
[ "Utility", "method", "to", "set", "property", "value", "of", "an", "object", "by", "using", "the", "dot", "notation", "of", "the", "affected", "property" ]
965cd8a966aed9fe2fb271bf9a1ba9692eb2f3a9
https://github.com/sumeetdas/Meow/blob/965cd8a966aed9fe2fb271bf9a1ba9692eb2f3a9/lib/utils.js#L32-L50
train