repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
switer/gulp-here
lib/tag.js
function (str) { // here:xx:xxx??inline var matches = /^<!--\s*here\:(.*?)\s*-->$/.exec(str.trim()) if (!matches || !matches[1]) return null var expr = matches[1] var parts = expr.split('??') var query = querystring.parse(parts[1] || '') var isInline = ('inline' in query) && query.inline != 'false' var isWrapping = query.wrap !== 'false' var namespace = '' var reg expr = parts[0] parts = expr.split(':') if (parts.length > 1) { namespace = parts.shift() } reg = new RegExp(parts.pop()) return { regexp: reg, // resource match validate regexp namespace: namespace, // resource namespace match inline: isInline, // whether inline resource or not wrap: isWrapping } }
javascript
function (str) { // here:xx:xxx??inline var matches = /^<!--\s*here\:(.*?)\s*-->$/.exec(str.trim()) if (!matches || !matches[1]) return null var expr = matches[1] var parts = expr.split('??') var query = querystring.parse(parts[1] || '') var isInline = ('inline' in query) && query.inline != 'false' var isWrapping = query.wrap !== 'false' var namespace = '' var reg expr = parts[0] parts = expr.split(':') if (parts.length > 1) { namespace = parts.shift() } reg = new RegExp(parts.pop()) return { regexp: reg, // resource match validate regexp namespace: namespace, // resource namespace match inline: isInline, // whether inline resource or not wrap: isWrapping } }
[ "function", "(", "str", ")", "{", "var", "matches", "=", "/", "^<!--\\s*here\\:(.*?)\\s*", "/", ".", "exec", "(", "str", ".", "trim", "(", ")", ")", "if", "(", "!", "matches", "||", "!", "matches", "[", "1", "]", ")", "return", "null", "var", "expr", "=", "matches", "[", "1", "]", "var", "parts", "=", "expr", ".", "split", "(", "'??'", ")", "var", "query", "=", "querystring", ".", "parse", "(", "parts", "[", "1", "]", "||", "''", ")", "var", "isInline", "=", "(", "'inline'", "in", "query", ")", "&&", "query", ".", "inline", "!=", "'false'", "var", "isWrapping", "=", "query", ".", "wrap", "!==", "'false'", "var", "namespace", "=", "''", "var", "reg", "expr", "=", "parts", "[", "0", "]", "parts", "=", "expr", ".", "split", "(", "':'", ")", "if", "(", "parts", ".", "length", ">", "1", ")", "{", "namespace", "=", "parts", ".", "shift", "(", ")", "}", "reg", "=", "new", "RegExp", "(", "parts", ".", "pop", "(", ")", ")", "return", "{", "regexp", ":", "reg", ",", "namespace", ":", "namespace", ",", "inline", ":", "isInline", ",", "wrap", ":", "isWrapping", "}", "}" ]
Here' tag expression parse functon
[ "Here", "tag", "expression", "parse", "functon" ]
911023a99bf0086b04d2198e5b9eb5b7bd8d2ae5
https://github.com/switer/gulp-here/blob/911023a99bf0086b04d2198e5b9eb5b7bd8d2ae5/lib/tag.js#L77-L102
train
thlorenz/pretty-trace
pretty-trace.js
prettyLines
function prettyLines(lines, theme) { if (!lines || !Array.isArray(lines)) throw new Error('Please supply an array of lines'); if (!theme) throw new Error('Please supply a theme'); function prettify(line) { if (!line) return null; return exports.line(line, theme); } return lines.map(prettify); }
javascript
function prettyLines(lines, theme) { if (!lines || !Array.isArray(lines)) throw new Error('Please supply an array of lines'); if (!theme) throw new Error('Please supply a theme'); function prettify(line) { if (!line) return null; return exports.line(line, theme); } return lines.map(prettify); }
[ "function", "prettyLines", "(", "lines", ",", "theme", ")", "{", "if", "(", "!", "lines", "||", "!", "Array", ".", "isArray", "(", "lines", ")", ")", "throw", "new", "Error", "(", "'Please supply an array of lines'", ")", ";", "if", "(", "!", "theme", ")", "throw", "new", "Error", "(", "'Please supply a theme'", ")", ";", "function", "prettify", "(", "line", ")", "{", "if", "(", "!", "line", ")", "return", "null", ";", "return", "exports", ".", "line", "(", "line", ",", "theme", ")", ";", "}", "return", "lines", ".", "map", "(", "prettify", ")", ";", "}" ]
Prettifies multiple lines. @name prettyTrace::lines @function @param {Array.<string>} lines lines to be prettified @param {Object} theme theme that specifies how to prettify a trace @see prettyTrace::line @return {Array.<string>} the prettified lines
[ "Prettifies", "multiple", "lines", "." ]
ecf0b0fd236459e260b20c8a8199a024ef8ceb62
https://github.com/thlorenz/pretty-trace/blob/ecf0b0fd236459e260b20c8a8199a024ef8ceb62/pretty-trace.js#L171-L181
train
anyfs/glob-stream-plugin
index.js
function(fs, ourGlob, negatives, opt) { // remove path relativity to make globs make sense ourGlob = resolveGlob(fs, ourGlob, opt); var ourOpt = extend({}, opt); delete ourOpt.root; // create globbing stuff var globber = new glob.Glob(fs, ourGlob, ourOpt); // extract base path from glob var basePath = opt.base || glob2base(globber); // create stream and map events from globber to it var stream = through2.obj(negatives.length ? filterNegatives : undefined); var found = false; globber.on('error', stream.emit.bind(stream, 'error')); globber.once('end', function(){ if (opt.allowEmpty !== true && !found && globIsSingular(globber)) { stream.emit('error', new Error('File not found with singular glob')); } stream.end(); }); globber.on('match', function(filename) { found = true; stream.write({ cwd: opt.cwd, base: basePath, path: fs.resolve(opt.cwd, filename) }); }); return stream; function filterNegatives(filename, enc, cb) { var matcha = isMatch.bind(null, filename); if (negatives.every(matcha)) { cb(null, filename); // pass } else { cb(); // ignore } } }
javascript
function(fs, ourGlob, negatives, opt) { // remove path relativity to make globs make sense ourGlob = resolveGlob(fs, ourGlob, opt); var ourOpt = extend({}, opt); delete ourOpt.root; // create globbing stuff var globber = new glob.Glob(fs, ourGlob, ourOpt); // extract base path from glob var basePath = opt.base || glob2base(globber); // create stream and map events from globber to it var stream = through2.obj(negatives.length ? filterNegatives : undefined); var found = false; globber.on('error', stream.emit.bind(stream, 'error')); globber.once('end', function(){ if (opt.allowEmpty !== true && !found && globIsSingular(globber)) { stream.emit('error', new Error('File not found with singular glob')); } stream.end(); }); globber.on('match', function(filename) { found = true; stream.write({ cwd: opt.cwd, base: basePath, path: fs.resolve(opt.cwd, filename) }); }); return stream; function filterNegatives(filename, enc, cb) { var matcha = isMatch.bind(null, filename); if (negatives.every(matcha)) { cb(null, filename); // pass } else { cb(); // ignore } } }
[ "function", "(", "fs", ",", "ourGlob", ",", "negatives", ",", "opt", ")", "{", "ourGlob", "=", "resolveGlob", "(", "fs", ",", "ourGlob", ",", "opt", ")", ";", "var", "ourOpt", "=", "extend", "(", "{", "}", ",", "opt", ")", ";", "delete", "ourOpt", ".", "root", ";", "var", "globber", "=", "new", "glob", ".", "Glob", "(", "fs", ",", "ourGlob", ",", "ourOpt", ")", ";", "var", "basePath", "=", "opt", ".", "base", "||", "glob2base", "(", "globber", ")", ";", "var", "stream", "=", "through2", ".", "obj", "(", "negatives", ".", "length", "?", "filterNegatives", ":", "undefined", ")", ";", "var", "found", "=", "false", ";", "globber", ".", "on", "(", "'error'", ",", "stream", ".", "emit", ".", "bind", "(", "stream", ",", "'error'", ")", ")", ";", "globber", ".", "once", "(", "'end'", ",", "function", "(", ")", "{", "if", "(", "opt", ".", "allowEmpty", "!==", "true", "&&", "!", "found", "&&", "globIsSingular", "(", "globber", ")", ")", "{", "stream", ".", "emit", "(", "'error'", ",", "new", "Error", "(", "'File not found with singular glob'", ")", ")", ";", "}", "stream", ".", "end", "(", ")", ";", "}", ")", ";", "globber", ".", "on", "(", "'match'", ",", "function", "(", "filename", ")", "{", "found", "=", "true", ";", "stream", ".", "write", "(", "{", "cwd", ":", "opt", ".", "cwd", ",", "base", ":", "basePath", ",", "path", ":", "fs", ".", "resolve", "(", "opt", ".", "cwd", ",", "filename", ")", "}", ")", ";", "}", ")", ";", "return", "stream", ";", "function", "filterNegatives", "(", "filename", ",", "enc", ",", "cb", ")", "{", "var", "matcha", "=", "isMatch", ".", "bind", "(", "null", ",", "filename", ")", ";", "if", "(", "negatives", ".", "every", "(", "matcha", ")", ")", "{", "cb", "(", "null", ",", "filename", ")", ";", "}", "else", "{", "cb", "(", ")", ";", "}", "}", "}" ]
creates a stream for a single glob or filter
[ "creates", "a", "stream", "for", "a", "single", "glob", "or", "filter" ]
e2f90ccc5627511632cec2bff1b32dfc44372f23
https://github.com/anyfs/glob-stream-plugin/blob/e2f90ccc5627511632cec2bff1b32dfc44372f23/index.js#L16-L61
train
anyfs/glob-stream-plugin
index.js
function(fs, globs, opt) { if (!opt) opt = {}; if (typeof opt.cwd !== 'string') opt.cwd = fs.resolve('.'); if (typeof opt.dot !== 'boolean') opt.dot = false; if (typeof opt.silent !== 'boolean') opt.silent = true; if (typeof opt.nonull !== 'boolean') opt.nonull = false; if (typeof opt.cwdbase !== 'boolean') opt.cwdbase = false; if (opt.cwdbase) opt.base = opt.cwd; // only one glob no need to aggregate if (!Array.isArray(globs)) globs = [globs]; var positives = []; var negatives = []; var ourOpt = extend({}, opt); delete ourOpt.root; globs.forEach(function(glob, index) { if (typeof glob !== 'string' && !(glob instanceof RegExp)) { throw new Error('Invalid glob at index ' + index); } var globArray = isNegative(glob) ? negatives : positives; // create Minimatch instances for negative glob patterns if (globArray === negatives && typeof glob === 'string') { var ourGlob = resolveGlob(glob, opt); glob = new Minimatch(ourGlob, ourOpt); } globArray.push({ index: index, glob: glob }); }); if (positives.length === 0) throw new Error('Missing positive glob'); // only one positive glob no need to aggregate if (positives.length === 1) return streamFromPositive(positives[0]); // create all individual streams var streams = positives.map(streamFromPositive); // then just pipe them to a single unique stream and return it var aggregate = new Combine(streams); var uniqueStream = unique('path'); var returnStream = aggregate.pipe(uniqueStream); aggregate.on('error', function (err) { returnStream.emit('error', err); }); return returnStream; function streamFromPositive(positive) { var negativeGlobs = negatives.filter(indexGreaterThan(positive.index)).map(toGlob); return gs.createStream(fs, positive.glob, negativeGlobs, opt); } }
javascript
function(fs, globs, opt) { if (!opt) opt = {}; if (typeof opt.cwd !== 'string') opt.cwd = fs.resolve('.'); if (typeof opt.dot !== 'boolean') opt.dot = false; if (typeof opt.silent !== 'boolean') opt.silent = true; if (typeof opt.nonull !== 'boolean') opt.nonull = false; if (typeof opt.cwdbase !== 'boolean') opt.cwdbase = false; if (opt.cwdbase) opt.base = opt.cwd; // only one glob no need to aggregate if (!Array.isArray(globs)) globs = [globs]; var positives = []; var negatives = []; var ourOpt = extend({}, opt); delete ourOpt.root; globs.forEach(function(glob, index) { if (typeof glob !== 'string' && !(glob instanceof RegExp)) { throw new Error('Invalid glob at index ' + index); } var globArray = isNegative(glob) ? negatives : positives; // create Minimatch instances for negative glob patterns if (globArray === negatives && typeof glob === 'string') { var ourGlob = resolveGlob(glob, opt); glob = new Minimatch(ourGlob, ourOpt); } globArray.push({ index: index, glob: glob }); }); if (positives.length === 0) throw new Error('Missing positive glob'); // only one positive glob no need to aggregate if (positives.length === 1) return streamFromPositive(positives[0]); // create all individual streams var streams = positives.map(streamFromPositive); // then just pipe them to a single unique stream and return it var aggregate = new Combine(streams); var uniqueStream = unique('path'); var returnStream = aggregate.pipe(uniqueStream); aggregate.on('error', function (err) { returnStream.emit('error', err); }); return returnStream; function streamFromPositive(positive) { var negativeGlobs = negatives.filter(indexGreaterThan(positive.index)).map(toGlob); return gs.createStream(fs, positive.glob, negativeGlobs, opt); } }
[ "function", "(", "fs", ",", "globs", ",", "opt", ")", "{", "if", "(", "!", "opt", ")", "opt", "=", "{", "}", ";", "if", "(", "typeof", "opt", ".", "cwd", "!==", "'string'", ")", "opt", ".", "cwd", "=", "fs", ".", "resolve", "(", "'.'", ")", ";", "if", "(", "typeof", "opt", ".", "dot", "!==", "'boolean'", ")", "opt", ".", "dot", "=", "false", ";", "if", "(", "typeof", "opt", ".", "silent", "!==", "'boolean'", ")", "opt", ".", "silent", "=", "true", ";", "if", "(", "typeof", "opt", ".", "nonull", "!==", "'boolean'", ")", "opt", ".", "nonull", "=", "false", ";", "if", "(", "typeof", "opt", ".", "cwdbase", "!==", "'boolean'", ")", "opt", ".", "cwdbase", "=", "false", ";", "if", "(", "opt", ".", "cwdbase", ")", "opt", ".", "base", "=", "opt", ".", "cwd", ";", "if", "(", "!", "Array", ".", "isArray", "(", "globs", ")", ")", "globs", "=", "[", "globs", "]", ";", "var", "positives", "=", "[", "]", ";", "var", "negatives", "=", "[", "]", ";", "var", "ourOpt", "=", "extend", "(", "{", "}", ",", "opt", ")", ";", "delete", "ourOpt", ".", "root", ";", "globs", ".", "forEach", "(", "function", "(", "glob", ",", "index", ")", "{", "if", "(", "typeof", "glob", "!==", "'string'", "&&", "!", "(", "glob", "instanceof", "RegExp", ")", ")", "{", "throw", "new", "Error", "(", "'Invalid glob at index '", "+", "index", ")", ";", "}", "var", "globArray", "=", "isNegative", "(", "glob", ")", "?", "negatives", ":", "positives", ";", "if", "(", "globArray", "===", "negatives", "&&", "typeof", "glob", "===", "'string'", ")", "{", "var", "ourGlob", "=", "resolveGlob", "(", "glob", ",", "opt", ")", ";", "glob", "=", "new", "Minimatch", "(", "ourGlob", ",", "ourOpt", ")", ";", "}", "globArray", ".", "push", "(", "{", "index", ":", "index", ",", "glob", ":", "glob", "}", ")", ";", "}", ")", ";", "if", "(", "positives", ".", "length", "===", "0", ")", "throw", "new", "Error", "(", "'Missing positive glob'", ")", ";", "if", "(", "positives", ".", "length", "===", "1", ")", "return", "streamFromPositive", "(", "positives", "[", "0", "]", ")", ";", "var", "streams", "=", "positives", ".", "map", "(", "streamFromPositive", ")", ";", "var", "aggregate", "=", "new", "Combine", "(", "streams", ")", ";", "var", "uniqueStream", "=", "unique", "(", "'path'", ")", ";", "var", "returnStream", "=", "aggregate", ".", "pipe", "(", "uniqueStream", ")", ";", "aggregate", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "returnStream", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", ")", ";", "return", "returnStream", ";", "function", "streamFromPositive", "(", "positive", ")", "{", "var", "negativeGlobs", "=", "negatives", ".", "filter", "(", "indexGreaterThan", "(", "positive", ".", "index", ")", ")", ".", "map", "(", "toGlob", ")", ";", "return", "gs", ".", "createStream", "(", "fs", ",", "positive", ".", "glob", ",", "negativeGlobs", ",", "opt", ")", ";", "}", "}" ]
creates a stream for multiple globs or filters
[ "creates", "a", "stream", "for", "multiple", "globs", "or", "filters" ]
e2f90ccc5627511632cec2bff1b32dfc44372f23
https://github.com/anyfs/glob-stream-plugin/blob/e2f90ccc5627511632cec2bff1b32dfc44372f23/index.js#L64-L124
train
wronex/node-conquer
bin/conquer.js
extensionsParser
function extensionsParser(str) { // Convert the file extensions string to a list. var list = str.split(','); for (var i = 0; i < list.length; i++) { // Make sure the file extension has the correct format: '.ext' var ext = '.' + list[i].replace(/(^\s?\.?)|(\s?$)/g, ''); list[i] = ext.toLowerCase(); } return list; }
javascript
function extensionsParser(str) { // Convert the file extensions string to a list. var list = str.split(','); for (var i = 0; i < list.length; i++) { // Make sure the file extension has the correct format: '.ext' var ext = '.' + list[i].replace(/(^\s?\.?)|(\s?$)/g, ''); list[i] = ext.toLowerCase(); } return list; }
[ "function", "extensionsParser", "(", "str", ")", "{", "var", "list", "=", "str", ".", "split", "(", "','", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "list", ".", "length", ";", "i", "++", ")", "{", "var", "ext", "=", "'.'", "+", "list", "[", "i", "]", ".", "replace", "(", "/", "(^\\s?\\.?)|(\\s?$)", "/", "g", ",", "''", ")", ";", "list", "[", "i", "]", "=", "ext", ".", "toLowerCase", "(", ")", ";", "}", "return", "list", ";", "}" ]
connected client of changes made to files. This will allow browsers to refresh their page. The WebSocket client will be sent 'restart' when the script is restarted and 'exit' when the script exists. Parses the supplied string of comma seperated file extensions and returns an array of its values. @param {String} str - a string on the format ".ext1,.ext2,.ext3". @retruns {String[]} - a list of all the found extensions in @a str.
[ "connected", "client", "of", "changes", "made", "to", "files", ".", "This", "will", "allow", "browsers", "to", "refresh", "their", "page", ".", "The", "WebSocket", "client", "will", "be", "sent", "restart", "when", "the", "script", "is", "restarted", "and", "exit", "when", "the", "script", "exists", ".", "Parses", "the", "supplied", "string", "of", "comma", "seperated", "file", "extensions", "and", "returns", "an", "array", "of", "its", "values", "." ]
48fa586d1fad15ad544d143d1ba4b97172fed0f1
https://github.com/wronex/node-conquer/blob/48fa586d1fad15ad544d143d1ba4b97172fed0f1/bin/conquer.js#L36-L45
train
wronex/node-conquer
bin/conquer.js
listParser
function listParser(str) { var list = str.split(','); for (var i = 0; i < list.length; i++) list[i] = list[i].replace(/(^\s?)|(\s?$)/g, ''); return list; }
javascript
function listParser(str) { var list = str.split(','); for (var i = 0; i < list.length; i++) list[i] = list[i].replace(/(^\s?)|(\s?$)/g, ''); return list; }
[ "function", "listParser", "(", "str", ")", "{", "var", "list", "=", "str", ".", "split", "(", "','", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "list", ".", "length", ";", "i", "++", ")", "list", "[", "i", "]", "=", "list", "[", "i", "]", ".", "replace", "(", "/", "(^\\s?)|(\\s?$)", "/", "g", ",", "''", ")", ";", "return", "list", ";", "}" ]
Parses the supplied string of comma seperated list and returns an array of its values. @param {String} str - a string on the format "value1, value2, value2". @retruns {String[]} - a list of all the found extensions in @a str.
[ "Parses", "the", "supplied", "string", "of", "comma", "seperated", "list", "and", "returns", "an", "array", "of", "its", "values", "." ]
48fa586d1fad15ad544d143d1ba4b97172fed0f1
https://github.com/wronex/node-conquer/blob/48fa586d1fad15ad544d143d1ba4b97172fed0f1/bin/conquer.js#L53-L58
train
wronex/node-conquer
bin/conquer.js
kill
function kill(noMsg, signal) { if (!instance) return false; try { if (signal) instance.kill(signal); else process.kill(instance.pid); if ((noMsg || false) !== true) logger.log('Killed', clc.green(script)); } catch (ex) { // Process was already dead. return false; } return true; }
javascript
function kill(noMsg, signal) { if (!instance) return false; try { if (signal) instance.kill(signal); else process.kill(instance.pid); if ((noMsg || false) !== true) logger.log('Killed', clc.green(script)); } catch (ex) { // Process was already dead. return false; } return true; }
[ "function", "kill", "(", "noMsg", ",", "signal", ")", "{", "if", "(", "!", "instance", ")", "return", "false", ";", "try", "{", "if", "(", "signal", ")", "instance", ".", "kill", "(", "signal", ")", ";", "else", "process", ".", "kill", "(", "instance", ".", "pid", ")", ";", "if", "(", "(", "noMsg", "||", "false", ")", "!==", "true", ")", "logger", ".", "log", "(", "'Killed'", ",", "clc", ".", "green", "(", "script", ")", ")", ";", "}", "catch", "(", "ex", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Kills the parser. @param {Boolean} [noMsg] - indicates if no message should be written to the log. Defaults to false. @param {String} [signal] - indicates which kill signal that sould be sent toLowerCase the child process (only applicable on Linux). Defaults to null. @return {Bool} - true if the process was killed; otherwise false.
[ "Kills", "the", "parser", "." ]
48fa586d1fad15ad544d143d1ba4b97172fed0f1
https://github.com/wronex/node-conquer/blob/48fa586d1fad15ad544d143d1ba4b97172fed0f1/bin/conquer.js#L68-L86
train
wronex/node-conquer
bin/conquer.js
restart
function restart() { logger.log('Restarting', clc.green(script)); notifyWebSocket('restart'); if (!kill(true)) { // The process wasn't running, start it now. start(true); } /*else { // The process will restart when its 'exit' event is emitted. }*/ }
javascript
function restart() { logger.log('Restarting', clc.green(script)); notifyWebSocket('restart'); if (!kill(true)) { // The process wasn't running, start it now. start(true); } /*else { // The process will restart when its 'exit' event is emitted. }*/ }
[ "function", "restart", "(", ")", "{", "logger", ".", "log", "(", "'Restarting'", ",", "clc", ".", "green", "(", "script", ")", ")", ";", "notifyWebSocket", "(", "'restart'", ")", ";", "if", "(", "!", "kill", "(", "true", ")", ")", "{", "start", "(", "true", ")", ";", "}", "}" ]
Restarts the parser.
[ "Restarts", "the", "parser", "." ]
48fa586d1fad15ad544d143d1ba4b97172fed0f1
https://github.com/wronex/node-conquer/blob/48fa586d1fad15ad544d143d1ba4b97172fed0f1/bin/conquer.js#L89-L98
train
wronex/node-conquer
bin/conquer.js
notifyWebSocket
function notifyWebSocket(message) { if (!webSocketServer || !message) return; // Send the message to all connection in the WebSocket server. for (var value in webSocketServer.conn) { var connection = webSocketServer.conn[value]; if (connection) connection.send(message) } }
javascript
function notifyWebSocket(message) { if (!webSocketServer || !message) return; // Send the message to all connection in the WebSocket server. for (var value in webSocketServer.conn) { var connection = webSocketServer.conn[value]; if (connection) connection.send(message) } }
[ "function", "notifyWebSocket", "(", "message", ")", "{", "if", "(", "!", "webSocketServer", "||", "!", "message", ")", "return", ";", "for", "(", "var", "value", "in", "webSocketServer", ".", "conn", ")", "{", "var", "connection", "=", "webSocketServer", ".", "conn", "[", "value", "]", ";", "if", "(", "connection", ")", "connection", ".", "send", "(", "message", ")", "}", "}" ]
Notifies all connection WebSocket clients by sending them the supplied message. @param message {String} - a message that will be sent to all WebSocket clients currently connected.
[ "Notifies", "all", "connection", "WebSocket", "clients", "by", "sending", "them", "the", "supplied", "message", "." ]
48fa586d1fad15ad544d143d1ba4b97172fed0f1
https://github.com/wronex/node-conquer/blob/48fa586d1fad15ad544d143d1ba4b97172fed0f1/bin/conquer.js#L106-L116
train
wronex/node-conquer
bin/conquer.js
start
function start(noMsg) { if ((noMsg || false) !== true) logger.log('Starting', clc.green(script), 'with', clc.magenta(parser)); if (instance) return; // Spawn an instance of the parser that will run the script. instance = spawn(parser, parserParams); // Redirect the parser/script's output to the console. instance.stdout.on('data', function (data) { logger.scriptLog(scriptName, data.toString()); }); instance.stderr.on('data', function (data) { logger.scriptLog(scriptName, data.toString(), true); }); instance.stderr.on('data', function (data) { if (/^execvp\(\)/.test(data.toString())) { logger.error('Failed to restart child process.'); process.exit(0); } }); instance.on('exit', function (code, signal) { instance = null; if (signal == 'SIGUSR2') { logger.error('Signal interuption'); start(); return; } logger.log(clc.green(script), 'exited with code', clc.yellow(code)); notifyWebSocket('exit'); if (keepAlive || (restartOnCleanExit && code == 0)) { start(); return; } }); }
javascript
function start(noMsg) { if ((noMsg || false) !== true) logger.log('Starting', clc.green(script), 'with', clc.magenta(parser)); if (instance) return; // Spawn an instance of the parser that will run the script. instance = spawn(parser, parserParams); // Redirect the parser/script's output to the console. instance.stdout.on('data', function (data) { logger.scriptLog(scriptName, data.toString()); }); instance.stderr.on('data', function (data) { logger.scriptLog(scriptName, data.toString(), true); }); instance.stderr.on('data', function (data) { if (/^execvp\(\)/.test(data.toString())) { logger.error('Failed to restart child process.'); process.exit(0); } }); instance.on('exit', function (code, signal) { instance = null; if (signal == 'SIGUSR2') { logger.error('Signal interuption'); start(); return; } logger.log(clc.green(script), 'exited with code', clc.yellow(code)); notifyWebSocket('exit'); if (keepAlive || (restartOnCleanExit && code == 0)) { start(); return; } }); }
[ "function", "start", "(", "noMsg", ")", "{", "if", "(", "(", "noMsg", "||", "false", ")", "!==", "true", ")", "logger", ".", "log", "(", "'Starting'", ",", "clc", ".", "green", "(", "script", ")", ",", "'with'", ",", "clc", ".", "magenta", "(", "parser", ")", ")", ";", "if", "(", "instance", ")", "return", ";", "instance", "=", "spawn", "(", "parser", ",", "parserParams", ")", ";", "instance", ".", "stdout", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "logger", ".", "scriptLog", "(", "scriptName", ",", "data", ".", "toString", "(", ")", ")", ";", "}", ")", ";", "instance", ".", "stderr", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "logger", ".", "scriptLog", "(", "scriptName", ",", "data", ".", "toString", "(", ")", ",", "true", ")", ";", "}", ")", ";", "instance", ".", "stderr", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "if", "(", "/", "^execvp\\(\\)", "/", ".", "test", "(", "data", ".", "toString", "(", ")", ")", ")", "{", "logger", ".", "error", "(", "'Failed to restart child process.'", ")", ";", "process", ".", "exit", "(", "0", ")", ";", "}", "}", ")", ";", "instance", ".", "on", "(", "'exit'", ",", "function", "(", "code", ",", "signal", ")", "{", "instance", "=", "null", ";", "if", "(", "signal", "==", "'SIGUSR2'", ")", "{", "logger", ".", "error", "(", "'Signal interuption'", ")", ";", "start", "(", ")", ";", "return", ";", "}", "logger", ".", "log", "(", "clc", ".", "green", "(", "script", ")", ",", "'exited with code'", ",", "clc", ".", "yellow", "(", "code", ")", ")", ";", "notifyWebSocket", "(", "'exit'", ")", ";", "if", "(", "keepAlive", "||", "(", "restartOnCleanExit", "&&", "code", "==", "0", ")", ")", "{", "start", "(", ")", ";", "return", ";", "}", "}", ")", ";", "}" ]
Starts and instance of the parser if none is running. @param {Boolean} [noMsg] - indicates if no message should be written to the log. Defaults to false.
[ "Starts", "and", "instance", "of", "the", "parser", "if", "none", "is", "running", "." ]
48fa586d1fad15ad544d143d1ba4b97172fed0f1
https://github.com/wronex/node-conquer/blob/48fa586d1fad15ad544d143d1ba4b97172fed0f1/bin/conquer.js#L123-L163
train
relief-melone/limitpromises
src/services/service.getLaunchIndex.js
getLaunchIndex
function getLaunchIndex(PromiseArray){ return PromiseArray.map(r => {return (r.isRunning === false && r.isRejected === false && r.isResolved === false)}).indexOf(true) }
javascript
function getLaunchIndex(PromiseArray){ return PromiseArray.map(r => {return (r.isRunning === false && r.isRejected === false && r.isResolved === false)}).indexOf(true) }
[ "function", "getLaunchIndex", "(", "PromiseArray", ")", "{", "return", "PromiseArray", ".", "map", "(", "r", "=>", "{", "return", "(", "r", ".", "isRunning", "===", "false", "&&", "r", ".", "isRejected", "===", "false", "&&", "r", ".", "isResolved", "===", "false", ")", "}", ")", ".", "indexOf", "(", "true", ")", "}" ]
Returns the first Element of a PromiseArray that hasn't been started yet @param {Object[]} PromiseArray The PromiseArray in which a new promise should be started @returns {Number} The index where you will start the resolveLaunchPromise
[ "Returns", "the", "first", "Element", "of", "a", "PromiseArray", "that", "hasn", "t", "been", "started", "yet" ]
1735b92749740204b597c1c6026257d54ade8200
https://github.com/relief-melone/limitpromises/blob/1735b92749740204b597c1c6026257d54ade8200/src/services/service.getLaunchIndex.js#L9-L11
train
juju/maraca
lib/parsers.js
parseAnnotation
function parseAnnotation(entity) { return { annotations: entity.annotations ? { bundleURL: entity.annotations['bundle-url'], guiX: entity.annotations['gui-x'], guiY: entity.annotations['gui-y'] } : undefined, modelUUID: entity['model-uuid'], tag: entity.tag }; }
javascript
function parseAnnotation(entity) { return { annotations: entity.annotations ? { bundleURL: entity.annotations['bundle-url'], guiX: entity.annotations['gui-x'], guiY: entity.annotations['gui-y'] } : undefined, modelUUID: entity['model-uuid'], tag: entity.tag }; }
[ "function", "parseAnnotation", "(", "entity", ")", "{", "return", "{", "annotations", ":", "entity", ".", "annotations", "?", "{", "bundleURL", ":", "entity", ".", "annotations", "[", "'bundle-url'", "]", ",", "guiX", ":", "entity", ".", "annotations", "[", "'gui-x'", "]", ",", "guiY", ":", "entity", ".", "annotations", "[", "'gui-y'", "]", "}", ":", "undefined", ",", "modelUUID", ":", "entity", "[", "'model-uuid'", "]", ",", "tag", ":", "entity", ".", "tag", "}", ";", "}" ]
Parse an annotation. @param {Object} entity - The entity details. @param {Object} entity.annotations - The annotation details. @param {String} entity.annotations.bunde-url - The bundle url. @param {String} entity.annotations.gui-x - The x position for the gui. @param {String} entity.annotations.gui-y - The y position for the gui. @param {String} entity.model-uuid - The model uuid this entity belongs to. @param {String} entity.tag - The tag for this entity. @returns {Object} return The parsed entity. @returns {Object} return.annotations - The annotation details. @returns {String} return.annotations.bundeURL - The bundle url. @returns {String} return.annotations.guiX - The x position for the gui. @returns {String} return.annotations.guiY - The y position for the gui. @returns {String} return.modelUUID - The model uuid this entity belongs to. @returns {String} return.tag - The tag for this entity.
[ "Parse", "an", "annotation", "." ]
0f245c6e09ef215fb4726bf7650320be2f49b6a0
https://github.com/juju/maraca/blob/0f245c6e09ef215fb4726bf7650320be2f49b6a0/lib/parsers.js#L21-L31
train
juju/maraca
lib/parsers.js
parseAnnotations
function parseAnnotations(response) { let entities = {}; Object.keys(response).forEach(key => { entities[key] = parseAnnotation(response[key]); }); return entities; }
javascript
function parseAnnotations(response) { let entities = {}; Object.keys(response).forEach(key => { entities[key] = parseAnnotation(response[key]); }); return entities; }
[ "function", "parseAnnotations", "(", "response", ")", "{", "let", "entities", "=", "{", "}", ";", "Object", ".", "keys", "(", "response", ")", ".", "forEach", "(", "key", "=>", "{", "entities", "[", "key", "]", "=", "parseAnnotation", "(", "response", "[", "key", "]", ")", ";", "}", ")", ";", "return", "entities", ";", "}" ]
Parse a collection of annotations. @param {Object} response - The collection, containing annotations as described in parseAnnotation(). @returns {Object} The parsed collection, containing annotations as described in parseAnnotation().
[ "Parse", "a", "collection", "of", "annotations", "." ]
0f245c6e09ef215fb4726bf7650320be2f49b6a0
https://github.com/juju/maraca/blob/0f245c6e09ef215fb4726bf7650320be2f49b6a0/lib/parsers.js#L40-L46
train
juju/maraca
lib/parsers.js
parseApplication
function parseApplication(entity) { return { charmURL: entity['charm-url'], // Config is arbitrary so leave the keys as defined. config: entity.config, // Constraints are arbitrary so leave the keys as defined. constraints: entity.constraints, exposed: entity.exposed, life: entity.life, minUnits: entity['min-units'], modelUUID: entity['model-uuid'], name: entity.name, ownerTag: entity['owner-tag'], status: entity.status ? { current: entity.status.current, message: entity.status.message, since: entity.status.since, version: entity.status.version } : undefined, subordinate: entity.subordinate, workloadVersion: entity['workload-version'] }; }
javascript
function parseApplication(entity) { return { charmURL: entity['charm-url'], // Config is arbitrary so leave the keys as defined. config: entity.config, // Constraints are arbitrary so leave the keys as defined. constraints: entity.constraints, exposed: entity.exposed, life: entity.life, minUnits: entity['min-units'], modelUUID: entity['model-uuid'], name: entity.name, ownerTag: entity['owner-tag'], status: entity.status ? { current: entity.status.current, message: entity.status.message, since: entity.status.since, version: entity.status.version } : undefined, subordinate: entity.subordinate, workloadVersion: entity['workload-version'] }; }
[ "function", "parseApplication", "(", "entity", ")", "{", "return", "{", "charmURL", ":", "entity", "[", "'charm-url'", "]", ",", "config", ":", "entity", ".", "config", ",", "constraints", ":", "entity", ".", "constraints", ",", "exposed", ":", "entity", ".", "exposed", ",", "life", ":", "entity", ".", "life", ",", "minUnits", ":", "entity", "[", "'min-units'", "]", ",", "modelUUID", ":", "entity", "[", "'model-uuid'", "]", ",", "name", ":", "entity", ".", "name", ",", "ownerTag", ":", "entity", "[", "'owner-tag'", "]", ",", "status", ":", "entity", ".", "status", "?", "{", "current", ":", "entity", ".", "status", ".", "current", ",", "message", ":", "entity", ".", "status", ".", "message", ",", "since", ":", "entity", ".", "status", ".", "since", ",", "version", ":", "entity", ".", "status", ".", "version", "}", ":", "undefined", ",", "subordinate", ":", "entity", ".", "subordinate", ",", "workloadVersion", ":", "entity", "[", "'workload-version'", "]", "}", ";", "}" ]
Parse an application. @param {Object} entity - The entity details. @param {String} entity.charm-url - The charmstore URL for the entity. @param {Object} entity.config - The arbitrary config details. @param {String} entity.config."config-key" - The config value. @param {Object} entity.constraints - The arbitrary constraints details. @param {String} entity.constraints."constraint-key" - The constraint value. @param {Boolean} entity.exposed - Whether the entity is exposed. @param {String} entity.life - The lifecycle status of the entity. @param {Integer} entity.min-units - The minimum number of units for the entity. @param {String} entity.model-uuid - The model uuid this entity belongs to. @param {String} entity.name - The name of the entity. @param {String} entity.owner-tag - The tag for the owner. @param {Object} entity.status - The entity status. @param {String} entity.status.current - The current entity status. @param {String} entity.status.message - The status message. @param {String} entity.status.since - The datetime for when the status was set. @param {String} entity.status.version - The status version. @param {Boolean} entity.subordinate - Whether this is entity is a subordinate. @param {String} entity.workload-version - The version of the workload. @returns {Object} return - The parsed entity. @returns {String} return.charmURL - The charmstore URL for the entity. @returns {Object} return.config - The arbitrary config details. @returns {String} return.config."config-key" - The config value. @returns {Object} return.constraints - The arbitrary constraints details. @returns {String} return.constraints."constraint-key" - The constraint value. @returns {Boolean} return.exposed - Whether the entity is exposed. @returns {String} return.life - The lifecycle status of the entity. @returns {Integer} return.minUnits - The minimum number of units for the entity. @returns {String} return.modelUUID - The model uuid this entity belongs to. @returns {String} return.name - The name of the entity. @returns {String} return.ownerTag - The tag for the owner. @returns {Object} return.status - The entity status. @returns {String} return.status.current - The current entity status. @returns {String} return.status.message - The status message. @returns {String} return.status.since - The datetime for when the status was set. @returns {String} return.status.version - The status version. @returns {Boolean} return.subordinate - Whether this is entity is a subordinate. @returns {String} return.workloadVersion - The version of the workload.
[ "Parse", "an", "application", "." ]
0f245c6e09ef215fb4726bf7650320be2f49b6a0
https://github.com/juju/maraca/blob/0f245c6e09ef215fb4726bf7650320be2f49b6a0/lib/parsers.js#L89-L111
train
juju/maraca
lib/parsers.js
parseApplications
function parseApplications(response) { let entities = {}; Object.keys(response).forEach(key => { entities[key] = parseApplication(response[key]); }); return entities; }
javascript
function parseApplications(response) { let entities = {}; Object.keys(response).forEach(key => { entities[key] = parseApplication(response[key]); }); return entities; }
[ "function", "parseApplications", "(", "response", ")", "{", "let", "entities", "=", "{", "}", ";", "Object", ".", "keys", "(", "response", ")", ".", "forEach", "(", "key", "=>", "{", "entities", "[", "key", "]", "=", "parseApplication", "(", "response", "[", "key", "]", ")", ";", "}", ")", ";", "return", "entities", ";", "}" ]
Parse a collection of applications. @param {Object} response - The collection, containing applications as described in parseApplication(). @returns {Object} The parsed collection, containing applications as described in parseApplication().
[ "Parse", "a", "collection", "of", "applications", "." ]
0f245c6e09ef215fb4726bf7650320be2f49b6a0
https://github.com/juju/maraca/blob/0f245c6e09ef215fb4726bf7650320be2f49b6a0/lib/parsers.js#L120-L126
train
juju/maraca
lib/parsers.js
parseMachine
function parseMachine(entity) { return { addresses: entity.addresses ? entity.addresses.map(address => ({ value: address.value, type: address.type, scope: address.scope })) : undefined, agentStatus: entity['agent-status'] ? { current: entity['agent-status'].current, message: entity['agent-status'].message, since: entity['agent-status'].since, version: entity['agent-status'].version } : undefined, // Hardware characteristics are arbitrary so leave the keys as defined. hardwareCharacteristics: entity['hardware-characteristics'], hasVote: entity['has-vote'], id: entity.id, instanceID: entity['instance-id'], instanceStatus: entity['instance-status'] ? { current: entity['instance-status'].current, message: entity['instance-status'].message, since: entity['instance-status'].since, version: entity['instance-status'].version } : undefined, jobs: entity.jobs, life: entity.life, modelUUID: entity['model-uuid'], series: entity.series, supportedContainers: entity['supported-containers'], supportedContainersKnown: entity['supported-containers-known'], wantsVote: entity['wants-vote'] }; }
javascript
function parseMachine(entity) { return { addresses: entity.addresses ? entity.addresses.map(address => ({ value: address.value, type: address.type, scope: address.scope })) : undefined, agentStatus: entity['agent-status'] ? { current: entity['agent-status'].current, message: entity['agent-status'].message, since: entity['agent-status'].since, version: entity['agent-status'].version } : undefined, // Hardware characteristics are arbitrary so leave the keys as defined. hardwareCharacteristics: entity['hardware-characteristics'], hasVote: entity['has-vote'], id: entity.id, instanceID: entity['instance-id'], instanceStatus: entity['instance-status'] ? { current: entity['instance-status'].current, message: entity['instance-status'].message, since: entity['instance-status'].since, version: entity['instance-status'].version } : undefined, jobs: entity.jobs, life: entity.life, modelUUID: entity['model-uuid'], series: entity.series, supportedContainers: entity['supported-containers'], supportedContainersKnown: entity['supported-containers-known'], wantsVote: entity['wants-vote'] }; }
[ "function", "parseMachine", "(", "entity", ")", "{", "return", "{", "addresses", ":", "entity", ".", "addresses", "?", "entity", ".", "addresses", ".", "map", "(", "address", "=>", "(", "{", "value", ":", "address", ".", "value", ",", "type", ":", "address", ".", "type", ",", "scope", ":", "address", ".", "scope", "}", ")", ")", ":", "undefined", ",", "agentStatus", ":", "entity", "[", "'agent-status'", "]", "?", "{", "current", ":", "entity", "[", "'agent-status'", "]", ".", "current", ",", "message", ":", "entity", "[", "'agent-status'", "]", ".", "message", ",", "since", ":", "entity", "[", "'agent-status'", "]", ".", "since", ",", "version", ":", "entity", "[", "'agent-status'", "]", ".", "version", "}", ":", "undefined", ",", "hardwareCharacteristics", ":", "entity", "[", "'hardware-characteristics'", "]", ",", "hasVote", ":", "entity", "[", "'has-vote'", "]", ",", "id", ":", "entity", ".", "id", ",", "instanceID", ":", "entity", "[", "'instance-id'", "]", ",", "instanceStatus", ":", "entity", "[", "'instance-status'", "]", "?", "{", "current", ":", "entity", "[", "'instance-status'", "]", ".", "current", ",", "message", ":", "entity", "[", "'instance-status'", "]", ".", "message", ",", "since", ":", "entity", "[", "'instance-status'", "]", ".", "since", ",", "version", ":", "entity", "[", "'instance-status'", "]", ".", "version", "}", ":", "undefined", ",", "jobs", ":", "entity", ".", "jobs", ",", "life", ":", "entity", ".", "life", ",", "modelUUID", ":", "entity", "[", "'model-uuid'", "]", ",", "series", ":", "entity", ".", "series", ",", "supportedContainers", ":", "entity", "[", "'supported-containers'", "]", ",", "supportedContainersKnown", ":", "entity", "[", "'supported-containers-known'", "]", ",", "wantsVote", ":", "entity", "[", "'wants-vote'", "]", "}", ";", "}" ]
Parse a machine. @param {Object} entity - The entity details. @param {Object[]} entity.addresses - The list of address objects. @param {String} entity.adresses[].value - The address. @param {String} entity.adresses[].type - The address type. @param {String} entity.adresses[].scope - The address scope. @param {Object} entity.agent-status - The agent status. @param {String} entity.agent-status.current - The current agent status. @param {String} entity.agent-status.message - The status message. @param {String} entity.agent-status.since - The datetime for when the status was set. @param {String} entity.agent-status.version - The status version. @param {Object} entity.hardware-characteristics - The arbitrary machine hardware details. @param {String} entity.hardware-characteristics."characteristic-key" - The characteristic value. @param {Boolean} entity.has-vote - Whether the entity has a vote. @param {String} entity.id - The entity id. @param {String} entity.instance-id - The instance id. @param {Object} entity.instance-status - The instance status. @param {String} entity.instance-status.current - The current instance status. @param {String} entity.instance-status.message - The status message. @param {String} entity.instance-status.since - The datetime for when the status was set. @param {String} entity.instance-status.version - The status version. @param {String} entity.jobs - The list of job strings. @param {String} entity.life - The lifecycle status of the entity. @param {String} entity.model-uuid - The model uuid this entity belongs to. @param {String} entity.series - The entity series. @param {String} entity.supported-containers - The list of supported container strings. @param {Boolean} entity.supported-containers-know - Whether the supported containers are known. @param {Boolean} entity.wants-vote - Whether the entity wants a vote. @returns {Object} return - The parsed entity. @returns {Object[]} return.addresses - The list of address objects. @returns {String} return.adresses[].value - The address. @returns {String} return.adresses[].type - The address type. @returns {String} return.adresses[].scope - The address scope. @returns {Object} return.agentStatus - The agent status. @returns {String} return.agentStatus.current - The current agent status. @returns {String} return.agentStatus.message - The status message. @returns {String} return.agentStatus.since - The datetime for when the status was set. @returns {String} return.agentStatus.version - The status version. @returns {Object} return.hardwareCharacteristics - The arbitrary machine hardware details. @returns {String} return.hardwareCharacteristics."characteristic-key" - The characteristic value. @returns {Boolean} return.hasVote - Whether the entity has a vote. @returns {String} return.id - The entity id. @returns {String} return.instanceId - The instance id. @returns {Object} return.instanceStatus - The instance status. @returns {String} return.instanceStatus.current - The current instance status. @returns {String} return.instanceStatus.message - The status message. @returns {String} return.instanceStatus.since - The datetime for when the status was set. @returns {String} return.instanceStatus.version - The status version. @returns {String} return.jobs - The list of job strings. @returns {String} return.life - The lifecycle status of the entity. @returns {String} return.modelUUID - The model uuid this entity belongs to. @returns {String} return.series - The entity series. @returns {String} return.supportedContainers - The list of supported container strings. @returns {Boolean} return.supportedContainersKnow - Whether the supported containers are known. @returns {Boolean} entity.wantsVote - Whether the entity wants a vote.
[ "Parse", "a", "machine", "." ]
0f245c6e09ef215fb4726bf7650320be2f49b6a0
https://github.com/juju/maraca/blob/0f245c6e09ef215fb4726bf7650320be2f49b6a0/lib/parsers.js#L189-L221
train
juju/maraca
lib/parsers.js
parseMachines
function parseMachines(response) { let entities = {}; Object.keys(response).forEach(key => { entities[key] = parseMachine(response[key]); }); return entities; }
javascript
function parseMachines(response) { let entities = {}; Object.keys(response).forEach(key => { entities[key] = parseMachine(response[key]); }); return entities; }
[ "function", "parseMachines", "(", "response", ")", "{", "let", "entities", "=", "{", "}", ";", "Object", ".", "keys", "(", "response", ")", ".", "forEach", "(", "key", "=>", "{", "entities", "[", "key", "]", "=", "parseMachine", "(", "response", "[", "key", "]", ")", ";", "}", ")", ";", "return", "entities", ";", "}" ]
Parse a collection of machines. @param {Object} response - The collection, containing machines as described in parseMachine(). @returns {Object} The parsed collection, containing machines as described in parseMachine().
[ "Parse", "a", "collection", "of", "machines", "." ]
0f245c6e09ef215fb4726bf7650320be2f49b6a0
https://github.com/juju/maraca/blob/0f245c6e09ef215fb4726bf7650320be2f49b6a0/lib/parsers.js#L230-L236
train
juju/maraca
lib/parsers.js
parseRelation
function parseRelation(entity) { return { endpoints: entity.endpoints ? entity.endpoints.map(endpoint => ({ applicationName: endpoint['application-name'], relation: { name: endpoint.relation.name, role: endpoint.relation.role, 'interface': endpoint.relation.interface, optional: endpoint.relation.optional, limit: endpoint.relation.limit, scope: endpoint.relation.scope } })) : undefined, id: entity.id, key: entity.key, modelUUID: entity['model-uuid'] }; }
javascript
function parseRelation(entity) { return { endpoints: entity.endpoints ? entity.endpoints.map(endpoint => ({ applicationName: endpoint['application-name'], relation: { name: endpoint.relation.name, role: endpoint.relation.role, 'interface': endpoint.relation.interface, optional: endpoint.relation.optional, limit: endpoint.relation.limit, scope: endpoint.relation.scope } })) : undefined, id: entity.id, key: entity.key, modelUUID: entity['model-uuid'] }; }
[ "function", "parseRelation", "(", "entity", ")", "{", "return", "{", "endpoints", ":", "entity", ".", "endpoints", "?", "entity", ".", "endpoints", ".", "map", "(", "endpoint", "=>", "(", "{", "applicationName", ":", "endpoint", "[", "'application-name'", "]", ",", "relation", ":", "{", "name", ":", "endpoint", ".", "relation", ".", "name", ",", "role", ":", "endpoint", ".", "relation", ".", "role", ",", "'interface'", ":", "endpoint", ".", "relation", ".", "interface", ",", "optional", ":", "endpoint", ".", "relation", ".", "optional", ",", "limit", ":", "endpoint", ".", "relation", ".", "limit", ",", "scope", ":", "endpoint", ".", "relation", ".", "scope", "}", "}", ")", ")", ":", "undefined", ",", "id", ":", "entity", ".", "id", ",", "key", ":", "entity", ".", "key", ",", "modelUUID", ":", "entity", "[", "'model-uuid'", "]", "}", ";", "}" ]
Parse a relation. @param {Object} entity - The entity details. @param {Object[]} entity.endpoints - The list of endpoint objects. @param {String} entity.endpoints[].application-name - The application name. @param {Object} entity.endpoints[].relation - The relation details. @param {String} entity.endpoints[].relation.name - The relation name. @param {String} entity.endpoints[].relation.role - The relation role. @param {String} entity.endpoints[].relation.interface - The relation interface. @param {Boolean} entity.endpoints[].relation.option - Whether the relation is optional. @param {Integer} entity.endpoints[].relation.limit - The relation limit. @param {String} entity.endpoints[].relation.scope - The relation scope. @param {String} entity.id - The entity id. @param {String} entity.string - The entity string. @param {String} entity.model-uuid - The model uuid this entity belongs to. @returns {Object} return - The parsed entity. @returns {Object[]} return.endpoints - The list of endpoint objects. @returns {String} return.endpoints[].applicationName - The application name. @returns {Object} return.endpoints[].relation - The relation details. @returns {String} return.endpoints[].relation.name - The relation name. @returns {String} return.endpoints[].relation.role - The relation role. @returns {String} return.endpoints[].relation.interface - The relation interface. @returns {Boolean} return.endpoints[].relation.option - Whether the relation is optional. @returns {Integer} return.endpoints[].relation.limit - The relation limit. @returns {String} return.endpoints[].relation.scope - The relation scope. @returns {String} return.id - The entity id. @returns {String} return.string - The entity string. @returns {String} return.modelUUID - The model uuid this entity belongs to.
[ "Parse", "a", "relation", "." ]
0f245c6e09ef215fb4726bf7650320be2f49b6a0
https://github.com/juju/maraca/blob/0f245c6e09ef215fb4726bf7650320be2f49b6a0/lib/parsers.js#L268-L285
train
juju/maraca
lib/parsers.js
parseRelations
function parseRelations(response) { let entities = {}; Object.keys(response).forEach(key => { entities[key] = parseRelation(response[key]); }); return entities; }
javascript
function parseRelations(response) { let entities = {}; Object.keys(response).forEach(key => { entities[key] = parseRelation(response[key]); }); return entities; }
[ "function", "parseRelations", "(", "response", ")", "{", "let", "entities", "=", "{", "}", ";", "Object", ".", "keys", "(", "response", ")", ".", "forEach", "(", "key", "=>", "{", "entities", "[", "key", "]", "=", "parseRelation", "(", "response", "[", "key", "]", ")", ";", "}", ")", ";", "return", "entities", ";", "}" ]
Parse a collection of relations. @param {Object} response - The collection, containing relations as described in parseRelation(). @returns {Object} The parsed collection, containing relations as described in parseRelation().
[ "Parse", "a", "collection", "of", "relations", "." ]
0f245c6e09ef215fb4726bf7650320be2f49b6a0
https://github.com/juju/maraca/blob/0f245c6e09ef215fb4726bf7650320be2f49b6a0/lib/parsers.js#L294-L300
train
juju/maraca
lib/parsers.js
parseRemoteApplication
function parseRemoteApplication(entity) { return { life: entity.life, modelUUID: entity['model-uuid'], name: entity.name, offerURL: entity['offer-url'], offerUUID: entity['offer-uuid'], status: entity.status ? { current: entity.status.current, message: entity.status.message, since: entity.status.since, version: entity.status.version } : undefined }; }
javascript
function parseRemoteApplication(entity) { return { life: entity.life, modelUUID: entity['model-uuid'], name: entity.name, offerURL: entity['offer-url'], offerUUID: entity['offer-uuid'], status: entity.status ? { current: entity.status.current, message: entity.status.message, since: entity.status.since, version: entity.status.version } : undefined }; }
[ "function", "parseRemoteApplication", "(", "entity", ")", "{", "return", "{", "life", ":", "entity", ".", "life", ",", "modelUUID", ":", "entity", "[", "'model-uuid'", "]", ",", "name", ":", "entity", ".", "name", ",", "offerURL", ":", "entity", "[", "'offer-url'", "]", ",", "offerUUID", ":", "entity", "[", "'offer-uuid'", "]", ",", "status", ":", "entity", ".", "status", "?", "{", "current", ":", "entity", ".", "status", ".", "current", ",", "message", ":", "entity", ".", "status", ".", "message", ",", "since", ":", "entity", ".", "status", ".", "since", ",", "version", ":", "entity", ".", "status", ".", "version", "}", ":", "undefined", "}", ";", "}" ]
Parse a remote application. @param {Object} entity - The entity details. @param {String} entity.life - The lifecycle status of the entity. @param {String} entity.model-uuid - The model uuid this entity belongs to. @param {String} entity.name - The entity name. @param {String} entity.offer-url - The offer URL. @param {String} entity.offer-uuid - The offer UUID. @param {Object} entity.status - The status. @param {String} entity.status.current - The current status. @param {String} entity.status.message - The status message. @param {String} entity.status.since - The datetime for when the status was set. @param {String} entity.status.version - The status version. @returns {Object} return - The parsed entity. @returns {String} return.life - The lifecycle status of the entity. @returns {String} return.modelUUID - The model uuid this entity belongs to. @returns {String} return.name - The entity name. @returns {String} return.offerURL - The offer URL. @returns {String} return.offerUUID - The offer UUID. @returns {Object} return.status - The status. @returns {String} return.status.current - The current status. @returns {String} return.status.message - The status message. @returns {String} return.status.since - The datetime for when the status was set. @returns {String} return.status.version - The status version.
[ "Parse", "a", "remote", "application", "." ]
0f245c6e09ef215fb4726bf7650320be2f49b6a0
https://github.com/juju/maraca/blob/0f245c6e09ef215fb4726bf7650320be2f49b6a0/lib/parsers.js#L327-L341
train
juju/maraca
lib/parsers.js
parseRemoteApplications
function parseRemoteApplications(response) { let entities = {}; Object.keys(response).forEach(key => { entities[key] = parseRemoteApplication(response[key]); }); return entities; }
javascript
function parseRemoteApplications(response) { let entities = {}; Object.keys(response).forEach(key => { entities[key] = parseRemoteApplication(response[key]); }); return entities; }
[ "function", "parseRemoteApplications", "(", "response", ")", "{", "let", "entities", "=", "{", "}", ";", "Object", ".", "keys", "(", "response", ")", ".", "forEach", "(", "key", "=>", "{", "entities", "[", "key", "]", "=", "parseRemoteApplication", "(", "response", "[", "key", "]", ")", ";", "}", ")", ";", "return", "entities", ";", "}" ]
Parse a collection of remote applications. @param {Object} response - The collection, containing remote applications as described in parseRemoteApplication(). @returns {Object} The parsed collection, containing remote applications as described in parseRemoteApplication().
[ "Parse", "a", "collection", "of", "remote", "applications", "." ]
0f245c6e09ef215fb4726bf7650320be2f49b6a0
https://github.com/juju/maraca/blob/0f245c6e09ef215fb4726bf7650320be2f49b6a0/lib/parsers.js#L350-L356
train
juju/maraca
lib/parsers.js
parseUnit
function parseUnit(entity) { return { agentStatus: entity['agent-status'] ? { current: entity['agent-status'].current, message: entity['agent-status'].message, since: entity['agent-status'].since, version: entity['agent-status'].version } : undefined, application: entity.application, charmURL: entity['charm-url'], machineID: entity['machine-id'], modelUUID: entity['model-uuid'], name: entity.name, portRanges: entity['port-ranges'] ? entity['port-ranges'].map(range => ({ fromPort: range['from-port'], toPort: range['to-port'], protocol: range.protocol })) : undefined, ports: entity.ports ? entity.ports.map(port => ({ protocol: port.protocol, number: port.number })) : undefined, privateAddress: entity['private-address'], publicAddress: entity['public-address'], series: entity.series, subordinate: entity.subordinate, workloadStatus: entity['workload-status'] ? { current: entity['workload-status'].current, message: entity['workload-status'].message, since: entity['workload-status'].since, version: entity['workload-status'].version } : undefined }; }
javascript
function parseUnit(entity) { return { agentStatus: entity['agent-status'] ? { current: entity['agent-status'].current, message: entity['agent-status'].message, since: entity['agent-status'].since, version: entity['agent-status'].version } : undefined, application: entity.application, charmURL: entity['charm-url'], machineID: entity['machine-id'], modelUUID: entity['model-uuid'], name: entity.name, portRanges: entity['port-ranges'] ? entity['port-ranges'].map(range => ({ fromPort: range['from-port'], toPort: range['to-port'], protocol: range.protocol })) : undefined, ports: entity.ports ? entity.ports.map(port => ({ protocol: port.protocol, number: port.number })) : undefined, privateAddress: entity['private-address'], publicAddress: entity['public-address'], series: entity.series, subordinate: entity.subordinate, workloadStatus: entity['workload-status'] ? { current: entity['workload-status'].current, message: entity['workload-status'].message, since: entity['workload-status'].since, version: entity['workload-status'].version } : undefined }; }
[ "function", "parseUnit", "(", "entity", ")", "{", "return", "{", "agentStatus", ":", "entity", "[", "'agent-status'", "]", "?", "{", "current", ":", "entity", "[", "'agent-status'", "]", ".", "current", ",", "message", ":", "entity", "[", "'agent-status'", "]", ".", "message", ",", "since", ":", "entity", "[", "'agent-status'", "]", ".", "since", ",", "version", ":", "entity", "[", "'agent-status'", "]", ".", "version", "}", ":", "undefined", ",", "application", ":", "entity", ".", "application", ",", "charmURL", ":", "entity", "[", "'charm-url'", "]", ",", "machineID", ":", "entity", "[", "'machine-id'", "]", ",", "modelUUID", ":", "entity", "[", "'model-uuid'", "]", ",", "name", ":", "entity", ".", "name", ",", "portRanges", ":", "entity", "[", "'port-ranges'", "]", "?", "entity", "[", "'port-ranges'", "]", ".", "map", "(", "range", "=>", "(", "{", "fromPort", ":", "range", "[", "'from-port'", "]", ",", "toPort", ":", "range", "[", "'to-port'", "]", ",", "protocol", ":", "range", ".", "protocol", "}", ")", ")", ":", "undefined", ",", "ports", ":", "entity", ".", "ports", "?", "entity", ".", "ports", ".", "map", "(", "port", "=>", "(", "{", "protocol", ":", "port", ".", "protocol", ",", "number", ":", "port", ".", "number", "}", ")", ")", ":", "undefined", ",", "privateAddress", ":", "entity", "[", "'private-address'", "]", ",", "publicAddress", ":", "entity", "[", "'public-address'", "]", ",", "series", ":", "entity", ".", "series", ",", "subordinate", ":", "entity", ".", "subordinate", ",", "workloadStatus", ":", "entity", "[", "'workload-status'", "]", "?", "{", "current", ":", "entity", "[", "'workload-status'", "]", ".", "current", ",", "message", ":", "entity", "[", "'workload-status'", "]", ".", "message", ",", "since", ":", "entity", "[", "'workload-status'", "]", ".", "since", ",", "version", ":", "entity", "[", "'workload-status'", "]", ".", "version", "}", ":", "undefined", "}", ";", "}" ]
Parse a unit. @param entity {Object} The entity details. @param {Object} entity.agent-status - The agent status. @param {String} entity.agent-status.current - The current status. @param {String} entity.agent-status.message - The status message. @param {String} entity.agent-status.since - The datetime for when the status was set. @param {String} entity.agent-status.version - The status version. @param {String} entity.application - The application this entity belongs to. @param {String} entity.charm-url - The charm URL for this unit. @param {String} entity.machine-id - The id of the machine this unit is on. @param {String} entity.model-uuid - The model uuid this entity belongs to. @param {String} entity.name - The name of the unit. @param {Object[]} entity.port-ranges[] - The collection of port range objects. @param {Integer} entity.port-ranges[].from-port - The start of the port range. @param {Integer} entity.port-ranges[].to-port - The end of the port range. @param {String} entity.port-ranges[].protocol - The port protocol. @param {Object[]} entity.ports - The collection of port objects. @param {String} entity.ports[].protocol - The port protocol. @param {Integer} entity.ports[].number - The port number. @param {String} entity.private-address - The unit's private address. @param {String} entity.public-address - The unit's public address. @param {String} entity.series - The series of the unit. @param {Boolean} entity.subordinate - Whether the unit is a subordinate. @param {Object} entity.workload-status - The workload status. @param {String} entity.workload-status.current - The current status. @param {String} entity.workload-status.message - The status message. @param {String} entity.workload-status.since - The datetime for when the status was set. @param {String} entity.workload-status.version - The status version. @returns {Object} return The parsed entity. @returns {Object} return.agentStatus - The agent status. @returns {String} return.agentStatus.current - The current status. @returns {String} return.agentStatus.message - The status message. @returns {String} return.agentStatus.since - The datetime for when the status was set. @returns {String} return.agentStatus.version - The status version. @returns {String} return.application - The application this entity belongs to. @returns {String} return.charmURL - The charm URL for this unit. @returns {String} return.machineID - The id of the machine this unit is on. @returns {String} return.modelUUID - The model uuid this entity belongs to. @returns {String} return.name - The name of the unit. @returns {Object[]} return.portRanges - The collection of port range objects. @returns {Integer} return.portRanges[].fromPort - The start of the port range. @returns {Integer} return.portRanges[].toPort - The end of the port range. @returns {String} return.portRanges[].protocol - The port protocol. @returns {Object[]} return.ports - The collection of port objects. @returns {String} return.ports[].protocol - The port protocol. @returns {Integer} return.ports[].number - The port number. @returns {String} return.privateAddress - The unit's private address. @returns {String} return.publicAddress - The unit's public address. @returns {String} return.series - The series of the unit. @returns {Boolean} return.subordinate - Whether the unit is a subordinate. @returns {Object} return.workloadStatus - The workload status. @returns {String} return.workloadStatus.current - The current status. @returns {String} return.workloadStatus.message - The status message. @returns {String} return.workloadStatus.since - The datetime for when the status was set. @returns {String} return.workloadStatus.version - The status version.
[ "Parse", "a", "unit", "." ]
0f245c6e09ef215fb4726bf7650320be2f49b6a0
https://github.com/juju/maraca/blob/0f245c6e09ef215fb4726bf7650320be2f49b6a0/lib/parsers.js#L415-L448
train
juju/maraca
lib/parsers.js
parseUnits
function parseUnits(response) { let entities = {}; Object.keys(response).forEach(key => { entities[key] = parseUnit(response[key]); }); return entities; }
javascript
function parseUnits(response) { let entities = {}; Object.keys(response).forEach(key => { entities[key] = parseUnit(response[key]); }); return entities; }
[ "function", "parseUnits", "(", "response", ")", "{", "let", "entities", "=", "{", "}", ";", "Object", ".", "keys", "(", "response", ")", ".", "forEach", "(", "key", "=>", "{", "entities", "[", "key", "]", "=", "parseUnit", "(", "response", "[", "key", "]", ")", ";", "}", ")", ";", "return", "entities", ";", "}" ]
Parse a collection of units. @param {Object} response - The collection, containing units as described in parseUnit(). @returns {Object} The parsed collection, containing units as described in parseUnit().
[ "Parse", "a", "collection", "of", "units", "." ]
0f245c6e09ef215fb4726bf7650320be2f49b6a0
https://github.com/juju/maraca/blob/0f245c6e09ef215fb4726bf7650320be2f49b6a0/lib/parsers.js#L457-L463
train
juju/maraca
lib/parsers.js
parseMegaWatcher
function parseMegaWatcher(response) { return { annotations: parseAnnotations(response.annotations), applications: parseApplications(response.applications), machines: parseMachines(response.machines), relations: parseRelations(response.relations), remoteApplications: parseRemoteApplications(response['remote-applications']), units: parseUnits(response.units) }; }
javascript
function parseMegaWatcher(response) { return { annotations: parseAnnotations(response.annotations), applications: parseApplications(response.applications), machines: parseMachines(response.machines), relations: parseRelations(response.relations), remoteApplications: parseRemoteApplications(response['remote-applications']), units: parseUnits(response.units) }; }
[ "function", "parseMegaWatcher", "(", "response", ")", "{", "return", "{", "annotations", ":", "parseAnnotations", "(", "response", ".", "annotations", ")", ",", "applications", ":", "parseApplications", "(", "response", ".", "applications", ")", ",", "machines", ":", "parseMachines", "(", "response", ".", "machines", ")", ",", "relations", ":", "parseRelations", "(", "response", ".", "relations", ")", ",", "remoteApplications", ":", "parseRemoteApplications", "(", "response", "[", "'remote-applications'", "]", ")", ",", "units", ":", "parseUnits", "(", "response", ".", "units", ")", "}", ";", "}" ]
Parse a full megawatcher object. @param {Object} response - The collections of entites. @param {Object} response.annotations - The collection of annotations. @param {Object} response.applications - The collection of applications. @param {Object} response.machines - The collection of machines. @param {Object} response.relations - The collection of relations. @param {Object} response.remote-applications - The collection of remote-applications. @returns {Object} return - The parsed collections. @returns {Object} return.annotations - The collection of annotations. @returns {Object} return.applications - The collection of applications. @returns {Object} return.machines - The collection of machines. @returns {Object} return.relations - The collection of relations. @returns {Object} return.remoteApplications - The collection of remote-applications.
[ "Parse", "a", "full", "megawatcher", "object", "." ]
0f245c6e09ef215fb4726bf7650320be2f49b6a0
https://github.com/juju/maraca/blob/0f245c6e09ef215fb4726bf7650320be2f49b6a0/lib/parsers.js#L480-L489
train
FH-Potsdam/mqtt-controls
dist/index.js
init
function init() { var _user = arguments.length <= 0 || arguments[0] === undefined ? 'try' : arguments[0]; var _pw = arguments.length <= 1 || arguments[1] === undefined ? 'try' : arguments[1]; var _clientId = arguments.length <= 2 || arguments[2] === undefined ? 'mqttControlsClient' : arguments[2]; var _broker = arguments.length <= 3 || arguments[3] === undefined ? 'broker.shiftr.io' : arguments[3]; var _topics = arguments.length <= 4 || arguments[4] === undefined ? { 'subscribe': '/output/#', 'publish': '/input/' } : arguments[4]; user = _user; pw = _pw; clientId = _clientId; broker = _broker; topics = _topics; url = '' + protocol + user + ':' + pw + '@' + broker; console.log('mqtt controller is initialised'); }
javascript
function init() { var _user = arguments.length <= 0 || arguments[0] === undefined ? 'try' : arguments[0]; var _pw = arguments.length <= 1 || arguments[1] === undefined ? 'try' : arguments[1]; var _clientId = arguments.length <= 2 || arguments[2] === undefined ? 'mqttControlsClient' : arguments[2]; var _broker = arguments.length <= 3 || arguments[3] === undefined ? 'broker.shiftr.io' : arguments[3]; var _topics = arguments.length <= 4 || arguments[4] === undefined ? { 'subscribe': '/output/#', 'publish': '/input/' } : arguments[4]; user = _user; pw = _pw; clientId = _clientId; broker = _broker; topics = _topics; url = '' + protocol + user + ':' + pw + '@' + broker; console.log('mqtt controller is initialised'); }
[ "function", "init", "(", ")", "{", "var", "_user", "=", "arguments", ".", "length", "<=", "0", "||", "arguments", "[", "0", "]", "===", "undefined", "?", "'try'", ":", "arguments", "[", "0", "]", ";", "var", "_pw", "=", "arguments", ".", "length", "<=", "1", "||", "arguments", "[", "1", "]", "===", "undefined", "?", "'try'", ":", "arguments", "[", "1", "]", ";", "var", "_clientId", "=", "arguments", ".", "length", "<=", "2", "||", "arguments", "[", "2", "]", "===", "undefined", "?", "'mqttControlsClient'", ":", "arguments", "[", "2", "]", ";", "var", "_broker", "=", "arguments", ".", "length", "<=", "3", "||", "arguments", "[", "3", "]", "===", "undefined", "?", "'broker.shiftr.io'", ":", "arguments", "[", "3", "]", ";", "var", "_topics", "=", "arguments", ".", "length", "<=", "4", "||", "arguments", "[", "4", "]", "===", "undefined", "?", "{", "'subscribe'", ":", "'/output/#'", ",", "'publish'", ":", "'/input/'", "}", ":", "arguments", "[", "4", "]", ";", "user", "=", "_user", ";", "pw", "=", "_pw", ";", "clientId", "=", "_clientId", ";", "broker", "=", "_broker", ";", "topics", "=", "_topics", ";", "url", "=", "''", "+", "protocol", "+", "user", "+", "':'", "+", "pw", "+", "'@'", "+", "broker", ";", "console", ".", "log", "(", "'mqtt controller is initialised'", ")", ";", "}" ]
export var url = url; export var topics = topics; export var isSubscribed = isSubscribed; export var isPublishing = isPublishing; export var stopPub = stopPub; export var protocol = protocol; export var broker = broker; export var user = user; export var pw = pw; export var clientId = clientId; init Initialize the library @param {String} _user The user name at your broker. Default: try @param {String} _pw The password at your broker. Default: try @param {String} _clientId The name you want to be displayed with: Default: mqttControlsClient @param {String} _broker The borker to connect to. Default: brker.shiftr.io @param {Object} _topics Topics to subscribe and th publish to. Currently one one per publish and subscribe. Default `{'subscribe':'/output/#','publih':'/input/'}`
[ "export", "var", "url", "=", "url", ";", "export", "var", "topics", "=", "topics", ";", "export", "var", "isSubscribed", "=", "isSubscribed", ";", "export", "var", "isPublishing", "=", "isPublishing", ";", "export", "var", "stopPub", "=", "stopPub", ";", "export", "var", "protocol", "=", "protocol", ";", "export", "var", "broker", "=", "broker", ";", "export", "var", "user", "=", "user", ";", "export", "var", "pw", "=", "pw", ";", "export", "var", "clientId", "=", "clientId", ";", "init", "Initialize", "the", "library" ]
762928c4218b94335114c2e35295e54b4f848531
https://github.com/FH-Potsdam/mqtt-controls/blob/762928c4218b94335114c2e35295e54b4f848531/dist/index.js#L60-L80
train
FH-Potsdam/mqtt-controls
dist/index.js
connect
function connect() { console.log('Connecting client: ' + clientId + ' to url:"' + url + '"'); client = mqtt.connect(url, { 'clientId': clientId }); }
javascript
function connect() { console.log('Connecting client: ' + clientId + ' to url:"' + url + '"'); client = mqtt.connect(url, { 'clientId': clientId }); }
[ "function", "connect", "(", ")", "{", "console", ".", "log", "(", "'Connecting client: '", "+", "clientId", "+", "' to url:\"'", "+", "url", "+", "'\"'", ")", ";", "client", "=", "mqtt", ".", "connect", "(", "url", ",", "{", "'clientId'", ":", "clientId", "}", ")", ";", "}" ]
connect Connect your client to the broker
[ "connect", "Connect", "your", "client", "to", "the", "broker" ]
762928c4218b94335114c2e35295e54b4f848531
https://github.com/FH-Potsdam/mqtt-controls/blob/762928c4218b94335114c2e35295e54b4f848531/dist/index.js#L85-L88
train
FH-Potsdam/mqtt-controls
dist/index.js
disconnect
function disconnect() { var force = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; var cb = arguments.length <= 1 || arguments[1] === undefined ? undefined : arguments[1]; console.log('Disconnecting client: ' + clientId); stopPub = true; client.end(force, cb); }
javascript
function disconnect() { var force = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; var cb = arguments.length <= 1 || arguments[1] === undefined ? undefined : arguments[1]; console.log('Disconnecting client: ' + clientId); stopPub = true; client.end(force, cb); }
[ "function", "disconnect", "(", ")", "{", "var", "force", "=", "arguments", ".", "length", "<=", "0", "||", "arguments", "[", "0", "]", "===", "undefined", "?", "false", ":", "arguments", "[", "0", "]", ";", "var", "cb", "=", "arguments", ".", "length", "<=", "1", "||", "arguments", "[", "1", "]", "===", "undefined", "?", "undefined", ":", "arguments", "[", "1", "]", ";", "console", ".", "log", "(", "'Disconnecting client: '", "+", "clientId", ")", ";", "stopPub", "=", "true", ";", "client", ".", "end", "(", "force", ",", "cb", ")", ";", "}" ]
disconnect disconnect from the broker @param {Boolean} force force disconnect. Default: false @param {Function} cb Callback function the be called after disconnect. Default: undefined
[ "disconnect", "disconnect", "from", "the", "broker" ]
762928c4218b94335114c2e35295e54b4f848531
https://github.com/FH-Potsdam/mqtt-controls/blob/762928c4218b94335114c2e35295e54b4f848531/dist/index.js#L94-L101
train
FH-Potsdam/mqtt-controls
dist/index.js
reconnect
function reconnect() { client.end(false, function () { console.log('Reconnecting client: ' + clientId); client.connect(url, { 'clientId': clientId }); }); }
javascript
function reconnect() { client.end(false, function () { console.log('Reconnecting client: ' + clientId); client.connect(url, { 'clientId': clientId }); }); }
[ "function", "reconnect", "(", ")", "{", "client", ".", "end", "(", "false", ",", "function", "(", ")", "{", "console", ".", "log", "(", "'Reconnecting client: '", "+", "clientId", ")", ";", "client", ".", "connect", "(", "url", ",", "{", "'clientId'", ":", "clientId", "}", ")", ";", "}", ")", ";", "}" ]
reconnect Reconnect to your broker
[ "reconnect", "Reconnect", "to", "your", "broker" ]
762928c4218b94335114c2e35295e54b4f848531
https://github.com/FH-Potsdam/mqtt-controls/blob/762928c4218b94335114c2e35295e54b4f848531/dist/index.js#L106-L111
train
FH-Potsdam/mqtt-controls
dist/index.js
subscribe
function subscribe() { console.log('Subscribing client ' + clientId + ' to topic: ' + topics.subscribe); client.subscribe(topics.subscribe); isSubscribed = true; }
javascript
function subscribe() { console.log('Subscribing client ' + clientId + ' to topic: ' + topics.subscribe); client.subscribe(topics.subscribe); isSubscribed = true; }
[ "function", "subscribe", "(", ")", "{", "console", ".", "log", "(", "'Subscribing client '", "+", "clientId", "+", "' to topic: '", "+", "topics", ".", "subscribe", ")", ";", "client", ".", "subscribe", "(", "topics", ".", "subscribe", ")", ";", "isSubscribed", "=", "true", ";", "}" ]
subscribe Subscribes to your topics
[ "subscribe", "Subscribes", "to", "your", "topics" ]
762928c4218b94335114c2e35295e54b4f848531
https://github.com/FH-Potsdam/mqtt-controls/blob/762928c4218b94335114c2e35295e54b4f848531/dist/index.js#L116-L120
train
FH-Potsdam/mqtt-controls
dist/index.js
publish
function publish() { console.log('Client ' + clientId + ' is publishing to topic ' + topics.publish); // client.on('message',()=>{}); // this is just for testing purpouse // maybe we dont need to stop and start publishing var timer = setInterval(function () { client.publish(topics.publish, 'ping'); if (stopPub === true) { clearInterval(timer); stopPub = false; } }, 1000); }
javascript
function publish() { console.log('Client ' + clientId + ' is publishing to topic ' + topics.publish); // client.on('message',()=>{}); // this is just for testing purpouse // maybe we dont need to stop and start publishing var timer = setInterval(function () { client.publish(topics.publish, 'ping'); if (stopPub === true) { clearInterval(timer); stopPub = false; } }, 1000); }
[ "function", "publish", "(", ")", "{", "console", ".", "log", "(", "'Client '", "+", "clientId", "+", "' is publishing to topic '", "+", "topics", ".", "publish", ")", ";", "var", "timer", "=", "setInterval", "(", "function", "(", ")", "{", "client", ".", "publish", "(", "topics", ".", "publish", ",", "'ping'", ")", ";", "if", "(", "stopPub", "===", "true", ")", "{", "clearInterval", "(", "timer", ")", ";", "stopPub", "=", "false", ";", "}", "}", ",", "1000", ")", ";", "}" ]
publish Start publishing in an interval to your broker this is more for testing then for real usage.
[ "publish", "Start", "publishing", "in", "an", "interval", "to", "your", "broker", "this", "is", "more", "for", "testing", "then", "for", "real", "usage", "." ]
762928c4218b94335114c2e35295e54b4f848531
https://github.com/FH-Potsdam/mqtt-controls/blob/762928c4218b94335114c2e35295e54b4f848531/dist/index.js#L147-L159
train
FH-Potsdam/mqtt-controls
dist/index.js
send
function send() { var message = arguments.length <= 0 || arguments[0] === undefined ? 'hello mqtt-controls' : arguments[0]; var topic = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; var t = undefined; if (topic === null) { t = topics.publish; } else { t = topic; } client.publish(t, message); }
javascript
function send() { var message = arguments.length <= 0 || arguments[0] === undefined ? 'hello mqtt-controls' : arguments[0]; var topic = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; var t = undefined; if (topic === null) { t = topics.publish; } else { t = topic; } client.publish(t, message); }
[ "function", "send", "(", ")", "{", "var", "message", "=", "arguments", ".", "length", "<=", "0", "||", "arguments", "[", "0", "]", "===", "undefined", "?", "'hello mqtt-controls'", ":", "arguments", "[", "0", "]", ";", "var", "topic", "=", "arguments", ".", "length", "<=", "1", "||", "arguments", "[", "1", "]", "===", "undefined", "?", "null", ":", "arguments", "[", "1", "]", ";", "var", "t", "=", "undefined", ";", "if", "(", "topic", "===", "null", ")", "{", "t", "=", "topics", ".", "publish", ";", "}", "else", "{", "t", "=", "topic", ";", "}", "client", ".", "publish", "(", "t", ",", "message", ")", ";", "}" ]
Send one signal to the borker @param {String} message - The message to send. Default: `{'hello mqtt-controls'}` @param {String} topic - The topic to send to. Default: is `topics = {'subscribe':'/output/#','publih':'/input/'}`
[ "Send", "one", "signal", "to", "the", "borker" ]
762928c4218b94335114c2e35295e54b4f848531
https://github.com/FH-Potsdam/mqtt-controls/blob/762928c4218b94335114c2e35295e54b4f848531/dist/index.js#L166-L177
train
fin-hypergrid/fincanvas
src/js/gc-console-logger.js
consoleLogger
function consoleLogger(prefix, name, args, value) { var result = value; if (typeof value === 'string') { result = '"' + result + '"'; } name = prefix + name; switch (args) { case 'getter': console.log(name, '=', result); break; case 'setter': console.log(name, YIELDS, result); break; default: // method call name += '(' + Array.prototype.slice.call(args).join(', ') + ')'; if (result === undefined) { console.log(name); } else { console.log(name, YIELDS, result); } } return value; }
javascript
function consoleLogger(prefix, name, args, value) { var result = value; if (typeof value === 'string') { result = '"' + result + '"'; } name = prefix + name; switch (args) { case 'getter': console.log(name, '=', result); break; case 'setter': console.log(name, YIELDS, result); break; default: // method call name += '(' + Array.prototype.slice.call(args).join(', ') + ')'; if (result === undefined) { console.log(name); } else { console.log(name, YIELDS, result); } } return value; }
[ "function", "consoleLogger", "(", "prefix", ",", "name", ",", "args", ",", "value", ")", "{", "var", "result", "=", "value", ";", "if", "(", "typeof", "value", "===", "'string'", ")", "{", "result", "=", "'\"'", "+", "result", "+", "'\"'", ";", "}", "name", "=", "prefix", "+", "name", ";", "switch", "(", "args", ")", "{", "case", "'getter'", ":", "console", ".", "log", "(", "name", ",", "'='", ",", "result", ")", ";", "break", ";", "case", "'setter'", ":", "console", ".", "log", "(", "name", ",", "YIELDS", ",", "result", ")", ";", "break", ";", "default", ":", "name", "+=", "'('", "+", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "args", ")", ".", "join", "(", "', '", ")", "+", "')'", ";", "if", "(", "result", "===", "undefined", ")", "{", "console", ".", "log", "(", "name", ")", ";", "}", "else", "{", "console", ".", "log", "(", "name", ",", "YIELDS", ",", "result", ")", ";", "}", "}", "return", "value", ";", "}" ]
LONG RIGHTWARDS DOUBLE ARROW
[ "LONG", "RIGHTWARDS", "DOUBLE", "ARROW" ]
1e4afb877923e3f26b62ee61a00abb1c3a1a071f
https://github.com/fin-hypergrid/fincanvas/blob/1e4afb877923e3f26b62ee61a00abb1c3a1a071f/src/js/gc-console-logger.js#L5-L33
train
RnbWd/parse-browserify
lib/object.js
function() { var self = this; if (self._refreshingCache) { return; } self._refreshingCache = true; Parse._objectEach(this.attributes, function(value, key) { if (value instanceof Parse.Object) { value._refreshCache(); } else if (_.isObject(value)) { if (self._resetCacheForKey(key)) { self.set(key, new Parse.Op.Set(value), { silent: true }); } } }); delete self._refreshingCache; }
javascript
function() { var self = this; if (self._refreshingCache) { return; } self._refreshingCache = true; Parse._objectEach(this.attributes, function(value, key) { if (value instanceof Parse.Object) { value._refreshCache(); } else if (_.isObject(value)) { if (self._resetCacheForKey(key)) { self.set(key, new Parse.Op.Set(value), { silent: true }); } } }); delete self._refreshingCache; }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "if", "(", "self", ".", "_refreshingCache", ")", "{", "return", ";", "}", "self", ".", "_refreshingCache", "=", "true", ";", "Parse", ".", "_objectEach", "(", "this", ".", "attributes", ",", "function", "(", "value", ",", "key", ")", "{", "if", "(", "value", "instanceof", "Parse", ".", "Object", ")", "{", "value", ".", "_refreshCache", "(", ")", ";", "}", "else", "if", "(", "_", ".", "isObject", "(", "value", ")", ")", "{", "if", "(", "self", ".", "_resetCacheForKey", "(", "key", ")", ")", "{", "self", ".", "set", "(", "key", ",", "new", "Parse", ".", "Op", ".", "Set", "(", "value", ")", ",", "{", "silent", ":", "true", "}", ")", ";", "}", "}", "}", ")", ";", "delete", "self", ".", "_refreshingCache", ";", "}" ]
Updates _hashedJSON to reflect the current state of this object. Adds any changed hash values to the set of pending changes.
[ "Updates", "_hashedJSON", "to", "reflect", "the", "current", "state", "of", "this", "object", ".", "Adds", "any", "changed", "hash", "values", "to", "the", "set", "of", "pending", "changes", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/object.js#L352-L368
train
RnbWd/parse-browserify
lib/object.js
function(attrs) { // Check for changes of magic fields. var model = this; var specialFields = ["id", "objectId", "createdAt", "updatedAt"]; Parse._arrayEach(specialFields, function(attr) { if (attrs[attr]) { if (attr === "objectId") { model.id = attrs[attr]; } else if ((attr === "createdAt" || attr === "updatedAt") && !_.isDate(attrs[attr])) { model[attr] = Parse._parseDate(attrs[attr]); } else { model[attr] = attrs[attr]; } delete attrs[attr]; } }); }
javascript
function(attrs) { // Check for changes of magic fields. var model = this; var specialFields = ["id", "objectId", "createdAt", "updatedAt"]; Parse._arrayEach(specialFields, function(attr) { if (attrs[attr]) { if (attr === "objectId") { model.id = attrs[attr]; } else if ((attr === "createdAt" || attr === "updatedAt") && !_.isDate(attrs[attr])) { model[attr] = Parse._parseDate(attrs[attr]); } else { model[attr] = attrs[attr]; } delete attrs[attr]; } }); }
[ "function", "(", "attrs", ")", "{", "var", "model", "=", "this", ";", "var", "specialFields", "=", "[", "\"id\"", ",", "\"objectId\"", ",", "\"createdAt\"", ",", "\"updatedAt\"", "]", ";", "Parse", ".", "_arrayEach", "(", "specialFields", ",", "function", "(", "attr", ")", "{", "if", "(", "attrs", "[", "attr", "]", ")", "{", "if", "(", "attr", "===", "\"objectId\"", ")", "{", "model", ".", "id", "=", "attrs", "[", "attr", "]", ";", "}", "else", "if", "(", "(", "attr", "===", "\"createdAt\"", "||", "attr", "===", "\"updatedAt\"", ")", "&&", "!", "_", ".", "isDate", "(", "attrs", "[", "attr", "]", ")", ")", "{", "model", "[", "attr", "]", "=", "Parse", ".", "_parseDate", "(", "attrs", "[", "attr", "]", ")", ";", "}", "else", "{", "model", "[", "attr", "]", "=", "attrs", "[", "attr", "]", ";", "}", "delete", "attrs", "[", "attr", "]", ";", "}", "}", ")", ";", "}" ]
Pulls "special" fields like objectId, createdAt, etc. out of attrs and puts them on "this" directly. Removes them from attrs. @param attrs - A dictionary with the data for this Parse.Object.
[ "Pulls", "special", "fields", "like", "objectId", "createdAt", "etc", ".", "out", "of", "attrs", "and", "puts", "them", "on", "this", "directly", ".", "Removes", "them", "from", "attrs", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/object.js#L473-L490
train
RnbWd/parse-browserify
lib/object.js
function(serverData) { // Copy server data var tempServerData = {}; Parse._objectEach(serverData, function(value, key) { tempServerData[key] = Parse._decode(key, value); }); this._serverData = tempServerData; // Refresh the attributes. this._rebuildAllEstimatedData(); // Clear out any changes the user might have made previously. this._refreshCache(); this._opSetQueue = [{}]; // Refresh the attributes again. this._rebuildAllEstimatedData(); }
javascript
function(serverData) { // Copy server data var tempServerData = {}; Parse._objectEach(serverData, function(value, key) { tempServerData[key] = Parse._decode(key, value); }); this._serverData = tempServerData; // Refresh the attributes. this._rebuildAllEstimatedData(); // Clear out any changes the user might have made previously. this._refreshCache(); this._opSetQueue = [{}]; // Refresh the attributes again. this._rebuildAllEstimatedData(); }
[ "function", "(", "serverData", ")", "{", "var", "tempServerData", "=", "{", "}", ";", "Parse", ".", "_objectEach", "(", "serverData", ",", "function", "(", "value", ",", "key", ")", "{", "tempServerData", "[", "key", "]", "=", "Parse", ".", "_decode", "(", "key", ",", "value", ")", ";", "}", ")", ";", "this", ".", "_serverData", "=", "tempServerData", ";", "this", ".", "_rebuildAllEstimatedData", "(", ")", ";", "this", ".", "_refreshCache", "(", ")", ";", "this", ".", "_opSetQueue", "=", "[", "{", "}", "]", ";", "this", ".", "_rebuildAllEstimatedData", "(", ")", ";", "}" ]
Copies the given serverData to "this", refreshes attributes, and clears pending changes;
[ "Copies", "the", "given", "serverData", "to", "this", "refreshes", "attributes", "and", "clears", "pending", "changes", ";" ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/object.js#L496-L514
train
RnbWd/parse-browserify
lib/object.js
function(other) { if (!other) { return; } // This does the inverse of _mergeMagicFields. this.id = other.id; this.createdAt = other.createdAt; this.updatedAt = other.updatedAt; this._copyServerData(other._serverData); this._hasData = true; }
javascript
function(other) { if (!other) { return; } // This does the inverse of _mergeMagicFields. this.id = other.id; this.createdAt = other.createdAt; this.updatedAt = other.updatedAt; this._copyServerData(other._serverData); this._hasData = true; }
[ "function", "(", "other", ")", "{", "if", "(", "!", "other", ")", "{", "return", ";", "}", "this", ".", "id", "=", "other", ".", "id", ";", "this", ".", "createdAt", "=", "other", ".", "createdAt", ";", "this", ".", "updatedAt", "=", "other", ".", "updatedAt", ";", "this", ".", "_copyServerData", "(", "other", ".", "_serverData", ")", ";", "this", ".", "_hasData", "=", "true", ";", "}" ]
Merges another object's attributes into this object.
[ "Merges", "another", "object", "s", "attributes", "into", "this", "object", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/object.js#L519-L532
train
RnbWd/parse-browserify
lib/object.js
function(opSet, target) { var self = this; Parse._objectEach(opSet, function(change, key) { target[key] = change._estimate(target[key], self, key); if (target[key] === Parse.Op._UNSET) { delete target[key]; } }); }
javascript
function(opSet, target) { var self = this; Parse._objectEach(opSet, function(change, key) { target[key] = change._estimate(target[key], self, key); if (target[key] === Parse.Op._UNSET) { delete target[key]; } }); }
[ "function", "(", "opSet", ",", "target", ")", "{", "var", "self", "=", "this", ";", "Parse", ".", "_objectEach", "(", "opSet", ",", "function", "(", "change", ",", "key", ")", "{", "target", "[", "key", "]", "=", "change", ".", "_estimate", "(", "target", "[", "key", "]", ",", "self", ",", "key", ")", ";", "if", "(", "target", "[", "key", "]", "===", "Parse", ".", "Op", ".", "_UNSET", ")", "{", "delete", "target", "[", "key", "]", ";", "}", "}", ")", ";", "}" ]
Applies the set of Parse.Op in opSet to the object target.
[ "Applies", "the", "set", "of", "Parse", ".", "Op", "in", "opSet", "to", "the", "object", "target", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/object.js#L628-L636
train
RnbWd/parse-browserify
lib/object.js
function() { var self = this; var previousAttributes = _.clone(this.attributes); this.attributes = _.clone(this._serverData); Parse._arrayEach(this._opSetQueue, function(opSet) { self._applyOpSet(opSet, self.attributes); Parse._objectEach(opSet, function(op, key) { self._resetCacheForKey(key); }); }); // Trigger change events for anything that changed because of the fetch. Parse._objectEach(previousAttributes, function(oldValue, key) { if (self.attributes[key] !== oldValue) { self.trigger('change:' + key, self, self.attributes[key], {}); } }); Parse._objectEach(this.attributes, function(newValue, key) { if (!_.has(previousAttributes, key)) { self.trigger('change:' + key, self, newValue, {}); } }); }
javascript
function() { var self = this; var previousAttributes = _.clone(this.attributes); this.attributes = _.clone(this._serverData); Parse._arrayEach(this._opSetQueue, function(opSet) { self._applyOpSet(opSet, self.attributes); Parse._objectEach(opSet, function(op, key) { self._resetCacheForKey(key); }); }); // Trigger change events for anything that changed because of the fetch. Parse._objectEach(previousAttributes, function(oldValue, key) { if (self.attributes[key] !== oldValue) { self.trigger('change:' + key, self, self.attributes[key], {}); } }); Parse._objectEach(this.attributes, function(newValue, key) { if (!_.has(previousAttributes, key)) { self.trigger('change:' + key, self, newValue, {}); } }); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "var", "previousAttributes", "=", "_", ".", "clone", "(", "this", ".", "attributes", ")", ";", "this", ".", "attributes", "=", "_", ".", "clone", "(", "this", ".", "_serverData", ")", ";", "Parse", ".", "_arrayEach", "(", "this", ".", "_opSetQueue", ",", "function", "(", "opSet", ")", "{", "self", ".", "_applyOpSet", "(", "opSet", ",", "self", ".", "attributes", ")", ";", "Parse", ".", "_objectEach", "(", "opSet", ",", "function", "(", "op", ",", "key", ")", "{", "self", ".", "_resetCacheForKey", "(", "key", ")", ";", "}", ")", ";", "}", ")", ";", "Parse", ".", "_objectEach", "(", "previousAttributes", ",", "function", "(", "oldValue", ",", "key", ")", "{", "if", "(", "self", ".", "attributes", "[", "key", "]", "!==", "oldValue", ")", "{", "self", ".", "trigger", "(", "'change:'", "+", "key", ",", "self", ",", "self", ".", "attributes", "[", "key", "]", ",", "{", "}", ")", ";", "}", "}", ")", ";", "Parse", ".", "_objectEach", "(", "this", ".", "attributes", ",", "function", "(", "newValue", ",", "key", ")", "{", "if", "(", "!", "_", ".", "has", "(", "previousAttributes", ",", "key", ")", ")", "{", "self", ".", "trigger", "(", "'change:'", "+", "key", ",", "self", ",", "newValue", ",", "{", "}", ")", ";", "}", "}", ")", ";", "}" ]
Populates attributes by starting with the last known data from the server, and applying all of the local changes that have been made since then.
[ "Populates", "attributes", "by", "starting", "with", "the", "last", "known", "data", "from", "the", "server", "and", "applying", "all", "of", "the", "local", "changes", "that", "have", "been", "made", "since", "then", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/object.js#L686-L710
train
RnbWd/parse-browserify
lib/object.js
function(attr, amount) { if (_.isUndefined(amount) || _.isNull(amount)) { amount = 1; } return this.set(attr, new Parse.Op.Increment(amount)); }
javascript
function(attr, amount) { if (_.isUndefined(amount) || _.isNull(amount)) { amount = 1; } return this.set(attr, new Parse.Op.Increment(amount)); }
[ "function", "(", "attr", ",", "amount", ")", "{", "if", "(", "_", ".", "isUndefined", "(", "amount", ")", "||", "_", ".", "isNull", "(", "amount", ")", ")", "{", "amount", "=", "1", ";", "}", "return", "this", ".", "set", "(", "attr", ",", "new", "Parse", ".", "Op", ".", "Increment", "(", "amount", ")", ")", ";", "}" ]
Atomically increments the value of the given attribute the next time the object is saved. If no amount is specified, 1 is used by default. @param attr {String} The key. @param amount {Number} The amount to increment by.
[ "Atomically", "increments", "the", "value", "of", "the", "given", "attribute", "the", "next", "time", "the", "object", "is", "saved", ".", "If", "no", "amount", "is", "specified", "1", "is", "used", "by", "default", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/object.js#L867-L872
train
RnbWd/parse-browserify
lib/object.js
function() { var json = _.clone(_.first(this._opSetQueue)); Parse._objectEach(json, function(op, key) { json[key] = op.toJSON(); }); return json; }
javascript
function() { var json = _.clone(_.first(this._opSetQueue)); Parse._objectEach(json, function(op, key) { json[key] = op.toJSON(); }); return json; }
[ "function", "(", ")", "{", "var", "json", "=", "_", ".", "clone", "(", "_", ".", "first", "(", "this", ".", "_opSetQueue", ")", ")", ";", "Parse", ".", "_objectEach", "(", "json", ",", "function", "(", "op", ",", "key", ")", "{", "json", "[", "key", "]", "=", "op", ".", "toJSON", "(", ")", ";", "}", ")", ";", "return", "json", ";", "}" ]
Returns a JSON-encoded set of operations to be sent with the next save request.
[ "Returns", "a", "JSON", "-", "encoded", "set", "of", "operations", "to", "be", "sent", "with", "the", "next", "save", "request", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/object.js#L935-L941
train
atuttle/corq
corq.js
$item
function $item(corq, item){ var typeName = item.type; if (!corq.callbacks[typeName]){ throw "Item handler not found for items of type `" + typeName + "`"; } $debug(corq, 'Corq: Calling handler for item `' + typeName + '`'); $debug(corq, item.data); var _next = function(){ var freq = (corq.delay) ? corq.delayLength : corq.frequency; setTimeout(function(){ $next(corq); }, freq); }; var _success = function(){ $debug(corq, 'Corq: Item processing SUCCESS `' + typeName + '` '); $debug(corq, item.data); $success(corq,item); _next(); }; var _fail = function(){ $debug(corq, 'Corq: Item processing FAILURE `' + typeName + '` '); $debug(corq, item.data); $fail(corq, item); _next(); }; try { corq.callbacks[typeName](item.data, _success, _fail); }catch(e){ $debug(corq, 'Corq: Error thrown by item processing function `' + typeName + '` '); $debug(corq, item.data); _fail(); throw e; } }
javascript
function $item(corq, item){ var typeName = item.type; if (!corq.callbacks[typeName]){ throw "Item handler not found for items of type `" + typeName + "`"; } $debug(corq, 'Corq: Calling handler for item `' + typeName + '`'); $debug(corq, item.data); var _next = function(){ var freq = (corq.delay) ? corq.delayLength : corq.frequency; setTimeout(function(){ $next(corq); }, freq); }; var _success = function(){ $debug(corq, 'Corq: Item processing SUCCESS `' + typeName + '` '); $debug(corq, item.data); $success(corq,item); _next(); }; var _fail = function(){ $debug(corq, 'Corq: Item processing FAILURE `' + typeName + '` '); $debug(corq, item.data); $fail(corq, item); _next(); }; try { corq.callbacks[typeName](item.data, _success, _fail); }catch(e){ $debug(corq, 'Corq: Error thrown by item processing function `' + typeName + '` '); $debug(corq, item.data); _fail(); throw e; } }
[ "function", "$item", "(", "corq", ",", "item", ")", "{", "var", "typeName", "=", "item", ".", "type", ";", "if", "(", "!", "corq", ".", "callbacks", "[", "typeName", "]", ")", "{", "throw", "\"Item handler not found for items of type `\"", "+", "typeName", "+", "\"`\"", ";", "}", "$debug", "(", "corq", ",", "'Corq: Calling handler for item `'", "+", "typeName", "+", "'`'", ")", ";", "$debug", "(", "corq", ",", "item", ".", "data", ")", ";", "var", "_next", "=", "function", "(", ")", "{", "var", "freq", "=", "(", "corq", ".", "delay", ")", "?", "corq", ".", "delayLength", ":", "corq", ".", "frequency", ";", "setTimeout", "(", "function", "(", ")", "{", "$next", "(", "corq", ")", ";", "}", ",", "freq", ")", ";", "}", ";", "var", "_success", "=", "function", "(", ")", "{", "$debug", "(", "corq", ",", "'Corq: Item processing SUCCESS `'", "+", "typeName", "+", "'` '", ")", ";", "$debug", "(", "corq", ",", "item", ".", "data", ")", ";", "$success", "(", "corq", ",", "item", ")", ";", "_next", "(", ")", ";", "}", ";", "var", "_fail", "=", "function", "(", ")", "{", "$debug", "(", "corq", ",", "'Corq: Item processing FAILURE `'", "+", "typeName", "+", "'` '", ")", ";", "$debug", "(", "corq", ",", "item", ".", "data", ")", ";", "$fail", "(", "corq", ",", "item", ")", ";", "_next", "(", ")", ";", "}", ";", "try", "{", "corq", ".", "callbacks", "[", "typeName", "]", "(", "item", ".", "data", ",", "_success", ",", "_fail", ")", ";", "}", "catch", "(", "e", ")", "{", "$debug", "(", "corq", ",", "'Corq: Error thrown by item processing function `'", "+", "typeName", "+", "'` '", ")", ";", "$debug", "(", "corq", ",", "item", ".", "data", ")", ";", "_fail", "(", ")", ";", "throw", "e", ";", "}", "}" ]
calls all necessary handlers for this item
[ "calls", "all", "necessary", "handlers", "for", "this", "item" ]
02738b3fedf54012b2df7b7b8dd0c4b96505fad5
https://github.com/atuttle/corq/blob/02738b3fedf54012b2df7b7b8dd0c4b96505fad5/corq.js#L105-L138
train
jameswyse/rego
lib/Registry.js
getOrRegister
function getOrRegister(name, definition) { if(name && !definition) { return registry.get(name); } if(name && definition) { return registry.register(name, definition); } return null; }
javascript
function getOrRegister(name, definition) { if(name && !definition) { return registry.get(name); } if(name && definition) { return registry.register(name, definition); } return null; }
[ "function", "getOrRegister", "(", "name", ",", "definition", ")", "{", "if", "(", "name", "&&", "!", "definition", ")", "{", "return", "registry", ".", "get", "(", "name", ")", ";", "}", "if", "(", "name", "&&", "definition", ")", "{", "return", "registry", ".", "register", "(", "name", ",", "definition", ")", ";", "}", "return", "null", ";", "}" ]
get or register a service
[ "get", "or", "register", "a", "service" ]
18565c733c91157ff1149e6e505ef84a3d6fd441
https://github.com/jameswyse/rego/blob/18565c733c91157ff1149e6e505ef84a3d6fd441/lib/Registry.js#L19-L28
train
allanmboyd/spidertest
lib/spider.js
extractHeaderCookies
function extractHeaderCookies(headerSet) { var cookie = headerSet.cookie; var cookies = cookie ? cookie.split(';') : []; delete headerSet.cookie; return cookies; }
javascript
function extractHeaderCookies(headerSet) { var cookie = headerSet.cookie; var cookies = cookie ? cookie.split(';') : []; delete headerSet.cookie; return cookies; }
[ "function", "extractHeaderCookies", "(", "headerSet", ")", "{", "var", "cookie", "=", "headerSet", ".", "cookie", ";", "var", "cookies", "=", "cookie", "?", "cookie", ".", "split", "(", "';'", ")", ":", "[", "]", ";", "delete", "headerSet", ".", "cookie", ";", "return", "cookies", ";", "}" ]
Pull out the cookie from a header set. It is assumed that there is a max of 1 cookie header per header set. The cookie is removed from the headerSet if found. @param {Object} headerSet the set of headers from which to extract the cookies
[ "Pull", "out", "the", "cookie", "from", "a", "header", "set", ".", "It", "is", "assumed", "that", "there", "is", "a", "max", "of", "1", "cookie", "header", "per", "header", "set", ".", "The", "cookie", "is", "removed", "from", "the", "headerSet", "if", "found", "." ]
c3f5ddc583a963706d31ec464bc128ec2db672dc
https://github.com/allanmboyd/spidertest/blob/c3f5ddc583a963706d31ec464bc128ec2db672dc/lib/spider.js#L267-L272
train
directiv/data-hyper-img
index.js
hyperImg
function hyperImg(store) { this.compile = function(input) { var path = input.split('.'); return { path: input, target: path[path.length - 1] }; }; this.state = function(config, state) { var res = store.get(config.path, state); if (!res.completed) return false; return state.set(config.target, res.value); }; this.props = function(config, state, props) { var image = state.get(config.target); if (!image || !image.src) return props; if (image.title) props = props.set('title', image.title); return props.set('src', image.src); }; }
javascript
function hyperImg(store) { this.compile = function(input) { var path = input.split('.'); return { path: input, target: path[path.length - 1] }; }; this.state = function(config, state) { var res = store.get(config.path, state); if (!res.completed) return false; return state.set(config.target, res.value); }; this.props = function(config, state, props) { var image = state.get(config.target); if (!image || !image.src) return props; if (image.title) props = props.set('title', image.title); return props.set('src', image.src); }; }
[ "function", "hyperImg", "(", "store", ")", "{", "this", ".", "compile", "=", "function", "(", "input", ")", "{", "var", "path", "=", "input", ".", "split", "(", "'.'", ")", ";", "return", "{", "path", ":", "input", ",", "target", ":", "path", "[", "path", ".", "length", "-", "1", "]", "}", ";", "}", ";", "this", ".", "state", "=", "function", "(", "config", ",", "state", ")", "{", "var", "res", "=", "store", ".", "get", "(", "config", ".", "path", ",", "state", ")", ";", "if", "(", "!", "res", ".", "completed", ")", "return", "false", ";", "return", "state", ".", "set", "(", "config", ".", "target", ",", "res", ".", "value", ")", ";", "}", ";", "this", ".", "props", "=", "function", "(", "config", ",", "state", ",", "props", ")", "{", "var", "image", "=", "state", ".", "get", "(", "config", ".", "target", ")", ";", "if", "(", "!", "image", "||", "!", "image", ".", "src", ")", "return", "props", ";", "if", "(", "image", ".", "title", ")", "props", "=", "props", ".", "set", "(", "'title'", ",", "image", ".", "title", ")", ";", "return", "props", ".", "set", "(", "'src'", ",", "image", ".", "src", ")", ";", "}", ";", "}" ]
Initialize the 'hyper-img' directive @param {StoreHyper} store
[ "Initialize", "the", "hyper", "-", "img", "directive" ]
18a285ecbef12e31d7dbc4186f9d50fa1e83aa98
https://github.com/directiv/data-hyper-img/blob/18a285ecbef12e31d7dbc4186f9d50fa1e83aa98/index.js#L19-L40
train
at88mph/opencadc-registry
registry.js
Registry
function Registry(opts) { var defaultOptions = { resourceCapabilitiesEndPoint: 'http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/reg/resource-caps' } var options = opts || {} this.axiosConfig = { method: 'get', withCredentials: true, crossDomain: true } this.resourceCapabilitiesURL = URL.parse( options.resourceCapabilitiesEndPoint || defaultOptions.resourceCapabilitiesEndPoint ) /** * @param {URL} URI of the resource to obtain a service URL for. * @param {{}} callback Function to callback. Optional, and defaults to a Promise. * @returns {Promise} */ this.capabilityURLs = async function(callback) { var aConf = Object.assign( { url: this.resourceCapabilitiesURL.href }, this.axiosConfig ) var p = axios(aConf) if (callback) { p.then(callback) } else { return p } } /** * Obtain a service URL endpoint for the given resource and standard IDs * * @param {String|URL} resourceURI The Resource URI to lookup. * @param {String|URL} The Standard ID URI to lookup. * @param {boolean} secureFlag Whether to look for HTTPS access URLs. Requires client certificate. * @param {{}} callback Optional function to callback. * @returns {Promise} */ this.serviceURL = async function( resourceURI, standardURI, secureFlag, callback ) { var aConf = Object.assign({}, this.axiosConfig) return this.capabilityURLs().then(function(results) { var properties = new PropertiesReader().read(results.data) var capabilitiesURL = properties.get(resourceURI) if (capabilitiesURL) { aConf.url = capabilitiesURL return axios(aConf).then(function(capResults) { var doc = new DOMParser().parseFromString(capResults.data) var capabilityFields = doc.documentElement.getElementsByTagName( 'capability' ) for (var i = 0, cfl = capabilityFields.length; i < cfl; i++) { var next = capabilityFields[i] if (next.getAttribute('standardID') === standardURI) { var interfaces = next.getElementsByTagName('interface') for (var j = 0, il = interfaces.length; j < il; j++) { var nextInterface = interfaces[j] var securityMethods = nextInterface.getElementsByTagName( 'securityMethod' ) if ( (secureFlag === false && securityMethods.length === 0) || (secureFlag === true && securityMethods.length > 0 && securityMethods[0].getAttribute('standardID') === 'ivo://ivoa.net/sso#tls-with-certificate') ) { // Actual URL value. var accessURLElements = nextInterface.getElementsByTagName( 'accessURL' ) return accessURLElements.length > 0 ? accessURLElements[0].childNodes[0].nodeValue : null } } } } throw 'No service URL found' }) } else { throw `No service entry found for ${resourceURI}` } }) } }
javascript
function Registry(opts) { var defaultOptions = { resourceCapabilitiesEndPoint: 'http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/reg/resource-caps' } var options = opts || {} this.axiosConfig = { method: 'get', withCredentials: true, crossDomain: true } this.resourceCapabilitiesURL = URL.parse( options.resourceCapabilitiesEndPoint || defaultOptions.resourceCapabilitiesEndPoint ) /** * @param {URL} URI of the resource to obtain a service URL for. * @param {{}} callback Function to callback. Optional, and defaults to a Promise. * @returns {Promise} */ this.capabilityURLs = async function(callback) { var aConf = Object.assign( { url: this.resourceCapabilitiesURL.href }, this.axiosConfig ) var p = axios(aConf) if (callback) { p.then(callback) } else { return p } } /** * Obtain a service URL endpoint for the given resource and standard IDs * * @param {String|URL} resourceURI The Resource URI to lookup. * @param {String|URL} The Standard ID URI to lookup. * @param {boolean} secureFlag Whether to look for HTTPS access URLs. Requires client certificate. * @param {{}} callback Optional function to callback. * @returns {Promise} */ this.serviceURL = async function( resourceURI, standardURI, secureFlag, callback ) { var aConf = Object.assign({}, this.axiosConfig) return this.capabilityURLs().then(function(results) { var properties = new PropertiesReader().read(results.data) var capabilitiesURL = properties.get(resourceURI) if (capabilitiesURL) { aConf.url = capabilitiesURL return axios(aConf).then(function(capResults) { var doc = new DOMParser().parseFromString(capResults.data) var capabilityFields = doc.documentElement.getElementsByTagName( 'capability' ) for (var i = 0, cfl = capabilityFields.length; i < cfl; i++) { var next = capabilityFields[i] if (next.getAttribute('standardID') === standardURI) { var interfaces = next.getElementsByTagName('interface') for (var j = 0, il = interfaces.length; j < il; j++) { var nextInterface = interfaces[j] var securityMethods = nextInterface.getElementsByTagName( 'securityMethod' ) if ( (secureFlag === false && securityMethods.length === 0) || (secureFlag === true && securityMethods.length > 0 && securityMethods[0].getAttribute('standardID') === 'ivo://ivoa.net/sso#tls-with-certificate') ) { // Actual URL value. var accessURLElements = nextInterface.getElementsByTagName( 'accessURL' ) return accessURLElements.length > 0 ? accessURLElements[0].childNodes[0].nodeValue : null } } } } throw 'No service URL found' }) } else { throw `No service entry found for ${resourceURI}` } }) } }
[ "function", "Registry", "(", "opts", ")", "{", "var", "defaultOptions", "=", "{", "resourceCapabilitiesEndPoint", ":", "'http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/reg/resource-caps'", "}", "var", "options", "=", "opts", "||", "{", "}", "this", ".", "axiosConfig", "=", "{", "method", ":", "'get'", ",", "withCredentials", ":", "true", ",", "crossDomain", ":", "true", "}", "this", ".", "resourceCapabilitiesURL", "=", "URL", ".", "parse", "(", "options", ".", "resourceCapabilitiesEndPoint", "||", "defaultOptions", ".", "resourceCapabilitiesEndPoint", ")", "this", ".", "capabilityURLs", "=", "async", "function", "(", "callback", ")", "{", "var", "aConf", "=", "Object", ".", "assign", "(", "{", "url", ":", "this", ".", "resourceCapabilitiesURL", ".", "href", "}", ",", "this", ".", "axiosConfig", ")", "var", "p", "=", "axios", "(", "aConf", ")", "if", "(", "callback", ")", "{", "p", ".", "then", "(", "callback", ")", "}", "else", "{", "return", "p", "}", "}", "this", ".", "serviceURL", "=", "async", "function", "(", "resourceURI", ",", "standardURI", ",", "secureFlag", ",", "callback", ")", "{", "var", "aConf", "=", "Object", ".", "assign", "(", "{", "}", ",", "this", ".", "axiosConfig", ")", "return", "this", ".", "capabilityURLs", "(", ")", ".", "then", "(", "function", "(", "results", ")", "{", "var", "properties", "=", "new", "PropertiesReader", "(", ")", ".", "read", "(", "results", ".", "data", ")", "var", "capabilitiesURL", "=", "properties", ".", "get", "(", "resourceURI", ")", "if", "(", "capabilitiesURL", ")", "{", "aConf", ".", "url", "=", "capabilitiesURL", "return", "axios", "(", "aConf", ")", ".", "then", "(", "function", "(", "capResults", ")", "{", "var", "doc", "=", "new", "DOMParser", "(", ")", ".", "parseFromString", "(", "capResults", ".", "data", ")", "var", "capabilityFields", "=", "doc", ".", "documentElement", ".", "getElementsByTagName", "(", "'capability'", ")", "for", "(", "var", "i", "=", "0", ",", "cfl", "=", "capabilityFields", ".", "length", ";", "i", "<", "cfl", ";", "i", "++", ")", "{", "var", "next", "=", "capabilityFields", "[", "i", "]", "if", "(", "next", ".", "getAttribute", "(", "'standardID'", ")", "===", "standardURI", ")", "{", "var", "interfaces", "=", "next", ".", "getElementsByTagName", "(", "'interface'", ")", "for", "(", "var", "j", "=", "0", ",", "il", "=", "interfaces", ".", "length", ";", "j", "<", "il", ";", "j", "++", ")", "{", "var", "nextInterface", "=", "interfaces", "[", "j", "]", "var", "securityMethods", "=", "nextInterface", ".", "getElementsByTagName", "(", "'securityMethod'", ")", "if", "(", "(", "secureFlag", "===", "false", "&&", "securityMethods", ".", "length", "===", "0", ")", "||", "(", "secureFlag", "===", "true", "&&", "securityMethods", ".", "length", ">", "0", "&&", "securityMethods", "[", "0", "]", ".", "getAttribute", "(", "'standardID'", ")", "===", "'ivo://ivoa.net/sso#tls-with-certificate'", ")", ")", "{", "var", "accessURLElements", "=", "nextInterface", ".", "getElementsByTagName", "(", "'accessURL'", ")", "return", "accessURLElements", ".", "length", ">", "0", "?", "accessURLElements", "[", "0", "]", ".", "childNodes", "[", "0", "]", ".", "nodeValue", ":", "null", "}", "}", "}", "}", "throw", "'No service URL found'", "}", ")", "}", "else", "{", "throw", "`", "${", "resourceURI", "}", "`", "}", "}", ")", "}", "}" ]
Registry client constructor. This client ALWAYS uses the JWT authorization. @param {{}} opts @constructor
[ "Registry", "client", "constructor", "." ]
379cd0479185ce1fd2e3cacd5f7ac6fe0672194a
https://github.com/at88mph/opencadc-registry/blob/379cd0479185ce1fd2e3cacd5f7ac6fe0672194a/registry.js#L18-L121
train
beschoenen/grunt-contrib-template
tasks/template.js
getSourceCode
function getSourceCode(filepath) { // The current folder var dir = filepath.substring(0, filepath.lastIndexOf("/") + 1); // Regex for file import var fileRegex = /(?:["'])<!=\s*(.+)\b\s*!>(?:["'])?;?/; // Regex for file extension var fileExtRegex = /\..+$/; // Read the file and check if anything should be imported into it; loop through them return grunt.file.read(filepath).replace(new RegExp(fileRegex.source, "g"), function(match) { // Log the number of imports we did files += 1; // Get the filename var file = match.match(fileRegex)[1]; // Check if it has an extension if(file.match(fileExtRegex) === null) { file += options.defaultExtension; // Add it } var source = ""; // Loop through files glob.sync(dir + file).forEach(function(filename) { // Read file var src = grunt.file.read(filename); // Check if it has imports too source += (function() { return fileRegex.test(src) ? getSourceCode(filename) : src; })() + options.separator; // Add separator }); return source; }); }
javascript
function getSourceCode(filepath) { // The current folder var dir = filepath.substring(0, filepath.lastIndexOf("/") + 1); // Regex for file import var fileRegex = /(?:["'])<!=\s*(.+)\b\s*!>(?:["'])?;?/; // Regex for file extension var fileExtRegex = /\..+$/; // Read the file and check if anything should be imported into it; loop through them return grunt.file.read(filepath).replace(new RegExp(fileRegex.source, "g"), function(match) { // Log the number of imports we did files += 1; // Get the filename var file = match.match(fileRegex)[1]; // Check if it has an extension if(file.match(fileExtRegex) === null) { file += options.defaultExtension; // Add it } var source = ""; // Loop through files glob.sync(dir + file).forEach(function(filename) { // Read file var src = grunt.file.read(filename); // Check if it has imports too source += (function() { return fileRegex.test(src) ? getSourceCode(filename) : src; })() + options.separator; // Add separator }); return source; }); }
[ "function", "getSourceCode", "(", "filepath", ")", "{", "var", "dir", "=", "filepath", ".", "substring", "(", "0", ",", "filepath", ".", "lastIndexOf", "(", "\"/\"", ")", "+", "1", ")", ";", "var", "fileRegex", "=", "/", "(?:[\"'])<!=\\s*(.+)\\b\\s*!>(?:[\"'])?;?", "/", ";", "var", "fileExtRegex", "=", "/", "\\..+$", "/", ";", "return", "grunt", ".", "file", ".", "read", "(", "filepath", ")", ".", "replace", "(", "new", "RegExp", "(", "fileRegex", ".", "source", ",", "\"g\"", ")", ",", "function", "(", "match", ")", "{", "files", "+=", "1", ";", "var", "file", "=", "match", ".", "match", "(", "fileRegex", ")", "[", "1", "]", ";", "if", "(", "file", ".", "match", "(", "fileExtRegex", ")", "===", "null", ")", "{", "file", "+=", "options", ".", "defaultExtension", ";", "}", "var", "source", "=", "\"\"", ";", "glob", ".", "sync", "(", "dir", "+", "file", ")", ".", "forEach", "(", "function", "(", "filename", ")", "{", "var", "src", "=", "grunt", ".", "file", ".", "read", "(", "filename", ")", ";", "source", "+=", "(", "function", "(", ")", "{", "return", "fileRegex", ".", "test", "(", "src", ")", "?", "getSourceCode", "(", "filename", ")", ":", "src", ";", "}", ")", "(", ")", "+", "options", ".", "separator", ";", "}", ")", ";", "return", "source", ";", "}", ")", ";", "}" ]
Recursively resolve the template
[ "Recursively", "resolve", "the", "template" ]
59cf9e5e69469984799d6818092de71e3839956c
https://github.com/beschoenen/grunt-contrib-template/blob/59cf9e5e69469984799d6818092de71e3839956c/tasks/template.js#L29-L65
train
WarWithinMe/grunt-seajs-build
tasks/seajs_build.js
function ( value, index, array ) { if ( visited.hasOwnProperty(value) ) { return; } visited[value] = true; var deps = projectData.dependency[ value ]; if ( !deps ) { return; } for ( var i = 0; i < deps.length; ++i ) { var depAbsPath = projectData.id2File[ deps[i] ]; if ( !depAbsPath ) { grunt.fail.fatal("Can't find file when merging, the file might exist but it's not a Sea.js module : [ " + deps[i] + " ]" ); } this.push( depAbsPath ); reverse_dep_map[ depAbsPath ] = true; } }
javascript
function ( value, index, array ) { if ( visited.hasOwnProperty(value) ) { return; } visited[value] = true; var deps = projectData.dependency[ value ]; if ( !deps ) { return; } for ( var i = 0; i < deps.length; ++i ) { var depAbsPath = projectData.id2File[ deps[i] ]; if ( !depAbsPath ) { grunt.fail.fatal("Can't find file when merging, the file might exist but it's not a Sea.js module : [ " + deps[i] + " ]" ); } this.push( depAbsPath ); reverse_dep_map[ depAbsPath ] = true; } }
[ "function", "(", "value", ",", "index", ",", "array", ")", "{", "if", "(", "visited", ".", "hasOwnProperty", "(", "value", ")", ")", "{", "return", ";", "}", "visited", "[", "value", "]", "=", "true", ";", "var", "deps", "=", "projectData", ".", "dependency", "[", "value", "]", ";", "if", "(", "!", "deps", ")", "{", "return", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "deps", ".", "length", ";", "++", "i", ")", "{", "var", "depAbsPath", "=", "projectData", ".", "id2File", "[", "deps", "[", "i", "]", "]", ";", "if", "(", "!", "depAbsPath", ")", "{", "grunt", ".", "fail", ".", "fatal", "(", "\"Can't find file when merging, the file might exist but it's not a Sea.js module : [ \"", "+", "deps", "[", "i", "]", "+", "\" ]\"", ")", ";", "}", "this", ".", "push", "(", "depAbsPath", ")", ";", "reverse_dep_map", "[", "depAbsPath", "]", "=", "true", ";", "}", "}" ]
Finds out which file can be the entry point.
[ "Finds", "out", "which", "file", "can", "be", "the", "entry", "point", "." ]
ff6ec8bebb0e83d2aaab3c78d4fb3580e4d80b1b
https://github.com/WarWithinMe/grunt-seajs-build/blob/ff6ec8bebb0e83d2aaab3c78d4fb3580e4d80b1b/tasks/seajs_build.js#L504-L521
train
YYago/fswsyn
index.js
writeFileSyncLong
function writeFileSyncLong(filepath, contents) { const options = arguments[2] || { flag: 'w', encoding: 'utf8' }; let lastPath; const pathNormal = path.normalize(filepath); if (path.isAbsolute(pathNormal)) { lastPath = pathNormal; } else { lastPath = path.resolve(pathNormal); } if (fs.existsSync(lastPath)) { fs.writeFileSync(lastPath, contents, options); } else { let prefixPath = []; let dir = path.dirname(lastPath); let splitPath = dir.split(path.sep) if (splitPath[0] == "") { splitPath.splice(0, 1, "/");// 将Unix 下的产生的root[""]替换为["/"]; } for (let i = 0; i < splitPath.length; i++) { prefixPath.push(splitPath[i]); let prefixPaths = prefixPath.join("/"); if (fs.existsSync(prefixPaths) == false) { fs.mkdirSync(prefixPaths); } } fs.writeFileSync(lastPath, contents, options); } }
javascript
function writeFileSyncLong(filepath, contents) { const options = arguments[2] || { flag: 'w', encoding: 'utf8' }; let lastPath; const pathNormal = path.normalize(filepath); if (path.isAbsolute(pathNormal)) { lastPath = pathNormal; } else { lastPath = path.resolve(pathNormal); } if (fs.existsSync(lastPath)) { fs.writeFileSync(lastPath, contents, options); } else { let prefixPath = []; let dir = path.dirname(lastPath); let splitPath = dir.split(path.sep) if (splitPath[0] == "") { splitPath.splice(0, 1, "/");// 将Unix 下的产生的root[""]替换为["/"]; } for (let i = 0; i < splitPath.length; i++) { prefixPath.push(splitPath[i]); let prefixPaths = prefixPath.join("/"); if (fs.existsSync(prefixPaths) == false) { fs.mkdirSync(prefixPaths); } } fs.writeFileSync(lastPath, contents, options); } }
[ "function", "writeFileSyncLong", "(", "filepath", ",", "contents", ")", "{", "const", "options", "=", "arguments", "[", "2", "]", "||", "{", "flag", ":", "'w'", ",", "encoding", ":", "'utf8'", "}", ";", "let", "lastPath", ";", "const", "pathNormal", "=", "path", ".", "normalize", "(", "filepath", ")", ";", "if", "(", "path", ".", "isAbsolute", "(", "pathNormal", ")", ")", "{", "lastPath", "=", "pathNormal", ";", "}", "else", "{", "lastPath", "=", "path", ".", "resolve", "(", "pathNormal", ")", ";", "}", "if", "(", "fs", ".", "existsSync", "(", "lastPath", ")", ")", "{", "fs", ".", "writeFileSync", "(", "lastPath", ",", "contents", ",", "options", ")", ";", "}", "else", "{", "let", "prefixPath", "=", "[", "]", ";", "let", "dir", "=", "path", ".", "dirname", "(", "lastPath", ")", ";", "let", "splitPath", "=", "dir", ".", "split", "(", "path", ".", "sep", ")", "if", "(", "splitPath", "[", "0", "]", "==", "\"\"", ")", "{", "splitPath", ".", "splice", "(", "0", ",", "1", ",", "\"/\"", ")", ";", "}", "for", "(", "let", "i", "=", "0", ";", "i", "<", "splitPath", ".", "length", ";", "i", "++", ")", "{", "prefixPath", ".", "push", "(", "splitPath", "[", "i", "]", ")", ";", "let", "prefixPaths", "=", "prefixPath", ".", "join", "(", "\"/\"", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "prefixPaths", ")", "==", "false", ")", "{", "fs", ".", "mkdirSync", "(", "prefixPaths", ")", ";", "}", "}", "fs", ".", "writeFileSync", "(", "lastPath", ",", "contents", ",", "options", ")", ";", "}", "}" ]
write a file with long path. @param {*} filepath file path @param {string} contents content @param {object} param2 options default:{flag:'w',encoding:'utf8'} WARRING: 不要在路径中使用单个“\\”符号作为路径分隔符,不管是Windows_NT系统还是Unix系统,它带来的问题目前无解。正则表达式:'/\\\\/g'无法匹配"\\",我也无能为力。 其实,这个问题貌似只出现Windows系统,在Unix系统中写代码的时候输入单个"\\"就已经发生了变化(用于转义),而不像在Windows中允许其作为一个有意义的字符存在。
[ "write", "a", "file", "with", "long", "path", "." ]
d6fa34b8d079aa28bf9a2a94d82717edfcb8eeba
https://github.com/YYago/fswsyn/blob/d6fa34b8d079aa28bf9a2a94d82717edfcb8eeba/index.js#L213-L240
train
wilmoore/function-accessor.js
index.js
isValid
function isValid (value, predicate, self) { if (predicate instanceof Function) { return predicate.call(self, value) } if (predicate instanceof RegExp) { return predicate.test(value) } return true }
javascript
function isValid (value, predicate, self) { if (predicate instanceof Function) { return predicate.call(self, value) } if (predicate instanceof RegExp) { return predicate.test(value) } return true }
[ "function", "isValid", "(", "value", ",", "predicate", ",", "self", ")", "{", "if", "(", "predicate", "instanceof", "Function", ")", "{", "return", "predicate", ".", "call", "(", "self", ",", "value", ")", "}", "if", "(", "predicate", "instanceof", "RegExp", ")", "{", "return", "predicate", ".", "test", "(", "value", ")", "}", "return", "true", "}" ]
Validates input per predicate if predicate is a `Function` or `RegExp`. @param {*} value Value to check. @param {Function|RegExp} [predicate] Predicate to check value against. @param {Object} [self] Object context. @return {Boolean} Whether value is valid.
[ "Validates", "input", "per", "predicate", "if", "predicate", "is", "a", "Function", "or", "RegExp", "." ]
49b6a8187b856b95a46b1a7703dbcea0cf3588b4
https://github.com/wilmoore/function-accessor.js/blob/49b6a8187b856b95a46b1a7703dbcea0cf3588b4/index.js#L78-L88
train
jimf/hour-convert
index.js
to12Hour
function to12Hour(hour) { var meridiem = hour < 12 ? 'am' : 'pm'; return { hour: ((hour + 11) % 12 + 1), meridiem: meridiem, meridian: meridiem }; }
javascript
function to12Hour(hour) { var meridiem = hour < 12 ? 'am' : 'pm'; return { hour: ((hour + 11) % 12 + 1), meridiem: meridiem, meridian: meridiem }; }
[ "function", "to12Hour", "(", "hour", ")", "{", "var", "meridiem", "=", "hour", "<", "12", "?", "'am'", ":", "'pm'", ";", "return", "{", "hour", ":", "(", "(", "hour", "+", "11", ")", "%", "12", "+", "1", ")", ",", "meridiem", ":", "meridiem", ",", "meridian", ":", "meridiem", "}", ";", "}" ]
Convert 24-hour time to 12-hour format. @param {number} hour Hour to convert (0-23) @return {object} { hour, meridiem } (meridian is also returned for backwards compatibility)
[ "Convert", "24", "-", "hour", "time", "to", "12", "-", "hour", "format", "." ]
f38d9700872cf99ebd6c87bbfeac1984d29d3c32
https://github.com/jimf/hour-convert/blob/f38d9700872cf99ebd6c87bbfeac1984d29d3c32/index.js#L11-L18
train
jimf/hour-convert
index.js
to24Hour
function to24Hour(time) { var meridiem = time.meridiem || time.meridian; return (meridiem === 'am' ? 0 : 12) + (time.hour % 12); }
javascript
function to24Hour(time) { var meridiem = time.meridiem || time.meridian; return (meridiem === 'am' ? 0 : 12) + (time.hour % 12); }
[ "function", "to24Hour", "(", "time", ")", "{", "var", "meridiem", "=", "time", ".", "meridiem", "||", "time", ".", "meridian", ";", "return", "(", "meridiem", "===", "'am'", "?", "0", ":", "12", ")", "+", "(", "time", ".", "hour", "%", "12", ")", ";", "}" ]
Convert 12-hour time to 24-hour format. @param {object} time Time object @param {number} time.hour Hour to convert (1-12) @param {string} time.meridiem Hour meridiem (am/pm). 'time.meridian' is supported for backwards compatibility. @return {number}
[ "Convert", "12", "-", "hour", "time", "to", "24", "-", "hour", "format", "." ]
f38d9700872cf99ebd6c87bbfeac1984d29d3c32
https://github.com/jimf/hour-convert/blob/f38d9700872cf99ebd6c87bbfeac1984d29d3c32/index.js#L29-L32
train
greggman/hft-sample-ui
src/hft/scripts/misc/logger.js
function(args) { var lastArgWasNumber = false; var numArgs = args.length; var strs = []; for (var ii = 0; ii < numArgs; ++ii) { var arg = args[ii]; if (arg === undefined) { strs.push('undefined'); } else if (typeof arg === 'number') { if (lastArgWasNumber) { strs.push(", "); } if (arg === Math.floor(arg)) { strs.push(arg.toFixed(0)); } else { strs.push(arg.toFixed(3)); } lastArgWasNumber = true; } else if (window.Float32Array && arg instanceof Float32Array) { // TODO(gman): Make this handle other types of arrays. strs.push(tdl.string.argsToString(arg)); } else { strs.push(arg.toString()); lastArgWasNumber = false; } } return strs.join(""); }
javascript
function(args) { var lastArgWasNumber = false; var numArgs = args.length; var strs = []; for (var ii = 0; ii < numArgs; ++ii) { var arg = args[ii]; if (arg === undefined) { strs.push('undefined'); } else if (typeof arg === 'number') { if (lastArgWasNumber) { strs.push(", "); } if (arg === Math.floor(arg)) { strs.push(arg.toFixed(0)); } else { strs.push(arg.toFixed(3)); } lastArgWasNumber = true; } else if (window.Float32Array && arg instanceof Float32Array) { // TODO(gman): Make this handle other types of arrays. strs.push(tdl.string.argsToString(arg)); } else { strs.push(arg.toString()); lastArgWasNumber = false; } } return strs.join(""); }
[ "function", "(", "args", ")", "{", "var", "lastArgWasNumber", "=", "false", ";", "var", "numArgs", "=", "args", ".", "length", ";", "var", "strs", "=", "[", "]", ";", "for", "(", "var", "ii", "=", "0", ";", "ii", "<", "numArgs", ";", "++", "ii", ")", "{", "var", "arg", "=", "args", "[", "ii", "]", ";", "if", "(", "arg", "===", "undefined", ")", "{", "strs", ".", "push", "(", "'undefined'", ")", ";", "}", "else", "if", "(", "typeof", "arg", "===", "'number'", ")", "{", "if", "(", "lastArgWasNumber", ")", "{", "strs", ".", "push", "(", "\", \"", ")", ";", "}", "if", "(", "arg", "===", "Math", ".", "floor", "(", "arg", ")", ")", "{", "strs", ".", "push", "(", "arg", ".", "toFixed", "(", "0", ")", ")", ";", "}", "else", "{", "strs", ".", "push", "(", "arg", ".", "toFixed", "(", "3", ")", ")", ";", "}", "lastArgWasNumber", "=", "true", ";", "}", "else", "if", "(", "window", ".", "Float32Array", "&&", "arg", "instanceof", "Float32Array", ")", "{", "strs", ".", "push", "(", "tdl", ".", "string", ".", "argsToString", "(", "arg", ")", ")", ";", "}", "else", "{", "strs", ".", "push", "(", "arg", ".", "toString", "(", ")", ")", ";", "lastArgWasNumber", "=", "false", ";", "}", "}", "return", "strs", ".", "join", "(", "\"\"", ")", ";", "}" ]
FIX! or move to strings.js
[ "FIX!", "or", "move", "to", "strings", ".", "js" ]
b9e20afd5183db73522bcfae48225c87e01f68c0
https://github.com/greggman/hft-sample-ui/blob/b9e20afd5183db73522bcfae48225c87e01f68c0/src/hft/scripts/misc/logger.js#L81-L108
train
baseprime/grapnel-server
index.js
shouldRun
function shouldRun(verb) { // Add extra middleware to check if this method matches the requested HTTP verb return function wareShouldRun(req, res, next) { var shouldRun = (this.running && (req.method === verb || verb.toLowerCase() === 'all')); // Call next in stack if it matches if (shouldRun) next(); } }
javascript
function shouldRun(verb) { // Add extra middleware to check if this method matches the requested HTTP verb return function wareShouldRun(req, res, next) { var shouldRun = (this.running && (req.method === verb || verb.toLowerCase() === 'all')); // Call next in stack if it matches if (shouldRun) next(); } }
[ "function", "shouldRun", "(", "verb", ")", "{", "return", "function", "wareShouldRun", "(", "req", ",", "res", ",", "next", ")", "{", "var", "shouldRun", "=", "(", "this", ".", "running", "&&", "(", "req", ".", "method", "===", "verb", "||", "verb", ".", "toLowerCase", "(", ")", "===", "'all'", ")", ")", ";", "if", "(", "shouldRun", ")", "next", "(", ")", ";", "}", "}" ]
Middleware to check whether or not handler should continue running @param {String} HTTP Method @return {Function} Middleware
[ "Middleware", "to", "check", "whether", "or", "not", "handler", "should", "continue", "running" ]
38b0148700f896c85b8c75713b27bfc5ebdf9bd5
https://github.com/baseprime/grapnel-server/blob/38b0148700f896c85b8c75713b27bfc5ebdf9bd5/index.js#L119-L126
train
Pocketbrain/native-ads-web-ad-library
helpers/xDomainStorageAPI.js
sendReadyMessage
function sendReadyMessage() { var data = { namespace: MESSAGE_NAMESPACE, id: 'iframe-ready' }; parent.postMessage(JSON.stringify(data), '*'); }
javascript
function sendReadyMessage() { var data = { namespace: MESSAGE_NAMESPACE, id: 'iframe-ready' }; parent.postMessage(JSON.stringify(data), '*'); }
[ "function", "sendReadyMessage", "(", ")", "{", "var", "data", "=", "{", "namespace", ":", "MESSAGE_NAMESPACE", ",", "id", ":", "'iframe-ready'", "}", ";", "parent", ".", "postMessage", "(", "JSON", ".", "stringify", "(", "data", ")", ",", "'*'", ")", ";", "}" ]
Send a message to the parent to indicate the page is done loading
[ "Send", "a", "message", "to", "the", "parent", "to", "indicate", "the", "page", "is", "done", "loading" ]
aafee1c42e0569ee77f334fc2c4eb71eb146957e
https://github.com/Pocketbrain/native-ads-web-ad-library/blob/aafee1c42e0569ee77f334fc2c4eb71eb146957e/helpers/xDomainStorageAPI.js#L59-L66
train
kirchrath/tpaxx
client/packages/local/tpaxx-core/.sencha/package/Microloader.js
function (asset, result) { var checksum; result = Microloader.parseResult(result); Microloader.remainingCachedAssets--; if (!result.error) { checksum = Microloader.checksum(result.content, asset.assetConfig.hash); if (!checksum) { _warn("Cached Asset '" + asset.assetConfig.path + "' has failed checksum. This asset will be uncached for future loading"); // Un cache this asset so it is loaded next time asset.uncache(); } //<debug> _debug("Checksum for Cached Asset: " + asset.assetConfig.path + " is " + checksum); //</debug> Boot.registerContent(asset.assetConfig.path, asset.type, result.content); asset.updateContent(result.content); asset.cache(); } else { _warn("There was an error pre-loading the asset '" + asset.assetConfig.path + "'. This asset will be uncached for future loading"); // Un cache this asset so it is loaded next time asset.uncache(); } if (Microloader.remainingCachedAssets === 0) { Microloader.onCachedAssetsReady(); } }
javascript
function (asset, result) { var checksum; result = Microloader.parseResult(result); Microloader.remainingCachedAssets--; if (!result.error) { checksum = Microloader.checksum(result.content, asset.assetConfig.hash); if (!checksum) { _warn("Cached Asset '" + asset.assetConfig.path + "' has failed checksum. This asset will be uncached for future loading"); // Un cache this asset so it is loaded next time asset.uncache(); } //<debug> _debug("Checksum for Cached Asset: " + asset.assetConfig.path + " is " + checksum); //</debug> Boot.registerContent(asset.assetConfig.path, asset.type, result.content); asset.updateContent(result.content); asset.cache(); } else { _warn("There was an error pre-loading the asset '" + asset.assetConfig.path + "'. This asset will be uncached for future loading"); // Un cache this asset so it is loaded next time asset.uncache(); } if (Microloader.remainingCachedAssets === 0) { Microloader.onCachedAssetsReady(); } }
[ "function", "(", "asset", ",", "result", ")", "{", "var", "checksum", ";", "result", "=", "Microloader", ".", "parseResult", "(", "result", ")", ";", "Microloader", ".", "remainingCachedAssets", "--", ";", "if", "(", "!", "result", ".", "error", ")", "{", "checksum", "=", "Microloader", ".", "checksum", "(", "result", ".", "content", ",", "asset", ".", "assetConfig", ".", "hash", ")", ";", "if", "(", "!", "checksum", ")", "{", "_warn", "(", "\"Cached Asset '\"", "+", "asset", ".", "assetConfig", ".", "path", "+", "\"' has failed checksum. This asset will be uncached for future loading\"", ")", ";", "asset", ".", "uncache", "(", ")", ";", "}", "_debug", "(", "\"Checksum for Cached Asset: \"", "+", "asset", ".", "assetConfig", ".", "path", "+", "\" is \"", "+", "checksum", ")", ";", "Boot", ".", "registerContent", "(", "asset", ".", "assetConfig", ".", "path", ",", "asset", ".", "type", ",", "result", ".", "content", ")", ";", "asset", ".", "updateContent", "(", "result", ".", "content", ")", ";", "asset", ".", "cache", "(", ")", ";", "}", "else", "{", "_warn", "(", "\"There was an error pre-loading the asset '\"", "+", "asset", ".", "assetConfig", ".", "path", "+", "\"'. This asset will be uncached for future loading\"", ")", ";", "asset", ".", "uncache", "(", ")", ";", "}", "if", "(", "Microloader", ".", "remainingCachedAssets", "===", "0", ")", "{", "Microloader", ".", "onCachedAssetsReady", "(", ")", ";", "}", "}" ]
Load the asset and seed its content into Boot to be evaluated in sequence
[ "Load", "the", "asset", "and", "seed", "its", "content", "into", "Boot", "to", "be", "evaluated", "in", "sequence" ]
3ccc5b77459d093e823d740ddc53feefb12a9344
https://github.com/kirchrath/tpaxx/blob/3ccc5b77459d093e823d740ddc53feefb12a9344/client/packages/local/tpaxx-core/.sencha/package/Microloader.js#L449-L479
train
kirchrath/tpaxx
client/packages/local/tpaxx-core/.sencha/package/Microloader.js
function (content, delta) { var output = [], chunk, i, ln; if (delta.length === 0) { return content; } for (i = 0,ln = delta.length; i < ln; i++) { chunk = delta[i]; if (typeof chunk === 'number') { output.push(content.substring(chunk, chunk + delta[++i])); } else { output.push(chunk); } } return output.join(''); }
javascript
function (content, delta) { var output = [], chunk, i, ln; if (delta.length === 0) { return content; } for (i = 0,ln = delta.length; i < ln; i++) { chunk = delta[i]; if (typeof chunk === 'number') { output.push(content.substring(chunk, chunk + delta[++i])); } else { output.push(chunk); } } return output.join(''); }
[ "function", "(", "content", ",", "delta", ")", "{", "var", "output", "=", "[", "]", ",", "chunk", ",", "i", ",", "ln", ";", "if", "(", "delta", ".", "length", "===", "0", ")", "{", "return", "content", ";", "}", "for", "(", "i", "=", "0", ",", "ln", "=", "delta", ".", "length", ";", "i", "<", "ln", ";", "i", "++", ")", "{", "chunk", "=", "delta", "[", "i", "]", ";", "if", "(", "typeof", "chunk", "===", "'number'", ")", "{", "output", ".", "push", "(", "content", ".", "substring", "(", "chunk", ",", "chunk", "+", "delta", "[", "++", "i", "]", ")", ")", ";", "}", "else", "{", "output", ".", "push", "(", "chunk", ")", ";", "}", "}", "return", "output", ".", "join", "(", "''", ")", ";", "}" ]
Delta patches content
[ "Delta", "patches", "content" ]
3ccc5b77459d093e823d740ddc53feefb12a9344
https://github.com/kirchrath/tpaxx/blob/3ccc5b77459d093e823d740ddc53feefb12a9344/client/packages/local/tpaxx-core/.sencha/package/Microloader.js#L534-L554
train
medic/couchdb-audit
couchdb-audit/log.js
function(doc, callback) { audit([doc], function(err) { if (err) { return callback(err); } docsDb.saveDoc(doc, callback); }); }
javascript
function(doc, callback) { audit([doc], function(err) { if (err) { return callback(err); } docsDb.saveDoc(doc, callback); }); }
[ "function", "(", "doc", ",", "callback", ")", "{", "audit", "(", "[", "doc", "]", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "docsDb", ".", "saveDoc", "(", "doc", ",", "callback", ")", ";", "}", ")", ";", "}" ]
Saves the given doc with an audit record @name saveDoc(doc, callback) @param {Object} doc @param {Function} callback(err,response) @api public
[ "Saves", "the", "given", "doc", "with", "an", "audit", "record" ]
88a2fde06830e91966fc82c7356ec46da043fc01
https://github.com/medic/couchdb-audit/blob/88a2fde06830e91966fc82c7356ec46da043fc01/couchdb-audit/log.js#L200-L207
train
medic/couchdb-audit
couchdb-audit/log.js
function(docs, options, callback) { if (!callback) { callback = options; options = {}; } audit(docs, function(err) { if (err) { return callback(err); } options.docs = docs; docsDb.bulkDocs(options, callback); }); }
javascript
function(docs, options, callback) { if (!callback) { callback = options; options = {}; } audit(docs, function(err) { if (err) { return callback(err); } options.docs = docs; docsDb.bulkDocs(options, callback); }); }
[ "function", "(", "docs", ",", "options", ",", "callback", ")", "{", "if", "(", "!", "callback", ")", "{", "callback", "=", "options", ";", "options", "=", "{", "}", ";", "}", "audit", "(", "docs", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "options", ".", "docs", "=", "docs", ";", "docsDb", ".", "bulkDocs", "(", "options", ",", "callback", ")", ";", "}", ")", ";", "}" ]
Saves the given docs with individual audit records @name bulkSave(docs, options, callback) @param {Array} docs An array of documents to be saved @param {Object} options Optional options to pass through to bulk save @param {Function} callback(err,response) @api public
[ "Saves", "the", "given", "docs", "with", "individual", "audit", "records" ]
88a2fde06830e91966fc82c7356ec46da043fc01
https://github.com/medic/couchdb-audit/blob/88a2fde06830e91966fc82c7356ec46da043fc01/couchdb-audit/log.js#L218-L230
train
medic/couchdb-audit
couchdb-audit/log.js
function(doc, callback) { audit([doc], 'delete', function(err) { if (err) { return callback(err); } docsDb.removeDoc(doc._id, doc._rev, callback); }); }
javascript
function(doc, callback) { audit([doc], 'delete', function(err) { if (err) { return callback(err); } docsDb.removeDoc(doc._id, doc._rev, callback); }); }
[ "function", "(", "doc", ",", "callback", ")", "{", "audit", "(", "[", "doc", "]", ",", "'delete'", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "docsDb", ".", "removeDoc", "(", "doc", ".", "_id", ",", "doc", ".", "_rev", ",", "callback", ")", ";", "}", ")", ";", "}" ]
Deletes the given doc with auditing @name removeDoc(doc, callback) @param {Object} doc @param {Function} callback(err,response) @api public
[ "Deletes", "the", "given", "doc", "with", "auditing" ]
88a2fde06830e91966fc82c7356ec46da043fc01
https://github.com/medic/couchdb-audit/blob/88a2fde06830e91966fc82c7356ec46da043fc01/couchdb-audit/log.js#L240-L247
train
zship/grunt-amd-check
tasks/amd-check.js
function(arr, i) { var ret = arr.slice(0); for (var j = 0; j < i; j++) { ret = [ret[ret.length - 1]].concat(ret.slice(0, ret.length - 1)); } return ret; }
javascript
function(arr, i) { var ret = arr.slice(0); for (var j = 0; j < i; j++) { ret = [ret[ret.length - 1]].concat(ret.slice(0, ret.length - 1)); } return ret; }
[ "function", "(", "arr", ",", "i", ")", "{", "var", "ret", "=", "arr", ".", "slice", "(", "0", ")", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "i", ";", "j", "++", ")", "{", "ret", "=", "[", "ret", "[", "ret", ".", "length", "-", "1", "]", "]", ".", "concat", "(", "ret", ".", "slice", "(", "0", ",", "ret", ".", "length", "-", "1", ")", ")", ";", "}", "return", "ret", ";", "}" ]
eliminate duplicate circular dependency loops
[ "eliminate", "duplicate", "circular", "dependency", "loops" ]
cabd51c2e33c2dae620420b568cc7853ff5e330c
https://github.com/zship/grunt-amd-check/blob/cabd51c2e33c2dae620420b568cc7853ff5e330c/tasks/amd-check.js#L163-L169
train
zship/grunt-amd-check
tasks/amd-check.js
function(first, second) { if (_equal(first, second)) { return true; } for (var i = 1; i <= first.length; i++) { if (_equal(first, _rotated(second, i))) { return true; } } return false; }
javascript
function(first, second) { if (_equal(first, second)) { return true; } for (var i = 1; i <= first.length; i++) { if (_equal(first, _rotated(second, i))) { return true; } } return false; }
[ "function", "(", "first", ",", "second", ")", "{", "if", "(", "_equal", "(", "first", ",", "second", ")", ")", "{", "return", "true", ";", "}", "for", "(", "var", "i", "=", "1", ";", "i", "<=", "first", ".", "length", ";", "i", "++", ")", "{", "if", "(", "_equal", "(", "first", ",", "_rotated", "(", "second", ",", "i", ")", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
loops are "equal" if their elements are equal when "shifted" to the right by some amount
[ "loops", "are", "equal", "if", "their", "elements", "are", "equal", "when", "shifted", "to", "the", "right", "by", "some", "amount" ]
cabd51c2e33c2dae620420b568cc7853ff5e330c
https://github.com/zship/grunt-amd-check/blob/cabd51c2e33c2dae620420b568cc7853ff5e330c/tasks/amd-check.js#L176-L186
train
bvalosek/sql-params
index.js
sqlParams
function sqlParams(sql, params) { var args = []; var keys = sql.match(/@\w+/g); var aKeys = sql.match(/\$\d+/g); if (keys && aKeys) throw new Error( 'Cannot use both array-style and object-style parametric values'); // Array-style (native) if (aKeys) { return { text: sql, values: params }; } // No params if (!keys) { return { text: sql, values: [] }; } var n = 1; keys.forEach(function(key) { key = key.substr(1); var val = params[key]; if (val === undefined) throw new Error('No value for @' + key + ' provided'); args.push(val); sql = sql.replace('@' + key, '$' + n++); }); return { text: sql, values: args }; }
javascript
function sqlParams(sql, params) { var args = []; var keys = sql.match(/@\w+/g); var aKeys = sql.match(/\$\d+/g); if (keys && aKeys) throw new Error( 'Cannot use both array-style and object-style parametric values'); // Array-style (native) if (aKeys) { return { text: sql, values: params }; } // No params if (!keys) { return { text: sql, values: [] }; } var n = 1; keys.forEach(function(key) { key = key.substr(1); var val = params[key]; if (val === undefined) throw new Error('No value for @' + key + ' provided'); args.push(val); sql = sql.replace('@' + key, '$' + n++); }); return { text: sql, values: args }; }
[ "function", "sqlParams", "(", "sql", ",", "params", ")", "{", "var", "args", "=", "[", "]", ";", "var", "keys", "=", "sql", ".", "match", "(", "/", "@\\w+", "/", "g", ")", ";", "var", "aKeys", "=", "sql", ".", "match", "(", "/", "\\$\\d+", "/", "g", ")", ";", "if", "(", "keys", "&&", "aKeys", ")", "throw", "new", "Error", "(", "'Cannot use both array-style and object-style parametric values'", ")", ";", "if", "(", "aKeys", ")", "{", "return", "{", "text", ":", "sql", ",", "values", ":", "params", "}", ";", "}", "if", "(", "!", "keys", ")", "{", "return", "{", "text", ":", "sql", ",", "values", ":", "[", "]", "}", ";", "}", "var", "n", "=", "1", ";", "keys", ".", "forEach", "(", "function", "(", "key", ")", "{", "key", "=", "key", ".", "substr", "(", "1", ")", ";", "var", "val", "=", "params", "[", "key", "]", ";", "if", "(", "val", "===", "undefined", ")", "throw", "new", "Error", "(", "'No value for @'", "+", "key", "+", "' provided'", ")", ";", "args", ".", "push", "(", "val", ")", ";", "sql", "=", "sql", ".", "replace", "(", "'@'", "+", "key", ",", "'$'", "+", "n", "++", ")", ";", "}", ")", ";", "return", "{", "text", ":", "sql", ",", "values", ":", "args", "}", ";", "}" ]
Given a hash and parametric sql string, swap all of the @vars into $N args and create an array @param {string} sql Parametric sql string @param {object} hash All of the named arguments @return {{sql:string, args:array.<any>}}
[ "Given", "a", "hash", "and", "parametric", "sql", "string", "swap", "all", "of", "the" ]
abaa04f95debb23353f214eb5dec27894851d259
https://github.com/bvalosek/sql-params/blob/abaa04f95debb23353f214eb5dec27894851d259/index.js#L10-L42
train
radiovisual/tokenize-whitespace
index.js
getWordToken
function getWordToken(str) { var word = str.split(/\s/g)[0]; return {text: word, type: 'WORD', length: word.length}; }
javascript
function getWordToken(str) { var word = str.split(/\s/g)[0]; return {text: word, type: 'WORD', length: word.length}; }
[ "function", "getWordToken", "(", "str", ")", "{", "var", "word", "=", "str", ".", "split", "(", "/", "\\s", "/", "g", ")", "[", "0", "]", ";", "return", "{", "text", ":", "word", ",", "type", ":", "'WORD'", ",", "length", ":", "word", ".", "length", "}", ";", "}" ]
Extract whole word values
[ "Extract", "whole", "word", "values" ]
de6991b9ca6e979202df9708770bd785672f8345
https://github.com/radiovisual/tokenize-whitespace/blob/de6991b9ca6e979202df9708770bd785672f8345/index.js#L41-L44
train
bredele/uri-params-match
index.js
contains
function contains (obj1, obj2) { const keys = Object.keys(obj1) let result = keys.length > 0 let l = keys.length while (l--) { const key = keys[l] result = result && match(obj1[key], obj2[key]) } return result }
javascript
function contains (obj1, obj2) { const keys = Object.keys(obj1) let result = keys.length > 0 let l = keys.length while (l--) { const key = keys[l] result = result && match(obj1[key], obj2[key]) } return result }
[ "function", "contains", "(", "obj1", ",", "obj2", ")", "{", "const", "keys", "=", "Object", ".", "keys", "(", "obj1", ")", "let", "result", "=", "keys", ".", "length", ">", "0", "let", "l", "=", "keys", ".", "length", "while", "(", "l", "--", ")", "{", "const", "key", "=", "keys", "[", "l", "]", "result", "=", "result", "&&", "match", "(", "obj1", "[", "key", "]", ",", "obj2", "[", "key", "]", ")", "}", "return", "result", "}" ]
Return true if second object contains all keys and values from the first object. @param {Object} obj1 @param {Object} obj2 @return {Boolean} @api private
[ "Return", "true", "if", "second", "object", "contains", "all", "keys", "and", "values", "from", "the", "first", "object", "." ]
093666babe2b270a99230358892db8e8651264bc
https://github.com/bredele/uri-params-match/blob/093666babe2b270a99230358892db8e8651264bc/index.js#L37-L46
train
Ravenwall/node-ravenwall
index.js
ravenwall
function ravenwall(options) { if (options instanceof statware) return options options = options || {} // set defaults options.sysstats = !(options.sysstats === false) options.procstats = !(options.procstats === false) options.memstats = !(options.memstats === false) options.push = !(options.push === false) options.pushApi = options.pushApi || "https://push.ravenwall.com" options.pushSeconds = options.pushSeconds || 10 options.logHandle = options.logHandle || console.log options.logSeconds = options.logSeconds || 60 options.initial = options.initial || {} options.initial.ravenwall_agent = "nodejs_" + VERSION if (options.id) id = options.id function startPusher(id) { if (!options.apiToken) throw new Error("Push API Requires an API token.") var pusherSettings = { url: options.pushApi + "/" + id, headers: { "Ravenwall-API-Token": options.apiToken, }, timeout: (options.pushSeconds * 900) | 0 } stats.pusher(pusherSettings, options.pushSeconds) stats.push() } // Create series/api client if (!options.noUpsert) { var client = api(options.apiToken, options.apiUrl) .upsertSeries({id: options.id, tags: options.tags}, function (err, res, body) { if (err) { console.log("Unable to upsert series to Ravenwall!", err) return } if (res.statusCode != 201) { console.log("Unable to upsert series to Ravenwall: server replied %s", res.statusCode) return } var results = JSON.parse(body) if (!options.id && options.push && !options.push) { // This is a new series, so the pusher wasn't set up yet. Set it up now. id = results.id startPusher(results.id) } }) } var stats = statware(options.initial) if (options.sysstats) stats.registerHelper(statware.sysstats) if (options.procstats) stats.registerHelper(statware.procstats) if (options.memstats) stats.registerHelper(statware.memstats) // Don't immediately start a pusher if no id specified (instead it will start after upsert) if (options.push && options.id) { startPusher(options.id) } if (options.page) { stats.page(options.pagePort) } if (options.log) { stats.logger(options.logHandle, options.logSeconds) stats.log() } return stats }
javascript
function ravenwall(options) { if (options instanceof statware) return options options = options || {} // set defaults options.sysstats = !(options.sysstats === false) options.procstats = !(options.procstats === false) options.memstats = !(options.memstats === false) options.push = !(options.push === false) options.pushApi = options.pushApi || "https://push.ravenwall.com" options.pushSeconds = options.pushSeconds || 10 options.logHandle = options.logHandle || console.log options.logSeconds = options.logSeconds || 60 options.initial = options.initial || {} options.initial.ravenwall_agent = "nodejs_" + VERSION if (options.id) id = options.id function startPusher(id) { if (!options.apiToken) throw new Error("Push API Requires an API token.") var pusherSettings = { url: options.pushApi + "/" + id, headers: { "Ravenwall-API-Token": options.apiToken, }, timeout: (options.pushSeconds * 900) | 0 } stats.pusher(pusherSettings, options.pushSeconds) stats.push() } // Create series/api client if (!options.noUpsert) { var client = api(options.apiToken, options.apiUrl) .upsertSeries({id: options.id, tags: options.tags}, function (err, res, body) { if (err) { console.log("Unable to upsert series to Ravenwall!", err) return } if (res.statusCode != 201) { console.log("Unable to upsert series to Ravenwall: server replied %s", res.statusCode) return } var results = JSON.parse(body) if (!options.id && options.push && !options.push) { // This is a new series, so the pusher wasn't set up yet. Set it up now. id = results.id startPusher(results.id) } }) } var stats = statware(options.initial) if (options.sysstats) stats.registerHelper(statware.sysstats) if (options.procstats) stats.registerHelper(statware.procstats) if (options.memstats) stats.registerHelper(statware.memstats) // Don't immediately start a pusher if no id specified (instead it will start after upsert) if (options.push && options.id) { startPusher(options.id) } if (options.page) { stats.page(options.pagePort) } if (options.log) { stats.logger(options.logHandle, options.logSeconds) stats.log() } return stats }
[ "function", "ravenwall", "(", "options", ")", "{", "if", "(", "options", "instanceof", "statware", ")", "return", "options", "options", "=", "options", "||", "{", "}", "options", ".", "sysstats", "=", "!", "(", "options", ".", "sysstats", "===", "false", ")", "options", ".", "procstats", "=", "!", "(", "options", ".", "procstats", "===", "false", ")", "options", ".", "memstats", "=", "!", "(", "options", ".", "memstats", "===", "false", ")", "options", ".", "push", "=", "!", "(", "options", ".", "push", "===", "false", ")", "options", ".", "pushApi", "=", "options", ".", "pushApi", "||", "\"https://push.ravenwall.com\"", "options", ".", "pushSeconds", "=", "options", ".", "pushSeconds", "||", "10", "options", ".", "logHandle", "=", "options", ".", "logHandle", "||", "console", ".", "log", "options", ".", "logSeconds", "=", "options", ".", "logSeconds", "||", "60", "options", ".", "initial", "=", "options", ".", "initial", "||", "{", "}", "options", ".", "initial", ".", "ravenwall_agent", "=", "\"nodejs_\"", "+", "VERSION", "if", "(", "options", ".", "id", ")", "id", "=", "options", ".", "id", "function", "startPusher", "(", "id", ")", "{", "if", "(", "!", "options", ".", "apiToken", ")", "throw", "new", "Error", "(", "\"Push API Requires an API token.\"", ")", "var", "pusherSettings", "=", "{", "url", ":", "options", ".", "pushApi", "+", "\"/\"", "+", "id", ",", "headers", ":", "{", "\"Ravenwall-API-Token\"", ":", "options", ".", "apiToken", ",", "}", ",", "timeout", ":", "(", "options", ".", "pushSeconds", "*", "900", ")", "|", "0", "}", "stats", ".", "pusher", "(", "pusherSettings", ",", "options", ".", "pushSeconds", ")", "stats", ".", "push", "(", ")", "}", "if", "(", "!", "options", ".", "noUpsert", ")", "{", "var", "client", "=", "api", "(", "options", ".", "apiToken", ",", "options", ".", "apiUrl", ")", ".", "upsertSeries", "(", "{", "id", ":", "options", ".", "id", ",", "tags", ":", "options", ".", "tags", "}", ",", "function", "(", "err", ",", "res", ",", "body", ")", "{", "if", "(", "err", ")", "{", "console", ".", "log", "(", "\"Unable to upsert series to Ravenwall!\"", ",", "err", ")", "return", "}", "if", "(", "res", ".", "statusCode", "!=", "201", ")", "{", "console", ".", "log", "(", "\"Unable to upsert series to Ravenwall: server replied %s\"", ",", "res", ".", "statusCode", ")", "return", "}", "var", "results", "=", "JSON", ".", "parse", "(", "body", ")", "if", "(", "!", "options", ".", "id", "&&", "options", ".", "push", "&&", "!", "options", ".", "push", ")", "{", "id", "=", "results", ".", "id", "startPusher", "(", "results", ".", "id", ")", "}", "}", ")", "}", "var", "stats", "=", "statware", "(", "options", ".", "initial", ")", "if", "(", "options", ".", "sysstats", ")", "stats", ".", "registerHelper", "(", "statware", ".", "sysstats", ")", "if", "(", "options", ".", "procstats", ")", "stats", ".", "registerHelper", "(", "statware", ".", "procstats", ")", "if", "(", "options", ".", "memstats", ")", "stats", ".", "registerHelper", "(", "statware", ".", "memstats", ")", "if", "(", "options", ".", "push", "&&", "options", ".", "id", ")", "{", "startPusher", "(", "options", ".", "id", ")", "}", "if", "(", "options", ".", "page", ")", "{", "stats", ".", "page", "(", "options", ".", "pagePort", ")", "}", "if", "(", "options", ".", "log", ")", "{", "stats", ".", "logger", "(", "options", ".", "logHandle", ",", "options", ".", "logSeconds", ")", "stats", ".", "log", "(", ")", "}", "return", "stats", "}" ]
The Ravenwall Agent. @param {Object} options The options to create the agent with. options.apiToken {string} set your Ravenwall API key. Can also use the RAVENWALL_API_TOKEN environment variable. options.id {string} set a series id. This defines where your data will be stored. If not specified, a uuid will be generated. options.tags {Array} tags to add/apply to the series. Add-only. Must match: /[a-zA-Z0-9:_-]+/ options.initial {Object} [{}] a default stats object. Useful for initializing values that may be set later for data continuity. options.sysstats {Bool} [true] whether to apply a default set of system-related stats. options.procstats {Bool} [true] whether to apply a default set of process-related stats. options.memstats {Bool} [true] whether to apply a default set of memory-related stats. options.push {Bool} [true] whether to create as a stats-pushing agent that will send data to Ravenwall. options.pushApi {string} [https://push.ravenwall.com] The ravenwall push api endpoint. options.pushSeconds {Int} [10] the frequency it will automatically push data. Setting this too low can get you throttled. Suggested minimum is ~10 seconds. Set to <= 0 to disable recurring push. options.page {Bool} [false] whether to create a status page that will report the stats that can be scraped. options.pagePort {Int} [7667] port to run the status page on (if enabled) options.log {Bool} [false] whether to create a recurring stat logger options.logHandle {Function} [console.log] a handle to log to options.logSeconds {Int} [60] the frequency to log the stats to the log handle. @return {Statware}
[ "The", "Ravenwall", "Agent", "." ]
23e6491f0dec26f7879103e3be1c88abad17a58f
https://github.com/Ravenwall/node-ravenwall/blob/23e6491f0dec26f7879103e3be1c88abad17a58f/index.js#L46-L119
train
mgesmundo/port-manager
lib/port-manager.js
normalize
function normalize(from, to) { if (from && (isNaN(from) || from <= 0) || (to && (isNaN(to) || to <= 0))) { throw new Error('invalid port range: required > 0'); } if ((from && from > MAX) || (to && to > MAX)) { throw new Error(f('invalid port range: required < %d', MAX)); } if (to && to < from) { throw new Error('invalid port range: required max >= min'); } if (!from) { from = min; to = to || max; } else { to = to || from; } return { from: from, to: to }; }
javascript
function normalize(from, to) { if (from && (isNaN(from) || from <= 0) || (to && (isNaN(to) || to <= 0))) { throw new Error('invalid port range: required > 0'); } if ((from && from > MAX) || (to && to > MAX)) { throw new Error(f('invalid port range: required < %d', MAX)); } if (to && to < from) { throw new Error('invalid port range: required max >= min'); } if (!from) { from = min; to = to || max; } else { to = to || from; } return { from: from, to: to }; }
[ "function", "normalize", "(", "from", ",", "to", ")", "{", "if", "(", "from", "&&", "(", "isNaN", "(", "from", ")", "||", "from", "<=", "0", ")", "||", "(", "to", "&&", "(", "isNaN", "(", "to", ")", "||", "to", "<=", "0", ")", ")", ")", "{", "throw", "new", "Error", "(", "'invalid port range: required > 0'", ")", ";", "}", "if", "(", "(", "from", "&&", "from", ">", "MAX", ")", "||", "(", "to", "&&", "to", ">", "MAX", ")", ")", "{", "throw", "new", "Error", "(", "f", "(", "'invalid port range: required < %d'", ",", "MAX", ")", ")", ";", "}", "if", "(", "to", "&&", "to", "<", "from", ")", "{", "throw", "new", "Error", "(", "'invalid port range: required max >= min'", ")", ";", "}", "if", "(", "!", "from", ")", "{", "from", "=", "min", ";", "to", "=", "to", "||", "max", ";", "}", "else", "{", "to", "=", "to", "||", "from", ";", "}", "return", "{", "from", ":", "from", ",", "to", ":", "to", "}", ";", "}" ]
Normalize a TCP ports range @param {Number} [from] Start port (included) @param {Number} [to] End port (included) @return {{from: {Number}, to: {Number}}} @private @ignore
[ "Normalize", "a", "TCP", "ports", "range" ]
a09356b9063c228616d0ffc56217b93c479f2604
https://github.com/mgesmundo/port-manager/blob/a09356b9063c228616d0ffc56217b93c479f2604/lib/port-manager.js#L24-L44
train
relief-melone/limitpromises
src/services/service.cleanObject.js
cleanObject
function cleanObject(Object){ delete Object.resolve; delete Object.reject; delete Object.resolveResult; delete Object.rejectResult; delete Object.launchPromise; delete Object.promiseFunc; }
javascript
function cleanObject(Object){ delete Object.resolve; delete Object.reject; delete Object.resolveResult; delete Object.rejectResult; delete Object.launchPromise; delete Object.promiseFunc; }
[ "function", "cleanObject", "(", "Object", ")", "{", "delete", "Object", ".", "resolve", ";", "delete", "Object", ".", "reject", ";", "delete", "Object", ".", "resolveResult", ";", "delete", "Object", ".", "rejectResult", ";", "delete", "Object", ".", "launchPromise", ";", "delete", "Object", ".", "promiseFunc", ";", "}" ]
Will be called if a resultPromise is either rejected or resolved to clean the Object of Attributes you don't want to send back to the user @param {Object} Object The Object you want to clean
[ "Will", "be", "called", "if", "a", "resultPromise", "is", "either", "rejected", "or", "resolved", "to", "clean", "the", "Object", "of", "Attributes", "you", "don", "t", "want", "to", "send", "back", "to", "the", "user" ]
1735b92749740204b597c1c6026257d54ade8200
https://github.com/relief-melone/limitpromises/blob/1735b92749740204b597c1c6026257d54ade8200/src/services/service.cleanObject.js#L8-L15
train
update/updater-example
updatefile.js
updateExample
function updateExample(app, str) { var cwd = app.options.dest || app.cwd; return app.src('example.txt', {cwd: cwd}) .pipe(append(str)) .pipe(app.dest(cwd)); }
javascript
function updateExample(app, str) { var cwd = app.options.dest || app.cwd; return app.src('example.txt', {cwd: cwd}) .pipe(append(str)) .pipe(app.dest(cwd)); }
[ "function", "updateExample", "(", "app", ",", "str", ")", "{", "var", "cwd", "=", "app", ".", "options", ".", "dest", "||", "app", ".", "cwd", ";", "return", "app", ".", "src", "(", "'example.txt'", ",", "{", "cwd", ":", "cwd", "}", ")", ".", "pipe", "(", "append", "(", "str", ")", ")", ".", "pipe", "(", "app", ".", "dest", "(", "cwd", ")", ")", ";", "}" ]
Append the given string to `example.txt` and re-write the file to the current working directory. The `.src` and `.dest` methods work exactly like gulp's (we use the same libs from the gulp team under the hood) @param {Object} `app` Instance of update, to get the cwd. Pass `--dest` on the command line to set `app.options.dest` @return {Stream} vinyl stream @api public
[ "Append", "the", "given", "string", "to", "example", ".", "txt", "and", "re", "-", "write", "the", "file", "to", "the", "current", "working", "directory", "." ]
5e89b9acc78f7789d344d4c2c7d2b94dd348734b
https://github.com/update/updater-example/blob/5e89b9acc78f7789d344d4c2c7d2b94dd348734b/updatefile.js#L58-L63
train
update/updater-example
updatefile.js
erase
function erase(num) { var n = typeof num === 'number' ? num : 1; return through.obj(function(file, enc, next) { var lines = file.contents.toString().trim().split('\n'); file.contents = new Buffer(lines.slice(0, -n).join('\n') + '\n'); next(null, file); }); }
javascript
function erase(num) { var n = typeof num === 'number' ? num : 1; return through.obj(function(file, enc, next) { var lines = file.contents.toString().trim().split('\n'); file.contents = new Buffer(lines.slice(0, -n).join('\n') + '\n'); next(null, file); }); }
[ "function", "erase", "(", "num", ")", "{", "var", "n", "=", "typeof", "num", "===", "'number'", "?", "num", ":", "1", ";", "return", "through", ".", "obj", "(", "function", "(", "file", ",", "enc", ",", "next", ")", "{", "var", "lines", "=", "file", ".", "contents", ".", "toString", "(", ")", ".", "trim", "(", ")", ".", "split", "(", "'\\n'", ")", ";", "\\n", "file", ".", "contents", "=", "new", "Buffer", "(", "lines", ".", "slice", "(", "0", ",", "-", "n", ")", ".", "join", "(", "'\\n'", ")", "+", "\\n", ")", ";", "}", ")", ";", "}" ]
Erase the given number of lines from the end of a string @param {String} `str` @return {Stream} vinyl stream @api public
[ "Erase", "the", "given", "number", "of", "lines", "from", "the", "end", "of", "a", "string" ]
5e89b9acc78f7789d344d4c2c7d2b94dd348734b
https://github.com/update/updater-example/blob/5e89b9acc78f7789d344d4c2c7d2b94dd348734b/updatefile.js#L88-L95
train
yoshuawuyts/virtual-raf
index.js
update
function update (state) { assert.ifError(inRenderingTransaction, 'infinite loop detected') // request a redraw for next frame if (currentState === null && !redrawScheduled) { redrawScheduled = true raf(function redraw () { redrawScheduled = false if (!currentState) return inRenderingTransaction = true var newTree = view(currentState) const patches = vdom.diff(tree, newTree) inRenderingTransaction = false target = vdom.patch(target, patches) tree = newTree currentState = null }) } // update data for redraw currentState = state }
javascript
function update (state) { assert.ifError(inRenderingTransaction, 'infinite loop detected') // request a redraw for next frame if (currentState === null && !redrawScheduled) { redrawScheduled = true raf(function redraw () { redrawScheduled = false if (!currentState) return inRenderingTransaction = true var newTree = view(currentState) const patches = vdom.diff(tree, newTree) inRenderingTransaction = false target = vdom.patch(target, patches) tree = newTree currentState = null }) } // update data for redraw currentState = state }
[ "function", "update", "(", "state", ")", "{", "assert", ".", "ifError", "(", "inRenderingTransaction", ",", "'infinite loop detected'", ")", "if", "(", "currentState", "===", "null", "&&", "!", "redrawScheduled", ")", "{", "redrawScheduled", "=", "true", "raf", "(", "function", "redraw", "(", ")", "{", "redrawScheduled", "=", "false", "if", "(", "!", "currentState", ")", "return", "inRenderingTransaction", "=", "true", "var", "newTree", "=", "view", "(", "currentState", ")", "const", "patches", "=", "vdom", ".", "diff", "(", "tree", ",", "newTree", ")", "inRenderingTransaction", "=", "false", "target", "=", "vdom", ".", "patch", "(", "target", ",", "patches", ")", "tree", "=", "newTree", "currentState", "=", "null", "}", ")", "}", "currentState", "=", "state", "}" ]
update the state and render function obj -> null
[ "update", "the", "state", "and", "render", "function", "obj", "-", ">", "null" ]
d2a8fcd49a6e55ca135d4a9c002bf6d7ffe0f76b
https://github.com/yoshuawuyts/virtual-raf/blob/d2a8fcd49a6e55ca135d4a9c002bf6d7ffe0f76b/index.js#L33-L57
train
commenthol/streamss
lib/split.js
Split
function Split (options) { if (!(this instanceof Split)) { return new Split(options) } if (options instanceof RegExp || typeof options === 'string') { options = { matcher: options } } this.options = Object.assign({ matcher: /(\r?\n)/, // emits also newlines encoding: 'utf8' }, options) this.buffer = '' Transform.call(this, _omit(this.options, ['matcher'])) return this }
javascript
function Split (options) { if (!(this instanceof Split)) { return new Split(options) } if (options instanceof RegExp || typeof options === 'string') { options = { matcher: options } } this.options = Object.assign({ matcher: /(\r?\n)/, // emits also newlines encoding: 'utf8' }, options) this.buffer = '' Transform.call(this, _omit(this.options, ['matcher'])) return this }
[ "function", "Split", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Split", ")", ")", "{", "return", "new", "Split", "(", "options", ")", "}", "if", "(", "options", "instanceof", "RegExp", "||", "typeof", "options", "===", "'string'", ")", "{", "options", "=", "{", "matcher", ":", "options", "}", "}", "this", ".", "options", "=", "Object", ".", "assign", "(", "{", "matcher", ":", "/", "(\\r?\\n)", "/", ",", "encoding", ":", "'utf8'", "}", ",", "options", ")", "this", ".", "buffer", "=", "''", "Transform", ".", "call", "(", "this", ",", "_omit", "(", "this", ".", "options", ",", "[", "'matcher'", "]", ")", ")", "return", "this", "}" ]
Split a stream using a regexp or string based matcher @constructor @param {Object} [options] - Stream Options `{encoding, highWaterMark, decodeStrings, ...}` @param {RegExp|String} options.matcher - RegExp or String use for splitting up the stream. Default=/(\r?\n)/ @return {Transform} A transform stream
[ "Split", "a", "stream", "using", "a", "regexp", "or", "string", "based", "matcher" ]
cfef5d0ed30c7efe002018886e2e843c91d3558f
https://github.com/commenthol/streamss/blob/cfef5d0ed30c7efe002018886e2e843c91d3558f/lib/split.js#L20-L37
train
AndreasMadsen/piccolo
lib/modules/url.js
copyObject
function copyObject(obj) { var ret = {}, name; for (name in obj) { if (obj.hasOwnProperty(name)) { ret[name] = obj[name]; } } return ret; }
javascript
function copyObject(obj) { var ret = {}, name; for (name in obj) { if (obj.hasOwnProperty(name)) { ret[name] = obj[name]; } } return ret; }
[ "function", "copyObject", "(", "obj", ")", "{", "var", "ret", "=", "{", "}", ",", "name", ";", "for", "(", "name", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "name", ")", ")", "{", "ret", "[", "name", "]", "=", "obj", "[", "name", "]", ";", "}", "}", "return", "ret", ";", "}" ]
copy an object without depth
[ "copy", "an", "object", "without", "depth" ]
ef43f5634c564eef0d21a4a6aa103b2f1e3baa3d
https://github.com/AndreasMadsen/piccolo/blob/ef43f5634c564eef0d21a4a6aa103b2f1e3baa3d/lib/modules/url.js#L7-L15
train
AndreasMadsen/piccolo
lib/modules/url.js
setHost
function setHost(uri) { if (uri.auth || uri.hostname || uri.port) { uri.host = ''; if (uri.auth) uri.host += uri.auth + '@'; if (uri.hostname) uri.host += uri.hostname; if (uri.port) uri.host += ':' + uri.port; } }
javascript
function setHost(uri) { if (uri.auth || uri.hostname || uri.port) { uri.host = ''; if (uri.auth) uri.host += uri.auth + '@'; if (uri.hostname) uri.host += uri.hostname; if (uri.port) uri.host += ':' + uri.port; } }
[ "function", "setHost", "(", "uri", ")", "{", "if", "(", "uri", ".", "auth", "||", "uri", ".", "hostname", "||", "uri", ".", "port", ")", "{", "uri", ".", "host", "=", "''", ";", "if", "(", "uri", ".", "auth", ")", "uri", ".", "host", "+=", "uri", ".", "auth", "+", "'@'", ";", "if", "(", "uri", ".", "hostname", ")", "uri", ".", "host", "+=", "uri", ".", "hostname", ";", "if", "(", "uri", ".", "port", ")", "uri", ".", "host", "+=", "':'", "+", "uri", ".", "port", ";", "}", "}" ]
construct host property
[ "construct", "host", "property" ]
ef43f5634c564eef0d21a4a6aa103b2f1e3baa3d
https://github.com/AndreasMadsen/piccolo/blob/ef43f5634c564eef0d21a4a6aa103b2f1e3baa3d/lib/modules/url.js#L18-L25
train
AndreasMadsen/piccolo
lib/modules/url.js
setHref
function setHref(uri) { uri.href = ''; if (uri.protocol) uri.href += uri.protocol + '//'; if (uri.host) uri.href += uri.host; if (uri.path) uri.href += uri.path; if (uri.hash) uri.href += uri.hash; }
javascript
function setHref(uri) { uri.href = ''; if (uri.protocol) uri.href += uri.protocol + '//'; if (uri.host) uri.href += uri.host; if (uri.path) uri.href += uri.path; if (uri.hash) uri.href += uri.hash; }
[ "function", "setHref", "(", "uri", ")", "{", "uri", ".", "href", "=", "''", ";", "if", "(", "uri", ".", "protocol", ")", "uri", ".", "href", "+=", "uri", ".", "protocol", "+", "'//'", ";", "if", "(", "uri", ".", "host", ")", "uri", ".", "href", "+=", "uri", ".", "host", ";", "if", "(", "uri", ".", "path", ")", "uri", ".", "href", "+=", "uri", ".", "path", ";", "if", "(", "uri", ".", "hash", ")", "uri", ".", "href", "+=", "uri", ".", "hash", ";", "}" ]
construct href property
[ "construct", "href", "property" ]
ef43f5634c564eef0d21a4a6aa103b2f1e3baa3d
https://github.com/AndreasMadsen/piccolo/blob/ef43f5634c564eef0d21a4a6aa103b2f1e3baa3d/lib/modules/url.js#L28-L34
train
AndreasMadsen/piccolo
lib/modules/url.js
setPath
function setPath(uri) { if (uri.path || (uri.pathname === undefined && uri.search === undefined)) return; uri.path = ''; if (uri.pathname) uri.path += uri.pathname; if (uri.search) uri.path += uri.search; }
javascript
function setPath(uri) { if (uri.path || (uri.pathname === undefined && uri.search === undefined)) return; uri.path = ''; if (uri.pathname) uri.path += uri.pathname; if (uri.search) uri.path += uri.search; }
[ "function", "setPath", "(", "uri", ")", "{", "if", "(", "uri", ".", "path", "||", "(", "uri", ".", "pathname", "===", "undefined", "&&", "uri", ".", "search", "===", "undefined", ")", ")", "return", ";", "uri", ".", "path", "=", "''", ";", "if", "(", "uri", ".", "pathname", ")", "uri", ".", "path", "+=", "uri", ".", "pathname", ";", "if", "(", "uri", ".", "search", ")", "uri", ".", "path", "+=", "uri", ".", "search", ";", "}" ]
construct path property
[ "construct", "path", "property" ]
ef43f5634c564eef0d21a4a6aa103b2f1e3baa3d
https://github.com/AndreasMadsen/piccolo/blob/ef43f5634c564eef0d21a4a6aa103b2f1e3baa3d/lib/modules/url.js#L37-L43
train
AndreasMadsen/piccolo
lib/modules/url.js
setSearch
function setSearch(uri) { if (typeof uri.search === 'string' || uri.query === undefined) return; if (typeof uri.query === 'string') { uri.search = '?' + uri.query; return; } var name, filled = false; uri.search = '?'; for (name in uri.query) { filled = true; uri.search += name + '=' + uri.query[name] + '&'; } uri.search = uri.search.substr(0, uri.search.length - 1); }
javascript
function setSearch(uri) { if (typeof uri.search === 'string' || uri.query === undefined) return; if (typeof uri.query === 'string') { uri.search = '?' + uri.query; return; } var name, filled = false; uri.search = '?'; for (name in uri.query) { filled = true; uri.search += name + '=' + uri.query[name] + '&'; } uri.search = uri.search.substr(0, uri.search.length - 1); }
[ "function", "setSearch", "(", "uri", ")", "{", "if", "(", "typeof", "uri", ".", "search", "===", "'string'", "||", "uri", ".", "query", "===", "undefined", ")", "return", ";", "if", "(", "typeof", "uri", ".", "query", "===", "'string'", ")", "{", "uri", ".", "search", "=", "'?'", "+", "uri", ".", "query", ";", "return", ";", "}", "var", "name", ",", "filled", "=", "false", ";", "uri", ".", "search", "=", "'?'", ";", "for", "(", "name", "in", "uri", ".", "query", ")", "{", "filled", "=", "true", ";", "uri", ".", "search", "+=", "name", "+", "'='", "+", "uri", ".", "query", "[", "name", "]", "+", "'&'", ";", "}", "uri", ".", "search", "=", "uri", ".", "search", ".", "substr", "(", "0", ",", "uri", ".", "search", ".", "length", "-", "1", ")", ";", "}" ]
construct search property
[ "construct", "search", "property" ]
ef43f5634c564eef0d21a4a6aa103b2f1e3baa3d
https://github.com/AndreasMadsen/piccolo/blob/ef43f5634c564eef0d21a4a6aa103b2f1e3baa3d/lib/modules/url.js#L46-L63
train
AndreasMadsen/piccolo
lib/modules/url.js
parseFilepath
function parseFilepath(path) { if (path === undefined) { return {filename: null, list: []}; } var list = path.split('/'), isDir = (path[path.length - 1] === '/') || (list[list.length - 1].indexOf('.') === -1); return { filename: isDir ? null : list.pop(), list: list }; }
javascript
function parseFilepath(path) { if (path === undefined) { return {filename: null, list: []}; } var list = path.split('/'), isDir = (path[path.length - 1] === '/') || (list[list.length - 1].indexOf('.') === -1); return { filename: isDir ? null : list.pop(), list: list }; }
[ "function", "parseFilepath", "(", "path", ")", "{", "if", "(", "path", "===", "undefined", ")", "{", "return", "{", "filename", ":", "null", ",", "list", ":", "[", "]", "}", ";", "}", "var", "list", "=", "path", ".", "split", "(", "'/'", ")", ",", "isDir", "=", "(", "path", "[", "path", ".", "length", "-", "1", "]", "===", "'/'", ")", "||", "(", "list", "[", "list", ".", "length", "-", "1", "]", ".", "indexOf", "(", "'.'", ")", "===", "-", "1", ")", ";", "return", "{", "filename", ":", "isDir", "?", "null", ":", "list", ".", "pop", "(", ")", ",", "list", ":", "list", "}", ";", "}" ]
split filepath from filename
[ "split", "filepath", "from", "filename" ]
ef43f5634c564eef0d21a4a6aa103b2f1e3baa3d
https://github.com/AndreasMadsen/piccolo/blob/ef43f5634c564eef0d21a4a6aa103b2f1e3baa3d/lib/modules/url.js#L66-L78
train
melvincarvalho/rdf-shell
lib/rm.js
bin
function bin(argv) { rm(argv, function(err, res, uri) { console.log('rm of : ' + uri); }); }
javascript
function bin(argv) { rm(argv, function(err, res, uri) { console.log('rm of : ' + uri); }); }
[ "function", "bin", "(", "argv", ")", "{", "rm", "(", "argv", ",", "function", "(", "err", ",", "res", ",", "uri", ")", "{", "console", ".", "log", "(", "'rm of : '", "+", "uri", ")", ";", "}", ")", ";", "}" ]
rm as a command @param {String} argv[2] login @callback {bin~cb} callback
[ "rm", "as", "a", "command" ]
bf2015f6f333855e69a18ce3ec9e917bbddfb425
https://github.com/melvincarvalho/rdf-shell/blob/bf2015f6f333855e69a18ce3ec9e917bbddfb425/lib/rm.js#L29-L33
train
iwillwen/co-e
index.js
buildError
function buildError(err, hackErr) { var stack1 = err.stack; var stack2 = hackErr.stack; var label = hackErr.label; var stack = []; stack1.split('\n').forEach(function(line, index, arr) { if (line.match(/^ at GeneratorFunctionPrototype.next/)) { stack = stack.concat(arr.slice(0, index)); return; } }); stack = stack.concat(stack2.split('\n').slice(2)); if (!stack[0].match(/^Error:/)) { stack.unshift(err.message); } if (!!label) { stack.unshift('[DEBUG: ' + label + ']'); } stack = stack.join('\n'); var newError = new Error(); newError.message = err.message; newError.stack = stack; return newError; }
javascript
function buildError(err, hackErr) { var stack1 = err.stack; var stack2 = hackErr.stack; var label = hackErr.label; var stack = []; stack1.split('\n').forEach(function(line, index, arr) { if (line.match(/^ at GeneratorFunctionPrototype.next/)) { stack = stack.concat(arr.slice(0, index)); return; } }); stack = stack.concat(stack2.split('\n').slice(2)); if (!stack[0].match(/^Error:/)) { stack.unshift(err.message); } if (!!label) { stack.unshift('[DEBUG: ' + label + ']'); } stack = stack.join('\n'); var newError = new Error(); newError.message = err.message; newError.stack = stack; return newError; }
[ "function", "buildError", "(", "err", ",", "hackErr", ")", "{", "var", "stack1", "=", "err", ".", "stack", ";", "var", "stack2", "=", "hackErr", ".", "stack", ";", "var", "label", "=", "hackErr", ".", "label", ";", "var", "stack", "=", "[", "]", ";", "stack1", ".", "split", "(", "'\\n'", ")", ".", "\\n", "forEach", ";", "(", "function", "(", "line", ",", "index", ",", "arr", ")", "{", "if", "(", "line", ".", "match", "(", "/", "^ at GeneratorFunctionPrototype.next", "/", ")", ")", "{", "stack", "=", "stack", ".", "concat", "(", "arr", ".", "slice", "(", "0", ",", "index", ")", ")", ";", "return", ";", "}", "}", ")", "stack", "=", "stack", ".", "concat", "(", "stack2", ".", "split", "(", "'\\n'", ")", ".", "\\n", "slice", ")", ";", "(", "2", ")", "if", "(", "!", "stack", "[", "0", "]", ".", "match", "(", "/", "^Error:", "/", ")", ")", "{", "stack", ".", "unshift", "(", "err", ".", "message", ")", ";", "}", "if", "(", "!", "!", "label", ")", "{", "stack", ".", "unshift", "(", "'[DEBUG: '", "+", "label", "+", "']'", ")", ";", "}", "stack", "=", "stack", ".", "join", "(", "'\\n'", ")", ";", "\\n", "var", "newError", "=", "new", "Error", "(", ")", ";", "}" ]
Build the full error stack
[ "Build", "the", "full", "error", "stack" ]
f8ac569e63028111c1942b6caadb651fc0e2e2a8
https://github.com/iwillwen/co-e/blob/f8ac569e63028111c1942b6caadb651fc0e2e2a8/index.js#L78-L106
train
deepjs/deep-promise
index.js
function(argument) { //console.log("deep.Deferred.resolve : ", argument); if (this.rejected || this.resolved) throw new Error("deferred has already been ended !"); if (argument instanceof Error) return this.reject(argument); this._success = argument; this.resolved = true; var self = this; this._promises.forEach(function(promise) { promise.resolve(argument); }); }
javascript
function(argument) { //console.log("deep.Deferred.resolve : ", argument); if (this.rejected || this.resolved) throw new Error("deferred has already been ended !"); if (argument instanceof Error) return this.reject(argument); this._success = argument; this.resolved = true; var self = this; this._promises.forEach(function(promise) { promise.resolve(argument); }); }
[ "function", "(", "argument", ")", "{", "if", "(", "this", ".", "rejected", "||", "this", ".", "resolved", ")", "throw", "new", "Error", "(", "\"deferred has already been ended !\"", ")", ";", "if", "(", "argument", "instanceof", "Error", ")", "return", "this", ".", "reject", "(", "argument", ")", ";", "this", ".", "_success", "=", "argument", ";", "this", ".", "resolved", "=", "true", ";", "var", "self", "=", "this", ";", "this", ".", "_promises", ".", "forEach", "(", "function", "(", "promise", ")", "{", "promise", ".", "resolve", "(", "argument", ")", ";", "}", ")", ";", "}" ]
resolve the Deferred and so the associated promise @method resolve @param {Object} argument the resolved object injected in promise @return {deep.Deferred} this
[ "resolve", "the", "Deferred", "and", "so", "the", "associated", "promise" ]
022fb9d99def95d0017d965efb88cc4c4393bd30
https://github.com/deepjs/deep-promise/blob/022fb9d99def95d0017d965efb88cc4c4393bd30/index.js#L263-L275
train
deepjs/deep-promise
index.js
function(argument) { // console.log("DeepDeferred.reject"); if (this.rejected || this.resolved) throw new Error("deferred has already been ended !"); this._error = argument; this.rejected = true; var self = this; this._promises.forEach(function(promise) { promise.reject(argument); }); }
javascript
function(argument) { // console.log("DeepDeferred.reject"); if (this.rejected || this.resolved) throw new Error("deferred has already been ended !"); this._error = argument; this.rejected = true; var self = this; this._promises.forEach(function(promise) { promise.reject(argument); }); }
[ "function", "(", "argument", ")", "{", "if", "(", "this", ".", "rejected", "||", "this", ".", "resolved", ")", "throw", "new", "Error", "(", "\"deferred has already been ended !\"", ")", ";", "this", ".", "_error", "=", "argument", ";", "this", ".", "rejected", "=", "true", ";", "var", "self", "=", "this", ";", "this", ".", "_promises", ".", "forEach", "(", "function", "(", "promise", ")", "{", "promise", ".", "reject", "(", "argument", ")", ";", "}", ")", ";", "}" ]
reject the Deferred and so the associated promise @method reject @param {Object} argument the rejected object injected in promise @return {deep.Deferred} this
[ "reject", "the", "Deferred", "and", "so", "the", "associated", "promise" ]
022fb9d99def95d0017d965efb88cc4c4393bd30
https://github.com/deepjs/deep-promise/blob/022fb9d99def95d0017d965efb88cc4c4393bd30/index.js#L282-L292
train
deepjs/deep-promise
index.js
function() { var prom = new promise.Promise(); //console.log("deep2.Deffered.promise : ", prom, " r,r,c : ", this.rejected, this.resolved, this.canceled) if (this.resolved) return prom.resolve(this._success); if (this.rejected) return prom.reject(this._error); this._promises.push(prom); return prom; }
javascript
function() { var prom = new promise.Promise(); //console.log("deep2.Deffered.promise : ", prom, " r,r,c : ", this.rejected, this.resolved, this.canceled) if (this.resolved) return prom.resolve(this._success); if (this.rejected) return prom.reject(this._error); this._promises.push(prom); return prom; }
[ "function", "(", ")", "{", "var", "prom", "=", "new", "promise", ".", "Promise", "(", ")", ";", "if", "(", "this", ".", "resolved", ")", "return", "prom", ".", "resolve", "(", "this", ".", "_success", ")", ";", "if", "(", "this", ".", "rejected", ")", "return", "prom", ".", "reject", "(", "this", ".", "_error", ")", ";", "this", ".", "_promises", ".", "push", "(", "prom", ")", ";", "return", "prom", ";", "}" ]
return a promise for this deferred @method promise @return {deep.Promise}
[ "return", "a", "promise", "for", "this", "deferred" ]
022fb9d99def95d0017d965efb88cc4c4393bd30
https://github.com/deepjs/deep-promise/blob/022fb9d99def95d0017d965efb88cc4c4393bd30/index.js#L298-L307
train
AlphaReplica/Connecta
lib/client/source/connecta.js
init
function init() { scope._servConn = new ConnectaSocket(scope._url,scope._reconnect,scope._encode); scope._servConn.onConnected = function(e) { scope.id = e; scope.dispatchEvent("connected"); } scope._servConn.onError = function(e) { scope.dispatchEvent("error",e); } scope._servConn.onClose = function(e) { scope.dispatchEvent("close"); scope.closePeers(); } scope._servConn.onJoinedRoom = onJoinedRoom; scope._servConn.onClientJoinedRoom = onClientJoinedRoom; scope._servConn.onLeftRoom = onLeftRoom; scope._servConn.onClientLeftRoom = onClientLeftRoom; scope._servConn.onSDPDescription = onSDPDescription; scope._servConn.onIceCandidate = onIceCandidate; scope._servConn.onRTCFallback = onRTCFallback; scope._servConn.onMessage = onServerMessage; scope._servConn.onBytesMessage = onServerByteArray; window.addEventListener("beforeunload", function (event) { scope.dispose(); }); }
javascript
function init() { scope._servConn = new ConnectaSocket(scope._url,scope._reconnect,scope._encode); scope._servConn.onConnected = function(e) { scope.id = e; scope.dispatchEvent("connected"); } scope._servConn.onError = function(e) { scope.dispatchEvent("error",e); } scope._servConn.onClose = function(e) { scope.dispatchEvent("close"); scope.closePeers(); } scope._servConn.onJoinedRoom = onJoinedRoom; scope._servConn.onClientJoinedRoom = onClientJoinedRoom; scope._servConn.onLeftRoom = onLeftRoom; scope._servConn.onClientLeftRoom = onClientLeftRoom; scope._servConn.onSDPDescription = onSDPDescription; scope._servConn.onIceCandidate = onIceCandidate; scope._servConn.onRTCFallback = onRTCFallback; scope._servConn.onMessage = onServerMessage; scope._servConn.onBytesMessage = onServerByteArray; window.addEventListener("beforeunload", function (event) { scope.dispose(); }); }
[ "function", "init", "(", ")", "{", "scope", ".", "_servConn", "=", "new", "ConnectaSocket", "(", "scope", ".", "_url", ",", "scope", ".", "_reconnect", ",", "scope", ".", "_encode", ")", ";", "scope", ".", "_servConn", ".", "onConnected", "=", "function", "(", "e", ")", "{", "scope", ".", "id", "=", "e", ";", "scope", ".", "dispatchEvent", "(", "\"connected\"", ")", ";", "}", "scope", ".", "_servConn", ".", "onError", "=", "function", "(", "e", ")", "{", "scope", ".", "dispatchEvent", "(", "\"error\"", ",", "e", ")", ";", "}", "scope", ".", "_servConn", ".", "onClose", "=", "function", "(", "e", ")", "{", "scope", ".", "dispatchEvent", "(", "\"close\"", ")", ";", "scope", ".", "closePeers", "(", ")", ";", "}", "scope", ".", "_servConn", ".", "onJoinedRoom", "=", "onJoinedRoom", ";", "scope", ".", "_servConn", ".", "onClientJoinedRoom", "=", "onClientJoinedRoom", ";", "scope", ".", "_servConn", ".", "onLeftRoom", "=", "onLeftRoom", ";", "scope", ".", "_servConn", ".", "onClientLeftRoom", "=", "onClientLeftRoom", ";", "scope", ".", "_servConn", ".", "onSDPDescription", "=", "onSDPDescription", ";", "scope", ".", "_servConn", ".", "onIceCandidate", "=", "onIceCandidate", ";", "scope", ".", "_servConn", ".", "onRTCFallback", "=", "onRTCFallback", ";", "scope", ".", "_servConn", ".", "onMessage", "=", "onServerMessage", ";", "scope", ".", "_servConn", ".", "onBytesMessage", "=", "onServerByteArray", ";", "window", ".", "addEventListener", "(", "\"beforeunload\"", ",", "function", "(", "event", ")", "{", "scope", ".", "dispose", "(", ")", ";", "}", ")", ";", "}" ]
init acts as constructor
[ "init", "acts", "as", "constructor" ]
bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0
https://github.com/AlphaReplica/Connecta/blob/bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0/lib/client/source/connecta.js#L28-L60
train
AlphaReplica/Connecta
lib/client/source/connecta.js
createPeerInstance
function createPeerInstance(id) { var peer = new ConnectaPeer(id,stunUrls); peer.onIceCandidate = gotIceCandidate; peer.onDescription = createdDescription; peer.onRemoteStream = gotRemoteStream; peer.onConnected = onPeerConnected; peer.onMessage = onPeerMessage; peer.onBytesMessage = onBytesMessage; peer.onConnectionFail = onPeerFailed; peer.onClosed = onPeerClose; peer.onError = onPeerError; peer.onChannelState = onPeerState; scope.peers[id] = peer; peer.init(); return peer; }
javascript
function createPeerInstance(id) { var peer = new ConnectaPeer(id,stunUrls); peer.onIceCandidate = gotIceCandidate; peer.onDescription = createdDescription; peer.onRemoteStream = gotRemoteStream; peer.onConnected = onPeerConnected; peer.onMessage = onPeerMessage; peer.onBytesMessage = onBytesMessage; peer.onConnectionFail = onPeerFailed; peer.onClosed = onPeerClose; peer.onError = onPeerError; peer.onChannelState = onPeerState; scope.peers[id] = peer; peer.init(); return peer; }
[ "function", "createPeerInstance", "(", "id", ")", "{", "var", "peer", "=", "new", "ConnectaPeer", "(", "id", ",", "stunUrls", ")", ";", "peer", ".", "onIceCandidate", "=", "gotIceCandidate", ";", "peer", ".", "onDescription", "=", "createdDescription", ";", "peer", ".", "onRemoteStream", "=", "gotRemoteStream", ";", "peer", ".", "onConnected", "=", "onPeerConnected", ";", "peer", ".", "onMessage", "=", "onPeerMessage", ";", "peer", ".", "onBytesMessage", "=", "onBytesMessage", ";", "peer", ".", "onConnectionFail", "=", "onPeerFailed", ";", "peer", ".", "onClosed", "=", "onPeerClose", ";", "peer", ".", "onError", "=", "onPeerError", ";", "peer", ".", "onChannelState", "=", "onPeerState", ";", "scope", ".", "peers", "[", "id", "]", "=", "peer", ";", "peer", ".", "init", "(", ")", ";", "return", "peer", ";", "}" ]
creates ConnectaPeer Instance and returns
[ "creates", "ConnectaPeer", "Instance", "and", "returns" ]
bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0
https://github.com/AlphaReplica/Connecta/blob/bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0/lib/client/source/connecta.js#L63-L81
train
AlphaReplica/Connecta
lib/client/source/connecta.js
getPeerByRTCId
function getPeerByRTCId(id) { for(var num = 0; num < scope._servConn.roomUsers.length; num++) { if(scope._servConn.roomUsers[num].rtcId == id) { return scope._servConn.roomUsers[num]; } } return null; }
javascript
function getPeerByRTCId(id) { for(var num = 0; num < scope._servConn.roomUsers.length; num++) { if(scope._servConn.roomUsers[num].rtcId == id) { return scope._servConn.roomUsers[num]; } } return null; }
[ "function", "getPeerByRTCId", "(", "id", ")", "{", "for", "(", "var", "num", "=", "0", ";", "num", "<", "scope", ".", "_servConn", ".", "roomUsers", ".", "length", ";", "num", "++", ")", "{", "if", "(", "scope", ".", "_servConn", ".", "roomUsers", "[", "num", "]", ".", "rtcId", "==", "id", ")", "{", "return", "scope", ".", "_servConn", ".", "roomUsers", "[", "num", "]", ";", "}", "}", "return", "null", ";", "}" ]
gets ConnectaPeer instance by rtcId
[ "gets", "ConnectaPeer", "instance", "by", "rtcId" ]
bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0
https://github.com/AlphaReplica/Connecta/blob/bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0/lib/client/source/connecta.js#L94-L104
train
AlphaReplica/Connecta
lib/client/source/connecta.js
getOrCreatePeer
function getOrCreatePeer(id) { if(scope.peers[id]) { return scope.peers[id]; } return createPeerInstance(id); }
javascript
function getOrCreatePeer(id) { if(scope.peers[id]) { return scope.peers[id]; } return createPeerInstance(id); }
[ "function", "getOrCreatePeer", "(", "id", ")", "{", "if", "(", "scope", ".", "peers", "[", "id", "]", ")", "{", "return", "scope", ".", "peers", "[", "id", "]", ";", "}", "return", "createPeerInstance", "(", "id", ")", ";", "}" ]
gets ConnectaPeer instance by id, if not exists, creates new and returns
[ "gets", "ConnectaPeer", "instance", "by", "id", "if", "not", "exists", "creates", "new", "and", "returns" ]
bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0
https://github.com/AlphaReplica/Connecta/blob/bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0/lib/client/source/connecta.js#L107-L114
train
AlphaReplica/Connecta
lib/client/source/connecta.js
onClientJoinedRoom
function onClientJoinedRoom(id) { if(scope._servConn.useRTC) { if(scope.hasWebRTCSupport()) { var peer = getOrCreatePeer(id); peer.createOffer(); } else { scope._servConn.sendRTCState(false,id); } } scope.dispatchEvent("clientJoinedRoom",id); }
javascript
function onClientJoinedRoom(id) { if(scope._servConn.useRTC) { if(scope.hasWebRTCSupport()) { var peer = getOrCreatePeer(id); peer.createOffer(); } else { scope._servConn.sendRTCState(false,id); } } scope.dispatchEvent("clientJoinedRoom",id); }
[ "function", "onClientJoinedRoom", "(", "id", ")", "{", "if", "(", "scope", ".", "_servConn", ".", "useRTC", ")", "{", "if", "(", "scope", ".", "hasWebRTCSupport", "(", ")", ")", "{", "var", "peer", "=", "getOrCreatePeer", "(", "id", ")", ";", "peer", ".", "createOffer", "(", ")", ";", "}", "else", "{", "scope", ".", "_servConn", ".", "sendRTCState", "(", "false", ",", "id", ")", ";", "}", "}", "scope", ".", "dispatchEvent", "(", "\"clientJoinedRoom\"", ",", "id", ")", ";", "}" ]
called when client joined in room, if rtc enabled and browser has support of rtc, creates offer and sends to peer by sending sdp string to server, else notifies server to add connection in fallback list
[ "called", "when", "client", "joined", "in", "room", "if", "rtc", "enabled", "and", "browser", "has", "support", "of", "rtc", "creates", "offer", "and", "sends", "to", "peer", "by", "sending", "sdp", "string", "to", "server", "else", "notifies", "server", "to", "add", "connection", "in", "fallback", "list" ]
bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0
https://github.com/AlphaReplica/Connecta/blob/bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0/lib/client/source/connecta.js#L123-L138
train
AlphaReplica/Connecta
lib/client/source/connecta.js
onRTCFallback
function onRTCFallback(from,data,isArray) { var peer = getPeerByRTCId(from); if(peer) { if(isArray == true) { data = sliceArray(data,0,data.length-2);// data.slice(0,data.length-2); } scope.dispatchEvent("peerMessage",{message:data,id:peer.id,rtc:peer.rtcId,array:isArray,fallback:true}); } }
javascript
function onRTCFallback(from,data,isArray) { var peer = getPeerByRTCId(from); if(peer) { if(isArray == true) { data = sliceArray(data,0,data.length-2);// data.slice(0,data.length-2); } scope.dispatchEvent("peerMessage",{message:data,id:peer.id,rtc:peer.rtcId,array:isArray,fallback:true}); } }
[ "function", "onRTCFallback", "(", "from", ",", "data", ",", "isArray", ")", "{", "var", "peer", "=", "getPeerByRTCId", "(", "from", ")", ";", "if", "(", "peer", ")", "{", "if", "(", "isArray", "==", "true", ")", "{", "data", "=", "sliceArray", "(", "data", ",", "0", ",", "data", ".", "length", "-", "2", ")", ";", "}", "scope", ".", "dispatchEvent", "(", "\"peerMessage\"", ",", "{", "message", ":", "data", ",", "id", ":", "peer", ".", "id", ",", "rtc", ":", "peer", ".", "rtcId", ",", "array", ":", "isArray", ",", "fallback", ":", "true", "}", ")", ";", "}", "}" ]
invoked when fallback message is received
[ "invoked", "when", "fallback", "message", "is", "received" ]
bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0
https://github.com/AlphaReplica/Connecta/blob/bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0/lib/client/source/connecta.js#L155-L167
train
AlphaReplica/Connecta
lib/client/source/connecta.js
onServerMessage
function onServerMessage(data) { if(data.ev) { scope.dispatchEvent("onServerMessage",data); scope.dispatchEvent(data.ev,data); } }
javascript
function onServerMessage(data) { if(data.ev) { scope.dispatchEvent("onServerMessage",data); scope.dispatchEvent(data.ev,data); } }
[ "function", "onServerMessage", "(", "data", ")", "{", "if", "(", "data", ".", "ev", ")", "{", "scope", ".", "dispatchEvent", "(", "\"onServerMessage\"", ",", "data", ")", ";", "scope", ".", "dispatchEvent", "(", "data", ".", "ev", ",", "data", ")", ";", "}", "}" ]
invoked when server message received
[ "invoked", "when", "server", "message", "received" ]
bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0
https://github.com/AlphaReplica/Connecta/blob/bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0/lib/client/source/connecta.js#L176-L183
train
AlphaReplica/Connecta
lib/client/source/connecta.js
onPeerConnected
function onPeerConnected(peer) { if(scope.localStream) { peer.updateStream(scope.localStream,false); } scope._servConn.sendRTCState(true,peer.id); scope.dispatchEvent("peerConnected",peer.id); }
javascript
function onPeerConnected(peer) { if(scope.localStream) { peer.updateStream(scope.localStream,false); } scope._servConn.sendRTCState(true,peer.id); scope.dispatchEvent("peerConnected",peer.id); }
[ "function", "onPeerConnected", "(", "peer", ")", "{", "if", "(", "scope", ".", "localStream", ")", "{", "peer", ".", "updateStream", "(", "scope", ".", "localStream", ",", "false", ")", ";", "}", "scope", ".", "_servConn", ".", "sendRTCState", "(", "true", ",", "peer", ".", "id", ")", ";", "scope", ".", "dispatchEvent", "(", "\"peerConnected\"", ",", "peer", ".", "id", ")", ";", "}" ]
invoked when peer connection, notifies server and resends offser if stream is enabled
[ "invoked", "when", "peer", "connection", "notifies", "server", "and", "resends", "offser", "if", "stream", "is", "enabled" ]
bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0
https://github.com/AlphaReplica/Connecta/blob/bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0/lib/client/source/connecta.js#L201-L210
train
AlphaReplica/Connecta
lib/client/source/connecta.js
onPeerFailed
function onPeerFailed(peer) { scope._servConn.sendRTCState(false,peer.id); scope.dispatchEvent("peerFailed",peer.id); }
javascript
function onPeerFailed(peer) { scope._servConn.sendRTCState(false,peer.id); scope.dispatchEvent("peerFailed",peer.id); }
[ "function", "onPeerFailed", "(", "peer", ")", "{", "scope", ".", "_servConn", ".", "sendRTCState", "(", "false", ",", "peer", ".", "id", ")", ";", "scope", ".", "dispatchEvent", "(", "\"peerFailed\"", ",", "peer", ".", "id", ")", ";", "}" ]
invoked when peer fails to connect
[ "invoked", "when", "peer", "fails", "to", "connect" ]
bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0
https://github.com/AlphaReplica/Connecta/blob/bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0/lib/client/source/connecta.js#L213-L217
train
AlphaReplica/Connecta
lib/client/source/connecta.js
onPeerClose
function onPeerClose(peer) { var id = peer.id; scope.removePeer(peer); sendPeerClose(id); scope.dispatchEvent("peerDisconnected",id); }
javascript
function onPeerClose(peer) { var id = peer.id; scope.removePeer(peer); sendPeerClose(id); scope.dispatchEvent("peerDisconnected",id); }
[ "function", "onPeerClose", "(", "peer", ")", "{", "var", "id", "=", "peer", ".", "id", ";", "scope", ".", "removePeer", "(", "peer", ")", ";", "sendPeerClose", "(", "id", ")", ";", "scope", ".", "dispatchEvent", "(", "\"peerDisconnected\"", ",", "id", ")", ";", "}" ]
invoked when peer closes, this will remove peer from dictionary
[ "invoked", "when", "peer", "closes", "this", "will", "remove", "peer", "from", "dictionary" ]
bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0
https://github.com/AlphaReplica/Connecta/blob/bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0/lib/client/source/connecta.js#L220-L227
train
AlphaReplica/Connecta
lib/client/source/connecta.js
onIceCandidate
function onIceCandidate(id,data) { if(scope.hasWebRTCSupport()) { getOrCreatePeer(id).onServerMessage(JSON.parse(data)); } }
javascript
function onIceCandidate(id,data) { if(scope.hasWebRTCSupport()) { getOrCreatePeer(id).onServerMessage(JSON.parse(data)); } }
[ "function", "onIceCandidate", "(", "id", ",", "data", ")", "{", "if", "(", "scope", ".", "hasWebRTCSupport", "(", ")", ")", "{", "getOrCreatePeer", "(", "id", ")", ".", "onServerMessage", "(", "JSON", ".", "parse", "(", "data", ")", ")", ";", "}", "}" ]
invoked when peer creates ice candidate and it's ready to send
[ "invoked", "when", "peer", "creates", "ice", "candidate", "and", "it", "s", "ready", "to", "send" ]
bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0
https://github.com/AlphaReplica/Connecta/blob/bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0/lib/client/source/connecta.js#L266-L272
train
AlphaReplica/Connecta
lib/client/source/connecta.js
onPeerMessage
function onPeerMessage(peer,msg) { scope.dispatchEvent("peerMessage",{message:msg,id:peer.id,rtc:peer.rtcId,array:false,fallback:false}); }
javascript
function onPeerMessage(peer,msg) { scope.dispatchEvent("peerMessage",{message:msg,id:peer.id,rtc:peer.rtcId,array:false,fallback:false}); }
[ "function", "onPeerMessage", "(", "peer", ",", "msg", ")", "{", "scope", ".", "dispatchEvent", "(", "\"peerMessage\"", ",", "{", "message", ":", "msg", ",", "id", ":", "peer", ".", "id", ",", "rtc", ":", "peer", ".", "rtcId", ",", "array", ":", "false", ",", "fallback", ":", "false", "}", ")", ";", "}" ]
invoked when string message received from peer
[ "invoked", "when", "string", "message", "received", "from", "peer" ]
bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0
https://github.com/AlphaReplica/Connecta/blob/bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0/lib/client/source/connecta.js#L275-L278
train
AlphaReplica/Connecta
lib/client/source/connecta.js
onBytesMessage
function onBytesMessage(peer,data) { var arr = bufferToArray(scope._servConn.byteType,data); if(arr) { if(scope._servConn.rtcFallback == true) { arr = arr.slice(0,arr.length-2); } scope.dispatchEvent("peerMessage",{message:arr,id:peer.id,rtc:peer.rtcId,array:true,fallback:false}); } }
javascript
function onBytesMessage(peer,data) { var arr = bufferToArray(scope._servConn.byteType,data); if(arr) { if(scope._servConn.rtcFallback == true) { arr = arr.slice(0,arr.length-2); } scope.dispatchEvent("peerMessage",{message:arr,id:peer.id,rtc:peer.rtcId,array:true,fallback:false}); } }
[ "function", "onBytesMessage", "(", "peer", ",", "data", ")", "{", "var", "arr", "=", "bufferToArray", "(", "scope", ".", "_servConn", ".", "byteType", ",", "data", ")", ";", "if", "(", "arr", ")", "{", "if", "(", "scope", ".", "_servConn", ".", "rtcFallback", "==", "true", ")", "{", "arr", "=", "arr", ".", "slice", "(", "0", ",", "arr", ".", "length", "-", "2", ")", ";", "}", "scope", ".", "dispatchEvent", "(", "\"peerMessage\"", ",", "{", "message", ":", "arr", ",", "id", ":", "peer", ".", "id", ",", "rtc", ":", "peer", ".", "rtcId", ",", "array", ":", "true", ",", "fallback", ":", "false", "}", ")", ";", "}", "}" ]
invoked when byte message received from peer
[ "invoked", "when", "byte", "message", "received", "from", "peer" ]
bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0
https://github.com/AlphaReplica/Connecta/blob/bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0/lib/client/source/connecta.js#L281-L293
train
compose-ui/dialog
index.js
addText
function addText() { // Add title dialogEl.querySelector( '#dialog-title' ).innerHTML = options.title // Add optional description var descriptionEl = dialogEl.querySelector( '#dialog-description' ) if ( options.description ) { descriptionEl.innerHTML = options.description } else { descriptionEl.parentElement.removeChild( descriptionEl ) dialogEl.removeAttribute( 'aria-labelledby' ) } }
javascript
function addText() { // Add title dialogEl.querySelector( '#dialog-title' ).innerHTML = options.title // Add optional description var descriptionEl = dialogEl.querySelector( '#dialog-description' ) if ( options.description ) { descriptionEl.innerHTML = options.description } else { descriptionEl.parentElement.removeChild( descriptionEl ) dialogEl.removeAttribute( 'aria-labelledby' ) } }
[ "function", "addText", "(", ")", "{", "dialogEl", ".", "querySelector", "(", "'#dialog-title'", ")", ".", "innerHTML", "=", "options", ".", "title", "var", "descriptionEl", "=", "dialogEl", ".", "querySelector", "(", "'#dialog-description'", ")", "if", "(", "options", ".", "description", ")", "{", "descriptionEl", ".", "innerHTML", "=", "options", ".", "description", "}", "else", "{", "descriptionEl", ".", "parentElement", ".", "removeChild", "(", "descriptionEl", ")", "dialogEl", ".", "removeAttribute", "(", "'aria-labelledby'", ")", "}", "}" ]
Add title and description from options
[ "Add", "title", "and", "description", "from", "options" ]
5d085394c4414d12ade5b7c864cbef80e2837f44
https://github.com/compose-ui/dialog/blob/5d085394c4414d12ade5b7c864cbef80e2837f44/index.js#L56-L71
train
compose-ui/dialog
index.js
tab
function tab( event ) { // Find all focusable elements in the dialog card var focusable = dialogEl.querySelectorAll('input:not([type=hidden]), textarea, select, button'), last = focusable[focusable.length - 1], focused = document.activeElement // If focused on the last focusable element, tab to the first element. if ( focused == last ) { if ( event ){ event.preventDefault() } focusable[0].focus() } // Focus on the last element if the focused element is not a child of the dialog if ( !focused || !toolbox.childOf( focused, dialogEl ) ) { last.focus() } }
javascript
function tab( event ) { // Find all focusable elements in the dialog card var focusable = dialogEl.querySelectorAll('input:not([type=hidden]), textarea, select, button'), last = focusable[focusable.length - 1], focused = document.activeElement // If focused on the last focusable element, tab to the first element. if ( focused == last ) { if ( event ){ event.preventDefault() } focusable[0].focus() } // Focus on the last element if the focused element is not a child of the dialog if ( !focused || !toolbox.childOf( focused, dialogEl ) ) { last.focus() } }
[ "function", "tab", "(", "event", ")", "{", "var", "focusable", "=", "dialogEl", ".", "querySelectorAll", "(", "'input:not([type=hidden]), textarea, select, button'", ")", ",", "last", "=", "focusable", "[", "focusable", ".", "length", "-", "1", "]", ",", "focused", "=", "document", ".", "activeElement", "if", "(", "focused", "==", "last", ")", "{", "if", "(", "event", ")", "{", "event", ".", "preventDefault", "(", ")", "}", "focusable", "[", "0", "]", ".", "focus", "(", ")", "}", "if", "(", "!", "focused", "||", "!", "toolbox", ".", "childOf", "(", "focused", ",", "dialogEl", ")", ")", "{", "last", ".", "focus", "(", ")", "}", "}" ]
In a modal window, `tab` must cycle between elements in the modal.
[ "In", "a", "modal", "window", "tab", "must", "cycle", "between", "elements", "in", "the", "modal", "." ]
5d085394c4414d12ade5b7c864cbef80e2837f44
https://github.com/compose-ui/dialog/blob/5d085394c4414d12ade5b7c864cbef80e2837f44/index.js#L98-L115
train
muigui/useful-date
index.js
function( d ) { // ISO-8601 year number. This has the same value as Y, except that if the ISO var m = d.getMonth(), w = DATE_PROTO.getISOWeek.call( d ); // week number (W) belongs to the previous or next year, that year is used instead. return ( d.getFullYear() + ( w == 1 && m > 0 ? 1 : ( w >= 52 && m < 11 ? -1 : 0 ) ) ); }
javascript
function( d ) { // ISO-8601 year number. This has the same value as Y, except that if the ISO var m = d.getMonth(), w = DATE_PROTO.getISOWeek.call( d ); // week number (W) belongs to the previous or next year, that year is used instead. return ( d.getFullYear() + ( w == 1 && m > 0 ? 1 : ( w >= 52 && m < 11 ? -1 : 0 ) ) ); }
[ "function", "(", "d", ")", "{", "var", "m", "=", "d", ".", "getMonth", "(", ")", ",", "w", "=", "DATE_PROTO", ".", "getISOWeek", ".", "call", "(", "d", ")", ";", "return", "(", "d", ".", "getFullYear", "(", ")", "+", "(", "w", "==", "1", "&&", "m", ">", "0", "?", "1", ":", "(", "w", ">=", "52", "&&", "m", "<", "11", "?", "-", "1", ":", "0", ")", ")", ")", ";", "}" ]
Whether it's a leap year
[ "Whether", "it", "s", "a", "leap", "year" ]
1dd1e82767336f5394bfc38570480340348ba966
https://github.com/muigui/useful-date/blob/1dd1e82767336f5394bfc38570480340348ba966/index.js#L761-L764
train
ItsAsbreuk/itsa-mojitonthefly-addon
examples/webapp using pjax/mojits/Navigation/controller.server.js
function(ac) { var data = {}, selectedmojit = ac.params.getFromRoute('mojit') || 'none'; data[selectedmojit] = true; ac.assets.addCss('./index.css'); ac.done(data); }
javascript
function(ac) { var data = {}, selectedmojit = ac.params.getFromRoute('mojit') || 'none'; data[selectedmojit] = true; ac.assets.addCss('./index.css'); ac.done(data); }
[ "function", "(", "ac", ")", "{", "var", "data", "=", "{", "}", ",", "selectedmojit", "=", "ac", ".", "params", ".", "getFromRoute", "(", "'mojit'", ")", "||", "'none'", ";", "data", "[", "selectedmojit", "]", "=", "true", ";", "ac", ".", "assets", ".", "addCss", "(", "'./index.css'", ")", ";", "ac", ".", "done", "(", "data", ")", ";", "}" ]
Method corresponding to the 'index' action. @param ac {Object} The ActionContext that provides access to the Mojito API.
[ "Method", "corresponding", "to", "the", "index", "action", "." ]
500de397fef8f80f719360d4ac023bb860934ec0
https://github.com/ItsAsbreuk/itsa-mojitonthefly-addon/blob/500de397fef8f80f719360d4ac023bb860934ec0/examples/webapp using pjax/mojits/Navigation/controller.server.js#L24-L30
train
Industryswarm/isnode-mod-data
lib/mongodb/mongodb/lib/bulk/ordered.js
executeCommands
function executeCommands(bulkOperation, options, callback) { if (bulkOperation.s.batches.length === 0) { return handleCallback(callback, null, new BulkWriteResult(bulkOperation.s.bulkResult)); } // Ordered execution of the command const batch = bulkOperation.s.batches.shift(); function resultHandler(err, result) { // Error is a driver related error not a bulk op error, terminate if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) { return handleCallback(callback, err); } // If we have and error if (err) err.ok = 0; if (err instanceof MongoWriteConcernError) { return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, true, err, callback); } // Merge the results together const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); const mergeResult = mergeBatchResults(true, batch, bulkOperation.s.bulkResult, err, result); if (mergeResult != null) { return handleCallback(callback, null, writeResult); } if (bulkOperation.handleWriteError(callback, writeResult)) return; // Execute the next command in line executeCommands(bulkOperation, options, callback); } bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback); }
javascript
function executeCommands(bulkOperation, options, callback) { if (bulkOperation.s.batches.length === 0) { return handleCallback(callback, null, new BulkWriteResult(bulkOperation.s.bulkResult)); } // Ordered execution of the command const batch = bulkOperation.s.batches.shift(); function resultHandler(err, result) { // Error is a driver related error not a bulk op error, terminate if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) { return handleCallback(callback, err); } // If we have and error if (err) err.ok = 0; if (err instanceof MongoWriteConcernError) { return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, true, err, callback); } // Merge the results together const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); const mergeResult = mergeBatchResults(true, batch, bulkOperation.s.bulkResult, err, result); if (mergeResult != null) { return handleCallback(callback, null, writeResult); } if (bulkOperation.handleWriteError(callback, writeResult)) return; // Execute the next command in line executeCommands(bulkOperation, options, callback); } bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback); }
[ "function", "executeCommands", "(", "bulkOperation", ",", "options", ",", "callback", ")", "{", "if", "(", "bulkOperation", ".", "s", ".", "batches", ".", "length", "===", "0", ")", "{", "return", "handleCallback", "(", "callback", ",", "null", ",", "new", "BulkWriteResult", "(", "bulkOperation", ".", "s", ".", "bulkResult", ")", ")", ";", "}", "const", "batch", "=", "bulkOperation", ".", "s", ".", "batches", ".", "shift", "(", ")", ";", "function", "resultHandler", "(", "err", ",", "result", ")", "{", "if", "(", "(", "(", "err", "&&", "err", ".", "driver", ")", "||", "(", "err", "&&", "err", ".", "message", ")", ")", "&&", "!", "(", "err", "instanceof", "MongoWriteConcernError", ")", ")", "{", "return", "handleCallback", "(", "callback", ",", "err", ")", ";", "}", "if", "(", "err", ")", "err", ".", "ok", "=", "0", ";", "if", "(", "err", "instanceof", "MongoWriteConcernError", ")", "{", "return", "handleMongoWriteConcernError", "(", "batch", ",", "bulkOperation", ".", "s", ".", "bulkResult", ",", "true", ",", "err", ",", "callback", ")", ";", "}", "const", "writeResult", "=", "new", "BulkWriteResult", "(", "bulkOperation", ".", "s", ".", "bulkResult", ")", ";", "const", "mergeResult", "=", "mergeBatchResults", "(", "true", ",", "batch", ",", "bulkOperation", ".", "s", ".", "bulkResult", ",", "err", ",", "result", ")", ";", "if", "(", "mergeResult", "!=", "null", ")", "{", "return", "handleCallback", "(", "callback", ",", "null", ",", "writeResult", ")", ";", "}", "if", "(", "bulkOperation", ".", "handleWriteError", "(", "callback", ",", "writeResult", ")", ")", "return", ";", "executeCommands", "(", "bulkOperation", ",", "options", ",", "callback", ")", ";", "}", "bulkOperation", ".", "finalOptionsHandler", "(", "{", "options", ",", "batch", ",", "resultHandler", "}", ",", "callback", ")", ";", "}" ]
Execute next write command in a chain @param {OrderedBulkOperation} bulkOperation @param {object} options @param {function} callback
[ "Execute", "next", "write", "command", "in", "a", "chain" ]
5adc639b88a0d72cbeef23a6b5df7f4540745089
https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb/lib/bulk/ordered.js#L132-L166
train