repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
j-/ok
ok.js
function () { var message = this.message; var name = this.name; var url = this.url; var result = name; if (message) { result += ': ' + message; } if (url) { result += ' (' + url + ')'; } return result; }
javascript
function () { var message = this.message; var name = this.name; var url = this.url; var result = name; if (message) { result += ': ' + message; } if (url) { result += ' (' + url + ')'; } return result; }
[ "function", "(", ")", "{", "var", "message", "=", "this", ".", "message", ";", "var", "name", "=", "this", ".", "name", ";", "var", "url", "=", "this", ".", "url", ";", "var", "result", "=", "name", ";", "if", "(", "message", ")", "{", "result", "+=", "': '", "+", "message", ";", "}", "if", "(", "url", ")", "{", "result", "+=", "' ('", "+", "url", "+", "')'", ";", "}", "return", "result", ";", "}" ]
Display the contents of this error. Always shows the name. If the message exists it is also displayed. A URL to, for example, help documentation can be displayed as well. @return {String} Contents of this error
[ "Display", "the", "contents", "of", "this", "error", ".", "Always", "shows", "the", "name", ".", "If", "the", "message", "exists", "it", "is", "also", "displayed", ".", "A", "URL", "to", "for", "example", "help", "documentation", "can", "be", "displayed", "as", "well", "." ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L1591-L1603
train
cubbles/cubx-grunt-webpackage-upload
tasks/cubx_webpackage_bulk_upload.js
function (err, files) { if (err) { grunt.fail.fatal(err); } files.forEach(function (file) { var pathName = path.join(workspacePath, file); if (fs.statSync(pathName).isDirectory()) { if (file === activeWebpackage && choices.length > 0) { choices.splice(0, 0, file); } else { choices.push(file); } } }); // get list of webpackages to upload from config var uploadWebpackages = grunt.config.get('workspaceConfig.uploadWebpackages'); var i = 0; if (uploadWebpackages && uploadWebpackages.length) { // create upload list from config grunt.log.writeln('Webpackages to upload:'); for (i = 0; i < uploadWebpackages.length; i++) { if (choices.indexOf(uploadWebpackages[i]) >= 0) { webpackages.push(uploadWebpackages[i]); grunt.log.writeln((i + 1) + ') ' + uploadWebpackages[i]); } } startUploads(); } else { // get user decision choices.push('CANCEL'); grunt.log.writeln('Please select all webpackages to upload ' + 'or to CANCEL: '); for (i = 0; i < choices.length; i++) { grunt.log.writeln((i + 1) + ') ' + choices[i]); } var options = { questions: [ { name: 'selectedWebpackages', type: 'input', message: 'Answer:' } ] }; inquirer.prompt(options.questions).then(webpackagesSelected); } }
javascript
function (err, files) { if (err) { grunt.fail.fatal(err); } files.forEach(function (file) { var pathName = path.join(workspacePath, file); if (fs.statSync(pathName).isDirectory()) { if (file === activeWebpackage && choices.length > 0) { choices.splice(0, 0, file); } else { choices.push(file); } } }); // get list of webpackages to upload from config var uploadWebpackages = grunt.config.get('workspaceConfig.uploadWebpackages'); var i = 0; if (uploadWebpackages && uploadWebpackages.length) { // create upload list from config grunt.log.writeln('Webpackages to upload:'); for (i = 0; i < uploadWebpackages.length; i++) { if (choices.indexOf(uploadWebpackages[i]) >= 0) { webpackages.push(uploadWebpackages[i]); grunt.log.writeln((i + 1) + ') ' + uploadWebpackages[i]); } } startUploads(); } else { // get user decision choices.push('CANCEL'); grunt.log.writeln('Please select all webpackages to upload ' + 'or to CANCEL: '); for (i = 0; i < choices.length; i++) { grunt.log.writeln((i + 1) + ') ' + choices[i]); } var options = { questions: [ { name: 'selectedWebpackages', type: 'input', message: 'Answer:' } ] }; inquirer.prompt(options.questions).then(webpackagesSelected); } }
[ "function", "(", "err", ",", "files", ")", "{", "if", "(", "err", ")", "{", "grunt", ".", "fail", ".", "fatal", "(", "err", ")", ";", "}", "files", ".", "forEach", "(", "function", "(", "file", ")", "{", "var", "pathName", "=", "path", ".", "join", "(", "workspacePath", ",", "file", ")", ";", "if", "(", "fs", ".", "statSync", "(", "pathName", ")", ".", "isDirectory", "(", ")", ")", "{", "if", "(", "file", "===", "activeWebpackage", "&&", "choices", ".", "length", ">", "0", ")", "{", "choices", ".", "splice", "(", "0", ",", "0", ",", "file", ")", ";", "}", "else", "{", "choices", ".", "push", "(", "file", ")", ";", "}", "}", "}", ")", ";", "var", "uploadWebpackages", "=", "grunt", ".", "config", ".", "get", "(", "'workspaceConfig.uploadWebpackages'", ")", ";", "var", "i", "=", "0", ";", "if", "(", "uploadWebpackages", "&&", "uploadWebpackages", ".", "length", ")", "{", "grunt", ".", "log", ".", "writeln", "(", "'Webpackages to upload:'", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "uploadWebpackages", ".", "length", ";", "i", "++", ")", "{", "if", "(", "choices", ".", "indexOf", "(", "uploadWebpackages", "[", "i", "]", ")", ">=", "0", ")", "{", "webpackages", ".", "push", "(", "uploadWebpackages", "[", "i", "]", ")", ";", "grunt", ".", "log", ".", "writeln", "(", "(", "i", "+", "1", ")", "+", "') '", "+", "uploadWebpackages", "[", "i", "]", ")", ";", "}", "}", "startUploads", "(", ")", ";", "}", "else", "{", "choices", ".", "push", "(", "'CANCEL'", ")", ";", "grunt", ".", "log", ".", "writeln", "(", "'Please select all webpackages to upload '", "+", "'or to CANCEL: '", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "choices", ".", "length", ";", "i", "++", ")", "{", "grunt", ".", "log", ".", "writeln", "(", "(", "i", "+", "1", ")", "+", "') '", "+", "choices", "[", "i", "]", ")", ";", "}", "var", "options", "=", "{", "questions", ":", "[", "{", "name", ":", "'selectedWebpackages'", ",", "type", ":", "'input'", ",", "message", ":", "'Answer:'", "}", "]", "}", ";", "inquirer", ".", "prompt", "(", "options", ".", "questions", ")", ".", "then", "(", "webpackagesSelected", ")", ";", "}", "}" ]
get all webpackages
[ "get", "all", "webpackages" ]
3fb7075fc9de2185475ade21c3be8d31f0f56e1d
https://github.com/cubbles/cubx-grunt-webpackage-upload/blob/3fb7075fc9de2185475ade21c3be8d31f0f56e1d/tasks/cubx_webpackage_bulk_upload.js#L33-L82
train
duzun/onemit
onemit.js
EmitEvent
function EmitEvent(props) { const event = this; if ( !(event instanceof EmitEvent) ) { return new EmitEvent(props); } if ( props == undefined ) { props = ''; } if ( typeof props == 'string' ) { props = { type: props }; } _extend(event, props); event.timeStamp = Date.now(); }
javascript
function EmitEvent(props) { const event = this; if ( !(event instanceof EmitEvent) ) { return new EmitEvent(props); } if ( props == undefined ) { props = ''; } if ( typeof props == 'string' ) { props = { type: props }; } _extend(event, props); event.timeStamp = Date.now(); }
[ "function", "EmitEvent", "(", "props", ")", "{", "const", "event", "=", "this", ";", "if", "(", "!", "(", "event", "instanceof", "EmitEvent", ")", ")", "{", "return", "new", "EmitEvent", "(", "props", ")", ";", "}", "if", "(", "props", "==", "undefined", ")", "{", "props", "=", "''", ";", "}", "if", "(", "typeof", "props", "==", "'string'", ")", "{", "props", "=", "{", "type", ":", "props", "}", ";", "}", "_extend", "(", "event", ",", "props", ")", ";", "event", ".", "timeStamp", "=", "Date", ".", "now", "(", ")", ";", "}" ]
Event constructor. @param (Object) props - { type: "eventName", ... } or just "eventName"
[ "Event", "constructor", "." ]
12360553cf36379e9fc91d36c40d519a822d4987
https://github.com/duzun/onemit/blob/12360553cf36379e9fc91d36c40d519a822d4987/onemit.js#L112-L125
train
duzun/onemit
onemit.js
_extend
function _extend(obj, from) { for ( let key in from ) if ( hop.call(from, key) ) { obj[key] = from[key]; } return obj; }
javascript
function _extend(obj, from) { for ( let key in from ) if ( hop.call(from, key) ) { obj[key] = from[key]; } return obj; }
[ "function", "_extend", "(", "obj", ",", "from", ")", "{", "for", "(", "let", "key", "in", "from", ")", "if", "(", "hop", ".", "call", "(", "from", ",", "key", ")", ")", "{", "obj", "[", "key", "]", "=", "from", "[", "key", "]", ";", "}", "return", "obj", ";", "}" ]
Copy properties to `obj` from `from` @param (Object) obj @param (Object) from - source object @return (Object) obj @api private
[ "Copy", "properties", "to", "obj", "from", "from" ]
12360553cf36379e9fc91d36c40d519a822d4987
https://github.com/duzun/onemit/blob/12360553cf36379e9fc91d36c40d519a822d4987/onemit.js#L522-L527
train
duzun/onemit
onemit.js
_append
function _append(array, args/*, ...*/) { var i = array.length , j , k = 1 , l , m = arguments.length , a ; for(; k < m; ++k) { a = arguments[k]; array.length = l = i + a.length; for(j = 0; i < l; ++i, ++j) { array[i] = a[j]; } } return array; }
javascript
function _append(array, args/*, ...*/) { var i = array.length , j , k = 1 , l , m = arguments.length , a ; for(; k < m; ++k) { a = arguments[k]; array.length = l = i + a.length; for(j = 0; i < l; ++i, ++j) { array[i] = a[j]; } } return array; }
[ "function", "_append", "(", "array", ",", "args", ")", "{", "var", "i", "=", "array", ".", "length", ",", "j", ",", "k", "=", "1", ",", "l", ",", "m", "=", "arguments", ".", "length", ",", "a", ";", "for", "(", ";", "k", "<", "m", ";", "++", "k", ")", "{", "a", "=", "arguments", "[", "k", "]", ";", "array", ".", "length", "=", "l", "=", "i", "+", "a", ".", "length", ";", "for", "(", "j", "=", "0", ";", "i", "<", "l", ";", "++", "i", ",", "++", "j", ")", "{", "array", "[", "i", "]", "=", "a", "[", "j", "]", ";", "}", "}", "return", "array", ";", "}" ]
Append elements of `args` to `array`. This function is similar to `array.concat(args)`, but also works on non-Array `args` as if it where an Array, and it modifies the original `array`. @param (Array) array - an array or array-like object @param (Array) args - an array or array-like object to append to `array` @return (Array) array
[ "Append", "elements", "of", "args", "to", "array", "." ]
12360553cf36379e9fc91d36c40d519a822d4987
https://github.com/duzun/onemit/blob/12360553cf36379e9fc91d36c40d519a822d4987/onemit.js#L541-L558
train
byu-oit/aws-scatter-gather
bin/response.js
function (data, circuitbreakerState, callback) { const responder = (circuitbreakerState===CB.OPEN) ? config.bypass : config.handler; // call the handler using its expected paradigm const promise = responder.length > 1 ? new Promise(function(resolve, reject) { responder(data, function(err, result) { if (err) return reject(err); resolve(result); }); }) : Promise.resolve(responder(data)); // provide an asynchronous response in the expected paradigm if (typeof callback !== 'function') return promise; promise.then( function (data) { callback(null, data); }, function (err) { callback(err, null); } ); }
javascript
function (data, circuitbreakerState, callback) { const responder = (circuitbreakerState===CB.OPEN) ? config.bypass : config.handler; // call the handler using its expected paradigm const promise = responder.length > 1 ? new Promise(function(resolve, reject) { responder(data, function(err, result) { if (err) return reject(err); resolve(result); }); }) : Promise.resolve(responder(data)); // provide an asynchronous response in the expected paradigm if (typeof callback !== 'function') return promise; promise.then( function (data) { callback(null, data); }, function (err) { callback(err, null); } ); }
[ "function", "(", "data", ",", "circuitbreakerState", ",", "callback", ")", "{", "const", "responder", "=", "(", "circuitbreakerState", "===", "CB", ".", "OPEN", ")", "?", "config", ".", "bypass", ":", "config", ".", "handler", ";", "const", "promise", "=", "responder", ".", "length", ">", "1", "?", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "responder", "(", "data", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "resolve", "(", "result", ")", ";", "}", ")", ";", "}", ")", ":", "Promise", ".", "resolve", "(", "responder", "(", "data", ")", ")", ";", "if", "(", "typeof", "callback", "!==", "'function'", ")", "return", "promise", ";", "promise", ".", "then", "(", "function", "(", "data", ")", "{", "callback", "(", "null", ",", "data", ")", ";", "}", ",", "function", "(", "err", ")", "{", "callback", "(", "err", ",", "null", ")", ";", "}", ")", ";", "}" ]
define the response function wrapper
[ "define", "the", "response", "function", "wrapper" ]
708e7caa6bea706276d55b3678d8468438d6d163
https://github.com/byu-oit/aws-scatter-gather/blob/708e7caa6bea706276d55b3678d8468438d6d163/bin/response.js#L48-L68
train
paukan-org/core
common/index.js
serviceConfig
function serviceConfig() { var arg = ld.values(arguments), cfg = {}; // try to load file from global directory if(typeof arg[0] === 'string') { var path = arg.shift(); try { cfg = require('/etc/paukan/'+path+'.json'); } catch (err) { // try to load file directly if global fails try { cfg = require(path); } catch (err) {} } } // append default settings var localCfg = arg.shift(); if(!ld.isPlainObject(localCfg)) { throw new Error('at least local config should be specified'); } ld.defaults(cfg, localCfg); // load specific field from package.json var packageCfg = arg.shift(); if(ld.isPlainObject(packageCfg)) { ld.defaults(cfg, ld.pick(packageCfg, ['version', 'description', 'homepage', 'author'])); } return cfg; }
javascript
function serviceConfig() { var arg = ld.values(arguments), cfg = {}; // try to load file from global directory if(typeof arg[0] === 'string') { var path = arg.shift(); try { cfg = require('/etc/paukan/'+path+'.json'); } catch (err) { // try to load file directly if global fails try { cfg = require(path); } catch (err) {} } } // append default settings var localCfg = arg.shift(); if(!ld.isPlainObject(localCfg)) { throw new Error('at least local config should be specified'); } ld.defaults(cfg, localCfg); // load specific field from package.json var packageCfg = arg.shift(); if(ld.isPlainObject(packageCfg)) { ld.defaults(cfg, ld.pick(packageCfg, ['version', 'description', 'homepage', 'author'])); } return cfg; }
[ "function", "serviceConfig", "(", ")", "{", "var", "arg", "=", "ld", ".", "values", "(", "arguments", ")", ",", "cfg", "=", "{", "}", ";", "if", "(", "typeof", "arg", "[", "0", "]", "===", "'string'", ")", "{", "var", "path", "=", "arg", ".", "shift", "(", ")", ";", "try", "{", "cfg", "=", "require", "(", "'/etc/paukan/'", "+", "path", "+", "'.json'", ")", ";", "}", "catch", "(", "err", ")", "{", "try", "{", "cfg", "=", "require", "(", "path", ")", ";", "}", "catch", "(", "err", ")", "{", "}", "}", "}", "var", "localCfg", "=", "arg", ".", "shift", "(", ")", ";", "if", "(", "!", "ld", ".", "isPlainObject", "(", "localCfg", ")", ")", "{", "throw", "new", "Error", "(", "'at least local config should be specified'", ")", ";", "}", "ld", ".", "defaults", "(", "cfg", ",", "localCfg", ")", ";", "var", "packageCfg", "=", "arg", ".", "shift", "(", ")", ";", "if", "(", "ld", ".", "isPlainObject", "(", "packageCfg", ")", ")", "{", "ld", ".", "defaults", "(", "cfg", ",", "ld", ".", "pick", "(", "packageCfg", ",", "[", "'version'", ",", "'description'", ",", "'homepage'", ",", "'author'", "]", ")", ")", ";", "}", "return", "cfg", ";", "}" ]
Take configuration files and service specific info from package.json @params {string|object} - if first parameter is string - will be added config from /etc/paukan/<name>.json - second parameter is confguration object with default settings - last (third, or second if name is not specified - object from package.json where service-specific info will be taken)
[ "Take", "configuration", "files", "and", "service", "specific", "info", "from", "package", ".", "json" ]
e6ff0667d50bc9b25ab5678852316e89521942ad
https://github.com/paukan-org/core/blob/e6ff0667d50bc9b25ab5678852316e89521942ad/common/index.js#L15-L45
train
paukan-org/core
common/index.js
StreamConsole
function StreamConsole(cfg) { cfg = cfg || {}; this.color = cfg.color || true; this.timestamp = (typeof cfg.timestamp === 'undefined') ? 'HH:mm:ss ' : cfg.timestamp; }
javascript
function StreamConsole(cfg) { cfg = cfg || {}; this.color = cfg.color || true; this.timestamp = (typeof cfg.timestamp === 'undefined') ? 'HH:mm:ss ' : cfg.timestamp; }
[ "function", "StreamConsole", "(", "cfg", ")", "{", "cfg", "=", "cfg", "||", "{", "}", ";", "this", ".", "color", "=", "cfg", ".", "color", "||", "true", ";", "this", ".", "timestamp", "=", "(", "typeof", "cfg", ".", "timestamp", "===", "'undefined'", ")", "?", "'HH:mm:ss '", ":", "cfg", ".", "timestamp", ";", "}" ]
Stream to console for bunyan logger
[ "Stream", "to", "console", "for", "bunyan", "logger" ]
e6ff0667d50bc9b25ab5678852316e89521942ad
https://github.com/paukan-org/core/blob/e6ff0667d50bc9b25ab5678852316e89521942ad/common/index.js#L50-L54
train
JGAntunes/ampersand-infinite-scroll
ampersand-infinite-scroll.js
InfiniteScrollSetup
function InfiniteScrollSetup (options) { options || (options = {}); var self = this; var gap = (options.gap || 20); // defaults to 20 self.events = self.events || {}; assign(self.events, {scroll: 'infiniteScroll'}); self.infiniteScroll = function () { if (this.el.scrollHeight - this.el.scrollTop <= this.el.clientHeight + gap) { this.collection.fetchPage(options); } }; }
javascript
function InfiniteScrollSetup (options) { options || (options = {}); var self = this; var gap = (options.gap || 20); // defaults to 20 self.events = self.events || {}; assign(self.events, {scroll: 'infiniteScroll'}); self.infiniteScroll = function () { if (this.el.scrollHeight - this.el.scrollTop <= this.el.clientHeight + gap) { this.collection.fetchPage(options); } }; }
[ "function", "InfiniteScrollSetup", "(", "options", ")", "{", "options", "||", "(", "options", "=", "{", "}", ")", ";", "var", "self", "=", "this", ";", "var", "gap", "=", "(", "options", ".", "gap", "||", "20", ")", ";", "self", ".", "events", "=", "self", ".", "events", "||", "{", "}", ";", "assign", "(", "self", ".", "events", ",", "{", "scroll", ":", "'infiniteScroll'", "}", ")", ";", "self", ".", "infiniteScroll", "=", "function", "(", ")", "{", "if", "(", "this", ".", "el", ".", "scrollHeight", "-", "this", ".", "el", ".", "scrollTop", "<=", "this", ".", "el", ".", "clientHeight", "+", "gap", ")", "{", "this", ".", "collection", ".", "fetchPage", "(", "options", ")", ";", "}", "}", ";", "}" ]
Setup the closure function for the Infinite Scroll callback @param {Object} options - the valid options are: .gap - the pixel margin to fire the request
[ "Setup", "the", "closure", "function", "for", "the", "Infinite", "Scroll", "callback" ]
6d3906eb1905fb2087199ba7daa64e93b06f7d5f
https://github.com/JGAntunes/ampersand-infinite-scroll/blob/6d3906eb1905fb2087199ba7daa64e93b06f7d5f/ampersand-infinite-scroll.js#L11-L24
train
JGAntunes/ampersand-infinite-scroll
ampersand-infinite-scroll.js
InfiniteScrollView
function InfiniteScrollView (options) { options || (options = {}); BaseView.call(this, options); InfiniteScrollSetup.call(this, options); }
javascript
function InfiniteScrollView (options) { options || (options = {}); BaseView.call(this, options); InfiniteScrollSetup.call(this, options); }
[ "function", "InfiniteScrollView", "(", "options", ")", "{", "options", "||", "(", "options", "=", "{", "}", ")", ";", "BaseView", ".", "call", "(", "this", ",", "options", ")", ";", "InfiniteScrollSetup", ".", "call", "(", "this", ",", "options", ")", ";", "}" ]
Infinite Scroll View constructor @param {Object} options - the valid options according to the `ampersand-view` and this module
[ "Infinite", "Scroll", "View", "constructor" ]
6d3906eb1905fb2087199ba7daa64e93b06f7d5f
https://github.com/JGAntunes/ampersand-infinite-scroll/blob/6d3906eb1905fb2087199ba7daa64e93b06f7d5f/ampersand-infinite-scroll.js#L37-L41
train
directiv/data-hyper-repeat
index.js
hyperRepeat
function hyperRepeat(store) { this.compile = compile; this.state = function(config, state) { var res = store.get(config.path, state); if (!res.completed) return false; return state.set(config.source, res.value); }; this.children = function(config, state, children) { var items = state.get(config.source); var arr = []; if (!items) return arr; var target = config.target; var i, c, child; var path = ['state', target]; for (i = 0; i < items.length; i++) { function update() {return items[i]}; for (c = 0; c < children.length; c++) { child = children[c]; if (!child) continue; // TODO set the key prop child = child.updateIn(path, update); arr.push(child); } } return arr; }; }
javascript
function hyperRepeat(store) { this.compile = compile; this.state = function(config, state) { var res = store.get(config.path, state); if (!res.completed) return false; return state.set(config.source, res.value); }; this.children = function(config, state, children) { var items = state.get(config.source); var arr = []; if (!items) return arr; var target = config.target; var i, c, child; var path = ['state', target]; for (i = 0; i < items.length; i++) { function update() {return items[i]}; for (c = 0; c < children.length; c++) { child = children[c]; if (!child) continue; // TODO set the key prop child = child.updateIn(path, update); arr.push(child); } } return arr; }; }
[ "function", "hyperRepeat", "(", "store", ")", "{", "this", ".", "compile", "=", "compile", ";", "this", ".", "state", "=", "function", "(", "config", ",", "state", ")", "{", "var", "res", "=", "store", ".", "get", "(", "config", ".", "path", ",", "state", ")", ";", "if", "(", "!", "res", ".", "completed", ")", "return", "false", ";", "return", "state", ".", "set", "(", "config", ".", "source", ",", "res", ".", "value", ")", ";", "}", ";", "this", ".", "children", "=", "function", "(", "config", ",", "state", ",", "children", ")", "{", "var", "items", "=", "state", ".", "get", "(", "config", ".", "source", ")", ";", "var", "arr", "=", "[", "]", ";", "if", "(", "!", "items", ")", "return", "arr", ";", "var", "target", "=", "config", ".", "target", ";", "var", "i", ",", "c", ",", "child", ";", "var", "path", "=", "[", "'state'", ",", "target", "]", ";", "for", "(", "i", "=", "0", ";", "i", "<", "items", ".", "length", ";", "i", "++", ")", "{", "function", "update", "(", ")", "{", "return", "items", "[", "i", "]", "}", ";", "for", "(", "c", "=", "0", ";", "c", "<", "children", ".", "length", ";", "c", "++", ")", "{", "child", "=", "children", "[", "c", "]", ";", "if", "(", "!", "child", ")", "continue", ";", "child", "=", "child", ".", "updateIn", "(", "path", ",", "update", ")", ";", "arr", ".", "push", "(", "child", ")", ";", "}", "}", "return", "arr", ";", "}", ";", "}" ]
Initialize the 'hyper-repeat' directive Examples: user <- users user <- users[0,2..8] user <- [.featured[0..2] .famous[0..2] .others[0..2]] @param {StoreHyper}
[ "Initialize", "the", "hyper", "-", "repeat", "directive" ]
2f2aab31d2f9db4ca83765a793ad6f0c795c3f58
https://github.com/directiv/data-hyper-repeat/blob/2f2aab31d2f9db4ca83765a793ad6f0c795c3f58/index.js#L28-L60
train
directiv/data-hyper-repeat
index.js
compile
function compile(input) { var res = input.match(REGEX); if (!res) throw new Error('Invalid expression: "' + input + '"'); var range = res[3]; var parsedRange; if (range) { parsedRange = parser(range); if (parsedRange === null) throw new Error('Invalid range expression: "' + range + '" in "' + input + '"'); } var path = res[2]; var source = path.split('.'); // TODO support ranges if (parsedRange) console.warn('data-hyper-repeat ranges are not supported at this time'); return { target: res[1], path: path, source: source[source.length - 1], range: parsedRange }; }
javascript
function compile(input) { var res = input.match(REGEX); if (!res) throw new Error('Invalid expression: "' + input + '"'); var range = res[3]; var parsedRange; if (range) { parsedRange = parser(range); if (parsedRange === null) throw new Error('Invalid range expression: "' + range + '" in "' + input + '"'); } var path = res[2]; var source = path.split('.'); // TODO support ranges if (parsedRange) console.warn('data-hyper-repeat ranges are not supported at this time'); return { target: res[1], path: path, source: source[source.length - 1], range: parsedRange }; }
[ "function", "compile", "(", "input", ")", "{", "var", "res", "=", "input", ".", "match", "(", "REGEX", ")", ";", "if", "(", "!", "res", ")", "throw", "new", "Error", "(", "'Invalid expression: \"'", "+", "input", "+", "'\"'", ")", ";", "var", "range", "=", "res", "[", "3", "]", ";", "var", "parsedRange", ";", "if", "(", "range", ")", "{", "parsedRange", "=", "parser", "(", "range", ")", ";", "if", "(", "parsedRange", "===", "null", ")", "throw", "new", "Error", "(", "'Invalid range expression: \"'", "+", "range", "+", "'\" in \"'", "+", "input", "+", "'\"'", ")", ";", "}", "var", "path", "=", "res", "[", "2", "]", ";", "var", "source", "=", "path", ".", "split", "(", "'.'", ")", ";", "if", "(", "parsedRange", ")", "console", ".", "warn", "(", "'data-hyper-repeat ranges are not supported at this time'", ")", ";", "return", "{", "target", ":", "res", "[", "1", "]", ",", "path", ":", "path", ",", "source", ":", "source", "[", "source", ".", "length", "-", "1", "]", ",", "range", ":", "parsedRange", "}", ";", "}" ]
Compile a 'hyper-repeat' expression
[ "Compile", "a", "hyper", "-", "repeat", "expression" ]
2f2aab31d2f9db4ca83765a793ad6f0c795c3f58
https://github.com/directiv/data-hyper-repeat/blob/2f2aab31d2f9db4ca83765a793ad6f0c795c3f58/index.js#L72-L95
train
RnbWd/parse-browserify
lib/file.js
function(file, type) { var promise = new Parse.Promise(); if (typeof(FileReader) === "undefined") { return Parse.Promise.error(new Parse.Error( Parse.Error.FILE_READ_ERROR, "Attempted to use a FileReader on an unsupported browser.")); } var reader = new FileReader(); reader.onloadend = function() { if (reader.readyState !== 2) { promise.reject(new Parse.Error( Parse.Error.FILE_READ_ERROR, "Error reading file.")); return; } var dataURL = reader.result; var matches = /^data:([^;]*);base64,(.*)$/.exec(dataURL); if (!matches) { promise.reject(new Parse.Error( Parse.ERROR.FILE_READ_ERROR, "Unable to interpret data URL: " + dataURL)); return; } promise.resolve(matches[2], type || matches[1]); }; reader.readAsDataURL(file); return promise; }
javascript
function(file, type) { var promise = new Parse.Promise(); if (typeof(FileReader) === "undefined") { return Parse.Promise.error(new Parse.Error( Parse.Error.FILE_READ_ERROR, "Attempted to use a FileReader on an unsupported browser.")); } var reader = new FileReader(); reader.onloadend = function() { if (reader.readyState !== 2) { promise.reject(new Parse.Error( Parse.Error.FILE_READ_ERROR, "Error reading file.")); return; } var dataURL = reader.result; var matches = /^data:([^;]*);base64,(.*)$/.exec(dataURL); if (!matches) { promise.reject(new Parse.Error( Parse.ERROR.FILE_READ_ERROR, "Unable to interpret data URL: " + dataURL)); return; } promise.resolve(matches[2], type || matches[1]); }; reader.readAsDataURL(file); return promise; }
[ "function", "(", "file", ",", "type", ")", "{", "var", "promise", "=", "new", "Parse", ".", "Promise", "(", ")", ";", "if", "(", "typeof", "(", "FileReader", ")", "===", "\"undefined\"", ")", "{", "return", "Parse", ".", "Promise", ".", "error", "(", "new", "Parse", ".", "Error", "(", "Parse", ".", "Error", ".", "FILE_READ_ERROR", ",", "\"Attempted to use a FileReader on an unsupported browser.\"", ")", ")", ";", "}", "var", "reader", "=", "new", "FileReader", "(", ")", ";", "reader", ".", "onloadend", "=", "function", "(", ")", "{", "if", "(", "reader", ".", "readyState", "!==", "2", ")", "{", "promise", ".", "reject", "(", "new", "Parse", ".", "Error", "(", "Parse", ".", "Error", ".", "FILE_READ_ERROR", ",", "\"Error reading file.\"", ")", ")", ";", "return", ";", "}", "var", "dataURL", "=", "reader", ".", "result", ";", "var", "matches", "=", "/", "^data:([^;]*);base64,(.*)$", "/", ".", "exec", "(", "dataURL", ")", ";", "if", "(", "!", "matches", ")", "{", "promise", ".", "reject", "(", "new", "Parse", ".", "Error", "(", "Parse", ".", "ERROR", ".", "FILE_READ_ERROR", ",", "\"Unable to interpret data URL: \"", "+", "dataURL", ")", ")", ";", "return", ";", "}", "promise", ".", "resolve", "(", "matches", "[", "2", "]", ",", "type", "||", "matches", "[", "1", "]", ")", ";", "}", ";", "reader", ".", "readAsDataURL", "(", "file", ")", ";", "return", "promise", ";", "}" ]
Reads a File using a FileReader. @param file {File} the File to read. @param type {String} (optional) the mimetype to override with. @return {Parse.Promise} A Promise that will be fulfilled with a base64-encoded string of the data and its mime type.
[ "Reads", "a", "File", "using", "a", "FileReader", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/file.js#L253-L284
train
RnbWd/parse-browserify
lib/file.js
function(options) { options= options || {}; var self = this; if (!self._previousSave) { self._previousSave = self._source.then(function(base64, type) { var data = { base64: base64, _ContentType: type }; return Parse._request({ route: "files", className: self._name, method: 'POST', data: data, useMasterKey: options.useMasterKey }); }).then(function(response) { self._name = response.name; self._url = response.url; return self; }); } return self._previousSave._thenRunCallbacks(options); }
javascript
function(options) { options= options || {}; var self = this; if (!self._previousSave) { self._previousSave = self._source.then(function(base64, type) { var data = { base64: base64, _ContentType: type }; return Parse._request({ route: "files", className: self._name, method: 'POST', data: data, useMasterKey: options.useMasterKey }); }).then(function(response) { self._name = response.name; self._url = response.url; return self; }); } return self._previousSave._thenRunCallbacks(options); }
[ "function", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "self", "=", "this", ";", "if", "(", "!", "self", ".", "_previousSave", ")", "{", "self", ".", "_previousSave", "=", "self", ".", "_source", ".", "then", "(", "function", "(", "base64", ",", "type", ")", "{", "var", "data", "=", "{", "base64", ":", "base64", ",", "_ContentType", ":", "type", "}", ";", "return", "Parse", ".", "_request", "(", "{", "route", ":", "\"files\"", ",", "className", ":", "self", ".", "_name", ",", "method", ":", "'POST'", ",", "data", ":", "data", ",", "useMasterKey", ":", "options", ".", "useMasterKey", "}", ")", ";", "}", ")", ".", "then", "(", "function", "(", "response", ")", "{", "self", ".", "_name", "=", "response", ".", "name", ";", "self", ".", "_url", "=", "response", ".", "url", ";", "return", "self", ";", "}", ")", ";", "}", "return", "self", ".", "_previousSave", ".", "_thenRunCallbacks", "(", "options", ")", ";", "}" ]
Saves the file to the Parse cloud. @param {Object} options A Backbone-style options object. @return {Parse.Promise} Promise that is resolved when the save finishes.
[ "Saves", "the", "file", "to", "the", "Parse", "cloud", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/file.js#L374-L399
train
Zenedith/npm-my-restify-api
lib/public/swagger/swagger-ui.js
function (operation, parameter) { // TODO the reference to operation.api is not available if (operation.api && operation.api.parameterMacro) { return operation.api.parameterMacro(operation, parameter); } else { return parameter.defaultValue; } }
javascript
function (operation, parameter) { // TODO the reference to operation.api is not available if (operation.api && operation.api.parameterMacro) { return operation.api.parameterMacro(operation, parameter); } else { return parameter.defaultValue; } }
[ "function", "(", "operation", ",", "parameter", ")", "{", "if", "(", "operation", ".", "api", "&&", "operation", ".", "api", ".", "parameterMacro", ")", "{", "return", "operation", ".", "api", ".", "parameterMacro", "(", "operation", ",", "parameter", ")", ";", "}", "else", "{", "return", "parameter", ".", "defaultValue", ";", "}", "}" ]
allows override of the default value based on the parameter being supplied
[ "allows", "override", "of", "the", "default", "value", "based", "on", "the", "parameter", "being", "supplied" ]
946e40ede37124f6f4acaea19d73ab3c9d5074d9
https://github.com/Zenedith/npm-my-restify-api/blob/946e40ede37124f6f4acaea19d73ab3c9d5074d9/lib/public/swagger/swagger-ui.js#L2650-L2657
train
Zenedith/npm-my-restify-api
lib/public/swagger/swagger-ui.js
function (model, property) { // TODO the reference to model.api is not available if (model.api && model.api.modelPropertyMacro) { return model.api.modelPropertyMacro(model, property); } else { return property.default; } }
javascript
function (model, property) { // TODO the reference to model.api is not available if (model.api && model.api.modelPropertyMacro) { return model.api.modelPropertyMacro(model, property); } else { return property.default; } }
[ "function", "(", "model", ",", "property", ")", "{", "if", "(", "model", ".", "api", "&&", "model", ".", "api", ".", "modelPropertyMacro", ")", "{", "return", "model", ".", "api", ".", "modelPropertyMacro", "(", "model", ",", "property", ")", ";", "}", "else", "{", "return", "property", ".", "default", ";", "}", "}" ]
allows overriding the default value of an model property
[ "allows", "overriding", "the", "default", "value", "of", "an", "model", "property" ]
946e40ede37124f6f4acaea19d73ab3c9d5074d9
https://github.com/Zenedith/npm-my-restify-api/blob/946e40ede37124f6f4acaea19d73ab3c9d5074d9/lib/public/swagger/swagger-ui.js#L2662-L2669
train
Zenedith/npm-my-restify-api
lib/public/swagger/swagger-ui.js
baseIsEqual
function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) { // Exit early for identical values. if (value === other) { // Treat `+0` vs. `-0` as not equal. return value !== 0 || (1 / value == 1 / other); } var valType = typeof value, othType = typeof other; // Exit early for unlike primitive values. if ((valType != 'function' && valType != 'object' && othType != 'function' && othType != 'object') || value == null || other == null) { // Return `false` unless both values are `NaN`. return value !== value && other !== other; } return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB); }
javascript
function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) { // Exit early for identical values. if (value === other) { // Treat `+0` vs. `-0` as not equal. return value !== 0 || (1 / value == 1 / other); } var valType = typeof value, othType = typeof other; // Exit early for unlike primitive values. if ((valType != 'function' && valType != 'object' && othType != 'function' && othType != 'object') || value == null || other == null) { // Return `false` unless both values are `NaN`. return value !== value && other !== other; } return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB); }
[ "function", "baseIsEqual", "(", "value", ",", "other", ",", "customizer", ",", "isLoose", ",", "stackA", ",", "stackB", ")", "{", "if", "(", "value", "===", "other", ")", "{", "return", "value", "!==", "0", "||", "(", "1", "/", "value", "==", "1", "/", "other", ")", ";", "}", "var", "valType", "=", "typeof", "value", ",", "othType", "=", "typeof", "other", ";", "if", "(", "(", "valType", "!=", "'function'", "&&", "valType", "!=", "'object'", "&&", "othType", "!=", "'function'", "&&", "othType", "!=", "'object'", ")", "||", "value", "==", "null", "||", "other", "==", "null", ")", "{", "return", "value", "!==", "value", "&&", "other", "!==", "other", ";", "}", "return", "baseIsEqualDeep", "(", "value", ",", "other", ",", "baseIsEqual", ",", "customizer", ",", "isLoose", ",", "stackA", ",", "stackB", ")", ";", "}" ]
The base implementation of `_.isEqual` without support for `this` binding `customizer` functions. @private @param {*} value The value to compare. @param {*} other The other value to compare. @param {Function} [customizer] The function to customize comparing values. @param {boolean} [isLoose] Specify performing partial comparisons. @param {Array} [stackA] Tracks traversed `value` objects. @param {Array} [stackB] Tracks traversed `other` objects. @returns {boolean} Returns `true` if the values are equivalent, else `false`.
[ "The", "base", "implementation", "of", "_", ".", "isEqual", "without", "support", "for", "this", "binding", "customizer", "functions", "." ]
946e40ede37124f6f4acaea19d73ab3c9d5074d9
https://github.com/Zenedith/npm-my-restify-api/blob/946e40ede37124f6f4acaea19d73ab3c9d5074d9/lib/public/swagger/swagger-ui.js#L16021-L16037
train
Zenedith/npm-my-restify-api
lib/public/swagger/swagger-ui.js
baseMatchesProperty
function baseMatchesProperty(key, value) { if (isStrictComparable(value)) { return function(object) { return object != null && object[key] === value && (typeof value != 'undefined' || (key in toObject(object))); }; } return function(object) { return object != null && baseIsEqual(value, object[key], null, true); }; }
javascript
function baseMatchesProperty(key, value) { if (isStrictComparable(value)) { return function(object) { return object != null && object[key] === value && (typeof value != 'undefined' || (key in toObject(object))); }; } return function(object) { return object != null && baseIsEqual(value, object[key], null, true); }; }
[ "function", "baseMatchesProperty", "(", "key", ",", "value", ")", "{", "if", "(", "isStrictComparable", "(", "value", ")", ")", "{", "return", "function", "(", "object", ")", "{", "return", "object", "!=", "null", "&&", "object", "[", "key", "]", "===", "value", "&&", "(", "typeof", "value", "!=", "'undefined'", "||", "(", "key", "in", "toObject", "(", "object", ")", ")", ")", ";", "}", ";", "}", "return", "function", "(", "object", ")", "{", "return", "object", "!=", "null", "&&", "baseIsEqual", "(", "value", ",", "object", "[", "key", "]", ",", "null", ",", "true", ")", ";", "}", ";", "}" ]
The base implementation of `_.matchesProperty` which does not coerce `key` to a string. @private @param {string} key The key of the property to get. @param {*} value The value to compare. @returns {Function} Returns the new function.
[ "The", "base", "implementation", "of", "_", ".", "matchesProperty", "which", "does", "not", "coerce", "key", "to", "a", "string", "." ]
946e40ede37124f6f4acaea19d73ab3c9d5074d9
https://github.com/Zenedith/npm-my-restify-api/blob/946e40ede37124f6f4acaea19d73ab3c9d5074d9/lib/public/swagger/swagger-ui.js#L16314-L16324
train
Zenedith/npm-my-restify-api
lib/public/swagger/swagger-ui.js
createBaseEach
function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { var length = collection ? collection.length : 0; if (!isLength(length)) { return eachFunc(collection, iteratee); } var index = fromRight ? length : -1, iterable = toObject(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; }
javascript
function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { var length = collection ? collection.length : 0; if (!isLength(length)) { return eachFunc(collection, iteratee); } var index = fromRight ? length : -1, iterable = toObject(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; }
[ "function", "createBaseEach", "(", "eachFunc", ",", "fromRight", ")", "{", "return", "function", "(", "collection", ",", "iteratee", ")", "{", "var", "length", "=", "collection", "?", "collection", ".", "length", ":", "0", ";", "if", "(", "!", "isLength", "(", "length", ")", ")", "{", "return", "eachFunc", "(", "collection", ",", "iteratee", ")", ";", "}", "var", "index", "=", "fromRight", "?", "length", ":", "-", "1", ",", "iterable", "=", "toObject", "(", "collection", ")", ";", "while", "(", "(", "fromRight", "?", "index", "--", ":", "++", "index", "<", "length", ")", ")", "{", "if", "(", "iteratee", "(", "iterable", "[", "index", "]", ",", "index", ",", "iterable", ")", "===", "false", ")", "{", "break", ";", "}", "}", "return", "collection", ";", "}", ";", "}" ]
Creates a `baseEach` or `baseEachRight` function. @private @param {Function} eachFunc The function to iterate over a collection. @param {boolean} [fromRight] Specify iterating from right to left. @returns {Function} Returns the new base function.
[ "Creates", "a", "baseEach", "or", "baseEachRight", "function", "." ]
946e40ede37124f6f4acaea19d73ab3c9d5074d9
https://github.com/Zenedith/npm-my-restify-api/blob/946e40ede37124f6f4acaea19d73ab3c9d5074d9/lib/public/swagger/swagger-ui.js#L16664-L16680
train
phun-ky/patsy
lib/config.js
function(config,callback,patsy){ patsy = typeof config === 'function' && typeof callback === 'object' ? callback : patsy; callback = typeof config === 'function' ? config : callback; config = typeof config === 'function' ? undefined : config; if(typeof config !== 'undefined' && typeof callback !== 'undefined' && typeof callback === 'function'){ try{ config = this.bake(config); fs.writeFileSync( "patsy.json", JSON.stringify( config, null, 2 ) ); callback(patsy); } catch(e){ console.log('config.create',e); return false; } } else { patsy.config.generateDefaultConfiguration(); callback(patsy); } }
javascript
function(config,callback,patsy){ patsy = typeof config === 'function' && typeof callback === 'object' ? callback : patsy; callback = typeof config === 'function' ? config : callback; config = typeof config === 'function' ? undefined : config; if(typeof config !== 'undefined' && typeof callback !== 'undefined' && typeof callback === 'function'){ try{ config = this.bake(config); fs.writeFileSync( "patsy.json", JSON.stringify( config, null, 2 ) ); callback(patsy); } catch(e){ console.log('config.create',e); return false; } } else { patsy.config.generateDefaultConfiguration(); callback(patsy); } }
[ "function", "(", "config", ",", "callback", ",", "patsy", ")", "{", "patsy", "=", "typeof", "config", "===", "'function'", "&&", "typeof", "callback", "===", "'object'", "?", "callback", ":", "patsy", ";", "callback", "=", "typeof", "config", "===", "'function'", "?", "config", ":", "callback", ";", "config", "=", "typeof", "config", "===", "'function'", "?", "undefined", ":", "config", ";", "if", "(", "typeof", "config", "!==", "'undefined'", "&&", "typeof", "callback", "!==", "'undefined'", "&&", "typeof", "callback", "===", "'function'", ")", "{", "try", "{", "config", "=", "this", ".", "bake", "(", "config", ")", ";", "fs", ".", "writeFileSync", "(", "\"patsy.json\"", ",", "JSON", ".", "stringify", "(", "config", ",", "null", ",", "2", ")", ")", ";", "callback", "(", "patsy", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "'config.create'", ",", "e", ")", ";", "return", "false", ";", "}", "}", "else", "{", "patsy", ".", "config", ".", "generateDefaultConfiguration", "(", ")", ";", "callback", "(", "patsy", ")", ";", "}", "}" ]
Function to create a config file with given configuration object @param Object config @param Funciton callback
[ "Function", "to", "create", "a", "config", "file", "with", "given", "configuration", "object" ]
b2bf3e6c72e17c38d9b2cf2fa4306478fc3858a5
https://github.com/phun-ky/patsy/blob/b2bf3e6c72e17c38d9b2cf2fa4306478fc3858a5/lib/config.js#L75-L110
train
phun-ky/patsy
lib/config.js
function(patsy, project_path){ if(opts.verbose){ util.print('>>'.cyan + ' Loading project configuration...'); } if(typeof project_path === 'undefined'){ if(opts.verbose){ patsy.utils.notice(); patsy.utils.notice('No project path set, declaring path to CWD: '.white + String(process.cwd() + path.sep).inverse.cyan + ''); } project_path = opts.project_path || process.cwd() + path.sep; } else { if(opts.verbose){ patsy.utils.ok(); } } var _path_to_config = project_path + 'patsy.json'; if(opts.verbose){ util.print('>>'.cyan + ' Reading project configuration file: ' + _path_to_config.inverse.cyan + '...\n'); } if(!fs.existsSync(_path_to_config)){ patsy.utils.notice(); if(opts.verbose){ patsy.utils.notice('Configuration file not found here, looking elsewhere: ' + _path_to_config.inverse.cyan + '...\n'); } patsy.scripture.print('[Patsy]'.yellow + ': <stumbling forward>\n'); _path_to_config = this.searchForConfigFile(patsy); } if(fs.existsSync(_path_to_config)){ if(opts.verbose){ patsy.utils.ok('File found here: ' + _path_to_config.inverse.cyan); util.print('>>'.cyan + ' Loading project configuration...'); } // Read file synchroneously, parse contents as JSON and return config var _config_json; try{ _config_json = require(_path_to_config); } catch (e){ patsy.utils.fail(); } if(this.validate(_config_json)){ if(opts.verbose){ patsy.utils.ok(); } } else { if(opts.verbose){ patsy.utils.fail('Configuration file is not valid!'); } patsy.scripture.print('[Patsy]'.yellow + ': Sire! The configuration script is not valid! We have to turn around!\n'); process.exit(1); } _config_json.project.environment.rel_path = path.relative(_config_json.appPath || '', _config_json.project.environment.abs_path) + path.sep; return _config_json; } else { if(opts.verbose){ util.print('>> FAIL'.red + ': Loading project configuration: Could not find configuration file!'.white + '\n'); } return undefined; } }
javascript
function(patsy, project_path){ if(opts.verbose){ util.print('>>'.cyan + ' Loading project configuration...'); } if(typeof project_path === 'undefined'){ if(opts.verbose){ patsy.utils.notice(); patsy.utils.notice('No project path set, declaring path to CWD: '.white + String(process.cwd() + path.sep).inverse.cyan + ''); } project_path = opts.project_path || process.cwd() + path.sep; } else { if(opts.verbose){ patsy.utils.ok(); } } var _path_to_config = project_path + 'patsy.json'; if(opts.verbose){ util.print('>>'.cyan + ' Reading project configuration file: ' + _path_to_config.inverse.cyan + '...\n'); } if(!fs.existsSync(_path_to_config)){ patsy.utils.notice(); if(opts.verbose){ patsy.utils.notice('Configuration file not found here, looking elsewhere: ' + _path_to_config.inverse.cyan + '...\n'); } patsy.scripture.print('[Patsy]'.yellow + ': <stumbling forward>\n'); _path_to_config = this.searchForConfigFile(patsy); } if(fs.existsSync(_path_to_config)){ if(opts.verbose){ patsy.utils.ok('File found here: ' + _path_to_config.inverse.cyan); util.print('>>'.cyan + ' Loading project configuration...'); } // Read file synchroneously, parse contents as JSON and return config var _config_json; try{ _config_json = require(_path_to_config); } catch (e){ patsy.utils.fail(); } if(this.validate(_config_json)){ if(opts.verbose){ patsy.utils.ok(); } } else { if(opts.verbose){ patsy.utils.fail('Configuration file is not valid!'); } patsy.scripture.print('[Patsy]'.yellow + ': Sire! The configuration script is not valid! We have to turn around!\n'); process.exit(1); } _config_json.project.environment.rel_path = path.relative(_config_json.appPath || '', _config_json.project.environment.abs_path) + path.sep; return _config_json; } else { if(opts.verbose){ util.print('>> FAIL'.red + ': Loading project configuration: Could not find configuration file!'.white + '\n'); } return undefined; } }
[ "function", "(", "patsy", ",", "project_path", ")", "{", "if", "(", "opts", ".", "verbose", ")", "{", "util", ".", "print", "(", "'>>'", ".", "cyan", "+", "' Loading project configuration...'", ")", ";", "}", "if", "(", "typeof", "project_path", "===", "'undefined'", ")", "{", "if", "(", "opts", ".", "verbose", ")", "{", "patsy", ".", "utils", ".", "notice", "(", ")", ";", "patsy", ".", "utils", ".", "notice", "(", "'No project path set, declaring path to CWD: '", ".", "white", "+", "String", "(", "process", ".", "cwd", "(", ")", "+", "path", ".", "sep", ")", ".", "inverse", ".", "cyan", "+", "''", ")", ";", "}", "project_path", "=", "opts", ".", "project_path", "||", "process", ".", "cwd", "(", ")", "+", "path", ".", "sep", ";", "}", "else", "{", "if", "(", "opts", ".", "verbose", ")", "{", "patsy", ".", "utils", ".", "ok", "(", ")", ";", "}", "}", "var", "_path_to_config", "=", "project_path", "+", "'patsy.json'", ";", "if", "(", "opts", ".", "verbose", ")", "{", "util", ".", "print", "(", "'>>'", ".", "cyan", "+", "' Reading project configuration file: '", "+", "_path_to_config", ".", "inverse", ".", "cyan", "+", "'...\\n'", ")", ";", "}", "\\n", "if", "(", "!", "fs", ".", "existsSync", "(", "_path_to_config", ")", ")", "{", "patsy", ".", "utils", ".", "notice", "(", ")", ";", "if", "(", "opts", ".", "verbose", ")", "{", "patsy", ".", "utils", ".", "notice", "(", "'Configuration file not found here, looking elsewhere: '", "+", "_path_to_config", ".", "inverse", ".", "cyan", "+", "'...\\n'", ")", ";", "}", "\\n", "patsy", ".", "scripture", ".", "print", "(", "'[Patsy]'", ".", "yellow", "+", "': <stumbling forward>\\n'", ")", ";", "}", "}" ]
Function to load patsy configuration @param Object patsy @param String projectPath @return Object
[ "Function", "to", "load", "patsy", "configuration" ]
b2bf3e6c72e17c38d9b2cf2fa4306478fc3858a5
https://github.com/phun-ky/patsy/blob/b2bf3e6c72e17c38d9b2cf2fa4306478fc3858a5/lib/config.js#L265-L374
train
phun-ky/patsy
lib/config.js
function () { var defaultConfig = JSON.parse(fs.readFileSync(__dirname + '/../patsy.default.json', 'utf8')); var projectSpecificSettings = { "project": { "details" : { "name" : path.basename(process.cwd()) }, "environment": { "root" : path.basename(process.cwd()), "abs_path": process.cwd() + path.sep } } }; var almostDefaultConfig = require('./utils').deepExtend(defaultConfig, projectSpecificSettings); almostDefaultConfig = JSON.stringify(almostDefaultConfig, null, 2); fs.writeFileSync("patsy.json", almostDefaultConfig); }
javascript
function () { var defaultConfig = JSON.parse(fs.readFileSync(__dirname + '/../patsy.default.json', 'utf8')); var projectSpecificSettings = { "project": { "details" : { "name" : path.basename(process.cwd()) }, "environment": { "root" : path.basename(process.cwd()), "abs_path": process.cwd() + path.sep } } }; var almostDefaultConfig = require('./utils').deepExtend(defaultConfig, projectSpecificSettings); almostDefaultConfig = JSON.stringify(almostDefaultConfig, null, 2); fs.writeFileSync("patsy.json", almostDefaultConfig); }
[ "function", "(", ")", "{", "var", "defaultConfig", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "__dirname", "+", "'/../patsy.default.json'", ",", "'utf8'", ")", ")", ";", "var", "projectSpecificSettings", "=", "{", "\"project\"", ":", "{", "\"details\"", ":", "{", "\"name\"", ":", "path", ".", "basename", "(", "process", ".", "cwd", "(", ")", ")", "}", ",", "\"environment\"", ":", "{", "\"root\"", ":", "path", ".", "basename", "(", "process", ".", "cwd", "(", ")", ")", ",", "\"abs_path\"", ":", "process", ".", "cwd", "(", ")", "+", "path", ".", "sep", "}", "}", "}", ";", "var", "almostDefaultConfig", "=", "require", "(", "'./utils'", ")", ".", "deepExtend", "(", "defaultConfig", ",", "projectSpecificSettings", ")", ";", "almostDefaultConfig", "=", "JSON", ".", "stringify", "(", "almostDefaultConfig", ",", "null", ",", "2", ")", ";", "fs", ".", "writeFileSync", "(", "\"patsy.json\"", ",", "almostDefaultConfig", ")", ";", "}" ]
Generates a default patsy.json configuration file in the root of the current project. @var Object
[ "Generates", "a", "default", "patsy", ".", "json", "configuration", "file", "in", "the", "root", "of", "the", "current", "project", "." ]
b2bf3e6c72e17c38d9b2cf2fa4306478fc3858a5
https://github.com/phun-ky/patsy/blob/b2bf3e6c72e17c38d9b2cf2fa4306478fc3858a5/lib/config.js#L380-L401
train
ltoussaint/node-bootstrap-core
application.js
dispatch
function dispatch(request, response) { return Promise.resolve() .then(resolveRouters.bind(this, request)) .then(callAction.bind(this, request, response)); }
javascript
function dispatch(request, response) { return Promise.resolve() .then(resolveRouters.bind(this, request)) .then(callAction.bind(this, request, response)); }
[ "function", "dispatch", "(", "request", ",", "response", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "resolveRouters", ".", "bind", "(", "this", ",", "request", ")", ")", ".", "then", "(", "callAction", ".", "bind", "(", "this", ",", "request", ",", "response", ")", ")", ";", "}" ]
Dispatch request in good action using routers @param request @param response @returns {Promise}
[ "Dispatch", "request", "in", "good", "action", "using", "routers" ]
b083b320900ed068007e58af2249825b8da24c79
https://github.com/ltoussaint/node-bootstrap-core/blob/b083b320900ed068007e58af2249825b8da24c79/application.js#L105-L109
train
ltoussaint/node-bootstrap-core
application.js
resolveRouters
function resolveRouters(request) { for (var i = 0, l = routers.length; i < l; i++) { var callback = routers[i].resolve(request); if (null != callback) { return Promise.resolve(callback); } } return Promise.reject('Route not defined for "' + request.url + '"'); }
javascript
function resolveRouters(request) { for (var i = 0, l = routers.length; i < l; i++) { var callback = routers[i].resolve(request); if (null != callback) { return Promise.resolve(callback); } } return Promise.reject('Route not defined for "' + request.url + '"'); }
[ "function", "resolveRouters", "(", "request", ")", "{", "for", "(", "var", "i", "=", "0", ",", "l", "=", "routers", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "var", "callback", "=", "routers", "[", "i", "]", ".", "resolve", "(", "request", ")", ";", "if", "(", "null", "!=", "callback", ")", "{", "return", "Promise", ".", "resolve", "(", "callback", ")", ";", "}", "}", "return", "Promise", ".", "reject", "(", "'Route not defined for \"'", "+", "request", ".", "url", "+", "'\"'", ")", ";", "}" ]
Resolve uri using routers @param request @returns {Promise}
[ "Resolve", "uri", "using", "routers" ]
b083b320900ed068007e58af2249825b8da24c79
https://github.com/ltoussaint/node-bootstrap-core/blob/b083b320900ed068007e58af2249825b8da24c79/application.js#L116-L124
train
ltoussaint/node-bootstrap-core
application.js
callAction
function callAction(request, response, callback) { if (typeof callback == 'function') { return Promive.resolve() .then(callback.bind(null, request, response)); } try { var Action = require(ACTION_PATH + '/' + callback.action + '.js'); } catch (error) { if (error.message == 'Cannot find module \'' + ACTION_PATH + '/' + callback.action + '.js\'') { return Promise.reject('Action ' + callback.action + ' does not exist.') .catch(this.onPageNotFound.bind(this, request, response)); } return Promise.reject(error) .catch(this.onError.bind(this, request, response)); } var instance = new Action(request, response); // Test if method exists if (!instance[callback.method]) { return Promise.reject(new Error('Method "' + callback.method + '" not found in action "' + callback.action + '"')); } var promise = Promise.resolve(); if (instance.init && 'function' == typeof instance.init) { promise = promise.then(function () { return instance.init(); }); } promise = promise.then(function () { return instance[callback.method].apply(instance, callback.arguments); }); if (instance.onError && 'function' == typeof instance.onError) { promise = promise.catch(function (error) { return instance.onError.call(instance, error) }); } promise = promise.catch(this.onError.bind(this, request, response)); return promise; }
javascript
function callAction(request, response, callback) { if (typeof callback == 'function') { return Promive.resolve() .then(callback.bind(null, request, response)); } try { var Action = require(ACTION_PATH + '/' + callback.action + '.js'); } catch (error) { if (error.message == 'Cannot find module \'' + ACTION_PATH + '/' + callback.action + '.js\'') { return Promise.reject('Action ' + callback.action + ' does not exist.') .catch(this.onPageNotFound.bind(this, request, response)); } return Promise.reject(error) .catch(this.onError.bind(this, request, response)); } var instance = new Action(request, response); // Test if method exists if (!instance[callback.method]) { return Promise.reject(new Error('Method "' + callback.method + '" not found in action "' + callback.action + '"')); } var promise = Promise.resolve(); if (instance.init && 'function' == typeof instance.init) { promise = promise.then(function () { return instance.init(); }); } promise = promise.then(function () { return instance[callback.method].apply(instance, callback.arguments); }); if (instance.onError && 'function' == typeof instance.onError) { promise = promise.catch(function (error) { return instance.onError.call(instance, error) }); } promise = promise.catch(this.onError.bind(this, request, response)); return promise; }
[ "function", "callAction", "(", "request", ",", "response", ",", "callback", ")", "{", "if", "(", "typeof", "callback", "==", "'function'", ")", "{", "return", "Promive", ".", "resolve", "(", ")", ".", "then", "(", "callback", ".", "bind", "(", "null", ",", "request", ",", "response", ")", ")", ";", "}", "try", "{", "var", "Action", "=", "require", "(", "ACTION_PATH", "+", "'/'", "+", "callback", ".", "action", "+", "'.js'", ")", ";", "}", "catch", "(", "error", ")", "{", "if", "(", "error", ".", "message", "==", "'Cannot find module \\''", "+", "\\'", "+", "ACTION_PATH", "+", "'/'", "+", "callback", ".", "action", ")", "'.js\\''", "\\'", "}", "{", "return", "Promise", ".", "reject", "(", "'Action '", "+", "callback", ".", "action", "+", "' does not exist.'", ")", ".", "catch", "(", "this", ".", "onPageNotFound", ".", "bind", "(", "this", ",", "request", ",", "response", ")", ")", ";", "}", "return", "Promise", ".", "reject", "(", "error", ")", ".", "catch", "(", "this", ".", "onError", ".", "bind", "(", "this", ",", "request", ",", "response", ")", ")", ";", "var", "instance", "=", "new", "Action", "(", "request", ",", "response", ")", ";", "if", "(", "!", "instance", "[", "callback", ".", "method", "]", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "'Method \"'", "+", "callback", ".", "method", "+", "'\" not found in action \"'", "+", "callback", ".", "action", "+", "'\"'", ")", ")", ";", "}", "var", "promise", "=", "Promise", ".", "resolve", "(", ")", ";", "if", "(", "instance", ".", "init", "&&", "'function'", "==", "typeof", "instance", ".", "init", ")", "{", "promise", "=", "promise", ".", "then", "(", "function", "(", ")", "{", "return", "instance", ".", "init", "(", ")", ";", "}", ")", ";", "}", "promise", "=", "promise", ".", "then", "(", "function", "(", ")", "{", "return", "instance", "[", "callback", ".", "method", "]", ".", "apply", "(", "instance", ",", "callback", ".", "arguments", ")", ";", "}", ")", ";", "if", "(", "instance", ".", "onError", "&&", "'function'", "==", "typeof", "instance", ".", "onError", ")", "{", "promise", "=", "promise", ".", "catch", "(", "function", "(", "error", ")", "{", "return", "instance", ".", "onError", ".", "call", "(", "instance", ",", "error", ")", "}", ")", ";", "}", "}" ]
Call action and method form resolved route @param request @param response @param callback @returns {*}
[ "Call", "action", "and", "method", "form", "resolved", "route" ]
b083b320900ed068007e58af2249825b8da24c79
https://github.com/ltoussaint/node-bootstrap-core/blob/b083b320900ed068007e58af2249825b8da24c79/application.js#L133-L176
train
ltoussaint/node-bootstrap-core
application.js
postDecode
function postDecode(request) { return new Promise(function promisePostDecode(resolve) { var postData = ''; if (request.method === 'POST') { request.on('data', function (chunk) { // append the current chunk of data to the fullBody variable postData += chunk.toString(); }); request.on('end', function () { request.body = qs.parse(postData); resolve(); }); } else { resolve(); } }); }
javascript
function postDecode(request) { return new Promise(function promisePostDecode(resolve) { var postData = ''; if (request.method === 'POST') { request.on('data', function (chunk) { // append the current chunk of data to the fullBody variable postData += chunk.toString(); }); request.on('end', function () { request.body = qs.parse(postData); resolve(); }); } else { resolve(); } }); }
[ "function", "postDecode", "(", "request", ")", "{", "return", "new", "Promise", "(", "function", "promisePostDecode", "(", "resolve", ")", "{", "var", "postData", "=", "''", ";", "if", "(", "request", ".", "method", "===", "'POST'", ")", "{", "request", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "postData", "+=", "chunk", ".", "toString", "(", ")", ";", "}", ")", ";", "request", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "request", ".", "body", "=", "qs", ".", "parse", "(", "postData", ")", ";", "resolve", "(", ")", ";", "}", ")", ";", "}", "else", "{", "resolve", "(", ")", ";", "}", "}", ")", ";", "}" ]
Decode post data and add input into request @param request @returns {Promise}
[ "Decode", "post", "data", "and", "add", "input", "into", "request" ]
b083b320900ed068007e58af2249825b8da24c79
https://github.com/ltoussaint/node-bootstrap-core/blob/b083b320900ed068007e58af2249825b8da24c79/application.js#L183-L201
train
ltoussaint/node-bootstrap-core
application.js
runHooks
function runHooks(request, response, hooks) { var promise = Promise.resolve(); for (var i = 0; i < hooks.length; i++) { promise = promise.then(hooks[i].bind(this, request, response)); } return promise; }
javascript
function runHooks(request, response, hooks) { var promise = Promise.resolve(); for (var i = 0; i < hooks.length; i++) { promise = promise.then(hooks[i].bind(this, request, response)); } return promise; }
[ "function", "runHooks", "(", "request", ",", "response", ",", "hooks", ")", "{", "var", "promise", "=", "Promise", ".", "resolve", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "hooks", ".", "length", ";", "i", "++", ")", "{", "promise", "=", "promise", ".", "then", "(", "hooks", "[", "i", "]", ".", "bind", "(", "this", ",", "request", ",", "response", ")", ")", ";", "}", "return", "promise", ";", "}" ]
Run given hooks @param request @param response @param hooks @returns {Promise}
[ "Run", "given", "hooks" ]
b083b320900ed068007e58af2249825b8da24c79
https://github.com/ltoussaint/node-bootstrap-core/blob/b083b320900ed068007e58af2249825b8da24c79/application.js#L210-L216
train
forfuturellc/node-simple-argparse
index.js
pad
function pad(text, width) { var space = (width - text.length) + 5; return text + Array(space).join(" "); }
javascript
function pad(text, width) { var space = (width - text.length) + 5; return text + Array(space).join(" "); }
[ "function", "pad", "(", "text", ",", "width", ")", "{", "var", "space", "=", "(", "width", "-", "text", ".", "length", ")", "+", "5", ";", "return", "text", "+", "Array", "(", "space", ")", ".", "join", "(", "\" \"", ")", ";", "}" ]
Appends padding space to some text. @param {String} text @param {Number} width - width of column @return {String} padded text
[ "Appends", "padding", "space", "to", "some", "text", "." ]
11f5d49cec5c891fb344c8a6a1e413b535dad331
https://github.com/forfuturellc/node-simple-argparse/blob/11f5d49cec5c891fb344c8a6a1e413b535dad331/index.js#L37-L40
train
hillscottc/nostra
dist/index.js
generate
function generate() { var rnum = Math.floor(Math.random() * 10); var mood = rnum <= 8 ? "good" : "bad"; var sentences = [_sentence_mgr2.default.feeling(mood), _word_library2.default.warning(), nu.chooseFrom([_sentence_mgr2.default.relationship(mood), _sentence_mgr2.default.encounter(mood)])]; // randomize (shuffle) the array sentences = nu.shuffle(sentences); // Select 2 or 3 sentences, to add to the random feel var num_s = Math.floor(Math.random() * 2) + 2; sentences = sentences.slice(0, num_s); sentences = sentences.join(" "); sentences += " " + _sentence_mgr2.default.datePredict(); debug(sentences); return sentences; }
javascript
function generate() { var rnum = Math.floor(Math.random() * 10); var mood = rnum <= 8 ? "good" : "bad"; var sentences = [_sentence_mgr2.default.feeling(mood), _word_library2.default.warning(), nu.chooseFrom([_sentence_mgr2.default.relationship(mood), _sentence_mgr2.default.encounter(mood)])]; // randomize (shuffle) the array sentences = nu.shuffle(sentences); // Select 2 or 3 sentences, to add to the random feel var num_s = Math.floor(Math.random() * 2) + 2; sentences = sentences.slice(0, num_s); sentences = sentences.join(" "); sentences += " " + _sentence_mgr2.default.datePredict(); debug(sentences); return sentences; }
[ "function", "generate", "(", ")", "{", "var", "rnum", "=", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "10", ")", ";", "var", "mood", "=", "rnum", "<=", "8", "?", "\"good\"", ":", "\"bad\"", ";", "var", "sentences", "=", "[", "_sentence_mgr2", ".", "default", ".", "feeling", "(", "mood", ")", ",", "_word_library2", ".", "default", ".", "warning", "(", ")", ",", "nu", ".", "chooseFrom", "(", "[", "_sentence_mgr2", ".", "default", ".", "relationship", "(", "mood", ")", ",", "_sentence_mgr2", ".", "default", ".", "encounter", "(", "mood", ")", "]", ")", "]", ";", "sentences", "=", "nu", ".", "shuffle", "(", "sentences", ")", ";", "var", "num_s", "=", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "2", ")", "+", "2", ";", "sentences", "=", "sentences", ".", "slice", "(", "0", ",", "num_s", ")", ";", "sentences", "=", "sentences", ".", "join", "(", "\" \"", ")", ";", "sentences", "+=", "\" \"", "+", "_sentence_mgr2", ".", "default", ".", "datePredict", "(", ")", ";", "debug", "(", "sentences", ")", ";", "return", "sentences", ";", "}" ]
Generate a three to four sentence horoscope. @returns {*[]}
[ "Generate", "a", "three", "to", "four", "sentence", "horoscope", "." ]
1801c8e19f7fab91dd29fea07195789d41624915
https://github.com/hillscottc/nostra/blob/1801c8e19f7fab91dd29fea07195789d41624915/dist/index.js#L28-L47
train
raincatcher-beta/raincatcher-file-angular
lib/file-list/file-list-controller.js
FileListController
function FileListController($scope, mediator, $stateParams, $window, userClient, fileMediatorService, $timeout, mobileCamera, desktopCamera, FILE_CONFIG) { var self = this; self.files = null; var _files; self.uploadEnabled = FILE_CONFIG.uploadEnabled; userClient.getProfile().then(function(profileData){ var userFilter; if(FILE_CONFIG.userMode){ userFilter = profileData.id; } function refreshFiles(){ fileMediatorService.listFiles(userFilter).then(function(files){ $timeout(function(){ _files = files; self.files = files; }); }); } refreshFiles(); fileMediatorService.subscribeToFileCRUDDoneTopics($scope, refreshFiles); self.selectFile = function(event, file){ self.selectedFileId = file.id; mediator.publish(fileMediatorService.fileUITopics.getTopic(CONSTANTS.TOPICS.SELECTED), file); }; //TODO: Move to service self.applyFilter = function(term){ term = term.toLowerCase(); self.files = _files.filter(function(file){ return String(file.name).toLowerCase().indexOf(term) !== -1 || String(file.id).indexOf(term) !== -1; }); }; $scope.$parent.selected = {id: null}; var captureThenUpload = function(){ if($window.cordova){ return mobileCamera.capture() .then(function(capture){ var fileData = { userId: profileData.id, fileURI: capture.fileURI, options: {fileName: capture.fileName} }; fileMediatorService.createFile(fileData); }); }else{ return desktopCamera.capture() .then(function(dataUrl){ return fileMediatorService.createFile({userId: profileData.id, dataUrl: dataUrl}); }); } }; self.capturePhoto = function(){ captureThenUpload().then(function(){ }, function(error){ console.error(error); }); }; }); }
javascript
function FileListController($scope, mediator, $stateParams, $window, userClient, fileMediatorService, $timeout, mobileCamera, desktopCamera, FILE_CONFIG) { var self = this; self.files = null; var _files; self.uploadEnabled = FILE_CONFIG.uploadEnabled; userClient.getProfile().then(function(profileData){ var userFilter; if(FILE_CONFIG.userMode){ userFilter = profileData.id; } function refreshFiles(){ fileMediatorService.listFiles(userFilter).then(function(files){ $timeout(function(){ _files = files; self.files = files; }); }); } refreshFiles(); fileMediatorService.subscribeToFileCRUDDoneTopics($scope, refreshFiles); self.selectFile = function(event, file){ self.selectedFileId = file.id; mediator.publish(fileMediatorService.fileUITopics.getTopic(CONSTANTS.TOPICS.SELECTED), file); }; //TODO: Move to service self.applyFilter = function(term){ term = term.toLowerCase(); self.files = _files.filter(function(file){ return String(file.name).toLowerCase().indexOf(term) !== -1 || String(file.id).indexOf(term) !== -1; }); }; $scope.$parent.selected = {id: null}; var captureThenUpload = function(){ if($window.cordova){ return mobileCamera.capture() .then(function(capture){ var fileData = { userId: profileData.id, fileURI: capture.fileURI, options: {fileName: capture.fileName} }; fileMediatorService.createFile(fileData); }); }else{ return desktopCamera.capture() .then(function(dataUrl){ return fileMediatorService.createFile({userId: profileData.id, dataUrl: dataUrl}); }); } }; self.capturePhoto = function(){ captureThenUpload().then(function(){ }, function(error){ console.error(error); }); }; }); }
[ "function", "FileListController", "(", "$scope", ",", "mediator", ",", "$stateParams", ",", "$window", ",", "userClient", ",", "fileMediatorService", ",", "$timeout", ",", "mobileCamera", ",", "desktopCamera", ",", "FILE_CONFIG", ")", "{", "var", "self", "=", "this", ";", "self", ".", "files", "=", "null", ";", "var", "_files", ";", "self", ".", "uploadEnabled", "=", "FILE_CONFIG", ".", "uploadEnabled", ";", "userClient", ".", "getProfile", "(", ")", ".", "then", "(", "function", "(", "profileData", ")", "{", "var", "userFilter", ";", "if", "(", "FILE_CONFIG", ".", "userMode", ")", "{", "userFilter", "=", "profileData", ".", "id", ";", "}", "function", "refreshFiles", "(", ")", "{", "fileMediatorService", ".", "listFiles", "(", "userFilter", ")", ".", "then", "(", "function", "(", "files", ")", "{", "$timeout", "(", "function", "(", ")", "{", "_files", "=", "files", ";", "self", ".", "files", "=", "files", ";", "}", ")", ";", "}", ")", ";", "}", "refreshFiles", "(", ")", ";", "fileMediatorService", ".", "subscribeToFileCRUDDoneTopics", "(", "$scope", ",", "refreshFiles", ")", ";", "self", ".", "selectFile", "=", "function", "(", "event", ",", "file", ")", "{", "self", ".", "selectedFileId", "=", "file", ".", "id", ";", "mediator", ".", "publish", "(", "fileMediatorService", ".", "fileUITopics", ".", "getTopic", "(", "CONSTANTS", ".", "TOPICS", ".", "SELECTED", ")", ",", "file", ")", ";", "}", ";", "self", ".", "applyFilter", "=", "function", "(", "term", ")", "{", "term", "=", "term", ".", "toLowerCase", "(", ")", ";", "self", ".", "files", "=", "_files", ".", "filter", "(", "function", "(", "file", ")", "{", "return", "String", "(", "file", ".", "name", ")", ".", "toLowerCase", "(", ")", ".", "indexOf", "(", "term", ")", "!==", "-", "1", "||", "String", "(", "file", ".", "id", ")", ".", "indexOf", "(", "term", ")", "!==", "-", "1", ";", "}", ")", ";", "}", ";", "$scope", ".", "$parent", ".", "selected", "=", "{", "id", ":", "null", "}", ";", "var", "captureThenUpload", "=", "function", "(", ")", "{", "if", "(", "$window", ".", "cordova", ")", "{", "return", "mobileCamera", ".", "capture", "(", ")", ".", "then", "(", "function", "(", "capture", ")", "{", "var", "fileData", "=", "{", "userId", ":", "profileData", ".", "id", ",", "fileURI", ":", "capture", ".", "fileURI", ",", "options", ":", "{", "fileName", ":", "capture", ".", "fileName", "}", "}", ";", "fileMediatorService", ".", "createFile", "(", "fileData", ")", ";", "}", ")", ";", "}", "else", "{", "return", "desktopCamera", ".", "capture", "(", ")", ".", "then", "(", "function", "(", "dataUrl", ")", "{", "return", "fileMediatorService", ".", "createFile", "(", "{", "userId", ":", "profileData", ".", "id", ",", "dataUrl", ":", "dataUrl", "}", ")", ";", "}", ")", ";", "}", "}", ";", "self", ".", "capturePhoto", "=", "function", "(", ")", "{", "captureThenUpload", "(", ")", ".", "then", "(", "function", "(", ")", "{", "}", ",", "function", "(", "error", ")", "{", "console", ".", "error", "(", "error", ")", ";", "}", ")", ";", "}", ";", "}", ")", ";", "}" ]
Controller for listing Files
[ "Controller", "for", "listing", "Files" ]
a76d406ca62d6c29da3caf94cc9db75f343ec797
https://github.com/raincatcher-beta/raincatcher-file-angular/blob/a76d406ca62d6c29da3caf94cc9db75f343ec797/lib/file-list/file-list-controller.js#L8-L72
train
JimmyRobz/grunt-mokuai-coffee
tasks/mokuai-coffee.js
optionResult
function optionResult(options, option){ var result = options[option]; // If the returned value is a function, call it with the dest option parameter if(_.isFunction(result)){ result = result(options.dest); } return result; }
javascript
function optionResult(options, option){ var result = options[option]; // If the returned value is a function, call it with the dest option parameter if(_.isFunction(result)){ result = result(options.dest); } return result; }
[ "function", "optionResult", "(", "options", ",", "option", ")", "{", "var", "result", "=", "options", "[", "option", "]", ";", "if", "(", "_", ".", "isFunction", "(", "result", ")", ")", "{", "result", "=", "result", "(", "options", ".", "dest", ")", ";", "}", "return", "result", ";", "}" ]
Get option result from options
[ "Get", "option", "result", "from", "options" ]
163a4cdea0a5451832444dfd1570e9b5daf3d2f8
https://github.com/JimmyRobz/grunt-mokuai-coffee/blob/163a4cdea0a5451832444dfd1570e9b5daf3d2f8/tasks/mokuai-coffee.js#L19-L26
train
reklatsmasters/win-ps
index.js
build_shell
function build_shell(fields) { var $fields = Array.isArray(fields) ? normalizeFields(fields) : ['ProcessId','Name','Path','ParentProcessId','Priority']; var args = command.shell_arg.split(' '); args.push(`${command.ps} | ${command.select} ${ $fields.join(',') } | ${command.convert}`); return shell(command.shell, args); }
javascript
function build_shell(fields) { var $fields = Array.isArray(fields) ? normalizeFields(fields) : ['ProcessId','Name','Path','ParentProcessId','Priority']; var args = command.shell_arg.split(' '); args.push(`${command.ps} | ${command.select} ${ $fields.join(',') } | ${command.convert}`); return shell(command.shell, args); }
[ "function", "build_shell", "(", "fields", ")", "{", "var", "$fields", "=", "Array", ".", "isArray", "(", "fields", ")", "?", "normalizeFields", "(", "fields", ")", ":", "[", "'ProcessId'", ",", "'Name'", ",", "'Path'", ",", "'ParentProcessId'", ",", "'Priority'", "]", ";", "var", "args", "=", "command", ".", "shell_arg", ".", "split", "(", "' '", ")", ";", "args", ".", "push", "(", "`", "${", "command", ".", "ps", "}", "${", "command", ".", "select", "}", "${", "$fields", ".", "join", "(", "','", ")", "}", "${", "command", ".", "convert", "}", "`", ")", ";", "return", "shell", "(", "command", ".", "shell", ",", "args", ")", ";", "}" ]
Build shell command @param {Array} fields @return {Object} child_process instance
[ "Build", "shell", "command" ]
ea5f7e5978b3a8620556a0d898000429e5baeb4f
https://github.com/reklatsmasters/win-ps/blob/ea5f7e5978b3a8620556a0d898000429e5baeb4f/index.js#L45-L52
train
MCluck90/clairvoyant
src/main.js
function(options) { options = extend({ src: '', output: '', is3d: false, failOnWarn: false, overwrite: false, reporter: 'default' }, options); if (!options.src || !options.output) { throw new Error('Must specify source file and output directory'); } var reporterConstructor; if (options.reporter === 'default') { reporterConstructor = require('./reporter.js').Reporter; } else { reporterConstructor = require('./reporters/' + options.reporter + '.js'); } if (reporterConstructor === undefined) { throw new Error('Invalid reporter given'); } this.reporter = new reporterConstructor(options.failOnWarn); this.sourceCode = fs.readFileSync(options.src, 'utf-8'); this.psykickVersion = (options.is3d) ? '3d' : '2d'; this.sourcePath = options.src; this.outputPath = options.output; this.overwrite = options.overwrite; this.ast = null; this.compiler = null; this.writer = null; }
javascript
function(options) { options = extend({ src: '', output: '', is3d: false, failOnWarn: false, overwrite: false, reporter: 'default' }, options); if (!options.src || !options.output) { throw new Error('Must specify source file and output directory'); } var reporterConstructor; if (options.reporter === 'default') { reporterConstructor = require('./reporter.js').Reporter; } else { reporterConstructor = require('./reporters/' + options.reporter + '.js'); } if (reporterConstructor === undefined) { throw new Error('Invalid reporter given'); } this.reporter = new reporterConstructor(options.failOnWarn); this.sourceCode = fs.readFileSync(options.src, 'utf-8'); this.psykickVersion = (options.is3d) ? '3d' : '2d'; this.sourcePath = options.src; this.outputPath = options.output; this.overwrite = options.overwrite; this.ast = null; this.compiler = null; this.writer = null; }
[ "function", "(", "options", ")", "{", "options", "=", "extend", "(", "{", "src", ":", "''", ",", "output", ":", "''", ",", "is3d", ":", "false", ",", "failOnWarn", ":", "false", ",", "overwrite", ":", "false", ",", "reporter", ":", "'default'", "}", ",", "options", ")", ";", "if", "(", "!", "options", ".", "src", "||", "!", "options", ".", "output", ")", "{", "throw", "new", "Error", "(", "'Must specify source file and output directory'", ")", ";", "}", "var", "reporterConstructor", ";", "if", "(", "options", ".", "reporter", "===", "'default'", ")", "{", "reporterConstructor", "=", "require", "(", "'./reporter.js'", ")", ".", "Reporter", ";", "}", "else", "{", "reporterConstructor", "=", "require", "(", "'./reporters/'", "+", "options", ".", "reporter", "+", "'.js'", ")", ";", "}", "if", "(", "reporterConstructor", "===", "undefined", ")", "{", "throw", "new", "Error", "(", "'Invalid reporter given'", ")", ";", "}", "this", ".", "reporter", "=", "new", "reporterConstructor", "(", "options", ".", "failOnWarn", ")", ";", "this", ".", "sourceCode", "=", "fs", ".", "readFileSync", "(", "options", ".", "src", ",", "'utf-8'", ")", ";", "this", ".", "psykickVersion", "=", "(", "options", ".", "is3d", ")", "?", "'3d'", ":", "'2d'", ";", "this", ".", "sourcePath", "=", "options", ".", "src", ";", "this", ".", "outputPath", "=", "options", ".", "output", ";", "this", ".", "overwrite", "=", "options", ".", "overwrite", ";", "this", ".", "ast", "=", "null", ";", "this", ".", "compiler", "=", "null", ";", "this", ".", "writer", "=", "null", ";", "}" ]
Exposes Clairvoyant as a module to use programatically @param {object} options @param {string} options.src - Source file @param {string} options.output - Path to the file to place the project in @param {boolean} [options.is3d=false] - If true, will compile for Psykick3D @param {boolean} [options.failOnWarn=false] - If true, will fail when a warning is issued @param {boolean} [options.overwrite=false] - If true, will overwrite existing files @param {string} [options.reporter='default'] - Specify which reporter to load @constructor
[ "Exposes", "Clairvoyant", "as", "a", "module", "to", "use", "programatically" ]
4c347499c5fe0f561a53e180d141884b1fa8c21b
https://github.com/MCluck90/clairvoyant/blob/4c347499c5fe0f561a53e180d141884b1fa8c21b/src/main.js#L24-L58
train
relief-melone/limitpromises
src/services/service.handleRejects.js
handleRejects
function handleRejects(PromiseFunc, Obj, Err, Options){ var rejectOpts = Options.Reject || rejectConfig; switch(rejectOpts.rejectBehaviour){ case "reject": // Every time a promise finishes start the first one from the currentPromiseArrays[typeKey]Array that hasnt been started yet; if(Obj.isRunning) return Obj.rejectResult(Err); break; case "resolve": if(Obj.isRunning) return Obj.resolveResult(rejectOpts.returnOnReject); break; case "retry": if(Obj.isRunning) return retryPromiseRejected(PromiseFunc, Obj, Options, Err); break; case "none": break; } }
javascript
function handleRejects(PromiseFunc, Obj, Err, Options){ var rejectOpts = Options.Reject || rejectConfig; switch(rejectOpts.rejectBehaviour){ case "reject": // Every time a promise finishes start the first one from the currentPromiseArrays[typeKey]Array that hasnt been started yet; if(Obj.isRunning) return Obj.rejectResult(Err); break; case "resolve": if(Obj.isRunning) return Obj.resolveResult(rejectOpts.returnOnReject); break; case "retry": if(Obj.isRunning) return retryPromiseRejected(PromiseFunc, Obj, Options, Err); break; case "none": break; } }
[ "function", "handleRejects", "(", "PromiseFunc", ",", "Obj", ",", "Err", ",", "Options", ")", "{", "var", "rejectOpts", "=", "Options", ".", "Reject", "||", "rejectConfig", ";", "switch", "(", "rejectOpts", ".", "rejectBehaviour", ")", "{", "case", "\"reject\"", ":", "if", "(", "Obj", ".", "isRunning", ")", "return", "Obj", ".", "rejectResult", "(", "Err", ")", ";", "break", ";", "case", "\"resolve\"", ":", "if", "(", "Obj", ".", "isRunning", ")", "return", "Obj", ".", "resolveResult", "(", "rejectOpts", ".", "returnOnReject", ")", ";", "break", ";", "case", "\"retry\"", ":", "if", "(", "Obj", ".", "isRunning", ")", "return", "retryPromiseRejected", "(", "PromiseFunc", ",", "Obj", ",", "Options", ",", "Err", ")", ";", "break", ";", "case", "\"none\"", ":", "break", ";", "}", "}" ]
Handle rejects will determine how a promise is beeing handled after it the PromiseFunc has been rejected @param {Function} PromiseFunc Function that returns a Promise with one InputParameter that is used @param {Object} Obj Current Object to be treated @param {Error} Err The error returned by the PromiseFunction @param {Object} Options Options that contain information about how the Reject is handelt under Object.Reject @returns {void}
[ "Handle", "rejects", "will", "determine", "how", "a", "promise", "is", "beeing", "handled", "after", "it", "the", "PromiseFunc", "has", "been", "rejected" ]
1735b92749740204b597c1c6026257d54ade8200
https://github.com/relief-melone/limitpromises/blob/1735b92749740204b597c1c6026257d54ade8200/src/services/service.handleRejects.js#L13-L29
train
imlucas/node-stor
adapters/backbone.js
getHandler
function getHandler(method){ var taxonomy = { create: store.set, read: store.get, update: store.set, 'delete': store.remove, patch: store.set, findAll: store.all, findById: store.get }; return store[method] || taxonomy[method]; }
javascript
function getHandler(method){ var taxonomy = { create: store.set, read: store.get, update: store.set, 'delete': store.remove, patch: store.set, findAll: store.all, findById: store.get }; return store[method] || taxonomy[method]; }
[ "function", "getHandler", "(", "method", ")", "{", "var", "taxonomy", "=", "{", "create", ":", "store", ".", "set", ",", "read", ":", "store", ".", "get", ",", "update", ":", "store", ".", "set", ",", "'delete'", ":", "store", ".", "remove", ",", "patch", ":", "store", ".", "set", ",", "findAll", ":", "store", ".", "all", ",", "findById", ":", "store", ".", "get", "}", ";", "return", "store", "[", "method", "]", "||", "taxonomy", "[", "method", "]", ";", "}" ]
normalize the api taxonomy with a convenience that returns the correct function for a store.
[ "normalize", "the", "api", "taxonomy", "with", "a", "convenience", "that", "returns", "the", "correct", "function", "for", "a", "store", "." ]
6b74af52bf160873658bc3570db716d44c33f335
https://github.com/imlucas/node-stor/blob/6b74af52bf160873658bc3570db716d44c33f335/adapters/backbone.js#L5-L16
train
weisjohn/tessel-apple-remote
index.js
valid_leader
function valid_leader(durations) { var on = durations[0]; var off = durations[1]; return (8900 < on && on < 9200) && (-4600 < off && off < -4350); }
javascript
function valid_leader(durations) { var on = durations[0]; var off = durations[1]; return (8900 < on && on < 9200) && (-4600 < off && off < -4350); }
[ "function", "valid_leader", "(", "durations", ")", "{", "var", "on", "=", "durations", "[", "0", "]", ";", "var", "off", "=", "durations", "[", "1", "]", ";", "return", "(", "8900", "<", "on", "&&", "on", "<", "9200", ")", "&&", "(", "-", "4600", "<", "off", "&&", "off", "<", "-", "4350", ")", ";", "}" ]
validate the leader bit
[ "validate", "the", "leader", "bit" ]
0b29abe595f53059eebd021c70b13c9d8720ac8d
https://github.com/weisjohn/tessel-apple-remote/blob/0b29abe595f53059eebd021c70b13c9d8720ac8d/index.js#L35-L39
train
weisjohn/tessel-apple-remote
index.js
command_id_from_buffer
function command_id_from_buffer(data) { var durations = command_durations_from_hex_buffer(data); if (!valid_leader(durations)) return; var binary = binary_from_durations(durations); if (!valid_binary(binary)) return; var bytes = bytes_from_binary(binary); if (!valid_bytes(bytes)) return; if (!valid_codes(bytes)) return; return command_id_from_bytes(bytes); }
javascript
function command_id_from_buffer(data) { var durations = command_durations_from_hex_buffer(data); if (!valid_leader(durations)) return; var binary = binary_from_durations(durations); if (!valid_binary(binary)) return; var bytes = bytes_from_binary(binary); if (!valid_bytes(bytes)) return; if (!valid_codes(bytes)) return; return command_id_from_bytes(bytes); }
[ "function", "command_id_from_buffer", "(", "data", ")", "{", "var", "durations", "=", "command_durations_from_hex_buffer", "(", "data", ")", ";", "if", "(", "!", "valid_leader", "(", "durations", ")", ")", "return", ";", "var", "binary", "=", "binary_from_durations", "(", "durations", ")", ";", "if", "(", "!", "valid_binary", "(", "binary", ")", ")", "return", ";", "var", "bytes", "=", "bytes_from_binary", "(", "binary", ")", ";", "if", "(", "!", "valid_bytes", "(", "bytes", ")", ")", "return", ";", "if", "(", "!", "valid_codes", "(", "bytes", ")", ")", "return", ";", "return", "command_id_from_bytes", "(", "bytes", ")", ";", "}" ]
a small implementation of the whole flow
[ "a", "small", "implementation", "of", "the", "whole", "flow" ]
0b29abe595f53059eebd021c70b13c9d8720ac8d
https://github.com/weisjohn/tessel-apple-remote/blob/0b29abe595f53059eebd021c70b13c9d8720ac8d/index.js#L111-L125
train
weisjohn/tessel-apple-remote
index.js
continue_from_buffer
function continue_from_buffer(data) { var durations = continue_durations_from_hex_buffer(data); var on = durations[0]; var off = durations[1]; var stop = durations[2]; return (8900 < on && on < 9200) && (-2350 < off && off < -2100) && (500 < stop && stop < 650); }
javascript
function continue_from_buffer(data) { var durations = continue_durations_from_hex_buffer(data); var on = durations[0]; var off = durations[1]; var stop = durations[2]; return (8900 < on && on < 9200) && (-2350 < off && off < -2100) && (500 < stop && stop < 650); }
[ "function", "continue_from_buffer", "(", "data", ")", "{", "var", "durations", "=", "continue_durations_from_hex_buffer", "(", "data", ")", ";", "var", "on", "=", "durations", "[", "0", "]", ";", "var", "off", "=", "durations", "[", "1", "]", ";", "var", "stop", "=", "durations", "[", "2", "]", ";", "return", "(", "8900", "<", "on", "&&", "on", "<", "9200", ")", "&&", "(", "-", "2350", "<", "off", "&&", "off", "<", "-", "2100", ")", "&&", "(", "500", "<", "stop", "&&", "stop", "<", "650", ")", ";", "}" ]
determine whether or not the buffer is a valid continuation code
[ "determine", "whether", "or", "not", "the", "buffer", "is", "a", "valid", "continuation", "code" ]
0b29abe595f53059eebd021c70b13c9d8720ac8d
https://github.com/weisjohn/tessel-apple-remote/blob/0b29abe595f53059eebd021c70b13c9d8720ac8d/index.js#L129-L140
train
Swaagie/npm-probe
probes/delta.js
versions
function versions(a, b) { if (!a || !b) return false; a = Array.isArray(a) ? a : Object.keys(a); b = Array.isArray(a) ? a : Object.keys(a); return a.length === b.length && a.reduce(function has(memo, item) { return memo && ~b.indexOf(item); }, true); }
javascript
function versions(a, b) { if (!a || !b) return false; a = Array.isArray(a) ? a : Object.keys(a); b = Array.isArray(a) ? a : Object.keys(a); return a.length === b.length && a.reduce(function has(memo, item) { return memo && ~b.indexOf(item); }, true); }
[ "function", "versions", "(", "a", ",", "b", ")", "{", "if", "(", "!", "a", "||", "!", "b", ")", "return", "false", ";", "a", "=", "Array", ".", "isArray", "(", "a", ")", "?", "a", ":", "Object", ".", "keys", "(", "a", ")", ";", "b", "=", "Array", ".", "isArray", "(", "a", ")", "?", "a", ":", "Object", ".", "keys", "(", "a", ")", ";", "return", "a", ".", "length", "===", "b", ".", "length", "&&", "a", ".", "reduce", "(", "function", "has", "(", "memo", ",", "item", ")", "{", "return", "memo", "&&", "~", "b", ".", "indexOf", "(", "item", ")", ";", "}", ",", "true", ")", ";", "}" ]
Unpublished modules will have no versions, modified time should be equal.
[ "Unpublished", "modules", "will", "have", "no", "versions", "modified", "time", "should", "be", "equal", "." ]
e9b717934ff3e3eb4f7c7a15f39728c380f1925e
https://github.com/Swaagie/npm-probe/blob/e9b717934ff3e3eb4f7c7a15f39728c380f1925e/probes/delta.js#L48-L57
train
oori/gulp-jsonschema-deref
index.js
dereference
function dereference(file, opts, cb) { parser.dereference(file.path, opts, (err, schema) => { if (err) { this.emit('error', new gutil.PluginError('gulp-jsonschema-deref', err, {fileName: file.path})); } else { file.contents = Buffer.from(JSON.stringify(schema)); this.push(file); } cb(); }); }
javascript
function dereference(file, opts, cb) { parser.dereference(file.path, opts, (err, schema) => { if (err) { this.emit('error', new gutil.PluginError('gulp-jsonschema-deref', err, {fileName: file.path})); } else { file.contents = Buffer.from(JSON.stringify(schema)); this.push(file); } cb(); }); }
[ "function", "dereference", "(", "file", ",", "opts", ",", "cb", ")", "{", "parser", ".", "dereference", "(", "file", ".", "path", ",", "opts", ",", "(", "err", ",", "schema", ")", "=>", "{", "if", "(", "err", ")", "{", "this", ".", "emit", "(", "'error'", ",", "new", "gutil", ".", "PluginError", "(", "'gulp-jsonschema-deref'", ",", "err", ",", "{", "fileName", ":", "file", ".", "path", "}", ")", ")", ";", "}", "else", "{", "file", ".", "contents", "=", "Buffer", ".", "from", "(", "JSON", ".", "stringify", "(", "schema", ")", ")", ";", "this", ".", "push", "(", "file", ")", ";", "}", "cb", "(", ")", ";", "}", ")", ";", "}" ]
Dereference a jsonschema
[ "Dereference", "a", "jsonschema" ]
51b6a8af2039fe3bac9af0d10b61320fc57ae122
https://github.com/oori/gulp-jsonschema-deref/blob/51b6a8af2039fe3bac9af0d10b61320fc57ae122/index.js#L9-L19
train
rumkin/keyget
index.js
breadcrumbs
function breadcrumbs(target, path) { path = pathToArray(path); const result = [target]; let part; let value = target; if (! isObject(value)) { return result; } for (let i = 0, l = path.length; i < l; i++) { part = path[i]; if (! value.hasOwnProperty(part)) { break; } result.push(value[part]); value = value[part]; } return result; }
javascript
function breadcrumbs(target, path) { path = pathToArray(path); const result = [target]; let part; let value = target; if (! isObject(value)) { return result; } for (let i = 0, l = path.length; i < l; i++) { part = path[i]; if (! value.hasOwnProperty(part)) { break; } result.push(value[part]); value = value[part]; } return result; }
[ "function", "breadcrumbs", "(", "target", ",", "path", ")", "{", "path", "=", "pathToArray", "(", "path", ")", ";", "const", "result", "=", "[", "target", "]", ";", "let", "part", ";", "let", "value", "=", "target", ";", "if", "(", "!", "isObject", "(", "value", ")", ")", "{", "return", "result", ";", "}", "for", "(", "let", "i", "=", "0", ",", "l", "=", "path", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "part", "=", "path", "[", "i", "]", ";", "if", "(", "!", "value", ".", "hasOwnProperty", "(", "part", ")", ")", "{", "break", ";", "}", "result", ".", "push", "(", "value", "[", "part", "]", ")", ";", "value", "=", "value", "[", "part", "]", ";", "}", "return", "result", ";", "}" ]
breadcrumbs - Extract nested value by path and return as array. If target is not an object or path is empty returns empty array. @param {*} target Value. @param {Path} path Path to value. @return {*[]} Values for path components. @example breadcrumbs({a: b: {1}}, ['a', 'b']); // -> [{b:1}, 1];
[ "breadcrumbs", "-", "Extract", "nested", "value", "by", "path", "and", "return", "as", "array", ".", "If", "target", "is", "not", "an", "object", "or", "path", "is", "empty", "returns", "empty", "array", "." ]
3198d6cfb22d10f98552b7cee0be6b1dab79b5fd
https://github.com/rumkin/keyget/blob/3198d6cfb22d10f98552b7cee0be6b1dab79b5fd/index.js#L39-L63
train
rumkin/keyget
index.js
hasPath
function hasPath(target, path) { path = pathToArray(path); const result = breadcrumbs(target, path); return result.length === path.length + 1; }
javascript
function hasPath(target, path) { path = pathToArray(path); const result = breadcrumbs(target, path); return result.length === path.length + 1; }
[ "function", "hasPath", "(", "target", ",", "path", ")", "{", "path", "=", "pathToArray", "(", "path", ")", ";", "const", "result", "=", "breadcrumbs", "(", "target", ",", "path", ")", ";", "return", "result", ".", "length", "===", "path", ".", "length", "+", "1", ";", "}" ]
hasPath - Set deeply nested value into target object. If nested properties are not an objects or not exists creates them. @param {Object} target Parent object. @param {Path} path Array of path segments. @return {Boolean} Returns true if object contains `path`.
[ "hasPath", "-", "Set", "deeply", "nested", "value", "into", "target", "object", ".", "If", "nested", "properties", "are", "not", "an", "objects", "or", "not", "exists", "creates", "them", "." ]
3198d6cfb22d10f98552b7cee0be6b1dab79b5fd
https://github.com/rumkin/keyget/blob/3198d6cfb22d10f98552b7cee0be6b1dab79b5fd/index.js#L73-L79
train
rumkin/keyget
index.js
setByPath
function setByPath(target, path, value) { path = pathToArray(path); if (! path.length) { return value; } const key = path[0]; if (isNumber(key)) { if (! Array.isArray(target)) { target = []; } } else if (! isObject(target)) { target = {}; } if (path.length > 1) { target[key] = setByPath(target[key], path.slice(1), value); } else { target[key] = value; } return target; }
javascript
function setByPath(target, path, value) { path = pathToArray(path); if (! path.length) { return value; } const key = path[0]; if (isNumber(key)) { if (! Array.isArray(target)) { target = []; } } else if (! isObject(target)) { target = {}; } if (path.length > 1) { target[key] = setByPath(target[key], path.slice(1), value); } else { target[key] = value; } return target; }
[ "function", "setByPath", "(", "target", ",", "path", ",", "value", ")", "{", "path", "=", "pathToArray", "(", "path", ")", ";", "if", "(", "!", "path", ".", "length", ")", "{", "return", "value", ";", "}", "const", "key", "=", "path", "[", "0", "]", ";", "if", "(", "isNumber", "(", "key", ")", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "target", ")", ")", "{", "target", "=", "[", "]", ";", "}", "}", "else", "if", "(", "!", "isObject", "(", "target", ")", ")", "{", "target", "=", "{", "}", ";", "}", "if", "(", "path", ".", "length", ">", "1", ")", "{", "target", "[", "key", "]", "=", "setByPath", "(", "target", "[", "key", "]", ",", "path", ".", "slice", "(", "1", ")", ",", "value", ")", ";", "}", "else", "{", "target", "[", "key", "]", "=", "value", ";", "}", "return", "target", ";", "}" ]
setByPath - Set deeply nested value into target object. If nested properties are not an objects or not exists creates them. @param {Object} target Parent object. @param {Path} path Array of path segments. @param {*} value Value to set. @return {void}
[ "setByPath", "-", "Set", "deeply", "nested", "value", "into", "target", "object", ".", "If", "nested", "properties", "are", "not", "an", "objects", "or", "not", "exists", "creates", "them", "." ]
3198d6cfb22d10f98552b7cee0be6b1dab79b5fd
https://github.com/rumkin/keyget/blob/3198d6cfb22d10f98552b7cee0be6b1dab79b5fd/index.js#L90-L115
train
rumkin/keyget
index.js
pushByPath
function pushByPath(target, path, value) { path = pathToArray(path); if (! path.length) { if (! Array.isArray(target)) { return [value]; } else { target.push(value); return target; } } if (! isObject(target)) { target = {}; } return at(target, path, function(finalTarget, key) { if (Array.isArray(finalTarget[key])) { finalTarget[key].push(value); } else { finalTarget[key] = [value]; } return finalTarget; }); }
javascript
function pushByPath(target, path, value) { path = pathToArray(path); if (! path.length) { if (! Array.isArray(target)) { return [value]; } else { target.push(value); return target; } } if (! isObject(target)) { target = {}; } return at(target, path, function(finalTarget, key) { if (Array.isArray(finalTarget[key])) { finalTarget[key].push(value); } else { finalTarget[key] = [value]; } return finalTarget; }); }
[ "function", "pushByPath", "(", "target", ",", "path", ",", "value", ")", "{", "path", "=", "pathToArray", "(", "path", ")", ";", "if", "(", "!", "path", ".", "length", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "target", ")", ")", "{", "return", "[", "value", "]", ";", "}", "else", "{", "target", ".", "push", "(", "value", ")", ";", "return", "target", ";", "}", "}", "if", "(", "!", "isObject", "(", "target", ")", ")", "{", "target", "=", "{", "}", ";", "}", "return", "at", "(", "target", ",", "path", ",", "function", "(", "finalTarget", ",", "key", ")", "{", "if", "(", "Array", ".", "isArray", "(", "finalTarget", "[", "key", "]", ")", ")", "{", "finalTarget", "[", "key", "]", ".", "push", "(", "value", ")", ";", "}", "else", "{", "finalTarget", "[", "key", "]", "=", "[", "value", "]", ";", "}", "return", "finalTarget", ";", "}", ")", ";", "}" ]
Push deeply nested value into target object. If nested properties are not an objects or not exists creates them. @param {*} target Parent object. @param {Path} path Array of path segments. @param {*} value Value to set. @return {Object|Array} Returns updated `target`.
[ "Push", "deeply", "nested", "value", "into", "target", "object", ".", "If", "nested", "properties", "are", "not", "an", "objects", "or", "not", "exists", "creates", "them", "." ]
3198d6cfb22d10f98552b7cee0be6b1dab79b5fd
https://github.com/rumkin/keyget/blob/3198d6cfb22d10f98552b7cee0be6b1dab79b5fd/index.js#L126-L153
train
rumkin/keyget
index.js
getByPath
function getByPath(target, path) { path = pathToArray(path); const values = breadcrumbs(target, path); return values[values.length - 1]; }
javascript
function getByPath(target, path) { path = pathToArray(path); const values = breadcrumbs(target, path); return values[values.length - 1]; }
[ "function", "getByPath", "(", "target", ",", "path", ")", "{", "path", "=", "pathToArray", "(", "path", ")", ";", "const", "values", "=", "breadcrumbs", "(", "target", ",", "path", ")", ";", "return", "values", "[", "values", ".", "length", "-", "1", "]", ";", "}" ]
getByPath - Get value from `target` by `path`. @param {*} target Nested object or anything else. @param {Path} path Path to nested property. @return {*} Returns value or undefined.
[ "getByPath", "-", "Get", "value", "from", "target", "by", "path", "." ]
3198d6cfb22d10f98552b7cee0be6b1dab79b5fd
https://github.com/rumkin/keyget/blob/3198d6cfb22d10f98552b7cee0be6b1dab79b5fd/index.js#L204-L210
train
rumkin/keyget
index.js
methodByPath
function methodByPath(target, path) { path = pathToArray(path); const values = breadcrumbs(target, path); if (values.length < path.length) { return noop; } if (typeof values[values.length - 1] !== 'function') { return noop; } if (values.length > 1) { return values[values.length - 1].bind(values[values.length - 2]); } else { return values[0].bind(target); } }
javascript
function methodByPath(target, path) { path = pathToArray(path); const values = breadcrumbs(target, path); if (values.length < path.length) { return noop; } if (typeof values[values.length - 1] !== 'function') { return noop; } if (values.length > 1) { return values[values.length - 1].bind(values[values.length - 2]); } else { return values[0].bind(target); } }
[ "function", "methodByPath", "(", "target", ",", "path", ")", "{", "path", "=", "pathToArray", "(", "path", ")", ";", "const", "values", "=", "breadcrumbs", "(", "target", ",", "path", ")", ";", "if", "(", "values", ".", "length", "<", "path", ".", "length", ")", "{", "return", "noop", ";", "}", "if", "(", "typeof", "values", "[", "values", ".", "length", "-", "1", "]", "!==", "'function'", ")", "{", "return", "noop", ";", "}", "if", "(", "values", ".", "length", ">", "1", ")", "{", "return", "values", "[", "values", ".", "length", "-", "1", "]", ".", "bind", "(", "values", "[", "values", ".", "length", "-", "2", "]", ")", ";", "}", "else", "{", "return", "values", "[", "0", "]", ".", "bind", "(", "target", ")", ";", "}", "}" ]
methodByPath - Receive method from deeply nested object as function with captured context as the method's owner object. @param {*} target Deeply nested object or anything else. @param {Path} path Path to the method. @return {Function} Returns function.
[ "methodByPath", "-", "Receive", "method", "from", "deeply", "nested", "object", "as", "function", "with", "captured", "context", "as", "the", "method", "s", "owner", "object", "." ]
3198d6cfb22d10f98552b7cee0be6b1dab79b5fd
https://github.com/rumkin/keyget/blob/3198d6cfb22d10f98552b7cee0be6b1dab79b5fd/index.js#L220-L239
train
rumkin/keyget
index.js
callByPath
function callByPath(target, path, args) { var fn = methodByPath(target, path); if (! fn) { return; } return fn.apply(null, args); }
javascript
function callByPath(target, path, args) { var fn = methodByPath(target, path); if (! fn) { return; } return fn.apply(null, args); }
[ "function", "callByPath", "(", "target", ",", "path", ",", "args", ")", "{", "var", "fn", "=", "methodByPath", "(", "target", ",", "path", ")", ";", "if", "(", "!", "fn", ")", "{", "return", ";", "}", "return", "fn", ".", "apply", "(", "null", ",", "args", ")", ";", "}" ]
callByPath - Call method by it's path in nested object. @param {*} target Nested object or anything else. @param {Path} path Path to nested property. @param {*[]} args Arguments of function call. @return {*} Result of function call or undefined if method not exists.
[ "callByPath", "-", "Call", "method", "by", "it", "s", "path", "in", "nested", "object", "." ]
3198d6cfb22d10f98552b7cee0be6b1dab79b5fd
https://github.com/rumkin/keyget/blob/3198d6cfb22d10f98552b7cee0be6b1dab79b5fd/index.js#L249-L256
train
RnbWd/parse-browserify
lib/geopoint.js
function(point) { var d2r = Math.PI / 180.0; var lat1rad = this.latitude * d2r; var long1rad = this.longitude * d2r; var lat2rad = point.latitude * d2r; var long2rad = point.longitude * d2r; var deltaLat = lat1rad - lat2rad; var deltaLong = long1rad - long2rad; var sinDeltaLatDiv2 = Math.sin(deltaLat / 2); var sinDeltaLongDiv2 = Math.sin(deltaLong / 2); // Square of half the straight line chord distance between both points. var a = ((sinDeltaLatDiv2 * sinDeltaLatDiv2) + (Math.cos(lat1rad) * Math.cos(lat2rad) * sinDeltaLongDiv2 * sinDeltaLongDiv2)); a = Math.min(1.0, a); return 2 * Math.asin(Math.sqrt(a)); }
javascript
function(point) { var d2r = Math.PI / 180.0; var lat1rad = this.latitude * d2r; var long1rad = this.longitude * d2r; var lat2rad = point.latitude * d2r; var long2rad = point.longitude * d2r; var deltaLat = lat1rad - lat2rad; var deltaLong = long1rad - long2rad; var sinDeltaLatDiv2 = Math.sin(deltaLat / 2); var sinDeltaLongDiv2 = Math.sin(deltaLong / 2); // Square of half the straight line chord distance between both points. var a = ((sinDeltaLatDiv2 * sinDeltaLatDiv2) + (Math.cos(lat1rad) * Math.cos(lat2rad) * sinDeltaLongDiv2 * sinDeltaLongDiv2)); a = Math.min(1.0, a); return 2 * Math.asin(Math.sqrt(a)); }
[ "function", "(", "point", ")", "{", "var", "d2r", "=", "Math", ".", "PI", "/", "180.0", ";", "var", "lat1rad", "=", "this", ".", "latitude", "*", "d2r", ";", "var", "long1rad", "=", "this", ".", "longitude", "*", "d2r", ";", "var", "lat2rad", "=", "point", ".", "latitude", "*", "d2r", ";", "var", "long2rad", "=", "point", ".", "longitude", "*", "d2r", ";", "var", "deltaLat", "=", "lat1rad", "-", "lat2rad", ";", "var", "deltaLong", "=", "long1rad", "-", "long2rad", ";", "var", "sinDeltaLatDiv2", "=", "Math", ".", "sin", "(", "deltaLat", "/", "2", ")", ";", "var", "sinDeltaLongDiv2", "=", "Math", ".", "sin", "(", "deltaLong", "/", "2", ")", ";", "var", "a", "=", "(", "(", "sinDeltaLatDiv2", "*", "sinDeltaLatDiv2", ")", "+", "(", "Math", ".", "cos", "(", "lat1rad", ")", "*", "Math", ".", "cos", "(", "lat2rad", ")", "*", "sinDeltaLongDiv2", "*", "sinDeltaLongDiv2", ")", ")", ";", "a", "=", "Math", ".", "min", "(", "1.0", ",", "a", ")", ";", "return", "2", "*", "Math", ".", "asin", "(", "Math", ".", "sqrt", "(", "a", ")", ")", ";", "}" ]
Returns the distance from this GeoPoint to another in radians. @param {Parse.GeoPoint} point the other Parse.GeoPoint. @return {Number}
[ "Returns", "the", "distance", "from", "this", "GeoPoint", "to", "another", "in", "radians", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/geopoint.js#L136-L152
train
allanmboyd/exceptions
lib/exceptions.js
throwError
function throwError(name, message) { var error = new Error(message); error.name = name; error.stack = formaterrors.stackFilter(error.stack, ["exceptions.js"], false); throw error; }
javascript
function throwError(name, message) { var error = new Error(message); error.name = name; error.stack = formaterrors.stackFilter(error.stack, ["exceptions.js"], false); throw error; }
[ "function", "throwError", "(", "name", ",", "message", ")", "{", "var", "error", "=", "new", "Error", "(", "message", ")", ";", "error", ".", "name", "=", "name", ";", "error", ".", "stack", "=", "formaterrors", ".", "stackFilter", "(", "error", ".", "stack", ",", "[", "\"exceptions.js\"", "]", ",", "false", ")", ";", "throw", "error", ";", "}" ]
Throw an error. This method ensures that no exceptions.js lines are included in the stack trace of the thrown error. @private @param {String} name the name of the Error to throw. @param {String} message the message part of the error to throw.
[ "Throw", "an", "error", ".", "This", "method", "ensures", "that", "no", "exceptions", ".", "js", "lines", "are", "included", "in", "the", "stack", "trace", "of", "the", "thrown", "error", "." ]
ea093be65aba73ededd98fccbf24e16e38f9629b
https://github.com/allanmboyd/exceptions/blob/ea093be65aba73ededd98fccbf24e16e38f9629b/lib/exceptions.js#L56-L63
train
imlucas/node-regret
index.js
regret
function regret(name, input){ var matchers, res = null, re, matches, matcher; if(typeof name.exec === 'function'){ matchers = Object.keys(regret.matchers).filter(function(m){ return name.test(m); }).map(function(m){ return regret.matchers[m]; }); } else { matchers = regret.matchers[name] ? [regret.matchers[name]] : []; } if(matchers.length === 0){ return undefined; } while(matchers.length > 0){ matcher = matchers.shift(); matches = matcher.pattern.exec(input); if(!matches){ continue; } res = {}; // pop off the input string matches.shift(); matches.map(function(p, i){ res[matcher.captures[i]] = p; }); break; } return res; }
javascript
function regret(name, input){ var matchers, res = null, re, matches, matcher; if(typeof name.exec === 'function'){ matchers = Object.keys(regret.matchers).filter(function(m){ return name.test(m); }).map(function(m){ return regret.matchers[m]; }); } else { matchers = regret.matchers[name] ? [regret.matchers[name]] : []; } if(matchers.length === 0){ return undefined; } while(matchers.length > 0){ matcher = matchers.shift(); matches = matcher.pattern.exec(input); if(!matches){ continue; } res = {}; // pop off the input string matches.shift(); matches.map(function(p, i){ res[matcher.captures[i]] = p; }); break; } return res; }
[ "function", "regret", "(", "name", ",", "input", ")", "{", "var", "matchers", ",", "res", "=", "null", ",", "re", ",", "matches", ",", "matcher", ";", "if", "(", "typeof", "name", ".", "exec", "===", "'function'", ")", "{", "matchers", "=", "Object", ".", "keys", "(", "regret", ".", "matchers", ")", ".", "filter", "(", "function", "(", "m", ")", "{", "return", "name", ".", "test", "(", "m", ")", ";", "}", ")", ".", "map", "(", "function", "(", "m", ")", "{", "return", "regret", ".", "matchers", "[", "m", "]", ";", "}", ")", ";", "}", "else", "{", "matchers", "=", "regret", ".", "matchers", "[", "name", "]", "?", "[", "regret", ".", "matchers", "[", "name", "]", "]", ":", "[", "]", ";", "}", "if", "(", "matchers", ".", "length", "===", "0", ")", "{", "return", "undefined", ";", "}", "while", "(", "matchers", ".", "length", ">", "0", ")", "{", "matcher", "=", "matchers", ".", "shift", "(", ")", ";", "matches", "=", "matcher", ".", "pattern", ".", "exec", "(", "input", ")", ";", "if", "(", "!", "matches", ")", "{", "continue", ";", "}", "res", "=", "{", "}", ";", "matches", ".", "shift", "(", ")", ";", "matches", ".", "map", "(", "function", "(", "p", ",", "i", ")", "{", "res", "[", "matcher", ".", "captures", "[", "i", "]", "]", "=", "p", ";", "}", ")", ";", "break", ";", "}", "return", "res", ";", "}" ]
Don't let the regex party get out of control.
[ "Don", "t", "let", "the", "regex", "party", "get", "out", "of", "control", "." ]
7e304af8575a9480028fc75fe62a3e1c5d893551
https://github.com/imlucas/node-regret/blob/7e304af8575a9480028fc75fe62a3e1c5d893551/index.js#L4-L38
train
antonycourtney/tabli-core
lib/js/utils.js
seqActions
function seqActions(actions, seed, onCompleted) { var index = 0; function invokeNext(v) { var action = actions[index]; action(v, function (res) { index = index + 1; if (index < actions.length) { invokeNext(res); } else { onCompleted(res); } }); } invokeNext(seed); }
javascript
function seqActions(actions, seed, onCompleted) { var index = 0; function invokeNext(v) { var action = actions[index]; action(v, function (res) { index = index + 1; if (index < actions.length) { invokeNext(res); } else { onCompleted(res); } }); } invokeNext(seed); }
[ "function", "seqActions", "(", "actions", ",", "seed", ",", "onCompleted", ")", "{", "var", "index", "=", "0", ";", "function", "invokeNext", "(", "v", ")", "{", "var", "action", "=", "actions", "[", "index", "]", ";", "action", "(", "v", ",", "function", "(", "res", ")", "{", "index", "=", "index", "+", "1", ";", "if", "(", "index", "<", "actions", ".", "length", ")", "{", "invokeNext", "(", "res", ")", ";", "}", "else", "{", "onCompleted", "(", "res", ")", ";", "}", "}", ")", ";", "}", "invokeNext", "(", "seed", ")", ";", "}" ]
chain a sequence of asynchronous actions
[ "chain", "a", "sequence", "of", "asynchronous", "actions" ]
76cc540891421bc6c8bdcf00f277ebb6e716fdd9
https://github.com/antonycourtney/tabli-core/blob/76cc540891421bc6c8bdcf00f277ebb6e716fdd9/lib/js/utils.js#L56-L72
train
stdarg/json-rest-api
index.js
RestApi
function RestApi(config, cb) { var self = this; self.routes = {}; self.bindTo = (config && config.bindTo) ? config.bindTo : undefined; self.port = (config && config.port) ? config.port : DEFAULT_PORT; // create the HTTP server object and on every request, try to match the // request with a known route. If there is no match, return a 404 error. self.HttpServer = http.createServer(function(req, res) { var uriPath; var queryStr; var urlParts = url.parse(req.url, true); if (is.obj(urlParts)) { uriPath = urlParts.pathname || undefined; queryStr = urlParts.query || undefined; debug('queryStr: '+inspect(queryStr)); } else { // no match was found, return a 404 error. res.writeHead(400, {'Content-Type': 'application/json; charset=utf-8'}); res.end('{status:400, message:"Bad URI path."}', 'utf8'); return; } // try to match the request & method with a handler for (var path in self.routes[req.method]) { if (path === uriPath) { self.routes[req.method][path](req, res, queryStr); return; } } // no match was found, return a 404 error. res.writeHead(404, {'Content-Type': 'application/json; charset=utf-8'}); res.end('{status:404, message:"Content not found."}', 'utf8'); }); if (cb) self.listen(cb); }
javascript
function RestApi(config, cb) { var self = this; self.routes = {}; self.bindTo = (config && config.bindTo) ? config.bindTo : undefined; self.port = (config && config.port) ? config.port : DEFAULT_PORT; // create the HTTP server object and on every request, try to match the // request with a known route. If there is no match, return a 404 error. self.HttpServer = http.createServer(function(req, res) { var uriPath; var queryStr; var urlParts = url.parse(req.url, true); if (is.obj(urlParts)) { uriPath = urlParts.pathname || undefined; queryStr = urlParts.query || undefined; debug('queryStr: '+inspect(queryStr)); } else { // no match was found, return a 404 error. res.writeHead(400, {'Content-Type': 'application/json; charset=utf-8'}); res.end('{status:400, message:"Bad URI path."}', 'utf8'); return; } // try to match the request & method with a handler for (var path in self.routes[req.method]) { if (path === uriPath) { self.routes[req.method][path](req, res, queryStr); return; } } // no match was found, return a 404 error. res.writeHead(404, {'Content-Type': 'application/json; charset=utf-8'}); res.end('{status:404, message:"Content not found."}', 'utf8'); }); if (cb) self.listen(cb); }
[ "function", "RestApi", "(", "config", ",", "cb", ")", "{", "var", "self", "=", "this", ";", "self", ".", "routes", "=", "{", "}", ";", "self", ".", "bindTo", "=", "(", "config", "&&", "config", ".", "bindTo", ")", "?", "config", ".", "bindTo", ":", "undefined", ";", "self", ".", "port", "=", "(", "config", "&&", "config", ".", "port", ")", "?", "config", ".", "port", ":", "DEFAULT_PORT", ";", "self", ".", "HttpServer", "=", "http", ".", "createServer", "(", "function", "(", "req", ",", "res", ")", "{", "var", "uriPath", ";", "var", "queryStr", ";", "var", "urlParts", "=", "url", ".", "parse", "(", "req", ".", "url", ",", "true", ")", ";", "if", "(", "is", ".", "obj", "(", "urlParts", ")", ")", "{", "uriPath", "=", "urlParts", ".", "pathname", "||", "undefined", ";", "queryStr", "=", "urlParts", ".", "query", "||", "undefined", ";", "debug", "(", "'queryStr: '", "+", "inspect", "(", "queryStr", ")", ")", ";", "}", "else", "{", "res", ".", "writeHead", "(", "400", ",", "{", "'Content-Type'", ":", "'application/json; charset=utf-8'", "}", ")", ";", "res", ".", "end", "(", "'{status:400, message:\"Bad URI path.\"}'", ",", "'utf8'", ")", ";", "return", ";", "}", "for", "(", "var", "path", "in", "self", ".", "routes", "[", "req", ".", "method", "]", ")", "{", "if", "(", "path", "===", "uriPath", ")", "{", "self", ".", "routes", "[", "req", ".", "method", "]", "[", "path", "]", "(", "req", ",", "res", ",", "queryStr", ")", ";", "return", ";", "}", "}", "res", ".", "writeHead", "(", "404", ",", "{", "'Content-Type'", ":", "'application/json; charset=utf-8'", "}", ")", ";", "res", ".", "end", "(", "'{status:404, message:\"Content not found.\"}'", ",", "'utf8'", ")", ";", "}", ")", ";", "if", "(", "cb", ")", "self", ".", "listen", "(", "cb", ")", ";", "}" ]
RestApi constructor. Creates the HTTP server objects and starts listening on the socket. @param {Object} [config] An optional configuration object to configure the RestApi. Possible properties are: port and bindTo to specify the listening port and the address to bind to. If no port is specified the default is 44401 and the default address is INADDR_ANY. @param {Function} [cb] An optional callback. If there is a callback, the process will be begin listening on the socket for HTTP requests. @constructor
[ "RestApi", "constructor", ".", "Creates", "the", "HTTP", "server", "objects", "and", "starts", "listening", "on", "the", "socket", "." ]
25e47f4d26d9391f6a8a3de37545029130e39d45
https://github.com/stdarg/json-rest-api/blob/25e47f4d26d9391f6a8a3de37545029130e39d45/index.js#L31-L69
train
pierrec/node-atok
lib/rule.js
Rule
function Rule (subrules, type, handler, props, groupProps, encoding) { var self = this var n = subrules.length this.props = props this.debug = false // Used for cloning this.subrules = subrules // Required by Atok#_resolveRules for (var p in groupProps) this[p] = groupProps[p] // Runtime values for continue props this.continue = this.props.continue[0] this.continueOnFail = this.props.continue[1] this.type = type this.handler = handler // For debug this.prevHandler = null this.id = this.type !== null ? this.type : handler // Id for debug this._id = (handler !== null ? (handler.name || '#emit()') : this.type) // Subrule pattern index that matched (-1 if only 1 pattern) this.idx = -1 // Single subrule: special case for trimRight this.single = (n === 1) // First subrule var subrule = this.first = n > 0 ? SubRule.firstSubRule( subrules[0], this.props, encoding, this.single ) // Special case: no rule given -> passthrough : SubRule.emptySubRule // Special case: one empty rule -> tokenize whole buffer if (n === 1 && subrule.length === 0) { subrule = this.first = SubRule.allSubRule // Make infinite loop detection ignore this this.length = -1 } else { // First subrule pattern length (max of all patterns if many) // - used in infinite loop detection this.length = this.first.length } // Instantiate and link the subrules // { test: {Function} // , next: {SubRule|undefined} // } var prev = subrule // Many subrules or none for (var i = 1; i < n; i++) { subrule = SubRule.SubRule( subrules[i], this.props, encoding ) prev.next = subrule subrule.prev = prev // Useful in some edge cases prev = subrule if (this.length < subrule.length) this.length = subrule.length } // Last subrule (used for trimRight and matched idx) this.last = subrule // Set the first and last subrules length based on trim properties if (!this.props.trimLeft) this.first.length = 0 if (!this.single && !this.props.trimRight) this.last.length = 0 this.next = null this.nextFail = null this.currentRule = null }
javascript
function Rule (subrules, type, handler, props, groupProps, encoding) { var self = this var n = subrules.length this.props = props this.debug = false // Used for cloning this.subrules = subrules // Required by Atok#_resolveRules for (var p in groupProps) this[p] = groupProps[p] // Runtime values for continue props this.continue = this.props.continue[0] this.continueOnFail = this.props.continue[1] this.type = type this.handler = handler // For debug this.prevHandler = null this.id = this.type !== null ? this.type : handler // Id for debug this._id = (handler !== null ? (handler.name || '#emit()') : this.type) // Subrule pattern index that matched (-1 if only 1 pattern) this.idx = -1 // Single subrule: special case for trimRight this.single = (n === 1) // First subrule var subrule = this.first = n > 0 ? SubRule.firstSubRule( subrules[0], this.props, encoding, this.single ) // Special case: no rule given -> passthrough : SubRule.emptySubRule // Special case: one empty rule -> tokenize whole buffer if (n === 1 && subrule.length === 0) { subrule = this.first = SubRule.allSubRule // Make infinite loop detection ignore this this.length = -1 } else { // First subrule pattern length (max of all patterns if many) // - used in infinite loop detection this.length = this.first.length } // Instantiate and link the subrules // { test: {Function} // , next: {SubRule|undefined} // } var prev = subrule // Many subrules or none for (var i = 1; i < n; i++) { subrule = SubRule.SubRule( subrules[i], this.props, encoding ) prev.next = subrule subrule.prev = prev // Useful in some edge cases prev = subrule if (this.length < subrule.length) this.length = subrule.length } // Last subrule (used for trimRight and matched idx) this.last = subrule // Set the first and last subrules length based on trim properties if (!this.props.trimLeft) this.first.length = 0 if (!this.single && !this.props.trimRight) this.last.length = 0 this.next = null this.nextFail = null this.currentRule = null }
[ "function", "Rule", "(", "subrules", ",", "type", ",", "handler", ",", "props", ",", "groupProps", ",", "encoding", ")", "{", "var", "self", "=", "this", "var", "n", "=", "subrules", ".", "length", "this", ".", "props", "=", "props", "this", ".", "debug", "=", "false", "this", ".", "subrules", "=", "subrules", "for", "(", "var", "p", "in", "groupProps", ")", "this", "[", "p", "]", "=", "groupProps", "[", "p", "]", "this", ".", "continue", "=", "this", ".", "props", ".", "continue", "[", "0", "]", "this", ".", "continueOnFail", "=", "this", ".", "props", ".", "continue", "[", "1", "]", "this", ".", "type", "=", "type", "this", ".", "handler", "=", "handler", "this", ".", "prevHandler", "=", "null", "this", ".", "id", "=", "this", ".", "type", "!==", "null", "?", "this", ".", "type", ":", "handler", "this", ".", "_id", "=", "(", "handler", "!==", "null", "?", "(", "handler", ".", "name", "||", "'#emit()'", ")", ":", "this", ".", "type", ")", "this", ".", "idx", "=", "-", "1", "this", ".", "single", "=", "(", "n", "===", "1", ")", "var", "subrule", "=", "this", ".", "first", "=", "n", ">", "0", "?", "SubRule", ".", "firstSubRule", "(", "subrules", "[", "0", "]", ",", "this", ".", "props", ",", "encoding", ",", "this", ".", "single", ")", ":", "SubRule", ".", "emptySubRule", "if", "(", "n", "===", "1", "&&", "subrule", ".", "length", "===", "0", ")", "{", "subrule", "=", "this", ".", "first", "=", "SubRule", ".", "allSubRule", "this", ".", "length", "=", "-", "1", "}", "else", "{", "this", ".", "length", "=", "this", ".", "first", ".", "length", "}", "var", "prev", "=", "subrule", "for", "(", "var", "i", "=", "1", ";", "i", "<", "n", ";", "i", "++", ")", "{", "subrule", "=", "SubRule", ".", "SubRule", "(", "subrules", "[", "i", "]", ",", "this", ".", "props", ",", "encoding", ")", "prev", ".", "next", "=", "subrule", "subrule", ".", "prev", "=", "prev", "prev", "=", "subrule", "if", "(", "this", ".", "length", "<", "subrule", ".", "length", ")", "this", ".", "length", "=", "subrule", ".", "length", "}", "this", ".", "last", "=", "subrule", "if", "(", "!", "this", ".", "props", ".", "trimLeft", ")", "this", ".", "first", ".", "length", "=", "0", "if", "(", "!", "this", ".", "single", "&&", "!", "this", ".", "props", ".", "trimRight", ")", "this", ".", "last", ".", "length", "=", "0", "this", ".", "next", "=", "null", "this", ".", "nextFail", "=", "null", "this", ".", "currentRule", "=", "null", "}" ]
Atok Rule constructor @param {array} list of subrules @param {string|number|null} rule type (set if handler is not) @param {function} rule handler (set if type is not) @param {Object} atok instance @constructor @api private
[ "Atok", "Rule", "constructor" ]
abe139e7fa8c092d87e528289b6abd9083df2323
https://github.com/pierrec/node-atok/blob/abe139e7fa8c092d87e528289b6abd9083df2323/lib/rule.js#L23-L98
train
donavon/storeit
lib/Storeit.js
initializeItemSerializer
function initializeItemSerializer(hasItems) { // Is there is a itemSerializer specified, we MUST use it. // If existing data and no itemSerializer specified, this is an old JSON database, // so "fake" the compatible JSON serializer var providerInfo = storageProvider.getMetadata(namespace); // TODO I hate this! var itemSerializerName = providerInfo ? providerInfo.itemSerializer : hasItems ? "JSONSerializer" : null; storageProvider.itemSerializer = itemSerializerName; }
javascript
function initializeItemSerializer(hasItems) { // Is there is a itemSerializer specified, we MUST use it. // If existing data and no itemSerializer specified, this is an old JSON database, // so "fake" the compatible JSON serializer var providerInfo = storageProvider.getMetadata(namespace); // TODO I hate this! var itemSerializerName = providerInfo ? providerInfo.itemSerializer : hasItems ? "JSONSerializer" : null; storageProvider.itemSerializer = itemSerializerName; }
[ "function", "initializeItemSerializer", "(", "hasItems", ")", "{", "var", "providerInfo", "=", "storageProvider", ".", "getMetadata", "(", "namespace", ")", ";", "var", "itemSerializerName", "=", "providerInfo", "?", "providerInfo", ".", "itemSerializer", ":", "hasItems", "?", "\"JSONSerializer\"", ":", "null", ";", "storageProvider", ".", "itemSerializer", "=", "itemSerializerName", ";", "}" ]
Read in the base namespace key.
[ "Read", "in", "the", "base", "namespace", "key", "." ]
f896ddd81394626073494c800076272b694d7ec8
https://github.com/donavon/storeit/blob/f896ddd81394626073494c800076272b694d7ec8/lib/Storeit.js#L211-L219
train
react-components/onus
index.js
_yield
function _yield(name, context) { var prop = this.props[name || 'children']; if (typeof prop !== 'function') return prop; var args = Array.prototype.slice.call(arguments, 2); return prop.apply(context, args); }
javascript
function _yield(name, context) { var prop = this.props[name || 'children']; if (typeof prop !== 'function') return prop; var args = Array.prototype.slice.call(arguments, 2); return prop.apply(context, args); }
[ "function", "_yield", "(", "name", ",", "context", ")", "{", "var", "prop", "=", "this", ".", "props", "[", "name", "||", "'children'", "]", ";", "if", "(", "typeof", "prop", "!==", "'function'", ")", "return", "prop", ";", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "2", ")", ";", "return", "prop", ".", "apply", "(", "context", ",", "args", ")", ";", "}" ]
Wrap the yield function
[ "Wrap", "the", "yield", "function" ]
ebe1884a8e70b3ca9d1e95e05c373525f7f5d71b
https://github.com/react-components/onus/blob/ebe1884a8e70b3ca9d1e95e05c373525f7f5d71b/index.js#L238-L244
train
ruifortes/json-deref
src/index.js
getJsonResource
function getJsonResource(url) { var protocol = url.match(/^(.*?):/) protocol = (protocol && protocol[1]) || 'file' const defaultLoader = defaultOptions.loaders[protocol] const loader = options.loaders[protocol] return Promise.resolve(cache[url]) .then(cached => { if(cached) { return cached } else { return loader(url, defaultOptions.loaders) .then(json => cache[url] = {raw: json, parsed: Array.isArray(json) ? [] : {} }) } }) }
javascript
function getJsonResource(url) { var protocol = url.match(/^(.*?):/) protocol = (protocol && protocol[1]) || 'file' const defaultLoader = defaultOptions.loaders[protocol] const loader = options.loaders[protocol] return Promise.resolve(cache[url]) .then(cached => { if(cached) { return cached } else { return loader(url, defaultOptions.loaders) .then(json => cache[url] = {raw: json, parsed: Array.isArray(json) ? [] : {} }) } }) }
[ "function", "getJsonResource", "(", "url", ")", "{", "var", "protocol", "=", "url", ".", "match", "(", "/", "^(.*?):", "/", ")", "protocol", "=", "(", "protocol", "&&", "protocol", "[", "1", "]", ")", "||", "'file'", "const", "defaultLoader", "=", "defaultOptions", ".", "loaders", "[", "protocol", "]", "const", "loader", "=", "options", ".", "loaders", "[", "protocol", "]", "return", "Promise", ".", "resolve", "(", "cache", "[", "url", "]", ")", ".", "then", "(", "cached", "=>", "{", "if", "(", "cached", ")", "{", "return", "cached", "}", "else", "{", "return", "loader", "(", "url", ",", "defaultOptions", ".", "loaders", ")", ".", "then", "(", "json", "=>", "cache", "[", "url", "]", "=", "{", "raw", ":", "json", ",", "parsed", ":", "Array", ".", "isArray", "(", "json", ")", "?", "[", "]", ":", "{", "}", "}", ")", "}", "}", ")", "}" ]
Gets raw and parsed json from cache @param {object} url - uri-js object @param {object} params - ...rest of the json-reference object @returns {Object} Returns an object containing raw, parsed and id
[ "Gets", "raw", "and", "parsed", "json", "from", "cache" ]
1d534d68e5067b3de4bc98080f6e989187a684ca
https://github.com/ruifortes/json-deref/blob/1d534d68e5067b3de4bc98080f6e989187a684ca/src/index.js#L87-L104
train
ruifortes/json-deref
src/index.js
processNode
function processNode({rawNode, parsedNode, parentId = resourceId, cursor, refChain, prop}) { logger.info(`processNode ${cursor}${prop ? '(' + prop + ')' : ''} with refChain ${refChain}`) const currentId = options.urlBaseKey && rawNode[options.urlBaseKey] ? parseRef(rawNode[options.urlBaseKey], parentId).fullUrl : parentId const props = !!prop ? [prop] : Object.getOwnPropertyNames(rawNode) let propIndex = -1, nodeChanged = 0 return new Promise((accept, reject) => { nextProp() function nextProp() { propIndex++ if(propIndex >= props.length) { if (!!prop) { accept(parsedNode[prop]) } else { accept(nodeChanged ? parsedNode : rawNode) } } else { const prop = props[propIndex] const sourceValue = rawNode[prop] const propCursor = `${cursor}/${prop}` // If prop is already defined in parsedNode assume complete and skip it if(parsedNode.hasOwnProperty(prop)){ nodeChanged |= parsedNode[prop] !== sourceValue nextProp() } // Is scalar, just set same and continue else if (typeof sourceValue !== 'object' || sourceValue === null) { parsedNode[prop] = sourceValue nextProp() } // prop is a reference else if(!!sourceValue.$ref) { const {$ref, ...params} = sourceValue const branchRefChain = [...refChain, propCursor] const {url, pointer, isLocalRef, isCircular} = parseRef($ref, currentId, branchRefChain) //, options.vars) if(!url) throw new Error(`Invalid $ref ${$ref}`) if(isCircular && options.skipCircular || isLocalRef && externalOnly) { // if(isLocalRef && externalOnly) { parsedNode[prop] = sourceValue nextProp() } else { Promise.resolve(isLocalRef ? solvePointer(pointer, branchRefChain, currentId) : externalOnly && pointer ? processResource(url, pointer, branchRefChain, false) : processResource(url, pointer, branchRefChain) ) .then(newValue => { nodeChanged = 1 parsedNode[prop] = newValue nextProp() }) .catch(err => { const log = `Error derefing ${cursor}/${prop}` if (options.failOnMissing) { reject(log) } else { logger.info(log) parsedNode[prop] = sourceValue nextProp() } }) } } else { const placeholder = parsedNode[prop] = Array.isArray(sourceValue) ? [] : {} processNode({ rawNode: sourceValue, parsedNode: placeholder, parentId: currentId, cursor: propCursor, refChain }) .then(newValue => { nodeChanged |= newValue !== sourceValue nextProp() }) .catch(reject) } } } }) }
javascript
function processNode({rawNode, parsedNode, parentId = resourceId, cursor, refChain, prop}) { logger.info(`processNode ${cursor}${prop ? '(' + prop + ')' : ''} with refChain ${refChain}`) const currentId = options.urlBaseKey && rawNode[options.urlBaseKey] ? parseRef(rawNode[options.urlBaseKey], parentId).fullUrl : parentId const props = !!prop ? [prop] : Object.getOwnPropertyNames(rawNode) let propIndex = -1, nodeChanged = 0 return new Promise((accept, reject) => { nextProp() function nextProp() { propIndex++ if(propIndex >= props.length) { if (!!prop) { accept(parsedNode[prop]) } else { accept(nodeChanged ? parsedNode : rawNode) } } else { const prop = props[propIndex] const sourceValue = rawNode[prop] const propCursor = `${cursor}/${prop}` // If prop is already defined in parsedNode assume complete and skip it if(parsedNode.hasOwnProperty(prop)){ nodeChanged |= parsedNode[prop] !== sourceValue nextProp() } // Is scalar, just set same and continue else if (typeof sourceValue !== 'object' || sourceValue === null) { parsedNode[prop] = sourceValue nextProp() } // prop is a reference else if(!!sourceValue.$ref) { const {$ref, ...params} = sourceValue const branchRefChain = [...refChain, propCursor] const {url, pointer, isLocalRef, isCircular} = parseRef($ref, currentId, branchRefChain) //, options.vars) if(!url) throw new Error(`Invalid $ref ${$ref}`) if(isCircular && options.skipCircular || isLocalRef && externalOnly) { // if(isLocalRef && externalOnly) { parsedNode[prop] = sourceValue nextProp() } else { Promise.resolve(isLocalRef ? solvePointer(pointer, branchRefChain, currentId) : externalOnly && pointer ? processResource(url, pointer, branchRefChain, false) : processResource(url, pointer, branchRefChain) ) .then(newValue => { nodeChanged = 1 parsedNode[prop] = newValue nextProp() }) .catch(err => { const log = `Error derefing ${cursor}/${prop}` if (options.failOnMissing) { reject(log) } else { logger.info(log) parsedNode[prop] = sourceValue nextProp() } }) } } else { const placeholder = parsedNode[prop] = Array.isArray(sourceValue) ? [] : {} processNode({ rawNode: sourceValue, parsedNode: placeholder, parentId: currentId, cursor: propCursor, refChain }) .then(newValue => { nodeChanged |= newValue !== sourceValue nextProp() }) .catch(reject) } } } }) }
[ "function", "processNode", "(", "{", "rawNode", ",", "parsedNode", ",", "parentId", "=", "resourceId", ",", "cursor", ",", "refChain", ",", "prop", "}", ")", "{", "logger", ".", "info", "(", "`", "${", "cursor", "}", "${", "prop", "?", "'('", "+", "prop", "+", "')'", ":", "''", "}", "${", "refChain", "}", "`", ")", "const", "currentId", "=", "options", ".", "urlBaseKey", "&&", "rawNode", "[", "options", ".", "urlBaseKey", "]", "?", "parseRef", "(", "rawNode", "[", "options", ".", "urlBaseKey", "]", ",", "parentId", ")", ".", "fullUrl", ":", "parentId", "const", "props", "=", "!", "!", "prop", "?", "[", "prop", "]", ":", "Object", ".", "getOwnPropertyNames", "(", "rawNode", ")", "let", "propIndex", "=", "-", "1", ",", "nodeChanged", "=", "0", "return", "new", "Promise", "(", "(", "accept", ",", "reject", ")", "=>", "{", "nextProp", "(", ")", "function", "nextProp", "(", ")", "{", "propIndex", "++", "if", "(", "propIndex", ">=", "props", ".", "length", ")", "{", "if", "(", "!", "!", "prop", ")", "{", "accept", "(", "parsedNode", "[", "prop", "]", ")", "}", "else", "{", "accept", "(", "nodeChanged", "?", "parsedNode", ":", "rawNode", ")", "}", "}", "else", "{", "const", "prop", "=", "props", "[", "propIndex", "]", "const", "sourceValue", "=", "rawNode", "[", "prop", "]", "const", "propCursor", "=", "`", "${", "cursor", "}", "${", "prop", "}", "`", "if", "(", "parsedNode", ".", "hasOwnProperty", "(", "prop", ")", ")", "{", "nodeChanged", "|=", "parsedNode", "[", "prop", "]", "!==", "sourceValue", "nextProp", "(", ")", "}", "else", "if", "(", "typeof", "sourceValue", "!==", "'object'", "||", "sourceValue", "===", "null", ")", "{", "parsedNode", "[", "prop", "]", "=", "sourceValue", "nextProp", "(", ")", "}", "else", "if", "(", "!", "!", "sourceValue", ".", "$ref", ")", "{", "const", "{", "$ref", ",", "...", "params", "}", "=", "sourceValue", "const", "branchRefChain", "=", "[", "...", "refChain", ",", "propCursor", "]", "const", "{", "url", ",", "pointer", ",", "isLocalRef", ",", "isCircular", "}", "=", "parseRef", "(", "$ref", ",", "currentId", ",", "branchRefChain", ")", "if", "(", "!", "url", ")", "throw", "new", "Error", "(", "`", "${", "$ref", "}", "`", ")", "if", "(", "isCircular", "&&", "options", ".", "skipCircular", "||", "isLocalRef", "&&", "externalOnly", ")", "{", "parsedNode", "[", "prop", "]", "=", "sourceValue", "nextProp", "(", ")", "}", "else", "{", "Promise", ".", "resolve", "(", "isLocalRef", "?", "solvePointer", "(", "pointer", ",", "branchRefChain", ",", "currentId", ")", ":", "externalOnly", "&&", "pointer", "?", "processResource", "(", "url", ",", "pointer", ",", "branchRefChain", ",", "false", ")", ":", "processResource", "(", "url", ",", "pointer", ",", "branchRefChain", ")", ")", ".", "then", "(", "newValue", "=>", "{", "nodeChanged", "=", "1", "parsedNode", "[", "prop", "]", "=", "newValue", "nextProp", "(", ")", "}", ")", ".", "catch", "(", "err", "=>", "{", "const", "log", "=", "`", "${", "cursor", "}", "${", "prop", "}", "`", "if", "(", "options", ".", "failOnMissing", ")", "{", "reject", "(", "log", ")", "}", "else", "{", "logger", ".", "info", "(", "log", ")", "parsedNode", "[", "prop", "]", "=", "sourceValue", "nextProp", "(", ")", "}", "}", ")", "}", "}", "else", "{", "const", "placeholder", "=", "parsedNode", "[", "prop", "]", "=", "Array", ".", "isArray", "(", "sourceValue", ")", "?", "[", "]", ":", "{", "}", "processNode", "(", "{", "rawNode", ":", "sourceValue", ",", "parsedNode", ":", "placeholder", ",", "parentId", ":", "currentId", ",", "cursor", ":", "propCursor", ",", "refChain", "}", ")", ".", "then", "(", "newValue", "=>", "{", "nodeChanged", "|=", "newValue", "!==", "sourceValue", "nextProp", "(", ")", "}", ")", ".", "catch", "(", "reject", ")", "}", "}", "}", "}", ")", "}" ]
Main recursive traverse function @param {Object} rawNode - The source node to processed @param {Object} parsedNode - Object to contain the processed properties @param {string} cursor - Path of the current node. Adds to refChain...do I need this? @param {string[]} [refChain=[]] - Parent pointers used to check circular references @param {string} [prop] - If provided returns an object just that prop parsed
[ "Main", "recursive", "traverse", "function" ]
1d534d68e5067b3de4bc98080f6e989187a684ca
https://github.com/ruifortes/json-deref/blob/1d534d68e5067b3de4bc98080f6e989187a684ca/src/index.js#L129-L224
train
camshaft/node-deploy-yml
index.js
getAll
function getAll(name, deploy, fn, single) { getTree(name, deploy, function(err, tree) { if (err) return fn(err); var acc = []; flatten(tree, acc); if (acc.length === 0) return fn(null); if (single && acc.length === 1) return fn(null, acc[0]); fn(err, acc); }); }
javascript
function getAll(name, deploy, fn, single) { getTree(name, deploy, function(err, tree) { if (err) return fn(err); var acc = []; flatten(tree, acc); if (acc.length === 0) return fn(null); if (single && acc.length === 1) return fn(null, acc[0]); fn(err, acc); }); }
[ "function", "getAll", "(", "name", ",", "deploy", ",", "fn", ",", "single", ")", "{", "getTree", "(", "name", ",", "deploy", ",", "function", "(", "err", ",", "tree", ")", "{", "if", "(", "err", ")", "return", "fn", "(", "err", ")", ";", "var", "acc", "=", "[", "]", ";", "flatten", "(", "tree", ",", "acc", ")", ";", "if", "(", "acc", ".", "length", "===", "0", ")", "return", "fn", "(", "null", ")", ";", "if", "(", "single", "&&", "acc", ".", "length", "===", "1", ")", "return", "fn", "(", "null", ",", "acc", "[", "0", "]", ")", ";", "fn", "(", "err", ",", "acc", ")", ";", "}", ")", ";", "}" ]
concats have to go all the way down the chain overrides work backwards and stop at first definition
[ "concats", "have", "to", "go", "all", "the", "way", "down", "the", "chain", "overrides", "work", "backwards", "and", "stop", "at", "first", "definition" ]
1c116f406b7e3c399bffec6732ea0fa1a52deb37
https://github.com/camshaft/node-deploy-yml/blob/1c116f406b7e3c399bffec6732ea0fa1a52deb37/index.js#L131-L140
train
georgenorman/tessel-kit
lib/tessel-utils.js
function(portKey) { var result = this.isValidPort(portKey) ? tessel.port[this.validLEDNames.indexOf(portKey)] : null; return result; }
javascript
function(portKey) { var result = this.isValidPort(portKey) ? tessel.port[this.validLEDNames.indexOf(portKey)] : null; return result; }
[ "function", "(", "portKey", ")", "{", "var", "result", "=", "this", ".", "isValidPort", "(", "portKey", ")", "?", "tessel", ".", "port", "[", "this", ".", "validLEDNames", ".", "indexOf", "(", "portKey", ")", "]", ":", "null", ";", "return", "result", ";", "}" ]
Return the Tessel port, if the given portKey is valid; otherwise, return null.
[ "Return", "the", "Tessel", "port", "if", "the", "given", "portKey", "is", "valid", ";", "otherwise", "return", "null", "." ]
487e91360f0ecf8500d24297228842e2c01ac762
https://github.com/georgenorman/tessel-kit/blob/487e91360f0ecf8500d24297228842e2c01ac762/lib/tessel-utils.js#L36-L40
train
georgenorman/tessel-kit
lib/tessel-utils.js
function(ledName) { var result = this.isValidLEDName(ledName) ? tessel.port[this.validLEDNames.indexOf(ledName)] : null; return result; }
javascript
function(ledName) { var result = this.isValidLEDName(ledName) ? tessel.port[this.validLEDNames.indexOf(ledName)] : null; return result; }
[ "function", "(", "ledName", ")", "{", "var", "result", "=", "this", ".", "isValidLEDName", "(", "ledName", ")", "?", "tessel", ".", "port", "[", "this", ".", "validLEDNames", ".", "indexOf", "(", "ledName", ")", "]", ":", "null", ";", "return", "result", ";", "}" ]
Return the Tessel LED, if the given LED name is valid; otherwise, return null.
[ "Return", "the", "Tessel", "LED", "if", "the", "given", "LED", "name", "is", "valid", ";", "otherwise", "return", "null", "." ]
487e91360f0ecf8500d24297228842e2c01ac762
https://github.com/georgenorman/tessel-kit/blob/487e91360f0ecf8500d24297228842e2c01ac762/lib/tessel-utils.js#L59-L63
train
LoveKino/cl-fsm
lib/nfa.js
function(startState) { let dfa = new DFA(); let stateMap = {}; let epsilonNFASetCache = {}; // NFA-set -> NFA-set let startOrigin = { [startState]: 1 }; let start = this.epsilonClosure(startOrigin); epsilonNFASetCache[hashNFAStates(startOrigin)] = start; let dfaStates = {}, newAdded = []; let last = 0, offset = 0; // distance between last state and current state dfaStates[hashNFAStates(start)] = 0; // default, the start state for DFA is 0 stateMap[0] = start; newAdded.push(start); while (newAdded.length) { let newAddedTmp = []; for (let i = 0, n = newAdded.length; i < n; i++) { let stateSet = newAdded[i]; let newMap = this._getNFASetTransitionMap(stateSet); let currentDFAState = i + offset; for (let letter in newMap) { let toSet = newMap[letter]; let hashKey = hashNFAStates(toSet); // find new state let newItem = null; if (epsilonNFASetCache[hashKey]) { newItem = epsilonNFASetCache[hashKey]; } else { newItem = this.epsilonClosure(newMap[letter]); } let newItemHashKey = hashNFAStates(newItem); // if (dfaStates[newItemHashKey] !== undefined) { dfa.addTransition(currentDFAState, letter, dfaStates[newItemHashKey]); } else { // find new item last++; // last + 1 as new DFA state dfaStates[newItemHashKey] = last; stateMap[last] = newItem; newAddedTmp.push(newItem); // build the connection from (index + offset) -> last dfa.addTransition(currentDFAState, letter, last); } } } offset += newAdded.length; newAdded = newAddedTmp; } return { dfa, stateMap }; }
javascript
function(startState) { let dfa = new DFA(); let stateMap = {}; let epsilonNFASetCache = {}; // NFA-set -> NFA-set let startOrigin = { [startState]: 1 }; let start = this.epsilonClosure(startOrigin); epsilonNFASetCache[hashNFAStates(startOrigin)] = start; let dfaStates = {}, newAdded = []; let last = 0, offset = 0; // distance between last state and current state dfaStates[hashNFAStates(start)] = 0; // default, the start state for DFA is 0 stateMap[0] = start; newAdded.push(start); while (newAdded.length) { let newAddedTmp = []; for (let i = 0, n = newAdded.length; i < n; i++) { let stateSet = newAdded[i]; let newMap = this._getNFASetTransitionMap(stateSet); let currentDFAState = i + offset; for (let letter in newMap) { let toSet = newMap[letter]; let hashKey = hashNFAStates(toSet); // find new state let newItem = null; if (epsilonNFASetCache[hashKey]) { newItem = epsilonNFASetCache[hashKey]; } else { newItem = this.epsilonClosure(newMap[letter]); } let newItemHashKey = hashNFAStates(newItem); // if (dfaStates[newItemHashKey] !== undefined) { dfa.addTransition(currentDFAState, letter, dfaStates[newItemHashKey]); } else { // find new item last++; // last + 1 as new DFA state dfaStates[newItemHashKey] = last; stateMap[last] = newItem; newAddedTmp.push(newItem); // build the connection from (index + offset) -> last dfa.addTransition(currentDFAState, letter, last); } } } offset += newAdded.length; newAdded = newAddedTmp; } return { dfa, stateMap }; }
[ "function", "(", "startState", ")", "{", "let", "dfa", "=", "new", "DFA", "(", ")", ";", "let", "stateMap", "=", "{", "}", ";", "let", "epsilonNFASetCache", "=", "{", "}", ";", "let", "startOrigin", "=", "{", "[", "startState", "]", ":", "1", "}", ";", "let", "start", "=", "this", ".", "epsilonClosure", "(", "startOrigin", ")", ";", "epsilonNFASetCache", "[", "hashNFAStates", "(", "startOrigin", ")", "]", "=", "start", ";", "let", "dfaStates", "=", "{", "}", ",", "newAdded", "=", "[", "]", ";", "let", "last", "=", "0", ",", "offset", "=", "0", ";", "dfaStates", "[", "hashNFAStates", "(", "start", ")", "]", "=", "0", ";", "stateMap", "[", "0", "]", "=", "start", ";", "newAdded", ".", "push", "(", "start", ")", ";", "while", "(", "newAdded", ".", "length", ")", "{", "let", "newAddedTmp", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ",", "n", "=", "newAdded", ".", "length", ";", "i", "<", "n", ";", "i", "++", ")", "{", "let", "stateSet", "=", "newAdded", "[", "i", "]", ";", "let", "newMap", "=", "this", ".", "_getNFASetTransitionMap", "(", "stateSet", ")", ";", "let", "currentDFAState", "=", "i", "+", "offset", ";", "for", "(", "let", "letter", "in", "newMap", ")", "{", "let", "toSet", "=", "newMap", "[", "letter", "]", ";", "let", "hashKey", "=", "hashNFAStates", "(", "toSet", ")", ";", "let", "newItem", "=", "null", ";", "if", "(", "epsilonNFASetCache", "[", "hashKey", "]", ")", "{", "newItem", "=", "epsilonNFASetCache", "[", "hashKey", "]", ";", "}", "else", "{", "newItem", "=", "this", ".", "epsilonClosure", "(", "newMap", "[", "letter", "]", ")", ";", "}", "let", "newItemHashKey", "=", "hashNFAStates", "(", "newItem", ")", ";", "if", "(", "dfaStates", "[", "newItemHashKey", "]", "!==", "undefined", ")", "{", "dfa", ".", "addTransition", "(", "currentDFAState", ",", "letter", ",", "dfaStates", "[", "newItemHashKey", "]", ")", ";", "}", "else", "{", "last", "++", ";", "dfaStates", "[", "newItemHashKey", "]", "=", "last", ";", "stateMap", "[", "last", "]", "=", "newItem", ";", "newAddedTmp", ".", "push", "(", "newItem", ")", ";", "dfa", ".", "addTransition", "(", "currentDFAState", ",", "letter", ",", "last", ")", ";", "}", "}", "}", "offset", "+=", "newAdded", ".", "length", ";", "newAdded", "=", "newAddedTmp", ";", "}", "return", "{", "dfa", ",", "stateMap", "}", ";", "}" ]
generate a new DFA and record which nfa states composed to a new DFA state
[ "generate", "a", "new", "DFA", "and", "record", "which", "nfa", "states", "composed", "to", "a", "new", "DFA", "state" ]
db7e8d5a5df6d10f285049d8f154c3f3a3f34211
https://github.com/LoveKino/cl-fsm/blob/db7e8d5a5df6d10f285049d8f154c3f3a3f34211/lib/nfa.js#L90-L153
train
yoshuawuyts/virtual-form
index.js
virtualForm
function virtualForm (h, opts, arr) { if (!arr) { arr = opts opts = {} } assert.equal(typeof h, 'function') assert.equal(typeof opts, 'object') assert.ok(Array.isArray(arr), 'is array') return arr.map(function createInput (val) { if (typeof val === 'string') { val = { type: 'text', name: val } } if (!val.value) val.value = '' assert.equal(typeof val, 'object') if (opts.label) { if (val.type === 'submit') return h('input', val) return h('fieldset', [ h('label', [ val.name ]), h('input', val) ]) } if (val.type !== 'submit' && !val.placeholder) { val.placeholder = val.name } return h('input', val) }) }
javascript
function virtualForm (h, opts, arr) { if (!arr) { arr = opts opts = {} } assert.equal(typeof h, 'function') assert.equal(typeof opts, 'object') assert.ok(Array.isArray(arr), 'is array') return arr.map(function createInput (val) { if (typeof val === 'string') { val = { type: 'text', name: val } } if (!val.value) val.value = '' assert.equal(typeof val, 'object') if (opts.label) { if (val.type === 'submit') return h('input', val) return h('fieldset', [ h('label', [ val.name ]), h('input', val) ]) } if (val.type !== 'submit' && !val.placeholder) { val.placeholder = val.name } return h('input', val) }) }
[ "function", "virtualForm", "(", "h", ",", "opts", ",", "arr", ")", "{", "if", "(", "!", "arr", ")", "{", "arr", "=", "opts", "opts", "=", "{", "}", "}", "assert", ".", "equal", "(", "typeof", "h", ",", "'function'", ")", "assert", ".", "equal", "(", "typeof", "opts", ",", "'object'", ")", "assert", ".", "ok", "(", "Array", ".", "isArray", "(", "arr", ")", ",", "'is array'", ")", "return", "arr", ".", "map", "(", "function", "createInput", "(", "val", ")", "{", "if", "(", "typeof", "val", "===", "'string'", ")", "{", "val", "=", "{", "type", ":", "'text'", ",", "name", ":", "val", "}", "}", "if", "(", "!", "val", ".", "value", ")", "val", ".", "value", "=", "''", "assert", ".", "equal", "(", "typeof", "val", ",", "'object'", ")", "if", "(", "opts", ".", "label", ")", "{", "if", "(", "val", ".", "type", "===", "'submit'", ")", "return", "h", "(", "'input'", ",", "val", ")", "return", "h", "(", "'fieldset'", ",", "[", "h", "(", "'label'", ",", "[", "val", ".", "name", "]", ")", ",", "h", "(", "'input'", ",", "val", ")", "]", ")", "}", "if", "(", "val", ".", "type", "!==", "'submit'", "&&", "!", "val", ".", "placeholder", ")", "{", "val", ".", "placeholder", "=", "val", ".", "name", "}", "return", "h", "(", "'input'", ",", "val", ")", "}", ")", "}" ]
Create a virtual-dom form null -> null
[ "Create", "a", "virtual", "-", "dom", "form", "null", "-", ">", "null" ]
acc64f437cccc8aa11681c2b8a042394b4844928
https://github.com/yoshuawuyts/virtual-form/blob/acc64f437cccc8aa11681c2b8a042394b4844928/index.js#L7-L38
train
Froguard/rgl-tplmin-loader
index.js
cleanRedundantCode
function cleanRedundantCode(str, opts){ opts = opts || {}; var minimize = def(opts.minimize, true); var comments = opts.comments || {}; var htmlComments = comments.html, rglComments = comments.rgl; if(minimize && typeof str === 'string'){ var SINGLE_SPACE = ' '; var EMPTY = ''; // remove html-comments <!-- xxx --> str = !htmlComments ? str.replace(/<!-[\s\S]*?-->/g, EMPTY) : str; // remove regular-comments {! xxx !} str = !rglComments ? str.replace(/{![\s\S]*?!}/g, EMPTY) : str; // 暴力全局替换\s,副作用:内容里面有带空格或回车的字符串会被替换截掉 // str = str.replace(/[\s]{2,}/g, SINGLE_SPACE); str = str.replace(/[\f\t\v]{2,}/g, SINGLE_SPACE); // // <abc>,<abc/> 左边 // str = str.replace(/[\s]{2,}(?=<\w+(\s[\s\S]*?)*?\/?>)/g, SINGLE_SPACE); // // </abc> 左边 // str = str.replace(/[\s]{2,}(?=<\/\w+>)/g, SINGLE_SPACE); // // // js并不支持'后行断言'(?<=condition)这种写法,这里只能采用callback函数来弥补 // // // <abc>,</abc>,<abc/>,/> 右边 // str = str.replace(/((?:<\/?\w+>)|(?:<\w+\/>)|(?:\/>))[\s]{2,}/g, function($0, $1){ // return ($1 ? ($ + SINGLE_SPACE) : $0); // }); // // 花括号左右 // str = str.replace(/[\s]+(?=(}|\{))/g, SINGLE_SPACE); // 左空格 // str = str.replace(/(}|\{)(\s+)/g, function($0, $1){ // 右空格 // return $1 + SINGLE_SPACE; // }); // // 大小于等号左右 // str = str.replace(/[\s]+(?=(>|<))/g, SINGLE_SPACE); // 左空格 // str = str.replace(/(>|<)(\s+)/g, function($0, $1){ // 右空格 // return $1 + SINGLE_SPACE; // }); // Last, trim str = str.trim(); } return str; }
javascript
function cleanRedundantCode(str, opts){ opts = opts || {}; var minimize = def(opts.minimize, true); var comments = opts.comments || {}; var htmlComments = comments.html, rglComments = comments.rgl; if(minimize && typeof str === 'string'){ var SINGLE_SPACE = ' '; var EMPTY = ''; // remove html-comments <!-- xxx --> str = !htmlComments ? str.replace(/<!-[\s\S]*?-->/g, EMPTY) : str; // remove regular-comments {! xxx !} str = !rglComments ? str.replace(/{![\s\S]*?!}/g, EMPTY) : str; // 暴力全局替换\s,副作用:内容里面有带空格或回车的字符串会被替换截掉 // str = str.replace(/[\s]{2,}/g, SINGLE_SPACE); str = str.replace(/[\f\t\v]{2,}/g, SINGLE_SPACE); // // <abc>,<abc/> 左边 // str = str.replace(/[\s]{2,}(?=<\w+(\s[\s\S]*?)*?\/?>)/g, SINGLE_SPACE); // // </abc> 左边 // str = str.replace(/[\s]{2,}(?=<\/\w+>)/g, SINGLE_SPACE); // // // js并不支持'后行断言'(?<=condition)这种写法,这里只能采用callback函数来弥补 // // // <abc>,</abc>,<abc/>,/> 右边 // str = str.replace(/((?:<\/?\w+>)|(?:<\w+\/>)|(?:\/>))[\s]{2,}/g, function($0, $1){ // return ($1 ? ($ + SINGLE_SPACE) : $0); // }); // // 花括号左右 // str = str.replace(/[\s]+(?=(}|\{))/g, SINGLE_SPACE); // 左空格 // str = str.replace(/(}|\{)(\s+)/g, function($0, $1){ // 右空格 // return $1 + SINGLE_SPACE; // }); // // 大小于等号左右 // str = str.replace(/[\s]+(?=(>|<))/g, SINGLE_SPACE); // 左空格 // str = str.replace(/(>|<)(\s+)/g, function($0, $1){ // 右空格 // return $1 + SINGLE_SPACE; // }); // Last, trim str = str.trim(); } return str; }
[ "function", "cleanRedundantCode", "(", "str", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "var", "minimize", "=", "def", "(", "opts", ".", "minimize", ",", "true", ")", ";", "var", "comments", "=", "opts", ".", "comments", "||", "{", "}", ";", "var", "htmlComments", "=", "comments", ".", "html", ",", "rglComments", "=", "comments", ".", "rgl", ";", "if", "(", "minimize", "&&", "typeof", "str", "===", "'string'", ")", "{", "var", "SINGLE_SPACE", "=", "' '", ";", "var", "EMPTY", "=", "''", ";", "str", "=", "!", "htmlComments", "?", "str", ".", "replace", "(", "/", "<!-[\\s\\S]*?", "/", "g", ",", "EMPTY", ")", ":", "str", ";", "str", "=", "!", "rglComments", "?", "str", ".", "replace", "(", "/", "{![\\s\\S]*?!}", "/", "g", ",", "EMPTY", ")", ":", "str", ";", "str", "=", "str", ".", "replace", "(", "/", "[\\f\\t\\v]{2,}", "/", "g", ",", "SINGLE_SPACE", ")", ";", "str", "=", "str", ".", "trim", "(", ")", ";", "}", "return", "str", ";", "}" ]
pure regEx to resolve it, not via a parser;
[ "pure", "regEx", "to", "resolve", "it", "not", "via", "a", "parser", ";" ]
74a8af5373cffe3998606dd89975cb0737e5014d
https://github.com/Froguard/rgl-tplmin-loader/blob/74a8af5373cffe3998606dd89975cb0737e5014d/index.js#L15-L63
train
dominictarr/npmd-unpack
index.js
getCache
function getCache (pkg, config) { pkg = toPkg(pkg) if(config && config.cacheHash) return path.join(config.cache, pkg.shasum, 'package.tgz') return path.join( config.cache || path.join(process.env.HOME, '.npm'), pkg.name, pkg.version, 'package.tgz' ) }
javascript
function getCache (pkg, config) { pkg = toPkg(pkg) if(config && config.cacheHash) return path.join(config.cache, pkg.shasum, 'package.tgz') return path.join( config.cache || path.join(process.env.HOME, '.npm'), pkg.name, pkg.version, 'package.tgz' ) }
[ "function", "getCache", "(", "pkg", ",", "config", ")", "{", "pkg", "=", "toPkg", "(", "pkg", ")", "if", "(", "config", "&&", "config", ".", "cacheHash", ")", "return", "path", ".", "join", "(", "config", ".", "cache", ",", "pkg", ".", "shasum", ",", "'package.tgz'", ")", "return", "path", ".", "join", "(", "config", ".", "cache", "||", "path", ".", "join", "(", "process", ".", "env", ".", "HOME", ",", "'.npm'", ")", ",", "pkg", ".", "name", ",", "pkg", ".", "version", ",", "'package.tgz'", ")", "}" ]
Would be better to store the tarball as it's hash, not it's version. that would allow exact shrinkwraps. Probably want to fallback to getting the other cache, for speed. But to pull down new deps... Also... hashes would allow peer to peer module hosting, and multiple repos...
[ "Would", "be", "better", "to", "store", "the", "tarball", "as", "it", "s", "hash", "not", "it", "s", "version", ".", "that", "would", "allow", "exact", "shrinkwraps", ".", "Probably", "want", "to", "fallback", "to", "getting", "the", "other", "cache", "for", "speed", ".", "But", "to", "pull", "down", "new", "deps", "...", "Also", "...", "hashes", "would", "allow", "peer", "to", "peer", "module", "hosting", "and", "multiple", "repos", "..." ]
5d6057ebf3413d256a2b2fc7724b4d7fbc424c53
https://github.com/dominictarr/npmd-unpack/blob/5d6057ebf3413d256a2b2fc7724b4d7fbc424c53/index.js#L44-L54
train
dominictarr/npmd-unpack
index.js
get
function get (url, cb) { var urls = [], end _get(url, cb) function _get (url) { urls.push(url) if(end) return if(urls.length > 5) cb(end = new Error('too many redirects\n'+JSON.stringify(urls))) console.error('GET', url) ;(/^https/.test(url) ? https : http).get(url, function next (res) { if(res.statusCode >= 300 && res.statusCode < 400) _get(res.headers.location) else { end = true, cb(null, res) } }) .on('error', function (err) { if(!end) cb(end = err) }) } }
javascript
function get (url, cb) { var urls = [], end _get(url, cb) function _get (url) { urls.push(url) if(end) return if(urls.length > 5) cb(end = new Error('too many redirects\n'+JSON.stringify(urls))) console.error('GET', url) ;(/^https/.test(url) ? https : http).get(url, function next (res) { if(res.statusCode >= 300 && res.statusCode < 400) _get(res.headers.location) else { end = true, cb(null, res) } }) .on('error', function (err) { if(!end) cb(end = err) }) } }
[ "function", "get", "(", "url", ",", "cb", ")", "{", "var", "urls", "=", "[", "]", ",", "end", "_get", "(", "url", ",", "cb", ")", "function", "_get", "(", "url", ")", "{", "urls", ".", "push", "(", "url", ")", "if", "(", "end", ")", "return", "if", "(", "urls", ".", "length", ">", "5", ")", "cb", "(", "end", "=", "new", "Error", "(", "'too many redirects\\n'", "+", "\\n", ")", ")", "JSON", ".", "stringify", "(", "urls", ")", "console", ".", "error", "(", "'GET'", ",", "url", ")", ";", "}", "}" ]
pull a package from the registry
[ "pull", "a", "package", "from", "the", "registry" ]
5d6057ebf3413d256a2b2fc7724b4d7fbc424c53
https://github.com/dominictarr/npmd-unpack/blob/5d6057ebf3413d256a2b2fc7724b4d7fbc424c53/index.js#L59-L83
train
dominictarr/npmd-unpack
index.js
getTarballStream
function getTarballStream (pkg, config, cb) { if(config.casDb && pkg.shasum) { var db = config.casDb db.has(pkg.shasum, function (err, stat) { if(!err) cb(null, db.getStream(pkg.shasum)) else //fallback to the old way... tryCache() }) } else tryCache() function tryCache () { var cache = getCache(pkg, config) fs.stat(cache, function (err) { if(!err) cb(null, fs.createReadStream(cache)) else getDownload(pkg, config, cb) }) } }
javascript
function getTarballStream (pkg, config, cb) { if(config.casDb && pkg.shasum) { var db = config.casDb db.has(pkg.shasum, function (err, stat) { if(!err) cb(null, db.getStream(pkg.shasum)) else //fallback to the old way... tryCache() }) } else tryCache() function tryCache () { var cache = getCache(pkg, config) fs.stat(cache, function (err) { if(!err) cb(null, fs.createReadStream(cache)) else getDownload(pkg, config, cb) }) } }
[ "function", "getTarballStream", "(", "pkg", ",", "config", ",", "cb", ")", "{", "if", "(", "config", ".", "casDb", "&&", "pkg", ".", "shasum", ")", "{", "var", "db", "=", "config", ".", "casDb", "db", ".", "has", "(", "pkg", ".", "shasum", ",", "function", "(", "err", ",", "stat", ")", "{", "if", "(", "!", "err", ")", "cb", "(", "null", ",", "db", ".", "getStream", "(", "pkg", ".", "shasum", ")", ")", "else", "tryCache", "(", ")", "}", ")", "}", "else", "tryCache", "(", ")", "function", "tryCache", "(", ")", "{", "var", "cache", "=", "getCache", "(", "pkg", ",", "config", ")", "fs", ".", "stat", "(", "cache", ",", "function", "(", "err", ")", "{", "if", "(", "!", "err", ")", "cb", "(", "null", ",", "fs", ".", "createReadStream", "(", "cache", ")", ")", "else", "getDownload", "(", "pkg", ",", "config", ",", "cb", ")", "}", ")", "}", "}" ]
stream a tarball - either from cache or registry
[ "stream", "a", "tarball", "-", "either", "from", "cache", "or", "registry" ]
5d6057ebf3413d256a2b2fc7724b4d7fbc424c53
https://github.com/dominictarr/npmd-unpack/blob/5d6057ebf3413d256a2b2fc7724b4d7fbc424c53/index.js#L111-L133
train
dominictarr/npmd-unpack
index.js
getTmp
function getTmp (config) { return path.join(config.tmpdir || '/tmp', ''+Date.now() + Math.random()) }
javascript
function getTmp (config) { return path.join(config.tmpdir || '/tmp', ''+Date.now() + Math.random()) }
[ "function", "getTmp", "(", "config", ")", "{", "return", "path", ".", "join", "(", "config", ".", "tmpdir", "||", "'/tmp'", ",", "''", "+", "Date", ".", "now", "(", ")", "+", "Math", ".", "random", "(", ")", ")", "}" ]
unpack a tarball to some target directory. recommend unpacking to tmpdir and then moving a following step. ALSO, should hash the file as we unpack it, and validate that we get the correct hash.
[ "unpack", "a", "tarball", "to", "some", "target", "directory", ".", "recommend", "unpacking", "to", "tmpdir", "and", "then", "moving", "a", "following", "step", ".", "ALSO", "should", "hash", "the", "file", "as", "we", "unpack", "it", "and", "validate", "that", "we", "get", "the", "correct", "hash", "." ]
5d6057ebf3413d256a2b2fc7724b4d7fbc424c53
https://github.com/dominictarr/npmd-unpack/blob/5d6057ebf3413d256a2b2fc7724b4d7fbc424c53/index.js#L140-L142
train
Wiredcraft/mixable-object
lib/mixin.js
mixin
function mixin(source) { var keys = []; if (arguments.length > 1) { for (var i = 1, len = arguments.length; i < len; i++) { var key = arguments[i]; if (!source.hasOwnProperty(key)) { throw new Error(util.format('Property not found: %s', key)); } keys.push(key); } } else { keys = Object.keys(source); } // Copy. for (var i = 0, len = keys.length; i < len; i++) { key = keys[i]; defineProp(this, key, descriptor(source, key)); } return this; }
javascript
function mixin(source) { var keys = []; if (arguments.length > 1) { for (var i = 1, len = arguments.length; i < len; i++) { var key = arguments[i]; if (!source.hasOwnProperty(key)) { throw new Error(util.format('Property not found: %s', key)); } keys.push(key); } } else { keys = Object.keys(source); } // Copy. for (var i = 0, len = keys.length; i < len; i++) { key = keys[i]; defineProp(this, key, descriptor(source, key)); } return this; }
[ "function", "mixin", "(", "source", ")", "{", "var", "keys", "=", "[", "]", ";", "if", "(", "arguments", ".", "length", ">", "1", ")", "{", "for", "(", "var", "i", "=", "1", ",", "len", "=", "arguments", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "key", "=", "arguments", "[", "i", "]", ";", "if", "(", "!", "source", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "throw", "new", "Error", "(", "util", ".", "format", "(", "'Property not found: %s'", ",", "key", ")", ")", ";", "}", "keys", ".", "push", "(", "key", ")", ";", "}", "}", "else", "{", "keys", "=", "Object", ".", "keys", "(", "source", ")", ";", "}", "for", "(", "var", "i", "=", "0", ",", "len", "=", "keys", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "key", "=", "keys", "[", "i", "]", ";", "defineProp", "(", "this", ",", "key", ",", "descriptor", "(", "source", ",", "key", ")", ")", ";", "}", "return", "this", ";", "}" ]
The common mixin, simply copies properties, by redefining the same properties from the source. @param {Object} source @param {Mixed} ...keys if given only the attributes with the keys are copied @return {this}
[ "The", "common", "mixin", "simply", "copies", "properties", "by", "redefining", "the", "same", "properties", "from", "the", "source", "." ]
1ddb656ab11399b8cffbbf300b51bd334a1a77e1
https://github.com/Wiredcraft/mixable-object/blob/1ddb656ab11399b8cffbbf300b51bd334a1a77e1/lib/mixin.js#L15-L34
train
wigy/chronicles_of_grunt
tasks/build.js
subst
function subst(str, file, dst) { if (dst !== undefined) { str = str.replace(/\{\{DST\}\}/g, dst); } var dir = path.dirname(file); str = str.replace(/\{\{SRC\}\}/g, file); var name = path.basename(file); str = str.replace(/\{\{NAME\}\}/g, name); name = name.replace(/\.\w+$/, ''); str = str.replace(/\{\{BASENAME\}\}/g, name); str = str.replace(/\{\{DIR\}\}/g, dir); var parts = dir.split(path.sep); parts.splice(0, 1); str = str.replace(/\{\{SUBDIR\}\}/g, path.join.apply(null, parts)); parts.splice(0, 1); str = str.replace(/\{\{SUBSUBDIR\}\}/g, path.join.apply(null, parts)); return str; }
javascript
function subst(str, file, dst) { if (dst !== undefined) { str = str.replace(/\{\{DST\}\}/g, dst); } var dir = path.dirname(file); str = str.replace(/\{\{SRC\}\}/g, file); var name = path.basename(file); str = str.replace(/\{\{NAME\}\}/g, name); name = name.replace(/\.\w+$/, ''); str = str.replace(/\{\{BASENAME\}\}/g, name); str = str.replace(/\{\{DIR\}\}/g, dir); var parts = dir.split(path.sep); parts.splice(0, 1); str = str.replace(/\{\{SUBDIR\}\}/g, path.join.apply(null, parts)); parts.splice(0, 1); str = str.replace(/\{\{SUBSUBDIR\}\}/g, path.join.apply(null, parts)); return str; }
[ "function", "subst", "(", "str", ",", "file", ",", "dst", ")", "{", "if", "(", "dst", "!==", "undefined", ")", "{", "str", "=", "str", ".", "replace", "(", "/", "\\{\\{DST\\}\\}", "/", "g", ",", "dst", ")", ";", "}", "var", "dir", "=", "path", ".", "dirname", "(", "file", ")", ";", "str", "=", "str", ".", "replace", "(", "/", "\\{\\{SRC\\}\\}", "/", "g", ",", "file", ")", ";", "var", "name", "=", "path", ".", "basename", "(", "file", ")", ";", "str", "=", "str", ".", "replace", "(", "/", "\\{\\{NAME\\}\\}", "/", "g", ",", "name", ")", ";", "name", "=", "name", ".", "replace", "(", "/", "\\.\\w+$", "/", ",", "''", ")", ";", "str", "=", "str", ".", "replace", "(", "/", "\\{\\{BASENAME\\}\\}", "/", "g", ",", "name", ")", ";", "str", "=", "str", ".", "replace", "(", "/", "\\{\\{DIR\\}\\}", "/", "g", ",", "dir", ")", ";", "var", "parts", "=", "dir", ".", "split", "(", "path", ".", "sep", ")", ";", "parts", ".", "splice", "(", "0", ",", "1", ")", ";", "str", "=", "str", ".", "replace", "(", "/", "\\{\\{SUBDIR\\}\\}", "/", "g", ",", "path", ".", "join", ".", "apply", "(", "null", ",", "parts", ")", ")", ";", "parts", ".", "splice", "(", "0", ",", "1", ")", ";", "str", "=", "str", ".", "replace", "(", "/", "\\{\\{SUBSUBDIR\\}\\}", "/", "g", ",", "path", ".", "join", ".", "apply", "(", "null", ",", "parts", ")", ")", ";", "return", "str", ";", "}" ]
Support function to substitute path variables.
[ "Support", "function", "to", "substitute", "path", "variables", "." ]
c5f089a6f391a0ca625fcb81ef51907713471bb3
https://github.com/wigy/chronicles_of_grunt/blob/c5f089a6f391a0ca625fcb81ef51907713471bb3/tasks/build.js#L57-L74
train
Chieze-Franklin/bolt-internal-checks
checks.js
function(request, response, next){ if (utils.Misc.isEmptyObject(request.query)) { var errApp = new Error(errors['130']); response.end(utils.Misc.createResponse(null, errApp, 130)); } else { next(); } }
javascript
function(request, response, next){ if (utils.Misc.isEmptyObject(request.query)) { var errApp = new Error(errors['130']); response.end(utils.Misc.createResponse(null, errApp, 130)); } else { next(); } }
[ "function", "(", "request", ",", "response", ",", "next", ")", "{", "if", "(", "utils", ".", "Misc", ".", "isEmptyObject", "(", "request", ".", "query", ")", ")", "{", "var", "errApp", "=", "new", "Error", "(", "errors", "[", "'130'", "]", ")", ";", "response", ".", "end", "(", "utils", ".", "Misc", ".", "createResponse", "(", "null", ",", "errApp", ",", "130", ")", ")", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}" ]
checks to be sure a criterion was specified for a bulk update operation
[ "checks", "to", "be", "sure", "a", "criterion", "was", "specified", "for", "a", "bulk", "update", "operation" ]
f1a7ccea701ec3e69f9bad0e0d6cf2efa6ee2225
https://github.com/Chieze-Franklin/bolt-internal-checks/blob/f1a7ccea701ec3e69f9bad0e0d6cf2efa6ee2225/checks.js#L81-L89
train
Chieze-Franklin/bolt-internal-checks
checks.js
function(request, response, next){ if (!utils.Misc.isNullOrUndefined(request.user)) { next(); } else { var error = new Error(errors['213']); response.end(utils.Misc.createResponse(null, error, 213)); } }
javascript
function(request, response, next){ if (!utils.Misc.isNullOrUndefined(request.user)) { next(); } else { var error = new Error(errors['213']); response.end(utils.Misc.createResponse(null, error, 213)); } }
[ "function", "(", "request", ",", "response", ",", "next", ")", "{", "if", "(", "!", "utils", ".", "Misc", ".", "isNullOrUndefined", "(", "request", ".", "user", ")", ")", "{", "next", "(", ")", ";", "}", "else", "{", "var", "error", "=", "new", "Error", "(", "errors", "[", "'213'", "]", ")", ";", "response", ".", "end", "(", "utils", ".", "Misc", ".", "createResponse", "(", "null", ",", "error", ",", "213", ")", ")", ";", "}", "}" ]
checks for logged-in user
[ "checks", "for", "logged", "-", "in", "user" ]
f1a7ccea701ec3e69f9bad0e0d6cf2efa6ee2225
https://github.com/Chieze-Franklin/bolt-internal-checks/blob/f1a7ccea701ec3e69f9bad0e0d6cf2efa6ee2225/checks.js#L91-L99
train
Chieze-Franklin/bolt-internal-checks
checks.js
function(request, response, next){ if (!utils.Misc.isNullOrUndefined(request.user) || request.originalUrl == '/error' || request.originalUrl.indexOf('/error?') == 0) { next(); } else { var success = encodeURIComponent(request.protocol + '://' + request.get('host') + request.originalUrl); response.redirect('/login?success=' + success + '&no_query=true'); //we don't want it to add any query string } }
javascript
function(request, response, next){ if (!utils.Misc.isNullOrUndefined(request.user) || request.originalUrl == '/error' || request.originalUrl.indexOf('/error?') == 0) { next(); } else { var success = encodeURIComponent(request.protocol + '://' + request.get('host') + request.originalUrl); response.redirect('/login?success=' + success + '&no_query=true'); //we don't want it to add any query string } }
[ "function", "(", "request", ",", "response", ",", "next", ")", "{", "if", "(", "!", "utils", ".", "Misc", ".", "isNullOrUndefined", "(", "request", ".", "user", ")", "||", "request", ".", "originalUrl", "==", "'/error'", "||", "request", ".", "originalUrl", ".", "indexOf", "(", "'/error?'", ")", "==", "0", ")", "{", "next", "(", ")", ";", "}", "else", "{", "var", "success", "=", "encodeURIComponent", "(", "request", ".", "protocol", "+", "'://'", "+", "request", ".", "get", "(", "'host'", ")", "+", "request", ".", "originalUrl", ")", ";", "response", ".", "redirect", "(", "'/login?success='", "+", "success", "+", "'&no_query=true'", ")", ";", "}", "}" ]
checks for logged-in UI user
[ "checks", "for", "logged", "-", "in", "UI", "user" ]
f1a7ccea701ec3e69f9bad0e0d6cf2efa6ee2225
https://github.com/Chieze-Franklin/bolt-internal-checks/blob/f1a7ccea701ec3e69f9bad0e0d6cf2efa6ee2225/checks.js#L101-L109
train
Chieze-Franklin/bolt-internal-checks
checks.js
function(request, response, next){ var apptkn; if (!utils.Misc.isNullOrUndefined(request.get(X_BOLT_APP_TOKEN))) { apptkn = request.get(X_BOLT_APP_TOKEN); } else { var error = new Error(errors['110']); response.end(utils.Misc.createResponse(null, error, 110)); return; } var name = __getAppFromAppToken(apptkn, request); if (utils.Misc.isNullOrUndefined(name)) { var error = new Error(errors['113']); response.end(utils.Misc.createResponse(null, error, 113)); return; } var appnm = utils.String.trim(name.toLowerCase()); if (appnm == 'bolt') { //native views next(); } else { models.app.findOne({ name: appnm, system: true }, function(appError, app){ if (!utils.Misc.isNullOrUndefined(appError)) { response.end(utils.Misc.createResponse(null, appError)); } else if(utils.Misc.isNullOrUndefined(app)){ var error = new Error(errors['504']); response.end(utils.Misc.createResponse(null, error, 504)); } else{ next(); } }); } }
javascript
function(request, response, next){ var apptkn; if (!utils.Misc.isNullOrUndefined(request.get(X_BOLT_APP_TOKEN))) { apptkn = request.get(X_BOLT_APP_TOKEN); } else { var error = new Error(errors['110']); response.end(utils.Misc.createResponse(null, error, 110)); return; } var name = __getAppFromAppToken(apptkn, request); if (utils.Misc.isNullOrUndefined(name)) { var error = new Error(errors['113']); response.end(utils.Misc.createResponse(null, error, 113)); return; } var appnm = utils.String.trim(name.toLowerCase()); if (appnm == 'bolt') { //native views next(); } else { models.app.findOne({ name: appnm, system: true }, function(appError, app){ if (!utils.Misc.isNullOrUndefined(appError)) { response.end(utils.Misc.createResponse(null, appError)); } else if(utils.Misc.isNullOrUndefined(app)){ var error = new Error(errors['504']); response.end(utils.Misc.createResponse(null, error, 504)); } else{ next(); } }); } }
[ "function", "(", "request", ",", "response", ",", "next", ")", "{", "var", "apptkn", ";", "if", "(", "!", "utils", ".", "Misc", ".", "isNullOrUndefined", "(", "request", ".", "get", "(", "X_BOLT_APP_TOKEN", ")", ")", ")", "{", "apptkn", "=", "request", ".", "get", "(", "X_BOLT_APP_TOKEN", ")", ";", "}", "else", "{", "var", "error", "=", "new", "Error", "(", "errors", "[", "'110'", "]", ")", ";", "response", ".", "end", "(", "utils", ".", "Misc", ".", "createResponse", "(", "null", ",", "error", ",", "110", ")", ")", ";", "return", ";", "}", "var", "name", "=", "__getAppFromAppToken", "(", "apptkn", ",", "request", ")", ";", "if", "(", "utils", ".", "Misc", ".", "isNullOrUndefined", "(", "name", ")", ")", "{", "var", "error", "=", "new", "Error", "(", "errors", "[", "'113'", "]", ")", ";", "response", ".", "end", "(", "utils", ".", "Misc", ".", "createResponse", "(", "null", ",", "error", ",", "113", ")", ")", ";", "return", ";", "}", "var", "appnm", "=", "utils", ".", "String", ".", "trim", "(", "name", ".", "toLowerCase", "(", ")", ")", ";", "if", "(", "appnm", "==", "'bolt'", ")", "{", "next", "(", ")", ";", "}", "else", "{", "models", ".", "app", ".", "findOne", "(", "{", "name", ":", "appnm", ",", "system", ":", "true", "}", ",", "function", "(", "appError", ",", "app", ")", "{", "if", "(", "!", "utils", ".", "Misc", ".", "isNullOrUndefined", "(", "appError", ")", ")", "{", "response", ".", "end", "(", "utils", ".", "Misc", ".", "createResponse", "(", "null", ",", "appError", ")", ")", ";", "}", "else", "if", "(", "utils", ".", "Misc", ".", "isNullOrUndefined", "(", "app", ")", ")", "{", "var", "error", "=", "new", "Error", "(", "errors", "[", "'504'", "]", ")", ";", "response", ".", "end", "(", "utils", ".", "Misc", ".", "createResponse", "(", "null", ",", "error", ",", "504", ")", ")", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}", ")", ";", "}", "}" ]
checks to be sure the app making this request is a system app
[ "checks", "to", "be", "sure", "the", "app", "making", "this", "request", "is", "a", "system", "app" ]
f1a7ccea701ec3e69f9bad0e0d6cf2efa6ee2225
https://github.com/Chieze-Franklin/bolt-internal-checks/blob/f1a7ccea701ec3e69f9bad0e0d6cf2efa6ee2225/checks.js#L111-L150
train
Chieze-Franklin/bolt-internal-checks
checks.js
function(request, response, next){ var apptkn; if (!utils.Misc.isNullOrUndefined(request.get(X_BOLT_APP_TOKEN))) { apptkn = request.get(X_BOLT_APP_TOKEN); } else { var error = new Error(errors['110']); response.end(utils.Misc.createResponse(null, error, 110)); return; } var name = __getAppFromAppToken(apptkn, request); if (utils.Misc.isNullOrUndefined(name)) { var error = new Error(errors['113']); response.end(utils.Misc.createResponse(null, error, 113)); return; } var appnm = utils.String.trim(name.toLowerCase()); request.appName = appnm; next(); }
javascript
function(request, response, next){ var apptkn; if (!utils.Misc.isNullOrUndefined(request.get(X_BOLT_APP_TOKEN))) { apptkn = request.get(X_BOLT_APP_TOKEN); } else { var error = new Error(errors['110']); response.end(utils.Misc.createResponse(null, error, 110)); return; } var name = __getAppFromAppToken(apptkn, request); if (utils.Misc.isNullOrUndefined(name)) { var error = new Error(errors['113']); response.end(utils.Misc.createResponse(null, error, 113)); return; } var appnm = utils.String.trim(name.toLowerCase()); request.appName = appnm; next(); }
[ "function", "(", "request", ",", "response", ",", "next", ")", "{", "var", "apptkn", ";", "if", "(", "!", "utils", ".", "Misc", ".", "isNullOrUndefined", "(", "request", ".", "get", "(", "X_BOLT_APP_TOKEN", ")", ")", ")", "{", "apptkn", "=", "request", ".", "get", "(", "X_BOLT_APP_TOKEN", ")", ";", "}", "else", "{", "var", "error", "=", "new", "Error", "(", "errors", "[", "'110'", "]", ")", ";", "response", ".", "end", "(", "utils", ".", "Misc", ".", "createResponse", "(", "null", ",", "error", ",", "110", ")", ")", ";", "return", ";", "}", "var", "name", "=", "__getAppFromAppToken", "(", "apptkn", ",", "request", ")", ";", "if", "(", "utils", ".", "Misc", ".", "isNullOrUndefined", "(", "name", ")", ")", "{", "var", "error", "=", "new", "Error", "(", "errors", "[", "'113'", "]", ")", ";", "response", ".", "end", "(", "utils", ".", "Misc", ".", "createResponse", "(", "null", ",", "error", ",", "113", ")", ")", ";", "return", ";", "}", "var", "appnm", "=", "utils", ".", "String", ".", "trim", "(", "name", ".", "toLowerCase", "(", ")", ")", ";", "request", ".", "appName", "=", "appnm", ";", "next", "(", ")", ";", "}" ]
gets the app name from the request
[ "gets", "the", "app", "name", "from", "the", "request" ]
f1a7ccea701ec3e69f9bad0e0d6cf2efa6ee2225
https://github.com/Chieze-Franklin/bolt-internal-checks/blob/f1a7ccea701ec3e69f9bad0e0d6cf2efa6ee2225/checks.js#L153-L174
train
Chieze-Franklin/bolt-internal-checks
checks.js
function(request, response, next){ if (!utils.Misc.isNullOrUndefined(request.body.db)) { request.db = request.body.db; } else if (!utils.Misc.isNullOrUndefined(request.body.app)) { request.db = request.body.app; } else { var apptkn; if (!utils.Misc.isNullOrUndefined(request.get(X_BOLT_APP_TOKEN))) { apptkn = request.get(X_BOLT_APP_TOKEN); } else { var error = new Error(errors['110']); response.end(utils.Misc.createResponse(null, error, 110)); return; } var name = __getAppFromAppToken(apptkn, request); if (utils.Misc.isNullOrUndefined(name)) { var error = new Error(errors['113']); response.end(utils.Misc.createResponse(null, error, 113)); return; } var appnm = utils.String.trim(name.toLowerCase()); request.db = appnm; } if (request.db.indexOf('/') > -1 || request.db.indexOf('\\') > -1 || request.db.indexOf('?') > -1 || request.db.indexOf('&') > -1) { //invalid characters in app name var error = new Error(errors['405']); response.end(utils.Misc.createResponse(null, error, 405)); return; } next(); }
javascript
function(request, response, next){ if (!utils.Misc.isNullOrUndefined(request.body.db)) { request.db = request.body.db; } else if (!utils.Misc.isNullOrUndefined(request.body.app)) { request.db = request.body.app; } else { var apptkn; if (!utils.Misc.isNullOrUndefined(request.get(X_BOLT_APP_TOKEN))) { apptkn = request.get(X_BOLT_APP_TOKEN); } else { var error = new Error(errors['110']); response.end(utils.Misc.createResponse(null, error, 110)); return; } var name = __getAppFromAppToken(apptkn, request); if (utils.Misc.isNullOrUndefined(name)) { var error = new Error(errors['113']); response.end(utils.Misc.createResponse(null, error, 113)); return; } var appnm = utils.String.trim(name.toLowerCase()); request.db = appnm; } if (request.db.indexOf('/') > -1 || request.db.indexOf('\\') > -1 || request.db.indexOf('?') > -1 || request.db.indexOf('&') > -1) { //invalid characters in app name var error = new Error(errors['405']); response.end(utils.Misc.createResponse(null, error, 405)); return; } next(); }
[ "function", "(", "request", ",", "response", ",", "next", ")", "{", "if", "(", "!", "utils", ".", "Misc", ".", "isNullOrUndefined", "(", "request", ".", "body", ".", "db", ")", ")", "{", "request", ".", "db", "=", "request", ".", "body", ".", "db", ";", "}", "else", "if", "(", "!", "utils", ".", "Misc", ".", "isNullOrUndefined", "(", "request", ".", "body", ".", "app", ")", ")", "{", "request", ".", "db", "=", "request", ".", "body", ".", "app", ";", "}", "else", "{", "var", "apptkn", ";", "if", "(", "!", "utils", ".", "Misc", ".", "isNullOrUndefined", "(", "request", ".", "get", "(", "X_BOLT_APP_TOKEN", ")", ")", ")", "{", "apptkn", "=", "request", ".", "get", "(", "X_BOLT_APP_TOKEN", ")", ";", "}", "else", "{", "var", "error", "=", "new", "Error", "(", "errors", "[", "'110'", "]", ")", ";", "response", ".", "end", "(", "utils", ".", "Misc", ".", "createResponse", "(", "null", ",", "error", ",", "110", ")", ")", ";", "return", ";", "}", "var", "name", "=", "__getAppFromAppToken", "(", "apptkn", ",", "request", ")", ";", "if", "(", "utils", ".", "Misc", ".", "isNullOrUndefined", "(", "name", ")", ")", "{", "var", "error", "=", "new", "Error", "(", "errors", "[", "'113'", "]", ")", ";", "response", ".", "end", "(", "utils", ".", "Misc", ".", "createResponse", "(", "null", ",", "error", ",", "113", ")", ")", ";", "return", ";", "}", "var", "appnm", "=", "utils", ".", "String", ".", "trim", "(", "name", ".", "toLowerCase", "(", ")", ")", ";", "request", ".", "db", "=", "appnm", ";", "}", "if", "(", "request", ".", "db", ".", "indexOf", "(", "'/'", ")", ">", "-", "1", "||", "request", ".", "db", ".", "indexOf", "(", "'\\\\'", ")", ">", "\\\\", "||", "-", "1", "||", "request", ".", "db", ".", "indexOf", "(", "'?'", ")", ">", "-", "1", ")", "request", ".", "db", ".", "indexOf", "(", "'&'", ")", ">", "-", "1", "{", "var", "error", "=", "new", "Error", "(", "errors", "[", "'405'", "]", ")", ";", "response", ".", "end", "(", "utils", ".", "Misc", ".", "createResponse", "(", "null", ",", "error", ",", "405", ")", ")", ";", "return", ";", "}", "}" ]
gets the DB name from the request, and creates the request.db field to hold the value
[ "gets", "the", "DB", "name", "from", "the", "request", "and", "creates", "the", "request", ".", "db", "field", "to", "hold", "the", "value" ]
f1a7ccea701ec3e69f9bad0e0d6cf2efa6ee2225
https://github.com/Chieze-Franklin/bolt-internal-checks/blob/f1a7ccea701ec3e69f9bad0e0d6cf2efa6ee2225/checks.js#L242-L278
train
Chieze-Franklin/bolt-internal-checks
checks.js
function(request, response, next) { var apptkn; if (!utils.Misc.isNullOrUndefined(request.get(X_BOLT_APP_TOKEN))) { apptkn = request.get(X_BOLT_APP_TOKEN); } else { var error = new Error(errors['110']); response.end(utils.Misc.createResponse(null, error, 110)); return; } var name = __getAppFromAppToken(apptkn, request); if (utils.Misc.isNullOrUndefined(name)) { var error = new Error(errors['113']); response.end(utils.Misc.createResponse(null, error, 113)); return; } var appnm = utils.String.trim(name.toLowerCase()); var dbOwner = request.body.db || request.body.app || appnm; models.collection.findOne({ name: request.params.collection, app: dbOwner }, function(collError, collection){ if (!utils.Misc.isNullOrUndefined(collError)){ response.end(utils.Misc.createResponse(null, collError)); } else if(utils.Misc.isNullOrUndefined(collection)){ var errColl = new Error(errors['703']); response.end(utils.Misc.createResponse(null, errColl, 703)); } else { //allow the owner to pass if (appnm == collection.app.toLowerCase()) { next(); return; } if (!utils.Misc.isNullOrUndefined(collection.tenants)) { //tenants allowed if ("*" == collection.tenants) { //every body is allowed next(); return; } //there is a tenant list; are u listed? else if (collection.tenants.map(function(value){ return value.toLowerCase(); }).indexOf(appnm) > -1) { next(); return; } } //no guests allowed var error = new Error(errors['704']); response.end(utils.Misc.createResponse(null, error, 704)); } }); }
javascript
function(request, response, next) { var apptkn; if (!utils.Misc.isNullOrUndefined(request.get(X_BOLT_APP_TOKEN))) { apptkn = request.get(X_BOLT_APP_TOKEN); } else { var error = new Error(errors['110']); response.end(utils.Misc.createResponse(null, error, 110)); return; } var name = __getAppFromAppToken(apptkn, request); if (utils.Misc.isNullOrUndefined(name)) { var error = new Error(errors['113']); response.end(utils.Misc.createResponse(null, error, 113)); return; } var appnm = utils.String.trim(name.toLowerCase()); var dbOwner = request.body.db || request.body.app || appnm; models.collection.findOne({ name: request.params.collection, app: dbOwner }, function(collError, collection){ if (!utils.Misc.isNullOrUndefined(collError)){ response.end(utils.Misc.createResponse(null, collError)); } else if(utils.Misc.isNullOrUndefined(collection)){ var errColl = new Error(errors['703']); response.end(utils.Misc.createResponse(null, errColl, 703)); } else { //allow the owner to pass if (appnm == collection.app.toLowerCase()) { next(); return; } if (!utils.Misc.isNullOrUndefined(collection.tenants)) { //tenants allowed if ("*" == collection.tenants) { //every body is allowed next(); return; } //there is a tenant list; are u listed? else if (collection.tenants.map(function(value){ return value.toLowerCase(); }).indexOf(appnm) > -1) { next(); return; } } //no guests allowed var error = new Error(errors['704']); response.end(utils.Misc.createResponse(null, error, 704)); } }); }
[ "function", "(", "request", ",", "response", ",", "next", ")", "{", "var", "apptkn", ";", "if", "(", "!", "utils", ".", "Misc", ".", "isNullOrUndefined", "(", "request", ".", "get", "(", "X_BOLT_APP_TOKEN", ")", ")", ")", "{", "apptkn", "=", "request", ".", "get", "(", "X_BOLT_APP_TOKEN", ")", ";", "}", "else", "{", "var", "error", "=", "new", "Error", "(", "errors", "[", "'110'", "]", ")", ";", "response", ".", "end", "(", "utils", ".", "Misc", ".", "createResponse", "(", "null", ",", "error", ",", "110", ")", ")", ";", "return", ";", "}", "var", "name", "=", "__getAppFromAppToken", "(", "apptkn", ",", "request", ")", ";", "if", "(", "utils", ".", "Misc", ".", "isNullOrUndefined", "(", "name", ")", ")", "{", "var", "error", "=", "new", "Error", "(", "errors", "[", "'113'", "]", ")", ";", "response", ".", "end", "(", "utils", ".", "Misc", ".", "createResponse", "(", "null", ",", "error", ",", "113", ")", ")", ";", "return", ";", "}", "var", "appnm", "=", "utils", ".", "String", ".", "trim", "(", "name", ".", "toLowerCase", "(", ")", ")", ";", "var", "dbOwner", "=", "request", ".", "body", ".", "db", "||", "request", ".", "body", ".", "app", "||", "appnm", ";", "models", ".", "collection", ".", "findOne", "(", "{", "name", ":", "request", ".", "params", ".", "collection", ",", "app", ":", "dbOwner", "}", ",", "function", "(", "collError", ",", "collection", ")", "{", "if", "(", "!", "utils", ".", "Misc", ".", "isNullOrUndefined", "(", "collError", ")", ")", "{", "response", ".", "end", "(", "utils", ".", "Misc", ".", "createResponse", "(", "null", ",", "collError", ")", ")", ";", "}", "else", "if", "(", "utils", ".", "Misc", ".", "isNullOrUndefined", "(", "collection", ")", ")", "{", "var", "errColl", "=", "new", "Error", "(", "errors", "[", "'703'", "]", ")", ";", "response", ".", "end", "(", "utils", ".", "Misc", ".", "createResponse", "(", "null", ",", "errColl", ",", "703", ")", ")", ";", "}", "else", "{", "if", "(", "appnm", "==", "collection", ".", "app", ".", "toLowerCase", "(", ")", ")", "{", "next", "(", ")", ";", "return", ";", "}", "if", "(", "!", "utils", ".", "Misc", ".", "isNullOrUndefined", "(", "collection", ".", "tenants", ")", ")", "{", "if", "(", "\"*\"", "==", "collection", ".", "tenants", ")", "{", "next", "(", ")", ";", "return", ";", "}", "else", "if", "(", "collection", ".", "tenants", ".", "map", "(", "function", "(", "value", ")", "{", "return", "value", ".", "toLowerCase", "(", ")", ";", "}", ")", ".", "indexOf", "(", "appnm", ")", ">", "-", "1", ")", "{", "next", "(", ")", ";", "return", ";", "}", "}", "var", "error", "=", "new", "Error", "(", "errors", "[", "'704'", "]", ")", ";", "response", ".", "end", "(", "utils", ".", "Misc", ".", "createResponse", "(", "null", ",", "error", ",", "704", ")", ")", ";", "}", "}", ")", ";", "}" ]
checks if this app has the right to write to the collection in the database
[ "checks", "if", "this", "app", "has", "the", "right", "to", "write", "to", "the", "collection", "in", "the", "database" ]
f1a7ccea701ec3e69f9bad0e0d6cf2efa6ee2225
https://github.com/Chieze-Franklin/bolt-internal-checks/blob/f1a7ccea701ec3e69f9bad0e0d6cf2efa6ee2225/checks.js#L280-L333
train
dignifiedquire/node-inotifyr
lib/bits.js
toBitMask
function toBitMask(event) { if (!_.has(eventMap, event)) { throw new Error('Unkown event: ' + event); } return eventMap[event]; }
javascript
function toBitMask(event) { if (!_.has(eventMap, event)) { throw new Error('Unkown event: ' + event); } return eventMap[event]; }
[ "function", "toBitMask", "(", "event", ")", "{", "if", "(", "!", "_", ".", "has", "(", "eventMap", ",", "event", ")", ")", "{", "throw", "new", "Error", "(", "'Unkown event: '", "+", "event", ")", ";", "}", "return", "eventMap", "[", "event", "]", ";", "}" ]
Convert a string to the corresponding bit mask. event - String Returns a binary number.
[ "Convert", "a", "string", "to", "the", "corresponding", "bit", "mask", ".", "event", "-", "String", "Returns", "a", "binary", "number", "." ]
6d161fed38c6d30951c46055939a5a2915304a53
https://github.com/dignifiedquire/node-inotifyr/blob/6d161fed38c6d30951c46055939a5a2915304a53/lib/bits.js#L37-L42
train
dignifiedquire/node-inotifyr
lib/bits.js
addFlags
function addFlags(mask, flags) { if (flags.onlydir) mask = mask | Inotify.IN_ONLYDIR; if (flags.dont_follow) mask = mask | Inotify.IN_DONT_FOLLOW; if (flags.oneshot) mask = mask | Inotify.IN_ONESHOT; return mask; }
javascript
function addFlags(mask, flags) { if (flags.onlydir) mask = mask | Inotify.IN_ONLYDIR; if (flags.dont_follow) mask = mask | Inotify.IN_DONT_FOLLOW; if (flags.oneshot) mask = mask | Inotify.IN_ONESHOT; return mask; }
[ "function", "addFlags", "(", "mask", ",", "flags", ")", "{", "if", "(", "flags", ".", "onlydir", ")", "mask", "=", "mask", "|", "Inotify", ".", "IN_ONLYDIR", ";", "if", "(", "flags", ".", "dont_follow", ")", "mask", "=", "mask", "|", "Inotify", ".", "IN_DONT_FOLLOW", ";", "if", "(", "flags", ".", "oneshot", ")", "mask", "=", "mask", "|", "Inotify", ".", "IN_ONESHOT", ";", "return", "mask", ";", "}" ]
Add additional flags to a given mask. mask - Number flags - Object Returns a number.
[ "Add", "additional", "flags", "to", "a", "given", "mask", ".", "mask", "-", "Number", "flags", "-", "Object", "Returns", "a", "number", "." ]
6d161fed38c6d30951c46055939a5a2915304a53
https://github.com/dignifiedquire/node-inotifyr/blob/6d161fed38c6d30951c46055939a5a2915304a53/lib/bits.js#L108-L113
train
5long/roil
src/console/socket.io.js
FABridge__bridgeInitialized
function FABridge__bridgeInitialized(bridgeName) { var objects = document.getElementsByTagName("object"); var ol = objects.length; var activeObjects = []; if (ol > 0) { for (var i = 0; i < ol; i++) { if (typeof objects[i].SetVariable != "undefined") { activeObjects[activeObjects.length] = objects[i]; } } } var embeds = document.getElementsByTagName("embed"); var el = embeds.length; var activeEmbeds = []; if (el > 0) { for (var j = 0; j < el; j++) { if (typeof embeds[j].SetVariable != "undefined") { activeEmbeds[activeEmbeds.length] = embeds[j]; } } } var aol = activeObjects.length; var ael = activeEmbeds.length; var searchStr = "bridgeName="+ bridgeName; if ((aol == 1 && !ael) || (aol == 1 && ael == 1)) { FABridge.attachBridge(activeObjects[0], bridgeName); } else if (ael == 1 && !aol) { FABridge.attachBridge(activeEmbeds[0], bridgeName); } else { var flash_found = false; if (aol > 1) { for (var k = 0; k < aol; k++) { var params = activeObjects[k].childNodes; for (var l = 0; l < params.length; l++) { var param = params[l]; if (param.nodeType == 1 && param.tagName.toLowerCase() == "param" && param["name"].toLowerCase() == "flashvars" && param["value"].indexOf(searchStr) >= 0) { FABridge.attachBridge(activeObjects[k], bridgeName); flash_found = true; break; } } if (flash_found) { break; } } } if (!flash_found && ael > 1) { for (var m = 0; m < ael; m++) { var flashVars = activeEmbeds[m].attributes.getNamedItem("flashVars").nodeValue; if (flashVars.indexOf(searchStr) >= 0) { FABridge.attachBridge(activeEmbeds[m], bridgeName); break; } } } } return true; }
javascript
function FABridge__bridgeInitialized(bridgeName) { var objects = document.getElementsByTagName("object"); var ol = objects.length; var activeObjects = []; if (ol > 0) { for (var i = 0; i < ol; i++) { if (typeof objects[i].SetVariable != "undefined") { activeObjects[activeObjects.length] = objects[i]; } } } var embeds = document.getElementsByTagName("embed"); var el = embeds.length; var activeEmbeds = []; if (el > 0) { for (var j = 0; j < el; j++) { if (typeof embeds[j].SetVariable != "undefined") { activeEmbeds[activeEmbeds.length] = embeds[j]; } } } var aol = activeObjects.length; var ael = activeEmbeds.length; var searchStr = "bridgeName="+ bridgeName; if ((aol == 1 && !ael) || (aol == 1 && ael == 1)) { FABridge.attachBridge(activeObjects[0], bridgeName); } else if (ael == 1 && !aol) { FABridge.attachBridge(activeEmbeds[0], bridgeName); } else { var flash_found = false; if (aol > 1) { for (var k = 0; k < aol; k++) { var params = activeObjects[k].childNodes; for (var l = 0; l < params.length; l++) { var param = params[l]; if (param.nodeType == 1 && param.tagName.toLowerCase() == "param" && param["name"].toLowerCase() == "flashvars" && param["value"].indexOf(searchStr) >= 0) { FABridge.attachBridge(activeObjects[k], bridgeName); flash_found = true; break; } } if (flash_found) { break; } } } if (!flash_found && ael > 1) { for (var m = 0; m < ael; m++) { var flashVars = activeEmbeds[m].attributes.getNamedItem("flashVars").nodeValue; if (flashVars.indexOf(searchStr) >= 0) { FABridge.attachBridge(activeEmbeds[m], bridgeName); break; } } } } return true; }
[ "function", "FABridge__bridgeInitialized", "(", "bridgeName", ")", "{", "var", "objects", "=", "document", ".", "getElementsByTagName", "(", "\"object\"", ")", ";", "var", "ol", "=", "objects", ".", "length", ";", "var", "activeObjects", "=", "[", "]", ";", "if", "(", "ol", ">", "0", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "ol", ";", "i", "++", ")", "{", "if", "(", "typeof", "objects", "[", "i", "]", ".", "SetVariable", "!=", "\"undefined\"", ")", "{", "activeObjects", "[", "activeObjects", ".", "length", "]", "=", "objects", "[", "i", "]", ";", "}", "}", "}", "var", "embeds", "=", "document", ".", "getElementsByTagName", "(", "\"embed\"", ")", ";", "var", "el", "=", "embeds", ".", "length", ";", "var", "activeEmbeds", "=", "[", "]", ";", "if", "(", "el", ">", "0", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "el", ";", "j", "++", ")", "{", "if", "(", "typeof", "embeds", "[", "j", "]", ".", "SetVariable", "!=", "\"undefined\"", ")", "{", "activeEmbeds", "[", "activeEmbeds", ".", "length", "]", "=", "embeds", "[", "j", "]", ";", "}", "}", "}", "var", "aol", "=", "activeObjects", ".", "length", ";", "var", "ael", "=", "activeEmbeds", ".", "length", ";", "var", "searchStr", "=", "\"bridgeName=\"", "+", "bridgeName", ";", "if", "(", "(", "aol", "==", "1", "&&", "!", "ael", ")", "||", "(", "aol", "==", "1", "&&", "ael", "==", "1", ")", ")", "{", "FABridge", ".", "attachBridge", "(", "activeObjects", "[", "0", "]", ",", "bridgeName", ")", ";", "}", "else", "if", "(", "ael", "==", "1", "&&", "!", "aol", ")", "{", "FABridge", ".", "attachBridge", "(", "activeEmbeds", "[", "0", "]", ",", "bridgeName", ")", ";", "}", "else", "{", "var", "flash_found", "=", "false", ";", "if", "(", "aol", ">", "1", ")", "{", "for", "(", "var", "k", "=", "0", ";", "k", "<", "aol", ";", "k", "++", ")", "{", "var", "params", "=", "activeObjects", "[", "k", "]", ".", "childNodes", ";", "for", "(", "var", "l", "=", "0", ";", "l", "<", "params", ".", "length", ";", "l", "++", ")", "{", "var", "param", "=", "params", "[", "l", "]", ";", "if", "(", "param", ".", "nodeType", "==", "1", "&&", "param", ".", "tagName", ".", "toLowerCase", "(", ")", "==", "\"param\"", "&&", "param", "[", "\"name\"", "]", ".", "toLowerCase", "(", ")", "==", "\"flashvars\"", "&&", "param", "[", "\"value\"", "]", ".", "indexOf", "(", "searchStr", ")", ">=", "0", ")", "{", "FABridge", ".", "attachBridge", "(", "activeObjects", "[", "k", "]", ",", "bridgeName", ")", ";", "flash_found", "=", "true", ";", "break", ";", "}", "}", "if", "(", "flash_found", ")", "{", "break", ";", "}", "}", "}", "if", "(", "!", "flash_found", "&&", "ael", ">", "1", ")", "{", "for", "(", "var", "m", "=", "0", ";", "m", "<", "ael", ";", "m", "++", ")", "{", "var", "flashVars", "=", "activeEmbeds", "[", "m", "]", ".", "attributes", ".", "getNamedItem", "(", "\"flashVars\"", ")", ".", "nodeValue", ";", "if", "(", "flashVars", ".", "indexOf", "(", "searchStr", ")", ">=", "0", ")", "{", "FABridge", ".", "attachBridge", "(", "activeEmbeds", "[", "m", "]", ",", "bridgeName", ")", ";", "break", ";", "}", "}", "}", "}", "return", "true", ";", "}" ]
updated for changes to SWFObject2
[ "updated", "for", "changes", "to", "SWFObject2" ]
37b14072a7aea17accc7f4e5e04dedc90a1358de
https://github.com/5long/roil/blob/37b14072a7aea17accc7f4e5e04dedc90a1358de/src/console/socket.io.js#L1029-L1088
train
5long/roil
src/console/socket.io.js
function(objRef, propName) { if (FABridge.refCount > 0) { throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround."); } else { FABridge.refCount++; retVal = this.target.getPropFromAS(objRef, propName); retVal = this.handleError(retVal); FABridge.refCount--; return retVal; } }
javascript
function(objRef, propName) { if (FABridge.refCount > 0) { throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround."); } else { FABridge.refCount++; retVal = this.target.getPropFromAS(objRef, propName); retVal = this.handleError(retVal); FABridge.refCount--; return retVal; } }
[ "function", "(", "objRef", ",", "propName", ")", "{", "if", "(", "FABridge", ".", "refCount", ">", "0", ")", "{", "throw", "new", "Error", "(", "\"You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.\"", ")", ";", "}", "else", "{", "FABridge", ".", "refCount", "++", ";", "retVal", "=", "this", ".", "target", ".", "getPropFromAS", "(", "objRef", ",", "propName", ")", ";", "retVal", "=", "this", ".", "handleError", "(", "retVal", ")", ";", "FABridge", ".", "refCount", "--", ";", "return", "retVal", ";", "}", "}" ]
low level access to the flash object get a named property from an AS object
[ "low", "level", "access", "to", "the", "flash", "object", "get", "a", "named", "property", "from", "an", "AS", "object" ]
37b14072a7aea17accc7f4e5e04dedc90a1358de
https://github.com/5long/roil/blob/37b14072a7aea17accc7f4e5e04dedc90a1358de/src/console/socket.io.js#L1181-L1195
train
5long/roil
src/console/socket.io.js
function(objRef,propName, value) { if (FABridge.refCount > 0) { throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround."); } else { FABridge.refCount++; retVal = this.target.setPropInAS(objRef,propName, this.serialize(value)); retVal = this.handleError(retVal); FABridge.refCount--; return retVal; } }
javascript
function(objRef,propName, value) { if (FABridge.refCount > 0) { throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround."); } else { FABridge.refCount++; retVal = this.target.setPropInAS(objRef,propName, this.serialize(value)); retVal = this.handleError(retVal); FABridge.refCount--; return retVal; } }
[ "function", "(", "objRef", ",", "propName", ",", "value", ")", "{", "if", "(", "FABridge", ".", "refCount", ">", "0", ")", "{", "throw", "new", "Error", "(", "\"You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.\"", ")", ";", "}", "else", "{", "FABridge", ".", "refCount", "++", ";", "retVal", "=", "this", ".", "target", ".", "setPropInAS", "(", "objRef", ",", "propName", ",", "this", ".", "serialize", "(", "value", ")", ")", ";", "retVal", "=", "this", ".", "handleError", "(", "retVal", ")", ";", "FABridge", ".", "refCount", "--", ";", "return", "retVal", ";", "}", "}" ]
set a named property on an AS object
[ "set", "a", "named", "property", "on", "an", "AS", "object" ]
37b14072a7aea17accc7f4e5e04dedc90a1358de
https://github.com/5long/roil/blob/37b14072a7aea17accc7f4e5e04dedc90a1358de/src/console/socket.io.js#L1197-L1211
train
5long/roil
src/console/socket.io.js
function(funcID, args) { if (FABridge.refCount > 0) { throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround."); } else { FABridge.refCount++; retVal = this.target.invokeASFunction(funcID, this.serialize(args)); retVal = this.handleError(retVal); FABridge.refCount--; return retVal; } }
javascript
function(funcID, args) { if (FABridge.refCount > 0) { throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround."); } else { FABridge.refCount++; retVal = this.target.invokeASFunction(funcID, this.serialize(args)); retVal = this.handleError(retVal); FABridge.refCount--; return retVal; } }
[ "function", "(", "funcID", ",", "args", ")", "{", "if", "(", "FABridge", ".", "refCount", ">", "0", ")", "{", "throw", "new", "Error", "(", "\"You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.\"", ")", ";", "}", "else", "{", "FABridge", ".", "refCount", "++", ";", "retVal", "=", "this", ".", "target", ".", "invokeASFunction", "(", "funcID", ",", "this", ".", "serialize", "(", "args", ")", ")", ";", "retVal", "=", "this", ".", "handleError", "(", "retVal", ")", ";", "FABridge", ".", "refCount", "--", ";", "return", "retVal", ";", "}", "}" ]
call an AS function
[ "call", "an", "AS", "function" ]
37b14072a7aea17accc7f4e5e04dedc90a1358de
https://github.com/5long/roil/blob/37b14072a7aea17accc7f4e5e04dedc90a1358de/src/console/socket.io.js#L1214-L1228
train
5long/roil
src/console/socket.io.js
function(objID, funcName, args) { if (FABridge.refCount > 0) { throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround."); } else { FABridge.refCount++; args = this.serialize(args); retVal = this.target.invokeASMethod(objID, funcName, args); retVal = this.handleError(retVal); FABridge.refCount--; return retVal; } }
javascript
function(objID, funcName, args) { if (FABridge.refCount > 0) { throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround."); } else { FABridge.refCount++; args = this.serialize(args); retVal = this.target.invokeASMethod(objID, funcName, args); retVal = this.handleError(retVal); FABridge.refCount--; return retVal; } }
[ "function", "(", "objID", ",", "funcName", ",", "args", ")", "{", "if", "(", "FABridge", ".", "refCount", ">", "0", ")", "{", "throw", "new", "Error", "(", "\"You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.\"", ")", ";", "}", "else", "{", "FABridge", ".", "refCount", "++", ";", "args", "=", "this", ".", "serialize", "(", "args", ")", ";", "retVal", "=", "this", ".", "target", ".", "invokeASMethod", "(", "objID", ",", "funcName", ",", "args", ")", ";", "retVal", "=", "this", ".", "handleError", "(", "retVal", ")", ";", "FABridge", ".", "refCount", "--", ";", "return", "retVal", ";", "}", "}" ]
call a method on an AS object
[ "call", "a", "method", "on", "an", "AS", "object" ]
37b14072a7aea17accc7f4e5e04dedc90a1358de
https://github.com/5long/roil/blob/37b14072a7aea17accc7f4e5e04dedc90a1358de/src/console/socket.io.js#L1230-L1245
train
5long/roil
src/console/socket.io.js
function(funcID, args) { var result; var func = this.localFunctionCache[funcID]; if(func != undefined) { result = this.serialize(func.apply(null, this.deserialize(args))); } return result; }
javascript
function(funcID, args) { var result; var func = this.localFunctionCache[funcID]; if(func != undefined) { result = this.serialize(func.apply(null, this.deserialize(args))); } return result; }
[ "function", "(", "funcID", ",", "args", ")", "{", "var", "result", ";", "var", "func", "=", "this", ".", "localFunctionCache", "[", "funcID", "]", ";", "if", "(", "func", "!=", "undefined", ")", "{", "result", "=", "this", ".", "serialize", "(", "func", ".", "apply", "(", "null", ",", "this", ".", "deserialize", "(", "args", ")", ")", ")", ";", "}", "return", "result", ";", "}" ]
callback from flash that executes a local JS function used mostly when setting js functions as callbacks on events
[ "callback", "from", "flash", "that", "executes", "a", "local", "JS", "function", "used", "mostly", "when", "setting", "js", "functions", "as", "callbacks", "on", "events" ]
37b14072a7aea17accc7f4e5e04dedc90a1358de
https://github.com/5long/roil/blob/37b14072a7aea17accc7f4e5e04dedc90a1358de/src/console/socket.io.js#L1251-L1262
train
5long/roil
src/console/socket.io.js
function(objID, typeName) { var objType = this.getTypeFromName(typeName); instanceFactory.prototype = objType; var instance = new instanceFactory(objID); this.remoteInstanceCache[objID] = instance; return instance; }
javascript
function(objID, typeName) { var objType = this.getTypeFromName(typeName); instanceFactory.prototype = objType; var instance = new instanceFactory(objID); this.remoteInstanceCache[objID] = instance; return instance; }
[ "function", "(", "objID", ",", "typeName", ")", "{", "var", "objType", "=", "this", ".", "getTypeFromName", "(", "typeName", ")", ";", "instanceFactory", ".", "prototype", "=", "objType", ";", "var", "instance", "=", "new", "instanceFactory", "(", "objID", ")", ";", "this", ".", "remoteInstanceCache", "[", "objID", "]", "=", "instance", ";", "return", "instance", ";", "}" ]
create an AS proxy for the given object ID and type
[ "create", "an", "AS", "proxy", "for", "the", "given", "object", "ID", "and", "type" ]
37b14072a7aea17accc7f4e5e04dedc90a1358de
https://github.com/5long/roil/blob/37b14072a7aea17accc7f4e5e04dedc90a1358de/src/console/socket.io.js#L1272-L1279
train
5long/roil
src/console/socket.io.js
function(typeData) { var newType = new ASProxy(this, typeData.name); var accessors = typeData.accessors; for (var i = 0; i < accessors.length; i++) { this.addPropertyToType(newType, accessors[i]); } var methods = typeData.methods; for (var i = 0; i < methods.length; i++) { if (FABridge.blockedMethods[methods[i]] == undefined) { this.addMethodToType(newType, methods[i]); } } this.remoteTypeCache[newType.typeName] = newType; return newType; }
javascript
function(typeData) { var newType = new ASProxy(this, typeData.name); var accessors = typeData.accessors; for (var i = 0; i < accessors.length; i++) { this.addPropertyToType(newType, accessors[i]); } var methods = typeData.methods; for (var i = 0; i < methods.length; i++) { if (FABridge.blockedMethods[methods[i]] == undefined) { this.addMethodToType(newType, methods[i]); } } this.remoteTypeCache[newType.typeName] = newType; return newType; }
[ "function", "(", "typeData", ")", "{", "var", "newType", "=", "new", "ASProxy", "(", "this", ",", "typeData", ".", "name", ")", ";", "var", "accessors", "=", "typeData", ".", "accessors", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "accessors", ".", "length", ";", "i", "++", ")", "{", "this", ".", "addPropertyToType", "(", "newType", ",", "accessors", "[", "i", "]", ")", ";", "}", "var", "methods", "=", "typeData", ".", "methods", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "methods", ".", "length", ";", "i", "++", ")", "{", "if", "(", "FABridge", ".", "blockedMethods", "[", "methods", "[", "i", "]", "]", "==", "undefined", ")", "{", "this", ".", "addMethodToType", "(", "newType", ",", "methods", "[", "i", "]", ")", ";", "}", "}", "this", ".", "remoteTypeCache", "[", "newType", ".", "typeName", "]", "=", "newType", ";", "return", "newType", ";", "}" ]
accepts a type structure, returns a constructed type
[ "accepts", "a", "type", "structure", "returns", "a", "constructed", "type" ]
37b14072a7aea17accc7f4e5e04dedc90a1358de
https://github.com/5long/roil/blob/37b14072a7aea17accc7f4e5e04dedc90a1358de/src/console/socket.io.js#L1287-L1308
train
5long/roil
src/console/socket.io.js
function(ty, propName) { var c = propName.charAt(0); var setterName; var getterName; if(c >= "a" && c <= "z") { getterName = "get" + c.toUpperCase() + propName.substr(1); setterName = "set" + c.toUpperCase() + propName.substr(1); } else { getterName = "get" + propName; setterName = "set" + propName; } ty[setterName] = function(val) { this.bridge.setPropertyInAS(this.fb_instance_id, propName, val); } ty[getterName] = function() { return this.bridge.deserialize(this.bridge.getPropertyFromAS(this.fb_instance_id, propName)); } }
javascript
function(ty, propName) { var c = propName.charAt(0); var setterName; var getterName; if(c >= "a" && c <= "z") { getterName = "get" + c.toUpperCase() + propName.substr(1); setterName = "set" + c.toUpperCase() + propName.substr(1); } else { getterName = "get" + propName; setterName = "set" + propName; } ty[setterName] = function(val) { this.bridge.setPropertyInAS(this.fb_instance_id, propName, val); } ty[getterName] = function() { return this.bridge.deserialize(this.bridge.getPropertyFromAS(this.fb_instance_id, propName)); } }
[ "function", "(", "ty", ",", "propName", ")", "{", "var", "c", "=", "propName", ".", "charAt", "(", "0", ")", ";", "var", "setterName", ";", "var", "getterName", ";", "if", "(", "c", ">=", "\"a\"", "&&", "c", "<=", "\"z\"", ")", "{", "getterName", "=", "\"get\"", "+", "c", ".", "toUpperCase", "(", ")", "+", "propName", ".", "substr", "(", "1", ")", ";", "setterName", "=", "\"set\"", "+", "c", ".", "toUpperCase", "(", ")", "+", "propName", ".", "substr", "(", "1", ")", ";", "}", "else", "{", "getterName", "=", "\"get\"", "+", "propName", ";", "setterName", "=", "\"set\"", "+", "propName", ";", "}", "ty", "[", "setterName", "]", "=", "function", "(", "val", ")", "{", "this", ".", "bridge", ".", "setPropertyInAS", "(", "this", ".", "fb_instance_id", ",", "propName", ",", "val", ")", ";", "}", "ty", "[", "getterName", "]", "=", "function", "(", ")", "{", "return", "this", ".", "bridge", ".", "deserialize", "(", "this", ".", "bridge", ".", "getPropertyFromAS", "(", "this", ".", "fb_instance_id", ",", "propName", ")", ")", ";", "}", "}" ]
add a property to a typename; used to define the properties that can be called on an AS proxied object
[ "add", "a", "property", "to", "a", "typename", ";", "used", "to", "define", "the", "properties", "that", "can", "be", "called", "on", "an", "AS", "proxied", "object" ]
37b14072a7aea17accc7f4e5e04dedc90a1358de
https://github.com/5long/roil/blob/37b14072a7aea17accc7f4e5e04dedc90a1358de/src/console/socket.io.js#L1311-L1334
train
5long/roil
src/console/socket.io.js
function(ty, methodName) { ty[methodName] = function() { return this.bridge.deserialize(this.bridge.callASMethod(this.fb_instance_id, methodName, FABridge.argsToArray(arguments))); } }
javascript
function(ty, methodName) { ty[methodName] = function() { return this.bridge.deserialize(this.bridge.callASMethod(this.fb_instance_id, methodName, FABridge.argsToArray(arguments))); } }
[ "function", "(", "ty", ",", "methodName", ")", "{", "ty", "[", "methodName", "]", "=", "function", "(", ")", "{", "return", "this", ".", "bridge", ".", "deserialize", "(", "this", ".", "bridge", ".", "callASMethod", "(", "this", ".", "fb_instance_id", ",", "methodName", ",", "FABridge", ".", "argsToArray", "(", "arguments", ")", ")", ")", ";", "}", "}" ]
add a method to a typename; used to define the methods that can be callefd on an AS proxied object
[ "add", "a", "method", "to", "a", "typename", ";", "used", "to", "define", "the", "methods", "that", "can", "be", "callefd", "on", "an", "AS", "proxied", "object" ]
37b14072a7aea17accc7f4e5e04dedc90a1358de
https://github.com/5long/roil/blob/37b14072a7aea17accc7f4e5e04dedc90a1358de/src/console/socket.io.js#L1337-L1343
train
5long/roil
src/console/socket.io.js
function(funcID) { var bridge = this; if (this.remoteFunctionCache[funcID] == null) { this.remoteFunctionCache[funcID] = function() { bridge.callASFunction(funcID, FABridge.argsToArray(arguments)); } } return this.remoteFunctionCache[funcID]; }
javascript
function(funcID) { var bridge = this; if (this.remoteFunctionCache[funcID] == null) { this.remoteFunctionCache[funcID] = function() { bridge.callASFunction(funcID, FABridge.argsToArray(arguments)); } } return this.remoteFunctionCache[funcID]; }
[ "function", "(", "funcID", ")", "{", "var", "bridge", "=", "this", ";", "if", "(", "this", ".", "remoteFunctionCache", "[", "funcID", "]", "==", "null", ")", "{", "this", ".", "remoteFunctionCache", "[", "funcID", "]", "=", "function", "(", ")", "{", "bridge", ".", "callASFunction", "(", "funcID", ",", "FABridge", ".", "argsToArray", "(", "arguments", ")", ")", ";", "}", "}", "return", "this", ".", "remoteFunctionCache", "[", "funcID", "]", ";", "}" ]
Function Proxies returns the AS proxy for the specified function ID
[ "Function", "Proxies", "returns", "the", "AS", "proxy", "for", "the", "specified", "function", "ID" ]
37b14072a7aea17accc7f4e5e04dedc90a1358de
https://github.com/5long/roil/blob/37b14072a7aea17accc7f4e5e04dedc90a1358de/src/console/socket.io.js#L1348-L1359
train
5long/roil
src/console/socket.io.js
function(func) { if (func.__bridge_id__ == undefined) { func.__bridge_id__ = this.makeID(this.nextLocalFuncID++); this.localFunctionCache[func.__bridge_id__] = func; } return func.__bridge_id__; }
javascript
function(func) { if (func.__bridge_id__ == undefined) { func.__bridge_id__ = this.makeID(this.nextLocalFuncID++); this.localFunctionCache[func.__bridge_id__] = func; } return func.__bridge_id__; }
[ "function", "(", "func", ")", "{", "if", "(", "func", ".", "__bridge_id__", "==", "undefined", ")", "{", "func", ".", "__bridge_id__", "=", "this", ".", "makeID", "(", "this", ".", "nextLocalFuncID", "++", ")", ";", "this", ".", "localFunctionCache", "[", "func", ".", "__bridge_id__", "]", "=", "func", ";", "}", "return", "func", ".", "__bridge_id__", ";", "}" ]
reutrns the ID of the given function; if it doesnt exist it is created and added to the local cache
[ "reutrns", "the", "ID", "of", "the", "given", "function", ";", "if", "it", "doesnt", "exist", "it", "is", "created", "and", "added", "to", "the", "local", "cache" ]
37b14072a7aea17accc7f4e5e04dedc90a1358de
https://github.com/5long/roil/blob/37b14072a7aea17accc7f4e5e04dedc90a1358de/src/console/socket.io.js#L1362-L1370
train
tracker1/mssql-ng
src/connections/shadow-close.js
shadowClose
function shadowClose(connection) { debug('shadowClose', 'start'); let close = connection.close; connection.close = function() { debug('connection.close','start'); //remove references delete promises[connection._mssqlngKey]; delete connections[connection._mssqlngKey]; //close original connection setImmediate(()=>{ try { debug('connection.close','apply'); close.apply(connection); debug('connection.close','applied'); //clear local references - allow GC close = null; connection - null; }catch(err){} }); debug('connection.close','end'); } }
javascript
function shadowClose(connection) { debug('shadowClose', 'start'); let close = connection.close; connection.close = function() { debug('connection.close','start'); //remove references delete promises[connection._mssqlngKey]; delete connections[connection._mssqlngKey]; //close original connection setImmediate(()=>{ try { debug('connection.close','apply'); close.apply(connection); debug('connection.close','applied'); //clear local references - allow GC close = null; connection - null; }catch(err){} }); debug('connection.close','end'); } }
[ "function", "shadowClose", "(", "connection", ")", "{", "debug", "(", "'shadowClose'", ",", "'start'", ")", ";", "let", "close", "=", "connection", ".", "close", ";", "connection", ".", "close", "=", "function", "(", ")", "{", "debug", "(", "'connection.close'", ",", "'start'", ")", ";", "delete", "promises", "[", "connection", ".", "_mssqlngKey", "]", ";", "delete", "connections", "[", "connection", ".", "_mssqlngKey", "]", ";", "setImmediate", "(", "(", ")", "=>", "{", "try", "{", "debug", "(", "'connection.close'", ",", "'apply'", ")", ";", "close", ".", "apply", "(", "connection", ")", ";", "debug", "(", "'connection.close'", ",", "'applied'", ")", ";", "close", "=", "null", ";", "connection", "-", "null", ";", "}", "catch", "(", "err", ")", "{", "}", "}", ")", ";", "debug", "(", "'connection.close'", ",", "'end'", ")", ";", "}", "}" ]
shadow the close method, so that it will clear itself from the pool
[ "shadow", "the", "close", "method", "so", "that", "it", "will", "clear", "itself", "from", "the", "pool" ]
7f32135d33f9b8324fdd94656136cae4087464ce
https://github.com/tracker1/mssql-ng/blob/7f32135d33f9b8324fdd94656136cae4087464ce/src/connections/shadow-close.js#L7-L31
train
jl-/gulp-docy
jsdoc.js
function (infos, name) { name = name || 'jsdoc.json'; var firstFile = null; var readme = null; var wp = new Parser(infos); var bufferFiles = function(file, enc, next){ if (file.isNull()) return; // ignore if (file.isStream()) return this.emit('error', new PluginError('gulp-jsdoc', 'Streaming not supported')); // Store firstFile to get a base and cwd later on if (!firstFile) firstFile = file; if (/[.]js$/i.test(file.path)) wp.parse(file); else if(/readme(?:[.]md)?$/i.test(file.path)) readme = marked(file.contents.toString('utf8')); next(); }; var endStream = function(conclude){ // Nothing? Exit right away if (!firstFile){ conclude(); return; } var data; try{ data = JSON.stringify(wp.complete(), null, 2); // data = parser(options, filemap)); }catch(e){ return this.emit('error', new PluginError('gulp-jsdoc', 'Oooooh! Failed parsing with jsdoc. What did you do?! ' + e)); } // Pump-up the generated output var vinyl = new File({ cwd: firstFile.cwd, base: firstFile.base, path: path.join(firstFile.base, name), contents: new Buffer(data) }); // Possibly stack-up the readme, if there was any in the first place vinyl.readme = readme; // Add that to the stream... this.push(vinyl); conclude(); }; // That's it for the parser return through2.obj(bufferFiles, endStream); }
javascript
function (infos, name) { name = name || 'jsdoc.json'; var firstFile = null; var readme = null; var wp = new Parser(infos); var bufferFiles = function(file, enc, next){ if (file.isNull()) return; // ignore if (file.isStream()) return this.emit('error', new PluginError('gulp-jsdoc', 'Streaming not supported')); // Store firstFile to get a base and cwd later on if (!firstFile) firstFile = file; if (/[.]js$/i.test(file.path)) wp.parse(file); else if(/readme(?:[.]md)?$/i.test(file.path)) readme = marked(file.contents.toString('utf8')); next(); }; var endStream = function(conclude){ // Nothing? Exit right away if (!firstFile){ conclude(); return; } var data; try{ data = JSON.stringify(wp.complete(), null, 2); // data = parser(options, filemap)); }catch(e){ return this.emit('error', new PluginError('gulp-jsdoc', 'Oooooh! Failed parsing with jsdoc. What did you do?! ' + e)); } // Pump-up the generated output var vinyl = new File({ cwd: firstFile.cwd, base: firstFile.base, path: path.join(firstFile.base, name), contents: new Buffer(data) }); // Possibly stack-up the readme, if there was any in the first place vinyl.readme = readme; // Add that to the stream... this.push(vinyl); conclude(); }; // That's it for the parser return through2.obj(bufferFiles, endStream); }
[ "function", "(", "infos", ",", "name", ")", "{", "name", "=", "name", "||", "'jsdoc.json'", ";", "var", "firstFile", "=", "null", ";", "var", "readme", "=", "null", ";", "var", "wp", "=", "new", "Parser", "(", "infos", ")", ";", "var", "bufferFiles", "=", "function", "(", "file", ",", "enc", ",", "next", ")", "{", "if", "(", "file", ".", "isNull", "(", ")", ")", "return", ";", "if", "(", "file", ".", "isStream", "(", ")", ")", "return", "this", ".", "emit", "(", "'error'", ",", "new", "PluginError", "(", "'gulp-jsdoc'", ",", "'Streaming not supported'", ")", ")", ";", "if", "(", "!", "firstFile", ")", "firstFile", "=", "file", ";", "if", "(", "/", "[.]js$", "/", "i", ".", "test", "(", "file", ".", "path", ")", ")", "wp", ".", "parse", "(", "file", ")", ";", "else", "if", "(", "/", "readme(?:[.]md)?$", "/", "i", ".", "test", "(", "file", ".", "path", ")", ")", "readme", "=", "marked", "(", "file", ".", "contents", ".", "toString", "(", "'utf8'", ")", ")", ";", "next", "(", ")", ";", "}", ";", "var", "endStream", "=", "function", "(", "conclude", ")", "{", "if", "(", "!", "firstFile", ")", "{", "conclude", "(", ")", ";", "return", ";", "}", "var", "data", ";", "try", "{", "data", "=", "JSON", ".", "stringify", "(", "wp", ".", "complete", "(", ")", ",", "null", ",", "2", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "this", ".", "emit", "(", "'error'", ",", "new", "PluginError", "(", "'gulp-jsdoc'", ",", "'Oooooh! Failed parsing with jsdoc. What did you do?! '", "+", "e", ")", ")", ";", "}", "var", "vinyl", "=", "new", "File", "(", "{", "cwd", ":", "firstFile", ".", "cwd", ",", "base", ":", "firstFile", ".", "base", ",", "path", ":", "path", ".", "join", "(", "firstFile", ".", "base", ",", "name", ")", ",", "contents", ":", "new", "Buffer", "(", "data", ")", "}", ")", ";", "vinyl", ".", "readme", "=", "readme", ";", "this", ".", "push", "(", "vinyl", ")", ";", "conclude", "(", ")", ";", "}", ";", "return", "through2", ".", "obj", "(", "bufferFiles", ",", "endStream", ")", ";", "}" ]
That's the plugin parser
[ "That", "s", "the", "plugin", "parser" ]
40c2ba2da57c8ddb0a877340acc9a0604b1bafb4
https://github.com/jl-/gulp-docy/blob/40c2ba2da57c8ddb0a877340acc9a0604b1bafb4/jsdoc.js#L29-L88
train
RnbWd/parse-browserify
lib/collection.js
function(model, options) { if (!(model instanceof Parse.Object)) { var attrs = model; options.collection = this; model = new this.model(attrs, options); if (!model._validate(model.attributes, options)) { model = false; } } else if (!model.collection) { model.collection = this; } return model; }
javascript
function(model, options) { if (!(model instanceof Parse.Object)) { var attrs = model; options.collection = this; model = new this.model(attrs, options); if (!model._validate(model.attributes, options)) { model = false; } } else if (!model.collection) { model.collection = this; } return model; }
[ "function", "(", "model", ",", "options", ")", "{", "if", "(", "!", "(", "model", "instanceof", "Parse", ".", "Object", ")", ")", "{", "var", "attrs", "=", "model", ";", "options", ".", "collection", "=", "this", ";", "model", "=", "new", "this", ".", "model", "(", "attrs", ",", "options", ")", ";", "if", "(", "!", "model", ".", "_validate", "(", "model", ".", "attributes", ",", "options", ")", ")", "{", "model", "=", "false", ";", "}", "}", "else", "if", "(", "!", "model", ".", "collection", ")", "{", "model", ".", "collection", "=", "this", ";", "}", "return", "model", ";", "}" ]
Prepare a model or hash of attributes to be added to this collection.
[ "Prepare", "a", "model", "or", "hash", "of", "attributes", "to", "be", "added", "to", "this", "collection", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/collection.js#L372-L384
train
d08ble/livecomment
livecomment.js
_configGetExtLang
function _configGetExtLang(filext) { var fileext1 = filext.indexOf('.') == 0 ? fileext.substring(1, filext.length) : fileext; if (!config.extlangs.hasOwnProperty(fileext1)) return null; return config.extlangs[fileext1]; }
javascript
function _configGetExtLang(filext) { var fileext1 = filext.indexOf('.') == 0 ? fileext.substring(1, filext.length) : fileext; if (!config.extlangs.hasOwnProperty(fileext1)) return null; return config.extlangs[fileext1]; }
[ "function", "_configGetExtLang", "(", "filext", ")", "{", "var", "fileext1", "=", "filext", ".", "indexOf", "(", "'.'", ")", "==", "0", "?", "fileext", ".", "substring", "(", "1", ",", "filext", ".", "length", ")", ":", "fileext", ";", "if", "(", "!", "config", ".", "extlangs", ".", "hasOwnProperty", "(", "fileext1", ")", ")", "return", "null", ";", "return", "config", ".", "extlangs", "[", "fileext1", "]", ";", "}" ]
CHECK EXTLANG [
[ "CHECK", "EXTLANG", "[" ]
9c4a00878101501411668070b4f6e7719e10d1fd
https://github.com/d08ble/livecomment/blob/9c4a00878101501411668070b4f6e7719e10d1fd/livecomment.js#L750-L756
train
d08ble/livecomment
livecomment.js
extractCommentTagFromLine
function extractCommentTagFromLine(fileext, line) { line = line.trim(); // CHECK FORMAT [ var b; function chkfmt(b) { if (line.indexOf(b) == 0 && line.indexOf('[') == line.length-1) // begin return [line.substr(b.length, line.length-b.length-1).trim(), 0]; if (line.indexOf(b) == 0 && line.indexOf(']') == line.length-1 && line.indexOf('[') == -1) // end return [line.substr(b.length, line.length-b.length-1).trim(), 1]; return null; }; // CHECK FORMAT ] // SUPPORT FORMATS [ switch (fileext) { case '.js': case '.java': case '.c': case '.h': case '.cpp': case '.hpp': case '.less': case '.m': case '.mm': return chkfmt('//') || false; case '.css': return chkfmt('/*') || false; case '.acpul': case '.sh': case '.py': case '.pro': return chkfmt('#') || false; case '.ejs': case '.jade': case '.sass': case '.styl': case '.coffee': break; default: return null; } // SUPPORT FORMATS ] return false; }
javascript
function extractCommentTagFromLine(fileext, line) { line = line.trim(); // CHECK FORMAT [ var b; function chkfmt(b) { if (line.indexOf(b) == 0 && line.indexOf('[') == line.length-1) // begin return [line.substr(b.length, line.length-b.length-1).trim(), 0]; if (line.indexOf(b) == 0 && line.indexOf(']') == line.length-1 && line.indexOf('[') == -1) // end return [line.substr(b.length, line.length-b.length-1).trim(), 1]; return null; }; // CHECK FORMAT ] // SUPPORT FORMATS [ switch (fileext) { case '.js': case '.java': case '.c': case '.h': case '.cpp': case '.hpp': case '.less': case '.m': case '.mm': return chkfmt('//') || false; case '.css': return chkfmt('/*') || false; case '.acpul': case '.sh': case '.py': case '.pro': return chkfmt('#') || false; case '.ejs': case '.jade': case '.sass': case '.styl': case '.coffee': break; default: return null; } // SUPPORT FORMATS ] return false; }
[ "function", "extractCommentTagFromLine", "(", "fileext", ",", "line", ")", "{", "line", "=", "line", ".", "trim", "(", ")", ";", "var", "b", ";", "function", "chkfmt", "(", "b", ")", "{", "if", "(", "line", ".", "indexOf", "(", "b", ")", "==", "0", "&&", "line", ".", "indexOf", "(", "'['", ")", "==", "line", ".", "length", "-", "1", ")", "return", "[", "line", ".", "substr", "(", "b", ".", "length", ",", "line", ".", "length", "-", "b", ".", "length", "-", "1", ")", ".", "trim", "(", ")", ",", "0", "]", ";", "if", "(", "line", ".", "indexOf", "(", "b", ")", "==", "0", "&&", "line", ".", "indexOf", "(", "']'", ")", "==", "line", ".", "length", "-", "1", "&&", "line", ".", "indexOf", "(", "'['", ")", "==", "-", "1", ")", "return", "[", "line", ".", "substr", "(", "b", ".", "length", ",", "line", ".", "length", "-", "b", ".", "length", "-", "1", ")", ".", "trim", "(", ")", ",", "1", "]", ";", "return", "null", ";", "}", ";", "switch", "(", "fileext", ")", "{", "case", "'.js'", ":", "case", "'.java'", ":", "case", "'.c'", ":", "case", "'.h'", ":", "case", "'.cpp'", ":", "case", "'.hpp'", ":", "case", "'.less'", ":", "case", "'.m'", ":", "case", "'.mm'", ":", "return", "chkfmt", "(", "'//'", ")", "||", "false", ";", "case", "'.css'", ":", "return", "chkfmt", "(", "'/*'", ")", "||", "false", ";", "case", "'.acpul'", ":", "case", "'.sh'", ":", "case", "'.py'", ":", "case", "'.pro'", ":", "return", "chkfmt", "(", "'#'", ")", "||", "false", ";", "case", "'.ejs'", ":", "case", "'.jade'", ":", "case", "'.sass'", ":", "case", "'.styl'", ":", "case", "'.coffee'", ":", "break", ";", "default", ":", "return", "null", ";", "}", "return", "false", ";", "}" ]
custom comment format use config.extractCommentTagFromLine [
[ "custom", "comment", "format", "use", "config", ".", "extractCommentTagFromLine", "[" ]
9c4a00878101501411668070b4f6e7719e10d1fd
https://github.com/d08ble/livecomment/blob/9c4a00878101501411668070b4f6e7719e10d1fd/livecomment.js#L778-L821
train
RnbWd/parse-browserify
lib/analytics.js
function(name, dimensions) { name = name || ''; name = name.replace(/^\s*/, ''); name = name.replace(/\s*$/, ''); if (name.length === 0) { throw 'A name for the custom event must be provided'; } _.each(dimensions, function(val, key) { if (!_.isString(key) || !_.isString(val)) { throw 'track() dimensions expects keys and values of type "string".'; } }); return Parse._request({ route: 'events', className: name, method: 'POST', data: { dimensions: dimensions } }); }
javascript
function(name, dimensions) { name = name || ''; name = name.replace(/^\s*/, ''); name = name.replace(/\s*$/, ''); if (name.length === 0) { throw 'A name for the custom event must be provided'; } _.each(dimensions, function(val, key) { if (!_.isString(key) || !_.isString(val)) { throw 'track() dimensions expects keys and values of type "string".'; } }); return Parse._request({ route: 'events', className: name, method: 'POST', data: { dimensions: dimensions } }); }
[ "function", "(", "name", ",", "dimensions", ")", "{", "name", "=", "name", "||", "''", ";", "name", "=", "name", ".", "replace", "(", "/", "^\\s*", "/", ",", "''", ")", ";", "name", "=", "name", ".", "replace", "(", "/", "\\s*$", "/", ",", "''", ")", ";", "if", "(", "name", ".", "length", "===", "0", ")", "{", "throw", "'A name for the custom event must be provided'", ";", "}", "_", ".", "each", "(", "dimensions", ",", "function", "(", "val", ",", "key", ")", "{", "if", "(", "!", "_", ".", "isString", "(", "key", ")", "||", "!", "_", ".", "isString", "(", "val", ")", ")", "{", "throw", "'track() dimensions expects keys and values of type \"string\".'", ";", "}", "}", ")", ";", "return", "Parse", ".", "_request", "(", "{", "route", ":", "'events'", ",", "className", ":", "name", ",", "method", ":", "'POST'", ",", "data", ":", "{", "dimensions", ":", "dimensions", "}", "}", ")", ";", "}" ]
Tracks the occurrence of a custom event with additional dimensions. Parse will store a data point at the time of invocation with the given event name. Dimensions will allow segmentation of the occurrences of this custom event. Keys and values should be {@code String}s, and will throw otherwise. To track a user signup along with additional metadata, consider the following: <pre> var dimensions = { gender: 'm', source: 'web', dayType: 'weekend' }; Parse.Analytics.track('signup', dimensions); </pre> There is a default limit of 4 dimensions per event tracked. @param {String} name The name of the custom event to report to Parse as having happened. @param {Object} dimensions The dictionary of information by which to segment this event. @return {Parse.Promise} A promise that is resolved when the round-trip to the server completes.
[ "Tracks", "the", "occurrence", "of", "a", "custom", "event", "with", "additional", "dimensions", ".", "Parse", "will", "store", "a", "data", "point", "at", "the", "time", "of", "invocation", "with", "the", "given", "event", "name", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/analytics.js#L40-L60
train
relief-melone/limitpromises
src/services/service.retryPromiseTimeout.js
retryPromiseTimeout
function retryPromiseTimeout(PromiseFunc, Obj, Options){ let timeoutOpts = Options.Timeout; limitpromises = limitpromises || require('../limitpromises'); setTimeout( () => { if(Obj.isRunning && Obj.attempt <= timeoutOpts.retryAttempts){ // Put a new promise on the same stack as the current one is, so you dont call more promises of one // group as specified. Input Value is just true as we dont need it and only make one promise let newPromise = limitpromises( () =>{ return new Promise((resolve, reject) => { PromiseFunc(Obj.inputValue).then(data => { resolve(data); }, err => { reject(err); }); }); },[true], Obj.maxAtOnce, Obj.TypeKey); // Wait for the PromiseArray and either resolve the current promise or handle the rejects Promise.all(newPromise.map(r => {return r.result})).then(data => { if(Obj.isRunning){ Obj.resolveResult(data); } }, err => { if(Obj.isRunning){ handleRejects(PromiseFunc, Obj, err, Options); } }); // Call the function again to check again after a given time retryPromiseTimeout(PromiseFunc, Obj, Options); // Count that an attempt has been made for that object Obj.attempt++; // If more retry attempts have been made than specified by the user, reject the result } else if (Obj.isRunning && Obj.attempt > timeoutOpts.retryAttempts){ Obj.rejectResult(new Error.TimeoutError(Obj)); } }, timeoutOpts.timeoutMillis); }
javascript
function retryPromiseTimeout(PromiseFunc, Obj, Options){ let timeoutOpts = Options.Timeout; limitpromises = limitpromises || require('../limitpromises'); setTimeout( () => { if(Obj.isRunning && Obj.attempt <= timeoutOpts.retryAttempts){ // Put a new promise on the same stack as the current one is, so you dont call more promises of one // group as specified. Input Value is just true as we dont need it and only make one promise let newPromise = limitpromises( () =>{ return new Promise((resolve, reject) => { PromiseFunc(Obj.inputValue).then(data => { resolve(data); }, err => { reject(err); }); }); },[true], Obj.maxAtOnce, Obj.TypeKey); // Wait for the PromiseArray and either resolve the current promise or handle the rejects Promise.all(newPromise.map(r => {return r.result})).then(data => { if(Obj.isRunning){ Obj.resolveResult(data); } }, err => { if(Obj.isRunning){ handleRejects(PromiseFunc, Obj, err, Options); } }); // Call the function again to check again after a given time retryPromiseTimeout(PromiseFunc, Obj, Options); // Count that an attempt has been made for that object Obj.attempt++; // If more retry attempts have been made than specified by the user, reject the result } else if (Obj.isRunning && Obj.attempt > timeoutOpts.retryAttempts){ Obj.rejectResult(new Error.TimeoutError(Obj)); } }, timeoutOpts.timeoutMillis); }
[ "function", "retryPromiseTimeout", "(", "PromiseFunc", ",", "Obj", ",", "Options", ")", "{", "let", "timeoutOpts", "=", "Options", ".", "Timeout", ";", "limitpromises", "=", "limitpromises", "||", "require", "(", "'../limitpromises'", ")", ";", "setTimeout", "(", "(", ")", "=>", "{", "if", "(", "Obj", ".", "isRunning", "&&", "Obj", ".", "attempt", "<=", "timeoutOpts", ".", "retryAttempts", ")", "{", "let", "newPromise", "=", "limitpromises", "(", "(", ")", "=>", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "PromiseFunc", "(", "Obj", ".", "inputValue", ")", ".", "then", "(", "data", "=>", "{", "resolve", "(", "data", ")", ";", "}", ",", "err", "=>", "{", "reject", "(", "err", ")", ";", "}", ")", ";", "}", ")", ";", "}", ",", "[", "true", "]", ",", "Obj", ".", "maxAtOnce", ",", "Obj", ".", "TypeKey", ")", ";", "Promise", ".", "all", "(", "newPromise", ".", "map", "(", "r", "=>", "{", "return", "r", ".", "result", "}", ")", ")", ".", "then", "(", "data", "=>", "{", "if", "(", "Obj", ".", "isRunning", ")", "{", "Obj", ".", "resolveResult", "(", "data", ")", ";", "}", "}", ",", "err", "=>", "{", "if", "(", "Obj", ".", "isRunning", ")", "{", "handleRejects", "(", "PromiseFunc", ",", "Obj", ",", "err", ",", "Options", ")", ";", "}", "}", ")", ";", "retryPromiseTimeout", "(", "PromiseFunc", ",", "Obj", ",", "Options", ")", ";", "Obj", ".", "attempt", "++", ";", "}", "else", "if", "(", "Obj", ".", "isRunning", "&&", "Obj", ".", "attempt", ">", "timeoutOpts", ".", "retryAttempts", ")", "{", "Obj", ".", "rejectResult", "(", "new", "Error", ".", "TimeoutError", "(", "Obj", ")", ")", ";", "}", "}", ",", "timeoutOpts", ".", "timeoutMillis", ")", ";", "}" ]
Handles Timeout of promises @public @param {Function} PromiseFunc Function that returns a Promise with one InputParameter that is used @param {Object} Obj The Object holding the current Promise request @param {Object} Options Options that have been specified by the user @returns {void}
[ "Handles", "Timeout", "of", "promises" ]
1735b92749740204b597c1c6026257d54ade8200
https://github.com/relief-melone/limitpromises/blob/1735b92749740204b597c1c6026257d54ade8200/src/services/service.retryPromiseTimeout.js#L17-L56
train
Zingle/http-later-redis
index.js
queue
function queue(task, done) { var storage = this, key = this.keygen(task); // store task as JSON serialized string task = JSON.stringify(task); // first add the key to the queue this.redis().rpush(this.queueKey(), key, function(err) { if (err) done(err); // now store task data else storage.redis().set(key, task, function(err) { if (err) done(err); else done(null, key); }); }); }
javascript
function queue(task, done) { var storage = this, key = this.keygen(task); // store task as JSON serialized string task = JSON.stringify(task); // first add the key to the queue this.redis().rpush(this.queueKey(), key, function(err) { if (err) done(err); // now store task data else storage.redis().set(key, task, function(err) { if (err) done(err); else done(null, key); }); }); }
[ "function", "queue", "(", "task", ",", "done", ")", "{", "var", "storage", "=", "this", ",", "key", "=", "this", ".", "keygen", "(", "task", ")", ";", "task", "=", "JSON", ".", "stringify", "(", "task", ")", ";", "this", ".", "redis", "(", ")", ".", "rpush", "(", "this", ".", "queueKey", "(", ")", ",", "key", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "done", "(", "err", ")", ";", "else", "storage", ".", "redis", "(", ")", ".", "set", "(", "key", ",", "task", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "done", "(", "err", ")", ";", "else", "done", "(", "null", ",", "key", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Queue a serialized request and pass the storage key to the callback. @param {object} task @param {function} done
[ "Queue", "a", "serialized", "request", "and", "pass", "the", "storage", "key", "to", "the", "callback", "." ]
43008afabb2800400557a66857d41818e22b0623
https://github.com/Zingle/http-later-redis/blob/43008afabb2800400557a66857d41818e22b0623/index.js#L10-L27
train
Zingle/http-later-redis
index.js
unqueue
function unqueue(done) { var storage = this; this.redis().lpop(this.queueKey(), function(err, key) { if (err) return done(err); storage.redis().get(key, function(err, task) { if (err) return done(err); if (!task) return done(); storage.redis().del(key); done(null, JSON.parse(task), key); }); }); }
javascript
function unqueue(done) { var storage = this; this.redis().lpop(this.queueKey(), function(err, key) { if (err) return done(err); storage.redis().get(key, function(err, task) { if (err) return done(err); if (!task) return done(); storage.redis().del(key); done(null, JSON.parse(task), key); }); }); }
[ "function", "unqueue", "(", "done", ")", "{", "var", "storage", "=", "this", ";", "this", ".", "redis", "(", ")", ".", "lpop", "(", "this", ".", "queueKey", "(", ")", ",", "function", "(", "err", ",", "key", ")", "{", "if", "(", "err", ")", "return", "done", "(", "err", ")", ";", "storage", ".", "redis", "(", ")", ".", "get", "(", "key", ",", "function", "(", "err", ",", "task", ")", "{", "if", "(", "err", ")", "return", "done", "(", "err", ")", ";", "if", "(", "!", "task", ")", "return", "done", "(", ")", ";", "storage", ".", "redis", "(", ")", ".", "del", "(", "key", ")", ";", "done", "(", "null", ",", "JSON", ".", "parse", "(", "task", ")", ",", "key", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Remove a task from the queue and pass it to the callback. @param {function} done
[ "Remove", "a", "task", "from", "the", "queue", "and", "pass", "it", "to", "the", "callback", "." ]
43008afabb2800400557a66857d41818e22b0623
https://github.com/Zingle/http-later-redis/blob/43008afabb2800400557a66857d41818e22b0623/index.js#L33-L47
train
Zingle/http-later-redis
index.js
log
function log(key, result, done) { var storage = this; // store result as JSON serialized string result = JSON.stringify(result); // generate result key from task key key = key + "-result"; // first add the key to the log this.redis().rpush(this.logKey(), key, function(err) { if (err) done(err); // now store result data else storage.redis().set(key, result, done); }); }
javascript
function log(key, result, done) { var storage = this; // store result as JSON serialized string result = JSON.stringify(result); // generate result key from task key key = key + "-result"; // first add the key to the log this.redis().rpush(this.logKey(), key, function(err) { if (err) done(err); // now store result data else storage.redis().set(key, result, done); }); }
[ "function", "log", "(", "key", ",", "result", ",", "done", ")", "{", "var", "storage", "=", "this", ";", "result", "=", "JSON", ".", "stringify", "(", "result", ")", ";", "key", "=", "key", "+", "\"-result\"", ";", "this", ".", "redis", "(", ")", ".", "rpush", "(", "this", ".", "logKey", "(", ")", ",", "key", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "done", "(", "err", ")", ";", "else", "storage", ".", "redis", "(", ")", ".", "set", "(", "key", ",", "result", ",", "done", ")", ";", "}", ")", ";", "}" ]
Log task result. @param {string} key @param {object} result @param {function} done
[ "Log", "task", "result", "." ]
43008afabb2800400557a66857d41818e22b0623
https://github.com/Zingle/http-later-redis/blob/43008afabb2800400557a66857d41818e22b0623/index.js#L55-L71
train