id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
52,200
deftly/node-deftly
src/log.js
addFilter
function addFilter (config, filter) { if (filter) { if (filter[ 0 ] === '-') { config.filters.ignore[ filter ] = new RegExp('^' + filter.slice(1).replace(/[*]/g, '.*?') + '$') } else { config.filters.should[ filter ] = new RegExp('^' + filter.replace(/[*]/g, '.*?') + '$') } } }
javascript
function addFilter (config, filter) { if (filter) { if (filter[ 0 ] === '-') { config.filters.ignore[ filter ] = new RegExp('^' + filter.slice(1).replace(/[*]/g, '.*?') + '$') } else { config.filters.should[ filter ] = new RegExp('^' + filter.replace(/[*]/g, '.*?') + '$') } } }
[ "function", "addFilter", "(", "config", ",", "filter", ")", "{", "if", "(", "filter", ")", "{", "if", "(", "filter", "[", "0", "]", "===", "'-'", ")", "{", "config", ".", "filters", ".", "ignore", "[", "filter", "]", "=", "new", "RegExp", "(", "'^'", "+", "filter", ".", "slice", "(", "1", ")", ".", "replace", "(", "/", "[*]", "/", "g", ",", "'.*?'", ")", "+", "'$'", ")", "}", "else", "{", "config", ".", "filters", ".", "should", "[", "filter", "]", "=", "new", "RegExp", "(", "'^'", "+", "filter", ".", "replace", "(", "/", "[*]", "/", "g", ",", "'.*?'", ")", "+", "'$'", ")", "}", "}", "}" ]
add the regex filter to the right hash for use later
[ "add", "the", "regex", "filter", "to", "the", "right", "hash", "for", "use", "later" ]
0c34205fd6726356b69bcdd6dec4fcba55027af6
https://github.com/deftly/node-deftly/blob/0c34205fd6726356b69bcdd6dec4fcba55027af6/src/log.js#L52-L60
52,201
deftly/node-deftly
src/log.js
addLogger
function addLogger (state, name, config, adapter) { config = Object.assign({}, defaultConfig, config) setFilters(config) const logger = { name: name, config: config, adapter: adapter, addFilter: addFilter.bind(null, config), removeFilter: removeFilter.bind(null, config), setFilter: setFilter.bind(null, config), setFilters: setFilters.bind(null, config) } if (config.namespaceInit) { logger.init = memoize(adapter) } logger.log = onEntry.bind(null, logger) state.loggers[ name ] = logger }
javascript
function addLogger (state, name, config, adapter) { config = Object.assign({}, defaultConfig, config) setFilters(config) const logger = { name: name, config: config, adapter: adapter, addFilter: addFilter.bind(null, config), removeFilter: removeFilter.bind(null, config), setFilter: setFilter.bind(null, config), setFilters: setFilters.bind(null, config) } if (config.namespaceInit) { logger.init = memoize(adapter) } logger.log = onEntry.bind(null, logger) state.loggers[ name ] = logger }
[ "function", "addLogger", "(", "state", ",", "name", ",", "config", ",", "adapter", ")", "{", "config", "=", "Object", ".", "assign", "(", "{", "}", ",", "defaultConfig", ",", "config", ")", "setFilters", "(", "config", ")", "const", "logger", "=", "{", "name", ":", "name", ",", "config", ":", "config", ",", "adapter", ":", "adapter", ",", "addFilter", ":", "addFilter", ".", "bind", "(", "null", ",", "config", ")", ",", "removeFilter", ":", "removeFilter", ".", "bind", "(", "null", ",", "config", ")", ",", "setFilter", ":", "setFilter", ".", "bind", "(", "null", ",", "config", ")", ",", "setFilters", ":", "setFilters", ".", "bind", "(", "null", ",", "config", ")", "}", "if", "(", "config", ".", "namespaceInit", ")", "{", "logger", ".", "init", "=", "memoize", "(", "adapter", ")", "}", "logger", ".", "log", "=", "onEntry", ".", "bind", "(", "null", ",", "logger", ")", "state", ".", "loggers", "[", "name", "]", "=", "logger", "}" ]
creates a logger from a user supplied adapter
[ "creates", "a", "logger", "from", "a", "user", "supplied", "adapter" ]
0c34205fd6726356b69bcdd6dec4fcba55027af6
https://github.com/deftly/node-deftly/blob/0c34205fd6726356b69bcdd6dec4fcba55027af6/src/log.js#L63-L80
52,202
deftly/node-deftly
src/log.js
attach
function attach (state, logger, namespace) { _.each(levels, function (level, name) { logger[ name ] = prepMessage.bind(null, state, name, namespace) }) }
javascript
function attach (state, logger, namespace) { _.each(levels, function (level, name) { logger[ name ] = prepMessage.bind(null, state, name, namespace) }) }
[ "function", "attach", "(", "state", ",", "logger", ",", "namespace", ")", "{", "_", ".", "each", "(", "levels", ",", "function", "(", "level", ",", "name", ")", "{", "logger", "[", "name", "]", "=", "prepMessage", ".", "bind", "(", "null", ",", "state", ",", "name", ",", "namespace", ")", "}", ")", "}" ]
create a bound prepMessage call for each log level
[ "create", "a", "bound", "prepMessage", "call", "for", "each", "log", "level" ]
0c34205fd6726356b69bcdd6dec4fcba55027af6
https://github.com/deftly/node-deftly/blob/0c34205fd6726356b69bcdd6dec4fcba55027af6/src/log.js#L83-L87
52,203
deftly/node-deftly
src/log.js
init
function init (state, namespace) { namespace = namespace || 'deftly' const logger = { namespace: namespace } attach(state, logger, namespace) return logger }
javascript
function init (state, namespace) { namespace = namespace || 'deftly' const logger = { namespace: namespace } attach(state, logger, namespace) return logger }
[ "function", "init", "(", "state", ",", "namespace", ")", "{", "namespace", "=", "namespace", "||", "'deftly'", "const", "logger", "=", "{", "namespace", ":", "namespace", "}", "attach", "(", "state", ",", "logger", ",", "namespace", ")", "return", "logger", "}" ]
create a namespaced log instance for use in modules
[ "create", "a", "namespaced", "log", "instance", "for", "use", "in", "modules" ]
0c34205fd6726356b69bcdd6dec4fcba55027af6
https://github.com/deftly/node-deftly/blob/0c34205fd6726356b69bcdd6dec4fcba55027af6/src/log.js#L90-L95
52,204
deftly/node-deftly
src/log.js
log
function log (state, type, namespace, message) { const level = levels[ type ] _.each(state.loggers, function (logger) { logger.log({ type: type, level: level, namespace: namespace, message: message }) }) }
javascript
function log (state, type, namespace, message) { const level = levels[ type ] _.each(state.loggers, function (logger) { logger.log({ type: type, level: level, namespace: namespace, message: message }) }) }
[ "function", "log", "(", "state", ",", "type", ",", "namespace", ",", "message", ")", "{", "const", "level", "=", "levels", "[", "type", "]", "_", ".", "each", "(", "state", ".", "loggers", ",", "function", "(", "logger", ")", "{", "logger", ".", "log", "(", "{", "type", ":", "type", ",", "level", ":", "level", ",", "namespace", ":", "namespace", ",", "message", ":", "message", "}", ")", "}", ")", "}" ]
calls log for each logger
[ "calls", "log", "for", "each", "logger" ]
0c34205fd6726356b69bcdd6dec4fcba55027af6
https://github.com/deftly/node-deftly/blob/0c34205fd6726356b69bcdd6dec4fcba55027af6/src/log.js#L98-L108
52,205
deftly/node-deftly
src/log.js
prepMessage
function prepMessage (state, level, namespace, message) { if (_.isString(message)) { const formatArgs = Array.prototype.slice.call(arguments, 3) message = format.apply(null, formatArgs) } log(state, level, namespace, message) }
javascript
function prepMessage (state, level, namespace, message) { if (_.isString(message)) { const formatArgs = Array.prototype.slice.call(arguments, 3) message = format.apply(null, formatArgs) } log(state, level, namespace, message) }
[ "function", "prepMessage", "(", "state", ",", "level", ",", "namespace", ",", "message", ")", "{", "if", "(", "_", ".", "isString", "(", "message", ")", ")", "{", "const", "formatArgs", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "3", ")", "message", "=", "format", ".", "apply", "(", "null", ",", "formatArgs", ")", "}", "log", "(", "state", ",", "level", ",", "namespace", ",", "message", ")", "}" ]
handles message format if necessary before calling the actual log function to emit
[ "handles", "message", "format", "if", "necessary", "before", "calling", "the", "actual", "log", "function", "to", "emit" ]
0c34205fd6726356b69bcdd6dec4fcba55027af6
https://github.com/deftly/node-deftly/blob/0c34205fd6726356b69bcdd6dec4fcba55027af6/src/log.js#L136-L142
52,206
deftly/node-deftly
src/log.js
removeFilter
function removeFilter (config, filter) { if (filter) { if (config.filters.ignore[ filter ]) { delete config.filters.ignore[ filter ] } else { delete config.filters.should[ filter ] } } }
javascript
function removeFilter (config, filter) { if (filter) { if (config.filters.ignore[ filter ]) { delete config.filters.ignore[ filter ] } else { delete config.filters.should[ filter ] } } }
[ "function", "removeFilter", "(", "config", ",", "filter", ")", "{", "if", "(", "filter", ")", "{", "if", "(", "config", ".", "filters", ".", "ignore", "[", "filter", "]", ")", "{", "delete", "config", ".", "filters", ".", "ignore", "[", "filter", "]", "}", "else", "{", "delete", "config", ".", "filters", ".", "should", "[", "filter", "]", "}", "}", "}" ]
remove the regex filter from the correct hash
[ "remove", "the", "regex", "filter", "from", "the", "correct", "hash" ]
0c34205fd6726356b69bcdd6dec4fcba55027af6
https://github.com/deftly/node-deftly/blob/0c34205fd6726356b69bcdd6dec4fcba55027af6/src/log.js#L145-L153
52,207
deftly/node-deftly
src/log.js
setFilters
function setFilters (config) { const parts = config.filter.split(/[\s,]+/) config.filters = { should: {}, ignore: {} } _.each(parts, addFilter.bind(null, config)) }
javascript
function setFilters (config) { const parts = config.filter.split(/[\s,]+/) config.filters = { should: {}, ignore: {} } _.each(parts, addFilter.bind(null, config)) }
[ "function", "setFilters", "(", "config", ")", "{", "const", "parts", "=", "config", ".", "filter", ".", "split", "(", "/", "[\\s,]+", "/", ")", "config", ".", "filters", "=", "{", "should", ":", "{", "}", ",", "ignore", ":", "{", "}", "}", "_", ".", "each", "(", "parts", ",", "addFilter", ".", "bind", "(", "null", ",", "config", ")", ")", "}" ]
sets should and musn't filters
[ "sets", "should", "and", "musn", "t", "filters" ]
0c34205fd6726356b69bcdd6dec4fcba55027af6
https://github.com/deftly/node-deftly/blob/0c34205fd6726356b69bcdd6dec4fcba55027af6/src/log.js#L167-L174
52,208
deftly/node-deftly
src/log.js
shouldRender
function shouldRender (config, entry) { // if we're below the log level, return false if (config.level < entry.level) { return false } // if we match the ignore list at all, return false const ignoreMatch = _.find(_.values(config.filters.ignore), ignore => { return ignore.test(entry.namespace) }) if (ignoreMatch) { return false } // if a should filter exists but we don't have a match, return false let shouldFiltered = false const shouldMatch = _.find(_.values(config.filters.should), should => { shouldFiltered = true return should.test(entry.namespace) }) if ((shouldFiltered && !shouldMatch)) { return false } return true }
javascript
function shouldRender (config, entry) { // if we're below the log level, return false if (config.level < entry.level) { return false } // if we match the ignore list at all, return false const ignoreMatch = _.find(_.values(config.filters.ignore), ignore => { return ignore.test(entry.namespace) }) if (ignoreMatch) { return false } // if a should filter exists but we don't have a match, return false let shouldFiltered = false const shouldMatch = _.find(_.values(config.filters.should), should => { shouldFiltered = true return should.test(entry.namespace) }) if ((shouldFiltered && !shouldMatch)) { return false } return true }
[ "function", "shouldRender", "(", "config", ",", "entry", ")", "{", "// if we're below the log level, return false", "if", "(", "config", ".", "level", "<", "entry", ".", "level", ")", "{", "return", "false", "}", "// if we match the ignore list at all, return false", "const", "ignoreMatch", "=", "_", ".", "find", "(", "_", ".", "values", "(", "config", ".", "filters", ".", "ignore", ")", ",", "ignore", "=>", "{", "return", "ignore", ".", "test", "(", "entry", ".", "namespace", ")", "}", ")", "if", "(", "ignoreMatch", ")", "{", "return", "false", "}", "// if a should filter exists but we don't have a match, return false", "let", "shouldFiltered", "=", "false", "const", "shouldMatch", "=", "_", ".", "find", "(", "_", ".", "values", "(", "config", ".", "filters", ".", "should", ")", ",", "should", "=>", "{", "shouldFiltered", "=", "true", "return", "should", ".", "test", "(", "entry", ".", "namespace", ")", "}", ")", "if", "(", "(", "shouldFiltered", "&&", "!", "shouldMatch", ")", ")", "{", "return", "false", "}", "return", "true", "}" ]
check entry against configuration to see if it should be logged by adapter
[ "check", "entry", "against", "configuration", "to", "see", "if", "it", "should", "be", "logged", "by", "adapter" ]
0c34205fd6726356b69bcdd6dec4fcba55027af6
https://github.com/deftly/node-deftly/blob/0c34205fd6726356b69bcdd6dec4fcba55027af6/src/log.js#L178-L203
52,209
skylarkax/skylark-slax-nodeserver
bin/cli.js
initTerminateHandlers
function initTerminateHandlers() { var readLine; if (process.platform === "win32"){ readLine = require("readline"); readLine.createInterface ({ input: process.stdin, output: process.stdout }).on("SIGINT", function () { process.emit("SIGINT"); }); } // handle INTERRUPT (CTRL+C) and TERM/KILL signals process.on('exit', function () { if (server) { console.log(chalk.blue('*'), 'Shutting down server'); server.stop(); } console.log(); // extra blank line }); process.on('SIGINT', function () { console.log(chalk.blue.bold('!'), chalk.yellow.bold('SIGINT'), 'detected'); process.exit(); }); process.on('SIGTERM', function () { console.log(chalk.blue.bold('!'), chalk.yellow.bold('SIGTERM'), 'detected'); process.exit(0); }); }
javascript
function initTerminateHandlers() { var readLine; if (process.platform === "win32"){ readLine = require("readline"); readLine.createInterface ({ input: process.stdin, output: process.stdout }).on("SIGINT", function () { process.emit("SIGINT"); }); } // handle INTERRUPT (CTRL+C) and TERM/KILL signals process.on('exit', function () { if (server) { console.log(chalk.blue('*'), 'Shutting down server'); server.stop(); } console.log(); // extra blank line }); process.on('SIGINT', function () { console.log(chalk.blue.bold('!'), chalk.yellow.bold('SIGINT'), 'detected'); process.exit(); }); process.on('SIGTERM', function () { console.log(chalk.blue.bold('!'), chalk.yellow.bold('SIGTERM'), 'detected'); process.exit(0); }); }
[ "function", "initTerminateHandlers", "(", ")", "{", "var", "readLine", ";", "if", "(", "process", ".", "platform", "===", "\"win32\"", ")", "{", "readLine", "=", "require", "(", "\"readline\"", ")", ";", "readLine", ".", "createInterface", "(", "{", "input", ":", "process", ".", "stdin", ",", "output", ":", "process", ".", "stdout", "}", ")", ".", "on", "(", "\"SIGINT\"", ",", "function", "(", ")", "{", "process", ".", "emit", "(", "\"SIGINT\"", ")", ";", "}", ")", ";", "}", "// handle INTERRUPT (CTRL+C) and TERM/KILL signals", "process", ".", "on", "(", "'exit'", ",", "function", "(", ")", "{", "if", "(", "server", ")", "{", "console", ".", "log", "(", "chalk", ".", "blue", "(", "'*'", ")", ",", "'Shutting down server'", ")", ";", "server", ".", "stop", "(", ")", ";", "}", "console", ".", "log", "(", ")", ";", "// extra blank line", "}", ")", ";", "process", ".", "on", "(", "'SIGINT'", ",", "function", "(", ")", "{", "console", ".", "log", "(", "chalk", ".", "blue", ".", "bold", "(", "'!'", ")", ",", "chalk", ".", "yellow", ".", "bold", "(", "'SIGINT'", ")", ",", "'detected'", ")", ";", "process", ".", "exit", "(", ")", ";", "}", ")", ";", "process", ".", "on", "(", "'SIGTERM'", ",", "function", "(", ")", "{", "console", ".", "log", "(", "chalk", ".", "blue", ".", "bold", "(", "'!'", ")", ",", "chalk", ".", "yellow", ".", "bold", "(", "'SIGTERM'", ")", ",", "'detected'", ")", ";", "process", ".", "exit", "(", "0", ")", ";", "}", ")", ";", "}" ]
Prepare the 'exit' handler for the program termination
[ "Prepare", "the", "exit", "handler", "for", "the", "program", "termination" ]
af0840a4689495a1efa3b23ad34848034fcc313f
https://github.com/skylarkax/skylark-slax-nodeserver/blob/af0840a4689495a1efa3b23ad34848034fcc313f/bin/cli.js#L55-L85
52,210
sendanor/nor-nopg
src/schema/v0020.js
fetch_object_by_uuid
function fetch_object_by_uuid(data, prop, uuid) { if(!is_object(data)) { return error('fetch_object_by_uuid(data, ..., ...) not object: '+ data); } if(!is_string(prop)) { return error('fetch_object_by_uuid(..., prop, ...) not string: '+ prop); } if(!is_uuid(uuid)) { return warn('Property ' + prop + ' was not uuid: ' + uuid); } if(data.documents[uuid] === undefined) { data.documents[uuid] = get_document(uuid); } else { return warn('Document already fetched: ' + uuid); } }
javascript
function fetch_object_by_uuid(data, prop, uuid) { if(!is_object(data)) { return error('fetch_object_by_uuid(data, ..., ...) not object: '+ data); } if(!is_string(prop)) { return error('fetch_object_by_uuid(..., prop, ...) not string: '+ prop); } if(!is_uuid(uuid)) { return warn('Property ' + prop + ' was not uuid: ' + uuid); } if(data.documents[uuid] === undefined) { data.documents[uuid] = get_document(uuid); } else { return warn('Document already fetched: ' + uuid); } }
[ "function", "fetch_object_by_uuid", "(", "data", ",", "prop", ",", "uuid", ")", "{", "if", "(", "!", "is_object", "(", "data", ")", ")", "{", "return", "error", "(", "'fetch_object_by_uuid(data, ..., ...) not object: '", "+", "data", ")", ";", "}", "if", "(", "!", "is_string", "(", "prop", ")", ")", "{", "return", "error", "(", "'fetch_object_by_uuid(..., prop, ...) not string: '", "+", "prop", ")", ";", "}", "if", "(", "!", "is_uuid", "(", "uuid", ")", ")", "{", "return", "warn", "(", "'Property '", "+", "prop", "+", "' was not uuid: '", "+", "uuid", ")", ";", "}", "if", "(", "data", ".", "documents", "[", "uuid", "]", "===", "undefined", ")", "{", "data", ".", "documents", "[", "uuid", "]", "=", "get_document", "(", "uuid", ")", ";", "}", "else", "{", "return", "warn", "(", "'Document already fetched: '", "+", "uuid", ")", ";", "}", "}" ]
Get document by UUID
[ "Get", "document", "by", "UUID" ]
0d99b86c1a1996b5828b56de8de23700df8bbc0c
https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/schema/v0020.js#L60-L69
52,211
buzzin0609/tagbuildr
src/setDomAttrs.js
setDomAttrs
function setDomAttrs(attrs, el) { for (let attr in attrs) { if (!attrs.hasOwnProperty(attr)) { continue; } switch (attr) { case 'className': case 'id': el[attr] = attrs[attr]; break; default: el.setAttribute(attr, attrs[attr]); break; } } return el; }
javascript
function setDomAttrs(attrs, el) { for (let attr in attrs) { if (!attrs.hasOwnProperty(attr)) { continue; } switch (attr) { case 'className': case 'id': el[attr] = attrs[attr]; break; default: el.setAttribute(attr, attrs[attr]); break; } } return el; }
[ "function", "setDomAttrs", "(", "attrs", ",", "el", ")", "{", "for", "(", "let", "attr", "in", "attrs", ")", "{", "if", "(", "!", "attrs", ".", "hasOwnProperty", "(", "attr", ")", ")", "{", "continue", ";", "}", "switch", "(", "attr", ")", "{", "case", "'className'", ":", "case", "'id'", ":", "el", "[", "attr", "]", "=", "attrs", "[", "attr", "]", ";", "break", ";", "default", ":", "el", ".", "setAttribute", "(", "attr", ",", "attrs", "[", "attr", "]", ")", ";", "break", ";", "}", "}", "return", "el", ";", "}" ]
Add attributes to the dom element @private @param {Object} attrs object of key-value pairs of dom attributes. Classes and Id are added directly to element and others are set via setAttribute @param {Element} el the dom element
[ "Add", "attributes", "to", "the", "dom", "element" ]
9d6a52ad51c0fc3230de2da1e8e3f63f95a6e542
https://github.com/buzzin0609/tagbuildr/blob/9d6a52ad51c0fc3230de2da1e8e3f63f95a6e542/src/setDomAttrs.js#L7-L22
52,212
rqt/github
build/api/activity/star.js
del
async function del(owner, repo) { const endpoint = `/user/starred/${owner}/${repo}` const { statusCode } = await this._request({ method: 'PUT', data: {}, endpoint, }) if (statusCode != 204) { throw new Error(`Unexpected status code ${statusCode}.`) } }
javascript
async function del(owner, repo) { const endpoint = `/user/starred/${owner}/${repo}` const { statusCode } = await this._request({ method: 'PUT', data: {}, endpoint, }) if (statusCode != 204) { throw new Error(`Unexpected status code ${statusCode}.`) } }
[ "async", "function", "del", "(", "owner", ",", "repo", ")", "{", "const", "endpoint", "=", "`", "${", "owner", "}", "${", "repo", "}", "`", "const", "{", "statusCode", "}", "=", "await", "this", ".", "_request", "(", "{", "method", ":", "'PUT'", ",", "data", ":", "{", "}", ",", "endpoint", ",", "}", ")", "if", "(", "statusCode", "!=", "204", ")", "{", "throw", "new", "Error", "(", "`", "${", "statusCode", "}", "`", ")", "}", "}" ]
Star a repository. @param {string} owner @param {string} repo
[ "Star", "a", "repository", "." ]
e6d3cdd8633628cd4aba30e70d8258aa7f6f0c5a
https://github.com/rqt/github/blob/e6d3cdd8633628cd4aba30e70d8258aa7f6f0c5a/build/api/activity/star.js#L6-L16
52,213
jigarjain/object-clean
index.js
objCleaner
function objCleaner(obj, removeTypes) { var defaultRemoveTypes = [null, 'undefined', false, '', [], {}]; var key; function allowEmptyObject() { var i; for (i = 0; i < removeTypes.length; i++) { if (removeTypes[i] instanceof Object && Object.keys(removeTypes[i]).length === 0) { return false; } } return true; } function allowEmptyArray() { var i; for (i = 0; i < removeTypes.length; i++) { if (Array.isArray(removeTypes[i]) && removeTypes[i].length === 0) { return false; } } return true; } if (!(obj instanceof Object || Array.isArray(obj))) { throw new Error('Argument must be an object or Array'); } if (typeof removeTypes === 'undefined') { removeTypes = defaultRemoveTypes; } for (key in obj) { if (typeof obj[key] === 'object') { if (obj[key] && Object.keys(obj[key]).length) { obj[key] = objCleaner(obj[key], removeTypes); } else { obj[key] = allowEmptyObject() ? obj[key] : null; } } if (Array.isArray(obj[key])) { if (obj[key] && obj[key].length) { obj[key] = objCleaner(obj[key], removeTypes); } else { obj[key] = allowEmptyArray() ? obj[key] : null; } } if (obj instanceof Object && obj.hasOwnProperty(key)) { removeTypes.forEach(function (typeVal) { if (typeof obj[key] === typeVal || obj[key] === typeVal) { delete obj[key]; } }); } if (Array.isArray(obj) && obj.length) { removeTypes.forEach(function (typeVal, index) { if (typeof obj[key] === typeVal || obj[key] === typeVal) { obj.splice(key, 1); } }); } } return obj; }
javascript
function objCleaner(obj, removeTypes) { var defaultRemoveTypes = [null, 'undefined', false, '', [], {}]; var key; function allowEmptyObject() { var i; for (i = 0; i < removeTypes.length; i++) { if (removeTypes[i] instanceof Object && Object.keys(removeTypes[i]).length === 0) { return false; } } return true; } function allowEmptyArray() { var i; for (i = 0; i < removeTypes.length; i++) { if (Array.isArray(removeTypes[i]) && removeTypes[i].length === 0) { return false; } } return true; } if (!(obj instanceof Object || Array.isArray(obj))) { throw new Error('Argument must be an object or Array'); } if (typeof removeTypes === 'undefined') { removeTypes = defaultRemoveTypes; } for (key in obj) { if (typeof obj[key] === 'object') { if (obj[key] && Object.keys(obj[key]).length) { obj[key] = objCleaner(obj[key], removeTypes); } else { obj[key] = allowEmptyObject() ? obj[key] : null; } } if (Array.isArray(obj[key])) { if (obj[key] && obj[key].length) { obj[key] = objCleaner(obj[key], removeTypes); } else { obj[key] = allowEmptyArray() ? obj[key] : null; } } if (obj instanceof Object && obj.hasOwnProperty(key)) { removeTypes.forEach(function (typeVal) { if (typeof obj[key] === typeVal || obj[key] === typeVal) { delete obj[key]; } }); } if (Array.isArray(obj) && obj.length) { removeTypes.forEach(function (typeVal, index) { if (typeof obj[key] === typeVal || obj[key] === typeVal) { obj.splice(key, 1); } }); } } return obj; }
[ "function", "objCleaner", "(", "obj", ",", "removeTypes", ")", "{", "var", "defaultRemoveTypes", "=", "[", "null", ",", "'undefined'", ",", "false", ",", "''", ",", "[", "]", ",", "{", "}", "]", ";", "var", "key", ";", "function", "allowEmptyObject", "(", ")", "{", "var", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "removeTypes", ".", "length", ";", "i", "++", ")", "{", "if", "(", "removeTypes", "[", "i", "]", "instanceof", "Object", "&&", "Object", ".", "keys", "(", "removeTypes", "[", "i", "]", ")", ".", "length", "===", "0", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", "function", "allowEmptyArray", "(", ")", "{", "var", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "removeTypes", ".", "length", ";", "i", "++", ")", "{", "if", "(", "Array", ".", "isArray", "(", "removeTypes", "[", "i", "]", ")", "&&", "removeTypes", "[", "i", "]", ".", "length", "===", "0", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", "if", "(", "!", "(", "obj", "instanceof", "Object", "||", "Array", ".", "isArray", "(", "obj", ")", ")", ")", "{", "throw", "new", "Error", "(", "'Argument must be an object or Array'", ")", ";", "}", "if", "(", "typeof", "removeTypes", "===", "'undefined'", ")", "{", "removeTypes", "=", "defaultRemoveTypes", ";", "}", "for", "(", "key", "in", "obj", ")", "{", "if", "(", "typeof", "obj", "[", "key", "]", "===", "'object'", ")", "{", "if", "(", "obj", "[", "key", "]", "&&", "Object", ".", "keys", "(", "obj", "[", "key", "]", ")", ".", "length", ")", "{", "obj", "[", "key", "]", "=", "objCleaner", "(", "obj", "[", "key", "]", ",", "removeTypes", ")", ";", "}", "else", "{", "obj", "[", "key", "]", "=", "allowEmptyObject", "(", ")", "?", "obj", "[", "key", "]", ":", "null", ";", "}", "}", "if", "(", "Array", ".", "isArray", "(", "obj", "[", "key", "]", ")", ")", "{", "if", "(", "obj", "[", "key", "]", "&&", "obj", "[", "key", "]", ".", "length", ")", "{", "obj", "[", "key", "]", "=", "objCleaner", "(", "obj", "[", "key", "]", ",", "removeTypes", ")", ";", "}", "else", "{", "obj", "[", "key", "]", "=", "allowEmptyArray", "(", ")", "?", "obj", "[", "key", "]", ":", "null", ";", "}", "}", "if", "(", "obj", "instanceof", "Object", "&&", "obj", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "removeTypes", ".", "forEach", "(", "function", "(", "typeVal", ")", "{", "if", "(", "typeof", "obj", "[", "key", "]", "===", "typeVal", "||", "obj", "[", "key", "]", "===", "typeVal", ")", "{", "delete", "obj", "[", "key", "]", ";", "}", "}", ")", ";", "}", "if", "(", "Array", ".", "isArray", "(", "obj", ")", "&&", "obj", ".", "length", ")", "{", "removeTypes", ".", "forEach", "(", "function", "(", "typeVal", ",", "index", ")", "{", "if", "(", "typeof", "obj", "[", "key", "]", "===", "typeVal", "||", "obj", "[", "key", "]", "===", "typeVal", ")", "{", "obj", ".", "splice", "(", "key", ",", "1", ")", ";", "}", "}", ")", ";", "}", "}", "return", "obj", ";", "}" ]
Will delete the keys of the object which are set to null, undefined or empty string @param {Object/Array} obj An object or array which needs to be cleaned @param {Array} removeTypes Array of values and/or types which needs to be discarded (OPTIONAL) @return {Object/Array}
[ "Will", "delete", "the", "keys", "of", "the", "object", "which", "are", "set", "to", "null", "undefined", "or", "empty", "string" ]
ebfad9301e6588796abb4f08a44fb3ab4b9af823
https://github.com/jigarjain/object-clean/blob/ebfad9301e6588796abb4f08a44fb3ab4b9af823/index.js#L11-L80
52,214
byron-dupreez/rcc-redis-mock-adapter
rcc-redis-mock-adapter.js
createClient
function createClient(redisClientOptions) { const client = redis.createClient(redisClientOptions); if (!client._options) { client._options = redisClientOptions; } return client; }
javascript
function createClient(redisClientOptions) { const client = redis.createClient(redisClientOptions); if (!client._options) { client._options = redisClientOptions; } return client; }
[ "function", "createClient", "(", "redisClientOptions", ")", "{", "const", "client", "=", "redis", ".", "createClient", "(", "redisClientOptions", ")", ";", "if", "(", "!", "client", ".", "_options", ")", "{", "client", ".", "_options", "=", "redisClientOptions", ";", "}", "return", "client", ";", "}" ]
Creates a new RedisClient instance. @param {RedisClientOptions|undefined} [redisClientOptions] - the options to use to construct the new RedisClient instance @return {RedisClient} returns the new RedisClient instance
[ "Creates", "a", "new", "RedisClient", "instance", "." ]
30297a11c2319b215f7826a39fc61a9d95ed810f
https://github.com/byron-dupreez/rcc-redis-mock-adapter/blob/30297a11c2319b215f7826a39fc61a9d95ed810f/rcc-redis-mock-adapter.js#L100-L106
52,215
alexcu/node-pact-publisher
lib/pact-publisher.js
PactPublisher
function PactPublisher (configOrVersion, brokerBaseUrl, pacts) { var _version, _brokerBaseUrl, _pacts; if (!_.contains(['object', 'string'], typeof configOrVersion)) { throw new TypeError('Invalid first parameter provided constructing Pact Publisher. Expected a config object or version string for first parameter.'); } _version = configOrVersion.appVersion || configOrVersion; _brokerBaseUrl = configOrVersion.brokerBaseUrl || brokerBaseUrl; _pacts = configOrVersion.pacts || pacts; _logging = _.isBoolean(configOrVersion.logging) ? configOrVersion.logging : true; if (!_.isString(_version)) { throw new Error("Expected a string for version number parameter."); } if (!_.isString(_brokerBaseUrl)) { throw new Error("Expected a string for broker base URL parameter."); } if (_pacts !== undefined && !(_.isString(_pacts) || _.isArray(_pacts))) { throw new Error("Expected a string or array for pacts parameter."); } this._appVersion = _version; this._pactBrokerBaseUrl = _brokerBaseUrl; this._pactUrl = "{pactBaseUrl}/pacts/provider/{provider}/consumer/{consumer}/version/{version}".replace("{pactBaseUrl}", this._pactBrokerBaseUrl).replace('{version}', this._appVersion); this._logging = _logging; if (_.isString(_pacts)) { if (!fs.existsSync(_pacts)) { throw new Error("Pact directory " + _pacts + " does not exist"); } this._enqueuedPactFiles = fs.readdirSync(_pacts).filter(function (file) { return path.extname(file) === '.json'; }).map(function (file) { return _pacts + '/' + file; }); } else if (_.isArray(_pacts)) { this._enqueuedPactFiles = _pacts; } else { this._enqueuedPactFiles = []; } }
javascript
function PactPublisher (configOrVersion, brokerBaseUrl, pacts) { var _version, _brokerBaseUrl, _pacts; if (!_.contains(['object', 'string'], typeof configOrVersion)) { throw new TypeError('Invalid first parameter provided constructing Pact Publisher. Expected a config object or version string for first parameter.'); } _version = configOrVersion.appVersion || configOrVersion; _brokerBaseUrl = configOrVersion.brokerBaseUrl || brokerBaseUrl; _pacts = configOrVersion.pacts || pacts; _logging = _.isBoolean(configOrVersion.logging) ? configOrVersion.logging : true; if (!_.isString(_version)) { throw new Error("Expected a string for version number parameter."); } if (!_.isString(_brokerBaseUrl)) { throw new Error("Expected a string for broker base URL parameter."); } if (_pacts !== undefined && !(_.isString(_pacts) || _.isArray(_pacts))) { throw new Error("Expected a string or array for pacts parameter."); } this._appVersion = _version; this._pactBrokerBaseUrl = _brokerBaseUrl; this._pactUrl = "{pactBaseUrl}/pacts/provider/{provider}/consumer/{consumer}/version/{version}".replace("{pactBaseUrl}", this._pactBrokerBaseUrl).replace('{version}', this._appVersion); this._logging = _logging; if (_.isString(_pacts)) { if (!fs.existsSync(_pacts)) { throw new Error("Pact directory " + _pacts + " does not exist"); } this._enqueuedPactFiles = fs.readdirSync(_pacts).filter(function (file) { return path.extname(file) === '.json'; }).map(function (file) { return _pacts + '/' + file; }); } else if (_.isArray(_pacts)) { this._enqueuedPactFiles = _pacts; } else { this._enqueuedPactFiles = []; } }
[ "function", "PactPublisher", "(", "configOrVersion", ",", "brokerBaseUrl", ",", "pacts", ")", "{", "var", "_version", ",", "_brokerBaseUrl", ",", "_pacts", ";", "if", "(", "!", "_", ".", "contains", "(", "[", "'object'", ",", "'string'", "]", ",", "typeof", "configOrVersion", ")", ")", "{", "throw", "new", "TypeError", "(", "'Invalid first parameter provided constructing Pact Publisher. Expected a config object or version string for first parameter.'", ")", ";", "}", "_version", "=", "configOrVersion", ".", "appVersion", "||", "configOrVersion", ";", "_brokerBaseUrl", "=", "configOrVersion", ".", "brokerBaseUrl", "||", "brokerBaseUrl", ";", "_pacts", "=", "configOrVersion", ".", "pacts", "||", "pacts", ";", "_logging", "=", "_", ".", "isBoolean", "(", "configOrVersion", ".", "logging", ")", "?", "configOrVersion", ".", "logging", ":", "true", ";", "if", "(", "!", "_", ".", "isString", "(", "_version", ")", ")", "{", "throw", "new", "Error", "(", "\"Expected a string for version number parameter.\"", ")", ";", "}", "if", "(", "!", "_", ".", "isString", "(", "_brokerBaseUrl", ")", ")", "{", "throw", "new", "Error", "(", "\"Expected a string for broker base URL parameter.\"", ")", ";", "}", "if", "(", "_pacts", "!==", "undefined", "&&", "!", "(", "_", ".", "isString", "(", "_pacts", ")", "||", "_", ".", "isArray", "(", "_pacts", ")", ")", ")", "{", "throw", "new", "Error", "(", "\"Expected a string or array for pacts parameter.\"", ")", ";", "}", "this", ".", "_appVersion", "=", "_version", ";", "this", ".", "_pactBrokerBaseUrl", "=", "_brokerBaseUrl", ";", "this", ".", "_pactUrl", "=", "\"{pactBaseUrl}/pacts/provider/{provider}/consumer/{consumer}/version/{version}\"", ".", "replace", "(", "\"{pactBaseUrl}\"", ",", "this", ".", "_pactBrokerBaseUrl", ")", ".", "replace", "(", "'{version}'", ",", "this", ".", "_appVersion", ")", ";", "this", ".", "_logging", "=", "_logging", ";", "if", "(", "_", ".", "isString", "(", "_pacts", ")", ")", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "_pacts", ")", ")", "{", "throw", "new", "Error", "(", "\"Pact directory \"", "+", "_pacts", "+", "\" does not exist\"", ")", ";", "}", "this", ".", "_enqueuedPactFiles", "=", "fs", ".", "readdirSync", "(", "_pacts", ")", ".", "filter", "(", "function", "(", "file", ")", "{", "return", "path", ".", "extname", "(", "file", ")", "===", "'.json'", ";", "}", ")", ".", "map", "(", "function", "(", "file", ")", "{", "return", "_pacts", "+", "'/'", "+", "file", ";", "}", ")", ";", "}", "else", "if", "(", "_", ".", "isArray", "(", "_pacts", ")", ")", "{", "this", ".", "_enqueuedPactFiles", "=", "_pacts", ";", "}", "else", "{", "this", ".", "_enqueuedPactFiles", "=", "[", "]", ";", "}", "}" ]
A pact publisher @param {Object|String} configOrVersion Config object or version number. If config object is provided, it's just an object containing: - {String} appVersion - {String} brokerBaseUrl - {Array|String} pact - {Boolean} logging (if set to false, no logs will be output) @param {String} brokerBaseUrl Base url of the remote pact broker. @param {Array|String} pacts Where pact contracts are located. Optional parameter. If array is provided, then it's expected that this will contain absolute paths of every pact JSON file. If string then it's expected that this is a directory containing pact JSON contracts and will publish every JSON file in that directory.
[ "A", "pact", "publisher" ]
b87bf328e1699409c09680d182505e18e0e397e0
https://github.com/alexcu/node-pact-publisher/blob/b87bf328e1699409c09680d182505e18e0e397e0/lib/pact-publisher.js#L36-L72
52,216
tolokoban/ToloFrameWork
ker/mod/wdg.input.js
function(opts) { Widget.call(this); var input = Widget.tag("input"); this._input = input; var that = this; this.addClass("wdg-input"); if (typeof opts !== 'object') opts = {}; if (typeof opts.type !== 'string') opts.type = 'text'; input.attr("type", opts.type); if (typeof opts.placeholder === 'string') { input.attr("placeholder", opts.placeholder); } if (typeof opts.size !== 'undefined') { opts.size = parseInt(opts.size) || 8; input.attr("size", opts.size); } if (typeof opts.width !== 'undefined') { input.css("width", opts.width); } var onValid = opts.onValid; if (typeof onValid === 'object' && typeof onValid.enabled === 'function') { opts.onValid = function(v) { onValid.enabled(v); }; } else if (typeof onValid !== 'function') opts.onValid = null; if (typeof opts.validator === 'object') { var rx = opts.validator; opts.validator = function(v) { return rx.test(v); }; } this._valid = 0; if (typeof opts.validator === 'function') { input.addEvent( "keyup", function() { opts.validator.call(this); } ); } input.addEvent( "keyup", function() { that.fireChange(); } ); if (typeof opts.onEnter === 'object' && typeof opts.onEnter.fire === 'function') { var onEnter = opts.onEnter; this.Enter(function() { onEnter.fire(); }); } input.addEvent( "keyup", function(evt) { if (that._valid > -1 && evt.keyCode == 13) { // On rend l'événement asynchrone pour éviter les // problèmes de clavier virtuel qui reste affiché. window.setTimeout( function() { that.fireEnter(); } ); } else { that.validate(); } } ); if (typeof opts.value !== 'string') { opts.value = ""; } input.addEvent( "focus", function() { that.selectAll(); } ); this._opts = opts; this.val(opts.value); if (typeof opts.label !== 'undefined') { var label = Widget.div("label").text(opts.label).attr("title", opts.label); this.append(label); } this.append(input); }
javascript
function(opts) { Widget.call(this); var input = Widget.tag("input"); this._input = input; var that = this; this.addClass("wdg-input"); if (typeof opts !== 'object') opts = {}; if (typeof opts.type !== 'string') opts.type = 'text'; input.attr("type", opts.type); if (typeof opts.placeholder === 'string') { input.attr("placeholder", opts.placeholder); } if (typeof opts.size !== 'undefined') { opts.size = parseInt(opts.size) || 8; input.attr("size", opts.size); } if (typeof opts.width !== 'undefined') { input.css("width", opts.width); } var onValid = opts.onValid; if (typeof onValid === 'object' && typeof onValid.enabled === 'function') { opts.onValid = function(v) { onValid.enabled(v); }; } else if (typeof onValid !== 'function') opts.onValid = null; if (typeof opts.validator === 'object') { var rx = opts.validator; opts.validator = function(v) { return rx.test(v); }; } this._valid = 0; if (typeof opts.validator === 'function') { input.addEvent( "keyup", function() { opts.validator.call(this); } ); } input.addEvent( "keyup", function() { that.fireChange(); } ); if (typeof opts.onEnter === 'object' && typeof opts.onEnter.fire === 'function') { var onEnter = opts.onEnter; this.Enter(function() { onEnter.fire(); }); } input.addEvent( "keyup", function(evt) { if (that._valid > -1 && evt.keyCode == 13) { // On rend l'événement asynchrone pour éviter les // problèmes de clavier virtuel qui reste affiché. window.setTimeout( function() { that.fireEnter(); } ); } else { that.validate(); } } ); if (typeof opts.value !== 'string') { opts.value = ""; } input.addEvent( "focus", function() { that.selectAll(); } ); this._opts = opts; this.val(opts.value); if (typeof opts.label !== 'undefined') { var label = Widget.div("label").text(opts.label).attr("title", opts.label); this.append(label); } this.append(input); }
[ "function", "(", "opts", ")", "{", "Widget", ".", "call", "(", "this", ")", ";", "var", "input", "=", "Widget", ".", "tag", "(", "\"input\"", ")", ";", "this", ".", "_input", "=", "input", ";", "var", "that", "=", "this", ";", "this", ".", "addClass", "(", "\"wdg-input\"", ")", ";", "if", "(", "typeof", "opts", "!==", "'object'", ")", "opts", "=", "{", "}", ";", "if", "(", "typeof", "opts", ".", "type", "!==", "'string'", ")", "opts", ".", "type", "=", "'text'", ";", "input", ".", "attr", "(", "\"type\"", ",", "opts", ".", "type", ")", ";", "if", "(", "typeof", "opts", ".", "placeholder", "===", "'string'", ")", "{", "input", ".", "attr", "(", "\"placeholder\"", ",", "opts", ".", "placeholder", ")", ";", "}", "if", "(", "typeof", "opts", ".", "size", "!==", "'undefined'", ")", "{", "opts", ".", "size", "=", "parseInt", "(", "opts", ".", "size", ")", "||", "8", ";", "input", ".", "attr", "(", "\"size\"", ",", "opts", ".", "size", ")", ";", "}", "if", "(", "typeof", "opts", ".", "width", "!==", "'undefined'", ")", "{", "input", ".", "css", "(", "\"width\"", ",", "opts", ".", "width", ")", ";", "}", "var", "onValid", "=", "opts", ".", "onValid", ";", "if", "(", "typeof", "onValid", "===", "'object'", "&&", "typeof", "onValid", ".", "enabled", "===", "'function'", ")", "{", "opts", ".", "onValid", "=", "function", "(", "v", ")", "{", "onValid", ".", "enabled", "(", "v", ")", ";", "}", ";", "}", "else", "if", "(", "typeof", "onValid", "!==", "'function'", ")", "opts", ".", "onValid", "=", "null", ";", "if", "(", "typeof", "opts", ".", "validator", "===", "'object'", ")", "{", "var", "rx", "=", "opts", ".", "validator", ";", "opts", ".", "validator", "=", "function", "(", "v", ")", "{", "return", "rx", ".", "test", "(", "v", ")", ";", "}", ";", "}", "this", ".", "_valid", "=", "0", ";", "if", "(", "typeof", "opts", ".", "validator", "===", "'function'", ")", "{", "input", ".", "addEvent", "(", "\"keyup\"", ",", "function", "(", ")", "{", "opts", ".", "validator", ".", "call", "(", "this", ")", ";", "}", ")", ";", "}", "input", ".", "addEvent", "(", "\"keyup\"", ",", "function", "(", ")", "{", "that", ".", "fireChange", "(", ")", ";", "}", ")", ";", "if", "(", "typeof", "opts", ".", "onEnter", "===", "'object'", "&&", "typeof", "opts", ".", "onEnter", ".", "fire", "===", "'function'", ")", "{", "var", "onEnter", "=", "opts", ".", "onEnter", ";", "this", ".", "Enter", "(", "function", "(", ")", "{", "onEnter", ".", "fire", "(", ")", ";", "}", ")", ";", "}", "input", ".", "addEvent", "(", "\"keyup\"", ",", "function", "(", "evt", ")", "{", "if", "(", "that", ".", "_valid", ">", "-", "1", "&&", "evt", ".", "keyCode", "==", "13", ")", "{", "// On rend l'événement asynchrone pour éviter les\r", "// problèmes de clavier virtuel qui reste affiché.\r", "window", ".", "setTimeout", "(", "function", "(", ")", "{", "that", ".", "fireEnter", "(", ")", ";", "}", ")", ";", "}", "else", "{", "that", ".", "validate", "(", ")", ";", "}", "}", ")", ";", "if", "(", "typeof", "opts", ".", "value", "!==", "'string'", ")", "{", "opts", ".", "value", "=", "\"\"", ";", "}", "input", ".", "addEvent", "(", "\"focus\"", ",", "function", "(", ")", "{", "that", ".", "selectAll", "(", ")", ";", "}", ")", ";", "this", ".", "_opts", "=", "opts", ";", "this", ".", "val", "(", "opts", ".", "value", ")", ";", "if", "(", "typeof", "opts", ".", "label", "!==", "'undefined'", ")", "{", "var", "label", "=", "Widget", ".", "div", "(", "\"label\"", ")", ".", "text", "(", "opts", ".", "label", ")", ".", "attr", "(", "\"title\"", ",", "opts", ".", "label", ")", ";", "this", ".", "append", "(", "label", ")", ";", "}", "this", ".", "append", "(", "input", ")", ";", "}" ]
HTML5 text input with many options. @param {string} opts.value Initial value. @param {string} opts.type Input's type. Can be `text`, `password`, ... @param {string} opts.name The name can be used by the browser to give a help combo. @param {string} opts.placeholder Text to display when input is empty. @param {function|regexp} opts.validator function to check the validity of this input. Takes the input value as argument and returns a boolean. `onEnter` is not fired until input is valid. You can use a RegExp instead of a function to check validity. @param {function|object} opts.onEnter function to call when user hits `enter` key. `function(this)`. It can be an object with a function called `fire()`. @param {function|object} opts.onValid function to call when validator has been called. `function(validity, this)`. It can be an object with a function `enabled({boolean})`. For instance a `wdg.Button`. @example var Input = require("wdg.input"); var opts = { placeholder: 'email address'; validator: /[^@]+@([^@\.]+\.)*[^@\.]+/, onEnter: function(wdg) { console.log("Enter has been hitten!"); }, onValid: function(validity, wdg) { console.log("Validity: ", validity); } } var instance = new Input(opts); @example var I = require("wdg.input").create; var btnNext = B(_("next")).Tap( function() { alert("Youpi!"); } ); var login = I( { type: "email", name: "email", placeholder: _("email"), validator: /^[^@]+@[^@]+$/, onEnter: btnNext, onValid: btnNext } ); @class Input
[ "HTML5", "text", "input", "with", "many", "options", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/wdg.input.js#L55-L142
52,217
tombenke/proper
bin/cli.js
function( fileName ) { // console.log('Read configuration from ' + fileName); var pathSep = require('path').sep; var inFileName = process.cwd() + pathSep + fileName; var config = require( inFileName ); // TODO: validate config for ( var procs in config ) { if ( config.hasOwnProperty(procs) ) { config[procs].forEach(function(proc){ if ( proc.hasOwnProperty('fileName') ) { proc.fileName = process.cwd() + pathSep + proc.fileName; } }); } } return config; }
javascript
function( fileName ) { // console.log('Read configuration from ' + fileName); var pathSep = require('path').sep; var inFileName = process.cwd() + pathSep + fileName; var config = require( inFileName ); // TODO: validate config for ( var procs in config ) { if ( config.hasOwnProperty(procs) ) { config[procs].forEach(function(proc){ if ( proc.hasOwnProperty('fileName') ) { proc.fileName = process.cwd() + pathSep + proc.fileName; } }); } } return config; }
[ "function", "(", "fileName", ")", "{", "// console.log('Read configuration from ' + fileName);", "var", "pathSep", "=", "require", "(", "'path'", ")", ".", "sep", ";", "var", "inFileName", "=", "process", ".", "cwd", "(", ")", "+", "pathSep", "+", "fileName", ";", "var", "config", "=", "require", "(", "inFileName", ")", ";", "// TODO: validate config", "for", "(", "var", "procs", "in", "config", ")", "{", "if", "(", "config", ".", "hasOwnProperty", "(", "procs", ")", ")", "{", "config", "[", "procs", "]", ".", "forEach", "(", "function", "(", "proc", ")", "{", "if", "(", "proc", ".", "hasOwnProperty", "(", "'fileName'", ")", ")", "{", "proc", ".", "fileName", "=", "process", ".", "cwd", "(", ")", "+", "pathSep", "+", "proc", ".", "fileName", ";", "}", "}", ")", ";", "}", "}", "return", "config", ";", "}" ]
Read the config file @param {string} fileName The name of the config file @return {Object} The configuration object
[ "Read", "the", "config", "file" ]
3f766df6ec7dbb0c4d136373a94002d00d340a48
https://github.com/tombenke/proper/blob/3f766df6ec7dbb0c4d136373a94002d00d340a48/bin/cli.js#L19-L38
52,218
redisjs/jsr-persistence
lib/index.js
saveSync
function saveSync(store, conf) { try { this.save(store, conf); }catch(e) { log.warning('failed to save rdb snapshot: %s', e.message); } }
javascript
function saveSync(store, conf) { try { this.save(store, conf); }catch(e) { log.warning('failed to save rdb snapshot: %s', e.message); } }
[ "function", "saveSync", "(", "store", ",", "conf", ")", "{", "try", "{", "this", ".", "save", "(", "store", ",", "conf", ")", ";", "}", "catch", "(", "e", ")", "{", "log", ".", "warning", "(", "'failed to save rdb snapshot: %s'", ",", "e", ".", "message", ")", ";", "}", "}" ]
Synchronous save.
[ "Synchronous", "save", "." ]
77f3fc84ea7cbdb9f41a4dfa7ee1d89be61f7510
https://github.com/redisjs/jsr-persistence/blob/77f3fc84ea7cbdb9f41a4dfa7ee1d89be61f7510/lib/index.js#L20-L26
52,219
pkrll/Salvation
src/salvation.js
function () { var emptyFunction = new RegExp(/(\{\s\})|(\{\})/), publicMethods = {}; for (property in this.settings) { if (typeof this.settings[property] == 'function' && typeof this[property] == 'function') { var method = this.settings[property]; if (emptyFunction.test(method)) { publicMethods[property] = this[property]; } else { var defaultMethodName = this.createDefaultMethodName(property); publicMethods[property] = this.settings[property]; publicMethods[defaultMethodName] = this[property]; } } } publicMethods.stylings = this.stylings; return publicMethods; }
javascript
function () { var emptyFunction = new RegExp(/(\{\s\})|(\{\})/), publicMethods = {}; for (property in this.settings) { if (typeof this.settings[property] == 'function' && typeof this[property] == 'function') { var method = this.settings[property]; if (emptyFunction.test(method)) { publicMethods[property] = this[property]; } else { var defaultMethodName = this.createDefaultMethodName(property); publicMethods[property] = this.settings[property]; publicMethods[defaultMethodName] = this[property]; } } } publicMethods.stylings = this.stylings; return publicMethods; }
[ "function", "(", ")", "{", "var", "emptyFunction", "=", "new", "RegExp", "(", "/", "(\\{\\s\\})|(\\{\\})", "/", ")", ",", "publicMethods", "=", "{", "}", ";", "for", "(", "property", "in", "this", ".", "settings", ")", "{", "if", "(", "typeof", "this", ".", "settings", "[", "property", "]", "==", "'function'", "&&", "typeof", "this", "[", "property", "]", "==", "'function'", ")", "{", "var", "method", "=", "this", ".", "settings", "[", "property", "]", ";", "if", "(", "emptyFunction", ".", "test", "(", "method", ")", ")", "{", "publicMethods", "[", "property", "]", "=", "this", "[", "property", "]", ";", "}", "else", "{", "var", "defaultMethodName", "=", "this", ".", "createDefaultMethodName", "(", "property", ")", ";", "publicMethods", "[", "property", "]", "=", "this", ".", "settings", "[", "property", "]", ";", "publicMethods", "[", "defaultMethodName", "]", "=", "this", "[", "property", "]", ";", "}", "}", "}", "publicMethods", ".", "stylings", "=", "this", ".", "stylings", ";", "return", "publicMethods", ";", "}" ]
Creates an object of pseudo-public methods that will be returned when the plugin is initialized. @returns Object
[ "Creates", "an", "object", "of", "pseudo", "-", "public", "methods", "that", "will", "be", "returned", "when", "the", "plugin", "is", "initialized", "." ]
143e8a69d1b81b409b4aeff106f7fba21cf14645
https://github.com/pkrll/Salvation/blob/143e8a69d1b81b409b4aeff106f7fba21cf14645/src/salvation.js#L97-L117
52,220
pkrll/Salvation
src/salvation.js
function(name) { if (/[A-Z]/.test(name.charAt(0))) return "default" + name; var firstLetter = name.charAt(0); return "default" + firstLetter.toUpperCase() + name.substring(1); }
javascript
function(name) { if (/[A-Z]/.test(name.charAt(0))) return "default" + name; var firstLetter = name.charAt(0); return "default" + firstLetter.toUpperCase() + name.substring(1); }
[ "function", "(", "name", ")", "{", "if", "(", "/", "[A-Z]", "/", ".", "test", "(", "name", ".", "charAt", "(", "0", ")", ")", ")", "return", "\"default\"", "+", "name", ";", "var", "firstLetter", "=", "name", ".", "charAt", "(", "0", ")", ";", "return", "\"default\"", "+", "firstLetter", ".", "toUpperCase", "(", ")", "+", "name", ".", "substring", "(", "1", ")", ";", "}" ]
Prepends method name with string "default", using camelCase. @param string Name to manipulate @returns string
[ "Prepends", "method", "name", "with", "string", "default", "using", "camelCase", "." ]
143e8a69d1b81b409b4aeff106f7fba21cf14645
https://github.com/pkrll/Salvation/blob/143e8a69d1b81b409b4aeff106f7fba21cf14645/src/salvation.js#L125-L130
52,221
pkrll/Salvation
src/salvation.js
function (primary, secondary) { var primary = primary || {}; for (var property in secondary) if (secondary.hasOwnProperty(property)) primary[property] = secondary[property]; return primary; }
javascript
function (primary, secondary) { var primary = primary || {}; for (var property in secondary) if (secondary.hasOwnProperty(property)) primary[property] = secondary[property]; return primary; }
[ "function", "(", "primary", ",", "secondary", ")", "{", "var", "primary", "=", "primary", "||", "{", "}", ";", "for", "(", "var", "property", "in", "secondary", ")", "if", "(", "secondary", ".", "hasOwnProperty", "(", "property", ")", ")", "primary", "[", "property", "]", "=", "secondary", "[", "property", "]", ";", "return", "primary", ";", "}" ]
Extend a given object with another object. @param object Object that is to be extended @param object Object with properties to add to first object @returns object
[ "Extend", "a", "given", "object", "with", "another", "object", "." ]
143e8a69d1b81b409b4aeff106f7fba21cf14645
https://github.com/pkrll/Salvation/blob/143e8a69d1b81b409b4aeff106f7fba21cf14645/src/salvation.js#L149-L155
52,222
pkrll/Salvation
src/salvation.js
function (event) { var self = this; if (this.invalidElements.length > 0) event.preventDefault(); // Even if the invalidElements count // does not indicate any invalidated // elements, the plugin should make // sure that there are none that did // somehow bypass the control. This // is an issue mainly when submitting // without editing a form. for (var validationType in self.validate) { var invalidFields = self.getElementsByPattern(self.validate[validationType], self.patterns[validationType], validationType); if (invalidFields.length > 0) { this.invalidElements = invalidFields; event.preventDefault(); // The warning method self.publicInterface.onInvalidation(invalidFields, this.legends[validationType]); } } }
javascript
function (event) { var self = this; if (this.invalidElements.length > 0) event.preventDefault(); // Even if the invalidElements count // does not indicate any invalidated // elements, the plugin should make // sure that there are none that did // somehow bypass the control. This // is an issue mainly when submitting // without editing a form. for (var validationType in self.validate) { var invalidFields = self.getElementsByPattern(self.validate[validationType], self.patterns[validationType], validationType); if (invalidFields.length > 0) { this.invalidElements = invalidFields; event.preventDefault(); // The warning method self.publicInterface.onInvalidation(invalidFields, this.legends[validationType]); } } }
[ "function", "(", "event", ")", "{", "var", "self", "=", "this", ";", "if", "(", "this", ".", "invalidElements", ".", "length", ">", "0", ")", "event", ".", "preventDefault", "(", ")", ";", "// Even if the invalidElements count", "// does not indicate any invalidated", "// elements, the plugin should make", "// sure that there are none that did", "// somehow bypass the control. This", "// is an issue mainly when submitting", "// without editing a form.", "for", "(", "var", "validationType", "in", "self", ".", "validate", ")", "{", "var", "invalidFields", "=", "self", ".", "getElementsByPattern", "(", "self", ".", "validate", "[", "validationType", "]", ",", "self", ".", "patterns", "[", "validationType", "]", ",", "validationType", ")", ";", "if", "(", "invalidFields", ".", "length", ">", "0", ")", "{", "this", ".", "invalidElements", "=", "invalidFields", ";", "event", ".", "preventDefault", "(", ")", ";", "// The warning method", "self", ".", "publicInterface", ".", "onInvalidation", "(", "invalidFields", ",", "this", ".", "legends", "[", "validationType", "]", ")", ";", "}", "}", "}" ]
Callback function for event submit. Validates elements, but will first check if the global "formInvalid"- variable is set, before validation. @param Event
[ "Callback", "function", "for", "event", "submit", ".", "Validates", "elements", "but", "will", "first", "check", "if", "the", "global", "formInvalid", "-", "variable", "is", "set", "before", "validation", "." ]
143e8a69d1b81b409b4aeff106f7fba21cf14645
https://github.com/pkrll/Salvation/blob/143e8a69d1b81b409b4aeff106f7fba21cf14645/src/salvation.js#L164-L184
52,223
pkrll/Salvation
src/salvation.js
function(event) { var target = event.target; if (this.checkElementByPattern(target)) { if (this.invalidElements.indexOf(target) > -1) this.invalidElements.splice(this.invalidElements.indexOf(target), 1); this.publicInterface.onValidation([target]); } else { if (this.invalidElements.indexOf(target) === -1) this.invalidElements.push(target); var legend = this.legends[this.currentValidationType] || this.legends.unknown; this.publicInterface.onInvalidation([target], legend); } }
javascript
function(event) { var target = event.target; if (this.checkElementByPattern(target)) { if (this.invalidElements.indexOf(target) > -1) this.invalidElements.splice(this.invalidElements.indexOf(target), 1); this.publicInterface.onValidation([target]); } else { if (this.invalidElements.indexOf(target) === -1) this.invalidElements.push(target); var legend = this.legends[this.currentValidationType] || this.legends.unknown; this.publicInterface.onInvalidation([target], legend); } }
[ "function", "(", "event", ")", "{", "var", "target", "=", "event", ".", "target", ";", "if", "(", "this", ".", "checkElementByPattern", "(", "target", ")", ")", "{", "if", "(", "this", ".", "invalidElements", ".", "indexOf", "(", "target", ")", ">", "-", "1", ")", "this", ".", "invalidElements", ".", "splice", "(", "this", ".", "invalidElements", ".", "indexOf", "(", "target", ")", ",", "1", ")", ";", "this", ".", "publicInterface", ".", "onValidation", "(", "[", "target", "]", ")", ";", "}", "else", "{", "if", "(", "this", ".", "invalidElements", ".", "indexOf", "(", "target", ")", "===", "-", "1", ")", "this", ".", "invalidElements", ".", "push", "(", "target", ")", ";", "var", "legend", "=", "this", ".", "legends", "[", "this", ".", "currentValidationType", "]", "||", "this", ".", "legends", ".", "unknown", ";", "this", ".", "publicInterface", ".", "onInvalidation", "(", "[", "target", "]", ",", "legend", ")", ";", "}", "}" ]
Callback function for the change event. Validates elements live. @param Event
[ "Callback", "function", "for", "the", "change", "event", ".", "Validates", "elements", "live", "." ]
143e8a69d1b81b409b4aeff106f7fba21cf14645
https://github.com/pkrll/Salvation/blob/143e8a69d1b81b409b4aeff106f7fba21cf14645/src/salvation.js#L191-L203
52,224
pkrll/Salvation
src/salvation.js
function (event) { // Check if the node is a child of the plugin's element. if (event.relatedNode === this.element) { var attributeValues = event.target.getAttribute("data-validate"); if (attributeValues !== null) { attributeValues = this.splitStringByComma(attributeValues); for (var x = 0; x < attributeValues.length; x++) { var key = attributeValues[x]; if (key === undefined || key === null) continue; this.validate[key].push(event.target); } } if (event.target.hasAttribute("data-length") && this.validate["length"].indexOf(event.target) === -1) this.validate["length"].push(event.target); } }
javascript
function (event) { // Check if the node is a child of the plugin's element. if (event.relatedNode === this.element) { var attributeValues = event.target.getAttribute("data-validate"); if (attributeValues !== null) { attributeValues = this.splitStringByComma(attributeValues); for (var x = 0; x < attributeValues.length; x++) { var key = attributeValues[x]; if (key === undefined || key === null) continue; this.validate[key].push(event.target); } } if (event.target.hasAttribute("data-length") && this.validate["length"].indexOf(event.target) === -1) this.validate["length"].push(event.target); } }
[ "function", "(", "event", ")", "{", "// Check if the node is a child of the plugin's element.", "if", "(", "event", ".", "relatedNode", "===", "this", ".", "element", ")", "{", "var", "attributeValues", "=", "event", ".", "target", ".", "getAttribute", "(", "\"data-validate\"", ")", ";", "if", "(", "attributeValues", "!==", "null", ")", "{", "attributeValues", "=", "this", ".", "splitStringByComma", "(", "attributeValues", ")", ";", "for", "(", "var", "x", "=", "0", ";", "x", "<", "attributeValues", ".", "length", ";", "x", "++", ")", "{", "var", "key", "=", "attributeValues", "[", "x", "]", ";", "if", "(", "key", "===", "undefined", "||", "key", "===", "null", ")", "continue", ";", "this", ".", "validate", "[", "key", "]", ".", "push", "(", "event", ".", "target", ")", ";", "}", "}", "if", "(", "event", ".", "target", ".", "hasAttribute", "(", "\"data-length\"", ")", "&&", "this", ".", "validate", "[", "\"length\"", "]", ".", "indexOf", "(", "event", ".", "target", ")", "===", "-", "1", ")", "this", ".", "validate", "[", "\"length\"", "]", ".", "push", "(", "event", ".", "target", ")", ";", "}", "}" ]
Callback for DOMNodeInserted. Adds inserted element to the elements list, if it has the appropriate attributes. @param Event
[ "Callback", "for", "DOMNodeInserted", ".", "Adds", "inserted", "element", "to", "the", "elements", "list", "if", "it", "has", "the", "appropriate", "attributes", "." ]
143e8a69d1b81b409b4aeff106f7fba21cf14645
https://github.com/pkrll/Salvation/blob/143e8a69d1b81b409b4aeff106f7fba21cf14645/src/salvation.js#L212-L229
52,225
pkrll/Salvation
src/salvation.js
function (elements, legend) { var elements = elements || []; for (var i = 0; i < elements.length; i++) { if (elements[i].classList.contains(this.stylings.error) === false) elements[i].classList.add(this.stylings.error); var legend = elements[i].getAttribute("data-label") || legend; var parent = elements[i].parentNode; parent.setAttribute("data-hint", legend); if (i === 0) elements[i].focus(); } }
javascript
function (elements, legend) { var elements = elements || []; for (var i = 0; i < elements.length; i++) { if (elements[i].classList.contains(this.stylings.error) === false) elements[i].classList.add(this.stylings.error); var legend = elements[i].getAttribute("data-label") || legend; var parent = elements[i].parentNode; parent.setAttribute("data-hint", legend); if (i === 0) elements[i].focus(); } }
[ "function", "(", "elements", ",", "legend", ")", "{", "var", "elements", "=", "elements", "||", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "elements", ".", "length", ";", "i", "++", ")", "{", "if", "(", "elements", "[", "i", "]", ".", "classList", ".", "contains", "(", "this", ".", "stylings", ".", "error", ")", "===", "false", ")", "elements", "[", "i", "]", ".", "classList", ".", "add", "(", "this", ".", "stylings", ".", "error", ")", ";", "var", "legend", "=", "elements", "[", "i", "]", ".", "getAttribute", "(", "\"data-label\"", ")", "||", "legend", ";", "var", "parent", "=", "elements", "[", "i", "]", ".", "parentNode", ";", "parent", ".", "setAttribute", "(", "\"data-hint\"", ",", "legend", ")", ";", "if", "(", "i", "===", "0", ")", "elements", "[", "i", "]", ".", "focus", "(", ")", ";", "}", "}" ]
Performs the default invalidation action on invalid elements. @param HTMLFormElement
[ "Performs", "the", "default", "invalidation", "action", "on", "invalid", "elements", "." ]
143e8a69d1b81b409b4aeff106f7fba21cf14645
https://github.com/pkrll/Salvation/blob/143e8a69d1b81b409b4aeff106f7fba21cf14645/src/salvation.js#L236-L247
52,226
pkrll/Salvation
src/salvation.js
function (elements) { var elements = elements || []; for (var i = 0; i < elements.length; i++) { if (elements[i].classList.contains(this.stylings.error)) { elements[i].classList.remove(this.stylings.error); var parent = elements[i].parentNode; parent.removeAttribute("data-hint"); } } }
javascript
function (elements) { var elements = elements || []; for (var i = 0; i < elements.length; i++) { if (elements[i].classList.contains(this.stylings.error)) { elements[i].classList.remove(this.stylings.error); var parent = elements[i].parentNode; parent.removeAttribute("data-hint"); } } }
[ "function", "(", "elements", ")", "{", "var", "elements", "=", "elements", "||", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "elements", ".", "length", ";", "i", "++", ")", "{", "if", "(", "elements", "[", "i", "]", ".", "classList", ".", "contains", "(", "this", ".", "stylings", ".", "error", ")", ")", "{", "elements", "[", "i", "]", ".", "classList", ".", "remove", "(", "this", ".", "stylings", ".", "error", ")", ";", "var", "parent", "=", "elements", "[", "i", "]", ".", "parentNode", ";", "parent", ".", "removeAttribute", "(", "\"data-hint\"", ")", ";", "}", "}", "}" ]
Performs the default validation action on revalidated elements. @param HTMLFormElement
[ "Performs", "the", "default", "validation", "action", "on", "revalidated", "elements", "." ]
143e8a69d1b81b409b4aeff106f7fba21cf14645
https://github.com/pkrll/Salvation/blob/143e8a69d1b81b409b4aeff106f7fba21cf14645/src/salvation.js#L254-L263
52,227
pkrll/Salvation
src/salvation.js
function (elements, attribute, value) { var foundElements = [], value = value || null; for (i = 0; i < elements.length; i++) { // If the value parameter is set, return only the // elements that has the given attribute value. if (value !== null) { if (elements[i].getAttribute(attribute) === value) foundElements.push(elements[i]); } else { if (elements[i].getAttribute(attribute) !== null) foundElements.push(elements[i]); } } return foundElements; }
javascript
function (elements, attribute, value) { var foundElements = [], value = value || null; for (i = 0; i < elements.length; i++) { // If the value parameter is set, return only the // elements that has the given attribute value. if (value !== null) { if (elements[i].getAttribute(attribute) === value) foundElements.push(elements[i]); } else { if (elements[i].getAttribute(attribute) !== null) foundElements.push(elements[i]); } } return foundElements; }
[ "function", "(", "elements", ",", "attribute", ",", "value", ")", "{", "var", "foundElements", "=", "[", "]", ",", "value", "=", "value", "||", "null", ";", "for", "(", "i", "=", "0", ";", "i", "<", "elements", ".", "length", ";", "i", "++", ")", "{", "// If the value parameter is set, return only the", "// elements that has the given attribute value.", "if", "(", "value", "!==", "null", ")", "{", "if", "(", "elements", "[", "i", "]", ".", "getAttribute", "(", "attribute", ")", "===", "value", ")", "foundElements", ".", "push", "(", "elements", "[", "i", "]", ")", ";", "}", "else", "{", "if", "(", "elements", "[", "i", "]", ".", "getAttribute", "(", "attribute", ")", "!==", "null", ")", "foundElements", ".", "push", "(", "elements", "[", "i", "]", ")", ";", "}", "}", "return", "foundElements", ";", "}" ]
Find elements by attribute name, with option to also go by the attribute value. @param elements Array of elements to search @param string Value to find @returns array List of elements found
[ "Find", "elements", "by", "attribute", "name", "with", "option", "to", "also", "go", "by", "the", "attribute", "value", "." ]
143e8a69d1b81b409b4aeff106f7fba21cf14645
https://github.com/pkrll/Salvation/blob/143e8a69d1b81b409b4aeff106f7fba21cf14645/src/salvation.js#L284-L299
52,228
pkrll/Salvation
src/salvation.js
function (elements, attribute) { var foundElements = {}; for (i = 0; i < elements.length; i++) { var attributeValues = elements[i].getAttribute(attribute); if (attributeValues === undefined || attributeValues === null) continue; // Elements can have multiple attribute values, // the string should be delimited by a comma. attributeValues = this.splitStringByComma(attributeValues); for (var x = 0; x < attributeValues.length; x++) { // The attribute value will also serve as the // key in the object that will be returned. var key = attributeValues[x]; if (key === undefined || key === null) continue; // The key must exist in the element as an // array, otherwise push() will fail. if (foundElements[key] === undefined || foundElements[key].constructor !== Array) foundElements[key] = []; foundElements[key].push(elements[i]); } } return foundElements; }
javascript
function (elements, attribute) { var foundElements = {}; for (i = 0; i < elements.length; i++) { var attributeValues = elements[i].getAttribute(attribute); if (attributeValues === undefined || attributeValues === null) continue; // Elements can have multiple attribute values, // the string should be delimited by a comma. attributeValues = this.splitStringByComma(attributeValues); for (var x = 0; x < attributeValues.length; x++) { // The attribute value will also serve as the // key in the object that will be returned. var key = attributeValues[x]; if (key === undefined || key === null) continue; // The key must exist in the element as an // array, otherwise push() will fail. if (foundElements[key] === undefined || foundElements[key].constructor !== Array) foundElements[key] = []; foundElements[key].push(elements[i]); } } return foundElements; }
[ "function", "(", "elements", ",", "attribute", ")", "{", "var", "foundElements", "=", "{", "}", ";", "for", "(", "i", "=", "0", ";", "i", "<", "elements", ".", "length", ";", "i", "++", ")", "{", "var", "attributeValues", "=", "elements", "[", "i", "]", ".", "getAttribute", "(", "attribute", ")", ";", "if", "(", "attributeValues", "===", "undefined", "||", "attributeValues", "===", "null", ")", "continue", ";", "// Elements can have multiple attribute values,", "// the string should be delimited by a comma.", "attributeValues", "=", "this", ".", "splitStringByComma", "(", "attributeValues", ")", ";", "for", "(", "var", "x", "=", "0", ";", "x", "<", "attributeValues", ".", "length", ";", "x", "++", ")", "{", "// The attribute value will also serve as the", "// key in the object that will be returned.", "var", "key", "=", "attributeValues", "[", "x", "]", ";", "if", "(", "key", "===", "undefined", "||", "key", "===", "null", ")", "continue", ";", "// The key must exist in the element as an", "// array, otherwise push() will fail.", "if", "(", "foundElements", "[", "key", "]", "===", "undefined", "||", "foundElements", "[", "key", "]", ".", "constructor", "!==", "Array", ")", "foundElements", "[", "key", "]", "=", "[", "]", ";", "foundElements", "[", "key", "]", ".", "push", "(", "elements", "[", "i", "]", ")", ";", "}", "}", "return", "foundElements", ";", "}" ]
Find elements by attribute name, and return them as an object with attribute value as key. This method will sort elements in different objects, depending on attributes. An element with multiple attribute values will be added to multiple objects. @param elements Array of elements to search @param string Attribute to find @returns object List of elements found
[ "Find", "elements", "by", "attribute", "name", "and", "return", "them", "as", "an", "object", "with", "attribute", "value", "as", "key", ".", "This", "method", "will", "sort", "elements", "in", "different", "objects", "depending", "on", "attributes", ".", "An", "element", "with", "multiple", "attribute", "values", "will", "be", "added", "to", "multiple", "objects", "." ]
143e8a69d1b81b409b4aeff106f7fba21cf14645
https://github.com/pkrll/Salvation/blob/143e8a69d1b81b409b4aeff106f7fba21cf14645/src/salvation.js#L340-L364
52,229
pkrll/Salvation
src/salvation.js
function (element) { // Begin with checking the validate var elementAsArray = [ element ], validationType = element.getAttribute("data-validate") || null; invalidElement = []; if (validationType !== null) { validationType = this.splitStringByComma(validationType); for (var i = 0; i < validationType.length; i++) { invalidElement = this.getElementsByPattern(elementAsArray, this.patterns[validationType[i]], validationType[i]); if (invalidElement.length > 0) { this.currentValidationType = validationType[i]; return false; } } } // As data-validate="length" has already been checked, // only check the elements with data-length set. if (element.getAttribute("data-length") === null || validationType !== null && validationType.indexOf("length") !== -1) return true; validationType = "length"; invalidElement = this.getElementsByPattern(elementAsArray, this.patterns[validationType], validationType); if (invalidElement.length > 0) return false; return true; }
javascript
function (element) { // Begin with checking the validate var elementAsArray = [ element ], validationType = element.getAttribute("data-validate") || null; invalidElement = []; if (validationType !== null) { validationType = this.splitStringByComma(validationType); for (var i = 0; i < validationType.length; i++) { invalidElement = this.getElementsByPattern(elementAsArray, this.patterns[validationType[i]], validationType[i]); if (invalidElement.length > 0) { this.currentValidationType = validationType[i]; return false; } } } // As data-validate="length" has already been checked, // only check the elements with data-length set. if (element.getAttribute("data-length") === null || validationType !== null && validationType.indexOf("length") !== -1) return true; validationType = "length"; invalidElement = this.getElementsByPattern(elementAsArray, this.patterns[validationType], validationType); if (invalidElement.length > 0) return false; return true; }
[ "function", "(", "element", ")", "{", "// Begin with checking the validate", "var", "elementAsArray", "=", "[", "element", "]", ",", "validationType", "=", "element", ".", "getAttribute", "(", "\"data-validate\"", ")", "||", "null", ";", "invalidElement", "=", "[", "]", ";", "if", "(", "validationType", "!==", "null", ")", "{", "validationType", "=", "this", ".", "splitStringByComma", "(", "validationType", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "validationType", ".", "length", ";", "i", "++", ")", "{", "invalidElement", "=", "this", ".", "getElementsByPattern", "(", "elementAsArray", ",", "this", ".", "patterns", "[", "validationType", "[", "i", "]", "]", ",", "validationType", "[", "i", "]", ")", ";", "if", "(", "invalidElement", ".", "length", ">", "0", ")", "{", "this", ".", "currentValidationType", "=", "validationType", "[", "i", "]", ";", "return", "false", ";", "}", "}", "}", "// As data-validate=\"length\" has already been checked,", "// only check the elements with data-length set.", "if", "(", "element", ".", "getAttribute", "(", "\"data-length\"", ")", "===", "null", "||", "validationType", "!==", "null", "&&", "validationType", ".", "indexOf", "(", "\"length\"", ")", "!==", "-", "1", ")", "return", "true", ";", "validationType", "=", "\"length\"", ";", "invalidElement", "=", "this", ".", "getElementsByPattern", "(", "elementAsArray", ",", "this", ".", "patterns", "[", "validationType", "]", ",", "validationType", ")", ";", "if", "(", "invalidElement", ".", "length", ">", "0", ")", "return", "false", ";", "return", "true", ";", "}" ]
Validates a single element. Used as callback on invalidated elements to check when they are valid. @param element The element to check. @returns bool True on valid
[ "Validates", "a", "single", "element", ".", "Used", "as", "callback", "on", "invalidated", "elements", "to", "check", "when", "they", "are", "valid", "." ]
143e8a69d1b81b409b4aeff106f7fba21cf14645
https://github.com/pkrll/Salvation/blob/143e8a69d1b81b409b4aeff106f7fba21cf14645/src/salvation.js#L527-L553
52,230
robertontiu/wrapper6
build/packages.js
requireDependencies
function requireDependencies(dependencies) { var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var promise = new _es6Promise.Promise(function (succeed, fail) { var requirements = {}; // no requirements if (!(dependencies instanceof Array)) { return succeed(requirements); } // check if succeeded function checkStatus() { if (Object.keys(requirements).length === dependencies.length) { succeed(requirements); } } dependencies.forEach(function (dependency) { if (packages.has(dependency)) { requirements[dependency] = packages.get(dependency); } else { events.once("load:" + dependency, function (requirement) { requirements[dependency] = requirement; checkStatus(); }); } }); // First check checkStatus(); }); return typeof callback === "function" ? promise.then(callback) : promise; }
javascript
function requireDependencies(dependencies) { var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var promise = new _es6Promise.Promise(function (succeed, fail) { var requirements = {}; // no requirements if (!(dependencies instanceof Array)) { return succeed(requirements); } // check if succeeded function checkStatus() { if (Object.keys(requirements).length === dependencies.length) { succeed(requirements); } } dependencies.forEach(function (dependency) { if (packages.has(dependency)) { requirements[dependency] = packages.get(dependency); } else { events.once("load:" + dependency, function (requirement) { requirements[dependency] = requirement; checkStatus(); }); } }); // First check checkStatus(); }); return typeof callback === "function" ? promise.then(callback) : promise; }
[ "function", "requireDependencies", "(", "dependencies", ")", "{", "var", "callback", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "null", ";", "var", "promise", "=", "new", "_es6Promise", ".", "Promise", "(", "function", "(", "succeed", ",", "fail", ")", "{", "var", "requirements", "=", "{", "}", ";", "// no requirements", "if", "(", "!", "(", "dependencies", "instanceof", "Array", ")", ")", "{", "return", "succeed", "(", "requirements", ")", ";", "}", "// check if succeeded", "function", "checkStatus", "(", ")", "{", "if", "(", "Object", ".", "keys", "(", "requirements", ")", ".", "length", "===", "dependencies", ".", "length", ")", "{", "succeed", "(", "requirements", ")", ";", "}", "}", "dependencies", ".", "forEach", "(", "function", "(", "dependency", ")", "{", "if", "(", "packages", ".", "has", "(", "dependency", ")", ")", "{", "requirements", "[", "dependency", "]", "=", "packages", ".", "get", "(", "dependency", ")", ";", "}", "else", "{", "events", ".", "once", "(", "\"load:\"", "+", "dependency", ",", "function", "(", "requirement", ")", "{", "requirements", "[", "dependency", "]", "=", "requirement", ";", "checkStatus", "(", ")", ";", "}", ")", ";", "}", "}", ")", ";", "// First check", "checkStatus", "(", ")", ";", "}", ")", ";", "return", "typeof", "callback", "===", "\"function\"", "?", "promise", ".", "then", "(", "callback", ")", ":", "promise", ";", "}" ]
Resolve an array of dependencies @param dependencies @returns {Promise}
[ "Resolve", "an", "array", "of", "dependencies" ]
70f99dcda0f2e0926b689be349ab9bb95e84a22d
https://github.com/robertontiu/wrapper6/blob/70f99dcda0f2e0926b689be349ab9bb95e84a22d/build/packages.js#L48-L82
52,231
robertontiu/wrapper6
build/packages.js
definePackage
function definePackage(name, dependencies, callback) { // Adjust arguments if (typeof name === "function") { callback = name; name = null; dependencies = null; } else if (typeof dependencies === "function") { callback = dependencies; dependencies = null; if (name instanceof Array) { dependencies = name; name = null; } } // Check name conflicts if (typeof name === "string") { if (packages.has(name)) { throw new Error("Package '" + name + "' is already loaded!"); } } // Resolve timeout var timeout = _config2.default.get('package_timeout', 5000), timer = null; return new _es6Promise.Promise(function (succeed, fail) { // Start timeout if (typeof timeout === "number") { timer = setTimeout(function () { timer = null; if (_config2.default.get("debug", true)) { throw new Error("Package '" + name + "' timed out!"); } }, timeout); } // Resolve dependencies requireDependencies(dependencies).then(function (requirements) { try { // register package var register = function register(pack) { // cancel timeout if (timer) { clearTimeout(timer); timer = null; } if (pack === false) { return; } if (typeof name === "string") { packages.set(name, pack); events.emit("load:" + name, packages.get(name)); } return succeed(pack); }; // Check boot response var bootResponse = typeof callback === "function" ? callback(requirements) : callback;return bootResponse instanceof _es6Promise.Promise ? bootResponse.then(register) : register(bootResponse); } catch (ex) { if (_config2.default.get("debug", true)) { console.error(ex); } return fail(ex); } }); }); }
javascript
function definePackage(name, dependencies, callback) { // Adjust arguments if (typeof name === "function") { callback = name; name = null; dependencies = null; } else if (typeof dependencies === "function") { callback = dependencies; dependencies = null; if (name instanceof Array) { dependencies = name; name = null; } } // Check name conflicts if (typeof name === "string") { if (packages.has(name)) { throw new Error("Package '" + name + "' is already loaded!"); } } // Resolve timeout var timeout = _config2.default.get('package_timeout', 5000), timer = null; return new _es6Promise.Promise(function (succeed, fail) { // Start timeout if (typeof timeout === "number") { timer = setTimeout(function () { timer = null; if (_config2.default.get("debug", true)) { throw new Error("Package '" + name + "' timed out!"); } }, timeout); } // Resolve dependencies requireDependencies(dependencies).then(function (requirements) { try { // register package var register = function register(pack) { // cancel timeout if (timer) { clearTimeout(timer); timer = null; } if (pack === false) { return; } if (typeof name === "string") { packages.set(name, pack); events.emit("load:" + name, packages.get(name)); } return succeed(pack); }; // Check boot response var bootResponse = typeof callback === "function" ? callback(requirements) : callback;return bootResponse instanceof _es6Promise.Promise ? bootResponse.then(register) : register(bootResponse); } catch (ex) { if (_config2.default.get("debug", true)) { console.error(ex); } return fail(ex); } }); }); }
[ "function", "definePackage", "(", "name", ",", "dependencies", ",", "callback", ")", "{", "// Adjust arguments", "if", "(", "typeof", "name", "===", "\"function\"", ")", "{", "callback", "=", "name", ";", "name", "=", "null", ";", "dependencies", "=", "null", ";", "}", "else", "if", "(", "typeof", "dependencies", "===", "\"function\"", ")", "{", "callback", "=", "dependencies", ";", "dependencies", "=", "null", ";", "if", "(", "name", "instanceof", "Array", ")", "{", "dependencies", "=", "name", ";", "name", "=", "null", ";", "}", "}", "// Check name conflicts", "if", "(", "typeof", "name", "===", "\"string\"", ")", "{", "if", "(", "packages", ".", "has", "(", "name", ")", ")", "{", "throw", "new", "Error", "(", "\"Package '\"", "+", "name", "+", "\"' is already loaded!\"", ")", ";", "}", "}", "// Resolve timeout", "var", "timeout", "=", "_config2", ".", "default", ".", "get", "(", "'package_timeout'", ",", "5000", ")", ",", "timer", "=", "null", ";", "return", "new", "_es6Promise", ".", "Promise", "(", "function", "(", "succeed", ",", "fail", ")", "{", "// Start timeout", "if", "(", "typeof", "timeout", "===", "\"number\"", ")", "{", "timer", "=", "setTimeout", "(", "function", "(", ")", "{", "timer", "=", "null", ";", "if", "(", "_config2", ".", "default", ".", "get", "(", "\"debug\"", ",", "true", ")", ")", "{", "throw", "new", "Error", "(", "\"Package '\"", "+", "name", "+", "\"' timed out!\"", ")", ";", "}", "}", ",", "timeout", ")", ";", "}", "// Resolve dependencies", "requireDependencies", "(", "dependencies", ")", ".", "then", "(", "function", "(", "requirements", ")", "{", "try", "{", "// register package", "var", "register", "=", "function", "register", "(", "pack", ")", "{", "// cancel timeout", "if", "(", "timer", ")", "{", "clearTimeout", "(", "timer", ")", ";", "timer", "=", "null", ";", "}", "if", "(", "pack", "===", "false", ")", "{", "return", ";", "}", "if", "(", "typeof", "name", "===", "\"string\"", ")", "{", "packages", ".", "set", "(", "name", ",", "pack", ")", ";", "events", ".", "emit", "(", "\"load:\"", "+", "name", ",", "packages", ".", "get", "(", "name", ")", ")", ";", "}", "return", "succeed", "(", "pack", ")", ";", "}", ";", "// Check boot response", "var", "bootResponse", "=", "typeof", "callback", "===", "\"function\"", "?", "callback", "(", "requirements", ")", ":", "callback", ";", "return", "bootResponse", "instanceof", "_es6Promise", ".", "Promise", "?", "bootResponse", ".", "then", "(", "register", ")", ":", "register", "(", "bootResponse", ")", ";", "}", "catch", "(", "ex", ")", "{", "if", "(", "_config2", ".", "default", ".", "get", "(", "\"debug\"", ",", "true", ")", ")", "{", "console", ".", "error", "(", "ex", ")", ";", "}", "return", "fail", "(", "ex", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Define a package @param name @param dependencies @param callback @returns {Promise.<TResult>}
[ "Define", "a", "package" ]
70f99dcda0f2e0926b689be349ab9bb95e84a22d
https://github.com/robertontiu/wrapper6/blob/70f99dcda0f2e0926b689be349ab9bb95e84a22d/build/packages.js#L92-L169
52,232
robertontiu/wrapper6
build/packages.js
wrapAll
function wrapAll(callback) { // Prepare packages var packs = {}; packages.forEach(function (pack, name) { packs[name] = pack; }); return callback(packs); }
javascript
function wrapAll(callback) { // Prepare packages var packs = {}; packages.forEach(function (pack, name) { packs[name] = pack; }); return callback(packs); }
[ "function", "wrapAll", "(", "callback", ")", "{", "// Prepare packages", "var", "packs", "=", "{", "}", ";", "packages", ".", "forEach", "(", "function", "(", "pack", ",", "name", ")", "{", "packs", "[", "name", "]", "=", "pack", ";", "}", ")", ";", "return", "callback", "(", "packs", ")", ";", "}" ]
Runs the callback with all currently loaded packages @param callback @returns {*}
[ "Runs", "the", "callback", "with", "all", "currently", "loaded", "packages" ]
70f99dcda0f2e0926b689be349ab9bb95e84a22d
https://github.com/robertontiu/wrapper6/blob/70f99dcda0f2e0926b689be349ab9bb95e84a22d/build/packages.js#L177-L186
52,233
gethuman/jyt
lib/jyt.utils.js
isEmptyObject
function isEmptyObject(obj) { if (obj === null) { return true; } if (!isObject(obj)) { return false; } for (var key in obj) { if (obj.hasOwnProperty(key) && obj[key]) { return false; } } return true; }
javascript
function isEmptyObject(obj) { if (obj === null) { return true; } if (!isObject(obj)) { return false; } for (var key in obj) { if (obj.hasOwnProperty(key) && obj[key]) { return false; } } return true; }
[ "function", "isEmptyObject", "(", "obj", ")", "{", "if", "(", "obj", "===", "null", ")", "{", "return", "true", ";", "}", "if", "(", "!", "isObject", "(", "obj", ")", ")", "{", "return", "false", ";", "}", "for", "(", "var", "key", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "key", ")", "&&", "obj", "[", "key", "]", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Return true if an object and is empty @param obj @returns {boolean}
[ "Return", "true", "if", "an", "object", "and", "is", "empty" ]
716be37e09217b4be917e179389f752212a428b3
https://github.com/gethuman/jyt/blob/716be37e09217b4be917e179389f752212a428b3/lib/jyt.utils.js#L53-L68
52,234
gethuman/jyt
lib/jyt.utils.js
dashToCamelCase
function dashToCamelCase(dashCase) { if (!dashCase) { return dashCase; } var parts = dashCase.split('-'); var camelCase = parts[0]; var part; for (var i = 1; i < parts.length; i++) { part = parts[i]; camelCase += part.substring(0, 1).toUpperCase() + part.substring(1); } return camelCase; }
javascript
function dashToCamelCase(dashCase) { if (!dashCase) { return dashCase; } var parts = dashCase.split('-'); var camelCase = parts[0]; var part; for (var i = 1; i < parts.length; i++) { part = parts[i]; camelCase += part.substring(0, 1).toUpperCase() + part.substring(1); } return camelCase; }
[ "function", "dashToCamelCase", "(", "dashCase", ")", "{", "if", "(", "!", "dashCase", ")", "{", "return", "dashCase", ";", "}", "var", "parts", "=", "dashCase", ".", "split", "(", "'-'", ")", ";", "var", "camelCase", "=", "parts", "[", "0", "]", ";", "var", "part", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "part", "=", "parts", "[", "i", "]", ";", "camelCase", "+=", "part", ".", "substring", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", ")", "+", "part", ".", "substring", "(", "1", ")", ";", "}", "return", "camelCase", ";", "}" ]
Convert a string with dashes to camel case @param dashCase
[ "Convert", "a", "string", "with", "dashes", "to", "camel", "case" ]
716be37e09217b4be917e179389f752212a428b3
https://github.com/gethuman/jyt/blob/716be37e09217b4be917e179389f752212a428b3/lib/jyt.utils.js#L74-L87
52,235
esoodev/eve-swagger-simple
index.js
function (route, parameters) { return new Promise((resolve, reject) => { request.get({ url: baseUrl + route + '?' + querystring.stringify(parameters) }, (error, response, body) => { if (error) { reject(error); } else if (response && body) { var result; try { result = JSON.parse(body); } catch (e) { reject(e); } if (result.error == 'Method not allowed') { this._post(route, parameters).then( res => { resolve(res) }, err => { reject(err) } ); } else { resolve(result); } } else { reject(response); } }); }); }
javascript
function (route, parameters) { return new Promise((resolve, reject) => { request.get({ url: baseUrl + route + '?' + querystring.stringify(parameters) }, (error, response, body) => { if (error) { reject(error); } else if (response && body) { var result; try { result = JSON.parse(body); } catch (e) { reject(e); } if (result.error == 'Method not allowed') { this._post(route, parameters).then( res => { resolve(res) }, err => { reject(err) } ); } else { resolve(result); } } else { reject(response); } }); }); }
[ "function", "(", "route", ",", "parameters", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "request", ".", "get", "(", "{", "url", ":", "baseUrl", "+", "route", "+", "'?'", "+", "querystring", ".", "stringify", "(", "parameters", ")", "}", ",", "(", "error", ",", "response", ",", "body", ")", "=>", "{", "if", "(", "error", ")", "{", "reject", "(", "error", ")", ";", "}", "else", "if", "(", "response", "&&", "body", ")", "{", "var", "result", ";", "try", "{", "result", "=", "JSON", ".", "parse", "(", "body", ")", ";", "}", "catch", "(", "e", ")", "{", "reject", "(", "e", ")", ";", "}", "if", "(", "result", ".", "error", "==", "'Method not allowed'", ")", "{", "this", ".", "_post", "(", "route", ",", "parameters", ")", ".", "then", "(", "res", "=>", "{", "resolve", "(", "res", ")", "}", ",", "err", "=>", "{", "reject", "(", "err", ")", "}", ")", ";", "}", "else", "{", "resolve", "(", "result", ")", ";", "}", "}", "else", "{", "reject", "(", "response", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Send a GET request to ESI - try POST if it fails.
[ "Send", "a", "GET", "request", "to", "ESI", "-", "try", "POST", "if", "it", "fails", "." ]
1a47aeb5074bc95c2e5caa7caf9fdbcc5ed302f9
https://github.com/esoodev/eve-swagger-simple/blob/1a47aeb5074bc95c2e5caa7caf9fdbcc5ed302f9/index.js#L8-L40
52,236
esoodev/eve-swagger-simple
index.js
function (route, parameters) { return new Promise((resolve, reject) => { request.post({ url: baseUrl + route, qs: parameters }, (error, response, body) => { if (error) { reject(error); } else { resolve('POST sent to ' + baseUrl + route + '\n' + JSON.stringify(parameters)); } }); }); }
javascript
function (route, parameters) { return new Promise((resolve, reject) => { request.post({ url: baseUrl + route, qs: parameters }, (error, response, body) => { if (error) { reject(error); } else { resolve('POST sent to ' + baseUrl + route + '\n' + JSON.stringify(parameters)); } }); }); }
[ "function", "(", "route", ",", "parameters", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "request", ".", "post", "(", "{", "url", ":", "baseUrl", "+", "route", ",", "qs", ":", "parameters", "}", ",", "(", "error", ",", "response", ",", "body", ")", "=>", "{", "if", "(", "error", ")", "{", "reject", "(", "error", ")", ";", "}", "else", "{", "resolve", "(", "'POST sent to '", "+", "baseUrl", "+", "route", "+", "'\\n'", "+", "JSON", ".", "stringify", "(", "parameters", ")", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Send a post request to ESI
[ "Send", "a", "post", "request", "to", "ESI" ]
1a47aeb5074bc95c2e5caa7caf9fdbcc5ed302f9
https://github.com/esoodev/eve-swagger-simple/blob/1a47aeb5074bc95c2e5caa7caf9fdbcc5ed302f9/index.js#L43-L57
52,237
danillouz/product-hunt
src/utils/http.js
GET
function GET(uri, params) { const reqUrl = `${uri}${url.format({ query: params })}`; log(`request URL: ${reqUrl}`); return fetch(reqUrl) .then(function handleGetRequest(res) { const status = res.status; const statusText = res.statusText; log(`status code: ${status}`); log(`status text: ${statusText}`); if (status !== 200) { const err = new Error(`Request failed: ${statusText}`); err.status = status; throw err; } return res.json(); }) .then(data => { const posts = data.posts; log(`${posts.length} posts were fetched`); return posts; }) .catch(err => { log('catched err: ', err); throw err; }); }
javascript
function GET(uri, params) { const reqUrl = `${uri}${url.format({ query: params })}`; log(`request URL: ${reqUrl}`); return fetch(reqUrl) .then(function handleGetRequest(res) { const status = res.status; const statusText = res.statusText; log(`status code: ${status}`); log(`status text: ${statusText}`); if (status !== 200) { const err = new Error(`Request failed: ${statusText}`); err.status = status; throw err; } return res.json(); }) .then(data => { const posts = data.posts; log(`${posts.length} posts were fetched`); return posts; }) .catch(err => { log('catched err: ', err); throw err; }); }
[ "function", "GET", "(", "uri", ",", "params", ")", "{", "const", "reqUrl", "=", "`", "${", "uri", "}", "${", "url", ".", "format", "(", "{", "query", ":", "params", "}", ")", "}", "`", ";", "log", "(", "`", "${", "reqUrl", "}", "`", ")", ";", "return", "fetch", "(", "reqUrl", ")", ".", "then", "(", "function", "handleGetRequest", "(", "res", ")", "{", "const", "status", "=", "res", ".", "status", ";", "const", "statusText", "=", "res", ".", "statusText", ";", "log", "(", "`", "${", "status", "}", "`", ")", ";", "log", "(", "`", "${", "statusText", "}", "`", ")", ";", "if", "(", "status", "!==", "200", ")", "{", "const", "err", "=", "new", "Error", "(", "`", "${", "statusText", "}", "`", ")", ";", "err", ".", "status", "=", "status", ";", "throw", "err", ";", "}", "return", "res", ".", "json", "(", ")", ";", "}", ")", ".", "then", "(", "data", "=>", "{", "const", "posts", "=", "data", ".", "posts", ";", "log", "(", "`", "${", "posts", ".", "length", "}", "`", ")", ";", "return", "posts", ";", "}", ")", ".", "catch", "(", "err", "=>", "{", "log", "(", "'catched err: '", ",", "err", ")", ";", "throw", "err", ";", "}", ")", ";", "}" ]
Makes an HTTP GET request for a specific URI. @param {String} uri - the request URI @param {Object} params - the request query parameters @return {Promise} resolves with the HTTP response
[ "Makes", "an", "HTTP", "GET", "request", "for", "a", "specific", "URI", "." ]
de7196db39365874055ad363cf3736de6de13856
https://github.com/danillouz/product-hunt/blob/de7196db39365874055ad363cf3736de6de13856/src/utils/http.js#L17-L52
52,238
jamiter/swapi-schema
src/schema.js
jsonSchemaTypeToGraphQL
function jsonSchemaTypeToGraphQL(jsonSchemaType, schemaName) { if (jsonSchemaType === "array") { if (graphQLObjectTypes[schemaName]) { return new GraphQLList(graphQLObjectTypes[schemaName]); } else { const translated = { pilots: "people", characters: "people", residents: "people" }[schemaName]; if (! translated) { throw new Error(`no type ${schemaName}`); } const type = graphQLObjectTypes[translated]; if (! type) { throw new Error(`no GraphQL type ${schemaName}`); } return new GraphQLList(type); } } return { string: GraphQLString, date: GraphQLString, integer: GraphQLInt, }[jsonSchemaType]; }
javascript
function jsonSchemaTypeToGraphQL(jsonSchemaType, schemaName) { if (jsonSchemaType === "array") { if (graphQLObjectTypes[schemaName]) { return new GraphQLList(graphQLObjectTypes[schemaName]); } else { const translated = { pilots: "people", characters: "people", residents: "people" }[schemaName]; if (! translated) { throw new Error(`no type ${schemaName}`); } const type = graphQLObjectTypes[translated]; if (! type) { throw new Error(`no GraphQL type ${schemaName}`); } return new GraphQLList(type); } } return { string: GraphQLString, date: GraphQLString, integer: GraphQLInt, }[jsonSchemaType]; }
[ "function", "jsonSchemaTypeToGraphQL", "(", "jsonSchemaType", ",", "schemaName", ")", "{", "if", "(", "jsonSchemaType", "===", "\"array\"", ")", "{", "if", "(", "graphQLObjectTypes", "[", "schemaName", "]", ")", "{", "return", "new", "GraphQLList", "(", "graphQLObjectTypes", "[", "schemaName", "]", ")", ";", "}", "else", "{", "const", "translated", "=", "{", "pilots", ":", "\"people\"", ",", "characters", ":", "\"people\"", ",", "residents", ":", "\"people\"", "}", "[", "schemaName", "]", ";", "if", "(", "!", "translated", ")", "{", "throw", "new", "Error", "(", "`", "${", "schemaName", "}", "`", ")", ";", "}", "const", "type", "=", "graphQLObjectTypes", "[", "translated", "]", ";", "if", "(", "!", "type", ")", "{", "throw", "new", "Error", "(", "`", "${", "schemaName", "}", "`", ")", ";", "}", "return", "new", "GraphQLList", "(", "type", ")", ";", "}", "}", "return", "{", "string", ":", "GraphQLString", ",", "date", ":", "GraphQLString", ",", "integer", ":", "GraphQLInt", ",", "}", "[", "jsonSchemaType", "]", ";", "}" ]
Convert the JSON Schema types to the actual GraphQL types in our schema
[ "Convert", "the", "JSON", "Schema", "types", "to", "the", "actual", "GraphQL", "types", "in", "our", "schema" ]
f05b28b75d7205739c0415bf379b5cd1f4936a7d
https://github.com/jamiter/swapi-schema/blob/f05b28b75d7205739c0415bf379b5cd1f4936a7d/src/schema.js#L55-L85
52,239
jamiter/swapi-schema
src/schema.js
fetchPageOfType
function fetchPageOfType(typePluralName, pageNumber) { let url = `http://swapi.co/api/${typePluralName}/`; if (pageNumber) { url += `?page=${pageNumber}`; }; return restLoader.load(url).then((data) => { // Paginated results have a different shape return data.results; }); }
javascript
function fetchPageOfType(typePluralName, pageNumber) { let url = `http://swapi.co/api/${typePluralName}/`; if (pageNumber) { url += `?page=${pageNumber}`; }; return restLoader.load(url).then((data) => { // Paginated results have a different shape return data.results; }); }
[ "function", "fetchPageOfType", "(", "typePluralName", ",", "pageNumber", ")", "{", "let", "url", "=", "`", "${", "typePluralName", "}", "`", ";", "if", "(", "pageNumber", ")", "{", "url", "+=", "`", "${", "pageNumber", "}", "`", ";", "}", ";", "return", "restLoader", ".", "load", "(", "url", ")", ".", "then", "(", "(", "data", ")", "=>", "{", "// Paginated results have a different shape", "return", "data", ".", "results", ";", "}", ")", ";", "}" ]
A helper to unwrap the paginated object from SWAPI
[ "A", "helper", "to", "unwrap", "the", "paginated", "object", "from", "SWAPI" ]
f05b28b75d7205739c0415bf379b5cd1f4936a7d
https://github.com/jamiter/swapi-schema/blob/f05b28b75d7205739c0415bf379b5cd1f4936a7d/src/schema.js#L134-L144
52,240
tolokoban/ToloFrameWork
ker/mod/tfw.color.js
rgb2hsl
function rgb2hsl() { const R = this.R, G = this.G, B = this.B, min = Math.min( R, G, B ), max = Math.max( R, G, B ), delta = max - min; this.L = 0.5 * ( max + min ); if ( delta < 0.000001 ) { this.H = 0; this.S = 0; } else { this.S = delta / ( 1 - Math.abs( ( 2 * this.L ) - 1 ) ); if ( max === R ) { if ( G >= B ) { this.H = INV6 * ( ( G - B ) / delta ); } else { this.H = 1 - ( INV6 * ( ( B - G ) / delta ) ); } } else if ( max === G ) { this.H = INV6 * ( 2 + ( ( B - R ) / delta ) ); } else { this.H = INV6 * ( 4 + ( ( R - G ) / delta ) ); } } }
javascript
function rgb2hsl() { const R = this.R, G = this.G, B = this.B, min = Math.min( R, G, B ), max = Math.max( R, G, B ), delta = max - min; this.L = 0.5 * ( max + min ); if ( delta < 0.000001 ) { this.H = 0; this.S = 0; } else { this.S = delta / ( 1 - Math.abs( ( 2 * this.L ) - 1 ) ); if ( max === R ) { if ( G >= B ) { this.H = INV6 * ( ( G - B ) / delta ); } else { this.H = 1 - ( INV6 * ( ( B - G ) / delta ) ); } } else if ( max === G ) { this.H = INV6 * ( 2 + ( ( B - R ) / delta ) ); } else { this.H = INV6 * ( 4 + ( ( R - G ) / delta ) ); } } }
[ "function", "rgb2hsl", "(", ")", "{", "const", "R", "=", "this", ".", "R", ",", "G", "=", "this", ".", "G", ",", "B", "=", "this", ".", "B", ",", "min", "=", "Math", ".", "min", "(", "R", ",", "G", ",", "B", ")", ",", "max", "=", "Math", ".", "max", "(", "R", ",", "G", ",", "B", ")", ",", "delta", "=", "max", "-", "min", ";", "this", ".", "L", "=", "0.5", "*", "(", "max", "+", "min", ")", ";", "if", "(", "delta", "<", "0.000001", ")", "{", "this", ".", "H", "=", "0", ";", "this", ".", "S", "=", "0", ";", "}", "else", "{", "this", ".", "S", "=", "delta", "/", "(", "1", "-", "Math", ".", "abs", "(", "(", "2", "*", "this", ".", "L", ")", "-", "1", ")", ")", ";", "if", "(", "max", "===", "R", ")", "{", "if", "(", "G", ">=", "B", ")", "{", "this", ".", "H", "=", "INV6", "*", "(", "(", "G", "-", "B", ")", "/", "delta", ")", ";", "}", "else", "{", "this", ".", "H", "=", "1", "-", "(", "INV6", "*", "(", "(", "B", "-", "G", ")", "/", "delta", ")", ")", ";", "}", "}", "else", "if", "(", "max", "===", "G", ")", "{", "this", ".", "H", "=", "INV6", "*", "(", "2", "+", "(", "(", "B", "-", "R", ")", "/", "delta", ")", ")", ";", "}", "else", "{", "this", ".", "H", "=", "INV6", "*", "(", "4", "+", "(", "(", "R", "-", "G", ")", "/", "delta", ")", ")", ";", "}", "}", "}" ]
Read R,G,B and write H,S,L. @this Color @returns {undefined}
[ "Read", "R", "G", "B", "and", "write", "H", "S", "L", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/tfw.color.js#L106-L134
52,241
BlueRival/confection
lib/core/index.js
getConf
function getConf( path, environment, callback, context ) { // relative paths need to be auto-prefixed with the environment if ( path.match( /^[^\.]/ ) ) { path = "." + environment + "." + path; } if ( !context ) { context = { pathsSeen: {} }; } // avoid circular references if ( context.pathsSeen[path] ) { callback( undefined ); return; } context.pathsSeen[path] = true; // calculate catch all path var catchAllPath = ".*." + path.replace( /^\.[^\.]*\./, '' ); if ( catchAllPath === path ) { catchAllPath = false; } // try exact path moduleConfig.storage.getConf( path, function ( err, conf ) { // if there was an error, don't try for wildcard if ( err ) { callback( undefined ); } // not found, try wildcard else if ( conf === null && catchAllPath ) { moduleConfig.storage.getConf( catchAllPath, function ( err, conf ) { // error searching for wild card if ( err ) { callback( undefined ); } // wild card found else { applyAbstractions( conf, environment, context, callback ); } } ); } // exact path found else { applyAbstractions( conf, environment, context, callback ); } } ); }
javascript
function getConf( path, environment, callback, context ) { // relative paths need to be auto-prefixed with the environment if ( path.match( /^[^\.]/ ) ) { path = "." + environment + "." + path; } if ( !context ) { context = { pathsSeen: {} }; } // avoid circular references if ( context.pathsSeen[path] ) { callback( undefined ); return; } context.pathsSeen[path] = true; // calculate catch all path var catchAllPath = ".*." + path.replace( /^\.[^\.]*\./, '' ); if ( catchAllPath === path ) { catchAllPath = false; } // try exact path moduleConfig.storage.getConf( path, function ( err, conf ) { // if there was an error, don't try for wildcard if ( err ) { callback( undefined ); } // not found, try wildcard else if ( conf === null && catchAllPath ) { moduleConfig.storage.getConf( catchAllPath, function ( err, conf ) { // error searching for wild card if ( err ) { callback( undefined ); } // wild card found else { applyAbstractions( conf, environment, context, callback ); } } ); } // exact path found else { applyAbstractions( conf, environment, context, callback ); } } ); }
[ "function", "getConf", "(", "path", ",", "environment", ",", "callback", ",", "context", ")", "{", "// relative paths need to be auto-prefixed with the environment", "if", "(", "path", ".", "match", "(", "/", "^[^\\.]", "/", ")", ")", "{", "path", "=", "\".\"", "+", "environment", "+", "\".\"", "+", "path", ";", "}", "if", "(", "!", "context", ")", "{", "context", "=", "{", "pathsSeen", ":", "{", "}", "}", ";", "}", "// avoid circular references", "if", "(", "context", ".", "pathsSeen", "[", "path", "]", ")", "{", "callback", "(", "undefined", ")", ";", "return", ";", "}", "context", ".", "pathsSeen", "[", "path", "]", "=", "true", ";", "// calculate catch all path", "var", "catchAllPath", "=", "\".*.\"", "+", "path", ".", "replace", "(", "/", "^\\.[^\\.]*\\.", "/", ",", "''", ")", ";", "if", "(", "catchAllPath", "===", "path", ")", "{", "catchAllPath", "=", "false", ";", "}", "// try exact path", "moduleConfig", ".", "storage", ".", "getConf", "(", "path", ",", "function", "(", "err", ",", "conf", ")", "{", "// if there was an error, don't try for wildcard", "if", "(", "err", ")", "{", "callback", "(", "undefined", ")", ";", "}", "// not found, try wildcard", "else", "if", "(", "conf", "===", "null", "&&", "catchAllPath", ")", "{", "moduleConfig", ".", "storage", ".", "getConf", "(", "catchAllPath", ",", "function", "(", "err", ",", "conf", ")", "{", "// error searching for wild card", "if", "(", "err", ")", "{", "callback", "(", "undefined", ")", ";", "}", "// wild card found", "else", "{", "applyAbstractions", "(", "conf", ",", "environment", ",", "context", ",", "callback", ")", ";", "}", "}", ")", ";", "}", "// exact path found", "else", "{", "applyAbstractions", "(", "conf", ",", "environment", ",", "context", ",", "callback", ")", ";", "}", "}", ")", ";", "}" ]
getConf is responsible for the core logic in the API. It handles applying all extensions and wildcard lookups. External Params: @param path the dot notation path to pull from the storage engine @param environment the name of the environment to pull the configuration for @param callback Recursive Params: @param context
[ "getConf", "is", "responsible", "for", "the", "core", "logic", "in", "the", "API", ".", "It", "handles", "applying", "all", "extensions", "and", "wildcard", "lookups", "." ]
c1eb8c78bae9eb059b825978896d0a4ef8ca6771
https://github.com/BlueRival/confection/blob/c1eb8c78bae9eb059b825978896d0a4ef8ca6771/lib/core/index.js#L131-L191
52,242
BlueRival/confection
lib/core/index.js
getPath
function getPath( req, res, next ) { var path = req.path.replace( /\..*$/, '' ).replace( /\//g, '.' ).replace( /^\.conf/, '' ).replace( /\.$/, '' ).trim(); if ( path.length < 1 ) { path = null; } var outputFilter = req.path.trim().match( /\.(.*)$/ ); if ( outputFilter ) { outputFilter = outputFilter[1].trim(); } if ( typeof outputFilter !== 'string' || outputFilter.length < 1 ) { outputFilter = 'json'; } req.confPath = path; req.outputFilter = outputFilter; return next(); }
javascript
function getPath( req, res, next ) { var path = req.path.replace( /\..*$/, '' ).replace( /\//g, '.' ).replace( /^\.conf/, '' ).replace( /\.$/, '' ).trim(); if ( path.length < 1 ) { path = null; } var outputFilter = req.path.trim().match( /\.(.*)$/ ); if ( outputFilter ) { outputFilter = outputFilter[1].trim(); } if ( typeof outputFilter !== 'string' || outputFilter.length < 1 ) { outputFilter = 'json'; } req.confPath = path; req.outputFilter = outputFilter; return next(); }
[ "function", "getPath", "(", "req", ",", "res", ",", "next", ")", "{", "var", "path", "=", "req", ".", "path", ".", "replace", "(", "/", "\\..*$", "/", ",", "''", ")", ".", "replace", "(", "/", "\\/", "/", "g", ",", "'.'", ")", ".", "replace", "(", "/", "^\\.conf", "/", ",", "''", ")", ".", "replace", "(", "/", "\\.$", "/", ",", "''", ")", ".", "trim", "(", ")", ";", "if", "(", "path", ".", "length", "<", "1", ")", "{", "path", "=", "null", ";", "}", "var", "outputFilter", "=", "req", ".", "path", ".", "trim", "(", ")", ".", "match", "(", "/", "\\.(.*)$", "/", ")", ";", "if", "(", "outputFilter", ")", "{", "outputFilter", "=", "outputFilter", "[", "1", "]", ".", "trim", "(", ")", ";", "}", "if", "(", "typeof", "outputFilter", "!==", "'string'", "||", "outputFilter", ".", "length", "<", "1", ")", "{", "outputFilter", "=", "'json'", ";", "}", "req", ".", "confPath", "=", "path", ";", "req", ".", "outputFilter", "=", "outputFilter", ";", "return", "next", "(", ")", ";", "}" ]
Get the conf path from the URL path. @param req The express request handle @param res The response object passed to the middleware @param next The next function to trigger the next middleware @return {null}
[ "Get", "the", "conf", "path", "from", "the", "URL", "path", "." ]
c1eb8c78bae9eb059b825978896d0a4ef8ca6771
https://github.com/BlueRival/confection/blob/c1eb8c78bae9eb059b825978896d0a4ef8ca6771/lib/core/index.js#L343-L365
52,243
BlueRival/confection
lib/core/index.js
configureExpress
function configureExpress() { // create configuration routes moduleConfig.express.get( /^\/conf.*/, checkAuth, getPath, getMiddlewareWrapper( onGetConf ) ); moduleConfig.express.post( /^\/conf.*/, storeRequestBody, checkAuth, getPath, getMiddlewareWrapper( onPostConf ) ); moduleConfig.express.delete( /^\/conf.*/, checkAuth, getPath, getMiddlewareWrapper( onDeleteConf ) ); // create auth management routes moduleConfig.express.post( "/auth", checkAuth, getMiddlewareWrapper( onPostAuth ) ); moduleConfig.express.delete( "/auth", checkAuth, getMiddlewareWrapper( onDeleteAuth ) ); }
javascript
function configureExpress() { // create configuration routes moduleConfig.express.get( /^\/conf.*/, checkAuth, getPath, getMiddlewareWrapper( onGetConf ) ); moduleConfig.express.post( /^\/conf.*/, storeRequestBody, checkAuth, getPath, getMiddlewareWrapper( onPostConf ) ); moduleConfig.express.delete( /^\/conf.*/, checkAuth, getPath, getMiddlewareWrapper( onDeleteConf ) ); // create auth management routes moduleConfig.express.post( "/auth", checkAuth, getMiddlewareWrapper( onPostAuth ) ); moduleConfig.express.delete( "/auth", checkAuth, getMiddlewareWrapper( onDeleteAuth ) ); }
[ "function", "configureExpress", "(", ")", "{", "// create configuration routes", "moduleConfig", ".", "express", ".", "get", "(", "/", "^\\/conf.*", "/", ",", "checkAuth", ",", "getPath", ",", "getMiddlewareWrapper", "(", "onGetConf", ")", ")", ";", "moduleConfig", ".", "express", ".", "post", "(", "/", "^\\/conf.*", "/", ",", "storeRequestBody", ",", "checkAuth", ",", "getPath", ",", "getMiddlewareWrapper", "(", "onPostConf", ")", ")", ";", "moduleConfig", ".", "express", ".", "delete", "(", "/", "^\\/conf.*", "/", ",", "checkAuth", ",", "getPath", ",", "getMiddlewareWrapper", "(", "onDeleteConf", ")", ")", ";", "// create auth management routes", "moduleConfig", ".", "express", ".", "post", "(", "\"/auth\"", ",", "checkAuth", ",", "getMiddlewareWrapper", "(", "onPostAuth", ")", ")", ";", "moduleConfig", ".", "express", ".", "delete", "(", "\"/auth\"", ",", "checkAuth", ",", "getMiddlewareWrapper", "(", "onDeleteAuth", ")", ")", ";", "}" ]
Configures the express instance.
[ "Configures", "the", "express", "instance", "." ]
c1eb8c78bae9eb059b825978896d0a4ef8ca6771
https://github.com/BlueRival/confection/blob/c1eb8c78bae9eb059b825978896d0a4ef8ca6771/lib/core/index.js#L386-L397
52,244
BlueRival/confection
lib/core/index.js
getMiddlewareWrapper
function getMiddlewareWrapper( middleware ) { return function ( req, res, next ) { try { middleware( req, res, next ); } catch ( e ) { getResponder( req, res )( 500 ); } }; }
javascript
function getMiddlewareWrapper( middleware ) { return function ( req, res, next ) { try { middleware( req, res, next ); } catch ( e ) { getResponder( req, res )( 500 ); } }; }
[ "function", "getMiddlewareWrapper", "(", "middleware", ")", "{", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "try", "{", "middleware", "(", "req", ",", "res", ",", "next", ")", ";", "}", "catch", "(", "e", ")", "{", "getResponder", "(", "req", ",", "res", ")", "(", "500", ")", ";", "}", "}", ";", "}" ]
This wrapper simply traps any uncaught exceptions. @param middleware The middleware function to wrap @return {Function} The wrapper function to pass to express
[ "This", "wrapper", "simply", "traps", "any", "uncaught", "exceptions", "." ]
c1eb8c78bae9eb059b825978896d0a4ef8ca6771
https://github.com/BlueRival/confection/blob/c1eb8c78bae9eb059b825978896d0a4ef8ca6771/lib/core/index.js#L405-L414
52,245
BlueRival/confection
lib/core/index.js
getResponder
function getResponder( req, res ) { return function ( code, body, contentType ) { if ( code !== 200 ) { body = ""; contentType = "text/html; charset=utf-8"; } if ( !contentType ) { contentType = "text/html; charset=utf-8"; } res.writeHead( code, { "Content-type": contentType } ); res.end( body ); }; }
javascript
function getResponder( req, res ) { return function ( code, body, contentType ) { if ( code !== 200 ) { body = ""; contentType = "text/html; charset=utf-8"; } if ( !contentType ) { contentType = "text/html; charset=utf-8"; } res.writeHead( code, { "Content-type": contentType } ); res.end( body ); }; }
[ "function", "getResponder", "(", "req", ",", "res", ")", "{", "return", "function", "(", "code", ",", "body", ",", "contentType", ")", "{", "if", "(", "code", "!==", "200", ")", "{", "body", "=", "\"\"", ";", "contentType", "=", "\"text/html; charset=utf-8\"", ";", "}", "if", "(", "!", "contentType", ")", "{", "contentType", "=", "\"text/html; charset=utf-8\"", ";", "}", "res", ".", "writeHead", "(", "code", ",", "{", "\"Content-type\"", ":", "contentType", "}", ")", ";", "res", ".", "end", "(", "body", ")", ";", "}", ";", "}" ]
Gets a response generating function. Used in middleware to simplify response logic. @param res A handle to a response object to send the response to when the responder function is called @return {Function} The responder function for middleware to call to send a response to a request
[ "Gets", "a", "response", "generating", "function", ".", "Used", "in", "middleware", "to", "simplify", "response", "logic", "." ]
c1eb8c78bae9eb059b825978896d0a4ef8ca6771
https://github.com/BlueRival/confection/blob/c1eb8c78bae9eb059b825978896d0a4ef8ca6771/lib/core/index.js#L422-L442
52,246
billinghamj/resilient-mailer-sendgrid
lib/sendgrid-provider.js
SendgridProvider
function SendgridProvider(apiUser, apiKey, options) { if (typeof apiUser !== 'string' || typeof apiKey !== 'string') { throw new Error('Invalid parameters'); } options = options || {}; if (typeof options.apiSecure === 'undefined') options.apiSecure = true; options.apiHostname = options.apiHostname || 'api.sendgrid.com'; options.apiPort = options.apiPort || (options.apiSecure ? 443 : 80); this.apiUser = apiUser; this.apiKey = apiKey; this.options = options; }
javascript
function SendgridProvider(apiUser, apiKey, options) { if (typeof apiUser !== 'string' || typeof apiKey !== 'string') { throw new Error('Invalid parameters'); } options = options || {}; if (typeof options.apiSecure === 'undefined') options.apiSecure = true; options.apiHostname = options.apiHostname || 'api.sendgrid.com'; options.apiPort = options.apiPort || (options.apiSecure ? 443 : 80); this.apiUser = apiUser; this.apiKey = apiKey; this.options = options; }
[ "function", "SendgridProvider", "(", "apiUser", ",", "apiKey", ",", "options", ")", "{", "if", "(", "typeof", "apiUser", "!==", "'string'", "||", "typeof", "apiKey", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'Invalid parameters'", ")", ";", "}", "options", "=", "options", "||", "{", "}", ";", "if", "(", "typeof", "options", ".", "apiSecure", "===", "'undefined'", ")", "options", ".", "apiSecure", "=", "true", ";", "options", ".", "apiHostname", "=", "options", ".", "apiHostname", "||", "'api.sendgrid.com'", ";", "options", ".", "apiPort", "=", "options", ".", "apiPort", "||", "(", "options", ".", "apiSecure", "?", "443", ":", "80", ")", ";", "this", ".", "apiUser", "=", "apiUser", ";", "this", ".", "apiKey", "=", "apiKey", ";", "this", ".", "options", "=", "options", ";", "}" ]
Creates an instance of the SendGrid email provider. @constructor @this {SendgridProvider} @param {string} apiUser API user for the SendGrid account. @param {string} apiKey API key for the SendGrid account. @param {object} [options] Additional optional configuration. @param {boolean} [options.apiSecure=true] API connection protocol - true = HTTPS, false = HTTP @param {string} [options.apiHostname=api.sendgrid.com] Hostname for the API connection @param {number} [options.apiPort] Port for the API connection - defaults to match the protocol (HTTPS-443, HTTP-80)
[ "Creates", "an", "instance", "of", "the", "SendGrid", "email", "provider", "." ]
89eec1fe27da6ba54dcb32fed111163d81a919f6
https://github.com/billinghamj/resilient-mailer-sendgrid/blob/89eec1fe27da6ba54dcb32fed111163d81a919f6/lib/sendgrid-provider.js#L19-L36
52,247
me-ventures/microservice-toolkit
src/context.js
consume
function consume(exchangeName, topics, handler) { // Setup chain var messageHandler = function(message) { // make sure we don't have things like buffers message.content = JSON.parse(message.content.toString()); topics.forEach(function(topic){ statusProvider.setEventConsumeExample( exchangeName, topic, message.content ); }); chain(message, handler) }; rabbitmq.connectExchange(exchangeName, topics, messageHandler); // add consume events to status provider topics.forEach(function(topic){ statusProvider.addEventConsume(exchangeName, topic, false); }); }
javascript
function consume(exchangeName, topics, handler) { // Setup chain var messageHandler = function(message) { // make sure we don't have things like buffers message.content = JSON.parse(message.content.toString()); topics.forEach(function(topic){ statusProvider.setEventConsumeExample( exchangeName, topic, message.content ); }); chain(message, handler) }; rabbitmq.connectExchange(exchangeName, topics, messageHandler); // add consume events to status provider topics.forEach(function(topic){ statusProvider.addEventConsume(exchangeName, topic, false); }); }
[ "function", "consume", "(", "exchangeName", ",", "topics", ",", "handler", ")", "{", "// Setup chain", "var", "messageHandler", "=", "function", "(", "message", ")", "{", "// make sure we don't have things like buffers", "message", ".", "content", "=", "JSON", ".", "parse", "(", "message", ".", "content", ".", "toString", "(", ")", ")", ";", "topics", ".", "forEach", "(", "function", "(", "topic", ")", "{", "statusProvider", ".", "setEventConsumeExample", "(", "exchangeName", ",", "topic", ",", "message", ".", "content", ")", ";", "}", ")", ";", "chain", "(", "message", ",", "handler", ")", "}", ";", "rabbitmq", ".", "connectExchange", "(", "exchangeName", ",", "topics", ",", "messageHandler", ")", ";", "// add consume events to status provider", "topics", ".", "forEach", "(", "function", "(", "topic", ")", "{", "statusProvider", ".", "addEventConsume", "(", "exchangeName", ",", "topic", ",", "false", ")", ";", "}", ")", ";", "}" ]
Create a consume function for an exchange. Handler should return a promise and accept a message. If this is reject promise the message is not acknowledged. If the resolves it should contain the original message. @param exchangeName @param topics @param handler
[ "Create", "a", "consume", "function", "for", "an", "exchange", "." ]
9aedc9542dffdc274a5142515bd22e92833220d2
https://github.com/me-ventures/microservice-toolkit/blob/9aedc9542dffdc274a5142515bd22e92833220d2/src/context.js#L35-L58
52,248
me-ventures/microservice-toolkit
src/context.js
consumeShared
function consumeShared(exchangeName, topics, queueName, handler, fetchCount = 1) { var messageHandler = function(message) { // make sure we don't have things like buffers message.content = JSON.parse(message.content.toString()); topics.forEach(function(topic){ statusProvider.setEventConsumeExample( exchangeName, topic, message.content ); }); chain(message, handler) }; rabbitmq.connectExchangeSharedQueue(exchangeName, topics, queueName, messageHandler, { prefetch: fetchCount }); // add consume events to status provider topics.forEach(function(topic){ statusProvider.addEventConsume(exchangeName, topic, true, queueName); }); }
javascript
function consumeShared(exchangeName, topics, queueName, handler, fetchCount = 1) { var messageHandler = function(message) { // make sure we don't have things like buffers message.content = JSON.parse(message.content.toString()); topics.forEach(function(topic){ statusProvider.setEventConsumeExample( exchangeName, topic, message.content ); }); chain(message, handler) }; rabbitmq.connectExchangeSharedQueue(exchangeName, topics, queueName, messageHandler, { prefetch: fetchCount }); // add consume events to status provider topics.forEach(function(topic){ statusProvider.addEventConsume(exchangeName, topic, true, queueName); }); }
[ "function", "consumeShared", "(", "exchangeName", ",", "topics", ",", "queueName", ",", "handler", ",", "fetchCount", "=", "1", ")", "{", "var", "messageHandler", "=", "function", "(", "message", ")", "{", "// make sure we don't have things like buffers", "message", ".", "content", "=", "JSON", ".", "parse", "(", "message", ".", "content", ".", "toString", "(", ")", ")", ";", "topics", ".", "forEach", "(", "function", "(", "topic", ")", "{", "statusProvider", ".", "setEventConsumeExample", "(", "exchangeName", ",", "topic", ",", "message", ".", "content", ")", ";", "}", ")", ";", "chain", "(", "message", ",", "handler", ")", "}", ";", "rabbitmq", ".", "connectExchangeSharedQueue", "(", "exchangeName", ",", "topics", ",", "queueName", ",", "messageHandler", ",", "{", "prefetch", ":", "fetchCount", "}", ")", ";", "// add consume events to status provider", "topics", ".", "forEach", "(", "function", "(", "topic", ")", "{", "statusProvider", ".", "addEventConsume", "(", "exchangeName", ",", "topic", ",", "true", ",", "queueName", ")", ";", "}", ")", ";", "}" ]
Create a consume function for an exchange using a shared queue. This queue can be used by other workers and the messages will be shared round-robin. Handler should return a promise and accept a message. If this is reject promise the message is not acknowledged. If the resolves it should contain the original message. @param exchangeName @param topics @param queueName @param handler @param fetchCount
[ "Create", "a", "consume", "function", "for", "an", "exchange", "using", "a", "shared", "queue", ".", "This", "queue", "can", "be", "used", "by", "other", "workers", "and", "the", "messages", "will", "be", "shared", "round", "-", "robin", "." ]
9aedc9542dffdc274a5142515bd22e92833220d2
https://github.com/me-ventures/microservice-toolkit/blob/9aedc9542dffdc274a5142515bd22e92833220d2/src/context.js#L73-L95
52,249
integreat-io/great-uri-template
lib/filters/upper.js
upper
function upper (value) { if (value === null || value === undefined) { return value } return String.prototype.toUpperCase.call(value) }
javascript
function upper (value) { if (value === null || value === undefined) { return value } return String.prototype.toUpperCase.call(value) }
[ "function", "upper", "(", "value", ")", "{", "if", "(", "value", "===", "null", "||", "value", "===", "undefined", ")", "{", "return", "value", "}", "return", "String", ".", "prototype", ".", "toUpperCase", ".", "call", "(", "value", ")", "}" ]
Returns the value in upper case. @param {string} value - The value @returns {string} Upper case value
[ "Returns", "the", "value", "in", "upper", "case", "." ]
0e896ead0567737cf31a4a8b76a26cfa6ce60759
https://github.com/integreat-io/great-uri-template/blob/0e896ead0567737cf31a4a8b76a26cfa6ce60759/lib/filters/upper.js#L6-L11
52,250
phelpstream/svp
lib/functions/iftr.js
iftr
function iftr(conditionResult, trueValue, falseValue) { if (conditionResult && (0, _is.isDefined)(trueValue)) return trueValue; if (!conditionResult && (0, _is.isDefined)(falseValue)) return falseValue; }
javascript
function iftr(conditionResult, trueValue, falseValue) { if (conditionResult && (0, _is.isDefined)(trueValue)) return trueValue; if (!conditionResult && (0, _is.isDefined)(falseValue)) return falseValue; }
[ "function", "iftr", "(", "conditionResult", ",", "trueValue", ",", "falseValue", ")", "{", "if", "(", "conditionResult", "&&", "(", "0", ",", "_is", ".", "isDefined", ")", "(", "trueValue", ")", ")", "return", "trueValue", ";", "if", "(", "!", "conditionResult", "&&", "(", "0", ",", "_is", ".", "isDefined", ")", "(", "falseValue", ")", ")", "return", "falseValue", ";", "}" ]
If Then Return
[ "If", "Then", "Return" ]
2f99adb9c5d0709e567264bba896d6a59f6a0a59
https://github.com/phelpstream/svp/blob/2f99adb9c5d0709e567264bba896d6a59f6a0a59/lib/functions/iftr.js#L11-L14
52,251
telyn/node-jrc
lib/message.js
function() { switch(self.command) { case constants.WHOIS: return (self.params[0][0] == 'A'); case constants.PASSWORD: return true; case constants.NUMERICINFO: case constants.GENERALINFO: // client-to-server return (self.params.length < 2) || (self.params[0][0] == 'c'); case constants.SERVERMESSAGE: return true; default: return false; } }
javascript
function() { switch(self.command) { case constants.WHOIS: return (self.params[0][0] == 'A'); case constants.PASSWORD: return true; case constants.NUMERICINFO: case constants.GENERALINFO: // client-to-server return (self.params.length < 2) || (self.params[0][0] == 'c'); case constants.SERVERMESSAGE: return true; default: return false; } }
[ "function", "(", ")", "{", "switch", "(", "self", ".", "command", ")", "{", "case", "constants", ".", "WHOIS", ":", "return", "(", "self", ".", "params", "[", "0", "]", "[", "0", "]", "==", "'A'", ")", ";", "case", "constants", ".", "PASSWORD", ":", "return", "true", ";", "case", "constants", ".", "NUMERICINFO", ":", "case", "constants", ".", "GENERALINFO", ":", "// client-to-server", "return", "(", "self", ".", "params", ".", "length", "<", "2", ")", "||", "(", "self", ".", "params", "[", "0", "]", "[", "0", "]", "==", "'c'", ")", ";", "case", "constants", ".", "SERVERMESSAGE", ":", "return", "true", ";", "default", ":", "return", "false", ";", "}", "}" ]
returns true for commands like HcCreatures
[ "returns", "true", "for", "commands", "like", "HcCreatures" ]
c91b8d0a7d95856b7650b815234d8ab77f06b3f5
https://github.com/telyn/node-jrc/blob/c91b8d0a7d95856b7650b815234d8ab77f06b3f5/lib/message.js#L13-L27
52,252
CHENXCHEN/merges-utils
lib/index.js
merge
function merge(need, options, level){ // 如果没有传第三个参数,默认无限递归右边覆盖左边 if (level == undefined) level = -1; if (options === undefined) options = {}; if (need.length == 1) return need[0]; var res = {}; for (var i = 0; i < need.length; i++){ _merge(res, need[i], options, level - 1); } return res; }
javascript
function merge(need, options, level){ // 如果没有传第三个参数,默认无限递归右边覆盖左边 if (level == undefined) level = -1; if (options === undefined) options = {}; if (need.length == 1) return need[0]; var res = {}; for (var i = 0; i < need.length; i++){ _merge(res, need[i], options, level - 1); } return res; }
[ "function", "merge", "(", "need", ",", "options", ",", "level", ")", "{", "// 如果没有传第三个参数,默认无限递归右边覆盖左边", "if", "(", "level", "==", "undefined", ")", "level", "=", "-", "1", ";", "if", "(", "options", "===", "undefined", ")", "options", "=", "{", "}", ";", "if", "(", "need", ".", "length", "==", "1", ")", "return", "need", "[", "0", "]", ";", "var", "res", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "need", ".", "length", ";", "i", "++", ")", "{", "_merge", "(", "res", ",", "need", "[", "i", "]", ",", "options", ",", "level", "-", "1", ")", ";", "}", "return", "res", ";", "}" ]
global merge function @param {Array} need need to merge @param {Object} options options for merge method @param {Number} level merge level @return {Object} the result of merges
[ "global", "merge", "function" ]
5fde6058ba791c58102a109ac4ac20e0afe7ebe7
https://github.com/CHENXCHEN/merges-utils/blob/5fde6058ba791c58102a109ac4ac20e0afe7ebe7/lib/index.js#L47-L57
52,253
meltmedia/node-usher
lib/decider/tasks/loop.js
Loop
function Loop(name, deps, fragment, loopFn, options) { if (!(this instanceof Loop)) { return new Loop(name, deps, fragment, loopFn, options); } Task.apply(this, Array.prototype.slice.call(arguments)); this.fragment = fragment; this.loopFn = (_.isFunction(loopFn)) ? loopFn : function (input) { return [input]; }; this.options = options || {}; }
javascript
function Loop(name, deps, fragment, loopFn, options) { if (!(this instanceof Loop)) { return new Loop(name, deps, fragment, loopFn, options); } Task.apply(this, Array.prototype.slice.call(arguments)); this.fragment = fragment; this.loopFn = (_.isFunction(loopFn)) ? loopFn : function (input) { return [input]; }; this.options = options || {}; }
[ "function", "Loop", "(", "name", ",", "deps", ",", "fragment", ",", "loopFn", ",", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Loop", ")", ")", "{", "return", "new", "Loop", "(", "name", ",", "deps", ",", "fragment", ",", "loopFn", ",", "options", ")", ";", "}", "Task", ".", "apply", "(", "this", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ")", ";", "this", ".", "fragment", "=", "fragment", ";", "this", ".", "loopFn", "=", "(", "_", ".", "isFunction", "(", "loopFn", ")", ")", "?", "loopFn", ":", "function", "(", "input", ")", "{", "return", "[", "input", "]", ";", "}", ";", "this", ".", "options", "=", "options", "||", "{", "}", ";", "}" ]
The loop executes in batches to help alleviate rate limit exceptions The number of items to proccess per batch and the delay between batches are both configurable @constructor
[ "The", "loop", "executes", "in", "batches", "to", "help", "alleviate", "rate", "limit", "exceptions", "The", "number", "of", "items", "to", "proccess", "per", "batch", "and", "the", "delay", "between", "batches", "are", "both", "configurable" ]
fe6183bf7097f84bef935e8d9c19463accc08ad6
https://github.com/meltmedia/node-usher/blob/fe6183bf7097f84bef935e8d9c19463accc08ad6/lib/decider/tasks/loop.js#L26-L37
52,254
quantumpayments/media
lib/qpm_media.js
createTables
function createTables() { // setup config var config = require('../config/config.js') var db = wc_db.getConnection(config.db) var sql = fs.readFileSync('model/Media.sql').toString() debug(sql) db.query(sql).then(function(ret){ debug(ret) }).catch(function(err) { debug(err) }) var sql = fs.readFileSync('model/Rating.sql').toString() debug(sql) db.query(sql).then(function(ret){ debug(ret) }).catch(function(err) { debug(err) }) var sql = fs.readFileSync('model/Tag.sql').toString() debug(sql) db.query(sql).then(function(ret){ debug(ret) }).catch(function(err) { debug(err) }) var sql = fs.readFileSync('model/MediaTag.sql').toString() debug(sql) db.query(sql).then(function(ret){ debug(ret) }).catch(function(err) { debug(err) }) var sql = fs.readFileSync('model/Fragment.sql').toString() debug(sql) db.query(sql).then(function(ret){ debug(ret) }).catch(function(err) { debug(err) }) var sql = fs.readFileSync('model/Meta.sql').toString() debug(sql) db.query(sql).then(function(ret){ debug(ret) }).catch(function(err) { debug(err) }) var sql = fs.readFileSync('model/User.sql').toString() debug(sql) db.query(sql).then(function(ret){ debug(ret) }).catch(function(err) { debug(err) }) }
javascript
function createTables() { // setup config var config = require('../config/config.js') var db = wc_db.getConnection(config.db) var sql = fs.readFileSync('model/Media.sql').toString() debug(sql) db.query(sql).then(function(ret){ debug(ret) }).catch(function(err) { debug(err) }) var sql = fs.readFileSync('model/Rating.sql').toString() debug(sql) db.query(sql).then(function(ret){ debug(ret) }).catch(function(err) { debug(err) }) var sql = fs.readFileSync('model/Tag.sql').toString() debug(sql) db.query(sql).then(function(ret){ debug(ret) }).catch(function(err) { debug(err) }) var sql = fs.readFileSync('model/MediaTag.sql').toString() debug(sql) db.query(sql).then(function(ret){ debug(ret) }).catch(function(err) { debug(err) }) var sql = fs.readFileSync('model/Fragment.sql').toString() debug(sql) db.query(sql).then(function(ret){ debug(ret) }).catch(function(err) { debug(err) }) var sql = fs.readFileSync('model/Meta.sql').toString() debug(sql) db.query(sql).then(function(ret){ debug(ret) }).catch(function(err) { debug(err) }) var sql = fs.readFileSync('model/User.sql').toString() debug(sql) db.query(sql).then(function(ret){ debug(ret) }).catch(function(err) { debug(err) }) }
[ "function", "createTables", "(", ")", "{", "// setup config", "var", "config", "=", "require", "(", "'../config/config.js'", ")", "var", "db", "=", "wc_db", ".", "getConnection", "(", "config", ".", "db", ")", "var", "sql", "=", "fs", ".", "readFileSync", "(", "'model/Media.sql'", ")", ".", "toString", "(", ")", "debug", "(", "sql", ")", "db", ".", "query", "(", "sql", ")", ".", "then", "(", "function", "(", "ret", ")", "{", "debug", "(", "ret", ")", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "debug", "(", "err", ")", "}", ")", "var", "sql", "=", "fs", ".", "readFileSync", "(", "'model/Rating.sql'", ")", ".", "toString", "(", ")", "debug", "(", "sql", ")", "db", ".", "query", "(", "sql", ")", ".", "then", "(", "function", "(", "ret", ")", "{", "debug", "(", "ret", ")", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "debug", "(", "err", ")", "}", ")", "var", "sql", "=", "fs", ".", "readFileSync", "(", "'model/Tag.sql'", ")", ".", "toString", "(", ")", "debug", "(", "sql", ")", "db", ".", "query", "(", "sql", ")", ".", "then", "(", "function", "(", "ret", ")", "{", "debug", "(", "ret", ")", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "debug", "(", "err", ")", "}", ")", "var", "sql", "=", "fs", ".", "readFileSync", "(", "'model/MediaTag.sql'", ")", ".", "toString", "(", ")", "debug", "(", "sql", ")", "db", ".", "query", "(", "sql", ")", ".", "then", "(", "function", "(", "ret", ")", "{", "debug", "(", "ret", ")", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "debug", "(", "err", ")", "}", ")", "var", "sql", "=", "fs", ".", "readFileSync", "(", "'model/Fragment.sql'", ")", ".", "toString", "(", ")", "debug", "(", "sql", ")", "db", ".", "query", "(", "sql", ")", ".", "then", "(", "function", "(", "ret", ")", "{", "debug", "(", "ret", ")", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "debug", "(", "err", ")", "}", ")", "var", "sql", "=", "fs", ".", "readFileSync", "(", "'model/Meta.sql'", ")", ".", "toString", "(", ")", "debug", "(", "sql", ")", "db", ".", "query", "(", "sql", ")", ".", "then", "(", "function", "(", "ret", ")", "{", "debug", "(", "ret", ")", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "debug", "(", "err", ")", "}", ")", "var", "sql", "=", "fs", ".", "readFileSync", "(", "'model/User.sql'", ")", ".", "toString", "(", ")", "debug", "(", "sql", ")", "db", ".", "query", "(", "sql", ")", ".", "then", "(", "function", "(", "ret", ")", "{", "debug", "(", "ret", ")", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "debug", "(", "err", ")", "}", ")", "}" ]
Creates database tables.
[ "Creates", "database", "tables", "." ]
b53034e6dd2a94dca950e60a49e403aceaa1cdf1
https://github.com/quantumpayments/media/blob/b53034e6dd2a94dca950e60a49e403aceaa1cdf1/lib/qpm_media.js#L37-L98
52,255
quantumpayments/media
lib/qpm_media.js
addMedia
function addMedia(uri, contentType, safe) { if (!uri || uri === '') { return 'You must enter a valid uri' } safe = safe || 0 return new Promise((resolve, reject) => { var config = require('../config/config.js') var conn = wc_db.getConnection(config.db) // sniff content type if (!contentType) { // image if (uri.indexOf('.jpg') !== -1) { contentType = 'image' } if (uri.indexOf('.png') !== -1) { contentType = 'image' } if (uri.indexOf('.gif') !== -1) { contentType = 'image' } if (uri.indexOf('.svg') !== -1) { contentType = 'image' } // video if (uri.indexOf('.mp4') !== -1) { contentType = 'video' } if (uri.indexOf('.mpg') !== -1) { contentType = 'video' } if (uri.indexOf('.mov') !== -1) { contentType = 'video' } if (uri.indexOf('.wmv') !== -1) { contentType = 'video' } if (uri.indexOf('.avi') !== -1) { contentType = 'video' } if (uri.indexOf('.m4v') !== -1) { contentType = 'video' } if (uri.indexOf('.mkv') !== -1) { contentType = 'video' } // audio if (uri.indexOf('.mp3') !== -1) { contentType = 'audio' } if (uri.indexOf('.ogg') !== -1) { contentType = 'video' } if (uri.indexOf('.flv') !== -1) { contentType = 'video' } } var sql = 'INSERT into Media values (NULL, :uri, NULL, NULL, NULL, :contentType, ' + safe + ')' conn.query(sql, { replacements: { "uri" : uri, "contentType" : contentType } }).then(function(ret){ return resolve({"ret" : ret, "conn" : conn}) }).catch(function(err) { return reject(err) }) }) }
javascript
function addMedia(uri, contentType, safe) { if (!uri || uri === '') { return 'You must enter a valid uri' } safe = safe || 0 return new Promise((resolve, reject) => { var config = require('../config/config.js') var conn = wc_db.getConnection(config.db) // sniff content type if (!contentType) { // image if (uri.indexOf('.jpg') !== -1) { contentType = 'image' } if (uri.indexOf('.png') !== -1) { contentType = 'image' } if (uri.indexOf('.gif') !== -1) { contentType = 'image' } if (uri.indexOf('.svg') !== -1) { contentType = 'image' } // video if (uri.indexOf('.mp4') !== -1) { contentType = 'video' } if (uri.indexOf('.mpg') !== -1) { contentType = 'video' } if (uri.indexOf('.mov') !== -1) { contentType = 'video' } if (uri.indexOf('.wmv') !== -1) { contentType = 'video' } if (uri.indexOf('.avi') !== -1) { contentType = 'video' } if (uri.indexOf('.m4v') !== -1) { contentType = 'video' } if (uri.indexOf('.mkv') !== -1) { contentType = 'video' } // audio if (uri.indexOf('.mp3') !== -1) { contentType = 'audio' } if (uri.indexOf('.ogg') !== -1) { contentType = 'video' } if (uri.indexOf('.flv') !== -1) { contentType = 'video' } } var sql = 'INSERT into Media values (NULL, :uri, NULL, NULL, NULL, :contentType, ' + safe + ')' conn.query(sql, { replacements: { "uri" : uri, "contentType" : contentType } }).then(function(ret){ return resolve({"ret" : ret, "conn" : conn}) }).catch(function(err) { return reject(err) }) }) }
[ "function", "addMedia", "(", "uri", ",", "contentType", ",", "safe", ")", "{", "if", "(", "!", "uri", "||", "uri", "===", "''", ")", "{", "return", "'You must enter a valid uri'", "}", "safe", "=", "safe", "||", "0", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "var", "config", "=", "require", "(", "'../config/config.js'", ")", "var", "conn", "=", "wc_db", ".", "getConnection", "(", "config", ".", "db", ")", "// sniff content type", "if", "(", "!", "contentType", ")", "{", "// image", "if", "(", "uri", ".", "indexOf", "(", "'.jpg'", ")", "!==", "-", "1", ")", "{", "contentType", "=", "'image'", "}", "if", "(", "uri", ".", "indexOf", "(", "'.png'", ")", "!==", "-", "1", ")", "{", "contentType", "=", "'image'", "}", "if", "(", "uri", ".", "indexOf", "(", "'.gif'", ")", "!==", "-", "1", ")", "{", "contentType", "=", "'image'", "}", "if", "(", "uri", ".", "indexOf", "(", "'.svg'", ")", "!==", "-", "1", ")", "{", "contentType", "=", "'image'", "}", "// video", "if", "(", "uri", ".", "indexOf", "(", "'.mp4'", ")", "!==", "-", "1", ")", "{", "contentType", "=", "'video'", "}", "if", "(", "uri", ".", "indexOf", "(", "'.mpg'", ")", "!==", "-", "1", ")", "{", "contentType", "=", "'video'", "}", "if", "(", "uri", ".", "indexOf", "(", "'.mov'", ")", "!==", "-", "1", ")", "{", "contentType", "=", "'video'", "}", "if", "(", "uri", ".", "indexOf", "(", "'.wmv'", ")", "!==", "-", "1", ")", "{", "contentType", "=", "'video'", "}", "if", "(", "uri", ".", "indexOf", "(", "'.avi'", ")", "!==", "-", "1", ")", "{", "contentType", "=", "'video'", "}", "if", "(", "uri", ".", "indexOf", "(", "'.m4v'", ")", "!==", "-", "1", ")", "{", "contentType", "=", "'video'", "}", "if", "(", "uri", ".", "indexOf", "(", "'.mkv'", ")", "!==", "-", "1", ")", "{", "contentType", "=", "'video'", "}", "// audio", "if", "(", "uri", ".", "indexOf", "(", "'.mp3'", ")", "!==", "-", "1", ")", "{", "contentType", "=", "'audio'", "}", "if", "(", "uri", ".", "indexOf", "(", "'.ogg'", ")", "!==", "-", "1", ")", "{", "contentType", "=", "'video'", "}", "if", "(", "uri", ".", "indexOf", "(", "'.flv'", ")", "!==", "-", "1", ")", "{", "contentType", "=", "'video'", "}", "}", "var", "sql", "=", "'INSERT into Media values (NULL, :uri, NULL, NULL, NULL, :contentType, '", "+", "safe", "+", "')'", "conn", ".", "query", "(", "sql", ",", "{", "replacements", ":", "{", "\"uri\"", ":", "uri", ",", "\"contentType\"", ":", "contentType", "}", "}", ")", ".", "then", "(", "function", "(", "ret", ")", "{", "return", "resolve", "(", "{", "\"ret\"", ":", "ret", ",", "\"conn\"", ":", "conn", "}", ")", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "return", "reject", "(", "err", ")", "}", ")", "}", ")", "}" ]
Adds media to the database @param {string} uri The URI to add. @param {string} contentType The content type. @param {Object} callback The callback.
[ "Adds", "media", "to", "the", "database" ]
b53034e6dd2a94dca950e60a49e403aceaa1cdf1
https://github.com/quantumpayments/media/blob/b53034e6dd2a94dca950e60a49e403aceaa1cdf1/lib/qpm_media.js#L106-L175
52,256
quantumpayments/media
lib/qpm_media.js
addRating
function addRating(rating, config, conn) { // validate if (!rating.uri || rating.uri === '') { return 'You must enter a valid uri' } if (!rating.reviewer || rating.reviewer === '') { return 'You must enter a valid reviewer' } if (isNaN(rating.rating)) { return 'You must enter a valid rating' } // defaults config = config || require('../config/config.js') debug(rating) // main return new Promise((resolve, reject) => { if (!conn) { var conn = wc_db.getConnection(config.db) } insertRating(rating, config, conn).then(function(ret) { return resolve({"ret": ret, "conn": conn}) }).catch(function(err) { debug('addRating', 'updating instead of insert') return updateRating(rating, config, conn) }).then(function(ret){ return resolve({"ret": ret, "conn": conn}) }).catch(function(){ return reject({"ret": ret, "conn": conn}) }) }) }
javascript
function addRating(rating, config, conn) { // validate if (!rating.uri || rating.uri === '') { return 'You must enter a valid uri' } if (!rating.reviewer || rating.reviewer === '') { return 'You must enter a valid reviewer' } if (isNaN(rating.rating)) { return 'You must enter a valid rating' } // defaults config = config || require('../config/config.js') debug(rating) // main return new Promise((resolve, reject) => { if (!conn) { var conn = wc_db.getConnection(config.db) } insertRating(rating, config, conn).then(function(ret) { return resolve({"ret": ret, "conn": conn}) }).catch(function(err) { debug('addRating', 'updating instead of insert') return updateRating(rating, config, conn) }).then(function(ret){ return resolve({"ret": ret, "conn": conn}) }).catch(function(){ return reject({"ret": ret, "conn": conn}) }) }) }
[ "function", "addRating", "(", "rating", ",", "config", ",", "conn", ")", "{", "// validate", "if", "(", "!", "rating", ".", "uri", "||", "rating", ".", "uri", "===", "''", ")", "{", "return", "'You must enter a valid uri'", "}", "if", "(", "!", "rating", ".", "reviewer", "||", "rating", ".", "reviewer", "===", "''", ")", "{", "return", "'You must enter a valid reviewer'", "}", "if", "(", "isNaN", "(", "rating", ".", "rating", ")", ")", "{", "return", "'You must enter a valid rating'", "}", "// defaults", "config", "=", "config", "||", "require", "(", "'../config/config.js'", ")", "debug", "(", "rating", ")", "// main", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "!", "conn", ")", "{", "var", "conn", "=", "wc_db", ".", "getConnection", "(", "config", ".", "db", ")", "}", "insertRating", "(", "rating", ",", "config", ",", "conn", ")", ".", "then", "(", "function", "(", "ret", ")", "{", "return", "resolve", "(", "{", "\"ret\"", ":", "ret", ",", "\"conn\"", ":", "conn", "}", ")", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "debug", "(", "'addRating'", ",", "'updating instead of insert'", ")", "return", "updateRating", "(", "rating", ",", "config", ",", "conn", ")", "}", ")", ".", "then", "(", "function", "(", "ret", ")", "{", "return", "resolve", "(", "{", "\"ret\"", ":", "ret", ",", "\"conn\"", ":", "conn", "}", ")", "}", ")", ".", "catch", "(", "function", "(", ")", "{", "return", "reject", "(", "{", "\"ret\"", ":", "ret", ",", "\"conn\"", ":", "conn", "}", ")", "}", ")", "}", ")", "}" ]
Adds rating to the database @param {Object} rating The rating to add. @param {Object} config The optional config. @param {Object} conn The optional db connection. @return {Object} Promise with success or fail.
[ "Adds", "rating", "to", "the", "database" ]
b53034e6dd2a94dca950e60a49e403aceaa1cdf1
https://github.com/quantumpayments/media/blob/b53034e6dd2a94dca950e60a49e403aceaa1cdf1/lib/qpm_media.js#L185-L224
52,257
quantumpayments/media
lib/qpm_media.js
addMeta
function addMeta(params, config, conn) { params = params || {} // validate if (!params.uri || params.uri === '') { return 'You must enter a valid uri' } // defaults config = config || require('../config/config.js') debug(params) // main // main return new Promise((resolve, reject) => { if (!conn) { var conn = wc_db.getConnection(config.db) } if (!params.subtitlesURI) { params.subtitlesURI = null } if (!params.charenc) { params.charenc = null } var sql = 'INSERT into Meta select a.id, :length, :subtitlesURI, :charenc from Media a where a.uri = :uri ;' debug('addMeta', sql, params) conn.query(sql, { replacements: { "length" : params.length, "subtitlesURI": params.subtitlesURI, "uri" : params.uri, "charenc" : params.charenc } }).then(function(ret){ return resolve({"ret" : ret, "conn" : conn}) }).catch(function(err) { return reject({"err" : err, "conn" : conn}) }) }) }
javascript
function addMeta(params, config, conn) { params = params || {} // validate if (!params.uri || params.uri === '') { return 'You must enter a valid uri' } // defaults config = config || require('../config/config.js') debug(params) // main // main return new Promise((resolve, reject) => { if (!conn) { var conn = wc_db.getConnection(config.db) } if (!params.subtitlesURI) { params.subtitlesURI = null } if (!params.charenc) { params.charenc = null } var sql = 'INSERT into Meta select a.id, :length, :subtitlesURI, :charenc from Media a where a.uri = :uri ;' debug('addMeta', sql, params) conn.query(sql, { replacements: { "length" : params.length, "subtitlesURI": params.subtitlesURI, "uri" : params.uri, "charenc" : params.charenc } }).then(function(ret){ return resolve({"ret" : ret, "conn" : conn}) }).catch(function(err) { return reject({"err" : err, "conn" : conn}) }) }) }
[ "function", "addMeta", "(", "params", ",", "config", ",", "conn", ")", "{", "params", "=", "params", "||", "{", "}", "// validate", "if", "(", "!", "params", ".", "uri", "||", "params", ".", "uri", "===", "''", ")", "{", "return", "'You must enter a valid uri'", "}", "// defaults", "config", "=", "config", "||", "require", "(", "'../config/config.js'", ")", "debug", "(", "params", ")", "// main", "// main", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "!", "conn", ")", "{", "var", "conn", "=", "wc_db", ".", "getConnection", "(", "config", ".", "db", ")", "}", "if", "(", "!", "params", ".", "subtitlesURI", ")", "{", "params", ".", "subtitlesURI", "=", "null", "}", "if", "(", "!", "params", ".", "charenc", ")", "{", "params", ".", "charenc", "=", "null", "}", "var", "sql", "=", "'INSERT into Meta select a.id, :length, :subtitlesURI, :charenc from Media a where a.uri = :uri ;'", "debug", "(", "'addMeta'", ",", "sql", ",", "params", ")", "conn", ".", "query", "(", "sql", ",", "{", "replacements", ":", "{", "\"length\"", ":", "params", ".", "length", ",", "\"subtitlesURI\"", ":", "params", ".", "subtitlesURI", ",", "\"uri\"", ":", "params", ".", "uri", ",", "\"charenc\"", ":", "params", ".", "charenc", "}", "}", ")", ".", "then", "(", "function", "(", "ret", ")", "{", "return", "resolve", "(", "{", "\"ret\"", ":", "ret", ",", "\"conn\"", ":", "conn", "}", ")", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "return", "reject", "(", "{", "\"err\"", ":", "err", ",", "\"conn\"", ":", "conn", "}", ")", "}", ")", "}", ")", "}" ]
Adds a meta record to the database @param {Object} params The meta info. @param {Object} config The optional config. @param {Object} conn The optional db connection. @return {Object} Promise with success or fail.
[ "Adds", "a", "meta", "record", "to", "the", "database" ]
b53034e6dd2a94dca950e60a49e403aceaa1cdf1
https://github.com/quantumpayments/media/blob/b53034e6dd2a94dca950e60a49e403aceaa1cdf1/lib/qpm_media.js#L274-L315
52,258
quantumpayments/media
lib/qpm_media.js
addFragment
function addFragment(params, config, conn) { // validate if ( (!params.id || params.id === '') && (!params.uri || params.uri === '') ) { return 'You must enter a valid id or uri' } // defaults config = config || require('../config/config.js') debug(params) // main return new Promise((resolve, reject) => { if (!conn) { var conn = wc_db.getConnection(config.db) } var sql if (params.id) { sql = 'INSERT into Fragment values (:id, :start, :end, NULL, NOW(), 1)' } else { sql = 'INSERT into Fragment Select m.id, :start, :end, NULL, NOW(), u.id from Media m, User u where m.uri = :uri and u.uri = :webid' } debug(sql) conn.query(sql, { replacements: { "id" : params.id, "start" : params.start, "end" : params.end, "uri" : params.uri, "webid" : params.webid } }).then(function(ret){ return resolve({"ret" : ret, "conn" : conn}) }).catch(function(err) { return reject({"err" : err, "conn" : conn}) }) }) }
javascript
function addFragment(params, config, conn) { // validate if ( (!params.id || params.id === '') && (!params.uri || params.uri === '') ) { return 'You must enter a valid id or uri' } // defaults config = config || require('../config/config.js') debug(params) // main return new Promise((resolve, reject) => { if (!conn) { var conn = wc_db.getConnection(config.db) } var sql if (params.id) { sql = 'INSERT into Fragment values (:id, :start, :end, NULL, NOW(), 1)' } else { sql = 'INSERT into Fragment Select m.id, :start, :end, NULL, NOW(), u.id from Media m, User u where m.uri = :uri and u.uri = :webid' } debug(sql) conn.query(sql, { replacements: { "id" : params.id, "start" : params.start, "end" : params.end, "uri" : params.uri, "webid" : params.webid } }).then(function(ret){ return resolve({"ret" : ret, "conn" : conn}) }).catch(function(err) { return reject({"err" : err, "conn" : conn}) }) }) }
[ "function", "addFragment", "(", "params", ",", "config", ",", "conn", ")", "{", "// validate", "if", "(", "(", "!", "params", ".", "id", "||", "params", ".", "id", "===", "''", ")", "&&", "(", "!", "params", ".", "uri", "||", "params", ".", "uri", "===", "''", ")", ")", "{", "return", "'You must enter a valid id or uri'", "}", "// defaults", "config", "=", "config", "||", "require", "(", "'../config/config.js'", ")", "debug", "(", "params", ")", "// main", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "!", "conn", ")", "{", "var", "conn", "=", "wc_db", ".", "getConnection", "(", "config", ".", "db", ")", "}", "var", "sql", "if", "(", "params", ".", "id", ")", "{", "sql", "=", "'INSERT into Fragment values (:id, :start, :end, NULL, NOW(), 1)'", "}", "else", "{", "sql", "=", "'INSERT into Fragment Select m.id, :start, :end, NULL, NOW(), u.id from Media m, User u where m.uri = :uri and u.uri = :webid'", "}", "debug", "(", "sql", ")", "conn", ".", "query", "(", "sql", ",", "{", "replacements", ":", "{", "\"id\"", ":", "params", ".", "id", ",", "\"start\"", ":", "params", ".", "start", ",", "\"end\"", ":", "params", ".", "end", ",", "\"uri\"", ":", "params", ".", "uri", ",", "\"webid\"", ":", "params", ".", "webid", "}", "}", ")", ".", "then", "(", "function", "(", "ret", ")", "{", "return", "resolve", "(", "{", "\"ret\"", ":", "ret", ",", "\"conn\"", ":", "conn", "}", ")", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "return", "reject", "(", "{", "\"err\"", ":", "err", ",", "\"conn\"", ":", "conn", "}", ")", "}", ")", "}", ")", "}" ]
Adds a fragment to the database @param {Object} params The parameter info. @param {Object} config The optional config. @param {Object} conn The optional db connection. @return {Object} Promise with success or fail.
[ "Adds", "a", "fragment", "to", "the", "database" ]
b53034e6dd2a94dca950e60a49e403aceaa1cdf1
https://github.com/quantumpayments/media/blob/b53034e6dd2a94dca950e60a49e403aceaa1cdf1/lib/qpm_media.js#L324-L359
52,259
quantumpayments/media
lib/qpm_media.js
insertRating
function insertRating(rating, config, conn) { // validate if ( (!rating.uri || rating.uri === '') && (!rating.cacheURI || rating.cacheURI === '') ) { return 'You must enter a valid uri' } if (!rating.reviewer || rating.reviewer === '') { return 'You must enter a valid reviewer' } // defaults config = config || require('../config/config.js') // main return new Promise((resolve, reject) => { if (!conn) { var conn = wc_db.getConnection(config.db) } var sql if (rating.uri) { sql = 'INSERT into Rating values (NULL, :uri, :rating, NULL, :reviewer, NULL, NOW())' } else { sql = 'INSERT into Rating SELECT NULL, a.uri, :rating, NULL, :reviewer, NULL, NOW() from Media a where a.cacheURI = :cacheURI ' } debug('insertRating', sql, rating) conn.query(sql, { replacements: { "uri" : rating.uri, "cacheURI" : rating.cacheURI, "reviewer" : rating.reviewer, "rating" : rating.rating ? rating.rating : null } }).then(function(ret){ return resolve({"ret" : ret, "conn" : conn}) }).catch(function(err) { return reject({"err" : err, "conn" : conn}) }) }) }
javascript
function insertRating(rating, config, conn) { // validate if ( (!rating.uri || rating.uri === '') && (!rating.cacheURI || rating.cacheURI === '') ) { return 'You must enter a valid uri' } if (!rating.reviewer || rating.reviewer === '') { return 'You must enter a valid reviewer' } // defaults config = config || require('../config/config.js') // main return new Promise((resolve, reject) => { if (!conn) { var conn = wc_db.getConnection(config.db) } var sql if (rating.uri) { sql = 'INSERT into Rating values (NULL, :uri, :rating, NULL, :reviewer, NULL, NOW())' } else { sql = 'INSERT into Rating SELECT NULL, a.uri, :rating, NULL, :reviewer, NULL, NOW() from Media a where a.cacheURI = :cacheURI ' } debug('insertRating', sql, rating) conn.query(sql, { replacements: { "uri" : rating.uri, "cacheURI" : rating.cacheURI, "reviewer" : rating.reviewer, "rating" : rating.rating ? rating.rating : null } }).then(function(ret){ return resolve({"ret" : ret, "conn" : conn}) }).catch(function(err) { return reject({"err" : err, "conn" : conn}) }) }) }
[ "function", "insertRating", "(", "rating", ",", "config", ",", "conn", ")", "{", "// validate", "if", "(", "(", "!", "rating", ".", "uri", "||", "rating", ".", "uri", "===", "''", ")", "&&", "(", "!", "rating", ".", "cacheURI", "||", "rating", ".", "cacheURI", "===", "''", ")", ")", "{", "return", "'You must enter a valid uri'", "}", "if", "(", "!", "rating", ".", "reviewer", "||", "rating", ".", "reviewer", "===", "''", ")", "{", "return", "'You must enter a valid reviewer'", "}", "// defaults", "config", "=", "config", "||", "require", "(", "'../config/config.js'", ")", "// main", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "!", "conn", ")", "{", "var", "conn", "=", "wc_db", ".", "getConnection", "(", "config", ".", "db", ")", "}", "var", "sql", "if", "(", "rating", ".", "uri", ")", "{", "sql", "=", "'INSERT into Rating values (NULL, :uri, :rating, NULL, :reviewer, NULL, NOW())'", "}", "else", "{", "sql", "=", "'INSERT into Rating SELECT NULL, a.uri, :rating, NULL, :reviewer, NULL, NOW() from Media a where a.cacheURI = :cacheURI '", "}", "debug", "(", "'insertRating'", ",", "sql", ",", "rating", ")", "conn", ".", "query", "(", "sql", ",", "{", "replacements", ":", "{", "\"uri\"", ":", "rating", ".", "uri", ",", "\"cacheURI\"", ":", "rating", ".", "cacheURI", ",", "\"reviewer\"", ":", "rating", ".", "reviewer", ",", "\"rating\"", ":", "rating", ".", "rating", "?", "rating", ".", "rating", ":", "null", "}", "}", ")", ".", "then", "(", "function", "(", "ret", ")", "{", "return", "resolve", "(", "{", "\"ret\"", ":", "ret", ",", "\"conn\"", ":", "conn", "}", ")", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "return", "reject", "(", "{", "\"err\"", ":", "err", ",", "\"conn\"", ":", "conn", "}", ")", "}", ")", "}", ")", "}" ]
Inserts rating to the database @param {Object} rating The rating to add. @param {Object} config The optional config. @param {Object} conn The optional db connection. @return {Object} Promise with success or fail.
[ "Inserts", "rating", "to", "the", "database" ]
b53034e6dd2a94dca950e60a49e403aceaa1cdf1
https://github.com/quantumpayments/media/blob/b53034e6dd2a94dca950e60a49e403aceaa1cdf1/lib/qpm_media.js#L413-L451
52,260
quantumpayments/media
lib/qpm_media.js
getTopImages
function getTopImages(params, config, conn) { // defaults config = config || require('../config/config.js') var limit = 10 if (!isNaN(params.limit)) { limit = params.limit } // main return new Promise((resolve, reject) => { if (!conn) { var conn = wc_db.getConnection(config.db) } var sql if (params.reviewer) { sql = 'SELECT * from Rating where reviewer = :reviewer order by rating DESC LIMIT :limit ' } else { sql = 'SELECT uri, avg(rating) rating from Rating group by uri order by rating DESC LIMIT :limit ' } conn.query(sql, { replacements: { "reviewer" : params.reviewer, "limit" : params.limit } }).then(function(ret){ return resolve({"ret" : ret, "conn" : conn}) }).catch(function(err) { return reject({"err" : err, "conn" : conn}) }) }) }
javascript
function getTopImages(params, config, conn) { // defaults config = config || require('../config/config.js') var limit = 10 if (!isNaN(params.limit)) { limit = params.limit } // main return new Promise((resolve, reject) => { if (!conn) { var conn = wc_db.getConnection(config.db) } var sql if (params.reviewer) { sql = 'SELECT * from Rating where reviewer = :reviewer order by rating DESC LIMIT :limit ' } else { sql = 'SELECT uri, avg(rating) rating from Rating group by uri order by rating DESC LIMIT :limit ' } conn.query(sql, { replacements: { "reviewer" : params.reviewer, "limit" : params.limit } }).then(function(ret){ return resolve({"ret" : ret, "conn" : conn}) }).catch(function(err) { return reject({"err" : err, "conn" : conn}) }) }) }
[ "function", "getTopImages", "(", "params", ",", "config", ",", "conn", ")", "{", "// defaults", "config", "=", "config", "||", "require", "(", "'../config/config.js'", ")", "var", "limit", "=", "10", "if", "(", "!", "isNaN", "(", "params", ".", "limit", ")", ")", "{", "limit", "=", "params", ".", "limit", "}", "// main", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "!", "conn", ")", "{", "var", "conn", "=", "wc_db", ".", "getConnection", "(", "config", ".", "db", ")", "}", "var", "sql", "if", "(", "params", ".", "reviewer", ")", "{", "sql", "=", "'SELECT * from Rating where reviewer = :reviewer order by rating DESC LIMIT :limit '", "}", "else", "{", "sql", "=", "'SELECT uri, avg(rating) rating from Rating group by uri order by rating DESC LIMIT :limit '", "}", "conn", ".", "query", "(", "sql", ",", "{", "replacements", ":", "{", "\"reviewer\"", ":", "params", ".", "reviewer", ",", "\"limit\"", ":", "params", ".", "limit", "}", "}", ")", ".", "then", "(", "function", "(", "ret", ")", "{", "return", "resolve", "(", "{", "\"ret\"", ":", "ret", ",", "\"conn\"", ":", "conn", "}", ")", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "return", "reject", "(", "{", "\"err\"", ":", "err", ",", "\"conn\"", ":", "conn", "}", ")", "}", ")", "}", ")", "}" ]
Get the top images @param {Object} rating The rating to add. @param {Object} config The optional config. @param {Object} conn The optional db connection. @return {Object} Promise with success or fail.
[ "Get", "the", "top", "images" ]
b53034e6dd2a94dca950e60a49e403aceaa1cdf1
https://github.com/quantumpayments/media/blob/b53034e6dd2a94dca950e60a49e403aceaa1cdf1/lib/qpm_media.js#L633-L667
52,261
quantumpayments/media
lib/qpm_media.js
getTags
function getTags(params, config, conn) { // defaults config = config || require('../config/config.js') params.limit = 100 // main return new Promise((resolve, reject) => { if (!conn) { var conn = wc_db.getConnection(config.db) } if (params.uri) { var sql = 'SELECT t.tag from Media m left join MediaTag mt on m.id = mt.media_id left join Tag t on mt.tag_id = t.id where m.uri = :uri order by t.tag LIMIT :limit ' } else { var sql = 'SELECT * from Tag order by id LIMIT :limit ' } debug(sql) conn.query(sql, { replacements: { "limit" : params.limit, "uri" : params.uri } }).then(function(ret){ return resolve({"ret" : ret, "conn" : conn}) }).catch(function(err) { return reject({"err" : err, "conn" : conn}) }) }) }
javascript
function getTags(params, config, conn) { // defaults config = config || require('../config/config.js') params.limit = 100 // main return new Promise((resolve, reject) => { if (!conn) { var conn = wc_db.getConnection(config.db) } if (params.uri) { var sql = 'SELECT t.tag from Media m left join MediaTag mt on m.id = mt.media_id left join Tag t on mt.tag_id = t.id where m.uri = :uri order by t.tag LIMIT :limit ' } else { var sql = 'SELECT * from Tag order by id LIMIT :limit ' } debug(sql) conn.query(sql, { replacements: { "limit" : params.limit, "uri" : params.uri } }).then(function(ret){ return resolve({"ret" : ret, "conn" : conn}) }).catch(function(err) { return reject({"err" : err, "conn" : conn}) }) }) }
[ "function", "getTags", "(", "params", ",", "config", ",", "conn", ")", "{", "// defaults", "config", "=", "config", "||", "require", "(", "'../config/config.js'", ")", "params", ".", "limit", "=", "100", "// main", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "!", "conn", ")", "{", "var", "conn", "=", "wc_db", ".", "getConnection", "(", "config", ".", "db", ")", "}", "if", "(", "params", ".", "uri", ")", "{", "var", "sql", "=", "'SELECT t.tag from Media m left join MediaTag mt on m.id = mt.media_id left join Tag t on mt.tag_id = t.id where m.uri = :uri order by t.tag LIMIT :limit '", "}", "else", "{", "var", "sql", "=", "'SELECT * from Tag order by id LIMIT :limit '", "}", "debug", "(", "sql", ")", "conn", ".", "query", "(", "sql", ",", "{", "replacements", ":", "{", "\"limit\"", ":", "params", ".", "limit", ",", "\"uri\"", ":", "params", ".", "uri", "}", "}", ")", ".", "then", "(", "function", "(", "ret", ")", "{", "return", "resolve", "(", "{", "\"ret\"", ":", "ret", ",", "\"conn\"", ":", "conn", "}", ")", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "return", "reject", "(", "{", "\"err\"", ":", "err", ",", "\"conn\"", ":", "conn", "}", ")", "}", ")", "}", ")", "}" ]
Get list of tags @param {Object} params Info about tags. @param {Object} config The optional config. @param {Object} conn The optional db connection. @return {Object} Promise with success or fail.
[ "Get", "list", "of", "tags" ]
b53034e6dd2a94dca950e60a49e403aceaa1cdf1
https://github.com/quantumpayments/media/blob/b53034e6dd2a94dca950e60a49e403aceaa1cdf1/lib/qpm_media.js#L677-L708
52,262
quantumpayments/media
lib/qpm_media.js
getRandomUnseenImage
function getRandomUnseenImage(params, config, conn) { // defaults config = config || require('../config/config.js') params = params || {} var max = config.db.max || 0 var optimization = config.optimization || 0 var offset = Math.floor(Math.random() * max) params.optimization = optimization params.offset = offset // main return new Promise((resolve, reject) => { if (!conn) { var conn = wc_db.getConnection(config.db) } var safeClause = '' if (params.safe !== undefined && params.safe !== null) { if (parseInt(params.safe) === 0) { safeClause = '' } else { safeClause = ' and a.safe = :safe ' } } else { safeClause = ' and a.safe = 1 ' } if (params.reviewer) { var sql = "SELECT * from Media m where m.uri not in (select r.uri from Rating r join User u on u.id = r.reviewer_id) and contentType = 'image' and lastSeen is NULL " + safeClause + " and FLOOR( m.id / :optimization ) = FLOOR( RAND() * :optimization ) and m.id >= :offset LIMIT 1;" } else { var sql = "SELECT * from Media m where contentType = 'image' and lastSeen is NULL order by RAND() LIMIT 1;" } debug('getRandomUnseenImage', sql, params) conn.query(sql, { replacements: { "optimization" : params.optimization, "offset" : params.offset } }).then(function(ret){ return resolve({"ret" : ret, "conn" : conn}) }).catch(function(err) { return reject({"err" : err, "conn" : conn}) }) }) }
javascript
function getRandomUnseenImage(params, config, conn) { // defaults config = config || require('../config/config.js') params = params || {} var max = config.db.max || 0 var optimization = config.optimization || 0 var offset = Math.floor(Math.random() * max) params.optimization = optimization params.offset = offset // main return new Promise((resolve, reject) => { if (!conn) { var conn = wc_db.getConnection(config.db) } var safeClause = '' if (params.safe !== undefined && params.safe !== null) { if (parseInt(params.safe) === 0) { safeClause = '' } else { safeClause = ' and a.safe = :safe ' } } else { safeClause = ' and a.safe = 1 ' } if (params.reviewer) { var sql = "SELECT * from Media m where m.uri not in (select r.uri from Rating r join User u on u.id = r.reviewer_id) and contentType = 'image' and lastSeen is NULL " + safeClause + " and FLOOR( m.id / :optimization ) = FLOOR( RAND() * :optimization ) and m.id >= :offset LIMIT 1;" } else { var sql = "SELECT * from Media m where contentType = 'image' and lastSeen is NULL order by RAND() LIMIT 1;" } debug('getRandomUnseenImage', sql, params) conn.query(sql, { replacements: { "optimization" : params.optimization, "offset" : params.offset } }).then(function(ret){ return resolve({"ret" : ret, "conn" : conn}) }).catch(function(err) { return reject({"err" : err, "conn" : conn}) }) }) }
[ "function", "getRandomUnseenImage", "(", "params", ",", "config", ",", "conn", ")", "{", "// defaults", "config", "=", "config", "||", "require", "(", "'../config/config.js'", ")", "params", "=", "params", "||", "{", "}", "var", "max", "=", "config", ".", "db", ".", "max", "||", "0", "var", "optimization", "=", "config", ".", "optimization", "||", "0", "var", "offset", "=", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "max", ")", "params", ".", "optimization", "=", "optimization", "params", ".", "offset", "=", "offset", "// main", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "!", "conn", ")", "{", "var", "conn", "=", "wc_db", ".", "getConnection", "(", "config", ".", "db", ")", "}", "var", "safeClause", "=", "''", "if", "(", "params", ".", "safe", "!==", "undefined", "&&", "params", ".", "safe", "!==", "null", ")", "{", "if", "(", "parseInt", "(", "params", ".", "safe", ")", "===", "0", ")", "{", "safeClause", "=", "''", "}", "else", "{", "safeClause", "=", "' and a.safe = :safe '", "}", "}", "else", "{", "safeClause", "=", "' and a.safe = 1 '", "}", "if", "(", "params", ".", "reviewer", ")", "{", "var", "sql", "=", "\"SELECT * from Media m where m.uri not in (select r.uri from Rating r join User u on u.id = r.reviewer_id) and contentType = 'image' and lastSeen is NULL \"", "+", "safeClause", "+", "\" and FLOOR( m.id / :optimization ) = FLOOR( RAND() * :optimization ) and m.id >= :offset LIMIT 1;\"", "}", "else", "{", "var", "sql", "=", "\"SELECT * from Media m where contentType = 'image' and lastSeen is NULL order by RAND() LIMIT 1;\"", "}", "debug", "(", "'getRandomUnseenImage'", ",", "sql", ",", "params", ")", "conn", ".", "query", "(", "sql", ",", "{", "replacements", ":", "{", "\"optimization\"", ":", "params", ".", "optimization", ",", "\"offset\"", ":", "params", ".", "offset", "}", "}", ")", ".", "then", "(", "function", "(", "ret", ")", "{", "return", "resolve", "(", "{", "\"ret\"", ":", "ret", ",", "\"conn\"", ":", "conn", "}", ")", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "return", "reject", "(", "{", "\"err\"", ":", "err", ",", "\"conn\"", ":", "conn", "}", ")", "}", ")", "}", ")", "}" ]
Get a random unseen image @param {Object} rating The rating to add. @param {Object} config The optional config. @param {Object} conn The optional db connection. @return {Object} Promise with success or fail.
[ "Get", "a", "random", "unseen", "image" ]
b53034e6dd2a94dca950e60a49e403aceaa1cdf1
https://github.com/quantumpayments/media/blob/b53034e6dd2a94dca950e60a49e403aceaa1cdf1/lib/qpm_media.js#L861-L909
52,263
quantumpayments/media
lib/qpm_media.js
getLastSeen
function getLastSeen(params, config, conn) { // defaults config = config || require('../config/config.js') params = params || {} params.webid = params.webid || 'http://melvincarvalho.com/#me' // main return new Promise((resolve, reject) => { if (!conn) { var conn = wc_db.getConnection(config.db) } var sql = "select f.* from Fragment f join User u on f.user_id = u.id where u.uri = :webid order by lastSeen desc LIMIT 1;" var fragLastSeen var mediaLastSeen var val debug('getLastSeen', sql, params) conn.query(sql, { replacements: { "webid" : params.webid } }).then(function(frag){ var sql = "select r.* from Rating r join User u on u.id = r.reviewer_id and u.uri = :webid order by datePublished desc LIMIT 1;" debug('getLastSeen', sql, params) debug(frag) val = frag fragLastSeen = frag[0][0].lastSeen debug(fragLastSeen) return conn.query(sql, { replacements: { "webid" : params.webid } }) }).then(function(media) { debug(media) mediaLastSeen = media[0][0].datePublished debug(mediaLastSeen) if (mediaLastSeen > fragLastSeen) { debug('media is latest : ' + media.lastSeen) return resolve({"ret" : media, "conn" : conn}) } else { debug('frag is latest : ' + media.lastSeen) return resolve({"ret" : val, "conn" : conn}) } }).catch(function(err) { return reject({"err" : err, "conn" : conn}) }) }) }
javascript
function getLastSeen(params, config, conn) { // defaults config = config || require('../config/config.js') params = params || {} params.webid = params.webid || 'http://melvincarvalho.com/#me' // main return new Promise((resolve, reject) => { if (!conn) { var conn = wc_db.getConnection(config.db) } var sql = "select f.* from Fragment f join User u on f.user_id = u.id where u.uri = :webid order by lastSeen desc LIMIT 1;" var fragLastSeen var mediaLastSeen var val debug('getLastSeen', sql, params) conn.query(sql, { replacements: { "webid" : params.webid } }).then(function(frag){ var sql = "select r.* from Rating r join User u on u.id = r.reviewer_id and u.uri = :webid order by datePublished desc LIMIT 1;" debug('getLastSeen', sql, params) debug(frag) val = frag fragLastSeen = frag[0][0].lastSeen debug(fragLastSeen) return conn.query(sql, { replacements: { "webid" : params.webid } }) }).then(function(media) { debug(media) mediaLastSeen = media[0][0].datePublished debug(mediaLastSeen) if (mediaLastSeen > fragLastSeen) { debug('media is latest : ' + media.lastSeen) return resolve({"ret" : media, "conn" : conn}) } else { debug('frag is latest : ' + media.lastSeen) return resolve({"ret" : val, "conn" : conn}) } }).catch(function(err) { return reject({"err" : err, "conn" : conn}) }) }) }
[ "function", "getLastSeen", "(", "params", ",", "config", ",", "conn", ")", "{", "// defaults", "config", "=", "config", "||", "require", "(", "'../config/config.js'", ")", "params", "=", "params", "||", "{", "}", "params", ".", "webid", "=", "params", ".", "webid", "||", "'http://melvincarvalho.com/#me'", "// main", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "!", "conn", ")", "{", "var", "conn", "=", "wc_db", ".", "getConnection", "(", "config", ".", "db", ")", "}", "var", "sql", "=", "\"select f.* from Fragment f join User u on f.user_id = u.id where u.uri = :webid order by lastSeen desc LIMIT 1;\"", "var", "fragLastSeen", "var", "mediaLastSeen", "var", "val", "debug", "(", "'getLastSeen'", ",", "sql", ",", "params", ")", "conn", ".", "query", "(", "sql", ",", "{", "replacements", ":", "{", "\"webid\"", ":", "params", ".", "webid", "}", "}", ")", ".", "then", "(", "function", "(", "frag", ")", "{", "var", "sql", "=", "\"select r.* from Rating r join User u on u.id = r.reviewer_id and u.uri = :webid order by datePublished desc LIMIT 1;\"", "debug", "(", "'getLastSeen'", ",", "sql", ",", "params", ")", "debug", "(", "frag", ")", "val", "=", "frag", "fragLastSeen", "=", "frag", "[", "0", "]", "[", "0", "]", ".", "lastSeen", "debug", "(", "fragLastSeen", ")", "return", "conn", ".", "query", "(", "sql", ",", "{", "replacements", ":", "{", "\"webid\"", ":", "params", ".", "webid", "}", "}", ")", "}", ")", ".", "then", "(", "function", "(", "media", ")", "{", "debug", "(", "media", ")", "mediaLastSeen", "=", "media", "[", "0", "]", "[", "0", "]", ".", "datePublished", "debug", "(", "mediaLastSeen", ")", "if", "(", "mediaLastSeen", ">", "fragLastSeen", ")", "{", "debug", "(", "'media is latest : '", "+", "media", ".", "lastSeen", ")", "return", "resolve", "(", "{", "\"ret\"", ":", "media", ",", "\"conn\"", ":", "conn", "}", ")", "}", "else", "{", "debug", "(", "'frag is latest : '", "+", "media", ".", "lastSeen", ")", "return", "resolve", "(", "{", "\"ret\"", ":", "val", ",", "\"conn\"", ":", "conn", "}", ")", "}", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "return", "reject", "(", "{", "\"err\"", ":", "err", ",", "\"conn\"", ":", "conn", "}", ")", "}", ")", "}", ")", "}" ]
Get get the last seen item @param {Object} rating The rating to add. @param {Object} config The optional config. @param {Object} conn The optional db connection. @return {Object} Promise with success or fail.
[ "Get", "get", "the", "last", "seen", "item" ]
b53034e6dd2a94dca950e60a49e403aceaa1cdf1
https://github.com/quantumpayments/media/blob/b53034e6dd2a94dca950e60a49e403aceaa1cdf1/lib/qpm_media.js#L1040-L1087
52,264
ljcl/hubot-iss
src/index.js
astroViewer
function astroViewer (options, cb) { request({ url: 'http://astroviewer-sat2c.appspot.com/predictor', qs: { var: 'passesData', lat: options.lat, lon: options.lon, name: options.name }, headers: { 'User-Agent': 'request' } }, function (error, response, body) { if (error) { cb(error) } // Trim the javascript response var raw = body.slice(17).slice(0, -2) // make sure the keys have quotes around them raw = raw.replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:/g, '"$2":') // turn the result into valid JSON (hopefully) var info = JSON.parse(raw) cb(false, info) }) }
javascript
function astroViewer (options, cb) { request({ url: 'http://astroviewer-sat2c.appspot.com/predictor', qs: { var: 'passesData', lat: options.lat, lon: options.lon, name: options.name }, headers: { 'User-Agent': 'request' } }, function (error, response, body) { if (error) { cb(error) } // Trim the javascript response var raw = body.slice(17).slice(0, -2) // make sure the keys have quotes around them raw = raw.replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:/g, '"$2":') // turn the result into valid JSON (hopefully) var info = JSON.parse(raw) cb(false, info) }) }
[ "function", "astroViewer", "(", "options", ",", "cb", ")", "{", "request", "(", "{", "url", ":", "'http://astroviewer-sat2c.appspot.com/predictor'", ",", "qs", ":", "{", "var", ":", "'passesData'", ",", "lat", ":", "options", ".", "lat", ",", "lon", ":", "options", ".", "lon", ",", "name", ":", "options", ".", "name", "}", ",", "headers", ":", "{", "'User-Agent'", ":", "'request'", "}", "}", ",", "function", "(", "error", ",", "response", ",", "body", ")", "{", "if", "(", "error", ")", "{", "cb", "(", "error", ")", "}", "// Trim the javascript response", "var", "raw", "=", "body", ".", "slice", "(", "17", ")", ".", "slice", "(", "0", ",", "-", "2", ")", "// make sure the keys have quotes around them", "raw", "=", "raw", ".", "replace", "(", "/", "(['\"])?([a-zA-Z0-9_]+)(['\"])?:", "/", "g", ",", "'\"$2\":'", ")", "// turn the result into valid JSON (hopefully)", "var", "info", "=", "JSON", ".", "parse", "(", "raw", ")", "cb", "(", "false", ",", "info", ")", "}", ")", "}" ]
Query astroviewer and dangerously turn the javascript into parsable JSON. @param {object} options An object containing the latitude, longitude and location name @param {Function} cb
[ "Query", "astroviewer", "and", "dangerously", "turn", "the", "javascript", "into", "parsable", "JSON", "." ]
15103c9e491e417406ae99a09e098d87fa02251f
https://github.com/ljcl/hubot-iss/blob/15103c9e491e417406ae99a09e098d87fa02251f/src/index.js#L27-L51
52,265
ljcl/hubot-iss
src/index.js
listPasses
function listPasses (data, cb) { var index = 0 var passes = data.passes var newpasses = '' if (passes.length === 0) { newpasses += ':( No results found for **' + data.location.name + '**' } else { passes.map(function (obj) { if (index === 0) { newpasses += '**' + data.location.name + '** (' + obj.timezone + ')\n' } var dateFormat = 'YYYYMMDDHHmmss' var newDateFormat = 'ddd MMM Do, hh:mma' var begin = moment(obj.begin, dateFormat).format(newDateFormat) var duration = moment.utc(moment(obj.end, dateFormat).diff(moment(obj.begin, dateFormat))).format('m\\m s\\s') newpasses += begin + ' (' + duration + ')\n' index++ }) } newpasses += ':satellite:' cb(false, newpasses) }
javascript
function listPasses (data, cb) { var index = 0 var passes = data.passes var newpasses = '' if (passes.length === 0) { newpasses += ':( No results found for **' + data.location.name + '**' } else { passes.map(function (obj) { if (index === 0) { newpasses += '**' + data.location.name + '** (' + obj.timezone + ')\n' } var dateFormat = 'YYYYMMDDHHmmss' var newDateFormat = 'ddd MMM Do, hh:mma' var begin = moment(obj.begin, dateFormat).format(newDateFormat) var duration = moment.utc(moment(obj.end, dateFormat).diff(moment(obj.begin, dateFormat))).format('m\\m s\\s') newpasses += begin + ' (' + duration + ')\n' index++ }) } newpasses += ':satellite:' cb(false, newpasses) }
[ "function", "listPasses", "(", "data", ",", "cb", ")", "{", "var", "index", "=", "0", "var", "passes", "=", "data", ".", "passes", "var", "newpasses", "=", "''", "if", "(", "passes", ".", "length", "===", "0", ")", "{", "newpasses", "+=", "':( No results found for **'", "+", "data", ".", "location", ".", "name", "+", "'**'", "}", "else", "{", "passes", ".", "map", "(", "function", "(", "obj", ")", "{", "if", "(", "index", "===", "0", ")", "{", "newpasses", "+=", "'**'", "+", "data", ".", "location", ".", "name", "+", "'** ('", "+", "obj", ".", "timezone", "+", "')\\n'", "}", "var", "dateFormat", "=", "'YYYYMMDDHHmmss'", "var", "newDateFormat", "=", "'ddd MMM Do, hh:mma'", "var", "begin", "=", "moment", "(", "obj", ".", "begin", ",", "dateFormat", ")", ".", "format", "(", "newDateFormat", ")", "var", "duration", "=", "moment", ".", "utc", "(", "moment", "(", "obj", ".", "end", ",", "dateFormat", ")", ".", "diff", "(", "moment", "(", "obj", ".", "begin", ",", "dateFormat", ")", ")", ")", ".", "format", "(", "'m\\\\m s\\\\s'", ")", "newpasses", "+=", "begin", "+", "' ('", "+", "duration", "+", "')\\n'", "index", "++", "}", ")", "}", "newpasses", "+=", "':satellite:'", "cb", "(", "false", ",", "newpasses", ")", "}" ]
Build up a string based on the astroViewer data @param {object} data Return the astroviewer object @param {Function} cb
[ "Build", "up", "a", "string", "based", "on", "the", "astroViewer", "data" ]
15103c9e491e417406ae99a09e098d87fa02251f
https://github.com/ljcl/hubot-iss/blob/15103c9e491e417406ae99a09e098d87fa02251f/src/index.js#L58-L79
52,266
konstantin24121/grunt-font-loader
tasks/font_loader.js
closeConnection
function closeConnection(errMsg) { if (ftp) { ftp.raw.quit(function(err, res) { if (err) { grunt.log.error(err); done(false); } ftp.destroy(); grunt.log.ok("FTP connection closed!"); done(); }); } else if (errMsg) { grunt.log.warn(errMsg); done(false); } else { done(); } }
javascript
function closeConnection(errMsg) { if (ftp) { ftp.raw.quit(function(err, res) { if (err) { grunt.log.error(err); done(false); } ftp.destroy(); grunt.log.ok("FTP connection closed!"); done(); }); } else if (errMsg) { grunt.log.warn(errMsg); done(false); } else { done(); } }
[ "function", "closeConnection", "(", "errMsg", ")", "{", "if", "(", "ftp", ")", "{", "ftp", ".", "raw", ".", "quit", "(", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "grunt", ".", "log", ".", "error", "(", "err", ")", ";", "done", "(", "false", ")", ";", "}", "ftp", ".", "destroy", "(", ")", ";", "grunt", ".", "log", ".", "ok", "(", "\"FTP connection closed!\"", ")", ";", "done", "(", ")", ";", "}", ")", ";", "}", "else", "if", "(", "errMsg", ")", "{", "grunt", ".", "log", ".", "warn", "(", "errMsg", ")", ";", "done", "(", "false", ")", ";", "}", "else", "{", "done", "(", ")", ";", "}", "}" ]
Close the connection and end the asynchronous task
[ "Close", "the", "connection", "and", "end", "the", "asynchronous", "task" ]
624d93efd6bdd6b52bfe24b28db715d065600661
https://github.com/konstantin24121/grunt-font-loader/blob/624d93efd6bdd6b52bfe24b28db715d065600661/tasks/font_loader.js#L71-L88
52,267
konstantin24121/grunt-font-loader
tasks/font_loader.js
getNextClar
function getNextClar(params, string, files) { if (params === 'all') { files.push(string); return true; } if (Array.isArray(params)){ params.forEach(function(item, i, array) { files.push(string + '.' + item + '$'); return true; }); }else if (typeof params === 'object'){ var param; for (param in params) { var buffer = string; var regular; if (param === 'all'){ regular = '\\w+'; }else{ regular = param; } string += !string ? regular : '-' + regular; getNextClar(params[param], string, files); string = buffer; } }else{ files.push(string + '.' + params + '$'); } return true; }
javascript
function getNextClar(params, string, files) { if (params === 'all') { files.push(string); return true; } if (Array.isArray(params)){ params.forEach(function(item, i, array) { files.push(string + '.' + item + '$'); return true; }); }else if (typeof params === 'object'){ var param; for (param in params) { var buffer = string; var regular; if (param === 'all'){ regular = '\\w+'; }else{ regular = param; } string += !string ? regular : '-' + regular; getNextClar(params[param], string, files); string = buffer; } }else{ files.push(string + '.' + params + '$'); } return true; }
[ "function", "getNextClar", "(", "params", ",", "string", ",", "files", ")", "{", "if", "(", "params", "===", "'all'", ")", "{", "files", ".", "push", "(", "string", ")", ";", "return", "true", ";", "}", "if", "(", "Array", ".", "isArray", "(", "params", ")", ")", "{", "params", ".", "forEach", "(", "function", "(", "item", ",", "i", ",", "array", ")", "{", "files", ".", "push", "(", "string", "+", "'.'", "+", "item", "+", "'$'", ")", ";", "return", "true", ";", "}", ")", ";", "}", "else", "if", "(", "typeof", "params", "===", "'object'", ")", "{", "var", "param", ";", "for", "(", "param", "in", "params", ")", "{", "var", "buffer", "=", "string", ";", "var", "regular", ";", "if", "(", "param", "===", "'all'", ")", "{", "regular", "=", "'\\\\w+'", ";", "}", "else", "{", "regular", "=", "param", ";", "}", "string", "+=", "!", "string", "?", "regular", ":", "'-'", "+", "regular", ";", "getNextClar", "(", "params", "[", "param", "]", ",", "string", ",", "files", ")", ";", "string", "=", "buffer", ";", "}", "}", "else", "{", "files", ".", "push", "(", "string", "+", "'.'", "+", "params", "+", "'$'", ")", ";", "}", "return", "true", ";", "}" ]
Create regexp massive @param {array} params massive @param {string} string regexp @param {array} files creating massive @return {boolean}
[ "Create", "regexp", "massive" ]
624d93efd6bdd6b52bfe24b28db715d065600661
https://github.com/konstantin24121/grunt-font-loader/blob/624d93efd6bdd6b52bfe24b28db715d065600661/tasks/font_loader.js#L97-L125
52,268
konstantin24121/grunt-font-loader
tasks/font_loader.js
createDownloadList
function createDownloadList() { uploadFiles = []; files.forEach(function(item, i, arr) { var preg = new RegExp(item); var check = false; serverFonts.forEach(function(item, i, arr) { if (preg.test(item)) { uploadFiles.push(item); check = true; // serverFonts.remove(item); } }); if (!check){ grunt.log.warn('You have no suitable fonts at pattern ' + item); } }); downloadFiles(); }
javascript
function createDownloadList() { uploadFiles = []; files.forEach(function(item, i, arr) { var preg = new RegExp(item); var check = false; serverFonts.forEach(function(item, i, arr) { if (preg.test(item)) { uploadFiles.push(item); check = true; // serverFonts.remove(item); } }); if (!check){ grunt.log.warn('You have no suitable fonts at pattern ' + item); } }); downloadFiles(); }
[ "function", "createDownloadList", "(", ")", "{", "uploadFiles", "=", "[", "]", ";", "files", ".", "forEach", "(", "function", "(", "item", ",", "i", ",", "arr", ")", "{", "var", "preg", "=", "new", "RegExp", "(", "item", ")", ";", "var", "check", "=", "false", ";", "serverFonts", ".", "forEach", "(", "function", "(", "item", ",", "i", ",", "arr", ")", "{", "if", "(", "preg", ".", "test", "(", "item", ")", ")", "{", "uploadFiles", ".", "push", "(", "item", ")", ";", "check", "=", "true", ";", "// serverFonts.remove(item);", "}", "}", ")", ";", "if", "(", "!", "check", ")", "{", "grunt", ".", "log", ".", "warn", "(", "'You have no suitable fonts at pattern '", "+", "item", ")", ";", "}", "}", ")", ";", "downloadFiles", "(", ")", ";", "}" ]
Create list for downloading
[ "Create", "list", "for", "downloading" ]
624d93efd6bdd6b52bfe24b28db715d065600661
https://github.com/konstantin24121/grunt-font-loader/blob/624d93efd6bdd6b52bfe24b28db715d065600661/tasks/font_loader.js#L130-L150
52,269
konstantin24121/grunt-font-loader
tasks/font_loader.js
removeFonts
function removeFonts(files){ var dest = normalizeDir(options.dest); files.forEach(function(item, i, arr){ grunt.file.delete(dest + item); grunt.log.warn('File ' + item + ' remove.'); }); }
javascript
function removeFonts(files){ var dest = normalizeDir(options.dest); files.forEach(function(item, i, arr){ grunt.file.delete(dest + item); grunt.log.warn('File ' + item + ' remove.'); }); }
[ "function", "removeFonts", "(", "files", ")", "{", "var", "dest", "=", "normalizeDir", "(", "options", ".", "dest", ")", ";", "files", ".", "forEach", "(", "function", "(", "item", ",", "i", ",", "arr", ")", "{", "grunt", ".", "file", ".", "delete", "(", "dest", "+", "item", ")", ";", "grunt", ".", "log", ".", "warn", "(", "'File '", "+", "item", "+", "' remove.'", ")", ";", "}", ")", ";", "}" ]
Remove unused files @param {array} files files need to remove
[ "Remove", "unused", "files" ]
624d93efd6bdd6b52bfe24b28db715d065600661
https://github.com/konstantin24121/grunt-font-loader/blob/624d93efd6bdd6b52bfe24b28db715d065600661/tasks/font_loader.js#L156-L162
52,270
konstantin24121/grunt-font-loader
tasks/font_loader.js
getFilesList
function getFilesList(pattern) { //If pattern empty return all avaliable fonts if (pattern === undefined || pattern === '') { formatingFontsArray(serverFonts); closeConnection(); return; // We are completed, close connection and end the program } var serverFiles = [], preg = new RegExp('[\\w\\-\\.]*' + pattern + '[\\w\\-\\.]*'); function regular() { if (serverFonts.length < 1) { if (serverFiles.length !== 0){ formatingFontsArray(serverFiles); }else{ grunt.log.warn('We haven\'t any suitable fonts'); } closeConnection(); return; // We are completed, close connection and end the program } var file = serverFonts.pop(); if (preg.test(file)) { serverFiles.push(file); } regular(); } regular(); }
javascript
function getFilesList(pattern) { //If pattern empty return all avaliable fonts if (pattern === undefined || pattern === '') { formatingFontsArray(serverFonts); closeConnection(); return; // We are completed, close connection and end the program } var serverFiles = [], preg = new RegExp('[\\w\\-\\.]*' + pattern + '[\\w\\-\\.]*'); function regular() { if (serverFonts.length < 1) { if (serverFiles.length !== 0){ formatingFontsArray(serverFiles); }else{ grunt.log.warn('We haven\'t any suitable fonts'); } closeConnection(); return; // We are completed, close connection and end the program } var file = serverFonts.pop(); if (preg.test(file)) { serverFiles.push(file); } regular(); } regular(); }
[ "function", "getFilesList", "(", "pattern", ")", "{", "//If pattern empty return all avaliable fonts", "if", "(", "pattern", "===", "undefined", "||", "pattern", "===", "''", ")", "{", "formatingFontsArray", "(", "serverFonts", ")", ";", "closeConnection", "(", ")", ";", "return", ";", "// We are completed, close connection and end the program", "}", "var", "serverFiles", "=", "[", "]", ",", "preg", "=", "new", "RegExp", "(", "'[\\\\w\\\\-\\\\.]*'", "+", "pattern", "+", "'[\\\\w\\\\-\\\\.]*'", ")", ";", "function", "regular", "(", ")", "{", "if", "(", "serverFonts", ".", "length", "<", "1", ")", "{", "if", "(", "serverFiles", ".", "length", "!==", "0", ")", "{", "formatingFontsArray", "(", "serverFiles", ")", ";", "}", "else", "{", "grunt", ".", "log", ".", "warn", "(", "'We haven\\'t any suitable fonts'", ")", ";", "}", "closeConnection", "(", ")", ";", "return", ";", "// We are completed, close connection and end the program", "}", "var", "file", "=", "serverFonts", ".", "pop", "(", ")", ";", "if", "(", "preg", ".", "test", "(", "file", ")", ")", "{", "serverFiles", ".", "push", "(", "file", ")", ";", "}", "regular", "(", ")", ";", "}", "regular", "(", ")", ";", "}" ]
Get list from server @param {String} pattern pattern for search
[ "Get", "list", "from", "server" ]
624d93efd6bdd6b52bfe24b28db715d065600661
https://github.com/konstantin24121/grunt-font-loader/blob/624d93efd6bdd6b52bfe24b28db715d065600661/tasks/font_loader.js#L214-L243
52,271
konstantin24121/grunt-font-loader
tasks/font_loader.js
formatingFontsArray
function formatingFontsArray(array) { var fileContent = '', file = [], buffer = array[0].split('.')[0], exp = []; function writeResult() { var str = buffer + ' [' + exp.join(', ') + ']'; fileContent += str + '\n'; grunt.log.ok(str); } array.forEach(function(item, i, arr) { file = item.split('.'); if (buffer === file[0]) { exp.push(file[1]); } else { writeResult(); buffer = file[0]; exp = []; exp.push(file[1]); } }); writeResult(); //Put last search result into file grunt.file.mkdir(options.dest); grunt.file.write(normalizeDir(options.dest) + '.fonts', fileContent); }
javascript
function formatingFontsArray(array) { var fileContent = '', file = [], buffer = array[0].split('.')[0], exp = []; function writeResult() { var str = buffer + ' [' + exp.join(', ') + ']'; fileContent += str + '\n'; grunt.log.ok(str); } array.forEach(function(item, i, arr) { file = item.split('.'); if (buffer === file[0]) { exp.push(file[1]); } else { writeResult(); buffer = file[0]; exp = []; exp.push(file[1]); } }); writeResult(); //Put last search result into file grunt.file.mkdir(options.dest); grunt.file.write(normalizeDir(options.dest) + '.fonts', fileContent); }
[ "function", "formatingFontsArray", "(", "array", ")", "{", "var", "fileContent", "=", "''", ",", "file", "=", "[", "]", ",", "buffer", "=", "array", "[", "0", "]", ".", "split", "(", "'.'", ")", "[", "0", "]", ",", "exp", "=", "[", "]", ";", "function", "writeResult", "(", ")", "{", "var", "str", "=", "buffer", "+", "' ['", "+", "exp", ".", "join", "(", "', '", ")", "+", "']'", ";", "fileContent", "+=", "str", "+", "'\\n'", ";", "grunt", ".", "log", ".", "ok", "(", "str", ")", ";", "}", "array", ".", "forEach", "(", "function", "(", "item", ",", "i", ",", "arr", ")", "{", "file", "=", "item", ".", "split", "(", "'.'", ")", ";", "if", "(", "buffer", "===", "file", "[", "0", "]", ")", "{", "exp", ".", "push", "(", "file", "[", "1", "]", ")", ";", "}", "else", "{", "writeResult", "(", ")", ";", "buffer", "=", "file", "[", "0", "]", ";", "exp", "=", "[", "]", ";", "exp", ".", "push", "(", "file", "[", "1", "]", ")", ";", "}", "}", ")", ";", "writeResult", "(", ")", ";", "//Put last search result into file", "grunt", ".", "file", ".", "mkdir", "(", "options", ".", "dest", ")", ";", "grunt", ".", "file", ".", "write", "(", "normalizeDir", "(", "options", ".", "dest", ")", "+", "'.fonts'", ",", "fileContent", ")", ";", "}" ]
Formating array with font into better readding @param {Array} array
[ "Formating", "array", "with", "font", "into", "better", "readding" ]
624d93efd6bdd6b52bfe24b28db715d065600661
https://github.com/konstantin24121/grunt-font-loader/blob/624d93efd6bdd6b52bfe24b28db715d065600661/tasks/font_loader.js#L249-L277
52,272
bholloway/browserify-anonymous-labeler
lib/source-replacer.js
sourceReplacer
function sourceReplacer(source, replacements) { // shared var getBefore = getField('before'); var getAfter = getField('after'); // split source code into lines, include the delimiter var lines = source.split(/(\r?\n)/g); // split each line further by the replacements for (var i = 0; i < lines.length; i += 2) { var split = lines[i] = [].concat(lines[i]); // initialise each line text into an array for (var before in replacements) { var after = replacements[before]; split.forEach(splitByReplacement(before, after)); } } // utility methods return { toStringBefore: toStringBefore, toStringAfter : toStringAfter, getColumnAfter: getColumnAfter }; /** * String representation of text before replacement * @returns {string} */ function toStringBefore() { return lines.map(getBefore).join(''); } /** * String representation of text after replacement * @returns {string} */ function toStringAfter() { return lines.map(getAfter).join(''); } /** * Get a column position delta as at the given line and column that has occured as a result of replacement. * @param {number} lineIndex The line in the original source at which to evaluate the offset * @param {number} columnIndex The column in the original source at which to evaluate the offset * @returns {number} A column offset in characters */ function getColumnAfter(lineIndex, columnIndex) { if (lineIndex in lines) { var line = lines[lineIndex]; var count = 0; var offset = 0; for (var i = 0; i < line.length; i++) { var widthBefore = getBefore(line[i]).length; var widthAfter = getAfter(line[i]).length; var nextCount = count + widthBefore; if (nextCount > columnIndex) { break; } else { count = nextCount; offset += widthAfter - widthBefore; } } return columnIndex + offset; } else { throw new Error('Line index is out of range'); } } }
javascript
function sourceReplacer(source, replacements) { // shared var getBefore = getField('before'); var getAfter = getField('after'); // split source code into lines, include the delimiter var lines = source.split(/(\r?\n)/g); // split each line further by the replacements for (var i = 0; i < lines.length; i += 2) { var split = lines[i] = [].concat(lines[i]); // initialise each line text into an array for (var before in replacements) { var after = replacements[before]; split.forEach(splitByReplacement(before, after)); } } // utility methods return { toStringBefore: toStringBefore, toStringAfter : toStringAfter, getColumnAfter: getColumnAfter }; /** * String representation of text before replacement * @returns {string} */ function toStringBefore() { return lines.map(getBefore).join(''); } /** * String representation of text after replacement * @returns {string} */ function toStringAfter() { return lines.map(getAfter).join(''); } /** * Get a column position delta as at the given line and column that has occured as a result of replacement. * @param {number} lineIndex The line in the original source at which to evaluate the offset * @param {number} columnIndex The column in the original source at which to evaluate the offset * @returns {number} A column offset in characters */ function getColumnAfter(lineIndex, columnIndex) { if (lineIndex in lines) { var line = lines[lineIndex]; var count = 0; var offset = 0; for (var i = 0; i < line.length; i++) { var widthBefore = getBefore(line[i]).length; var widthAfter = getAfter(line[i]).length; var nextCount = count + widthBefore; if (nextCount > columnIndex) { break; } else { count = nextCount; offset += widthAfter - widthBefore; } } return columnIndex + offset; } else { throw new Error('Line index is out of range'); } } }
[ "function", "sourceReplacer", "(", "source", ",", "replacements", ")", "{", "// shared", "var", "getBefore", "=", "getField", "(", "'before'", ")", ";", "var", "getAfter", "=", "getField", "(", "'after'", ")", ";", "// split source code into lines, include the delimiter", "var", "lines", "=", "source", ".", "split", "(", "/", "(\\r?\\n)", "/", "g", ")", ";", "// split each line further by the replacements", "for", "(", "var", "i", "=", "0", ";", "i", "<", "lines", ".", "length", ";", "i", "+=", "2", ")", "{", "var", "split", "=", "lines", "[", "i", "]", "=", "[", "]", ".", "concat", "(", "lines", "[", "i", "]", ")", ";", "// initialise each line text into an array", "for", "(", "var", "before", "in", "replacements", ")", "{", "var", "after", "=", "replacements", "[", "before", "]", ";", "split", ".", "forEach", "(", "splitByReplacement", "(", "before", ",", "after", ")", ")", ";", "}", "}", "// utility methods", "return", "{", "toStringBefore", ":", "toStringBefore", ",", "toStringAfter", ":", "toStringAfter", ",", "getColumnAfter", ":", "getColumnAfter", "}", ";", "/**\n * String representation of text before replacement\n * @returns {string}\n */", "function", "toStringBefore", "(", ")", "{", "return", "lines", ".", "map", "(", "getBefore", ")", ".", "join", "(", "''", ")", ";", "}", "/**\n * String representation of text after replacement\n * @returns {string}\n */", "function", "toStringAfter", "(", ")", "{", "return", "lines", ".", "map", "(", "getAfter", ")", ".", "join", "(", "''", ")", ";", "}", "/**\n * Get a column position delta as at the given line and column that has occured as a result of replacement.\n * @param {number} lineIndex The line in the original source at which to evaluate the offset\n * @param {number} columnIndex The column in the original source at which to evaluate the offset\n * @returns {number} A column offset in characters\n */", "function", "getColumnAfter", "(", "lineIndex", ",", "columnIndex", ")", "{", "if", "(", "lineIndex", "in", "lines", ")", "{", "var", "line", "=", "lines", "[", "lineIndex", "]", ";", "var", "count", "=", "0", ";", "var", "offset", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "line", ".", "length", ";", "i", "++", ")", "{", "var", "widthBefore", "=", "getBefore", "(", "line", "[", "i", "]", ")", ".", "length", ";", "var", "widthAfter", "=", "getAfter", "(", "line", "[", "i", "]", ")", ".", "length", ";", "var", "nextCount", "=", "count", "+", "widthBefore", ";", "if", "(", "nextCount", ">", "columnIndex", ")", "{", "break", ";", "}", "else", "{", "count", "=", "nextCount", ";", "offset", "+=", "widthAfter", "-", "widthBefore", ";", "}", "}", "return", "columnIndex", "+", "offset", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Line index is out of range'", ")", ";", "}", "}", "}" ]
Make replacements to the given source code and return a set of methods to utilise it. @param {string} source Source code text without source-map comment @param {object} replacements A hash of replacements to make @returns {{toStringBefore:function, toStringAfter:function, getColumnAfter:function}} A set of methods
[ "Make", "replacements", "to", "the", "given", "source", "code", "and", "return", "a", "set", "of", "methods", "to", "utilise", "it", "." ]
651b124eefe8d1a567b2a03a0b8a3dfea87c2703
https://github.com/bholloway/browserify-anonymous-labeler/blob/651b124eefe8d1a567b2a03a0b8a3dfea87c2703/lib/source-replacer.js#L12-L80
52,273
bholloway/browserify-anonymous-labeler
lib/source-replacer.js
getColumnAfter
function getColumnAfter(lineIndex, columnIndex) { if (lineIndex in lines) { var line = lines[lineIndex]; var count = 0; var offset = 0; for (var i = 0; i < line.length; i++) { var widthBefore = getBefore(line[i]).length; var widthAfter = getAfter(line[i]).length; var nextCount = count + widthBefore; if (nextCount > columnIndex) { break; } else { count = nextCount; offset += widthAfter - widthBefore; } } return columnIndex + offset; } else { throw new Error('Line index is out of range'); } }
javascript
function getColumnAfter(lineIndex, columnIndex) { if (lineIndex in lines) { var line = lines[lineIndex]; var count = 0; var offset = 0; for (var i = 0; i < line.length; i++) { var widthBefore = getBefore(line[i]).length; var widthAfter = getAfter(line[i]).length; var nextCount = count + widthBefore; if (nextCount > columnIndex) { break; } else { count = nextCount; offset += widthAfter - widthBefore; } } return columnIndex + offset; } else { throw new Error('Line index is out of range'); } }
[ "function", "getColumnAfter", "(", "lineIndex", ",", "columnIndex", ")", "{", "if", "(", "lineIndex", "in", "lines", ")", "{", "var", "line", "=", "lines", "[", "lineIndex", "]", ";", "var", "count", "=", "0", ";", "var", "offset", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "line", ".", "length", ";", "i", "++", ")", "{", "var", "widthBefore", "=", "getBefore", "(", "line", "[", "i", "]", ")", ".", "length", ";", "var", "widthAfter", "=", "getAfter", "(", "line", "[", "i", "]", ")", ".", "length", ";", "var", "nextCount", "=", "count", "+", "widthBefore", ";", "if", "(", "nextCount", ">", "columnIndex", ")", "{", "break", ";", "}", "else", "{", "count", "=", "nextCount", ";", "offset", "+=", "widthAfter", "-", "widthBefore", ";", "}", "}", "return", "columnIndex", "+", "offset", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Line index is out of range'", ")", ";", "}", "}" ]
Get a column position delta as at the given line and column that has occured as a result of replacement. @param {number} lineIndex The line in the original source at which to evaluate the offset @param {number} columnIndex The column in the original source at which to evaluate the offset @returns {number} A column offset in characters
[ "Get", "a", "column", "position", "delta", "as", "at", "the", "given", "line", "and", "column", "that", "has", "occured", "as", "a", "result", "of", "replacement", "." ]
651b124eefe8d1a567b2a03a0b8a3dfea87c2703
https://github.com/bholloway/browserify-anonymous-labeler/blob/651b124eefe8d1a567b2a03a0b8a3dfea87c2703/lib/source-replacer.js#L59-L79
52,274
vamship/wysknd-test
lib/utils.js
function(args) { if (!args) { return []; } if (args[0] instanceof Array) { return args[0]; } return Array.prototype.slice.call(args, 0); }
javascript
function(args) { if (!args) { return []; } if (args[0] instanceof Array) { return args[0]; } return Array.prototype.slice.call(args, 0); }
[ "function", "(", "args", ")", "{", "if", "(", "!", "args", ")", "{", "return", "[", "]", ";", "}", "if", "(", "args", "[", "0", "]", "instanceof", "Array", ")", "{", "return", "args", "[", "0", "]", ";", "}", "return", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "args", ",", "0", ")", ";", "}" ]
Converts input arguments into an addy of args. If the first arg is an array, it is used as is. If not, all input args are converted into a single array. @param {Object} args The arguments object to be converted into an array. @return {Array} An array representing the parsed arguments.
[ "Converts", "input", "arguments", "into", "an", "addy", "of", "args", ".", "If", "the", "first", "arg", "is", "an", "array", "it", "is", "used", "as", "is", ".", "If", "not", "all", "input", "args", "are", "converted", "into", "a", "single", "array", "." ]
b7791c42f1c1b36be7738e2c6d24748360634003
https://github.com/vamship/wysknd-test/blob/b7791c42f1c1b36be7738e2c6d24748360634003/lib/utils.js#L13-L22
52,275
dalekjs/dalek-reporter-json
index.js
Reporter
function Reporter (opts) { this.events = opts.events; this.config = opts.config; this.data = {}; this.actionQueue = []; this.data.tests = []; this.browser = null; var defaultReportFolder = 'report'; this.dest = this.config.get('json-reporter') && this.config.get('json-reporter').dest ? this.config.get('json-reporter').dest : defaultReportFolder; this.startListening(); }
javascript
function Reporter (opts) { this.events = opts.events; this.config = opts.config; this.data = {}; this.actionQueue = []; this.data.tests = []; this.browser = null; var defaultReportFolder = 'report'; this.dest = this.config.get('json-reporter') && this.config.get('json-reporter').dest ? this.config.get('json-reporter').dest : defaultReportFolder; this.startListening(); }
[ "function", "Reporter", "(", "opts", ")", "{", "this", ".", "events", "=", "opts", ".", "events", ";", "this", ".", "config", "=", "opts", ".", "config", ";", "this", ".", "data", "=", "{", "}", ";", "this", ".", "actionQueue", "=", "[", "]", ";", "this", ".", "data", ".", "tests", "=", "[", "]", ";", "this", ".", "browser", "=", "null", ";", "var", "defaultReportFolder", "=", "'report'", ";", "this", ".", "dest", "=", "this", ".", "config", ".", "get", "(", "'json-reporter'", ")", "&&", "this", ".", "config", ".", "get", "(", "'json-reporter'", ")", ".", "dest", "?", "this", ".", "config", ".", "get", "(", "'json-reporter'", ")", ".", "dest", ":", "defaultReportFolder", ";", "this", ".", "startListening", "(", ")", ";", "}" ]
The JSON reporter can produce a file with the results of your testrun. The reporter can be installed with the following command: ``` $ npm install dalek-reporter-json --save-dev ``` The file will follow the following format. This is a first draft and will definitly change in future versions. ```javascript { "tests": [ { "id": "test806", "name": "Can get !url (OK, TDD style, message, chained)", "browser": "Chrome", "status": true, "passedAssertions": 1, "failedAssertions": 0, "actions": [ { "value": "http://localhost:5000/index.html", "type": "open", "uuid": "6ea84fc0-58bf-4e1f-bb9c-f035c6e6fae2", "kind": "action", "isAction": true }, { "success": true, "expected": "http://localhost:5000/guinea.html", "value": "http://localhost:5000/index.html", "message": "Url is not whatever", "type": "url", "kind": "assertion", "isAssertion": true } ] } ], "elapsedTime": { "minutes": 1, "seconds": 43.328535046 }, "status": true, "assertions": 1, "assertionsFailed": 0, "assertionsPassed": 1 } ``` By default the file will be written to `report/dalek.json`, you can change this by adding a config option to the your Dalekfile ```javascript "json-reporter": { "dest": "your/folder/your_file.json" } ``` @class Reporter @constructor @part JSON @api
[ "The", "JSON", "reporter", "can", "produce", "a", "file", "with", "the", "results", "of", "your", "testrun", "." ]
05c538813fd8e32d45c0aa480a7059df90f8c2c8
https://github.com/dalekjs/dalek-reporter-json/blob/05c538813fd8e32d45c0aa480a7059df90f8c2c8/index.js#L101-L113
52,276
dalekjs/dalek-reporter-json
index.js
function (data) { this.data.tests.push({ id: data.id, name: data.name, browser: this.browser, status: data.status, passedAssertions: data.passedAssertions, failedAssertions: data.failedAssertions, actions: this.actionQueue }); return this; }
javascript
function (data) { this.data.tests.push({ id: data.id, name: data.name, browser: this.browser, status: data.status, passedAssertions: data.passedAssertions, failedAssertions: data.failedAssertions, actions: this.actionQueue }); return this; }
[ "function", "(", "data", ")", "{", "this", ".", "data", ".", "tests", ".", "push", "(", "{", "id", ":", "data", ".", "id", ",", "name", ":", "data", ".", "name", ",", "browser", ":", "this", ".", "browser", ",", "status", ":", "data", ".", "status", ",", "passedAssertions", ":", "data", ".", "passedAssertions", ",", "failedAssertions", ":", "data", ".", "failedAssertions", ",", "actions", ":", "this", ".", "actionQueue", "}", ")", ";", "return", "this", ";", "}" ]
Writes data for a finished testcase @method testFinished @param {object} data Event data @chainable
[ "Writes", "data", "for", "a", "finished", "testcase" ]
05c538813fd8e32d45c0aa480a7059df90f8c2c8
https://github.com/dalekjs/dalek-reporter-json/blob/05c538813fd8e32d45c0aa480a7059df90f8c2c8/index.js#L211-L222
52,277
dalekjs/dalek-reporter-json
index.js
function (data) { this.data.elapsedTime = data.elapsedTime; this.data.status = data.status; this.data.assertions = data.assertions; this.data.assertionsFailed = data.assertionsFailed; this.data.assertionsPassed = data.assertionsPassed; var contents = JSON.stringify(this.data, false, 4); if (path.extname(this.dest) !== '.json') { this.dest = this.dest + '/dalek.json'; } this.events.emit('report:written', {type: 'json', dest: this.dest}); this._recursiveMakeDirSync(path.dirname(this.dest.replace(path.basename(this.dest, '')))); fs.writeFileSync(this.dest, contents, 'utf8'); return this; }
javascript
function (data) { this.data.elapsedTime = data.elapsedTime; this.data.status = data.status; this.data.assertions = data.assertions; this.data.assertionsFailed = data.assertionsFailed; this.data.assertionsPassed = data.assertionsPassed; var contents = JSON.stringify(this.data, false, 4); if (path.extname(this.dest) !== '.json') { this.dest = this.dest + '/dalek.json'; } this.events.emit('report:written', {type: 'json', dest: this.dest}); this._recursiveMakeDirSync(path.dirname(this.dest.replace(path.basename(this.dest, '')))); fs.writeFileSync(this.dest, contents, 'utf8'); return this; }
[ "function", "(", "data", ")", "{", "this", ".", "data", ".", "elapsedTime", "=", "data", ".", "elapsedTime", ";", "this", ".", "data", ".", "status", "=", "data", ".", "status", ";", "this", ".", "data", ".", "assertions", "=", "data", ".", "assertions", ";", "this", ".", "data", ".", "assertionsFailed", "=", "data", ".", "assertionsFailed", ";", "this", ".", "data", ".", "assertionsPassed", "=", "data", ".", "assertionsPassed", ";", "var", "contents", "=", "JSON", ".", "stringify", "(", "this", ".", "data", ",", "false", ",", "4", ")", ";", "if", "(", "path", ".", "extname", "(", "this", ".", "dest", ")", "!==", "'.json'", ")", "{", "this", ".", "dest", "=", "this", ".", "dest", "+", "'/dalek.json'", ";", "}", "this", ".", "events", ".", "emit", "(", "'report:written'", ",", "{", "type", ":", "'json'", ",", "dest", ":", "this", ".", "dest", "}", ")", ";", "this", ".", "_recursiveMakeDirSync", "(", "path", ".", "dirname", "(", "this", ".", "dest", ".", "replace", "(", "path", ".", "basename", "(", "this", ".", "dest", ",", "''", ")", ")", ")", ")", ";", "fs", ".", "writeFileSync", "(", "this", ".", "dest", ",", "contents", ",", "'utf8'", ")", ";", "return", "this", ";", "}" ]
Serializes JSON and writes file to the file system @method runnerFinished @param {object} data Event data @chainable
[ "Serializes", "JSON", "and", "writes", "file", "to", "the", "file", "system" ]
05c538813fd8e32d45c0aa480a7059df90f8c2c8
https://github.com/dalekjs/dalek-reporter-json/blob/05c538813fd8e32d45c0aa480a7059df90f8c2c8/index.js#L232-L249
52,278
schwarzkopfb/hand-over
index.js
cloneArray
function cloneArray(a) { var b = [], i = a.length while (i--) b[ i ] = a[ i ] return b }
javascript
function cloneArray(a) { var b = [], i = a.length while (i--) b[ i ] = a[ i ] return b }
[ "function", "cloneArray", "(", "a", ")", "{", "var", "b", "=", "[", "]", ",", "i", "=", "a", ".", "length", "while", "(", "i", "--", ")", "b", "[", "i", "]", "=", "a", "[", "i", "]", "return", "b", "}" ]
Utility that clones an array. @param {Array} a @return {Array}
[ "Utility", "that", "clones", "an", "array", "." ]
d09b97e3da8f323df93ad00f10bff32ee8cf8acc
https://github.com/schwarzkopfb/hand-over/blob/d09b97e3da8f323df93ad00f10bff32ee8cf8acc/index.js#L162-L166
52,279
schwarzkopfb/hand-over
index.js
installPlugin
function installPlugin(nameOrPlugin, options) { assert(nameOrPlugin, 'name or plugin is required') var plugin, ctor, self = this, parent = module.parent if (typeof nameOrPlugin === 'string') try { // local plugin if (nameOrPlugin.substring(0, 2) === './') ctor = parent.require(nameOrPlugin) // installed plugin with prefixed name 'hand-over-' else ctor = parent.require('hand-over-' + nameOrPlugin) } catch (ex) { // installed plugin without prefix ctor = parent.require(nameOrPlugin) } else ctor = nameOrPlugin // maybe we've got an already instantiated plugin if (ctor instanceof Plugin) plugin = ctor else { assert.equal(typeof ctor, 'function', 'plugin must provide a constructor') plugin = new ctor(options || {}) assert(plugin instanceof Plugin, 'plugin must be a descendant of Handover.Plugin') } assert(plugin.name, 'plugin must expose a channel name') assert(!(plugin.name in this._plugins), 'plugin is already installed') assert.equal(typeof plugin.send, 'function', "'" + plugin.name + '" does not implements `send()`') assert(plugin.send.length >= 3, "'" + plugin.name + "' plugin's `send()` method must take at least three arguments") assert.equal(typeof plugin.destroy, 'function', "'" + plugin.name + '" does not implements `destroy()`') this._plugins[ plugin.name ] = plugin // delegate plugin errors for convenience plugin.on('error', function (err) { // decorate error object with channel name if (err && typeof err === 'object') err.channel = plugin.name self.emit('error', err) }) // make it chainable return this }
javascript
function installPlugin(nameOrPlugin, options) { assert(nameOrPlugin, 'name or plugin is required') var plugin, ctor, self = this, parent = module.parent if (typeof nameOrPlugin === 'string') try { // local plugin if (nameOrPlugin.substring(0, 2) === './') ctor = parent.require(nameOrPlugin) // installed plugin with prefixed name 'hand-over-' else ctor = parent.require('hand-over-' + nameOrPlugin) } catch (ex) { // installed plugin without prefix ctor = parent.require(nameOrPlugin) } else ctor = nameOrPlugin // maybe we've got an already instantiated plugin if (ctor instanceof Plugin) plugin = ctor else { assert.equal(typeof ctor, 'function', 'plugin must provide a constructor') plugin = new ctor(options || {}) assert(plugin instanceof Plugin, 'plugin must be a descendant of Handover.Plugin') } assert(plugin.name, 'plugin must expose a channel name') assert(!(plugin.name in this._plugins), 'plugin is already installed') assert.equal(typeof plugin.send, 'function', "'" + plugin.name + '" does not implements `send()`') assert(plugin.send.length >= 3, "'" + plugin.name + "' plugin's `send()` method must take at least three arguments") assert.equal(typeof plugin.destroy, 'function', "'" + plugin.name + '" does not implements `destroy()`') this._plugins[ plugin.name ] = plugin // delegate plugin errors for convenience plugin.on('error', function (err) { // decorate error object with channel name if (err && typeof err === 'object') err.channel = plugin.name self.emit('error', err) }) // make it chainable return this }
[ "function", "installPlugin", "(", "nameOrPlugin", ",", "options", ")", "{", "assert", "(", "nameOrPlugin", ",", "'name or plugin is required'", ")", "var", "plugin", ",", "ctor", ",", "self", "=", "this", ",", "parent", "=", "module", ".", "parent", "if", "(", "typeof", "nameOrPlugin", "===", "'string'", ")", "try", "{", "// local plugin", "if", "(", "nameOrPlugin", ".", "substring", "(", "0", ",", "2", ")", "===", "'./'", ")", "ctor", "=", "parent", ".", "require", "(", "nameOrPlugin", ")", "// installed plugin with prefixed name 'hand-over-'", "else", "ctor", "=", "parent", ".", "require", "(", "'hand-over-'", "+", "nameOrPlugin", ")", "}", "catch", "(", "ex", ")", "{", "// installed plugin without prefix", "ctor", "=", "parent", ".", "require", "(", "nameOrPlugin", ")", "}", "else", "ctor", "=", "nameOrPlugin", "// maybe we've got an already instantiated plugin", "if", "(", "ctor", "instanceof", "Plugin", ")", "plugin", "=", "ctor", "else", "{", "assert", ".", "equal", "(", "typeof", "ctor", ",", "'function'", ",", "'plugin must provide a constructor'", ")", "plugin", "=", "new", "ctor", "(", "options", "||", "{", "}", ")", "assert", "(", "plugin", "instanceof", "Plugin", ",", "'plugin must be a descendant of Handover.Plugin'", ")", "}", "assert", "(", "plugin", ".", "name", ",", "'plugin must expose a channel name'", ")", "assert", "(", "!", "(", "plugin", ".", "name", "in", "this", ".", "_plugins", ")", ",", "'plugin is already installed'", ")", "assert", ".", "equal", "(", "typeof", "plugin", ".", "send", ",", "'function'", ",", "\"'\"", "+", "plugin", ".", "name", "+", "'\" does not implements `send()`'", ")", "assert", "(", "plugin", ".", "send", ".", "length", ">=", "3", ",", "\"'\"", "+", "plugin", ".", "name", "+", "\"' plugin's `send()` method must take at least three arguments\"", ")", "assert", ".", "equal", "(", "typeof", "plugin", ".", "destroy", ",", "'function'", ",", "\"'\"", "+", "plugin", ".", "name", "+", "'\" does not implements `destroy()`'", ")", "this", ".", "_plugins", "[", "plugin", ".", "name", "]", "=", "plugin", "// delegate plugin errors for convenience", "plugin", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "// decorate error object with channel name", "if", "(", "err", "&&", "typeof", "err", "===", "'object'", ")", "err", ".", "channel", "=", "plugin", ".", "name", "self", ".", "emit", "(", "'error'", ",", "err", ")", "}", ")", "// make it chainable", "return", "this", "}" ]
Include and initialize a plugin that handles a notification channel. @param {string|function|object} nameOrPlugin - Plugin name, constructor or instance to install. @param {*} [options] - Initialization settings for the plugin. @returns {Handover}
[ "Include", "and", "initialize", "a", "plugin", "that", "handles", "a", "notification", "channel", "." ]
d09b97e3da8f323df93ad00f10bff32ee8cf8acc
https://github.com/schwarzkopfb/hand-over/blob/d09b97e3da8f323df93ad00f10bff32ee8cf8acc/index.js#L175-L227
52,280
schwarzkopfb/hand-over
index.js
failed
function failed(err, userId, channel, target) { if (err && typeof err === 'object') { err.userId = userId err.channel = channel err.target = target } errors.push(err) done() }
javascript
function failed(err, userId, channel, target) { if (err && typeof err === 'object') { err.userId = userId err.channel = channel err.target = target } errors.push(err) done() }
[ "function", "failed", "(", "err", ",", "userId", ",", "channel", ",", "target", ")", "{", "if", "(", "err", "&&", "typeof", "err", "===", "'object'", ")", "{", "err", ".", "userId", "=", "userId", "err", ".", "channel", "=", "channel", "err", ".", "target", "=", "target", "}", "errors", ".", "push", "(", "err", ")", "done", "(", ")", "}" ]
helper for decorating error objects with debug info when possible and storing them to pass back to the caller when we're done
[ "helper", "for", "decorating", "error", "objects", "with", "debug", "info", "when", "possible", "and", "storing", "them", "to", "pass", "back", "to", "the", "caller", "when", "we", "re", "done" ]
d09b97e3da8f323df93ad00f10bff32ee8cf8acc
https://github.com/schwarzkopfb/hand-over/blob/d09b97e3da8f323df93ad00f10bff32ee8cf8acc/index.js#L250-L259
52,281
schwarzkopfb/hand-over
index.js
done
function done() { var arg = errors.length ? errors : null --pending || process.nextTick(callback, arg) }
javascript
function done() { var arg = errors.length ? errors : null --pending || process.nextTick(callback, arg) }
[ "function", "done", "(", ")", "{", "var", "arg", "=", "errors", ".", "length", "?", "errors", ":", "null", "--", "pending", "||", "process", ".", "nextTick", "(", "callback", ",", "arg", ")", "}" ]
helper for counting finished operations and call back when we're done
[ "helper", "for", "counting", "finished", "operations", "and", "call", "back", "when", "we", "re", "done" ]
d09b97e3da8f323df93ad00f10bff32ee8cf8acc
https://github.com/schwarzkopfb/hand-over/blob/d09b97e3da8f323df93ad00f10bff32ee8cf8acc/index.js#L262-L265
52,282
schwarzkopfb/hand-over
index.js
registerTarget
function registerTarget(userId, channel, target, callback) { this.save(userId, channel, target, function (err) { // ensure that we're firing the callback asynchronously process.nextTick(callback, err) }) // make it chainable return this }
javascript
function registerTarget(userId, channel, target, callback) { this.save(userId, channel, target, function (err) { // ensure that we're firing the callback asynchronously process.nextTick(callback, err) }) // make it chainable return this }
[ "function", "registerTarget", "(", "userId", ",", "channel", ",", "target", ",", "callback", ")", "{", "this", ".", "save", "(", "userId", ",", "channel", ",", "target", ",", "function", "(", "err", ")", "{", "// ensure that we're firing the callback asynchronously", "process", ".", "nextTick", "(", "callback", ",", "err", ")", "}", ")", "// make it chainable", "return", "this", "}" ]
Register a new target of a channel. @param {*} userId - User identifier. Type is mostly string or number but depends on the consumer. @param {string} channel - Channel name. @param {*} target - An address to send notifications to. Eg. phone number, email address, push notification token, etc. @param {function} callback @returns {Handover}
[ "Register", "a", "new", "target", "of", "a", "channel", "." ]
d09b97e3da8f323df93ad00f10bff32ee8cf8acc
https://github.com/schwarzkopfb/hand-over/blob/d09b97e3da8f323df93ad00f10bff32ee8cf8acc/index.js#L334-L342
52,283
schwarzkopfb/hand-over
index.js
unregisterTargets
function unregisterTargets(userId, channel, targets, callback) { var self = this // no target list specified, so we need to load all the targets // of the supplied channel if (arguments.length < 4) { // probably we've got the callback as the third arg callback = targets this.load(userId, channel, function (err, targets) { // cannot load targets of the given channel // call back with the error if (err) { if (typeof err === 'object') { err.userId = userId err.channel = channel } process.nextTick(callback, [ err ]) } // we've got that list! else { // ...or maybe that's not really a list? if (!Array.isArray(targets)) targets = [ targets ] removeTargets(self, userId, channel, targets, callback) } }) } // we've got an explicit target list, go remove them else { // ...or maybe that's not really a list? if (!Array.isArray(targets)) targets = [ targets ] removeTargets(self, userId, channel, targets, callback) } // make it chainable return this }
javascript
function unregisterTargets(userId, channel, targets, callback) { var self = this // no target list specified, so we need to load all the targets // of the supplied channel if (arguments.length < 4) { // probably we've got the callback as the third arg callback = targets this.load(userId, channel, function (err, targets) { // cannot load targets of the given channel // call back with the error if (err) { if (typeof err === 'object') { err.userId = userId err.channel = channel } process.nextTick(callback, [ err ]) } // we've got that list! else { // ...or maybe that's not really a list? if (!Array.isArray(targets)) targets = [ targets ] removeTargets(self, userId, channel, targets, callback) } }) } // we've got an explicit target list, go remove them else { // ...or maybe that's not really a list? if (!Array.isArray(targets)) targets = [ targets ] removeTargets(self, userId, channel, targets, callback) } // make it chainable return this }
[ "function", "unregisterTargets", "(", "userId", ",", "channel", ",", "targets", ",", "callback", ")", "{", "var", "self", "=", "this", "// no target list specified, so we need to load all the targets", "// of the supplied channel", "if", "(", "arguments", ".", "length", "<", "4", ")", "{", "// probably we've got the callback as the third arg", "callback", "=", "targets", "this", ".", "load", "(", "userId", ",", "channel", ",", "function", "(", "err", ",", "targets", ")", "{", "// cannot load targets of the given channel", "// call back with the error", "if", "(", "err", ")", "{", "if", "(", "typeof", "err", "===", "'object'", ")", "{", "err", ".", "userId", "=", "userId", "err", ".", "channel", "=", "channel", "}", "process", ".", "nextTick", "(", "callback", ",", "[", "err", "]", ")", "}", "// we've got that list!", "else", "{", "// ...or maybe that's not really a list?", "if", "(", "!", "Array", ".", "isArray", "(", "targets", ")", ")", "targets", "=", "[", "targets", "]", "removeTargets", "(", "self", ",", "userId", ",", "channel", ",", "targets", ",", "callback", ")", "}", "}", ")", "}", "// we've got an explicit target list, go remove them", "else", "{", "// ...or maybe that's not really a list?", "if", "(", "!", "Array", ".", "isArray", "(", "targets", ")", ")", "targets", "=", "[", "targets", "]", "removeTargets", "(", "self", ",", "userId", ",", "channel", ",", "targets", ",", "callback", ")", "}", "// make it chainable", "return", "this", "}" ]
Remove a previously saved channel or target. @param {*} userId - User identifier. Type is mostly string or number but depends on the consumer. @param {string} channel - Channel name. @param {*|*[]} [targets] - The target or list of targets to remove. If not supplied, then all the targets of the given channel will be removed. @param {function(?Error[])} callback @returns {Handover}
[ "Remove", "a", "previously", "saved", "channel", "or", "target", "." ]
d09b97e3da8f323df93ad00f10bff32ee8cf8acc
https://github.com/schwarzkopfb/hand-over/blob/d09b97e3da8f323df93ad00f10bff32ee8cf8acc/index.js#L353-L394
52,284
schwarzkopfb/hand-over
index.js
removeTargets
function removeTargets(self, userId, channel, targets, callback) { // dereference the original array, // because that may not be trustworthy targets = cloneArray(targets) var pending = targets.length, errors = [] if (pending) targets.forEach(function (target) { self.remove(userId, channel, target, function (err) { // something went wrong if (err) { // decorate errors with debug info if (typeof err === 'object') { err.userId = userId err.channel = channel err.target = target } // collect errors to pass back later to the caller errors.push(err) } // count pending operations and then pass back the control to the caller --pending || process.nextTick(callback, errors.length ? errors : null) }) }) else { // no targets found, so // there is nothing to do here process.nextTick(callback, null) } }
javascript
function removeTargets(self, userId, channel, targets, callback) { // dereference the original array, // because that may not be trustworthy targets = cloneArray(targets) var pending = targets.length, errors = [] if (pending) targets.forEach(function (target) { self.remove(userId, channel, target, function (err) { // something went wrong if (err) { // decorate errors with debug info if (typeof err === 'object') { err.userId = userId err.channel = channel err.target = target } // collect errors to pass back later to the caller errors.push(err) } // count pending operations and then pass back the control to the caller --pending || process.nextTick(callback, errors.length ? errors : null) }) }) else { // no targets found, so // there is nothing to do here process.nextTick(callback, null) } }
[ "function", "removeTargets", "(", "self", ",", "userId", ",", "channel", ",", "targets", ",", "callback", ")", "{", "// dereference the original array,", "// because that may not be trustworthy", "targets", "=", "cloneArray", "(", "targets", ")", "var", "pending", "=", "targets", ".", "length", ",", "errors", "=", "[", "]", "if", "(", "pending", ")", "targets", ".", "forEach", "(", "function", "(", "target", ")", "{", "self", ".", "remove", "(", "userId", ",", "channel", ",", "target", ",", "function", "(", "err", ")", "{", "// something went wrong", "if", "(", "err", ")", "{", "// decorate errors with debug info", "if", "(", "typeof", "err", "===", "'object'", ")", "{", "err", ".", "userId", "=", "userId", "err", ".", "channel", "=", "channel", "err", ".", "target", "=", "target", "}", "// collect errors to pass back later to the caller", "errors", ".", "push", "(", "err", ")", "}", "// count pending operations and then pass back the control to the caller", "--", "pending", "||", "process", ".", "nextTick", "(", "callback", ",", "errors", ".", "length", "?", "errors", ":", "null", ")", "}", ")", "}", ")", "else", "{", "// no targets found, so", "// there is nothing to do here", "process", ".", "nextTick", "(", "callback", ",", "null", ")", "}", "}" ]
Internal func to remove the provided targets. Same as `unregisterTargets` but it assumes that `targets` is an array. @param {Handover} self - Handover instance to work on. @param {*} userId @param {string} channel @param {*[]} targets @param {function} callback
[ "Internal", "func", "to", "remove", "the", "provided", "targets", ".", "Same", "as", "unregisterTargets", "but", "it", "assumes", "that", "targets", "is", "an", "array", "." ]
d09b97e3da8f323df93ad00f10bff32ee8cf8acc
https://github.com/schwarzkopfb/hand-over/blob/d09b97e3da8f323df93ad00f10bff32ee8cf8acc/index.js#L405-L438
52,285
schwarzkopfb/hand-over
index.js
unreference
function unreference() { var plugins = this._plugins Object.keys(plugins).forEach(function (name) { var plugin = plugins[ name ] // `unref()` is preferred if (typeof plugin.unref === 'function') plugin.unref() // if we cannot stop gracefully then destroy open // connections immediately else { // `destroy()` is required by `Plugin` base class, // so it's guaranteed that it exists plugin.destroy() } }) // make it chainable return this }
javascript
function unreference() { var plugins = this._plugins Object.keys(plugins).forEach(function (name) { var plugin = plugins[ name ] // `unref()` is preferred if (typeof plugin.unref === 'function') plugin.unref() // if we cannot stop gracefully then destroy open // connections immediately else { // `destroy()` is required by `Plugin` base class, // so it's guaranteed that it exists plugin.destroy() } }) // make it chainable return this }
[ "function", "unreference", "(", ")", "{", "var", "plugins", "=", "this", ".", "_plugins", "Object", ".", "keys", "(", "plugins", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "var", "plugin", "=", "plugins", "[", "name", "]", "// `unref()` is preferred", "if", "(", "typeof", "plugin", ".", "unref", "===", "'function'", ")", "plugin", ".", "unref", "(", ")", "// if we cannot stop gracefully then destroy open", "// connections immediately", "else", "{", "// `destroy()` is required by `Plugin` base class,", "// so it's guaranteed that it exists", "plugin", ".", "destroy", "(", ")", "}", "}", ")", "// make it chainable", "return", "this", "}" ]
Unreference all the included plugins to let the process exit gracefully. @returns {Handover}
[ "Unreference", "all", "the", "included", "plugins", "to", "let", "the", "process", "exit", "gracefully", "." ]
d09b97e3da8f323df93ad00f10bff32ee8cf8acc
https://github.com/schwarzkopfb/hand-over/blob/d09b97e3da8f323df93ad00f10bff32ee8cf8acc/index.js#L445-L465
52,286
xhochy/node-tomahawkjs
lib/cli/commands.js
function (path, callback) { fs.stat(path, function (err, stats) { failOn(err, "Error while reading the resolver path:", err); if (stats.isFile()) { TomahawkJS.loadAxe(path, _.partial(statResolver, callback)); } else if (stats.isDirectory()) { // Load the resolver from a directory. TomahawkJS.loadDirectory(path, _.partial(startResolver, callback)); } else { // Will be interesting what kind of fs type people will access here console.error("Unsupported FS item for a resolver bundle."); process.exit(1); } }); }
javascript
function (path, callback) { fs.stat(path, function (err, stats) { failOn(err, "Error while reading the resolver path:", err); if (stats.isFile()) { TomahawkJS.loadAxe(path, _.partial(statResolver, callback)); } else if (stats.isDirectory()) { // Load the resolver from a directory. TomahawkJS.loadDirectory(path, _.partial(startResolver, callback)); } else { // Will be interesting what kind of fs type people will access here console.error("Unsupported FS item for a resolver bundle."); process.exit(1); } }); }
[ "function", "(", "path", ",", "callback", ")", "{", "fs", ".", "stat", "(", "path", ",", "function", "(", "err", ",", "stats", ")", "{", "failOn", "(", "err", ",", "\"Error while reading the resolver path:\"", ",", "err", ")", ";", "if", "(", "stats", ".", "isFile", "(", ")", ")", "{", "TomahawkJS", ".", "loadAxe", "(", "path", ",", "_", ".", "partial", "(", "statResolver", ",", "callback", ")", ")", ";", "}", "else", "if", "(", "stats", ".", "isDirectory", "(", ")", ")", "{", "// Load the resolver from a directory.", "TomahawkJS", ".", "loadDirectory", "(", "path", ",", "_", ".", "partial", "(", "startResolver", ",", "callback", ")", ")", ";", "}", "else", "{", "// Will be interesting what kind of fs type people will access here", "console", ".", "error", "(", "\"Unsupported FS item for a resolver bundle.\"", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", "}", ")", ";", "}" ]
Load an AXE bundle and terminate on errors.
[ "Load", "an", "AXE", "bundle", "and", "terminate", "on", "errors", "." ]
5f3e71a361dcb7a8517807826668332ed5b30303
https://github.com/xhochy/node-tomahawkjs/blob/5f3e71a361dcb7a8517807826668332ed5b30303/lib/cli/commands.js#L29-L43
52,287
mnichols/node-event-store
storage/redis/redis-stream.js
concat
function concat (target, data) { target = target || [] if(Object.prototype.toString.call(data)!=='[object Array]') { data = [data] } Array.prototype.push.apply(target, data) return target }
javascript
function concat (target, data) { target = target || [] if(Object.prototype.toString.call(data)!=='[object Array]') { data = [data] } Array.prototype.push.apply(target, data) return target }
[ "function", "concat", "(", "target", ",", "data", ")", "{", "target", "=", "target", "||", "[", "]", "if", "(", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "data", ")", "!==", "'[object Array]'", ")", "{", "data", "=", "[", "data", "]", "}", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "target", ",", "data", ")", "return", "target", "}" ]
presumably faster than Array.concat
[ "presumably", "faster", "than", "Array", ".", "concat" ]
1b03fc39604b100acf4404484a35e3042efddc4a
https://github.com/mnichols/node-event-store/blob/1b03fc39604b100acf4404484a35e3042efddc4a/storage/redis/redis-stream.js#L118-L125
52,288
vkiding/judpack-common
src/util/xml-helpers.js
function(doc, nodes, selector, after) { var parent = module.exports.resolveParent(doc, selector); if (!parent) { //Try to create the parent recursively if necessary try { var parentToCreate = et.XML('<' + path.basename(selector) + '>'), parentSelector = path.dirname(selector); this.graftXML(doc, [parentToCreate], parentSelector); } catch (e) { return false; } parent = module.exports.resolveParent(doc, selector); if (!parent) return false; } nodes.forEach(function (node) { // check if child is unique first if (uniqueChild(node, parent)) { var children = parent.getchildren(); var insertIdx = after ? findInsertIdx(children, after) : children.length; //TODO: replace with parent.insert after the bug in ElementTree is fixed parent.getchildren().splice(insertIdx, 0, node); } }); return true; }
javascript
function(doc, nodes, selector, after) { var parent = module.exports.resolveParent(doc, selector); if (!parent) { //Try to create the parent recursively if necessary try { var parentToCreate = et.XML('<' + path.basename(selector) + '>'), parentSelector = path.dirname(selector); this.graftXML(doc, [parentToCreate], parentSelector); } catch (e) { return false; } parent = module.exports.resolveParent(doc, selector); if (!parent) return false; } nodes.forEach(function (node) { // check if child is unique first if (uniqueChild(node, parent)) { var children = parent.getchildren(); var insertIdx = after ? findInsertIdx(children, after) : children.length; //TODO: replace with parent.insert after the bug in ElementTree is fixed parent.getchildren().splice(insertIdx, 0, node); } }); return true; }
[ "function", "(", "doc", ",", "nodes", ",", "selector", ",", "after", ")", "{", "var", "parent", "=", "module", ".", "exports", ".", "resolveParent", "(", "doc", ",", "selector", ")", ";", "if", "(", "!", "parent", ")", "{", "//Try to create the parent recursively if necessary", "try", "{", "var", "parentToCreate", "=", "et", ".", "XML", "(", "'<'", "+", "path", ".", "basename", "(", "selector", ")", "+", "'>'", ")", ",", "parentSelector", "=", "path", ".", "dirname", "(", "selector", ")", ";", "this", ".", "graftXML", "(", "doc", ",", "[", "parentToCreate", "]", ",", "parentSelector", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "parent", "=", "module", ".", "exports", ".", "resolveParent", "(", "doc", ",", "selector", ")", ";", "if", "(", "!", "parent", ")", "return", "false", ";", "}", "nodes", ".", "forEach", "(", "function", "(", "node", ")", "{", "// check if child is unique first", "if", "(", "uniqueChild", "(", "node", ",", "parent", ")", ")", "{", "var", "children", "=", "parent", ".", "getchildren", "(", ")", ";", "var", "insertIdx", "=", "after", "?", "findInsertIdx", "(", "children", ",", "after", ")", ":", "children", ".", "length", ";", "//TODO: replace with parent.insert after the bug in ElementTree is fixed", "parent", ".", "getchildren", "(", ")", ".", "splice", "(", "insertIdx", ",", "0", ",", "node", ")", ";", "}", "}", ")", ";", "return", "true", ";", "}" ]
adds node to doc at selector, creating parent if it doesn't exist
[ "adds", "node", "to", "doc", "at", "selector", "creating", "parent", "if", "it", "doesn", "t", "exist" ]
5b87d3f1cb10c2c867243e3a692d39b4bb189dd4
https://github.com/vkiding/judpack-common/blob/5b87d3f1cb10c2c867243e3a692d39b4bb189dd4/src/util/xml-helpers.js#L59-L87
52,289
vkiding/judpack-common
src/util/xml-helpers.js
function(doc, nodes, selector) { var parent = module.exports.resolveParent(doc, selector); if (!parent) return false; nodes.forEach(function (node) { var matchingKid = null; if ((matchingKid = findChild(node, parent)) !== null) { // stupid elementtree takes an index argument it doesn't use // and does not conform to the python lib parent.remove(matchingKid); } }); return true; }
javascript
function(doc, nodes, selector) { var parent = module.exports.resolveParent(doc, selector); if (!parent) return false; nodes.forEach(function (node) { var matchingKid = null; if ((matchingKid = findChild(node, parent)) !== null) { // stupid elementtree takes an index argument it doesn't use // and does not conform to the python lib parent.remove(matchingKid); } }); return true; }
[ "function", "(", "doc", ",", "nodes", ",", "selector", ")", "{", "var", "parent", "=", "module", ".", "exports", ".", "resolveParent", "(", "doc", ",", "selector", ")", ";", "if", "(", "!", "parent", ")", "return", "false", ";", "nodes", ".", "forEach", "(", "function", "(", "node", ")", "{", "var", "matchingKid", "=", "null", ";", "if", "(", "(", "matchingKid", "=", "findChild", "(", "node", ",", "parent", ")", ")", "!==", "null", ")", "{", "// stupid elementtree takes an index argument it doesn't use", "// and does not conform to the python lib", "parent", ".", "remove", "(", "matchingKid", ")", ";", "}", "}", ")", ";", "return", "true", ";", "}" ]
removes node from doc at selector
[ "removes", "node", "from", "doc", "at", "selector" ]
5b87d3f1cb10c2c867243e3a692d39b4bb189dd4
https://github.com/vkiding/judpack-common/blob/5b87d3f1cb10c2c867243e3a692d39b4bb189dd4/src/util/xml-helpers.js#L135-L149
52,290
vkiding/judpack-common
src/util/xml-helpers.js
function(doc, selector, xml) { var target = module.exports.resolveParent(doc, selector); if (!target) return false; if (xml.oldAttrib) { target.attrib = _.extend({}, xml.oldAttrib); } return true; }
javascript
function(doc, selector, xml) { var target = module.exports.resolveParent(doc, selector); if (!target) return false; if (xml.oldAttrib) { target.attrib = _.extend({}, xml.oldAttrib); } return true; }
[ "function", "(", "doc", ",", "selector", ",", "xml", ")", "{", "var", "target", "=", "module", ".", "exports", ".", "resolveParent", "(", "doc", ",", "selector", ")", ";", "if", "(", "!", "target", ")", "return", "false", ";", "if", "(", "xml", ".", "oldAttrib", ")", "{", "target", ".", "attrib", "=", "_", ".", "extend", "(", "{", "}", ",", "xml", ".", "oldAttrib", ")", ";", "}", "return", "true", ";", "}" ]
restores attributes from doc at selector
[ "restores", "attributes", "from", "doc", "at", "selector" ]
5b87d3f1cb10c2c867243e3a692d39b4bb189dd4
https://github.com/vkiding/judpack-common/blob/5b87d3f1cb10c2c867243e3a692d39b4bb189dd4/src/util/xml-helpers.js#L152-L161
52,291
vkiding/judpack-common
src/util/xml-helpers.js
findInsertIdx
function findInsertIdx(children, after) { var childrenTags = children.map(function(child) { return child.tag; }); var afters = after.split(';'); var afterIndexes = afters.map(function(current) { return childrenTags.lastIndexOf(current); }); var foundIndex = _.find(afterIndexes, function(index) { return index != -1; }); //add to the beginning if no matching nodes are found return typeof foundIndex === 'undefined' ? 0 : foundIndex+1; }
javascript
function findInsertIdx(children, after) { var childrenTags = children.map(function(child) { return child.tag; }); var afters = after.split(';'); var afterIndexes = afters.map(function(current) { return childrenTags.lastIndexOf(current); }); var foundIndex = _.find(afterIndexes, function(index) { return index != -1; }); //add to the beginning if no matching nodes are found return typeof foundIndex === 'undefined' ? 0 : foundIndex+1; }
[ "function", "findInsertIdx", "(", "children", ",", "after", ")", "{", "var", "childrenTags", "=", "children", ".", "map", "(", "function", "(", "child", ")", "{", "return", "child", ".", "tag", ";", "}", ")", ";", "var", "afters", "=", "after", ".", "split", "(", "';'", ")", ";", "var", "afterIndexes", "=", "afters", ".", "map", "(", "function", "(", "current", ")", "{", "return", "childrenTags", ".", "lastIndexOf", "(", "current", ")", ";", "}", ")", ";", "var", "foundIndex", "=", "_", ".", "find", "(", "afterIndexes", ",", "function", "(", "index", ")", "{", "return", "index", "!=", "-", "1", ";", "}", ")", ";", "//add to the beginning if no matching nodes are found", "return", "typeof", "foundIndex", "===", "'undefined'", "?", "0", ":", "foundIndex", "+", "1", ";", "}" ]
Find the index at which to insert an entry. After is a ;-separated priority list of tags after which the insertion should be made. E.g. If we need to insert an element C, and the rule is that the order of children has to be As, Bs, Cs. After will be equal to "C;B;A".
[ "Find", "the", "index", "at", "which", "to", "insert", "an", "entry", ".", "After", "is", "a", ";", "-", "separated", "priority", "list", "of", "tags", "after", "which", "the", "insertion", "should", "be", "made", ".", "E", ".", "g", ".", "If", "we", "need", "to", "insert", "an", "element", "C", "and", "the", "rule", "is", "that", "the", "order", "of", "children", "has", "to", "be", "As", "Bs", "Cs", ".", "After", "will", "be", "equal", "to", "C", ";", "B", ";", "A", "." ]
5b87d3f1cb10c2c867243e3a692d39b4bb189dd4
https://github.com/vkiding/judpack-common/blob/5b87d3f1cb10c2c867243e3a692d39b4bb189dd4/src/util/xml-helpers.js#L247-L255
52,292
gethuman/pancakes-angular
lib/middleware/jng.utils.js
attachToScope
function attachToScope(model, itemsToAttach) { var me = this; _.each(itemsToAttach, function (item) { if (me.pancakes.exists(item, null)) { model[item] = me.pancakes.cook(item, null); } }); }
javascript
function attachToScope(model, itemsToAttach) { var me = this; _.each(itemsToAttach, function (item) { if (me.pancakes.exists(item, null)) { model[item] = me.pancakes.cook(item, null); } }); }
[ "function", "attachToScope", "(", "model", ",", "itemsToAttach", ")", "{", "var", "me", "=", "this", ";", "_", ".", "each", "(", "itemsToAttach", ",", "function", "(", "item", ")", "{", "if", "(", "me", ".", "pancakes", ".", "exists", "(", "item", ",", "null", ")", ")", "{", "model", "[", "item", "]", "=", "me", ".", "pancakes", ".", "cook", "(", "item", ",", "null", ")", ";", "}", "}", ")", ";", "}" ]
Given an array of items, load them and add them to the model @param model @param itemsToAttach
[ "Given", "an", "array", "of", "items", "load", "them", "and", "add", "them", "to", "the", "model" ]
9589b7ba09619843e271293088005c62ed23f355
https://github.com/gethuman/pancakes-angular/blob/9589b7ba09619843e271293088005c62ed23f355/lib/middleware/jng.utils.js#L222-L230
52,293
gethuman/pancakes-angular
lib/middleware/jng.utils.js
getAppFileNames
function getAppFileNames(appName, dir) { var partialsDir = this.pancakes.getRootDir() + delim + 'app' + delim + appName + delim + dir; return fs.existsSync(partialsDir) ? fs.readdirSync(partialsDir) : []; }
javascript
function getAppFileNames(appName, dir) { var partialsDir = this.pancakes.getRootDir() + delim + 'app' + delim + appName + delim + dir; return fs.existsSync(partialsDir) ? fs.readdirSync(partialsDir) : []; }
[ "function", "getAppFileNames", "(", "appName", ",", "dir", ")", "{", "var", "partialsDir", "=", "this", ".", "pancakes", ".", "getRootDir", "(", ")", "+", "delim", "+", "'app'", "+", "delim", "+", "appName", "+", "delim", "+", "dir", ";", "return", "fs", ".", "existsSync", "(", "partialsDir", ")", "?", "fs", ".", "readdirSync", "(", "partialsDir", ")", ":", "[", "]", ";", "}" ]
Get all file names in a given app's directory @param appName @param dir @returns {*}
[ "Get", "all", "file", "names", "in", "a", "given", "app", "s", "directory" ]
9589b7ba09619843e271293088005c62ed23f355
https://github.com/gethuman/pancakes-angular/blob/9589b7ba09619843e271293088005c62ed23f355/lib/middleware/jng.utils.js#L238-L241
52,294
gethuman/pancakes-angular
lib/middleware/jng.utils.js
dotToCamelCase
function dotToCamelCase(name) { if (!name) { return name; } if (name.substring(name.length - 3) === '.js') { name = name.substring(0, name.length - 3); } name = name.toLowerCase(); var parts = name.split('.'); name = parts[0]; for (var i = 1; i < parts.length; i++) { name += parts[i].substring(0, 1).toUpperCase() + parts[i].substring(1); } return name; }
javascript
function dotToCamelCase(name) { if (!name) { return name; } if (name.substring(name.length - 3) === '.js') { name = name.substring(0, name.length - 3); } name = name.toLowerCase(); var parts = name.split('.'); name = parts[0]; for (var i = 1; i < parts.length; i++) { name += parts[i].substring(0, 1).toUpperCase() + parts[i].substring(1); } return name; }
[ "function", "dotToCamelCase", "(", "name", ")", "{", "if", "(", "!", "name", ")", "{", "return", "name", ";", "}", "if", "(", "name", ".", "substring", "(", "name", ".", "length", "-", "3", ")", "===", "'.js'", ")", "{", "name", "=", "name", ".", "substring", "(", "0", ",", "name", ".", "length", "-", "3", ")", ";", "}", "name", "=", "name", ".", "toLowerCase", "(", ")", ";", "var", "parts", "=", "name", ".", "split", "(", "'.'", ")", ";", "name", "=", "parts", "[", "0", "]", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "name", "+=", "parts", "[", "i", "]", ".", "substring", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", ")", "+", "parts", "[", "i", "]", ".", "substring", "(", "1", ")", ";", "}", "return", "name", ";", "}" ]
Convert a name with dot delim to camel case and remove any .js @param name
[ "Convert", "a", "name", "with", "dot", "delim", "to", "camel", "case", "and", "remove", "any", ".", "js" ]
9589b7ba09619843e271293088005c62ed23f355
https://github.com/gethuman/pancakes-angular/blob/9589b7ba09619843e271293088005c62ed23f355/lib/middleware/jng.utils.js#L260-L276
52,295
gethuman/pancakes-angular
lib/middleware/jng.utils.js
registerJytPlugins
function registerJytPlugins() { var rootDir = this.pancakes.getRootDir(); var pluginDir = path.normalize(rootDir + '/app/common/jyt.plugins'); var me = this; // if plugin dir doesn't exist, just return if (!fs.existsSync(pluginDir)) { return; } // else get all plugin files from the jyt.plugins dir var pluginFiles = fs.readdirSync(pluginDir); var deps = { dependencies: me.getJangularDeps() }; _.each(pluginFiles, function (pluginFile) { var name = me.dotToCamelCase(pluginFile); var pluginFlapjack = me.pancakes.requireModule(pluginDir + delim + pluginFile); var plugin = me.pancakes.cook(pluginFlapjack, deps); jangular.registerPlugin(name, plugin); me.jangularDeps[name] = plugin; }); }
javascript
function registerJytPlugins() { var rootDir = this.pancakes.getRootDir(); var pluginDir = path.normalize(rootDir + '/app/common/jyt.plugins'); var me = this; // if plugin dir doesn't exist, just return if (!fs.existsSync(pluginDir)) { return; } // else get all plugin files from the jyt.plugins dir var pluginFiles = fs.readdirSync(pluginDir); var deps = { dependencies: me.getJangularDeps() }; _.each(pluginFiles, function (pluginFile) { var name = me.dotToCamelCase(pluginFile); var pluginFlapjack = me.pancakes.requireModule(pluginDir + delim + pluginFile); var plugin = me.pancakes.cook(pluginFlapjack, deps); jangular.registerPlugin(name, plugin); me.jangularDeps[name] = plugin; }); }
[ "function", "registerJytPlugins", "(", ")", "{", "var", "rootDir", "=", "this", ".", "pancakes", ".", "getRootDir", "(", ")", ";", "var", "pluginDir", "=", "path", ".", "normalize", "(", "rootDir", "+", "'/app/common/jyt.plugins'", ")", ";", "var", "me", "=", "this", ";", "// if plugin dir doesn't exist, just return", "if", "(", "!", "fs", ".", "existsSync", "(", "pluginDir", ")", ")", "{", "return", ";", "}", "// else get all plugin files from the jyt.plugins dir", "var", "pluginFiles", "=", "fs", ".", "readdirSync", "(", "pluginDir", ")", ";", "var", "deps", "=", "{", "dependencies", ":", "me", ".", "getJangularDeps", "(", ")", "}", ";", "_", ".", "each", "(", "pluginFiles", ",", "function", "(", "pluginFile", ")", "{", "var", "name", "=", "me", ".", "dotToCamelCase", "(", "pluginFile", ")", ";", "var", "pluginFlapjack", "=", "me", ".", "pancakes", ".", "requireModule", "(", "pluginDir", "+", "delim", "+", "pluginFile", ")", ";", "var", "plugin", "=", "me", ".", "pancakes", ".", "cook", "(", "pluginFlapjack", ",", "deps", ")", ";", "jangular", ".", "registerPlugin", "(", "name", ",", "plugin", ")", ";", "me", ".", "jangularDeps", "[", "name", "]", "=", "plugin", ";", "}", ")", ";", "}" ]
Register plugins from the jyt.plugins dir
[ "Register", "plugins", "from", "the", "jyt", ".", "plugins", "dir" ]
9589b7ba09619843e271293088005c62ed23f355
https://github.com/gethuman/pancakes-angular/blob/9589b7ba09619843e271293088005c62ed23f355/lib/middleware/jng.utils.js#L281-L299
52,296
gethuman/pancakes-angular
lib/middleware/jng.utils.js
isMobileApp
function isMobileApp() { var isMobile = false; var appConfigs = this.pancakes.cook('appConfigs', null); _.each(appConfigs, function (appConfig) { if (appConfig.isMobile) { isMobile = true; } }); return isMobile; }
javascript
function isMobileApp() { var isMobile = false; var appConfigs = this.pancakes.cook('appConfigs', null); _.each(appConfigs, function (appConfig) { if (appConfig.isMobile) { isMobile = true; } }); return isMobile; }
[ "function", "isMobileApp", "(", ")", "{", "var", "isMobile", "=", "false", ";", "var", "appConfigs", "=", "this", ".", "pancakes", ".", "cook", "(", "'appConfigs'", ",", "null", ")", ";", "_", ".", "each", "(", "appConfigs", ",", "function", "(", "appConfig", ")", "{", "if", "(", "appConfig", ".", "isMobile", ")", "{", "isMobile", "=", "true", ";", "}", "}", ")", ";", "return", "isMobile", ";", "}" ]
Find out if there is a mobile app in the current project @returns {boolean}
[ "Find", "out", "if", "there", "is", "a", "mobile", "app", "in", "the", "current", "project" ]
9589b7ba09619843e271293088005c62ed23f355
https://github.com/gethuman/pancakes-angular/blob/9589b7ba09619843e271293088005c62ed23f355/lib/middleware/jng.utils.js#L305-L316
52,297
gethuman/pancakes-angular
lib/middleware/jng.utils.js
doesFileExist
function doesFileExist(filePath) { if (!fileExistsCache.hasOwnProperty(filePath)) { fileExistsCache[filePath] = fs.existsSync(filePath); } return fileExistsCache[filePath]; }
javascript
function doesFileExist(filePath) { if (!fileExistsCache.hasOwnProperty(filePath)) { fileExistsCache[filePath] = fs.existsSync(filePath); } return fileExistsCache[filePath]; }
[ "function", "doesFileExist", "(", "filePath", ")", "{", "if", "(", "!", "fileExistsCache", ".", "hasOwnProperty", "(", "filePath", ")", ")", "{", "fileExistsCache", "[", "filePath", "]", "=", "fs", ".", "existsSync", "(", "filePath", ")", ";", "}", "return", "fileExistsCache", "[", "filePath", "]", ";", "}" ]
Check to see if a particular file exists; cache results @param filePath @returns {*}
[ "Check", "to", "see", "if", "a", "particular", "file", "exists", ";", "cache", "results" ]
9589b7ba09619843e271293088005c62ed23f355
https://github.com/gethuman/pancakes-angular/blob/9589b7ba09619843e271293088005c62ed23f355/lib/middleware/jng.utils.js#L342-L348
52,298
beeblebrox3/super-helpers
src/object/isCyclic.js
isCyclic
function isCyclic(obj) { let seenObjects = []; const detect = obj => { if (obj && typeof obj === "object") { if (seenObjects.includes(obj)) { return true; } seenObjects.push(obj); for (const key in obj) { if (obj.hasOwnProperty(key) && detect(obj[key])) { return true; } } } return false; }; return detect(obj); }
javascript
function isCyclic(obj) { let seenObjects = []; const detect = obj => { if (obj && typeof obj === "object") { if (seenObjects.includes(obj)) { return true; } seenObjects.push(obj); for (const key in obj) { if (obj.hasOwnProperty(key) && detect(obj[key])) { return true; } } } return false; }; return detect(obj); }
[ "function", "isCyclic", "(", "obj", ")", "{", "let", "seenObjects", "=", "[", "]", ";", "const", "detect", "=", "obj", "=>", "{", "if", "(", "obj", "&&", "typeof", "obj", "===", "\"object\"", ")", "{", "if", "(", "seenObjects", ".", "includes", "(", "obj", ")", ")", "{", "return", "true", ";", "}", "seenObjects", ".", "push", "(", "obj", ")", ";", "for", "(", "const", "key", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "key", ")", "&&", "detect", "(", "obj", "[", "key", "]", ")", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}", ";", "return", "detect", "(", "obj", ")", ";", "}" ]
Check if any given object has some kind of cyclic reference. @param {Object} obj the source to be checked @return {boolean} @memberof object
[ "Check", "if", "any", "given", "object", "has", "some", "kind", "of", "cyclic", "reference", "." ]
15deaf3509bfe47817e6dd3ecd3e6879743b7dd9
https://github.com/beeblebrox3/super-helpers/blob/15deaf3509bfe47817e6dd3ecd3e6879743b7dd9/src/object/isCyclic.js#L8-L29
52,299
copress/copress-component-oauth2
lib/oauth2.js
function (req, res, next) { if (options.forceAuthorize) { return next(); } var userId = req.oauth2.user.id; var clientId = req.oauth2.client.id; var scope = req.oauth2.req.scope; models.Permissions.isAuthorized(clientId, userId, scope, function (err, authorized) { if (err) { return next(err); } else if (authorized) { req.oauth2.res = {}; req.oauth2.res.allow = true; server._respond(req.oauth2, res, function (err) { if (err) { return next(err); } return next(new AuthorizationError('Unsupported response type: ' + req.oauth2.req.type, 'unsupported_response_type')); }); } else { next(); } }); }
javascript
function (req, res, next) { if (options.forceAuthorize) { return next(); } var userId = req.oauth2.user.id; var clientId = req.oauth2.client.id; var scope = req.oauth2.req.scope; models.Permissions.isAuthorized(clientId, userId, scope, function (err, authorized) { if (err) { return next(err); } else if (authorized) { req.oauth2.res = {}; req.oauth2.res.allow = true; server._respond(req.oauth2, res, function (err) { if (err) { return next(err); } return next(new AuthorizationError('Unsupported response type: ' + req.oauth2.req.type, 'unsupported_response_type')); }); } else { next(); } }); }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "options", ".", "forceAuthorize", ")", "{", "return", "next", "(", ")", ";", "}", "var", "userId", "=", "req", ".", "oauth2", ".", "user", ".", "id", ";", "var", "clientId", "=", "req", ".", "oauth2", ".", "client", ".", "id", ";", "var", "scope", "=", "req", ".", "oauth2", ".", "req", ".", "scope", ";", "models", ".", "Permissions", ".", "isAuthorized", "(", "clientId", ",", "userId", ",", "scope", ",", "function", "(", "err", ",", "authorized", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", ";", "}", "else", "if", "(", "authorized", ")", "{", "req", ".", "oauth2", ".", "res", "=", "{", "}", ";", "req", ".", "oauth2", ".", "res", ".", "allow", "=", "true", ";", "server", ".", "_respond", "(", "req", ".", "oauth2", ",", "res", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", ";", "}", "return", "next", "(", "new", "AuthorizationError", "(", "'Unsupported response type: '", "+", "req", ".", "oauth2", ".", "req", ".", "type", ",", "'unsupported_response_type'", ")", ")", ";", "}", ")", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}", ")", ";", "}" ]
Check if the user has granted permissions to the client app
[ "Check", "if", "the", "user", "has", "granted", "permissions", "to", "the", "client", "app" ]
4819f379a0d42753bfd51e237c5c3aaddee37544
https://github.com/copress/copress-component-oauth2/blob/4819f379a0d42753bfd51e237c5c3aaddee37544/lib/oauth2.js#L601-L626