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
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
byCedric/semantic-release-git-branches
lib/git.js
getModifiedFiles
async function getModifiedFiles() { return (await execa.stdout('git', ['ls-files', '-m', '-o', '--exclude-standard'])) .split('\n') .map(tag => tag.trim()) .filter(tag => Boolean(tag)); }
javascript
async function getModifiedFiles() { return (await execa.stdout('git', ['ls-files', '-m', '-o', '--exclude-standard'])) .split('\n') .map(tag => tag.trim()) .filter(tag => Boolean(tag)); }
[ "async", "function", "getModifiedFiles", "(", ")", "{", "return", "(", "await", "execa", ".", "stdout", "(", "'git'", ",", "[", "'ls-files'", ",", "'-m'", ",", "'-o'", ",", "'--exclude-standard'", "]", ")", ")", ".", "split", "(", "'\\n'", ")", ".", "\\n", "map", ".", "(", "tag", "=>", "tag", ".", "trim", "(", ")", ")", "filter", ";", "}" ]
Retrieve the list of files modified on the local repository. @return {Array<String>} Array of modified files path.
[ "Retrieve", "the", "list", "of", "files", "modified", "on", "the", "local", "repository", "." ]
199337210d7dd21d9cd8442604ef9e063ef69dc2
https://github.com/byCedric/semantic-release-git-branches/blob/199337210d7dd21d9cd8442604ef9e063ef69dc2/lib/git.js#L9-L14
train
fibo/dflow
src/engine/level.js
level
function level (pipe, cachedLevelOf, taskKey) { var taskLevel = 0 var parentsOf = parents.bind(null, pipe) if (typeof cachedLevelOf[taskKey] === 'number') { return cachedLevelOf[taskKey] } function computeLevel (parentTaskKey) { // ↓ Recursion here: the level of a task is the max level of its parents + 1. taskLevel = Math.max(taskLevel, level(pipe, cachedLevelOf, parentTaskKey) + 1) } parentsOf(taskKey).forEach(computeLevel) cachedLevelOf[taskKey] = taskLevel return taskLevel }
javascript
function level (pipe, cachedLevelOf, taskKey) { var taskLevel = 0 var parentsOf = parents.bind(null, pipe) if (typeof cachedLevelOf[taskKey] === 'number') { return cachedLevelOf[taskKey] } function computeLevel (parentTaskKey) { // ↓ Recursion here: the level of a task is the max level of its parents + 1. taskLevel = Math.max(taskLevel, level(pipe, cachedLevelOf, parentTaskKey) + 1) } parentsOf(taskKey).forEach(computeLevel) cachedLevelOf[taskKey] = taskLevel return taskLevel }
[ "function", "level", "(", "pipe", ",", "cachedLevelOf", ",", "taskKey", ")", "{", "var", "taskLevel", "=", "0", "var", "parentsOf", "=", "parents", ".", "bind", "(", "null", ",", "pipe", ")", "if", "(", "typeof", "cachedLevelOf", "[", "taskKey", "]", "===", "'number'", ")", "{", "return", "cachedLevelOf", "[", "taskKey", "]", "}", "function", "computeLevel", "(", "parentTaskKey", ")", "{", "taskLevel", "=", "Math", ".", "max", "(", "taskLevel", ",", "level", "(", "pipe", ",", "cachedLevelOf", ",", "parentTaskKey", ")", "+", "1", ")", "}", "parentsOf", "(", "taskKey", ")", ".", "forEach", "(", "computeLevel", ")", "cachedLevelOf", "[", "taskKey", "]", "=", "taskLevel", "return", "taskLevel", "}" ]
Compute level of task. @param {Object} pipe @param {Object} cachedLevelOf @param {String} taskKey @returns {Number} taskLevel
[ "Compute", "level", "of", "task", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/level.js#L13-L31
train
fedecia/gmail-api-sync
index.js
function (callback) { fs.readFile(clientSecretPath, function processClientSecrets(err, content) { if (err) { debug('Error loading client secret file: ' + err); return callback(err); } else { credentials = JSON.parse(content); return callback(); } }); }
javascript
function (callback) { fs.readFile(clientSecretPath, function processClientSecrets(err, content) { if (err) { debug('Error loading client secret file: ' + err); return callback(err); } else { credentials = JSON.parse(content); return callback(); } }); }
[ "function", "(", "callback", ")", "{", "fs", ".", "readFile", "(", "clientSecretPath", ",", "function", "processClientSecrets", "(", "err", ",", "content", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "'Error loading client secret file: '", "+", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "else", "{", "credentials", "=", "JSON", ".", "parse", "(", "content", ")", ";", "return", "callback", "(", ")", ";", "}", "}", ")", ";", "}" ]
Load client secrets from a local file.
[ "Load", "client", "secrets", "from", "a", "local", "file", "." ]
c29bfda8735eaa6590d05f59e45d6301385a321c
https://github.com/fedecia/gmail-api-sync/blob/c29bfda8735eaa6590d05f59e45d6301385a321c/index.js#L23-L33
train
fibo/dflow
src/engine/isDflowFun.js
isDflowFun
function isDflowFun (f) { var isFunction = typeof f === 'function' var hasFuncsObject = typeof f.funcs === 'object' var hasGraphObject = typeof f.graph === 'object' var hasValidGraph = true if (!isFunction || !hasFuncsObject || !hasGraphObject) return false if (isFunction && hasGraphObject && hasFuncsObject) { try { validate(f.graph, f.funcs) } catch (ignore) { hasValidGraph = false } } return hasValidGraph }
javascript
function isDflowFun (f) { var isFunction = typeof f === 'function' var hasFuncsObject = typeof f.funcs === 'object' var hasGraphObject = typeof f.graph === 'object' var hasValidGraph = true if (!isFunction || !hasFuncsObject || !hasGraphObject) return false if (isFunction && hasGraphObject && hasFuncsObject) { try { validate(f.graph, f.funcs) } catch (ignore) { hasValidGraph = false } } return hasValidGraph }
[ "function", "isDflowFun", "(", "f", ")", "{", "var", "isFunction", "=", "typeof", "f", "===", "'function'", "var", "hasFuncsObject", "=", "typeof", "f", ".", "funcs", "===", "'object'", "var", "hasGraphObject", "=", "typeof", "f", ".", "graph", "===", "'object'", "var", "hasValidGraph", "=", "true", "if", "(", "!", "isFunction", "||", "!", "hasFuncsObject", "||", "!", "hasGraphObject", ")", "return", "false", "if", "(", "isFunction", "&&", "hasGraphObject", "&&", "hasFuncsObject", ")", "{", "try", "{", "validate", "(", "f", ".", "graph", ",", "f", ".", "funcs", ")", "}", "catch", "(", "ignore", ")", "{", "hasValidGraph", "=", "false", "}", "}", "return", "hasValidGraph", "}" ]
Duct tape for dflow functions. @param {Function} f @returns {Boolean} ok, it looks like a dflowFun
[ "Duct", "tape", "for", "dflow", "functions", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/isDflowFun.js#L11-L28
train
OADA/oada-formats
formats.js
Formats
function Formats(options) { options = options || {}; this.debugConstructor = options.debug || debug; this.debug = this.debugConstructor('oada:formats'); this.errorConstructor = options.error || debug; this.error = this.errorConstructor('oada:formats:error'); this.Model = Model; this.models = {}; this.mediatypes = {}; // Add the built in models this.use(require('./JsonModel')); // Add the built in media types this.use(require('./formats/index.js')); }
javascript
function Formats(options) { options = options || {}; this.debugConstructor = options.debug || debug; this.debug = this.debugConstructor('oada:formats'); this.errorConstructor = options.error || debug; this.error = this.errorConstructor('oada:formats:error'); this.Model = Model; this.models = {}; this.mediatypes = {}; // Add the built in models this.use(require('./JsonModel')); // Add the built in media types this.use(require('./formats/index.js')); }
[ "function", "Formats", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "debugConstructor", "=", "options", ".", "debug", "||", "debug", ";", "this", ".", "debug", "=", "this", ".", "debugConstructor", "(", "'oada:formats'", ")", ";", "this", ".", "errorConstructor", "=", "options", ".", "error", "||", "debug", ";", "this", ".", "error", "=", "this", ".", "errorConstructor", "(", "'oada:formats:error'", ")", ";", "this", ".", "Model", "=", "Model", ";", "this", ".", "models", "=", "{", "}", ";", "this", ".", "mediatypes", "=", "{", "}", ";", "this", ".", "use", "(", "require", "(", "'./JsonModel'", ")", ")", ";", "this", ".", "use", "(", "require", "(", "'./formats/index.js'", ")", ")", ";", "}" ]
Maintains and builds OADA format models @constructor @param {object} options - Various optional options @param {function} options.debug - A custom debug logger, debug.js interface @param {function} options.error - A custom error logger, debug.js interface
[ "Maintains", "and", "builds", "OADA", "format", "models" ]
ac4b4ab496736c0803e00e1eaf98377d6b15058d
https://github.com/OADA/oada-formats/blob/ac4b4ab496736c0803e00e1eaf98377d6b15058d/formats.js#L43-L61
train
fibo/dflow
src/engine/inputArgs.js
inputArgs
function inputArgs (outs, pipe, taskKey) { var args = [] var inputPipesOf = inputPipes.bind(null, pipe) function populateArg (inputPipe) { var index = inputPipe[2] || 0 var value = outs[inputPipe[0]] args[index] = value } inputPipesOf(taskKey).forEach(populateArg) return args }
javascript
function inputArgs (outs, pipe, taskKey) { var args = [] var inputPipesOf = inputPipes.bind(null, pipe) function populateArg (inputPipe) { var index = inputPipe[2] || 0 var value = outs[inputPipe[0]] args[index] = value } inputPipesOf(taskKey).forEach(populateArg) return args }
[ "function", "inputArgs", "(", "outs", ",", "pipe", ",", "taskKey", ")", "{", "var", "args", "=", "[", "]", "var", "inputPipesOf", "=", "inputPipes", ".", "bind", "(", "null", ",", "pipe", ")", "function", "populateArg", "(", "inputPipe", ")", "{", "var", "index", "=", "inputPipe", "[", "2", "]", "||", "0", "var", "value", "=", "outs", "[", "inputPipe", "[", "0", "]", "]", "args", "[", "index", "]", "=", "value", "}", "inputPipesOf", "(", "taskKey", ")", ".", "forEach", "(", "populateArg", ")", "return", "args", "}" ]
Retrieve input arguments of a task. @param {Object} outs @param {Object} pipe @param {String} taskKey @returns {Array} args
[ "Retrieve", "input", "arguments", "of", "a", "task", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inputArgs.js#L13-L27
train
mojitoholic/pauldron
pauldron-policy/SimplePolicyDecisionCombinerEngine.js
evaluate
function evaluate(request, policies, engines) { const decisions = policies.map((policy) => ( engines[policy.type].evaluate(request, policy) )); return combineDecisionsDenyOverrides(decisions); }
javascript
function evaluate(request, policies, engines) { const decisions = policies.map((policy) => ( engines[policy.type].evaluate(request, policy) )); return combineDecisionsDenyOverrides(decisions); }
[ "function", "evaluate", "(", "request", ",", "policies", ",", "engines", ")", "{", "const", "decisions", "=", "policies", ".", "map", "(", "(", "policy", ")", "=>", "(", "engines", "[", "policy", ".", "type", "]", ".", "evaluate", "(", "request", ",", "policy", ")", ")", ")", ";", "return", "combineDecisionsDenyOverrides", "(", "decisions", ")", ";", "}" ]
deny-override
[ "deny", "-", "override" ]
ec5acc53be9ae75436ef46cef6dddd8f088732a3
https://github.com/mojitoholic/pauldron/blob/ec5acc53be9ae75436ef46cef6dddd8f088732a3/pauldron-policy/SimplePolicyDecisionCombinerEngine.js#L31-L36
train
retextjs/retext-emoji
index.js
toGemoji
function toGemoji(node) { var value = toString(node) var info = (unicodes[value] || emoticons[value] || {}).shortcode if (info) { node.value = info } }
javascript
function toGemoji(node) { var value = toString(node) var info = (unicodes[value] || emoticons[value] || {}).shortcode if (info) { node.value = info } }
[ "function", "toGemoji", "(", "node", ")", "{", "var", "value", "=", "toString", "(", "node", ")", "var", "info", "=", "(", "unicodes", "[", "value", "]", "||", "emoticons", "[", "value", "]", "||", "{", "}", ")", ".", "shortcode", "if", "(", "info", ")", "{", "node", ".", "value", "=", "info", "}", "}" ]
Replace a unicode emoji with a short-code.
[ "Replace", "a", "unicode", "emoji", "with", "a", "short", "-", "code", "." ]
2edeea12f59bed2b0cb29acbf93bfb29fd8b1b1e
https://github.com/retextjs/retext-emoji/blob/2edeea12f59bed2b0cb29acbf93bfb29fd8b1b1e/index.js#L80-L87
train
retextjs/retext-emoji
index.js
toEmoji
function toEmoji(node) { var value = toString(node) var info = (shortcodes[value] || emoticons[value] || {}).emoji if (info) { node.value = info } }
javascript
function toEmoji(node) { var value = toString(node) var info = (shortcodes[value] || emoticons[value] || {}).emoji if (info) { node.value = info } }
[ "function", "toEmoji", "(", "node", ")", "{", "var", "value", "=", "toString", "(", "node", ")", "var", "info", "=", "(", "shortcodes", "[", "value", "]", "||", "emoticons", "[", "value", "]", "||", "{", "}", ")", ".", "emoji", "if", "(", "info", ")", "{", "node", ".", "value", "=", "info", "}", "}" ]
Replace a short-code with a unicode emoji.
[ "Replace", "a", "short", "-", "code", "with", "a", "unicode", "emoji", "." ]
2edeea12f59bed2b0cb29acbf93bfb29fd8b1b1e
https://github.com/retextjs/retext-emoji/blob/2edeea12f59bed2b0cb29acbf93bfb29fd8b1b1e/index.js#L90-L97
train
fabric8-ui/ngx-widgets
gulpfile.js
minifyTemplate
function minifyTemplate(file) { try { let minifiedFile = htmlMinifier.minify(file, { collapseWhitespace: true, caseSensitive: true, removeComments: true }); return minifiedFile; } catch (err) { console.log(err); } }
javascript
function minifyTemplate(file) { try { let minifiedFile = htmlMinifier.minify(file, { collapseWhitespace: true, caseSensitive: true, removeComments: true }); return minifiedFile; } catch (err) { console.log(err); } }
[ "function", "minifyTemplate", "(", "file", ")", "{", "try", "{", "let", "minifiedFile", "=", "htmlMinifier", ".", "minify", "(", "file", ",", "{", "collapseWhitespace", ":", "true", ",", "caseSensitive", ":", "true", ",", "removeComments", ":", "true", "}", ")", ";", "return", "minifiedFile", ";", "}", "catch", "(", "err", ")", "{", "console", ".", "log", "(", "err", ")", ";", "}", "}" ]
Minify HTML templates
[ "Minify", "HTML", "templates" ]
b569e15fac75c5739d87b1c9a46216bb792c8d80
https://github.com/fabric8-ui/ngx-widgets/blob/b569e15fac75c5739d87b1c9a46216bb792c8d80/gulpfile.js#L73-L84
train
fabric8-ui/ngx-widgets
gulpfile.js
transpile
function transpile() { return exec('node_modules/.bin/ngc -p tsconfig.json', function (err, stdout, stderr) { console.log(stdout); console.log(stderr); if (err !== null) { process.exit(1); } }); }
javascript
function transpile() { return exec('node_modules/.bin/ngc -p tsconfig.json', function (err, stdout, stderr) { console.log(stdout); console.log(stderr); if (err !== null) { process.exit(1); } }); }
[ "function", "transpile", "(", ")", "{", "return", "exec", "(", "'node_modules/.bin/ngc -p tsconfig.json'", ",", "function", "(", "err", ",", "stdout", ",", "stderr", ")", "{", "console", ".", "log", "(", "stdout", ")", ";", "console", ".", "log", "(", "stderr", ")", ";", "if", "(", "err", "!==", "null", ")", "{", "process", ".", "exit", "(", "1", ")", ";", "}", "}", ")", ";", "}" ]
Build the components Since the gulpngc is no longer being supported we need to us ngc @returns {ChildProcess}
[ "Build", "the", "components", "Since", "the", "gulpngc", "is", "no", "longer", "being", "supported", "we", "need", "to", "us", "ngc" ]
b569e15fac75c5739d87b1c9a46216bb792c8d80
https://github.com/fabric8-ui/ngx-widgets/blob/b569e15fac75c5739d87b1c9a46216bb792c8d80/gulpfile.js#L158-L166
train
ShoppinPal/Materializecss-Autocomplete
dist/js/materializecss-autocomplete.js
clearValue
function clearValue() { clearSelectedItem(); setInputClearButton(); if (self.parentForm && self.parentForm !== null) { self.parentForm.$setDirty(); } }
javascript
function clearValue() { clearSelectedItem(); setInputClearButton(); if (self.parentForm && self.parentForm !== null) { self.parentForm.$setDirty(); } }
[ "function", "clearValue", "(", ")", "{", "clearSelectedItem", "(", ")", ";", "setInputClearButton", "(", ")", ";", "if", "(", "self", ".", "parentForm", "&&", "self", ".", "parentForm", "!==", "null", ")", "{", "self", ".", "parentForm", ".", "$setDirty", "(", ")", ";", "}", "}" ]
clear the input text field using clear button Check clear button visble and hidden
[ "clear", "the", "input", "text", "field", "using", "clear", "button", "Check", "clear", "button", "visble", "and", "hidden" ]
07bef97b9b373949058716054ec84c5ec5a397b9
https://github.com/ShoppinPal/Materializecss-Autocomplete/blob/07bef97b9b373949058716054ec84c5ec5a397b9/dist/js/materializecss-autocomplete.js#L263-L269
train
ShoppinPal/Materializecss-Autocomplete
dist/js/materializecss-autocomplete.js
handleSearchText
function handleSearchText(searchText, previousSearchText) { self.index = -1; // do nothing on init if (searchText === previousSearchText) return; else if (self.selectedItem && self.displayProperty1) { setLoading(false); if (self.selectedItem[self.displayProperty1] !== searchText) { self.selectedItem = null; self.hidden = shouldHide(); if (self.itemList && self.itemListCopy) { self.itemList = angular.copy(self.itemListCopy); } } } else if (self.remoteMethod) { fetchResults(searchText); } else if (self.itemList) { self.itemList = $filter('filter')(self.itemListCopy, searchText); } }
javascript
function handleSearchText(searchText, previousSearchText) { self.index = -1; // do nothing on init if (searchText === previousSearchText) return; else if (self.selectedItem && self.displayProperty1) { setLoading(false); if (self.selectedItem[self.displayProperty1] !== searchText) { self.selectedItem = null; self.hidden = shouldHide(); if (self.itemList && self.itemListCopy) { self.itemList = angular.copy(self.itemListCopy); } } } else if (self.remoteMethod) { fetchResults(searchText); } else if (self.itemList) { self.itemList = $filter('filter')(self.itemListCopy, searchText); } }
[ "function", "handleSearchText", "(", "searchText", ",", "previousSearchText", ")", "{", "self", ".", "index", "=", "-", "1", ";", "if", "(", "searchText", "===", "previousSearchText", ")", "return", ";", "else", "if", "(", "self", ".", "selectedItem", "&&", "self", ".", "displayProperty1", ")", "{", "setLoading", "(", "false", ")", ";", "if", "(", "self", ".", "selectedItem", "[", "self", ".", "displayProperty1", "]", "!==", "searchText", ")", "{", "self", ".", "selectedItem", "=", "null", ";", "self", ".", "hidden", "=", "shouldHide", "(", ")", ";", "if", "(", "self", ".", "itemList", "&&", "self", ".", "itemListCopy", ")", "{", "self", ".", "itemList", "=", "angular", ".", "copy", "(", "self", ".", "itemListCopy", ")", ";", "}", "}", "}", "else", "if", "(", "self", ".", "remoteMethod", ")", "{", "fetchResults", "(", "searchText", ")", ";", "}", "else", "if", "(", "self", ".", "itemList", ")", "{", "self", ".", "itemList", "=", "$filter", "(", "'filter'", ")", "(", "self", ".", "itemListCopy", ",", "searchText", ")", ";", "}", "}" ]
Handles changes to the searchText property. @param searchText @param previousSearchText
[ "Handles", "changes", "to", "the", "searchText", "property", "." ]
07bef97b9b373949058716054ec84c5ec5a397b9
https://github.com/ShoppinPal/Materializecss-Autocomplete/blob/07bef97b9b373949058716054ec84c5ec5a397b9/dist/js/materializecss-autocomplete.js#L458-L478
train
ShoppinPal/Materializecss-Autocomplete
dist/js/materializecss-autocomplete.js
selectedItemChange
function selectedItemChange(selectedItem, previousSelectedItem) { if (selectedItem) { if (self.displayProperty1) { self.searchText = selectedItem[self.displayProperty1]; } if (self.parentForm && self.parentForm !== null) { self.parentForm.$setDirty(); } } else if (previousSelectedItem && self.searchText) { if (previousSelectedItem[self.displayProperty1] === self.searchText) { self.searchText = ''; } } if (selectedItem !== previousSelectedItem) announceItemChange(); }
javascript
function selectedItemChange(selectedItem, previousSelectedItem) { if (selectedItem) { if (self.displayProperty1) { self.searchText = selectedItem[self.displayProperty1]; } if (self.parentForm && self.parentForm !== null) { self.parentForm.$setDirty(); } } else if (previousSelectedItem && self.searchText) { if (previousSelectedItem[self.displayProperty1] === self.searchText) { self.searchText = ''; } } if (selectedItem !== previousSelectedItem) announceItemChange(); }
[ "function", "selectedItemChange", "(", "selectedItem", ",", "previousSelectedItem", ")", "{", "if", "(", "selectedItem", ")", "{", "if", "(", "self", ".", "displayProperty1", ")", "{", "self", ".", "searchText", "=", "selectedItem", "[", "self", ".", "displayProperty1", "]", ";", "}", "if", "(", "self", ".", "parentForm", "&&", "self", ".", "parentForm", "!==", "null", ")", "{", "self", ".", "parentForm", ".", "$setDirty", "(", ")", ";", "}", "}", "else", "if", "(", "previousSelectedItem", "&&", "self", ".", "searchText", ")", "{", "if", "(", "previousSelectedItem", "[", "self", ".", "displayProperty1", "]", "===", "self", ".", "searchText", ")", "{", "self", ".", "searchText", "=", "''", ";", "}", "}", "if", "(", "selectedItem", "!==", "previousSelectedItem", ")", "announceItemChange", "(", ")", ";", "}" ]
Handles changes to the selected item. @param selectedItem @param previousSelectedItem
[ "Handles", "changes", "to", "the", "selected", "item", "." ]
07bef97b9b373949058716054ec84c5ec5a397b9
https://github.com/ShoppinPal/Materializecss-Autocomplete/blob/07bef97b9b373949058716054ec84c5ec5a397b9/dist/js/materializecss-autocomplete.js#L485-L501
train
ShoppinPal/Materializecss-Autocomplete
dist/js/materializecss-autocomplete.js
updateScroll
function updateScroll() { if (!self.element.li[0]) return; var height = self.element.li[0].offsetHeight, top = height * self.index, bot = top + height, hgt = self.element.scroller.clientHeight, scrollTop = self.element.scroller.scrollTop; if (top<scrollTop) { scrollTo(top); }else if (bot>scrollTop + hgt) { scrollTo(bot - hgt); } }
javascript
function updateScroll() { if (!self.element.li[0]) return; var height = self.element.li[0].offsetHeight, top = height * self.index, bot = top + height, hgt = self.element.scroller.clientHeight, scrollTop = self.element.scroller.scrollTop; if (top<scrollTop) { scrollTo(top); }else if (bot>scrollTop + hgt) { scrollTo(bot - hgt); } }
[ "function", "updateScroll", "(", ")", "{", "if", "(", "!", "self", ".", "element", ".", "li", "[", "0", "]", ")", "return", ";", "var", "height", "=", "self", ".", "element", ".", "li", "[", "0", "]", ".", "offsetHeight", ",", "top", "=", "height", "*", "self", ".", "index", ",", "bot", "=", "top", "+", "height", ",", "hgt", "=", "self", ".", "element", ".", "scroller", ".", "clientHeight", ",", "scrollTop", "=", "self", ".", "element", ".", "scroller", ".", "scrollTop", ";", "if", "(", "top", "<", "scrollTop", ")", "{", "scrollTo", "(", "top", ")", ";", "}", "else", "if", "(", "bot", ">", "scrollTop", "+", "hgt", ")", "{", "scrollTo", "(", "bot", "-", "hgt", ")", ";", "}", "}" ]
Makes sure that the focused element is within view.
[ "Makes", "sure", "that", "the", "focused", "element", "is", "within", "view", "." ]
07bef97b9b373949058716054ec84c5ec5a397b9
https://github.com/ShoppinPal/Materializecss-Autocomplete/blob/07bef97b9b373949058716054ec84c5ec5a397b9/dist/js/materializecss-autocomplete.js#L527-L539
train
ShoppinPal/Materializecss-Autocomplete
dist/js/materializecss-autocomplete.js
handleUniqueResult
function handleUniqueResult(results) { var res = [], flag = {}; for (var i = 0; i<results.length; i++) { if (flag[results[i][self.displayProperty1]]) continue; flag[results[i][self.displayProperty1]] = true; res.push(results[i]); } return res; }
javascript
function handleUniqueResult(results) { var res = [], flag = {}; for (var i = 0; i<results.length; i++) { if (flag[results[i][self.displayProperty1]]) continue; flag[results[i][self.displayProperty1]] = true; res.push(results[i]); } return res; }
[ "function", "handleUniqueResult", "(", "results", ")", "{", "var", "res", "=", "[", "]", ",", "flag", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "results", ".", "length", ";", "i", "++", ")", "{", "if", "(", "flag", "[", "results", "[", "i", "]", "[", "self", ".", "displayProperty1", "]", "]", ")", "continue", ";", "flag", "[", "results", "[", "i", "]", "[", "self", ".", "displayProperty1", "]", "]", "=", "true", ";", "res", ".", "push", "(", "results", "[", "i", "]", ")", ";", "}", "return", "res", ";", "}" ]
This function check for result uniqueness on displayProperty1 params and return unique array @param results @returns {Array}
[ "This", "function", "check", "for", "result", "uniqueness", "on", "displayProperty1", "params", "and", "return", "unique", "array" ]
07bef97b9b373949058716054ec84c5ec5a397b9
https://github.com/ShoppinPal/Materializecss-Autocomplete/blob/07bef97b9b373949058716054ec84c5ec5a397b9/dist/js/materializecss-autocomplete.js#L604-L612
train
ShoppinPal/Materializecss-Autocomplete
dist/js/materializecss-autocomplete.js
convertArrayToObject
function convertArrayToObject(array) { var temp = []; array.forEach(function (text) { temp.push({ index: text }); }); return temp; }
javascript
function convertArrayToObject(array) { var temp = []; array.forEach(function (text) { temp.push({ index: text }); }); return temp; }
[ "function", "convertArrayToObject", "(", "array", ")", "{", "var", "temp", "=", "[", "]", ";", "array", ".", "forEach", "(", "function", "(", "text", ")", "{", "temp", ".", "push", "(", "{", "index", ":", "text", "}", ")", ";", "}", ")", ";", "return", "temp", ";", "}" ]
This function converts an array of strings to object of strings with key "index" @param array @returns {Array}
[ "This", "function", "converts", "an", "array", "of", "strings", "to", "object", "of", "strings", "with", "key", "index" ]
07bef97b9b373949058716054ec84c5ec5a397b9
https://github.com/ShoppinPal/Materializecss-Autocomplete/blob/07bef97b9b373949058716054ec84c5ec5a397b9/dist/js/materializecss-autocomplete.js#L636-L644
train
cgmartin/express-api-server
src/lib/graceful-shutdown.js
function(retCode) { retCode = (typeof retCode !== 'undefined') ? retCode : 0; if (server) { if (shutdownInProgress) { return; } shutdownInProgress = true; console.info('Shutting down gracefully...'); server.close(function() { console.info('Closed out remaining connections'); process.exit(retCode); }); setTimeout(function() { console.error('Could not close out connections in time, force shutdown'); process.exit(retCode); }, 10 * 1000).unref(); } else { console.debug('Http server is not running. Exiting'); process.exit(retCode); } }
javascript
function(retCode) { retCode = (typeof retCode !== 'undefined') ? retCode : 0; if (server) { if (shutdownInProgress) { return; } shutdownInProgress = true; console.info('Shutting down gracefully...'); server.close(function() { console.info('Closed out remaining connections'); process.exit(retCode); }); setTimeout(function() { console.error('Could not close out connections in time, force shutdown'); process.exit(retCode); }, 10 * 1000).unref(); } else { console.debug('Http server is not running. Exiting'); process.exit(retCode); } }
[ "function", "(", "retCode", ")", "{", "retCode", "=", "(", "typeof", "retCode", "!==", "'undefined'", ")", "?", "retCode", ":", "0", ";", "if", "(", "server", ")", "{", "if", "(", "shutdownInProgress", ")", "{", "return", ";", "}", "shutdownInProgress", "=", "true", ";", "console", ".", "info", "(", "'Shutting down gracefully...'", ")", ";", "server", ".", "close", "(", "function", "(", ")", "{", "console", ".", "info", "(", "'Closed out remaining connections'", ")", ";", "process", ".", "exit", "(", "retCode", ")", ";", "}", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "console", ".", "error", "(", "'Could not close out connections in time, force shutdown'", ")", ";", "process", ".", "exit", "(", "retCode", ")", ";", "}", ",", "10", "*", "1000", ")", ".", "unref", "(", ")", ";", "}", "else", "{", "console", ".", "debug", "(", "'Http server is not running. Exiting'", ")", ";", "process", ".", "exit", "(", "retCode", ")", ";", "}", "}" ]
Shut down gracefully
[ "Shut", "down", "gracefully" ]
9d6de16e7c84d21b83639a904f2eaed4a30a4088
https://github.com/cgmartin/express-api-server/blob/9d6de16e7c84d21b83639a904f2eaed4a30a4088/src/lib/graceful-shutdown.js#L12-L34
train
fibo/dflow
src/engine/inject/arguments.js
injectArguments
function injectArguments (funcs, task, args) { function getArgument (index) { return args[index] } /** * Inject arguments. */ function inject (taskKey) { var funcName = task[taskKey] if (funcName === 'arguments') { funcs[funcName] = function getArguments () { return args } } else { var arg = regexArgument.exec(funcName) if (arg) { funcs[funcName] = getArgument.bind(null, arg[1]) } } } Object.keys(task) .forEach(inject) }
javascript
function injectArguments (funcs, task, args) { function getArgument (index) { return args[index] } /** * Inject arguments. */ function inject (taskKey) { var funcName = task[taskKey] if (funcName === 'arguments') { funcs[funcName] = function getArguments () { return args } } else { var arg = regexArgument.exec(funcName) if (arg) { funcs[funcName] = getArgument.bind(null, arg[1]) } } } Object.keys(task) .forEach(inject) }
[ "function", "injectArguments", "(", "funcs", ",", "task", ",", "args", ")", "{", "function", "getArgument", "(", "index", ")", "{", "return", "args", "[", "index", "]", "}", "function", "inject", "(", "taskKey", ")", "{", "var", "funcName", "=", "task", "[", "taskKey", "]", "if", "(", "funcName", "===", "'arguments'", ")", "{", "funcs", "[", "funcName", "]", "=", "function", "getArguments", "(", ")", "{", "return", "args", "}", "}", "else", "{", "var", "arg", "=", "regexArgument", ".", "exec", "(", "funcName", ")", "if", "(", "arg", ")", "{", "funcs", "[", "funcName", "]", "=", "getArgument", ".", "bind", "(", "null", ",", "arg", "[", "1", "]", ")", "}", "}", "}", "Object", ".", "keys", "(", "task", ")", ".", "forEach", "(", "inject", ")", "}" ]
Inject functions to retrieve arguments. @param {Object} funcs reference @param {Object} task @param {Object} args
[ "Inject", "functions", "to", "retrieve", "arguments", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/arguments.js#L11-L36
train
fibo/dflow
src/engine/inject/arguments.js
inject
function inject (taskKey) { var funcName = task[taskKey] if (funcName === 'arguments') { funcs[funcName] = function getArguments () { return args } } else { var arg = regexArgument.exec(funcName) if (arg) { funcs[funcName] = getArgument.bind(null, arg[1]) } } }
javascript
function inject (taskKey) { var funcName = task[taskKey] if (funcName === 'arguments') { funcs[funcName] = function getArguments () { return args } } else { var arg = regexArgument.exec(funcName) if (arg) { funcs[funcName] = getArgument.bind(null, arg[1]) } } }
[ "function", "inject", "(", "taskKey", ")", "{", "var", "funcName", "=", "task", "[", "taskKey", "]", "if", "(", "funcName", "===", "'arguments'", ")", "{", "funcs", "[", "funcName", "]", "=", "function", "getArguments", "(", ")", "{", "return", "args", "}", "}", "else", "{", "var", "arg", "=", "regexArgument", ".", "exec", "(", "funcName", ")", "if", "(", "arg", ")", "{", "funcs", "[", "funcName", "]", "=", "getArgument", ".", "bind", "(", "null", ",", "arg", "[", "1", "]", ")", "}", "}", "}" ]
Inject arguments.
[ "Inject", "arguments", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/arguments.js#L20-L32
train
fibo/dflow
src/engine/inject/globals.js
injectGlobals
function injectGlobals (funcs, task) { /** * Inject task */ function inject (taskKey) { var taskName = task[taskKey] // Do not overwrite a function if already defined. // For example, console.log cannot be used as is, it must binded to console. if (typeof funcs[taskName] === 'function') return // Skip also reserved keywords. if (reservedKeys.indexOf(taskName) > -1) return var globalValue = walkGlobal(taskName) if (no(globalValue)) return if (typeof globalValue === 'function') { funcs[taskName] = globalValue } else { funcs[taskName] = function () { return globalValue } } } Object.keys(task) .forEach(inject) }
javascript
function injectGlobals (funcs, task) { /** * Inject task */ function inject (taskKey) { var taskName = task[taskKey] // Do not overwrite a function if already defined. // For example, console.log cannot be used as is, it must binded to console. if (typeof funcs[taskName] === 'function') return // Skip also reserved keywords. if (reservedKeys.indexOf(taskName) > -1) return var globalValue = walkGlobal(taskName) if (no(globalValue)) return if (typeof globalValue === 'function') { funcs[taskName] = globalValue } else { funcs[taskName] = function () { return globalValue } } } Object.keys(task) .forEach(inject) }
[ "function", "injectGlobals", "(", "funcs", ",", "task", ")", "{", "function", "inject", "(", "taskKey", ")", "{", "var", "taskName", "=", "task", "[", "taskKey", "]", "if", "(", "typeof", "funcs", "[", "taskName", "]", "===", "'function'", ")", "return", "if", "(", "reservedKeys", ".", "indexOf", "(", "taskName", ")", ">", "-", "1", ")", "return", "var", "globalValue", "=", "walkGlobal", "(", "taskName", ")", "if", "(", "no", "(", "globalValue", ")", ")", "return", "if", "(", "typeof", "globalValue", "===", "'function'", ")", "{", "funcs", "[", "taskName", "]", "=", "globalValue", "}", "else", "{", "funcs", "[", "taskName", "]", "=", "function", "(", ")", "{", "return", "globalValue", "}", "}", "}", "Object", ".", "keys", "(", "task", ")", ".", "forEach", "(", "inject", ")", "}" ]
Inject globals. @param {Object} funcs reference @param {Object} task
[ "Inject", "globals", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/globals.js#L12-L42
train
fibo/dflow
src/examples/renderer/client-side.js
renderExample
function renderExample (divId, example) { var graph = graphs[example] var canvas = new Canvas(divId, { node: { DefaultNode: Node, InvalidNode, ToggleNode }, util: { typeOfNode } }) canvas.render(graph.view) dflow.fun(graph)() }
javascript
function renderExample (divId, example) { var graph = graphs[example] var canvas = new Canvas(divId, { node: { DefaultNode: Node, InvalidNode, ToggleNode }, util: { typeOfNode } }) canvas.render(graph.view) dflow.fun(graph)() }
[ "function", "renderExample", "(", "divId", ",", "example", ")", "{", "var", "graph", "=", "graphs", "[", "example", "]", "var", "canvas", "=", "new", "Canvas", "(", "divId", ",", "{", "node", ":", "{", "DefaultNode", ":", "Node", ",", "InvalidNode", ",", "ToggleNode", "}", ",", "util", ":", "{", "typeOfNode", "}", "}", ")", "canvas", ".", "render", "(", "graph", ".", "view", ")", "dflow", ".", "fun", "(", "graph", ")", "(", ")", "}" ]
Render example into given div and execute dflow graph. @param {String} divId @param {String} example @returns {undefined}
[ "Render", "example", "into", "given", "div", "and", "execute", "dflow", "graph", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/examples/renderer/client-side.js#L18-L33
train
fibo/dflow
src/engine/inject/references.js
injectReferences
function injectReferences (funcs, task) { /** * Inject task. * * @param {String} taskKey */ function inject (taskKey) { var referenceName = null var referencedFunction = null var taskName = task[taskKey] /** * Inject reference. */ function reference () { return referencedFunction } if (regexReference.test(taskName)) { referenceName = taskName.substring(1) if (typeof funcs[referenceName] === 'function') { referencedFunction = funcs[referenceName] } else { referencedFunction = walkGlobal(referenceName) } if (typeof referencedFunction === 'function') { funcs[taskName] = reference } } } Object.keys(task).forEach(inject) }
javascript
function injectReferences (funcs, task) { /** * Inject task. * * @param {String} taskKey */ function inject (taskKey) { var referenceName = null var referencedFunction = null var taskName = task[taskKey] /** * Inject reference. */ function reference () { return referencedFunction } if (regexReference.test(taskName)) { referenceName = taskName.substring(1) if (typeof funcs[referenceName] === 'function') { referencedFunction = funcs[referenceName] } else { referencedFunction = walkGlobal(referenceName) } if (typeof referencedFunction === 'function') { funcs[taskName] = reference } } } Object.keys(task).forEach(inject) }
[ "function", "injectReferences", "(", "funcs", ",", "task", ")", "{", "function", "inject", "(", "taskKey", ")", "{", "var", "referenceName", "=", "null", "var", "referencedFunction", "=", "null", "var", "taskName", "=", "task", "[", "taskKey", "]", "function", "reference", "(", ")", "{", "return", "referencedFunction", "}", "if", "(", "regexReference", ".", "test", "(", "taskName", ")", ")", "{", "referenceName", "=", "taskName", ".", "substring", "(", "1", ")", "if", "(", "typeof", "funcs", "[", "referenceName", "]", "===", "'function'", ")", "{", "referencedFunction", "=", "funcs", "[", "referenceName", "]", "}", "else", "{", "referencedFunction", "=", "walkGlobal", "(", "referenceName", ")", "}", "if", "(", "typeof", "referencedFunction", "===", "'function'", ")", "{", "funcs", "[", "taskName", "]", "=", "reference", "}", "}", "}", "Object", ".", "keys", "(", "task", ")", ".", "forEach", "(", "inject", ")", "}" ]
Inject references to functions. @param {Object} funcs reference @param {Object} task
[ "Inject", "references", "to", "functions", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/references.js#L11-L47
train
fibo/dflow
src/engine/inject/references.js
inject
function inject (taskKey) { var referenceName = null var referencedFunction = null var taskName = task[taskKey] /** * Inject reference. */ function reference () { return referencedFunction } if (regexReference.test(taskName)) { referenceName = taskName.substring(1) if (typeof funcs[referenceName] === 'function') { referencedFunction = funcs[referenceName] } else { referencedFunction = walkGlobal(referenceName) } if (typeof referencedFunction === 'function') { funcs[taskName] = reference } } }
javascript
function inject (taskKey) { var referenceName = null var referencedFunction = null var taskName = task[taskKey] /** * Inject reference. */ function reference () { return referencedFunction } if (regexReference.test(taskName)) { referenceName = taskName.substring(1) if (typeof funcs[referenceName] === 'function') { referencedFunction = funcs[referenceName] } else { referencedFunction = walkGlobal(referenceName) } if (typeof referencedFunction === 'function') { funcs[taskName] = reference } } }
[ "function", "inject", "(", "taskKey", ")", "{", "var", "referenceName", "=", "null", "var", "referencedFunction", "=", "null", "var", "taskName", "=", "task", "[", "taskKey", "]", "function", "reference", "(", ")", "{", "return", "referencedFunction", "}", "if", "(", "regexReference", ".", "test", "(", "taskName", ")", ")", "{", "referenceName", "=", "taskName", ".", "substring", "(", "1", ")", "if", "(", "typeof", "funcs", "[", "referenceName", "]", "===", "'function'", ")", "{", "referencedFunction", "=", "funcs", "[", "referenceName", "]", "}", "else", "{", "referencedFunction", "=", "walkGlobal", "(", "referenceName", ")", "}", "if", "(", "typeof", "referencedFunction", "===", "'function'", ")", "{", "funcs", "[", "taskName", "]", "=", "reference", "}", "}", "}" ]
Inject task. @param {String} taskKey
[ "Inject", "task", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/references.js#L18-L44
train
fibo/dflow
src/engine/inject/strings.js
injectStrings
function injectStrings (funcs, task) { /** * Inject a function that returns a string. */ function inject (taskKey) { var taskName = task[taskKey] if (regexQuoted.test(taskName)) { funcs[taskName] = function () { return taskName.substr(1, taskName.length - 2) } } } Object.keys(task) .forEach(inject) }
javascript
function injectStrings (funcs, task) { /** * Inject a function that returns a string. */ function inject (taskKey) { var taskName = task[taskKey] if (regexQuoted.test(taskName)) { funcs[taskName] = function () { return taskName.substr(1, taskName.length - 2) } } } Object.keys(task) .forEach(inject) }
[ "function", "injectStrings", "(", "funcs", ",", "task", ")", "{", "function", "inject", "(", "taskKey", ")", "{", "var", "taskName", "=", "task", "[", "taskKey", "]", "if", "(", "regexQuoted", ".", "test", "(", "taskName", ")", ")", "{", "funcs", "[", "taskName", "]", "=", "function", "(", ")", "{", "return", "taskName", ".", "substr", "(", "1", ",", "taskName", ".", "length", "-", "2", ")", "}", "}", "}", "Object", ".", "keys", "(", "task", ")", ".", "forEach", "(", "inject", ")", "}" ]
Inject functions that return strings. @param {Object} funcs reference @param {Object} task collection
[ "Inject", "functions", "that", "return", "strings", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/strings.js#L10-L27
train
fibo/dflow
src/engine/inject/strings.js
inject
function inject (taskKey) { var taskName = task[taskKey] if (regexQuoted.test(taskName)) { funcs[taskName] = function () { return taskName.substr(1, taskName.length - 2) } } }
javascript
function inject (taskKey) { var taskName = task[taskKey] if (regexQuoted.test(taskName)) { funcs[taskName] = function () { return taskName.substr(1, taskName.length - 2) } } }
[ "function", "inject", "(", "taskKey", ")", "{", "var", "taskName", "=", "task", "[", "taskKey", "]", "if", "(", "regexQuoted", ".", "test", "(", "taskName", ")", ")", "{", "funcs", "[", "taskName", "]", "=", "function", "(", ")", "{", "return", "taskName", ".", "substr", "(", "1", ",", "taskName", ".", "length", "-", "2", ")", "}", "}", "}" ]
Inject a function that returns a string.
[ "Inject", "a", "function", "that", "returns", "a", "string", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/strings.js#L15-L23
train
macbre/wayback-machine
lib/wayback.js
request
function request(url, options, callback) { var debug = require('debug')('wayback:http'); debug('req', url); callback = typeof callback === 'undefined' ? options : callback; // @see https://www.npmjs.com/package/fetch var stream = new fetch(url, typeof options === 'object' ? options : undefined); stream.on('error', function(err) { debug('error', err); callback(err, null); }); stream.on('meta', function(meta) { debug('resp', 'HTTP ' + meta.status); debug('resp', meta.responseHeaders); callback(null, stream); }); }
javascript
function request(url, options, callback) { var debug = require('debug')('wayback:http'); debug('req', url); callback = typeof callback === 'undefined' ? options : callback; // @see https://www.npmjs.com/package/fetch var stream = new fetch(url, typeof options === 'object' ? options : undefined); stream.on('error', function(err) { debug('error', err); callback(err, null); }); stream.on('meta', function(meta) { debug('resp', 'HTTP ' + meta.status); debug('resp', meta.responseHeaders); callback(null, stream); }); }
[ "function", "request", "(", "url", ",", "options", ",", "callback", ")", "{", "var", "debug", "=", "require", "(", "'debug'", ")", "(", "'wayback:http'", ")", ";", "debug", "(", "'req'", ",", "url", ")", ";", "callback", "=", "typeof", "callback", "===", "'undefined'", "?", "options", ":", "callback", ";", "var", "stream", "=", "new", "fetch", "(", "url", ",", "typeof", "options", "===", "'object'", "?", "options", ":", "undefined", ")", ";", "stream", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "debug", "(", "'error'", ",", "err", ")", ";", "callback", "(", "err", ",", "null", ")", ";", "}", ")", ";", "stream", ".", "on", "(", "'meta'", ",", "function", "(", "meta", ")", "{", "debug", "(", "'resp'", ",", "'HTTP '", "+", "meta", ".", "status", ")", ";", "debug", "(", "'resp'", ",", "meta", ".", "responseHeaders", ")", ";", "callback", "(", "null", ",", "stream", ")", ";", "}", ")", ";", "}" ]
a simple HTTP client wrapper returning a response stream
[ "a", "simple", "HTTP", "client", "wrapper", "returning", "a", "response", "stream" ]
b48fbf4735efad4fd6571cc292d28dc17cf6786c
https://github.com/macbre/wayback-machine/blob/b48fbf4735efad4fd6571cc292d28dc17cf6786c/lib/wayback.js#L9-L28
train
Bandwidth/opkit
lib/Persisters/filepersister.js
filePersister
function filePersister(filepath) { var self = this; this.initialized = false; this.filepath = filepath; /** * Check to see if the specified file path is available. * @returns A promise appropriately resolving or rejecting. */ this.start = function() { if (!this.initialized) { return fsp.emptyDir(this.filepath) .then(function() { self.initialized = true; return Promise.resolve('User has permissions to write to that file.'); }) .catch(function(err) { return Promise.reject('User does not have permissions to write to that folder.'); }); } return Promise.reject('Error: Persister already initialized.'); }; /** * Save the passed state to the file. * @param {Object} passedState - State to be saved in the file. * @returns A promise resolving to an appropriate success message or an error message. */ this.save = function(brain, package) { var filepath = this.filepath; if (this.initialized) { return fsp.remove(filepath + '/' + package + '.txt') .then(function(){ return fsp.writeFile(filepath + '/' + package + '.txt', JSON.stringify(brain)); }) .then(function(){ return Promise.resolve('Saved.'); }) } return Promise.reject('Error: Persister not initialized.'); }; /** * Retrieve data from the file. * @returns The most recent entry to the file, as a JavaScript object. */ this.recover = function(package) { if (this.initialized) { var filepath = this.filepath return fsp.ensureFile(filepath +'/' + package + '.txt') .then(function(){ return fsp.readFile(filepath + '/' + package + '.txt', 'utf8') }) .then(function(data) { if (data === ''){ return Promise.resolve({}); } else { return Promise.resolve(JSON.parse(data)); } }); } return Promise.reject('Error: Persister not initialized.'); }; }
javascript
function filePersister(filepath) { var self = this; this.initialized = false; this.filepath = filepath; /** * Check to see if the specified file path is available. * @returns A promise appropriately resolving or rejecting. */ this.start = function() { if (!this.initialized) { return fsp.emptyDir(this.filepath) .then(function() { self.initialized = true; return Promise.resolve('User has permissions to write to that file.'); }) .catch(function(err) { return Promise.reject('User does not have permissions to write to that folder.'); }); } return Promise.reject('Error: Persister already initialized.'); }; /** * Save the passed state to the file. * @param {Object} passedState - State to be saved in the file. * @returns A promise resolving to an appropriate success message or an error message. */ this.save = function(brain, package) { var filepath = this.filepath; if (this.initialized) { return fsp.remove(filepath + '/' + package + '.txt') .then(function(){ return fsp.writeFile(filepath + '/' + package + '.txt', JSON.stringify(brain)); }) .then(function(){ return Promise.resolve('Saved.'); }) } return Promise.reject('Error: Persister not initialized.'); }; /** * Retrieve data from the file. * @returns The most recent entry to the file, as a JavaScript object. */ this.recover = function(package) { if (this.initialized) { var filepath = this.filepath return fsp.ensureFile(filepath +'/' + package + '.txt') .then(function(){ return fsp.readFile(filepath + '/' + package + '.txt', 'utf8') }) .then(function(data) { if (data === ''){ return Promise.resolve({}); } else { return Promise.resolve(JSON.parse(data)); } }); } return Promise.reject('Error: Persister not initialized.'); }; }
[ "function", "filePersister", "(", "filepath", ")", "{", "var", "self", "=", "this", ";", "this", ".", "initialized", "=", "false", ";", "this", ".", "filepath", "=", "filepath", ";", "this", ".", "start", "=", "function", "(", ")", "{", "if", "(", "!", "this", ".", "initialized", ")", "{", "return", "fsp", ".", "emptyDir", "(", "this", ".", "filepath", ")", ".", "then", "(", "function", "(", ")", "{", "self", ".", "initialized", "=", "true", ";", "return", "Promise", ".", "resolve", "(", "'User has permissions to write to that file.'", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "return", "Promise", ".", "reject", "(", "'User does not have permissions to write to that folder.'", ")", ";", "}", ")", ";", "}", "return", "Promise", ".", "reject", "(", "'Error: Persister already initialized.'", ")", ";", "}", ";", "this", ".", "save", "=", "function", "(", "brain", ",", "package", ")", "{", "var", "filepath", "=", "this", ".", "filepath", ";", "if", "(", "this", ".", "initialized", ")", "{", "return", "fsp", ".", "remove", "(", "filepath", "+", "'/'", "+", "package", "+", "'.txt'", ")", ".", "then", "(", "function", "(", ")", "{", "return", "fsp", ".", "writeFile", "(", "filepath", "+", "'/'", "+", "package", "+", "'.txt'", ",", "JSON", ".", "stringify", "(", "brain", ")", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "Promise", ".", "resolve", "(", "'Saved.'", ")", ";", "}", ")", "}", "return", "Promise", ".", "reject", "(", "'Error: Persister not initialized.'", ")", ";", "}", ";", "this", ".", "recover", "=", "function", "(", "package", ")", "{", "if", "(", "this", ".", "initialized", ")", "{", "var", "filepath", "=", "this", ".", "filepath", "return", "fsp", ".", "ensureFile", "(", "filepath", "+", "'/'", "+", "package", "+", "'.txt'", ")", ".", "then", "(", "function", "(", ")", "{", "return", "fsp", ".", "readFile", "(", "filepath", "+", "'/'", "+", "package", "+", "'.txt'", ",", "'utf8'", ")", "}", ")", ".", "then", "(", "function", "(", "data", ")", "{", "if", "(", "data", "===", "''", ")", "{", "return", "Promise", ".", "resolve", "(", "{", "}", ")", ";", "}", "else", "{", "return", "Promise", ".", "resolve", "(", "JSON", ".", "parse", "(", "data", ")", ")", ";", "}", "}", ")", ";", "}", "return", "Promise", ".", "reject", "(", "'Error: Persister not initialized.'", ")", ";", "}", ";", "}" ]
File persister factory method. Returns a persister object. @param {Schema} filepath - Directory to store the data @param {Object} persisterPluginObject - For users who have written their own persister object.
[ "File", "persister", "factory", "method", ".", "Returns", "a", "persister", "object", "." ]
f83321ee93dd8362370fc4ce0790658bead64337
https://github.com/Bandwidth/opkit/blob/f83321ee93dd8362370fc4ce0790658bead64337/lib/Persisters/filepersister.js#L10-L75
train
alliance-pcsg/primo-explore-custom-actions
dist/module.js
addAction
function addAction(action, ctrl) { this.addActionIcon(action, ctrl); if (!this.actionExists(action, ctrl)) { ctrl.actionListService.requiredActionsList.splice(action.index, 0, action.name); ctrl.actionListService.actionsToIndex[action.name] = action.index; ctrl.actionListService.onToggle[action.name] = action.onToggle; ctrl.actionListService.actionsToDisplay.unshift(action.name); } }
javascript
function addAction(action, ctrl) { this.addActionIcon(action, ctrl); if (!this.actionExists(action, ctrl)) { ctrl.actionListService.requiredActionsList.splice(action.index, 0, action.name); ctrl.actionListService.actionsToIndex[action.name] = action.index; ctrl.actionListService.onToggle[action.name] = action.onToggle; ctrl.actionListService.actionsToDisplay.unshift(action.name); } }
[ "function", "addAction", "(", "action", ",", "ctrl", ")", "{", "this", ".", "addActionIcon", "(", "action", ",", "ctrl", ")", ";", "if", "(", "!", "this", ".", "actionExists", "(", "action", ",", "ctrl", ")", ")", "{", "ctrl", ".", "actionListService", ".", "requiredActionsList", ".", "splice", "(", "action", ".", "index", ",", "0", ",", "action", ".", "name", ")", ";", "ctrl", ".", "actionListService", ".", "actionsToIndex", "[", "action", ".", "name", "]", "=", "action", ".", "index", ";", "ctrl", ".", "actionListService", ".", "onToggle", "[", "action", ".", "name", "]", "=", "action", ".", "onToggle", ";", "ctrl", ".", "actionListService", ".", "actionsToDisplay", ".", "unshift", "(", "action", ".", "name", ")", ";", "}", "}" ]
Adds an action to the actions menu, including its icon. @param {object} action action object @param {object} ctrl instance of prmActionCtrl TODO coerce action.index to be <= requiredActionsList.length
[ "Adds", "an", "action", "to", "the", "actions", "menu", "including", "its", "icon", "." ]
f5457699d27c0b76e61aab584eb4065a7a985b9d
https://github.com/alliance-pcsg/primo-explore-custom-actions/blob/f5457699d27c0b76e61aab584eb4065a7a985b9d/dist/module.js#L50-L58
train
alliance-pcsg/primo-explore-custom-actions
dist/module.js
removeAction
function removeAction(action, ctrl) { if (this.actionExists(action, ctrl)) { this.removeActionIcon(action, ctrl); delete ctrl.actionListService.actionsToIndex[action.name]; delete ctrl.actionListService.onToggle[action.name]; var i = ctrl.actionListService.actionsToDisplay.indexOf(action.name); ctrl.actionListService.actionsToDisplay.splice(i, 1); i = ctrl.actionListService.requiredActionsList.indexOf(action.name); ctrl.actionListService.requiredActionsList.splice(i, 1); } }
javascript
function removeAction(action, ctrl) { if (this.actionExists(action, ctrl)) { this.removeActionIcon(action, ctrl); delete ctrl.actionListService.actionsToIndex[action.name]; delete ctrl.actionListService.onToggle[action.name]; var i = ctrl.actionListService.actionsToDisplay.indexOf(action.name); ctrl.actionListService.actionsToDisplay.splice(i, 1); i = ctrl.actionListService.requiredActionsList.indexOf(action.name); ctrl.actionListService.requiredActionsList.splice(i, 1); } }
[ "function", "removeAction", "(", "action", ",", "ctrl", ")", "{", "if", "(", "this", ".", "actionExists", "(", "action", ",", "ctrl", ")", ")", "{", "this", ".", "removeActionIcon", "(", "action", ",", "ctrl", ")", ";", "delete", "ctrl", ".", "actionListService", ".", "actionsToIndex", "[", "action", ".", "name", "]", ";", "delete", "ctrl", ".", "actionListService", ".", "onToggle", "[", "action", ".", "name", "]", ";", "var", "i", "=", "ctrl", ".", "actionListService", ".", "actionsToDisplay", ".", "indexOf", "(", "action", ".", "name", ")", ";", "ctrl", ".", "actionListService", ".", "actionsToDisplay", ".", "splice", "(", "i", ",", "1", ")", ";", "i", "=", "ctrl", ".", "actionListService", ".", "requiredActionsList", ".", "indexOf", "(", "action", ".", "name", ")", ";", "ctrl", ".", "actionListService", ".", "requiredActionsList", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "}" ]
Removes an action from the actions menu, including its icon. @param {object} action action object @param {object} ctrl instance of prmActionCtrl
[ "Removes", "an", "action", "from", "the", "actions", "menu", "including", "its", "icon", "." ]
f5457699d27c0b76e61aab584eb4065a7a985b9d
https://github.com/alliance-pcsg/primo-explore-custom-actions/blob/f5457699d27c0b76e61aab584eb4065a7a985b9d/dist/module.js#L64-L74
train
Bandwidth/opkit
lib/ec2.js
dataFormatter
function dataFormatter(data) { var instanceInfoArray = []; var instanceInfoObject = {}; var reservations = data.Reservations; for (var reservation in reservations) { var instances = reservations[reservation].Instances; for (var instance in instances) { var tags = instances[instance].Tags; for (var tag in tags) { if (tags[tag].Key === 'Name') { instanceInfoObject = _.assign(instanceInfoObject, {Name: tags[tag].Value}); } } instanceInfoObject = _.assign(instanceInfoObject, {State: instances[instance].State.Name}, {id: instances[instance].InstanceId}); instanceInfoArray.push(instanceInfoObject); instanceInfoObject = {}; } } return Promise.resolve(instanceInfoArray); }
javascript
function dataFormatter(data) { var instanceInfoArray = []; var instanceInfoObject = {}; var reservations = data.Reservations; for (var reservation in reservations) { var instances = reservations[reservation].Instances; for (var instance in instances) { var tags = instances[instance].Tags; for (var tag in tags) { if (tags[tag].Key === 'Name') { instanceInfoObject = _.assign(instanceInfoObject, {Name: tags[tag].Value}); } } instanceInfoObject = _.assign(instanceInfoObject, {State: instances[instance].State.Name}, {id: instances[instance].InstanceId}); instanceInfoArray.push(instanceInfoObject); instanceInfoObject = {}; } } return Promise.resolve(instanceInfoArray); }
[ "function", "dataFormatter", "(", "data", ")", "{", "var", "instanceInfoArray", "=", "[", "]", ";", "var", "instanceInfoObject", "=", "{", "}", ";", "var", "reservations", "=", "data", ".", "Reservations", ";", "for", "(", "var", "reservation", "in", "reservations", ")", "{", "var", "instances", "=", "reservations", "[", "reservation", "]", ".", "Instances", ";", "for", "(", "var", "instance", "in", "instances", ")", "{", "var", "tags", "=", "instances", "[", "instance", "]", ".", "Tags", ";", "for", "(", "var", "tag", "in", "tags", ")", "{", "if", "(", "tags", "[", "tag", "]", ".", "Key", "===", "'Name'", ")", "{", "instanceInfoObject", "=", "_", ".", "assign", "(", "instanceInfoObject", ",", "{", "Name", ":", "tags", "[", "tag", "]", ".", "Value", "}", ")", ";", "}", "}", "instanceInfoObject", "=", "_", ".", "assign", "(", "instanceInfoObject", ",", "{", "State", ":", "instances", "[", "instance", "]", ".", "State", ".", "Name", "}", ",", "{", "id", ":", "instances", "[", "instance", "]", ".", "InstanceId", "}", ")", ";", "instanceInfoArray", ".", "push", "(", "instanceInfoObject", ")", ";", "instanceInfoObject", "=", "{", "}", ";", "}", "}", "return", "Promise", ".", "resolve", "(", "instanceInfoArray", ")", ";", "}" ]
Helper function to format data returned by AWS EC2 queries.
[ "Helper", "function", "to", "format", "data", "returned", "by", "AWS", "EC2", "queries", "." ]
f83321ee93dd8362370fc4ce0790658bead64337
https://github.com/Bandwidth/opkit/blob/f83321ee93dd8362370fc4ce0790658bead64337/lib/ec2.js#L264-L287
train
jcreigno/nodejs-file-extractor
lib/main.js
Extractor
function Extractor(ac , options) { EventEmitter.call(this); var self = this; self.matchers = []; self.vars = ac || {}; self.options = options || {}; self.watchers = []; self._listen = function (car, file) { car.once('end', function () { self.emit('end', self.vars); }); car.on('line', function (line) { var i; var firstMatch = true; for (i = 0; i < self.matchers.length; i++) { var matcher = self.matchers[i]; var m; while(matcher.handler && (m = matcher.re.exec(line)) !== null){ matcher.handler(m, self.vars, file , firstMatch); firstMatch = false; if(!self.options.successive){ i = self.matchers.length; break; } } } }); return self; }; }
javascript
function Extractor(ac , options) { EventEmitter.call(this); var self = this; self.matchers = []; self.vars = ac || {}; self.options = options || {}; self.watchers = []; self._listen = function (car, file) { car.once('end', function () { self.emit('end', self.vars); }); car.on('line', function (line) { var i; var firstMatch = true; for (i = 0; i < self.matchers.length; i++) { var matcher = self.matchers[i]; var m; while(matcher.handler && (m = matcher.re.exec(line)) !== null){ matcher.handler(m, self.vars, file , firstMatch); firstMatch = false; if(!self.options.successive){ i = self.matchers.length; break; } } } }); return self; }; }
[ "function", "Extractor", "(", "ac", ",", "options", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "var", "self", "=", "this", ";", "self", ".", "matchers", "=", "[", "]", ";", "self", ".", "vars", "=", "ac", "||", "{", "}", ";", "self", ".", "options", "=", "options", "||", "{", "}", ";", "self", ".", "watchers", "=", "[", "]", ";", "self", ".", "_listen", "=", "function", "(", "car", ",", "file", ")", "{", "car", ".", "once", "(", "'end'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'end'", ",", "self", ".", "vars", ")", ";", "}", ")", ";", "car", ".", "on", "(", "'line'", ",", "function", "(", "line", ")", "{", "var", "i", ";", "var", "firstMatch", "=", "true", ";", "for", "(", "i", "=", "0", ";", "i", "<", "self", ".", "matchers", ".", "length", ";", "i", "++", ")", "{", "var", "matcher", "=", "self", ".", "matchers", "[", "i", "]", ";", "var", "m", ";", "while", "(", "matcher", ".", "handler", "&&", "(", "m", "=", "matcher", ".", "re", ".", "exec", "(", "line", ")", ")", "!==", "null", ")", "{", "matcher", ".", "handler", "(", "m", ",", "self", ".", "vars", ",", "file", ",", "firstMatch", ")", ";", "firstMatch", "=", "false", ";", "if", "(", "!", "self", ".", "options", ".", "successive", ")", "{", "i", "=", "self", ".", "matchers", ".", "length", ";", "break", ";", "}", "}", "}", "}", ")", ";", "return", "self", ";", "}", ";", "}" ]
Extractor Object.
[ "Extractor", "Object", "." ]
ce071d1a50eed08e0e593d0609de8b61da320280
https://github.com/jcreigno/nodejs-file-extractor/blob/ce071d1a50eed08e0e593d0609de8b61da320280/lib/main.js#L13-L42
train
jcreigno/nodejs-file-extractor
lib/main.js
wildcards
function wildcards(f, cb, ctxt) { var starmatch = f.match(/([^*]*)\*.*/); if (!starmatch) { //keep async process.nextTick(function () { cb.apply(ctxt, [f]); }); return; } var basedirPath = starmatch[1].split(/\//); basedirPath.pop(); var wkdir = basedirPath.join('/'); //console.log('search base : %s', wkdir); var r = f.substring(wkdir.length + 1); //console.log('match pattern: %s', r); glob(r, { cwd: wkdir }, function (err, matches) { if (err) { ctxt.emit('error', err); } else { console.log(matches); matches.forEach(function (f) { cb.apply(ctxt, [path.join(wkdir, f)]); }); } }); }
javascript
function wildcards(f, cb, ctxt) { var starmatch = f.match(/([^*]*)\*.*/); if (!starmatch) { //keep async process.nextTick(function () { cb.apply(ctxt, [f]); }); return; } var basedirPath = starmatch[1].split(/\//); basedirPath.pop(); var wkdir = basedirPath.join('/'); //console.log('search base : %s', wkdir); var r = f.substring(wkdir.length + 1); //console.log('match pattern: %s', r); glob(r, { cwd: wkdir }, function (err, matches) { if (err) { ctxt.emit('error', err); } else { console.log(matches); matches.forEach(function (f) { cb.apply(ctxt, [path.join(wkdir, f)]); }); } }); }
[ "function", "wildcards", "(", "f", ",", "cb", ",", "ctxt", ")", "{", "var", "starmatch", "=", "f", ".", "match", "(", "/", "([^*]*)\\*.*", "/", ")", ";", "if", "(", "!", "starmatch", ")", "{", "process", ".", "nextTick", "(", "function", "(", ")", "{", "cb", ".", "apply", "(", "ctxt", ",", "[", "f", "]", ")", ";", "}", ")", ";", "return", ";", "}", "var", "basedirPath", "=", "starmatch", "[", "1", "]", ".", "split", "(", "/", "\\/", "/", ")", ";", "basedirPath", ".", "pop", "(", ")", ";", "var", "wkdir", "=", "basedirPath", ".", "join", "(", "'/'", ")", ";", "var", "r", "=", "f", ".", "substring", "(", "wkdir", ".", "length", "+", "1", ")", ";", "glob", "(", "r", ",", "{", "cwd", ":", "wkdir", "}", ",", "function", "(", "err", ",", "matches", ")", "{", "if", "(", "err", ")", "{", "ctxt", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", "else", "{", "console", ".", "log", "(", "matches", ")", ";", "matches", ".", "forEach", "(", "function", "(", "f", ")", "{", "cb", ".", "apply", "(", "ctxt", ",", "[", "path", ".", "join", "(", "wkdir", ",", "f", ")", "]", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
handle wildcards in filenames @param f: filename. @param cb : callback when a matching file is found. @param ctxt : callback invocation context.
[ "handle", "wildcards", "in", "filenames" ]
ce071d1a50eed08e0e593d0609de8b61da320280
https://github.com/jcreigno/nodejs-file-extractor/blob/ce071d1a50eed08e0e593d0609de8b61da320280/lib/main.js#L81-L108
train
SpoonX/Censoring
index.js
Censoring
function Censoring() { /** * The string to replaces found matches with. Defaults to *** * * @type {String} */ this.replacementString = '***'; /** * The color used for highlighting * * @type {string} */ this.highlightColor = 'F2B8B8'; /** * Holds the currently matched text. * * @type {{replace: string, hasMatches: boolean}} */ this.currentMatch = { replace: '', hasMatches: false, matches: [] }; /** * The available patterns. These are as follows: * [name] [description] * - long_number ; Matches long, consecutive numbers * - phone_number ; Matches phone numbers. * - email_address ; Matches email addresses in many formats. * - url ; Matches URL patterns/ * - words ; Finds words, even when in disguise. * * @type {{long_number: {pattern: RegExp, enabled: boolean}, phone_number: {pattern: RegExp, enabled: boolean}, email_address: {pattern: RegExp, enabled: boolean}, url: {pattern: RegExp, enabled: boolean}, words: {enabled: boolean, pattern: Array}}} */ this.patterns = { long_number: { pattern: /\d{8,}/, enabled: false }, phone_number: { pattern: /([+-]?[\d]{1,}[\d\s-]+|\([\d]+\))[-\d.\s]{8,}/gi, enabled: false }, email_address: { pattern: /[\w._%+-]+(@|\[at\]|\(at\))[\w.-]+(\.|\[dot\]|\(dot\)|\(punt\)|\[punt\])[a-zA-Z]{2,4}/gi, enabled: false }, url: { pattern: /((https?:\/{1,2})?([-\w]\.{0,1}){2,}(\.|\[dot\]|\(dot\)|\(punt\)|\[punt\])([a-zA-Z]{2}\.[a-zA-Z]{2,3}|[a-zA-Z]{2,4}).*?(?=$|[^\w\/-]))/gi, enabled: false }, words: { pattern: [], enabled: false } }; /** * A mapping that maps regular characters to 1337 characters. * * @type {{o: string, g: string, b: Array, t: string, s: string, a: string, e: string, z: string, i: string, l: string}} */ this.map1337 = { o: '0', g: '9', b: ['8', '6'], t: '7', s: '5', a: '4', e: '3', z: '2', i: '1', l: '1' }; }
javascript
function Censoring() { /** * The string to replaces found matches with. Defaults to *** * * @type {String} */ this.replacementString = '***'; /** * The color used for highlighting * * @type {string} */ this.highlightColor = 'F2B8B8'; /** * Holds the currently matched text. * * @type {{replace: string, hasMatches: boolean}} */ this.currentMatch = { replace: '', hasMatches: false, matches: [] }; /** * The available patterns. These are as follows: * [name] [description] * - long_number ; Matches long, consecutive numbers * - phone_number ; Matches phone numbers. * - email_address ; Matches email addresses in many formats. * - url ; Matches URL patterns/ * - words ; Finds words, even when in disguise. * * @type {{long_number: {pattern: RegExp, enabled: boolean}, phone_number: {pattern: RegExp, enabled: boolean}, email_address: {pattern: RegExp, enabled: boolean}, url: {pattern: RegExp, enabled: boolean}, words: {enabled: boolean, pattern: Array}}} */ this.patterns = { long_number: { pattern: /\d{8,}/, enabled: false }, phone_number: { pattern: /([+-]?[\d]{1,}[\d\s-]+|\([\d]+\))[-\d.\s]{8,}/gi, enabled: false }, email_address: { pattern: /[\w._%+-]+(@|\[at\]|\(at\))[\w.-]+(\.|\[dot\]|\(dot\)|\(punt\)|\[punt\])[a-zA-Z]{2,4}/gi, enabled: false }, url: { pattern: /((https?:\/{1,2})?([-\w]\.{0,1}){2,}(\.|\[dot\]|\(dot\)|\(punt\)|\[punt\])([a-zA-Z]{2}\.[a-zA-Z]{2,3}|[a-zA-Z]{2,4}).*?(?=$|[^\w\/-]))/gi, enabled: false }, words: { pattern: [], enabled: false } }; /** * A mapping that maps regular characters to 1337 characters. * * @type {{o: string, g: string, b: Array, t: string, s: string, a: string, e: string, z: string, i: string, l: string}} */ this.map1337 = { o: '0', g: '9', b: ['8', '6'], t: '7', s: '5', a: '4', e: '3', z: '2', i: '1', l: '1' }; }
[ "function", "Censoring", "(", ")", "{", "this", ".", "replacementString", "=", "'***'", ";", "this", ".", "highlightColor", "=", "'F2B8B8'", ";", "this", ".", "currentMatch", "=", "{", "replace", ":", "''", ",", "hasMatches", ":", "false", ",", "matches", ":", "[", "]", "}", ";", "this", ".", "patterns", "=", "{", "long_number", ":", "{", "pattern", ":", "/", "\\d{8,}", "/", ",", "enabled", ":", "false", "}", ",", "phone_number", ":", "{", "pattern", ":", "/", "([+-]?[\\d]{1,}[\\d\\s-]+|\\([\\d]+\\))[-\\d.\\s]{8,}", "/", "gi", ",", "enabled", ":", "false", "}", ",", "email_address", ":", "{", "pattern", ":", "/", "[\\w._%+-]+(@|\\[at\\]|\\(at\\))[\\w.-]+(\\.|\\[dot\\]|\\(dot\\)|\\(punt\\)|\\[punt\\])[a-zA-Z]{2,4}", "/", "gi", ",", "enabled", ":", "false", "}", ",", "url", ":", "{", "pattern", ":", "/", "((https?:\\/{1,2})?([-\\w]\\.{0,1}){2,}(\\.|\\[dot\\]|\\(dot\\)|\\(punt\\)|\\[punt\\])([a-zA-Z]{2}\\.[a-zA-Z]{2,3}|[a-zA-Z]{2,4}).*?(?=$|[^\\w\\/-]))", "/", "gi", ",", "enabled", ":", "false", "}", ",", "words", ":", "{", "pattern", ":", "[", "]", ",", "enabled", ":", "false", "}", "}", ";", "this", ".", "map1337", "=", "{", "o", ":", "'0'", ",", "g", ":", "'9'", ",", "b", ":", "[", "'8'", ",", "'6'", "]", ",", "t", ":", "'7'", ",", "s", ":", "'5'", ",", "a", ":", "'4'", ",", "e", ":", "'3'", ",", "z", ":", "'2'", ",", "i", ":", "'1'", ",", "l", ":", "'1'", "}", ";", "}" ]
The Censoring object constructor. @constructor
[ "The", "Censoring", "object", "constructor", "." ]
9ffc8c42d67a5773f6a09821a3f84b7482b41f3c
https://github.com/SpoonX/Censoring/blob/9ffc8c42d67a5773f6a09821a3f84b7482b41f3c/index.js#L9-L87
train
SpoonX/Censoring
index.js
function (filters) { if (!this.isArray(filters)) { throw 'Invalid filters type supplied. Expected Array.'; } for (var i = 0; i < filters.length; i++) { this.enableFilter(filters[i]); } return this; }
javascript
function (filters) { if (!this.isArray(filters)) { throw 'Invalid filters type supplied. Expected Array.'; } for (var i = 0; i < filters.length; i++) { this.enableFilter(filters[i]); } return this; }
[ "function", "(", "filters", ")", "{", "if", "(", "!", "this", ".", "isArray", "(", "filters", ")", ")", "{", "throw", "'Invalid filters type supplied. Expected Array.'", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "filters", ".", "length", ";", "i", "++", ")", "{", "this", ".", "enableFilter", "(", "filters", "[", "i", "]", ")", ";", "}", "return", "this", ";", "}" ]
Enable multiple filters at once. @param {Array} filters @returns {Censoring} @see Censoring.enableFilter
[ "Enable", "multiple", "filters", "at", "once", "." ]
9ffc8c42d67a5773f6a09821a3f84b7482b41f3c
https://github.com/SpoonX/Censoring/blob/9ffc8c42d67a5773f6a09821a3f84b7482b41f3c/index.js#L142-L152
train
SpoonX/Censoring
index.js
function (words) { if (!this.isArray(words)) { throw 'Invalid type supplied for addFilterWords. Expected array.'; } for (var i = 0; i < words.length; i++) { this.addFilterWord(words[i]); } return this; }
javascript
function (words) { if (!this.isArray(words)) { throw 'Invalid type supplied for addFilterWords. Expected array.'; } for (var i = 0; i < words.length; i++) { this.addFilterWord(words[i]); } return this; }
[ "function", "(", "words", ")", "{", "if", "(", "!", "this", ".", "isArray", "(", "words", ")", ")", "{", "throw", "'Invalid type supplied for addFilterWords. Expected array.'", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "words", ".", "length", ";", "i", "++", ")", "{", "this", ".", "addFilterWord", "(", "words", "[", "i", "]", ")", ";", "}", "return", "this", ";", "}" ]
Add multiple filterWords. @param {[]} words @returns {Censoring}
[ "Add", "multiple", "filterWords", "." ]
9ffc8c42d67a5773f6a09821a3f84b7482b41f3c
https://github.com/SpoonX/Censoring/blob/9ffc8c42d67a5773f6a09821a3f84b7482b41f3c/index.js#L176-L186
train
SpoonX/Censoring
index.js
function (word) { var pattern = '', any = '[^a-z0-9]?', last = false, character; for (var i = 0; i < word.length; i++) { last = i === (word.length - 1); character = word.charAt(i); if (typeof this.map1337[character] === 'undefined') { pattern += (character + (!last ? any : '')); continue; } if (typeof this.map1337[character] === 'string') { pattern += ('((' + character + '|' + this.map1337[character] + ')' + (!last ? any : '') + ')'); continue; } pattern += '((' + character; for (var m = 0; m < this.map1337[character].length; m++) { pattern += '|' + this.map1337[character][m]; } pattern += ')' + (!last ? any : '') + ')'; } this.patterns.words.pattern.push(new RegExp(pattern, 'ig')); return this; }
javascript
function (word) { var pattern = '', any = '[^a-z0-9]?', last = false, character; for (var i = 0; i < word.length; i++) { last = i === (word.length - 1); character = word.charAt(i); if (typeof this.map1337[character] === 'undefined') { pattern += (character + (!last ? any : '')); continue; } if (typeof this.map1337[character] === 'string') { pattern += ('((' + character + '|' + this.map1337[character] + ')' + (!last ? any : '') + ')'); continue; } pattern += '((' + character; for (var m = 0; m < this.map1337[character].length; m++) { pattern += '|' + this.map1337[character][m]; } pattern += ')' + (!last ? any : '') + ')'; } this.patterns.words.pattern.push(new RegExp(pattern, 'ig')); return this; }
[ "function", "(", "word", ")", "{", "var", "pattern", "=", "''", ",", "any", "=", "'[^a-z0-9]?'", ",", "last", "=", "false", ",", "character", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "word", ".", "length", ";", "i", "++", ")", "{", "last", "=", "i", "===", "(", "word", ".", "length", "-", "1", ")", ";", "character", "=", "word", ".", "charAt", "(", "i", ")", ";", "if", "(", "typeof", "this", ".", "map1337", "[", "character", "]", "===", "'undefined'", ")", "{", "pattern", "+=", "(", "character", "+", "(", "!", "last", "?", "any", ":", "''", ")", ")", ";", "continue", ";", "}", "if", "(", "typeof", "this", ".", "map1337", "[", "character", "]", "===", "'string'", ")", "{", "pattern", "+=", "(", "'(('", "+", "character", "+", "'|'", "+", "this", ".", "map1337", "[", "character", "]", "+", "')'", "+", "(", "!", "last", "?", "any", ":", "''", ")", "+", "')'", ")", ";", "continue", ";", "}", "pattern", "+=", "'(('", "+", "character", ";", "for", "(", "var", "m", "=", "0", ";", "m", "<", "this", ".", "map1337", "[", "character", "]", ".", "length", ";", "m", "++", ")", "{", "pattern", "+=", "'|'", "+", "this", ".", "map1337", "[", "character", "]", "[", "m", "]", ";", "}", "pattern", "+=", "')'", "+", "(", "!", "last", "?", "any", ":", "''", ")", "+", "')'", ";", "}", "this", ".", "patterns", ".", "words", ".", "pattern", ".", "push", "(", "new", "RegExp", "(", "pattern", ",", "'ig'", ")", ")", ";", "return", "this", ";", "}" ]
Add a word to filter out. @param {String} word @returns {Censoring}
[ "Add", "a", "word", "to", "filter", "out", "." ]
9ffc8c42d67a5773f6a09821a3f84b7482b41f3c
https://github.com/SpoonX/Censoring/blob/9ffc8c42d67a5773f6a09821a3f84b7482b41f3c/index.js#L194-L228
train
SpoonX/Censoring
index.js
function (str, highlight) { this.currentMatch.replace = this.filterString(str, highlight); this.currentMatch.hasMatches = str !== this.currentMatch.replace; return this; }
javascript
function (str, highlight) { this.currentMatch.replace = this.filterString(str, highlight); this.currentMatch.hasMatches = str !== this.currentMatch.replace; return this; }
[ "function", "(", "str", ",", "highlight", ")", "{", "this", ".", "currentMatch", ".", "replace", "=", "this", ".", "filterString", "(", "str", ",", "highlight", ")", ";", "this", ".", "currentMatch", ".", "hasMatches", "=", "str", "!==", "this", ".", "currentMatch", ".", "replace", ";", "return", "this", ";", "}" ]
Prepare some text to be matched against. @param {String} str @param {Boolean} highlight @returns {Censoring}
[ "Prepare", "some", "text", "to", "be", "matched", "against", "." ]
9ffc8c42d67a5773f6a09821a3f84b7482b41f3c
https://github.com/SpoonX/Censoring/blob/9ffc8c42d67a5773f6a09821a3f84b7482b41f3c/index.js#L269-L274
train
SpoonX/Censoring
index.js
function (str, highlight) { highlight = highlight || false; var self = this; var highlightColor = this.highlightColor; var replace = function (str, pattern) { if (!highlight) { return str.replace(pattern, function (match) { self.currentMatch.matches.push(match); return self.replacementString; }); } return str.replace(pattern, function (match) { self.currentMatch.matches.push(match); return '<span style="background: #' + highlightColor + ';">' + match + '</span>'; }); }.bind(this); if (typeof str !== 'string') { throw 'Invalid "str" type supplied in filterString. Expected string.'; } for (var p in this.patterns) { if (!this.patterns[p].enabled) { continue; } if (this.patterns[p].pattern instanceof RegExp) { str = replace(str, this.patterns[p].pattern); continue; } if (!this.isArray(this.patterns[p].pattern)) { throw 'Invalid pattern type supplied. Expected Array.'; } for (var i = 0; i < this.patterns[p].pattern.length; i++) { if (!this.patterns[p].pattern[i] instanceof RegExp) { throw 'Expected valid RegExp.'; } str = replace(str, this.patterns[p].pattern[i]); } } return str; }
javascript
function (str, highlight) { highlight = highlight || false; var self = this; var highlightColor = this.highlightColor; var replace = function (str, pattern) { if (!highlight) { return str.replace(pattern, function (match) { self.currentMatch.matches.push(match); return self.replacementString; }); } return str.replace(pattern, function (match) { self.currentMatch.matches.push(match); return '<span style="background: #' + highlightColor + ';">' + match + '</span>'; }); }.bind(this); if (typeof str !== 'string') { throw 'Invalid "str" type supplied in filterString. Expected string.'; } for (var p in this.patterns) { if (!this.patterns[p].enabled) { continue; } if (this.patterns[p].pattern instanceof RegExp) { str = replace(str, this.patterns[p].pattern); continue; } if (!this.isArray(this.patterns[p].pattern)) { throw 'Invalid pattern type supplied. Expected Array.'; } for (var i = 0; i < this.patterns[p].pattern.length; i++) { if (!this.patterns[p].pattern[i] instanceof RegExp) { throw 'Expected valid RegExp.'; } str = replace(str, this.patterns[p].pattern[i]); } } return str; }
[ "function", "(", "str", ",", "highlight", ")", "{", "highlight", "=", "highlight", "||", "false", ";", "var", "self", "=", "this", ";", "var", "highlightColor", "=", "this", ".", "highlightColor", ";", "var", "replace", "=", "function", "(", "str", ",", "pattern", ")", "{", "if", "(", "!", "highlight", ")", "{", "return", "str", ".", "replace", "(", "pattern", ",", "function", "(", "match", ")", "{", "self", ".", "currentMatch", ".", "matches", ".", "push", "(", "match", ")", ";", "return", "self", ".", "replacementString", ";", "}", ")", ";", "}", "return", "str", ".", "replace", "(", "pattern", ",", "function", "(", "match", ")", "{", "self", ".", "currentMatch", ".", "matches", ".", "push", "(", "match", ")", ";", "return", "'<span style=\"background: #'", "+", "highlightColor", "+", "';\">'", "+", "match", "+", "'</span>'", ";", "}", ")", ";", "}", ".", "bind", "(", "this", ")", ";", "if", "(", "typeof", "str", "!==", "'string'", ")", "{", "throw", "'Invalid \"str\" type supplied in filterString. Expected string.'", ";", "}", "for", "(", "var", "p", "in", "this", ".", "patterns", ")", "{", "if", "(", "!", "this", ".", "patterns", "[", "p", "]", ".", "enabled", ")", "{", "continue", ";", "}", "if", "(", "this", ".", "patterns", "[", "p", "]", ".", "pattern", "instanceof", "RegExp", ")", "{", "str", "=", "replace", "(", "str", ",", "this", ".", "patterns", "[", "p", "]", ".", "pattern", ")", ";", "continue", ";", "}", "if", "(", "!", "this", ".", "isArray", "(", "this", ".", "patterns", "[", "p", "]", ".", "pattern", ")", ")", "{", "throw", "'Invalid pattern type supplied. Expected Array.'", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "patterns", "[", "p", "]", ".", "pattern", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "this", ".", "patterns", "[", "p", "]", ".", "pattern", "[", "i", "]", "instanceof", "RegExp", ")", "{", "throw", "'Expected valid RegExp.'", ";", "}", "str", "=", "replace", "(", "str", ",", "this", ".", "patterns", "[", "p", "]", ".", "pattern", "[", "i", "]", ")", ";", "}", "}", "return", "str", ";", "}" ]
Filter the string. @param {String} str @param {Boolean} highlight @returns {String}}
[ "Filter", "the", "string", "." ]
9ffc8c42d67a5773f6a09821a3f84b7482b41f3c
https://github.com/SpoonX/Censoring/blob/9ffc8c42d67a5773f6a09821a3f84b7482b41f3c/index.js#L292-L340
train
ipetez/react-create
src/scripts/component.js
addCssExtension
function addCssExtension(args, styleExts, extensions) { for (let x = 0, len = args.length; x < len; x++) { if (styleExts.includes(args[x])) { extensions.push('.' + args[x].slice(2)); } } }
javascript
function addCssExtension(args, styleExts, extensions) { for (let x = 0, len = args.length; x < len; x++) { if (styleExts.includes(args[x])) { extensions.push('.' + args[x].slice(2)); } } }
[ "function", "addCssExtension", "(", "args", ",", "styleExts", ",", "extensions", ")", "{", "for", "(", "let", "x", "=", "0", ",", "len", "=", "args", ".", "length", ";", "x", "<", "len", ";", "x", "++", ")", "{", "if", "(", "styleExts", ".", "includes", "(", "args", "[", "x", "]", ")", ")", "{", "extensions", ".", "push", "(", "'.'", "+", "args", "[", "x", "]", ".", "slice", "(", "2", ")", ")", ";", "}", "}", "}" ]
Grabbing style extension from arguments and adding to full list of extensions
[ "Grabbing", "style", "extension", "from", "arguments", "and", "adding", "to", "full", "list", "of", "extensions" ]
1b77954244aab1aac2133fe4bc4fa943d3c2c6d7
https://github.com/ipetez/react-create/blob/1b77954244aab1aac2133fe4bc4fa943d3c2c6d7/src/scripts/component.js#L23-L29
train
strapi/strapi-generate-email
files/api/email/models/Email.js
function (values, next) { const api = path.basename(__filename, '.js').toLowerCase(); if (strapi.api.hasOwnProperty(api) && _.size(strapi.api[api].templates)) { const template = _.includes(strapi.api[api].templates, values.template) ? values.template : strapi.models[api].defaultTemplate; // Set template with correct value values.template = template; // Merge model type with template validations const templateAttributes = _.merge(_.pick(strapi.models[api].attributes, 'lang'), strapi.api[api].templates[template].attributes); const err = []; _.forEach(templateAttributes, function (rules, key) { if (values.hasOwnProperty(key) || key === 'lang') { if (key === 'lang') { // Set lang with correct value values[key] = _.includes(strapi.config.i18n.locales, values[key]) ? values[key] : strapi.config.i18n.defaultLocale; } else { // Check validations const rulesTest = anchor(values[key]).to(rules); if (rulesTest) { err.push(rulesTest[0]); } } } else { rules.required && err.push({ rule: 'required', message: 'Missing attributes ' + key }); } }); // Go next step or not _.isEmpty(err) ? next() : next(err); } else { next(new Error('Unknow API or no template detected')); } }
javascript
function (values, next) { const api = path.basename(__filename, '.js').toLowerCase(); if (strapi.api.hasOwnProperty(api) && _.size(strapi.api[api].templates)) { const template = _.includes(strapi.api[api].templates, values.template) ? values.template : strapi.models[api].defaultTemplate; // Set template with correct value values.template = template; // Merge model type with template validations const templateAttributes = _.merge(_.pick(strapi.models[api].attributes, 'lang'), strapi.api[api].templates[template].attributes); const err = []; _.forEach(templateAttributes, function (rules, key) { if (values.hasOwnProperty(key) || key === 'lang') { if (key === 'lang') { // Set lang with correct value values[key] = _.includes(strapi.config.i18n.locales, values[key]) ? values[key] : strapi.config.i18n.defaultLocale; } else { // Check validations const rulesTest = anchor(values[key]).to(rules); if (rulesTest) { err.push(rulesTest[0]); } } } else { rules.required && err.push({ rule: 'required', message: 'Missing attributes ' + key }); } }); // Go next step or not _.isEmpty(err) ? next() : next(err); } else { next(new Error('Unknow API or no template detected')); } }
[ "function", "(", "values", ",", "next", ")", "{", "const", "api", "=", "path", ".", "basename", "(", "__filename", ",", "'.js'", ")", ".", "toLowerCase", "(", ")", ";", "if", "(", "strapi", ".", "api", ".", "hasOwnProperty", "(", "api", ")", "&&", "_", ".", "size", "(", "strapi", ".", "api", "[", "api", "]", ".", "templates", ")", ")", "{", "const", "template", "=", "_", ".", "includes", "(", "strapi", ".", "api", "[", "api", "]", ".", "templates", ",", "values", ".", "template", ")", "?", "values", ".", "template", ":", "strapi", ".", "models", "[", "api", "]", ".", "defaultTemplate", ";", "values", ".", "template", "=", "template", ";", "const", "templateAttributes", "=", "_", ".", "merge", "(", "_", ".", "pick", "(", "strapi", ".", "models", "[", "api", "]", ".", "attributes", ",", "'lang'", ")", ",", "strapi", ".", "api", "[", "api", "]", ".", "templates", "[", "template", "]", ".", "attributes", ")", ";", "const", "err", "=", "[", "]", ";", "_", ".", "forEach", "(", "templateAttributes", ",", "function", "(", "rules", ",", "key", ")", "{", "if", "(", "values", ".", "hasOwnProperty", "(", "key", ")", "||", "key", "===", "'lang'", ")", "{", "if", "(", "key", "===", "'lang'", ")", "{", "values", "[", "key", "]", "=", "_", ".", "includes", "(", "strapi", ".", "config", ".", "i18n", ".", "locales", ",", "values", "[", "key", "]", ")", "?", "values", "[", "key", "]", ":", "strapi", ".", "config", ".", "i18n", ".", "defaultLocale", ";", "}", "else", "{", "const", "rulesTest", "=", "anchor", "(", "values", "[", "key", "]", ")", ".", "to", "(", "rules", ")", ";", "if", "(", "rulesTest", ")", "{", "err", ".", "push", "(", "rulesTest", "[", "0", "]", ")", ";", "}", "}", "}", "else", "{", "rules", ".", "required", "&&", "err", ".", "push", "(", "{", "rule", ":", "'required'", ",", "message", ":", "'Missing attributes '", "+", "key", "}", ")", ";", "}", "}", ")", ";", "_", ".", "isEmpty", "(", "err", ")", "?", "next", "(", ")", ":", "next", "(", "err", ")", ";", "}", "else", "{", "next", "(", "new", "Error", "(", "'Unknow API or no template detected'", ")", ")", ";", "}", "}" ]
Lifecycle callbacks Before validate
[ "Lifecycle", "callbacks", "Before", "validate" ]
e29983b725d4089364ebe6e5f6449c709bbac51d
https://github.com/strapi/strapi-generate-email/blob/e29983b725d4089364ebe6e5f6449c709bbac51d/files/api/email/models/Email.js#L55-L94
train
jokesterfr/node-pcsc
lib/node-pcsc.js
getItem
function getItem(ATR) { var item; while( item === undefined ) { item = slist[ATR]; if(!ATR) break; ATR = ATR.substring(0, ATR.length-1); } return item; }
javascript
function getItem(ATR) { var item; while( item === undefined ) { item = slist[ATR]; if(!ATR) break; ATR = ATR.substring(0, ATR.length-1); } return item; }
[ "function", "getItem", "(", "ATR", ")", "{", "var", "item", ";", "while", "(", "item", "===", "undefined", ")", "{", "item", "=", "slist", "[", "ATR", "]", ";", "if", "(", "!", "ATR", ")", "break", ";", "ATR", "=", "ATR", ".", "substring", "(", "0", ",", "ATR", ".", "length", "-", "1", ")", ";", "}", "return", "item", ";", "}" ]
Retrieve some more infos about the inserted card @param ATR {String} atr of the inserted card @return {Object} if defined, the card name and info details
[ "Retrieve", "some", "more", "infos", "about", "the", "inserted", "card" ]
8593d1bf784afe1fc605b936de9af266dac02eb1
https://github.com/jokesterfr/node-pcsc/blob/8593d1bf784afe1fc605b936de9af266dac02eb1/lib/node-pcsc.js#L72-L80
train
creamidea/keyboard-js
samples/heatmap.js
Log
function Log(keyboardInfo) { var log = keyboardInfo.querySelector('ul') var st = keyboardInfo.querySelector('.statistic') var totalAvgTime = 0 var totalCount = 0 return function (key, statistic) { var count = statistic.count var average = statistic.average totalCount = totalCount + 1 totalAvgTime = totalAvgTime + statistic.average totalAvg = +(totalAvgTime/totalCount).toFixed(2) || 0 var li = document.createElement('li') li.className = "bounceIn animated" li.innerHTML = '<kbd>'+key+'</kbd><div><p><span class="avg">avg: </span><span class="value">'+average.toFixed(2)+'</span>ms</p><p><span class="count">count: </span><span class="value">'+count+'</span></p></div>' log.insertBefore(li, log.firstChild) // http://callmenick.com/post/prepend-child-javascript if (log.children.length > 10) { log.lastChild.remove() } st.innerHTML = '<div><span class="avg">Total Avg: </span><span class="value">'+totalAvg+' ms</span></div><div><span class="count">Total Count: </span><span class="value">'+totalCount+'</span></div>' } }
javascript
function Log(keyboardInfo) { var log = keyboardInfo.querySelector('ul') var st = keyboardInfo.querySelector('.statistic') var totalAvgTime = 0 var totalCount = 0 return function (key, statistic) { var count = statistic.count var average = statistic.average totalCount = totalCount + 1 totalAvgTime = totalAvgTime + statistic.average totalAvg = +(totalAvgTime/totalCount).toFixed(2) || 0 var li = document.createElement('li') li.className = "bounceIn animated" li.innerHTML = '<kbd>'+key+'</kbd><div><p><span class="avg">avg: </span><span class="value">'+average.toFixed(2)+'</span>ms</p><p><span class="count">count: </span><span class="value">'+count+'</span></p></div>' log.insertBefore(li, log.firstChild) // http://callmenick.com/post/prepend-child-javascript if (log.children.length > 10) { log.lastChild.remove() } st.innerHTML = '<div><span class="avg">Total Avg: </span><span class="value">'+totalAvg+' ms</span></div><div><span class="count">Total Count: </span><span class="value">'+totalCount+'</span></div>' } }
[ "function", "Log", "(", "keyboardInfo", ")", "{", "var", "log", "=", "keyboardInfo", ".", "querySelector", "(", "'ul'", ")", "var", "st", "=", "keyboardInfo", ".", "querySelector", "(", "'.statistic'", ")", "var", "totalAvgTime", "=", "0", "var", "totalCount", "=", "0", "return", "function", "(", "key", ",", "statistic", ")", "{", "var", "count", "=", "statistic", ".", "count", "var", "average", "=", "statistic", ".", "average", "totalCount", "=", "totalCount", "+", "1", "totalAvgTime", "=", "totalAvgTime", "+", "statistic", ".", "average", "totalAvg", "=", "+", "(", "totalAvgTime", "/", "totalCount", ")", ".", "toFixed", "(", "2", ")", "||", "0", "var", "li", "=", "document", ".", "createElement", "(", "'li'", ")", "li", ".", "className", "=", "\"bounceIn animated\"", "li", ".", "innerHTML", "=", "'<kbd>'", "+", "key", "+", "'</kbd><div><p><span class=\"avg\">avg: </span><span class=\"value\">'", "+", "average", ".", "toFixed", "(", "2", ")", "+", "'</span>ms</p><p><span class=\"count\">count: </span><span class=\"value\">'", "+", "count", "+", "'</span></p></div>'", "log", ".", "insertBefore", "(", "li", ",", "log", ".", "firstChild", ")", "if", "(", "log", ".", "children", ".", "length", ">", "10", ")", "{", "log", ".", "lastChild", ".", "remove", "(", ")", "}", "st", ".", "innerHTML", "=", "'<div><span class=\"avg\">Total Avg: </span><span class=\"value\">'", "+", "totalAvg", "+", "' ms</span></div><div><span class=\"count\">Total Count: </span><span class=\"value\">'", "+", "totalCount", "+", "'</span></div>'", "}", "}" ]
canvas.style.zIndex = 10
[ "canvas", ".", "style", ".", "zIndex", "=", "10" ]
71b6f21899eca0154a3fd5494fe5dd5d4db2b887
https://github.com/creamidea/keyboard-js/blob/71b6f21899eca0154a3fd5494fe5dd5d4db2b887/samples/heatmap.js#L40-L61
train
jonschlinkert/read-data
index.js
extname
function extname(ext) { var str = ext.charAt(0) === '.' ? ext.slice(1) : ext; if (str === 'yml') str = 'yaml'; return str; }
javascript
function extname(ext) { var str = ext.charAt(0) === '.' ? ext.slice(1) : ext; if (str === 'yml') str = 'yaml'; return str; }
[ "function", "extname", "(", "ext", ")", "{", "var", "str", "=", "ext", ".", "charAt", "(", "0", ")", "===", "'.'", "?", "ext", ".", "slice", "(", "1", ")", ":", "ext", ";", "if", "(", "str", "===", "'yml'", ")", "str", "=", "'yaml'", ";", "return", "str", ";", "}" ]
Get the extname without leading `.`
[ "Get", "the", "extname", "without", "leading", "." ]
0d9636f9d1d064d57fd0d0e2948bcbd77ba8acfd
https://github.com/jonschlinkert/read-data/blob/0d9636f9d1d064d57fd0d0e2948bcbd77ba8acfd/index.js#L179-L183
train
SimpleRegex/SRL-JavaScript
lib/Language/Helpers/buildQuery.js
buildQuery
function buildQuery(query, builder = new Builder()) { for (let i = 0; i < query.length; i++) { const method = query[i] if (Array.isArray(method)) { builder.and(buildQuery(method, new NonCapture())) continue } if (!method instanceof Method) { // At this point, there should only be methods left, since all parameters are already taken care of. // If that's not the case, something didn't work out. throw new SyntaxException(`Unexpected statement: ${method}`) } const parameters = [] // If there are parameters, walk through them and apply them if they don't start a new method. while (query[i + 1] && !(query[i + 1] instanceof Method)) { parameters.push(query[i + 1]) // Since the parameters will be appended to the method object, they are already parsed and can be // removed from further parsing. Don't use unset to keep keys incrementing. query.splice(i + 1, 1) } try { // Now, append that method to the builder object. method.setParameters(parameters).callMethodOn(builder) } catch (e) { const lastIndex = parameters.length - 1 if (Array.isArray(parameters[lastIndex])) { if (lastIndex !== 0) { method.setParameters(parameters.slice(0, lastIndex)) } method.callMethodOn(builder) builder.and(buildQuery(parameters[lastIndex], new NonCapture())) } else { throw new SyntaxException(`Invalid parameter given for ${method.origin}`) } } } return builder }
javascript
function buildQuery(query, builder = new Builder()) { for (let i = 0; i < query.length; i++) { const method = query[i] if (Array.isArray(method)) { builder.and(buildQuery(method, new NonCapture())) continue } if (!method instanceof Method) { // At this point, there should only be methods left, since all parameters are already taken care of. // If that's not the case, something didn't work out. throw new SyntaxException(`Unexpected statement: ${method}`) } const parameters = [] // If there are parameters, walk through them and apply them if they don't start a new method. while (query[i + 1] && !(query[i + 1] instanceof Method)) { parameters.push(query[i + 1]) // Since the parameters will be appended to the method object, they are already parsed and can be // removed from further parsing. Don't use unset to keep keys incrementing. query.splice(i + 1, 1) } try { // Now, append that method to the builder object. method.setParameters(parameters).callMethodOn(builder) } catch (e) { const lastIndex = parameters.length - 1 if (Array.isArray(parameters[lastIndex])) { if (lastIndex !== 0) { method.setParameters(parameters.slice(0, lastIndex)) } method.callMethodOn(builder) builder.and(buildQuery(parameters[lastIndex], new NonCapture())) } else { throw new SyntaxException(`Invalid parameter given for ${method.origin}`) } } } return builder }
[ "function", "buildQuery", "(", "query", ",", "builder", "=", "new", "Builder", "(", ")", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "query", ".", "length", ";", "i", "++", ")", "{", "const", "method", "=", "query", "[", "i", "]", "if", "(", "Array", ".", "isArray", "(", "method", ")", ")", "{", "builder", ".", "and", "(", "buildQuery", "(", "method", ",", "new", "NonCapture", "(", ")", ")", ")", "continue", "}", "if", "(", "!", "method", "instanceof", "Method", ")", "{", "throw", "new", "SyntaxException", "(", "`", "${", "method", "}", "`", ")", "}", "const", "parameters", "=", "[", "]", "while", "(", "query", "[", "i", "+", "1", "]", "&&", "!", "(", "query", "[", "i", "+", "1", "]", "instanceof", "Method", ")", ")", "{", "parameters", ".", "push", "(", "query", "[", "i", "+", "1", "]", ")", "query", ".", "splice", "(", "i", "+", "1", ",", "1", ")", "}", "try", "{", "method", ".", "setParameters", "(", "parameters", ")", ".", "callMethodOn", "(", "builder", ")", "}", "catch", "(", "e", ")", "{", "const", "lastIndex", "=", "parameters", ".", "length", "-", "1", "if", "(", "Array", ".", "isArray", "(", "parameters", "[", "lastIndex", "]", ")", ")", "{", "if", "(", "lastIndex", "!==", "0", ")", "{", "method", ".", "setParameters", "(", "parameters", ".", "slice", "(", "0", ",", "lastIndex", ")", ")", "}", "method", ".", "callMethodOn", "(", "builder", ")", "builder", ".", "and", "(", "buildQuery", "(", "parameters", "[", "lastIndex", "]", ",", "new", "NonCapture", "(", ")", ")", ")", "}", "else", "{", "throw", "new", "SyntaxException", "(", "`", "${", "method", ".", "origin", "}", "`", ")", "}", "}", "}", "return", "builder", "}" ]
After the query was resolved, it can be built and thus executed. @param array $query @param Builder|null $builder If no Builder is given, the default Builder will be taken. @return Builder @throws SyntaxException
[ "After", "the", "query", "was", "resolved", "it", "can", "be", "built", "and", "thus", "executed", "." ]
eb2f0576ec49076e95fc2adec57e10d83c24d438
https://github.com/SimpleRegex/SRL-JavaScript/blob/eb2f0576ec49076e95fc2adec57e10d83c24d438/lib/Language/Helpers/buildQuery.js#L16-L59
train
nhn/tui.dom
src/js/domutil.js
setClassName
function setClassName(element, cssClass) { cssClass = snippet.isArray(cssClass) ? cssClass.join(' ') : cssClass; cssClass = trim(cssClass); if (snippet.isUndefined(element.className.baseVal)) { element.className = cssClass; return; } element.className.baseVal = cssClass; }
javascript
function setClassName(element, cssClass) { cssClass = snippet.isArray(cssClass) ? cssClass.join(' ') : cssClass; cssClass = trim(cssClass); if (snippet.isUndefined(element.className.baseVal)) { element.className = cssClass; return; } element.className.baseVal = cssClass; }
[ "function", "setClassName", "(", "element", ",", "cssClass", ")", "{", "cssClass", "=", "snippet", ".", "isArray", "(", "cssClass", ")", "?", "cssClass", ".", "join", "(", "' '", ")", ":", "cssClass", ";", "cssClass", "=", "trim", "(", "cssClass", ")", ";", "if", "(", "snippet", ".", "isUndefined", "(", "element", ".", "className", ".", "baseVal", ")", ")", "{", "element", ".", "className", "=", "cssClass", ";", "return", ";", "}", "element", ".", "className", ".", "baseVal", "=", "cssClass", ";", "}" ]
Set className value @param {(HTMLElement|SVGElement)} element - target element @param {(string|string[])} cssClass - class names @ignore
[ "Set", "className", "value" ]
beafe74afb8f647d770e202894ecc9c2dc0ca2b5
https://github.com/nhn/tui.dom/blob/beafe74afb8f647d770e202894ecc9c2dc0ca2b5/src/js/domutil.js#L82-L94
train
kozhevnikov/jsdoc-memberof-namespace
index.js
getNamespace
function getNamespace(file, path) { const files = namespaces.filter(ns => ns.meta.filename === file && ns.meta.path === path); if (files.length > 0) { return files[files.length - 1]; } const paths = namespaces.filter(ns => isIndex(ns.meta.filename) && isParent(ns.meta.path, path)); if (paths.length > 0) { paths.sort((ns1, ns2) => ns1.meta.path.length - ns2.meta.path.length); return paths[paths.length - 1]; } return null; }
javascript
function getNamespace(file, path) { const files = namespaces.filter(ns => ns.meta.filename === file && ns.meta.path === path); if (files.length > 0) { return files[files.length - 1]; } const paths = namespaces.filter(ns => isIndex(ns.meta.filename) && isParent(ns.meta.path, path)); if (paths.length > 0) { paths.sort((ns1, ns2) => ns1.meta.path.length - ns2.meta.path.length); return paths[paths.length - 1]; } return null; }
[ "function", "getNamespace", "(", "file", ",", "path", ")", "{", "const", "files", "=", "namespaces", ".", "filter", "(", "ns", "=>", "ns", ".", "meta", ".", "filename", "===", "file", "&&", "ns", ".", "meta", ".", "path", "===", "path", ")", ";", "if", "(", "files", ".", "length", ">", "0", ")", "{", "return", "files", "[", "files", ".", "length", "-", "1", "]", ";", "}", "const", "paths", "=", "namespaces", ".", "filter", "(", "ns", "=>", "isIndex", "(", "ns", ".", "meta", ".", "filename", ")", "&&", "isParent", "(", "ns", ".", "meta", ".", "path", ",", "path", ")", ")", ";", "if", "(", "paths", ".", "length", ">", "0", ")", "{", "paths", ".", "sort", "(", "(", "ns1", ",", "ns2", ")", "=>", "ns1", ".", "meta", ".", "path", ".", "length", "-", "ns2", ".", "meta", ".", "path", ".", "length", ")", ";", "return", "paths", "[", "paths", ".", "length", "-", "1", "]", ";", "}", "return", "null", ";", "}" ]
Get closest namespace doclet previously parsed either from the same file as the doclet or from one of the index.js files present in the same directory or any of its parents @param {string} file - File name of the doclet @param {string} path - Directory path of the doclet @return {?Doclet} - Namespace doclet or null
[ "Get", "closest", "namespace", "doclet", "previously", "parsed", "either", "from", "the", "same", "file", "as", "the", "doclet", "or", "from", "one", "of", "the", "index", ".", "js", "files", "present", "in", "the", "same", "directory", "or", "any", "of", "its", "parents" ]
6035128bd605c427105c5fabed31114f806c9e7b
https://github.com/kozhevnikov/jsdoc-memberof-namespace/blob/6035128bd605c427105c5fabed31114f806c9e7b/index.js#L95-L108
train
hubiinetwork/nahmii-sdk
lib/utils.js
expandPropertyNameGlobs
function expandPropertyNameGlobs(object, globPatterns) { const result = []; if (!globPatterns.length) return result; const arrayGroupPattern = globPatterns[0]; const indexOfArrayGroup = arrayGroupPattern.indexOf('[]'); if (indexOfArrayGroup !== -1) { const {arrayProp, arrayPropName} = getArrayProperty(object, arrayGroupPattern, indexOfArrayGroup); arrayProp.forEach((v, i) => { const pp = `${arrayPropName}[${i}]`; const propertyGroup = []; for (let i = 1; i < globPatterns.length; i++) { const pattern = `${pp}.${globPatterns[i]}`; propertyGroup.push(pattern); } result.push(propertyGroup); }); return result; } for (let pattern of globPatterns) { let indexOfGlob = pattern.indexOf('*'); if (indexOfGlob === -1) { result.push(pattern); } else { const {arrayProp, arrayPropName} = getArrayProperty(object, pattern, indexOfGlob); arrayProp.forEach((v, i) => { const pp = `${arrayPropName}[${i}]`; if (indexOfGlob < pattern.length - 1) result.push(pp + pattern.substring(indexOfGlob + 1)); else if (typeof v === 'object') Object.getOwnPropertyNames(v).forEach(n => result.push(`${pp}.${n}`)); else result.push(pp); }); } } return result; }
javascript
function expandPropertyNameGlobs(object, globPatterns) { const result = []; if (!globPatterns.length) return result; const arrayGroupPattern = globPatterns[0]; const indexOfArrayGroup = arrayGroupPattern.indexOf('[]'); if (indexOfArrayGroup !== -1) { const {arrayProp, arrayPropName} = getArrayProperty(object, arrayGroupPattern, indexOfArrayGroup); arrayProp.forEach((v, i) => { const pp = `${arrayPropName}[${i}]`; const propertyGroup = []; for (let i = 1; i < globPatterns.length; i++) { const pattern = `${pp}.${globPatterns[i]}`; propertyGroup.push(pattern); } result.push(propertyGroup); }); return result; } for (let pattern of globPatterns) { let indexOfGlob = pattern.indexOf('*'); if (indexOfGlob === -1) { result.push(pattern); } else { const {arrayProp, arrayPropName} = getArrayProperty(object, pattern, indexOfGlob); arrayProp.forEach((v, i) => { const pp = `${arrayPropName}[${i}]`; if (indexOfGlob < pattern.length - 1) result.push(pp + pattern.substring(indexOfGlob + 1)); else if (typeof v === 'object') Object.getOwnPropertyNames(v).forEach(n => result.push(`${pp}.${n}`)); else result.push(pp); }); } } return result; }
[ "function", "expandPropertyNameGlobs", "(", "object", ",", "globPatterns", ")", "{", "const", "result", "=", "[", "]", ";", "if", "(", "!", "globPatterns", ".", "length", ")", "return", "result", ";", "const", "arrayGroupPattern", "=", "globPatterns", "[", "0", "]", ";", "const", "indexOfArrayGroup", "=", "arrayGroupPattern", ".", "indexOf", "(", "'[]'", ")", ";", "if", "(", "indexOfArrayGroup", "!==", "-", "1", ")", "{", "const", "{", "arrayProp", ",", "arrayPropName", "}", "=", "getArrayProperty", "(", "object", ",", "arrayGroupPattern", ",", "indexOfArrayGroup", ")", ";", "arrayProp", ".", "forEach", "(", "(", "v", ",", "i", ")", "=>", "{", "const", "pp", "=", "`", "${", "arrayPropName", "}", "${", "i", "}", "`", ";", "const", "propertyGroup", "=", "[", "]", ";", "for", "(", "let", "i", "=", "1", ";", "i", "<", "globPatterns", ".", "length", ";", "i", "++", ")", "{", "const", "pattern", "=", "`", "${", "pp", "}", "${", "globPatterns", "[", "i", "]", "}", "`", ";", "propertyGroup", ".", "push", "(", "pattern", ")", ";", "}", "result", ".", "push", "(", "propertyGroup", ")", ";", "}", ")", ";", "return", "result", ";", "}", "for", "(", "let", "pattern", "of", "globPatterns", ")", "{", "let", "indexOfGlob", "=", "pattern", ".", "indexOf", "(", "'*'", ")", ";", "if", "(", "indexOfGlob", "===", "-", "1", ")", "{", "result", ".", "push", "(", "pattern", ")", ";", "}", "else", "{", "const", "{", "arrayProp", ",", "arrayPropName", "}", "=", "getArrayProperty", "(", "object", ",", "pattern", ",", "indexOfGlob", ")", ";", "arrayProp", ".", "forEach", "(", "(", "v", ",", "i", ")", "=>", "{", "const", "pp", "=", "`", "${", "arrayPropName", "}", "${", "i", "}", "`", ";", "if", "(", "indexOfGlob", "<", "pattern", ".", "length", "-", "1", ")", "result", ".", "push", "(", "pp", "+", "pattern", ".", "substring", "(", "indexOfGlob", "+", "1", ")", ")", ";", "else", "if", "(", "typeof", "v", "===", "'object'", ")", "Object", ".", "getOwnPropertyNames", "(", "v", ")", ".", "forEach", "(", "n", "=>", "result", ".", "push", "(", "`", "${", "pp", "}", "${", "n", "}", "`", ")", ")", ";", "else", "result", ".", "push", "(", "pp", ")", ";", "}", ")", ";", "}", "}", "return", "result", ";", "}" ]
Takes an array of property patterns and expands any glob pattern it finds based on the provided object. @private @param object @param globPatterns @returns {Array}
[ "Takes", "an", "array", "of", "property", "patterns", "and", "expands", "any", "glob", "pattern", "it", "finds", "based", "on", "the", "provided", "object", "." ]
7a372deebf7d7326e3639ddb01c9ce6224fc83d6
https://github.com/hubiinetwork/nahmii-sdk/blob/7a372deebf7d7326e3639ddb01c9ce6224fc83d6/lib/utils.js#L80-L125
train
hubiinetwork/nahmii-sdk
lib/utils.js
fromRpcSig
function fromRpcSig(flatSig) { const expandedSig = ethutil.fromRpcSig(flatSig); return { s: ethutil.bufferToHex(expandedSig.s), r: ethutil.bufferToHex(expandedSig.r), v: expandedSig.v }; }
javascript
function fromRpcSig(flatSig) { const expandedSig = ethutil.fromRpcSig(flatSig); return { s: ethutil.bufferToHex(expandedSig.s), r: ethutil.bufferToHex(expandedSig.r), v: expandedSig.v }; }
[ "function", "fromRpcSig", "(", "flatSig", ")", "{", "const", "expandedSig", "=", "ethutil", ".", "fromRpcSig", "(", "flatSig", ")", ";", "return", "{", "s", ":", "ethutil", ".", "bufferToHex", "(", "expandedSig", ".", "s", ")", ",", "r", ":", "ethutil", ".", "bufferToHex", "(", "expandedSig", ".", "r", ")", ",", "v", ":", "expandedSig", ".", "v", "}", ";", "}" ]
Takes a flat format RPC signature and returns it in expanded form, with s, r in hex string form, and v a number @param {String} flatSig Flat form signature @returns {Object} Expanded form signature
[ "Takes", "a", "flat", "format", "RPC", "signature", "and", "returns", "it", "in", "expanded", "form", "with", "s", "r", "in", "hex", "string", "form", "and", "v", "a", "number" ]
7a372deebf7d7326e3639ddb01c9ce6224fc83d6
https://github.com/hubiinetwork/nahmii-sdk/blob/7a372deebf7d7326e3639ddb01c9ce6224fc83d6/lib/utils.js#L177-L185
train
hubiinetwork/nahmii-sdk
lib/utils.js
isSignedBy
function isSignedBy(message, signature, address) { try { const ethMessage = ethHash(message); return caseInsensitiveCompare(recoverAddress(ethMessage, signature), prefix0x(address)); } catch (e) { return false; } }
javascript
function isSignedBy(message, signature, address) { try { const ethMessage = ethHash(message); return caseInsensitiveCompare(recoverAddress(ethMessage, signature), prefix0x(address)); } catch (e) { return false; } }
[ "function", "isSignedBy", "(", "message", ",", "signature", ",", "address", ")", "{", "try", "{", "const", "ethMessage", "=", "ethHash", "(", "message", ")", ";", "return", "caseInsensitiveCompare", "(", "recoverAddress", "(", "ethMessage", ",", "signature", ")", ",", "prefix0x", "(", "address", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "}" ]
Checks whether or not the address is the address of the private key used to sign the specified message and signature. @param {String} message - A message hash as a hexadecimal string @param {Object} signature - The signature of the message given as V, R and S properties @param {String} address - A hexadecimal representation of the address to verify @returns {Boolean} True if address belongs to the signed message
[ "Checks", "whether", "or", "not", "the", "address", "is", "the", "address", "of", "the", "private", "key", "used", "to", "sign", "the", "specified", "message", "and", "signature", "." ]
7a372deebf7d7326e3639ddb01c9ce6224fc83d6
https://github.com/hubiinetwork/nahmii-sdk/blob/7a372deebf7d7326e3639ddb01c9ce6224fc83d6/lib/utils.js#L243-L251
train
SimpleRegex/SRL-JavaScript
lib/Language/Helpers/methodMatch.js
methodMatch
function methodMatch(part) { let maxMatch = null let maxMatchCount = 0 // Go through each mapper and check if the name matches. Then, take the highest match to avoid matching // 'any', if 'any character' was given, and so on. Object.keys(mapper).forEach((key) => { const regex = new RegExp(`^(${key.replace(' ', ') (')})`, 'i') const matches = part.match(regex) const count = matches ? matches.length : 0 if (count > maxMatchCount) { maxMatchCount = count maxMatch = key } }) if (maxMatch) { // We've got a match. Create the desired object and populate it. const item = mapper[maxMatch] return new item['class'](maxMatch, item.method, buildQuery) } throw new SyntaxException(`Invalid method: ${part}`) }
javascript
function methodMatch(part) { let maxMatch = null let maxMatchCount = 0 // Go through each mapper and check if the name matches. Then, take the highest match to avoid matching // 'any', if 'any character' was given, and so on. Object.keys(mapper).forEach((key) => { const regex = new RegExp(`^(${key.replace(' ', ') (')})`, 'i') const matches = part.match(regex) const count = matches ? matches.length : 0 if (count > maxMatchCount) { maxMatchCount = count maxMatch = key } }) if (maxMatch) { // We've got a match. Create the desired object and populate it. const item = mapper[maxMatch] return new item['class'](maxMatch, item.method, buildQuery) } throw new SyntaxException(`Invalid method: ${part}`) }
[ "function", "methodMatch", "(", "part", ")", "{", "let", "maxMatch", "=", "null", "let", "maxMatchCount", "=", "0", "Object", ".", "keys", "(", "mapper", ")", ".", "forEach", "(", "(", "key", ")", "=>", "{", "const", "regex", "=", "new", "RegExp", "(", "`", "${", "key", ".", "replace", "(", "' '", ",", "') ('", ")", "}", "`", ",", "'i'", ")", "const", "matches", "=", "part", ".", "match", "(", "regex", ")", "const", "count", "=", "matches", "?", "matches", ".", "length", ":", "0", "if", "(", "count", ">", "maxMatchCount", ")", "{", "maxMatchCount", "=", "count", "maxMatch", "=", "key", "}", "}", ")", "if", "(", "maxMatch", ")", "{", "const", "item", "=", "mapper", "[", "maxMatch", "]", "return", "new", "item", "[", "'class'", "]", "(", "maxMatch", ",", "item", ".", "method", ",", "buildQuery", ")", "}", "throw", "new", "SyntaxException", "(", "`", "${", "part", "}", "`", ")", "}" ]
Match a string part to a method. Please note that the string must start with a method. @param {string} part @throws {SyntaxException} If no method was found, a SyntaxException will be thrown. @return {method}
[ "Match", "a", "string", "part", "to", "a", "method", ".", "Please", "note", "that", "the", "string", "must", "start", "with", "a", "method", "." ]
eb2f0576ec49076e95fc2adec57e10d83c24d438
https://github.com/SimpleRegex/SRL-JavaScript/blob/eb2f0576ec49076e95fc2adec57e10d83c24d438/lib/Language/Helpers/methodMatch.js#L75-L100
train
jahting/pnltri.js
build/pnltri.js
function () { // <<<<<< public var newMono, newMonoTo, toFirstOutSeg, fromRevSeg; for ( var i = 0, j = this.segments.length; i < j; i++) { newMono = this.segments[i]; if ( this.PolyLeftArr[newMono.chainId] ) { // preserve winding order newMonoTo = newMono.vTo; // target of segment newMono.mprev = newMono.sprev; // doubly linked list for monotone chains (sub-polygons) newMono.mnext = newMono.snext; } else { // reverse winding order newMonoTo = newMono.vFrom; newMono = newMono.snext; newMono.mprev = newMono.snext; newMono.mnext = newMono.sprev; } if ( fromRevSeg = newMono.vFrom.lastInDiag ) { // assignment ! fromRevSeg.mnext = newMono; newMono.mprev = fromRevSeg; newMono.vFrom.lastInDiag = null; // cleanup } if ( toFirstOutSeg = newMonoTo.firstOutDiag ) { // assignment ! toFirstOutSeg.mprev = newMono; newMono.mnext = toFirstOutSeg; newMonoTo.firstOutDiag = null; // cleanup } } }
javascript
function () { // <<<<<< public var newMono, newMonoTo, toFirstOutSeg, fromRevSeg; for ( var i = 0, j = this.segments.length; i < j; i++) { newMono = this.segments[i]; if ( this.PolyLeftArr[newMono.chainId] ) { // preserve winding order newMonoTo = newMono.vTo; // target of segment newMono.mprev = newMono.sprev; // doubly linked list for monotone chains (sub-polygons) newMono.mnext = newMono.snext; } else { // reverse winding order newMonoTo = newMono.vFrom; newMono = newMono.snext; newMono.mprev = newMono.snext; newMono.mnext = newMono.sprev; } if ( fromRevSeg = newMono.vFrom.lastInDiag ) { // assignment ! fromRevSeg.mnext = newMono; newMono.mprev = fromRevSeg; newMono.vFrom.lastInDiag = null; // cleanup } if ( toFirstOutSeg = newMonoTo.firstOutDiag ) { // assignment ! toFirstOutSeg.mprev = newMono; newMono.mnext = toFirstOutSeg; newMonoTo.firstOutDiag = null; // cleanup } } }
[ "function", "(", ")", "{", "var", "newMono", ",", "newMonoTo", ",", "toFirstOutSeg", ",", "fromRevSeg", ";", "for", "(", "var", "i", "=", "0", ",", "j", "=", "this", ".", "segments", ".", "length", ";", "i", "<", "j", ";", "i", "++", ")", "{", "newMono", "=", "this", ".", "segments", "[", "i", "]", ";", "if", "(", "this", ".", "PolyLeftArr", "[", "newMono", ".", "chainId", "]", ")", "{", "newMonoTo", "=", "newMono", ".", "vTo", ";", "newMono", ".", "mprev", "=", "newMono", ".", "sprev", ";", "newMono", ".", "mnext", "=", "newMono", ".", "snext", ";", "}", "else", "{", "newMonoTo", "=", "newMono", ".", "vFrom", ";", "newMono", "=", "newMono", ".", "snext", ";", "newMono", ".", "mprev", "=", "newMono", ".", "snext", ";", "newMono", ".", "mnext", "=", "newMono", ".", "sprev", ";", "}", "if", "(", "fromRevSeg", "=", "newMono", ".", "vFrom", ".", "lastInDiag", ")", "{", "fromRevSeg", ".", "mnext", "=", "newMono", ";", "newMono", ".", "mprev", "=", "fromRevSeg", ";", "newMono", ".", "vFrom", ".", "lastInDiag", "=", "null", ";", "}", "if", "(", "toFirstOutSeg", "=", "newMonoTo", ".", "firstOutDiag", ")", "{", "toFirstOutSeg", ".", "mprev", "=", "newMono", ";", "newMono", ".", "mnext", "=", "toFirstOutSeg", ";", "newMonoTo", ".", "firstOutDiag", "=", "null", ";", "}", "}", "}" ]
Generate the uni-y-monotone sub-polygons from the trapezoidation of the polygon.
[ "Generate", "the", "uni", "-", "y", "-", "monotone", "sub", "-", "polygons", "from", "the", "trapezoidation", "of", "the", "polygon", "." ]
72f162d39da3a84c78ff16181940da79f3f50ba9
https://github.com/jahting/pnltri.js/blob/72f162d39da3a84c78ff16181940da79f3f50ba9/build/pnltri.js#L350-L377
train
jahting/pnltri.js
build/pnltri.js
function () { // <<<<<<<<<< public var normedMonoChains = this.polyData.getMonoSubPolys(); this.polyData.clearTriangles(); for ( var i=0; i<normedMonoChains.length; i++ ) { // loop through uni-y-monotone chains // => monoPosmin is next to monoPosmax (left or right) var monoPosmax = normedMonoChains[i]; var prevMono = monoPosmax.mprev; var nextMono = monoPosmax.mnext; if ( nextMono.mnext == prevMono ) { // already a triangle this.polyData.addTriangle( monoPosmax.vFrom, nextMono.vFrom, prevMono.vFrom ); } else { // triangulate the polygon this.triangulate_monotone_polygon( monoPosmax ); } } }
javascript
function () { // <<<<<<<<<< public var normedMonoChains = this.polyData.getMonoSubPolys(); this.polyData.clearTriangles(); for ( var i=0; i<normedMonoChains.length; i++ ) { // loop through uni-y-monotone chains // => monoPosmin is next to monoPosmax (left or right) var monoPosmax = normedMonoChains[i]; var prevMono = monoPosmax.mprev; var nextMono = monoPosmax.mnext; if ( nextMono.mnext == prevMono ) { // already a triangle this.polyData.addTriangle( monoPosmax.vFrom, nextMono.vFrom, prevMono.vFrom ); } else { // triangulate the polygon this.triangulate_monotone_polygon( monoPosmax ); } } }
[ "function", "(", ")", "{", "var", "normedMonoChains", "=", "this", ".", "polyData", ".", "getMonoSubPolys", "(", ")", ";", "this", ".", "polyData", ".", "clearTriangles", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "normedMonoChains", ".", "length", ";", "i", "++", ")", "{", "var", "monoPosmax", "=", "normedMonoChains", "[", "i", "]", ";", "var", "prevMono", "=", "monoPosmax", ".", "mprev", ";", "var", "nextMono", "=", "monoPosmax", ".", "mnext", ";", "if", "(", "nextMono", ".", "mnext", "==", "prevMono", ")", "{", "this", ".", "polyData", ".", "addTriangle", "(", "monoPosmax", ".", "vFrom", ",", "nextMono", ".", "vFrom", ",", "prevMono", ".", "vFrom", ")", ";", "}", "else", "{", "this", ".", "triangulate_monotone_polygon", "(", "monoPosmax", ")", ";", "}", "}", "}" ]
Pass each uni-y-monotone polygon with start at Y-max for greedy triangulation.
[ "Pass", "each", "uni", "-", "y", "-", "monotone", "polygon", "with", "start", "at", "Y", "-", "max", "for", "greedy", "triangulation", "." ]
72f162d39da3a84c78ff16181940da79f3f50ba9
https://github.com/jahting/pnltri.js/blob/72f162d39da3a84c78ff16181940da79f3f50ba9/build/pnltri.js#L1897-L1913
train
3rd-Eden/FlashPolicyFileServer
index.js
Server
function Server (options, origins) { var me = this; this.origins = origins || ['*:*']; this.port = 843; this.log = console.log; // merge `this` with the options Object.keys(options).forEach(function (key) { me[key] && (me[key] = options[key]) }); // create the net server this.socket = net.createServer(function createServer (socket) { socket.on('error', function socketError () { me.responder.call(me, socket); }); me.responder.call(me, socket); }); // Listen for errors as the port might be blocked because we do not have root priv. this.socket.on('error', function serverError (err) { // Special and common case error handling if (err.errno == 13) { me.log && me.log( 'Unable to listen to port `' + me.port + '` as your Node.js instance does not have root privileges. ' + ( me.server ? 'The Flash Policy File requests will only be served inline over the supplied HTTP server. Inline serving is slower than a dedicated server instance.' : 'No fallback server supplied, we will be unable to answer Flash Policy File requests.' ) ); me.emit('connect_failed', err); me.socket.removeAllListeners(); delete me.socket; } else { me.log && me.log('FlashPolicyFileServer received an error event:\n' + (err.message ? err.message : err)); } }); this.socket.on('timeout', function serverTimeout () {}); this.socket.on('close', function serverClosed (err) { err && me.log && me.log('Server closing due to an error: \n' + (err.message ? err.message : err)); if (me.server) { // Remove the inline policy listener if we close down // but only when the server was `online` (see listen prototype) if (me.server['@'] && me.server.online) { me.server.removeListener('connection', me.server['@']); } // not online anymore delete me.server.online; } }); // Compile the initial `buffer` this.compile(); }
javascript
function Server (options, origins) { var me = this; this.origins = origins || ['*:*']; this.port = 843; this.log = console.log; // merge `this` with the options Object.keys(options).forEach(function (key) { me[key] && (me[key] = options[key]) }); // create the net server this.socket = net.createServer(function createServer (socket) { socket.on('error', function socketError () { me.responder.call(me, socket); }); me.responder.call(me, socket); }); // Listen for errors as the port might be blocked because we do not have root priv. this.socket.on('error', function serverError (err) { // Special and common case error handling if (err.errno == 13) { me.log && me.log( 'Unable to listen to port `' + me.port + '` as your Node.js instance does not have root privileges. ' + ( me.server ? 'The Flash Policy File requests will only be served inline over the supplied HTTP server. Inline serving is slower than a dedicated server instance.' : 'No fallback server supplied, we will be unable to answer Flash Policy File requests.' ) ); me.emit('connect_failed', err); me.socket.removeAllListeners(); delete me.socket; } else { me.log && me.log('FlashPolicyFileServer received an error event:\n' + (err.message ? err.message : err)); } }); this.socket.on('timeout', function serverTimeout () {}); this.socket.on('close', function serverClosed (err) { err && me.log && me.log('Server closing due to an error: \n' + (err.message ? err.message : err)); if (me.server) { // Remove the inline policy listener if we close down // but only when the server was `online` (see listen prototype) if (me.server['@'] && me.server.online) { me.server.removeListener('connection', me.server['@']); } // not online anymore delete me.server.online; } }); // Compile the initial `buffer` this.compile(); }
[ "function", "Server", "(", "options", ",", "origins", ")", "{", "var", "me", "=", "this", ";", "this", ".", "origins", "=", "origins", "||", "[", "'*:*'", "]", ";", "this", ".", "port", "=", "843", ";", "this", ".", "log", "=", "console", ".", "log", ";", "Object", ".", "keys", "(", "options", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "me", "[", "key", "]", "&&", "(", "me", "[", "key", "]", "=", "options", "[", "key", "]", ")", "}", ")", ";", "this", ".", "socket", "=", "net", ".", "createServer", "(", "function", "createServer", "(", "socket", ")", "{", "socket", ".", "on", "(", "'error'", ",", "function", "socketError", "(", ")", "{", "me", ".", "responder", ".", "call", "(", "me", ",", "socket", ")", ";", "}", ")", ";", "me", ".", "responder", ".", "call", "(", "me", ",", "socket", ")", ";", "}", ")", ";", "this", ".", "socket", ".", "on", "(", "'error'", ",", "function", "serverError", "(", "err", ")", "{", "if", "(", "err", ".", "errno", "==", "13", ")", "{", "me", ".", "log", "&&", "me", ".", "log", "(", "'Unable to listen to port `'", "+", "me", ".", "port", "+", "'` as your Node.js instance does not have root privileges. '", "+", "(", "me", ".", "server", "?", "'The Flash Policy File requests will only be served inline over the supplied HTTP server. Inline serving is slower than a dedicated server instance.'", ":", "'No fallback server supplied, we will be unable to answer Flash Policy File requests.'", ")", ")", ";", "me", ".", "emit", "(", "'connect_failed'", ",", "err", ")", ";", "me", ".", "socket", ".", "removeAllListeners", "(", ")", ";", "delete", "me", ".", "socket", ";", "}", "else", "{", "me", ".", "log", "&&", "me", ".", "log", "(", "'FlashPolicyFileServer received an error event:\\n'", "+", "\\n", ")", ";", "}", "}", ")", ";", "(", "err", ".", "message", "?", "err", ".", "message", ":", "err", ")", "this", ".", "socket", ".", "on", "(", "'timeout'", ",", "function", "serverTimeout", "(", ")", "{", "}", ")", ";", "this", ".", "socket", ".", "on", "(", "'close'", ",", "function", "serverClosed", "(", "err", ")", "{", "err", "&&", "me", ".", "log", "&&", "me", ".", "log", "(", "'Server closing due to an error: \\n'", "+", "\\n", ")", ";", "(", "err", ".", "message", "?", "err", ".", "message", ":", "err", ")", "}", ")", ";", "}" ]
The server that does the Policy File severing Options: - `log` false or a function that can output log information, defaults to console.log? @param {Object} options Options to customize the servers functionality. @param {Array} origins The origins that are allowed on this server, defaults to `*:*`. @api public
[ "The", "server", "that", "does", "the", "Policy", "File", "severing" ]
a3ad25396a63db58afff8d1c1358e1f30458ec37
https://github.com/3rd-Eden/FlashPolicyFileServer/blob/a3ad25396a63db58afff8d1c1358e1f30458ec37/index.js#L20-L80
train
hubiinetwork/nahmii-sdk
lib/settlement/utils.js
determineNonceFromReceipt
function determineNonceFromReceipt(receipt, address) { const {sender, recipient} = receipt; return caseInsensitiveCompare(sender.wallet, address) ? sender.nonce : recipient.nonce; }
javascript
function determineNonceFromReceipt(receipt, address) { const {sender, recipient} = receipt; return caseInsensitiveCompare(sender.wallet, address) ? sender.nonce : recipient.nonce; }
[ "function", "determineNonceFromReceipt", "(", "receipt", ",", "address", ")", "{", "const", "{", "sender", ",", "recipient", "}", "=", "receipt", ";", "return", "caseInsensitiveCompare", "(", "sender", ".", "wallet", ",", "address", ")", "?", "sender", ".", "nonce", ":", "recipient", ".", "nonce", ";", "}" ]
Determine the settlement nonce for a wallet. @param {Receipt} receipt - The receipt object @param {Address} address - The wallet address @returns {number} The nonce
[ "Determine", "the", "settlement", "nonce", "for", "a", "wallet", "." ]
7a372deebf7d7326e3639ddb01c9ce6224fc83d6
https://github.com/hubiinetwork/nahmii-sdk/blob/7a372deebf7d7326e3639ddb01c9ce6224fc83d6/lib/settlement/utils.js#L20-L23
train
InsideInc/node-pinterest-api
index.js
function(seriesCallback) { async.eachLimit(groupedPinIds, 50, function(groupOfPinIds, eachCallback) { var pinIdsString = groupOfPinIds.join(','); getCache(pinIdsString, true, function (cacheData) { if (cacheData === null) { get('http://api.pinterest.com/v3/pidgets/pins/info/?pin_ids=' + pinIdsString, true, function (response) { putCache(pinIdsString, JSON.stringify(response)); allPinsData = allPinsData.concat(response.data ? response.data : []); eachCallback(); return; }); } else { allPinsData = allPinsData.concat(cacheData.data ? cacheData.data : []); eachCallback(); return; } }); }, function (err) { if(err) { throw err; } seriesCallback(); return; }); }
javascript
function(seriesCallback) { async.eachLimit(groupedPinIds, 50, function(groupOfPinIds, eachCallback) { var pinIdsString = groupOfPinIds.join(','); getCache(pinIdsString, true, function (cacheData) { if (cacheData === null) { get('http://api.pinterest.com/v3/pidgets/pins/info/?pin_ids=' + pinIdsString, true, function (response) { putCache(pinIdsString, JSON.stringify(response)); allPinsData = allPinsData.concat(response.data ? response.data : []); eachCallback(); return; }); } else { allPinsData = allPinsData.concat(cacheData.data ? cacheData.data : []); eachCallback(); return; } }); }, function (err) { if(err) { throw err; } seriesCallback(); return; }); }
[ "function", "(", "seriesCallback", ")", "{", "async", ".", "eachLimit", "(", "groupedPinIds", ",", "50", ",", "function", "(", "groupOfPinIds", ",", "eachCallback", ")", "{", "var", "pinIdsString", "=", "groupOfPinIds", ".", "join", "(", "','", ")", ";", "getCache", "(", "pinIdsString", ",", "true", ",", "function", "(", "cacheData", ")", "{", "if", "(", "cacheData", "===", "null", ")", "{", "get", "(", "'http://api.pinterest.com/v3/pidgets/pins/info/?pin_ids='", "+", "pinIdsString", ",", "true", ",", "function", "(", "response", ")", "{", "putCache", "(", "pinIdsString", ",", "JSON", ".", "stringify", "(", "response", ")", ")", ";", "allPinsData", "=", "allPinsData", ".", "concat", "(", "response", ".", "data", "?", "response", ".", "data", ":", "[", "]", ")", ";", "eachCallback", "(", ")", ";", "return", ";", "}", ")", ";", "}", "else", "{", "allPinsData", "=", "allPinsData", ".", "concat", "(", "cacheData", ".", "data", "?", "cacheData", ".", "data", ":", "[", "]", ")", ";", "eachCallback", "(", ")", ";", "return", ";", "}", "}", ")", ";", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "throw", "err", ";", "}", "seriesCallback", "(", ")", ";", "return", ";", "}", ")", ";", "}" ]
get pin data from API
[ "get", "pin", "data", "from", "API" ]
74b94fc5ecfc8a52752bcd99b5d25d1223b49692
https://github.com/InsideInc/node-pinterest-api/blob/74b94fc5ecfc8a52752bcd99b5d25d1223b49692/index.js#L646-L670
train
InsideInc/node-pinterest-api
index.js
function(seriesCallback) { var userBoardAlreadyAdded = {}; for(var i = 0; i < allPinsData.length; i++) { var pin = allPinsData[i]; if(pin.board) { var boardUrlParts = pin.board.url.split('/'); var user = boardUrlParts[1]; var board = boardUrlParts[2]; if(!userBoardAlreadyAdded[user + board]) { userBoardAlreadyAdded[user + board] = true; boards.push({user: user, board: board}); } } } seriesCallback(); return; }
javascript
function(seriesCallback) { var userBoardAlreadyAdded = {}; for(var i = 0; i < allPinsData.length; i++) { var pin = allPinsData[i]; if(pin.board) { var boardUrlParts = pin.board.url.split('/'); var user = boardUrlParts[1]; var board = boardUrlParts[2]; if(!userBoardAlreadyAdded[user + board]) { userBoardAlreadyAdded[user + board] = true; boards.push({user: user, board: board}); } } } seriesCallback(); return; }
[ "function", "(", "seriesCallback", ")", "{", "var", "userBoardAlreadyAdded", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "allPinsData", ".", "length", ";", "i", "++", ")", "{", "var", "pin", "=", "allPinsData", "[", "i", "]", ";", "if", "(", "pin", ".", "board", ")", "{", "var", "boardUrlParts", "=", "pin", ".", "board", ".", "url", ".", "split", "(", "'/'", ")", ";", "var", "user", "=", "boardUrlParts", "[", "1", "]", ";", "var", "board", "=", "boardUrlParts", "[", "2", "]", ";", "if", "(", "!", "userBoardAlreadyAdded", "[", "user", "+", "board", "]", ")", "{", "userBoardAlreadyAdded", "[", "user", "+", "board", "]", "=", "true", ";", "boards", ".", "push", "(", "{", "user", ":", "user", ",", "board", ":", "board", "}", ")", ";", "}", "}", "}", "seriesCallback", "(", ")", ";", "return", ";", "}" ]
create list of boards that the pins belong to
[ "create", "list", "of", "boards", "that", "the", "pins", "belong", "to" ]
74b94fc5ecfc8a52752bcd99b5d25d1223b49692
https://github.com/InsideInc/node-pinterest-api/blob/74b94fc5ecfc8a52752bcd99b5d25d1223b49692/index.js#L672-L691
train
InsideInc/node-pinterest-api
index.js
function(seriesCallback) { if(!obtainDates) { seriesCallback(); return; } var pinDateMaps = []; async.eachLimit(boards, 5, function(board, eachCallback) { getDatesForBoardPinsFromRss(board.user, board.board, function(result) { pinDateMaps.push(result); eachCallback(); }); }, function (err) { if(err) { throw err; } var pinDateMap = mergeMaps(pinDateMaps); for (var i = 0; i < allPinsData.length; i++) { allPinsData[i].created_at = null; allPinsData[i].created_at_source = null; if (pinDateMap[allPinsData[i].id]) { allPinsData[i].created_at = pinDateMap[allPinsData[i].id]; allPinsData[i].created_at_source = 'rss'; } else { pinsThatNeedScrapedDates.push(allPinsData[i].id); } } seriesCallback(); return; }); }
javascript
function(seriesCallback) { if(!obtainDates) { seriesCallback(); return; } var pinDateMaps = []; async.eachLimit(boards, 5, function(board, eachCallback) { getDatesForBoardPinsFromRss(board.user, board.board, function(result) { pinDateMaps.push(result); eachCallback(); }); }, function (err) { if(err) { throw err; } var pinDateMap = mergeMaps(pinDateMaps); for (var i = 0; i < allPinsData.length; i++) { allPinsData[i].created_at = null; allPinsData[i].created_at_source = null; if (pinDateMap[allPinsData[i].id]) { allPinsData[i].created_at = pinDateMap[allPinsData[i].id]; allPinsData[i].created_at_source = 'rss'; } else { pinsThatNeedScrapedDates.push(allPinsData[i].id); } } seriesCallback(); return; }); }
[ "function", "(", "seriesCallback", ")", "{", "if", "(", "!", "obtainDates", ")", "{", "seriesCallback", "(", ")", ";", "return", ";", "}", "var", "pinDateMaps", "=", "[", "]", ";", "async", ".", "eachLimit", "(", "boards", ",", "5", ",", "function", "(", "board", ",", "eachCallback", ")", "{", "getDatesForBoardPinsFromRss", "(", "board", ".", "user", ",", "board", ".", "board", ",", "function", "(", "result", ")", "{", "pinDateMaps", ".", "push", "(", "result", ")", ";", "eachCallback", "(", ")", ";", "}", ")", ";", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "throw", "err", ";", "}", "var", "pinDateMap", "=", "mergeMaps", "(", "pinDateMaps", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "allPinsData", ".", "length", ";", "i", "++", ")", "{", "allPinsData", "[", "i", "]", ".", "created_at", "=", "null", ";", "allPinsData", "[", "i", "]", ".", "created_at_source", "=", "null", ";", "if", "(", "pinDateMap", "[", "allPinsData", "[", "i", "]", ".", "id", "]", ")", "{", "allPinsData", "[", "i", "]", ".", "created_at", "=", "pinDateMap", "[", "allPinsData", "[", "i", "]", ".", "id", "]", ";", "allPinsData", "[", "i", "]", ".", "created_at_source", "=", "'rss'", ";", "}", "else", "{", "pinsThatNeedScrapedDates", ".", "push", "(", "allPinsData", "[", "i", "]", ".", "id", ")", ";", "}", "}", "seriesCallback", "(", ")", ";", "return", ";", "}", ")", ";", "}" ]
get what dates we can for pins from the board RSS feeds
[ "get", "what", "dates", "we", "can", "for", "pins", "from", "the", "board", "RSS", "feeds" ]
74b94fc5ecfc8a52752bcd99b5d25d1223b49692
https://github.com/InsideInc/node-pinterest-api/blob/74b94fc5ecfc8a52752bcd99b5d25d1223b49692/index.js#L693-L726
train
InsideInc/node-pinterest-api
index.js
function(seriesCallback) { if(!obtainDates) { seriesCallback(); return; } getDatesForPinsFromScraping(pinsThatNeedScrapedDates, null, function (pinDateMap) { for (var i = 0; i < allPinsData.length; i++) { if (allPinsData[i].created_at == null && pinDateMap[allPinsData[i].id] && pinDateMap[allPinsData[i].id].date) { allPinsData[i].created_at = pinDateMap[allPinsData[i].id].date; allPinsData[i].created_at_source = pinDateMap[allPinsData[i].id].source; } } seriesCallback(); return; }); }
javascript
function(seriesCallback) { if(!obtainDates) { seriesCallback(); return; } getDatesForPinsFromScraping(pinsThatNeedScrapedDates, null, function (pinDateMap) { for (var i = 0; i < allPinsData.length; i++) { if (allPinsData[i].created_at == null && pinDateMap[allPinsData[i].id] && pinDateMap[allPinsData[i].id].date) { allPinsData[i].created_at = pinDateMap[allPinsData[i].id].date; allPinsData[i].created_at_source = pinDateMap[allPinsData[i].id].source; } } seriesCallback(); return; }); }
[ "function", "(", "seriesCallback", ")", "{", "if", "(", "!", "obtainDates", ")", "{", "seriesCallback", "(", ")", ";", "return", ";", "}", "getDatesForPinsFromScraping", "(", "pinsThatNeedScrapedDates", ",", "null", ",", "function", "(", "pinDateMap", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "allPinsData", ".", "length", ";", "i", "++", ")", "{", "if", "(", "allPinsData", "[", "i", "]", ".", "created_at", "==", "null", "&&", "pinDateMap", "[", "allPinsData", "[", "i", "]", ".", "id", "]", "&&", "pinDateMap", "[", "allPinsData", "[", "i", "]", ".", "id", "]", ".", "date", ")", "{", "allPinsData", "[", "i", "]", ".", "created_at", "=", "pinDateMap", "[", "allPinsData", "[", "i", "]", ".", "id", "]", ".", "date", ";", "allPinsData", "[", "i", "]", ".", "created_at_source", "=", "pinDateMap", "[", "allPinsData", "[", "i", "]", ".", "id", "]", ".", "source", ";", "}", "}", "seriesCallback", "(", ")", ";", "return", ";", "}", ")", ";", "}" ]
get remaining dates by scraping
[ "get", "remaining", "dates", "by", "scraping" ]
74b94fc5ecfc8a52752bcd99b5d25d1223b49692
https://github.com/InsideInc/node-pinterest-api/blob/74b94fc5ecfc8a52752bcd99b5d25d1223b49692/index.js#L728-L744
train
jpederson/Squirrel.js
jquery.squirrel.js
stash
function stash(storage, storageKey, key, value) { // get the squirrel storage object. var store = window.JSON.parse(storage.getItem(storageKey)); // if it doesn't exist, create an empty object. if (store === null) { store = {}; } // if a value isn't specified. if (isUndefined(value) || value === null) { // return the store value if the store value exists; otherwise, null. return !isUndefined(store[key]) ? store[key] : null; } // if a value is specified. // create an append object literal. var append = {}; // add the new value to the object that we'll append to the store object. append[key] = value; // extend the squirrel store object. // in ES6 this can be shortened to just $.extend(store, {[key]: value}), as there would be no need // to create a temporary storage object. $.extend(store, append); // re-session the squirrel store again. storage.setItem(storageKey, window.JSON.stringify(store)); // return the value. return value; }
javascript
function stash(storage, storageKey, key, value) { // get the squirrel storage object. var store = window.JSON.parse(storage.getItem(storageKey)); // if it doesn't exist, create an empty object. if (store === null) { store = {}; } // if a value isn't specified. if (isUndefined(value) || value === null) { // return the store value if the store value exists; otherwise, null. return !isUndefined(store[key]) ? store[key] : null; } // if a value is specified. // create an append object literal. var append = {}; // add the new value to the object that we'll append to the store object. append[key] = value; // extend the squirrel store object. // in ES6 this can be shortened to just $.extend(store, {[key]: value}), as there would be no need // to create a temporary storage object. $.extend(store, append); // re-session the squirrel store again. storage.setItem(storageKey, window.JSON.stringify(store)); // return the value. return value; }
[ "function", "stash", "(", "storage", ",", "storageKey", ",", "key", ",", "value", ")", "{", "var", "store", "=", "window", ".", "JSON", ".", "parse", "(", "storage", ".", "getItem", "(", "storageKey", ")", ")", ";", "if", "(", "store", "===", "null", ")", "{", "store", "=", "{", "}", ";", "}", "if", "(", "isUndefined", "(", "value", ")", "||", "value", "===", "null", ")", "{", "return", "!", "isUndefined", "(", "store", "[", "key", "]", ")", "?", "store", "[", "key", "]", ":", "null", ";", "}", "var", "append", "=", "{", "}", ";", "append", "[", "key", "]", "=", "value", ";", "$", ".", "extend", "(", "store", ",", "append", ")", ";", "storage", ".", "setItem", "(", "storageKey", ",", "window", ".", "JSON", ".", "stringify", "(", "store", ")", ")", ";", "return", "value", ";", "}" ]
METHODS stash or grab a value from our session store object.
[ "METHODS", "stash", "or", "grab", "a", "value", "from", "our", "session", "store", "object", "." ]
9b8897f2ec03afcf7d4262706a6169c6c196c7ee
https://github.com/jpederson/Squirrel.js/blob/9b8897f2ec03afcf7d4262706a6169c6c196c7ee/jquery.squirrel.js#L295-L333
train
SimpleRegex/SRL-JavaScript
lib/Language/Helpers/parseParentheses.js
createLiterallyObjects
function createLiterallyObjects(query, openPos, stringPositions) { const firstRaw = query.substr(0, openPos) const result = [firstRaw.trim()] let pointer = 0 stringPositions.forEach((stringPosition) => { if (!stringPosition.end) { throw new SyntaxException('Invalid string ending found.') } if (stringPosition.end < firstRaw.length) { // At least one string exists in first part, create a new object. // Remove the last part, since this wasn't parsed. result.pop() // Add part between pointer and string occurrence. result.push(firstRaw.substr(pointer, stringPosition.start - pointer).trim()) // Add the string as object. result.push(new Literally(firstRaw.substr( stringPosition.start + 1, stringPosition.end - stringPosition.start ))) result.push(firstRaw.substr(stringPosition.end + 2).trim()) pointer = stringPosition.end + 2 } }) return result }
javascript
function createLiterallyObjects(query, openPos, stringPositions) { const firstRaw = query.substr(0, openPos) const result = [firstRaw.trim()] let pointer = 0 stringPositions.forEach((stringPosition) => { if (!stringPosition.end) { throw new SyntaxException('Invalid string ending found.') } if (stringPosition.end < firstRaw.length) { // At least one string exists in first part, create a new object. // Remove the last part, since this wasn't parsed. result.pop() // Add part between pointer and string occurrence. result.push(firstRaw.substr(pointer, stringPosition.start - pointer).trim()) // Add the string as object. result.push(new Literally(firstRaw.substr( stringPosition.start + 1, stringPosition.end - stringPosition.start ))) result.push(firstRaw.substr(stringPosition.end + 2).trim()) pointer = stringPosition.end + 2 } }) return result }
[ "function", "createLiterallyObjects", "(", "query", ",", "openPos", ",", "stringPositions", ")", "{", "const", "firstRaw", "=", "query", ".", "substr", "(", "0", ",", "openPos", ")", "const", "result", "=", "[", "firstRaw", ".", "trim", "(", ")", "]", "let", "pointer", "=", "0", "stringPositions", ".", "forEach", "(", "(", "stringPosition", ")", "=>", "{", "if", "(", "!", "stringPosition", ".", "end", ")", "{", "throw", "new", "SyntaxException", "(", "'Invalid string ending found.'", ")", "}", "if", "(", "stringPosition", ".", "end", "<", "firstRaw", ".", "length", ")", "{", "result", ".", "pop", "(", ")", "result", ".", "push", "(", "firstRaw", ".", "substr", "(", "pointer", ",", "stringPosition", ".", "start", "-", "pointer", ")", ".", "trim", "(", ")", ")", "result", ".", "push", "(", "new", "Literally", "(", "firstRaw", ".", "substr", "(", "stringPosition", ".", "start", "+", "1", ",", "stringPosition", ".", "end", "-", "stringPosition", ".", "start", ")", ")", ")", "result", ".", "push", "(", "firstRaw", ".", "substr", "(", "stringPosition", ".", "end", "+", "2", ")", ".", "trim", "(", ")", ")", "pointer", "=", "stringPosition", ".", "end", "+", "2", "}", "}", ")", "return", "result", "}" ]
Replace all "literal strings" with a Literally object to simplify parsing later on. @param {string} string @param {number} openPos @param {array} stringPositions @return {array} @throws {SyntaxException}
[ "Replace", "all", "literal", "strings", "with", "a", "Literally", "object", "to", "simplify", "parsing", "later", "on", "." ]
eb2f0576ec49076e95fc2adec57e10d83c24d438
https://github.com/SimpleRegex/SRL-JavaScript/blob/eb2f0576ec49076e95fc2adec57e10d83c24d438/lib/Language/Helpers/parseParentheses.js#L118-L150
train
nhn/tui.dom
src/js/domevent.js
memorizeHandler
function memorizeHandler(element, type, keyFn, valueFn) { const map = safeEvent(element, type); let items = map.get(keyFn); if (items) { items.push(valueFn); } else { items = [valueFn]; map.set(keyFn, items); } }
javascript
function memorizeHandler(element, type, keyFn, valueFn) { const map = safeEvent(element, type); let items = map.get(keyFn); if (items) { items.push(valueFn); } else { items = [valueFn]; map.set(keyFn, items); } }
[ "function", "memorizeHandler", "(", "element", ",", "type", ",", "keyFn", ",", "valueFn", ")", "{", "const", "map", "=", "safeEvent", "(", "element", ",", "type", ")", ";", "let", "items", "=", "map", ".", "get", "(", "keyFn", ")", ";", "if", "(", "items", ")", "{", "items", ".", "push", "(", "valueFn", ")", ";", "}", "else", "{", "items", "=", "[", "valueFn", "]", ";", "map", ".", "set", "(", "keyFn", ",", "items", ")", ";", "}", "}" ]
Memorize DOM event handler for unbinding @param {HTMLElement} element - element to bind events @param {string} type - events name @param {function} keyFn - handler function that user passed at on() use @param {function} valueFn - handler function that wrapped by domevent for implementing some features
[ "Memorize", "DOM", "event", "handler", "for", "unbinding" ]
beafe74afb8f647d770e202894ecc9c2dc0ca2b5
https://github.com/nhn/tui.dom/blob/beafe74afb8f647d770e202894ecc9c2dc0ca2b5/src/js/domevent.js#L50-L60
train
nhn/tui.dom
src/js/domevent.js
bindEvent
function bindEvent(element, type, handler, context) { /** * Event handler * @param {Event} e - event object */ function eventHandler(e) { handler.call(context || element, e || window.event); } /** * Event handler for normalize mouseenter event * @param {MouseEvent} e - event object */ function mouseEnterHandler(e) { e = e || window.event; if (checkMouse(element, e)) { eventHandler(e); } } if ('addEventListener' in element) { if (type === 'mouseenter' || type === 'mouseleave') { type = (type === 'mouseenter') ? 'mouseover' : 'mouseout'; element.addEventListener(type, mouseEnterHandler); memorizeHandler(element, type, handler, mouseEnterHandler); } else { element.addEventListener(type, eventHandler); memorizeHandler(element, type, handler, eventHandler); } } else if ('attachEvent' in element) { element.attachEvent(`on${type}`, eventHandler); memorizeHandler(element, type, handler, eventHandler); } }
javascript
function bindEvent(element, type, handler, context) { /** * Event handler * @param {Event} e - event object */ function eventHandler(e) { handler.call(context || element, e || window.event); } /** * Event handler for normalize mouseenter event * @param {MouseEvent} e - event object */ function mouseEnterHandler(e) { e = e || window.event; if (checkMouse(element, e)) { eventHandler(e); } } if ('addEventListener' in element) { if (type === 'mouseenter' || type === 'mouseleave') { type = (type === 'mouseenter') ? 'mouseover' : 'mouseout'; element.addEventListener(type, mouseEnterHandler); memorizeHandler(element, type, handler, mouseEnterHandler); } else { element.addEventListener(type, eventHandler); memorizeHandler(element, type, handler, eventHandler); } } else if ('attachEvent' in element) { element.attachEvent(`on${type}`, eventHandler); memorizeHandler(element, type, handler, eventHandler); } }
[ "function", "bindEvent", "(", "element", ",", "type", ",", "handler", ",", "context", ")", "{", "function", "eventHandler", "(", "e", ")", "{", "handler", ".", "call", "(", "context", "||", "element", ",", "e", "||", "window", ".", "event", ")", ";", "}", "function", "mouseEnterHandler", "(", "e", ")", "{", "e", "=", "e", "||", "window", ".", "event", ";", "if", "(", "checkMouse", "(", "element", ",", "e", ")", ")", "{", "eventHandler", "(", "e", ")", ";", "}", "}", "if", "(", "'addEventListener'", "in", "element", ")", "{", "if", "(", "type", "===", "'mouseenter'", "||", "type", "===", "'mouseleave'", ")", "{", "type", "=", "(", "type", "===", "'mouseenter'", ")", "?", "'mouseover'", ":", "'mouseout'", ";", "element", ".", "addEventListener", "(", "type", ",", "mouseEnterHandler", ")", ";", "memorizeHandler", "(", "element", ",", "type", ",", "handler", ",", "mouseEnterHandler", ")", ";", "}", "else", "{", "element", ".", "addEventListener", "(", "type", ",", "eventHandler", ")", ";", "memorizeHandler", "(", "element", ",", "type", ",", "handler", ",", "eventHandler", ")", ";", "}", "}", "else", "if", "(", "'attachEvent'", "in", "element", ")", "{", "element", ".", "attachEvent", "(", "`", "${", "type", "}", "`", ",", "eventHandler", ")", ";", "memorizeHandler", "(", "element", ",", "type", ",", "handler", ",", "eventHandler", ")", ";", "}", "}" ]
Bind DOM events @param {HTMLElement} element - element to bind events @param {string} type - events name @param {function} handler - handler function or context for handler method @param {object} [context] context - context for handler method.
[ "Bind", "DOM", "events" ]
beafe74afb8f647d770e202894ecc9c2dc0ca2b5
https://github.com/nhn/tui.dom/blob/beafe74afb8f647d770e202894ecc9c2dc0ca2b5/src/js/domevent.js#L80-L114
train
nhn/tui.dom
src/js/domevent.js
mouseEnterHandler
function mouseEnterHandler(e) { e = e || window.event; if (checkMouse(element, e)) { eventHandler(e); } }
javascript
function mouseEnterHandler(e) { e = e || window.event; if (checkMouse(element, e)) { eventHandler(e); } }
[ "function", "mouseEnterHandler", "(", "e", ")", "{", "e", "=", "e", "||", "window", ".", "event", ";", "if", "(", "checkMouse", "(", "element", ",", "e", ")", ")", "{", "eventHandler", "(", "e", ")", ";", "}", "}" ]
Event handler for normalize mouseenter event @param {MouseEvent} e - event object
[ "Event", "handler", "for", "normalize", "mouseenter", "event" ]
beafe74afb8f647d770e202894ecc9c2dc0ca2b5
https://github.com/nhn/tui.dom/blob/beafe74afb8f647d770e202894ecc9c2dc0ca2b5/src/js/domevent.js#L93-L99
train
nhn/tui.dom
src/js/domevent.js
unbindEvent
function unbindEvent(element, type, handler) { const events = safeEvent(element, type); const items = events.get(handler); if (!items) { return; } forgetHandler(element, type, handler); util.forEach(items, func => { if ('removeEventListener' in element) { element.removeEventListener(type, func); } else if ('detachEvent' in element) { element.detachEvent(`on${type}`, func); } }); }
javascript
function unbindEvent(element, type, handler) { const events = safeEvent(element, type); const items = events.get(handler); if (!items) { return; } forgetHandler(element, type, handler); util.forEach(items, func => { if ('removeEventListener' in element) { element.removeEventListener(type, func); } else if ('detachEvent' in element) { element.detachEvent(`on${type}`, func); } }); }
[ "function", "unbindEvent", "(", "element", ",", "type", ",", "handler", ")", "{", "const", "events", "=", "safeEvent", "(", "element", ",", "type", ")", ";", "const", "items", "=", "events", ".", "get", "(", "handler", ")", ";", "if", "(", "!", "items", ")", "{", "return", ";", "}", "forgetHandler", "(", "element", ",", "type", ",", "handler", ")", ";", "util", ".", "forEach", "(", "items", ",", "func", "=>", "{", "if", "(", "'removeEventListener'", "in", "element", ")", "{", "element", ".", "removeEventListener", "(", "type", ",", "func", ")", ";", "}", "else", "if", "(", "'detachEvent'", "in", "element", ")", "{", "element", ".", "detachEvent", "(", "`", "${", "type", "}", "`", ",", "func", ")", ";", "}", "}", ")", ";", "}" ]
Unbind DOM events @param {HTMLElement} element - element to unbind events @param {string} type - events name @param {function} handler - handler function or context for handler method
[ "Unbind", "DOM", "events" ]
beafe74afb8f647d770e202894ecc9c2dc0ca2b5
https://github.com/nhn/tui.dom/blob/beafe74afb8f647d770e202894ecc9c2dc0ca2b5/src/js/domevent.js#L123-L140
train
lukaaash/sftp-ws
examples/console-client/index.js
execute
function execute(context, action) { if (!remote) return fail(context, "Not connected to a server"); // prepare source path if (context.args.length < 1) return fail(context, "Remote path missing"); var path = remote.join(remotePath, context.args[0]); action(path); }
javascript
function execute(context, action) { if (!remote) return fail(context, "Not connected to a server"); // prepare source path if (context.args.length < 1) return fail(context, "Remote path missing"); var path = remote.join(remotePath, context.args[0]); action(path); }
[ "function", "execute", "(", "context", ",", "action", ")", "{", "if", "(", "!", "remote", ")", "return", "fail", "(", "context", ",", "\"Not connected to a server\"", ")", ";", "if", "(", "context", ".", "args", ".", "length", "<", "1", ")", "return", "fail", "(", "context", ",", "\"Remote path missing\"", ")", ";", "var", "path", "=", "remote", ".", "join", "(", "remotePath", ",", "context", ".", "args", "[", "0", "]", ")", ";", "action", "(", "path", ")", ";", "}" ]
execute a simple action on a remote path
[ "execute", "a", "simple", "action", "on", "a", "remote", "path" ]
ec48b5974f13233285483201c1808d7c3b3045c3
https://github.com/lukaaash/sftp-ws/blob/ec48b5974f13233285483201c1808d7c3b3045c3/examples/console-client/index.js#L267-L274
train
lukaaash/sftp-ws
examples/console-client/index.js
list
function list(context, err, items, paths) { if (err) return fail(context, err); var long = context.options["l"]; if (typeof long === "undefined") long = (context.command.slice(-3) === "dir"); items.forEach(function (item) { if (item.filename == "." || item.filename == "..") return; if (paths) { shell.write(item.path); } else if (long) { shell.write(item.longname); } else { shell.write(item.filename); } }); context.end(); }
javascript
function list(context, err, items, paths) { if (err) return fail(context, err); var long = context.options["l"]; if (typeof long === "undefined") long = (context.command.slice(-3) === "dir"); items.forEach(function (item) { if (item.filename == "." || item.filename == "..") return; if (paths) { shell.write(item.path); } else if (long) { shell.write(item.longname); } else { shell.write(item.filename); } }); context.end(); }
[ "function", "list", "(", "context", ",", "err", ",", "items", ",", "paths", ")", "{", "if", "(", "err", ")", "return", "fail", "(", "context", ",", "err", ")", ";", "var", "long", "=", "context", ".", "options", "[", "\"l\"", "]", ";", "if", "(", "typeof", "long", "===", "\"undefined\"", ")", "long", "=", "(", "context", ".", "command", ".", "slice", "(", "-", "3", ")", "===", "\"dir\"", ")", ";", "items", ".", "forEach", "(", "function", "(", "item", ")", "{", "if", "(", "item", ".", "filename", "==", "\".\"", "||", "item", ".", "filename", "==", "\"..\"", ")", "return", ";", "if", "(", "paths", ")", "{", "shell", ".", "write", "(", "item", ".", "path", ")", ";", "}", "else", "if", "(", "long", ")", "{", "shell", ".", "write", "(", "item", ".", "longname", ")", ";", "}", "else", "{", "shell", ".", "write", "(", "item", ".", "filename", ")", ";", "}", "}", ")", ";", "context", ".", "end", "(", ")", ";", "}" ]
display a list of items
[ "display", "a", "list", "of", "items" ]
ec48b5974f13233285483201c1808d7c3b3045c3
https://github.com/lukaaash/sftp-ws/blob/ec48b5974f13233285483201c1808d7c3b3045c3/examples/console-client/index.js#L277-L297
train
lukaaash/sftp-ws
examples/console-client/index.js
done
function done(context, err, message) { if (err) return fail(context, err); if (typeof message !== "undefined") shell.write(message); context.end(); }
javascript
function done(context, err, message) { if (err) return fail(context, err); if (typeof message !== "undefined") shell.write(message); context.end(); }
[ "function", "done", "(", "context", ",", "err", ",", "message", ")", "{", "if", "(", "err", ")", "return", "fail", "(", "context", ",", "err", ")", ";", "if", "(", "typeof", "message", "!==", "\"undefined\"", ")", "shell", ".", "write", "(", "message", ")", ";", "context", ".", "end", "(", ")", ";", "}" ]
finish command successfully or with an error
[ "finish", "command", "successfully", "or", "with", "an", "error" ]
ec48b5974f13233285483201c1808d7c3b3045c3
https://github.com/lukaaash/sftp-ws/blob/ec48b5974f13233285483201c1808d7c3b3045c3/examples/console-client/index.js#L327-L331
train
lukaaash/sftp-ws
examples/console-client/index.js
fail
function fail(context, err) { var message; switch (err.code) { case "ENOENT": message = err.path + ": No such file or directory"; break; case "ENOSYS": message = "Command not supported"; break; default: message = err["description"] || err.message; break; } return context.fail(message); }
javascript
function fail(context, err) { var message; switch (err.code) { case "ENOENT": message = err.path + ": No such file or directory"; break; case "ENOSYS": message = "Command not supported"; break; default: message = err["description"] || err.message; break; } return context.fail(message); }
[ "function", "fail", "(", "context", ",", "err", ")", "{", "var", "message", ";", "switch", "(", "err", ".", "code", ")", "{", "case", "\"ENOENT\"", ":", "message", "=", "err", ".", "path", "+", "\": No such file or directory\"", ";", "break", ";", "case", "\"ENOSYS\"", ":", "message", "=", "\"Command not supported\"", ";", "break", ";", "default", ":", "message", "=", "err", "[", "\"description\"", "]", "||", "err", ".", "message", ";", "break", ";", "}", "return", "context", ".", "fail", "(", "message", ")", ";", "}" ]
fail command with an error message
[ "fail", "command", "with", "an", "error", "message" ]
ec48b5974f13233285483201c1808d7c3b3045c3
https://github.com/lukaaash/sftp-ws/blob/ec48b5974f13233285483201c1808d7c3b3045c3/examples/console-client/index.js#L334-L349
train
leodido/luhn.js
gulpfile.babel.js
umd
function umd() { let bundler = browserify(src, { debug: true, standalone: 'luhn' }) .transform(babelify) // .configure({ optional: ['runtime'] }) .bundle(); return bundler .pipe(source(pack.main)) // gives streaming vinyl file object .pipe(buffer()) // convert from streaming to buffered vinyl file object .pipe(sourcemaps.init({ loadMaps: true })) // loads map from browserify file .pipe(sourcemaps.write('./')) .pipe(gulp.dest('./')); }
javascript
function umd() { let bundler = browserify(src, { debug: true, standalone: 'luhn' }) .transform(babelify) // .configure({ optional: ['runtime'] }) .bundle(); return bundler .pipe(source(pack.main)) // gives streaming vinyl file object .pipe(buffer()) // convert from streaming to buffered vinyl file object .pipe(sourcemaps.init({ loadMaps: true })) // loads map from browserify file .pipe(sourcemaps.write('./')) .pipe(gulp.dest('./')); }
[ "function", "umd", "(", ")", "{", "let", "bundler", "=", "browserify", "(", "src", ",", "{", "debug", ":", "true", ",", "standalone", ":", "'luhn'", "}", ")", ".", "transform", "(", "babelify", ")", ".", "bundle", "(", ")", ";", "return", "bundler", ".", "pipe", "(", "source", "(", "pack", ".", "main", ")", ")", ".", "pipe", "(", "buffer", "(", ")", ")", ".", "pipe", "(", "sourcemaps", ".", "init", "(", "{", "loadMaps", ":", "true", "}", ")", ")", ".", "pipe", "(", "sourcemaps", ".", "write", "(", "'./'", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "'./'", ")", ")", ";", "}" ]
umd standalone library with sourcemaps
[ "umd", "standalone", "library", "with", "sourcemaps" ]
ef24d03e0e7f56ba6bafde0f966813ecb8cf7419
https://github.com/leodido/luhn.js/blob/ef24d03e0e7f56ba6bafde0f966813ecb8cf7419/gulpfile.babel.js#L33-L44
train
leodido/luhn.js
gulpfile.babel.js
min
function min() { return gulp.src(pack.main) .pipe(uglify()) .on('error', gutil.log) .pipe(rename({ extname: minext + '.js' })) .pipe(gulp.dest('./')); }
javascript
function min() { return gulp.src(pack.main) .pipe(uglify()) .on('error', gutil.log) .pipe(rename({ extname: minext + '.js' })) .pipe(gulp.dest('./')); }
[ "function", "min", "(", ")", "{", "return", "gulp", ".", "src", "(", "pack", ".", "main", ")", ".", "pipe", "(", "uglify", "(", ")", ")", ".", "on", "(", "'error'", ",", "gutil", ".", "log", ")", ".", "pipe", "(", "rename", "(", "{", "extname", ":", "minext", "+", "'.js'", "}", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "'./'", ")", ")", ";", "}" ]
minified umd standalone library
[ "minified", "umd", "standalone", "library" ]
ef24d03e0e7f56ba6bafde0f966813ecb8cf7419
https://github.com/leodido/luhn.js/blob/ef24d03e0e7f56ba6bafde0f966813ecb8cf7419/gulpfile.babel.js#L47-L53
train
hubiinetwork/nahmii-sdk
lib/event-provider/index.js
subscribeToEvents
function subscribeToEvents() { const socket = _socket.get(this); function onEventApiError(error) { dbg('Event API connection error: ' + JSON.stringify(error)); } socket.on('pong', (latency) => { dbg(`Event API latency: ${latency} ms`); }); socket.on('connect_error', onEventApiError); socket.on('error', onEventApiError); socket.on('disconnect', onEventApiError); socket.on('reconnect_error', onEventApiError); socket.on('reconnect_failed', () => { onEventApiError('Reconnecting to the Event API failed'); }); socket.on('new_receipt', receiptJSON => { const receipt = Receipt.from(receiptJSON, _provider.get(this)); _eventEmitter.get(this).emit(EventNames.newReceipt, receipt); }); }
javascript
function subscribeToEvents() { const socket = _socket.get(this); function onEventApiError(error) { dbg('Event API connection error: ' + JSON.stringify(error)); } socket.on('pong', (latency) => { dbg(`Event API latency: ${latency} ms`); }); socket.on('connect_error', onEventApiError); socket.on('error', onEventApiError); socket.on('disconnect', onEventApiError); socket.on('reconnect_error', onEventApiError); socket.on('reconnect_failed', () => { onEventApiError('Reconnecting to the Event API failed'); }); socket.on('new_receipt', receiptJSON => { const receipt = Receipt.from(receiptJSON, _provider.get(this)); _eventEmitter.get(this).emit(EventNames.newReceipt, receipt); }); }
[ "function", "subscribeToEvents", "(", ")", "{", "const", "socket", "=", "_socket", ".", "get", "(", "this", ")", ";", "function", "onEventApiError", "(", "error", ")", "{", "dbg", "(", "'Event API connection error: '", "+", "JSON", ".", "stringify", "(", "error", ")", ")", ";", "}", "socket", ".", "on", "(", "'pong'", ",", "(", "latency", ")", "=>", "{", "dbg", "(", "`", "${", "latency", "}", "`", ")", ";", "}", ")", ";", "socket", ".", "on", "(", "'connect_error'", ",", "onEventApiError", ")", ";", "socket", ".", "on", "(", "'error'", ",", "onEventApiError", ")", ";", "socket", ".", "on", "(", "'disconnect'", ",", "onEventApiError", ")", ";", "socket", ".", "on", "(", "'reconnect_error'", ",", "onEventApiError", ")", ";", "socket", ".", "on", "(", "'reconnect_failed'", ",", "(", ")", "=>", "{", "onEventApiError", "(", "'Reconnecting to the Event API failed'", ")", ";", "}", ")", ";", "socket", ".", "on", "(", "'new_receipt'", ",", "receiptJSON", "=>", "{", "const", "receipt", "=", "Receipt", ".", "from", "(", "receiptJSON", ",", "_provider", ".", "get", "(", "this", ")", ")", ";", "_eventEmitter", ".", "get", "(", "this", ")", ".", "emit", "(", "EventNames", ".", "newReceipt", ",", "receipt", ")", ";", "}", ")", ";", "}" ]
Subscribes to critical socket.io events and relays nahmii events to any registered listeners. Private method, invoke with 'this' bound to provider instance. @private
[ "Subscribes", "to", "critical", "socket", ".", "io", "events", "and", "relays", "nahmii", "events", "to", "any", "registered", "listeners", ".", "Private", "method", "invoke", "with", "this", "bound", "to", "provider", "instance", "." ]
7a372deebf7d7326e3639ddb01c9ce6224fc83d6
https://github.com/hubiinetwork/nahmii-sdk/blob/7a372deebf7d7326e3639ddb01c9ce6224fc83d6/lib/event-provider/index.js#L136-L158
train
AdamBrodzinski/RedScript
lib/transform.js
function(line) { // example: def bar(a, b) do // // (^\s*) begining of line // (def|defp) $1 public or private def // (.*?) $2 in betweend def ... do // \s* optional space // do opening keyword (bracket in JS) // \s*$ end of line var parts = line.match(/^(\s*)(defp\s|def\s)(.*?)\s*do\s*$/); if (!parts) return line; // ^( $1 // \s*[\w$]+ function name // ) // ( $2 optional params including parens // \( literal parens // (.*?) $3 just params // \) literal parens // )? // \s*$ trailing space var middle = /^(\s*[\w$]+)(\((.*?)\))?\s*$/; var leading = parts[1]; var funcName = parts[3].trim().match(middle)[1]; var params = parts[3].trim().match(middle)[3] || ''; var _export = (parts[2].trim() === 'def') ? 'export ' : ''; return leading + _export + 'function ' + funcName + '('+ params +') {'; }
javascript
function(line) { // example: def bar(a, b) do // // (^\s*) begining of line // (def|defp) $1 public or private def // (.*?) $2 in betweend def ... do // \s* optional space // do opening keyword (bracket in JS) // \s*$ end of line var parts = line.match(/^(\s*)(defp\s|def\s)(.*?)\s*do\s*$/); if (!parts) return line; // ^( $1 // \s*[\w$]+ function name // ) // ( $2 optional params including parens // \( literal parens // (.*?) $3 just params // \) literal parens // )? // \s*$ trailing space var middle = /^(\s*[\w$]+)(\((.*?)\))?\s*$/; var leading = parts[1]; var funcName = parts[3].trim().match(middle)[1]; var params = parts[3].trim().match(middle)[3] || ''; var _export = (parts[2].trim() === 'def') ? 'export ' : ''; return leading + _export + 'function ' + funcName + '('+ params +') {'; }
[ "function", "(", "line", ")", "{", "var", "parts", "=", "line", ".", "match", "(", "/", "^(\\s*)(defp\\s|def\\s)(.*?)\\s*do\\s*$", "/", ")", ";", "if", "(", "!", "parts", ")", "return", "line", ";", "var", "middle", "=", "/", "^(\\s*[\\w$]+)(\\((.*?)\\))?\\s*$", "/", ";", "var", "leading", "=", "parts", "[", "1", "]", ";", "var", "funcName", "=", "parts", "[", "3", "]", ".", "trim", "(", ")", ".", "match", "(", "middle", ")", "[", "1", "]", ";", "var", "params", "=", "parts", "[", "3", "]", ".", "trim", "(", ")", ".", "match", "(", "middle", ")", "[", "3", "]", "||", "''", ";", "var", "_export", "=", "(", "parts", "[", "2", "]", ".", "trim", "(", ")", "===", "'def'", ")", "?", "'export '", ":", "''", ";", "return", "leading", "+", "_export", "+", "'function '", "+", "funcName", "+", "'('", "+", "params", "+", "') {'", ";", "}" ]
defines public and private module functions returns String a -> String b
[ "defines", "public", "and", "private", "module", "functions", "returns", "String", "a", "-", ">", "String", "b" ]
ec5b657770c268441bb9cf37cac2080a5707da95
https://github.com/AdamBrodzinski/RedScript/blob/ec5b657770c268441bb9cf37cac2080a5707da95/lib/transform.js#L38-L67
train
AdamBrodzinski/RedScript
lib/transform.js
function(line) { var newLine; // ex: [foo <- 1,2,3] // [ opening array // (.*) $1 array to concat into // (<-) $2 // (.*) $3 content to be merged // ] closing array var regexArr = /\[(.*)(\<\-)(.*)\]/; // ex: {foo <- foo: true, bar: 2} // { opening object // (.*) $1 obj to merge into // (<-) $2 // (.*) $3 content to be merged // } closing object var regexObj = /\{(.*)(\<\-)(.*)\}/; newLine = line.replace(regexArr, function($0, $1, $2, $3) { return $1.trim() + '.concat([' + $3 + ']);'; }); return newLine.replace(regexObj, function($0, $1, $2, $3) { return $1.trim() + '.merge({' + $3 + '});'; }); }
javascript
function(line) { var newLine; // ex: [foo <- 1,2,3] // [ opening array // (.*) $1 array to concat into // (<-) $2 // (.*) $3 content to be merged // ] closing array var regexArr = /\[(.*)(\<\-)(.*)\]/; // ex: {foo <- foo: true, bar: 2} // { opening object // (.*) $1 obj to merge into // (<-) $2 // (.*) $3 content to be merged // } closing object var regexObj = /\{(.*)(\<\-)(.*)\}/; newLine = line.replace(regexArr, function($0, $1, $2, $3) { return $1.trim() + '.concat([' + $3 + ']);'; }); return newLine.replace(regexObj, function($0, $1, $2, $3) { return $1.trim() + '.merge({' + $3 + '});'; }); }
[ "function", "(", "line", ")", "{", "var", "newLine", ";", "var", "regexArr", "=", "/", "\\[(.*)(\\<\\-)(.*)\\]", "/", ";", "var", "regexObj", "=", "/", "\\{(.*)(\\<\\-)(.*)\\}", "/", ";", "newLine", "=", "line", ".", "replace", "(", "regexArr", ",", "function", "(", "$0", ",", "$1", ",", "$2", ",", "$3", ")", "{", "return", "$1", ".", "trim", "(", ")", "+", "'.concat(['", "+", "$3", "+", "']);'", ";", "}", ")", ";", "return", "newLine", ".", "replace", "(", "regexObj", ",", "function", "(", "$0", ",", "$1", ",", "$2", ",", "$3", ")", "{", "return", "$1", ".", "trim", "(", ")", "+", "'.merge({'", "+", "$3", "+", "'});'", ";", "}", ")", ";", "}" ]
merges immutable objects or arrays together returns String a -> String b
[ "merges", "immutable", "objects", "or", "arrays", "together", "returns", "String", "a", "-", ">", "String", "b" ]
ec5b657770c268441bb9cf37cac2080a5707da95
https://github.com/AdamBrodzinski/RedScript/blob/ec5b657770c268441bb9cf37cac2080a5707da95/lib/transform.js#L72-L98
train
AdamBrodzinski/RedScript
lib/transform.js
function(line, index, lines) { var newLine; if (insideString('|>', line)) return line; // line does not have a one liner pipeline if (!line.match(/(\=|return)(.*?)(\|\>)/)) return line; // if next line has a pipe operator if (lines[index] && lines[index + 1].match(/^\s*\|\>/)) return line; // http://rubular.com/r/wiBJtf12Vn // (^.+?) $1 value to pipe // \s* optional spaces // (\|\>) $2 |> pipe operator // (.*?)$ $3 tail minus first pipe ($2) // var parts = line.match(/(^.+?)\s*(\|\>)(.*?)$/); var head = parts[1] var tail = parts[2].concat(parts[3]); // process head depending on if it's immuttable or not if (head.match('Immutable')) { head = head.replace('Immutable', '_.chain(Immutable'); } else if (head.match(/^\s*return/)) { head = head.replace('return ', 'return _.chain('); } else if (head.match(/\s=\s/)) { head = head.replace('= ', '= _.chain('); } tail = tail.replace(/(\s*\|\>\s*)/g, function($0, $1) { return ').pipesCall('; }) return head + tail + ').value();' }
javascript
function(line, index, lines) { var newLine; if (insideString('|>', line)) return line; // line does not have a one liner pipeline if (!line.match(/(\=|return)(.*?)(\|\>)/)) return line; // if next line has a pipe operator if (lines[index] && lines[index + 1].match(/^\s*\|\>/)) return line; // http://rubular.com/r/wiBJtf12Vn // (^.+?) $1 value to pipe // \s* optional spaces // (\|\>) $2 |> pipe operator // (.*?)$ $3 tail minus first pipe ($2) // var parts = line.match(/(^.+?)\s*(\|\>)(.*?)$/); var head = parts[1] var tail = parts[2].concat(parts[3]); // process head depending on if it's immuttable or not if (head.match('Immutable')) { head = head.replace('Immutable', '_.chain(Immutable'); } else if (head.match(/^\s*return/)) { head = head.replace('return ', 'return _.chain('); } else if (head.match(/\s=\s/)) { head = head.replace('= ', '= _.chain('); } tail = tail.replace(/(\s*\|\>\s*)/g, function($0, $1) { return ').pipesCall('; }) return head + tail + ').value();' }
[ "function", "(", "line", ",", "index", ",", "lines", ")", "{", "var", "newLine", ";", "if", "(", "insideString", "(", "'|>'", ",", "line", ")", ")", "return", "line", ";", "if", "(", "!", "line", ".", "match", "(", "/", "(\\=|return)(.*?)(\\|\\>)", "/", ")", ")", "return", "line", ";", "if", "(", "lines", "[", "index", "]", "&&", "lines", "[", "index", "+", "1", "]", ".", "match", "(", "/", "^\\s*\\|\\>", "/", ")", ")", "return", "line", ";", "var", "parts", "=", "line", ".", "match", "(", "/", "(^.+?)\\s*(\\|\\>)(.*?)$", "/", ")", ";", "var", "head", "=", "parts", "[", "1", "]", "var", "tail", "=", "parts", "[", "2", "]", ".", "concat", "(", "parts", "[", "3", "]", ")", ";", "if", "(", "head", ".", "match", "(", "'Immutable'", ")", ")", "{", "head", "=", "head", ".", "replace", "(", "'Immutable'", ",", "'_.chain(Immutable'", ")", ";", "}", "else", "if", "(", "head", ".", "match", "(", "/", "^\\s*return", "/", ")", ")", "{", "head", "=", "head", ".", "replace", "(", "'return '", ",", "'return _.chain('", ")", ";", "}", "else", "if", "(", "head", ".", "match", "(", "/", "\\s=\\s", "/", ")", ")", "{", "head", "=", "head", ".", "replace", "(", "'= '", ",", "'= _.chain('", ")", ";", "}", "tail", "=", "tail", ".", "replace", "(", "/", "(\\s*\\|\\>\\s*)", "/", "g", ",", "function", "(", "$0", ",", "$1", ")", "{", "return", "').pipesCall('", ";", "}", ")", "return", "head", "+", "tail", "+", "').value();'", "}" ]
One liner piping returns String a -> String b
[ "One", "liner", "piping", "returns", "String", "a", "-", ">", "String", "b" ]
ec5b657770c268441bb9cf37cac2080a5707da95
https://github.com/AdamBrodzinski/RedScript/blob/ec5b657770c268441bb9cf37cac2080a5707da95/lib/transform.js#L120-L154
train
AdamBrodzinski/RedScript
lib/transform.js
function(line) { //^ // (\s*) $1 opts leading spaces // ([\w$]+\s*) $2 variable name & trailing spaces // (\=) $3 division equals OR // \s* opt spaces // (.*?) rest of expression to assign // $ var parts = line.match(/^(\s*)([\w$]+)\s*(\=)\s*(.*?)$/); if (!parts) return line; var leadingSpace = parts[1]; var name = parts[2].trim(); var operator = parts[3].trim(); var rest = parts[4]; return leadingSpace + 'const ' + name + ' ' + operator + ' ' + rest; }
javascript
function(line) { //^ // (\s*) $1 opts leading spaces // ([\w$]+\s*) $2 variable name & trailing spaces // (\=) $3 division equals OR // \s* opt spaces // (.*?) rest of expression to assign // $ var parts = line.match(/^(\s*)([\w$]+)\s*(\=)\s*(.*?)$/); if (!parts) return line; var leadingSpace = parts[1]; var name = parts[2].trim(); var operator = parts[3].trim(); var rest = parts[4]; return leadingSpace + 'const ' + name + ' ' + operator + ' ' + rest; }
[ "function", "(", "line", ")", "{", "var", "parts", "=", "line", ".", "match", "(", "/", "^(\\s*)([\\w$]+)\\s*(\\=)\\s*(.*?)$", "/", ")", ";", "if", "(", "!", "parts", ")", "return", "line", ";", "var", "leadingSpace", "=", "parts", "[", "1", "]", ";", "var", "name", "=", "parts", "[", "2", "]", ".", "trim", "(", ")", ";", "var", "operator", "=", "parts", "[", "3", "]", ".", "trim", "(", ")", ";", "var", "rest", "=", "parts", "[", "4", "]", ";", "return", "leadingSpace", "+", "'const '", "+", "name", "+", "' '", "+", "operator", "+", "' '", "+", "rest", ";", "}" ]
adds `const` to any declaration, works with shorthand operators String a -> String b
[ "adds", "const", "to", "any", "declaration", "works", "with", "shorthand", "operators", "String", "a", "-", ">", "String", "b" ]
ec5b657770c268441bb9cf37cac2080a5707da95
https://github.com/AdamBrodzinski/RedScript/blob/ec5b657770c268441bb9cf37cac2080a5707da95/lib/transform.js#L229-L246
train
GrosSacASac/DOM99
documentation/presentation/reveal.js-2.6.2/plugin/zoom-js/zoom.js
magnify
function magnify( pageOffsetX, pageOffsetY, elementOffsetX, elementOffsetY, scale ) { if( supportsTransforms ) { var origin = pageOffsetX +'px '+ pageOffsetY +'px', transform = 'translate('+ -elementOffsetX +'px,'+ -elementOffsetY +'px) scale('+ scale +')'; document.body.style.transformOrigin = origin; document.body.style.OTransformOrigin = origin; document.body.style.msTransformOrigin = origin; document.body.style.MozTransformOrigin = origin; document.body.style.WebkitTransformOrigin = origin; document.body.style.transform = transform; document.body.style.OTransform = transform; document.body.style.msTransform = transform; document.body.style.MozTransform = transform; document.body.style.WebkitTransform = transform; } else { // Reset all values if( scale === 1 ) { document.body.style.position = ''; document.body.style.left = ''; document.body.style.top = ''; document.body.style.width = ''; document.body.style.height = ''; document.body.style.zoom = ''; } // Apply scale else { document.body.style.position = 'relative'; document.body.style.left = ( - ( pageOffsetX + elementOffsetX ) / scale ) + 'px'; document.body.style.top = ( - ( pageOffsetY + elementOffsetY ) / scale ) + 'px'; document.body.style.width = ( scale * 100 ) + '%'; document.body.style.height = ( scale * 100 ) + '%'; document.body.style.zoom = scale; } } level = scale; if( level !== 1 && document.documentElement.classList ) { document.documentElement.classList.add( 'zoomed' ); } else { document.documentElement.classList.remove( 'zoomed' ); } }
javascript
function magnify( pageOffsetX, pageOffsetY, elementOffsetX, elementOffsetY, scale ) { if( supportsTransforms ) { var origin = pageOffsetX +'px '+ pageOffsetY +'px', transform = 'translate('+ -elementOffsetX +'px,'+ -elementOffsetY +'px) scale('+ scale +')'; document.body.style.transformOrigin = origin; document.body.style.OTransformOrigin = origin; document.body.style.msTransformOrigin = origin; document.body.style.MozTransformOrigin = origin; document.body.style.WebkitTransformOrigin = origin; document.body.style.transform = transform; document.body.style.OTransform = transform; document.body.style.msTransform = transform; document.body.style.MozTransform = transform; document.body.style.WebkitTransform = transform; } else { // Reset all values if( scale === 1 ) { document.body.style.position = ''; document.body.style.left = ''; document.body.style.top = ''; document.body.style.width = ''; document.body.style.height = ''; document.body.style.zoom = ''; } // Apply scale else { document.body.style.position = 'relative'; document.body.style.left = ( - ( pageOffsetX + elementOffsetX ) / scale ) + 'px'; document.body.style.top = ( - ( pageOffsetY + elementOffsetY ) / scale ) + 'px'; document.body.style.width = ( scale * 100 ) + '%'; document.body.style.height = ( scale * 100 ) + '%'; document.body.style.zoom = scale; } } level = scale; if( level !== 1 && document.documentElement.classList ) { document.documentElement.classList.add( 'zoomed' ); } else { document.documentElement.classList.remove( 'zoomed' ); } }
[ "function", "magnify", "(", "pageOffsetX", ",", "pageOffsetY", ",", "elementOffsetX", ",", "elementOffsetY", ",", "scale", ")", "{", "if", "(", "supportsTransforms", ")", "{", "var", "origin", "=", "pageOffsetX", "+", "'px '", "+", "pageOffsetY", "+", "'px'", ",", "transform", "=", "'translate('", "+", "-", "elementOffsetX", "+", "'px,'", "+", "-", "elementOffsetY", "+", "'px) scale('", "+", "scale", "+", "')'", ";", "document", ".", "body", ".", "style", ".", "transformOrigin", "=", "origin", ";", "document", ".", "body", ".", "style", ".", "OTransformOrigin", "=", "origin", ";", "document", ".", "body", ".", "style", ".", "msTransformOrigin", "=", "origin", ";", "document", ".", "body", ".", "style", ".", "MozTransformOrigin", "=", "origin", ";", "document", ".", "body", ".", "style", ".", "WebkitTransformOrigin", "=", "origin", ";", "document", ".", "body", ".", "style", ".", "transform", "=", "transform", ";", "document", ".", "body", ".", "style", ".", "OTransform", "=", "transform", ";", "document", ".", "body", ".", "style", ".", "msTransform", "=", "transform", ";", "document", ".", "body", ".", "style", ".", "MozTransform", "=", "transform", ";", "document", ".", "body", ".", "style", ".", "WebkitTransform", "=", "transform", ";", "}", "else", "{", "if", "(", "scale", "===", "1", ")", "{", "document", ".", "body", ".", "style", ".", "position", "=", "''", ";", "document", ".", "body", ".", "style", ".", "left", "=", "''", ";", "document", ".", "body", ".", "style", ".", "top", "=", "''", ";", "document", ".", "body", ".", "style", ".", "width", "=", "''", ";", "document", ".", "body", ".", "style", ".", "height", "=", "''", ";", "document", ".", "body", ".", "style", ".", "zoom", "=", "''", ";", "}", "else", "{", "document", ".", "body", ".", "style", ".", "position", "=", "'relative'", ";", "document", ".", "body", ".", "style", ".", "left", "=", "(", "-", "(", "pageOffsetX", "+", "elementOffsetX", ")", "/", "scale", ")", "+", "'px'", ";", "document", ".", "body", ".", "style", ".", "top", "=", "(", "-", "(", "pageOffsetY", "+", "elementOffsetY", ")", "/", "scale", ")", "+", "'px'", ";", "document", ".", "body", ".", "style", ".", "width", "=", "(", "scale", "*", "100", ")", "+", "'%'", ";", "document", ".", "body", ".", "style", ".", "height", "=", "(", "scale", "*", "100", ")", "+", "'%'", ";", "document", ".", "body", ".", "style", ".", "zoom", "=", "scale", ";", "}", "}", "level", "=", "scale", ";", "if", "(", "level", "!==", "1", "&&", "document", ".", "documentElement", ".", "classList", ")", "{", "document", ".", "documentElement", ".", "classList", ".", "add", "(", "'zoomed'", ")", ";", "}", "else", "{", "document", ".", "documentElement", ".", "classList", ".", "remove", "(", "'zoomed'", ")", ";", "}", "}" ]
Applies the CSS required to zoom in, prioritizes use of CSS3 transforms but falls back on zoom for IE. @param {Number} pageOffsetX @param {Number} pageOffsetY @param {Number} elementOffsetX @param {Number} elementOffsetY @param {Number} scale
[ "Applies", "the", "CSS", "required", "to", "zoom", "in", "prioritizes", "use", "of", "CSS3", "transforms", "but", "falls", "back", "on", "zoom", "for", "IE", "." ]
0563cb3d4865d968e829d39c68dc62af3fc95cc8
https://github.com/GrosSacASac/DOM99/blob/0563cb3d4865d968e829d39c68dc62af3fc95cc8/documentation/presentation/reveal.js-2.6.2/plugin/zoom-js/zoom.js#L81-L128
train
GrosSacASac/DOM99
documentation/presentation/reveal.js-2.6.2/plugin/zoom-js/zoom.js
pan
function pan() { var range = 0.12, rangeX = window.innerWidth * range, rangeY = window.innerHeight * range, scrollOffset = getScrollOffset(); // Up if( mouseY < rangeY ) { window.scroll( scrollOffset.x, scrollOffset.y - ( 1 - ( mouseY / rangeY ) ) * ( 14 / level ) ); } // Down else if( mouseY > window.innerHeight - rangeY ) { window.scroll( scrollOffset.x, scrollOffset.y + ( 1 - ( window.innerHeight - mouseY ) / rangeY ) * ( 14 / level ) ); } // Left if( mouseX < rangeX ) { window.scroll( scrollOffset.x - ( 1 - ( mouseX / rangeX ) ) * ( 14 / level ), scrollOffset.y ); } // Right else if( mouseX > window.innerWidth - rangeX ) { window.scroll( scrollOffset.x + ( 1 - ( window.innerWidth - mouseX ) / rangeX ) * ( 14 / level ), scrollOffset.y ); } }
javascript
function pan() { var range = 0.12, rangeX = window.innerWidth * range, rangeY = window.innerHeight * range, scrollOffset = getScrollOffset(); // Up if( mouseY < rangeY ) { window.scroll( scrollOffset.x, scrollOffset.y - ( 1 - ( mouseY / rangeY ) ) * ( 14 / level ) ); } // Down else if( mouseY > window.innerHeight - rangeY ) { window.scroll( scrollOffset.x, scrollOffset.y + ( 1 - ( window.innerHeight - mouseY ) / rangeY ) * ( 14 / level ) ); } // Left if( mouseX < rangeX ) { window.scroll( scrollOffset.x - ( 1 - ( mouseX / rangeX ) ) * ( 14 / level ), scrollOffset.y ); } // Right else if( mouseX > window.innerWidth - rangeX ) { window.scroll( scrollOffset.x + ( 1 - ( window.innerWidth - mouseX ) / rangeX ) * ( 14 / level ), scrollOffset.y ); } }
[ "function", "pan", "(", ")", "{", "var", "range", "=", "0.12", ",", "rangeX", "=", "window", ".", "innerWidth", "*", "range", ",", "rangeY", "=", "window", ".", "innerHeight", "*", "range", ",", "scrollOffset", "=", "getScrollOffset", "(", ")", ";", "if", "(", "mouseY", "<", "rangeY", ")", "{", "window", ".", "scroll", "(", "scrollOffset", ".", "x", ",", "scrollOffset", ".", "y", "-", "(", "1", "-", "(", "mouseY", "/", "rangeY", ")", ")", "*", "(", "14", "/", "level", ")", ")", ";", "}", "else", "if", "(", "mouseY", ">", "window", ".", "innerHeight", "-", "rangeY", ")", "{", "window", ".", "scroll", "(", "scrollOffset", ".", "x", ",", "scrollOffset", ".", "y", "+", "(", "1", "-", "(", "window", ".", "innerHeight", "-", "mouseY", ")", "/", "rangeY", ")", "*", "(", "14", "/", "level", ")", ")", ";", "}", "if", "(", "mouseX", "<", "rangeX", ")", "{", "window", ".", "scroll", "(", "scrollOffset", ".", "x", "-", "(", "1", "-", "(", "mouseX", "/", "rangeX", ")", ")", "*", "(", "14", "/", "level", ")", ",", "scrollOffset", ".", "y", ")", ";", "}", "else", "if", "(", "mouseX", ">", "window", ".", "innerWidth", "-", "rangeX", ")", "{", "window", ".", "scroll", "(", "scrollOffset", ".", "x", "+", "(", "1", "-", "(", "window", ".", "innerWidth", "-", "mouseX", ")", "/", "rangeX", ")", "*", "(", "14", "/", "level", ")", ",", "scrollOffset", ".", "y", ")", ";", "}", "}" ]
Pan the document when the mosue cursor approaches the edges of the window.
[ "Pan", "the", "document", "when", "the", "mosue", "cursor", "approaches", "the", "edges", "of", "the", "window", "." ]
0563cb3d4865d968e829d39c68dc62af3fc95cc8
https://github.com/GrosSacASac/DOM99/blob/0563cb3d4865d968e829d39c68dc62af3fc95cc8/documentation/presentation/reveal.js-2.6.2/plugin/zoom-js/zoom.js#L134-L157
train
GrosSacASac/DOM99
documentation/presentation/reveal.js-2.6.2/plugin/zoom-js/zoom.js
function() { clearTimeout( panEngageTimeout ); clearInterval( panUpdateInterval ); var scrollOffset = getScrollOffset(); if( currentOptions && currentOptions.element ) { scrollOffset.x -= ( window.innerWidth - ( currentOptions.width * currentOptions.scale ) ) / 2; } magnify( scrollOffset.x, scrollOffset.y, 0, 0, 1 ); level = 1; }
javascript
function() { clearTimeout( panEngageTimeout ); clearInterval( panUpdateInterval ); var scrollOffset = getScrollOffset(); if( currentOptions && currentOptions.element ) { scrollOffset.x -= ( window.innerWidth - ( currentOptions.width * currentOptions.scale ) ) / 2; } magnify( scrollOffset.x, scrollOffset.y, 0, 0, 1 ); level = 1; }
[ "function", "(", ")", "{", "clearTimeout", "(", "panEngageTimeout", ")", ";", "clearInterval", "(", "panUpdateInterval", ")", ";", "var", "scrollOffset", "=", "getScrollOffset", "(", ")", ";", "if", "(", "currentOptions", "&&", "currentOptions", ".", "element", ")", "{", "scrollOffset", ".", "x", "-=", "(", "window", ".", "innerWidth", "-", "(", "currentOptions", ".", "width", "*", "currentOptions", ".", "scale", ")", ")", "/", "2", ";", "}", "magnify", "(", "scrollOffset", ".", "x", ",", "scrollOffset", ".", "y", ",", "0", ",", "0", ",", "1", ")", ";", "level", "=", "1", ";", "}" ]
Resets the document zoom state to its default.
[ "Resets", "the", "document", "zoom", "state", "to", "its", "default", "." ]
0563cb3d4865d968e829d39c68dc62af3fc95cc8
https://github.com/GrosSacASac/DOM99/blob/0563cb3d4865d968e829d39c68dc62af3fc95cc8/documentation/presentation/reveal.js-2.6.2/plugin/zoom-js/zoom.js#L233-L246
train
Botanalyticsco/botanalytics
examples/amazon-lex-with-lambda.js
buildResponseCard
function buildResponseCard(title, subTitle, options) { let buttons = null; if (options != null) { buttons = []; for (let i = 0; i < Math.min(5, options.length); i++) { buttons.push(options[i]); } } return { contentType: 'application/vnd.amazonaws.card.generic', version: 1, genericAttachments: [{ title, subTitle, buttons, }], }; }
javascript
function buildResponseCard(title, subTitle, options) { let buttons = null; if (options != null) { buttons = []; for (let i = 0; i < Math.min(5, options.length); i++) { buttons.push(options[i]); } } return { contentType: 'application/vnd.amazonaws.card.generic', version: 1, genericAttachments: [{ title, subTitle, buttons, }], }; }
[ "function", "buildResponseCard", "(", "title", ",", "subTitle", ",", "options", ")", "{", "let", "buttons", "=", "null", ";", "if", "(", "options", "!=", "null", ")", "{", "buttons", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "Math", ".", "min", "(", "5", ",", "options", ".", "length", ")", ";", "i", "++", ")", "{", "buttons", ".", "push", "(", "options", "[", "i", "]", ")", ";", "}", "}", "return", "{", "contentType", ":", "'application/vnd.amazonaws.card.generic'", ",", "version", ":", "1", ",", "genericAttachments", ":", "[", "{", "title", ",", "subTitle", ",", "buttons", ",", "}", "]", ",", "}", ";", "}" ]
Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons.
[ "Build", "a", "responseCard", "with", "a", "title", "subtitle", "and", "an", "optional", "set", "of", "options", "which", "should", "be", "displayed", "as", "buttons", "." ]
a6ca41f226752ab765b939dbc11bb6402465603a
https://github.com/Botanalyticsco/botanalytics/blob/a6ca41f226752ab765b939dbc11bb6402465603a/examples/amazon-lex-with-lambda.js#L74-L91
train
Botanalyticsco/botanalytics
examples/amazon-lex-with-lambda.js
getAvailabilities
function getAvailabilities(date) { const dayOfWeek = parseLocalDate(date).getDay(); const availabilities = []; const availableProbability = 0.3; if (dayOfWeek === 1) { let startHour = 10; while (startHour <= 16) { if (Math.random() < availableProbability) { // Add an availability window for the given hour, with duration determined by another random number. const appointmentType = getRandomInt(1, 4); if (appointmentType === 1) { availabilities.push(`${startHour}:00`); } else if (appointmentType === 2) { availabilities.push(`${startHour}:30`); } else { availabilities.push(`${startHour}:00`); availabilities.push(`${startHour}:30`); } } startHour++; } } if (dayOfWeek === 3 || dayOfWeek === 5) { availabilities.push('10:00'); availabilities.push('16:00'); availabilities.push('16:30'); } return availabilities; }
javascript
function getAvailabilities(date) { const dayOfWeek = parseLocalDate(date).getDay(); const availabilities = []; const availableProbability = 0.3; if (dayOfWeek === 1) { let startHour = 10; while (startHour <= 16) { if (Math.random() < availableProbability) { // Add an availability window for the given hour, with duration determined by another random number. const appointmentType = getRandomInt(1, 4); if (appointmentType === 1) { availabilities.push(`${startHour}:00`); } else if (appointmentType === 2) { availabilities.push(`${startHour}:30`); } else { availabilities.push(`${startHour}:00`); availabilities.push(`${startHour}:30`); } } startHour++; } } if (dayOfWeek === 3 || dayOfWeek === 5) { availabilities.push('10:00'); availabilities.push('16:00'); availabilities.push('16:30'); } return availabilities; }
[ "function", "getAvailabilities", "(", "date", ")", "{", "const", "dayOfWeek", "=", "parseLocalDate", "(", "date", ")", ".", "getDay", "(", ")", ";", "const", "availabilities", "=", "[", "]", ";", "const", "availableProbability", "=", "0.3", ";", "if", "(", "dayOfWeek", "===", "1", ")", "{", "let", "startHour", "=", "10", ";", "while", "(", "startHour", "<=", "16", ")", "{", "if", "(", "Math", ".", "random", "(", ")", "<", "availableProbability", ")", "{", "const", "appointmentType", "=", "getRandomInt", "(", "1", ",", "4", ")", ";", "if", "(", "appointmentType", "===", "1", ")", "{", "availabilities", ".", "push", "(", "`", "${", "startHour", "}", "`", ")", ";", "}", "else", "if", "(", "appointmentType", "===", "2", ")", "{", "availabilities", ".", "push", "(", "`", "${", "startHour", "}", "`", ")", ";", "}", "else", "{", "availabilities", ".", "push", "(", "`", "${", "startHour", "}", "`", ")", ";", "availabilities", ".", "push", "(", "`", "${", "startHour", "}", "`", ")", ";", "}", "}", "startHour", "++", ";", "}", "}", "if", "(", "dayOfWeek", "===", "3", "||", "dayOfWeek", "===", "5", ")", "{", "availabilities", ".", "push", "(", "'10:00'", ")", ";", "availabilities", ".", "push", "(", "'16:00'", ")", ";", "availabilities", ".", "push", "(", "'16:30'", ")", ";", "}", "return", "availabilities", ";", "}" ]
Helper function which in a full implementation would feed into a backend API to provide query schedule availability. The output of this function is an array of 30 minute periods of availability, expressed in ISO-8601 time format. In order to enable quick demonstration of all possible conversation paths supported in this example, the function returns a mixture of fixed and randomized results. On Mondays, availability is randomized; otherwise there is no availability on Tuesday / Thursday and availability at 10:00 - 10:30 and 4:00 - 5:00 on Wednesday / Friday.
[ "Helper", "function", "which", "in", "a", "full", "implementation", "would", "feed", "into", "a", "backend", "API", "to", "provide", "query", "schedule", "availability", ".", "The", "output", "of", "this", "function", "is", "an", "array", "of", "30", "minute", "periods", "of", "availability", "expressed", "in", "ISO", "-", "8601", "time", "format", "." ]
a6ca41f226752ab765b939dbc11bb6402465603a
https://github.com/Botanalyticsco/botanalytics/blob/a6ca41f226752ab765b939dbc11bb6402465603a/examples/amazon-lex-with-lambda.js#L138-L166
train
Botanalyticsco/botanalytics
examples/amazon-lex-with-lambda.js
getAvailabilitiesForDuration
function getAvailabilitiesForDuration(duration, availabilities) { const durationAvailabilities = []; let startTime = '10:00'; while (startTime !== '17:00') { if (availabilities.indexOf(startTime) !== -1) { if (duration === 30) { durationAvailabilities.push(startTime); } else if (availabilities.indexOf(incrementTimeByThirtyMins(startTime)) !== -1) { durationAvailabilities.push(startTime); } } startTime = incrementTimeByThirtyMins(startTime); } return durationAvailabilities; }
javascript
function getAvailabilitiesForDuration(duration, availabilities) { const durationAvailabilities = []; let startTime = '10:00'; while (startTime !== '17:00') { if (availabilities.indexOf(startTime) !== -1) { if (duration === 30) { durationAvailabilities.push(startTime); } else if (availabilities.indexOf(incrementTimeByThirtyMins(startTime)) !== -1) { durationAvailabilities.push(startTime); } } startTime = incrementTimeByThirtyMins(startTime); } return durationAvailabilities; }
[ "function", "getAvailabilitiesForDuration", "(", "duration", ",", "availabilities", ")", "{", "const", "durationAvailabilities", "=", "[", "]", ";", "let", "startTime", "=", "'10:00'", ";", "while", "(", "startTime", "!==", "'17:00'", ")", "{", "if", "(", "availabilities", ".", "indexOf", "(", "startTime", ")", "!==", "-", "1", ")", "{", "if", "(", "duration", "===", "30", ")", "{", "durationAvailabilities", ".", "push", "(", "startTime", ")", ";", "}", "else", "if", "(", "availabilities", ".", "indexOf", "(", "incrementTimeByThirtyMins", "(", "startTime", ")", ")", "!==", "-", "1", ")", "{", "durationAvailabilities", ".", "push", "(", "startTime", ")", ";", "}", "}", "startTime", "=", "incrementTimeByThirtyMins", "(", "startTime", ")", ";", "}", "return", "durationAvailabilities", ";", "}" ]
Helper function to return the windows of availability of the given duration, when provided a set of 30 minute windows.
[ "Helper", "function", "to", "return", "the", "windows", "of", "availability", "of", "the", "given", "duration", "when", "provided", "a", "set", "of", "30", "minute", "windows", "." ]
a6ca41f226752ab765b939dbc11bb6402465603a
https://github.com/Botanalyticsco/botanalytics/blob/a6ca41f226752ab765b939dbc11bb6402465603a/examples/amazon-lex-with-lambda.js#L187-L201
train
Botanalyticsco/botanalytics
examples/amazon-lex-with-lambda.js
buildAvailableTimeString
function buildAvailableTimeString(availabilities) { let prefix = 'We have availabilities at '; if (availabilities.length > 3) { prefix = 'We have plenty of availability, including '; } prefix += buildTimeOutputString(availabilities[0]); if (availabilities.length === 2) { return `${prefix} and ${buildTimeOutputString(availabilities[1])}`; } return `${prefix}, ${buildTimeOutputString(availabilities[1])} and ${buildTimeOutputString(availabilities[2])}`; }
javascript
function buildAvailableTimeString(availabilities) { let prefix = 'We have availabilities at '; if (availabilities.length > 3) { prefix = 'We have plenty of availability, including '; } prefix += buildTimeOutputString(availabilities[0]); if (availabilities.length === 2) { return `${prefix} and ${buildTimeOutputString(availabilities[1])}`; } return `${prefix}, ${buildTimeOutputString(availabilities[1])} and ${buildTimeOutputString(availabilities[2])}`; }
[ "function", "buildAvailableTimeString", "(", "availabilities", ")", "{", "let", "prefix", "=", "'We have availabilities at '", ";", "if", "(", "availabilities", ".", "length", ">", "3", ")", "{", "prefix", "=", "'We have plenty of availability, including '", ";", "}", "prefix", "+=", "buildTimeOutputString", "(", "availabilities", "[", "0", "]", ")", ";", "if", "(", "availabilities", ".", "length", "===", "2", ")", "{", "return", "`", "${", "prefix", "}", "${", "buildTimeOutputString", "(", "availabilities", "[", "1", "]", ")", "}", "`", ";", "}", "return", "`", "${", "prefix", "}", "${", "buildTimeOutputString", "(", "availabilities", "[", "1", "]", ")", "}", "${", "buildTimeOutputString", "(", "availabilities", "[", "2", "]", ")", "}", "`", ";", "}" ]
Build a string eliciting for a possible time slot among at least two availabilities.
[ "Build", "a", "string", "eliciting", "for", "a", "possible", "time", "slot", "among", "at", "least", "two", "availabilities", "." ]
a6ca41f226752ab765b939dbc11bb6402465603a
https://github.com/Botanalyticsco/botanalytics/blob/a6ca41f226752ab765b939dbc11bb6402465603a/examples/amazon-lex-with-lambda.js#L260-L270
train
Botanalyticsco/botanalytics
examples/amazon-lex-with-lambda.js
buildOptions
function buildOptions(slot, appointmentType, date, bookingMap) { const dayStrings = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; if (slot === 'AppointmentType') { return [ { text: 'cleaning (30 min)', value: 'cleaning' }, { text: 'root canal (60 min)', value: 'root canal' }, { text: 'whitening (30 min)', value: 'whitening' }, ]; } else if (slot === 'Date') { // Return the next five weekdays. const options = []; const potentialDate = new Date(); while (options.length < 5) { potentialDate.setDate(potentialDate.getDate() + 1); if (potentialDate.getDay() > 0 && potentialDate.getDay() < 6) { options.push({ text: `${potentialDate.getMonth() + 1}-${potentialDate.getDate()} (${dayStrings[potentialDate.getDay()]})`, value: potentialDate.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }) }); } } return options; } else if (slot === 'Time') { // Return the availabilities on the given date. if (!appointmentType || !date) { return null; } let availabilities = bookingMap[`${date}`]; if (!availabilities) { return null; } availabilities = getAvailabilitiesForDuration(getDuration(appointmentType), availabilities); if (availabilities.length === 0) { return null; } const options = []; for (let i = 0; i < Math.min(availabilities.length, 5); i++) { options.push({ text: buildTimeOutputString(availabilities[i]), value: buildTimeOutputString(availabilities[i]) }); } return options; } }
javascript
function buildOptions(slot, appointmentType, date, bookingMap) { const dayStrings = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; if (slot === 'AppointmentType') { return [ { text: 'cleaning (30 min)', value: 'cleaning' }, { text: 'root canal (60 min)', value: 'root canal' }, { text: 'whitening (30 min)', value: 'whitening' }, ]; } else if (slot === 'Date') { // Return the next five weekdays. const options = []; const potentialDate = new Date(); while (options.length < 5) { potentialDate.setDate(potentialDate.getDate() + 1); if (potentialDate.getDay() > 0 && potentialDate.getDay() < 6) { options.push({ text: `${potentialDate.getMonth() + 1}-${potentialDate.getDate()} (${dayStrings[potentialDate.getDay()]})`, value: potentialDate.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }) }); } } return options; } else if (slot === 'Time') { // Return the availabilities on the given date. if (!appointmentType || !date) { return null; } let availabilities = bookingMap[`${date}`]; if (!availabilities) { return null; } availabilities = getAvailabilitiesForDuration(getDuration(appointmentType), availabilities); if (availabilities.length === 0) { return null; } const options = []; for (let i = 0; i < Math.min(availabilities.length, 5); i++) { options.push({ text: buildTimeOutputString(availabilities[i]), value: buildTimeOutputString(availabilities[i]) }); } return options; } }
[ "function", "buildOptions", "(", "slot", ",", "appointmentType", ",", "date", ",", "bookingMap", ")", "{", "const", "dayStrings", "=", "[", "'Sun'", ",", "'Mon'", ",", "'Tue'", ",", "'Wed'", ",", "'Thu'", ",", "'Fri'", ",", "'Sat'", "]", ";", "if", "(", "slot", "===", "'AppointmentType'", ")", "{", "return", "[", "{", "text", ":", "'cleaning (30 min)'", ",", "value", ":", "'cleaning'", "}", ",", "{", "text", ":", "'root canal (60 min)'", ",", "value", ":", "'root canal'", "}", ",", "{", "text", ":", "'whitening (30 min)'", ",", "value", ":", "'whitening'", "}", ",", "]", ";", "}", "else", "if", "(", "slot", "===", "'Date'", ")", "{", "const", "options", "=", "[", "]", ";", "const", "potentialDate", "=", "new", "Date", "(", ")", ";", "while", "(", "options", ".", "length", "<", "5", ")", "{", "potentialDate", ".", "setDate", "(", "potentialDate", ".", "getDate", "(", ")", "+", "1", ")", ";", "if", "(", "potentialDate", ".", "getDay", "(", ")", ">", "0", "&&", "potentialDate", ".", "getDay", "(", ")", "<", "6", ")", "{", "options", ".", "push", "(", "{", "text", ":", "`", "${", "potentialDate", ".", "getMonth", "(", ")", "+", "1", "}", "${", "potentialDate", ".", "getDate", "(", ")", "}", "${", "dayStrings", "[", "potentialDate", ".", "getDay", "(", ")", "]", "}", "`", ",", "value", ":", "potentialDate", ".", "toLocaleDateString", "(", "'en-US'", ",", "{", "year", ":", "'numeric'", ",", "month", ":", "'long'", ",", "day", ":", "'numeric'", "}", ")", "}", ")", ";", "}", "}", "return", "options", ";", "}", "else", "if", "(", "slot", "===", "'Time'", ")", "{", "if", "(", "!", "appointmentType", "||", "!", "date", ")", "{", "return", "null", ";", "}", "let", "availabilities", "=", "bookingMap", "[", "`", "${", "date", "}", "`", "]", ";", "if", "(", "!", "availabilities", ")", "{", "return", "null", ";", "}", "availabilities", "=", "getAvailabilitiesForDuration", "(", "getDuration", "(", "appointmentType", ")", ",", "availabilities", ")", ";", "if", "(", "availabilities", ".", "length", "===", "0", ")", "{", "return", "null", ";", "}", "const", "options", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "Math", ".", "min", "(", "availabilities", ".", "length", ",", "5", ")", ";", "i", "++", ")", "{", "options", ".", "push", "(", "{", "text", ":", "buildTimeOutputString", "(", "availabilities", "[", "i", "]", ")", ",", "value", ":", "buildTimeOutputString", "(", "availabilities", "[", "i", "]", ")", "}", ")", ";", "}", "return", "options", ";", "}", "}" ]
Build a list of potential options for a given slot, to be used in responseCard generation.
[ "Build", "a", "list", "of", "potential", "options", "for", "a", "given", "slot", "to", "be", "used", "in", "responseCard", "generation", "." ]
a6ca41f226752ab765b939dbc11bb6402465603a
https://github.com/Botanalyticsco/botanalytics/blob/a6ca41f226752ab765b939dbc11bb6402465603a/examples/amazon-lex-with-lambda.js#L273-L312
train
alltherooms/cached-request
lib/cached-request.js
makeRequest
function makeRequest () { request = self.request.apply(null, args); requestMiddleware.use(request); request.on("response", function (response) { var contentEncoding, gzipper; //Only cache successful responses if (response.statusCode >= 200 && response.statusCode < 300) { response.on('error', function (error) { self.handleError(error); }); fs.writeFile(self.cacheDirectory + key + ".json", JSON.stringify(response.headers), function (error) { if (error) self.handleError(error); }); responseWriter = fs.createWriteStream(self.cacheDirectory + key); responseWriter.on('error', function (error) { self.handleError(error); }); contentEncoding = response.headers['content-encoding'] || ''; contentEncoding = contentEncoding.trim().toLowerCase(); if (contentEncoding === 'gzip') { response.on('error', function (error) { responseWriter.end(); }); response.pipe(responseWriter); } else { gzipper = zlib.createGzip(); response.on('error', function (error) { gzipper.end(); }); gzipper.on('error', function (error) { self.handleError(error); responseWriter.end(); }); responseWriter.on('error', function (error) { response.unpipe(gzipper); gzipper.end(); }); response.pipe(gzipper).pipe(responseWriter); } } }); self.emit("request", args[0]); }
javascript
function makeRequest () { request = self.request.apply(null, args); requestMiddleware.use(request); request.on("response", function (response) { var contentEncoding, gzipper; //Only cache successful responses if (response.statusCode >= 200 && response.statusCode < 300) { response.on('error', function (error) { self.handleError(error); }); fs.writeFile(self.cacheDirectory + key + ".json", JSON.stringify(response.headers), function (error) { if (error) self.handleError(error); }); responseWriter = fs.createWriteStream(self.cacheDirectory + key); responseWriter.on('error', function (error) { self.handleError(error); }); contentEncoding = response.headers['content-encoding'] || ''; contentEncoding = contentEncoding.trim().toLowerCase(); if (contentEncoding === 'gzip') { response.on('error', function (error) { responseWriter.end(); }); response.pipe(responseWriter); } else { gzipper = zlib.createGzip(); response.on('error', function (error) { gzipper.end(); }); gzipper.on('error', function (error) { self.handleError(error); responseWriter.end(); }); responseWriter.on('error', function (error) { response.unpipe(gzipper); gzipper.end(); }); response.pipe(gzipper).pipe(responseWriter); } } }); self.emit("request", args[0]); }
[ "function", "makeRequest", "(", ")", "{", "request", "=", "self", ".", "request", ".", "apply", "(", "null", ",", "args", ")", ";", "requestMiddleware", ".", "use", "(", "request", ")", ";", "request", ".", "on", "(", "\"response\"", ",", "function", "(", "response", ")", "{", "var", "contentEncoding", ",", "gzipper", ";", "if", "(", "response", ".", "statusCode", ">=", "200", "&&", "response", ".", "statusCode", "<", "300", ")", "{", "response", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "self", ".", "handleError", "(", "error", ")", ";", "}", ")", ";", "fs", ".", "writeFile", "(", "self", ".", "cacheDirectory", "+", "key", "+", "\".json\"", ",", "JSON", ".", "stringify", "(", "response", ".", "headers", ")", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "self", ".", "handleError", "(", "error", ")", ";", "}", ")", ";", "responseWriter", "=", "fs", ".", "createWriteStream", "(", "self", ".", "cacheDirectory", "+", "key", ")", ";", "responseWriter", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "self", ".", "handleError", "(", "error", ")", ";", "}", ")", ";", "contentEncoding", "=", "response", ".", "headers", "[", "'content-encoding'", "]", "||", "''", ";", "contentEncoding", "=", "contentEncoding", ".", "trim", "(", ")", ".", "toLowerCase", "(", ")", ";", "if", "(", "contentEncoding", "===", "'gzip'", ")", "{", "response", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "responseWriter", ".", "end", "(", ")", ";", "}", ")", ";", "response", ".", "pipe", "(", "responseWriter", ")", ";", "}", "else", "{", "gzipper", "=", "zlib", ".", "createGzip", "(", ")", ";", "response", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "gzipper", ".", "end", "(", ")", ";", "}", ")", ";", "gzipper", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "self", ".", "handleError", "(", "error", ")", ";", "responseWriter", ".", "end", "(", ")", ";", "}", ")", ";", "responseWriter", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "response", ".", "unpipe", "(", "gzipper", ")", ";", "gzipper", ".", "end", "(", ")", ";", "}", ")", ";", "response", ".", "pipe", "(", "gzipper", ")", ".", "pipe", "(", "responseWriter", ")", ";", "}", "}", "}", ")", ";", "self", ".", "emit", "(", "\"request\"", ",", "args", "[", "0", "]", ")", ";", "}" ]
Makes the actual request and caches the response
[ "Makes", "the", "actual", "request", "and", "caches", "the", "response" ]
41a841cb05e338dda40a055c682a9ee493757023
https://github.com/alltherooms/cached-request/blob/41a841cb05e338dda40a055c682a9ee493757023/lib/cached-request.js#L259-L306
train
echo008/xmi
packages/xmi-router/src/dynamic.js
dynamicLoad
function dynamicLoad(dynamicOptions, options, defaultOptions) { let loadableFn = Loadable let loadableOptions = defaultOptions if (typeof dynamicOptions.then === 'function') { // Support for direct import(), // eg: dynamic(import('../hello-world')) loadableOptions.loader = () => dynamicOptions } else if (typeof dynamicOptions === 'object') { // Support for having first argument being options, // eg: dynamic({loader: import('../hello-world')}) loadableOptions = { ...loadableOptions, ...dynamicOptions } } // Support for passing options, // eg: dynamic(import('../hello-world'), {loading: () => <p>Loading something</p>}) loadableOptions = { ...loadableOptions, ...options } // Support for `render` when using a mapping, // eg: `dynamic({ modules: () => {return {HelloWorld: import('../hello-world')}, render(props, loaded) {} } }) if (dynamicOptions.render) { loadableOptions.render = (loaded, props) => dynamicOptions.render(props, loaded) } // Support for `modules` when using a mapping, // eg: `dynamic({ modules: () => {return {HelloWorld: import('../hello-world')}, render(props, loaded) {} } }) if (dynamicOptions.modules) { loadableFn = Loadable.Map const loadModules = {} const modules = dynamicOptions.modules() Object.keys(modules).forEach(key => { const value = modules[key] if (typeof value.then === 'function') { loadModules[key] = () => value.then(mod => mod.default || mod) return } loadModules[key] = value }) loadableOptions.loader = loadModules } return loadableFn(loadableOptions) }
javascript
function dynamicLoad(dynamicOptions, options, defaultOptions) { let loadableFn = Loadable let loadableOptions = defaultOptions if (typeof dynamicOptions.then === 'function') { // Support for direct import(), // eg: dynamic(import('../hello-world')) loadableOptions.loader = () => dynamicOptions } else if (typeof dynamicOptions === 'object') { // Support for having first argument being options, // eg: dynamic({loader: import('../hello-world')}) loadableOptions = { ...loadableOptions, ...dynamicOptions } } // Support for passing options, // eg: dynamic(import('../hello-world'), {loading: () => <p>Loading something</p>}) loadableOptions = { ...loadableOptions, ...options } // Support for `render` when using a mapping, // eg: `dynamic({ modules: () => {return {HelloWorld: import('../hello-world')}, render(props, loaded) {} } }) if (dynamicOptions.render) { loadableOptions.render = (loaded, props) => dynamicOptions.render(props, loaded) } // Support for `modules` when using a mapping, // eg: `dynamic({ modules: () => {return {HelloWorld: import('../hello-world')}, render(props, loaded) {} } }) if (dynamicOptions.modules) { loadableFn = Loadable.Map const loadModules = {} const modules = dynamicOptions.modules() Object.keys(modules).forEach(key => { const value = modules[key] if (typeof value.then === 'function') { loadModules[key] = () => value.then(mod => mod.default || mod) return } loadModules[key] = value }) loadableOptions.loader = loadModules } return loadableFn(loadableOptions) }
[ "function", "dynamicLoad", "(", "dynamicOptions", ",", "options", ",", "defaultOptions", ")", "{", "let", "loadableFn", "=", "Loadable", "let", "loadableOptions", "=", "defaultOptions", "if", "(", "typeof", "dynamicOptions", ".", "then", "===", "'function'", ")", "{", "loadableOptions", ".", "loader", "=", "(", ")", "=>", "dynamicOptions", "}", "else", "if", "(", "typeof", "dynamicOptions", "===", "'object'", ")", "{", "loadableOptions", "=", "{", "...", "loadableOptions", ",", "...", "dynamicOptions", "}", "}", "loadableOptions", "=", "{", "...", "loadableOptions", ",", "...", "options", "}", "if", "(", "dynamicOptions", ".", "render", ")", "{", "loadableOptions", ".", "render", "=", "(", "loaded", ",", "props", ")", "=>", "dynamicOptions", ".", "render", "(", "props", ",", "loaded", ")", "}", "if", "(", "dynamicOptions", ".", "modules", ")", "{", "loadableFn", "=", "Loadable", ".", "Map", "const", "loadModules", "=", "{", "}", "const", "modules", "=", "dynamicOptions", ".", "modules", "(", ")", "Object", ".", "keys", "(", "modules", ")", ".", "forEach", "(", "key", "=>", "{", "const", "value", "=", "modules", "[", "key", "]", "if", "(", "typeof", "value", ".", "then", "===", "'function'", ")", "{", "loadModules", "[", "key", "]", "=", "(", ")", "=>", "value", ".", "then", "(", "mod", "=>", "mod", ".", "default", "||", "mod", ")", "return", "}", "loadModules", "[", "key", "]", "=", "value", "}", ")", "loadableOptions", ".", "loader", "=", "loadModules", "}", "return", "loadableFn", "(", "loadableOptions", ")", "}" ]
Thanks to umi
[ "Thanks", "to", "umi" ]
c751515b537fa713a6df45b30d0767bbb1e8c66c
https://github.com/echo008/xmi/blob/c751515b537fa713a6df45b30d0767bbb1e8c66c/packages/xmi-router/src/dynamic.js#L19-L62
train
sebarmeli/bamboo-api
lib/bamboo.js
function(host, username, password) { var defaultUrl = "http://localhost:8085"; host = host || defaultUrl; if (username && password) { var protocol = host.match(/(^|\s)(https?:\/\/)/i); if (_.isArray(protocol)) { protocol = _.first(protocol); var url = host.substr(protocol.length); host = protocol + username + ":" + password + "@" + url; } } this.host = host || defaultUrl; }
javascript
function(host, username, password) { var defaultUrl = "http://localhost:8085"; host = host || defaultUrl; if (username && password) { var protocol = host.match(/(^|\s)(https?:\/\/)/i); if (_.isArray(protocol)) { protocol = _.first(protocol); var url = host.substr(protocol.length); host = protocol + username + ":" + password + "@" + url; } } this.host = host || defaultUrl; }
[ "function", "(", "host", ",", "username", ",", "password", ")", "{", "var", "defaultUrl", "=", "\"http://localhost:8085\"", ";", "host", "=", "host", "||", "defaultUrl", ";", "if", "(", "username", "&&", "password", ")", "{", "var", "protocol", "=", "host", ".", "match", "(", "/", "(^|\\s)(https?:\\/\\/)", "/", "i", ")", ";", "if", "(", "_", ".", "isArray", "(", "protocol", ")", ")", "{", "protocol", "=", "_", ".", "first", "(", "protocol", ")", ";", "var", "url", "=", "host", ".", "substr", "(", "protocol", ".", "length", ")", ";", "host", "=", "protocol", "+", "username", "+", "\":\"", "+", "password", "+", "\"@\"", "+", "url", ";", "}", "}", "this", ".", "host", "=", "host", "||", "defaultUrl", ";", "}" ]
Function defining a Bamboo instance @param {String} host - hostname. By default "http://localhost:8085" @param {String=} username - optional param for base HTTP authentication. Username @param {String=} password - optional param for base HTTP authentication. Password @constructor
[ "Function", "defining", "a", "Bamboo", "instance" ]
2ef5a9040dfb1c05dc55d14629db3f544a446f4d
https://github.com/sebarmeli/bamboo-api/blob/2ef5a9040dfb1c05dc55d14629db3f544a446f4d/lib/bamboo.js#L25-L43
train
sebarmeli/bamboo-api
lib/bamboo.js
checkErrorsWithResult
function checkErrorsWithResult(error, response) { var errors = checkErrors(error, response); if (errors !== false) { return errors; } try { var body = JSON.parse(response.body); } catch (parseError) { return parseError; } var results = body.results; if (typeof results === "undefined" || results.result.length === 0) { return new Error("The plan doesn't contain any result"); } return false; }
javascript
function checkErrorsWithResult(error, response) { var errors = checkErrors(error, response); if (errors !== false) { return errors; } try { var body = JSON.parse(response.body); } catch (parseError) { return parseError; } var results = body.results; if (typeof results === "undefined" || results.result.length === 0) { return new Error("The plan doesn't contain any result"); } return false; }
[ "function", "checkErrorsWithResult", "(", "error", ",", "response", ")", "{", "var", "errors", "=", "checkErrors", "(", "error", ",", "response", ")", ";", "if", "(", "errors", "!==", "false", ")", "{", "return", "errors", ";", "}", "try", "{", "var", "body", "=", "JSON", ".", "parse", "(", "response", ".", "body", ")", ";", "}", "catch", "(", "parseError", ")", "{", "return", "parseError", ";", "}", "var", "results", "=", "body", ".", "results", ";", "if", "(", "typeof", "results", "===", "\"undefined\"", "||", "results", ".", "result", ".", "length", "===", "0", ")", "{", "return", "new", "Error", "(", "\"The plan doesn't contain any result\"", ")", ";", "}", "return", "false", ";", "}" ]
Method checks for errors in error and server response Additionally parsing response body and checking if it contain any results @param {Error|null} error @param {Object} response @returns {Error|Boolean} if error, will return Error otherwise false @protected
[ "Method", "checks", "for", "errors", "in", "error", "and", "server", "response", "Additionally", "parsing", "response", "body", "and", "checking", "if", "it", "contain", "any", "results" ]
2ef5a9040dfb1c05dc55d14629db3f544a446f4d
https://github.com/sebarmeli/bamboo-api/blob/2ef5a9040dfb1c05dc55d14629db3f544a446f4d/lib/bamboo.js#L711-L731
train
sebarmeli/bamboo-api
lib/bamboo.js
checkErrors
function checkErrors(error, response) { if (error) { return error instanceof Error ? error : new Error(error); } // Bamboo API enable plan returns 204 with empty response in case of success if ((response.statusCode !== 200) && (response.statusCode !== 204)) { return new Error("Unreachable endpoint! Response status code: " + response.statusCode); } return false; }
javascript
function checkErrors(error, response) { if (error) { return error instanceof Error ? error : new Error(error); } // Bamboo API enable plan returns 204 with empty response in case of success if ((response.statusCode !== 200) && (response.statusCode !== 204)) { return new Error("Unreachable endpoint! Response status code: " + response.statusCode); } return false; }
[ "function", "checkErrors", "(", "error", ",", "response", ")", "{", "if", "(", "error", ")", "{", "return", "error", "instanceof", "Error", "?", "error", ":", "new", "Error", "(", "error", ")", ";", "}", "if", "(", "(", "response", ".", "statusCode", "!==", "200", ")", "&&", "(", "response", ".", "statusCode", "!==", "204", ")", ")", "{", "return", "new", "Error", "(", "\"Unreachable endpoint! Response status code: \"", "+", "response", ".", "statusCode", ")", ";", "}", "return", "false", ";", "}" ]
Method checks for errors in error and server response @param {Error|null} error @param {Object} response @returns {Error|Boolean} if error, will return Error otherwise false @protected
[ "Method", "checks", "for", "errors", "in", "error", "and", "server", "response" ]
2ef5a9040dfb1c05dc55d14629db3f544a446f4d
https://github.com/sebarmeli/bamboo-api/blob/2ef5a9040dfb1c05dc55d14629db3f544a446f4d/lib/bamboo.js#L741-L752
train
sebarmeli/bamboo-api
lib/bamboo.js
mergeUrlWithParams
function mergeUrlWithParams(url, params) { params = params || {}; return _.isEmpty(params) ? url : url + "?" + qs.stringify(params); }
javascript
function mergeUrlWithParams(url, params) { params = params || {}; return _.isEmpty(params) ? url : url + "?" + qs.stringify(params); }
[ "function", "mergeUrlWithParams", "(", "url", ",", "params", ")", "{", "params", "=", "params", "||", "{", "}", ";", "return", "_", ".", "isEmpty", "(", "params", ")", "?", "url", ":", "url", "+", "\"?\"", "+", "qs", ".", "stringify", "(", "params", ")", ";", "}" ]
Method will add params to the specified url @param {String} url @param {Object=} params - optional, object with parameters that should be merged with specified url @returns {String} @protected
[ "Method", "will", "add", "params", "to", "the", "specified", "url" ]
2ef5a9040dfb1c05dc55d14629db3f544a446f4d
https://github.com/sebarmeli/bamboo-api/blob/2ef5a9040dfb1c05dc55d14629db3f544a446f4d/lib/bamboo.js#L762-L765
train
pa11y/pa11y-webservice-client-node
lib/client.js
client
function client (root) { return { tasks: { // Create a new task create: function (task, done) { post(root + 'tasks', task, done); }, // Get all tasks get: function (query, done) { get(root + 'tasks', query, done); }, // Get results for all tasks results: function (query, done) { get(root + 'tasks/results', query, done); } }, task: function (id) { return { // Get a task get: function (query, done) { get(root + 'tasks/' + id, query, done); }, // Edit a task edit: function (edits, done) { patch(root + 'tasks/' + id, edits, done); }, // Remove a task remove: function (done) { del(root + 'tasks/' + id, null, done); }, // Run a task run: function (done) { post(root + 'tasks/' + id + '/run', null, done); }, // Get results for a task results: function (query, done) { get(root + 'tasks/' + id + '/results', query, done); }, result: function (rid) { return { // Get a result get: function (query, done) { get(root + 'tasks/' + id + '/results/' + rid, query, done); } }; } }; } }; }
javascript
function client (root) { return { tasks: { // Create a new task create: function (task, done) { post(root + 'tasks', task, done); }, // Get all tasks get: function (query, done) { get(root + 'tasks', query, done); }, // Get results for all tasks results: function (query, done) { get(root + 'tasks/results', query, done); } }, task: function (id) { return { // Get a task get: function (query, done) { get(root + 'tasks/' + id, query, done); }, // Edit a task edit: function (edits, done) { patch(root + 'tasks/' + id, edits, done); }, // Remove a task remove: function (done) { del(root + 'tasks/' + id, null, done); }, // Run a task run: function (done) { post(root + 'tasks/' + id + '/run', null, done); }, // Get results for a task results: function (query, done) { get(root + 'tasks/' + id + '/results', query, done); }, result: function (rid) { return { // Get a result get: function (query, done) { get(root + 'tasks/' + id + '/results/' + rid, query, done); } }; } }; } }; }
[ "function", "client", "(", "root", ")", "{", "return", "{", "tasks", ":", "{", "create", ":", "function", "(", "task", ",", "done", ")", "{", "post", "(", "root", "+", "'tasks'", ",", "task", ",", "done", ")", ";", "}", ",", "get", ":", "function", "(", "query", ",", "done", ")", "{", "get", "(", "root", "+", "'tasks'", ",", "query", ",", "done", ")", ";", "}", ",", "results", ":", "function", "(", "query", ",", "done", ")", "{", "get", "(", "root", "+", "'tasks/results'", ",", "query", ",", "done", ")", ";", "}", "}", ",", "task", ":", "function", "(", "id", ")", "{", "return", "{", "get", ":", "function", "(", "query", ",", "done", ")", "{", "get", "(", "root", "+", "'tasks/'", "+", "id", ",", "query", ",", "done", ")", ";", "}", ",", "edit", ":", "function", "(", "edits", ",", "done", ")", "{", "patch", "(", "root", "+", "'tasks/'", "+", "id", ",", "edits", ",", "done", ")", ";", "}", ",", "remove", ":", "function", "(", "done", ")", "{", "del", "(", "root", "+", "'tasks/'", "+", "id", ",", "null", ",", "done", ")", ";", "}", ",", "run", ":", "function", "(", "done", ")", "{", "post", "(", "root", "+", "'tasks/'", "+", "id", "+", "'/run'", ",", "null", ",", "done", ")", ";", "}", ",", "results", ":", "function", "(", "query", ",", "done", ")", "{", "get", "(", "root", "+", "'tasks/'", "+", "id", "+", "'/results'", ",", "query", ",", "done", ")", ";", "}", ",", "result", ":", "function", "(", "rid", ")", "{", "return", "{", "get", ":", "function", "(", "query", ",", "done", ")", "{", "get", "(", "root", "+", "'tasks/'", "+", "id", "+", "'/results/'", "+", "rid", ",", "query", ",", "done", ")", ";", "}", "}", ";", "}", "}", ";", "}", "}", ";", "}" ]
Create a web-service client
[ "Create", "a", "web", "-", "service", "client" ]
841f1bf26dce4de578add0761fa88e00c7a2d3bf
https://github.com/pa11y/pa11y-webservice-client-node/blob/841f1bf26dce4de578add0761fa88e00c7a2d3bf/lib/client.js#L23-L88
train
matrix-org/matrix-react-skin
src/app/index.js
routeUrl
function routeUrl(location) { if (location.hash.indexOf('#/register') == 0) { var hashparts = location.hash.split('?'); var params = {}; if (hashparts.length == 2) { var pairs = hashparts[1].split('&'); for (var i = 0; i < pairs.length; ++i) { var parts = pairs[i].split('='); if (parts.length != 2) continue; params[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]); } } window.matrixChat.showScreen('register', params); } }
javascript
function routeUrl(location) { if (location.hash.indexOf('#/register') == 0) { var hashparts = location.hash.split('?'); var params = {}; if (hashparts.length == 2) { var pairs = hashparts[1].split('&'); for (var i = 0; i < pairs.length; ++i) { var parts = pairs[i].split('='); if (parts.length != 2) continue; params[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]); } } window.matrixChat.showScreen('register', params); } }
[ "function", "routeUrl", "(", "location", ")", "{", "if", "(", "location", ".", "hash", ".", "indexOf", "(", "'#/register'", ")", "==", "0", ")", "{", "var", "hashparts", "=", "location", ".", "hash", ".", "split", "(", "'?'", ")", ";", "var", "params", "=", "{", "}", ";", "if", "(", "hashparts", ".", "length", "==", "2", ")", "{", "var", "pairs", "=", "hashparts", "[", "1", "]", ".", "split", "(", "'&'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "pairs", ".", "length", ";", "++", "i", ")", "{", "var", "parts", "=", "pairs", "[", "i", "]", ".", "split", "(", "'='", ")", ";", "if", "(", "parts", ".", "length", "!=", "2", ")", "continue", ";", "params", "[", "decodeURIComponent", "(", "parts", "[", "0", "]", ")", "]", "=", "decodeURIComponent", "(", "parts", "[", "1", "]", ")", ";", "}", "}", "window", ".", "matrixChat", ".", "showScreen", "(", "'register'", ",", "params", ")", ";", "}", "}" ]
Here, we do some crude URL analysis to allow deep-linking. We only support registration deep-links in this example.
[ "Here", "we", "do", "some", "crude", "URL", "analysis", "to", "allow", "deep", "-", "linking", ".", "We", "only", "support", "registration", "deep", "-", "links", "in", "this", "example", "." ]
a5b7a790f332d74d74f52b2cbaa1fd68559aae4d
https://github.com/matrix-org/matrix-react-skin/blob/a5b7a790f332d74d74f52b2cbaa1fd68559aae4d/src/app/index.js#L27-L41
train
GrosSacASac/DOM99
documentation/presentation/reveal.js-2.6.2/plugin/markdown/markdown.js
processSlides
function processSlides() { var sections = document.querySelectorAll( '[data-markdown]'), section; for( var i = 0, len = sections.length; i < len; i++ ) { section = sections[i]; if( section.getAttribute( 'data-markdown' ).length ) { var xhr = new XMLHttpRequest(), url = section.getAttribute( 'data-markdown' ); datacharset = section.getAttribute( 'data-charset' ); // see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes if( datacharset != null && datacharset != '' ) { xhr.overrideMimeType( 'text/html; charset=' + datacharset ); } xhr.onreadystatechange = function() { if( xhr.readyState === 4 ) { if ( xhr.status >= 200 && xhr.status < 300 ) { section.outerHTML = slidify( xhr.responseText, { separator: section.getAttribute( 'data-separator' ), verticalSeparator: section.getAttribute( 'data-vertical' ), notesSeparator: section.getAttribute( 'data-notes' ), attributes: getForwardedAttributes( section ) }); } else { section.outerHTML = '<section data-state="alert">' + 'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' + 'Check your browser\'s JavaScript console for more details.' + '<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' + '</section>'; } } }; xhr.open( 'GET', url, false ); try { xhr.send(); } catch ( e ) { alert( 'Failed to get the Markdown file ' + url + '. Make sure that the presentation and the file are served by a HTTP server and the file can be found there. ' + e ); } } else if( section.getAttribute( 'data-separator' ) || section.getAttribute( 'data-vertical' ) || section.getAttribute( 'data-notes' ) ) { section.outerHTML = slidify( getMarkdownFromSlide( section ), { separator: section.getAttribute( 'data-separator' ), verticalSeparator: section.getAttribute( 'data-vertical' ), notesSeparator: section.getAttribute( 'data-notes' ), attributes: getForwardedAttributes( section ) }); } else { section.innerHTML = createMarkdownSlide( getMarkdownFromSlide( section ) ); } } }
javascript
function processSlides() { var sections = document.querySelectorAll( '[data-markdown]'), section; for( var i = 0, len = sections.length; i < len; i++ ) { section = sections[i]; if( section.getAttribute( 'data-markdown' ).length ) { var xhr = new XMLHttpRequest(), url = section.getAttribute( 'data-markdown' ); datacharset = section.getAttribute( 'data-charset' ); // see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes if( datacharset != null && datacharset != '' ) { xhr.overrideMimeType( 'text/html; charset=' + datacharset ); } xhr.onreadystatechange = function() { if( xhr.readyState === 4 ) { if ( xhr.status >= 200 && xhr.status < 300 ) { section.outerHTML = slidify( xhr.responseText, { separator: section.getAttribute( 'data-separator' ), verticalSeparator: section.getAttribute( 'data-vertical' ), notesSeparator: section.getAttribute( 'data-notes' ), attributes: getForwardedAttributes( section ) }); } else { section.outerHTML = '<section data-state="alert">' + 'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' + 'Check your browser\'s JavaScript console for more details.' + '<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' + '</section>'; } } }; xhr.open( 'GET', url, false ); try { xhr.send(); } catch ( e ) { alert( 'Failed to get the Markdown file ' + url + '. Make sure that the presentation and the file are served by a HTTP server and the file can be found there. ' + e ); } } else if( section.getAttribute( 'data-separator' ) || section.getAttribute( 'data-vertical' ) || section.getAttribute( 'data-notes' ) ) { section.outerHTML = slidify( getMarkdownFromSlide( section ), { separator: section.getAttribute( 'data-separator' ), verticalSeparator: section.getAttribute( 'data-vertical' ), notesSeparator: section.getAttribute( 'data-notes' ), attributes: getForwardedAttributes( section ) }); } else { section.innerHTML = createMarkdownSlide( getMarkdownFromSlide( section ) ); } } }
[ "function", "processSlides", "(", ")", "{", "var", "sections", "=", "document", ".", "querySelectorAll", "(", "'[data-markdown]'", ")", ",", "section", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "sections", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "section", "=", "sections", "[", "i", "]", ";", "if", "(", "section", ".", "getAttribute", "(", "'data-markdown'", ")", ".", "length", ")", "{", "var", "xhr", "=", "new", "XMLHttpRequest", "(", ")", ",", "url", "=", "section", ".", "getAttribute", "(", "'data-markdown'", ")", ";", "datacharset", "=", "section", ".", "getAttribute", "(", "'data-charset'", ")", ";", "if", "(", "datacharset", "!=", "null", "&&", "datacharset", "!=", "''", ")", "{", "xhr", ".", "overrideMimeType", "(", "'text/html; charset='", "+", "datacharset", ")", ";", "}", "xhr", ".", "onreadystatechange", "=", "function", "(", ")", "{", "if", "(", "xhr", ".", "readyState", "===", "4", ")", "{", "if", "(", "xhr", ".", "status", ">=", "200", "&&", "xhr", ".", "status", "<", "300", ")", "{", "section", ".", "outerHTML", "=", "slidify", "(", "xhr", ".", "responseText", ",", "{", "separator", ":", "section", ".", "getAttribute", "(", "'data-separator'", ")", ",", "verticalSeparator", ":", "section", ".", "getAttribute", "(", "'data-vertical'", ")", ",", "notesSeparator", ":", "section", ".", "getAttribute", "(", "'data-notes'", ")", ",", "attributes", ":", "getForwardedAttributes", "(", "section", ")", "}", ")", ";", "}", "else", "{", "section", ".", "outerHTML", "=", "'<section data-state=\"alert\">'", "+", "'ERROR: The attempt to fetch '", "+", "url", "+", "' failed with HTTP status '", "+", "xhr", ".", "status", "+", "'.'", "+", "'Check your browser\\'s JavaScript console for more details.'", "+", "\\'", "+", "'<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>'", ";", "}", "}", "}", ";", "'</section>'", "xhr", ".", "open", "(", "'GET'", ",", "url", ",", "false", ")", ";", "}", "else", "try", "{", "xhr", ".", "send", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "alert", "(", "'Failed to get the Markdown file '", "+", "url", "+", "'. Make sure that the presentation and the file are served by a HTTP server and the file can be found there. '", "+", "e", ")", ";", "}", "}", "}" ]
Parses any current data-markdown slides, splits multi-slide markdown into separate sections and handles loading of external markdown.
[ "Parses", "any", "current", "data", "-", "markdown", "slides", "splits", "multi", "-", "slide", "markdown", "into", "separate", "sections", "and", "handles", "loading", "of", "external", "markdown", "." ]
0563cb3d4865d968e829d39c68dc62af3fc95cc8
https://github.com/GrosSacASac/DOM99/blob/0563cb3d4865d968e829d39c68dc62af3fc95cc8/documentation/presentation/reveal.js-2.6.2/plugin/markdown/markdown.js#L199-L269
train
rlmv/gitbook-plugin-anchors
index.js
insertAnchors
function insertAnchors(content) { var $ = cheerio.load(content); $(':header').each(function(i, elem) { var header = $(elem); var id = header.attr("id"); if (!id) { id = slug(header.text()); header.attr("id", id); } header.prepend('<a name="' + id + '" class="plugin-anchor" ' + 'href="#' + id + '">' + '<i class="fa fa-link" aria-hidden="true"></i>' + '</a>'); }); return $.html(); }
javascript
function insertAnchors(content) { var $ = cheerio.load(content); $(':header').each(function(i, elem) { var header = $(elem); var id = header.attr("id"); if (!id) { id = slug(header.text()); header.attr("id", id); } header.prepend('<a name="' + id + '" class="plugin-anchor" ' + 'href="#' + id + '">' + '<i class="fa fa-link" aria-hidden="true"></i>' + '</a>'); }); return $.html(); }
[ "function", "insertAnchors", "(", "content", ")", "{", "var", "$", "=", "cheerio", ".", "load", "(", "content", ")", ";", "$", "(", "':header'", ")", ".", "each", "(", "function", "(", "i", ",", "elem", ")", "{", "var", "header", "=", "$", "(", "elem", ")", ";", "var", "id", "=", "header", ".", "attr", "(", "\"id\"", ")", ";", "if", "(", "!", "id", ")", "{", "id", "=", "slug", "(", "header", ".", "text", "(", ")", ")", ";", "header", ".", "attr", "(", "\"id\"", ",", "id", ")", ";", "}", "header", ".", "prepend", "(", "'<a name=\"'", "+", "id", "+", "'\" class=\"plugin-anchor\" '", "+", "'href=\"#'", "+", "id", "+", "'\">'", "+", "'<i class=\"fa fa-link\" aria-hidden=\"true\"></i>'", "+", "'</a>'", ")", ";", "}", ")", ";", "return", "$", ".", "html", "(", ")", ";", "}" ]
insert anchor link into section
[ "insert", "anchor", "link", "into", "section" ]
ba139e94705b71d7c752015e6e7407aaaf07528f
https://github.com/rlmv/gitbook-plugin-anchors/blob/ba139e94705b71d7c752015e6e7407aaaf07528f/index.js#L5-L20
train
lil5/simple-cryptor-pouch
src/index.js
simplecryptor
function simplecryptor (password, options = {}) { const db = this // set default ignore options.ignore = ['_id', '_rev', '_deleted'].concat(options.ignore) const simpleCryptoJS = new SimpleCryptoJS(password) // https://github.com/pouchdb-community/transform-pouch#example-encryption db.transform({ incoming: function (doc) { return cryptor(simpleCryptoJS, doc, options.ignore, true) }, outgoing: function (doc) { return cryptor(simpleCryptoJS, doc, options.ignore, false) }, }) }
javascript
function simplecryptor (password, options = {}) { const db = this // set default ignore options.ignore = ['_id', '_rev', '_deleted'].concat(options.ignore) const simpleCryptoJS = new SimpleCryptoJS(password) // https://github.com/pouchdb-community/transform-pouch#example-encryption db.transform({ incoming: function (doc) { return cryptor(simpleCryptoJS, doc, options.ignore, true) }, outgoing: function (doc) { return cryptor(simpleCryptoJS, doc, options.ignore, false) }, }) }
[ "function", "simplecryptor", "(", "password", ",", "options", "=", "{", "}", ")", "{", "const", "db", "=", "this", "options", ".", "ignore", "=", "[", "'_id'", ",", "'_rev'", ",", "'_deleted'", "]", ".", "concat", "(", "options", ".", "ignore", ")", "const", "simpleCryptoJS", "=", "new", "SimpleCryptoJS", "(", "password", ")", "db", ".", "transform", "(", "{", "incoming", ":", "function", "(", "doc", ")", "{", "return", "cryptor", "(", "simpleCryptoJS", ",", "doc", ",", "options", ".", "ignore", ",", "true", ")", "}", ",", "outgoing", ":", "function", "(", "doc", ")", "{", "return", "cryptor", "(", "simpleCryptoJS", ",", "doc", ",", "options", ".", "ignore", ",", "false", ")", "}", ",", "}", ")", "}" ]
pouch function to encrypt and decrypt @param {string} password @param {Object} [options={}] @return {Object | Promise}
[ "pouch", "function", "to", "encrypt", "and", "decrypt" ]
15179a510cc707c3402472716ef029d3255b12ee
https://github.com/lil5/simple-cryptor-pouch/blob/15179a510cc707c3402472716ef029d3255b12ee/src/index.js#L12-L29
train
nickyout/fast-stable-stringify
cli/files-to-comparison-results.js
mergeToMap
function mergeToMap(arrFileObj) { return arrFileObj.reduce(function(result, fileObj) { var name; var libData; for (name in fileObj) { libData = fileObj[name]; obj.setObject(result, [libData.suite, libData.browser, libData.name], libData); } return result; }, {}); }
javascript
function mergeToMap(arrFileObj) { return arrFileObj.reduce(function(result, fileObj) { var name; var libData; for (name in fileObj) { libData = fileObj[name]; obj.setObject(result, [libData.suite, libData.browser, libData.name], libData); } return result; }, {}); }
[ "function", "mergeToMap", "(", "arrFileObj", ")", "{", "return", "arrFileObj", ".", "reduce", "(", "function", "(", "result", ",", "fileObj", ")", "{", "var", "name", ";", "var", "libData", ";", "for", "(", "name", "in", "fileObj", ")", "{", "libData", "=", "fileObj", "[", "name", "]", ";", "obj", ".", "setObject", "(", "result", ",", "[", "libData", ".", "suite", ",", "libData", ".", "browser", ",", "libData", ".", "name", "]", ",", "libData", ")", ";", "}", "return", "result", ";", "}", ",", "{", "}", ")", ";", "}" ]
Converts the file contents generated by BenchmarkStatsProcessor to a DataSetComparisonResult array. @param {Array} arrFileObj @returns {Object}
[ "Converts", "the", "file", "contents", "generated", "by", "BenchmarkStatsProcessor", "to", "a", "DataSetComparisonResult", "array", "." ]
53460c31e7b4b0cccb7c7ddacc89bf42ccd5eb0c
https://github.com/nickyout/fast-stable-stringify/blob/53460c31e7b4b0cccb7c7ddacc89bf42ccd5eb0c/cli/files-to-comparison-results.js#L9-L19
train
svagi/redux-routines
lib/index.js
createActionType
function createActionType(prefix, stage, separator) { if (typeof prefix !== 'string' || typeof stage !== 'string') { throw new Error('Invalid routine prefix or stage. It should be string.'); } return '' + prefix + separator + stage; }
javascript
function createActionType(prefix, stage, separator) { if (typeof prefix !== 'string' || typeof stage !== 'string') { throw new Error('Invalid routine prefix or stage. It should be string.'); } return '' + prefix + separator + stage; }
[ "function", "createActionType", "(", "prefix", ",", "stage", ",", "separator", ")", "{", "if", "(", "typeof", "prefix", "!==", "'string'", "||", "typeof", "stage", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'Invalid routine prefix or stage. It should be string.'", ")", ";", "}", "return", "''", "+", "prefix", "+", "separator", "+", "stage", ";", "}" ]
Routine action type factory
[ "Routine", "action", "type", "factory" ]
d9585eab26c15c032a5ca9a759eea35782cc3436
https://github.com/svagi/redux-routines/blob/d9585eab26c15c032a5ca9a759eea35782cc3436/lib/index.js#L21-L26
train
nickyout/fast-stable-stringify
cli/format-table.js
toFixedWidth
function toFixedWidth(value, maxChars) { var result = value.toFixed(2).substr(0, maxChars); if (result[result.length - 1] == '.') { result = result.substr(0, result.length - 2) + ' '; } return result; }
javascript
function toFixedWidth(value, maxChars) { var result = value.toFixed(2).substr(0, maxChars); if (result[result.length - 1] == '.') { result = result.substr(0, result.length - 2) + ' '; } return result; }
[ "function", "toFixedWidth", "(", "value", ",", "maxChars", ")", "{", "var", "result", "=", "value", ".", "toFixed", "(", "2", ")", ".", "substr", "(", "0", ",", "maxChars", ")", ";", "if", "(", "result", "[", "result", ".", "length", "-", "1", "]", "==", "'.'", ")", "{", "result", "=", "result", ".", "substr", "(", "0", ",", "result", ".", "length", "-", "2", ")", "+", "' '", ";", "}", "return", "result", ";", "}" ]
Crude, but should be enough internally
[ "Crude", "but", "should", "be", "enough", "internally" ]
53460c31e7b4b0cccb7c7ddacc89bf42ccd5eb0c
https://github.com/nickyout/fast-stable-stringify/blob/53460c31e7b4b0cccb7c7ddacc89bf42ccd5eb0c/cli/format-table.js#L4-L10
train
JamesMGreene/qunit-assert-html
src/qunit-assert-html.js
_getPushContext
function _getPushContext(context) { var pushContext; if (context && typeof context.push === "function") { // `context` is an `Assert` context pushContext = context; } else if (context && context.assert && typeof context.assert.push === "function") { // `context` is a `Test` context pushContext = context.assert; } else if ( QUnit && QUnit.config && QUnit.config.current && QUnit.config.current.assert && typeof QUnit.config.current.assert.push === "function" ) { // `context` is an unknown context but we can find the `Assert` context via QUnit pushContext = QUnit.config.current.assert; } else if (QUnit && typeof QUnit.push === "function") { pushContext = QUnit.push; } else { throw new Error("Could not find the QUnit `Assert` context to push results"); } return pushContext; }
javascript
function _getPushContext(context) { var pushContext; if (context && typeof context.push === "function") { // `context` is an `Assert` context pushContext = context; } else if (context && context.assert && typeof context.assert.push === "function") { // `context` is a `Test` context pushContext = context.assert; } else if ( QUnit && QUnit.config && QUnit.config.current && QUnit.config.current.assert && typeof QUnit.config.current.assert.push === "function" ) { // `context` is an unknown context but we can find the `Assert` context via QUnit pushContext = QUnit.config.current.assert; } else if (QUnit && typeof QUnit.push === "function") { pushContext = QUnit.push; } else { throw new Error("Could not find the QUnit `Assert` context to push results"); } return pushContext; }
[ "function", "_getPushContext", "(", "context", ")", "{", "var", "pushContext", ";", "if", "(", "context", "&&", "typeof", "context", ".", "push", "===", "\"function\"", ")", "{", "pushContext", "=", "context", ";", "}", "else", "if", "(", "context", "&&", "context", ".", "assert", "&&", "typeof", "context", ".", "assert", ".", "push", "===", "\"function\"", ")", "{", "pushContext", "=", "context", ".", "assert", ";", "}", "else", "if", "(", "QUnit", "&&", "QUnit", ".", "config", "&&", "QUnit", ".", "config", ".", "current", "&&", "QUnit", ".", "config", ".", "current", ".", "assert", "&&", "typeof", "QUnit", ".", "config", ".", "current", ".", "assert", ".", "push", "===", "\"function\"", ")", "{", "pushContext", "=", "QUnit", ".", "config", ".", "current", ".", "assert", ";", "}", "else", "if", "(", "QUnit", "&&", "typeof", "QUnit", ".", "push", "===", "\"function\"", ")", "{", "pushContext", "=", "QUnit", ".", "push", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"Could not find the QUnit `Assert` context to push results\"", ")", ";", "}", "return", "pushContext", ";", "}" ]
Find an appropriate `Assert` context to `push` results to. @param * context - An unknown context, possibly `Assert`, `Test`, or neither @private
[ "Find", "an", "appropriate", "Assert", "context", "to", "push", "results", "to", "." ]
670b20e64b68465934d0bfedf5fbf952b45c3b5e
https://github.com/JamesMGreene/qunit-assert-html/blob/670b20e64b68465934d0bfedf5fbf952b45c3b5e/src/qunit-assert-html.js#L36-L62
train
yvele/poosh
packages/poosh-core/src/pipeline/appendContentBuffer.js
shouldSkip
function shouldSkip(file, rough) { // Basically, if rough, any small change should still process the content return rough ? file.cache.status === LocalStatus.Unchanged : file.content.status === LocalStatus.Unchanged; }
javascript
function shouldSkip(file, rough) { // Basically, if rough, any small change should still process the content return rough ? file.cache.status === LocalStatus.Unchanged : file.content.status === LocalStatus.Unchanged; }
[ "function", "shouldSkip", "(", "file", ",", "rough", ")", "{", "return", "rough", "?", "file", ".", "cache", ".", "status", "===", "LocalStatus", ".", "Unchanged", ":", "file", ".", "content", ".", "status", "===", "LocalStatus", ".", "Unchanged", ";", "}" ]
When content status is labeled as unchanged, buffer doesn't need to be processed.
[ "When", "content", "status", "is", "labeled", "as", "unchanged", "buffer", "doesn", "t", "need", "to", "be", "processed", "." ]
1b8a84d2bc38d92711405004270c0dcc84e4dbf0
https://github.com/yvele/poosh/blob/1b8a84d2bc38d92711405004270c0dcc84e4dbf0/packages/poosh-core/src/pipeline/appendContentBuffer.js#L8-L13
train