id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
25,900
C2FO/comb
lib/async.js
asyncZip
function asyncZip() { return asyncArray(when.apply(null, argsToArray(arguments)).chain(function (result) { return zip.apply(array, normalizeResult(result).map(function (arg) { return isArray(arg) ? arg : [arg]; })); })); }
javascript
function asyncZip() { return asyncArray(when.apply(null, argsToArray(arguments)).chain(function (result) { return zip.apply(array, normalizeResult(result).map(function (arg) { return isArray(arg) ? arg : [arg]; })); })); }
[ "function", "asyncZip", "(", ")", "{", "return", "asyncArray", "(", "when", ".", "apply", "(", "null", ",", "argsToArray", "(", "arguments", ")", ")", ".", "chain", "(", "function", "(", "result", ")", "{", "return", "zip", ".", "apply", "(", "array", ",", "normalizeResult", "(", "result", ")", ".", "map", "(", "function", "(", "arg", ")", "{", "return", "isArray", "(", "arg", ")", "?", "arg", ":", "[", "arg", "]", ";", "}", ")", ")", ";", "}", ")", ")", ";", "}" ]
Zips results from promises into an array. ``` function asyncArr(){ var ret = new comb.Promise(); process.nextTick(ret.callback.bind(ret, [1,2,3,4,5]); return ret.promise; } comb.async.zip(asyncArr(), asyncArr()).then(function(zipped){ console.log(zipped); //[[1,1],[2,2],[3,3], [4,4], [5,5]] }); comb.async.array(asyncArr()).zip(asyncArr()).then(function(zipped){ console.log(zipped); //[[1,1],[2,2],[3,3], [4,4], [5,5]] }); ``` @return {comb.Promise} an array with all the arrays zipped together. @static @memberof comb.async @name zip
[ "Zips", "results", "from", "promises", "into", "an", "array", "." ]
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/async.js#L394-L400
25,901
peerlibrary/node-xml4js
lib/validator.js
function (namespaces, defaultNamespace, name) { var self = this; assert(namespaces); assert(name); if (/^\{.+\}/.test(name)) { return name; } else if (/:/.test(name)) { var parts = name.split(':'); assert(parts.length === 2, parts); if (!namespaces[parts[0]]) { throw new xml2js.ValidationError("Unknown namespace " + parts[0] + ", name: " + name + ", known namespaces: " + util.inspect(namespaces, false, null)); } return '{' + namespaces[parts[0]] + '}' + parts[1]; } else if (defaultNamespace) { return '{' + defaultNamespace + '}' + name; } else { throw new xml2js.ValidationError("Unqualified name and no default namespace: " + name); } }
javascript
function (namespaces, defaultNamespace, name) { var self = this; assert(namespaces); assert(name); if (/^\{.+\}/.test(name)) { return name; } else if (/:/.test(name)) { var parts = name.split(':'); assert(parts.length === 2, parts); if (!namespaces[parts[0]]) { throw new xml2js.ValidationError("Unknown namespace " + parts[0] + ", name: " + name + ", known namespaces: " + util.inspect(namespaces, false, null)); } return '{' + namespaces[parts[0]] + '}' + parts[1]; } else if (defaultNamespace) { return '{' + defaultNamespace + '}' + name; } else { throw new xml2js.ValidationError("Unqualified name and no default namespace: " + name); } }
[ "function", "(", "namespaces", ",", "defaultNamespace", ",", "name", ")", "{", "var", "self", "=", "this", ";", "assert", "(", "namespaces", ")", ";", "assert", "(", "name", ")", ";", "if", "(", "/", "^\\{.+\\}", "/", ".", "test", "(", "name", ")", ")", "{", "return", "name", ";", "}", "else", "if", "(", "/", ":", "/", ".", "test", "(", "name", ")", ")", "{", "var", "parts", "=", "name", ".", "split", "(", "':'", ")", ";", "assert", "(", "parts", ".", "length", "===", "2", ",", "parts", ")", ";", "if", "(", "!", "namespaces", "[", "parts", "[", "0", "]", "]", ")", "{", "throw", "new", "xml2js", ".", "ValidationError", "(", "\"Unknown namespace \"", "+", "parts", "[", "0", "]", "+", "\", name: \"", "+", "name", "+", "\", known namespaces: \"", "+", "util", ".", "inspect", "(", "namespaces", ",", "false", ",", "null", ")", ")", ";", "}", "return", "'{'", "+", "namespaces", "[", "parts", "[", "0", "]", "]", "+", "'}'", "+", "parts", "[", "1", "]", ";", "}", "else", "if", "(", "defaultNamespace", ")", "{", "return", "'{'", "+", "defaultNamespace", "+", "'}'", "+", "name", ";", "}", "else", "{", "throw", "new", "xml2js", ".", "ValidationError", "(", "\"Unqualified name and no default namespace: \"", "+", "name", ")", ";", "}", "}" ]
Similar to XsdSchema.namespacedName, just using arguments
[ "Similar", "to", "XsdSchema", ".", "namespacedName", "just", "using", "arguments" ]
fe24c3105c3a22e7285443af364fab9dea2d7ed8
https://github.com/peerlibrary/node-xml4js/blob/fe24c3105c3a22e7285443af364fab9dea2d7ed8/lib/validator.js#L266-L288
25,902
PatrickJS/angular-intercom
angular-intercom.js
createScript
function createScript(url, appID) { if (!document) { return; } var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = url+appID; // Attach the script tag to the document head var s = document.getElementsByTagName('head')[0]; s.appendChild(script); }
javascript
function createScript(url, appID) { if (!document) { return; } var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = url+appID; // Attach the script tag to the document head var s = document.getElementsByTagName('head')[0]; s.appendChild(script); }
[ "function", "createScript", "(", "url", ",", "appID", ")", "{", "if", "(", "!", "document", ")", "{", "return", ";", "}", "var", "script", "=", "document", ".", "createElement", "(", "'script'", ")", ";", "script", ".", "type", "=", "'text/javascript'", ";", "script", ".", "async", "=", "true", ";", "script", ".", "src", "=", "url", "+", "appID", ";", "// Attach the script tag to the document head", "var", "s", "=", "document", ".", "getElementsByTagName", "(", "'head'", ")", "[", "0", "]", ";", "s", ".", "appendChild", "(", "script", ")", ";", "}" ]
Create a script tag with moment as the source and call our onScriptLoad callback when it has been loaded
[ "Create", "a", "script", "tag", "with", "moment", "as", "the", "source", "and", "call", "our", "onScriptLoad", "callback", "when", "it", "has", "been", "loaded" ]
60198a6c5abb1a388a3582e43b0255e9c6b3666e
https://github.com/PatrickJS/angular-intercom/blob/60198a6c5abb1a388a3582e43b0255e9c6b3666e/angular-intercom.js#L62-L71
25,903
ClickerMonkey/SemanticUI-Angular
angular-semantic-ui.js
function() { if ( !(scope.model instanceof Array) ) { scope.model = scope.model ? [ scope.model ] : []; } return scope.model; }
javascript
function() { if ( !(scope.model instanceof Array) ) { scope.model = scope.model ? [ scope.model ] : []; } return scope.model; }
[ "function", "(", ")", "{", "if", "(", "!", "(", "scope", ".", "model", "instanceof", "Array", ")", ")", "{", "scope", ".", "model", "=", "scope", ".", "model", "?", "[", "scope", ".", "model", "]", ":", "[", "]", ";", "}", "return", "scope", ".", "model", ";", "}" ]
Returns the model on the scope, converting it to an array if it's not one.
[ "Returns", "the", "model", "on", "the", "scope", "converting", "it", "to", "an", "array", "if", "it", "s", "not", "one", "." ]
b4b89a288535e56d61c3c8e86e47b84495d5d76d
https://github.com/ClickerMonkey/SemanticUI-Angular/blob/b4b89a288535e56d61c3c8e86e47b84495d5d76d/angular-semantic-ui.js#L1328-L1333
25,904
ClickerMonkey/SemanticUI-Angular
angular-semantic-ui.js
SemanticPopup
function SemanticPopup(SemanticPopupLink) { return { restrict: 'A', scope: { /* Required */ smPopup: '=', /* Optional */ smPopupTitle: '=', smPopupHtml: '=', smPopupPosition: '@', smPopupVariation: '@', smPopupSettings: '=', smPopupOnInit: '=', /* Events */ smPopupOnCreate: '=', smPopupOnRemove: '=', smPopupOnShow: '=', smPopupOnVisible: '=', smPopupOnHide: '=', smPopupOnHidden: '=' }, link: SemanticPopupLink }; }
javascript
function SemanticPopup(SemanticPopupLink) { return { restrict: 'A', scope: { /* Required */ smPopup: '=', /* Optional */ smPopupTitle: '=', smPopupHtml: '=', smPopupPosition: '@', smPopupVariation: '@', smPopupSettings: '=', smPopupOnInit: '=', /* Events */ smPopupOnCreate: '=', smPopupOnRemove: '=', smPopupOnShow: '=', smPopupOnVisible: '=', smPopupOnHide: '=', smPopupOnHidden: '=' }, link: SemanticPopupLink }; }
[ "function", "SemanticPopup", "(", "SemanticPopupLink", ")", "{", "return", "{", "restrict", ":", "'A'", ",", "scope", ":", "{", "/* Required */", "smPopup", ":", "'='", ",", "/* Optional */", "smPopupTitle", ":", "'='", ",", "smPopupHtml", ":", "'='", ",", "smPopupPosition", ":", "'@'", ",", "smPopupVariation", ":", "'@'", ",", "smPopupSettings", ":", "'='", ",", "smPopupOnInit", ":", "'='", ",", "/* Events */", "smPopupOnCreate", ":", "'='", ",", "smPopupOnRemove", ":", "'='", ",", "smPopupOnShow", ":", "'='", ",", "smPopupOnVisible", ":", "'='", ",", "smPopupOnHide", ":", "'='", ",", "smPopupOnHidden", ":", "'='", "}", ",", "link", ":", "SemanticPopupLink", "}", ";", "}" ]
An attribute directive which displays a popup for this element.
[ "An", "attribute", "directive", "which", "displays", "a", "popup", "for", "this", "element", "." ]
b4b89a288535e56d61c3c8e86e47b84495d5d76d
https://github.com/ClickerMonkey/SemanticUI-Angular/blob/b4b89a288535e56d61c3c8e86e47b84495d5d76d/angular-semantic-ui.js#L1856-L1883
25,905
ClickerMonkey/SemanticUI-Angular
angular-semantic-ui.js
SemanticPopupInline
function SemanticPopupInline(SemanticPopupInlineLink) { return { restrict: 'A', scope: { /* Optional */ smPopupInline: '=', smPopupInlineOnInit: '=', /* Events */ smPopupInlineOnCreate: '=', smPopupInlineOnRemove: '=', smPopupInlineOnShow: '=', smPopupInlineOnVisible: '=', smPopupInlineOnHide: '=', smPopupInlineOnHidden: '=' }, link: SemanticPopupInlineLink }; }
javascript
function SemanticPopupInline(SemanticPopupInlineLink) { return { restrict: 'A', scope: { /* Optional */ smPopupInline: '=', smPopupInlineOnInit: '=', /* Events */ smPopupInlineOnCreate: '=', smPopupInlineOnRemove: '=', smPopupInlineOnShow: '=', smPopupInlineOnVisible: '=', smPopupInlineOnHide: '=', smPopupInlineOnHidden: '=' }, link: SemanticPopupInlineLink }; }
[ "function", "SemanticPopupInline", "(", "SemanticPopupInlineLink", ")", "{", "return", "{", "restrict", ":", "'A'", ",", "scope", ":", "{", "/* Optional */", "smPopupInline", ":", "'='", ",", "smPopupInlineOnInit", ":", "'='", ",", "/* Events */", "smPopupInlineOnCreate", ":", "'='", ",", "smPopupInlineOnRemove", ":", "'='", ",", "smPopupInlineOnShow", ":", "'='", ",", "smPopupInlineOnVisible", ":", "'='", ",", "smPopupInlineOnHide", ":", "'='", ",", "smPopupInlineOnHidden", ":", "'='", "}", ",", "link", ":", "SemanticPopupInlineLink", "}", ";", "}" ]
An attribute directive to show the detached popup which follows this element.
[ "An", "attribute", "directive", "to", "show", "the", "detached", "popup", "which", "follows", "this", "element", "." ]
b4b89a288535e56d61c3c8e86e47b84495d5d76d
https://github.com/ClickerMonkey/SemanticUI-Angular/blob/b4b89a288535e56d61c3c8e86e47b84495d5d76d/angular-semantic-ui.js#L1918-L1939
25,906
ClickerMonkey/SemanticUI-Angular
angular-semantic-ui.js
SemanticPopupDisplay
function SemanticPopupDisplay(SemanticPopupDisplayLink) { return { restrict: 'A', scope: { /* Required */ smPopupDisplay: '@', /* Optional */ smPopupDisplaySettings: '=', smPopupDisplayOnInit: '=', /* Events */ smPopupDisplayOnCreate: '=', smPopupDisplayOnRemove: '=', smPopupDisplayOnShow: '=', smPopupDisplayOnVisible: '=', smPopupDisplayOnHide: '=', smPopupDisplayOnHidden: '=' }, link: SemanticPopupDisplayLink }; }
javascript
function SemanticPopupDisplay(SemanticPopupDisplayLink) { return { restrict: 'A', scope: { /* Required */ smPopupDisplay: '@', /* Optional */ smPopupDisplaySettings: '=', smPopupDisplayOnInit: '=', /* Events */ smPopupDisplayOnCreate: '=', smPopupDisplayOnRemove: '=', smPopupDisplayOnShow: '=', smPopupDisplayOnVisible: '=', smPopupDisplayOnHide: '=', smPopupDisplayOnHidden: '=' }, link: SemanticPopupDisplayLink }; }
[ "function", "SemanticPopupDisplay", "(", "SemanticPopupDisplayLink", ")", "{", "return", "{", "restrict", ":", "'A'", ",", "scope", ":", "{", "/* Required */", "smPopupDisplay", ":", "'@'", ",", "/* Optional */", "smPopupDisplaySettings", ":", "'='", ",", "smPopupDisplayOnInit", ":", "'='", ",", "/* Events */", "smPopupDisplayOnCreate", ":", "'='", ",", "smPopupDisplayOnRemove", ":", "'='", ",", "smPopupDisplayOnShow", ":", "'='", ",", "smPopupDisplayOnVisible", ":", "'='", ",", "smPopupDisplayOnHide", ":", "'='", ",", "smPopupDisplayOnHidden", ":", "'='", "}", ",", "link", ":", "SemanticPopupDisplayLink", "}", ";", "}" ]
An attribute directive to show a detached popup over this element given it's name.
[ "An", "attribute", "directive", "to", "show", "a", "detached", "popup", "over", "this", "element", "given", "it", "s", "name", "." ]
b4b89a288535e56d61c3c8e86e47b84495d5d76d
https://github.com/ClickerMonkey/SemanticUI-Angular/blob/b4b89a288535e56d61c3c8e86e47b84495d5d76d/angular-semantic-ui.js#L1969-L1992
25,907
dvdln/jsonpath-object-transform
lib/jsonpath-object-transform.js
walk
function walk(data, path, result, key) { var fn; switch (type(path)) { case 'string': fn = seekSingle; break; case 'array': fn = seekArray; break; case 'object': fn = seekObject; break; } if (fn) { fn(data, path, result, key); } }
javascript
function walk(data, path, result, key) { var fn; switch (type(path)) { case 'string': fn = seekSingle; break; case 'array': fn = seekArray; break; case 'object': fn = seekObject; break; } if (fn) { fn(data, path, result, key); } }
[ "function", "walk", "(", "data", ",", "path", ",", "result", ",", "key", ")", "{", "var", "fn", ";", "switch", "(", "type", "(", "path", ")", ")", "{", "case", "'string'", ":", "fn", "=", "seekSingle", ";", "break", ";", "case", "'array'", ":", "fn", "=", "seekArray", ";", "break", ";", "case", "'object'", ":", "fn", "=", "seekObject", ";", "break", ";", "}", "if", "(", "fn", ")", "{", "fn", "(", "data", ",", "path", ",", "result", ",", "key", ")", ";", "}", "}" ]
Step through data object and apply path transforms. @param {object} data @param {object} path @param {object} result @param {string} key
[ "Step", "through", "data", "object", "and", "apply", "path", "transforms", "." ]
e33f4f143976db3c2a52439ff42a5e1982e2defe
https://github.com/dvdln/jsonpath-object-transform/blob/e33f4f143976db3c2a52439ff42a5e1982e2defe/lib/jsonpath-object-transform.js#L34-L54
25,908
dvdln/jsonpath-object-transform
lib/jsonpath-object-transform.js
seekSingle
function seekSingle(data, pathStr, result, key) { if(pathStr.indexOf('$') < 0){ result[key] = pathStr; }else{ var seek = jsonPath.eval(data, pathStr) || []; result[key] = seek.length ? seek[0] : undefined; } }
javascript
function seekSingle(data, pathStr, result, key) { if(pathStr.indexOf('$') < 0){ result[key] = pathStr; }else{ var seek = jsonPath.eval(data, pathStr) || []; result[key] = seek.length ? seek[0] : undefined; } }
[ "function", "seekSingle", "(", "data", ",", "pathStr", ",", "result", ",", "key", ")", "{", "if", "(", "pathStr", ".", "indexOf", "(", "'$'", ")", "<", "0", ")", "{", "result", "[", "key", "]", "=", "pathStr", ";", "}", "else", "{", "var", "seek", "=", "jsonPath", ".", "eval", "(", "data", ",", "pathStr", ")", "||", "[", "]", ";", "result", "[", "key", "]", "=", "seek", ".", "length", "?", "seek", "[", "0", "]", ":", "undefined", ";", "}", "}" ]
Get single property from data object. @param {object} data @param {string} pathStr @param {object} result @param {string} key
[ "Get", "single", "property", "from", "data", "object", "." ]
e33f4f143976db3c2a52439ff42a5e1982e2defe
https://github.com/dvdln/jsonpath-object-transform/blob/e33f4f143976db3c2a52439ff42a5e1982e2defe/lib/jsonpath-object-transform.js#L74-L82
25,909
dvdln/jsonpath-object-transform
lib/jsonpath-object-transform.js
seekArray
function seekArray(data, pathArr, result, key) { var subpath = pathArr[1]; var path = pathArr[0]; var seek = jsonPath.eval(data, path) || []; if (seek.length && subpath) { result = result[key] = []; seek[0].forEach(function(item, index) { walk(item, subpath, result, index); }); } else { result[key] = seek; } }
javascript
function seekArray(data, pathArr, result, key) { var subpath = pathArr[1]; var path = pathArr[0]; var seek = jsonPath.eval(data, path) || []; if (seek.length && subpath) { result = result[key] = []; seek[0].forEach(function(item, index) { walk(item, subpath, result, index); }); } else { result[key] = seek; } }
[ "function", "seekArray", "(", "data", ",", "pathArr", ",", "result", ",", "key", ")", "{", "var", "subpath", "=", "pathArr", "[", "1", "]", ";", "var", "path", "=", "pathArr", "[", "0", "]", ";", "var", "seek", "=", "jsonPath", ".", "eval", "(", "data", ",", "path", ")", "||", "[", "]", ";", "if", "(", "seek", ".", "length", "&&", "subpath", ")", "{", "result", "=", "result", "[", "key", "]", "=", "[", "]", ";", "seek", "[", "0", "]", ".", "forEach", "(", "function", "(", "item", ",", "index", ")", "{", "walk", "(", "item", ",", "subpath", ",", "result", ",", "index", ")", ";", "}", ")", ";", "}", "else", "{", "result", "[", "key", "]", "=", "seek", ";", "}", "}" ]
Get array of properties from data object. @param {object} data @param {array} pathArr @param {object} result @param {string} key
[ "Get", "array", "of", "properties", "from", "data", "object", "." ]
e33f4f143976db3c2a52439ff42a5e1982e2defe
https://github.com/dvdln/jsonpath-object-transform/blob/e33f4f143976db3c2a52439ff42a5e1982e2defe/lib/jsonpath-object-transform.js#L92-L106
25,910
dvdln/jsonpath-object-transform
lib/jsonpath-object-transform.js
seekObject
function seekObject(data, pathObj, result, key) { if (typeof key !== 'undefined') { result = result[key] = {}; } Object.keys(pathObj).forEach(function(name) { walk(data, pathObj[name], result, name); }); }
javascript
function seekObject(data, pathObj, result, key) { if (typeof key !== 'undefined') { result = result[key] = {}; } Object.keys(pathObj).forEach(function(name) { walk(data, pathObj[name], result, name); }); }
[ "function", "seekObject", "(", "data", ",", "pathObj", ",", "result", ",", "key", ")", "{", "if", "(", "typeof", "key", "!==", "'undefined'", ")", "{", "result", "=", "result", "[", "key", "]", "=", "{", "}", ";", "}", "Object", ".", "keys", "(", "pathObj", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "walk", "(", "data", ",", "pathObj", "[", "name", "]", ",", "result", ",", "name", ")", ";", "}", ")", ";", "}" ]
Get object property from data object. @param {object} data @param {object} pathObj @param {object} result @param {string} key
[ "Get", "object", "property", "from", "data", "object", "." ]
e33f4f143976db3c2a52439ff42a5e1982e2defe
https://github.com/dvdln/jsonpath-object-transform/blob/e33f4f143976db3c2a52439ff42a5e1982e2defe/lib/jsonpath-object-transform.js#L116-L124
25,911
mixmaxhq/electron-editor-context-menu
src/index.js
function(selection, mainTemplate, suggestionsTemplate) { selection = defaults({}, selection, { isMisspelled: false, spellingSuggestions: [] }); var template = getTemplate(mainTemplate, DEFAULT_MAIN_TPL); var suggestionsTpl = getTemplate(suggestionsTemplate, DEFAULT_SUGGESTIONS_TPL); if (selection.isMisspelled) { var suggestions = selection.spellingSuggestions; if (isEmpty(suggestions)) { template.unshift.apply(template, suggestionsTpl); } else { template.unshift.apply(template, suggestions.map(function(suggestion) { return { label: suggestion, click: function() { BrowserWindow.getFocusedWindow().webContents.replaceMisspelling(suggestion); } }; }).concat({ type: 'separator' })); } } return Menu.buildFromTemplate(template); }
javascript
function(selection, mainTemplate, suggestionsTemplate) { selection = defaults({}, selection, { isMisspelled: false, spellingSuggestions: [] }); var template = getTemplate(mainTemplate, DEFAULT_MAIN_TPL); var suggestionsTpl = getTemplate(suggestionsTemplate, DEFAULT_SUGGESTIONS_TPL); if (selection.isMisspelled) { var suggestions = selection.spellingSuggestions; if (isEmpty(suggestions)) { template.unshift.apply(template, suggestionsTpl); } else { template.unshift.apply(template, suggestions.map(function(suggestion) { return { label: suggestion, click: function() { BrowserWindow.getFocusedWindow().webContents.replaceMisspelling(suggestion); } }; }).concat({ type: 'separator' })); } } return Menu.buildFromTemplate(template); }
[ "function", "(", "selection", ",", "mainTemplate", ",", "suggestionsTemplate", ")", "{", "selection", "=", "defaults", "(", "{", "}", ",", "selection", ",", "{", "isMisspelled", ":", "false", ",", "spellingSuggestions", ":", "[", "]", "}", ")", ";", "var", "template", "=", "getTemplate", "(", "mainTemplate", ",", "DEFAULT_MAIN_TPL", ")", ";", "var", "suggestionsTpl", "=", "getTemplate", "(", "suggestionsTemplate", ",", "DEFAULT_SUGGESTIONS_TPL", ")", ";", "if", "(", "selection", ".", "isMisspelled", ")", "{", "var", "suggestions", "=", "selection", ".", "spellingSuggestions", ";", "if", "(", "isEmpty", "(", "suggestions", ")", ")", "{", "template", ".", "unshift", ".", "apply", "(", "template", ",", "suggestionsTpl", ")", ";", "}", "else", "{", "template", ".", "unshift", ".", "apply", "(", "template", ",", "suggestions", ".", "map", "(", "function", "(", "suggestion", ")", "{", "return", "{", "label", ":", "suggestion", ",", "click", ":", "function", "(", ")", "{", "BrowserWindow", ".", "getFocusedWindow", "(", ")", ".", "webContents", ".", "replaceMisspelling", "(", "suggestion", ")", ";", "}", "}", ";", "}", ")", ".", "concat", "(", "{", "type", ":", "'separator'", "}", ")", ")", ";", "}", "}", "return", "Menu", ".", "buildFromTemplate", "(", "template", ")", ";", "}" ]
Builds a context menu suitable for showing in a text editor. @param {Object=} selection - An object describing the current text selection. @property {Boolean=false} isMisspelled - `true` if the selection is misspelled, `false` if it is spelled correctly or is not text. @property {Array<String>=[]} spellingSuggestions - An array of suggestions to show to correct the misspelling. Ignored if `isMisspelled` is `false`. @param {Function|Array} mainTemplate - Optional. If it's an array, use as is. If it's a function, used to customize the template of always-present menu items. Receives the default template as a parameter. Should return a template. @param {Function|Array} suggestionsTemplate - Optional. If it's an array, use as is. If it's a function, used to customize the template of spelling suggestion items. Receives the default suggestions template as a parameter. Should return a template. @return {Menu}
[ "Builds", "a", "context", "menu", "suitable", "for", "showing", "in", "a", "text", "editor", "." ]
dbb3474f0767304a7fb5a7f50e36c0b34ef1de03
https://github.com/mixmaxhq/electron-editor-context-menu/blob/dbb3474f0767304a7fb5a7f50e36c0b34ef1de03/src/index.js#L83-L112
25,912
xdenser/node-firebird-libfbclient
samples/fileman/static/elfinder/elfinder.full.js
resize
function resize(w, h) { w && self.view.win.width(w); h && self.view.nav.add(self.view.cwd).height(h); }
javascript
function resize(w, h) { w && self.view.win.width(w); h && self.view.nav.add(self.view.cwd).height(h); }
[ "function", "resize", "(", "w", ",", "h", ")", "{", "w", "&&", "self", ".", "view", ".", "win", ".", "width", "(", "w", ")", ";", "h", "&&", "self", ".", "view", ".", "nav", ".", "add", "(", "self", ".", "view", ".", "cwd", ")", ".", "height", "(", "h", ")", ";", "}" ]
Resize file manager @param Number width @param Number height
[ "Resize", "file", "manager" ]
455c5e023b979d68e41ef8946dbdc9abd0a6e2d0
https://github.com/xdenser/node-firebird-libfbclient/blob/455c5e023b979d68e41ef8946dbdc9abd0a6e2d0/samples/fileman/static/elfinder/elfinder.full.js#L550-L553
25,913
xdenser/node-firebird-libfbclient
samples/fileman/static/elfinder/elfinder.full.js
dialogResize
function dialogResize() { resize(null, self.dialog.height()-self.view.tlb.parent().height()-($.browser.msie ? 47 : 32)) }
javascript
function dialogResize() { resize(null, self.dialog.height()-self.view.tlb.parent().height()-($.browser.msie ? 47 : 32)) }
[ "function", "dialogResize", "(", ")", "{", "resize", "(", "null", ",", "self", ".", "dialog", ".", "height", "(", ")", "-", "self", ".", "view", ".", "tlb", ".", "parent", "(", ")", ".", "height", "(", ")", "-", "(", "$", ".", "browser", ".", "msie", "?", "47", ":", "32", ")", ")", "}" ]
Resize file manager in dialog window while it resize
[ "Resize", "file", "manager", "in", "dialog", "window", "while", "it", "resize" ]
455c5e023b979d68e41ef8946dbdc9abd0a6e2d0
https://github.com/xdenser/node-firebird-libfbclient/blob/455c5e023b979d68e41ef8946dbdc9abd0a6e2d0/samples/fileman/static/elfinder/elfinder.full.js#L559-L561
25,914
xdenser/node-firebird-libfbclient
samples/fileman/static/elfinder/elfinder.full.js
reset
function reset() { self.media.hide().empty(); self.win.attr('class', 'el-finder-ql').css('z-index', self.fm.zIndex); self.title.empty(); self.ico.removeAttr('style').show(); self.add.hide().empty(); self._hash = ''; }
javascript
function reset() { self.media.hide().empty(); self.win.attr('class', 'el-finder-ql').css('z-index', self.fm.zIndex); self.title.empty(); self.ico.removeAttr('style').show(); self.add.hide().empty(); self._hash = ''; }
[ "function", "reset", "(", ")", "{", "self", ".", "media", ".", "hide", "(", ")", ".", "empty", "(", ")", ";", "self", ".", "win", ".", "attr", "(", "'class'", ",", "'el-finder-ql'", ")", ".", "css", "(", "'z-index'", ",", "self", ".", "fm", ".", "zIndex", ")", ";", "self", ".", "title", ".", "empty", "(", ")", ";", "self", ".", "ico", ".", "removeAttr", "(", "'style'", ")", ".", "show", "(", ")", ";", "self", ".", "add", ".", "hide", "(", ")", ".", "empty", "(", ")", ";", "self", ".", "_hash", "=", "''", ";", "}" ]
Clean quickLook window DOM elements
[ "Clean", "quickLook", "window", "DOM", "elements" ]
455c5e023b979d68e41ef8946dbdc9abd0a6e2d0
https://github.com/xdenser/node-firebird-libfbclient/blob/455c5e023b979d68e41ef8946dbdc9abd0a6e2d0/samples/fileman/static/elfinder/elfinder.full.js#L2728-L2735
25,915
xdenser/node-firebird-libfbclient
samples/fileman/static/elfinder/elfinder.full.js
update
function update() { var f = self.fm.getSelected(0); reset(); self._hash = f.hash; self.title.text(f.name); self.win.addClass(self.fm.view.mime2class(f.mime)); self.name.text(f.name); self.kind.text(self.fm.view.mime2kind(f.link ? 'symlink' : f.mime)); self.size.text(self.fm.view.formatSize(f.size)); self.date.text(self.fm.i18n('Modified')+': '+self.fm.view.formatDate(f.date)); f.dim && self.add.append('<span>'+f.dim+' px</span>').show(); f.tmb && self.ico.css('background', 'url("'+f.tmb+'") 0 0 no-repeat'); if (f.url) { self.url.text(f.url).attr('href', f.url).show(); for (var i in self.plugins) { if (self.plugins[i].test && self.plugins[i].test(f.mime, self.mimes, f.name)) { self.plugins[i].show(self, f); return; } } } else { self.url.hide(); } self.win.css({ width : '420px', height : 'auto' }); }
javascript
function update() { var f = self.fm.getSelected(0); reset(); self._hash = f.hash; self.title.text(f.name); self.win.addClass(self.fm.view.mime2class(f.mime)); self.name.text(f.name); self.kind.text(self.fm.view.mime2kind(f.link ? 'symlink' : f.mime)); self.size.text(self.fm.view.formatSize(f.size)); self.date.text(self.fm.i18n('Modified')+': '+self.fm.view.formatDate(f.date)); f.dim && self.add.append('<span>'+f.dim+' px</span>').show(); f.tmb && self.ico.css('background', 'url("'+f.tmb+'") 0 0 no-repeat'); if (f.url) { self.url.text(f.url).attr('href', f.url).show(); for (var i in self.plugins) { if (self.plugins[i].test && self.plugins[i].test(f.mime, self.mimes, f.name)) { self.plugins[i].show(self, f); return; } } } else { self.url.hide(); } self.win.css({ width : '420px', height : 'auto' }); }
[ "function", "update", "(", ")", "{", "var", "f", "=", "self", ".", "fm", ".", "getSelected", "(", "0", ")", ";", "reset", "(", ")", ";", "self", ".", "_hash", "=", "f", ".", "hash", ";", "self", ".", "title", ".", "text", "(", "f", ".", "name", ")", ";", "self", ".", "win", ".", "addClass", "(", "self", ".", "fm", ".", "view", ".", "mime2class", "(", "f", ".", "mime", ")", ")", ";", "self", ".", "name", ".", "text", "(", "f", ".", "name", ")", ";", "self", ".", "kind", ".", "text", "(", "self", ".", "fm", ".", "view", ".", "mime2kind", "(", "f", ".", "link", "?", "'symlink'", ":", "f", ".", "mime", ")", ")", ";", "self", ".", "size", ".", "text", "(", "self", ".", "fm", ".", "view", ".", "formatSize", "(", "f", ".", "size", ")", ")", ";", "self", ".", "date", ".", "text", "(", "self", ".", "fm", ".", "i18n", "(", "'Modified'", ")", "+", "': '", "+", "self", ".", "fm", ".", "view", ".", "formatDate", "(", "f", ".", "date", ")", ")", ";", "f", ".", "dim", "&&", "self", ".", "add", ".", "append", "(", "'<span>'", "+", "f", ".", "dim", "+", "' px</span>'", ")", ".", "show", "(", ")", ";", "f", ".", "tmb", "&&", "self", ".", "ico", ".", "css", "(", "'background'", ",", "'url(\"'", "+", "f", ".", "tmb", "+", "'\") 0 0 no-repeat'", ")", ";", "if", "(", "f", ".", "url", ")", "{", "self", ".", "url", ".", "text", "(", "f", ".", "url", ")", ".", "attr", "(", "'href'", ",", "f", ".", "url", ")", ".", "show", "(", ")", ";", "for", "(", "var", "i", "in", "self", ".", "plugins", ")", "{", "if", "(", "self", ".", "plugins", "[", "i", "]", ".", "test", "&&", "self", ".", "plugins", "[", "i", "]", ".", "test", "(", "f", ".", "mime", ",", "self", ".", "mimes", ",", "f", ".", "name", ")", ")", "{", "self", ".", "plugins", "[", "i", "]", ".", "show", "(", "self", ",", "f", ")", ";", "return", ";", "}", "}", "}", "else", "{", "self", ".", "url", ".", "hide", "(", ")", ";", "}", "self", ".", "win", ".", "css", "(", "{", "width", ":", "'420px'", ",", "height", ":", "'auto'", "}", ")", ";", "}" ]
Update quickLook window content
[ "Update", "quickLook", "window", "content" ]
455c5e023b979d68e41ef8946dbdc9abd0a6e2d0
https://github.com/xdenser/node-firebird-libfbclient/blob/455c5e023b979d68e41ef8946dbdc9abd0a6e2d0/samples/fileman/static/elfinder/elfinder.full.js#L2740-L2769
25,916
xdenser/node-firebird-libfbclient
samples/fileman/static/elfinder/elfinder.full.js
moveSelection
function moveSelection(forward, reset) { var p, _p, cur; if (!$('[key]', self.cwd).length) { return; } if (self.fm.selected.length == 0) { p = $('[key]:'+(forward ? 'first' : 'last'), self.cwd); self.fm.select(p); } else if (reset) { p = $('.ui-selected:'+(forward ? 'last' : 'first'), self.cwd); _p = p[forward ? 'next' : 'prev']('[key]'); if (_p.length) { p = _p; } self.fm.select(p, true); } else { if (self.pointer) { cur = $('[key="'+self.pointer+'"].ui-selected', self.cwd); } if (!cur || !cur.length) { cur = $('.ui-selected:'+(forward ? 'last' : 'first'), self.cwd); } p = cur[forward ? 'next' : 'prev']('[key]'); if (!p.length) { p = cur; } else { if (!p.hasClass('ui-selected')) { self.fm.select(p); } else { if (!cur.hasClass('ui-selected')) { self.fm.unselect(p); } else { _p = cur[forward ? 'prev' : 'next']('[key]') if (!_p.length || !_p.hasClass('ui-selected')) { self.fm.unselect(cur); } else { while ((_p = forward ? p.next('[key]') : p.prev('[key]')) && p.hasClass('ui-selected')) { p = _p; } self.fm.select(p); } } } } } self.pointer = p.attr('key'); self.fm.checkSelectedPos(forward); }
javascript
function moveSelection(forward, reset) { var p, _p, cur; if (!$('[key]', self.cwd).length) { return; } if (self.fm.selected.length == 0) { p = $('[key]:'+(forward ? 'first' : 'last'), self.cwd); self.fm.select(p); } else if (reset) { p = $('.ui-selected:'+(forward ? 'last' : 'first'), self.cwd); _p = p[forward ? 'next' : 'prev']('[key]'); if (_p.length) { p = _p; } self.fm.select(p, true); } else { if (self.pointer) { cur = $('[key="'+self.pointer+'"].ui-selected', self.cwd); } if (!cur || !cur.length) { cur = $('.ui-selected:'+(forward ? 'last' : 'first'), self.cwd); } p = cur[forward ? 'next' : 'prev']('[key]'); if (!p.length) { p = cur; } else { if (!p.hasClass('ui-selected')) { self.fm.select(p); } else { if (!cur.hasClass('ui-selected')) { self.fm.unselect(p); } else { _p = cur[forward ? 'prev' : 'next']('[key]') if (!_p.length || !_p.hasClass('ui-selected')) { self.fm.unselect(cur); } else { while ((_p = forward ? p.next('[key]') : p.prev('[key]')) && p.hasClass('ui-selected')) { p = _p; } self.fm.select(p); } } } } } self.pointer = p.attr('key'); self.fm.checkSelectedPos(forward); }
[ "function", "moveSelection", "(", "forward", ",", "reset", ")", "{", "var", "p", ",", "_p", ",", "cur", ";", "if", "(", "!", "$", "(", "'[key]'", ",", "self", ".", "cwd", ")", ".", "length", ")", "{", "return", ";", "}", "if", "(", "self", ".", "fm", ".", "selected", ".", "length", "==", "0", ")", "{", "p", "=", "$", "(", "'[key]:'", "+", "(", "forward", "?", "'first'", ":", "'last'", ")", ",", "self", ".", "cwd", ")", ";", "self", ".", "fm", ".", "select", "(", "p", ")", ";", "}", "else", "if", "(", "reset", ")", "{", "p", "=", "$", "(", "'.ui-selected:'", "+", "(", "forward", "?", "'last'", ":", "'first'", ")", ",", "self", ".", "cwd", ")", ";", "_p", "=", "p", "[", "forward", "?", "'next'", ":", "'prev'", "]", "(", "'[key]'", ")", ";", "if", "(", "_p", ".", "length", ")", "{", "p", "=", "_p", ";", "}", "self", ".", "fm", ".", "select", "(", "p", ",", "true", ")", ";", "}", "else", "{", "if", "(", "self", ".", "pointer", ")", "{", "cur", "=", "$", "(", "'[key=\"'", "+", "self", ".", "pointer", "+", "'\"].ui-selected'", ",", "self", ".", "cwd", ")", ";", "}", "if", "(", "!", "cur", "||", "!", "cur", ".", "length", ")", "{", "cur", "=", "$", "(", "'.ui-selected:'", "+", "(", "forward", "?", "'last'", ":", "'first'", ")", ",", "self", ".", "cwd", ")", ";", "}", "p", "=", "cur", "[", "forward", "?", "'next'", ":", "'prev'", "]", "(", "'[key]'", ")", ";", "if", "(", "!", "p", ".", "length", ")", "{", "p", "=", "cur", ";", "}", "else", "{", "if", "(", "!", "p", ".", "hasClass", "(", "'ui-selected'", ")", ")", "{", "self", ".", "fm", ".", "select", "(", "p", ")", ";", "}", "else", "{", "if", "(", "!", "cur", ".", "hasClass", "(", "'ui-selected'", ")", ")", "{", "self", ".", "fm", ".", "unselect", "(", "p", ")", ";", "}", "else", "{", "_p", "=", "cur", "[", "forward", "?", "'prev'", ":", "'next'", "]", "(", "'[key]'", ")", "if", "(", "!", "_p", ".", "length", "||", "!", "_p", ".", "hasClass", "(", "'ui-selected'", ")", ")", "{", "self", ".", "fm", ".", "unselect", "(", "cur", ")", ";", "}", "else", "{", "while", "(", "(", "_p", "=", "forward", "?", "p", ".", "next", "(", "'[key]'", ")", ":", "p", ".", "prev", "(", "'[key]'", ")", ")", "&&", "p", ".", "hasClass", "(", "'ui-selected'", ")", ")", "{", "p", "=", "_p", ";", "}", "self", ".", "fm", ".", "select", "(", "p", ")", ";", "}", "}", "}", "}", "}", "self", ".", "pointer", "=", "p", ".", "attr", "(", "'key'", ")", ";", "self", ".", "fm", ".", "checkSelectedPos", "(", "forward", ")", ";", "}" ]
Move selection in current dir @param Boolean move forward? @param Boolean clear current selection?
[ "Move", "selection", "in", "current", "dir" ]
455c5e023b979d68e41ef8946dbdc9abd0a6e2d0
https://github.com/xdenser/node-firebird-libfbclient/blob/455c5e023b979d68e41ef8946dbdc9abd0a6e2d0/samples/fileman/static/elfinder/elfinder.full.js#L3277-L3327
25,917
DevExpress/testcafe-legacy-api
src/compiler/tools/uglify-js/lib/consolidator.js
function(oExpression, sIdentifierName) { fCountPrimaryExpression( EPrimaryExpressionCategories.N_IDENTIFIER_NAMES, EValuePrefixes.S_STRING + sIdentifierName); return ['dot', oWalker.walk(oExpression), sIdentifierName]; }
javascript
function(oExpression, sIdentifierName) { fCountPrimaryExpression( EPrimaryExpressionCategories.N_IDENTIFIER_NAMES, EValuePrefixes.S_STRING + sIdentifierName); return ['dot', oWalker.walk(oExpression), sIdentifierName]; }
[ "function", "(", "oExpression", ",", "sIdentifierName", ")", "{", "fCountPrimaryExpression", "(", "EPrimaryExpressionCategories", ".", "N_IDENTIFIER_NAMES", ",", "EValuePrefixes", ".", "S_STRING", "+", "sIdentifierName", ")", ";", "return", "[", "'dot'", ",", "oWalker", ".", "walk", "(", "oExpression", ")", ",", "sIdentifierName", "]", ";", "}" ]
Increments the count of the number of occurrences of the String value that is equivalent to the sequence of terminal symbols that constitute the encountered identifier name. @param {!TSyntacticCodeUnit} oExpression The nonterminal MemberExpression. @param {string} sIdentifierName The identifier name used as the property accessor. @return {!Array} The encountered branch of an <abbr title= "abstract syntax tree">AST</abbr> with its nonterminal MemberExpression traversed.
[ "Increments", "the", "count", "of", "the", "number", "of", "occurrences", "of", "the", "String", "value", "that", "is", "equivalent", "to", "the", "sequence", "of", "terminal", "symbols", "that", "constitute", "the", "encountered", "identifier", "name", "." ]
97c5dcfe46fb6a43efd2cc571bb1aa8c654c1947
https://github.com/DevExpress/testcafe-legacy-api/blob/97c5dcfe46fb6a43efd2cc571bb1aa8c654c1947/src/compiler/tools/uglify-js/lib/consolidator.js#L401-L406
25,918
DevExpress/testcafe-legacy-api
src/compiler/tools/uglify-js/lib/consolidator.js
function(oExpression, sIdentifierName) { /** * The prefixed String value that is equivalent to the * sequence of terminal symbols that constitute the * encountered identifier name. * @type {string} */ var sPrefixed = EValuePrefixes.S_STRING + sIdentifierName; return oSolutionBest.oPrimitiveValues.hasOwnProperty( sPrefixed) && oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ? ['sub', oWalker.walk(oExpression), ['name', oSolutionBest.oPrimitiveValues[sPrefixed].sName]] : ['dot', oWalker.walk(oExpression), sIdentifierName]; }
javascript
function(oExpression, sIdentifierName) { /** * The prefixed String value that is equivalent to the * sequence of terminal symbols that constitute the * encountered identifier name. * @type {string} */ var sPrefixed = EValuePrefixes.S_STRING + sIdentifierName; return oSolutionBest.oPrimitiveValues.hasOwnProperty( sPrefixed) && oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ? ['sub', oWalker.walk(oExpression), ['name', oSolutionBest.oPrimitiveValues[sPrefixed].sName]] : ['dot', oWalker.walk(oExpression), sIdentifierName]; }
[ "function", "(", "oExpression", ",", "sIdentifierName", ")", "{", "/**\n * The prefixed String value that is equivalent to the\n * sequence of terminal symbols that constitute the\n * encountered identifier name.\n * @type {string}\n */", "var", "sPrefixed", "=", "EValuePrefixes", ".", "S_STRING", "+", "sIdentifierName", ";", "return", "oSolutionBest", ".", "oPrimitiveValues", ".", "hasOwnProperty", "(", "sPrefixed", ")", "&&", "oSolutionBest", ".", "oPrimitiveValues", "[", "sPrefixed", "]", ".", "nSaving", ">", "0", "?", "[", "'sub'", ",", "oWalker", ".", "walk", "(", "oExpression", ")", ",", "[", "'name'", ",", "oSolutionBest", ".", "oPrimitiveValues", "[", "sPrefixed", "]", ".", "sName", "]", "]", ":", "[", "'dot'", ",", "oWalker", ".", "walk", "(", "oExpression", ")", ",", "sIdentifierName", "]", ";", "}" ]
If the String value that is equivalent to the sequence of terminal symbols that constitute the encountered identifier name is worthwhile, a syntactic conversion from the dot notation to the bracket notation ensues with that sequence being substituted by an identifier name to which the value is assigned. Applies to property accessors that use the dot notation. @param {!TSyntacticCodeUnit} oExpression The nonterminal MemberExpression. @param {string} sIdentifierName The identifier name used as the property accessor. @return {!Array} A syntactic code unit that is equivalent to the one encountered. @see TPrimitiveValue#nSaving
[ "If", "the", "String", "value", "that", "is", "equivalent", "to", "the", "sequence", "of", "terminal", "symbols", "that", "constitute", "the", "encountered", "identifier", "name", "is", "worthwhile", "a", "syntactic", "conversion", "from", "the", "dot", "notation", "to", "the", "bracket", "notation", "ensues", "with", "that", "sequence", "being", "substituted", "by", "an", "identifier", "name", "to", "which", "the", "value", "is", "assigned", ".", "Applies", "to", "property", "accessors", "that", "use", "the", "dot", "notation", "." ]
97c5dcfe46fb6a43efd2cc571bb1aa8c654c1947
https://github.com/DevExpress/testcafe-legacy-api/blob/97c5dcfe46fb6a43efd2cc571bb1aa8c654c1947/src/compiler/tools/uglify-js/lib/consolidator.js#L685-L702
25,919
DevExpress/testcafe-legacy-api
src/compiler/tools/uglify-js/lib/consolidator.js
function(sIdentifier) { /** * The prefixed representation String of the identifier. * @type {string} */ var sPrefixed = EValuePrefixes.S_SYMBOLIC + sIdentifier; return [ 'name', oSolutionBest.oPrimitiveValues.hasOwnProperty(sPrefixed) && oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ? oSolutionBest.oPrimitiveValues[sPrefixed].sName : sIdentifier ]; }
javascript
function(sIdentifier) { /** * The prefixed representation String of the identifier. * @type {string} */ var sPrefixed = EValuePrefixes.S_SYMBOLIC + sIdentifier; return [ 'name', oSolutionBest.oPrimitiveValues.hasOwnProperty(sPrefixed) && oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ? oSolutionBest.oPrimitiveValues[sPrefixed].sName : sIdentifier ]; }
[ "function", "(", "sIdentifier", ")", "{", "/**\n * The prefixed representation String of the identifier.\n * @type {string}\n */", "var", "sPrefixed", "=", "EValuePrefixes", ".", "S_SYMBOLIC", "+", "sIdentifier", ";", "return", "[", "'name'", ",", "oSolutionBest", ".", "oPrimitiveValues", ".", "hasOwnProperty", "(", "sPrefixed", ")", "&&", "oSolutionBest", ".", "oPrimitiveValues", "[", "sPrefixed", "]", ".", "nSaving", ">", "0", "?", "oSolutionBest", ".", "oPrimitiveValues", "[", "sPrefixed", "]", ".", "sName", ":", "sIdentifier", "]", ";", "}" ]
If the encountered identifier is a null or Boolean literal and its value is worthwhile, the identifier is substituted by an identifier name to which that value is assigned. Applies to identifier names. @param {string} sIdentifier The identifier encountered. @return {!Array} A syntactic code unit that is equivalent to the one encountered. @see TPrimitiveValue#nSaving
[ "If", "the", "encountered", "identifier", "is", "a", "null", "or", "Boolean", "literal", "and", "its", "value", "is", "worthwhile", "the", "identifier", "is", "substituted", "by", "an", "identifier", "name", "to", "which", "that", "value", "is", "assigned", ".", "Applies", "to", "identifier", "names", "." ]
97c5dcfe46fb6a43efd2cc571bb1aa8c654c1947
https://github.com/DevExpress/testcafe-legacy-api/blob/97c5dcfe46fb6a43efd2cc571bb1aa8c654c1947/src/compiler/tools/uglify-js/lib/consolidator.js#L713-L727
25,920
DevExpress/testcafe-legacy-api
src/compiler/tools/uglify-js/lib/consolidator.js
function(sStringValue) { /** * The prefixed representation String of the primitive value * of the literal. * @type {string} */ var sPrefixed = EValuePrefixes.S_STRING + sStringValue; return oSolutionBest.oPrimitiveValues.hasOwnProperty( sPrefixed) && oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ? ['name', oSolutionBest.oPrimitiveValues[sPrefixed].sName] : ['string', sStringValue]; }
javascript
function(sStringValue) { /** * The prefixed representation String of the primitive value * of the literal. * @type {string} */ var sPrefixed = EValuePrefixes.S_STRING + sStringValue; return oSolutionBest.oPrimitiveValues.hasOwnProperty( sPrefixed) && oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ? ['name', oSolutionBest.oPrimitiveValues[sPrefixed].sName] : ['string', sStringValue]; }
[ "function", "(", "sStringValue", ")", "{", "/**\n * The prefixed representation String of the primitive value\n * of the literal.\n * @type {string}\n */", "var", "sPrefixed", "=", "EValuePrefixes", ".", "S_STRING", "+", "sStringValue", ";", "return", "oSolutionBest", ".", "oPrimitiveValues", ".", "hasOwnProperty", "(", "sPrefixed", ")", "&&", "oSolutionBest", ".", "oPrimitiveValues", "[", "sPrefixed", "]", ".", "nSaving", ">", "0", "?", "[", "'name'", ",", "oSolutionBest", ".", "oPrimitiveValues", "[", "sPrefixed", "]", ".", "sName", "]", ":", "[", "'string'", ",", "sStringValue", "]", ";", "}" ]
If the encountered String value is worthwhile, it is substituted by an identifier name to which that value is assigned. Applies to String values. @param {string} sStringValue The String value of the string literal encountered. @return {!Array} A syntactic code unit that is equivalent to the one encountered. @see TPrimitiveValue#nSaving
[ "If", "the", "encountered", "String", "value", "is", "worthwhile", "it", "is", "substituted", "by", "an", "identifier", "name", "to", "which", "that", "value", "is", "assigned", ".", "Applies", "to", "String", "values", "." ]
97c5dcfe46fb6a43efd2cc571bb1aa8c654c1947
https://github.com/DevExpress/testcafe-legacy-api/blob/97c5dcfe46fb6a43efd2cc571bb1aa8c654c1947/src/compiler/tools/uglify-js/lib/consolidator.js#L739-L754
25,921
iVis-at-Bilkent/cytoscape.js-grid-guide
src/alignment.js
moveTopDown
function moveTopDown(node, dx, dy) { var nodes = node.union(node.descendants()); nodes.filter(":childless").positions(function (node, i) { if(typeof node === "number") { node = i; } var pos = node.position(); return { x: pos.x + dx, y: pos.y + dy }; }); }
javascript
function moveTopDown(node, dx, dy) { var nodes = node.union(node.descendants()); nodes.filter(":childless").positions(function (node, i) { if(typeof node === "number") { node = i; } var pos = node.position(); return { x: pos.x + dx, y: pos.y + dy }; }); }
[ "function", "moveTopDown", "(", "node", ",", "dx", ",", "dy", ")", "{", "var", "nodes", "=", "node", ".", "union", "(", "node", ".", "descendants", "(", ")", ")", ";", "nodes", ".", "filter", "(", "\":childless\"", ")", ".", "positions", "(", "function", "(", "node", ",", "i", ")", "{", "if", "(", "typeof", "node", "===", "\"number\"", ")", "{", "node", "=", "i", ";", "}", "var", "pos", "=", "node", ".", "position", "(", ")", ";", "return", "{", "x", ":", "pos", ".", "x", "+", "dx", ",", "y", ":", "pos", ".", "y", "+", "dy", "}", ";", "}", ")", ";", "}" ]
Needed because parent nodes cannot be moved in Cytoscape.js < v3.2
[ "Needed", "because", "parent", "nodes", "cannot", "be", "moved", "in", "Cytoscape", ".", "js", "<", "v3", ".", "2" ]
9649d89aafd702b097456adccdcf0395a818907d
https://github.com/iVis-at-Bilkent/cytoscape.js-grid-guide/blob/9649d89aafd702b097456adccdcf0395a818907d/src/alignment.js#L4-L17
25,922
forsigner/node-pngdefry
lib/index.js
getOutputDir
function getOutputDir(output) { var arr = output.split(path.sep); arr.pop(); return arr.join(path.sep); }
javascript
function getOutputDir(output) { var arr = output.split(path.sep); arr.pop(); return arr.join(path.sep); }
[ "function", "getOutputDir", "(", "output", ")", "{", "var", "arr", "=", "output", ".", "split", "(", "path", ".", "sep", ")", ";", "arr", ".", "pop", "(", ")", ";", "return", "arr", ".", "join", "(", "path", ".", "sep", ")", ";", "}" ]
get output directory from original output @param {string} output @return {string} outputDir @private
[ "get", "output", "directory", "from", "original", "output" ]
a6c0e501afb36b11af3db8f5afa59bfed71377a8
https://github.com/forsigner/node-pngdefry/blob/a6c0e501afb36b11af3db8f5afa59bfed71377a8/lib/index.js#L31-L35
25,923
forsigner/node-pngdefry
lib/index.js
getOutputFilePath
function getOutputFilePath(input, outputDir, suffix) { var inputArr = input.split(path.sep); var originFileName = inputArr[inputArr.length - 1]; var newFileName = originFileName.replace(/\.png$/, suffix + '.png'); var outputFilePath = path.join(outputDir, newFileName); return outputFilePath; }
javascript
function getOutputFilePath(input, outputDir, suffix) { var inputArr = input.split(path.sep); var originFileName = inputArr[inputArr.length - 1]; var newFileName = originFileName.replace(/\.png$/, suffix + '.png'); var outputFilePath = path.join(outputDir, newFileName); return outputFilePath; }
[ "function", "getOutputFilePath", "(", "input", ",", "outputDir", ",", "suffix", ")", "{", "var", "inputArr", "=", "input", ".", "split", "(", "path", ".", "sep", ")", ";", "var", "originFileName", "=", "inputArr", "[", "inputArr", ".", "length", "-", "1", "]", ";", "var", "newFileName", "=", "originFileName", ".", "replace", "(", "/", "\\.png$", "/", ",", "suffix", "+", "'.png'", ")", ";", "var", "outputFilePath", "=", "path", ".", "join", "(", "outputDir", ",", "newFileName", ")", ";", "return", "outputFilePath", ";", "}" ]
get temp output file path with our suffix @param {string} output @return {string} outputDir @return {string} suffix @return {string} outputFilePath @private
[ "get", "temp", "output", "file", "path", "with", "our", "suffix" ]
a6c0e501afb36b11af3db8f5afa59bfed71377a8
https://github.com/forsigner/node-pngdefry/blob/a6c0e501afb36b11af3db8f5afa59bfed71377a8/lib/index.js#L45-L51
25,924
marcuswestin/fin
engines/redis/storage.js
getBytes
function getBytes(key, callback) { this.redisClient.get(key, function(err, valueBytes) { if (err) { return callback(err) } if (!valueBytes) { return callback(null, null) } callback(null, valueBytes.toString()) }) }
javascript
function getBytes(key, callback) { this.redisClient.get(key, function(err, valueBytes) { if (err) { return callback(err) } if (!valueBytes) { return callback(null, null) } callback(null, valueBytes.toString()) }) }
[ "function", "getBytes", "(", "key", ",", "callback", ")", "{", "this", ".", "redisClient", ".", "get", "(", "key", ",", "function", "(", "err", ",", "valueBytes", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", "}", "if", "(", "!", "valueBytes", ")", "{", "return", "callback", "(", "null", ",", "null", ")", "}", "callback", "(", "null", ",", "valueBytes", ".", "toString", "(", ")", ")", "}", ")", "}" ]
Returns a string
[ "Returns", "a", "string" ]
25060c404fdc8f3baf9c99ebc89fa0cb04cbfb05
https://github.com/marcuswestin/fin/blob/25060c404fdc8f3baf9c99ebc89fa0cb04cbfb05/engines/redis/storage.js#L43-L49
25,925
warehouseai/smart-private-npm
lib/npm-proxy.js
onDecision
function onDecision(err, target) { // // If there was no target then this is a 404 by definition // even if it exists in the public registry because of a // potential whitelist. // if (err || !target) { return self.notFound(req, res, err || { message: 'Unknown pkg: ' + pkg }); } // if X-Forwarded-Host is set, npm returns 404 {"error":"not_found","reason":"no_db_file"} if (req.headers["x-forwarded-host"]) delete req.headers["x-forwarded-host"]; // // If we get a valid target then we can proxy to it // self.log.info('[decide] %s - %s %s %s %j', address, req.method, req.url, target.vhost || target.host || target.hostname, req.headers); self.emit('headers', req, req.headers, target); req.headers.host = target.vhost || target.host || target.hostname; proxy.web(req, res, { target: target.href }); }
javascript
function onDecision(err, target) { // // If there was no target then this is a 404 by definition // even if it exists in the public registry because of a // potential whitelist. // if (err || !target) { return self.notFound(req, res, err || { message: 'Unknown pkg: ' + pkg }); } // if X-Forwarded-Host is set, npm returns 404 {"error":"not_found","reason":"no_db_file"} if (req.headers["x-forwarded-host"]) delete req.headers["x-forwarded-host"]; // // If we get a valid target then we can proxy to it // self.log.info('[decide] %s - %s %s %s %j', address, req.method, req.url, target.vhost || target.host || target.hostname, req.headers); self.emit('headers', req, req.headers, target); req.headers.host = target.vhost || target.host || target.hostname; proxy.web(req, res, { target: target.href }); }
[ "function", "onDecision", "(", "err", ",", "target", ")", "{", "//", "// If there was no target then this is a 404 by definition", "// even if it exists in the public registry because of a", "// potential whitelist.", "//", "if", "(", "err", "||", "!", "target", ")", "{", "return", "self", ".", "notFound", "(", "req", ",", "res", ",", "err", "||", "{", "message", ":", "'Unknown pkg: '", "+", "pkg", "}", ")", ";", "}", "// if X-Forwarded-Host is set, npm returns 404 {\"error\":\"not_found\",\"reason\":\"no_db_file\"}", "if", "(", "req", ".", "headers", "[", "\"x-forwarded-host\"", "]", ")", "delete", "req", ".", "headers", "[", "\"x-forwarded-host\"", "]", ";", "//", "// If we get a valid target then we can proxy to it", "//", "self", ".", "log", ".", "info", "(", "'[decide] %s - %s %s %s %j'", ",", "address", ",", "req", ".", "method", ",", "req", ".", "url", ",", "target", ".", "vhost", "||", "target", ".", "host", "||", "target", ".", "hostname", ",", "req", ".", "headers", ")", ";", "self", ".", "emit", "(", "'headers'", ",", "req", ",", "req", ".", "headers", ",", "target", ")", ";", "req", ".", "headers", ".", "host", "=", "target", ".", "vhost", "||", "target", ".", "host", "||", "target", ".", "hostname", ";", "proxy", ".", "web", "(", "req", ",", "res", ",", "{", "target", ":", "target", ".", "href", "}", ")", ";", "}" ]
Proxy or serve not found based on the decision
[ "Proxy", "or", "serve", "not", "found", "based", "on", "the", "decision" ]
c5e1f2bc62fbb51f6ee56f93ec6e24753849c9b7
https://github.com/warehouseai/smart-private-npm/blob/c5e1f2bc62fbb51f6ee56f93ec6e24753849c9b7/lib/npm-proxy.js#L245-L269
25,926
sassoftware/restaf
src/serverCalls/index.js
implicitGrant
function implicitGrant (iconfig) { /* */ let link = iconfig.link ; window.location.href = `${iconfig.host + link.href}?response_type=${link.responseType}&client_id=${iconfig.clientID}`; return new Promise.resolve() }
javascript
function implicitGrant (iconfig) { /* */ let link = iconfig.link ; window.location.href = `${iconfig.host + link.href}?response_type=${link.responseType}&client_id=${iconfig.clientID}`; return new Promise.resolve() }
[ "function", "implicitGrant", "(", "iconfig", ")", "{", "/* */", "let", "link", "=", "iconfig", ".", "link", ";", "window", ".", "location", ".", "href", "=", "`", "${", "iconfig", ".", "host", "+", "link", ".", "href", "}", "${", "link", ".", "responseType", "}", "${", "iconfig", ".", "clientID", "}", "`", ";", "return", "new", "Promise", ".", "resolve", "(", ")", "}" ]
Code below is for experimenting.
[ "Code", "below", "is", "for", "experimenting", "." ]
fc3122184ab8cf32dd431f0b832b87d156873d0b
https://github.com/sassoftware/restaf/blob/fc3122184ab8cf32dd431f0b832b87d156873d0b/src/serverCalls/index.js#L282-L289
25,927
sassoftware/restaf
src/store/apiSubmit.js
apiSubmit
async function apiSubmit (store, iroute, payload, delay, jobContext, onCompletion, progress){ if (progress) { progress('pending', jobContext); } let job = await iapiCall(store, iroute, API_CALL, payload, 0, null, null, jobContext); if (job.links('state')) { let status = await jobState(store, job, null, 'wait', delay, progress, jobContext); completion(store, onCompletion,status.data,status.job, jobContext); return status.job; } else { completion(store, onCompletion, 'unknown', job, jobContext); return job; } }
javascript
async function apiSubmit (store, iroute, payload, delay, jobContext, onCompletion, progress){ if (progress) { progress('pending', jobContext); } let job = await iapiCall(store, iroute, API_CALL, payload, 0, null, null, jobContext); if (job.links('state')) { let status = await jobState(store, job, null, 'wait', delay, progress, jobContext); completion(store, onCompletion,status.data,status.job, jobContext); return status.job; } else { completion(store, onCompletion, 'unknown', job, jobContext); return job; } }
[ "async", "function", "apiSubmit", "(", "store", ",", "iroute", ",", "payload", ",", "delay", ",", "jobContext", ",", "onCompletion", ",", "progress", ")", "{", "if", "(", "progress", ")", "{", "progress", "(", "'pending'", ",", "jobContext", ")", ";", "}", "let", "job", "=", "await", "iapiCall", "(", "store", ",", "iroute", ",", "API_CALL", ",", "payload", ",", "0", ",", "null", ",", "null", ",", "jobContext", ")", ";", "if", "(", "job", ".", "links", "(", "'state'", ")", ")", "{", "let", "status", "=", "await", "jobState", "(", "store", ",", "job", ",", "null", ",", "'wait'", ",", "delay", ",", "progress", ",", "jobContext", ")", ";", "completion", "(", "store", ",", "onCompletion", ",", "status", ".", "data", ",", "status", ".", "job", ",", "jobContext", ")", ";", "return", "status", ".", "job", ";", "}", "else", "{", "completion", "(", "store", ",", "onCompletion", ",", "'unknown'", ",", "job", ",", "jobContext", ")", ";", "return", "job", ";", "}", "}" ]
store, iroute, actionType, payload, delay, eventHandler, parentRoute, jobContext
[ "store", "iroute", "actionType", "payload", "delay", "eventHandler", "parentRoute", "jobContext" ]
fc3122184ab8cf32dd431f0b832b87d156873d0b
https://github.com/sassoftware/restaf/blob/fc3122184ab8cf32dd431f0b832b87d156873d0b/src/store/apiSubmit.js#L26-L43
25,928
m19c/gulp-run
command.js
Command
function Command(command, options) { var previousPath; this.command = command; // We're on Windows if `process.platform` starts with "win", i.e. "win32". this.isWindows = (process.platform.lastIndexOf('win') === 0); // the cwd and environment of the command are the same as the main node // process by default. this.options = defaults(options || {}, { cwd: process.cwd(), env: process.env, verbosity: (options && options.silent) ? 1 : 2, usePowerShell: false }); // include node_modules/.bin on the path when we execute the command. previousPath = this.options.env.PATH; this.options.env.PATH = path.join(this.options.cwd, 'node_modules', '.bin'); this.options.env.PATH += path.delimiter; this.options.env.PATH += previousPath; }
javascript
function Command(command, options) { var previousPath; this.command = command; // We're on Windows if `process.platform` starts with "win", i.e. "win32". this.isWindows = (process.platform.lastIndexOf('win') === 0); // the cwd and environment of the command are the same as the main node // process by default. this.options = defaults(options || {}, { cwd: process.cwd(), env: process.env, verbosity: (options && options.silent) ? 1 : 2, usePowerShell: false }); // include node_modules/.bin on the path when we execute the command. previousPath = this.options.env.PATH; this.options.env.PATH = path.join(this.options.cwd, 'node_modules', '.bin'); this.options.env.PATH += path.delimiter; this.options.env.PATH += previousPath; }
[ "function", "Command", "(", "command", ",", "options", ")", "{", "var", "previousPath", ";", "this", ".", "command", "=", "command", ";", "// We're on Windows if `process.platform` starts with \"win\", i.e. \"win32\".", "this", ".", "isWindows", "=", "(", "process", ".", "platform", ".", "lastIndexOf", "(", "'win'", ")", "===", "0", ")", ";", "// the cwd and environment of the command are the same as the main node", "// process by default.", "this", ".", "options", "=", "defaults", "(", "options", "||", "{", "}", ",", "{", "cwd", ":", "process", ".", "cwd", "(", ")", ",", "env", ":", "process", ".", "env", ",", "verbosity", ":", "(", "options", "&&", "options", ".", "silent", ")", "?", "1", ":", "2", ",", "usePowerShell", ":", "false", "}", ")", ";", "// include node_modules/.bin on the path when we execute the command.", "previousPath", "=", "this", ".", "options", ".", "env", ".", "PATH", ";", "this", ".", "options", ".", "env", ".", "PATH", "=", "path", ".", "join", "(", "this", ".", "options", ".", "cwd", ",", "'node_modules'", ",", "'.bin'", ")", ";", "this", ".", "options", ".", "env", ".", "PATH", "+=", "path", ".", "delimiter", ";", "this", ".", "options", ".", "env", ".", "PATH", "+=", "previousPath", ";", "}" ]
Creates a new `gulp-run` command. @param {string} command @param {object} options
[ "Creates", "a", "new", "gulp", "-", "run", "command", "." ]
f58b6dbeb2d9f1c21579a7654d28ce6764f3a541
https://github.com/m19c/gulp-run/blob/f58b6dbeb2d9f1c21579a7654d28ce6764f3a541/command.js#L16-L38
25,929
m19c/gulp-run
index.js
GulpRunner
function GulpRunner(template, options) { if (!(this instanceof GulpRunner)) { return new GulpRunner(template, options); } this.command = new Command(template, options || {}); Transform.call(this, { objectMode: true }); }
javascript
function GulpRunner(template, options) { if (!(this instanceof GulpRunner)) { return new GulpRunner(template, options); } this.command = new Command(template, options || {}); Transform.call(this, { objectMode: true }); }
[ "function", "GulpRunner", "(", "template", ",", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "GulpRunner", ")", ")", "{", "return", "new", "GulpRunner", "(", "template", ",", "options", ")", ";", "}", "this", ".", "command", "=", "new", "Command", "(", "template", ",", "options", "||", "{", "}", ")", ";", "Transform", ".", "call", "(", "this", ",", "{", "objectMode", ":", "true", "}", ")", ";", "}" ]
Creates a GulpRunner. A GulpRunner is a Vinyl transform stream that spawns a child process to transform the file. A separate process is spawned to handle each file passing through the stream. @param {string} template @param {object} options
[ "Creates", "a", "GulpRunner", "." ]
f58b6dbeb2d9f1c21579a7654d28ce6764f3a541
https://github.com/m19c/gulp-run/blob/f58b6dbeb2d9f1c21579a7654d28ce6764f3a541/index.js#L20-L27
25,930
gruntjs/grunt-init
tasks/init.js
function(arg1) { if (arg1 == null) { return null; } var args = [name, 'root'].concat(grunt.util.toArray(arguments)); return helpers.getFile.apply(helpers, args); }
javascript
function(arg1) { if (arg1 == null) { return null; } var args = [name, 'root'].concat(grunt.util.toArray(arguments)); return helpers.getFile.apply(helpers, args); }
[ "function", "(", "arg1", ")", "{", "if", "(", "arg1", "==", "null", ")", "{", "return", "null", ";", "}", "var", "args", "=", "[", "name", ",", "'root'", "]", ".", "concat", "(", "grunt", ".", "util", ".", "toArray", "(", "arguments", ")", ")", ";", "return", "helpers", ".", "getFile", ".", "apply", "(", "helpers", ",", "args", ")", ";", "}" ]
Search init template paths for filename.
[ "Search", "init", "template", "paths", "for", "filename", "." ]
cbec886f26dce52d19c828df3fed031ce9767663
https://github.com/gruntjs/grunt-init/blob/cbec886f26dce52d19c828df3fed031ce9767663/tasks/init.js#L342-L346
25,931
gruntjs/grunt-init
tasks/init.js
function(files, licenses) { licenses.forEach(function(license) { var fileobj = helpers.expand({filter: 'isFile'}, 'licenses/LICENSE-' + license)[0]; if(fileobj) { files['LICENSE-' + license] = fileobj.rel; } }); }
javascript
function(files, licenses) { licenses.forEach(function(license) { var fileobj = helpers.expand({filter: 'isFile'}, 'licenses/LICENSE-' + license)[0]; if(fileobj) { files['LICENSE-' + license] = fileobj.rel; } }); }
[ "function", "(", "files", ",", "licenses", ")", "{", "licenses", ".", "forEach", "(", "function", "(", "license", ")", "{", "var", "fileobj", "=", "helpers", ".", "expand", "(", "{", "filter", ":", "'isFile'", "}", ",", "'licenses/LICENSE-'", "+", "license", ")", "[", "0", "]", ";", "if", "(", "fileobj", ")", "{", "files", "[", "'LICENSE-'", "+", "license", "]", "=", "fileobj", ".", "rel", ";", "}", "}", ")", ";", "}" ]
Given some number of licenses, add properly-named license files to the files object.
[ "Given", "some", "number", "of", "licenses", "add", "properly", "-", "named", "license", "files", "to", "the", "files", "object", "." ]
cbec886f26dce52d19c828df3fed031ce9767663
https://github.com/gruntjs/grunt-init/blob/cbec886f26dce52d19c828df3fed031ce9767663/tasks/init.js#L351-L358
25,932
gruntjs/grunt-init
tasks/init.js
function(srcpath, destpath, options) { // Destpath is optional. if (typeof destpath !== 'string') { options = destpath; destpath = srcpath; } // Ensure srcpath is absolute. if (!grunt.file.isPathAbsolute(srcpath)) { srcpath = init.srcpath(srcpath); } // Use placeholder file if no src exists. if (!srcpath) { srcpath = helpers.getFile('misc/placeholder'); } grunt.verbose.or.write('Writing ' + destpath + '...'); try { grunt.file.copy(srcpath, init.destpath(destpath), options); grunt.verbose.or.ok(); } catch(e) { grunt.verbose.or.error().error(e); throw e; } }
javascript
function(srcpath, destpath, options) { // Destpath is optional. if (typeof destpath !== 'string') { options = destpath; destpath = srcpath; } // Ensure srcpath is absolute. if (!grunt.file.isPathAbsolute(srcpath)) { srcpath = init.srcpath(srcpath); } // Use placeholder file if no src exists. if (!srcpath) { srcpath = helpers.getFile('misc/placeholder'); } grunt.verbose.or.write('Writing ' + destpath + '...'); try { grunt.file.copy(srcpath, init.destpath(destpath), options); grunt.verbose.or.ok(); } catch(e) { grunt.verbose.or.error().error(e); throw e; } }
[ "function", "(", "srcpath", ",", "destpath", ",", "options", ")", "{", "// Destpath is optional.", "if", "(", "typeof", "destpath", "!==", "'string'", ")", "{", "options", "=", "destpath", ";", "destpath", "=", "srcpath", ";", "}", "// Ensure srcpath is absolute.", "if", "(", "!", "grunt", ".", "file", ".", "isPathAbsolute", "(", "srcpath", ")", ")", "{", "srcpath", "=", "init", ".", "srcpath", "(", "srcpath", ")", ";", "}", "// Use placeholder file if no src exists.", "if", "(", "!", "srcpath", ")", "{", "srcpath", "=", "helpers", ".", "getFile", "(", "'misc/placeholder'", ")", ";", "}", "grunt", ".", "verbose", ".", "or", ".", "write", "(", "'Writing '", "+", "destpath", "+", "'...'", ")", ";", "try", "{", "grunt", ".", "file", ".", "copy", "(", "srcpath", ",", "init", ".", "destpath", "(", "destpath", ")", ",", "options", ")", ";", "grunt", ".", "verbose", ".", "or", ".", "ok", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "grunt", ".", "verbose", ".", "or", ".", "error", "(", ")", ".", "error", "(", "e", ")", ";", "throw", "e", ";", "}", "}" ]
Given an absolute or relative source path, and an optional relative destination path, copy a file, optionally processing it through the passed callback.
[ "Given", "an", "absolute", "or", "relative", "source", "path", "and", "an", "optional", "relative", "destination", "path", "copy", "a", "file", "optionally", "processing", "it", "through", "the", "passed", "callback", "." ]
cbec886f26dce52d19c828df3fed031ce9767663
https://github.com/gruntjs/grunt-init/blob/cbec886f26dce52d19c828df3fed031ce9767663/tasks/init.js#L362-L384
25,933
gruntjs/grunt-init
tasks/init.js
function(files, props, options) { options = _.defaults(options || {}, { process: function(contents) { return grunt.template.process(contents, {data: props, delimiters: 'init'}); } }); Object.keys(files).forEach(function(destpath) { var o = Object.create(options); var srcpath = files[destpath]; // If srcpath is relative, match it against options.noProcess if // necessary, then make srcpath absolute. var relpath; if (srcpath && !grunt.file.isPathAbsolute(srcpath)) { if (o.noProcess) { relpath = srcpath.slice(pathPrefix.length); o.noProcess = grunt.file.isMatch({matchBase: true}, o.noProcess, relpath); } srcpath = helpers.getFile(srcpath); } // Copy! init.copy(srcpath, destpath, o); }); }
javascript
function(files, props, options) { options = _.defaults(options || {}, { process: function(contents) { return grunt.template.process(contents, {data: props, delimiters: 'init'}); } }); Object.keys(files).forEach(function(destpath) { var o = Object.create(options); var srcpath = files[destpath]; // If srcpath is relative, match it against options.noProcess if // necessary, then make srcpath absolute. var relpath; if (srcpath && !grunt.file.isPathAbsolute(srcpath)) { if (o.noProcess) { relpath = srcpath.slice(pathPrefix.length); o.noProcess = grunt.file.isMatch({matchBase: true}, o.noProcess, relpath); } srcpath = helpers.getFile(srcpath); } // Copy! init.copy(srcpath, destpath, o); }); }
[ "function", "(", "files", ",", "props", ",", "options", ")", "{", "options", "=", "_", ".", "defaults", "(", "options", "||", "{", "}", ",", "{", "process", ":", "function", "(", "contents", ")", "{", "return", "grunt", ".", "template", ".", "process", "(", "contents", ",", "{", "data", ":", "props", ",", "delimiters", ":", "'init'", "}", ")", ";", "}", "}", ")", ";", "Object", ".", "keys", "(", "files", ")", ".", "forEach", "(", "function", "(", "destpath", ")", "{", "var", "o", "=", "Object", ".", "create", "(", "options", ")", ";", "var", "srcpath", "=", "files", "[", "destpath", "]", ";", "// If srcpath is relative, match it against options.noProcess if", "// necessary, then make srcpath absolute.", "var", "relpath", ";", "if", "(", "srcpath", "&&", "!", "grunt", ".", "file", ".", "isPathAbsolute", "(", "srcpath", ")", ")", "{", "if", "(", "o", ".", "noProcess", ")", "{", "relpath", "=", "srcpath", ".", "slice", "(", "pathPrefix", ".", "length", ")", ";", "o", ".", "noProcess", "=", "grunt", ".", "file", ".", "isMatch", "(", "{", "matchBase", ":", "true", "}", ",", "o", ".", "noProcess", ",", "relpath", ")", ";", "}", "srcpath", "=", "helpers", ".", "getFile", "(", "srcpath", ")", ";", "}", "// Copy!", "init", ".", "copy", "(", "srcpath", ",", "destpath", ",", "o", ")", ";", "}", ")", ";", "}" ]
Iterate over all files in the passed object, copying the source file to the destination, processing the contents.
[ "Iterate", "over", "all", "files", "in", "the", "passed", "object", "copying", "the", "source", "file", "to", "the", "destination", "processing", "the", "contents", "." ]
cbec886f26dce52d19c828df3fed031ce9767663
https://github.com/gruntjs/grunt-init/blob/cbec886f26dce52d19c828df3fed031ce9767663/tasks/init.js#L387-L409
25,934
vskosp/vsGoogleAutocomplete
dist/vs-autocomplete-validator.js
Validator
function Validator(validatorsNamesList) { // add default embedded validator name validatorsNamesList.unshift('vsGooglePlace'); this._embeddedValidators = vsEmbeddedValidatorsInjector.get(validatorsNamesList); this.error = {}; this.valid = true; }
javascript
function Validator(validatorsNamesList) { // add default embedded validator name validatorsNamesList.unshift('vsGooglePlace'); this._embeddedValidators = vsEmbeddedValidatorsInjector.get(validatorsNamesList); this.error = {}; this.valid = true; }
[ "function", "Validator", "(", "validatorsNamesList", ")", "{", "// add default embedded validator name", "validatorsNamesList", ".", "unshift", "(", "'vsGooglePlace'", ")", ";", "this", ".", "_embeddedValidators", "=", "vsEmbeddedValidatorsInjector", ".", "get", "(", "validatorsNamesList", ")", ";", "this", ".", "error", "=", "{", "}", ";", "this", ".", "valid", "=", "true", ";", "}" ]
Class making validator associated with vsGoogleAutocomplete controller. @constructor @param {Array.<string>} validatorsNamesList - List of embedded validator names.
[ "Class", "making", "validator", "associated", "with", "vsGoogleAutocomplete", "controller", "." ]
4ec8b242904d3a94761f4278989f161c910f71ac
https://github.com/vskosp/vsGoogleAutocomplete/blob/4ec8b242904d3a94761f4278989f161c910f71ac/dist/vs-autocomplete-validator.js#L60-L67
25,935
vskosp/vsGoogleAutocomplete
dist/vs-autocomplete-validator.js
parseValidatorNames
function parseValidatorNames(attrs) { var attrValue = attrs.vsAutocompleteValidator, validatorNames = (attrValue!=="") ? attrValue.trim().split(',') : []; // normalize validator names for (var i = 0; i < validatorNames.length; i++) { validatorNames[i] = attrs.$normalize(validatorNames[i]); } return validatorNames; }
javascript
function parseValidatorNames(attrs) { var attrValue = attrs.vsAutocompleteValidator, validatorNames = (attrValue!=="") ? attrValue.trim().split(',') : []; // normalize validator names for (var i = 0; i < validatorNames.length; i++) { validatorNames[i] = attrs.$normalize(validatorNames[i]); } return validatorNames; }
[ "function", "parseValidatorNames", "(", "attrs", ")", "{", "var", "attrValue", "=", "attrs", ".", "vsAutocompleteValidator", ",", "validatorNames", "=", "(", "attrValue", "!==", "\"\"", ")", "?", "attrValue", ".", "trim", "(", ")", ".", "split", "(", "','", ")", ":", "[", "]", ";", "// normalize validator names", "for", "(", "var", "i", "=", "0", ";", "i", "<", "validatorNames", ".", "length", ";", "i", "++", ")", "{", "validatorNames", "[", "i", "]", "=", "attrs", ".", "$normalize", "(", "validatorNames", "[", "i", "]", ")", ";", "}", "return", "validatorNames", ";", "}" ]
Parse validator names from attribute. @param {$compile.directive.Attributes} attrs Element attributes @return {Array.<string>} Returns array of normalized validator names.
[ "Parse", "validator", "names", "from", "attribute", "." ]
4ec8b242904d3a94761f4278989f161c910f71ac
https://github.com/vskosp/vsGoogleAutocomplete/blob/4ec8b242904d3a94761f4278989f161c910f71ac/dist/vs-autocomplete-validator.js#L126-L136
25,936
mongodb-js/extended-json
lib/serialize.js
serialize
function serialize(value) { if (Array.isArray(value) === true) { return serializeArray(value); } if (isObject(value) === false) { return serializePrimitive(value); } return serializeObject(value); }
javascript
function serialize(value) { if (Array.isArray(value) === true) { return serializeArray(value); } if (isObject(value) === false) { return serializePrimitive(value); } return serializeObject(value); }
[ "function", "serialize", "(", "value", ")", "{", "if", "(", "Array", ".", "isArray", "(", "value", ")", "===", "true", ")", "{", "return", "serializeArray", "(", "value", ")", ";", "}", "if", "(", "isObject", "(", "value", ")", "===", "false", ")", "{", "return", "serializePrimitive", "(", "value", ")", ";", "}", "return", "serializeObject", "(", "value", ")", ";", "}" ]
Format values with extra extended json type data. @param {Any} value - What to wrap as a `{$<type>: <encoded>}` object. @return {Any} @api private
[ "Format", "values", "with", "extra", "extended", "json", "type", "data", "." ]
3116e58531c504d9c9f1c6a5f53c24bb7d1ec65f
https://github.com/mongodb-js/extended-json/blob/3116e58531c504d9c9f1c6a5f53c24bb7d1ec65f/lib/serialize.js#L44-L52
25,937
canjs/can-compile
example/js/components/todo-app.js
function () { var filter = can.route.attr('filter'); return this.todos.filter(function (todo) { if (filter === 'completed') { return todo.attr('complete'); } if (filter === 'active') { return !todo.attr('complete'); } return true; }); }
javascript
function () { var filter = can.route.attr('filter'); return this.todos.filter(function (todo) { if (filter === 'completed') { return todo.attr('complete'); } if (filter === 'active') { return !todo.attr('complete'); } return true; }); }
[ "function", "(", ")", "{", "var", "filter", "=", "can", ".", "route", ".", "attr", "(", "'filter'", ")", ";", "return", "this", ".", "todos", ".", "filter", "(", "function", "(", "todo", ")", "{", "if", "(", "filter", "===", "'completed'", ")", "{", "return", "todo", ".", "attr", "(", "'complete'", ")", ";", "}", "if", "(", "filter", "===", "'active'", ")", "{", "return", "!", "todo", ".", "attr", "(", "'complete'", ")", ";", "}", "return", "true", ";", "}", ")", ";", "}" ]
Returns a list of Todos filtered based on the route
[ "Returns", "a", "list", "of", "Todos", "filtered", "based", "on", "the", "route" ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/js/components/todo-app.js#L27-L40
25,938
canjs/can-compile
example/dist/production.js
function(el, val) { if (val == null || val === "") { el.removeAttribute("src"); return null; } else { el.setAttribute("src", val); return val; } }
javascript
function(el, val) { if (val == null || val === "") { el.removeAttribute("src"); return null; } else { el.setAttribute("src", val); return val; } }
[ "function", "(", "el", ",", "val", ")", "{", "if", "(", "val", "==", "null", "||", "val", "===", "\"\"", ")", "{", "el", ".", "removeAttribute", "(", "\"src\"", ")", ";", "return", "null", ";", "}", "else", "{", "el", ".", "setAttribute", "(", "\"src\"", ",", "val", ")", ";", "return", "val", ";", "}", "}" ]
For the `src` attribute we are using a setter function to prevent values such as an empty string or null from being set. An `img` tag attempts to fetch the `src` when it is set, so we need to prevent that from happening by removing the attribute instead.
[ "For", "the", "src", "attribute", "we", "are", "using", "a", "setter", "function", "to", "prevent", "values", "such", "as", "an", "empty", "string", "or", "null", "from", "being", "set", ".", "An", "img", "tag", "attempts", "to", "fetch", "the", "src", "when", "it", "is", "set", "so", "we", "need", "to", "prevent", "that", "from", "happening", "by", "removing", "the", "attribute", "instead", "." ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L9149-L9157
25,939
canjs/can-compile
example/dist/production.js
function() { if (arguments.length === 0 && can.Control && this instanceof can.Control) { return can.Control.prototype.on.call(this); } else { return can.addEvent.apply(this, arguments); } }
javascript
function() { if (arguments.length === 0 && can.Control && this instanceof can.Control) { return can.Control.prototype.on.call(this); } else { return can.addEvent.apply(this, arguments); } }
[ "function", "(", ")", "{", "if", "(", "arguments", ".", "length", "===", "0", "&&", "can", ".", "Control", "&&", "this", "instanceof", "can", ".", "Control", ")", "{", "return", "can", ".", "Control", ".", "prototype", ".", "on", ".", "call", "(", "this", ")", ";", "}", "else", "{", "return", "can", ".", "addEvent", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "}" ]
Event method aliases
[ "Event", "method", "aliases" ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L9461-L9467
25,940
canjs/can-compile
example/dist/production.js
function(fullName, klass, proto) { // Figure out what was passed and normalize it. if (typeof fullName !== 'string') { proto = klass; klass = fullName; fullName = null; } if (!proto) { proto = klass; klass = null; } proto = proto || {}; var _super_class = this, _super = this.prototype, parts, current, _fullName, _shortName, name, shortName, namespace, prototype; // Instantiate a base class (but only create the instance, // don't run the init constructor). prototype = this.instance(); // Copy the properties over onto the new prototype. can.Construct._inherit(proto, _super, prototype); // The dummy class constructor. function Constructor() { // All construction is actually done in the init method. if (!initializing) { return this.constructor !== Constructor && // We are being called without `new` or we are extending. arguments.length && Constructor.constructorExtends ? Constructor.extend.apply(Constructor, arguments) : // We are being called with `new`. Constructor.newInstance.apply(Constructor, arguments); } } // Copy old stuff onto class (can probably be merged w/ inherit) for (name in _super_class) { if (_super_class.hasOwnProperty(name)) { Constructor[name] = _super_class[name]; } } // Copy new static properties on class. can.Construct._inherit(klass, _super_class, Constructor); // Setup namespaces. if (fullName) { parts = fullName.split('.'); shortName = parts.pop(); current = can.getObject(parts.join('.'), window, true); namespace = current; _fullName = can.underscore(fullName.replace(/\./g, "_")); _shortName = can.underscore(shortName); current[shortName] = Constructor; } // Set things that shouldn't be overwritten. can.extend(Constructor, { constructor: Constructor, prototype: prototype, namespace: namespace, _shortName: _shortName, fullName: fullName, _fullName: _fullName }); // Dojo and YUI extend undefined if (shortName !== undefined) { Constructor.shortName = shortName; } // Make sure our prototype looks nice. Constructor.prototype.constructor = Constructor; // Call the class `setup` and `init` var t = [_super_class].concat(can.makeArray(arguments)), args = Constructor.setup.apply(Constructor, t); if (Constructor.init) { Constructor.init.apply(Constructor, args || t); } return Constructor; }
javascript
function(fullName, klass, proto) { // Figure out what was passed and normalize it. if (typeof fullName !== 'string') { proto = klass; klass = fullName; fullName = null; } if (!proto) { proto = klass; klass = null; } proto = proto || {}; var _super_class = this, _super = this.prototype, parts, current, _fullName, _shortName, name, shortName, namespace, prototype; // Instantiate a base class (but only create the instance, // don't run the init constructor). prototype = this.instance(); // Copy the properties over onto the new prototype. can.Construct._inherit(proto, _super, prototype); // The dummy class constructor. function Constructor() { // All construction is actually done in the init method. if (!initializing) { return this.constructor !== Constructor && // We are being called without `new` or we are extending. arguments.length && Constructor.constructorExtends ? Constructor.extend.apply(Constructor, arguments) : // We are being called with `new`. Constructor.newInstance.apply(Constructor, arguments); } } // Copy old stuff onto class (can probably be merged w/ inherit) for (name in _super_class) { if (_super_class.hasOwnProperty(name)) { Constructor[name] = _super_class[name]; } } // Copy new static properties on class. can.Construct._inherit(klass, _super_class, Constructor); // Setup namespaces. if (fullName) { parts = fullName.split('.'); shortName = parts.pop(); current = can.getObject(parts.join('.'), window, true); namespace = current; _fullName = can.underscore(fullName.replace(/\./g, "_")); _shortName = can.underscore(shortName); current[shortName] = Constructor; } // Set things that shouldn't be overwritten. can.extend(Constructor, { constructor: Constructor, prototype: prototype, namespace: namespace, _shortName: _shortName, fullName: fullName, _fullName: _fullName }); // Dojo and YUI extend undefined if (shortName !== undefined) { Constructor.shortName = shortName; } // Make sure our prototype looks nice. Constructor.prototype.constructor = Constructor; // Call the class `setup` and `init` var t = [_super_class].concat(can.makeArray(arguments)), args = Constructor.setup.apply(Constructor, t); if (Constructor.init) { Constructor.init.apply(Constructor, args || t); } return Constructor; }
[ "function", "(", "fullName", ",", "klass", ",", "proto", ")", "{", "// Figure out what was passed and normalize it.", "if", "(", "typeof", "fullName", "!==", "'string'", ")", "{", "proto", "=", "klass", ";", "klass", "=", "fullName", ";", "fullName", "=", "null", ";", "}", "if", "(", "!", "proto", ")", "{", "proto", "=", "klass", ";", "klass", "=", "null", ";", "}", "proto", "=", "proto", "||", "{", "}", ";", "var", "_super_class", "=", "this", ",", "_super", "=", "this", ".", "prototype", ",", "parts", ",", "current", ",", "_fullName", ",", "_shortName", ",", "name", ",", "shortName", ",", "namespace", ",", "prototype", ";", "// Instantiate a base class (but only create the instance,", "// don't run the init constructor).", "prototype", "=", "this", ".", "instance", "(", ")", ";", "// Copy the properties over onto the new prototype.", "can", ".", "Construct", ".", "_inherit", "(", "proto", ",", "_super", ",", "prototype", ")", ";", "// The dummy class constructor.", "function", "Constructor", "(", ")", "{", "// All construction is actually done in the init method.", "if", "(", "!", "initializing", ")", "{", "return", "this", ".", "constructor", "!==", "Constructor", "&&", "// We are being called without `new` or we are extending.", "arguments", ".", "length", "&&", "Constructor", ".", "constructorExtends", "?", "Constructor", ".", "extend", ".", "apply", "(", "Constructor", ",", "arguments", ")", ":", "// We are being called with `new`.", "Constructor", ".", "newInstance", ".", "apply", "(", "Constructor", ",", "arguments", ")", ";", "}", "}", "// Copy old stuff onto class (can probably be merged w/ inherit)", "for", "(", "name", "in", "_super_class", ")", "{", "if", "(", "_super_class", ".", "hasOwnProperty", "(", "name", ")", ")", "{", "Constructor", "[", "name", "]", "=", "_super_class", "[", "name", "]", ";", "}", "}", "// Copy new static properties on class.", "can", ".", "Construct", ".", "_inherit", "(", "klass", ",", "_super_class", ",", "Constructor", ")", ";", "// Setup namespaces.", "if", "(", "fullName", ")", "{", "parts", "=", "fullName", ".", "split", "(", "'.'", ")", ";", "shortName", "=", "parts", ".", "pop", "(", ")", ";", "current", "=", "can", ".", "getObject", "(", "parts", ".", "join", "(", "'.'", ")", ",", "window", ",", "true", ")", ";", "namespace", "=", "current", ";", "_fullName", "=", "can", ".", "underscore", "(", "fullName", ".", "replace", "(", "/", "\\.", "/", "g", ",", "\"_\"", ")", ")", ";", "_shortName", "=", "can", ".", "underscore", "(", "shortName", ")", ";", "current", "[", "shortName", "]", "=", "Constructor", ";", "}", "// Set things that shouldn't be overwritten.", "can", ".", "extend", "(", "Constructor", ",", "{", "constructor", ":", "Constructor", ",", "prototype", ":", "prototype", ",", "namespace", ":", "namespace", ",", "_shortName", ":", "_shortName", ",", "fullName", ":", "fullName", ",", "_fullName", ":", "_fullName", "}", ")", ";", "// Dojo and YUI extend undefined", "if", "(", "shortName", "!==", "undefined", ")", "{", "Constructor", ".", "shortName", "=", "shortName", ";", "}", "// Make sure our prototype looks nice.", "Constructor", ".", "prototype", ".", "constructor", "=", "Constructor", ";", "// Call the class `setup` and `init`", "var", "t", "=", "[", "_super_class", "]", ".", "concat", "(", "can", ".", "makeArray", "(", "arguments", ")", ")", ",", "args", "=", "Constructor", ".", "setup", ".", "apply", "(", "Constructor", ",", "t", ")", ";", "if", "(", "Constructor", ".", "init", ")", "{", "Constructor", ".", "init", ".", "apply", "(", "Constructor", ",", "args", "||", "t", ")", ";", "}", "return", "Constructor", ";", "}" ]
Extends classes.
[ "Extends", "classes", "." ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L10667-L10749
25,941
canjs/can-compile
example/dist/production.js
function() { for (var cid in madeMap) { if (madeMap[cid].added) { delete madeMap[cid].obj._cid; } } madeMap = null; }
javascript
function() { for (var cid in madeMap) { if (madeMap[cid].added) { delete madeMap[cid].obj._cid; } } madeMap = null; }
[ "function", "(", ")", "{", "for", "(", "var", "cid", "in", "madeMap", ")", "{", "if", "(", "madeMap", "[", "cid", "]", ".", "added", ")", "{", "delete", "madeMap", "[", "cid", "]", ".", "obj", ".", "_cid", ";", "}", "}", "madeMap", "=", "null", ";", "}" ]
Clears out map of converted objects.
[ "Clears", "out", "map", "of", "converted", "objects", "." ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L11306-L11313
25,942
canjs/can-compile
example/dist/production.js
function() { var computes = this.constructor._computes; this._computedBindings = {}; for (var i = 0, len = computes.length, prop; i < len; i++) { prop = computes[i]; // Make the context of the compute the current Map this[prop] = this[prop].clone(this); // Keep track of computed properties this._computedBindings[prop] = { count: 0 }; } }
javascript
function() { var computes = this.constructor._computes; this._computedBindings = {}; for (var i = 0, len = computes.length, prop; i < len; i++) { prop = computes[i]; // Make the context of the compute the current Map this[prop] = this[prop].clone(this); // Keep track of computed properties this._computedBindings[prop] = { count: 0 }; } }
[ "function", "(", ")", "{", "var", "computes", "=", "this", ".", "constructor", ".", "_computes", ";", "this", ".", "_computedBindings", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "computes", ".", "length", ",", "prop", ";", "i", "<", "len", ";", "i", "++", ")", "{", "prop", "=", "computes", "[", "i", "]", ";", "// Make the context of the compute the current Map", "this", "[", "prop", "]", "=", "this", "[", "prop", "]", ".", "clone", "(", "this", ")", ";", "// Keep track of computed properties", "this", ".", "_computedBindings", "[", "prop", "]", "=", "{", "count", ":", "0", "}", ";", "}", "}" ]
Sets up computed properties on a Map.
[ "Sets", "up", "computed", "properties", "on", "a", "Map", "." ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L11517-L11530
25,943
canjs/can-compile
example/dist/production.js
function(ev, attr, how, newVal, oldVal) { // when a change happens, create the named event. can.batch.trigger(this, { type: attr, batchNum: ev.batchNum }, [newVal, oldVal]); if (how === "remove" || how === "add") { can.batch.trigger(this, { type: "__keys", batchNum: ev.batchNum }); } }
javascript
function(ev, attr, how, newVal, oldVal) { // when a change happens, create the named event. can.batch.trigger(this, { type: attr, batchNum: ev.batchNum }, [newVal, oldVal]); if (how === "remove" || how === "add") { can.batch.trigger(this, { type: "__keys", batchNum: ev.batchNum }); } }
[ "function", "(", "ev", ",", "attr", ",", "how", ",", "newVal", ",", "oldVal", ")", "{", "// when a change happens, create the named event.", "can", ".", "batch", ".", "trigger", "(", "this", ",", "{", "type", ":", "attr", ",", "batchNum", ":", "ev", ".", "batchNum", "}", ",", "[", "newVal", ",", "oldVal", "]", ")", ";", "if", "(", "how", "===", "\"remove\"", "||", "how", "===", "\"add\"", ")", "{", "can", ".", "batch", ".", "trigger", "(", "this", ",", "{", "type", ":", "\"__keys\"", ",", "batchNum", ":", "ev", ".", "batchNum", "}", ")", ";", "}", "}" ]
`change`event handler.
[ "change", "event", "handler", "." ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L11539-L11552
25,944
canjs/can-compile
example/dist/production.js
function(attr, how, newVal, oldVal) { can.batch.trigger(this, "change", can.makeArray(arguments)); }
javascript
function(attr, how, newVal, oldVal) { can.batch.trigger(this, "change", can.makeArray(arguments)); }
[ "function", "(", "attr", ",", "how", ",", "newVal", ",", "oldVal", ")", "{", "can", ".", "batch", ".", "trigger", "(", "this", ",", "\"change\"", ",", "can", ".", "makeArray", "(", "arguments", ")", ")", ";", "}" ]
Trigger a change event.
[ "Trigger", "a", "change", "event", "." ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L11554-L11556
25,945
canjs/can-compile
example/dist/production.js
function(callback) { var data = this.__get(); for (var prop in data) { if (data.hasOwnProperty(prop)) { callback(data[prop], prop); } } }
javascript
function(callback) { var data = this.__get(); for (var prop in data) { if (data.hasOwnProperty(prop)) { callback(data[prop], prop); } } }
[ "function", "(", "callback", ")", "{", "var", "data", "=", "this", ".", "__get", "(", ")", ";", "for", "(", "var", "prop", "in", "data", ")", "{", "if", "(", "data", ".", "hasOwnProperty", "(", "prop", ")", ")", "{", "callback", "(", "data", "[", "prop", "]", ",", "prop", ")", ";", "}", "}", "}" ]
Iterator that does not trigger live binding.
[ "Iterator", "that", "does", "not", "trigger", "live", "binding", "." ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L11558-L11565
25,946
canjs/can-compile
example/dist/production.js
function(prop, current) { if (prop in this._data) { // Delete the property from `_data` and the Map // as long as it isn't part of the Map's prototype. delete this._data[prop]; if (!(prop in this.constructor.prototype)) { delete this[prop]; } // Let others now this property has been removed. this._triggerChange(prop, "remove", undefined, current); } }
javascript
function(prop, current) { if (prop in this._data) { // Delete the property from `_data` and the Map // as long as it isn't part of the Map's prototype. delete this._data[prop]; if (!(prop in this.constructor.prototype)) { delete this[prop]; } // Let others now this property has been removed. this._triggerChange(prop, "remove", undefined, current); } }
[ "function", "(", "prop", ",", "current", ")", "{", "if", "(", "prop", "in", "this", ".", "_data", ")", "{", "// Delete the property from `_data` and the Map", "// as long as it isn't part of the Map's prototype.", "delete", "this", ".", "_data", "[", "prop", "]", ";", "if", "(", "!", "(", "prop", "in", "this", ".", "constructor", ".", "prototype", ")", ")", "{", "delete", "this", "[", "prop", "]", ";", "}", "// Let others now this property has been removed.", "this", ".", "_triggerChange", "(", "prop", ",", "\"remove\"", ",", "undefined", ",", "current", ")", ";", "}", "}" ]
Remove a property.
[ "Remove", "a", "property", "." ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L11614-L11626
25,947
canjs/can-compile
example/dist/production.js
function(value, prop) { // If we are getting an object. if (!(value instanceof can.Map) && can.Map.helpers.canMakeObserve(value)) { var cached = getMapFromObject(value); if (cached) { return cached; } if (can.isArray(value)) { var List = can.List; return new List(value); } else { var Map = this.constructor.Map || can.Map; return new Map(value); } } return value; }
javascript
function(value, prop) { // If we are getting an object. if (!(value instanceof can.Map) && can.Map.helpers.canMakeObserve(value)) { var cached = getMapFromObject(value); if (cached) { return cached; } if (can.isArray(value)) { var List = can.List; return new List(value); } else { var Map = this.constructor.Map || can.Map; return new Map(value); } } return value; }
[ "function", "(", "value", ",", "prop", ")", "{", "// If we are getting an object.", "if", "(", "!", "(", "value", "instanceof", "can", ".", "Map", ")", "&&", "can", ".", "Map", ".", "helpers", ".", "canMakeObserve", "(", "value", ")", ")", "{", "var", "cached", "=", "getMapFromObject", "(", "value", ")", ";", "if", "(", "cached", ")", "{", "return", "cached", ";", "}", "if", "(", "can", ".", "isArray", "(", "value", ")", ")", "{", "var", "List", "=", "can", ".", "List", ";", "return", "new", "List", "(", "value", ")", ";", "}", "else", "{", "var", "Map", "=", "this", ".", "constructor", ".", "Map", "||", "can", ".", "Map", ";", "return", "new", "Map", "(", "value", ")", ";", "}", "}", "return", "value", ";", "}" ]
converts the value into an observable if needed
[ "converts", "the", "value", "into", "an", "observable", "if", "needed" ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L11672-L11689
25,948
canjs/can-compile
example/dist/production.js
function(updater) { for (var name in readInfo.observed) { var ob = readInfo.observed[name]; ob.obj.unbind(ob.event, onchanged); } }
javascript
function(updater) { for (var name in readInfo.observed) { var ob = readInfo.observed[name]; ob.obj.unbind(ob.event, onchanged); } }
[ "function", "(", "updater", ")", "{", "for", "(", "var", "name", "in", "readInfo", ".", "observed", ")", "{", "var", "ob", "=", "readInfo", ".", "observed", "[", "name", "]", ";", "ob", ".", "obj", ".", "unbind", "(", "ob", ".", "event", ",", "onchanged", ")", ";", "}", "}" ]
Remove handler for the compute
[ "Remove", "handler", "for", "the", "compute" ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L12397-L12402
25,949
canjs/can-compile
example/dist/production.js
function(newValue, oldValue, batchNum) { setCached(newValue); updateOnChange(computed, newValue, oldValue, batchNum); }
javascript
function(newValue, oldValue, batchNum) { setCached(newValue); updateOnChange(computed, newValue, oldValue, batchNum); }
[ "function", "(", "newValue", ",", "oldValue", ",", "batchNum", ")", "{", "setCached", "(", "newValue", ")", ";", "updateOnChange", "(", "computed", ",", "newValue", ",", "oldValue", ",", "batchNum", ")", ";", "}" ]
The computed object
[ "The", "computed", "object" ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L12449-L12452
25,950
canjs/can-compile
example/dist/production.js
function() { for (var i = 0, len = computes.length; i < len; i++) { computes[i].unbind('change', k); } computes = null; }
javascript
function() { for (var i = 0, len = computes.length; i < len; i++) { computes[i].unbind('change', k); } computes = null; }
[ "function", "(", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "computes", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "computes", "[", "i", "]", ".", "unbind", "(", "'change'", ",", "k", ")", ";", "}", "computes", "=", "null", ";", "}" ]
A list of temporarily bound computes
[ "A", "list", "of", "temporarily", "bound", "computes" ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L12677-L12682
25,951
canjs/can-compile
example/dist/production.js
function(parentValue, nameIndex) { if (nameIndex > defaultPropertyDepth) { defaultObserve = currentObserve; defaultReads = currentReads; defaultPropertyDepth = nameIndex; defaultScope = scope; defaultComputeReadings = can.__clearReading(); } }
javascript
function(parentValue, nameIndex) { if (nameIndex > defaultPropertyDepth) { defaultObserve = currentObserve; defaultReads = currentReads; defaultPropertyDepth = nameIndex; defaultScope = scope; defaultComputeReadings = can.__clearReading(); } }
[ "function", "(", "parentValue", ",", "nameIndex", ")", "{", "if", "(", "nameIndex", ">", "defaultPropertyDepth", ")", "{", "defaultObserve", "=", "currentObserve", ";", "defaultReads", "=", "currentReads", ";", "defaultPropertyDepth", "=", "nameIndex", ";", "defaultScope", "=", "scope", ";", "defaultComputeReadings", "=", "can", ".", "__clearReading", "(", ")", ";", "}", "}" ]
Called when we were unable to find a value.
[ "Called", "when", "we", "were", "unable", "to", "find", "a", "value", "." ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L13034-L13044
25,952
canjs/can-compile
example/dist/production.js
function() { if (!tornDown) { tornDown = true; unbind(data); can.unbind.call(el, 'removed', teardown); } return true; }
javascript
function() { if (!tornDown) { tornDown = true; unbind(data); can.unbind.call(el, 'removed', teardown); } return true; }
[ "function", "(", ")", "{", "if", "(", "!", "tornDown", ")", "{", "tornDown", "=", "true", ";", "unbind", "(", "data", ")", ";", "can", ".", "unbind", ".", "call", "(", "el", ",", "'removed'", ",", "teardown", ")", ";", "}", "return", "true", ";", "}" ]
Removing an element can call teardown which unregister the nodeList which calls teardown
[ "Removing", "an", "element", "can", "call", "teardown", "which", "unregister", "the", "nodeList", "which", "calls", "teardown" ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L14373-L14380
25,953
canjs/can-compile
example/dist/production.js
function(expr, options) { var value; // if it's a function, wrap its value in a compute // that will only change values from true to false if (can.isFunction(expr)) { value = can.compute.truthy(expr)(); } else { value = !! Mustache.resolve(expr); } if (value) { return options.fn(options.contexts || this); } else { return options.inverse(options.contexts || this); } }
javascript
function(expr, options) { var value; // if it's a function, wrap its value in a compute // that will only change values from true to false if (can.isFunction(expr)) { value = can.compute.truthy(expr)(); } else { value = !! Mustache.resolve(expr); } if (value) { return options.fn(options.contexts || this); } else { return options.inverse(options.contexts || this); } }
[ "function", "(", "expr", ",", "options", ")", "{", "var", "value", ";", "// if it's a function, wrap its value in a compute", "// that will only change values from true to false", "if", "(", "can", ".", "isFunction", "(", "expr", ")", ")", "{", "value", "=", "can", ".", "compute", ".", "truthy", "(", "expr", ")", "(", ")", ";", "}", "else", "{", "value", "=", "!", "!", "Mustache", ".", "resolve", "(", "expr", ")", ";", "}", "if", "(", "value", ")", "{", "return", "options", ".", "fn", "(", "options", ".", "contexts", "||", "this", ")", ";", "}", "else", "{", "return", "options", ".", "inverse", "(", "options", ".", "contexts", "||", "this", ")", ";", "}", "}" ]
Implements the `if` built-in helper.
[ "Implements", "the", "if", "built", "-", "in", "helper", "." ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L15826-L15841
25,954
canjs/can-compile
example/dist/production.js
function(expr, options) { var fn = options.fn; options.fn = options.inverse; options.inverse = fn; return Mustache._helpers['if'].fn.apply(this, arguments); }
javascript
function(expr, options) { var fn = options.fn; options.fn = options.inverse; options.inverse = fn; return Mustache._helpers['if'].fn.apply(this, arguments); }
[ "function", "(", "expr", ",", "options", ")", "{", "var", "fn", "=", "options", ".", "fn", ";", "options", ".", "fn", "=", "options", ".", "inverse", ";", "options", ".", "inverse", "=", "fn", ";", "return", "Mustache", ".", "_helpers", "[", "'if'", "]", ".", "fn", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}" ]
Implements the `unless` built-in helper.
[ "Implements", "the", "unless", "built", "-", "in", "helper", "." ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L15844-L15849
25,955
canjs/can-compile
example/dist/production.js
function(expr, options) { // Check if this is a list or a compute that resolves to a list, and setup // the incremental live-binding // First, see what we are dealing with. It's ok to read the compute // because can.view.text is only temporarily binding to what is going on here. // Calling can.view.lists prevents anything from listening on that compute. var resolved = Mustache.resolve(expr), result = [], keys, key, i; // When resolved === undefined, the property hasn't been defined yet // Assume it is intended to be a list if (can.view.lists && (resolved instanceof can.List || (expr && expr.isComputed && resolved === undefined))) { return can.view.lists(expr, function(item, index) { return options.fn(options.scope.add({ "@index": index }) .add(item)); }); } expr = resolved; if ( !! expr && isArrayLike(expr)) { for (i = 0; i < expr.length; i++) { result.push(options.fn(options.scope.add({ "@index": i }) .add(expr[i]))); } return result.join(''); } else if (isObserveLike(expr)) { keys = can.Map.keys(expr); // listen to keys changing so we can livebind lists of attributes. for (i = 0; i < keys.length; i++) { key = keys[i]; result.push(options.fn(options.scope.add({ "@key": key }) .add(expr[key]))); } return result.join(''); } else if (expr instanceof Object) { for (key in expr) { result.push(options.fn(options.scope.add({ "@key": key }) .add(expr[key]))); } return result.join(''); } }
javascript
function(expr, options) { // Check if this is a list or a compute that resolves to a list, and setup // the incremental live-binding // First, see what we are dealing with. It's ok to read the compute // because can.view.text is only temporarily binding to what is going on here. // Calling can.view.lists prevents anything from listening on that compute. var resolved = Mustache.resolve(expr), result = [], keys, key, i; // When resolved === undefined, the property hasn't been defined yet // Assume it is intended to be a list if (can.view.lists && (resolved instanceof can.List || (expr && expr.isComputed && resolved === undefined))) { return can.view.lists(expr, function(item, index) { return options.fn(options.scope.add({ "@index": index }) .add(item)); }); } expr = resolved; if ( !! expr && isArrayLike(expr)) { for (i = 0; i < expr.length; i++) { result.push(options.fn(options.scope.add({ "@index": i }) .add(expr[i]))); } return result.join(''); } else if (isObserveLike(expr)) { keys = can.Map.keys(expr); // listen to keys changing so we can livebind lists of attributes. for (i = 0; i < keys.length; i++) { key = keys[i]; result.push(options.fn(options.scope.add({ "@key": key }) .add(expr[key]))); } return result.join(''); } else if (expr instanceof Object) { for (key in expr) { result.push(options.fn(options.scope.add({ "@key": key }) .add(expr[key]))); } return result.join(''); } }
[ "function", "(", "expr", ",", "options", ")", "{", "// Check if this is a list or a compute that resolves to a list, and setup", "// the incremental live-binding ", "// First, see what we are dealing with. It's ok to read the compute", "// because can.view.text is only temporarily binding to what is going on here.", "// Calling can.view.lists prevents anything from listening on that compute.", "var", "resolved", "=", "Mustache", ".", "resolve", "(", "expr", ")", ",", "result", "=", "[", "]", ",", "keys", ",", "key", ",", "i", ";", "// When resolved === undefined, the property hasn't been defined yet", "// Assume it is intended to be a list", "if", "(", "can", ".", "view", ".", "lists", "&&", "(", "resolved", "instanceof", "can", ".", "List", "||", "(", "expr", "&&", "expr", ".", "isComputed", "&&", "resolved", "===", "undefined", ")", ")", ")", "{", "return", "can", ".", "view", ".", "lists", "(", "expr", ",", "function", "(", "item", ",", "index", ")", "{", "return", "options", ".", "fn", "(", "options", ".", "scope", ".", "add", "(", "{", "\"@index\"", ":", "index", "}", ")", ".", "add", "(", "item", ")", ")", ";", "}", ")", ";", "}", "expr", "=", "resolved", ";", "if", "(", "!", "!", "expr", "&&", "isArrayLike", "(", "expr", ")", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "expr", ".", "length", ";", "i", "++", ")", "{", "result", ".", "push", "(", "options", ".", "fn", "(", "options", ".", "scope", ".", "add", "(", "{", "\"@index\"", ":", "i", "}", ")", ".", "add", "(", "expr", "[", "i", "]", ")", ")", ")", ";", "}", "return", "result", ".", "join", "(", "''", ")", ";", "}", "else", "if", "(", "isObserveLike", "(", "expr", ")", ")", "{", "keys", "=", "can", ".", "Map", ".", "keys", "(", "expr", ")", ";", "// listen to keys changing so we can livebind lists of attributes.", "for", "(", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "key", "=", "keys", "[", "i", "]", ";", "result", ".", "push", "(", "options", ".", "fn", "(", "options", ".", "scope", ".", "add", "(", "{", "\"@key\"", ":", "key", "}", ")", ".", "add", "(", "expr", "[", "key", "]", ")", ")", ")", ";", "}", "return", "result", ".", "join", "(", "''", ")", ";", "}", "else", "if", "(", "expr", "instanceof", "Object", ")", "{", "for", "(", "key", "in", "expr", ")", "{", "result", ".", "push", "(", "options", ".", "fn", "(", "options", ".", "scope", ".", "add", "(", "{", "\"@key\"", ":", "key", "}", ")", ".", "add", "(", "expr", "[", "key", "]", ")", ")", ")", ";", "}", "return", "result", ".", "join", "(", "''", ")", ";", "}", "}" ]
Implements the `each` built-in helper.
[ "Implements", "the", "each", "built", "-", "in", "helper", "." ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L15853-L15908
25,956
canjs/can-compile
example/dist/production.js
function(expr, options) { var ctx = expr; expr = Mustache.resolve(expr); if ( !! expr) { return options.fn(ctx); } }
javascript
function(expr, options) { var ctx = expr; expr = Mustache.resolve(expr); if ( !! expr) { return options.fn(ctx); } }
[ "function", "(", "expr", ",", "options", ")", "{", "var", "ctx", "=", "expr", ";", "expr", "=", "Mustache", ".", "resolve", "(", "expr", ")", ";", "if", "(", "!", "!", "expr", ")", "{", "return", "options", ".", "fn", "(", "ctx", ")", ";", "}", "}" ]
Implements the `with` built-in helper.
[ "Implements", "the", "with", "built", "-", "in", "helper", "." ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L15911-L15917
25,957
canjs/can-compile
example/dist/production.js
function(id, src) { return "can.Mustache(function(" + ARG_NAMES + ") { " + new Mustache({ text: src, name: id }) .template.out + " })"; }
javascript
function(id, src) { return "can.Mustache(function(" + ARG_NAMES + ") { " + new Mustache({ text: src, name: id }) .template.out + " })"; }
[ "function", "(", "id", ",", "src", ")", "{", "return", "\"can.Mustache(function(\"", "+", "ARG_NAMES", "+", "\") { \"", "+", "new", "Mustache", "(", "{", "text", ":", "src", ",", "name", ":", "id", "}", ")", ".", "template", ".", "out", "+", "\" })\"", ";", "}" ]
Returns a `function` that renders the view.
[ "Returns", "a", "function", "that", "renders", "the", "view", "." ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L15941-L15947
25,958
canjs/can-compile
example/dist/production.js
function(value) { if (value[0] === "{" && value[value.length - 1] === "}") { return value.substr(1, value.length - 2); } return value; }
javascript
function(value) { if (value[0] === "{" && value[value.length - 1] === "}") { return value.substr(1, value.length - 2); } return value; }
[ "function", "(", "value", ")", "{", "if", "(", "value", "[", "0", "]", "===", "\"{\"", "&&", "value", "[", "value", ".", "length", "-", "1", "]", "===", "\"}\"", ")", "{", "return", "value", ".", "substr", "(", "1", ",", "value", ".", "length", "-", "2", ")", ";", "}", "return", "value", ";", "}" ]
Function for determining of an element is contenteditable
[ "Function", "for", "determining", "of", "an", "element", "is", "contenteditable" ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L15996-L16001
25,959
canjs/can-compile
example/dist/production.js
function(ev) { // The attribute value, representing the name of the method to call (i.e. can-submit="foo" foo is the // name of the method) var attr = removeCurly(el.getAttribute(attributeName)), scopeData = data.scope.read(attr, { returnObserveMethods: true, isArgument: true }); return scopeData.value.call(scopeData.parent, data.scope._context, can.$(this), ev); }
javascript
function(ev) { // The attribute value, representing the name of the method to call (i.e. can-submit="foo" foo is the // name of the method) var attr = removeCurly(el.getAttribute(attributeName)), scopeData = data.scope.read(attr, { returnObserveMethods: true, isArgument: true }); return scopeData.value.call(scopeData.parent, data.scope._context, can.$(this), ev); }
[ "function", "(", "ev", ")", "{", "// The attribute value, representing the name of the method to call (i.e. can-submit=\"foo\" foo is the ", "// name of the method)", "var", "attr", "=", "removeCurly", "(", "el", ".", "getAttribute", "(", "attributeName", ")", ")", ",", "scopeData", "=", "data", ".", "scope", ".", "read", "(", "attr", ",", "{", "returnObserveMethods", ":", "true", ",", "isArgument", ":", "true", "}", ")", ";", "return", "scopeData", ".", "value", ".", "call", "(", "scopeData", ".", "parent", ",", "data", ".", "scope", ".", "_context", ",", "can", ".", "$", "(", "this", ")", ",", "ev", ")", ";", "}" ]
the attribute name is the function to call
[ "the", "attribute", "name", "is", "the", "function", "to", "call" ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L16116-L16125
25,960
canjs/can-compile
example/dist/production.js
function() { // Get an array of the currently selected values var value = this.get(), currentValue = this.options.value(); // If the compute is a string, set its value to the joined version of the values array (i.e. "foo;bar") if (this.isString || typeof currentValue === "string") { this.isString = true; this.options.value(value.join(this.delimiter)); } // If the compute is a can.List, replace its current contents with the new array of values else if (currentValue instanceof can.List) { currentValue.attr(value, true); } // Otherwise set the value to the array of values selected in the input. else { this.options.value(value); } }
javascript
function() { // Get an array of the currently selected values var value = this.get(), currentValue = this.options.value(); // If the compute is a string, set its value to the joined version of the values array (i.e. "foo;bar") if (this.isString || typeof currentValue === "string") { this.isString = true; this.options.value(value.join(this.delimiter)); } // If the compute is a can.List, replace its current contents with the new array of values else if (currentValue instanceof can.List) { currentValue.attr(value, true); } // Otherwise set the value to the array of values selected in the input. else { this.options.value(value); } }
[ "function", "(", ")", "{", "// Get an array of the currently selected values", "var", "value", "=", "this", ".", "get", "(", ")", ",", "currentValue", "=", "this", ".", "options", ".", "value", "(", ")", ";", "// If the compute is a string, set its value to the joined version of the values array (i.e. \"foo;bar\")", "if", "(", "this", ".", "isString", "||", "typeof", "currentValue", "===", "\"string\"", ")", "{", "this", ".", "isString", "=", "true", ";", "this", ".", "options", ".", "value", "(", "value", ".", "join", "(", "this", ".", "delimiter", ")", ")", ";", "}", "// If the compute is a can.List, replace its current contents with the new array of values", "else", "if", "(", "currentValue", "instanceof", "can", ".", "List", ")", "{", "currentValue", ".", "attr", "(", "value", ",", "true", ")", ";", "}", "// Otherwise set the value to the array of values selected in the input.", "else", "{", "this", ".", "options", ".", "value", "(", "value", ")", ";", "}", "}" ]
Called when the user changes this input in any way.
[ "Called", "when", "the", "user", "changes", "this", "input", "in", "any", "way", "." ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L16283-L16302
25,961
canjs/can-compile
example/dist/production.js
function(ev, newVal) { scopePropertyUpdating = name; componentScope.attr(name, newVal); scopePropertyUpdating = null; }
javascript
function(ev, newVal) { scopePropertyUpdating = name; componentScope.attr(name, newVal); scopePropertyUpdating = null; }
[ "function", "(", "ev", ",", "newVal", ")", "{", "scopePropertyUpdating", "=", "name", ";", "componentScope", ".", "attr", "(", "name", ",", "newVal", ")", ";", "scopePropertyUpdating", "=", "null", ";", "}" ]
bind on this, check it's value, if it has dependencies
[ "bind", "on", "this", "check", "it", "s", "value", "if", "it", "has", "dependencies" ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L16447-L16451
25,962
canjs/can-compile
example/dist/production.js
function(name) { var parseName = "parse" + can.capitalize(name); return function(data) { // If there's a `parse...` function, use its output. if (this[parseName]) { data = this[parseName].apply(this, arguments); } // Run our maybe-parsed data through `model` or `models`. return this[name](data); }; }
javascript
function(name) { var parseName = "parse" + can.capitalize(name); return function(data) { // If there's a `parse...` function, use its output. if (this[parseName]) { data = this[parseName].apply(this, arguments); } // Run our maybe-parsed data through `model` or `models`. return this[name](data); }; }
[ "function", "(", "name", ")", "{", "var", "parseName", "=", "\"parse\"", "+", "can", ".", "capitalize", "(", "name", ")", ";", "return", "function", "(", "data", ")", "{", "// If there's a `parse...` function, use its output.", "if", "(", "this", "[", "parseName", "]", ")", "{", "data", "=", "this", "[", "parseName", "]", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "// Run our maybe-parsed data through `model` or `models`.", "return", "this", "[", "name", "]", "(", "data", ")", ";", "}", ";", "}" ]
Returns a function that knows how to prepare data from `findAll` or `findOne` calls. `name` should be either `model` or `models`.
[ "Returns", "a", "function", "that", "knows", "how", "to", "prepare", "data", "from", "findAll", "or", "findOne", "calls", ".", "name", "should", "be", "either", "model", "or", "models", "." ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L17307-L17317
25,963
canjs/can-compile
example/dist/production.js
function() { if (!can.route.currentBinding) { can.route._call("bind"); can.route.bind("change", onRouteDataChange); can.route.currentBinding = can.route.defaultBinding; } }
javascript
function() { if (!can.route.currentBinding) { can.route._call("bind"); can.route.bind("change", onRouteDataChange); can.route.currentBinding = can.route.defaultBinding; } }
[ "function", "(", ")", "{", "if", "(", "!", "can", ".", "route", ".", "currentBinding", ")", "{", "can", ".", "route", ".", "_call", "(", "\"bind\"", ")", ";", "can", ".", "route", ".", "bind", "(", "\"change\"", ",", "onRouteDataChange", ")", ";", "can", ".", "route", ".", "currentBinding", "=", "can", ".", "route", ".", "defaultBinding", ";", "}", "}" ]
we need to be able to easily kick off calling setState teardown whatever is there turn on a particular binding called when the route is ready
[ "we", "need", "to", "be", "able", "to", "easily", "kick", "off", "calling", "setState", "teardown", "whatever", "is", "there", "turn", "on", "a", "particular", "binding", "called", "when", "the", "route", "is", "ready" ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L17833-L17839
25,964
canjs/can-compile
example/dist/production.js
function() { var args = can.makeArray(arguments), prop = args.shift(), binding = can.route.bindings[can.route.currentBinding || can.route.defaultBinding], method = binding[prop]; if (method.apply) { return method.apply(binding, args); } else { return method; } }
javascript
function() { var args = can.makeArray(arguments), prop = args.shift(), binding = can.route.bindings[can.route.currentBinding || can.route.defaultBinding], method = binding[prop]; if (method.apply) { return method.apply(binding, args); } else { return method; } }
[ "function", "(", ")", "{", "var", "args", "=", "can", ".", "makeArray", "(", "arguments", ")", ",", "prop", "=", "args", ".", "shift", "(", ")", ",", "binding", "=", "can", ".", "route", ".", "bindings", "[", "can", ".", "route", ".", "currentBinding", "||", "can", ".", "route", ".", "defaultBinding", "]", ",", "method", "=", "binding", "[", "prop", "]", ";", "if", "(", "method", ".", "apply", ")", "{", "return", "method", ".", "apply", "(", "binding", ",", "args", ")", ";", "}", "else", "{", "return", "method", ";", "}", "}" ]
a helper to get stuff from the current or default bindings
[ "a", "helper", "to", "get", "stuff", "from", "the", "current", "or", "default", "bindings" ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L17850-L17860
25,965
component/toidentifier
index.js
toIdentifier
function toIdentifier (str) { return str .split(' ') .map(function (token) { return token.slice(0, 1).toUpperCase() + token.slice(1) }) .join('') .replace(/[^ _0-9a-z]/gi, '') }
javascript
function toIdentifier (str) { return str .split(' ') .map(function (token) { return token.slice(0, 1).toUpperCase() + token.slice(1) }) .join('') .replace(/[^ _0-9a-z]/gi, '') }
[ "function", "toIdentifier", "(", "str", ")", "{", "return", "str", ".", "split", "(", "' '", ")", ".", "map", "(", "function", "(", "token", ")", "{", "return", "token", ".", "slice", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", ")", "+", "token", ".", "slice", "(", "1", ")", "}", ")", ".", "join", "(", "''", ")", ".", "replace", "(", "/", "[^ _0-9a-z]", "/", "gi", ",", "''", ")", "}" ]
Trasform the given string into a JavaScript identifier @param {string} str @returns {string} @public
[ "Trasform", "the", "given", "string", "into", "a", "JavaScript", "identifier" ]
8c09cba5e530de7d74b087ea66740c0e4a5af02b
https://github.com/component/toidentifier/blob/8c09cba5e530de7d74b087ea66740c0e4a5af02b/index.js#L22-L30
25,966
canjs/can-compile
gulp.js
runCompile
function runCompile(file, options) { if (!file) { throw new PluginError('can-compile', 'Missing file option for can-compile'); } var templatePaths = [], latestFile; options = options || {}; function bufferStream (file, enc, cb) { // ignore empty files if (file.isNull()) { cb(); return; } // can't do streams yet if (file.isStream()) { this.emit('error', new PluginError('can-compile', 'Streaming not supported for can-compile')); cb(); return; } // set latest file if not already set, // or if the current file was modified more recently. if (!latestFile || file.stat && file.stat.mtime > latestFile.stat.mtime) { latestFile = file; } templatePaths.push(file.path); cb(); } function endStream(cb) { var self = this; // no files passed in, no file goes out if (!latestFile || !templatePaths.length) { cb(); return; } compile(templatePaths, options, function (err, result) { if (err) { self.emit('error', new PluginError('can-compile', err)); return cb(err); } var joinedFile; // if file opt was a file path // clone everything from the latest file if (typeof file === 'string') { joinedFile = latestFile.clone({ contents: false }); joinedFile.path = path.join(latestFile.base, file); } else { joinedFile = new File(file); } joinedFile.contents = new Buffer(result); self.push(joinedFile); cb(); }); } return through.obj(bufferStream, endStream); }
javascript
function runCompile(file, options) { if (!file) { throw new PluginError('can-compile', 'Missing file option for can-compile'); } var templatePaths = [], latestFile; options = options || {}; function bufferStream (file, enc, cb) { // ignore empty files if (file.isNull()) { cb(); return; } // can't do streams yet if (file.isStream()) { this.emit('error', new PluginError('can-compile', 'Streaming not supported for can-compile')); cb(); return; } // set latest file if not already set, // or if the current file was modified more recently. if (!latestFile || file.stat && file.stat.mtime > latestFile.stat.mtime) { latestFile = file; } templatePaths.push(file.path); cb(); } function endStream(cb) { var self = this; // no files passed in, no file goes out if (!latestFile || !templatePaths.length) { cb(); return; } compile(templatePaths, options, function (err, result) { if (err) { self.emit('error', new PluginError('can-compile', err)); return cb(err); } var joinedFile; // if file opt was a file path // clone everything from the latest file if (typeof file === 'string') { joinedFile = latestFile.clone({ contents: false }); joinedFile.path = path.join(latestFile.base, file); } else { joinedFile = new File(file); } joinedFile.contents = new Buffer(result); self.push(joinedFile); cb(); }); } return through.obj(bufferStream, endStream); }
[ "function", "runCompile", "(", "file", ",", "options", ")", "{", "if", "(", "!", "file", ")", "{", "throw", "new", "PluginError", "(", "'can-compile'", ",", "'Missing file option for can-compile'", ")", ";", "}", "var", "templatePaths", "=", "[", "]", ",", "latestFile", ";", "options", "=", "options", "||", "{", "}", ";", "function", "bufferStream", "(", "file", ",", "enc", ",", "cb", ")", "{", "// ignore empty files", "if", "(", "file", ".", "isNull", "(", ")", ")", "{", "cb", "(", ")", ";", "return", ";", "}", "// can't do streams yet", "if", "(", "file", ".", "isStream", "(", ")", ")", "{", "this", ".", "emit", "(", "'error'", ",", "new", "PluginError", "(", "'can-compile'", ",", "'Streaming not supported for can-compile'", ")", ")", ";", "cb", "(", ")", ";", "return", ";", "}", "// set latest file if not already set,", "// or if the current file was modified more recently.", "if", "(", "!", "latestFile", "||", "file", ".", "stat", "&&", "file", ".", "stat", ".", "mtime", ">", "latestFile", ".", "stat", ".", "mtime", ")", "{", "latestFile", "=", "file", ";", "}", "templatePaths", ".", "push", "(", "file", ".", "path", ")", ";", "cb", "(", ")", ";", "}", "function", "endStream", "(", "cb", ")", "{", "var", "self", "=", "this", ";", "// no files passed in, no file goes out", "if", "(", "!", "latestFile", "||", "!", "templatePaths", ".", "length", ")", "{", "cb", "(", ")", ";", "return", ";", "}", "compile", "(", "templatePaths", ",", "options", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "self", ".", "emit", "(", "'error'", ",", "new", "PluginError", "(", "'can-compile'", ",", "err", ")", ")", ";", "return", "cb", "(", "err", ")", ";", "}", "var", "joinedFile", ";", "// if file opt was a file path", "// clone everything from the latest file", "if", "(", "typeof", "file", "===", "'string'", ")", "{", "joinedFile", "=", "latestFile", ".", "clone", "(", "{", "contents", ":", "false", "}", ")", ";", "joinedFile", ".", "path", "=", "path", ".", "join", "(", "latestFile", ".", "base", ",", "file", ")", ";", "}", "else", "{", "joinedFile", "=", "new", "File", "(", "file", ")", ";", "}", "joinedFile", ".", "contents", "=", "new", "Buffer", "(", "result", ")", ";", "self", ".", "push", "(", "joinedFile", ")", ";", "cb", "(", ")", ";", "}", ")", ";", "}", "return", "through", ".", "obj", "(", "bufferStream", ",", "endStream", ")", ";", "}" ]
file can be a vinyl file object or a string when a string it will construct a new one
[ "file", "can", "be", "a", "vinyl", "file", "object", "or", "a", "string", "when", "a", "string", "it", "will", "construct", "a", "new", "one" ]
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/gulp.js#L12-L81
25,967
GluuFederation/oxd-node
oxd-node/utility.js
oxdSocketRequest
function oxdSocketRequest(port, host, params, command, callback) { // OXD data let data = { command, params }; // Create socket object const client = new net.Socket(); // Initiate a connection on a given socket. client.connect(port, host, () => { data = JSON.stringify(data); console.log('Connected'); try { if (data.length > 0 && data.length <= 100) { console.log(`Send data : 00${data.length + data}`); client.write(`00${data.length + data}`); } else if (data.length > 100 && data.length < 1000) { console.log(`Send data : 0${data.length + data}`); client.write(`0${data.length + data}`); } } catch (err) { console.log('Send data error:', err); } }); // Emitted when data is received client.on('data', (req) => { data = req.toString(); console.log('Response : ', data); callback(null, JSON.parse(data.substring(4, data.length))); client.end(); // kill client after server's response }); // Emitted when an error occurs. The 'close' event will be called directly following this event. client.on('error', (err) => { console.log('Error: ', err); callback(err, null); client.end(); // kill client after server's response }); // Emitted when the server closes. client.on('close', () => { console.log('Connection closed'); }); }
javascript
function oxdSocketRequest(port, host, params, command, callback) { // OXD data let data = { command, params }; // Create socket object const client = new net.Socket(); // Initiate a connection on a given socket. client.connect(port, host, () => { data = JSON.stringify(data); console.log('Connected'); try { if (data.length > 0 && data.length <= 100) { console.log(`Send data : 00${data.length + data}`); client.write(`00${data.length + data}`); } else if (data.length > 100 && data.length < 1000) { console.log(`Send data : 0${data.length + data}`); client.write(`0${data.length + data}`); } } catch (err) { console.log('Send data error:', err); } }); // Emitted when data is received client.on('data', (req) => { data = req.toString(); console.log('Response : ', data); callback(null, JSON.parse(data.substring(4, data.length))); client.end(); // kill client after server's response }); // Emitted when an error occurs. The 'close' event will be called directly following this event. client.on('error', (err) => { console.log('Error: ', err); callback(err, null); client.end(); // kill client after server's response }); // Emitted when the server closes. client.on('close', () => { console.log('Connection closed'); }); }
[ "function", "oxdSocketRequest", "(", "port", ",", "host", ",", "params", ",", "command", ",", "callback", ")", "{", "// OXD data", "let", "data", "=", "{", "command", ",", "params", "}", ";", "// Create socket object", "const", "client", "=", "new", "net", ".", "Socket", "(", ")", ";", "// Initiate a connection on a given socket.", "client", ".", "connect", "(", "port", ",", "host", ",", "(", ")", "=>", "{", "data", "=", "JSON", ".", "stringify", "(", "data", ")", ";", "console", ".", "log", "(", "'Connected'", ")", ";", "try", "{", "if", "(", "data", ".", "length", ">", "0", "&&", "data", ".", "length", "<=", "100", ")", "{", "console", ".", "log", "(", "`", "${", "data", ".", "length", "+", "data", "}", "`", ")", ";", "client", ".", "write", "(", "`", "${", "data", ".", "length", "+", "data", "}", "`", ")", ";", "}", "else", "if", "(", "data", ".", "length", ">", "100", "&&", "data", ".", "length", "<", "1000", ")", "{", "console", ".", "log", "(", "`", "${", "data", ".", "length", "+", "data", "}", "`", ")", ";", "client", ".", "write", "(", "`", "${", "data", ".", "length", "+", "data", "}", "`", ")", ";", "}", "}", "catch", "(", "err", ")", "{", "console", ".", "log", "(", "'Send data error:'", ",", "err", ")", ";", "}", "}", ")", ";", "// Emitted when data is received", "client", ".", "on", "(", "'data'", ",", "(", "req", ")", "=>", "{", "data", "=", "req", ".", "toString", "(", ")", ";", "console", ".", "log", "(", "'Response : '", ",", "data", ")", ";", "callback", "(", "null", ",", "JSON", ".", "parse", "(", "data", ".", "substring", "(", "4", ",", "data", ".", "length", ")", ")", ")", ";", "client", ".", "end", "(", ")", ";", "// kill client after server's response", "}", ")", ";", "// Emitted when an error occurs. The 'close' event will be called directly following this event.", "client", ".", "on", "(", "'error'", ",", "(", "err", ")", "=>", "{", "console", ".", "log", "(", "'Error: '", ",", "err", ")", ";", "callback", "(", "err", ",", "null", ")", ";", "client", ".", "end", "(", ")", ";", "// kill client after server's response", "}", ")", ";", "// Emitted when the server closes.", "client", ".", "on", "(", "'close'", ",", "(", ")", "=>", "{", "console", ".", "log", "(", "'Connection closed'", ")", ";", "}", ")", ";", "}" ]
Function for oxd-server socket manipulation @param {int} port - OXD port number for oxd-server @param {int} host - URL of the oxd-server @param {object} params - List of parameters to request oxd-server command @param {string} command - OXD Command name @param {function} callback - Callback response function
[ "Function", "for", "oxd", "-", "server", "socket", "manipulation" ]
b8d794fcb65bfc7c33364695b8875ef5fa555a06
https://github.com/GluuFederation/oxd-node/blob/b8d794fcb65bfc7c33364695b8875ef5fa555a06/oxd-node/utility.js#L12-L58
25,968
ujjwalguptaofficial/sqlweb
examples/simple example/scripts/index.js
showTableData
function showTableData() { connection.runSql('select * from Student').then(function (students) { var HtmlString = ""; students.forEach(function (student) { HtmlString += "<tr ItemId=" + student.Id + "><td>" + student.Name + "</td><td>" + student.Gender + "</td><td>" + student.Country + "</td><td>" + student.City + "</td><td>" + "<a href='#' class='edit'>Edit</a></td>" + "<td><a href='#' class='delete''>Delete</a></td>"; }) $('#tblGrid tbody').html(HtmlString); }).catch(function (error) { console.log(error); }); }
javascript
function showTableData() { connection.runSql('select * from Student').then(function (students) { var HtmlString = ""; students.forEach(function (student) { HtmlString += "<tr ItemId=" + student.Id + "><td>" + student.Name + "</td><td>" + student.Gender + "</td><td>" + student.Country + "</td><td>" + student.City + "</td><td>" + "<a href='#' class='edit'>Edit</a></td>" + "<td><a href='#' class='delete''>Delete</a></td>"; }) $('#tblGrid tbody').html(HtmlString); }).catch(function (error) { console.log(error); }); }
[ "function", "showTableData", "(", ")", "{", "connection", ".", "runSql", "(", "'select * from Student'", ")", ".", "then", "(", "function", "(", "students", ")", "{", "var", "HtmlString", "=", "\"\"", ";", "students", ".", "forEach", "(", "function", "(", "student", ")", "{", "HtmlString", "+=", "\"<tr ItemId=\"", "+", "student", ".", "Id", "+", "\"><td>\"", "+", "student", ".", "Name", "+", "\"</td><td>\"", "+", "student", ".", "Gender", "+", "\"</td><td>\"", "+", "student", ".", "Country", "+", "\"</td><td>\"", "+", "student", ".", "City", "+", "\"</td><td>\"", "+", "\"<a href='#' class='edit'>Edit</a></td>\"", "+", "\"<td><a href='#' class='delete''>Delete</a></td>\"", ";", "}", ")", "$", "(", "'#tblGrid tbody'", ")", ".", "html", "(", "HtmlString", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "error", ")", "{", "console", ".", "log", "(", "error", ")", ";", "}", ")", ";", "}" ]
This function refreshes the table
[ "This", "function", "refreshes", "the", "table" ]
51fa7dbb53076ef2b0eff87c4bcedafcc0ec3f29
https://github.com/ujjwalguptaofficial/sqlweb/blob/51fa7dbb53076ef2b0eff87c4bcedafcc0ec3f29/examples/simple example/scripts/index.js#L86-L102
25,969
TooTallNate/node-icy
lib/client.js
Client
function Client (options, cb) { if (typeof options == 'string') options = url.parse(options) var req; if (options.protocol == "https:") req = https.request(options); else req = http.request(options); // add the "Icy-MetaData" header req.setHeader('Icy-MetaData', '1'); if ('function' == typeof cb) { req.once('icyResponse', cb); } req.once('response', icyOnResponse); req.once('socket', icyOnSocket); return req; }
javascript
function Client (options, cb) { if (typeof options == 'string') options = url.parse(options) var req; if (options.protocol == "https:") req = https.request(options); else req = http.request(options); // add the "Icy-MetaData" header req.setHeader('Icy-MetaData', '1'); if ('function' == typeof cb) { req.once('icyResponse', cb); } req.once('response', icyOnResponse); req.once('socket', icyOnSocket); return req; }
[ "function", "Client", "(", "options", ",", "cb", ")", "{", "if", "(", "typeof", "options", "==", "'string'", ")", "options", "=", "url", ".", "parse", "(", "options", ")", "var", "req", ";", "if", "(", "options", ".", "protocol", "==", "\"https:\"", ")", "req", "=", "https", ".", "request", "(", "options", ")", ";", "else", "req", "=", "http", ".", "request", "(", "options", ")", ";", "// add the \"Icy-MetaData\" header", "req", ".", "setHeader", "(", "'Icy-MetaData'", ",", "'1'", ")", ";", "if", "(", "'function'", "==", "typeof", "cb", ")", "{", "req", ".", "once", "(", "'icyResponse'", ",", "cb", ")", ";", "}", "req", ".", "once", "(", "'response'", ",", "icyOnResponse", ")", ";", "req", ".", "once", "(", "'socket'", ",", "icyOnSocket", ")", ";", "return", "req", ";", "}" ]
The `Client` class is a subclass of the `http.ClientRequest` object. It adds a stream preprocessor to make "ICY" responses work. This is only needed because of the strictness of node's HTTP parser. I'll volley for ICY to be supported (or at least configurable) in the http header for the JavaScript HTTP rewrite (v0.12 of node?). The other big difference is that it passes an `icy.Reader` instance instead of a `http.ClientResponse` instance to the "response" event callback, so that the "metadata" events are automatically parsed and the raw audio stream it output without the ICY bytes. Also see the [`request()`](#request) and [`get()`](#get) convenience functions. @param {Object} options connection info and options object @param {Function} cb optional callback function for the "response" event @api public
[ "The", "Client", "class", "is", "a", "subclass", "of", "the", "http", ".", "ClientRequest", "object", "." ]
1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6
https://github.com/TooTallNate/node-icy/blob/1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6/lib/client.js#L39-L60
25,970
TooTallNate/node-icy
lib/client.js
icyOnResponse
function icyOnResponse (res) { debug('request "response" event'); var s = res; var metaint = res.headers['icy-metaint']; if (metaint) { debug('got metaint: %d', metaint); s = new Reader(metaint); res.pipe(s); s.res = res; Object.keys(res).forEach(function (k) { if ('_' === k[0]) return; debug('proxying %j', k); proxy(s, k); }); } if (res.connection._wasIcy) { s.httpVersion = 'ICY'; } this.emit('icyResponse', s); }
javascript
function icyOnResponse (res) { debug('request "response" event'); var s = res; var metaint = res.headers['icy-metaint']; if (metaint) { debug('got metaint: %d', metaint); s = new Reader(metaint); res.pipe(s); s.res = res; Object.keys(res).forEach(function (k) { if ('_' === k[0]) return; debug('proxying %j', k); proxy(s, k); }); } if (res.connection._wasIcy) { s.httpVersion = 'ICY'; } this.emit('icyResponse', s); }
[ "function", "icyOnResponse", "(", "res", ")", "{", "debug", "(", "'request \"response\" event'", ")", ";", "var", "s", "=", "res", ";", "var", "metaint", "=", "res", ".", "headers", "[", "'icy-metaint'", "]", ";", "if", "(", "metaint", ")", "{", "debug", "(", "'got metaint: %d'", ",", "metaint", ")", ";", "s", "=", "new", "Reader", "(", "metaint", ")", ";", "res", ".", "pipe", "(", "s", ")", ";", "s", ".", "res", "=", "res", ";", "Object", ".", "keys", "(", "res", ")", ".", "forEach", "(", "function", "(", "k", ")", "{", "if", "(", "'_'", "===", "k", "[", "0", "]", ")", "return", ";", "debug", "(", "'proxying %j'", ",", "k", ")", ";", "proxy", "(", "s", ",", "k", ")", ";", "}", ")", ";", "}", "if", "(", "res", ".", "connection", ".", "_wasIcy", ")", "{", "s", ".", "httpVersion", "=", "'ICY'", ";", "}", "this", ".", "emit", "(", "'icyResponse'", ",", "s", ")", ";", "}" ]
"response" event listener. @api private
[ "response", "event", "listener", "." ]
1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6
https://github.com/TooTallNate/node-icy/blob/1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6/lib/client.js#L68-L90
25,971
TooTallNate/node-icy
lib/client.js
proxy
function proxy (stream, key) { if (key in stream) { debug('not proxying prop "%s" because it already exists on target stream', key); return; } function get () { return stream.res[key]; } function set (v) { return stream.res[key] = v; } Object.defineProperty(stream, key, { configurable: true, enumerable: true, get: get, set: set }); }
javascript
function proxy (stream, key) { if (key in stream) { debug('not proxying prop "%s" because it already exists on target stream', key); return; } function get () { return stream.res[key]; } function set (v) { return stream.res[key] = v; } Object.defineProperty(stream, key, { configurable: true, enumerable: true, get: get, set: set }); }
[ "function", "proxy", "(", "stream", ",", "key", ")", "{", "if", "(", "key", "in", "stream", ")", "{", "debug", "(", "'not proxying prop \"%s\" because it already exists on target stream'", ",", "key", ")", ";", "return", ";", "}", "function", "get", "(", ")", "{", "return", "stream", ".", "res", "[", "key", "]", ";", "}", "function", "set", "(", "v", ")", "{", "return", "stream", ".", "res", "[", "key", "]", "=", "v", ";", "}", "Object", ".", "defineProperty", "(", "stream", ",", "key", ",", "{", "configurable", ":", "true", ",", "enumerable", ":", "true", ",", "get", ":", "get", ",", "set", ":", "set", "}", ")", ";", "}" ]
Proxies "key" from `stream` to `stream.res`. @api private
[ "Proxies", "key", "from", "stream", "to", "stream", ".", "res", "." ]
1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6
https://github.com/TooTallNate/node-icy/blob/1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6/lib/client.js#L113-L131
25,972
TooTallNate/node-icy
lib/stringify.js
stringify
function stringify (obj) { var s = []; Object.keys(obj).forEach(function (key) { s.push(key); s.push('=\''); s.push(obj[key]); s.push('\';'); }); return s.join(''); }
javascript
function stringify (obj) { var s = []; Object.keys(obj).forEach(function (key) { s.push(key); s.push('=\''); s.push(obj[key]); s.push('\';'); }); return s.join(''); }
[ "function", "stringify", "(", "obj", ")", "{", "var", "s", "=", "[", "]", ";", "Object", ".", "keys", "(", "obj", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "s", ".", "push", "(", "key", ")", ";", "s", ".", "push", "(", "'=\\''", ")", ";", "s", ".", "push", "(", "obj", "[", "key", "]", ")", ";", "s", ".", "push", "(", "'\\';'", ")", ";", "}", ")", ";", "return", "s", ".", "join", "(", "''", ")", ";", "}" ]
Takes an Object and converts it into an ICY metadata string. @param {Object} obj @return {String} @api public
[ "Takes", "an", "Object", "and", "converts", "it", "into", "an", "ICY", "metadata", "string", "." ]
1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6
https://github.com/TooTallNate/node-icy/blob/1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6/lib/stringify.js#L16-L25
25,973
TooTallNate/node-icy
examples/client.js
onMetadata
function onMetadata (metadata) { metadata = icy.parse(metadata); console.error('METADATA EVENT:'); console.error(metadata); }
javascript
function onMetadata (metadata) { metadata = icy.parse(metadata); console.error('METADATA EVENT:'); console.error(metadata); }
[ "function", "onMetadata", "(", "metadata", ")", "{", "metadata", "=", "icy", ".", "parse", "(", "metadata", ")", ";", "console", ".", "error", "(", "'METADATA EVENT:'", ")", ";", "console", ".", "error", "(", "metadata", ")", ";", "}" ]
Invoked for every "metadata" event from the `res` stream.
[ "Invoked", "for", "every", "metadata", "event", "from", "the", "res", "stream", "." ]
1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6
https://github.com/TooTallNate/node-icy/blob/1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6/examples/client.js#L50-L54
25,974
TooTallNate/node-icy
lib/preprocessor.js
preprocessor
function preprocessor (socket) { debug('setting up "data" preprocessor'); function ondata (chunk) { // TODO: don't be lazy, buffer if needed... assert(chunk.length >= 3, 'buffer too small! ' + chunk.length); if (/icy/i.test(chunk.slice(0, 3))) { debug('got ICY response!'); var b = new Buffer(chunk.length + HTTP10.length - 'icy'.length); var i = 0; i += HTTP10.copy(b); i += chunk.copy(b, i, 3); assert.equal(i, b.length); chunk = b; socket._wasIcy = true; } else { socket._wasIcy = false; } return chunk; } var listeners; function icyOnData (buf) { var chunk = ondata(buf); // clean up, and re-emit "data" event socket.removeListener('data', icyOnData); listeners.forEach(function (listener) { socket.on('data', listener); }); listeners = null; socket.emit('data', chunk); } if ('function' == typeof socket.ondata) { // node < v0.11.3, the `ondata` function is set on the socket var origOnData = socket.ondata; socket.ondata = function (buf, start, length) { var chunk = ondata(buf.slice(start, length)); // now clean up and inject the modified `chunk` socket.ondata = origOnData; origOnData = null; socket.ondata(chunk, 0, chunk.length); }; } else if (socket.listeners('data').length > 0) { // node >= v0.11.3, the "data" event is listened for directly // add our own "data" listener, and remove all the old ones listeners = socket.listeners('data'); socket.removeAllListeners('data'); socket.on('data', icyOnData); } else { // never? throw new Error('should not happen...'); } }
javascript
function preprocessor (socket) { debug('setting up "data" preprocessor'); function ondata (chunk) { // TODO: don't be lazy, buffer if needed... assert(chunk.length >= 3, 'buffer too small! ' + chunk.length); if (/icy/i.test(chunk.slice(0, 3))) { debug('got ICY response!'); var b = new Buffer(chunk.length + HTTP10.length - 'icy'.length); var i = 0; i += HTTP10.copy(b); i += chunk.copy(b, i, 3); assert.equal(i, b.length); chunk = b; socket._wasIcy = true; } else { socket._wasIcy = false; } return chunk; } var listeners; function icyOnData (buf) { var chunk = ondata(buf); // clean up, and re-emit "data" event socket.removeListener('data', icyOnData); listeners.forEach(function (listener) { socket.on('data', listener); }); listeners = null; socket.emit('data', chunk); } if ('function' == typeof socket.ondata) { // node < v0.11.3, the `ondata` function is set on the socket var origOnData = socket.ondata; socket.ondata = function (buf, start, length) { var chunk = ondata(buf.slice(start, length)); // now clean up and inject the modified `chunk` socket.ondata = origOnData; origOnData = null; socket.ondata(chunk, 0, chunk.length); }; } else if (socket.listeners('data').length > 0) { // node >= v0.11.3, the "data" event is listened for directly // add our own "data" listener, and remove all the old ones listeners = socket.listeners('data'); socket.removeAllListeners('data'); socket.on('data', icyOnData); } else { // never? throw new Error('should not happen...'); } }
[ "function", "preprocessor", "(", "socket", ")", "{", "debug", "(", "'setting up \"data\" preprocessor'", ")", ";", "function", "ondata", "(", "chunk", ")", "{", "// TODO: don't be lazy, buffer if needed...", "assert", "(", "chunk", ".", "length", ">=", "3", ",", "'buffer too small! '", "+", "chunk", ".", "length", ")", ";", "if", "(", "/", "icy", "/", "i", ".", "test", "(", "chunk", ".", "slice", "(", "0", ",", "3", ")", ")", ")", "{", "debug", "(", "'got ICY response!'", ")", ";", "var", "b", "=", "new", "Buffer", "(", "chunk", ".", "length", "+", "HTTP10", ".", "length", "-", "'icy'", ".", "length", ")", ";", "var", "i", "=", "0", ";", "i", "+=", "HTTP10", ".", "copy", "(", "b", ")", ";", "i", "+=", "chunk", ".", "copy", "(", "b", ",", "i", ",", "3", ")", ";", "assert", ".", "equal", "(", "i", ",", "b", ".", "length", ")", ";", "chunk", "=", "b", ";", "socket", ".", "_wasIcy", "=", "true", ";", "}", "else", "{", "socket", ".", "_wasIcy", "=", "false", ";", "}", "return", "chunk", ";", "}", "var", "listeners", ";", "function", "icyOnData", "(", "buf", ")", "{", "var", "chunk", "=", "ondata", "(", "buf", ")", ";", "// clean up, and re-emit \"data\" event", "socket", ".", "removeListener", "(", "'data'", ",", "icyOnData", ")", ";", "listeners", ".", "forEach", "(", "function", "(", "listener", ")", "{", "socket", ".", "on", "(", "'data'", ",", "listener", ")", ";", "}", ")", ";", "listeners", "=", "null", ";", "socket", ".", "emit", "(", "'data'", ",", "chunk", ")", ";", "}", "if", "(", "'function'", "==", "typeof", "socket", ".", "ondata", ")", "{", "// node < v0.11.3, the `ondata` function is set on the socket", "var", "origOnData", "=", "socket", ".", "ondata", ";", "socket", ".", "ondata", "=", "function", "(", "buf", ",", "start", ",", "length", ")", "{", "var", "chunk", "=", "ondata", "(", "buf", ".", "slice", "(", "start", ",", "length", ")", ")", ";", "// now clean up and inject the modified `chunk`", "socket", ".", "ondata", "=", "origOnData", ";", "origOnData", "=", "null", ";", "socket", ".", "ondata", "(", "chunk", ",", "0", ",", "chunk", ".", "length", ")", ";", "}", ";", "}", "else", "if", "(", "socket", ".", "listeners", "(", "'data'", ")", ".", "length", ">", "0", ")", "{", "// node >= v0.11.3, the \"data\" event is listened for directly", "// add our own \"data\" listener, and remove all the old ones", "listeners", "=", "socket", ".", "listeners", "(", "'data'", ")", ";", "socket", ".", "removeAllListeners", "(", "'data'", ")", ";", "socket", ".", "on", "(", "'data'", ",", "icyOnData", ")", ";", "}", "else", "{", "// never?", "throw", "new", "Error", "(", "'should not happen...'", ")", ";", "}", "}" ]
This all really... really.. sucks...
[ "This", "all", "really", "...", "really", "..", "sucks", "..." ]
1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6
https://github.com/TooTallNate/node-icy/blob/1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6/lib/preprocessor.js#L25-L82
25,975
hypery2k/galenframework-cli
core/postinstall.js
writeLocationFile
function writeLocationFile(location) { log.info('Writing location.js file'); if (process.platform === 'win32') { location = location.replace(/\\/g, '\\\\'); } fs.writeFileSync(path.join(libPath, 'location.js'), 'module.exports.location = \'' + location + '\';'); }
javascript
function writeLocationFile(location) { log.info('Writing location.js file'); if (process.platform === 'win32') { location = location.replace(/\\/g, '\\\\'); } fs.writeFileSync(path.join(libPath, 'location.js'), 'module.exports.location = \'' + location + '\';'); }
[ "function", "writeLocationFile", "(", "location", ")", "{", "log", ".", "info", "(", "'Writing location.js file'", ")", ";", "if", "(", "process", ".", "platform", "===", "'win32'", ")", "{", "location", "=", "location", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "'\\\\\\\\'", ")", ";", "}", "fs", ".", "writeFileSync", "(", "path", ".", "join", "(", "libPath", ",", "'location.js'", ")", ",", "'module.exports.location = \\''", "+", "location", "+", "'\\';'", ")", ";", "}" ]
Save the destination directory back @param {string} location - path of the directory
[ "Save", "the", "destination", "directory", "back" ]
eb18499201779bdef072cbad67bb8ce0360980cb
https://github.com/hypery2k/galenframework-cli/blob/eb18499201779bdef072cbad67bb8ce0360980cb/core/postinstall.js#L157-L164
25,976
hypery2k/galenframework-cli
core/postinstall.js
findSuitableTempDirectory
function findSuitableTempDirectory(npmConf) { const now = Date.now(); const candidateTmpDirs = [ process.env.TMPDIR || process.env.TEMP || npmConf.get('tmp'), path.join(process.cwd(), 'tmp', '/tmp') ]; for (let i = 0; i < candidateTmpDirs.length; i++) { const candidatePath = path.join(candidateTmpDirs[i], 'galenframework'); try { fs.mkdirsSync(candidatePath, '0777'); // Make double sure we have 0777 permissions; some operating systems // default umask does not allow write by default. fs.chmodSync(candidatePath, '0777'); const testFile = path.join(candidatePath, now + '.tmp'); fs.writeFileSync(testFile, 'test'); fs.unlinkSync(testFile); return candidatePath; } catch (e) { log.info(candidatePath, 'is not writable:', e.message); } } log.error('Can not find a writable tmp directory.'); exit(1); }
javascript
function findSuitableTempDirectory(npmConf) { const now = Date.now(); const candidateTmpDirs = [ process.env.TMPDIR || process.env.TEMP || npmConf.get('tmp'), path.join(process.cwd(), 'tmp', '/tmp') ]; for (let i = 0; i < candidateTmpDirs.length; i++) { const candidatePath = path.join(candidateTmpDirs[i], 'galenframework'); try { fs.mkdirsSync(candidatePath, '0777'); // Make double sure we have 0777 permissions; some operating systems // default umask does not allow write by default. fs.chmodSync(candidatePath, '0777'); const testFile = path.join(candidatePath, now + '.tmp'); fs.writeFileSync(testFile, 'test'); fs.unlinkSync(testFile); return candidatePath; } catch (e) { log.info(candidatePath, 'is not writable:', e.message); } } log.error('Can not find a writable tmp directory.'); exit(1); }
[ "function", "findSuitableTempDirectory", "(", "npmConf", ")", "{", "const", "now", "=", "Date", ".", "now", "(", ")", ";", "const", "candidateTmpDirs", "=", "[", "process", ".", "env", ".", "TMPDIR", "||", "process", ".", "env", ".", "TEMP", "||", "npmConf", ".", "get", "(", "'tmp'", ")", ",", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "'tmp'", ",", "'/tmp'", ")", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "candidateTmpDirs", ".", "length", ";", "i", "++", ")", "{", "const", "candidatePath", "=", "path", ".", "join", "(", "candidateTmpDirs", "[", "i", "]", ",", "'galenframework'", ")", ";", "try", "{", "fs", ".", "mkdirsSync", "(", "candidatePath", ",", "'0777'", ")", ";", "// Make double sure we have 0777 permissions; some operating systems", "// default umask does not allow write by default.", "fs", ".", "chmodSync", "(", "candidatePath", ",", "'0777'", ")", ";", "const", "testFile", "=", "path", ".", "join", "(", "candidatePath", ",", "now", "+", "'.tmp'", ")", ";", "fs", ".", "writeFileSync", "(", "testFile", ",", "'test'", ")", ";", "fs", ".", "unlinkSync", "(", "testFile", ")", ";", "return", "candidatePath", ";", "}", "catch", "(", "e", ")", "{", "log", ".", "info", "(", "candidatePath", ",", "'is not writable:'", ",", "e", ".", "message", ")", ";", "}", "}", "log", ".", "error", "(", "'Can not find a writable tmp directory.'", ")", ";", "exit", "(", "1", ")", ";", "}" ]
Function to find an writable temp directory @param {object} npmConf - current NPM configuration @returns {string} representing suitable temp directory @function
[ "Function", "to", "find", "an", "writable", "temp", "directory" ]
eb18499201779bdef072cbad67bb8ce0360980cb
https://github.com/hypery2k/galenframework-cli/blob/eb18499201779bdef072cbad67bb8ce0360980cb/core/postinstall.js#L183-L210
25,977
hypery2k/galenframework-cli
core/postinstall.js
getRequestOptions
function getRequestOptions(conf) { const strictSSL = conf.get('strict-ssl'); let options = { uri: downloadUrl, encoding: null, // Get response as a buffer followRedirect: true, // The default download path redirects to a CDN URL. headers: {}, strictSSL: strictSSL }; let proxyUrl = conf.get('https-proxy') || conf.get('http-proxy') || conf.get('proxy'); if (proxyUrl) { // Print using proxy let proxy = url.parse(proxyUrl); if (proxy.auth) { // Mask password proxy.auth = proxy.auth.replace(/:.*$/, ':******'); } log.info('Using proxy ' + url.format(proxy)); // Enable proxy options.proxy = proxyUrl; // If going through proxy, use the user-agent string from the npm config options.headers['User-Agent'] = conf.get('user-agent'); } // Use certificate authority settings from npm const ca = conf.get('ca'); if (ca) { log.info('Using npmconf ca'); options.ca = ca; } return options; }
javascript
function getRequestOptions(conf) { const strictSSL = conf.get('strict-ssl'); let options = { uri: downloadUrl, encoding: null, // Get response as a buffer followRedirect: true, // The default download path redirects to a CDN URL. headers: {}, strictSSL: strictSSL }; let proxyUrl = conf.get('https-proxy') || conf.get('http-proxy') || conf.get('proxy'); if (proxyUrl) { // Print using proxy let proxy = url.parse(proxyUrl); if (proxy.auth) { // Mask password proxy.auth = proxy.auth.replace(/:.*$/, ':******'); } log.info('Using proxy ' + url.format(proxy)); // Enable proxy options.proxy = proxyUrl; // If going through proxy, use the user-agent string from the npm config options.headers['User-Agent'] = conf.get('user-agent'); } // Use certificate authority settings from npm const ca = conf.get('ca'); if (ca) { log.info('Using npmconf ca'); options.ca = ca; } return options; }
[ "function", "getRequestOptions", "(", "conf", ")", "{", "const", "strictSSL", "=", "conf", ".", "get", "(", "'strict-ssl'", ")", ";", "let", "options", "=", "{", "uri", ":", "downloadUrl", ",", "encoding", ":", "null", ",", "// Get response as a buffer", "followRedirect", ":", "true", ",", "// The default download path redirects to a CDN URL.", "headers", ":", "{", "}", ",", "strictSSL", ":", "strictSSL", "}", ";", "let", "proxyUrl", "=", "conf", ".", "get", "(", "'https-proxy'", ")", "||", "conf", ".", "get", "(", "'http-proxy'", ")", "||", "conf", ".", "get", "(", "'proxy'", ")", ";", "if", "(", "proxyUrl", ")", "{", "// Print using proxy", "let", "proxy", "=", "url", ".", "parse", "(", "proxyUrl", ")", ";", "if", "(", "proxy", ".", "auth", ")", "{", "// Mask password", "proxy", ".", "auth", "=", "proxy", ".", "auth", ".", "replace", "(", "/", ":.*$", "/", ",", "':******'", ")", ";", "}", "log", ".", "info", "(", "'Using proxy '", "+", "url", ".", "format", "(", "proxy", ")", ")", ";", "// Enable proxy", "options", ".", "proxy", "=", "proxyUrl", ";", "// If going through proxy, use the user-agent string from the npm config", "options", ".", "headers", "[", "'User-Agent'", "]", "=", "conf", ".", "get", "(", "'user-agent'", ")", ";", "}", "// Use certificate authority settings from npm", "const", "ca", "=", "conf", ".", "get", "(", "'ca'", ")", ";", "if", "(", "ca", ")", "{", "log", ".", "info", "(", "'Using npmconf ca'", ")", ";", "options", ".", "ca", "=", "ca", ";", "}", "return", "options", ";", "}" ]
Create request opions object @param {object} conf - current NPM config @returns {{uri: string, encoding: null, followRedirect: boolean, headers: {}, strictSSL: *}} @function
[ "Create", "request", "opions", "object" ]
eb18499201779bdef072cbad67bb8ce0360980cb
https://github.com/hypery2k/galenframework-cli/blob/eb18499201779bdef072cbad67bb8ce0360980cb/core/postinstall.js#L218-L255
25,978
hypery2k/galenframework-cli
core/postinstall.js
requestBinary
function requestBinary(requestOptions, filePath) { const deferred = kew.defer(); const writePath = filePath + '-download-' + Date.now(); log.info('Receiving...'); let bar = null; requestProgress(request(requestOptions, (error, response, body) => { log.info(''); if (!error && response.statusCode === 200) { fs.writeFileSync(writePath, body); log.info('Received ' + Math.floor(body.length / 1024) + 'K total.'); fs.renameSync(writePath, filePath); deferred.resolve({ requestOptions: requestOptions, downloadedFile: filePath }); } else if (response) { log.error('Error requesting archive.\n' + 'Status: ' + response.statusCode + '\n' + 'Request options: ' + JSON.stringify(requestOptions, null, 2) + '\n' + 'Response headers: ' + JSON.stringify(response.headers, null, 2) + '\n' + 'Make sure your network and proxy settings are correct.\n\n'); exit(1); } else if (error && error.stack && error.stack.indexOf('SELF_SIGNED_CERT_IN_CHAIN') != -1) { log.error('Error making request.'); exit(1); } else if (error) { log.error('Error making request.\n' + error.stack + '\n\n' + 'Please report this full log at https://github.com/hypery2k/galenframework-cli/issues'); exit(1); } else { log.error('Something unexpected happened, please report this full ' + 'log at https://github.com/hypery2k/galenframework-cli/issues'); exit(1); } })).on('progress', (state) => { if (!bar) { bar = new Progress(' [:bar] :percent :etas', { total: state.total, width: 40 }); } bar.curr = state.received; bar.tick(0); }); return deferred.promise; }
javascript
function requestBinary(requestOptions, filePath) { const deferred = kew.defer(); const writePath = filePath + '-download-' + Date.now(); log.info('Receiving...'); let bar = null; requestProgress(request(requestOptions, (error, response, body) => { log.info(''); if (!error && response.statusCode === 200) { fs.writeFileSync(writePath, body); log.info('Received ' + Math.floor(body.length / 1024) + 'K total.'); fs.renameSync(writePath, filePath); deferred.resolve({ requestOptions: requestOptions, downloadedFile: filePath }); } else if (response) { log.error('Error requesting archive.\n' + 'Status: ' + response.statusCode + '\n' + 'Request options: ' + JSON.stringify(requestOptions, null, 2) + '\n' + 'Response headers: ' + JSON.stringify(response.headers, null, 2) + '\n' + 'Make sure your network and proxy settings are correct.\n\n'); exit(1); } else if (error && error.stack && error.stack.indexOf('SELF_SIGNED_CERT_IN_CHAIN') != -1) { log.error('Error making request.'); exit(1); } else if (error) { log.error('Error making request.\n' + error.stack + '\n\n' + 'Please report this full log at https://github.com/hypery2k/galenframework-cli/issues'); exit(1); } else { log.error('Something unexpected happened, please report this full ' + 'log at https://github.com/hypery2k/galenframework-cli/issues'); exit(1); } })).on('progress', (state) => { if (!bar) { bar = new Progress(' [:bar] :percent :etas', { total: state.total, width: 40 }); } bar.curr = state.received; bar.tick(0); }); return deferred.promise; }
[ "function", "requestBinary", "(", "requestOptions", ",", "filePath", ")", "{", "const", "deferred", "=", "kew", ".", "defer", "(", ")", ";", "const", "writePath", "=", "filePath", "+", "'-download-'", "+", "Date", ".", "now", "(", ")", ";", "log", ".", "info", "(", "'Receiving...'", ")", ";", "let", "bar", "=", "null", ";", "requestProgress", "(", "request", "(", "requestOptions", ",", "(", "error", ",", "response", ",", "body", ")", "=>", "{", "log", ".", "info", "(", "''", ")", ";", "if", "(", "!", "error", "&&", "response", ".", "statusCode", "===", "200", ")", "{", "fs", ".", "writeFileSync", "(", "writePath", ",", "body", ")", ";", "log", ".", "info", "(", "'Received '", "+", "Math", ".", "floor", "(", "body", ".", "length", "/", "1024", ")", "+", "'K total.'", ")", ";", "fs", ".", "renameSync", "(", "writePath", ",", "filePath", ")", ";", "deferred", ".", "resolve", "(", "{", "requestOptions", ":", "requestOptions", ",", "downloadedFile", ":", "filePath", "}", ")", ";", "}", "else", "if", "(", "response", ")", "{", "log", ".", "error", "(", "'Error requesting archive.\\n'", "+", "'Status: '", "+", "response", ".", "statusCode", "+", "'\\n'", "+", "'Request options: '", "+", "JSON", ".", "stringify", "(", "requestOptions", ",", "null", ",", "2", ")", "+", "'\\n'", "+", "'Response headers: '", "+", "JSON", ".", "stringify", "(", "response", ".", "headers", ",", "null", ",", "2", ")", "+", "'\\n'", "+", "'Make sure your network and proxy settings are correct.\\n\\n'", ")", ";", "exit", "(", "1", ")", ";", "}", "else", "if", "(", "error", "&&", "error", ".", "stack", "&&", "error", ".", "stack", ".", "indexOf", "(", "'SELF_SIGNED_CERT_IN_CHAIN'", ")", "!=", "-", "1", ")", "{", "log", ".", "error", "(", "'Error making request.'", ")", ";", "exit", "(", "1", ")", ";", "}", "else", "if", "(", "error", ")", "{", "log", ".", "error", "(", "'Error making request.\\n'", "+", "error", ".", "stack", "+", "'\\n\\n'", "+", "'Please report this full log at https://github.com/hypery2k/galenframework-cli/issues'", ")", ";", "exit", "(", "1", ")", ";", "}", "else", "{", "log", ".", "error", "(", "'Something unexpected happened, please report this full '", "+", "'log at https://github.com/hypery2k/galenframework-cli/issues'", ")", ";", "exit", "(", "1", ")", ";", "}", "}", ")", ")", ".", "on", "(", "'progress'", ",", "(", "state", ")", "=>", "{", "if", "(", "!", "bar", ")", "{", "bar", "=", "new", "Progress", "(", "' [:bar] :percent :etas'", ",", "{", "total", ":", "state", ".", "total", ",", "width", ":", "40", "}", ")", ";", "}", "bar", ".", "curr", "=", "state", ".", "received", ";", "bar", ".", "tick", "(", "0", ")", ";", "}", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Downloads binary file @param {object} requestOptions - to use for HTTP call @param {string} filePath - download URL @returns {*} @function
[ "Downloads", "binary", "file" ]
eb18499201779bdef072cbad67bb8ce0360980cb
https://github.com/hypery2k/galenframework-cli/blob/eb18499201779bdef072cbad67bb8ce0360980cb/core/postinstall.js#L264-L309
25,979
hypery2k/galenframework-cli
core/postinstall.js
extractDownload
function extractDownload(filePath, requestOptions, retry) { const deferred = kew.defer(); // extract to a unique directory in case multiple processes are // installing and extracting at once const extractedPath = filePath + '-extract-' + Date.now(); let options = { cwd: extractedPath }; fs.mkdirsSync(extractedPath, '0777'); // Make double sure we have 0777 permissions; some operating systems // default umask does not allow write by default. fs.chmodSync(extractedPath, '0777'); if (filePath.substr(-4) === '.zip') { log.info('Extracting zip contents'); try { let zip = new AdmZip(filePath); zip.extractAllTo(extractedPath, true); deferred.resolve(extractedPath); } catch (err) { log.error('Error extracting zip'); deferred.reject(err); } } else { log.info('Extracting tar contents (via spawned process)'); cp.execFile('tar', ['jxf', filePath], options, function (err) { if (err) { if (!retry) { log.info('Error during extracting. Trying to download again.'); fs.unlinkSync(filePath); return requestBinary(requestOptions, filePath).then(function (downloadedFile) { return extractDownload(downloadedFile, requestOptions, true); }); } else { deferred.reject(err); log.error('Error extracting archive'); } } else { deferred.resolve(extractedPath); } }); } return deferred.promise; }
javascript
function extractDownload(filePath, requestOptions, retry) { const deferred = kew.defer(); // extract to a unique directory in case multiple processes are // installing and extracting at once const extractedPath = filePath + '-extract-' + Date.now(); let options = { cwd: extractedPath }; fs.mkdirsSync(extractedPath, '0777'); // Make double sure we have 0777 permissions; some operating systems // default umask does not allow write by default. fs.chmodSync(extractedPath, '0777'); if (filePath.substr(-4) === '.zip') { log.info('Extracting zip contents'); try { let zip = new AdmZip(filePath); zip.extractAllTo(extractedPath, true); deferred.resolve(extractedPath); } catch (err) { log.error('Error extracting zip'); deferred.reject(err); } } else { log.info('Extracting tar contents (via spawned process)'); cp.execFile('tar', ['jxf', filePath], options, function (err) { if (err) { if (!retry) { log.info('Error during extracting. Trying to download again.'); fs.unlinkSync(filePath); return requestBinary(requestOptions, filePath).then(function (downloadedFile) { return extractDownload(downloadedFile, requestOptions, true); }); } else { deferred.reject(err); log.error('Error extracting archive'); } } else { deferred.resolve(extractedPath); } }); } return deferred.promise; }
[ "function", "extractDownload", "(", "filePath", ",", "requestOptions", ",", "retry", ")", "{", "const", "deferred", "=", "kew", ".", "defer", "(", ")", ";", "// extract to a unique directory in case multiple processes are", "// installing and extracting at once", "const", "extractedPath", "=", "filePath", "+", "'-extract-'", "+", "Date", ".", "now", "(", ")", ";", "let", "options", "=", "{", "cwd", ":", "extractedPath", "}", ";", "fs", ".", "mkdirsSync", "(", "extractedPath", ",", "'0777'", ")", ";", "// Make double sure we have 0777 permissions; some operating systems", "// default umask does not allow write by default.", "fs", ".", "chmodSync", "(", "extractedPath", ",", "'0777'", ")", ";", "if", "(", "filePath", ".", "substr", "(", "-", "4", ")", "===", "'.zip'", ")", "{", "log", ".", "info", "(", "'Extracting zip contents'", ")", ";", "try", "{", "let", "zip", "=", "new", "AdmZip", "(", "filePath", ")", ";", "zip", ".", "extractAllTo", "(", "extractedPath", ",", "true", ")", ";", "deferred", ".", "resolve", "(", "extractedPath", ")", ";", "}", "catch", "(", "err", ")", "{", "log", ".", "error", "(", "'Error extracting zip'", ")", ";", "deferred", ".", "reject", "(", "err", ")", ";", "}", "}", "else", "{", "log", ".", "info", "(", "'Extracting tar contents (via spawned process)'", ")", ";", "cp", ".", "execFile", "(", "'tar'", ",", "[", "'jxf'", ",", "filePath", "]", ",", "options", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "if", "(", "!", "retry", ")", "{", "log", ".", "info", "(", "'Error during extracting. Trying to download again.'", ")", ";", "fs", ".", "unlinkSync", "(", "filePath", ")", ";", "return", "requestBinary", "(", "requestOptions", ",", "filePath", ")", ".", "then", "(", "function", "(", "downloadedFile", ")", "{", "return", "extractDownload", "(", "downloadedFile", ",", "requestOptions", ",", "true", ")", ";", "}", ")", ";", "}", "else", "{", "deferred", ".", "reject", "(", "err", ")", ";", "log", ".", "error", "(", "'Error extracting archive'", ")", ";", "}", "}", "else", "{", "deferred", ".", "resolve", "(", "extractedPath", ")", ";", "}", "}", ")", ";", "}", "return", "deferred", ".", "promise", ";", "}" ]
Extracts the given Archive @param {string} filePath - path of the ZIP archive to extract @param {object} requestOptions - request options for retry attempt @param {boolean} retry - set to true if it's already an retry attempt @returns {*} - path of the extracted archive content @function
[ "Extracts", "the", "given", "Archive" ]
eb18499201779bdef072cbad67bb8ce0360980cb
https://github.com/hypery2k/galenframework-cli/blob/eb18499201779bdef072cbad67bb8ce0360980cb/core/postinstall.js#L319-L363
25,980
hypery2k/galenframework-cli
core/postinstall.js
copyIntoPlace
function copyIntoPlace(extractedPath, targetPath) { log.info('Removing', targetPath); return kew.nfcall(fs.remove, targetPath).then(function () { // Look for the extracted directory, so we can rename it. const files = fs.readdirSync(extractedPath); for (let i = 0; i < files.length; i++) { const file = path.join(extractedPath, files[i]); if (fs.statSync(file).isDirectory() && file.indexOf(helper.version) !== -1) { log.info('Copying extracted folder', file, '->', targetPath); return kew.nfcall(fs.move, file, targetPath); } } log.info('Could not find extracted file', files); throw new Error('Could not find extracted file'); }); }
javascript
function copyIntoPlace(extractedPath, targetPath) { log.info('Removing', targetPath); return kew.nfcall(fs.remove, targetPath).then(function () { // Look for the extracted directory, so we can rename it. const files = fs.readdirSync(extractedPath); for (let i = 0; i < files.length; i++) { const file = path.join(extractedPath, files[i]); if (fs.statSync(file).isDirectory() && file.indexOf(helper.version) !== -1) { log.info('Copying extracted folder', file, '->', targetPath); return kew.nfcall(fs.move, file, targetPath); } } log.info('Could not find extracted file', files); throw new Error('Could not find extracted file'); }); }
[ "function", "copyIntoPlace", "(", "extractedPath", ",", "targetPath", ")", "{", "log", ".", "info", "(", "'Removing'", ",", "targetPath", ")", ";", "return", "kew", ".", "nfcall", "(", "fs", ".", "remove", ",", "targetPath", ")", ".", "then", "(", "function", "(", ")", "{", "// Look for the extracted directory, so we can rename it.", "const", "files", "=", "fs", ".", "readdirSync", "(", "extractedPath", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "files", ".", "length", ";", "i", "++", ")", "{", "const", "file", "=", "path", ".", "join", "(", "extractedPath", ",", "files", "[", "i", "]", ")", ";", "if", "(", "fs", ".", "statSync", "(", "file", ")", ".", "isDirectory", "(", ")", "&&", "file", ".", "indexOf", "(", "helper", ".", "version", ")", "!==", "-", "1", ")", "{", "log", ".", "info", "(", "'Copying extracted folder'", ",", "file", ",", "'->'", ",", "targetPath", ")", ";", "return", "kew", ".", "nfcall", "(", "fs", ".", "move", ",", "file", ",", "targetPath", ")", ";", "}", "}", "log", ".", "info", "(", "'Could not find extracted file'", ",", "files", ")", ";", "throw", "new", "Error", "(", "'Could not find extracted file'", ")", ";", "}", ")", ";", "}" ]
Helper function to move folder contents to target directory @param {string} extractedPath - source directory path @param {string} targetPath - target directory path @returns {string} {!Promise.<RESULT>} promise for chaing @function
[ "Helper", "function", "to", "move", "folder", "contents", "to", "target", "directory" ]
eb18499201779bdef072cbad67bb8ce0360980cb
https://github.com/hypery2k/galenframework-cli/blob/eb18499201779bdef072cbad67bb8ce0360980cb/core/postinstall.js#L372-L387
25,981
Azure/azure-openapi-validator
gulpfile.js
getPathVariableName
function getPathVariableName() { // windows calls it's path 'Path' usually, but this is not guaranteed. if (process.platform === 'win32') { for (const key of Object.keys(process.env)) if (key.match(/^PATH$/i)) return key; return 'Path'; } return "PATH"; }
javascript
function getPathVariableName() { // windows calls it's path 'Path' usually, but this is not guaranteed. if (process.platform === 'win32') { for (const key of Object.keys(process.env)) if (key.match(/^PATH$/i)) return key; return 'Path'; } return "PATH"; }
[ "function", "getPathVariableName", "(", ")", "{", "// windows calls it's path 'Path' usually, but this is not guaranteed.", "if", "(", "process", ".", "platform", "===", "'win32'", ")", "{", "for", "(", "const", "key", "of", "Object", ".", "keys", "(", "process", ".", "env", ")", ")", "if", "(", "key", ".", "match", "(", "/", "^PATH$", "/", "i", ")", ")", "return", "key", ";", "return", "'Path'", ";", "}", "return", "\"PATH\"", ";", "}" ]
add .bin to PATH
[ "add", ".", "bin", "to", "PATH" ]
10ae24980631f9eae638e58f3953c38c6f8a852f
https://github.com/Azure/azure-openapi-validator/blob/10ae24980631f9eae638e58f3953c38c6f8a852f/gulpfile.js#L14-L23
25,982
clay/amphora-storage-postgres
services/db.js
put
function put(key, value, testCacheEnabled) { const cacheEnabled = testCacheEnabled || CACHE_ENABLED; return postgres.put(key, value) .then((res) => { // persist to cache only if cache is set up/enabled, return postgres result regardless if (cacheEnabled) { return redis.put(key, value).then(() => res); } return res; }); }
javascript
function put(key, value, testCacheEnabled) { const cacheEnabled = testCacheEnabled || CACHE_ENABLED; return postgres.put(key, value) .then((res) => { // persist to cache only if cache is set up/enabled, return postgres result regardless if (cacheEnabled) { return redis.put(key, value).then(() => res); } return res; }); }
[ "function", "put", "(", "key", ",", "value", ",", "testCacheEnabled", ")", "{", "const", "cacheEnabled", "=", "testCacheEnabled", "||", "CACHE_ENABLED", ";", "return", "postgres", ".", "put", "(", "key", ",", "value", ")", ".", "then", "(", "(", "res", ")", "=>", "{", "// persist to cache only if cache is set up/enabled, return postgres result regardless", "if", "(", "cacheEnabled", ")", "{", "return", "redis", ".", "put", "(", "key", ",", "value", ")", ".", "then", "(", "(", ")", "=>", "res", ")", ";", "}", "return", "res", ";", "}", ")", ";", "}" ]
Write a single value to cache and db @param {String} key @param {Object} value @param {Boolean} testCacheEnabled used for tests @return {Promise}
[ "Write", "a", "single", "value", "to", "cache", "and", "db" ]
4279f932eed660737f5e2565d8e6cc3349d2776b
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/services/db.js#L16-L28
25,983
clay/amphora-storage-postgres
services/db.js
get
function get(key) { return redis.get(key) .then(data => { if (isUri(key)) return data; return JSON.parse(data); // Parse non-uri data to match Postgres }) .catch(() => postgres.get(key)); }
javascript
function get(key) { return redis.get(key) .then(data => { if (isUri(key)) return data; return JSON.parse(data); // Parse non-uri data to match Postgres }) .catch(() => postgres.get(key)); }
[ "function", "get", "(", "key", ")", "{", "return", "redis", ".", "get", "(", "key", ")", ".", "then", "(", "data", "=>", "{", "if", "(", "isUri", "(", "key", ")", ")", "return", "data", ";", "return", "JSON", ".", "parse", "(", "data", ")", ";", "// Parse non-uri data to match Postgres", "}", ")", ".", "catch", "(", "(", ")", "=>", "postgres", ".", "get", "(", "key", ")", ")", ";", "}" ]
Return a value from the db or cache. Must return a Object, not stringified JSON @param {String} key @return {Promise}
[ "Return", "a", "value", "from", "the", "db", "or", "cache", ".", "Must", "return", "a", "Object", "not", "stringified", "JSON" ]
4279f932eed660737f5e2565d8e6cc3349d2776b
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/services/db.js#L37-L44
25,984
clay/amphora-storage-postgres
services/db.js
batch
function batch(ops, testCacheEnabled) { const cacheEnabled = testCacheEnabled || CACHE_ENABLED; return postgres.batch(ops) .then((res) => { if (cacheEnabled) { return redis.batch(ops).then(() => res); } return res; }); }
javascript
function batch(ops, testCacheEnabled) { const cacheEnabled = testCacheEnabled || CACHE_ENABLED; return postgres.batch(ops) .then((res) => { if (cacheEnabled) { return redis.batch(ops).then(() => res); } return res; }); }
[ "function", "batch", "(", "ops", ",", "testCacheEnabled", ")", "{", "const", "cacheEnabled", "=", "testCacheEnabled", "||", "CACHE_ENABLED", ";", "return", "postgres", ".", "batch", "(", "ops", ")", ".", "then", "(", "(", "res", ")", "=>", "{", "if", "(", "cacheEnabled", ")", "{", "return", "redis", ".", "batch", "(", "ops", ")", ".", "then", "(", "(", ")", "=>", "res", ")", ";", "}", "return", "res", ";", "}", ")", ";", "}" ]
Process a whole group of saves @param {Array} ops @param {Boolean} testCacheEnabled used for tests @return {Promise}
[ "Process", "a", "whole", "group", "of", "saves" ]
4279f932eed660737f5e2565d8e6cc3349d2776b
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/services/db.js#L53-L64
25,985
clay/amphora-storage-postgres
postgres/client.js
createDBIfNotExists
function createDBIfNotExists() { const tmpClient = knexLib({ client: 'pg', connection: { host: POSTGRES_HOST, user: POSTGRES_USER, password: POSTGRES_PASSWORD, database: 'postgres', port: POSTGRES_PORT }, pool: { min: CONNECTION_POOL_MIN, max: CONNECTION_POOL_MAX } }); // https://github.com/clay/amphora-storage-postgres/pull/7/files/16d3429767943a593ad9667b0d471fefc15088d3#diff-6a1e11a6146d3a5a01f955a44a2ac07a return tmpClient.raw('CREATE DATABASE ??', [POSTGRES_DB]) .then(() => tmpClient.destroy()) .then(connect); }
javascript
function createDBIfNotExists() { const tmpClient = knexLib({ client: 'pg', connection: { host: POSTGRES_HOST, user: POSTGRES_USER, password: POSTGRES_PASSWORD, database: 'postgres', port: POSTGRES_PORT }, pool: { min: CONNECTION_POOL_MIN, max: CONNECTION_POOL_MAX } }); // https://github.com/clay/amphora-storage-postgres/pull/7/files/16d3429767943a593ad9667b0d471fefc15088d3#diff-6a1e11a6146d3a5a01f955a44a2ac07a return tmpClient.raw('CREATE DATABASE ??', [POSTGRES_DB]) .then(() => tmpClient.destroy()) .then(connect); }
[ "function", "createDBIfNotExists", "(", ")", "{", "const", "tmpClient", "=", "knexLib", "(", "{", "client", ":", "'pg'", ",", "connection", ":", "{", "host", ":", "POSTGRES_HOST", ",", "user", ":", "POSTGRES_USER", ",", "password", ":", "POSTGRES_PASSWORD", ",", "database", ":", "'postgres'", ",", "port", ":", "POSTGRES_PORT", "}", ",", "pool", ":", "{", "min", ":", "CONNECTION_POOL_MIN", ",", "max", ":", "CONNECTION_POOL_MAX", "}", "}", ")", ";", "// https://github.com/clay/amphora-storage-postgres/pull/7/files/16d3429767943a593ad9667b0d471fefc15088d3#diff-6a1e11a6146d3a5a01f955a44a2ac07a", "return", "tmpClient", ".", "raw", "(", "'CREATE DATABASE ??'", ",", "[", "POSTGRES_DB", "]", ")", ".", "then", "(", "(", ")", "=>", "tmpClient", ".", "destroy", "(", ")", ")", ".", "then", "(", "connect", ")", ";", "}" ]
Connect to the default DB and create the Clay DB. Once the DB has been made the connection can be killed and we can try to re-connect to the Clay DB @returns {Promise}
[ "Connect", "to", "the", "default", "DB", "and", "create", "the", "Clay", "DB", ".", "Once", "the", "DB", "has", "been", "made", "the", "connection", "can", "be", "killed", "and", "we", "can", "try", "to", "re", "-", "connect", "to", "the", "Clay", "DB" ]
4279f932eed660737f5e2565d8e6cc3349d2776b
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/postgres/client.js#L21-L38
25,986
clay/amphora-storage-postgres
postgres/client.js
connect
function connect() { log('debug', `Connecting to Postgres at ${POSTGRES_HOST}:${POSTGRES_PORT}`); knex = knexLib({ client: 'pg', connection: { host: POSTGRES_HOST, user: POSTGRES_USER, password: POSTGRES_PASSWORD, database: POSTGRES_DB, port: POSTGRES_PORT }, pool: { min: CONNECTION_POOL_MIN, max: CONNECTION_POOL_MAX } }); // TODO: improve error catch! https://github.com/clay/amphora-storage-postgres/pull/7/files/16d3429767943a593ad9667b0d471fefc15088d3#diff-6a1e11a6146d3a5a01f955a44a2ac07a return knex.table('information_schema.tables').first() .catch(createDBIfNotExists); }
javascript
function connect() { log('debug', `Connecting to Postgres at ${POSTGRES_HOST}:${POSTGRES_PORT}`); knex = knexLib({ client: 'pg', connection: { host: POSTGRES_HOST, user: POSTGRES_USER, password: POSTGRES_PASSWORD, database: POSTGRES_DB, port: POSTGRES_PORT }, pool: { min: CONNECTION_POOL_MIN, max: CONNECTION_POOL_MAX } }); // TODO: improve error catch! https://github.com/clay/amphora-storage-postgres/pull/7/files/16d3429767943a593ad9667b0d471fefc15088d3#diff-6a1e11a6146d3a5a01f955a44a2ac07a return knex.table('information_schema.tables').first() .catch(createDBIfNotExists); }
[ "function", "connect", "(", ")", "{", "log", "(", "'debug'", ",", "`", "${", "POSTGRES_HOST", "}", "${", "POSTGRES_PORT", "}", "`", ")", ";", "knex", "=", "knexLib", "(", "{", "client", ":", "'pg'", ",", "connection", ":", "{", "host", ":", "POSTGRES_HOST", ",", "user", ":", "POSTGRES_USER", ",", "password", ":", "POSTGRES_PASSWORD", ",", "database", ":", "POSTGRES_DB", ",", "port", ":", "POSTGRES_PORT", "}", ",", "pool", ":", "{", "min", ":", "CONNECTION_POOL_MIN", ",", "max", ":", "CONNECTION_POOL_MAX", "}", "}", ")", ";", "// TODO: improve error catch! https://github.com/clay/amphora-storage-postgres/pull/7/files/16d3429767943a593ad9667b0d471fefc15088d3#diff-6a1e11a6146d3a5a01f955a44a2ac07a", "return", "knex", ".", "table", "(", "'information_schema.tables'", ")", ".", "first", "(", ")", ".", "catch", "(", "createDBIfNotExists", ")", ";", "}" ]
Connect to the DB. We need to do a quick check to see if we're actually connected to the Clay DB. If we aren't, connect to default and then use that connection to create the Clay DB. @returns {Promise}
[ "Connect", "to", "the", "DB", ".", "We", "need", "to", "do", "a", "quick", "check", "to", "see", "if", "we", "re", "actually", "connected", "to", "the", "Clay", "DB", ".", "If", "we", "aren", "t", "connect", "to", "default", "and", "then", "use", "that", "connection", "to", "create", "the", "Clay", "DB", "." ]
4279f932eed660737f5e2565d8e6cc3349d2776b
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/postgres/client.js#L48-L66
25,987
clay/amphora-storage-postgres
postgres/client.js
get
function get(key) { const dataProp = 'data'; return baseQuery(key) .select(dataProp) .where('id', key) .then(pullValFromRows(key, dataProp)); }
javascript
function get(key) { const dataProp = 'data'; return baseQuery(key) .select(dataProp) .where('id', key) .then(pullValFromRows(key, dataProp)); }
[ "function", "get", "(", "key", ")", "{", "const", "dataProp", "=", "'data'", ";", "return", "baseQuery", "(", "key", ")", ".", "select", "(", "dataProp", ")", ".", "where", "(", "'id'", ",", "key", ")", ".", "then", "(", "pullValFromRows", "(", "key", ",", "dataProp", ")", ")", ";", "}" ]
Retrieve a single entry from the DB @param {String} key @return {Promise}
[ "Retrieve", "a", "single", "entry", "from", "the", "DB" ]
4279f932eed660737f5e2565d8e6cc3349d2776b
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/postgres/client.js#L99-L106
25,988
clay/amphora-storage-postgres
postgres/client.js
put
function put(key, value) { const { schema, table } = findSchemaAndTable(key), map = columnToValueMap('id', key); // create the value map // add data to the map columnToValueMap('data', wrapInObject(key, parseOrNot(value)), map); let url; if (isUri(key)) { url = decode(key.split('/_uris/').pop()); // add url column to map if we're PUTting a uri columnToValueMap('url', url, map); } return onConflictPut(map, schema, table) .then(() => map.data); }
javascript
function put(key, value) { const { schema, table } = findSchemaAndTable(key), map = columnToValueMap('id', key); // create the value map // add data to the map columnToValueMap('data', wrapInObject(key, parseOrNot(value)), map); let url; if (isUri(key)) { url = decode(key.split('/_uris/').pop()); // add url column to map if we're PUTting a uri columnToValueMap('url', url, map); } return onConflictPut(map, schema, table) .then(() => map.data); }
[ "function", "put", "(", "key", ",", "value", ")", "{", "const", "{", "schema", ",", "table", "}", "=", "findSchemaAndTable", "(", "key", ")", ",", "map", "=", "columnToValueMap", "(", "'id'", ",", "key", ")", ";", "// create the value map", "// add data to the map", "columnToValueMap", "(", "'data'", ",", "wrapInObject", "(", "key", ",", "parseOrNot", "(", "value", ")", ")", ",", "map", ")", ";", "let", "url", ";", "if", "(", "isUri", "(", "key", ")", ")", "{", "url", "=", "decode", "(", "key", ".", "split", "(", "'/_uris/'", ")", ".", "pop", "(", ")", ")", ";", "// add url column to map if we're PUTting a uri", "columnToValueMap", "(", "'url'", ",", "url", ",", "map", ")", ";", "}", "return", "onConflictPut", "(", "map", ",", "schema", ",", "table", ")", ".", "then", "(", "(", ")", "=>", "map", ".", "data", ")", ";", "}" ]
Insert a row into the DB @param {String} key @param {Object} value @return {Promise}
[ "Insert", "a", "row", "into", "the", "DB" ]
4279f932eed660737f5e2565d8e6cc3349d2776b
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/postgres/client.js#L131-L150
25,989
clay/amphora-storage-postgres
postgres/client.js
patch
function patch(prop) { return (key, value) => { const { schema, table } = findSchemaAndTable(key); return raw('UPDATE ?? SET ?? = ?? || ? WHERE id = ?', [`${schema ? `${schema}.` : ''}${table}`, prop, prop, JSON.stringify(value), key]); }; }
javascript
function patch(prop) { return (key, value) => { const { schema, table } = findSchemaAndTable(key); return raw('UPDATE ?? SET ?? = ?? || ? WHERE id = ?', [`${schema ? `${schema}.` : ''}${table}`, prop, prop, JSON.stringify(value), key]); }; }
[ "function", "patch", "(", "prop", ")", "{", "return", "(", "key", ",", "value", ")", "=>", "{", "const", "{", "schema", ",", "table", "}", "=", "findSchemaAndTable", "(", "key", ")", ";", "return", "raw", "(", "'UPDATE ?? SET ?? = ?? || ? WHERE id = ?'", ",", "[", "`", "${", "schema", "?", "`", "${", "schema", "}", "`", ":", "''", "}", "${", "table", "}", "`", ",", "prop", ",", "prop", ",", "JSON", ".", "stringify", "(", "value", ")", ",", "key", "]", ")", ";", "}", ";", "}" ]
Returns a function that handles data patching based on the curried prop. @param {String} prop @return {Function}
[ "Returns", "a", "function", "that", "handles", "data", "patching", "based", "on", "the", "curried", "prop", "." ]
4279f932eed660737f5e2565d8e6cc3349d2776b
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/postgres/client.js#L157-L163
25,990
clay/amphora-storage-postgres
postgres/client.js
createReadStream
function createReadStream(options) { const { prefix, values, keys } = options, transform = TransformStream(options), selects = []; if (keys) selects.push('id'); if (values) selects.push('data'); baseQuery(prefix) .select(...selects) .where('id', 'like', `${prefix}%`) .pipe(transform); return transform; }
javascript
function createReadStream(options) { const { prefix, values, keys } = options, transform = TransformStream(options), selects = []; if (keys) selects.push('id'); if (values) selects.push('data'); baseQuery(prefix) .select(...selects) .where('id', 'like', `${prefix}%`) .pipe(transform); return transform; }
[ "function", "createReadStream", "(", "options", ")", "{", "const", "{", "prefix", ",", "values", ",", "keys", "}", "=", "options", ",", "transform", "=", "TransformStream", "(", "options", ")", ",", "selects", "=", "[", "]", ";", "if", "(", "keys", ")", "selects", ".", "push", "(", "'id'", ")", ";", "if", "(", "values", ")", "selects", ".", "push", "(", "'data'", ")", ";", "baseQuery", "(", "prefix", ")", ".", "select", "(", "...", "selects", ")", ".", "where", "(", "'id'", ",", "'like'", ",", "`", "${", "prefix", "}", "`", ")", ".", "pipe", "(", "transform", ")", ";", "return", "transform", ";", "}" ]
Return a readable stream of query results from the db @param {Object} options @return {Stream}
[ "Return", "a", "readable", "stream", "of", "query", "results", "from", "the", "db" ]
4279f932eed660737f5e2565d8e6cc3349d2776b
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/postgres/client.js#L240-L254
25,991
clay/amphora-storage-postgres
postgres/client.js
raw
function raw(cmd, args = []) { if (!Array.isArray(args)) throw new Error('`args` must be an array!'); return knex.raw(cmd, args); }
javascript
function raw(cmd, args = []) { if (!Array.isArray(args)) throw new Error('`args` must be an array!'); return knex.raw(cmd, args); }
[ "function", "raw", "(", "cmd", ",", "args", "=", "[", "]", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "args", ")", ")", "throw", "new", "Error", "(", "'`args` must be an array!'", ")", ";", "return", "knex", ".", "raw", "(", "cmd", ",", "args", ")", ";", "}" ]
Executes a raw query against the database @param {String} cmd @param {Array<Any>} args @return {Promise<Object>}
[ "Executes", "a", "raw", "query", "against", "the", "database" ]
4279f932eed660737f5e2565d8e6cc3349d2776b
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/postgres/client.js#L327-L331
25,992
clay/amphora-storage-postgres
postgres/index.js
createTables
function createTables() { return bluebird.all(getComponents().map(component => client.createTable(`components.${component}`))) .then(() => bluebird.all(getLayouts().map(layout => client.createTableWithMeta(`layouts.${layout}`)))) .then(() => client.createTableWithMeta('pages')) .then(() => client.raw('CREATE TABLE IF NOT EXISTS ?? ( id TEXT PRIMARY KEY NOT NULL, data TEXT NOT NULL, url TEXT );', ['uris'])) .then(() => createRemainingTables()); }
javascript
function createTables() { return bluebird.all(getComponents().map(component => client.createTable(`components.${component}`))) .then(() => bluebird.all(getLayouts().map(layout => client.createTableWithMeta(`layouts.${layout}`)))) .then(() => client.createTableWithMeta('pages')) .then(() => client.raw('CREATE TABLE IF NOT EXISTS ?? ( id TEXT PRIMARY KEY NOT NULL, data TEXT NOT NULL, url TEXT );', ['uris'])) .then(() => createRemainingTables()); }
[ "function", "createTables", "(", ")", "{", "return", "bluebird", ".", "all", "(", "getComponents", "(", ")", ".", "map", "(", "component", "=>", "client", ".", "createTable", "(", "`", "${", "component", "}", "`", ")", ")", ")", ".", "then", "(", "(", ")", "=>", "bluebird", ".", "all", "(", "getLayouts", "(", ")", ".", "map", "(", "layout", "=>", "client", ".", "createTableWithMeta", "(", "`", "${", "layout", "}", "`", ")", ")", ")", ")", ".", "then", "(", "(", ")", "=>", "client", ".", "createTableWithMeta", "(", "'pages'", ")", ")", ".", "then", "(", "(", ")", "=>", "client", ".", "raw", "(", "'CREATE TABLE IF NOT EXISTS ?? ( id TEXT PRIMARY KEY NOT NULL, data TEXT NOT NULL, url TEXT );'", ",", "[", "'uris'", "]", ")", ")", ".", "then", "(", "(", ")", "=>", "createRemainingTables", "(", ")", ")", ";", "}" ]
Create all tables needed @return {Promise}
[ "Create", "all", "tables", "needed" ]
4279f932eed660737f5e2565d8e6cc3349d2776b
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/postgres/index.js#L30-L36
25,993
clay/amphora-storage-postgres
redis/index.js
createClient
function createClient(testRedisUrl) { const redisUrl = testRedisUrl || REDIS_URL; if (!redisUrl) { return bluebird.reject(new Error('No Redis URL set')); } log('debug', `Connecting to Redis at ${redisUrl}`); return new bluebird(resolve => { module.exports.client = bluebird.promisifyAll(new Redis(redisUrl)); module.exports.client.on('error', logGenericError(__filename)); resolve({ server: redisUrl }); }); }
javascript
function createClient(testRedisUrl) { const redisUrl = testRedisUrl || REDIS_URL; if (!redisUrl) { return bluebird.reject(new Error('No Redis URL set')); } log('debug', `Connecting to Redis at ${redisUrl}`); return new bluebird(resolve => { module.exports.client = bluebird.promisifyAll(new Redis(redisUrl)); module.exports.client.on('error', logGenericError(__filename)); resolve({ server: redisUrl }); }); }
[ "function", "createClient", "(", "testRedisUrl", ")", "{", "const", "redisUrl", "=", "testRedisUrl", "||", "REDIS_URL", ";", "if", "(", "!", "redisUrl", ")", "{", "return", "bluebird", ".", "reject", "(", "new", "Error", "(", "'No Redis URL set'", ")", ")", ";", "}", "log", "(", "'debug'", ",", "`", "${", "redisUrl", "}", "`", ")", ";", "return", "new", "bluebird", "(", "resolve", "=>", "{", "module", ".", "exports", ".", "client", "=", "bluebird", ".", "promisifyAll", "(", "new", "Redis", "(", "redisUrl", ")", ")", ";", "module", ".", "exports", ".", "client", ".", "on", "(", "'error'", ",", "logGenericError", "(", "__filename", ")", ")", ";", "resolve", "(", "{", "server", ":", "redisUrl", "}", ")", ";", "}", ")", ";", "}" ]
Connect to Redis and store the client @param {String} testRedisUrl, used for testing only @return {Promise}
[ "Connect", "to", "Redis", "and", "store", "the", "client" ]
4279f932eed660737f5e2565d8e6cc3349d2776b
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/redis/index.js#L16-L31
25,994
clay/amphora-storage-postgres
redis/index.js
put
function put(key, value) { if (!shouldProcess(key)) return bluebird.resolve(); return module.exports.client.hsetAsync(REDIS_HASH, key, value); }
javascript
function put(key, value) { if (!shouldProcess(key)) return bluebird.resolve(); return module.exports.client.hsetAsync(REDIS_HASH, key, value); }
[ "function", "put", "(", "key", ",", "value", ")", "{", "if", "(", "!", "shouldProcess", "(", "key", ")", ")", "return", "bluebird", ".", "resolve", "(", ")", ";", "return", "module", ".", "exports", ".", "client", ".", "hsetAsync", "(", "REDIS_HASH", ",", "key", ",", "value", ")", ";", "}" ]
Write a single value to a hash @param {String} key @param {String} value @return {Promise}
[ "Write", "a", "single", "value", "to", "a", "hash" ]
4279f932eed660737f5e2565d8e6cc3349d2776b
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/redis/index.js#L50-L54
25,995
clay/amphora-storage-postgres
redis/index.js
get
function get(key) { if (!module.exports.client) { return bluebird.reject(notFoundError(key)); } return module.exports.client.hgetAsync(REDIS_HASH, key) .then(data => data || bluebird.reject(notFoundError(key))); }
javascript
function get(key) { if (!module.exports.client) { return bluebird.reject(notFoundError(key)); } return module.exports.client.hgetAsync(REDIS_HASH, key) .then(data => data || bluebird.reject(notFoundError(key))); }
[ "function", "get", "(", "key", ")", "{", "if", "(", "!", "module", ".", "exports", ".", "client", ")", "{", "return", "bluebird", ".", "reject", "(", "notFoundError", "(", "key", ")", ")", ";", "}", "return", "module", ".", "exports", ".", "client", ".", "hgetAsync", "(", "REDIS_HASH", ",", "key", ")", ".", "then", "(", "data", "=>", "data", "||", "bluebird", ".", "reject", "(", "notFoundError", "(", "key", ")", ")", ")", ";", "}" ]
Read a single value from a hash @param {String} key @return {Promise}
[ "Read", "a", "single", "value", "from", "a", "hash" ]
4279f932eed660737f5e2565d8e6cc3349d2776b
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/redis/index.js#L62-L69
25,996
ngryman/gulp-bro
index.js
createBundler
function createBundler(opts, file, transform) { // omit file contents to make browserify-incremental work propery // on main entry (#4) opts.entries = file.path opts.basedir = path.dirname(file.path) let bundler = bundlers[file.path] if (bundler) { bundler.removeAllListeners('log') bundler.removeAllListeners('time') } else { bundler = browserify(Object.assign(opts, incremental.args)) // only available via method call (#25) if (opts.external) { bundler.external(opts.external) } incremental(bundler) bundlers[file.path] = bundler } bundler.on('log', message => transform.emit('log', message)) bundler.on('time', time => transform.emit('time', time)) return bundler }
javascript
function createBundler(opts, file, transform) { // omit file contents to make browserify-incremental work propery // on main entry (#4) opts.entries = file.path opts.basedir = path.dirname(file.path) let bundler = bundlers[file.path] if (bundler) { bundler.removeAllListeners('log') bundler.removeAllListeners('time') } else { bundler = browserify(Object.assign(opts, incremental.args)) // only available via method call (#25) if (opts.external) { bundler.external(opts.external) } incremental(bundler) bundlers[file.path] = bundler } bundler.on('log', message => transform.emit('log', message)) bundler.on('time', time => transform.emit('time', time)) return bundler }
[ "function", "createBundler", "(", "opts", ",", "file", ",", "transform", ")", "{", "// omit file contents to make browserify-incremental work propery", "// on main entry (#4)", "opts", ".", "entries", "=", "file", ".", "path", "opts", ".", "basedir", "=", "path", ".", "dirname", "(", "file", ".", "path", ")", "let", "bundler", "=", "bundlers", "[", "file", ".", "path", "]", "if", "(", "bundler", ")", "{", "bundler", ".", "removeAllListeners", "(", "'log'", ")", "bundler", ".", "removeAllListeners", "(", "'time'", ")", "}", "else", "{", "bundler", "=", "browserify", "(", "Object", ".", "assign", "(", "opts", ",", "incremental", ".", "args", ")", ")", "// only available via method call (#25)", "if", "(", "opts", ".", "external", ")", "{", "bundler", ".", "external", "(", "opts", ".", "external", ")", "}", "incremental", "(", "bundler", ")", "bundlers", "[", "file", ".", "path", "]", "=", "bundler", "}", "bundler", ".", "on", "(", "'log'", ",", "message", "=>", "transform", ".", "emit", "(", "'log'", ",", "message", ")", ")", "bundler", ".", "on", "(", "'time'", ",", "time", "=>", "transform", ".", "emit", "(", "'time'", ",", "time", ")", ")", "return", "bundler", "}" ]
Return a new browserify bundler. @param {object} opts @param {vinyl} file @param {stream.Transform} transform @return {Browserify}
[ "Return", "a", "new", "browserify", "bundler", "." ]
4b9deb5f90242ba352317d879268bfaedc5133de
https://github.com/ngryman/gulp-bro/blob/4b9deb5f90242ba352317d879268bfaedc5133de/index.js#L56-L82
25,997
ngryman/gulp-bro
index.js
createErrorHandler
function createErrorHandler(opts, transform) { return err => { if ('emit' === opts.error) { transform.emit('error', err) } else if ('function' === typeof opts.error) { opts.error(err) } else { const message = colors.red(err.name) + '\n' + err.toString() .replace(/(ParseError.*)/, colors.red('$1')) log(message) } transform.emit('end') if (opts.callback) { opts.callback(through2()) } } }
javascript
function createErrorHandler(opts, transform) { return err => { if ('emit' === opts.error) { transform.emit('error', err) } else if ('function' === typeof opts.error) { opts.error(err) } else { const message = colors.red(err.name) + '\n' + err.toString() .replace(/(ParseError.*)/, colors.red('$1')) log(message) } transform.emit('end') if (opts.callback) { opts.callback(through2()) } } }
[ "function", "createErrorHandler", "(", "opts", ",", "transform", ")", "{", "return", "err", "=>", "{", "if", "(", "'emit'", "===", "opts", ".", "error", ")", "{", "transform", ".", "emit", "(", "'error'", ",", "err", ")", "}", "else", "if", "(", "'function'", "===", "typeof", "opts", ".", "error", ")", "{", "opts", ".", "error", "(", "err", ")", "}", "else", "{", "const", "message", "=", "colors", ".", "red", "(", "err", ".", "name", ")", "+", "'\\n'", "+", "err", ".", "toString", "(", ")", ".", "replace", "(", "/", "(ParseError.*)", "/", ",", "colors", ".", "red", "(", "'$1'", ")", ")", "log", "(", "message", ")", "}", "transform", ".", "emit", "(", "'end'", ")", "if", "(", "opts", ".", "callback", ")", "{", "opts", ".", "callback", "(", "through2", "(", ")", ")", "}", "}", "}" ]
Return a new error handler. @param {object} opts @param {stream.Transform} transform @return {function}
[ "Return", "a", "new", "error", "handler", "." ]
4b9deb5f90242ba352317d879268bfaedc5133de
https://github.com/ngryman/gulp-bro/blob/4b9deb5f90242ba352317d879268bfaedc5133de/index.js#L91-L111
25,998
ngnjs/NGN
lib/Utility.js
function (options, callback) { let me = this let tunnel let sshcfg = { host: this.host + ':' + (options.sshport || 22), user: options.username, remoteport: this.port } if (options.password) { sshcfg.password = options.password } if (options.key) { sshcfg.key = options.key } // Dynamically determine port by availability or via option. // Then open the tunnel. if (options.port) { sshcfg.port = options.port tunnel = new NGN.Tunnel(sshcfg) tunnel.on('ready', function () { NGN.BUS.emit('sshtunnel.create', tunnel) callback && callback(me.host, options.port) }) tunnel.connect() } else { // Create a quick TCP server on random port to secure the port, // then shut it down and use the newly freed port. let tmp = net.createServer().listen(0, '127.0.0.1', function () { sshcfg.port = this.address().port tmp.close() }) tmp.on('close', function () { // Launch the tunnel tunnel = new NGN.Tunnel(sshcfg) tunnel.on('ready', function () { callback && callback('127.0.0.1', sshcfg.port) }) tunnel.connect() }) } }
javascript
function (options, callback) { let me = this let tunnel let sshcfg = { host: this.host + ':' + (options.sshport || 22), user: options.username, remoteport: this.port } if (options.password) { sshcfg.password = options.password } if (options.key) { sshcfg.key = options.key } // Dynamically determine port by availability or via option. // Then open the tunnel. if (options.port) { sshcfg.port = options.port tunnel = new NGN.Tunnel(sshcfg) tunnel.on('ready', function () { NGN.BUS.emit('sshtunnel.create', tunnel) callback && callback(me.host, options.port) }) tunnel.connect() } else { // Create a quick TCP server on random port to secure the port, // then shut it down and use the newly freed port. let tmp = net.createServer().listen(0, '127.0.0.1', function () { sshcfg.port = this.address().port tmp.close() }) tmp.on('close', function () { // Launch the tunnel tunnel = new NGN.Tunnel(sshcfg) tunnel.on('ready', function () { callback && callback('127.0.0.1', sshcfg.port) }) tunnel.connect() }) } }
[ "function", "(", "options", ",", "callback", ")", "{", "let", "me", "=", "this", "let", "tunnel", "let", "sshcfg", "=", "{", "host", ":", "this", ".", "host", "+", "':'", "+", "(", "options", ".", "sshport", "||", "22", ")", ",", "user", ":", "options", ".", "username", ",", "remoteport", ":", "this", ".", "port", "}", "if", "(", "options", ".", "password", ")", "{", "sshcfg", ".", "password", "=", "options", ".", "password", "}", "if", "(", "options", ".", "key", ")", "{", "sshcfg", ".", "key", "=", "options", ".", "key", "}", "// Dynamically determine port by availability or via option.", "// Then open the tunnel.", "if", "(", "options", ".", "port", ")", "{", "sshcfg", ".", "port", "=", "options", ".", "port", "tunnel", "=", "new", "NGN", ".", "Tunnel", "(", "sshcfg", ")", "tunnel", ".", "on", "(", "'ready'", ",", "function", "(", ")", "{", "NGN", ".", "BUS", ".", "emit", "(", "'sshtunnel.create'", ",", "tunnel", ")", "callback", "&&", "callback", "(", "me", ".", "host", ",", "options", ".", "port", ")", "}", ")", "tunnel", ".", "connect", "(", ")", "}", "else", "{", "// Create a quick TCP server on random port to secure the port,", "// then shut it down and use the newly freed port.", "let", "tmp", "=", "net", ".", "createServer", "(", ")", ".", "listen", "(", "0", ",", "'127.0.0.1'", ",", "function", "(", ")", "{", "sshcfg", ".", "port", "=", "this", ".", "address", "(", ")", ".", "port", "tmp", ".", "close", "(", ")", "}", ")", "tmp", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "// Launch the tunnel", "tunnel", "=", "new", "NGN", ".", "Tunnel", "(", "sshcfg", ")", "tunnel", ".", "on", "(", "'ready'", ",", "function", "(", ")", "{", "callback", "&&", "callback", "(", "'127.0.0.1'", ",", "sshcfg", ".", "port", ")", "}", ")", "tunnel", ".", "connect", "(", ")", "}", ")", "}", "}" ]
Creates an SSH Tunnel
[ "Creates", "an", "SSH", "Tunnel" ]
b18c73b87051a742dbebe9335ebbec030ceabac6
https://github.com/ngnjs/NGN/blob/b18c73b87051a742dbebe9335ebbec030ceabac6/lib/Utility.js#L10-L54
25,999
wayfair/tungstenjs
src/template/compiler/index.js
getTemplate
function getTemplate(template, options) { stack.clear(); parser.reset(); let opts = typeof options === 'undefined' ? {} : options; opts.strict = typeof opts.strict === 'boolean' ? opts.strict : true; opts.preserveWhitespace = typeof opts.preserveWhitespace === 'boolean' ? opts.preserveWhitespace : false; opts.validateHtml = opts.validateHtml != null ? opts.validateHtml : 'strict'; opts.logger = opts.logger != null ? opts.logger : {}; let lambdas = {}; if (_.isArray(opts.lambdas)) { for (let i = 0; i < opts.lambdas.length; i++) { lambdas[opts.lambdas[i]] = true; } } opts.lambdas = lambdas; opts.processingHTML = typeof opts.processingHTML === 'boolean' ? opts.processingHTML : true; compilerLogger.setStrictMode(opts.strict); compilerLogger.setOverrides(opts.logger); stack.setHtmlValidation(opts.validateHtml); let templateStr = template.toString(); processTemplate(templateStr, opts); let output = {}; if (stack.stack.length > 0) { compilerErrors.notAllTagsWereClosedProperly(stack.stack); } parser.end(); output.templateObj = stack.getOutput(); const Template = require('../template'); output.template = new Template(output.templateObj); output.source = template; output.tokens = {}; _.each(stack.tokens, function(values, type) { output.tokens[type] = _.keys(values); }); return output; }
javascript
function getTemplate(template, options) { stack.clear(); parser.reset(); let opts = typeof options === 'undefined' ? {} : options; opts.strict = typeof opts.strict === 'boolean' ? opts.strict : true; opts.preserveWhitespace = typeof opts.preserveWhitespace === 'boolean' ? opts.preserveWhitespace : false; opts.validateHtml = opts.validateHtml != null ? opts.validateHtml : 'strict'; opts.logger = opts.logger != null ? opts.logger : {}; let lambdas = {}; if (_.isArray(opts.lambdas)) { for (let i = 0; i < opts.lambdas.length; i++) { lambdas[opts.lambdas[i]] = true; } } opts.lambdas = lambdas; opts.processingHTML = typeof opts.processingHTML === 'boolean' ? opts.processingHTML : true; compilerLogger.setStrictMode(opts.strict); compilerLogger.setOverrides(opts.logger); stack.setHtmlValidation(opts.validateHtml); let templateStr = template.toString(); processTemplate(templateStr, opts); let output = {}; if (stack.stack.length > 0) { compilerErrors.notAllTagsWereClosedProperly(stack.stack); } parser.end(); output.templateObj = stack.getOutput(); const Template = require('../template'); output.template = new Template(output.templateObj); output.source = template; output.tokens = {}; _.each(stack.tokens, function(values, type) { output.tokens[type] = _.keys(values); }); return output; }
[ "function", "getTemplate", "(", "template", ",", "options", ")", "{", "stack", ".", "clear", "(", ")", ";", "parser", ".", "reset", "(", ")", ";", "let", "opts", "=", "typeof", "options", "===", "'undefined'", "?", "{", "}", ":", "options", ";", "opts", ".", "strict", "=", "typeof", "opts", ".", "strict", "===", "'boolean'", "?", "opts", ".", "strict", ":", "true", ";", "opts", ".", "preserveWhitespace", "=", "typeof", "opts", ".", "preserveWhitespace", "===", "'boolean'", "?", "opts", ".", "preserveWhitespace", ":", "false", ";", "opts", ".", "validateHtml", "=", "opts", ".", "validateHtml", "!=", "null", "?", "opts", ".", "validateHtml", ":", "'strict'", ";", "opts", ".", "logger", "=", "opts", ".", "logger", "!=", "null", "?", "opts", ".", "logger", ":", "{", "}", ";", "let", "lambdas", "=", "{", "}", ";", "if", "(", "_", ".", "isArray", "(", "opts", ".", "lambdas", ")", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "opts", ".", "lambdas", ".", "length", ";", "i", "++", ")", "{", "lambdas", "[", "opts", ".", "lambdas", "[", "i", "]", "]", "=", "true", ";", "}", "}", "opts", ".", "lambdas", "=", "lambdas", ";", "opts", ".", "processingHTML", "=", "typeof", "opts", ".", "processingHTML", "===", "'boolean'", "?", "opts", ".", "processingHTML", ":", "true", ";", "compilerLogger", ".", "setStrictMode", "(", "opts", ".", "strict", ")", ";", "compilerLogger", ".", "setOverrides", "(", "opts", ".", "logger", ")", ";", "stack", ".", "setHtmlValidation", "(", "opts", ".", "validateHtml", ")", ";", "let", "templateStr", "=", "template", ".", "toString", "(", ")", ";", "processTemplate", "(", "templateStr", ",", "opts", ")", ";", "let", "output", "=", "{", "}", ";", "if", "(", "stack", ".", "stack", ".", "length", ">", "0", ")", "{", "compilerErrors", ".", "notAllTagsWereClosedProperly", "(", "stack", ".", "stack", ")", ";", "}", "parser", ".", "end", "(", ")", ";", "output", ".", "templateObj", "=", "stack", ".", "getOutput", "(", ")", ";", "const", "Template", "=", "require", "(", "'../template'", ")", ";", "output", ".", "template", "=", "new", "Template", "(", "output", ".", "templateObj", ")", ";", "output", ".", "source", "=", "template", ";", "output", ".", "tokens", "=", "{", "}", ";", "_", ".", "each", "(", "stack", ".", "tokens", ",", "function", "(", "values", ",", "type", ")", "{", "output", ".", "tokens", "[", "type", "]", "=", "_", ".", "keys", "(", "values", ")", ";", "}", ")", ";", "return", "output", ";", "}" ]
Processes a template string into a Template @param {string} template Mustache template string @return {Object} Processed template object
[ "Processes", "a", "template", "string", "into", "a", "Template" ]
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/template/compiler/index.js#L17-L60