id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
43,800
aaaristo/grunt-html-builder
tasks/rdfstore/index.js
function(input, frame) { var rval = false; // frame must not have a specific type var type = '@type'; if(!(type in frame)) { // get frame properties that must exist on input var props = Object.keys(frame).filter(function(e) { // filter non-keywords return e.indexOf('@') !== 0; }); if(props.length === 0) { // input always matches if there are no properties rval = true; } // input must be a subject with all the given properties else if(input.constructor === Object && '@id' in input) { rval = true; for(var i in props) { if(!(props[i] in input)) { rval = false; break; } } } } return rval; }
javascript
function(input, frame) { var rval = false; // frame must not have a specific type var type = '@type'; if(!(type in frame)) { // get frame properties that must exist on input var props = Object.keys(frame).filter(function(e) { // filter non-keywords return e.indexOf('@') !== 0; }); if(props.length === 0) { // input always matches if there are no properties rval = true; } // input must be a subject with all the given properties else if(input.constructor === Object && '@id' in input) { rval = true; for(var i in props) { if(!(props[i] in input)) { rval = false; break; } } } } return rval; }
[ "function", "(", "input", ",", "frame", ")", "{", "var", "rval", "=", "false", ";", "// frame must not have a specific type", "var", "type", "=", "'@type'", ";", "if", "(", "!", "(", "type", "in", "frame", ")", ")", "{", "// get frame properties that must exist on input", "var", "props", "=", "Object", ".", "keys", "(", "frame", ")", ".", "filter", "(", "function", "(", "e", ")", "{", "// filter non-keywords", "return", "e", ".", "indexOf", "(", "'@'", ")", "!==", "0", ";", "}", ")", ";", "if", "(", "props", ".", "length", "===", "0", ")", "{", "// input always matches if there are no properties", "rval", "=", "true", ";", "}", "// input must be a subject with all the given properties", "else", "if", "(", "input", ".", "constructor", "===", "Object", "&&", "'@id'", "in", "input", ")", "{", "rval", "=", "true", ";", "for", "(", "var", "i", "in", "props", ")", "{", "if", "(", "!", "(", "props", "[", "i", "]", "in", "input", ")", ")", "{", "rval", "=", "false", ";", "break", ";", "}", "}", "}", "}", "return", "rval", ";", "}" ]
Returns true if the given input matches the given frame via duck-typing. @param input the input. @param frame the frame to check against. @return true if the input matches the frame.
[ "Returns", "true", "if", "the", "given", "input", "matches", "the", "given", "frame", "via", "duck", "-", "typing", "." ]
9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1
https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/rdfstore/index.js#L4754-L4789
43,801
aaaristo/grunt-html-builder
tasks/rdfstore/index.js
function(iri) { var iris = Object.keys(embeds); for(var i in iris) { i = iris[i]; if(i in embeds && embeds[i].parent !== null && embeds[i].parent['@id'] === iri) { delete embeds[i]; removeDependents(i); } } }
javascript
function(iri) { var iris = Object.keys(embeds); for(var i in iris) { i = iris[i]; if(i in embeds && embeds[i].parent !== null && embeds[i].parent['@id'] === iri) { delete embeds[i]; removeDependents(i); } } }
[ "function", "(", "iri", ")", "{", "var", "iris", "=", "Object", ".", "keys", "(", "embeds", ")", ";", "for", "(", "var", "i", "in", "iris", ")", "{", "i", "=", "iris", "[", "i", "]", ";", "if", "(", "i", "in", "embeds", "&&", "embeds", "[", "i", "]", ".", "parent", "!==", "null", "&&", "embeds", "[", "i", "]", ".", "parent", "[", "'@id'", "]", "===", "iri", ")", "{", "delete", "embeds", "[", "i", "]", ";", "removeDependents", "(", "i", ")", ";", "}", "}", "}" ]
recursively remove any dependent dangling embeds
[ "recursively", "remove", "any", "dependent", "dangling", "embeds" ]
9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1
https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/rdfstore/index.js#L4858-L4871
43,802
aaaristo/grunt-html-builder
tasks/rdfstore/index.js
function( subjects, input, frame, embeds, autoembed, parent, parentKey, options) { var rval = null; // prepare output, set limit, get array of frames var limit = -1; var frames; if(frame.constructor === Array) { rval = []; frames = frame; if(frames.length === 0) { frames.push({}); } } else { frames = [frame]; limit = 1; } // iterate over frames adding input matches to list var values = []; for(var i = 0; i < frames.length && limit !== 0; ++i) { // get next frame frame = frames[i]; if(frame.constructor !== Object) { throw { message: 'Invalid JSON-LD frame. ' + 'Frame must be an object or an array.', frame: frame }; } // create array of values for each frame values[i] = []; for(var n = 0; n < input.length && limit !== 0; ++n) { // add input to list if it matches frame specific type or duck-type var next = input[n]; if(_isType(next, frame) || _isDuckType(next, frame)) { values[i].push(next); --limit; } } } // for each matching value, add it to the output for(var i1 in values) { for(var i2 in values[i1]) { frame = frames[i1]; var value = values[i1][i2]; // if value is a subject, do subframing if(_isSubject(value)) { value = _subframe( subjects, value, frame, embeds, autoembed, parent, parentKey, options); } // add value to output if(rval === null) { rval = value; } else { // determine if value is a reference to an embed var isRef = (_isReference(value) && value['@id'] in embeds); // push any value that isn't a parentless reference if(!(parent === null && isRef)) { rval.push(value); } } } } return rval; }
javascript
function( subjects, input, frame, embeds, autoembed, parent, parentKey, options) { var rval = null; // prepare output, set limit, get array of frames var limit = -1; var frames; if(frame.constructor === Array) { rval = []; frames = frame; if(frames.length === 0) { frames.push({}); } } else { frames = [frame]; limit = 1; } // iterate over frames adding input matches to list var values = []; for(var i = 0; i < frames.length && limit !== 0; ++i) { // get next frame frame = frames[i]; if(frame.constructor !== Object) { throw { message: 'Invalid JSON-LD frame. ' + 'Frame must be an object or an array.', frame: frame }; } // create array of values for each frame values[i] = []; for(var n = 0; n < input.length && limit !== 0; ++n) { // add input to list if it matches frame specific type or duck-type var next = input[n]; if(_isType(next, frame) || _isDuckType(next, frame)) { values[i].push(next); --limit; } } } // for each matching value, add it to the output for(var i1 in values) { for(var i2 in values[i1]) { frame = frames[i1]; var value = values[i1][i2]; // if value is a subject, do subframing if(_isSubject(value)) { value = _subframe( subjects, value, frame, embeds, autoembed, parent, parentKey, options); } // add value to output if(rval === null) { rval = value; } else { // determine if value is a reference to an embed var isRef = (_isReference(value) && value['@id'] in embeds); // push any value that isn't a parentless reference if(!(parent === null && isRef)) { rval.push(value); } } } } return rval; }
[ "function", "(", "subjects", ",", "input", ",", "frame", ",", "embeds", ",", "autoembed", ",", "parent", ",", "parentKey", ",", "options", ")", "{", "var", "rval", "=", "null", ";", "// prepare output, set limit, get array of frames", "var", "limit", "=", "-", "1", ";", "var", "frames", ";", "if", "(", "frame", ".", "constructor", "===", "Array", ")", "{", "rval", "=", "[", "]", ";", "frames", "=", "frame", ";", "if", "(", "frames", ".", "length", "===", "0", ")", "{", "frames", ".", "push", "(", "{", "}", ")", ";", "}", "}", "else", "{", "frames", "=", "[", "frame", "]", ";", "limit", "=", "1", ";", "}", "// iterate over frames adding input matches to list", "var", "values", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "frames", ".", "length", "&&", "limit", "!==", "0", ";", "++", "i", ")", "{", "// get next frame", "frame", "=", "frames", "[", "i", "]", ";", "if", "(", "frame", ".", "constructor", "!==", "Object", ")", "{", "throw", "{", "message", ":", "'Invalid JSON-LD frame. '", "+", "'Frame must be an object or an array.'", ",", "frame", ":", "frame", "}", ";", "}", "// create array of values for each frame", "values", "[", "i", "]", "=", "[", "]", ";", "for", "(", "var", "n", "=", "0", ";", "n", "<", "input", ".", "length", "&&", "limit", "!==", "0", ";", "++", "n", ")", "{", "// add input to list if it matches frame specific type or duck-type", "var", "next", "=", "input", "[", "n", "]", ";", "if", "(", "_isType", "(", "next", ",", "frame", ")", "||", "_isDuckType", "(", "next", ",", "frame", ")", ")", "{", "values", "[", "i", "]", ".", "push", "(", "next", ")", ";", "--", "limit", ";", "}", "}", "}", "// for each matching value, add it to the output", "for", "(", "var", "i1", "in", "values", ")", "{", "for", "(", "var", "i2", "in", "values", "[", "i1", "]", ")", "{", "frame", "=", "frames", "[", "i1", "]", ";", "var", "value", "=", "values", "[", "i1", "]", "[", "i2", "]", ";", "// if value is a subject, do subframing", "if", "(", "_isSubject", "(", "value", ")", ")", "{", "value", "=", "_subframe", "(", "subjects", ",", "value", ",", "frame", ",", "embeds", ",", "autoembed", ",", "parent", ",", "parentKey", ",", "options", ")", ";", "}", "// add value to output", "if", "(", "rval", "===", "null", ")", "{", "rval", "=", "value", ";", "}", "else", "{", "// determine if value is a reference to an embed", "var", "isRef", "=", "(", "_isReference", "(", "value", ")", "&&", "value", "[", "'@id'", "]", "in", "embeds", ")", ";", "// push any value that isn't a parentless reference", "if", "(", "!", "(", "parent", "===", "null", "&&", "isRef", ")", ")", "{", "rval", ".", "push", "(", "value", ")", ";", "}", "}", "}", "}", "return", "rval", ";", "}" ]
Recursively frames the given input according to the given frame. @param subjects a map of subjects in the graph. @param input the input to frame. @param frame the frame to use. @param embeds a map of previously embedded subjects, used to prevent cycles. @param autoembed true if auto-embed is on, false if not. @param parent the parent object (for subframing), null for none. @param parentKey the parent key (for subframing), null for none. @param options the framing options. @return the framed input.
[ "Recursively", "frames", "the", "given", "input", "according", "to", "the", "given", "frame", "." ]
9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1
https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/rdfstore/index.js#L4995-L5083
43,803
aaaristo/grunt-html-builder
tasks/rdfstore/index.js
RDFMakeTerm
function RDFMakeTerm(formula,val, canonicalize) { if (typeof val != 'object') { if (typeof val == 'string') return new N3Parser.Literal(val); if (typeof val == 'number') return new N3Parser.Literal(val); // @@ differet types if (typeof val == 'boolean') return new N3Parser.Literal(val?"1":"0", undefined, N3Parser.Symbol.prototype.XSDboolean); else if (typeof val == 'number') return new N3Parser.Literal(''+val); // @@ datatypes else if (typeof val == 'undefined') return undefined; else // @@ add converting of dates and numbers throw "Can't make Term from " + val + " of type " + typeof val; } return val; }
javascript
function RDFMakeTerm(formula,val, canonicalize) { if (typeof val != 'object') { if (typeof val == 'string') return new N3Parser.Literal(val); if (typeof val == 'number') return new N3Parser.Literal(val); // @@ differet types if (typeof val == 'boolean') return new N3Parser.Literal(val?"1":"0", undefined, N3Parser.Symbol.prototype.XSDboolean); else if (typeof val == 'number') return new N3Parser.Literal(''+val); // @@ datatypes else if (typeof val == 'undefined') return undefined; else // @@ add converting of dates and numbers throw "Can't make Term from " + val + " of type " + typeof val; } return val; }
[ "function", "RDFMakeTerm", "(", "formula", ",", "val", ",", "canonicalize", ")", "{", "if", "(", "typeof", "val", "!=", "'object'", ")", "{", "if", "(", "typeof", "val", "==", "'string'", ")", "return", "new", "N3Parser", ".", "Literal", "(", "val", ")", ";", "if", "(", "typeof", "val", "==", "'number'", ")", "return", "new", "N3Parser", ".", "Literal", "(", "val", ")", ";", "// @@ differet types", "if", "(", "typeof", "val", "==", "'boolean'", ")", "return", "new", "N3Parser", ".", "Literal", "(", "val", "?", "\"1\"", ":", "\"0\"", ",", "undefined", ",", "N3Parser", ".", "Symbol", ".", "prototype", ".", "XSDboolean", ")", ";", "else", "if", "(", "typeof", "val", "==", "'number'", ")", "return", "new", "N3Parser", ".", "Literal", "(", "''", "+", "val", ")", ";", "// @@ datatypes", "else", "if", "(", "typeof", "val", "==", "'undefined'", ")", "return", "undefined", ";", "else", "// @@ add converting of dates and numbers", "throw", "\"Can't make Term from \"", "+", "val", "+", "\" of type \"", "+", "typeof", "val", ";", "}", "return", "val", ";", "}" ]
On input parameters, convert constants to terms
[ "On", "input", "parameters", "convert", "constants", "to", "terms" ]
9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1
https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/rdfstore/index.js#L24922-L24939
43,804
silas/swagger-framework
lib/schema/environment.js
Environment
function Environment(options) { if (!(this instanceof Environment)) { return new Environment(options); } // defaults options = lodash.defaults(options || {}, { setup: true, }); this.env = jjv(); this.env.defaultOptions.checkRequired = true; this.env.defaultOptions.useDefault = true; this.env.defaultOptions.useCoerce = false; this._jjve = jjve(this.env); if (options.setup) this.setup(); }
javascript
function Environment(options) { if (!(this instanceof Environment)) { return new Environment(options); } // defaults options = lodash.defaults(options || {}, { setup: true, }); this.env = jjv(); this.env.defaultOptions.checkRequired = true; this.env.defaultOptions.useDefault = true; this.env.defaultOptions.useCoerce = false; this._jjve = jjve(this.env); if (options.setup) this.setup(); }
[ "function", "Environment", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Environment", ")", ")", "{", "return", "new", "Environment", "(", "options", ")", ";", "}", "// defaults", "options", "=", "lodash", ".", "defaults", "(", "options", "||", "{", "}", ",", "{", "setup", ":", "true", ",", "}", ")", ";", "this", ".", "env", "=", "jjv", "(", ")", ";", "this", ".", "env", ".", "defaultOptions", ".", "checkRequired", "=", "true", ";", "this", ".", "env", ".", "defaultOptions", ".", "useDefault", "=", "true", ";", "this", ".", "env", ".", "defaultOptions", ".", "useCoerce", "=", "false", ";", "this", ".", "_jjve", "=", "jjve", "(", "this", ".", "env", ")", ";", "if", "(", "options", ".", "setup", ")", "this", ".", "setup", "(", ")", ";", "}" ]
Initialize a new `Environment`. @param {Object} options @api public
[ "Initialize", "a", "new", "Environment", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/schema/environment.js#L24-L41
43,805
opendxl/opendxl-client-javascript
lib/_provisioning/update-config.js
updateBrokerCertChain
function updateBrokerCertChain (configDir, certChainFile, certChain, verbosity) { var caBundleFileName = util.getConfigFilePath(configDir, certChainFile) if (verbosity) { console.log('Updating certs in ' + caBundleFileName) } provisionUtil.saveToFile(caBundleFileName, certChain) }
javascript
function updateBrokerCertChain (configDir, certChainFile, certChain, verbosity) { var caBundleFileName = util.getConfigFilePath(configDir, certChainFile) if (verbosity) { console.log('Updating certs in ' + caBundleFileName) } provisionUtil.saveToFile(caBundleFileName, certChain) }
[ "function", "updateBrokerCertChain", "(", "configDir", ",", "certChainFile", ",", "certChain", ",", "verbosity", ")", "{", "var", "caBundleFileName", "=", "util", ".", "getConfigFilePath", "(", "configDir", ",", "certChainFile", ")", "if", "(", "verbosity", ")", "{", "console", ".", "log", "(", "'Updating certs in '", "+", "caBundleFileName", ")", "}", "provisionUtil", ".", "saveToFile", "(", "caBundleFileName", ",", "certChain", ")", "}" ]
Stores a broker certificate chain into a file. @param {String} configDir - Directory in which to store the certificate chain. This is only used if certChainFile is not an absolute path to an existing certificate chain file. @param {String} certChainFile - Name of the file at which to store the broker certificate chain. @param {String} certChain - Broker certificate chain to store. @param {Number} verbosity - Level of verbosity at which to log any error or trace messages. @private
[ "Stores", "a", "broker", "certificate", "chain", "into", "a", "file", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_provisioning/update-config.js#L43-L49
43,806
opendxl/opendxl-client-javascript
lib/_provisioning/update-config.js
updateBrokerListInConfigFile
function updateBrokerListInConfigFile (configFileName, brokerLines, verbosity) { if (verbosity) { console.log('Updating DXL config file at ' + configFileName) } var inBrokerSection = false var linesAfterBrokerSection = [] var configFileData = util.getConfigFileData(configFileName) // Replace the current contents of the broker section with the new broker // lines. Preserve existing content in the file which relates to other // sections - for example, the 'Certs' section. var newConfigLines = configFileData.lines.reduce( function (acc, line) { if (line === '[Brokers]') { inBrokerSection = true acc.push(line) } else { if (inBrokerSection) { // Skip over any existing lines in the broker section since these // will be replaced. if (line.match(/^\s*($|[;#])/)) { // Preserve any empty/comment lines if there is another section // after the Broker section. Comments may pertain to the content of // the next section. linesAfterBrokerSection.push(line) } else if (line.match(/^\[.*]$/)) { // A section after the broker section has been reached. inBrokerSection = false Array.prototype.push.apply(acc, brokerLines) if (linesAfterBrokerSection.length === 0) { newConfigLines.push(configFileData.lineSeparator) } else { Array.prototype.push.apply(acc, linesAfterBrokerSection) } acc.push(line) } else { // A broker config entry in the existing file, which will be // replaced by the new broker lines, has been encountered. Any // prior empty/comment lines which had been stored so far would // be between broker config entries. Those lines should be dropped // since they might not line up with the new broker list data. linesAfterBrokerSection = [] } } else { acc.push(line) } } return acc }, [] ) if (inBrokerSection) { Array.prototype.push.apply(newConfigLines, brokerLines) } // Flatten the broker line array back into a string, delimited using the // line separator which appeared to be used in the original config file. var newConfig = newConfigLines.join(configFileData.lineSeparator) if (inBrokerSection) { newConfig += configFileData.lineSeparator } provisionUtil.saveToFile(configFileName, newConfig) }
javascript
function updateBrokerListInConfigFile (configFileName, brokerLines, verbosity) { if (verbosity) { console.log('Updating DXL config file at ' + configFileName) } var inBrokerSection = false var linesAfterBrokerSection = [] var configFileData = util.getConfigFileData(configFileName) // Replace the current contents of the broker section with the new broker // lines. Preserve existing content in the file which relates to other // sections - for example, the 'Certs' section. var newConfigLines = configFileData.lines.reduce( function (acc, line) { if (line === '[Brokers]') { inBrokerSection = true acc.push(line) } else { if (inBrokerSection) { // Skip over any existing lines in the broker section since these // will be replaced. if (line.match(/^\s*($|[;#])/)) { // Preserve any empty/comment lines if there is another section // after the Broker section. Comments may pertain to the content of // the next section. linesAfterBrokerSection.push(line) } else if (line.match(/^\[.*]$/)) { // A section after the broker section has been reached. inBrokerSection = false Array.prototype.push.apply(acc, brokerLines) if (linesAfterBrokerSection.length === 0) { newConfigLines.push(configFileData.lineSeparator) } else { Array.prototype.push.apply(acc, linesAfterBrokerSection) } acc.push(line) } else { // A broker config entry in the existing file, which will be // replaced by the new broker lines, has been encountered. Any // prior empty/comment lines which had been stored so far would // be between broker config entries. Those lines should be dropped // since they might not line up with the new broker list data. linesAfterBrokerSection = [] } } else { acc.push(line) } } return acc }, [] ) if (inBrokerSection) { Array.prototype.push.apply(newConfigLines, brokerLines) } // Flatten the broker line array back into a string, delimited using the // line separator which appeared to be used in the original config file. var newConfig = newConfigLines.join(configFileData.lineSeparator) if (inBrokerSection) { newConfig += configFileData.lineSeparator } provisionUtil.saveToFile(configFileName, newConfig) }
[ "function", "updateBrokerListInConfigFile", "(", "configFileName", ",", "brokerLines", ",", "verbosity", ")", "{", "if", "(", "verbosity", ")", "{", "console", ".", "log", "(", "'Updating DXL config file at '", "+", "configFileName", ")", "}", "var", "inBrokerSection", "=", "false", "var", "linesAfterBrokerSection", "=", "[", "]", "var", "configFileData", "=", "util", ".", "getConfigFileData", "(", "configFileName", ")", "// Replace the current contents of the broker section with the new broker", "// lines. Preserve existing content in the file which relates to other", "// sections - for example, the 'Certs' section.", "var", "newConfigLines", "=", "configFileData", ".", "lines", ".", "reduce", "(", "function", "(", "acc", ",", "line", ")", "{", "if", "(", "line", "===", "'[Brokers]'", ")", "{", "inBrokerSection", "=", "true", "acc", ".", "push", "(", "line", ")", "}", "else", "{", "if", "(", "inBrokerSection", ")", "{", "// Skip over any existing lines in the broker section since these", "// will be replaced.", "if", "(", "line", ".", "match", "(", "/", "^\\s*($|[;#])", "/", ")", ")", "{", "// Preserve any empty/comment lines if there is another section", "// after the Broker section. Comments may pertain to the content of", "// the next section.", "linesAfterBrokerSection", ".", "push", "(", "line", ")", "}", "else", "if", "(", "line", ".", "match", "(", "/", "^\\[.*]$", "/", ")", ")", "{", "// A section after the broker section has been reached.", "inBrokerSection", "=", "false", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "acc", ",", "brokerLines", ")", "if", "(", "linesAfterBrokerSection", ".", "length", "===", "0", ")", "{", "newConfigLines", ".", "push", "(", "configFileData", ".", "lineSeparator", ")", "}", "else", "{", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "acc", ",", "linesAfterBrokerSection", ")", "}", "acc", ".", "push", "(", "line", ")", "}", "else", "{", "// A broker config entry in the existing file, which will be", "// replaced by the new broker lines, has been encountered. Any", "// prior empty/comment lines which had been stored so far would", "// be between broker config entries. Those lines should be dropped", "// since they might not line up with the new broker list data.", "linesAfterBrokerSection", "=", "[", "]", "}", "}", "else", "{", "acc", ".", "push", "(", "line", ")", "}", "}", "return", "acc", "}", ",", "[", "]", ")", "if", "(", "inBrokerSection", ")", "{", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "newConfigLines", ",", "brokerLines", ")", "}", "// Flatten the broker line array back into a string, delimited using the", "// line separator which appeared to be used in the original config file.", "var", "newConfig", "=", "newConfigLines", ".", "join", "(", "configFileData", ".", "lineSeparator", ")", "if", "(", "inBrokerSection", ")", "{", "newConfig", "+=", "configFileData", ".", "lineSeparator", "}", "provisionUtil", ".", "saveToFile", "(", "configFileName", ",", "newConfig", ")", "}" ]
Updates the broker section in a client configuration file with a list of broker data lines. @param {String} configFileName - Name of the configuration file to update. @param {Array<String>} brokerLines - List of broker data strings to insert into the configuration file. @param {Number} verbosity - Level of verbosity at which to log any error or trace messages. @private
[ "Updates", "the", "broker", "section", "in", "a", "client", "configuration", "file", "with", "a", "list", "of", "broker", "data", "lines", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_provisioning/update-config.js#L94-L158
43,807
tonistiigi/styler
lib/public/build/main.js
function(models, options) { var i, l, index, model; options || (options = {}); models = _.isArray(models) ? models.slice() : [models]; for (i = 0, l = models.length; i < l; i++) { model = this.getByCid(models[i]) || this.get(models[i]); if (!model) continue; delete this._byId[model.id]; delete this._byCid[model.cid]; index = this.indexOf(model); this.models.splice(index, 1); this.length--; if (!options.silent) { options.index = index; model.trigger('remove', model, this, options); } this._removeReference(model); } return this; }
javascript
function(models, options) { var i, l, index, model; options || (options = {}); models = _.isArray(models) ? models.slice() : [models]; for (i = 0, l = models.length; i < l; i++) { model = this.getByCid(models[i]) || this.get(models[i]); if (!model) continue; delete this._byId[model.id]; delete this._byCid[model.cid]; index = this.indexOf(model); this.models.splice(index, 1); this.length--; if (!options.silent) { options.index = index; model.trigger('remove', model, this, options); } this._removeReference(model); } return this; }
[ "function", "(", "models", ",", "options", ")", "{", "var", "i", ",", "l", ",", "index", ",", "model", ";", "options", "||", "(", "options", "=", "{", "}", ")", ";", "models", "=", "_", ".", "isArray", "(", "models", ")", "?", "models", ".", "slice", "(", ")", ":", "[", "models", "]", ";", "for", "(", "i", "=", "0", ",", "l", "=", "models", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "model", "=", "this", ".", "getByCid", "(", "models", "[", "i", "]", ")", "||", "this", ".", "get", "(", "models", "[", "i", "]", ")", ";", "if", "(", "!", "model", ")", "continue", ";", "delete", "this", ".", "_byId", "[", "model", ".", "id", "]", ";", "delete", "this", ".", "_byCid", "[", "model", ".", "cid", "]", ";", "index", "=", "this", ".", "indexOf", "(", "model", ")", ";", "this", ".", "models", ".", "splice", "(", "index", ",", "1", ")", ";", "this", ".", "length", "--", ";", "if", "(", "!", "options", ".", "silent", ")", "{", "options", ".", "index", "=", "index", ";", "model", ".", "trigger", "(", "'remove'", ",", "model", ",", "this", ",", "options", ")", ";", "}", "this", ".", "_removeReference", "(", "model", ")", ";", "}", "return", "this", ";", "}" ]
Remove a model, or a list of models from the set. Pass silent to avoid firing the `remove` event for every model removed.
[ "Remove", "a", "model", "or", "a", "list", "of", "models", "from", "the", "set", ".", "Pass", "silent", "to", "avoid", "firing", "the", "remove", "event", "for", "every", "model", "removed", "." ]
f20dd9621f671b77cbb660d35327e007e8a56e2a
https://github.com/tonistiigi/styler/blob/f20dd9621f671b77cbb660d35327e007e8a56e2a/lib/public/build/main.js#L4388-L4407
43,808
netzkolchose/node-ansiparser
dist/ansiparser.js
add
function add(table, inp, state, action, next) { table[state<<8|inp] = ((action | 0) << 4) | ((next === undefined) ? state : next); }
javascript
function add(table, inp, state, action, next) { table[state<<8|inp] = ((action | 0) << 4) | ((next === undefined) ? state : next); }
[ "function", "add", "(", "table", ",", "inp", ",", "state", ",", "action", ",", "next", ")", "{", "table", "[", "state", "<<", "8", "|", "inp", "]", "=", "(", "(", "action", "|", "0", ")", "<<", "4", ")", "|", "(", "(", "next", "===", "undefined", ")", "?", "state", ":", "next", ")", ";", "}" ]
Add a transition to the transition table. @param table - table to add transition @param {number} inp - input character code @param {number} state - current state @param {number=} action - action to be taken @param {number=} next - next state
[ "Add", "a", "transition", "to", "the", "transition", "table", "." ]
548ba7d39d0cc937d85ffdd2430424a4bff137df
https://github.com/netzkolchose/node-ansiparser/blob/548ba7d39d0cc937d85ffdd2430424a4bff137df/dist/ansiparser.js#L28-L30
43,809
netzkolchose/node-ansiparser
dist/ansiparser.js
add_list
function add_list(table, inps, state, action, next) { for (var i=0; i<inps.length; i++) add(table, inps[i], state, action, next); }
javascript
function add_list(table, inps, state, action, next) { for (var i=0; i<inps.length; i++) add(table, inps[i], state, action, next); }
[ "function", "add_list", "(", "table", ",", "inps", ",", "state", ",", "action", ",", "next", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "inps", ".", "length", ";", "i", "++", ")", "add", "(", "table", ",", "inps", "[", "i", "]", ",", "state", ",", "action", ",", "next", ")", ";", "}" ]
Add multiple transitions to the transition table. @param table - table to add transition @param {Array} inps - array of input character codes @param {number} state - current state @param {number=} action - action to be taken @param {number=} next - next state
[ "Add", "multiple", "transitions", "to", "the", "transition", "table", "." ]
548ba7d39d0cc937d85ffdd2430424a4bff137df
https://github.com/netzkolchose/node-ansiparser/blob/548ba7d39d0cc937d85ffdd2430424a4bff137df/dist/ansiparser.js#L41-L44
43,810
netzkolchose/node-ansiparser
dist/ansiparser.js
AnsiParser
function AnsiParser(terminal) { this.initial_state = 0; // 'GROUND' is default this.current_state = this.initial_state|0; // clone global transition table this.transitions = new Uint8Array(4095); this.transitions.set(TRANSITION_TABLE); // global non pushable buffers for multiple parse invocations this.osc = ''; this.params = [0]; this.collected = ''; // back reference to terminal this.term = terminal || {}; var instructions = ['inst_p', 'inst_o', 'inst_x', 'inst_c', 'inst_e', 'inst_H', 'inst_P', 'inst_U', 'inst_E']; for (var i=0; i<instructions.length; ++i) if (!(instructions[i] in this.term)) this.term[instructions[i]] = function() {}; }
javascript
function AnsiParser(terminal) { this.initial_state = 0; // 'GROUND' is default this.current_state = this.initial_state|0; // clone global transition table this.transitions = new Uint8Array(4095); this.transitions.set(TRANSITION_TABLE); // global non pushable buffers for multiple parse invocations this.osc = ''; this.params = [0]; this.collected = ''; // back reference to terminal this.term = terminal || {}; var instructions = ['inst_p', 'inst_o', 'inst_x', 'inst_c', 'inst_e', 'inst_H', 'inst_P', 'inst_U', 'inst_E']; for (var i=0; i<instructions.length; ++i) if (!(instructions[i] in this.term)) this.term[instructions[i]] = function() {}; }
[ "function", "AnsiParser", "(", "terminal", ")", "{", "this", ".", "initial_state", "=", "0", ";", "// 'GROUND' is default", "this", ".", "current_state", "=", "this", ".", "initial_state", "|", "0", ";", "// clone global transition table", "this", ".", "transitions", "=", "new", "Uint8Array", "(", "4095", ")", ";", "this", ".", "transitions", ".", "set", "(", "TRANSITION_TABLE", ")", ";", "// global non pushable buffers for multiple parse invocations", "this", ".", "osc", "=", "''", ";", "this", ".", "params", "=", "[", "0", "]", ";", "this", ".", "collected", "=", "''", ";", "// back reference to terminal", "this", ".", "term", "=", "terminal", "||", "{", "}", ";", "var", "instructions", "=", "[", "'inst_p'", ",", "'inst_o'", ",", "'inst_x'", ",", "'inst_c'", ",", "'inst_e'", ",", "'inst_H'", ",", "'inst_P'", ",", "'inst_U'", ",", "'inst_E'", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "instructions", ".", "length", ";", "++", "i", ")", "if", "(", "!", "(", "instructions", "[", "i", "]", "in", "this", ".", "term", ")", ")", "this", ".", "term", "[", "instructions", "[", "i", "]", "]", "=", "function", "(", ")", "{", "}", ";", "}" ]
AnsiParser - Parser for ANSI terminal escape sequences. @param {Object=} terminal emulation object @constructor
[ "AnsiParser", "-", "Parser", "for", "ANSI", "terminal", "escape", "sequences", "." ]
548ba7d39d0cc937d85ffdd2430424a4bff137df
https://github.com/netzkolchose/node-ansiparser/blob/548ba7d39d0cc937d85ffdd2430424a4bff137df/dist/ansiparser.js#L217-L237
43,811
opendxl/opendxl-client-javascript
lib/config.js
getSetting
function getSetting (config, section, setting, required, readFromFile, configPath) { if (typeof (required) === 'undefined') { required = true } if (typeof (configPath) === 'undefined') { configPath = null } if (!config[section]) { if (required) { throw new DxlError('Required section not found in config: ' + section) } else { return null } } if (!config[section][setting]) { if (required) { throw new DxlError('Required setting not found in config: ' + setting) } else { return null } } var value = config[section][setting] if (readFromFile) { var fileToRead = util.getConfigFilePath(configPath, value) if (fs.existsSync(fileToRead)) { try { value = fs.readFileSync(fileToRead) } catch (err) { throw new DxlError('Unable to read file for ' + setting + ': ' + err.message) } } else { throw new DxlError('Unable to locate file for ' + setting + ': ' + value) } } return value }
javascript
function getSetting (config, section, setting, required, readFromFile, configPath) { if (typeof (required) === 'undefined') { required = true } if (typeof (configPath) === 'undefined') { configPath = null } if (!config[section]) { if (required) { throw new DxlError('Required section not found in config: ' + section) } else { return null } } if (!config[section][setting]) { if (required) { throw new DxlError('Required setting not found in config: ' + setting) } else { return null } } var value = config[section][setting] if (readFromFile) { var fileToRead = util.getConfigFilePath(configPath, value) if (fs.existsSync(fileToRead)) { try { value = fs.readFileSync(fileToRead) } catch (err) { throw new DxlError('Unable to read file for ' + setting + ': ' + err.message) } } else { throw new DxlError('Unable to locate file for ' + setting + ': ' + value) } } return value }
[ "function", "getSetting", "(", "config", ",", "section", ",", "setting", ",", "required", ",", "readFromFile", ",", "configPath", ")", "{", "if", "(", "typeof", "(", "required", ")", "===", "'undefined'", ")", "{", "required", "=", "true", "}", "if", "(", "typeof", "(", "configPath", ")", "===", "'undefined'", ")", "{", "configPath", "=", "null", "}", "if", "(", "!", "config", "[", "section", "]", ")", "{", "if", "(", "required", ")", "{", "throw", "new", "DxlError", "(", "'Required section not found in config: '", "+", "section", ")", "}", "else", "{", "return", "null", "}", "}", "if", "(", "!", "config", "[", "section", "]", "[", "setting", "]", ")", "{", "if", "(", "required", ")", "{", "throw", "new", "DxlError", "(", "'Required setting not found in config: '", "+", "setting", ")", "}", "else", "{", "return", "null", "}", "}", "var", "value", "=", "config", "[", "section", "]", "[", "setting", "]", "if", "(", "readFromFile", ")", "{", "var", "fileToRead", "=", "util", ".", "getConfigFilePath", "(", "configPath", ",", "value", ")", "if", "(", "fs", ".", "existsSync", "(", "fileToRead", ")", ")", "{", "try", "{", "value", "=", "fs", ".", "readFileSync", "(", "fileToRead", ")", "}", "catch", "(", "err", ")", "{", "throw", "new", "DxlError", "(", "'Unable to read file for '", "+", "setting", "+", "': '", "+", "err", ".", "message", ")", "}", "}", "else", "{", "throw", "new", "DxlError", "(", "'Unable to locate file for '", "+", "setting", "+", "': '", "+", "value", ")", "}", "}", "return", "value", "}" ]
Get the value for a setting from a configuration file. @private @param {Object} config - Object representation of a config file where each key corresponds to a section or setting name and each value corresponds to the contents of the section or the value for a setting, respectively. @param {String} section - Name of the configuration section in which the setting resides. @param {String} setting - Name of the setting whose value should be obtained. @param {Boolean} [required=true] - Whether or not the setting is required to exist in the configuration file. If _true_ and the setting cannot be found, a {@link DxlError} is thrown. @param {Boolean} [readFromFile=false] - Whether or not to try to treat the value of setting as a file whose contents should be read and returned as the value for the setting. @param {String} [configPath=null] - Directory path in which the configuration file should reside. @returns {Object} Value for the setting. @throws {DxlError} If the setting is required but cannot be found or if the value should be read from a file but a problem occurs in reading the file - for example, if the file cannot be found.
[ "Get", "the", "value", "for", "a", "setting", "from", "a", "configuration", "file", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/config.js#L37-L78
43,812
jeffbski/autoflow
lib/core.js
mergeOptions
function mergeOptions(parsedOptions) { return Object.keys(autoflowOptions).reduce(function (accum, k) { if (!accum[k]) accum[k] = autoflowOptions[k]; return accum; }, parsedOptions); }
javascript
function mergeOptions(parsedOptions) { return Object.keys(autoflowOptions).reduce(function (accum, k) { if (!accum[k]) accum[k] = autoflowOptions[k]; return accum; }, parsedOptions); }
[ "function", "mergeOptions", "(", "parsedOptions", ")", "{", "return", "Object", ".", "keys", "(", "autoflowOptions", ")", ".", "reduce", "(", "function", "(", "accum", ",", "k", ")", "{", "if", "(", "!", "accum", "[", "k", "]", ")", "accum", "[", "k", "]", "=", "autoflowOptions", "[", "k", "]", ";", "return", "accum", ";", "}", ",", "parsedOptions", ")", ";", "}" ]
the top emitter merge global autoflow options with parsed options
[ "the", "top", "emitter", "merge", "global", "autoflow", "options", "with", "parsed", "options" ]
aa30f6e6c2e74aa72a018c65698acac3fb478cbb
https://github.com/jeffbski/autoflow/blob/aa30f6e6c2e74aa72a018c65698acac3fb478cbb/lib/core.js#L22-L27
43,813
silas/swagger-framework
lib/framework/middleware.js
describe
function describe(ctx) { try { return ctx.operation.spec.method + ' ' + ctx.operation.resource.spec.path + ' '; } catch (err) { return ''; } }
javascript
function describe(ctx) { try { return ctx.operation.spec.method + ' ' + ctx.operation.resource.spec.path + ' '; } catch (err) { return ''; } }
[ "function", "describe", "(", "ctx", ")", "{", "try", "{", "return", "ctx", ".", "operation", ".", "spec", ".", "method", "+", "' '", "+", "ctx", ".", "operation", ".", "resource", ".", "spec", ".", "path", "+", "' '", ";", "}", "catch", "(", "err", ")", "{", "return", "''", ";", "}", "}" ]
Operation debug prefix.
[ "Operation", "debug", "prefix", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/framework/middleware.js#L25-L32
43,814
silas/swagger-framework
lib/framework/middleware.js
validate
function validate(res, result) { if (!result) return true; var err = new Error('Validation failed'); try { err.errors = result.errors(); } catch (err) { err.errors = [result.validation]; } err.expose = true; err.statusCode = 400; err.toJSON = function() { return { message: this.message, errors: this.errors, }; }; res.sf.reply(err); }
javascript
function validate(res, result) { if (!result) return true; var err = new Error('Validation failed'); try { err.errors = result.errors(); } catch (err) { err.errors = [result.validation]; } err.expose = true; err.statusCode = 400; err.toJSON = function() { return { message: this.message, errors: this.errors, }; }; res.sf.reply(err); }
[ "function", "validate", "(", "res", ",", "result", ")", "{", "if", "(", "!", "result", ")", "return", "true", ";", "var", "err", "=", "new", "Error", "(", "'Validation failed'", ")", ";", "try", "{", "err", ".", "errors", "=", "result", ".", "errors", "(", ")", ";", "}", "catch", "(", "err", ")", "{", "err", ".", "errors", "=", "[", "result", ".", "validation", "]", ";", "}", "err", ".", "expose", "=", "true", ";", "err", ".", "statusCode", "=", "400", ";", "err", ".", "toJSON", "=", "function", "(", ")", "{", "return", "{", "message", ":", "this", ".", "message", ",", "errors", ":", "this", ".", "errors", ",", "}", ";", "}", ";", "res", ".", "sf", ".", "reply", "(", "err", ")", ";", "}" ]
Render validation errors.
[ "Render", "validation", "errors", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/framework/middleware.js#L38-L57
43,815
silas/swagger-framework
lib/framework/middleware.js
lookup
function lookup(obj, type, name) { while (obj) { if (obj[type] && obj[type].hasOwnProperty(name)) { return obj[type][name]; } obj = obj.parent; } }
javascript
function lookup(obj, type, name) { while (obj) { if (obj[type] && obj[type].hasOwnProperty(name)) { return obj[type][name]; } obj = obj.parent; } }
[ "function", "lookup", "(", "obj", ",", "type", ",", "name", ")", "{", "while", "(", "obj", ")", "{", "if", "(", "obj", "[", "type", "]", "&&", "obj", "[", "type", "]", ".", "hasOwnProperty", "(", "name", ")", ")", "{", "return", "obj", "[", "type", "]", "[", "name", "]", ";", "}", "obj", "=", "obj", ".", "parent", ";", "}", "}" ]
Lookup property.
[ "Lookup", "property", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/framework/middleware.js#L63-L70
43,816
silas/swagger-framework
lib/framework/middleware.js
validateOptions
function validateOptions(operation, type, useCoerce) { var options = { useCoerce: useCoerce }; // capitalize type var suffix = type[0].toUpperCase() + type.slice(1); // Get remove option (ex: options.removeHeader) var removeAdditional = lookup(operation, 'options', 'remove' + suffix); if (typeof removeAdditional === 'undefined') { removeAdditional = true; } options.removeAdditional = !!removeAdditional; return options; }
javascript
function validateOptions(operation, type, useCoerce) { var options = { useCoerce: useCoerce }; // capitalize type var suffix = type[0].toUpperCase() + type.slice(1); // Get remove option (ex: options.removeHeader) var removeAdditional = lookup(operation, 'options', 'remove' + suffix); if (typeof removeAdditional === 'undefined') { removeAdditional = true; } options.removeAdditional = !!removeAdditional; return options; }
[ "function", "validateOptions", "(", "operation", ",", "type", ",", "useCoerce", ")", "{", "var", "options", "=", "{", "useCoerce", ":", "useCoerce", "}", ";", "// capitalize type", "var", "suffix", "=", "type", "[", "0", "]", ".", "toUpperCase", "(", ")", "+", "type", ".", "slice", "(", "1", ")", ";", "// Get remove option (ex: options.removeHeader)", "var", "removeAdditional", "=", "lookup", "(", "operation", ",", "'options'", ",", "'remove'", "+", "suffix", ")", ";", "if", "(", "typeof", "removeAdditional", "===", "'undefined'", ")", "{", "removeAdditional", "=", "true", ";", "}", "options", ".", "removeAdditional", "=", "!", "!", "removeAdditional", ";", "return", "options", ";", "}" ]
Setup validation options.
[ "Setup", "validation", "options", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/framework/middleware.js#L76-L91
43,817
silas/swagger-framework
lib/framework/middleware.js
before
function before(ctx) { var fn = lookup(ctx.operation, 'middleware', 'before'); var prefix = describe(ctx); if (fn) { return fn(ctx); } else { debug(prefix + 'before middleware disabled (not defined)'); } }
javascript
function before(ctx) { var fn = lookup(ctx.operation, 'middleware', 'before'); var prefix = describe(ctx); if (fn) { return fn(ctx); } else { debug(prefix + 'before middleware disabled (not defined)'); } }
[ "function", "before", "(", "ctx", ")", "{", "var", "fn", "=", "lookup", "(", "ctx", ".", "operation", ",", "'middleware'", ",", "'before'", ")", ";", "var", "prefix", "=", "describe", "(", "ctx", ")", ";", "if", "(", "fn", ")", "{", "return", "fn", "(", "ctx", ")", ";", "}", "else", "{", "debug", "(", "prefix", "+", "'before middleware disabled (not defined)'", ")", ";", "}", "}" ]
Before middleware.
[ "Before", "middleware", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/framework/middleware.js#L97-L106
43,818
silas/swagger-framework
lib/framework/middleware.js
header
function header(ctx) { var prefix = describe(ctx); var schema = transform.parameters(ctx.operation.spec, 'header'); if (!schema) { debug(prefix + 'header middleware disabled (no schema)'); return; } var env = ctx.operation.resource.api.env; var options = validateOptions(ctx.operation, 'header', true); // Create a list of headers to split on comma var allowMultiple = {}; ctx.operation.spec.parameters.forEach(function(parameter) { if (parameter.paramType === 'header' && parameter.allowMultiple) { var name = parameter.name.toLowerCase(); allowMultiple[name] = constants.singleHeaders.indexOf(name) < 0; } }); schema = { type: 'object', properties: { header: schema }, required: ['header'], }; return function(req, res, next) { var header = lodash.cloneDeep(req.headers); // This only works for small subset of headers before Node v0.11 lodash.forOwn(header, function(value, name) { if (allowMultiple[name]) header[name] = value.split(', '); }); if (validate(res, env.validate(schema, { header: header }, options))) { req.sf.header = header; next(); } }; }
javascript
function header(ctx) { var prefix = describe(ctx); var schema = transform.parameters(ctx.operation.spec, 'header'); if (!schema) { debug(prefix + 'header middleware disabled (no schema)'); return; } var env = ctx.operation.resource.api.env; var options = validateOptions(ctx.operation, 'header', true); // Create a list of headers to split on comma var allowMultiple = {}; ctx.operation.spec.parameters.forEach(function(parameter) { if (parameter.paramType === 'header' && parameter.allowMultiple) { var name = parameter.name.toLowerCase(); allowMultiple[name] = constants.singleHeaders.indexOf(name) < 0; } }); schema = { type: 'object', properties: { header: schema }, required: ['header'], }; return function(req, res, next) { var header = lodash.cloneDeep(req.headers); // This only works for small subset of headers before Node v0.11 lodash.forOwn(header, function(value, name) { if (allowMultiple[name]) header[name] = value.split(', '); }); if (validate(res, env.validate(schema, { header: header }, options))) { req.sf.header = header; next(); } }; }
[ "function", "header", "(", "ctx", ")", "{", "var", "prefix", "=", "describe", "(", "ctx", ")", ";", "var", "schema", "=", "transform", ".", "parameters", "(", "ctx", ".", "operation", ".", "spec", ",", "'header'", ")", ";", "if", "(", "!", "schema", ")", "{", "debug", "(", "prefix", "+", "'header middleware disabled (no schema)'", ")", ";", "return", ";", "}", "var", "env", "=", "ctx", ".", "operation", ".", "resource", ".", "api", ".", "env", ";", "var", "options", "=", "validateOptions", "(", "ctx", ".", "operation", ",", "'header'", ",", "true", ")", ";", "// Create a list of headers to split on comma", "var", "allowMultiple", "=", "{", "}", ";", "ctx", ".", "operation", ".", "spec", ".", "parameters", ".", "forEach", "(", "function", "(", "parameter", ")", "{", "if", "(", "parameter", ".", "paramType", "===", "'header'", "&&", "parameter", ".", "allowMultiple", ")", "{", "var", "name", "=", "parameter", ".", "name", ".", "toLowerCase", "(", ")", ";", "allowMultiple", "[", "name", "]", "=", "constants", ".", "singleHeaders", ".", "indexOf", "(", "name", ")", "<", "0", ";", "}", "}", ")", ";", "schema", "=", "{", "type", ":", "'object'", ",", "properties", ":", "{", "header", ":", "schema", "}", ",", "required", ":", "[", "'header'", "]", ",", "}", ";", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "var", "header", "=", "lodash", ".", "cloneDeep", "(", "req", ".", "headers", ")", ";", "// This only works for small subset of headers before Node v0.11", "lodash", ".", "forOwn", "(", "header", ",", "function", "(", "value", ",", "name", ")", "{", "if", "(", "allowMultiple", "[", "name", "]", ")", "header", "[", "name", "]", "=", "value", ".", "split", "(", "', '", ")", ";", "}", ")", ";", "if", "(", "validate", "(", "res", ",", "env", ".", "validate", "(", "schema", ",", "{", "header", ":", "header", "}", ",", "options", ")", ")", ")", "{", "req", ".", "sf", ".", "header", "=", "header", ";", "next", "(", ")", ";", "}", "}", ";", "}" ]
Validate headers based on Swagger spec.
[ "Validate", "headers", "based", "on", "Swagger", "spec", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/framework/middleware.js#L112-L152
43,819
silas/swagger-framework
lib/framework/middleware.js
produces
function produces(ctx) { var mimes = ctx.operation.spec.produces || ctx.operation.resource.api.spec.produces || []; var prefix = describe(ctx); if (!mimes.length) { debug(prefix + 'produces validation disabled (no produces)'); } return function(req, res, next) { req.sf.accept = accepts(req); if (!mimes.length) return next(); var types = req.sf.accept.types(mimes); if (!types) { debug(prefix + 'produces mime not supported: "%s" not in "%s"', req.headers.accept, mimes); var err = new Error('Not acceptable (' + req.headers.accept + '), supports: ' + mimes.join(', ')); err.statusCode = 406; err.expose = true; return res.sf.reply(err); } if (typeof types === 'string') types = [types]; types.some(function(type) { if (!req.sf.router.encoder[type]) return; res.sf.produce = { encoder: req.sf.router.encoder[type], mime: type }; return true; }); next(); }; }
javascript
function produces(ctx) { var mimes = ctx.operation.spec.produces || ctx.operation.resource.api.spec.produces || []; var prefix = describe(ctx); if (!mimes.length) { debug(prefix + 'produces validation disabled (no produces)'); } return function(req, res, next) { req.sf.accept = accepts(req); if (!mimes.length) return next(); var types = req.sf.accept.types(mimes); if (!types) { debug(prefix + 'produces mime not supported: "%s" not in "%s"', req.headers.accept, mimes); var err = new Error('Not acceptable (' + req.headers.accept + '), supports: ' + mimes.join(', ')); err.statusCode = 406; err.expose = true; return res.sf.reply(err); } if (typeof types === 'string') types = [types]; types.some(function(type) { if (!req.sf.router.encoder[type]) return; res.sf.produce = { encoder: req.sf.router.encoder[type], mime: type }; return true; }); next(); }; }
[ "function", "produces", "(", "ctx", ")", "{", "var", "mimes", "=", "ctx", ".", "operation", ".", "spec", ".", "produces", "||", "ctx", ".", "operation", ".", "resource", ".", "api", ".", "spec", ".", "produces", "||", "[", "]", ";", "var", "prefix", "=", "describe", "(", "ctx", ")", ";", "if", "(", "!", "mimes", ".", "length", ")", "{", "debug", "(", "prefix", "+", "'produces validation disabled (no produces)'", ")", ";", "}", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "req", ".", "sf", ".", "accept", "=", "accepts", "(", "req", ")", ";", "if", "(", "!", "mimes", ".", "length", ")", "return", "next", "(", ")", ";", "var", "types", "=", "req", ".", "sf", ".", "accept", ".", "types", "(", "mimes", ")", ";", "if", "(", "!", "types", ")", "{", "debug", "(", "prefix", "+", "'produces mime not supported: \"%s\" not in \"%s\"'", ",", "req", ".", "headers", ".", "accept", ",", "mimes", ")", ";", "var", "err", "=", "new", "Error", "(", "'Not acceptable ('", "+", "req", ".", "headers", ".", "accept", "+", "'), supports: '", "+", "mimes", ".", "join", "(", "', '", ")", ")", ";", "err", ".", "statusCode", "=", "406", ";", "err", ".", "expose", "=", "true", ";", "return", "res", ".", "sf", ".", "reply", "(", "err", ")", ";", "}", "if", "(", "typeof", "types", "===", "'string'", ")", "types", "=", "[", "types", "]", ";", "types", ".", "some", "(", "function", "(", "type", ")", "{", "if", "(", "!", "req", ".", "sf", ".", "router", ".", "encoder", "[", "type", "]", ")", "return", ";", "res", ".", "sf", ".", "produce", "=", "{", "encoder", ":", "req", ".", "sf", ".", "router", ".", "encoder", "[", "type", "]", ",", "mime", ":", "type", "}", ";", "return", "true", ";", "}", ")", ";", "next", "(", ")", ";", "}", ";", "}" ]
Check produces.
[ "Check", "produces", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/framework/middleware.js#L158-L202
43,820
silas/swagger-framework
lib/framework/middleware.js
query
function query(ctx) { var prefix = describe(ctx); var schema = transform.parameters(ctx.operation.spec, 'query'); if (!schema) { debug(prefix + 'query middleware disabled (no schema)'); return; } var env = ctx.operation.resource.api.env; var options = validateOptions(ctx.operation, 'query', true); schema = { type: 'object', properties: { query: schema }, required: ['query'], }; return function(req, res, next) { var query = lodash.clone(req.sf.url.query); if (validate(res, env.validate(schema, { query: query }, options))) { req.sf.query = query; next(); } }; }
javascript
function query(ctx) { var prefix = describe(ctx); var schema = transform.parameters(ctx.operation.spec, 'query'); if (!schema) { debug(prefix + 'query middleware disabled (no schema)'); return; } var env = ctx.operation.resource.api.env; var options = validateOptions(ctx.operation, 'query', true); schema = { type: 'object', properties: { query: schema }, required: ['query'], }; return function(req, res, next) { var query = lodash.clone(req.sf.url.query); if (validate(res, env.validate(schema, { query: query }, options))) { req.sf.query = query; next(); } }; }
[ "function", "query", "(", "ctx", ")", "{", "var", "prefix", "=", "describe", "(", "ctx", ")", ";", "var", "schema", "=", "transform", ".", "parameters", "(", "ctx", ".", "operation", ".", "spec", ",", "'query'", ")", ";", "if", "(", "!", "schema", ")", "{", "debug", "(", "prefix", "+", "'query middleware disabled (no schema)'", ")", ";", "return", ";", "}", "var", "env", "=", "ctx", ".", "operation", ".", "resource", ".", "api", ".", "env", ";", "var", "options", "=", "validateOptions", "(", "ctx", ".", "operation", ",", "'query'", ",", "true", ")", ";", "schema", "=", "{", "type", ":", "'object'", ",", "properties", ":", "{", "query", ":", "schema", "}", ",", "required", ":", "[", "'query'", "]", ",", "}", ";", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "var", "query", "=", "lodash", ".", "clone", "(", "req", ".", "sf", ".", "url", ".", "query", ")", ";", "if", "(", "validate", "(", "res", ",", "env", ".", "validate", "(", "schema", ",", "{", "query", ":", "query", "}", ",", "options", ")", ")", ")", "{", "req", ".", "sf", ".", "query", "=", "query", ";", "next", "(", ")", ";", "}", "}", ";", "}" ]
Validate query based on Swagger spec.
[ "Validate", "query", "based", "on", "Swagger", "spec", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/framework/middleware.js#L240-L266
43,821
silas/swagger-framework
lib/framework/middleware.js
authenticate
function authenticate(ctx) { var fn = lookup(ctx.operation, 'middleware', 'authenticate'); var prefix = describe(ctx); if (fn) { return fn(ctx); } else { debug(prefix + 'authenticate middleware disabled (not defined)'); } }
javascript
function authenticate(ctx) { var fn = lookup(ctx.operation, 'middleware', 'authenticate'); var prefix = describe(ctx); if (fn) { return fn(ctx); } else { debug(prefix + 'authenticate middleware disabled (not defined)'); } }
[ "function", "authenticate", "(", "ctx", ")", "{", "var", "fn", "=", "lookup", "(", "ctx", ".", "operation", ",", "'middleware'", ",", "'authenticate'", ")", ";", "var", "prefix", "=", "describe", "(", "ctx", ")", ";", "if", "(", "fn", ")", "{", "return", "fn", "(", "ctx", ")", ";", "}", "else", "{", "debug", "(", "prefix", "+", "'authenticate middleware disabled (not defined)'", ")", ";", "}", "}" ]
Authenticate request.
[ "Authenticate", "request", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/framework/middleware.js#L272-L281
43,822
silas/swagger-framework
lib/framework/middleware.js
consumes
function consumes(ctx) { if (['HEAD', 'GET'].indexOf(ctx.operation.spec.method) >= 0) return; var mimes = ctx.operation.spec.consumes || ctx.operation.resource.api.spec.consumes || []; var prefix = describe(ctx); if (!mimes.length) { debug(prefix + 'consumes middleware disabled (no consumes)'); return; } return function(req, res, next) { if (req.sf.text && !is(req, mimes)) { debug(prefix + 'consumes mime not supported: "%s" not in "%s"', req.headers['content-type'], mimes); var err = new Error('Unsupported Content-Type (' + req.headers['content-type'] + '), supports: ' + mimes.join(', ')); err.statusCode = 415; err.expose = true; return res.sf.reply(err); } next(); }; }
javascript
function consumes(ctx) { if (['HEAD', 'GET'].indexOf(ctx.operation.spec.method) >= 0) return; var mimes = ctx.operation.spec.consumes || ctx.operation.resource.api.spec.consumes || []; var prefix = describe(ctx); if (!mimes.length) { debug(prefix + 'consumes middleware disabled (no consumes)'); return; } return function(req, res, next) { if (req.sf.text && !is(req, mimes)) { debug(prefix + 'consumes mime not supported: "%s" not in "%s"', req.headers['content-type'], mimes); var err = new Error('Unsupported Content-Type (' + req.headers['content-type'] + '), supports: ' + mimes.join(', ')); err.statusCode = 415; err.expose = true; return res.sf.reply(err); } next(); }; }
[ "function", "consumes", "(", "ctx", ")", "{", "if", "(", "[", "'HEAD'", ",", "'GET'", "]", ".", "indexOf", "(", "ctx", ".", "operation", ".", "spec", ".", "method", ")", ">=", "0", ")", "return", ";", "var", "mimes", "=", "ctx", ".", "operation", ".", "spec", ".", "consumes", "||", "ctx", ".", "operation", ".", "resource", ".", "api", ".", "spec", ".", "consumes", "||", "[", "]", ";", "var", "prefix", "=", "describe", "(", "ctx", ")", ";", "if", "(", "!", "mimes", ".", "length", ")", "{", "debug", "(", "prefix", "+", "'consumes middleware disabled (no consumes)'", ")", ";", "return", ";", "}", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "req", ".", "sf", ".", "text", "&&", "!", "is", "(", "req", ",", "mimes", ")", ")", "{", "debug", "(", "prefix", "+", "'consumes mime not supported: \"%s\" not in \"%s\"'", ",", "req", ".", "headers", "[", "'content-type'", "]", ",", "mimes", ")", ";", "var", "err", "=", "new", "Error", "(", "'Unsupported Content-Type ('", "+", "req", ".", "headers", "[", "'content-type'", "]", "+", "'), supports: '", "+", "mimes", ".", "join", "(", "', '", ")", ")", ";", "err", ".", "statusCode", "=", "415", ";", "err", ".", "expose", "=", "true", ";", "return", "res", ".", "sf", ".", "reply", "(", "err", ")", ";", "}", "next", "(", ")", ";", "}", ";", "}" ]
Check consumes.
[ "Check", "consumes", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/framework/middleware.js#L287-L315
43,823
silas/swagger-framework
lib/framework/middleware.js
raw
function raw(ctx) { if (['HEAD', 'GET'].indexOf(ctx.operation.spec.method) >= 0) return; var limit = lookup(ctx.operation, 'options', 'bodyLimit') || '100kb'; return function(req, res, next) { rawBody(req, { length: req.headers['content-length'], limit: limit, encoding: http.CHARSET }, function(err, text) { if (err) { if (err.statusCode) return res.sf.reply(err); return next(err); } req.sf.text = text; // Mimic body-parser for use by proxies if (text && text.length) { req.body = text; } next(); }); }; }
javascript
function raw(ctx) { if (['HEAD', 'GET'].indexOf(ctx.operation.spec.method) >= 0) return; var limit = lookup(ctx.operation, 'options', 'bodyLimit') || '100kb'; return function(req, res, next) { rawBody(req, { length: req.headers['content-length'], limit: limit, encoding: http.CHARSET }, function(err, text) { if (err) { if (err.statusCode) return res.sf.reply(err); return next(err); } req.sf.text = text; // Mimic body-parser for use by proxies if (text && text.length) { req.body = text; } next(); }); }; }
[ "function", "raw", "(", "ctx", ")", "{", "if", "(", "[", "'HEAD'", ",", "'GET'", "]", ".", "indexOf", "(", "ctx", ".", "operation", ".", "spec", ".", "method", ")", ">=", "0", ")", "return", ";", "var", "limit", "=", "lookup", "(", "ctx", ".", "operation", ",", "'options'", ",", "'bodyLimit'", ")", "||", "'100kb'", ";", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "rawBody", "(", "req", ",", "{", "length", ":", "req", ".", "headers", "[", "'content-length'", "]", ",", "limit", ":", "limit", ",", "encoding", ":", "http", ".", "CHARSET", "}", ",", "function", "(", "err", ",", "text", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", ".", "statusCode", ")", "return", "res", ".", "sf", ".", "reply", "(", "err", ")", ";", "return", "next", "(", "err", ")", ";", "}", "req", ".", "sf", ".", "text", "=", "text", ";", "// Mimic body-parser for use by proxies", "if", "(", "text", "&&", "text", ".", "length", ")", "{", "req", ".", "body", "=", "text", ";", "}", "next", "(", ")", ";", "}", ")", ";", "}", ";", "}" ]
Parse raw body.
[ "Parse", "raw", "body", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/framework/middleware.js#L321-L347
43,824
silas/swagger-framework
lib/framework/middleware.js
form
function form(ctx) { if (['HEAD', 'GET'].indexOf(ctx.operation.spec.method) >= 0) return; var mimes = ctx.operation.spec.consumes || ctx.operation.resource.api.spec.consumes || []; var mime = 'application/x-www-form-urlencoded'; var prefix = describe(ctx); var decode = ctx.router.decoder[mime]; if (mimes.indexOf(mime) === -1) { debug(prefix + 'form middleware disabled (no consumes)'); return; } var env = ctx.operation.resource.api.env; var options = validateOptions(ctx.operation, 'form', true); var schema = transform.parameters(ctx.operation.spec, 'form'); if (!schema) { debug(prefix + 'form middleware disabled (no schema)'); return; } schema = { type: 'object', properties: { form: schema }, required: ['form'], }; return function(req, res, next) { if (is(req, [mime])) { var form; try { form = decode(req.sf.text); } catch (err) { return next(err); } form = req.sf.form = lodash.clone(form); if (validate(res, env.validate(schema, { form: form }, options))) { next(); } } else { next(); } }; }
javascript
function form(ctx) { if (['HEAD', 'GET'].indexOf(ctx.operation.spec.method) >= 0) return; var mimes = ctx.operation.spec.consumes || ctx.operation.resource.api.spec.consumes || []; var mime = 'application/x-www-form-urlencoded'; var prefix = describe(ctx); var decode = ctx.router.decoder[mime]; if (mimes.indexOf(mime) === -1) { debug(prefix + 'form middleware disabled (no consumes)'); return; } var env = ctx.operation.resource.api.env; var options = validateOptions(ctx.operation, 'form', true); var schema = transform.parameters(ctx.operation.spec, 'form'); if (!schema) { debug(prefix + 'form middleware disabled (no schema)'); return; } schema = { type: 'object', properties: { form: schema }, required: ['form'], }; return function(req, res, next) { if (is(req, [mime])) { var form; try { form = decode(req.sf.text); } catch (err) { return next(err); } form = req.sf.form = lodash.clone(form); if (validate(res, env.validate(schema, { form: form }, options))) { next(); } } else { next(); } }; }
[ "function", "form", "(", "ctx", ")", "{", "if", "(", "[", "'HEAD'", ",", "'GET'", "]", ".", "indexOf", "(", "ctx", ".", "operation", ".", "spec", ".", "method", ")", ">=", "0", ")", "return", ";", "var", "mimes", "=", "ctx", ".", "operation", ".", "spec", ".", "consumes", "||", "ctx", ".", "operation", ".", "resource", ".", "api", ".", "spec", ".", "consumes", "||", "[", "]", ";", "var", "mime", "=", "'application/x-www-form-urlencoded'", ";", "var", "prefix", "=", "describe", "(", "ctx", ")", ";", "var", "decode", "=", "ctx", ".", "router", ".", "decoder", "[", "mime", "]", ";", "if", "(", "mimes", ".", "indexOf", "(", "mime", ")", "===", "-", "1", ")", "{", "debug", "(", "prefix", "+", "'form middleware disabled (no consumes)'", ")", ";", "return", ";", "}", "var", "env", "=", "ctx", ".", "operation", ".", "resource", ".", "api", ".", "env", ";", "var", "options", "=", "validateOptions", "(", "ctx", ".", "operation", ",", "'form'", ",", "true", ")", ";", "var", "schema", "=", "transform", ".", "parameters", "(", "ctx", ".", "operation", ".", "spec", ",", "'form'", ")", ";", "if", "(", "!", "schema", ")", "{", "debug", "(", "prefix", "+", "'form middleware disabled (no schema)'", ")", ";", "return", ";", "}", "schema", "=", "{", "type", ":", "'object'", ",", "properties", ":", "{", "form", ":", "schema", "}", ",", "required", ":", "[", "'form'", "]", ",", "}", ";", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "is", "(", "req", ",", "[", "mime", "]", ")", ")", "{", "var", "form", ";", "try", "{", "form", "=", "decode", "(", "req", ".", "sf", ".", "text", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "next", "(", "err", ")", ";", "}", "form", "=", "req", ".", "sf", ".", "form", "=", "lodash", ".", "clone", "(", "form", ")", ";", "if", "(", "validate", "(", "res", ",", "env", ".", "validate", "(", "schema", ",", "{", "form", ":", "form", "}", ",", "options", ")", ")", ")", "{", "next", "(", ")", ";", "}", "}", "else", "{", "next", "(", ")", ";", "}", "}", ";", "}" ]
Validate form based on Swagger spec.
[ "Validate", "form", "based", "on", "Swagger", "spec", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/framework/middleware.js#L353-L401
43,825
silas/swagger-framework
lib/framework/middleware.js
body
function body(ctx) { if (['HEAD', 'GET'].indexOf(ctx.operation.spec.method) >= 0) return; var consumeMimes = ctx.operation.spec.consumes || ctx.operation.resource.api.spec.consumes || []; var mimes = lodash.intersection(consumeMimes, Object.keys(ctx.router.decoder)); var prefix = describe(ctx); if (!mimes.length) { debug(prefix + 'body middleware disabled (no consumes)'); return; } var env = ctx.operation.resource.api.env; var options = validateOptions(ctx.operation, 'form', false); var schema = transform.parameters(ctx.operation.spec, 'body'); if (!schema) { debug(prefix + 'body middleware disabled (no schema)'); return; } return function(req, res, next) { var mime = is(req, mimes); var bodyErr; if (mime) { var body; if (req.sf.text) { try { body = ctx.router.decoder[mime](req.sf.text); } catch (err) { debug(prefix + 'body decoder failed', err); bodyErr = new Error('Decode body failed'); bodyErr.statusCode = 400; bodyErr.parent = err; bodyErr.expose = true; return next(bodyErr); } } else if (schema.required) { bodyErr = new Error('Body required'); bodyErr.statusCode = 400; bodyErr.expose = true; return next(bodyErr); } else { return next(); } req.sf.body = body; if (validate(res, env.validate(schema, { body: body }, options))) { next(); } } else if (schema.required) { bodyErr = new Error('Body required'); bodyErr.statusCode = 400; bodyErr.expose = true; return next(bodyErr); } else { next(); } }; }
javascript
function body(ctx) { if (['HEAD', 'GET'].indexOf(ctx.operation.spec.method) >= 0) return; var consumeMimes = ctx.operation.spec.consumes || ctx.operation.resource.api.spec.consumes || []; var mimes = lodash.intersection(consumeMimes, Object.keys(ctx.router.decoder)); var prefix = describe(ctx); if (!mimes.length) { debug(prefix + 'body middleware disabled (no consumes)'); return; } var env = ctx.operation.resource.api.env; var options = validateOptions(ctx.operation, 'form', false); var schema = transform.parameters(ctx.operation.spec, 'body'); if (!schema) { debug(prefix + 'body middleware disabled (no schema)'); return; } return function(req, res, next) { var mime = is(req, mimes); var bodyErr; if (mime) { var body; if (req.sf.text) { try { body = ctx.router.decoder[mime](req.sf.text); } catch (err) { debug(prefix + 'body decoder failed', err); bodyErr = new Error('Decode body failed'); bodyErr.statusCode = 400; bodyErr.parent = err; bodyErr.expose = true; return next(bodyErr); } } else if (schema.required) { bodyErr = new Error('Body required'); bodyErr.statusCode = 400; bodyErr.expose = true; return next(bodyErr); } else { return next(); } req.sf.body = body; if (validate(res, env.validate(schema, { body: body }, options))) { next(); } } else if (schema.required) { bodyErr = new Error('Body required'); bodyErr.statusCode = 400; bodyErr.expose = true; return next(bodyErr); } else { next(); } }; }
[ "function", "body", "(", "ctx", ")", "{", "if", "(", "[", "'HEAD'", ",", "'GET'", "]", ".", "indexOf", "(", "ctx", ".", "operation", ".", "spec", ".", "method", ")", ">=", "0", ")", "return", ";", "var", "consumeMimes", "=", "ctx", ".", "operation", ".", "spec", ".", "consumes", "||", "ctx", ".", "operation", ".", "resource", ".", "api", ".", "spec", ".", "consumes", "||", "[", "]", ";", "var", "mimes", "=", "lodash", ".", "intersection", "(", "consumeMimes", ",", "Object", ".", "keys", "(", "ctx", ".", "router", ".", "decoder", ")", ")", ";", "var", "prefix", "=", "describe", "(", "ctx", ")", ";", "if", "(", "!", "mimes", ".", "length", ")", "{", "debug", "(", "prefix", "+", "'body middleware disabled (no consumes)'", ")", ";", "return", ";", "}", "var", "env", "=", "ctx", ".", "operation", ".", "resource", ".", "api", ".", "env", ";", "var", "options", "=", "validateOptions", "(", "ctx", ".", "operation", ",", "'form'", ",", "false", ")", ";", "var", "schema", "=", "transform", ".", "parameters", "(", "ctx", ".", "operation", ".", "spec", ",", "'body'", ")", ";", "if", "(", "!", "schema", ")", "{", "debug", "(", "prefix", "+", "'body middleware disabled (no schema)'", ")", ";", "return", ";", "}", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "var", "mime", "=", "is", "(", "req", ",", "mimes", ")", ";", "var", "bodyErr", ";", "if", "(", "mime", ")", "{", "var", "body", ";", "if", "(", "req", ".", "sf", ".", "text", ")", "{", "try", "{", "body", "=", "ctx", ".", "router", ".", "decoder", "[", "mime", "]", "(", "req", ".", "sf", ".", "text", ")", ";", "}", "catch", "(", "err", ")", "{", "debug", "(", "prefix", "+", "'body decoder failed'", ",", "err", ")", ";", "bodyErr", "=", "new", "Error", "(", "'Decode body failed'", ")", ";", "bodyErr", ".", "statusCode", "=", "400", ";", "bodyErr", ".", "parent", "=", "err", ";", "bodyErr", ".", "expose", "=", "true", ";", "return", "next", "(", "bodyErr", ")", ";", "}", "}", "else", "if", "(", "schema", ".", "required", ")", "{", "bodyErr", "=", "new", "Error", "(", "'Body required'", ")", ";", "bodyErr", ".", "statusCode", "=", "400", ";", "bodyErr", ".", "expose", "=", "true", ";", "return", "next", "(", "bodyErr", ")", ";", "}", "else", "{", "return", "next", "(", ")", ";", "}", "req", ".", "sf", ".", "body", "=", "body", ";", "if", "(", "validate", "(", "res", ",", "env", ".", "validate", "(", "schema", ",", "{", "body", ":", "body", "}", ",", "options", ")", ")", ")", "{", "next", "(", ")", ";", "}", "}", "else", "if", "(", "schema", ".", "required", ")", "{", "bodyErr", "=", "new", "Error", "(", "'Body required'", ")", ";", "bodyErr", ".", "statusCode", "=", "400", ";", "bodyErr", ".", "expose", "=", "true", ";", "return", "next", "(", "bodyErr", ")", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}", ";", "}" ]
Validate body based on Swagger spec.
[ "Validate", "body", "based", "on", "Swagger", "spec", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/framework/middleware.js#L407-L475
43,826
silas/swagger-framework
lib/framework/middleware.js
authorize
function authorize(ctx) { var fn = lookup(ctx.operation, 'middleware', 'authorize'); var prefix = describe(ctx); if (fn) { return fn(ctx); } else { debug(prefix + 'authorize middleware disabled (not defined)'); } }
javascript
function authorize(ctx) { var fn = lookup(ctx.operation, 'middleware', 'authorize'); var prefix = describe(ctx); if (fn) { return fn(ctx); } else { debug(prefix + 'authorize middleware disabled (not defined)'); } }
[ "function", "authorize", "(", "ctx", ")", "{", "var", "fn", "=", "lookup", "(", "ctx", ".", "operation", ",", "'middleware'", ",", "'authorize'", ")", ";", "var", "prefix", "=", "describe", "(", "ctx", ")", ";", "if", "(", "fn", ")", "{", "return", "fn", "(", "ctx", ")", ";", "}", "else", "{", "debug", "(", "prefix", "+", "'authorize middleware disabled (not defined)'", ")", ";", "}", "}" ]
Authorize request.
[ "Authorize", "request", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/framework/middleware.js#L481-L490
43,827
silas/swagger-framework
lib/framework/middleware.js
after
function after(ctx) { var fn = lookup(ctx.operation, 'middleware', 'after'); var prefix = describe(ctx); if (fn) { return fn(ctx); } else { debug(prefix + 'after middleware disabled (not defined)'); } }
javascript
function after(ctx) { var fn = lookup(ctx.operation, 'middleware', 'after'); var prefix = describe(ctx); if (fn) { return fn(ctx); } else { debug(prefix + 'after middleware disabled (not defined)'); } }
[ "function", "after", "(", "ctx", ")", "{", "var", "fn", "=", "lookup", "(", "ctx", ".", "operation", ",", "'middleware'", ",", "'after'", ")", ";", "var", "prefix", "=", "describe", "(", "ctx", ")", ";", "if", "(", "fn", ")", "{", "return", "fn", "(", "ctx", ")", ";", "}", "else", "{", "debug", "(", "prefix", "+", "'after middleware disabled (not defined)'", ")", ";", "}", "}" ]
After middleware.
[ "After", "middleware", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/framework/middleware.js#L496-L505
43,828
imsobear/node-qrcode
index.js
getScript
function getScript(cfg) { var script = function(cfg) { $('#J_Qrcode').qrcode({ 'render': 'canvas', 'size': cfg.size || 150, 'color': '#3a3', 'text': cfg.text }); var canvas = $('#J_Qrcode canvas')[0]; // here is the most important part because if you dont replace you will get a DOM 18 exception. var imageData = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream'); endCallback(imageData); }; return '(' + script.toString() + ')(' + JSON.stringify(cfg) + ');'; }
javascript
function getScript(cfg) { var script = function(cfg) { $('#J_Qrcode').qrcode({ 'render': 'canvas', 'size': cfg.size || 150, 'color': '#3a3', 'text': cfg.text }); var canvas = $('#J_Qrcode canvas')[0]; // here is the most important part because if you dont replace you will get a DOM 18 exception. var imageData = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream'); endCallback(imageData); }; return '(' + script.toString() + ')(' + JSON.stringify(cfg) + ');'; }
[ "function", "getScript", "(", "cfg", ")", "{", "var", "script", "=", "function", "(", "cfg", ")", "{", "$", "(", "'#J_Qrcode'", ")", ".", "qrcode", "(", "{", "'render'", ":", "'canvas'", ",", "'size'", ":", "cfg", ".", "size", "||", "150", ",", "'color'", ":", "'#3a3'", ",", "'text'", ":", "cfg", ".", "text", "}", ")", ";", "var", "canvas", "=", "$", "(", "'#J_Qrcode canvas'", ")", "[", "0", "]", ";", "// here is the most important part because if you dont replace you will get a DOM 18 exception.", "var", "imageData", "=", "canvas", ".", "toDataURL", "(", "'image/png'", ")", ".", "replace", "(", "'image/png'", ",", "'image/octet-stream'", ")", ";", "endCallback", "(", "imageData", ")", ";", "}", ";", "return", "'('", "+", "script", ".", "toString", "(", ")", "+", "')('", "+", "JSON", ".", "stringify", "(", "cfg", ")", "+", "');'", ";", "}" ]
get the script to generate canvas in the browser
[ "get", "the", "script", "to", "generate", "canvas", "in", "the", "browser" ]
4544c3856a7f9a8e01292619964f75c5b7217598
https://github.com/imsobear/node-qrcode/blob/4544c3856a7f9a8e01292619964f75c5b7217598/index.js#L84-L102
43,829
layerhq/node-layer-webhooks-services
examples/server.js
startInlineServices
function startInlineServices() { // Provide a webhook definition var hook = { name: 'Inline Sample', events: ['message.sent'], path: '/inline_sample_message_sent', }; // Register this webhook with Layer's Services webhooksServices.register({ secret: SECRET, url: HOST + ':' + PORT, hooks: [hook] }); // Listen for events from Layer's Services, and call our callbackAsync with each event webhooksServices.listen({ expressApp: app, secret: SECRET, hooks: [hook] }, redis); // Setup your callback to handle the webhook events queue.process(hook.name, 50, function(job, done) { console.log(new Date().toLocaleString() + ': Inline Sample: Message Received from ' + (job.data.message.sender.user_id || job.data.message.sender.name)); done(); }); }
javascript
function startInlineServices() { // Provide a webhook definition var hook = { name: 'Inline Sample', events: ['message.sent'], path: '/inline_sample_message_sent', }; // Register this webhook with Layer's Services webhooksServices.register({ secret: SECRET, url: HOST + ':' + PORT, hooks: [hook] }); // Listen for events from Layer's Services, and call our callbackAsync with each event webhooksServices.listen({ expressApp: app, secret: SECRET, hooks: [hook] }, redis); // Setup your callback to handle the webhook events queue.process(hook.name, 50, function(job, done) { console.log(new Date().toLocaleString() + ': Inline Sample: Message Received from ' + (job.data.message.sender.user_id || job.data.message.sender.name)); done(); }); }
[ "function", "startInlineServices", "(", ")", "{", "// Provide a webhook definition", "var", "hook", "=", "{", "name", ":", "'Inline Sample'", ",", "events", ":", "[", "'message.sent'", "]", ",", "path", ":", "'/inline_sample_message_sent'", ",", "}", ";", "// Register this webhook with Layer's Services", "webhooksServices", ".", "register", "(", "{", "secret", ":", "SECRET", ",", "url", ":", "HOST", "+", "':'", "+", "PORT", ",", "hooks", ":", "[", "hook", "]", "}", ")", ";", "// Listen for events from Layer's Services, and call our callbackAsync with each event", "webhooksServices", ".", "listen", "(", "{", "expressApp", ":", "app", ",", "secret", ":", "SECRET", ",", "hooks", ":", "[", "hook", "]", "}", ",", "redis", ")", ";", "// Setup your callback to handle the webhook events", "queue", ".", "process", "(", "hook", ".", "name", ",", "50", ",", "function", "(", "job", ",", "done", ")", "{", "console", ".", "log", "(", "new", "Date", "(", ")", ".", "toLocaleString", "(", ")", "+", "': Inline Sample: Message Received from '", "+", "(", "job", ".", "data", ".", "message", ".", "sender", ".", "user_id", "||", "job", ".", "data", ".", "message", ".", "sender", ".", "name", ")", ")", ";", "done", "(", ")", ";", "}", ")", ";", "}" ]
Example shows quick and simple setup of a webhooks service. This example shows a single inline service that logs new messages.
[ "Example", "shows", "quick", "and", "simple", "setup", "of", "a", "webhooks", "service", ".", "This", "example", "shows", "a", "single", "inline", "service", "that", "logs", "new", "messages", "." ]
7ef63df31fb5b769ebe57b8855806178e1ce8dd8
https://github.com/layerhq/node-layer-webhooks-services/blob/7ef63df31fb5b769ebe57b8855806178e1ce8dd8/examples/server.js#L50-L77
43,830
aaaristo/grunt-html-builder
tasks/jsonld/js/request.js
_typedParse
function _typedParse(loc, type, data, callback) { switch(type.toLowerCase()) { case 'text': case 'plain': case 'text/plain': callback(null, data); break; case 'json': case 'jsonld': case 'json-ld': case 'ld+json': case 'application/json': case 'application/ld+json': try { callback(null, JSON.parse(data)); } catch(ex) { callback({ message: 'Error parsing JSON.', contentType: type, url: loc, exception: ex.toString() }); } break; case 'xml': case 'html': case 'xhtml': case 'text/html': case 'application/xhtml+xml': if(typeof jsdom === 'undefined') { callback({ message: 'jsdom module not found.', contentType: type, url: loc }); break; } if(typeof RDFa === 'undefined') { callback({ message: 'RDFa module not found.', contentType: type, url: loc }); break; } // input is RDFa try { jsdom.env({ html: data, done: function(errors, window) { if(errors && errors.length > 0) { return callback({ message: 'DOM Errors:', errors: errors, url: loc }); } try { // extract JSON-LD from RDFa RDFa.attach(window.document); jsonld.fromRDF(window.document.data, {format: 'rdfa-api'}, callback); } catch(ex) { // FIXME: expose RDFa/jsonld ex? callback({ message: 'RDFa extraction error.', contentType: type, url: loc }); } } }); } catch(ex) { // FIXME: expose jsdom(?) ex? callback({ message: 'jsdom error.', contentType: type, url: loc }); } break; default: callback({ message: 'Unknown Content-Type.', contentType: type, url: loc }); } }
javascript
function _typedParse(loc, type, data, callback) { switch(type.toLowerCase()) { case 'text': case 'plain': case 'text/plain': callback(null, data); break; case 'json': case 'jsonld': case 'json-ld': case 'ld+json': case 'application/json': case 'application/ld+json': try { callback(null, JSON.parse(data)); } catch(ex) { callback({ message: 'Error parsing JSON.', contentType: type, url: loc, exception: ex.toString() }); } break; case 'xml': case 'html': case 'xhtml': case 'text/html': case 'application/xhtml+xml': if(typeof jsdom === 'undefined') { callback({ message: 'jsdom module not found.', contentType: type, url: loc }); break; } if(typeof RDFa === 'undefined') { callback({ message: 'RDFa module not found.', contentType: type, url: loc }); break; } // input is RDFa try { jsdom.env({ html: data, done: function(errors, window) { if(errors && errors.length > 0) { return callback({ message: 'DOM Errors:', errors: errors, url: loc }); } try { // extract JSON-LD from RDFa RDFa.attach(window.document); jsonld.fromRDF(window.document.data, {format: 'rdfa-api'}, callback); } catch(ex) { // FIXME: expose RDFa/jsonld ex? callback({ message: 'RDFa extraction error.', contentType: type, url: loc }); } } }); } catch(ex) { // FIXME: expose jsdom(?) ex? callback({ message: 'jsdom error.', contentType: type, url: loc }); } break; default: callback({ message: 'Unknown Content-Type.', contentType: type, url: loc }); } }
[ "function", "_typedParse", "(", "loc", ",", "type", ",", "data", ",", "callback", ")", "{", "switch", "(", "type", ".", "toLowerCase", "(", ")", ")", "{", "case", "'text'", ":", "case", "'plain'", ":", "case", "'text/plain'", ":", "callback", "(", "null", ",", "data", ")", ";", "break", ";", "case", "'json'", ":", "case", "'jsonld'", ":", "case", "'json-ld'", ":", "case", "'ld+json'", ":", "case", "'application/json'", ":", "case", "'application/ld+json'", ":", "try", "{", "callback", "(", "null", ",", "JSON", ".", "parse", "(", "data", ")", ")", ";", "}", "catch", "(", "ex", ")", "{", "callback", "(", "{", "message", ":", "'Error parsing JSON.'", ",", "contentType", ":", "type", ",", "url", ":", "loc", ",", "exception", ":", "ex", ".", "toString", "(", ")", "}", ")", ";", "}", "break", ";", "case", "'xml'", ":", "case", "'html'", ":", "case", "'xhtml'", ":", "case", "'text/html'", ":", "case", "'application/xhtml+xml'", ":", "if", "(", "typeof", "jsdom", "===", "'undefined'", ")", "{", "callback", "(", "{", "message", ":", "'jsdom module not found.'", ",", "contentType", ":", "type", ",", "url", ":", "loc", "}", ")", ";", "break", ";", "}", "if", "(", "typeof", "RDFa", "===", "'undefined'", ")", "{", "callback", "(", "{", "message", ":", "'RDFa module not found.'", ",", "contentType", ":", "type", ",", "url", ":", "loc", "}", ")", ";", "break", ";", "}", "// input is RDFa", "try", "{", "jsdom", ".", "env", "(", "{", "html", ":", "data", ",", "done", ":", "function", "(", "errors", ",", "window", ")", "{", "if", "(", "errors", "&&", "errors", ".", "length", ">", "0", ")", "{", "return", "callback", "(", "{", "message", ":", "'DOM Errors:'", ",", "errors", ":", "errors", ",", "url", ":", "loc", "}", ")", ";", "}", "try", "{", "// extract JSON-LD from RDFa", "RDFa", ".", "attach", "(", "window", ".", "document", ")", ";", "jsonld", ".", "fromRDF", "(", "window", ".", "document", ".", "data", ",", "{", "format", ":", "'rdfa-api'", "}", ",", "callback", ")", ";", "}", "catch", "(", "ex", ")", "{", "// FIXME: expose RDFa/jsonld ex?", "callback", "(", "{", "message", ":", "'RDFa extraction error.'", ",", "contentType", ":", "type", ",", "url", ":", "loc", "}", ")", ";", "}", "}", "}", ")", ";", "}", "catch", "(", "ex", ")", "{", "// FIXME: expose jsdom(?) ex?", "callback", "(", "{", "message", ":", "'jsdom error.'", ",", "contentType", ":", "type", ",", "url", ":", "loc", "}", ")", ";", "}", "break", ";", "default", ":", "callback", "(", "{", "message", ":", "'Unknown Content-Type.'", ",", "contentType", ":", "type", ",", "url", ":", "loc", "}", ")", ";", "}", "}" ]
Parse data with given type. @param loc location string came from @param type content type of the string @param data the data string or buffer @param callback function(err, data) called with errors and result data
[ "Parse", "data", "with", "given", "type", "." ]
9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1
https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/request.js#L55-L147
43,831
opendxl/opendxl-client-javascript
lib/_provisioning/provision-config.js
requestProvisionConfig
function requestProvisionConfig (managementService, csr, verbosity, callback) { managementService.request('Requesting client certificate', PROVISION_COMMAND, {csrString: csr}, verbosity, callback) }
javascript
function requestProvisionConfig (managementService, csr, verbosity, callback) { managementService.request('Requesting client certificate', PROVISION_COMMAND, {csrString: csr}, verbosity, callback) }
[ "function", "requestProvisionConfig", "(", "managementService", ",", "csr", ",", "verbosity", ",", "callback", ")", "{", "managementService", ".", "request", "(", "'Requesting client certificate'", ",", "PROVISION_COMMAND", ",", "{", "csrString", ":", "csr", "}", ",", "verbosity", ",", "callback", ")", "}" ]
Gets the provision configuration from the management service. @param {ManagementService} managementService - The management service instance. @param {String} csr - The CSR string to send to the management service for signing. @param {Number} verbosity - Level of verbosity at which to log any error or trace messages. @param {Function} callback - Callback to invoke with the configuration retrieved from the management service. @private
[ "Gets", "the", "provision", "configuration", "from", "the", "management", "service", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_provisioning/provision-config.js#L31-L34
43,832
opendxl/opendxl-client-javascript
lib/_provisioning/provision-config.js
brokersForConfig
function brokersForConfig (brokerLines) { return brokerLines.reduce(function (acc, brokerLine) { var brokerElements = brokerLine.split('=') if (brokerElements.length !== 2) { throw new DxlError('Invalid key value pair for broker entry: ' + brokerLine) } acc[brokerElements[0]] = brokerElements[1] return acc }, {}) }
javascript
function brokersForConfig (brokerLines) { return brokerLines.reduce(function (acc, brokerLine) { var brokerElements = brokerLine.split('=') if (brokerElements.length !== 2) { throw new DxlError('Invalid key value pair for broker entry: ' + brokerLine) } acc[brokerElements[0]] = brokerElements[1] return acc }, {}) }
[ "function", "brokersForConfig", "(", "brokerLines", ")", "{", "return", "brokerLines", ".", "reduce", "(", "function", "(", "acc", ",", "brokerLine", ")", "{", "var", "brokerElements", "=", "brokerLine", ".", "split", "(", "'='", ")", "if", "(", "brokerElements", ".", "length", "!==", "2", ")", "{", "throw", "new", "DxlError", "(", "'Invalid key value pair for broker entry: '", "+", "brokerLine", ")", "}", "acc", "[", "brokerElements", "[", "0", "]", "]", "=", "brokerElements", "[", "1", "]", "return", "acc", "}", ",", "{", "}", ")", "}" ]
Converts the broker lines received from the management service into an object which can be used for rewriting the full configuration ini file. @param {Array<String>} brokerLines - List of broker lines. @example For a value of "id1=id1;host1;8883;127.0.0.1\nid2=id2;host2;8883;127.0.0.2", this function would return an object with keys named 'id1' and 'id2' with corresponding values of 'id1;host1;8883;127.0.0.1' and 'id2;host2;8883;127.0.0.2'. @returns {Object} Object representation of the broker lines. @private
[ "Converts", "the", "broker", "lines", "received", "from", "the", "management", "service", "into", "an", "object", "which", "can", "be", "used", "for", "rewriting", "the", "full", "configuration", "ini", "file", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_provisioning/provision-config.js#L47-L57
43,833
opendxl/opendxl-client-javascript
lib/_provisioning/provision-config.js
storeProvisionConfig
function storeProvisionConfig (config, configDir, filePrefix, privateKeyFileName, verbosity) { if (typeof config !== 'string') { throw new DxlError('Unexpected data type for response: ' + typeof config) } var configElements = config.split(',') if (configElements.length < 3) { throw new DxlError('Did not receive expected number of response ' + 'elements. Expected: 3, Received: ' + configElements.length + '. Value: ' + config) } var brokerLines = configElements[2].split( /[\r\n]+/).filter(function (brokerLine) { return brokerLine.length > 0 } ) var brokers = brokersForConfig(brokerLines) var certFileName = filePrefix + '.crt' var configString = ini.encode({ Certs: { BrokerCertChain: DEFAULT_BROKER_CERT_CHAIN_FILE_NAME, CertFile: path.basename(certFileName), PrivateKey: path.basename(privateKeyFileName) }, Brokers: brokers }).replace(/\\;/g, ';') var configFileName = path.join(configDir, provisionUtil.DEFAULT_CONFIG_FILE_NAME) if (verbosity) { console.log('Saving DXL config file to ' + configFileName) } provisionUtil.saveToFile(configFileName, configString) var caBundleFileName = path.join(configDir, DEFAULT_BROKER_CERT_CHAIN_FILE_NAME) if (verbosity) { console.log('Saving ca bundle file to ' + caBundleFileName) } provisionUtil.saveToFile(caBundleFileName, configElements[0]) var fullCertFileName = path.join(configDir, certFileName) if (verbosity) { console.log('Saving client certificate file to ' + fullCertFileName) } provisionUtil.saveToFile(fullCertFileName, configElements[1]) }
javascript
function storeProvisionConfig (config, configDir, filePrefix, privateKeyFileName, verbosity) { if (typeof config !== 'string') { throw new DxlError('Unexpected data type for response: ' + typeof config) } var configElements = config.split(',') if (configElements.length < 3) { throw new DxlError('Did not receive expected number of response ' + 'elements. Expected: 3, Received: ' + configElements.length + '. Value: ' + config) } var brokerLines = configElements[2].split( /[\r\n]+/).filter(function (brokerLine) { return brokerLine.length > 0 } ) var brokers = brokersForConfig(brokerLines) var certFileName = filePrefix + '.crt' var configString = ini.encode({ Certs: { BrokerCertChain: DEFAULT_BROKER_CERT_CHAIN_FILE_NAME, CertFile: path.basename(certFileName), PrivateKey: path.basename(privateKeyFileName) }, Brokers: brokers }).replace(/\\;/g, ';') var configFileName = path.join(configDir, provisionUtil.DEFAULT_CONFIG_FILE_NAME) if (verbosity) { console.log('Saving DXL config file to ' + configFileName) } provisionUtil.saveToFile(configFileName, configString) var caBundleFileName = path.join(configDir, DEFAULT_BROKER_CERT_CHAIN_FILE_NAME) if (verbosity) { console.log('Saving ca bundle file to ' + caBundleFileName) } provisionUtil.saveToFile(caBundleFileName, configElements[0]) var fullCertFileName = path.join(configDir, certFileName) if (verbosity) { console.log('Saving client certificate file to ' + fullCertFileName) } provisionUtil.saveToFile(fullCertFileName, configElements[1]) }
[ "function", "storeProvisionConfig", "(", "config", ",", "configDir", ",", "filePrefix", ",", "privateKeyFileName", ",", "verbosity", ")", "{", "if", "(", "typeof", "config", "!==", "'string'", ")", "{", "throw", "new", "DxlError", "(", "'Unexpected data type for response: '", "+", "typeof", "config", ")", "}", "var", "configElements", "=", "config", ".", "split", "(", "','", ")", "if", "(", "configElements", ".", "length", "<", "3", ")", "{", "throw", "new", "DxlError", "(", "'Did not receive expected number of response '", "+", "'elements. Expected: 3, Received: '", "+", "configElements", ".", "length", "+", "'. Value: '", "+", "config", ")", "}", "var", "brokerLines", "=", "configElements", "[", "2", "]", ".", "split", "(", "/", "[\\r\\n]+", "/", ")", ".", "filter", "(", "function", "(", "brokerLine", ")", "{", "return", "brokerLine", ".", "length", ">", "0", "}", ")", "var", "brokers", "=", "brokersForConfig", "(", "brokerLines", ")", "var", "certFileName", "=", "filePrefix", "+", "'.crt'", "var", "configString", "=", "ini", ".", "encode", "(", "{", "Certs", ":", "{", "BrokerCertChain", ":", "DEFAULT_BROKER_CERT_CHAIN_FILE_NAME", ",", "CertFile", ":", "path", ".", "basename", "(", "certFileName", ")", ",", "PrivateKey", ":", "path", ".", "basename", "(", "privateKeyFileName", ")", "}", ",", "Brokers", ":", "brokers", "}", ")", ".", "replace", "(", "/", "\\\\;", "/", "g", ",", "';'", ")", "var", "configFileName", "=", "path", ".", "join", "(", "configDir", ",", "provisionUtil", ".", "DEFAULT_CONFIG_FILE_NAME", ")", "if", "(", "verbosity", ")", "{", "console", ".", "log", "(", "'Saving DXL config file to '", "+", "configFileName", ")", "}", "provisionUtil", ".", "saveToFile", "(", "configFileName", ",", "configString", ")", "var", "caBundleFileName", "=", "path", ".", "join", "(", "configDir", ",", "DEFAULT_BROKER_CERT_CHAIN_FILE_NAME", ")", "if", "(", "verbosity", ")", "{", "console", ".", "log", "(", "'Saving ca bundle file to '", "+", "caBundleFileName", ")", "}", "provisionUtil", ".", "saveToFile", "(", "caBundleFileName", ",", "configElements", "[", "0", "]", ")", "var", "fullCertFileName", "=", "path", ".", "join", "(", "configDir", ",", "certFileName", ")", "if", "(", "verbosity", ")", "{", "console", ".", "log", "(", "'Saving client certificate file to '", "+", "fullCertFileName", ")", "}", "provisionUtil", ".", "saveToFile", "(", "fullCertFileName", ",", "configElements", "[", "1", "]", ")", "}" ]
Store the configuration data received from the management service to the local file system. @param {String} config - Configuration data received from the management service. @param {String} configDir - Directory in which to store the configuration data. @param {String} filePrefix - Prefix of the certificate file to store. @param {String} privateKeyFileName - Name of the private key file to include in the stored configuration file. @param {Number} verbosity - Level of verbosity at which to log any error or trace messages. @private
[ "Store", "the", "configuration", "data", "received", "from", "the", "management", "service", "to", "the", "local", "file", "system", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_provisioning/provision-config.js#L73-L123
43,834
opendxl/opendxl-client-javascript
lib/_provisioning/management-service.js
ManagementService
function ManagementService (hostInfo) { if (!hostInfo.hostname) { throw new TypeError('Hostname is required for management service requests') } if (!hostInfo.user) { throw new TypeError('User name is required for management service requests') } if (!hostInfo.password) { throw new TypeError('Password is required for management service requests') } this.hostname = hostInfo.hostname this.port = hostInfo.port || ManagementService.DEFAULT_PORT this.auth = hostInfo.user + ':' + hostInfo.password this.trustStoreFile = hostInfo.truststore }
javascript
function ManagementService (hostInfo) { if (!hostInfo.hostname) { throw new TypeError('Hostname is required for management service requests') } if (!hostInfo.user) { throw new TypeError('User name is required for management service requests') } if (!hostInfo.password) { throw new TypeError('Password is required for management service requests') } this.hostname = hostInfo.hostname this.port = hostInfo.port || ManagementService.DEFAULT_PORT this.auth = hostInfo.user + ':' + hostInfo.password this.trustStoreFile = hostInfo.truststore }
[ "function", "ManagementService", "(", "hostInfo", ")", "{", "if", "(", "!", "hostInfo", ".", "hostname", ")", "{", "throw", "new", "TypeError", "(", "'Hostname is required for management service requests'", ")", "}", "if", "(", "!", "hostInfo", ".", "user", ")", "{", "throw", "new", "TypeError", "(", "'User name is required for management service requests'", ")", "}", "if", "(", "!", "hostInfo", ".", "password", ")", "{", "throw", "new", "TypeError", "(", "'Password is required for management service requests'", ")", "}", "this", ".", "hostname", "=", "hostInfo", ".", "hostname", "this", ".", "port", "=", "hostInfo", ".", "port", "||", "ManagementService", ".", "DEFAULT_PORT", "this", ".", "auth", "=", "hostInfo", ".", "user", "+", "':'", "+", "hostInfo", ".", "password", "this", ".", "trustStoreFile", "=", "hostInfo", ".", "truststore", "}" ]
Host info for the management service @typedef {Object} ManagementServiceHostInfo @property {String} hostname - Name of the host where the management service resides. @property {String} user - Username to run remote commands as. @property {String} password - Password for the management service user. @property {String} [port=8443] - Port at which the management service resides. @property {String} [truststore] - Location of a file of CA certificates to use when verifying the management service's certificate. If no value is specified, no validation of the management service's certificate is performed. @private @classdesc Handles REST invocation of a management service. @param {ManagementServiceHostInfo} hostInfo - Options for the management service host. @constructor @private
[ "Host", "info", "for", "the", "management", "service" ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_provisioning/management-service.js#L34-L48
43,835
opendxl/opendxl-client-javascript
lib/_provisioning/management-service.js
httpGet
function httpGet (description, currentRedirects, requestOptions, verbosity, responseCallback) { var requestUrl = toUrlString(requestOptions) var responseBody = '' if (verbosity > 1) { console.log('HTTP request to: ' + requestUrl) } var request = https.get(requestOptions, function (response) { if (verbosity > 1) { console.log('HTTP response status code: ' + response.statusCode) } if (response.statusCode === 302) { if (currentRedirects === HTTP_MAX_REDIRECTS) { responseCallback(provisionUtil.createFormattedDxlError( 'Reached maximum redirects for request to ' + requestUrl, description) ) } else { var redirectLocation = response.headers.location if (!redirectLocation) { responseCallback(provisionUtil.createFormattedDxlError( 'Redirect with no location specified for ' + requestUrl, description)) return } if (verbosity > 1) { console.log('HTTP response redirect to: ' + redirectLocation) } var parsedRedirectLocation = url.parse(redirectLocation) if ((parsedRedirectLocation.hostname && (parsedRedirectLocation.hostname !== requestOptions.hostname)) || (parsedRedirectLocation.port && (parsedRedirectLocation.port !== requestOptions.port))) { responseCallback(provisionUtil.createFormattedDxlError( 'Redirect to different host or port not supported. ' + 'Original URL: ' + requestUrl + '. Redirect URL: ' + redirectLocation + '.', description)) return } if (response.headers['set-cookie']) { if (!requestOptions.headers) { requestOptions.headers = {} } requestOptions.headers.cookie = response.headers['set-cookie'] } requestOptions.path = response.headers.location httpGet(description, currentRedirects + 1, requestOptions, verbosity, responseCallback) response.resume() return } } response.on('data', function (chunk) { responseBody += chunk }) response.on('end', function () { if (response.statusCode >= 200 && response.statusCode <= 299) { responseCallback(null, responseBody) } else { responseCallback(provisionUtil.createFormattedDxlError( 'Request to ' + requestUrl + ' failed with HTTP error code: ' + response.statusCode + '. Reason: ' + response.statusMessage + '.', description)) } }) }) request.on('error', function (error) { responseCallback(provisionUtil.createFormattedDxlError( 'Error processing request to ' + requestUrl + ': ' + error, description)) }) }
javascript
function httpGet (description, currentRedirects, requestOptions, verbosity, responseCallback) { var requestUrl = toUrlString(requestOptions) var responseBody = '' if (verbosity > 1) { console.log('HTTP request to: ' + requestUrl) } var request = https.get(requestOptions, function (response) { if (verbosity > 1) { console.log('HTTP response status code: ' + response.statusCode) } if (response.statusCode === 302) { if (currentRedirects === HTTP_MAX_REDIRECTS) { responseCallback(provisionUtil.createFormattedDxlError( 'Reached maximum redirects for request to ' + requestUrl, description) ) } else { var redirectLocation = response.headers.location if (!redirectLocation) { responseCallback(provisionUtil.createFormattedDxlError( 'Redirect with no location specified for ' + requestUrl, description)) return } if (verbosity > 1) { console.log('HTTP response redirect to: ' + redirectLocation) } var parsedRedirectLocation = url.parse(redirectLocation) if ((parsedRedirectLocation.hostname && (parsedRedirectLocation.hostname !== requestOptions.hostname)) || (parsedRedirectLocation.port && (parsedRedirectLocation.port !== requestOptions.port))) { responseCallback(provisionUtil.createFormattedDxlError( 'Redirect to different host or port not supported. ' + 'Original URL: ' + requestUrl + '. Redirect URL: ' + redirectLocation + '.', description)) return } if (response.headers['set-cookie']) { if (!requestOptions.headers) { requestOptions.headers = {} } requestOptions.headers.cookie = response.headers['set-cookie'] } requestOptions.path = response.headers.location httpGet(description, currentRedirects + 1, requestOptions, verbosity, responseCallback) response.resume() return } } response.on('data', function (chunk) { responseBody += chunk }) response.on('end', function () { if (response.statusCode >= 200 && response.statusCode <= 299) { responseCallback(null, responseBody) } else { responseCallback(provisionUtil.createFormattedDxlError( 'Request to ' + requestUrl + ' failed with HTTP error code: ' + response.statusCode + '. Reason: ' + response.statusMessage + '.', description)) } }) }) request.on('error', function (error) { responseCallback(provisionUtil.createFormattedDxlError( 'Error processing request to ' + requestUrl + ': ' + error, description)) }) }
[ "function", "httpGet", "(", "description", ",", "currentRedirects", ",", "requestOptions", ",", "verbosity", ",", "responseCallback", ")", "{", "var", "requestUrl", "=", "toUrlString", "(", "requestOptions", ")", "var", "responseBody", "=", "''", "if", "(", "verbosity", ">", "1", ")", "{", "console", ".", "log", "(", "'HTTP request to: '", "+", "requestUrl", ")", "}", "var", "request", "=", "https", ".", "get", "(", "requestOptions", ",", "function", "(", "response", ")", "{", "if", "(", "verbosity", ">", "1", ")", "{", "console", ".", "log", "(", "'HTTP response status code: '", "+", "response", ".", "statusCode", ")", "}", "if", "(", "response", ".", "statusCode", "===", "302", ")", "{", "if", "(", "currentRedirects", "===", "HTTP_MAX_REDIRECTS", ")", "{", "responseCallback", "(", "provisionUtil", ".", "createFormattedDxlError", "(", "'Reached maximum redirects for request to '", "+", "requestUrl", ",", "description", ")", ")", "}", "else", "{", "var", "redirectLocation", "=", "response", ".", "headers", ".", "location", "if", "(", "!", "redirectLocation", ")", "{", "responseCallback", "(", "provisionUtil", ".", "createFormattedDxlError", "(", "'Redirect with no location specified for '", "+", "requestUrl", ",", "description", ")", ")", "return", "}", "if", "(", "verbosity", ">", "1", ")", "{", "console", ".", "log", "(", "'HTTP response redirect to: '", "+", "redirectLocation", ")", "}", "var", "parsedRedirectLocation", "=", "url", ".", "parse", "(", "redirectLocation", ")", "if", "(", "(", "parsedRedirectLocation", ".", "hostname", "&&", "(", "parsedRedirectLocation", ".", "hostname", "!==", "requestOptions", ".", "hostname", ")", ")", "||", "(", "parsedRedirectLocation", ".", "port", "&&", "(", "parsedRedirectLocation", ".", "port", "!==", "requestOptions", ".", "port", ")", ")", ")", "{", "responseCallback", "(", "provisionUtil", ".", "createFormattedDxlError", "(", "'Redirect to different host or port not supported. '", "+", "'Original URL: '", "+", "requestUrl", "+", "'. Redirect URL: '", "+", "redirectLocation", "+", "'.'", ",", "description", ")", ")", "return", "}", "if", "(", "response", ".", "headers", "[", "'set-cookie'", "]", ")", "{", "if", "(", "!", "requestOptions", ".", "headers", ")", "{", "requestOptions", ".", "headers", "=", "{", "}", "}", "requestOptions", ".", "headers", ".", "cookie", "=", "response", ".", "headers", "[", "'set-cookie'", "]", "}", "requestOptions", ".", "path", "=", "response", ".", "headers", ".", "location", "httpGet", "(", "description", ",", "currentRedirects", "+", "1", ",", "requestOptions", ",", "verbosity", ",", "responseCallback", ")", "response", ".", "resume", "(", ")", "return", "}", "}", "response", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "responseBody", "+=", "chunk", "}", ")", "response", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "if", "(", "response", ".", "statusCode", ">=", "200", "&&", "response", ".", "statusCode", "<=", "299", ")", "{", "responseCallback", "(", "null", ",", "responseBody", ")", "}", "else", "{", "responseCallback", "(", "provisionUtil", ".", "createFormattedDxlError", "(", "'Request to '", "+", "requestUrl", "+", "' failed with HTTP error code: '", "+", "response", ".", "statusCode", "+", "'. Reason: '", "+", "response", ".", "statusMessage", "+", "'.'", ",", "description", ")", ")", "}", "}", ")", "}", ")", "request", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "responseCallback", "(", "provisionUtil", ".", "createFormattedDxlError", "(", "'Error processing request to '", "+", "requestUrl", "+", "': '", "+", "error", ",", "description", ")", ")", "}", ")", "}" ]
Performs an HTTP get to the management service. The response received from the service is supplied as an argument to the responseCallback function. @param {String} description - Textual description of the HTTP request (used in log and error messages). @param {Number} currentRedirects - Number of HTTP redirects which have been followed thus far for this request. @param {Object} requestOptions - Request options to pass along to the underlying HTTP request library. @param {Number} verbosity - Level of verbosity at which to log any error or trace messages. @param {Function} responseCallback - Function to invoke with the response body received from the management service. If an error occurs during request processing, the first parameter delivered to the callback includes the associated `Error` instance. If the request is successful, the response body is provided in the second parameter (as an object parsed from the response JSON). @private
[ "Performs", "an", "HTTP", "get", "to", "the", "management", "service", ".", "The", "response", "received", "from", "the", "service", "is", "supplied", "as", "an", "argument", "to", "the", "responseCallback", "function", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_provisioning/management-service.js#L105-L180
43,836
assemble/assemble-core
index.js
Assemble
function Assemble(options) { if (!(this instanceof Assemble)) { return new Assemble(options); } Templates.call(this, options); this.is('assemble'); this.initCore(); }
javascript
function Assemble(options) { if (!(this instanceof Assemble)) { return new Assemble(options); } Templates.call(this, options); this.is('assemble'); this.initCore(); }
[ "function", "Assemble", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Assemble", ")", ")", "{", "return", "new", "Assemble", "(", "options", ")", ";", "}", "Templates", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "is", "(", "'assemble'", ")", ";", "this", ".", "initCore", "(", ")", ";", "}" ]
Create an `assemble` application. This is the main function exported by the assemble module. ```js var assemble = require('assemble'); var app = assemble(); ``` @param {Object} `options` Optionally pass default options to use. @api public
[ "Create", "an", "assemble", "application", ".", "This", "is", "the", "main", "function", "exported", "by", "the", "assemble", "module", "." ]
ed8c3b5a7885ebcb911eb69a3cc8e98f4e27ab01
https://github.com/assemble/assemble-core/blob/ed8c3b5a7885ebcb911eb69a3cc8e98f4e27ab01/index.js#L22-L29
43,837
cast-org/figuration
js/tooltip.js
function(e) { this._tabReset(); if (e.which == 9) { this.flags.keyTab = true; if (e.shiftKey) { this.flags.keyShift = true; } } }
javascript
function(e) { this._tabReset(); if (e.which == 9) { this.flags.keyTab = true; if (e.shiftKey) { this.flags.keyShift = true; } } }
[ "function", "(", "e", ")", "{", "this", ".", "_tabReset", "(", ")", ";", "if", "(", "e", ".", "which", "==", "9", ")", "{", "this", ".", "flags", ".", "keyTab", "=", "true", ";", "if", "(", "e", ".", "shiftKey", ")", "{", "this", ".", "flags", ".", "keyShift", "=", "true", ";", "}", "}", "}" ]
Set flags for `tab` key interactions
[ "Set", "flags", "for", "tab", "key", "interactions" ]
c82f491ebccb477f7e1c945bfff61c2340afe1ac
https://github.com/cast-org/figuration/blob/c82f491ebccb477f7e1c945bfff61c2340afe1ac/js/tooltip.js#L930-L936
43,838
cast-org/figuration
js/tooltip.js
function(current, $scope) { var $selfRef = this; var selectables = $selfRef._tabItems($scope); var nextIndex = 0; if ($(current).length === 1){ var currentIndex = selectables.index(current); if (currentIndex + 1 < selectables.length) { nextIndex = currentIndex + 1; } } return selectables.eq(nextIndex); }
javascript
function(current, $scope) { var $selfRef = this; var selectables = $selfRef._tabItems($scope); var nextIndex = 0; if ($(current).length === 1){ var currentIndex = selectables.index(current); if (currentIndex + 1 < selectables.length) { nextIndex = currentIndex + 1; } } return selectables.eq(nextIndex); }
[ "function", "(", "current", ",", "$scope", ")", "{", "var", "$selfRef", "=", "this", ";", "var", "selectables", "=", "$selfRef", ".", "_tabItems", "(", "$scope", ")", ";", "var", "nextIndex", "=", "0", ";", "if", "(", "$", "(", "current", ")", ".", "length", "===", "1", ")", "{", "var", "currentIndex", "=", "selectables", ".", "index", "(", "current", ")", ";", "if", "(", "currentIndex", "+", "1", "<", "selectables", ".", "length", ")", "{", "nextIndex", "=", "currentIndex", "+", "1", ";", "}", "}", "return", "selectables", ".", "eq", "(", "nextIndex", ")", ";", "}" ]
Find the next tabbabale item after given element
[ "Find", "the", "next", "tabbabale", "item", "after", "given", "element" ]
c82f491ebccb477f7e1c945bfff61c2340afe1ac
https://github.com/cast-org/figuration/blob/c82f491ebccb477f7e1c945bfff61c2340afe1ac/js/tooltip.js#L976-L988
43,839
silas/swagger-framework
lib/operation.js
Operation
function Operation(spec, options, fn) { if (typeof options === 'function') { fn = [].slice.call(arguments).slice(1); options = {}; } else if (Array.isArray(options)) { fn = options; options = {}; } else if (!Array.isArray(fn)) { fn = [].slice.call(arguments).slice(2); } if (!(this instanceof Operation)) { return new Operation(spec, options, fn); } if (typeof spec !== 'object') { throw new Error('operation spec must be an object'); } debug('create operation', spec); this.spec = spec; this.options = options || {}; this.fn = fn; this.middleware = {}; }
javascript
function Operation(spec, options, fn) { if (typeof options === 'function') { fn = [].slice.call(arguments).slice(1); options = {}; } else if (Array.isArray(options)) { fn = options; options = {}; } else if (!Array.isArray(fn)) { fn = [].slice.call(arguments).slice(2); } if (!(this instanceof Operation)) { return new Operation(spec, options, fn); } if (typeof spec !== 'object') { throw new Error('operation spec must be an object'); } debug('create operation', spec); this.spec = spec; this.options = options || {}; this.fn = fn; this.middleware = {}; }
[ "function", "Operation", "(", "spec", ",", "options", ",", "fn", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "fn", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ")", ".", "slice", "(", "1", ")", ";", "options", "=", "{", "}", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "options", ")", ")", "{", "fn", "=", "options", ";", "options", "=", "{", "}", ";", "}", "else", "if", "(", "!", "Array", ".", "isArray", "(", "fn", ")", ")", "{", "fn", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ")", ".", "slice", "(", "2", ")", ";", "}", "if", "(", "!", "(", "this", "instanceof", "Operation", ")", ")", "{", "return", "new", "Operation", "(", "spec", ",", "options", ",", "fn", ")", ";", "}", "if", "(", "typeof", "spec", "!==", "'object'", ")", "{", "throw", "new", "Error", "(", "'operation spec must be an object'", ")", ";", "}", "debug", "(", "'create operation'", ",", "spec", ")", ";", "this", ".", "spec", "=", "spec", ";", "this", ".", "options", "=", "options", "||", "{", "}", ";", "this", ".", "fn", "=", "fn", ";", "this", ".", "middleware", "=", "{", "}", ";", "}" ]
Initialize a new `Operation`. @param {Object} spec @param {Object} options @param {Function} fn @api public
[ "Initialize", "a", "new", "Operation", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/operation.js#L27-L52
43,840
victorporof/MAX7219.js
MAX7219.js
function(n, symbol, dp, callback) { if (n < 0 || n > 7) { throw "Invalid digit number"; } if (!(symbol in MAX7219._Font)) { throw "Invalid symbol string"; } var byte = MAX7219._Font[symbol] | (dp ? (1 << 7) : 0); this._shiftOut(MAX7219._Registers["Digit" + n], byte, callback); }
javascript
function(n, symbol, dp, callback) { if (n < 0 || n > 7) { throw "Invalid digit number"; } if (!(symbol in MAX7219._Font)) { throw "Invalid symbol string"; } var byte = MAX7219._Font[symbol] | (dp ? (1 << 7) : 0); this._shiftOut(MAX7219._Registers["Digit" + n], byte, callback); }
[ "function", "(", "n", ",", "symbol", ",", "dp", ",", "callback", ")", "{", "if", "(", "n", "<", "0", "||", "n", ">", "7", ")", "{", "throw", "\"Invalid digit number\"", ";", "}", "if", "(", "!", "(", "symbol", "in", "MAX7219", ".", "_Font", ")", ")", "{", "throw", "\"Invalid symbol string\"", ";", "}", "var", "byte", "=", "MAX7219", ".", "_Font", "[", "symbol", "]", "|", "(", "dp", "?", "(", "1", "<<", "7", ")", ":", "0", ")", ";", "this", ".", "_shiftOut", "(", "MAX7219", ".", "_Registers", "[", "\"Digit\"", "+", "n", "]", ",", "byte", ",", "callback", ")", ";", "}" ]
Sets the symbol displayed in a digit. For this to work properly, the digit should be in decode mode. @param number n The digit number, from 0 up to and including 7. @param string symbol The symbol do display: "0".."9", "E", "H", "L", "P", "-" or " ". @param boolean dp Specifies if the decimal point should be on or off. @param function callback [optional] Invoked once the write to the SPI device finishes.
[ "Sets", "the", "symbol", "displayed", "in", "a", "digit", ".", "For", "this", "to", "work", "properly", "the", "digit", "should", "be", "in", "decode", "mode", "." ]
dec565caa8d33f1fdd1a36b309a74cd06f1e6837
https://github.com/victorporof/MAX7219.js/blob/dec565caa8d33f1fdd1a36b309a74cd06f1e6837/MAX7219.js#L271-L280
43,841
victorporof/MAX7219.js
MAX7219.js
function(callback) { if (!this._decodeModes) { this.setDecodeNone(); } for (var i = 0; i < this._decodeModes.length; i++) { var mode = this._decodeModes[i]; if (mode == 0) { this.setDigitSegmentsByte(i, 0x00, callback); } else { this.setDigitSymbol(i, " ", false, callback); } } }
javascript
function(callback) { if (!this._decodeModes) { this.setDecodeNone(); } for (var i = 0; i < this._decodeModes.length; i++) { var mode = this._decodeModes[i]; if (mode == 0) { this.setDigitSegmentsByte(i, 0x00, callback); } else { this.setDigitSymbol(i, " ", false, callback); } } }
[ "function", "(", "callback", ")", "{", "if", "(", "!", "this", ".", "_decodeModes", ")", "{", "this", ".", "setDecodeNone", "(", ")", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "_decodeModes", ".", "length", ";", "i", "++", ")", "{", "var", "mode", "=", "this", ".", "_decodeModes", "[", "i", "]", ";", "if", "(", "mode", "==", "0", ")", "{", "this", ".", "setDigitSegmentsByte", "(", "i", ",", "0x00", ",", "callback", ")", ";", "}", "else", "{", "this", ".", "setDigitSymbol", "(", "i", ",", "\" \"", ",", "false", ",", "callback", ")", ";", "}", "}", "}" ]
Sets all segments for all digits off. Shortcut for manually calling setDigitSegments or setDigitSymbol with the appropriate params. If a decode mode wasn't specifically set beforehand, no-decode mode is assumed. @param function callback [optional] Invoked once the write to the SPI device finishes.
[ "Sets", "all", "segments", "for", "all", "digits", "off", "." ]
dec565caa8d33f1fdd1a36b309a74cd06f1e6837
https://github.com/victorporof/MAX7219.js/blob/dec565caa8d33f1fdd1a36b309a74cd06f1e6837/MAX7219.js#L292-L305
43,842
victorporof/MAX7219.js
MAX7219.js
function(brightness, callback) { if (brightness < 0 || brightness > 15) { throw "Invalid brightness number"; } this._shiftOut(MAX7219._Registers.Intensity, brightness, callback); }
javascript
function(brightness, callback) { if (brightness < 0 || brightness > 15) { throw "Invalid brightness number"; } this._shiftOut(MAX7219._Registers.Intensity, brightness, callback); }
[ "function", "(", "brightness", ",", "callback", ")", "{", "if", "(", "brightness", "<", "0", "||", "brightness", ">", "15", ")", "{", "throw", "\"Invalid brightness number\"", ";", "}", "this", ".", "_shiftOut", "(", "MAX7219", ".", "_Registers", ".", "Intensity", ",", "brightness", ",", "callback", ")", ";", "}" ]
Sets digital control of display brightness. @param number brightness The brightness from 0 (dimmest) up to and including 15 (brightest). @param function callback [optional] Invoked once the write to the SPI device finishes.
[ "Sets", "digital", "control", "of", "display", "brightness", "." ]
dec565caa8d33f1fdd1a36b309a74cd06f1e6837
https://github.com/victorporof/MAX7219.js/blob/dec565caa8d33f1fdd1a36b309a74cd06f1e6837/MAX7219.js#L316-L321
43,843
victorporof/MAX7219.js
MAX7219.js
function(limit, callback) { if (limit < 1 || limit > 8) { throw "Invalid scan limit number"; } this._shiftOut(MAX7219._Registers.ScanLimit, limit - 1, callback); }
javascript
function(limit, callback) { if (limit < 1 || limit > 8) { throw "Invalid scan limit number"; } this._shiftOut(MAX7219._Registers.ScanLimit, limit - 1, callback); }
[ "function", "(", "limit", ",", "callback", ")", "{", "if", "(", "limit", "<", "1", "||", "limit", ">", "8", ")", "{", "throw", "\"Invalid scan limit number\"", ";", "}", "this", ".", "_shiftOut", "(", "MAX7219", ".", "_Registers", ".", "ScanLimit", ",", "limit", "-", "1", ",", "callback", ")", ";", "}" ]
Sets how many digits are displayed, from 1 digit to 8 digits. @param number limit The number of digits displayed, counting from first to last. E.g., to display only the first digit, limit would be 1. E.g., to display only digits 0, 1 and 2, limit would be 3. @param function callback [optional] Invoked once the write to the SPI device finishes.
[ "Sets", "how", "many", "digits", "are", "displayed", "from", "1", "digit", "to", "8", "digits", "." ]
dec565caa8d33f1fdd1a36b309a74cd06f1e6837
https://github.com/victorporof/MAX7219.js/blob/dec565caa8d33f1fdd1a36b309a74cd06f1e6837/MAX7219.js#L334-L339
43,844
victorporof/MAX7219.js
MAX7219.js
function(firstByte, secondByte, callback) { if (!this._spi) { throw "SPI device not initialized"; } for (var i = 0; i < this._buffer.length; i += 2) { this._buffer[i] = MAX7219._Registers.NoOp; this._buffer[i + 1] = 0x00; } var offset = this._activeController * 2; this._buffer[offset] = firstByte; this._buffer[offset + 1] = secondByte; this._spi.write(this._buffer, callback); }
javascript
function(firstByte, secondByte, callback) { if (!this._spi) { throw "SPI device not initialized"; } for (var i = 0; i < this._buffer.length; i += 2) { this._buffer[i] = MAX7219._Registers.NoOp; this._buffer[i + 1] = 0x00; } var offset = this._activeController * 2; this._buffer[offset] = firstByte; this._buffer[offset + 1] = secondByte; this._spi.write(this._buffer, callback); }
[ "function", "(", "firstByte", ",", "secondByte", ",", "callback", ")", "{", "if", "(", "!", "this", ".", "_spi", ")", "{", "throw", "\"SPI device not initialized\"", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "_buffer", ".", "length", ";", "i", "+=", "2", ")", "{", "this", ".", "_buffer", "[", "i", "]", "=", "MAX7219", ".", "_Registers", ".", "NoOp", ";", "this", ".", "_buffer", "[", "i", "+", "1", "]", "=", "0x00", ";", "}", "var", "offset", "=", "this", ".", "_activeController", "*", "2", ";", "this", ".", "_buffer", "[", "offset", "]", "=", "firstByte", ";", "this", ".", "_buffer", "[", "offset", "+", "1", "]", "=", "secondByte", ";", "this", ".", "_spi", ".", "write", "(", "this", ".", "_buffer", ",", "callback", ")", ";", "}" ]
Shifts two bytes to the SPI device. @param number firstByte The first byte, as a number. @param number secondByte The second byte, as a number. @param function callback [optional] Invoked once the write to the SPI device finishes.
[ "Shifts", "two", "bytes", "to", "the", "SPI", "device", "." ]
dec565caa8d33f1fdd1a36b309a74cd06f1e6837
https://github.com/victorporof/MAX7219.js/blob/dec565caa8d33f1fdd1a36b309a74cd06f1e6837/MAX7219.js#L371-L386
43,845
opendxl/opendxl-client-javascript
lib/service-manager.js
registerService
function registerService (client, service) { clearTtlTimeout(service) if (client.connected) { var request = new Request(DXL_SERVICE_REGISTER_REQUEST_TOPIC) request.payload = JSON.stringify({ serviceType: service.info.serviceType, metaData: service.info.metadata, requestChannels: service.info.topics, ttlMins: service.info.ttl, serviceGuid: service.info.serviceId }) request.destinationTenantGuids = service.info.destinationTenantGuids client.asyncRequest(request, function (error) { if (service.onFirstRegistrationCallback) { service.onFirstRegistrationCallback(error) service.onFirstRegistrationCallback = null } }) service.ttlTimeout = setTimeout(registerService, service.info.ttl * 60 * 1000, client, service) } }
javascript
function registerService (client, service) { clearTtlTimeout(service) if (client.connected) { var request = new Request(DXL_SERVICE_REGISTER_REQUEST_TOPIC) request.payload = JSON.stringify({ serviceType: service.info.serviceType, metaData: service.info.metadata, requestChannels: service.info.topics, ttlMins: service.info.ttl, serviceGuid: service.info.serviceId }) request.destinationTenantGuids = service.info.destinationTenantGuids client.asyncRequest(request, function (error) { if (service.onFirstRegistrationCallback) { service.onFirstRegistrationCallback(error) service.onFirstRegistrationCallback = null } }) service.ttlTimeout = setTimeout(registerService, service.info.ttl * 60 * 1000, client, service) } }
[ "function", "registerService", "(", "client", ",", "service", ")", "{", "clearTtlTimeout", "(", "service", ")", "if", "(", "client", ".", "connected", ")", "{", "var", "request", "=", "new", "Request", "(", "DXL_SERVICE_REGISTER_REQUEST_TOPIC", ")", "request", ".", "payload", "=", "JSON", ".", "stringify", "(", "{", "serviceType", ":", "service", ".", "info", ".", "serviceType", ",", "metaData", ":", "service", ".", "info", ".", "metadata", ",", "requestChannels", ":", "service", ".", "info", ".", "topics", ",", "ttlMins", ":", "service", ".", "info", ".", "ttl", ",", "serviceGuid", ":", "service", ".", "info", ".", "serviceId", "}", ")", "request", ".", "destinationTenantGuids", "=", "service", ".", "info", ".", "destinationTenantGuids", "client", ".", "asyncRequest", "(", "request", ",", "function", "(", "error", ")", "{", "if", "(", "service", ".", "onFirstRegistrationCallback", ")", "{", "service", ".", "onFirstRegistrationCallback", "(", "error", ")", "service", ".", "onFirstRegistrationCallback", "=", "null", "}", "}", ")", "service", ".", "ttlTimeout", "=", "setTimeout", "(", "registerService", ",", "service", ".", "info", ".", "ttl", "*", "60", "*", "1000", ",", "client", ",", "service", ")", "}", "}" ]
Registers the service with the DXL fabric. @private @param {Client} client - Client to be used for registering the service. @param {Object} service - Metadata for the service. @param {ServiceRegistrationInfo} service.info - Info supplied for the service registration via a call to the {@link ServiceManager#registerServiceAsync} function. @param {Function} [service.onFirstRegistrationCallback=null] - An optional callback that will be invoked when the initial registration attempt is complete. If an error occurs during the registration attempt, the first parameter supplied to the callback contains an {@link Error} with failure details. @param {Object} service.ttlTimeout - Id for a callback to be invoked to re-register the service when its {@link ServiceRegistrationInfo#ttl} expires.
[ "Registers", "the", "service", "with", "the", "DXL", "fabric", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/service-manager.js#L101-L126
43,846
opendxl/opendxl-client-javascript
lib/service-manager.js
unregisterService
function unregisterService (client, service, callback) { if (client.connected) { var request = new Request(DXL_SERVICE_UNREGISTER_REQUEST_TOPIC) request.payload = JSON.stringify({ serviceGuid: service.info.serviceId}) var unregisterCallback = null if (callback) { unregisterCallback = function (error) { callback(error) } } client.asyncRequest(request, unregisterCallback) } Object.keys(service.callbacksByTopic).forEach(function (topic) { service.callbacksByTopic[topic].forEach(function (callback) { client.removeRequestCallback(topic, callback) }) }) clearTtlTimeout(service) }
javascript
function unregisterService (client, service, callback) { if (client.connected) { var request = new Request(DXL_SERVICE_UNREGISTER_REQUEST_TOPIC) request.payload = JSON.stringify({ serviceGuid: service.info.serviceId}) var unregisterCallback = null if (callback) { unregisterCallback = function (error) { callback(error) } } client.asyncRequest(request, unregisterCallback) } Object.keys(service.callbacksByTopic).forEach(function (topic) { service.callbacksByTopic[topic].forEach(function (callback) { client.removeRequestCallback(topic, callback) }) }) clearTtlTimeout(service) }
[ "function", "unregisterService", "(", "client", ",", "service", ",", "callback", ")", "{", "if", "(", "client", ".", "connected", ")", "{", "var", "request", "=", "new", "Request", "(", "DXL_SERVICE_UNREGISTER_REQUEST_TOPIC", ")", "request", ".", "payload", "=", "JSON", ".", "stringify", "(", "{", "serviceGuid", ":", "service", ".", "info", ".", "serviceId", "}", ")", "var", "unregisterCallback", "=", "null", "if", "(", "callback", ")", "{", "unregisterCallback", "=", "function", "(", "error", ")", "{", "callback", "(", "error", ")", "}", "}", "client", ".", "asyncRequest", "(", "request", ",", "unregisterCallback", ")", "}", "Object", ".", "keys", "(", "service", ".", "callbacksByTopic", ")", ".", "forEach", "(", "function", "(", "topic", ")", "{", "service", ".", "callbacksByTopic", "[", "topic", "]", ".", "forEach", "(", "function", "(", "callback", ")", "{", "client", ".", "removeRequestCallback", "(", "topic", ",", "callback", ")", "}", ")", "}", ")", "clearTtlTimeout", "(", "service", ")", "}" ]
Unregisters the service from the DXL fabric. @private @param {Client} client - Client to be used for unregistering the service. @param {Object} service - Metadata for the service. @param {ServiceRegistrationInfo} service.info - Info supplied for the service registration via a call to the {@link ServiceManager#registerServiceAsync} function. @param {Object} service.ttlTimeout - Id for the service's ttl callback. @param {Function} [callback=null] - An optional callback that will be invoked when the unregistration attempt is complete. If an error occurs during the unregistration attempt, the first parameter supplied to the callback contains an {@link Error} with failure details.
[ "Unregisters", "the", "service", "from", "the", "DXL", "fabric", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/service-manager.js#L142-L161
43,847
opendxl/opendxl-client-javascript
lib/_provisioning/pki.js
findOpenSslBin
function findOpenSslBin (opensslBin) { if (opensslBin) { if (!fs.existsSync(opensslBin)) { throw new DxlError('Unable to find openssl at: ' + opensslBin) } } else { opensslBin = which.sync('openssl', {nothrow: true}) if (!opensslBin && (os.platform() === 'win32')) { opensslBin = DEFAULT_OPENSSL_WIN32_INSTALL_DIRS.reduce( function (acc, candidatePath) { candidatePath = path.join(candidatePath, 'openssl.exe') if (!acc && fs.existsSync(candidatePath)) { acc = candidatePath } return acc }, null ) } if (!opensslBin) { throw new DxlError('Unable to find openssl from system path') } } return opensslBin }
javascript
function findOpenSslBin (opensslBin) { if (opensslBin) { if (!fs.existsSync(opensslBin)) { throw new DxlError('Unable to find openssl at: ' + opensslBin) } } else { opensslBin = which.sync('openssl', {nothrow: true}) if (!opensslBin && (os.platform() === 'win32')) { opensslBin = DEFAULT_OPENSSL_WIN32_INSTALL_DIRS.reduce( function (acc, candidatePath) { candidatePath = path.join(candidatePath, 'openssl.exe') if (!acc && fs.existsSync(candidatePath)) { acc = candidatePath } return acc }, null ) } if (!opensslBin) { throw new DxlError('Unable to find openssl from system path') } } return opensslBin }
[ "function", "findOpenSslBin", "(", "opensslBin", ")", "{", "if", "(", "opensslBin", ")", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "opensslBin", ")", ")", "{", "throw", "new", "DxlError", "(", "'Unable to find openssl at: '", "+", "opensslBin", ")", "}", "}", "else", "{", "opensslBin", "=", "which", ".", "sync", "(", "'openssl'", ",", "{", "nothrow", ":", "true", "}", ")", "if", "(", "!", "opensslBin", "&&", "(", "os", ".", "platform", "(", ")", "===", "'win32'", ")", ")", "{", "opensslBin", "=", "DEFAULT_OPENSSL_WIN32_INSTALL_DIRS", ".", "reduce", "(", "function", "(", "acc", ",", "candidatePath", ")", "{", "candidatePath", "=", "path", ".", "join", "(", "candidatePath", ",", "'openssl.exe'", ")", "if", "(", "!", "acc", "&&", "fs", ".", "existsSync", "(", "candidatePath", ")", ")", "{", "acc", "=", "candidatePath", "}", "return", "acc", "}", ",", "null", ")", "}", "if", "(", "!", "opensslBin", ")", "{", "throw", "new", "DxlError", "(", "'Unable to find openssl from system path'", ")", "}", "}", "return", "opensslBin", "}" ]
Returns the first location found for the openssl executable. @param {String} [opensslBin=null] - If non-null and the named file exists, this value is returned. @returns {String} Path to the openssl executable. @throws {DxlError} If openssl cannot be found.
[ "Returns", "the", "first", "location", "found", "for", "the", "openssl", "executable", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_provisioning/pki.js#L88-L112
43,848
opendxl/opendxl-client-javascript
lib/_provisioning/pki.js
indentedLogOutput
function indentedLogOutput (logOutput) { logOutput = logOutput.toString() if (logOutput) { logOutput = '\n ' + logOutput.toString().replace(/(\r?\n)/g, '$1 ') } return logOutput }
javascript
function indentedLogOutput (logOutput) { logOutput = logOutput.toString() if (logOutput) { logOutput = '\n ' + logOutput.toString().replace(/(\r?\n)/g, '$1 ') } return logOutput }
[ "function", "indentedLogOutput", "(", "logOutput", ")", "{", "logOutput", "=", "logOutput", ".", "toString", "(", ")", "if", "(", "logOutput", ")", "{", "logOutput", "=", "'\\n '", "+", "logOutput", ".", "toString", "(", ")", ".", "replace", "(", "/", "(\\r?\\n)", "/", "g", ",", "'$1 '", ")", "}", "return", "logOutput", "}" ]
Indents the lines in the supplied string for display in log output. @param {String} logOutput - The data to indent. @returns {String} The indented output.
[ "Indents", "the", "lines", "in", "the", "supplied", "string", "for", "display", "in", "log", "output", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_provisioning/pki.js#L119-L125
43,849
opendxl/opendxl-client-javascript
lib/_provisioning/pki.js
buildCsrSubject
function buildCsrSubject (commonName, options) { var subject = '/CN=' + commonName Object.keys(SUBJECT_ATTRIBUTES).forEach(function (key) { if (options[key]) { subject = subject + '/' + SUBJECT_ATTRIBUTES[key].name + '=' + options[key] } }) return subject }
javascript
function buildCsrSubject (commonName, options) { var subject = '/CN=' + commonName Object.keys(SUBJECT_ATTRIBUTES).forEach(function (key) { if (options[key]) { subject = subject + '/' + SUBJECT_ATTRIBUTES[key].name + '=' + options[key] } }) return subject }
[ "function", "buildCsrSubject", "(", "commonName", ",", "options", ")", "{", "var", "subject", "=", "'/CN='", "+", "commonName", "Object", ".", "keys", "(", "SUBJECT_ATTRIBUTES", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "options", "[", "key", "]", ")", "{", "subject", "=", "subject", "+", "'/'", "+", "SUBJECT_ATTRIBUTES", "[", "key", "]", ".", "name", "+", "'='", "+", "options", "[", "key", "]", "}", "}", ")", "return", "subject", "}" ]
Convert the X509 subject attributes specified on the command-line into a flat X509 subject string for use with openssl commands. @param {String} commonName - The X509 Common Name (CN) specified on the command line. @param {Object} [options] - Options to use in generating the CSR and private key. @returns {String} The X509 Subject in openssl display format.
[ "Convert", "the", "X509", "subject", "attributes", "specified", "on", "the", "command", "-", "line", "into", "a", "flat", "X509", "subject", "string", "for", "use", "with", "openssl", "commands", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_provisioning/pki.js#L136-L145
43,850
opendxl/opendxl-client-javascript
lib/_provisioning/pki.js
function (description, commandArgs, opensslBin, verbosity, input) { opensslBin = findOpenSslBin(opensslBin) if (verbosity) { if (description) { console.log(description) } if (verbosity > 1) { console.log("Running openssl. Path: '" + opensslBin + "', Command: '" + commandArgs.join(' ')) } } var command = childProcess.spawnSync(opensslBin, commandArgs, input ? {input: input} : {}) if (command.stdout && (verbosity > 1)) { console.log('OpenSSL OUTPUT LOG: ' + indentedLogOutput(command.stdout)) } if (command.stderr && ((command.status !== 0) || (verbosity > 1))) { provisionUtil.logError(indentedLogOutput(command.stderr), {header: 'OpenSSL ERROR LOG', verbosity: verbosity}) } if (command.status !== 0) { var errorMessage = 'openssl execution failed' if (command.error) { errorMessage = command.error.message } if (command.status) { errorMessage = errorMessage + ', status code: ' + command.status } throw provisionUtil.createFormattedDxlError(errorMessage, description) } return command }
javascript
function (description, commandArgs, opensslBin, verbosity, input) { opensslBin = findOpenSslBin(opensslBin) if (verbosity) { if (description) { console.log(description) } if (verbosity > 1) { console.log("Running openssl. Path: '" + opensslBin + "', Command: '" + commandArgs.join(' ')) } } var command = childProcess.spawnSync(opensslBin, commandArgs, input ? {input: input} : {}) if (command.stdout && (verbosity > 1)) { console.log('OpenSSL OUTPUT LOG: ' + indentedLogOutput(command.stdout)) } if (command.stderr && ((command.status !== 0) || (verbosity > 1))) { provisionUtil.logError(indentedLogOutput(command.stderr), {header: 'OpenSSL ERROR LOG', verbosity: verbosity}) } if (command.status !== 0) { var errorMessage = 'openssl execution failed' if (command.error) { errorMessage = command.error.message } if (command.status) { errorMessage = errorMessage + ', status code: ' + command.status } throw provisionUtil.createFormattedDxlError(errorMessage, description) } return command }
[ "function", "(", "description", ",", "commandArgs", ",", "opensslBin", ",", "verbosity", ",", "input", ")", "{", "opensslBin", "=", "findOpenSslBin", "(", "opensslBin", ")", "if", "(", "verbosity", ")", "{", "if", "(", "description", ")", "{", "console", ".", "log", "(", "description", ")", "}", "if", "(", "verbosity", ">", "1", ")", "{", "console", ".", "log", "(", "\"Running openssl. Path: '\"", "+", "opensslBin", "+", "\"', Command: '\"", "+", "commandArgs", ".", "join", "(", "' '", ")", ")", "}", "}", "var", "command", "=", "childProcess", ".", "spawnSync", "(", "opensslBin", ",", "commandArgs", ",", "input", "?", "{", "input", ":", "input", "}", ":", "{", "}", ")", "if", "(", "command", ".", "stdout", "&&", "(", "verbosity", ">", "1", ")", ")", "{", "console", ".", "log", "(", "'OpenSSL OUTPUT LOG: '", "+", "indentedLogOutput", "(", "command", ".", "stdout", ")", ")", "}", "if", "(", "command", ".", "stderr", "&&", "(", "(", "command", ".", "status", "!==", "0", ")", "||", "(", "verbosity", ">", "1", ")", ")", ")", "{", "provisionUtil", ".", "logError", "(", "indentedLogOutput", "(", "command", ".", "stderr", ")", ",", "{", "header", ":", "'OpenSSL ERROR LOG'", ",", "verbosity", ":", "verbosity", "}", ")", "}", "if", "(", "command", ".", "status", "!==", "0", ")", "{", "var", "errorMessage", "=", "'openssl execution failed'", "if", "(", "command", ".", "error", ")", "{", "errorMessage", "=", "command", ".", "error", ".", "message", "}", "if", "(", "command", ".", "status", ")", "{", "errorMessage", "=", "errorMessage", "+", "', status code: '", "+", "command", ".", "status", "}", "throw", "provisionUtil", ".", "createFormattedDxlError", "(", "errorMessage", ",", "description", ")", "}", "return", "command", "}" ]
Runs an openssl command. @param {String} description - Textual description of the HTTP request (used in log and error messages). @param {Array<String>} commandArgs - Array of arguments to supply to the openssl command line. @param {String} [opensslBin] - Path to the openssl executable. If not specified, the function attempts to find the openssl executable from the environment path. @param {Number} [verbosity] - Level of verbosity at which to log any error or trace messages. @param {String} [input] - Optional standard input to provide to the openssl command. @returns {Object} Results of the openssl command. The object returned is from the underlying call to child_process.spawnSync. @throws {DxlError} If the openssl command fails. A non-zero exit code for the command is interpreted as failure.
[ "Runs", "an", "openssl", "command", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_provisioning/pki.js#L178-L214
43,851
aholstenson/ecolect-js
src/time/dates.js
adjust
function adjust(r, e, time, def) { const requested = r[def.field]; const current = def.get(time, e.options); if(r.relationToCurrent === 'auto') { if(requested < current) { time = def.set(def.adjuster(time, 1, e.options), requested, e.options); } else { time = def.set(time, requested, e.options); } } else if(r.relationToCurrent === 'current-period') { if(def.parentData(r) && requested < current) { time = def.set(def.adjuster(time, 1, e.options), requested, e.options); } else { time = def.set(time, requested, e.options); } } else if(r.relationToCurrent === 'future') { if(requested <= current) { time = def.set(def.adjuster(time, 1, e.options), requested, e.options); } else { time = def.set(time, requested, e.options); } } else if(r.relationToCurrent === 'past') { if(requested >= current) { time = def.set(def.adjuster(time, -1, e.options), requested, e.options); } else { time = def.set(time, requested, e.options); } } return time; }
javascript
function adjust(r, e, time, def) { const requested = r[def.field]; const current = def.get(time, e.options); if(r.relationToCurrent === 'auto') { if(requested < current) { time = def.set(def.adjuster(time, 1, e.options), requested, e.options); } else { time = def.set(time, requested, e.options); } } else if(r.relationToCurrent === 'current-period') { if(def.parentData(r) && requested < current) { time = def.set(def.adjuster(time, 1, e.options), requested, e.options); } else { time = def.set(time, requested, e.options); } } else if(r.relationToCurrent === 'future') { if(requested <= current) { time = def.set(def.adjuster(time, 1, e.options), requested, e.options); } else { time = def.set(time, requested, e.options); } } else if(r.relationToCurrent === 'past') { if(requested >= current) { time = def.set(def.adjuster(time, -1, e.options), requested, e.options); } else { time = def.set(time, requested, e.options); } } return time; }
[ "function", "adjust", "(", "r", ",", "e", ",", "time", ",", "def", ")", "{", "const", "requested", "=", "r", "[", "def", ".", "field", "]", ";", "const", "current", "=", "def", ".", "get", "(", "time", ",", "e", ".", "options", ")", ";", "if", "(", "r", ".", "relationToCurrent", "===", "'auto'", ")", "{", "if", "(", "requested", "<", "current", ")", "{", "time", "=", "def", ".", "set", "(", "def", ".", "adjuster", "(", "time", ",", "1", ",", "e", ".", "options", ")", ",", "requested", ",", "e", ".", "options", ")", ";", "}", "else", "{", "time", "=", "def", ".", "set", "(", "time", ",", "requested", ",", "e", ".", "options", ")", ";", "}", "}", "else", "if", "(", "r", ".", "relationToCurrent", "===", "'current-period'", ")", "{", "if", "(", "def", ".", "parentData", "(", "r", ")", "&&", "requested", "<", "current", ")", "{", "time", "=", "def", ".", "set", "(", "def", ".", "adjuster", "(", "time", ",", "1", ",", "e", ".", "options", ")", ",", "requested", ",", "e", ".", "options", ")", ";", "}", "else", "{", "time", "=", "def", ".", "set", "(", "time", ",", "requested", ",", "e", ".", "options", ")", ";", "}", "}", "else", "if", "(", "r", ".", "relationToCurrent", "===", "'future'", ")", "{", "if", "(", "requested", "<=", "current", ")", "{", "time", "=", "def", ".", "set", "(", "def", ".", "adjuster", "(", "time", ",", "1", ",", "e", ".", "options", ")", ",", "requested", ",", "e", ".", "options", ")", ";", "}", "else", "{", "time", "=", "def", ".", "set", "(", "time", ",", "requested", ",", "e", ".", "options", ")", ";", "}", "}", "else", "if", "(", "r", ".", "relationToCurrent", "===", "'past'", ")", "{", "if", "(", "requested", ">=", "current", ")", "{", "time", "=", "def", ".", "set", "(", "def", ".", "adjuster", "(", "time", ",", "-", "1", ",", "e", ".", "options", ")", ",", "requested", ",", "e", ".", "options", ")", ";", "}", "else", "{", "time", "=", "def", ".", "set", "(", "time", ",", "requested", ",", "e", ".", "options", ")", ";", "}", "}", "return", "time", ";", "}" ]
Adjust the current time based on a field. Implements different strategies such as automatic, which tries to adjust the field forward if it's in the past. @param {Date} time the current time @param {Object} r the object containing the data @param {*} def definition describing the field to modify
[ "Adjust", "the", "current", "time", "based", "on", "a", "field", ".", "Implements", "different", "strategies", "such", "as", "automatic", "which", "tries", "to", "adjust", "the", "field", "forward", "if", "it", "s", "in", "the", "past", "." ]
db7f473a7d38588778b5724daa6ad38ac5ea4ec4
https://github.com/aholstenson/ecolect-js/blob/db7f473a7d38588778b5724daa6ad38ac5ea4ec4/src/time/dates.js#L118-L149
43,852
silas/swagger-framework
lib/schema/transform.js
traverse
function traverse(value, cbs) { cbs = cbs || {}; if (Array.isArray(value)) { if (cbs.beforeArray) value = cbs.beforeArray(value, cbs); value = value.map(function(v) { return traverse(v, cbs); }); if (cbs.afterArray) value = cbs.afterArray(value, cbs); } else if (typeof value === 'object') { if (cbs.beforeObject) value = cbs.beforeObject(value, cbs); Object.keys(value).forEach(function(key) { value[key] = traverse(value[key], cbs); }); if (cbs.afterObject) value = cbs.afterObject(value, cbs); } return value; }
javascript
function traverse(value, cbs) { cbs = cbs || {}; if (Array.isArray(value)) { if (cbs.beforeArray) value = cbs.beforeArray(value, cbs); value = value.map(function(v) { return traverse(v, cbs); }); if (cbs.afterArray) value = cbs.afterArray(value, cbs); } else if (typeof value === 'object') { if (cbs.beforeObject) value = cbs.beforeObject(value, cbs); Object.keys(value).forEach(function(key) { value[key] = traverse(value[key], cbs); }); if (cbs.afterObject) value = cbs.afterObject(value, cbs); } return value; }
[ "function", "traverse", "(", "value", ",", "cbs", ")", "{", "cbs", "=", "cbs", "||", "{", "}", ";", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "if", "(", "cbs", ".", "beforeArray", ")", "value", "=", "cbs", ".", "beforeArray", "(", "value", ",", "cbs", ")", ";", "value", "=", "value", ".", "map", "(", "function", "(", "v", ")", "{", "return", "traverse", "(", "v", ",", "cbs", ")", ";", "}", ")", ";", "if", "(", "cbs", ".", "afterArray", ")", "value", "=", "cbs", ".", "afterArray", "(", "value", ",", "cbs", ")", ";", "}", "else", "if", "(", "typeof", "value", "===", "'object'", ")", "{", "if", "(", "cbs", ".", "beforeObject", ")", "value", "=", "cbs", ".", "beforeObject", "(", "value", ",", "cbs", ")", ";", "Object", ".", "keys", "(", "value", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "value", "[", "key", "]", "=", "traverse", "(", "value", "[", "key", "]", ",", "cbs", ")", ";", "}", ")", ";", "if", "(", "cbs", ".", "afterObject", ")", "value", "=", "cbs", ".", "afterObject", "(", "value", ",", "cbs", ")", ";", "}", "return", "value", ";", "}" ]
Traverse object.
[ "Traverse", "object", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/schema/transform.js#L19-L41
43,853
silas/swagger-framework
lib/schema/transform.js
transform
function transform(value, options) { options = options || {}; return traverse(value, { beforeObject: function(v) { if (options.removeFormats && typeof v.format === 'string' && typeof v.type === 'string' && v.type !== 'string') { delete v.format; } return v; }, afterObject: function(v) { if (options.convertRefs && typeof v.type === 'string' && constants.notModel.indexOf(v.type) < 0) { return { $ref: v.type }; } return v; }, }); }
javascript
function transform(value, options) { options = options || {}; return traverse(value, { beforeObject: function(v) { if (options.removeFormats && typeof v.format === 'string' && typeof v.type === 'string' && v.type !== 'string') { delete v.format; } return v; }, afterObject: function(v) { if (options.convertRefs && typeof v.type === 'string' && constants.notModel.indexOf(v.type) < 0) { return { $ref: v.type }; } return v; }, }); }
[ "function", "transform", "(", "value", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "return", "traverse", "(", "value", ",", "{", "beforeObject", ":", "function", "(", "v", ")", "{", "if", "(", "options", ".", "removeFormats", "&&", "typeof", "v", ".", "format", "===", "'string'", "&&", "typeof", "v", ".", "type", "===", "'string'", "&&", "v", ".", "type", "!==", "'string'", ")", "{", "delete", "v", ".", "format", ";", "}", "return", "v", ";", "}", ",", "afterObject", ":", "function", "(", "v", ")", "{", "if", "(", "options", ".", "convertRefs", "&&", "typeof", "v", ".", "type", "===", "'string'", "&&", "constants", ".", "notModel", ".", "indexOf", "(", "v", ".", "type", ")", "<", "0", ")", "{", "return", "{", "$ref", ":", "v", ".", "type", "}", ";", "}", "return", "v", ";", "}", ",", "}", ")", ";", "}" ]
Transform Swagger spec.
[ "Transform", "Swagger", "spec", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/schema/transform.js#L47-L71
43,854
silas/swagger-framework
lib/schema/transform.js
model
function model(spec) { var schema = lodash.cloneDeep(spec); delete schema.id; schema = transform(schema, { removeFormats: true, }); return schema; }
javascript
function model(spec) { var schema = lodash.cloneDeep(spec); delete schema.id; schema = transform(schema, { removeFormats: true, }); return schema; }
[ "function", "model", "(", "spec", ")", "{", "var", "schema", "=", "lodash", ".", "cloneDeep", "(", "spec", ")", ";", "delete", "schema", ".", "id", ";", "schema", "=", "transform", "(", "schema", ",", "{", "removeFormats", ":", "true", ",", "}", ")", ";", "return", "schema", ";", "}" ]
Convert Swagger model to JSON Schema.
[ "Convert", "Swagger", "model", "to", "JSON", "Schema", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/schema/transform.js#L202-L212
43,855
layerhq/node-layer-webhooks-services
examples/basic-services/message-sent.js
getText
function getText(msg) { return msg.parts.filter(function (part) { return part.mime_type === 'text/plain'; }).map(function (part) { return part.body; }).join('; '); }
javascript
function getText(msg) { return msg.parts.filter(function (part) { return part.mime_type === 'text/plain'; }).map(function (part) { return part.body; }).join('; '); }
[ "function", "getText", "(", "msg", ")", "{", "return", "msg", ".", "parts", ".", "filter", "(", "function", "(", "part", ")", "{", "return", "part", ".", "mime_type", "===", "'text/plain'", ";", "}", ")", ".", "map", "(", "function", "(", "part", ")", "{", "return", "part", ".", "body", ";", "}", ")", ".", "join", "(", "'; '", ")", ";", "}" ]
Get the text from a Message.
[ "Get", "the", "text", "from", "a", "Message", "." ]
7ef63df31fb5b769ebe57b8855806178e1ce8dd8
https://github.com/layerhq/node-layer-webhooks-services/blob/7ef63df31fb5b769ebe57b8855806178e1ce8dd8/examples/basic-services/message-sent.js#L20-L26
43,856
layerhq/node-layer-webhooks-services
examples/basic-services/message-sent.js
rollTheDie
function rollTheDie(msg, text) { var conversationId = msg.conversation.id; var matches = text.match(/die (\d+)/i); if (matches && matches[1]) { var dieCount = Number(matches[1]); var result = []; if (dieCount > 20) { layerClient.messages.sendTextFromName(conversationId, 'Die-bot', 'So much death is a terrible thing to ask of me. You should be ashamed!'); } else { for (var i = 0; i < dieCount; i++) { result.push(Math.floor(Math.random() * 6) + 1); // Simple 6 sided die } layerClient.messages.sendTextFromName(conversationId, 'Die-bot', 'Rolled a ' + result.join(', ').replace(/(.*),(.*)/, '$1 and$2')); } } }
javascript
function rollTheDie(msg, text) { var conversationId = msg.conversation.id; var matches = text.match(/die (\d+)/i); if (matches && matches[1]) { var dieCount = Number(matches[1]); var result = []; if (dieCount > 20) { layerClient.messages.sendTextFromName(conversationId, 'Die-bot', 'So much death is a terrible thing to ask of me. You should be ashamed!'); } else { for (var i = 0; i < dieCount; i++) { result.push(Math.floor(Math.random() * 6) + 1); // Simple 6 sided die } layerClient.messages.sendTextFromName(conversationId, 'Die-bot', 'Rolled a ' + result.join(', ').replace(/(.*),(.*)/, '$1 and$2')); } } }
[ "function", "rollTheDie", "(", "msg", ",", "text", ")", "{", "var", "conversationId", "=", "msg", ".", "conversation", ".", "id", ";", "var", "matches", "=", "text", ".", "match", "(", "/", "die (\\d+)", "/", "i", ")", ";", "if", "(", "matches", "&&", "matches", "[", "1", "]", ")", "{", "var", "dieCount", "=", "Number", "(", "matches", "[", "1", "]", ")", ";", "var", "result", "=", "[", "]", ";", "if", "(", "dieCount", ">", "20", ")", "{", "layerClient", ".", "messages", ".", "sendTextFromName", "(", "conversationId", ",", "'Die-bot'", ",", "'So much death is a terrible thing to ask of me. You should be ashamed!'", ")", ";", "}", "else", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "dieCount", ";", "i", "++", ")", "{", "result", ".", "push", "(", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "6", ")", "+", "1", ")", ";", "// Simple 6 sided die", "}", "layerClient", ".", "messages", ".", "sendTextFromName", "(", "conversationId", ",", "'Die-bot'", ",", "'Rolled a '", "+", "result", ".", "join", "(", "', '", ")", ".", "replace", "(", "/", "(.*),(.*)", "/", ",", "'$1 and$2'", ")", ")", ";", "}", "}", "}" ]
If someone sends the phrase "die 5" roll the dice 5 times and report the results
[ "If", "someone", "sends", "the", "phrase", "die", "5", "roll", "the", "dice", "5", "times", "and", "report", "the", "results" ]
7ef63df31fb5b769ebe57b8855806178e1ce8dd8
https://github.com/layerhq/node-layer-webhooks-services/blob/7ef63df31fb5b769ebe57b8855806178e1ce8dd8/examples/basic-services/message-sent.js#L58-L74
43,857
layerhq/node-layer-webhooks-services
examples/basic-services/message-sent.js
foodTalk
function foodTalk (msg, text) { var conversationId = msg.conversation.id; var matches = text.match(/eat my (.+?)\b/i); if (matches) { layerClient.messages.sendTextFromName(conversationId, 'Food-bot', 'My ' + matches[1] + ' taste a lot better than yours'); } else { var messages = [ 'I\'m eating yummy carbon', 'I\'m eating yummy silicon', 'I\'m eating your keyboard. Yummy!', 'I\'m nibbling on your screen. Sorry about the dead pixels.', 'I\'m eating your fingers. Seriously, you should get more of these!', 'Feed me....' ]; layerClient.messages.sendTextFromName(conversationId, 'Food-bot', messages[Math.floor(Math.random() * 6)]); } }
javascript
function foodTalk (msg, text) { var conversationId = msg.conversation.id; var matches = text.match(/eat my (.+?)\b/i); if (matches) { layerClient.messages.sendTextFromName(conversationId, 'Food-bot', 'My ' + matches[1] + ' taste a lot better than yours'); } else { var messages = [ 'I\'m eating yummy carbon', 'I\'m eating yummy silicon', 'I\'m eating your keyboard. Yummy!', 'I\'m nibbling on your screen. Sorry about the dead pixels.', 'I\'m eating your fingers. Seriously, you should get more of these!', 'Feed me....' ]; layerClient.messages.sendTextFromName(conversationId, 'Food-bot', messages[Math.floor(Math.random() * 6)]); } }
[ "function", "foodTalk", "(", "msg", ",", "text", ")", "{", "var", "conversationId", "=", "msg", ".", "conversation", ".", "id", ";", "var", "matches", "=", "text", ".", "match", "(", "/", "eat my (.+?)\\b", "/", "i", ")", ";", "if", "(", "matches", ")", "{", "layerClient", ".", "messages", ".", "sendTextFromName", "(", "conversationId", ",", "'Food-bot'", ",", "'My '", "+", "matches", "[", "1", "]", "+", "' taste a lot better than yours'", ")", ";", "}", "else", "{", "var", "messages", "=", "[", "'I\\'m eating yummy carbon'", ",", "'I\\'m eating yummy silicon'", ",", "'I\\'m eating your keyboard. Yummy!'", ",", "'I\\'m nibbling on your screen. Sorry about the dead pixels.'", ",", "'I\\'m eating your fingers. Seriously, you should get more of these!'", ",", "'Feed me....'", "]", ";", "layerClient", ".", "messages", ".", "sendTextFromName", "(", "conversationId", ",", "'Food-bot'", ",", "messages", "[", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "6", ")", "]", ")", ";", "}", "}" ]
If someone sends any phrase that has the word eat in it, respond with some food talk...
[ "If", "someone", "sends", "any", "phrase", "that", "has", "the", "word", "eat", "in", "it", "respond", "with", "some", "food", "talk", "..." ]
7ef63df31fb5b769ebe57b8855806178e1ce8dd8
https://github.com/layerhq/node-layer-webhooks-services/blob/7ef63df31fb5b769ebe57b8855806178e1ce8dd8/examples/basic-services/message-sent.js#L79-L96
43,858
jeffbski/autoflow
lib/autoflow.js
logEvents
function logEvents(flowFn, eventWildcard) { if (typeof(flowFn) !== 'function') { // only wildcard provided eventWildcard = flowFn; flowFn = undefined; } if (!flowFn) flowFn = autoflow; // use global trackTasks(); return logEventsMod.logEvents(flowFn, eventWildcard); }
javascript
function logEvents(flowFn, eventWildcard) { if (typeof(flowFn) !== 'function') { // only wildcard provided eventWildcard = flowFn; flowFn = undefined; } if (!flowFn) flowFn = autoflow; // use global trackTasks(); return logEventsMod.logEvents(flowFn, eventWildcard); }
[ "function", "logEvents", "(", "flowFn", ",", "eventWildcard", ")", "{", "if", "(", "typeof", "(", "flowFn", ")", "!==", "'function'", ")", "{", "// only wildcard provided", "eventWildcard", "=", "flowFn", ";", "flowFn", "=", "undefined", ";", "}", "if", "(", "!", "flowFn", ")", "flowFn", "=", "autoflow", ";", "// use global", "trackTasks", "(", ")", ";", "return", "logEventsMod", ".", "logEvents", "(", "flowFn", ",", "eventWildcard", ")", ";", "}" ]
If called, load the built-in plugin for log events and invoke @param flowFn [function] if not provided uses global autoflow @param eventWildcard [string] pattern to log events for
[ "If", "called", "load", "the", "built", "-", "in", "plugin", "for", "log", "events", "and", "invoke" ]
aa30f6e6c2e74aa72a018c65698acac3fb478cbb
https://github.com/jeffbski/autoflow/blob/aa30f6e6c2e74aa72a018c65698acac3fb478cbb/lib/autoflow.js#L34-L42
43,859
rakuten-frontend/bower-browser
client/assets/scripts/services/process.js
function (command, id) { id = id || ''; if (id) { this.queue.push(id); } SocketService.emit('execute', { command: command, id: id }); }
javascript
function (command, id) { id = id || ''; if (id) { this.queue.push(id); } SocketService.emit('execute', { command: command, id: id }); }
[ "function", "(", "command", ",", "id", ")", "{", "id", "=", "id", "||", "''", ";", "if", "(", "id", ")", "{", "this", ".", "queue", ".", "push", "(", "id", ")", ";", "}", "SocketService", ".", "emit", "(", "'execute'", ",", "{", "command", ":", "command", ",", "id", ":", "id", "}", ")", ";", "}" ]
WebSocket to execute command
[ "WebSocket", "to", "execute", "command" ]
d7875331f5d6f6ad0b7164d6116a341ac97f613f
https://github.com/rakuten-frontend/bower-browser/blob/d7875331f5d6f6ad0b7164d6116a341ac97f613f/client/assets/scripts/services/process.js#L35-L44
43,860
rakuten-frontend/bower-browser
client/assets/scripts/services/settings.js
function (data) { var validData = _.deepMapValues(this.config, function (value, propertyPath) { return _.deepGet(data, propertyPath.join('.')); }); _.merge(this.config, validData); }
javascript
function (data) { var validData = _.deepMapValues(this.config, function (value, propertyPath) { return _.deepGet(data, propertyPath.join('.')); }); _.merge(this.config, validData); }
[ "function", "(", "data", ")", "{", "var", "validData", "=", "_", ".", "deepMapValues", "(", "this", ".", "config", ",", "function", "(", "value", ",", "propertyPath", ")", "{", "return", "_", ".", "deepGet", "(", "data", ",", "propertyPath", ".", "join", "(", "'.'", ")", ")", ";", "}", ")", ";", "_", ".", "merge", "(", "this", ".", "config", ",", "validData", ")", ";", "}" ]
Set settings Invalid properties are ignored
[ "Set", "settings", "Invalid", "properties", "are", "ignored" ]
d7875331f5d6f6ad0b7164d6116a341ac97f613f
https://github.com/rakuten-frontend/bower-browser/blob/d7875331f5d6f6ad0b7164d6116a341ac97f613f/client/assets/scripts/services/settings.js#L38-L43
43,861
rakuten-frontend/bower-browser
client/assets/scripts/services/settings.js
function () { var self = this; $http.get(settingsApi) .success(function (data) { self.set(data); $timeout(function () { self.loaded = true; }); }) .error(function () { self.reset(); $timeout(function () { self.loaded = true; }); }); }
javascript
function () { var self = this; $http.get(settingsApi) .success(function (data) { self.set(data); $timeout(function () { self.loaded = true; }); }) .error(function () { self.reset(); $timeout(function () { self.loaded = true; }); }); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "$http", ".", "get", "(", "settingsApi", ")", ".", "success", "(", "function", "(", "data", ")", "{", "self", ".", "set", "(", "data", ")", ";", "$timeout", "(", "function", "(", ")", "{", "self", ".", "loaded", "=", "true", ";", "}", ")", ";", "}", ")", ".", "error", "(", "function", "(", ")", "{", "self", ".", "reset", "(", ")", ";", "$timeout", "(", "function", "(", ")", "{", "self", ".", "loaded", "=", "true", ";", "}", ")", ";", "}", ")", ";", "}" ]
Load settings from server
[ "Load", "settings", "from", "server" ]
d7875331f5d6f6ad0b7164d6116a341ac97f613f
https://github.com/rakuten-frontend/bower-browser/blob/d7875331f5d6f6ad0b7164d6116a341ac97f613f/client/assets/scripts/services/settings.js#L46-L61
43,862
rakuten-frontend/bower-browser
client/assets/scripts/services/settings.js
function () { var searchField = this.config.searchField; return searchField && Object.keys(searchField).every(function (key) { return searchField[key] === false; }); }
javascript
function () { var searchField = this.config.searchField; return searchField && Object.keys(searchField).every(function (key) { return searchField[key] === false; }); }
[ "function", "(", ")", "{", "var", "searchField", "=", "this", ".", "config", ".", "searchField", ";", "return", "searchField", "&&", "Object", ".", "keys", "(", "searchField", ")", ".", "every", "(", "function", "(", "key", ")", "{", "return", "searchField", "[", "key", "]", "===", "false", ";", "}", ")", ";", "}" ]
Warn when no search field is selected
[ "Warn", "when", "no", "search", "field", "is", "selected" ]
d7875331f5d6f6ad0b7164d6116a341ac97f613f
https://github.com/rakuten-frontend/bower-browser/blob/d7875331f5d6f6ad0b7164d6116a341ac97f613f/client/assets/scripts/services/settings.js#L74-L80
43,863
opendxl/opendxl-client-javascript
sample/common.js
function (module) { if (module === SDK_PACKAGE_NAME) { var packageFile = path.join(__dirname, '..', 'package.json') if (fs.existsSync(packageFile)) { var packageInfo = JSON.parse(fs.readFileSync(packageFile)) if (packageInfo.name === SDK_PACKAGE_NAME) { // Use local library sources if the example is being run from source. module = '..' } } } else if (fs.existsSync(path.join(__dirname, '..', 'node_modules', SDK_PACKAGE_NAME, 'node_modules', module))) { // Prior to NPM version 3, an 'npm install' would nest a package's // dependencies under a 'node_modules' subdirectory. Adjust the module // name to reflect the nested location if found there. module = '../node_modules/' + SDK_PACKAGE_NAME + '/node_modules/' + module } return require(module) }
javascript
function (module) { if (module === SDK_PACKAGE_NAME) { var packageFile = path.join(__dirname, '..', 'package.json') if (fs.existsSync(packageFile)) { var packageInfo = JSON.parse(fs.readFileSync(packageFile)) if (packageInfo.name === SDK_PACKAGE_NAME) { // Use local library sources if the example is being run from source. module = '..' } } } else if (fs.existsSync(path.join(__dirname, '..', 'node_modules', SDK_PACKAGE_NAME, 'node_modules', module))) { // Prior to NPM version 3, an 'npm install' would nest a package's // dependencies under a 'node_modules' subdirectory. Adjust the module // name to reflect the nested location if found there. module = '../node_modules/' + SDK_PACKAGE_NAME + '/node_modules/' + module } return require(module) }
[ "function", "(", "module", ")", "{", "if", "(", "module", "===", "SDK_PACKAGE_NAME", ")", "{", "var", "packageFile", "=", "path", ".", "join", "(", "__dirname", ",", "'..'", ",", "'package.json'", ")", "if", "(", "fs", ".", "existsSync", "(", "packageFile", ")", ")", "{", "var", "packageInfo", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "packageFile", ")", ")", "if", "(", "packageInfo", ".", "name", "===", "SDK_PACKAGE_NAME", ")", "{", "// Use local library sources if the example is being run from source.", "module", "=", "'..'", "}", "}", "}", "else", "if", "(", "fs", ".", "existsSync", "(", "path", ".", "join", "(", "__dirname", ",", "'..'", ",", "'node_modules'", ",", "SDK_PACKAGE_NAME", ",", "'node_modules'", ",", "module", ")", ")", ")", "{", "// Prior to NPM version 3, an 'npm install' would nest a package's", "// dependencies under a 'node_modules' subdirectory. Adjust the module", "// name to reflect the nested location if found there.", "module", "=", "'../node_modules/'", "+", "SDK_PACKAGE_NAME", "+", "'/node_modules/'", "+", "module", "}", "return", "require", "(", "module", ")", "}" ]
Load a module, adjusting for an alternate location when running from an SDK sample. This function adjusts for differences in the module path when running a sample from a repository source checkout vs. an installed release package and for flat (NPM version 2) vs. nested (NPM version 3 and later) dependency installation. This function should only be needed for running the SDK samples. For code which references the SDK module as a dependency via an NPM `package.json` file, the built-in `require` can be used directly rather than this wrapper function. @param {String} module - Name of the module to load @returns The result from the underlying call to the built-in `require` function.
[ "Load", "a", "module", "adjusting", "for", "an", "alternate", "location", "when", "running", "from", "an", "SDK", "sample", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/sample/common.js#L37-L55
43,864
rakuten-frontend/bower-browser
client/assets/scripts/services/search.js
function (params) { var self = this; this.parseParams(params); if (!this.loaded) { this.fetchApi(api).success(function (data) { packages = data; self.loaded = true; self.search(); }); } else { this.search(); } }
javascript
function (params) { var self = this; this.parseParams(params); if (!this.loaded) { this.fetchApi(api).success(function (data) { packages = data; self.loaded = true; self.search(); }); } else { this.search(); } }
[ "function", "(", "params", ")", "{", "var", "self", "=", "this", ";", "this", ".", "parseParams", "(", "params", ")", ";", "if", "(", "!", "this", ".", "loaded", ")", "{", "this", ".", "fetchApi", "(", "api", ")", ".", "success", "(", "function", "(", "data", ")", "{", "packages", "=", "data", ";", "self", ".", "loaded", "=", "true", ";", "self", ".", "search", "(", ")", ";", "}", ")", ";", "}", "else", "{", "this", ".", "search", "(", ")", ";", "}", "}" ]
Set params and update results
[ "Set", "params", "and", "update", "results" ]
d7875331f5d6f6ad0b7164d6116a341ac97f613f
https://github.com/rakuten-frontend/bower-browser/blob/d7875331f5d6f6ad0b7164d6116a341ac97f613f/client/assets/scripts/services/search.js#L42-L55
43,865
rakuten-frontend/bower-browser
client/assets/scripts/services/search.js
function (params) { this.query = params.q !== undefined ? String(params.q) : defaultParams.query; this.page = params.p !== undefined ? parseInt(params.p, 10) : defaultParams.page; switch (params.s) { case 'name': case 'owner': case 'stars': case 'updated': this.sorting = params.s; break; default: this.sorting = defaultParams.sorting; } switch (params.o) { case 'asc': case 'desc': this.order = params.o; break; default: this.order = defaultParams.order; } }
javascript
function (params) { this.query = params.q !== undefined ? String(params.q) : defaultParams.query; this.page = params.p !== undefined ? parseInt(params.p, 10) : defaultParams.page; switch (params.s) { case 'name': case 'owner': case 'stars': case 'updated': this.sorting = params.s; break; default: this.sorting = defaultParams.sorting; } switch (params.o) { case 'asc': case 'desc': this.order = params.o; break; default: this.order = defaultParams.order; } }
[ "function", "(", "params", ")", "{", "this", ".", "query", "=", "params", ".", "q", "!==", "undefined", "?", "String", "(", "params", ".", "q", ")", ":", "defaultParams", ".", "query", ";", "this", ".", "page", "=", "params", ".", "p", "!==", "undefined", "?", "parseInt", "(", "params", ".", "p", ",", "10", ")", ":", "defaultParams", ".", "page", ";", "switch", "(", "params", ".", "s", ")", "{", "case", "'name'", ":", "case", "'owner'", ":", "case", "'stars'", ":", "case", "'updated'", ":", "this", ".", "sorting", "=", "params", ".", "s", ";", "break", ";", "default", ":", "this", ".", "sorting", "=", "defaultParams", ".", "sorting", ";", "}", "switch", "(", "params", ".", "o", ")", "{", "case", "'asc'", ":", "case", "'desc'", ":", "this", ".", "order", "=", "params", ".", "o", ";", "break", ";", "default", ":", "this", ".", "order", "=", "defaultParams", ".", "order", ";", "}", "}" ]
Parse params to set correct value
[ "Parse", "params", "to", "set", "correct", "value" ]
d7875331f5d6f6ad0b7164d6116a341ac97f613f
https://github.com/rakuten-frontend/bower-browser/blob/d7875331f5d6f6ad0b7164d6116a341ac97f613f/client/assets/scripts/services/search.js#L58-L79
43,866
rakuten-frontend/bower-browser
client/assets/scripts/services/search.js
function (url) { var self = this; this.searching = true; this.loadingError = false; return $http.get(url) .success(function (res) { self.searching = false; return res.data; }) .error(function () { self.searching = false; self.loadingError = true; return false; }); }
javascript
function (url) { var self = this; this.searching = true; this.loadingError = false; return $http.get(url) .success(function (res) { self.searching = false; return res.data; }) .error(function () { self.searching = false; self.loadingError = true; return false; }); }
[ "function", "(", "url", ")", "{", "var", "self", "=", "this", ";", "this", ".", "searching", "=", "true", ";", "this", ".", "loadingError", "=", "false", ";", "return", "$http", ".", "get", "(", "url", ")", ".", "success", "(", "function", "(", "res", ")", "{", "self", ".", "searching", "=", "false", ";", "return", "res", ".", "data", ";", "}", ")", ".", "error", "(", "function", "(", ")", "{", "self", ".", "searching", "=", "false", ";", "self", ".", "loadingError", "=", "true", ";", "return", "false", ";", "}", ")", ";", "}" ]
Get component list from API
[ "Get", "component", "list", "from", "API" ]
d7875331f5d6f6ad0b7164d6116a341ac97f613f
https://github.com/rakuten-frontend/bower-browser/blob/d7875331f5d6f6ad0b7164d6116a341ac97f613f/client/assets/scripts/services/search.js#L82-L96
43,867
rakuten-frontend/bower-browser
client/assets/scripts/services/search.js
function (items) { if (!config.ignoreDeprecatedPackages) { return items; } var list = _.filter(items, function (item) { // Ignore packages if (ignore.indexOf(item.name) !== -1) { return false; } // Limit to whitelisted packages if (whitelist[item.website] && item.name !== whitelist[item.website]) { return false; } return true; }); return list; }
javascript
function (items) { if (!config.ignoreDeprecatedPackages) { return items; } var list = _.filter(items, function (item) { // Ignore packages if (ignore.indexOf(item.name) !== -1) { return false; } // Limit to whitelisted packages if (whitelist[item.website] && item.name !== whitelist[item.website]) { return false; } return true; }); return list; }
[ "function", "(", "items", ")", "{", "if", "(", "!", "config", ".", "ignoreDeprecatedPackages", ")", "{", "return", "items", ";", "}", "var", "list", "=", "_", ".", "filter", "(", "items", ",", "function", "(", "item", ")", "{", "// Ignore packages", "if", "(", "ignore", ".", "indexOf", "(", "item", ".", "name", ")", "!==", "-", "1", ")", "{", "return", "false", ";", "}", "// Limit to whitelisted packages", "if", "(", "whitelist", "[", "item", ".", "website", "]", "&&", "item", ".", "name", "!==", "whitelist", "[", "item", ".", "website", "]", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", ")", ";", "return", "list", ";", "}" ]
Exclude ignoring packages
[ "Exclude", "ignoring", "packages" ]
d7875331f5d6f6ad0b7164d6116a341ac97f613f
https://github.com/rakuten-frontend/bower-browser/blob/d7875331f5d6f6ad0b7164d6116a341ac97f613f/client/assets/scripts/services/search.js#L133-L149
43,868
rakuten-frontend/bower-browser
client/assets/scripts/services/search.js
function (items, query, fields, exact) { var self = this; var isTarget = function (fieldName) { return fields.indexOf(fieldName) !== -1; }; if (query === '') { return items; } fields = fields || ['name', 'owner', 'description', 'keyword']; return _.filter(items, function (item) { if ((isTarget('name') && self.matchedInString(query, item.name, exact)) || (isTarget('owner') && self.matchedInString(query, item.owner, exact)) || (isTarget('description') && self.matchedInString(query, item.description, exact)) || (isTarget('keyword') && self.matchedInArray(query, item.keywords, exact))) { return true; } return false; }); }
javascript
function (items, query, fields, exact) { var self = this; var isTarget = function (fieldName) { return fields.indexOf(fieldName) !== -1; }; if (query === '') { return items; } fields = fields || ['name', 'owner', 'description', 'keyword']; return _.filter(items, function (item) { if ((isTarget('name') && self.matchedInString(query, item.name, exact)) || (isTarget('owner') && self.matchedInString(query, item.owner, exact)) || (isTarget('description') && self.matchedInString(query, item.description, exact)) || (isTarget('keyword') && self.matchedInArray(query, item.keywords, exact))) { return true; } return false; }); }
[ "function", "(", "items", ",", "query", ",", "fields", ",", "exact", ")", "{", "var", "self", "=", "this", ";", "var", "isTarget", "=", "function", "(", "fieldName", ")", "{", "return", "fields", ".", "indexOf", "(", "fieldName", ")", "!==", "-", "1", ";", "}", ";", "if", "(", "query", "===", "''", ")", "{", "return", "items", ";", "}", "fields", "=", "fields", "||", "[", "'name'", ",", "'owner'", ",", "'description'", ",", "'keyword'", "]", ";", "return", "_", ".", "filter", "(", "items", ",", "function", "(", "item", ")", "{", "if", "(", "(", "isTarget", "(", "'name'", ")", "&&", "self", ".", "matchedInString", "(", "query", ",", "item", ".", "name", ",", "exact", ")", ")", "||", "(", "isTarget", "(", "'owner'", ")", "&&", "self", ".", "matchedInString", "(", "query", ",", "item", ".", "owner", ",", "exact", ")", ")", "||", "(", "isTarget", "(", "'description'", ")", "&&", "self", ".", "matchedInString", "(", "query", ",", "item", ".", "description", ",", "exact", ")", ")", "||", "(", "isTarget", "(", "'keyword'", ")", "&&", "self", ".", "matchedInArray", "(", "query", ",", "item", ".", "keywords", ",", "exact", ")", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", ")", ";", "}" ]
Find items by query
[ "Find", "items", "by", "query" ]
d7875331f5d6f6ad0b7164d6116a341ac97f613f
https://github.com/rakuten-frontend/bower-browser/blob/d7875331f5d6f6ad0b7164d6116a341ac97f613f/client/assets/scripts/services/search.js#L177-L195
43,869
rakuten-frontend/bower-browser
client/assets/scripts/services/search.js
function (query, string, exact) { if (typeof string !== 'string' || string === '') { return false; } if (exact) { return string.toLowerCase() === query.toLowerCase(); } return string.toLowerCase().indexOf(query.toLowerCase()) !== -1; }
javascript
function (query, string, exact) { if (typeof string !== 'string' || string === '') { return false; } if (exact) { return string.toLowerCase() === query.toLowerCase(); } return string.toLowerCase().indexOf(query.toLowerCase()) !== -1; }
[ "function", "(", "query", ",", "string", ",", "exact", ")", "{", "if", "(", "typeof", "string", "!==", "'string'", "||", "string", "===", "''", ")", "{", "return", "false", ";", "}", "if", "(", "exact", ")", "{", "return", "string", ".", "toLowerCase", "(", ")", "===", "query", ".", "toLowerCase", "(", ")", ";", "}", "return", "string", ".", "toLowerCase", "(", ")", ".", "indexOf", "(", "query", ".", "toLowerCase", "(", ")", ")", "!==", "-", "1", ";", "}" ]
Search in string field
[ "Search", "in", "string", "field" ]
d7875331f5d6f6ad0b7164d6116a341ac97f613f
https://github.com/rakuten-frontend/bower-browser/blob/d7875331f5d6f6ad0b7164d6116a341ac97f613f/client/assets/scripts/services/search.js#L198-L206
43,870
rakuten-frontend/bower-browser
client/assets/scripts/services/search.js
function (query, array, exact) { if (!_.isArray(array) || array.length === 0) { return false; } return array.some(function (string) { if (exact) { return query.toLowerCase() === string.toLowerCase(); } return string.toLowerCase().indexOf(query.toLowerCase()) !== -1; }); }
javascript
function (query, array, exact) { if (!_.isArray(array) || array.length === 0) { return false; } return array.some(function (string) { if (exact) { return query.toLowerCase() === string.toLowerCase(); } return string.toLowerCase().indexOf(query.toLowerCase()) !== -1; }); }
[ "function", "(", "query", ",", "array", ",", "exact", ")", "{", "if", "(", "!", "_", ".", "isArray", "(", "array", ")", "||", "array", ".", "length", "===", "0", ")", "{", "return", "false", ";", "}", "return", "array", ".", "some", "(", "function", "(", "string", ")", "{", "if", "(", "exact", ")", "{", "return", "query", ".", "toLowerCase", "(", ")", "===", "string", ".", "toLowerCase", "(", ")", ";", "}", "return", "string", ".", "toLowerCase", "(", ")", ".", "indexOf", "(", "query", ".", "toLowerCase", "(", ")", ")", "!==", "-", "1", ";", "}", ")", ";", "}" ]
Search in array field
[ "Search", "in", "array", "field" ]
d7875331f5d6f6ad0b7164d6116a341ac97f613f
https://github.com/rakuten-frontend/bower-browser/blob/d7875331f5d6f6ad0b7164d6116a341ac97f613f/client/assets/scripts/services/search.js#L209-L219
43,871
rakuten-frontend/bower-browser
client/assets/scripts/services/search.js
function (items, query) { if (!config.exactMatch || !config.searchField.name) { return items; } var list = items; var match = _.findIndex(list, function (item) { return query.toLowerCase() === item.name.toLowerCase(); }); if (match !== -1) { list.splice(0, 0, list.splice(match, 1)[0]); } return list; }
javascript
function (items, query) { if (!config.exactMatch || !config.searchField.name) { return items; } var list = items; var match = _.findIndex(list, function (item) { return query.toLowerCase() === item.name.toLowerCase(); }); if (match !== -1) { list.splice(0, 0, list.splice(match, 1)[0]); } return list; }
[ "function", "(", "items", ",", "query", ")", "{", "if", "(", "!", "config", ".", "exactMatch", "||", "!", "config", ".", "searchField", ".", "name", ")", "{", "return", "items", ";", "}", "var", "list", "=", "items", ";", "var", "match", "=", "_", ".", "findIndex", "(", "list", ",", "function", "(", "item", ")", "{", "return", "query", ".", "toLowerCase", "(", ")", "===", "item", ".", "name", ".", "toLowerCase", "(", ")", ";", "}", ")", ";", "if", "(", "match", "!==", "-", "1", ")", "{", "list", ".", "splice", "(", "0", ",", "0", ",", "list", ".", "splice", "(", "match", ",", "1", ")", "[", "0", "]", ")", ";", "}", "return", "list", ";", "}" ]
Prioritize exact match
[ "Prioritize", "exact", "match" ]
d7875331f5d6f6ad0b7164d6116a341ac97f613f
https://github.com/rakuten-frontend/bower-browser/blob/d7875331f5d6f6ad0b7164d6116a341ac97f613f/client/assets/scripts/services/search.js#L233-L245
43,872
layerhq/node-layer-webhooks-services
src/receipts.js
processMessage
function processMessage(message) { var recipients = Object.keys(message.recipient_status).filter(function(userId) { return hook.receipts.reportForStatus.indexOf(message.recipient_status[userId]) !== -1; }); if (recipients.length) { var identities = [message.sender.user_id].concat(recipients); var identityHash = {}; if (!hook.receipts.identities) { createJob(message, recipients, {}); } else { if (!(hook.receipts.identities instanceof Function)) { hook.receipts.identities = getUserFromIdentities; } var getUser = hook.receipts.identities; var count = 0; identities.forEach(function(userId) { getUser(userId, function(err, data) { identityHash[userId] = data; count++; if (count === identities.length) createJob(message, recipients, identityHash); }) }); } } }
javascript
function processMessage(message) { var recipients = Object.keys(message.recipient_status).filter(function(userId) { return hook.receipts.reportForStatus.indexOf(message.recipient_status[userId]) !== -1; }); if (recipients.length) { var identities = [message.sender.user_id].concat(recipients); var identityHash = {}; if (!hook.receipts.identities) { createJob(message, recipients, {}); } else { if (!(hook.receipts.identities instanceof Function)) { hook.receipts.identities = getUserFromIdentities; } var getUser = hook.receipts.identities; var count = 0; identities.forEach(function(userId) { getUser(userId, function(err, data) { identityHash[userId] = data; count++; if (count === identities.length) createJob(message, recipients, identityHash); }) }); } } }
[ "function", "processMessage", "(", "message", ")", "{", "var", "recipients", "=", "Object", ".", "keys", "(", "message", ".", "recipient_status", ")", ".", "filter", "(", "function", "(", "userId", ")", "{", "return", "hook", ".", "receipts", ".", "reportForStatus", ".", "indexOf", "(", "message", ".", "recipient_status", "[", "userId", "]", ")", "!==", "-", "1", ";", "}", ")", ";", "if", "(", "recipients", ".", "length", ")", "{", "var", "identities", "=", "[", "message", ".", "sender", ".", "user_id", "]", ".", "concat", "(", "recipients", ")", ";", "var", "identityHash", "=", "{", "}", ";", "if", "(", "!", "hook", ".", "receipts", ".", "identities", ")", "{", "createJob", "(", "message", ",", "recipients", ",", "{", "}", ")", ";", "}", "else", "{", "if", "(", "!", "(", "hook", ".", "receipts", ".", "identities", "instanceof", "Function", ")", ")", "{", "hook", ".", "receipts", ".", "identities", "=", "getUserFromIdentities", ";", "}", "var", "getUser", "=", "hook", ".", "receipts", ".", "identities", ";", "var", "count", "=", "0", ";", "identities", ".", "forEach", "(", "function", "(", "userId", ")", "{", "getUser", "(", "userId", ",", "function", "(", "err", ",", "data", ")", "{", "identityHash", "[", "userId", "]", "=", "data", ";", "count", "++", ";", "if", "(", "count", "===", "identities", ".", "length", ")", "createJob", "(", "message", ",", "recipients", ",", "identityHash", ")", ";", "}", ")", "}", ")", ";", "}", "}", "}" ]
Process an individual Message and create a job if there are matching recipients.
[ "Process", "an", "individual", "Message", "and", "create", "a", "job", "if", "there", "are", "matching", "recipients", "." ]
7ef63df31fb5b769ebe57b8855806178e1ce8dd8
https://github.com/layerhq/node-layer-webhooks-services/blob/7ef63df31fb5b769ebe57b8855806178e1ce8dd8/src/receipts.js#L155-L180
43,873
serkanyersen/kwargsjs
kwargs.js
function() { var args = Array.prototype.slice.call(arguments, 0), org = args.shift(); return kwargs.apply(org, args); }
javascript
function() { var args = Array.prototype.slice.call(arguments, 0), org = args.shift(); return kwargs.apply(org, args); }
[ "function", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ",", "org", "=", "args", ".", "shift", "(", ")", ";", "return", "kwargs", ".", "apply", "(", "org", ",", "args", ")", ";", "}" ]
as a separate function for module loaders
[ "as", "a", "separate", "function", "for", "module", "loaders" ]
fa294ffea701d14977c5b2ded3c8c73e5cec5b04
https://github.com/serkanyersen/kwargsjs/blob/fa294ffea701d14977c5b2ded3c8c73e5cec5b04/kwargs.js#L72-L77
43,874
silas/swagger-framework
lib/docs/router.js
DocsRouter
function DocsRouter(docs, options) { debug('create docs router'); options = options || {}; this.docs = docs; this.prefix = options.prefix || '/'; }
javascript
function DocsRouter(docs, options) { debug('create docs router'); options = options || {}; this.docs = docs; this.prefix = options.prefix || '/'; }
[ "function", "DocsRouter", "(", "docs", ",", "options", ")", "{", "debug", "(", "'create docs router'", ")", ";", "options", "=", "options", "||", "{", "}", ";", "this", ".", "docs", "=", "docs", ";", "this", ".", "prefix", "=", "options", ".", "prefix", "||", "'/'", ";", "}" ]
Initialize a new `DocsRouter`. @param {Docs} docs @param {Object} options @api private
[ "Initialize", "a", "new", "DocsRouter", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/docs/router.js#L27-L34
43,875
silas/swagger-framework
lib/docs/router.js
function(path, handler) { var node = trie.define(path)[0]; if (typeof handler !== 'function') { throw new Error('invalid handler'); } node.handler = handler; }
javascript
function(path, handler) { var node = trie.define(path)[0]; if (typeof handler !== 'function') { throw new Error('invalid handler'); } node.handler = handler; }
[ "function", "(", "path", ",", "handler", ")", "{", "var", "node", "=", "trie", ".", "define", "(", "path", ")", "[", "0", "]", ";", "if", "(", "typeof", "handler", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "'invalid handler'", ")", ";", "}", "node", ".", "handler", "=", "handler", ";", "}" ]
check and define routes
[ "check", "and", "define", "routes" ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/docs/router.js#L60-L68
43,876
layerhq/node-layer-webhooks-services
src/register.js
verifyWebhook
function verifyWebhook(hookDef, webhook) { logger(hookDef.name + ': Webhook already registered: ' + webhook.id + ': ' + webhook.status); if (webhook.status !== 'active') { logger(hookDef.name + ': Enabling webhook'); webhooksClient.enable(webhook.id); } }
javascript
function verifyWebhook(hookDef, webhook) { logger(hookDef.name + ': Webhook already registered: ' + webhook.id + ': ' + webhook.status); if (webhook.status !== 'active') { logger(hookDef.name + ': Enabling webhook'); webhooksClient.enable(webhook.id); } }
[ "function", "verifyWebhook", "(", "hookDef", ",", "webhook", ")", "{", "logger", "(", "hookDef", ".", "name", "+", "': Webhook already registered: '", "+", "webhook", ".", "id", "+", "': '", "+", "webhook", ".", "status", ")", ";", "if", "(", "webhook", ".", "status", "!==", "'active'", ")", "{", "logger", "(", "hookDef", ".", "name", "+", "': Enabling webhook'", ")", ";", "webhooksClient", ".", "enable", "(", "webhook", ".", "id", ")", ";", "}", "}" ]
Verify that the webhook is active; activate it if its not. @param {Object} hookDef -- A webhook definition object @param {Object} webhook -- A webhook object from Layer
[ "Verify", "that", "the", "webhook", "is", "active", ";", "activate", "it", "if", "its", "not", "." ]
7ef63df31fb5b769ebe57b8855806178e1ce8dd8
https://github.com/layerhq/node-layer-webhooks-services/blob/7ef63df31fb5b769ebe57b8855806178e1ce8dd8/src/register.js#L56-L62
43,877
NickCis/react-data-ssr
packages/express-data-ssr/src/createFetch.js
createRequest
function createRequest(url, req, { method, query } = {}) { const request = { url, method: method || 'GET', query: query || {}, }; return new Proxy(req, { set: (target, name, value, receiver) => { request[name] = value; return true; }, get: (target, name) => { if (name in request) return request[name]; switch (name) { // TODO: case 'next': case 'params': case 'baseUrl': case 'originalUrl': case '_parsedUrl': return undefined; default: return target[name]; } }, }); }
javascript
function createRequest(url, req, { method, query } = {}) { const request = { url, method: method || 'GET', query: query || {}, }; return new Proxy(req, { set: (target, name, value, receiver) => { request[name] = value; return true; }, get: (target, name) => { if (name in request) return request[name]; switch (name) { // TODO: case 'next': case 'params': case 'baseUrl': case 'originalUrl': case '_parsedUrl': return undefined; default: return target[name]; } }, }); }
[ "function", "createRequest", "(", "url", ",", "req", ",", "{", "method", ",", "query", "}", "=", "{", "}", ")", "{", "const", "request", "=", "{", "url", ",", "method", ":", "method", "||", "'GET'", ",", "query", ":", "query", "||", "{", "}", ",", "}", ";", "return", "new", "Proxy", "(", "req", ",", "{", "set", ":", "(", "target", ",", "name", ",", "value", ",", "receiver", ")", "=>", "{", "request", "[", "name", "]", "=", "value", ";", "return", "true", ";", "}", ",", "get", ":", "(", "target", ",", "name", ")", "=>", "{", "if", "(", "name", "in", "request", ")", "return", "request", "[", "name", "]", ";", "switch", "(", "name", ")", "{", "// TODO:", "case", "'next'", ":", "case", "'params'", ":", "case", "'baseUrl'", ":", "case", "'originalUrl'", ":", "case", "'_parsedUrl'", ":", "return", "undefined", ";", "default", ":", "return", "target", "[", "name", "]", ";", "}", "}", ",", "}", ")", ";", "}" ]
Creates a Proxy object for the request. XXX: It only supports `GET`, but, will we need another method for SSR? @param {String} url - @param {Object} req - Express request object @param {String} method - GET @param {Object} query - Url query parameters @return {Proxy} Request object
[ "Creates", "a", "Proxy", "object", "for", "the", "request", "." ]
5271a04ed62e53a6a0fef09471f751e778aede10
https://github.com/NickCis/react-data-ssr/blob/5271a04ed62e53a6a0fef09471f751e778aede10/packages/express-data-ssr/src/createFetch.js#L14-L43
43,878
opendxl/opendxl-client-javascript
lib/client.js
addSubscription
function addSubscription (client, topic, messageType, callback, subscribeToTopic) { if (typeof (subscribeToTopic) === 'undefined') { subscribeToTopic = true } if (callback !== explicitSubscriptionCallback) { client._callbackManager.addCallback(messageType, topic, callback) } if (subscribeToTopic && topic) { var topicMessageTypes = client._subscriptionsByMessageType[topic] // Only subscribe for the topic with the broker if no prior // subscription has been established if (!topicMessageTypes) { if (client._mqttClient) { client._mqttClient.subscribe(topic) } topicMessageTypes = {} client._subscriptionsByMessageType[topic] = topicMessageTypes } var messageTypeCallbacks = topicMessageTypes[messageType] if (messageTypeCallbacks) { if (messageTypeCallbacks.indexOf(callback) < 0) { messageTypeCallbacks.push(callback) } } else { topicMessageTypes[messageType] = [callback] } } }
javascript
function addSubscription (client, topic, messageType, callback, subscribeToTopic) { if (typeof (subscribeToTopic) === 'undefined') { subscribeToTopic = true } if (callback !== explicitSubscriptionCallback) { client._callbackManager.addCallback(messageType, topic, callback) } if (subscribeToTopic && topic) { var topicMessageTypes = client._subscriptionsByMessageType[topic] // Only subscribe for the topic with the broker if no prior // subscription has been established if (!topicMessageTypes) { if (client._mqttClient) { client._mqttClient.subscribe(topic) } topicMessageTypes = {} client._subscriptionsByMessageType[topic] = topicMessageTypes } var messageTypeCallbacks = topicMessageTypes[messageType] if (messageTypeCallbacks) { if (messageTypeCallbacks.indexOf(callback) < 0) { messageTypeCallbacks.push(callback) } } else { topicMessageTypes[messageType] = [callback] } } }
[ "function", "addSubscription", "(", "client", ",", "topic", ",", "messageType", ",", "callback", ",", "subscribeToTopic", ")", "{", "if", "(", "typeof", "(", "subscribeToTopic", ")", "===", "'undefined'", ")", "{", "subscribeToTopic", "=", "true", "}", "if", "(", "callback", "!==", "explicitSubscriptionCallback", ")", "{", "client", ".", "_callbackManager", ".", "addCallback", "(", "messageType", ",", "topic", ",", "callback", ")", "}", "if", "(", "subscribeToTopic", "&&", "topic", ")", "{", "var", "topicMessageTypes", "=", "client", ".", "_subscriptionsByMessageType", "[", "topic", "]", "// Only subscribe for the topic with the broker if no prior", "// subscription has been established", "if", "(", "!", "topicMessageTypes", ")", "{", "if", "(", "client", ".", "_mqttClient", ")", "{", "client", ".", "_mqttClient", ".", "subscribe", "(", "topic", ")", "}", "topicMessageTypes", "=", "{", "}", "client", ".", "_subscriptionsByMessageType", "[", "topic", "]", "=", "topicMessageTypes", "}", "var", "messageTypeCallbacks", "=", "topicMessageTypes", "[", "messageType", "]", "if", "(", "messageTypeCallbacks", ")", "{", "if", "(", "messageTypeCallbacks", ".", "indexOf", "(", "callback", ")", "<", "0", ")", "{", "messageTypeCallbacks", ".", "push", "(", "callback", ")", "}", "}", "else", "{", "topicMessageTypes", "[", "messageType", "]", "=", "[", "callback", "]", "}", "}", "}" ]
Add a topic subscription. @private @param {Client} client - The {@link Client} instance to which the topic subscription should be added. @param {String} topic - Topic to subscribe to. An empty string or null value indicates that the callback should receive messages for all topics (no filtering). @param {(Number|String)} messageType - Type of DXL messages for which the callback should be invoked. Corresponds to one of the message type constants in the {@link Message} class - for example, {@link Message.MESSAGE_TYPE_RESPONSE}. @param {Function} callback - Callback function which should be invoked for a matching message. The first argument passed to the callback function is the DXL Message object. @param {Boolean} [subscribeToTopic=true] - Whether or not to subscribe for the topic with the broker.
[ "Add", "a", "topic", "subscription", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/client.js#L183-L212
43,879
opendxl/opendxl-client-javascript
lib/client.js
removeSubscription
function removeSubscription (client, topic, messageType, callback) { if (callback !== explicitSubscriptionCallback) { client._callbackManager.removeCallback(messageType, topic, callback) } if (topic) { var subscriptionsByMessageType = client._subscriptionsByMessageType var topicMessageTypes = subscriptionsByMessageType[topic] if (topicMessageTypes) { // If a call to the client's unsubscribe() function for the topic // was made, unsubscribe regardless of any other active // callback-based subscriptions if (callback === explicitSubscriptionCallback) { delete subscriptionsByMessageType[topic] } else { var messageTypeCallbacks = topicMessageTypes[messageType] if (messageTypeCallbacks) { var callbackPosition = messageTypeCallbacks.indexOf(callback) if (callbackPosition > -1) { if (messageTypeCallbacks.length > 1) { // Remove the callback from the list of subscribers // for the topic and associated message type messageTypeCallbacks.splice(callbackPosition, 1) } else { if (Object.keys(topicMessageTypes).length > 1) { // Remove the message type entry since no more callbacks // are registered for the topic delete topicMessageTypes[messageType] } else { // Remove the topic entry since no more message types are // registered for it delete subscriptionsByMessageType[topic] } } } } } if (client._mqttClient && !subscriptionsByMessageType[topic]) { client._mqttClient.unsubscribe(topic) } } } }
javascript
function removeSubscription (client, topic, messageType, callback) { if (callback !== explicitSubscriptionCallback) { client._callbackManager.removeCallback(messageType, topic, callback) } if (topic) { var subscriptionsByMessageType = client._subscriptionsByMessageType var topicMessageTypes = subscriptionsByMessageType[topic] if (topicMessageTypes) { // If a call to the client's unsubscribe() function for the topic // was made, unsubscribe regardless of any other active // callback-based subscriptions if (callback === explicitSubscriptionCallback) { delete subscriptionsByMessageType[topic] } else { var messageTypeCallbacks = topicMessageTypes[messageType] if (messageTypeCallbacks) { var callbackPosition = messageTypeCallbacks.indexOf(callback) if (callbackPosition > -1) { if (messageTypeCallbacks.length > 1) { // Remove the callback from the list of subscribers // for the topic and associated message type messageTypeCallbacks.splice(callbackPosition, 1) } else { if (Object.keys(topicMessageTypes).length > 1) { // Remove the message type entry since no more callbacks // are registered for the topic delete topicMessageTypes[messageType] } else { // Remove the topic entry since no more message types are // registered for it delete subscriptionsByMessageType[topic] } } } } } if (client._mqttClient && !subscriptionsByMessageType[topic]) { client._mqttClient.unsubscribe(topic) } } } }
[ "function", "removeSubscription", "(", "client", ",", "topic", ",", "messageType", ",", "callback", ")", "{", "if", "(", "callback", "!==", "explicitSubscriptionCallback", ")", "{", "client", ".", "_callbackManager", ".", "removeCallback", "(", "messageType", ",", "topic", ",", "callback", ")", "}", "if", "(", "topic", ")", "{", "var", "subscriptionsByMessageType", "=", "client", ".", "_subscriptionsByMessageType", "var", "topicMessageTypes", "=", "subscriptionsByMessageType", "[", "topic", "]", "if", "(", "topicMessageTypes", ")", "{", "// If a call to the client's unsubscribe() function for the topic", "// was made, unsubscribe regardless of any other active", "// callback-based subscriptions", "if", "(", "callback", "===", "explicitSubscriptionCallback", ")", "{", "delete", "subscriptionsByMessageType", "[", "topic", "]", "}", "else", "{", "var", "messageTypeCallbacks", "=", "topicMessageTypes", "[", "messageType", "]", "if", "(", "messageTypeCallbacks", ")", "{", "var", "callbackPosition", "=", "messageTypeCallbacks", ".", "indexOf", "(", "callback", ")", "if", "(", "callbackPosition", ">", "-", "1", ")", "{", "if", "(", "messageTypeCallbacks", ".", "length", ">", "1", ")", "{", "// Remove the callback from the list of subscribers", "// for the topic and associated message type", "messageTypeCallbacks", ".", "splice", "(", "callbackPosition", ",", "1", ")", "}", "else", "{", "if", "(", "Object", ".", "keys", "(", "topicMessageTypes", ")", ".", "length", ">", "1", ")", "{", "// Remove the message type entry since no more callbacks", "// are registered for the topic", "delete", "topicMessageTypes", "[", "messageType", "]", "}", "else", "{", "// Remove the topic entry since no more message types are", "// registered for it", "delete", "subscriptionsByMessageType", "[", "topic", "]", "}", "}", "}", "}", "}", "if", "(", "client", ".", "_mqttClient", "&&", "!", "subscriptionsByMessageType", "[", "topic", "]", ")", "{", "client", ".", "_mqttClient", ".", "unsubscribe", "(", "topic", ")", "}", "}", "}", "}" ]
Removes a topic subscription. @private @param {Client} client - The {@link Client} instance from which the topic subscription should be removed. @param {String} topic - Topic to unsubscribe from. @param {(Number|String)} messageType - Type of DXL messages for which the callback should be invoked. Corresponds to one of the message type constants in the {@link Message} class - for example, {@link Message.MESSAGE_TYPE_RESPONSE}. @param {Function} callback - Callback function which should be invoked for a matching message.
[ "Removes", "a", "topic", "subscription", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/client.js#L227-L269
43,880
opendxl/opendxl-client-javascript
lib/client.js
publish
function publish (client, topic, message) { if (client._mqttClient) { client._mqttClient.publish(topic, message) } else { throw new DxlError( 'Client not connected, unable to publish data to: ' + topic) } }
javascript
function publish (client, topic, message) { if (client._mqttClient) { client._mqttClient.publish(topic, message) } else { throw new DxlError( 'Client not connected, unable to publish data to: ' + topic) } }
[ "function", "publish", "(", "client", ",", "topic", ",", "message", ")", "{", "if", "(", "client", ".", "_mqttClient", ")", "{", "client", ".", "_mqttClient", ".", "publish", "(", "topic", ",", "message", ")", "}", "else", "{", "throw", "new", "DxlError", "(", "'Client not connected, unable to publish data to: '", "+", "topic", ")", "}", "}" ]
Publishes data to a specific topic. @private @param {Client} client - The {@link Client} instance to which the message should be published. @param {String} topic - Topic to publish message to. @param {(String|Buffer)} message - Message to publish. @throws {DxlError} If the MQTT client is not connected.
[ "Publishes", "data", "to", "a", "specific", "topic", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/client.js#L280-L287
43,881
andreypopp/xcss
lib/expression-compiler.js
compile
function compile(str, scope) { if (!/[\(\){}]/.exec(str)) return literal(str); var nodes = compile2(compile1(str), scope || {}); if (nodes.length === 0) return literal(''); return foldLiterals(nodes) .reduce(function(c, e) {return binaryExpression('+', c, e)}); }
javascript
function compile(str, scope) { if (!/[\(\){}]/.exec(str)) return literal(str); var nodes = compile2(compile1(str), scope || {}); if (nodes.length === 0) return literal(''); return foldLiterals(nodes) .reduce(function(c, e) {return binaryExpression('+', c, e)}); }
[ "function", "compile", "(", "str", ",", "scope", ")", "{", "if", "(", "!", "/", "[\\(\\){}]", "/", ".", "exec", "(", "str", ")", ")", "return", "literal", "(", "str", ")", ";", "var", "nodes", "=", "compile2", "(", "compile1", "(", "str", ")", ",", "scope", "||", "{", "}", ")", ";", "if", "(", "nodes", ".", "length", "===", "0", ")", "return", "literal", "(", "''", ")", ";", "return", "foldLiterals", "(", "nodes", ")", ".", "reduce", "(", "function", "(", "c", ",", "e", ")", "{", "return", "binaryExpression", "(", "'+'", ",", "c", ",", "e", ")", "}", ")", ";", "}" ]
Compile xCSS expression. @param {String} str @param {Object} scope
[ "Compile", "xCSS", "expression", "." ]
2beae072eb8c7e41e9434565bb8c3a0389c8053d
https://github.com/andreypopp/xcss/blob/2beae072eb8c7e41e9434565bb8c3a0389c8053d/lib/expression-compiler.js#L24-L32
43,882
andreypopp/xcss
lib/expression-compiler.js
foldLiterals
function foldLiterals(nodes) { return nodes.reduce(function(c, e) { if (e.type === 'Literal') { var last = c[c.length - 1]; if (last && last.type === 'Literal') { c.pop(); return c.concat(literal(last.value + e.value)); } } return c.concat(e); }, []) }
javascript
function foldLiterals(nodes) { return nodes.reduce(function(c, e) { if (e.type === 'Literal') { var last = c[c.length - 1]; if (last && last.type === 'Literal') { c.pop(); return c.concat(literal(last.value + e.value)); } } return c.concat(e); }, []) }
[ "function", "foldLiterals", "(", "nodes", ")", "{", "return", "nodes", ".", "reduce", "(", "function", "(", "c", ",", "e", ")", "{", "if", "(", "e", ".", "type", "===", "'Literal'", ")", "{", "var", "last", "=", "c", "[", "c", ".", "length", "-", "1", "]", ";", "if", "(", "last", "&&", "last", ".", "type", "===", "'Literal'", ")", "{", "c", ".", "pop", "(", ")", ";", "return", "c", ".", "concat", "(", "literal", "(", "last", ".", "value", "+", "e", ".", "value", ")", ")", ";", "}", "}", "return", "c", ".", "concat", "(", "e", ")", ";", "}", ",", "[", "]", ")", "}" ]
Fold adjacent string literals
[ "Fold", "adjacent", "string", "literals" ]
2beae072eb8c7e41e9434565bb8c3a0389c8053d
https://github.com/andreypopp/xcss/blob/2beae072eb8c7e41e9434565bb8c3a0389c8053d/lib/expression-compiler.js#L37-L48
43,883
andreypopp/xcss
lib/expression-compiler.js
compile1
function compile1(str) { if (!/[{}]/.exec(str)) return [literal(str)]; var depth = 0; var nodes = []; var m; var buffer = ''; while ((m = /[{}]/.exec(str)) && str.length > 0) { var chunk = str.substring(0, m.index); switch (m[0]) { case '{': depth += 1; if (depth === 1) { buffer += chunk; if (buffer.length > 0) nodes.push(literal(buffer)); buffer = ''; } else { buffer += chunk + '{'; } break; case '}': depth -= 1; if (depth === 0) { buffer += chunk; if (buffer.length > 0) nodes.push(utils.parseExpression(buffer)); buffer = ''; } else { buffer += chunk + '}'; } break; } str = str.substring(m.index + 1); } if (str.length > 0) nodes.push(literal(str)); return nodes; }
javascript
function compile1(str) { if (!/[{}]/.exec(str)) return [literal(str)]; var depth = 0; var nodes = []; var m; var buffer = ''; while ((m = /[{}]/.exec(str)) && str.length > 0) { var chunk = str.substring(0, m.index); switch (m[0]) { case '{': depth += 1; if (depth === 1) { buffer += chunk; if (buffer.length > 0) nodes.push(literal(buffer)); buffer = ''; } else { buffer += chunk + '{'; } break; case '}': depth -= 1; if (depth === 0) { buffer += chunk; if (buffer.length > 0) nodes.push(utils.parseExpression(buffer)); buffer = ''; } else { buffer += chunk + '}'; } break; } str = str.substring(m.index + 1); } if (str.length > 0) nodes.push(literal(str)); return nodes; }
[ "function", "compile1", "(", "str", ")", "{", "if", "(", "!", "/", "[{}]", "/", ".", "exec", "(", "str", ")", ")", "return", "[", "literal", "(", "str", ")", "]", ";", "var", "depth", "=", "0", ";", "var", "nodes", "=", "[", "]", ";", "var", "m", ";", "var", "buffer", "=", "''", ";", "while", "(", "(", "m", "=", "/", "[{}]", "/", ".", "exec", "(", "str", ")", ")", "&&", "str", ".", "length", ">", "0", ")", "{", "var", "chunk", "=", "str", ".", "substring", "(", "0", ",", "m", ".", "index", ")", ";", "switch", "(", "m", "[", "0", "]", ")", "{", "case", "'{'", ":", "depth", "+=", "1", ";", "if", "(", "depth", "===", "1", ")", "{", "buffer", "+=", "chunk", ";", "if", "(", "buffer", ".", "length", ">", "0", ")", "nodes", ".", "push", "(", "literal", "(", "buffer", ")", ")", ";", "buffer", "=", "''", ";", "}", "else", "{", "buffer", "+=", "chunk", "+", "'{'", ";", "}", "break", ";", "case", "'}'", ":", "depth", "-=", "1", ";", "if", "(", "depth", "===", "0", ")", "{", "buffer", "+=", "chunk", ";", "if", "(", "buffer", ".", "length", ">", "0", ")", "nodes", ".", "push", "(", "utils", ".", "parseExpression", "(", "buffer", ")", ")", ";", "buffer", "=", "''", ";", "}", "else", "{", "buffer", "+=", "chunk", "+", "'}'", ";", "}", "break", ";", "}", "str", "=", "str", ".", "substring", "(", "m", ".", "index", "+", "1", ")", ";", "}", "if", "(", "str", ".", "length", ">", "0", ")", "nodes", ".", "push", "(", "literal", "(", "str", ")", ")", ";", "return", "nodes", ";", "}" ]
Compile JS interpolations. @param {String} str
[ "Compile", "JS", "interpolations", "." ]
2beae072eb8c7e41e9434565bb8c3a0389c8053d
https://github.com/andreypopp/xcss/blob/2beae072eb8c7e41e9434565bb8c3a0389c8053d/lib/expression-compiler.js#L55-L94
43,884
andreypopp/xcss
lib/expression-compiler.js
compile2
function compile2(nodes, scope) { var toks = flatMap(nodes, function(expr) { return expr.type === 'Literal' ? tokenize2(expr.value) : expr; }); return parse2(toks, scope); }
javascript
function compile2(nodes, scope) { var toks = flatMap(nodes, function(expr) { return expr.type === 'Literal' ? tokenize2(expr.value) : expr; }); return parse2(toks, scope); }
[ "function", "compile2", "(", "nodes", ",", "scope", ")", "{", "var", "toks", "=", "flatMap", "(", "nodes", ",", "function", "(", "expr", ")", "{", "return", "expr", ".", "type", "===", "'Literal'", "?", "tokenize2", "(", "expr", ".", "value", ")", ":", "expr", ";", "}", ")", ";", "return", "parse2", "(", "toks", ",", "scope", ")", ";", "}" ]
Compile function calls and variable references @param {Array<Node>} nodes @param {Object} scope
[ "Compile", "function", "calls", "and", "variable", "references" ]
2beae072eb8c7e41e9434565bb8c3a0389c8053d
https://github.com/andreypopp/xcss/blob/2beae072eb8c7e41e9434565bb8c3a0389c8053d/lib/expression-compiler.js#L102-L107
43,885
silas/swagger-framework
lib/framework.js
Framework
function Framework(spec, options) { if (!(this instanceof Framework)) { return new Framework(spec, options); } debug('create framework', spec, options); spec = lodash.cloneDeep(spec || {}); options = lodash.cloneDeep(options || {}); spec = lodash.defaults(spec, { swaggerVersion: '1.2', apis: [], }); options = lodash.defaults(options, lodash.pick(spec, 'basePath') ); delete spec.basePath; schema.validateThrow('ResourceListing', spec); schema.validateThrow(frameworkOptions, options); if (spec.swaggerVersion !== '1.2') { throw new Error('swaggerVersion not supported: ' + spec.swaggerVersion); } this.spec = spec; this.options = options; this.docs = new Docs(this); this.router = new Router(this); this.apis = {}; this.middleware = {}; }
javascript
function Framework(spec, options) { if (!(this instanceof Framework)) { return new Framework(spec, options); } debug('create framework', spec, options); spec = lodash.cloneDeep(spec || {}); options = lodash.cloneDeep(options || {}); spec = lodash.defaults(spec, { swaggerVersion: '1.2', apis: [], }); options = lodash.defaults(options, lodash.pick(spec, 'basePath') ); delete spec.basePath; schema.validateThrow('ResourceListing', spec); schema.validateThrow(frameworkOptions, options); if (spec.swaggerVersion !== '1.2') { throw new Error('swaggerVersion not supported: ' + spec.swaggerVersion); } this.spec = spec; this.options = options; this.docs = new Docs(this); this.router = new Router(this); this.apis = {}; this.middleware = {}; }
[ "function", "Framework", "(", "spec", ",", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Framework", ")", ")", "{", "return", "new", "Framework", "(", "spec", ",", "options", ")", ";", "}", "debug", "(", "'create framework'", ",", "spec", ",", "options", ")", ";", "spec", "=", "lodash", ".", "cloneDeep", "(", "spec", "||", "{", "}", ")", ";", "options", "=", "lodash", ".", "cloneDeep", "(", "options", "||", "{", "}", ")", ";", "spec", "=", "lodash", ".", "defaults", "(", "spec", ",", "{", "swaggerVersion", ":", "'1.2'", ",", "apis", ":", "[", "]", ",", "}", ")", ";", "options", "=", "lodash", ".", "defaults", "(", "options", ",", "lodash", ".", "pick", "(", "spec", ",", "'basePath'", ")", ")", ";", "delete", "spec", ".", "basePath", ";", "schema", ".", "validateThrow", "(", "'ResourceListing'", ",", "spec", ")", ";", "schema", ".", "validateThrow", "(", "frameworkOptions", ",", "options", ")", ";", "if", "(", "spec", ".", "swaggerVersion", "!==", "'1.2'", ")", "{", "throw", "new", "Error", "(", "'swaggerVersion not supported: '", "+", "spec", ".", "swaggerVersion", ")", ";", "}", "this", ".", "spec", "=", "spec", ";", "this", ".", "options", "=", "options", ";", "this", ".", "docs", "=", "new", "Docs", "(", "this", ")", ";", "this", ".", "router", "=", "new", "Router", "(", "this", ")", ";", "this", ".", "apis", "=", "{", "}", ";", "this", ".", "middleware", "=", "{", "}", ";", "}" ]
Initialize a new `Framework`. @param {Object} spec @param {Object} options @api public
[ "Initialize", "a", "new", "Framework", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/framework.js#L30-L64
43,886
opendxl/opendxl-client-javascript
lib/_cli/cli-pki.js
fieldAsOption
function fieldAsOption (field) { var option = '' for (var i = 0; i < field.length; i++) { var c = field.charAt(i) if (c < 'a') { option = option + '-' + c.toLowerCase() } else { option += c } } return option }
javascript
function fieldAsOption (field) { var option = '' for (var i = 0; i < field.length; i++) { var c = field.charAt(i) if (c < 'a') { option = option + '-' + c.toLowerCase() } else { option += c } } return option }
[ "function", "fieldAsOption", "(", "field", ")", "{", "var", "option", "=", "''", "for", "(", "var", "i", "=", "0", ";", "i", "<", "field", ".", "length", ";", "i", "++", ")", "{", "var", "c", "=", "field", ".", "charAt", "(", "i", ")", "if", "(", "c", "<", "'a'", ")", "{", "option", "=", "option", "+", "'-'", "+", "c", ".", "toLowerCase", "(", ")", "}", "else", "{", "option", "+=", "c", "}", "}", "return", "option", "}" ]
Converts a camelCase field name to lowercase hyphen-delimited format for use as a command-line option. For example, this method would convert 'optionName' to 'option-name'. @param {String} field - Name of the field to convert. @returns {String} Field name in lowercase hyphen-delimited format.
[ "Converts", "a", "camelCase", "field", "name", "to", "lowercase", "hyphen", "-", "delimited", "format", "for", "use", "as", "a", "command", "-", "line", "option", ".", "For", "example", "this", "method", "would", "convert", "optionName", "to", "option", "-", "name", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_cli/cli-pki.js#L21-L32
43,887
opendxl/opendxl-client-javascript
lib/_cli/cli-pki.js
function (command) { command.option('--opensslbin <file>', 'Location of the OpenSSL executable that the command uses. If not ' + 'specified, the command attempts to find an OpenSSL executable in ' + 'the current environment path.') command.option('-s, --san [value]', 'add Subject Alternative Name(s) to the CSR', sanOption, []) command.option('-P, --passphrase [pass]', 'Password for the private key. If specified with no value, prompts ' + 'for the value.') Object.keys(pki.SUBJECT_ATTRIBUTES).forEach(function (key) { var attributeInfo = pki.SUBJECT_ATTRIBUTES[key] var optionName = fieldAsOption(key) var optionValue = attributeInfo.optionValue || optionName.toLowerCase() command.option('--' + fieldAsOption(key) + ' <' + optionValue + '>', attributeInfo.description) }) return command }
javascript
function (command) { command.option('--opensslbin <file>', 'Location of the OpenSSL executable that the command uses. If not ' + 'specified, the command attempts to find an OpenSSL executable in ' + 'the current environment path.') command.option('-s, --san [value]', 'add Subject Alternative Name(s) to the CSR', sanOption, []) command.option('-P, --passphrase [pass]', 'Password for the private key. If specified with no value, prompts ' + 'for the value.') Object.keys(pki.SUBJECT_ATTRIBUTES).forEach(function (key) { var attributeInfo = pki.SUBJECT_ATTRIBUTES[key] var optionName = fieldAsOption(key) var optionValue = attributeInfo.optionValue || optionName.toLowerCase() command.option('--' + fieldAsOption(key) + ' <' + optionValue + '>', attributeInfo.description) }) return command }
[ "function", "(", "command", ")", "{", "command", ".", "option", "(", "'--opensslbin <file>'", ",", "'Location of the OpenSSL executable that the command uses. If not '", "+", "'specified, the command attempts to find an OpenSSL executable in '", "+", "'the current environment path.'", ")", "command", ".", "option", "(", "'-s, --san [value]'", ",", "'add Subject Alternative Name(s) to the CSR'", ",", "sanOption", ",", "[", "]", ")", "command", ".", "option", "(", "'-P, --passphrase [pass]'", ",", "'Password for the private key. If specified with no value, prompts '", "+", "'for the value.'", ")", "Object", ".", "keys", "(", "pki", ".", "SUBJECT_ATTRIBUTES", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "var", "attributeInfo", "=", "pki", ".", "SUBJECT_ATTRIBUTES", "[", "key", "]", "var", "optionName", "=", "fieldAsOption", "(", "key", ")", "var", "optionValue", "=", "attributeInfo", ".", "optionValue", "||", "optionName", ".", "toLowerCase", "(", ")", "command", ".", "option", "(", "'--'", "+", "fieldAsOption", "(", "key", ")", "+", "' <'", "+", "optionValue", "+", "'>'", ",", "attributeInfo", ".", "description", ")", "}", ")", "return", "command", "}" ]
Appends options related to the use of PKI utilities to a Commander-based command. @param {Command} command - The Commander command to append options onto. @returns {Command}
[ "Appends", "options", "related", "to", "the", "use", "of", "PKI", "utilities", "to", "a", "Commander", "-", "based", "command", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_cli/cli-pki.js#L55-L73
43,888
opendxl/opendxl-client-javascript
lib/_cli/cli-pki.js
function (command, responseCallback) { if (command.passphrase === true) { cliUtil.getValueFromPrompt('private key passphrase', true, function (error, passphrase) { if (error) { provisionUtil.invokeCallback(error, responseCallback, command.verbosity) } else { command.passphrase = passphrase provisionUtil.invokeCallback(null, responseCallback) } } ) } else { provisionUtil.invokeCallback(null, responseCallback) } }
javascript
function (command, responseCallback) { if (command.passphrase === true) { cliUtil.getValueFromPrompt('private key passphrase', true, function (error, passphrase) { if (error) { provisionUtil.invokeCallback(error, responseCallback, command.verbosity) } else { command.passphrase = passphrase provisionUtil.invokeCallback(null, responseCallback) } } ) } else { provisionUtil.invokeCallback(null, responseCallback) } }
[ "function", "(", "command", ",", "responseCallback", ")", "{", "if", "(", "command", ".", "passphrase", "===", "true", ")", "{", "cliUtil", ".", "getValueFromPrompt", "(", "'private key passphrase'", ",", "true", ",", "function", "(", "error", ",", "passphrase", ")", "{", "if", "(", "error", ")", "{", "provisionUtil", ".", "invokeCallback", "(", "error", ",", "responseCallback", ",", "command", ".", "verbosity", ")", "}", "else", "{", "command", ".", "passphrase", "=", "passphrase", "provisionUtil", ".", "invokeCallback", "(", "null", ",", "responseCallback", ")", "}", "}", ")", "}", "else", "{", "provisionUtil", ".", "invokeCallback", "(", "null", ",", "responseCallback", ")", "}", "}" ]
Process the private key passphrase from the supplied Commander-based command. @param {Command} command - Commander-based command which contains options to use in generating the CSR and private key. @param {(String|Boolean)} [command.passphrase] - If `true`, prompt from the command line for the private key passphrase to use and store the entered value back to the `command.passphrase` property. @param {Function} [responseCallback] - Function to invoke with the result from private key passphrase processing. The first parameter in the callback is an `Error` instance if the attempt to obtain the passphrase fails.
[ "Process", "the", "private", "key", "passphrase", "from", "the", "supplied", "Commander", "-", "based", "command", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_cli/cli-pki.js#L87-L103
43,889
cast-org/figuration
js/util.js
CFW_transitionCssDuration
function CFW_transitionCssDuration($node) { var durationArray = [0]; // Set a min value -- otherwise get `Infinity` $node.each(function() { var durations = $node.css('transition-duration') || $node.css('-webkit-transition-duration') || $node.css('-moz-transition-duration') || $node.css('-ms-transition-duration') || $node.css('-o-transition-duration'); if (durations) { var times = durations.split(','); for (var i = times.length; i--;) { // Reverse loop should be faster durationArray = durationArray.concat(parseFloat(times[i])); } } }); var duration = Math.max.apply(Math, durationArray); // http://stackoverflow.com/a/1379560 duration = duration * 1000; // convert to milliseconds return duration; }
javascript
function CFW_transitionCssDuration($node) { var durationArray = [0]; // Set a min value -- otherwise get `Infinity` $node.each(function() { var durations = $node.css('transition-duration') || $node.css('-webkit-transition-duration') || $node.css('-moz-transition-duration') || $node.css('-ms-transition-duration') || $node.css('-o-transition-duration'); if (durations) { var times = durations.split(','); for (var i = times.length; i--;) { // Reverse loop should be faster durationArray = durationArray.concat(parseFloat(times[i])); } } }); var duration = Math.max.apply(Math, durationArray); // http://stackoverflow.com/a/1379560 duration = duration * 1000; // convert to milliseconds return duration; }
[ "function", "CFW_transitionCssDuration", "(", "$node", ")", "{", "var", "durationArray", "=", "[", "0", "]", ";", "// Set a min value -- otherwise get `Infinity`", "$node", ".", "each", "(", "function", "(", ")", "{", "var", "durations", "=", "$node", ".", "css", "(", "'transition-duration'", ")", "||", "$node", ".", "css", "(", "'-webkit-transition-duration'", ")", "||", "$node", ".", "css", "(", "'-moz-transition-duration'", ")", "||", "$node", ".", "css", "(", "'-ms-transition-duration'", ")", "||", "$node", ".", "css", "(", "'-o-transition-duration'", ")", ";", "if", "(", "durations", ")", "{", "var", "times", "=", "durations", ".", "split", "(", "','", ")", ";", "for", "(", "var", "i", "=", "times", ".", "length", ";", "i", "--", ";", ")", "{", "// Reverse loop should be faster", "durationArray", "=", "durationArray", ".", "concat", "(", "parseFloat", "(", "times", "[", "i", "]", ")", ")", ";", "}", "}", "}", ")", ";", "var", "duration", "=", "Math", ".", "max", ".", "apply", "(", "Math", ",", "durationArray", ")", ";", "// http://stackoverflow.com/a/1379560", "duration", "=", "duration", "*", "1000", ";", "// convert to milliseconds", "return", "duration", ";", "}" ]
Get longest CSS transition duration
[ "Get", "longest", "CSS", "transition", "duration" ]
c82f491ebccb477f7e1c945bfff61c2340afe1ac
https://github.com/cast-org/figuration/blob/c82f491ebccb477f7e1c945bfff61c2340afe1ac/js/util.js#L62-L78
43,890
jeffbski/autoflow
dist/autoflow.js
nameTasks
function nameTasks(tasks) { //name tasks that are not already named, validation done elsewhere, ret map var namesMap = tasks.reduce(function (map, t) { if (t.name) { map[t.name] = t; } return map; }, {}); tasks.forEach(function (t, idx) { if (!t.name) { //not already named var name = fName(t.f); if (!name) name = sprintf(DEFAULT_TASK_NAME, idx); if (!name || namesMap[name]) { name = sprintf('%s_%s', name, idx); //if empty or already used, postfix with _idx } t.name = name; namesMap[name] = t; } }); return namesMap; }
javascript
function nameTasks(tasks) { //name tasks that are not already named, validation done elsewhere, ret map var namesMap = tasks.reduce(function (map, t) { if (t.name) { map[t.name] = t; } return map; }, {}); tasks.forEach(function (t, idx) { if (!t.name) { //not already named var name = fName(t.f); if (!name) name = sprintf(DEFAULT_TASK_NAME, idx); if (!name || namesMap[name]) { name = sprintf('%s_%s', name, idx); //if empty or already used, postfix with _idx } t.name = name; namesMap[name] = t; } }); return namesMap; }
[ "function", "nameTasks", "(", "tasks", ")", "{", "//name tasks that are not already named, validation done elsewhere, ret map", "var", "namesMap", "=", "tasks", ".", "reduce", "(", "function", "(", "map", ",", "t", ")", "{", "if", "(", "t", ".", "name", ")", "{", "map", "[", "t", ".", "name", "]", "=", "t", ";", "}", "return", "map", ";", "}", ",", "{", "}", ")", ";", "tasks", ".", "forEach", "(", "function", "(", "t", ",", "idx", ")", "{", "if", "(", "!", "t", ".", "name", ")", "{", "//not already named", "var", "name", "=", "fName", "(", "t", ".", "f", ")", ";", "if", "(", "!", "name", ")", "name", "=", "sprintf", "(", "DEFAULT_TASK_NAME", ",", "idx", ")", ";", "if", "(", "!", "name", "||", "namesMap", "[", "name", "]", ")", "{", "name", "=", "sprintf", "(", "'%s_%s'", ",", "name", ",", "idx", ")", ";", "//if empty or already used, postfix with _idx", "}", "t", ".", "name", "=", "name", ";", "namesMap", "[", "name", "]", "=", "t", ";", "}", "}", ")", ";", "return", "namesMap", ";", "}" ]
Name tasks that are not already named. Prenamed task uniquness validation will be done in validate. This modifies the tasks with the new names. @returns map of names to tasks
[ "Name", "tasks", "that", "are", "not", "already", "named", ".", "Prenamed", "task", "uniquness", "validation", "will", "be", "done", "in", "validate", "." ]
aa30f6e6c2e74aa72a018c65698acac3fb478cbb
https://github.com/jeffbski/autoflow/blob/aa30f6e6c2e74aa72a018c65698acac3fb478cbb/dist/autoflow.js#L2133-L2150
43,891
jeffbski/autoflow
dist/autoflow.js
validate
function validate(ast) { if (!ast || !ast.inParams || !ast.tasks || !ast.outTask) return [AST_IS_OBJECT]; var errors = []; errors = errors.concat(validateInParams(ast.inParams)); errors = errors.concat(validateTasks(ast.tasks)); errors = errors.concat(validateTaskNamesUnique(ast.tasks)); errors = errors.concat(taskUtil.validateOutTask(ast.outTask)); errors = errors.concat(validateLocals(ast.locals)); if (errors.length === 0) { // if no errors do additional validation if (ast.outTask.type !== 'finalcbFirst') errors = errors.concat(validateOuputsUnique(ast.tasks)); errors = errors.concat(taskUtil.validateLocalFunctions(ast.inParams, ast.tasks, ast.locals)); errors = errors.concat(validateNoMissingNames(ast)); } return errors; }
javascript
function validate(ast) { if (!ast || !ast.inParams || !ast.tasks || !ast.outTask) return [AST_IS_OBJECT]; var errors = []; errors = errors.concat(validateInParams(ast.inParams)); errors = errors.concat(validateTasks(ast.tasks)); errors = errors.concat(validateTaskNamesUnique(ast.tasks)); errors = errors.concat(taskUtil.validateOutTask(ast.outTask)); errors = errors.concat(validateLocals(ast.locals)); if (errors.length === 0) { // if no errors do additional validation if (ast.outTask.type !== 'finalcbFirst') errors = errors.concat(validateOuputsUnique(ast.tasks)); errors = errors.concat(taskUtil.validateLocalFunctions(ast.inParams, ast.tasks, ast.locals)); errors = errors.concat(validateNoMissingNames(ast)); } return errors; }
[ "function", "validate", "(", "ast", ")", "{", "if", "(", "!", "ast", "||", "!", "ast", ".", "inParams", "||", "!", "ast", ".", "tasks", "||", "!", "ast", ".", "outTask", ")", "return", "[", "AST_IS_OBJECT", "]", ";", "var", "errors", "=", "[", "]", ";", "errors", "=", "errors", ".", "concat", "(", "validateInParams", "(", "ast", ".", "inParams", ")", ")", ";", "errors", "=", "errors", ".", "concat", "(", "validateTasks", "(", "ast", ".", "tasks", ")", ")", ";", "errors", "=", "errors", ".", "concat", "(", "validateTaskNamesUnique", "(", "ast", ".", "tasks", ")", ")", ";", "errors", "=", "errors", ".", "concat", "(", "taskUtil", ".", "validateOutTask", "(", "ast", ".", "outTask", ")", ")", ";", "errors", "=", "errors", ".", "concat", "(", "validateLocals", "(", "ast", ".", "locals", ")", ")", ";", "if", "(", "errors", ".", "length", "===", "0", ")", "{", "// if no errors do additional validation", "if", "(", "ast", ".", "outTask", ".", "type", "!==", "'finalcbFirst'", ")", "errors", "=", "errors", ".", "concat", "(", "validateOuputsUnique", "(", "ast", ".", "tasks", ")", ")", ";", "errors", "=", "errors", ".", "concat", "(", "taskUtil", ".", "validateLocalFunctions", "(", "ast", ".", "inParams", ",", "ast", ".", "tasks", ",", "ast", ".", "locals", ")", ")", ";", "errors", "=", "errors", ".", "concat", "(", "validateNoMissingNames", "(", "ast", ")", ")", ";", "}", "return", "errors", ";", "}" ]
validate the AST return Errors @example var validate = require('./validate'); var errors = validate(ast); @returns array of errors, could be empty
[ "validate", "the", "AST", "return", "Errors" ]
aa30f6e6c2e74aa72a018c65698acac3fb478cbb
https://github.com/jeffbski/autoflow/blob/aa30f6e6c2e74aa72a018c65698acac3fb478cbb/dist/autoflow.js#L2280-L2294
43,892
jeffbski/autoflow
dist/autoflow.js
validateNoMissingNames
function validateNoMissingNames(ast) { var errors = []; var names = {}; if (ast.locals) { names = Object.keys(ast.locals).reduce(function (accum, k) { // start with locals accum[k] = true; return accum; }, names); } ast.inParams.reduce(function (accum, p) { // add input params accum[p] = true; return accum; }, names); ast.tasks.reduce(function (accum, t) { // add task outputs return t.out.reduce(function (innerAccum, p) { innerAccum[p] = true; return innerAccum; }, accum); }, names); // now we have all possible provided vars, check task inputs are accounted for ast.tasks.reduce(function (accum, t) { // for all tasks return t.a.reduce(function (innerAccum, p) { // for all in params, except property if (!isLiteralOrProp(p) && !names[p]) innerAccum.push(sprintf(MISSING_INPUTS, p)); // add error if missing return innerAccum; }, accum); }, errors); // now check the final task outputs ast.outTask.a.reduce(function (accum, p) { // for final task out params if (!isLiteralOrProp(p) && !names[p]) accum.push(sprintf(MISSING_INPUTS, p)); // add error if missing return accum; }, errors); return errors; }
javascript
function validateNoMissingNames(ast) { var errors = []; var names = {}; if (ast.locals) { names = Object.keys(ast.locals).reduce(function (accum, k) { // start with locals accum[k] = true; return accum; }, names); } ast.inParams.reduce(function (accum, p) { // add input params accum[p] = true; return accum; }, names); ast.tasks.reduce(function (accum, t) { // add task outputs return t.out.reduce(function (innerAccum, p) { innerAccum[p] = true; return innerAccum; }, accum); }, names); // now we have all possible provided vars, check task inputs are accounted for ast.tasks.reduce(function (accum, t) { // for all tasks return t.a.reduce(function (innerAccum, p) { // for all in params, except property if (!isLiteralOrProp(p) && !names[p]) innerAccum.push(sprintf(MISSING_INPUTS, p)); // add error if missing return innerAccum; }, accum); }, errors); // now check the final task outputs ast.outTask.a.reduce(function (accum, p) { // for final task out params if (!isLiteralOrProp(p) && !names[p]) accum.push(sprintf(MISSING_INPUTS, p)); // add error if missing return accum; }, errors); return errors; }
[ "function", "validateNoMissingNames", "(", "ast", ")", "{", "var", "errors", "=", "[", "]", ";", "var", "names", "=", "{", "}", ";", "if", "(", "ast", ".", "locals", ")", "{", "names", "=", "Object", ".", "keys", "(", "ast", ".", "locals", ")", ".", "reduce", "(", "function", "(", "accum", ",", "k", ")", "{", "// start with locals", "accum", "[", "k", "]", "=", "true", ";", "return", "accum", ";", "}", ",", "names", ")", ";", "}", "ast", ".", "inParams", ".", "reduce", "(", "function", "(", "accum", ",", "p", ")", "{", "// add input params", "accum", "[", "p", "]", "=", "true", ";", "return", "accum", ";", "}", ",", "names", ")", ";", "ast", ".", "tasks", ".", "reduce", "(", "function", "(", "accum", ",", "t", ")", "{", "// add task outputs", "return", "t", ".", "out", ".", "reduce", "(", "function", "(", "innerAccum", ",", "p", ")", "{", "innerAccum", "[", "p", "]", "=", "true", ";", "return", "innerAccum", ";", "}", ",", "accum", ")", ";", "}", ",", "names", ")", ";", "// now we have all possible provided vars, check task inputs are accounted for", "ast", ".", "tasks", ".", "reduce", "(", "function", "(", "accum", ",", "t", ")", "{", "// for all tasks", "return", "t", ".", "a", ".", "reduce", "(", "function", "(", "innerAccum", ",", "p", ")", "{", "// for all in params, except property", "if", "(", "!", "isLiteralOrProp", "(", "p", ")", "&&", "!", "names", "[", "p", "]", ")", "innerAccum", ".", "push", "(", "sprintf", "(", "MISSING_INPUTS", ",", "p", ")", ")", ";", "// add error if missing", "return", "innerAccum", ";", "}", ",", "accum", ")", ";", "}", ",", "errors", ")", ";", "// now check the final task outputs", "ast", ".", "outTask", ".", "a", ".", "reduce", "(", "function", "(", "accum", ",", "p", ")", "{", "// for final task out params", "if", "(", "!", "isLiteralOrProp", "(", "p", ")", "&&", "!", "names", "[", "p", "]", ")", "accum", ".", "push", "(", "sprintf", "(", "MISSING_INPUTS", ",", "p", ")", ")", ";", "// add error if missing", "return", "accum", ";", "}", ",", "errors", ")", ";", "return", "errors", ";", "}" ]
validate there are no missing or mispelled param names in any task inputs or the final task output @return array of errors, or empty array if none
[ "validate", "there", "are", "no", "missing", "or", "mispelled", "param", "names", "in", "any", "task", "inputs", "or", "the", "final", "task", "output" ]
aa30f6e6c2e74aa72a018c65698acac3fb478cbb
https://github.com/jeffbski/autoflow/blob/aa30f6e6c2e74aa72a018c65698acac3fb478cbb/dist/autoflow.js#L2361-L2395
43,893
jeffbski/autoflow
dist/autoflow.js
filterOutTrailingCbParam
function filterOutTrailingCbParam(args) { // if has trailing cb | callback param, filter it out if (args.length && args[args.length - 1].match(CB_NAMES_RE)) args.pop(); return args; }
javascript
function filterOutTrailingCbParam(args) { // if has trailing cb | callback param, filter it out if (args.length && args[args.length - 1].match(CB_NAMES_RE)) args.pop(); return args; }
[ "function", "filterOutTrailingCbParam", "(", "args", ")", "{", "// if has trailing cb | callback param, filter it out", "if", "(", "args", ".", "length", "&&", "args", "[", "args", ".", "length", "-", "1", "]", ".", "match", "(", "CB_NAMES_RE", ")", ")", "args", ".", "pop", "(", ")", ";", "return", "args", ";", "}" ]
err, ERR, Err, ...
[ "err", "ERR", "Err", "..." ]
aa30f6e6c2e74aa72a018c65698acac3fb478cbb
https://github.com/jeffbski/autoflow/blob/aa30f6e6c2e74aa72a018c65698acac3fb478cbb/dist/autoflow.js#L2669-L2672
43,894
tonistiigi/styler
support/dryice.js
CommonJsProject
function CommonJsProject(opts) { this.roots = opts.roots; this.textPluginPattern = opts.textPluginPattern || /^text!/; opts.roots = this.roots.map(function(root) { if (!copy.isDirectory(root)) { throw new Error('Each commonjs root should be a directory: ' + root); } return ensureTrailingSlash(root); }, this); // A module is a Location that also has dep this.currentModules = {}; this.ignoredModules = {}; }
javascript
function CommonJsProject(opts) { this.roots = opts.roots; this.textPluginPattern = opts.textPluginPattern || /^text!/; opts.roots = this.roots.map(function(root) { if (!copy.isDirectory(root)) { throw new Error('Each commonjs root should be a directory: ' + root); } return ensureTrailingSlash(root); }, this); // A module is a Location that also has dep this.currentModules = {}; this.ignoredModules = {}; }
[ "function", "CommonJsProject", "(", "opts", ")", "{", "this", ".", "roots", "=", "opts", ".", "roots", ";", "this", ".", "textPluginPattern", "=", "opts", ".", "textPluginPattern", "||", "/", "^text!", "/", ";", "opts", ".", "roots", "=", "this", ".", "roots", ".", "map", "(", "function", "(", "root", ")", "{", "if", "(", "!", "copy", ".", "isDirectory", "(", "root", ")", ")", "{", "throw", "new", "Error", "(", "'Each commonjs root should be a directory: '", "+", "root", ")", ";", "}", "return", "ensureTrailingSlash", "(", "root", ")", ";", "}", ",", "this", ")", ";", "// A module is a Location that also has dep", "this", ".", "currentModules", "=", "{", "}", ";", "this", ".", "ignoredModules", "=", "{", "}", ";", "}" ]
Keep track of the files in a project
[ "Keep", "track", "of", "the", "files", "in", "a", "project" ]
f20dd9621f671b77cbb660d35327e007e8a56e2a
https://github.com/tonistiigi/styler/blob/f20dd9621f671b77cbb660d35327e007e8a56e2a/support/dryice.js#L659-L673
43,895
silas/swagger-framework
lib/schema/find.js
model
function model(obj) { if (!obj) return; if (obj.$ref) { obj = obj.$ref; } else if (obj.type === 'array' && obj.items && obj.items.$ref) { obj = obj.items.$ref; } else if (obj.type) { obj = obj.type; } // ensure valid type if (typeof obj !== 'string') return; // ensure non-builtin type if (constants.notModel.indexOf(obj) >= 0) return; return obj; }
javascript
function model(obj) { if (!obj) return; if (obj.$ref) { obj = obj.$ref; } else if (obj.type === 'array' && obj.items && obj.items.$ref) { obj = obj.items.$ref; } else if (obj.type) { obj = obj.type; } // ensure valid type if (typeof obj !== 'string') return; // ensure non-builtin type if (constants.notModel.indexOf(obj) >= 0) return; return obj; }
[ "function", "model", "(", "obj", ")", "{", "if", "(", "!", "obj", ")", "return", ";", "if", "(", "obj", ".", "$ref", ")", "{", "obj", "=", "obj", ".", "$ref", ";", "}", "else", "if", "(", "obj", ".", "type", "===", "'array'", "&&", "obj", ".", "items", "&&", "obj", ".", "items", ".", "$ref", ")", "{", "obj", "=", "obj", ".", "items", ".", "$ref", ";", "}", "else", "if", "(", "obj", ".", "type", ")", "{", "obj", "=", "obj", ".", "type", ";", "}", "// ensure valid type", "if", "(", "typeof", "obj", "!==", "'string'", ")", "return", ";", "// ensure non-builtin type", "if", "(", "constants", ".", "notModel", ".", "indexOf", "(", "obj", ")", ">=", "0", ")", "return", ";", "return", "obj", ";", "}" ]
Find model.
[ "Find", "model", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/schema/find.js#L19-L36
43,896
silas/swagger-framework
lib/schema/find.js
models
function models(spec) { var ids = {}; if (!spec) return ids; var add = function(obj) { var type = model(obj); if (type) ids[type] = true; }; add(spec); if (spec.properties) { lodash.forOwn(spec.properties, function(p) { add(p); }); } else if (spec.parameters) { spec.parameters.forEach(function(p) { add(p); }); } return Object.keys(ids); }
javascript
function models(spec) { var ids = {}; if (!spec) return ids; var add = function(obj) { var type = model(obj); if (type) ids[type] = true; }; add(spec); if (spec.properties) { lodash.forOwn(spec.properties, function(p) { add(p); }); } else if (spec.parameters) { spec.parameters.forEach(function(p) { add(p); }); } return Object.keys(ids); }
[ "function", "models", "(", "spec", ")", "{", "var", "ids", "=", "{", "}", ";", "if", "(", "!", "spec", ")", "return", "ids", ";", "var", "add", "=", "function", "(", "obj", ")", "{", "var", "type", "=", "model", "(", "obj", ")", ";", "if", "(", "type", ")", "ids", "[", "type", "]", "=", "true", ";", "}", ";", "add", "(", "spec", ")", ";", "if", "(", "spec", ".", "properties", ")", "{", "lodash", ".", "forOwn", "(", "spec", ".", "properties", ",", "function", "(", "p", ")", "{", "add", "(", "p", ")", ";", "}", ")", ";", "}", "else", "if", "(", "spec", ".", "parameters", ")", "{", "spec", ".", "parameters", ".", "forEach", "(", "function", "(", "p", ")", "{", "add", "(", "p", ")", ";", "}", ")", ";", "}", "return", "Object", ".", "keys", "(", "ids", ")", ";", "}" ]
Find models.
[ "Find", "models", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/schema/find.js#L42-L61
43,897
layerhq/node-layer-webhooks-services
examples/basic-services/conversation-delete.js
getDescription
function getDescription(conversation) { if (conversation.metadata.conversationersationName) { return 'The Conversation ' + conversation.metadata.conversationersationName + ' has been deleted'; } else { return 'The Conversation with ' + conversation.participants.join(', ').replace(/(.*),(.*)/, '$1 and$2') + ' has been deleted'; } }
javascript
function getDescription(conversation) { if (conversation.metadata.conversationersationName) { return 'The Conversation ' + conversation.metadata.conversationersationName + ' has been deleted'; } else { return 'The Conversation with ' + conversation.participants.join(', ').replace(/(.*),(.*)/, '$1 and$2') + ' has been deleted'; } }
[ "function", "getDescription", "(", "conversation", ")", "{", "if", "(", "conversation", ".", "metadata", ".", "conversationersationName", ")", "{", "return", "'The Conversation '", "+", "conversation", ".", "metadata", ".", "conversationersationName", "+", "' has been deleted'", ";", "}", "else", "{", "return", "'The Conversation with '", "+", "conversation", ".", "participants", ".", "join", "(", "', '", ")", ".", "replace", "(", "/", "(.*),(.*)", "/", ",", "'$1 and$2'", ")", "+", "' has been deleted'", ";", "}", "}" ]
Return a message body describing the deletion
[ "Return", "a", "message", "body", "describing", "the", "deletion" ]
7ef63df31fb5b769ebe57b8855806178e1ce8dd8
https://github.com/layerhq/node-layer-webhooks-services/blob/7ef63df31fb5b769ebe57b8855806178e1ce8dd8/examples/basic-services/conversation-delete.js#L53-L61
43,898
opendxl/opendxl-client-javascript
lib/_cli/cli-generate-csr.js
cliGenerateCsr
function cliGenerateCsr (configDir, commonOrCsrFileName, command) { cliPki.processPrivateKeyPassphrase(command, function (error) { if (error) { provisionUtil.invokeCallback(error, command.doneCallback, command.verbosity) } else { pki.generatePrivateKeyAndCsr(configDir, commonOrCsrFileName, command) } } ) }
javascript
function cliGenerateCsr (configDir, commonOrCsrFileName, command) { cliPki.processPrivateKeyPassphrase(command, function (error) { if (error) { provisionUtil.invokeCallback(error, command.doneCallback, command.verbosity) } else { pki.generatePrivateKeyAndCsr(configDir, commonOrCsrFileName, command) } } ) }
[ "function", "cliGenerateCsr", "(", "configDir", ",", "commonOrCsrFileName", ",", "command", ")", "{", "cliPki", ".", "processPrivateKeyPassphrase", "(", "command", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "provisionUtil", ".", "invokeCallback", "(", "error", ",", "command", ".", "doneCallback", ",", "command", ".", "verbosity", ")", "}", "else", "{", "pki", ".", "generatePrivateKeyAndCsr", "(", "configDir", ",", "commonOrCsrFileName", ",", "command", ")", "}", "}", ")", "}" ]
Action function invoked for the generatecsr subcommand. @param {String} configDir - Directory in which to store the private key and CSR file. @param {String} commonOrCsrFileName - A string representing either a common name (CN) to add into the generated file or the path to the location of an existing CSR file. The parameter is interpreted as a path to an existing CSR file if a property named certRequestFile exists on the command object and has a truthy value. If the parameter represents a path to an existing CSR file, this function does not generate a new CSR file. @param {Command} command - The Commander command to append options onto.
[ "Action", "function", "invoked", "for", "the", "generatecsr", "subcommand", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_cli/cli-generate-csr.js#L24-L35
43,899
tonistiigi/styler
lib/public/build/editor.js
function(win) { win = win || window; this.lastFocus = new Date().getTime(); this._isFocused = true; var _self = this; // IE < 9 supports focusin and focusout events if ("onfocusin" in win.document) { event.addListener(win.document, "focusin", function(e) { _self._setFocused(true); }); event.addListener(win.document, "focusout", function(e) { _self._setFocused(!!e.toElement); }); } else { event.addListener(win, "blur", function(e) { _self._setFocused(false); }); event.addListener(win, "focus", function(e) { _self._setFocused(true); }); } }
javascript
function(win) { win = win || window; this.lastFocus = new Date().getTime(); this._isFocused = true; var _self = this; // IE < 9 supports focusin and focusout events if ("onfocusin" in win.document) { event.addListener(win.document, "focusin", function(e) { _self._setFocused(true); }); event.addListener(win.document, "focusout", function(e) { _self._setFocused(!!e.toElement); }); } else { event.addListener(win, "blur", function(e) { _self._setFocused(false); }); event.addListener(win, "focus", function(e) { _self._setFocused(true); }); } }
[ "function", "(", "win", ")", "{", "win", "=", "win", "||", "window", ";", "this", ".", "lastFocus", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", ";", "this", ".", "_isFocused", "=", "true", ";", "var", "_self", "=", "this", ";", "// IE < 9 supports focusin and focusout events", "if", "(", "\"onfocusin\"", "in", "win", ".", "document", ")", "{", "event", ".", "addListener", "(", "win", ".", "document", ",", "\"focusin\"", ",", "function", "(", "e", ")", "{", "_self", ".", "_setFocused", "(", "true", ")", ";", "}", ")", ";", "event", ".", "addListener", "(", "win", ".", "document", ",", "\"focusout\"", ",", "function", "(", "e", ")", "{", "_self", ".", "_setFocused", "(", "!", "!", "e", ".", "toElement", ")", ";", "}", ")", ";", "}", "else", "{", "event", ".", "addListener", "(", "win", ",", "\"blur\"", ",", "function", "(", "e", ")", "{", "_self", ".", "_setFocused", "(", "false", ")", ";", "}", ")", ";", "event", ".", "addListener", "(", "win", ",", "\"focus\"", ",", "function", "(", "e", ")", "{", "_self", ".", "_setFocused", "(", "true", ")", ";", "}", ")", ";", "}", "}" ]
This class keeps track of the focus state of the given window. Focus changes for example when the user switches a browser tab, goes to the location bar or switches to another application.
[ "This", "class", "keeps", "track", "of", "the", "focus", "state", "of", "the", "given", "window", ".", "Focus", "changes", "for", "example", "when", "the", "user", "switches", "a", "browser", "tab", "goes", "to", "the", "location", "bar", "or", "switches", "to", "another", "application", "." ]
f20dd9621f671b77cbb660d35327e007e8a56e2a
https://github.com/tonistiigi/styler/blob/f20dd9621f671b77cbb660d35327e007e8a56e2a/lib/public/build/editor.js#L7768-L7795