repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
fasttime/JScrewIt
lib/jscrewit.js
function (str, options) { options = options || { }; var optimize = options.optimize; var optimizerList = []; if (optimize) { var optimizeComplex; var optimizeToString; if (typeof optimize === 'object') { optimizeComplex = !!optimize.complexOpt; optimizeToString = !!optimize.toStringOpt; } else optimizeComplex = optimizeToString = true; var optimizers = this.optimizers; var optimizer; if (optimizeComplex) { var complexOptimizers = optimizers.complex; if (!complexOptimizers) complexOptimizers = optimizers.complex = createEmpty(); for (var complex in COMPLEX) { var entry = COMPLEX[complex]; if (this.hasFeatures(entry.mask) && str.indexOf(complex) >= 0) { optimizer = complexOptimizers[complex] || ( complexOptimizers[complex] = getComplexOptimizer(this, complex, entry.definition) ); optimizerList.push(optimizer); } } } if (optimizeToString) { optimizer = optimizers.toString || (optimizers.toString = getToStringOptimizer(this)); optimizerList.push(optimizer); } } var buffer = new ScrewBuffer (options.bond, options.forceString, this.maxGroupThreshold, optimizerList); var firstSolution = options.firstSolution; var maxLength = options.maxLength; if (firstSolution) { buffer.append(firstSolution); if (buffer.length > maxLength) return; } var match; var regExp = _RegExp(STR_TOKEN_PATTERN, 'g'); while (match = regExp.exec(str)) { var token; var solution; if (token = match[2]) solution = this.resolveCharacter(token); else { token = match[1]; solution = SIMPLE[token]; } if (!buffer.append(solution) || buffer.length > maxLength) return; } var result = _String(buffer); if (!(result.length > maxLength)) return result; }
javascript
function (str, options) { options = options || { }; var optimize = options.optimize; var optimizerList = []; if (optimize) { var optimizeComplex; var optimizeToString; if (typeof optimize === 'object') { optimizeComplex = !!optimize.complexOpt; optimizeToString = !!optimize.toStringOpt; } else optimizeComplex = optimizeToString = true; var optimizers = this.optimizers; var optimizer; if (optimizeComplex) { var complexOptimizers = optimizers.complex; if (!complexOptimizers) complexOptimizers = optimizers.complex = createEmpty(); for (var complex in COMPLEX) { var entry = COMPLEX[complex]; if (this.hasFeatures(entry.mask) && str.indexOf(complex) >= 0) { optimizer = complexOptimizers[complex] || ( complexOptimizers[complex] = getComplexOptimizer(this, complex, entry.definition) ); optimizerList.push(optimizer); } } } if (optimizeToString) { optimizer = optimizers.toString || (optimizers.toString = getToStringOptimizer(this)); optimizerList.push(optimizer); } } var buffer = new ScrewBuffer (options.bond, options.forceString, this.maxGroupThreshold, optimizerList); var firstSolution = options.firstSolution; var maxLength = options.maxLength; if (firstSolution) { buffer.append(firstSolution); if (buffer.length > maxLength) return; } var match; var regExp = _RegExp(STR_TOKEN_PATTERN, 'g'); while (match = regExp.exec(str)) { var token; var solution; if (token = match[2]) solution = this.resolveCharacter(token); else { token = match[1]; solution = SIMPLE[token]; } if (!buffer.append(solution) || buffer.length > maxLength) return; } var result = _String(buffer); if (!(result.length > maxLength)) return result; }
[ "function", "(", "str", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "optimize", "=", "options", ".", "optimize", ";", "var", "optimizerList", "=", "[", "]", ";", "if", "(", "optimize", ")", "{", "var", "optimizeComplex", ";", "var", "optimizeToString", ";", "if", "(", "typeof", "optimize", "===", "'object'", ")", "{", "optimizeComplex", "=", "!", "!", "optimize", ".", "complexOpt", ";", "optimizeToString", "=", "!", "!", "optimize", ".", "toStringOpt", ";", "}", "else", "optimizeComplex", "=", "optimizeToString", "=", "true", ";", "var", "optimizers", "=", "this", ".", "optimizers", ";", "var", "optimizer", ";", "if", "(", "optimizeComplex", ")", "{", "var", "complexOptimizers", "=", "optimizers", ".", "complex", ";", "if", "(", "!", "complexOptimizers", ")", "complexOptimizers", "=", "optimizers", ".", "complex", "=", "createEmpty", "(", ")", ";", "for", "(", "var", "complex", "in", "COMPLEX", ")", "{", "var", "entry", "=", "COMPLEX", "[", "complex", "]", ";", "if", "(", "this", ".", "hasFeatures", "(", "entry", ".", "mask", ")", "&&", "str", ".", "indexOf", "(", "complex", ")", ">=", "0", ")", "{", "optimizer", "=", "complexOptimizers", "[", "complex", "]", "||", "(", "complexOptimizers", "[", "complex", "]", "=", "getComplexOptimizer", "(", "this", ",", "complex", ",", "entry", ".", "definition", ")", ")", ";", "optimizerList", ".", "push", "(", "optimizer", ")", ";", "}", "}", "}", "if", "(", "optimizeToString", ")", "{", "optimizer", "=", "optimizers", ".", "toString", "||", "(", "optimizers", ".", "toString", "=", "getToStringOptimizer", "(", "this", ")", ")", ";", "optimizerList", ".", "push", "(", "optimizer", ")", ";", "}", "}", "var", "buffer", "=", "new", "ScrewBuffer", "(", "options", ".", "bond", ",", "options", ".", "forceString", ",", "this", ".", "maxGroupThreshold", ",", "optimizerList", ")", ";", "var", "firstSolution", "=", "options", ".", "firstSolution", ";", "var", "maxLength", "=", "options", ".", "maxLength", ";", "if", "(", "firstSolution", ")", "{", "buffer", ".", "append", "(", "firstSolution", ")", ";", "if", "(", "buffer", ".", "length", ">", "maxLength", ")", "return", ";", "}", "var", "match", ";", "var", "regExp", "=", "_RegExp", "(", "STR_TOKEN_PATTERN", ",", "'g'", ")", ";", "while", "(", "match", "=", "regExp", ".", "exec", "(", "str", ")", ")", "{", "var", "token", ";", "var", "solution", ";", "if", "(", "token", "=", "match", "[", "2", "]", ")", "solution", "=", "this", ".", "resolveCharacter", "(", "token", ")", ";", "else", "{", "token", "=", "match", "[", "1", "]", ";", "solution", "=", "SIMPLE", "[", "token", "]", ";", "}", "if", "(", "!", "buffer", ".", "append", "(", "solution", ")", "||", "buffer", ".", "length", ">", "maxLength", ")", "return", ";", "}", "var", "result", "=", "_String", "(", "buffer", ")", ";", "if", "(", "!", "(", "result", ".", "length", ">", "maxLength", ")", ")", "return", "result", ";", "}" ]
Replaces a given string with equivalent JSFuck code. @function Encoder#replaceString @param {string} str The string to replace. @param {object} [options={ }] An optional object specifying replacement options. @param {boolean} [options.bond=false] Indicates whether the replacement expression should be bonded. An expression is bonded if it can be treated as a single unit by any valid operators placed immediately before or after it. E.g. `[][[]]` is bonded but `![]` is not, because `![][[]]` is different from `(![])[[]]`. More exactly, a bonded expression does not contain an outer plus and does not start with `!`. Any expression becomes bonded when enclosed into parentheses. @param {Solution} [options.firstSolution] An optional solution to be prepended to the replacement string. @param {boolean} [options.forceString=false] Indicates whether the replacement expression should evaluate to a string. If this parameter is falsy, the value of the replacement expression may not be equal to the input string, but will have the same string representation. @param {number} [options.maxLength=(NaN)] The maximum length of the replacement expression. If the replacement expression exceeds the specified length, the return value is `undefined`. If this parameter is `NaN`, then no length limit is imposed. @param {boolean|object<string, boolean|*>} [options.optimize=false] Specifies which optimizations should be attempted. Optimizations may reduce the length of the replacement string, but they also reduce the performance and may lead to unwanted circular dependencies when resolving definitions. This parameter can be set to a boolean value in order to turn all optimizations on (`true`) or off (`false`). In order to turn specific optimizations on or off, specify an object that maps optimization names with the suffix "Opt" to booleans, or to any other optimization specific kind of data. @returns {string|undefined} The replacement string or `undefined`.
[ "Replaces", "a", "given", "string", "with", "equivalent", "JSFuck", "code", "." ]
f0a9e93ccbc957d72ed775a7ad528a6b1fe9ffcc
https://github.com/fasttime/JScrewIt/blob/f0a9e93ccbc957d72ed775a7ad528a6b1fe9ffcc/lib/jscrewit.js#L5801-L5876
train
fasttime/JScrewIt
lib/jscrewit.js
function (array, maxLength) { var result = this.replaceStringArray(array, [FALSE_FREE_DELIMITER], null, false, maxLength); return result; }
javascript
function (array, maxLength) { var result = this.replaceStringArray(array, [FALSE_FREE_DELIMITER], null, false, maxLength); return result; }
[ "function", "(", "array", ",", "maxLength", ")", "{", "var", "result", "=", "this", ".", "replaceStringArray", "(", "array", ",", "[", "FALSE_FREE_DELIMITER", "]", ",", "null", ",", "false", ",", "maxLength", ")", ";", "return", "result", ";", "}" ]
Array elements may not contain the substring "false", because the value false could be used as a separator in the encoding.
[ "Array", "elements", "may", "not", "contain", "the", "substring", "false", "because", "the", "value", "false", "could", "be", "used", "as", "a", "separator", "in", "the", "encoding", "." ]
f0a9e93ccbc957d72ed775a7ad528a6b1fe9ffcc
https://github.com/fasttime/JScrewIt/blob/f0a9e93ccbc957d72ed775a7ad528a6b1fe9ffcc/lib/jscrewit.js#L7469-L7474
train
fasttime/JScrewIt
lib/jscrewit.js
encode
function encode(input, options) { input = esToString(input); options = options || { }; var features = options.features; var runAsData; var runAs = options.runAs; if (runAs !== undefined) runAsData = filterRunAs(runAs, 'runAs'); else runAsData = filterRunAs(options.wrapWith, 'wrapWith'); var wrapper = runAsData[0]; var strategyNames = runAsData[1]; if (options.trimCode) input = trimJS(input); var perfInfo = options.perfInfo; var encoder = getEncoder(features); var output = encoder.exec(input, wrapper, strategyNames, perfInfo); return output; }
javascript
function encode(input, options) { input = esToString(input); options = options || { }; var features = options.features; var runAsData; var runAs = options.runAs; if (runAs !== undefined) runAsData = filterRunAs(runAs, 'runAs'); else runAsData = filterRunAs(options.wrapWith, 'wrapWith'); var wrapper = runAsData[0]; var strategyNames = runAsData[1]; if (options.trimCode) input = trimJS(input); var perfInfo = options.perfInfo; var encoder = getEncoder(features); var output = encoder.exec(input, wrapper, strategyNames, perfInfo); return output; }
[ "function", "encode", "(", "input", ",", "options", ")", "{", "input", "=", "esToString", "(", "input", ")", ";", "options", "=", "options", "||", "{", "}", ";", "var", "features", "=", "options", ".", "features", ";", "var", "runAsData", ";", "var", "runAs", "=", "options", ".", "runAs", ";", "if", "(", "runAs", "!==", "undefined", ")", "runAsData", "=", "filterRunAs", "(", "runAs", ",", "'runAs'", ")", ";", "else", "runAsData", "=", "filterRunAs", "(", "options", ".", "wrapWith", ",", "'wrapWith'", ")", ";", "var", "wrapper", "=", "runAsData", "[", "0", "]", ";", "var", "strategyNames", "=", "runAsData", "[", "1", "]", ";", "if", "(", "options", ".", "trimCode", ")", "input", "=", "trimJS", "(", "input", ")", ";", "var", "perfInfo", "=", "options", ".", "perfInfo", ";", "var", "encoder", "=", "getEncoder", "(", "features", ")", ";", "var", "output", "=", "encoder", ".", "exec", "(", "input", ",", "wrapper", ",", "strategyNames", ",", "perfInfo", ")", ";", "return", "output", ";", "}" ]
Encodes a given string into JSFuck. @function JScrewIt.encode @param {string} input The string to encode. @param {object} [options={ }] An optional object specifying encoding options. @param {FeatureElement|CompatibleFeatureArray} [options.features=JScrewIt.Feature.DEFAULT] <p> Specifies the features available in the engines that evaluate the encoded output.</p> <p> If this parameter is unspecified, [`JScrewIt.Feature.DEFAULT`](Features.md#DEFAULT) is assumed: this ensures maximum compatibility but also generates the largest code. To generate shorter code, specify all features available in all target engines explicitly.</p> @param {string} [options.runAs=express-eval] This option controls the type of code generated from the given input. Allowed values are listed below. <dl> <dt><code>"call"</code></dt> <dd> Produces code evaluating to a call to a function whose body contains the specified input string.</dd> <dt><code>"eval"</code></dt> <dd> Produces code evaluating to the result of invoking <code>eval</code> with the specified input string as parameter.</dd> <dt><code>"express"</code></dt> <dd> Attempts to interpret the specified string as JavaScript code and produce functionally equivalent JSFuck code. Fails if the specified string cannot be expressed as JavaScript, or if no functionally equivalent JSFuck code can be generated.</dd> <dt><code>"express-call"</code></dt> <dd> Applies the code generation process of both <code>"express"</code> and <code>"call"</code> and returns the shortest output.</dd> <dt><code>"express-eval"</code> (default)</dt> <dd> Applies the code generation process of both <code>"express"</code> and <code>"eval"</code> and returns the shortest output.</dd> <dt><code>"none"</code></dt> <dd> Produces JSFuck code that translates to the specified input string (except for trimmed parts when used in conjunction with the option <code>trimCode</code>). Unlike other methods, <code>"none"</code> does not generate executable code but just a plain string. </dd> </dl> @param {boolean} [options.trimCode=false] <p> If this parameter is truthy, lines in the beginning and in the end of the file containing nothing but space characters and JavaScript comments are removed from the generated output. A newline terminator in the last preserved line is also removed.</p> <p> This option is especially useful to strip banner comments and trailing newline characters which are sometimes found in minified scripts.</p> <p> Using this option may produce unexpected results if the input is not well-formed JavaScript code.</p> @param {string} [options.wrapWith=express-eval] An alias for `runAs`. @returns {string} The encoded string. @throws An `Error` is thrown under the following circumstances. - The specified string cannot be encoded with the specified options. - Some unknown features were specified. - A combination of mutually incompatible features was specified. - The option `runAs` (or `wrapWith`) was specified with an invalid value. Also, an out of memory condition may occur when processing very large data.
[ "Encodes", "a", "given", "string", "into", "JSFuck", "." ]
f0a9e93ccbc957d72ed775a7ad528a6b1fe9ffcc
https://github.com/fasttime/JScrewIt/blob/f0a9e93ccbc957d72ed775a7ad528a6b1fe9ffcc/lib/jscrewit.js#L7928-L7947
train
basho/riak-nodejs-client
lib/commands/crdt/updatemap.js
MapOperation
function MapOperation() { this.counters = { increment: [], remove : []}; this.maps = { modify: [], remove: []}; this.sets = { adds: [], removes: [], remove: []}; this.registers = { set: [], remove: [] }; this.flags = { set: [], remove: [] }; }
javascript
function MapOperation() { this.counters = { increment: [], remove : []}; this.maps = { modify: [], remove: []}; this.sets = { adds: [], removes: [], remove: []}; this.registers = { set: [], remove: [] }; this.flags = { set: [], remove: [] }; }
[ "function", "MapOperation", "(", ")", "{", "this", ".", "counters", "=", "{", "increment", ":", "[", "]", ",", "remove", ":", "[", "]", "}", ";", "this", ".", "maps", "=", "{", "modify", ":", "[", "]", ",", "remove", ":", "[", "]", "}", ";", "this", ".", "sets", "=", "{", "adds", ":", "[", "]", ",", "removes", ":", "[", "]", ",", "remove", ":", "[", "]", "}", ";", "this", ".", "registers", "=", "{", "set", ":", "[", "]", ",", "remove", ":", "[", "]", "}", ";", "this", ".", "flags", "=", "{", "set", ":", "[", "]", ",", "remove", ":", "[", "]", "}", ";", "}" ]
Class that encapsulates modifications to a Map in Riak. Rather than manually constructing this yourself, a fluent API is provided. var mapOp = new UpdateMap.MapOperation(); mapOp.incrementCounter('counter_1', 50) .addToSet('set_1', 'set_value_1') .setRegister('register_1', new Buffer('register_value_1')) .setFlag('flag_1', true) .map('inner_map') .incrementCounter('counter_1', 50) .addToSet('set_2', 'set_value_2'); @class UpdateMap.MapOperation @constructor
[ "Class", "that", "encapsulates", "modifications", "to", "a", "Map", "in", "Riak", "." ]
4823460b56b4defee69837995bde98e789b635bd
https://github.com/basho/riak-nodejs-client/blob/4823460b56b4defee69837995bde98e789b635bd/lib/commands/crdt/updatemap.js#L476-L482
train
basho/riak-nodejs-client
lib/commands/crdt/updatemap.js
function(key) { this._removeAddsOrRemoves(this.counters.increment, key); if (this.counters.remove.indexOf(key) === -1) { this.counters.remove.push(key); } return this; }
javascript
function(key) { this._removeAddsOrRemoves(this.counters.increment, key); if (this.counters.remove.indexOf(key) === -1) { this.counters.remove.push(key); } return this; }
[ "function", "(", "key", ")", "{", "this", ".", "_removeAddsOrRemoves", "(", "this", ".", "counters", ".", "increment", ",", "key", ")", ";", "if", "(", "this", ".", "counters", ".", "remove", ".", "indexOf", "(", "key", ")", "===", "-", "1", ")", "{", "this", ".", "counters", ".", "remove", ".", "push", "(", "key", ")", ";", "}", "return", "this", ";", "}" ]
Remove a counter from a map. @method removeCounter @param {String} key the key in the map for this counter. @chainable
[ "Remove", "a", "counter", "from", "a", "map", "." ]
4823460b56b4defee69837995bde98e789b635bd
https://github.com/basho/riak-nodejs-client/blob/4823460b56b4defee69837995bde98e789b635bd/lib/commands/crdt/updatemap.js#L509-L515
train
basho/riak-nodejs-client
lib/commands/crdt/updatemap.js
function(key, value) { this._removeRemove(this.sets.remove, key); var op = this._getOp(this.sets.removes, key); if (op) { op.remove.push(value); } else { this.sets.removes.push({key: key, remove: [value]}); } return this; }
javascript
function(key, value) { this._removeRemove(this.sets.remove, key); var op = this._getOp(this.sets.removes, key); if (op) { op.remove.push(value); } else { this.sets.removes.push({key: key, remove: [value]}); } return this; }
[ "function", "(", "key", ",", "value", ")", "{", "this", ".", "_removeRemove", "(", "this", ".", "sets", ".", "remove", ",", "key", ")", ";", "var", "op", "=", "this", ".", "_getOp", "(", "this", ".", "sets", ".", "removes", ",", "key", ")", ";", "if", "(", "op", ")", "{", "op", ".", "remove", ".", "push", "(", "value", ")", ";", "}", "else", "{", "this", ".", "sets", ".", "removes", ".", "push", "(", "{", "key", ":", "key", ",", "remove", ":", "[", "value", "]", "}", ")", ";", "}", "return", "this", ";", "}" ]
Remove a value from a set in a map. @method removeFromSet @param {String} key the key for the set in the map. @param {String|Buffer} value the value to remove from the set. @chainable
[ "Remove", "a", "value", "from", "a", "set", "in", "a", "map", "." ]
4823460b56b4defee69837995bde98e789b635bd
https://github.com/basho/riak-nodejs-client/blob/4823460b56b4defee69837995bde98e789b635bd/lib/commands/crdt/updatemap.js#L540-L549
train
basho/riak-nodejs-client
lib/commands/crdt/updatemap.js
function(key) { this._removeAddsOrRemoves(this.sets.adds, key); this._removeAddsOrRemoves(this.sets.removes, key); if (this.sets.remove.indexOf(key) === -1) { this.sets.remove.push(key); } return this; }
javascript
function(key) { this._removeAddsOrRemoves(this.sets.adds, key); this._removeAddsOrRemoves(this.sets.removes, key); if (this.sets.remove.indexOf(key) === -1) { this.sets.remove.push(key); } return this; }
[ "function", "(", "key", ")", "{", "this", ".", "_removeAddsOrRemoves", "(", "this", ".", "sets", ".", "adds", ",", "key", ")", ";", "this", ".", "_removeAddsOrRemoves", "(", "this", ".", "sets", ".", "removes", ",", "key", ")", ";", "if", "(", "this", ".", "sets", ".", "remove", ".", "indexOf", "(", "key", ")", "===", "-", "1", ")", "{", "this", ".", "sets", ".", "remove", ".", "push", "(", "key", ")", ";", "}", "return", "this", ";", "}" ]
Remove a set from a map. @method removeSet @param {String} key the key for the set in the map. @chainable
[ "Remove", "a", "set", "from", "a", "map", "." ]
4823460b56b4defee69837995bde98e789b635bd
https://github.com/basho/riak-nodejs-client/blob/4823460b56b4defee69837995bde98e789b635bd/lib/commands/crdt/updatemap.js#L556-L563
train
basho/riak-nodejs-client
lib/commands/crdt/updatemap.js
function(key, value) { this._removeRemove(this.registers.remove, key); var op = this._getOp(this.registers.set, key); if (op) { op.value = value; } else { this.registers.set.push({key: key, value: value}); } return this; }
javascript
function(key, value) { this._removeRemove(this.registers.remove, key); var op = this._getOp(this.registers.set, key); if (op) { op.value = value; } else { this.registers.set.push({key: key, value: value}); } return this; }
[ "function", "(", "key", ",", "value", ")", "{", "this", ".", "_removeRemove", "(", "this", ".", "registers", ".", "remove", ",", "key", ")", ";", "var", "op", "=", "this", ".", "_getOp", "(", "this", ".", "registers", ".", "set", ",", "key", ")", ";", "if", "(", "op", ")", "{", "op", ".", "value", "=", "value", ";", "}", "else", "{", "this", ".", "registers", ".", "set", ".", "push", "(", "{", "key", ":", "key", ",", "value", ":", "value", "}", ")", ";", "}", "return", "this", ";", "}" ]
Set a register in a map. @method setRegister @param {String} key the key for the register in the map. @param {String|Buffer} value the value for the register. @chainable}
[ "Set", "a", "register", "in", "a", "map", "." ]
4823460b56b4defee69837995bde98e789b635bd
https://github.com/basho/riak-nodejs-client/blob/4823460b56b4defee69837995bde98e789b635bd/lib/commands/crdt/updatemap.js#L571-L580
train
basho/riak-nodejs-client
lib/commands/crdt/updatemap.js
function(key) { this._removeAddsOrRemoves(this.registers.set, key); if (this.registers.remove.indexOf(key) === -1) { this.registers.remove.push(key); } return this; }
javascript
function(key) { this._removeAddsOrRemoves(this.registers.set, key); if (this.registers.remove.indexOf(key) === -1) { this.registers.remove.push(key); } return this; }
[ "function", "(", "key", ")", "{", "this", ".", "_removeAddsOrRemoves", "(", "this", ".", "registers", ".", "set", ",", "key", ")", ";", "if", "(", "this", ".", "registers", ".", "remove", ".", "indexOf", "(", "key", ")", "===", "-", "1", ")", "{", "this", ".", "registers", ".", "remove", ".", "push", "(", "key", ")", ";", "}", "return", "this", ";", "}" ]
Remove a register from a map. @method removeRegister @param {String} key the key for the register in the map. @chainable
[ "Remove", "a", "register", "from", "a", "map", "." ]
4823460b56b4defee69837995bde98e789b635bd
https://github.com/basho/riak-nodejs-client/blob/4823460b56b4defee69837995bde98e789b635bd/lib/commands/crdt/updatemap.js#L587-L593
train
basho/riak-nodejs-client
lib/commands/crdt/updatemap.js
function(key, state) { this._removeRemove(this.flags.remove, key); var op = this._getOp(this.flags.set, key); if (op) { op.state = state; } else { this.flags.set.push({key: key, state: state}); } return this; }
javascript
function(key, state) { this._removeRemove(this.flags.remove, key); var op = this._getOp(this.flags.set, key); if (op) { op.state = state; } else { this.flags.set.push({key: key, state: state}); } return this; }
[ "function", "(", "key", ",", "state", ")", "{", "this", ".", "_removeRemove", "(", "this", ".", "flags", ".", "remove", ",", "key", ")", ";", "var", "op", "=", "this", ".", "_getOp", "(", "this", ".", "flags", ".", "set", ",", "key", ")", ";", "if", "(", "op", ")", "{", "op", ".", "state", "=", "state", ";", "}", "else", "{", "this", ".", "flags", ".", "set", ".", "push", "(", "{", "key", ":", "key", ",", "state", ":", "state", "}", ")", ";", "}", "return", "this", ";", "}" ]
Set a flag in a map. @method setFlag @param {String} key the key for the set in the map. @param {Boolean} value the value for the flag. @chainable}
[ "Set", "a", "flag", "in", "a", "map", "." ]
4823460b56b4defee69837995bde98e789b635bd
https://github.com/basho/riak-nodejs-client/blob/4823460b56b4defee69837995bde98e789b635bd/lib/commands/crdt/updatemap.js#L601-L610
train
basho/riak-nodejs-client
lib/commands/crdt/updatemap.js
function(key) { this._removeAddsOrRemoves(this.flags.set, key); if (this.flags.remove.indexOf(key) === -1) { this.flags.remove.push(key); } return this; }
javascript
function(key) { this._removeAddsOrRemoves(this.flags.set, key); if (this.flags.remove.indexOf(key) === -1) { this.flags.remove.push(key); } return this; }
[ "function", "(", "key", ")", "{", "this", ".", "_removeAddsOrRemoves", "(", "this", ".", "flags", ".", "set", ",", "key", ")", ";", "if", "(", "this", ".", "flags", ".", "remove", ".", "indexOf", "(", "key", ")", "===", "-", "1", ")", "{", "this", ".", "flags", ".", "remove", ".", "push", "(", "key", ")", ";", "}", "return", "this", ";", "}" ]
Remove a flag from a map. @method removeFlag @param {String} key the key for the flag in the map. @chainable
[ "Remove", "a", "flag", "from", "a", "map", "." ]
4823460b56b4defee69837995bde98e789b635bd
https://github.com/basho/riak-nodejs-client/blob/4823460b56b4defee69837995bde98e789b635bd/lib/commands/crdt/updatemap.js#L617-L623
train
basho/riak-nodejs-client
lib/commands/crdt/updatemap.js
function(key) { this._removeAddsOrRemoves(this.maps.modify, key); if (this.maps.remove.indexOf(key) === -1) { this.maps.remove.push(key); } return this; }
javascript
function(key) { this._removeAddsOrRemoves(this.maps.modify, key); if (this.maps.remove.indexOf(key) === -1) { this.maps.remove.push(key); } return this; }
[ "function", "(", "key", ")", "{", "this", ".", "_removeAddsOrRemoves", "(", "this", ".", "maps", ".", "modify", ",", "key", ")", ";", "if", "(", "this", ".", "maps", ".", "remove", ".", "indexOf", "(", "key", ")", "===", "-", "1", ")", "{", "this", ".", "maps", ".", "remove", ".", "push", "(", "key", ")", ";", "}", "return", "this", ";", "}" ]
Remove a map from a map. @method removeMap @param {String} key the key for the map in the map. @chainable
[ "Remove", "a", "map", "from", "a", "map", "." ]
4823460b56b4defee69837995bde98e789b635bd
https://github.com/basho/riak-nodejs-client/blob/4823460b56b4defee69837995bde98e789b635bd/lib/commands/crdt/updatemap.js#L654-L660
train
basho/riak-nodejs-client
lib/core/riakcluster.js
function(nodes) { for (var i = 0; i < nodes.length; i++) { if (nodes[i] instanceof RiakNode) { this.nodes.push(nodes[i]); } } return this; }
javascript
function(nodes) { for (var i = 0; i < nodes.length; i++) { if (nodes[i] instanceof RiakNode) { this.nodes.push(nodes[i]); } } return this; }
[ "function", "(", "nodes", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "nodes", ".", "length", ";", "i", "++", ")", "{", "if", "(", "nodes", "[", "i", "]", "instanceof", "RiakNode", ")", "{", "this", ".", "nodes", ".", "push", "(", "nodes", "[", "i", "]", ")", ";", "}", "}", "return", "this", ";", "}" ]
The RiakNodes to use. @method withRiakNodes @param {RiakNode[]} nodes array of (unstarted) {{#crossLink "RiakNode"}}{{/crossLink}} instances. @return {RiakCluster.Builder}
[ "The", "RiakNodes", "to", "use", "." ]
4823460b56b4defee69837995bde98e789b635bd
https://github.com/basho/riak-nodejs-client/blob/4823460b56b4defee69837995bde98e789b635bd/lib/core/riakcluster.js#L485-L492
train
d3plus/d3plus-react
bin/release.js
finishRelease
function finishRelease() { log.done(); execSync("npm run examples", {stdio: "inherit"}); execSync("npm run docs", {stdio: "inherit"}); let commits = "", releaseUrl = "", zipSize = 0; log.timer("compiling release notes"); execAsync("git log --pretty=format:'* %s (%h)' `git describe --tags --abbrev=0`...HEAD") .then(stdout => { commits = stdout; log.timer("publishing npm package"); return execAsync("npm publish ./"); }) .then(() => { log.timer("commiting all modified files for release"); return execAsync("git add --all"); }) .then(() => execAsync(`git commit -m \"compiles v${version}\"`)) .then(() => { log.timer("tagging latest commit"); return execAsync(`git tag v${version}`); }) .then(() => { log.timer("pushing to repository"); return execAsync("git push origin --follow-tags"); }) .then(() => { log.timer("publishing release notes"); github.authenticate({type: "oauth", token}); return github.repos.createRelease({ owner: "d3plus", repo: name, tag_name: `v${version}`, name: `v${version}`, body: commits, prerelease }); }) .then(() => { log.timer("attaching .zip distribution to release"); return github.repos.getReleaseByTag({ owner: "d3plus", repo: name, tag: `v${version}` }); }) .then(release => { releaseUrl = release.data.upload_url; zipSize = fs.statSync(`build/${name}.zip`).size; return github.repos.uploadAsset({ url: releaseUrl, file: fs.createReadStream(`build/${name}.zip`), contentType: "application/zip", contentLength: zipSize, name: `${name}.zip`, label: `${name}.zip`, owner: "d3plus", repo: name }); }) .then(() => { log.exit(); shell.exit(0); }) .catch(err => { log.fail(err); log.exit(); shell.exit(1); }); }
javascript
function finishRelease() { log.done(); execSync("npm run examples", {stdio: "inherit"}); execSync("npm run docs", {stdio: "inherit"}); let commits = "", releaseUrl = "", zipSize = 0; log.timer("compiling release notes"); execAsync("git log --pretty=format:'* %s (%h)' `git describe --tags --abbrev=0`...HEAD") .then(stdout => { commits = stdout; log.timer("publishing npm package"); return execAsync("npm publish ./"); }) .then(() => { log.timer("commiting all modified files for release"); return execAsync("git add --all"); }) .then(() => execAsync(`git commit -m \"compiles v${version}\"`)) .then(() => { log.timer("tagging latest commit"); return execAsync(`git tag v${version}`); }) .then(() => { log.timer("pushing to repository"); return execAsync("git push origin --follow-tags"); }) .then(() => { log.timer("publishing release notes"); github.authenticate({type: "oauth", token}); return github.repos.createRelease({ owner: "d3plus", repo: name, tag_name: `v${version}`, name: `v${version}`, body: commits, prerelease }); }) .then(() => { log.timer("attaching .zip distribution to release"); return github.repos.getReleaseByTag({ owner: "d3plus", repo: name, tag: `v${version}` }); }) .then(release => { releaseUrl = release.data.upload_url; zipSize = fs.statSync(`build/${name}.zip`).size; return github.repos.uploadAsset({ url: releaseUrl, file: fs.createReadStream(`build/${name}.zip`), contentType: "application/zip", contentLength: zipSize, name: `${name}.zip`, label: `${name}.zip`, owner: "d3plus", repo: name }); }) .then(() => { log.exit(); shell.exit(0); }) .catch(err => { log.fail(err); log.exit(); shell.exit(1); }); }
[ "function", "finishRelease", "(", ")", "{", "log", ".", "done", "(", ")", ";", "execSync", "(", "\"npm run examples\"", ",", "{", "stdio", ":", "\"inherit\"", "}", ")", ";", "execSync", "(", "\"npm run docs\"", ",", "{", "stdio", ":", "\"inherit\"", "}", ")", ";", "let", "commits", "=", "\"\"", ",", "releaseUrl", "=", "\"\"", ",", "zipSize", "=", "0", ";", "log", ".", "timer", "(", "\"compiling release notes\"", ")", ";", "execAsync", "(", "\"git log --pretty=format:'* %s (%h)' `git describe --tags --abbrev=0`...HEAD\"", ")", ".", "then", "(", "stdout", "=>", "{", "commits", "=", "stdout", ";", "log", ".", "timer", "(", "\"publishing npm package\"", ")", ";", "return", "execAsync", "(", "\"npm publish ./\"", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "log", ".", "timer", "(", "\"commiting all modified files for release\"", ")", ";", "return", "execAsync", "(", "\"git add --all\"", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "execAsync", "(", "`", "\\\"", "${", "version", "}", "\\\"", "`", ")", ")", ".", "then", "(", "(", ")", "=>", "{", "log", ".", "timer", "(", "\"tagging latest commit\"", ")", ";", "return", "execAsync", "(", "`", "${", "version", "}", "`", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "log", ".", "timer", "(", "\"pushing to repository\"", ")", ";", "return", "execAsync", "(", "\"git push origin --follow-tags\"", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "log", ".", "timer", "(", "\"publishing release notes\"", ")", ";", "github", ".", "authenticate", "(", "{", "type", ":", "\"oauth\"", ",", "token", "}", ")", ";", "return", "github", ".", "repos", ".", "createRelease", "(", "{", "owner", ":", "\"d3plus\"", ",", "repo", ":", "name", ",", "tag_name", ":", "`", "${", "version", "}", "`", ",", "name", ":", "`", "${", "version", "}", "`", ",", "body", ":", "commits", ",", "prerelease", "}", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "log", ".", "timer", "(", "\"attaching .zip distribution to release\"", ")", ";", "return", "github", ".", "repos", ".", "getReleaseByTag", "(", "{", "owner", ":", "\"d3plus\"", ",", "repo", ":", "name", ",", "tag", ":", "`", "${", "version", "}", "`", "}", ")", ";", "}", ")", ".", "then", "(", "release", "=>", "{", "releaseUrl", "=", "release", ".", "data", ".", "upload_url", ";", "zipSize", "=", "fs", ".", "statSync", "(", "`", "${", "name", "}", "`", ")", ".", "size", ";", "return", "github", ".", "repos", ".", "uploadAsset", "(", "{", "url", ":", "releaseUrl", ",", "file", ":", "fs", ".", "createReadStream", "(", "`", "${", "name", "}", "`", ")", ",", "contentType", ":", "\"application/zip\"", ",", "contentLength", ":", "zipSize", ",", "name", ":", "`", "${", "name", "}", "`", ",", "label", ":", "`", "${", "name", "}", "`", ",", "owner", ":", "\"d3plus\"", ",", "repo", ":", "name", "}", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "log", ".", "exit", "(", ")", ";", "shell", ".", "exit", "(", "0", ")", ";", "}", ")", ".", "catch", "(", "err", "=>", "{", "log", ".", "fail", "(", "err", ")", ";", "log", ".", "exit", "(", ")", ";", "shell", ".", "exit", "(", "1", ")", ";", "}", ")", ";", "}" ]
Final steps for release. @private
[ "Final", "steps", "for", "release", "." ]
5f1edc97c3156ca7b24d70bd655898cc0708d879
https://github.com/d3plus/d3plus-react/blob/5f1edc97c3156ca7b24d70bd655898cc0708d879/bin/release.js#L25-L98
train
basho/riak-nodejs-client
lib/core/riakconnection.js
initBuffer
function initBuffer(data) { // Create a new buffer to receive data if needed if (buffer === null) { buffer = new ByteBuffer(initBufferSize); } buffer.append(data); buffer.flip(); }
javascript
function initBuffer(data) { // Create a new buffer to receive data if needed if (buffer === null) { buffer = new ByteBuffer(initBufferSize); } buffer.append(data); buffer.flip(); }
[ "function", "initBuffer", "(", "data", ")", "{", "if", "(", "buffer", "===", "null", ")", "{", "buffer", "=", "new", "ByteBuffer", "(", "initBufferSize", ")", ";", "}", "buffer", ".", "append", "(", "data", ")", ";", "buffer", ".", "flip", "(", ")", ";", "}" ]
private buffer functions
[ "private", "buffer", "functions" ]
4823460b56b4defee69837995bde98e789b635bd
https://github.com/basho/riak-nodejs-client/blob/4823460b56b4defee69837995bde98e789b635bd/lib/core/riakconnection.js#L159-L166
train
basho/riak-nodejs-client
lib/core/riaknode.js
function (addresses, options) { var riakNodes = []; if (options === undefined) { options = {}; } for (var i = 0; i < addresses.length; i++) { var split = addresses[i].split(':'); options.remoteAddress = split[0]; if (split.length === 2) { options.remotePort = split[1]; } riakNodes.push(new RiakNode(options)); } return riakNodes; }
javascript
function (addresses, options) { var riakNodes = []; if (options === undefined) { options = {}; } for (var i = 0; i < addresses.length; i++) { var split = addresses[i].split(':'); options.remoteAddress = split[0]; if (split.length === 2) { options.remotePort = split[1]; } riakNodes.push(new RiakNode(options)); } return riakNodes; }
[ "function", "(", "addresses", ",", "options", ")", "{", "var", "riakNodes", "=", "[", "]", ";", "if", "(", "options", "===", "undefined", ")", "{", "options", "=", "{", "}", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "addresses", ".", "length", ";", "i", "++", ")", "{", "var", "split", "=", "addresses", "[", "i", "]", ".", "split", "(", "':'", ")", ";", "options", ".", "remoteAddress", "=", "split", "[", "0", "]", ";", "if", "(", "split", ".", "length", "===", "2", ")", "{", "options", ".", "remotePort", "=", "split", "[", "1", "]", ";", "}", "riakNodes", ".", "push", "(", "new", "RiakNode", "(", "options", ")", ")", ";", "}", "return", "riakNodes", ";", "}" ]
Static factory for constructing a set of RiakNodes. To create a set of RiakNodes with the same options: var options = new RiakNode.Builder().withMinConnections(10); var nodes = RiakNode.buildNodes(['192.168.1.1', '192.168.1.2'], options); __options__ can be manually constructed or an instance of the Builder. @static @method buildNodes @param {String[]} addresses - an array of IP|hostname[:port] @param {Object} [options] - the options to use for all RiakNodes. @return {Array/RiakNode}
[ "Static", "factory", "for", "constructing", "a", "set", "of", "RiakNodes", "." ]
4823460b56b4defee69837995bde98e789b635bd
https://github.com/basho/riak-nodejs-client/blob/4823460b56b4defee69837995bde98e789b635bd/lib/core/riaknode.js#L875-L892
train
d3plus/d3plus-react
bin/execAsync.js
execAsync
function execAsync(cmd, opts = {}) { return new Promise((resolve, reject) => { shell.exec(cmd, opts, (code, stdout, stderr) => { if (code !== 0) return reject(new Error(stderr)); return resolve(stdout); }); }); }
javascript
function execAsync(cmd, opts = {}) { return new Promise((resolve, reject) => { shell.exec(cmd, opts, (code, stdout, stderr) => { if (code !== 0) return reject(new Error(stderr)); return resolve(stdout); }); }); }
[ "function", "execAsync", "(", "cmd", ",", "opts", "=", "{", "}", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "shell", ".", "exec", "(", "cmd", ",", "opts", ",", "(", "code", ",", "stdout", ",", "stderr", ")", "=>", "{", "if", "(", "code", "!==", "0", ")", "return", "reject", "(", "new", "Error", "(", "stderr", ")", ")", ";", "return", "resolve", "(", "stdout", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Asynchronously executes a shell command and returns a promise that resolves with the result. The `opts` object will be passed to shelljs's `exec()` and then to Node's native `child_process.exec()`. The most commonly used opts properties are: - {String} cwd - A full path to the working directory to execute the `cmd` in - {Boolean} silent - If `true`, the process won't log to `stdout` See shell.js docs: https://github.com/shelljs/shelljs#execcommand--options--callback See Node docs: https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback @example const execAsync = require('execAsync'); execAsync('ls -al', { silent: true, cwd: '/Users/admin/' }); @param {String} cmd - The shell command to execute @param {Object} opts - Any opts to pass in to exec (see shell.js docs and Node's native `exec` documentation) @returns {String.<Promise>} - Resolves with the command results from `stdout` @private
[ "Asynchronously", "executes", "a", "shell", "command", "and", "returns", "a", "promise", "that", "resolves", "with", "the", "result", "." ]
5f1edc97c3156ca7b24d70bd655898cc0708d879
https://github.com/d3plus/d3plus-react/blob/5f1edc97c3156ca7b24d70bd655898cc0708d879/bin/execAsync.js#L27-L34
train
basho/riak-nodejs-client
lib/commands/commandbase.js
CommandBase
function CommandBase(pbRequestName, pbResponseName, callback) { var requestCode = ProtoBufFactory.getCodeFor(pbRequestName); this.expectedCode = ProtoBufFactory.getCodeFor(pbResponseName); this.pbBuilder = ProtoBufFactory.getProtoFor(pbRequestName); var schema = Joi.func().required(); var self = this; Joi.validate(callback, schema, function(err, option) { if (err) { throw new Error('callback is required and must be a function'); } self.callback = callback; }); this.header = new Buffer(5); this.header.writeUInt8(requestCode, 4); this.remainingTries = 1; // This is to facilitate debugging what pb messages this Command represents this.name = util.format('%s-%d', pbRequestName, cid); cid++; this.validateOptions = function (arg_options, arg_schema, arg_joi_opts) { var self = this; Joi.validate(arg_options, arg_schema, arg_joi_opts, function(err, opts) { if (err) { throw err; } self.options = opts; }); }; }
javascript
function CommandBase(pbRequestName, pbResponseName, callback) { var requestCode = ProtoBufFactory.getCodeFor(pbRequestName); this.expectedCode = ProtoBufFactory.getCodeFor(pbResponseName); this.pbBuilder = ProtoBufFactory.getProtoFor(pbRequestName); var schema = Joi.func().required(); var self = this; Joi.validate(callback, schema, function(err, option) { if (err) { throw new Error('callback is required and must be a function'); } self.callback = callback; }); this.header = new Buffer(5); this.header.writeUInt8(requestCode, 4); this.remainingTries = 1; // This is to facilitate debugging what pb messages this Command represents this.name = util.format('%s-%d', pbRequestName, cid); cid++; this.validateOptions = function (arg_options, arg_schema, arg_joi_opts) { var self = this; Joi.validate(arg_options, arg_schema, arg_joi_opts, function(err, opts) { if (err) { throw err; } self.options = opts; }); }; }
[ "function", "CommandBase", "(", "pbRequestName", ",", "pbResponseName", ",", "callback", ")", "{", "var", "requestCode", "=", "ProtoBufFactory", ".", "getCodeFor", "(", "pbRequestName", ")", ";", "this", ".", "expectedCode", "=", "ProtoBufFactory", ".", "getCodeFor", "(", "pbResponseName", ")", ";", "this", ".", "pbBuilder", "=", "ProtoBufFactory", ".", "getProtoFor", "(", "pbRequestName", ")", ";", "var", "schema", "=", "Joi", ".", "func", "(", ")", ".", "required", "(", ")", ";", "var", "self", "=", "this", ";", "Joi", ".", "validate", "(", "callback", ",", "schema", ",", "function", "(", "err", ",", "option", ")", "{", "if", "(", "err", ")", "{", "throw", "new", "Error", "(", "'callback is required and must be a function'", ")", ";", "}", "self", ".", "callback", "=", "callback", ";", "}", ")", ";", "this", ".", "header", "=", "new", "Buffer", "(", "5", ")", ";", "this", ".", "header", ".", "writeUInt8", "(", "requestCode", ",", "4", ")", ";", "this", ".", "remainingTries", "=", "1", ";", "this", ".", "name", "=", "util", ".", "format", "(", "'%s-%d'", ",", "pbRequestName", ",", "cid", ")", ";", "cid", "++", ";", "this", ".", "validateOptions", "=", "function", "(", "arg_options", ",", "arg_schema", ",", "arg_joi_opts", ")", "{", "var", "self", "=", "this", ";", "Joi", ".", "validate", "(", "arg_options", ",", "arg_schema", ",", "arg_joi_opts", ",", "function", "(", "err", ",", "opts", ")", "{", "if", "(", "err", ")", "{", "throw", "err", ";", "}", "self", ".", "options", "=", "opts", ";", "}", ")", ";", "}", ";", "}" ]
Provides a base class for all commands. @module Core Base class for all commands. Classes extending this need to override: constructPbRequest onSuccess onRiakError onError @class CommandBase @constructor @param {String} pbRequestName name of the Riak protocol buffer this command will send @param {String} pbResponseName name of the Riak protocol buffer this command will receive @param {Function} callback The callback to be executed when the operation completes. @param {String} callback.err An error message. Will be null if no error. @param {Object} callback.response the response from Riak. @param {Object} callback.data additional error data. Will be null if no error.
[ "Provides", "a", "base", "class", "for", "all", "commands", "." ]
4823460b56b4defee69837995bde98e789b635bd
https://github.com/basho/riak-nodejs-client/blob/4823460b56b4defee69837995bde98e789b635bd/lib/commands/commandbase.js#L51-L83
train
basho/riak-nodejs-client
lib/commands/ts/bykeybase.js
ByKeyBase
function ByKeyBase(options, pbRequestName, pbResponseName, callback) { CommandBase.call(this, pbRequestName, pbResponseName, callback); this.validateOptions(options, schema); }
javascript
function ByKeyBase(options, pbRequestName, pbResponseName, callback) { CommandBase.call(this, pbRequestName, pbResponseName, callback); this.validateOptions(options, schema); }
[ "function", "ByKeyBase", "(", "options", ",", "pbRequestName", ",", "pbResponseName", ",", "callback", ")", "{", "CommandBase", ".", "call", "(", "this", ",", "pbRequestName", ",", "pbResponseName", ",", "callback", ")", ";", "this", ".", "validateOptions", "(", "options", ",", "schema", ")", ";", "}" ]
Base class for Get and Delete classes. @module TS @class ByKeyBase @constructor @param {Object} options The options for this command. @param {String} options.table The timeseries table from which retrieve a key from Riak. @param {Object[]} options.key The timeseries composite key to retrieve from Riak. @param {Function} callback The allback to be executed when the operation completes. @param {String} callback.err An error message. Will be null if no error. @param {Object} callback.response Object containing timeseries data. @param {Object} callback.response.columns Timeseries column data @param {Object} callback.response.rows Timeseries row data @param {Object} callback.data additional error data. Will be null if no error. @extends CommandBase
[ "Base", "class", "for", "Get", "and", "Delete", "classes", "." ]
4823460b56b4defee69837995bde98e789b635bd
https://github.com/basho/riak-nodejs-client/blob/4823460b56b4defee69837995bde98e789b635bd/lib/commands/ts/bykeybase.js#L47-L50
train
basho/riak-nodejs-client
lib/commands/kv/riakobject.js
function(indexName, key) { if (this.indexes === undefined) { this.indexes = {}; } if (!this.indexes.hasOwnProperty(indexName)) { this.indexes[indexName] = []; } for (var i = 1; i < arguments.length; i++) { this.indexes[indexName].push(arguments[i]); } return this; }
javascript
function(indexName, key) { if (this.indexes === undefined) { this.indexes = {}; } if (!this.indexes.hasOwnProperty(indexName)) { this.indexes[indexName] = []; } for (var i = 1; i < arguments.length; i++) { this.indexes[indexName].push(arguments[i]); } return this; }
[ "function", "(", "indexName", ",", "key", ")", "{", "if", "(", "this", ".", "indexes", "===", "undefined", ")", "{", "this", ".", "indexes", "=", "{", "}", ";", "}", "if", "(", "!", "this", ".", "indexes", ".", "hasOwnProperty", "(", "indexName", ")", ")", "{", "this", ".", "indexes", "[", "indexName", "]", "=", "[", "]", ";", "}", "for", "(", "var", "i", "=", "1", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "this", ".", "indexes", "[", "indexName", "]", ".", "push", "(", "arguments", "[", "i", "]", ")", ";", "}", "return", "this", ";", "}" ]
Add one or more keys to an index. If the index does not exist it will be created. @method addToIndex @param {String} indexName the index name @param {String|Number} ...key 1 or more keys to add @chainable
[ "Add", "one", "or", "more", "keys", "to", "an", "index", "." ]
4823460b56b4defee69837995bde98e789b635bd
https://github.com/basho/riak-nodejs-client/blob/4823460b56b4defee69837995bde98e789b635bd/lib/commands/kv/riakobject.js#L254-L265
train
dperini/nwmatcher
build/packer/packer.js
encodeBlocks
function encodeBlocks($, prefix, blockType, args, block) { if (!prefix) prefix = ""; if (blockType == "function") { // decode the function block (THIS IS THE IMPORTANT BIT) // We are retrieving all sub-blocks and will re-parse them in light // of newly shrunk variables block = args + decodeBlocks(block, SCOPED); prefix = prefix.replace(BRACKETS, ""); // create the list of variable and argument names args = args.slice(1, -1); if (args != "_no_shrink_") { var vars = match(block, VARS).join(";").replace(VAR_g, ";var"); while (BRACKETS.test(vars)) { vars = vars.replace(BRACKETS_g, ""); } vars = vars.replace(VAR_TIDY, "").replace(VAR_EQUAL, ""); } block = decodeBlocks(block, ENCODED_BLOCK); // process each identifier if (args != "_no_shrink_") { var count = 0, shortId; var ids = match([args, vars], IDENTIFIER); var processed = {}; for (var i = 0; i < ids.length; i++) { id = ids[i]; if (!processed["#" + id]) { processed["#" + id] = true; id = rescape(id); // encode variable names while (new RegExp(Shrinker.PREFIX + count + "\\b").test(block)) count++; var reg = new RegExp("([^\\w$.])" + id + "([^\\w$:])"); while (reg.test(block)) { block = block.replace(global(reg), "$1" + Shrinker.PREFIX + count + "$2"); } var reg = new RegExp("([^{,\\w$.])" + id + ":", "g"); block = block.replace(reg, "$1" + Shrinker.PREFIX + count + ":"); count++; } } total = Math.max(total, count); } var replacement = prefix + "~" + blocks.length + "~"; blocks.push(block); } else { var replacement = "~#" + blocks.length + "~"; blocks.push(prefix + block); } return replacement; }
javascript
function encodeBlocks($, prefix, blockType, args, block) { if (!prefix) prefix = ""; if (blockType == "function") { // decode the function block (THIS IS THE IMPORTANT BIT) // We are retrieving all sub-blocks and will re-parse them in light // of newly shrunk variables block = args + decodeBlocks(block, SCOPED); prefix = prefix.replace(BRACKETS, ""); // create the list of variable and argument names args = args.slice(1, -1); if (args != "_no_shrink_") { var vars = match(block, VARS).join(";").replace(VAR_g, ";var"); while (BRACKETS.test(vars)) { vars = vars.replace(BRACKETS_g, ""); } vars = vars.replace(VAR_TIDY, "").replace(VAR_EQUAL, ""); } block = decodeBlocks(block, ENCODED_BLOCK); // process each identifier if (args != "_no_shrink_") { var count = 0, shortId; var ids = match([args, vars], IDENTIFIER); var processed = {}; for (var i = 0; i < ids.length; i++) { id = ids[i]; if (!processed["#" + id]) { processed["#" + id] = true; id = rescape(id); // encode variable names while (new RegExp(Shrinker.PREFIX + count + "\\b").test(block)) count++; var reg = new RegExp("([^\\w$.])" + id + "([^\\w$:])"); while (reg.test(block)) { block = block.replace(global(reg), "$1" + Shrinker.PREFIX + count + "$2"); } var reg = new RegExp("([^{,\\w$.])" + id + ":", "g"); block = block.replace(reg, "$1" + Shrinker.PREFIX + count + ":"); count++; } } total = Math.max(total, count); } var replacement = prefix + "~" + blocks.length + "~"; blocks.push(block); } else { var replacement = "~#" + blocks.length + "~"; blocks.push(prefix + block); } return replacement; }
[ "function", "encodeBlocks", "(", "$", ",", "prefix", ",", "blockType", ",", "args", ",", "block", ")", "{", "if", "(", "!", "prefix", ")", "prefix", "=", "\"\"", ";", "if", "(", "blockType", "==", "\"function\"", ")", "{", "block", "=", "args", "+", "decodeBlocks", "(", "block", ",", "SCOPED", ")", ";", "prefix", "=", "prefix", ".", "replace", "(", "BRACKETS", ",", "\"\"", ")", ";", "args", "=", "args", ".", "slice", "(", "1", ",", "-", "1", ")", ";", "if", "(", "args", "!=", "\"_no_shrink_\"", ")", "{", "var", "vars", "=", "match", "(", "block", ",", "VARS", ")", ".", "join", "(", "\";\"", ")", ".", "replace", "(", "VAR_g", ",", "\";var\"", ")", ";", "while", "(", "BRACKETS", ".", "test", "(", "vars", ")", ")", "{", "vars", "=", "vars", ".", "replace", "(", "BRACKETS_g", ",", "\"\"", ")", ";", "}", "vars", "=", "vars", ".", "replace", "(", "VAR_TIDY", ",", "\"\"", ")", ".", "replace", "(", "VAR_EQUAL", ",", "\"\"", ")", ";", "}", "block", "=", "decodeBlocks", "(", "block", ",", "ENCODED_BLOCK", ")", ";", "if", "(", "args", "!=", "\"_no_shrink_\"", ")", "{", "var", "count", "=", "0", ",", "shortId", ";", "var", "ids", "=", "match", "(", "[", "args", ",", "vars", "]", ",", "IDENTIFIER", ")", ";", "var", "processed", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "ids", ".", "length", ";", "i", "++", ")", "{", "id", "=", "ids", "[", "i", "]", ";", "if", "(", "!", "processed", "[", "\"#\"", "+", "id", "]", ")", "{", "processed", "[", "\"#\"", "+", "id", "]", "=", "true", ";", "id", "=", "rescape", "(", "id", ")", ";", "while", "(", "new", "RegExp", "(", "Shrinker", ".", "PREFIX", "+", "count", "+", "\"\\\\b\"", ")", ".", "\\\\", "test", ")", "(", "block", ")", "count", "++", ";", "var", "reg", "=", "new", "RegExp", "(", "\"([^\\\\w$.])\"", "+", "\\\\", "+", "id", ")", ";", "\"([^\\\\w$:])\"", "\\\\", "while", "(", "reg", ".", "test", "(", "block", ")", ")", "{", "block", "=", "block", ".", "replace", "(", "global", "(", "reg", ")", ",", "\"$1\"", "+", "Shrinker", ".", "PREFIX", "+", "count", "+", "\"$2\"", ")", ";", "}", "}", "}", "var", "reg", "=", "new", "RegExp", "(", "\"([^{,\\\\w$.])\"", "+", "\\\\", "+", "id", ",", "\":\"", ")", ";", "}", "\"g\"", "block", "=", "block", ".", "replace", "(", "reg", ",", "\"$1\"", "+", "Shrinker", ".", "PREFIX", "+", "count", "+", "\":\"", ")", ";", "}", "else", "count", "++", ";", "total", "=", "Math", ".", "max", "(", "total", ",", "count", ")", ";", "}" ]
encoder for program blocks
[ "encoder", "for", "program", "blocks" ]
3edb471e12ce7f7d46dc1606c7f659ff45675a29
https://github.com/dperini/nwmatcher/blob/3edb471e12ce7f7d46dc1606c7f659ff45675a29/build/packer/packer.js#L471-L522
train
dperini/nwmatcher
build/packer/packer.js
decodeBlocks
function decodeBlocks(script, encoded) { while (encoded.test(script)) { script = script.replace(global(encoded), function(match, index) { return blocks[index]; }); } return script; }
javascript
function decodeBlocks(script, encoded) { while (encoded.test(script)) { script = script.replace(global(encoded), function(match, index) { return blocks[index]; }); } return script; }
[ "function", "decodeBlocks", "(", "script", ",", "encoded", ")", "{", "while", "(", "encoded", ".", "test", "(", "script", ")", ")", "{", "script", "=", "script", ".", "replace", "(", "global", "(", "encoded", ")", ",", "function", "(", "match", ",", "index", ")", "{", "return", "blocks", "[", "index", "]", ";", "}", ")", ";", "}", "return", "script", ";", "}" ]
decoder for program blocks
[ "decoder", "for", "program", "blocks" ]
3edb471e12ce7f7d46dc1606c7f659ff45675a29
https://github.com/dperini/nwmatcher/blob/3edb471e12ce7f7d46dc1606c7f659ff45675a29/build/packer/packer.js#L525-L532
train
djm/remark-shortcodes
index.js
parseShortcode
function parseShortcode(innerShortcode) { var trimmedInnerShortcode = innerShortcode.trim(); // If no shortcode, it was blank between the blocks - return nothing. if (!trimmedInnerShortcode) return; // If no whitespace, then shortcode is just name with no attributes. if (!hasWhiteSpace(trimmedInnerShortcode)) { return { identifier: trimmedInnerShortcode, attributes: {} }; } var splitShortcode = trimmedInnerShortcode.match(/^(\S+)\s(.*)/).slice(1); var shortcodeName = splitShortcode[0]; var attributeString = splitShortcode[1]; var attributes = parseShortcodeAttributes(attributeString); // If no attributes parsed, something went wrong - return nothing. if (!attributes) return; return { identifier: shortcodeName, attributes: attributes }; }
javascript
function parseShortcode(innerShortcode) { var trimmedInnerShortcode = innerShortcode.trim(); // If no shortcode, it was blank between the blocks - return nothing. if (!trimmedInnerShortcode) return; // If no whitespace, then shortcode is just name with no attributes. if (!hasWhiteSpace(trimmedInnerShortcode)) { return { identifier: trimmedInnerShortcode, attributes: {} }; } var splitShortcode = trimmedInnerShortcode.match(/^(\S+)\s(.*)/).slice(1); var shortcodeName = splitShortcode[0]; var attributeString = splitShortcode[1]; var attributes = parseShortcodeAttributes(attributeString); // If no attributes parsed, something went wrong - return nothing. if (!attributes) return; return { identifier: shortcodeName, attributes: attributes }; }
[ "function", "parseShortcode", "(", "innerShortcode", ")", "{", "var", "trimmedInnerShortcode", "=", "innerShortcode", ".", "trim", "(", ")", ";", "if", "(", "!", "trimmedInnerShortcode", ")", "return", ";", "if", "(", "!", "hasWhiteSpace", "(", "trimmedInnerShortcode", ")", ")", "{", "return", "{", "identifier", ":", "trimmedInnerShortcode", ",", "attributes", ":", "{", "}", "}", ";", "}", "var", "splitShortcode", "=", "trimmedInnerShortcode", ".", "match", "(", "/", "^(\\S+)\\s(.*)", "/", ")", ".", "slice", "(", "1", ")", ";", "var", "shortcodeName", "=", "splitShortcode", "[", "0", "]", ";", "var", "attributeString", "=", "splitShortcode", "[", "1", "]", ";", "var", "attributes", "=", "parseShortcodeAttributes", "(", "attributeString", ")", ";", "if", "(", "!", "attributes", ")", "return", ";", "return", "{", "identifier", ":", "shortcodeName", ",", "attributes", ":", "attributes", "}", ";", "}" ]
Parses the inner shortcode to extract shortcode name & key-value attributes. @param {string} innerShortcode - Extracted shortcode from between the start & end blocks.
[ "Parses", "the", "inner", "shortcode", "to", "extract", "shortcode", "name", "&", "key", "-", "value", "attributes", "." ]
490a56b8e491faeb6899a267e42395462e0f9254
https://github.com/djm/remark-shortcodes/blob/490a56b8e491faeb6899a267e42395462e0f9254/index.js#L120-L143
train
dperini/nwmatcher
build/packer/base2.js
_Array_forEach
function _Array_forEach(array, block, context) { if (array == null) array = global; var length = array.length || 0, i; // preserve length if (typeof array == "string") { for (i = 0; i < length; i++) { block.call(context, array.charAt(i), i, array); } } else { // Cater for sparse arrays. for (i = 0; i < length; i++) { /*@cc_on @*/ /*@if (@_jscript_version < 5.2) if ($Legacy.has(array, i)) @else @*/ if (i in array) /*@end @*/ block.call(context, array[i], i, array); } } }
javascript
function _Array_forEach(array, block, context) { if (array == null) array = global; var length = array.length || 0, i; // preserve length if (typeof array == "string") { for (i = 0; i < length; i++) { block.call(context, array.charAt(i), i, array); } } else { // Cater for sparse arrays. for (i = 0; i < length; i++) { /*@cc_on @*/ /*@if (@_jscript_version < 5.2) if ($Legacy.has(array, i)) @else @*/ if (i in array) /*@end @*/ block.call(context, array[i], i, array); } } }
[ "function", "_Array_forEach", "(", "array", ",", "block", ",", "context", ")", "{", "if", "(", "array", "==", "null", ")", "array", "=", "global", ";", "var", "length", "=", "array", ".", "length", "||", "0", ",", "i", ";", "if", "(", "typeof", "array", "==", "\"string\"", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "block", ".", "call", "(", "context", ",", "array", ".", "charAt", "(", "i", ")", ",", "i", ",", "array", ")", ";", "}", "}", "else", "{", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "if", "(", "i", "in", "array", ")", "block", ".", "call", "(", "context", ",", "array", "[", "i", "]", ",", "i", ",", "array", ")", ";", "}", "}", "}" ]
These are the two core enumeration methods. All other forEach methods eventually call one of these two.
[ "These", "are", "the", "two", "core", "enumeration", "methods", ".", "All", "other", "forEach", "methods", "eventually", "call", "one", "of", "these", "two", "." ]
3edb471e12ce7f7d46dc1606c7f659ff45675a29
https://github.com/dperini/nwmatcher/blob/3edb471e12ce7f7d46dc1606c7f659ff45675a29/build/packer/base2.js#L993-L1011
train
nib-health-funds/gulp-rev-delete-original
index.js
function() { if(file.revOrigPath) { rimraf(file.revOrigPath, function(err) { if (err) return cb(err); cb(null, file); }); } else { cb(null); } }
javascript
function() { if(file.revOrigPath) { rimraf(file.revOrigPath, function(err) { if (err) return cb(err); cb(null, file); }); } else { cb(null); } }
[ "function", "(", ")", "{", "if", "(", "file", ".", "revOrigPath", ")", "{", "rimraf", "(", "file", ".", "revOrigPath", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "cb", "(", "null", ",", "file", ")", ";", "}", ")", ";", "}", "else", "{", "cb", "(", "null", ")", ";", "}", "}" ]
delete the original file
[ "delete", "the", "original", "file" ]
85adbb9007b328d940df10854fcfaf81c84ef657
https://github.com/nib-health-funds/gulp-rev-delete-original/blob/85adbb9007b328d940df10854fcfaf81c84ef657/index.js#L20-L29
train
Janis-ai/Janis-for-npm
examples/microsoft/nodejs/index.js
function(message) { // Send notification as a proactive message var activity = message.activity var reference = TurnContext.getConversationReference(activity); MicrosoftAppCredentials.trustServiceUrl(activity.serviceUrl); adapter.continueConversation(reference, async (context) => { // Complete the job. await bot.processChatResponse(context, message); }); }
javascript
function(message) { // Send notification as a proactive message var activity = message.activity var reference = TurnContext.getConversationReference(activity); MicrosoftAppCredentials.trustServiceUrl(activity.serviceUrl); adapter.continueConversation(reference, async (context) => { // Complete the job. await bot.processChatResponse(context, message); }); }
[ "function", "(", "message", ")", "{", "var", "activity", "=", "message", ".", "activity", "var", "reference", "=", "TurnContext", ".", "getConversationReference", "(", "activity", ")", ";", "MicrosoftAppCredentials", ".", "trustServiceUrl", "(", "activity", ".", "serviceUrl", ")", ";", "adapter", ".", "continueConversation", "(", "reference", ",", "async", "(", "context", ")", "=>", "{", "await", "bot", ".", "processChatResponse", "(", "context", ",", "message", ")", ";", "}", ")", ";", "}" ]
Handle forwarding the messages sent by a human through your bot
[ "Handle", "forwarding", "the", "messages", "sent", "by", "a", "human", "through", "your", "bot" ]
4d4c7e4072d8c8b9300e0dd47bbce43c51f685bd
https://github.com/Janis-ai/Janis-for-npm/blob/4d4c7e4072d8c8b9300e0dd47bbce43c51f685bd/examples/microsoft/nodejs/index.js#L43-L53
train
kmiyashiro/grunt-mocha
phantomjs/bridge.js
sendMessage
function sendMessage() { var cache = []; var args = [].slice.call(arguments); // Safe stringifying of cyclical JSON function decycle(key, val) { if (typeof val === 'object' && val !== null) { if (cache.indexOf(val) >= 0) return; cache.push(val); } return val; } alert(JSON.stringify(args, decycle)); }
javascript
function sendMessage() { var cache = []; var args = [].slice.call(arguments); // Safe stringifying of cyclical JSON function decycle(key, val) { if (typeof val === 'object' && val !== null) { if (cache.indexOf(val) >= 0) return; cache.push(val); } return val; } alert(JSON.stringify(args, decycle)); }
[ "function", "sendMessage", "(", ")", "{", "var", "cache", "=", "[", "]", ";", "var", "args", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ")", ";", "function", "decycle", "(", "key", ",", "val", ")", "{", "if", "(", "typeof", "val", "===", "'object'", "&&", "val", "!==", "null", ")", "{", "if", "(", "cache", ".", "indexOf", "(", "val", ")", ">=", "0", ")", "return", ";", "cache", ".", "push", "(", "val", ")", ";", "}", "return", "val", ";", "}", "alert", "(", "JSON", ".", "stringify", "(", "args", ",", "decycle", ")", ")", ";", "}" ]
Send messages to the parent phantom.js process via alert! Good times!!
[ "Send", "messages", "to", "the", "parent", "phantom", ".", "js", "process", "via", "alert!", "Good", "times!!" ]
88a4fe36bdf223c9aa3eac5a88dc765c7c60e3b9
https://github.com/kmiyashiro/grunt-mocha/blob/88a4fe36bdf223c9aa3eac5a88dc765c7c60e3b9/phantomjs/bridge.js#L26-L40
train
kmiyashiro/grunt-mocha
phantomjs/bridge.js
decycle
function decycle(key, val) { if (typeof val === 'object' && val !== null) { if (cache.indexOf(val) >= 0) return; cache.push(val); } return val; }
javascript
function decycle(key, val) { if (typeof val === 'object' && val !== null) { if (cache.indexOf(val) >= 0) return; cache.push(val); } return val; }
[ "function", "decycle", "(", "key", ",", "val", ")", "{", "if", "(", "typeof", "val", "===", "'object'", "&&", "val", "!==", "null", ")", "{", "if", "(", "cache", ".", "indexOf", "(", "val", ")", ">=", "0", ")", "return", ";", "cache", ".", "push", "(", "val", ")", ";", "}", "return", "val", ";", "}" ]
Safe stringifying of cyclical JSON
[ "Safe", "stringifying", "of", "cyclical", "JSON" ]
88a4fe36bdf223c9aa3eac5a88dc765c7c60e3b9
https://github.com/kmiyashiro/grunt-mocha/blob/88a4fe36bdf223c9aa3eac5a88dc765c7c60e3b9/phantomjs/bridge.js#L31-L37
train
kmiyashiro/grunt-mocha
phantomjs/bridge.js
createGruntListener
function createGruntListener(ev, runner) { runner.on(ev, function(test, err) { var data = { err: err }; if (test) { data.title = test.title; data.fullTitle = test.fullTitle(); data.state = test.state; data.duration = test.duration; data.slow = test.slow; data.pending = test.isPending(); } sendMessage('mocha.' + ev, data); }); }
javascript
function createGruntListener(ev, runner) { runner.on(ev, function(test, err) { var data = { err: err }; if (test) { data.title = test.title; data.fullTitle = test.fullTitle(); data.state = test.state; data.duration = test.duration; data.slow = test.slow; data.pending = test.isPending(); } sendMessage('mocha.' + ev, data); }); }
[ "function", "createGruntListener", "(", "ev", ",", "runner", ")", "{", "runner", ".", "on", "(", "ev", ",", "function", "(", "test", ",", "err", ")", "{", "var", "data", "=", "{", "err", ":", "err", "}", ";", "if", "(", "test", ")", "{", "data", ".", "title", "=", "test", ".", "title", ";", "data", ".", "fullTitle", "=", "test", ".", "fullTitle", "(", ")", ";", "data", ".", "state", "=", "test", ".", "state", ";", "data", ".", "duration", "=", "test", ".", "duration", ";", "data", ".", "slow", "=", "test", ".", "slow", ";", "data", ".", "pending", "=", "test", ".", "isPending", "(", ")", ";", "}", "sendMessage", "(", "'mocha.'", "+", "ev", ",", "data", ")", ";", "}", ")", ";", "}" ]
Create a listener who'll bubble events from PhantomJS to Grunt
[ "Create", "a", "listener", "who", "ll", "bubble", "events", "from", "PhantomJS", "to", "Grunt" ]
88a4fe36bdf223c9aa3eac5a88dc765c7c60e3b9
https://github.com/kmiyashiro/grunt-mocha/blob/88a4fe36bdf223c9aa3eac5a88dc765c7c60e3b9/phantomjs/bridge.js#L43-L60
train
kmiyashiro/grunt-mocha
tasks/mocha.js
function(err) { var stats = runner.stats; testStats.push(stats); if (err) { // Show Growl notice // @TODO: Get an example of this // growl('PhantomJS Error!'); // If there was a PhantomJS error, abort the series. grunt.fatal(err); done(false); } else { // If failures, show growl notice if (stats.failures > 0) { var reduced = helpers.reduceStats([stats]); var failMsg = reduced.failures + '/' + reduced.tests + ' tests failed (' + reduced.duration + 's)'; // Show Growl notice, if avail growl(failMsg, { image: asset('growl/error.png'), title: 'Failure in ' + grunt.task.current.target, priority: 3 }); // Bail tests if bail option is true if (options.bail) grunt.warn(failMsg); } // Process next file/url next(); } }
javascript
function(err) { var stats = runner.stats; testStats.push(stats); if (err) { // Show Growl notice // @TODO: Get an example of this // growl('PhantomJS Error!'); // If there was a PhantomJS error, abort the series. grunt.fatal(err); done(false); } else { // If failures, show growl notice if (stats.failures > 0) { var reduced = helpers.reduceStats([stats]); var failMsg = reduced.failures + '/' + reduced.tests + ' tests failed (' + reduced.duration + 's)'; // Show Growl notice, if avail growl(failMsg, { image: asset('growl/error.png'), title: 'Failure in ' + grunt.task.current.target, priority: 3 }); // Bail tests if bail option is true if (options.bail) grunt.warn(failMsg); } // Process next file/url next(); } }
[ "function", "(", "err", ")", "{", "var", "stats", "=", "runner", ".", "stats", ";", "testStats", ".", "push", "(", "stats", ")", ";", "if", "(", "err", ")", "{", "grunt", ".", "fatal", "(", "err", ")", ";", "done", "(", "false", ")", ";", "}", "else", "{", "if", "(", "stats", ".", "failures", ">", "0", ")", "{", "var", "reduced", "=", "helpers", ".", "reduceStats", "(", "[", "stats", "]", ")", ";", "var", "failMsg", "=", "reduced", ".", "failures", "+", "'/'", "+", "reduced", ".", "tests", "+", "' tests failed ('", "+", "reduced", ".", "duration", "+", "'s)'", ";", "growl", "(", "failMsg", ",", "{", "image", ":", "asset", "(", "'growl/error.png'", ")", ",", "title", ":", "'Failure in '", "+", "grunt", ".", "task", ".", "current", ".", "target", ",", "priority", ":", "3", "}", ")", ";", "if", "(", "options", ".", "bail", ")", "grunt", ".", "warn", "(", "failMsg", ")", ";", "}", "next", "(", ")", ";", "}", "}" ]
Do stuff when done.
[ "Do", "stuff", "when", "done", "." ]
88a4fe36bdf223c9aa3eac5a88dc765c7c60e3b9
https://github.com/kmiyashiro/grunt-mocha/blob/88a4fe36bdf223c9aa3eac5a88dc765c7c60e3b9/tasks/mocha.js#L248-L281
train
kmiyashiro/grunt-mocha
phantomjs/main.js
function(arg) { var args = Array.isArray(arg) ? arg : [].slice.call(arguments); last = new Date(); fs.write(tmpfile, JSON.stringify(args) + '\n', 'a'); }
javascript
function(arg) { var args = Array.isArray(arg) ? arg : [].slice.call(arguments); last = new Date(); fs.write(tmpfile, JSON.stringify(args) + '\n', 'a'); }
[ "function", "(", "arg", ")", "{", "var", "args", "=", "Array", ".", "isArray", "(", "arg", ")", "?", "arg", ":", "[", "]", ".", "slice", ".", "call", "(", "arguments", ")", ";", "last", "=", "new", "Date", "(", ")", ";", "fs", ".", "write", "(", "tmpfile", ",", "JSON", ".", "stringify", "(", "args", ")", "+", "'\\n'", ",", "\\n", ")", ";", "}" ]
Messages are sent to the parent by appending them to the tempfile.
[ "Messages", "are", "sent", "to", "the", "parent", "by", "appending", "them", "to", "the", "tempfile", "." ]
88a4fe36bdf223c9aa3eac5a88dc765c7c60e3b9
https://github.com/kmiyashiro/grunt-mocha/blob/88a4fe36bdf223c9aa3eac5a88dc765c7c60e3b9/phantomjs/main.js#L30-L34
train
mqlight/nodejs-mqlight
samples/uiworkout.js
bluemixServiceLookup
function bluemixServiceLookup(options, verbose) { var result = false; if (process.env.VCAP_SERVICES) { if (verbose) console.log('VCAP_SERVICES variable present in environment'); var services = JSON.parse(process.env.VCAP_SERVICES); for (var key in services) { if (key.lastIndexOf(mqlightServiceName, 0) === 0) { var mqlightService = services[key][0]; options.service = mqlightService.credentials.connectionLookupURI; options.user = mqlightService.credentials.username; options.password = mqlightService.credentials.password; } else if (key.lastIndexOf(messageHubServiceName, 0) === 0) { var messageHubService = services[key][0]; options.service = messageHubService.credentials.mqlight_lookup_url; options.user = messageHubService.credentials.user; options.password = messageHubService.credentials.password; } } if (!options.hasOwnProperty('service') || !options.hasOwnProperty('user') || !options.hasOwnProperty('password')) { throw 'Error - Check that app is bound to service'; } result = true; } else if (verbose) { console.log('VCAP_SERVICES variable not present in environment'); } return result; }
javascript
function bluemixServiceLookup(options, verbose) { var result = false; if (process.env.VCAP_SERVICES) { if (verbose) console.log('VCAP_SERVICES variable present in environment'); var services = JSON.parse(process.env.VCAP_SERVICES); for (var key in services) { if (key.lastIndexOf(mqlightServiceName, 0) === 0) { var mqlightService = services[key][0]; options.service = mqlightService.credentials.connectionLookupURI; options.user = mqlightService.credentials.username; options.password = mqlightService.credentials.password; } else if (key.lastIndexOf(messageHubServiceName, 0) === 0) { var messageHubService = services[key][0]; options.service = messageHubService.credentials.mqlight_lookup_url; options.user = messageHubService.credentials.user; options.password = messageHubService.credentials.password; } } if (!options.hasOwnProperty('service') || !options.hasOwnProperty('user') || !options.hasOwnProperty('password')) { throw 'Error - Check that app is bound to service'; } result = true; } else if (verbose) { console.log('VCAP_SERVICES variable not present in environment'); } return result; }
[ "function", "bluemixServiceLookup", "(", "options", ",", "verbose", ")", "{", "var", "result", "=", "false", ";", "if", "(", "process", ".", "env", ".", "VCAP_SERVICES", ")", "{", "if", "(", "verbose", ")", "console", ".", "log", "(", "'VCAP_SERVICES variable present in environment'", ")", ";", "var", "services", "=", "JSON", ".", "parse", "(", "process", ".", "env", ".", "VCAP_SERVICES", ")", ";", "for", "(", "var", "key", "in", "services", ")", "{", "if", "(", "key", ".", "lastIndexOf", "(", "mqlightServiceName", ",", "0", ")", "===", "0", ")", "{", "var", "mqlightService", "=", "services", "[", "key", "]", "[", "0", "]", ";", "options", ".", "service", "=", "mqlightService", ".", "credentials", ".", "connectionLookupURI", ";", "options", ".", "user", "=", "mqlightService", ".", "credentials", ".", "username", ";", "options", ".", "password", "=", "mqlightService", ".", "credentials", ".", "password", ";", "}", "else", "if", "(", "key", ".", "lastIndexOf", "(", "messageHubServiceName", ",", "0", ")", "===", "0", ")", "{", "var", "messageHubService", "=", "services", "[", "key", "]", "[", "0", "]", ";", "options", ".", "service", "=", "messageHubService", ".", "credentials", ".", "mqlight_lookup_url", ";", "options", ".", "user", "=", "messageHubService", ".", "credentials", ".", "user", ";", "options", ".", "password", "=", "messageHubService", ".", "credentials", ".", "password", ";", "}", "}", "if", "(", "!", "options", ".", "hasOwnProperty", "(", "'service'", ")", "||", "!", "options", ".", "hasOwnProperty", "(", "'user'", ")", "||", "!", "options", ".", "hasOwnProperty", "(", "'password'", ")", ")", "{", "throw", "'Error - Check that app is bound to service'", ";", "}", "result", "=", "true", ";", "}", "else", "if", "(", "verbose", ")", "{", "console", ".", "log", "(", "'VCAP_SERVICES variable not present in environment'", ")", ";", "}", "return", "result", ";", "}" ]
Checks to see if the application is running in IBM Bluemix. If it is, tries to retrieve connection details from the environent and populates the options object passed as an argument.
[ "Checks", "to", "see", "if", "the", "application", "is", "running", "in", "IBM", "Bluemix", ".", "If", "it", "is", "tries", "to", "retrieve", "connection", "details", "from", "the", "environent", "and", "populates", "the", "options", "object", "passed", "as", "an", "argument", "." ]
cf20a62d003fe6052569124bb85957d02ddb93ab
https://github.com/mqlight/nodejs-mqlight/blob/cf20a62d003fe6052569124bb85957d02ddb93ab/samples/uiworkout.js#L184-L212
train
mqlight/nodejs-mqlight
mqlight.js
setupError
function setupError(obj, name, message) { if (obj) { Error.call(obj); Object.defineProperty(obj, 'name', { value: name, enumerable: false }); Object.defineProperty(obj, 'message', { value: message, enumerable: false }); } else { logger.ffdc('setupError', 'ffdc001', null, 'Client object not provided'); } }
javascript
function setupError(obj, name, message) { if (obj) { Error.call(obj); Object.defineProperty(obj, 'name', { value: name, enumerable: false }); Object.defineProperty(obj, 'message', { value: message, enumerable: false }); } else { logger.ffdc('setupError', 'ffdc001', null, 'Client object not provided'); } }
[ "function", "setupError", "(", "obj", ",", "name", ",", "message", ")", "{", "if", "(", "obj", ")", "{", "Error", ".", "call", "(", "obj", ")", ";", "Object", ".", "defineProperty", "(", "obj", ",", "'name'", ",", "{", "value", ":", "name", ",", "enumerable", ":", "false", "}", ")", ";", "Object", ".", "defineProperty", "(", "obj", ",", "'message'", ",", "{", "value", ":", "message", ",", "enumerable", ":", "false", "}", ")", ";", "}", "else", "{", "logger", ".", "ffdc", "(", "'setupError'", ",", "'ffdc001'", ",", "null", ",", "'Client object not provided'", ")", ";", "}", "}" ]
Generic helper method to use for Error sub-typing @param {Object} obj - the object upon which to define Error properties @param {String} name - the sub-type Error object name @param {String} message - Human-readable description of the error
[ "Generic", "helper", "method", "to", "use", "for", "Error", "sub", "-", "typing" ]
cf20a62d003fe6052569124bb85957d02ddb93ab
https://github.com/mqlight/nodejs-mqlight/blob/cf20a62d003fe6052569124bb85957d02ddb93ab/mqlight.js#L125-L139
train
mqlight/nodejs-mqlight
mqlight.js
getNamedError
function getNamedError(obj) { if (obj && obj instanceof Error && 'name' in obj) { var Constructor = exports[obj.name]; if (typeof Constructor === 'function') { var res = new Constructor(obj.message); if (res) { res.stack = obj.stack; return res; } } } return obj; }
javascript
function getNamedError(obj) { if (obj && obj instanceof Error && 'name' in obj) { var Constructor = exports[obj.name]; if (typeof Constructor === 'function') { var res = new Constructor(obj.message); if (res) { res.stack = obj.stack; return res; } } } return obj; }
[ "function", "getNamedError", "(", "obj", ")", "{", "if", "(", "obj", "&&", "obj", "instanceof", "Error", "&&", "'name'", "in", "obj", ")", "{", "var", "Constructor", "=", "exports", "[", "obj", ".", "name", "]", ";", "if", "(", "typeof", "Constructor", "===", "'function'", ")", "{", "var", "res", "=", "new", "Constructor", "(", "obj", ".", "message", ")", ";", "if", "(", "res", ")", "{", "res", ".", "stack", "=", "obj", ".", "stack", ";", "return", "res", ";", "}", "}", "}", "return", "obj", ";", "}" ]
Generic helper method to map a named Error object into the correct sub-type so that instanceof checking works as expected. @param {Object} obj - the Error object to remap. @return {Object} a sub-typed Error object.
[ "Generic", "helper", "method", "to", "map", "a", "named", "Error", "object", "into", "the", "correct", "sub", "-", "type", "so", "that", "instanceof", "checking", "works", "as", "expected", "." ]
cf20a62d003fe6052569124bb85957d02ddb93ab
https://github.com/mqlight/nodejs-mqlight/blob/cf20a62d003fe6052569124bb85957d02ddb93ab/mqlight.js#L149-L161
train
mqlight/nodejs-mqlight
mqlight.js
shouldReconnect
function shouldReconnect(err) { // exclude all programming errors return (!(err instanceof TypeError) && !(err instanceof InvalidArgumentError) && !(err instanceof NotPermittedError) && !(err instanceof ReplacedError) && !(err instanceof StoppedError) && !(err instanceof SubscribedError) && !(err instanceof UnsubscribedError) ); }
javascript
function shouldReconnect(err) { // exclude all programming errors return (!(err instanceof TypeError) && !(err instanceof InvalidArgumentError) && !(err instanceof NotPermittedError) && !(err instanceof ReplacedError) && !(err instanceof StoppedError) && !(err instanceof SubscribedError) && !(err instanceof UnsubscribedError) ); }
[ "function", "shouldReconnect", "(", "err", ")", "{", "return", "(", "!", "(", "err", "instanceof", "TypeError", ")", "&&", "!", "(", "err", "instanceof", "InvalidArgumentError", ")", "&&", "!", "(", "err", "instanceof", "NotPermittedError", ")", "&&", "!", "(", "err", "instanceof", "ReplacedError", ")", "&&", "!", "(", "err", "instanceof", "StoppedError", ")", "&&", "!", "(", "err", "instanceof", "SubscribedError", ")", "&&", "!", "(", "err", "instanceof", "UnsubscribedError", ")", ")", ";", "}" ]
Generic helper method to determine if we should automatically reconnect for the given type of error. @param {Object} err - the Error object to check. @return {Object} true if we should reconnect, false otherwise.
[ "Generic", "helper", "method", "to", "determine", "if", "we", "should", "automatically", "reconnect", "for", "the", "given", "type", "of", "error", "." ]
cf20a62d003fe6052569124bb85957d02ddb93ab
https://github.com/mqlight/nodejs-mqlight/blob/cf20a62d003fe6052569124bb85957d02ddb93ab/mqlight.js#L332-L342
train
mqlight/nodejs-mqlight
mqlight.js
function(fileUrl) { logger.entry('getFileServiceFunction', logger.NO_CLIENT_ID); logger.log('parms', logger.NO_CLIENT_ID, 'fileUrl:', fileUrl); if (typeof fileUrl !== 'string') { var err = new TypeError('fileUrl must be a string type'); logger.ffdc('getFileServiceFunction', 'ffdc001', null, err); logger.throw('getFileServiceFunction', logger.NO_CLIENT_ID, err); throw err; } var filePath = fileUrl; // special case for Windows drive letters in file URIs, trim the leading / if (os.platform() === 'win32' && filePath.match('^/[a-zA-Z]:/')) { filePath = filePath.substring(1); } var fileServiceFunction = function(callback) { logger.entry('fileServiceFunction', logger.NO_CLIENT_ID); logger.log('parms', logger.NO_CLIENT_ID, 'filePath:', filePath); fs.readFile(filePath, {encoding: 'utf8'}, function(err, data) { logger.entry('fileServiceFunction.readFile.callback', logger.NO_CLIENT_ID); logger.log('parms', logger.NO_CLIENT_ID, 'err:', err); logger.log('parms', logger.NO_CLIENT_ID, 'data:', data); if (err) { err.message = 'attempt to read ' + filePath + ' failed with the ' + 'following error: ' + err.message; logger.log('error', logger.NO_CLIENT_ID, err); logger.entry('fileServiceFunction.callback', logger.NO_CLIENT_ID); logger.log('parms', logger.NO_CLIENT_ID, 'err:', err); callback(err); logger.exit('fileServiceFunction.callback', logger.NO_CLIENT_ID, null); } else { var obj; try { obj = JSON.parse(data); } catch (err) { err.message = 'the content read from ' + filePath + ' contained ' + 'unparseable JSON: ' + err.message; logger.caught('fileServiceFunction.readFile.callback', logger.NO_CLIENT_ID, err); logger.entry('fileServiceFunction.callback', logger.NO_CLIENT_ID); logger.log('parms', logger.NO_CLIENT_ID, 'err:', err); callback(err); logger.exit('fileServiceFunction.callback', logger.NO_CLIENT_ID, null); } if (obj) { logger.entry('fileServiceFunction.callback', logger.NO_CLIENT_ID); logger.log('parms', logger.NO_CLIENT_ID, 'service:', obj.service); callback(null, obj.service); logger.exit('fileServiceFunction.callback', logger.NO_CLIENT_ID, null); } } logger.exit('fileServiceFunction.readFile.callback', logger.NO_CLIENT_ID, null); }); logger.exit('fileServiceFunction', logger.NO_CLIENT_ID, null); }; logger.exit('getFileServiceFunction', logger.NO_CLIENT_ID, fileServiceFunction); return fileServiceFunction; }
javascript
function(fileUrl) { logger.entry('getFileServiceFunction', logger.NO_CLIENT_ID); logger.log('parms', logger.NO_CLIENT_ID, 'fileUrl:', fileUrl); if (typeof fileUrl !== 'string') { var err = new TypeError('fileUrl must be a string type'); logger.ffdc('getFileServiceFunction', 'ffdc001', null, err); logger.throw('getFileServiceFunction', logger.NO_CLIENT_ID, err); throw err; } var filePath = fileUrl; // special case for Windows drive letters in file URIs, trim the leading / if (os.platform() === 'win32' && filePath.match('^/[a-zA-Z]:/')) { filePath = filePath.substring(1); } var fileServiceFunction = function(callback) { logger.entry('fileServiceFunction', logger.NO_CLIENT_ID); logger.log('parms', logger.NO_CLIENT_ID, 'filePath:', filePath); fs.readFile(filePath, {encoding: 'utf8'}, function(err, data) { logger.entry('fileServiceFunction.readFile.callback', logger.NO_CLIENT_ID); logger.log('parms', logger.NO_CLIENT_ID, 'err:', err); logger.log('parms', logger.NO_CLIENT_ID, 'data:', data); if (err) { err.message = 'attempt to read ' + filePath + ' failed with the ' + 'following error: ' + err.message; logger.log('error', logger.NO_CLIENT_ID, err); logger.entry('fileServiceFunction.callback', logger.NO_CLIENT_ID); logger.log('parms', logger.NO_CLIENT_ID, 'err:', err); callback(err); logger.exit('fileServiceFunction.callback', logger.NO_CLIENT_ID, null); } else { var obj; try { obj = JSON.parse(data); } catch (err) { err.message = 'the content read from ' + filePath + ' contained ' + 'unparseable JSON: ' + err.message; logger.caught('fileServiceFunction.readFile.callback', logger.NO_CLIENT_ID, err); logger.entry('fileServiceFunction.callback', logger.NO_CLIENT_ID); logger.log('parms', logger.NO_CLIENT_ID, 'err:', err); callback(err); logger.exit('fileServiceFunction.callback', logger.NO_CLIENT_ID, null); } if (obj) { logger.entry('fileServiceFunction.callback', logger.NO_CLIENT_ID); logger.log('parms', logger.NO_CLIENT_ID, 'service:', obj.service); callback(null, obj.service); logger.exit('fileServiceFunction.callback', logger.NO_CLIENT_ID, null); } } logger.exit('fileServiceFunction.readFile.callback', logger.NO_CLIENT_ID, null); }); logger.exit('fileServiceFunction', logger.NO_CLIENT_ID, null); }; logger.exit('getFileServiceFunction', logger.NO_CLIENT_ID, fileServiceFunction); return fileServiceFunction; }
[ "function", "(", "fileUrl", ")", "{", "logger", ".", "entry", "(", "'getFileServiceFunction'", ",", "logger", ".", "NO_CLIENT_ID", ")", ";", "logger", ".", "log", "(", "'parms'", ",", "logger", ".", "NO_CLIENT_ID", ",", "'fileUrl:'", ",", "fileUrl", ")", ";", "if", "(", "typeof", "fileUrl", "!==", "'string'", ")", "{", "var", "err", "=", "new", "TypeError", "(", "'fileUrl must be a string type'", ")", ";", "logger", ".", "ffdc", "(", "'getFileServiceFunction'", ",", "'ffdc001'", ",", "null", ",", "err", ")", ";", "logger", ".", "throw", "(", "'getFileServiceFunction'", ",", "logger", ".", "NO_CLIENT_ID", ",", "err", ")", ";", "throw", "err", ";", "}", "var", "filePath", "=", "fileUrl", ";", "if", "(", "os", ".", "platform", "(", ")", "===", "'win32'", "&&", "filePath", ".", "match", "(", "'^/[a-zA-Z]:/'", ")", ")", "{", "filePath", "=", "filePath", ".", "substring", "(", "1", ")", ";", "}", "var", "fileServiceFunction", "=", "function", "(", "callback", ")", "{", "logger", ".", "entry", "(", "'fileServiceFunction'", ",", "logger", ".", "NO_CLIENT_ID", ")", ";", "logger", ".", "log", "(", "'parms'", ",", "logger", ".", "NO_CLIENT_ID", ",", "'filePath:'", ",", "filePath", ")", ";", "fs", ".", "readFile", "(", "filePath", ",", "{", "encoding", ":", "'utf8'", "}", ",", "function", "(", "err", ",", "data", ")", "{", "logger", ".", "entry", "(", "'fileServiceFunction.readFile.callback'", ",", "logger", ".", "NO_CLIENT_ID", ")", ";", "logger", ".", "log", "(", "'parms'", ",", "logger", ".", "NO_CLIENT_ID", ",", "'err:'", ",", "err", ")", ";", "logger", ".", "log", "(", "'parms'", ",", "logger", ".", "NO_CLIENT_ID", ",", "'data:'", ",", "data", ")", ";", "if", "(", "err", ")", "{", "err", ".", "message", "=", "'attempt to read '", "+", "filePath", "+", "' failed with the '", "+", "'following error: '", "+", "err", ".", "message", ";", "logger", ".", "log", "(", "'error'", ",", "logger", ".", "NO_CLIENT_ID", ",", "err", ")", ";", "logger", ".", "entry", "(", "'fileServiceFunction.callback'", ",", "logger", ".", "NO_CLIENT_ID", ")", ";", "logger", ".", "log", "(", "'parms'", ",", "logger", ".", "NO_CLIENT_ID", ",", "'err:'", ",", "err", ")", ";", "callback", "(", "err", ")", ";", "logger", ".", "exit", "(", "'fileServiceFunction.callback'", ",", "logger", ".", "NO_CLIENT_ID", ",", "null", ")", ";", "}", "else", "{", "var", "obj", ";", "try", "{", "obj", "=", "JSON", ".", "parse", "(", "data", ")", ";", "}", "catch", "(", "err", ")", "{", "err", ".", "message", "=", "'the content read from '", "+", "filePath", "+", "' contained '", "+", "'unparseable JSON: '", "+", "err", ".", "message", ";", "logger", ".", "caught", "(", "'fileServiceFunction.readFile.callback'", ",", "logger", ".", "NO_CLIENT_ID", ",", "err", ")", ";", "logger", ".", "entry", "(", "'fileServiceFunction.callback'", ",", "logger", ".", "NO_CLIENT_ID", ")", ";", "logger", ".", "log", "(", "'parms'", ",", "logger", ".", "NO_CLIENT_ID", ",", "'err:'", ",", "err", ")", ";", "callback", "(", "err", ")", ";", "logger", ".", "exit", "(", "'fileServiceFunction.callback'", ",", "logger", ".", "NO_CLIENT_ID", ",", "null", ")", ";", "}", "if", "(", "obj", ")", "{", "logger", ".", "entry", "(", "'fileServiceFunction.callback'", ",", "logger", ".", "NO_CLIENT_ID", ")", ";", "logger", ".", "log", "(", "'parms'", ",", "logger", ".", "NO_CLIENT_ID", ",", "'service:'", ",", "obj", ".", "service", ")", ";", "callback", "(", "null", ",", "obj", ".", "service", ")", ";", "logger", ".", "exit", "(", "'fileServiceFunction.callback'", ",", "logger", ".", "NO_CLIENT_ID", ",", "null", ")", ";", "}", "}", "logger", ".", "exit", "(", "'fileServiceFunction.readFile.callback'", ",", "logger", ".", "NO_CLIENT_ID", ",", "null", ")", ";", "}", ")", ";", "logger", ".", "exit", "(", "'fileServiceFunction'", ",", "logger", ".", "NO_CLIENT_ID", ",", "null", ")", ";", "}", ";", "logger", ".", "exit", "(", "'getFileServiceFunction'", ",", "logger", ".", "NO_CLIENT_ID", ",", "fileServiceFunction", ")", ";", "return", "fileServiceFunction", ";", "}" ]
Function to take a single FILE URL and using the JSON retrieved from it to return an array of service URLs. @param {String} fileUrl - Required; a FILE address to retrieve service info from (e.g., file:///tmp/config.json). @return {function(callback)} a function which will call the given callback with a list of AMQP service URLs retrieved from the FILE. @throws TypeError If fileUrl is not a string. @throws Error if an unsupported or invalid FILE address is specified.
[ "Function", "to", "take", "a", "single", "FILE", "URL", "and", "using", "the", "JSON", "retrieved", "from", "it", "to", "return", "an", "array", "of", "service", "URLs", "." ]
cf20a62d003fe6052569124bb85957d02ddb93ab
https://github.com/mqlight/nodejs-mqlight/blob/cf20a62d003fe6052569124bb85957d02ddb93ab/mqlight.js#L358-L426
train
mqlight/nodejs-mqlight
mqlight.js
function(client) { if (typeof client === 'undefined'/* || client.constructor !== Client*/) { logger.entry('Client.reconnect', logger.NO_CLIENT_ID); logger.log('parms', logger.NO_CLIENT_ID, 'client:', client); logger.exit('Client.reconnect', logger.NO_CLIENT_ID, undefined); return; } logger.entry('Client.reconnect', client.id); if (client.state !== STATE_STARTED) { if (client.isStopped()) { logger.exit('Client.reconnect', client.id, null); return; } else if (client.state === STATE_RETRYING) { logger.exit('Client.reconnect', client.id, client); return client; } } client._setState(STATE_RETRYING); setImmediate(function() { // stop the messenger to free the object then attempt a reconnect stopMessenger(client, function(client) { logger.entry('Client.reconnect.stopProcessing', client.id); // clear the subscriptions list, if the cause of the reconnect happens // during check for messages we need a 0 length so it will check once // reconnected. logger.log('data', client.id, 'client._subscriptions:', client._subscriptions); while (client._subscriptions.length > 0) { client._queuedSubscriptions.push(client._subscriptions.shift()); } // also clear any left over outstanding sends while (client._outstandingSends.length > 0) { client._outstandingSends.shift(); } client._queuedStartCallbacks.push({ callback: processQueuedActions, create: false }); process.nextTick(function() { client._performConnect(false, true); }); logger.exit('Client.reconnect.stopProcessing', client.id, null); }); }); logger.exit('Client.reconnect', client.id, client); return client; }
javascript
function(client) { if (typeof client === 'undefined'/* || client.constructor !== Client*/) { logger.entry('Client.reconnect', logger.NO_CLIENT_ID); logger.log('parms', logger.NO_CLIENT_ID, 'client:', client); logger.exit('Client.reconnect', logger.NO_CLIENT_ID, undefined); return; } logger.entry('Client.reconnect', client.id); if (client.state !== STATE_STARTED) { if (client.isStopped()) { logger.exit('Client.reconnect', client.id, null); return; } else if (client.state === STATE_RETRYING) { logger.exit('Client.reconnect', client.id, client); return client; } } client._setState(STATE_RETRYING); setImmediate(function() { // stop the messenger to free the object then attempt a reconnect stopMessenger(client, function(client) { logger.entry('Client.reconnect.stopProcessing', client.id); // clear the subscriptions list, if the cause of the reconnect happens // during check for messages we need a 0 length so it will check once // reconnected. logger.log('data', client.id, 'client._subscriptions:', client._subscriptions); while (client._subscriptions.length > 0) { client._queuedSubscriptions.push(client._subscriptions.shift()); } // also clear any left over outstanding sends while (client._outstandingSends.length > 0) { client._outstandingSends.shift(); } client._queuedStartCallbacks.push({ callback: processQueuedActions, create: false }); process.nextTick(function() { client._performConnect(false, true); }); logger.exit('Client.reconnect.stopProcessing', client.id, null); }); }); logger.exit('Client.reconnect', client.id, client); return client; }
[ "function", "(", "client", ")", "{", "if", "(", "typeof", "client", "===", "'undefined'", ")", "{", "logger", ".", "entry", "(", "'Client.reconnect'", ",", "logger", ".", "NO_CLIENT_ID", ")", ";", "logger", ".", "log", "(", "'parms'", ",", "logger", ".", "NO_CLIENT_ID", ",", "'client:'", ",", "client", ")", ";", "logger", ".", "exit", "(", "'Client.reconnect'", ",", "logger", ".", "NO_CLIENT_ID", ",", "undefined", ")", ";", "return", ";", "}", "logger", ".", "entry", "(", "'Client.reconnect'", ",", "client", ".", "id", ")", ";", "if", "(", "client", ".", "state", "!==", "STATE_STARTED", ")", "{", "if", "(", "client", ".", "isStopped", "(", ")", ")", "{", "logger", ".", "exit", "(", "'Client.reconnect'", ",", "client", ".", "id", ",", "null", ")", ";", "return", ";", "}", "else", "if", "(", "client", ".", "state", "===", "STATE_RETRYING", ")", "{", "logger", ".", "exit", "(", "'Client.reconnect'", ",", "client", ".", "id", ",", "client", ")", ";", "return", "client", ";", "}", "}", "client", ".", "_setState", "(", "STATE_RETRYING", ")", ";", "setImmediate", "(", "function", "(", ")", "{", "stopMessenger", "(", "client", ",", "function", "(", "client", ")", "{", "logger", ".", "entry", "(", "'Client.reconnect.stopProcessing'", ",", "client", ".", "id", ")", ";", "logger", ".", "log", "(", "'data'", ",", "client", ".", "id", ",", "'client._subscriptions:'", ",", "client", ".", "_subscriptions", ")", ";", "while", "(", "client", ".", "_subscriptions", ".", "length", ">", "0", ")", "{", "client", ".", "_queuedSubscriptions", ".", "push", "(", "client", ".", "_subscriptions", ".", "shift", "(", ")", ")", ";", "}", "while", "(", "client", ".", "_outstandingSends", ".", "length", ">", "0", ")", "{", "client", ".", "_outstandingSends", ".", "shift", "(", ")", ";", "}", "client", ".", "_queuedStartCallbacks", ".", "push", "(", "{", "callback", ":", "processQueuedActions", ",", "create", ":", "false", "}", ")", ";", "process", ".", "nextTick", "(", "function", "(", ")", "{", "client", ".", "_performConnect", "(", "false", ",", "true", ")", ";", "}", ")", ";", "logger", ".", "exit", "(", "'Client.reconnect.stopProcessing'", ",", "client", ".", "id", ",", "null", ")", ";", "}", ")", ";", "}", ")", ";", "logger", ".", "exit", "(", "'Client.reconnect'", ",", "client", ".", "id", ",", "client", ")", ";", "return", "client", ";", "}" ]
Reconnects the client to the MQ Light service, implicitly closing any subscriptions that the client has open. The 'restarted' event will be emitted once the client has reconnected. @param {client} client - the client object to reconnect @return {Object} The instance of client that it is invoked on - allowing for chaining of other method calls on the client object.
[ "Reconnects", "the", "client", "to", "the", "MQ", "Light", "service", "implicitly", "closing", "any", "subscriptions", "that", "the", "client", "has", "open", ".", "The", "restarted", "event", "will", "be", "emitted", "once", "the", "client", "has", "reconnected", "." ]
cf20a62d003fe6052569124bb85957d02ddb93ab
https://github.com/mqlight/nodejs-mqlight/blob/cf20a62d003fe6052569124bb85957d02ddb93ab/mqlight.js#L743-L793
train
mqlight/nodejs-mqlight
mqlight.js
function(error) { logger.entry('Client._tryService.tryNextService', _id); if (serviceList.length === 1) { // We've tried all services without success. Pause for a while // before trying again logger.log('data', _id, 'End of service list'); client._setState(STATE_RETRYING); var retry = function() { logger.entryLevel('entry_often', 'Client._tryService.retry', _id); if (!client.isStopped()) { process.nextTick(function() { client._performConnect(false, true); }); } logger.exitLevel('exit_often', 'Client._tryService.retry', _id, null); }; client._retryCount++; var retryCap = 60000; // Limit to the power of 8 as anything above this will put the // interval higher than the cap straight away. var exponent = (client._retryCount <= 8) ? client._retryCount : 8; var upperBound = Math.pow(2, exponent); var lowerBound = 0.75 * upperBound; var jitter = Math.random() * (0.25 * upperBound); var interval = Math.min(retryCap, (lowerBound + jitter) * 1000); // times by CONNECT_RETRY_INTERVAL for unittest purposes interval = Math.round(interval) * CONNECT_RETRY_INTERVAL; logger.log('data', _id, 'trying to connect again ' + 'after ' + (interval / 1000) + ' seconds'); setTimeout(retry, interval); if (error) { setImmediate(function() { logger.log('emit', _id, 'error', error); client.emit('error', error); }); } } else { // Try the next service in the list logger.log('data', _id, 'Trying next service'); client._tryService(serviceList.slice(1)); } logger.exit('Client._tryService.tryNextService', _id, null); }
javascript
function(error) { logger.entry('Client._tryService.tryNextService', _id); if (serviceList.length === 1) { // We've tried all services without success. Pause for a while // before trying again logger.log('data', _id, 'End of service list'); client._setState(STATE_RETRYING); var retry = function() { logger.entryLevel('entry_often', 'Client._tryService.retry', _id); if (!client.isStopped()) { process.nextTick(function() { client._performConnect(false, true); }); } logger.exitLevel('exit_often', 'Client._tryService.retry', _id, null); }; client._retryCount++; var retryCap = 60000; // Limit to the power of 8 as anything above this will put the // interval higher than the cap straight away. var exponent = (client._retryCount <= 8) ? client._retryCount : 8; var upperBound = Math.pow(2, exponent); var lowerBound = 0.75 * upperBound; var jitter = Math.random() * (0.25 * upperBound); var interval = Math.min(retryCap, (lowerBound + jitter) * 1000); // times by CONNECT_RETRY_INTERVAL for unittest purposes interval = Math.round(interval) * CONNECT_RETRY_INTERVAL; logger.log('data', _id, 'trying to connect again ' + 'after ' + (interval / 1000) + ' seconds'); setTimeout(retry, interval); if (error) { setImmediate(function() { logger.log('emit', _id, 'error', error); client.emit('error', error); }); } } else { // Try the next service in the list logger.log('data', _id, 'Trying next service'); client._tryService(serviceList.slice(1)); } logger.exit('Client._tryService.tryNextService', _id, null); }
[ "function", "(", "error", ")", "{", "logger", ".", "entry", "(", "'Client._tryService.tryNextService'", ",", "_id", ")", ";", "if", "(", "serviceList", ".", "length", "===", "1", ")", "{", "logger", ".", "log", "(", "'data'", ",", "_id", ",", "'End of service list'", ")", ";", "client", ".", "_setState", "(", "STATE_RETRYING", ")", ";", "var", "retry", "=", "function", "(", ")", "{", "logger", ".", "entryLevel", "(", "'entry_often'", ",", "'Client._tryService.retry'", ",", "_id", ")", ";", "if", "(", "!", "client", ".", "isStopped", "(", ")", ")", "{", "process", ".", "nextTick", "(", "function", "(", ")", "{", "client", ".", "_performConnect", "(", "false", ",", "true", ")", ";", "}", ")", ";", "}", "logger", ".", "exitLevel", "(", "'exit_often'", ",", "'Client._tryService.retry'", ",", "_id", ",", "null", ")", ";", "}", ";", "client", ".", "_retryCount", "++", ";", "var", "retryCap", "=", "60000", ";", "var", "exponent", "=", "(", "client", ".", "_retryCount", "<=", "8", ")", "?", "client", ".", "_retryCount", ":", "8", ";", "var", "upperBound", "=", "Math", ".", "pow", "(", "2", ",", "exponent", ")", ";", "var", "lowerBound", "=", "0.75", "*", "upperBound", ";", "var", "jitter", "=", "Math", ".", "random", "(", ")", "*", "(", "0.25", "*", "upperBound", ")", ";", "var", "interval", "=", "Math", ".", "min", "(", "retryCap", ",", "(", "lowerBound", "+", "jitter", ")", "*", "1000", ")", ";", "interval", "=", "Math", ".", "round", "(", "interval", ")", "*", "CONNECT_RETRY_INTERVAL", ";", "logger", ".", "log", "(", "'data'", ",", "_id", ",", "'trying to connect again '", "+", "'after '", "+", "(", "interval", "/", "1000", ")", "+", "' seconds'", ")", ";", "setTimeout", "(", "retry", ",", "interval", ")", ";", "if", "(", "error", ")", "{", "setImmediate", "(", "function", "(", ")", "{", "logger", ".", "log", "(", "'emit'", ",", "_id", ",", "'error'", ",", "error", ")", ";", "client", ".", "emit", "(", "'error'", ",", "error", ")", ";", "}", ")", ";", "}", "}", "else", "{", "logger", ".", "log", "(", "'data'", ",", "_id", ",", "'Trying next service'", ")", ";", "client", ".", "_tryService", "(", "serviceList", ".", "slice", "(", "1", ")", ")", ";", "}", "logger", ".", "exit", "(", "'Client._tryService.tryNextService'", ",", "_id", ",", "null", ")", ";", "}" ]
Try and connect to the next service in the list, or retry from the beginning if we've run out of services.
[ "Try", "and", "connect", "to", "the", "next", "service", "in", "the", "list", "or", "retry", "from", "the", "beginning", "if", "we", "ve", "run", "out", "of", "services", "." ]
cf20a62d003fe6052569124bb85957d02ddb93ab
https://github.com/mqlight/nodejs-mqlight/blob/cf20a62d003fe6052569124bb85957d02ddb93ab/mqlight.js#L1548-L1595
train
mqlight/nodejs-mqlight
mqlight.js
function(err) { logger.entry('Client._tryService.connError', _id); err = lookupError(err); logger.log('data', _id, 'failed to connect to: ' + logUrl + ' due to error: ' + util.inspect(err)); // This service failed to connect. Try the next one. // XXX: wrap in shouldReconnect ? tryNextService(err); logger.exit('Client._tryService.connError', _id, null); }
javascript
function(err) { logger.entry('Client._tryService.connError', _id); err = lookupError(err); logger.log('data', _id, 'failed to connect to: ' + logUrl + ' due to error: ' + util.inspect(err)); // This service failed to connect. Try the next one. // XXX: wrap in shouldReconnect ? tryNextService(err); logger.exit('Client._tryService.connError', _id, null); }
[ "function", "(", "err", ")", "{", "logger", ".", "entry", "(", "'Client._tryService.connError'", ",", "_id", ")", ";", "err", "=", "lookupError", "(", "err", ")", ";", "logger", ".", "log", "(", "'data'", ",", "_id", ",", "'failed to connect to: '", "+", "logUrl", "+", "' due to error: '", "+", "util", ".", "inspect", "(", "err", ")", ")", ";", "tryNextService", "(", "err", ")", ";", "logger", ".", "exit", "(", "'Client._tryService.connError'", ",", "_id", ",", "null", ")", ";", "}" ]
Define an error handler for connection errors. Log the failure and then try the next service.
[ "Define", "an", "error", "handler", "for", "connection", "errors", ".", "Log", "the", "failure", "and", "then", "try", "the", "next", "service", "." ]
cf20a62d003fe6052569124bb85957d02ddb93ab
https://github.com/mqlight/nodejs-mqlight/blob/cf20a62d003fe6052569124bb85957d02ddb93ab/mqlight.js#L1599-L1611
train
berlinonline/converjon
lib/cache.js
meta_data_still_fresh
function meta_data_still_fresh(item) { var promise = read_meta_data(item). then(function(item) { return new Promise(function(resolve, reject) { if (headers_still_fresh(item.meta_data.headers)) { resolve(item); } else { reject(item); } }); }); return promise; }
javascript
function meta_data_still_fresh(item) { var promise = read_meta_data(item). then(function(item) { return new Promise(function(resolve, reject) { if (headers_still_fresh(item.meta_data.headers)) { resolve(item); } else { reject(item); } }); }); return promise; }
[ "function", "meta_data_still_fresh", "(", "item", ")", "{", "var", "promise", "=", "read_meta_data", "(", "item", ")", ".", "then", "(", "function", "(", "item", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "headers_still_fresh", "(", "item", ".", "meta_data", ".", "headers", ")", ")", "{", "resolve", "(", "item", ")", ";", "}", "else", "{", "reject", "(", "item", ")", ";", "}", "}", ")", ";", "}", ")", ";", "return", "promise", ";", "}" ]
returns a promise that resolves into the meta data or rejects in case of an error
[ "returns", "a", "promise", "that", "resolves", "into", "the", "meta", "data", "or", "rejects", "in", "case", "of", "an", "error" ]
ace8c1b8ff0c3077919b73d3d7604c60a60f37f3
https://github.com/berlinonline/converjon/blob/ace8c1b8ff0c3077919b73d3d7604c60a60f37f3/lib/cache.js#L86-L99
train
strongloop/microgateway-datastore
apim-pull.js
ModelType
function ModelType(name, prefix, endp) { this.name = name; this.prefix = prefix; this.endp = endp; }
javascript
function ModelType(name, prefix, endp) { this.name = name; this.prefix = prefix; this.endp = endp; }
[ "function", "ModelType", "(", "name", ",", "prefix", ",", "endp", ")", "{", "this", ".", "name", "=", "name", ";", "this", ".", "prefix", "=", "prefix", ";", "this", ".", "endp", "=", "endp", ";", "}" ]
Creates a model type @class @param {string} name - name of the model @param {string} prefix - file name prefix associated with the model
[ "Creates", "a", "model", "type" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/apim-pull.js#L59-L63
train
strongloop/microgateway-datastore
apim-pull.js
getDataBasedOnCatalog
function getDataBasedOnCatalog(options, catalogs, models, cb) { async.each(catalogs, function(catalog, catcallback) { /* Next, go to APIs for each catalog */ async.each(models, function(model, modelcallback) { pullDataFromEndp(options, catalog, model, function(err) { if (err) { logger.error(err); } modelcallback(err); }); }, function(err) { catcallback(err); }); }, function(err) { cb(err, response); } ); }
javascript
function getDataBasedOnCatalog(options, catalogs, models, cb) { async.each(catalogs, function(catalog, catcallback) { /* Next, go to APIs for each catalog */ async.each(models, function(model, modelcallback) { pullDataFromEndp(options, catalog, model, function(err) { if (err) { logger.error(err); } modelcallback(err); }); }, function(err) { catcallback(err); }); }, function(err) { cb(err, response); } ); }
[ "function", "getDataBasedOnCatalog", "(", "options", ",", "catalogs", ",", "models", ",", "cb", ")", "{", "async", ".", "each", "(", "catalogs", ",", "function", "(", "catalog", ",", "catcallback", ")", "{", "async", ".", "each", "(", "models", ",", "function", "(", "model", ",", "modelcallback", ")", "{", "pullDataFromEndp", "(", "options", ",", "catalog", ",", "model", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "logger", ".", "error", "(", "err", ")", ";", "}", "modelcallback", "(", "err", ")", ";", "}", ")", ";", "}", ",", "function", "(", "err", ")", "{", "catcallback", "(", "err", ")", ";", "}", ")", ";", "}", ",", "function", "(", "err", ")", "{", "cb", "(", "err", ",", "response", ")", ";", "}", ")", ";", "}" ]
Fetches data from APIm for each catalog such as APIs, products and subscriptions
[ "Fetches", "data", "from", "APIm", "for", "each", "catalog", "such", "as", "APIs", "products", "and", "subscriptions" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/apim-pull.js#L111-L133
train
strongloop/microgateway-datastore
apim-pull.js
fetchFromCache
function fetchFromCache(options, opts, cb) { // look for existing cached resource if (indirFiles.length > 0) { var etag; var regexp = '^' + opts.prefix + '([A-Za-z0-9]+={0,2})' + // base64 encoded opts.suffix + '$'; var regex = new RegExp(regexp); var i; for (i = 0; i < indirFiles.length; i++) { var file = regex.exec(indirFiles[i]); if (file) { etag = new Buffer(file[1], 'base64').toString(); break; } } if (etag) { try { var headOpts = JSON.parse(JSON.stringify(options)); // clone options headOpts.headers = { 'If-None-Match': etag }; request.head(headOpts, function(err, res, body) { if (err) { logger.error(err); cb(); // not fatal; continue } else if (res.statusCode === 304) { var filename = path.join(opts.outdir, indirFiles[i]); fs.copy(path.join(opts.indir, indirFiles[i]), filename, { preserveTimestamps: true }, function(err) { if (err) { throw (err); } var body = decryptData(fs.readFileSync(filename)); logger.info('Using cached copy of %s', indirFiles[i]); var result = { file: filename, contents: body }; cb(null, result); }); } else { cb(); } }); } catch (e) { logger.error(e); cb(); // not fatal; continue } } else { cb(); } } else { cb(); } }
javascript
function fetchFromCache(options, opts, cb) { // look for existing cached resource if (indirFiles.length > 0) { var etag; var regexp = '^' + opts.prefix + '([A-Za-z0-9]+={0,2})' + // base64 encoded opts.suffix + '$'; var regex = new RegExp(regexp); var i; for (i = 0; i < indirFiles.length; i++) { var file = regex.exec(indirFiles[i]); if (file) { etag = new Buffer(file[1], 'base64').toString(); break; } } if (etag) { try { var headOpts = JSON.parse(JSON.stringify(options)); // clone options headOpts.headers = { 'If-None-Match': etag }; request.head(headOpts, function(err, res, body) { if (err) { logger.error(err); cb(); // not fatal; continue } else if (res.statusCode === 304) { var filename = path.join(opts.outdir, indirFiles[i]); fs.copy(path.join(opts.indir, indirFiles[i]), filename, { preserveTimestamps: true }, function(err) { if (err) { throw (err); } var body = decryptData(fs.readFileSync(filename)); logger.info('Using cached copy of %s', indirFiles[i]); var result = { file: filename, contents: body }; cb(null, result); }); } else { cb(); } }); } catch (e) { logger.error(e); cb(); // not fatal; continue } } else { cb(); } } else { cb(); } }
[ "function", "fetchFromCache", "(", "options", ",", "opts", ",", "cb", ")", "{", "if", "(", "indirFiles", ".", "length", ">", "0", ")", "{", "var", "etag", ";", "var", "regexp", "=", "'^'", "+", "opts", ".", "prefix", "+", "'([A-Za-z0-9]+={0,2})'", "+", "opts", ".", "suffix", "+", "'$'", ";", "var", "regex", "=", "new", "RegExp", "(", "regexp", ")", ";", "var", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "indirFiles", ".", "length", ";", "i", "++", ")", "{", "var", "file", "=", "regex", ".", "exec", "(", "indirFiles", "[", "i", "]", ")", ";", "if", "(", "file", ")", "{", "etag", "=", "new", "Buffer", "(", "file", "[", "1", "]", ",", "'base64'", ")", ".", "toString", "(", ")", ";", "break", ";", "}", "}", "if", "(", "etag", ")", "{", "try", "{", "var", "headOpts", "=", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "options", ")", ")", ";", "headOpts", ".", "headers", "=", "{", "'If-None-Match'", ":", "etag", "}", ";", "request", ".", "head", "(", "headOpts", ",", "function", "(", "err", ",", "res", ",", "body", ")", "{", "if", "(", "err", ")", "{", "logger", ".", "error", "(", "err", ")", ";", "cb", "(", ")", ";", "}", "else", "if", "(", "res", ".", "statusCode", "===", "304", ")", "{", "var", "filename", "=", "path", ".", "join", "(", "opts", ".", "outdir", ",", "indirFiles", "[", "i", "]", ")", ";", "fs", ".", "copy", "(", "path", ".", "join", "(", "opts", ".", "indir", ",", "indirFiles", "[", "i", "]", ")", ",", "filename", ",", "{", "preserveTimestamps", ":", "true", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "throw", "(", "err", ")", ";", "}", "var", "body", "=", "decryptData", "(", "fs", ".", "readFileSync", "(", "filename", ")", ")", ";", "logger", ".", "info", "(", "'Using cached copy of %s'", ",", "indirFiles", "[", "i", "]", ")", ";", "var", "result", "=", "{", "file", ":", "filename", ",", "contents", ":", "body", "}", ";", "cb", "(", "null", ",", "result", ")", ";", "}", ")", ";", "}", "else", "{", "cb", "(", ")", ";", "}", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "logger", ".", "error", "(", "e", ")", ";", "cb", "(", ")", ";", "}", "}", "else", "{", "cb", "(", ")", ";", "}", "}", "else", "{", "cb", "(", ")", ";", "}", "}" ]
Uses cached configuration if still fresh
[ "Uses", "cached", "configuration", "if", "still", "fresh" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/apim-pull.js#L237-L294
train
strongloop/microgateway-datastore
server/boot/load-model.js
function(callback) { stageModels(app, models, function(err) { models.pop(); // remove snapshot model models.pop(); // remove optimizedData model callback(err); }); }
javascript
function(callback) { stageModels(app, models, function(err) { models.pop(); // remove snapshot model models.pop(); // remove optimizedData model callback(err); }); }
[ "function", "(", "callback", ")", "{", "stageModels", "(", "app", ",", "models", ",", "function", "(", "err", ")", "{", "models", ".", "pop", "(", ")", ";", "models", ".", "pop", "(", ")", ";", "callback", "(", "err", ")", ";", "}", ")", ";", "}" ]
stage the models
[ "stage", "the", "models" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/server/boot/load-model.js#L128-L134
train
strongloop/microgateway-datastore
server/boot/load-model.js
function(err) { if (!err) { loadData(app, apimanager, models, true, uid); } if (!apimanager.host) { //monitor the file changes, load data again if any changes fs.watch(definitionsDir, function(event, filename) { if (filename !== '.datastore') { logger.debug('File changed in %s%s, reload data', definitionsDir, filename); loadData(app, apimanager, models, false, uid); } }); } }
javascript
function(err) { if (!err) { loadData(app, apimanager, models, true, uid); } if (!apimanager.host) { //monitor the file changes, load data again if any changes fs.watch(definitionsDir, function(event, filename) { if (filename !== '.datastore') { logger.debug('File changed in %s%s, reload data', definitionsDir, filename); loadData(app, apimanager, models, false, uid); } }); } }
[ "function", "(", "err", ")", "{", "if", "(", "!", "err", ")", "{", "loadData", "(", "app", ",", "apimanager", ",", "models", ",", "true", ",", "uid", ")", ";", "}", "if", "(", "!", "apimanager", ".", "host", ")", "{", "fs", ".", "watch", "(", "definitionsDir", ",", "function", "(", "event", ",", "filename", ")", "{", "if", "(", "filename", "!==", "'.datastore'", ")", "{", "logger", ".", "debug", "(", "'File changed in %s%s, reload data'", ",", "definitionsDir", ",", "filename", ")", ";", "loadData", "(", "app", ",", "apimanager", ",", "models", ",", "false", ",", "uid", ")", ";", "}", "}", ")", ";", "}", "}" ]
load the data into the models
[ "load", "the", "data", "into", "the", "models" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/server/boot/load-model.js#L184-L197
train
strongloop/microgateway-datastore
server/boot/load-model.js
loadData
function loadData(app, apimanager, models, reload, uid) { var currdir = getPreviousSnapshotDir(); var snapdir; var snapshotID = getSnapshotID(); var populatedSnapshot = false; async.series([ function(callback) { logger.debug('apimanager before pullFromAPIm: %j', apimanager); if (apimanager.host) { // && apimanager.handshakeOk << shouldn't call if handshake failed.. not ready #TODO // && apimanager.webhooksOk << shouldn't call if handshake failed.. not ready #TODO // don't look for successful handshake/webhooks currently because UT depends on this // we have an APIm, handshake succeeded, so try to pull data.. pullFromAPIm(apimanager, currdir, snapshotID, function(err, dir) { if (err) { if (uid) { snapshotID = uid; } // in case of error, try the previous snapshot } snapdir = dir; // even in case of error, we need to try loading from the file system callback(); }); } else { snapdir = ''; callback(); } }, // populate snapshot model function(callback) { populateSnapshot(app, snapshotID, callback); }, // load current config function(callback) { populatedSnapshot = true; loadConfig(app, apimanager, models, currdir, snapdir, snapshotID, callback); } ], function(err, results) { if (!reload) { return; } var interval = apimanager.maxRefresh; // if no error and APIs specified, do not agressively reload config if (!err && apimanager.host && (http || https)) { apimanager.startupRefresh = interval; // if the previous snapshot hasn't be loaded, delete it if (uid && snapshotID !== uid) { try { fs.removeSync(currdir); } catch (e) { logger.error(e); //continue } } } else if (apimanager.startupRefresh < apimanager.maxRefresh) { // try agressively at first, and slowly back off interval = apimanager.startupRefresh; apimanager.startupRefresh *= 2; } if (err) { if (populatedSnapshot) { releaseSnapshot(app, snapshotID, function(err) { if (err) { /* suppress eslint handle-callback-err */ } process.send({ LOADED: false }); }); } else { process.send({ LOADED: false }); } } else if (!apimanager.host || http || https) { // neither http nor https would be set if there were no APIs // defined; if no APIs defined, let's try again in a while process.send({ LOADED: true, https: https }); } setImmediate(scheduleLoadData, app, interval, apimanager, models); }); }
javascript
function loadData(app, apimanager, models, reload, uid) { var currdir = getPreviousSnapshotDir(); var snapdir; var snapshotID = getSnapshotID(); var populatedSnapshot = false; async.series([ function(callback) { logger.debug('apimanager before pullFromAPIm: %j', apimanager); if (apimanager.host) { // && apimanager.handshakeOk << shouldn't call if handshake failed.. not ready #TODO // && apimanager.webhooksOk << shouldn't call if handshake failed.. not ready #TODO // don't look for successful handshake/webhooks currently because UT depends on this // we have an APIm, handshake succeeded, so try to pull data.. pullFromAPIm(apimanager, currdir, snapshotID, function(err, dir) { if (err) { if (uid) { snapshotID = uid; } // in case of error, try the previous snapshot } snapdir = dir; // even in case of error, we need to try loading from the file system callback(); }); } else { snapdir = ''; callback(); } }, // populate snapshot model function(callback) { populateSnapshot(app, snapshotID, callback); }, // load current config function(callback) { populatedSnapshot = true; loadConfig(app, apimanager, models, currdir, snapdir, snapshotID, callback); } ], function(err, results) { if (!reload) { return; } var interval = apimanager.maxRefresh; // if no error and APIs specified, do not agressively reload config if (!err && apimanager.host && (http || https)) { apimanager.startupRefresh = interval; // if the previous snapshot hasn't be loaded, delete it if (uid && snapshotID !== uid) { try { fs.removeSync(currdir); } catch (e) { logger.error(e); //continue } } } else if (apimanager.startupRefresh < apimanager.maxRefresh) { // try agressively at first, and slowly back off interval = apimanager.startupRefresh; apimanager.startupRefresh *= 2; } if (err) { if (populatedSnapshot) { releaseSnapshot(app, snapshotID, function(err) { if (err) { /* suppress eslint handle-callback-err */ } process.send({ LOADED: false }); }); } else { process.send({ LOADED: false }); } } else if (!apimanager.host || http || https) { // neither http nor https would be set if there were no APIs // defined; if no APIs defined, let's try again in a while process.send({ LOADED: true, https: https }); } setImmediate(scheduleLoadData, app, interval, apimanager, models); }); }
[ "function", "loadData", "(", "app", ",", "apimanager", ",", "models", ",", "reload", ",", "uid", ")", "{", "var", "currdir", "=", "getPreviousSnapshotDir", "(", ")", ";", "var", "snapdir", ";", "var", "snapshotID", "=", "getSnapshotID", "(", ")", ";", "var", "populatedSnapshot", "=", "false", ";", "async", ".", "series", "(", "[", "function", "(", "callback", ")", "{", "logger", ".", "debug", "(", "'apimanager before pullFromAPIm: %j'", ",", "apimanager", ")", ";", "if", "(", "apimanager", ".", "host", ")", "{", "pullFromAPIm", "(", "apimanager", ",", "currdir", ",", "snapshotID", ",", "function", "(", "err", ",", "dir", ")", "{", "if", "(", "err", ")", "{", "if", "(", "uid", ")", "{", "snapshotID", "=", "uid", ";", "}", "}", "snapdir", "=", "dir", ";", "callback", "(", ")", ";", "}", ")", ";", "}", "else", "{", "snapdir", "=", "''", ";", "callback", "(", ")", ";", "}", "}", ",", "function", "(", "callback", ")", "{", "populateSnapshot", "(", "app", ",", "snapshotID", ",", "callback", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "populatedSnapshot", "=", "true", ";", "loadConfig", "(", "app", ",", "apimanager", ",", "models", ",", "currdir", ",", "snapdir", ",", "snapshotID", ",", "callback", ")", ";", "}", "]", ",", "function", "(", "err", ",", "results", ")", "{", "if", "(", "!", "reload", ")", "{", "return", ";", "}", "var", "interval", "=", "apimanager", ".", "maxRefresh", ";", "if", "(", "!", "err", "&&", "apimanager", ".", "host", "&&", "(", "http", "||", "https", ")", ")", "{", "apimanager", ".", "startupRefresh", "=", "interval", ";", "if", "(", "uid", "&&", "snapshotID", "!==", "uid", ")", "{", "try", "{", "fs", ".", "removeSync", "(", "currdir", ")", ";", "}", "catch", "(", "e", ")", "{", "logger", ".", "error", "(", "e", ")", ";", "}", "}", "}", "else", "if", "(", "apimanager", ".", "startupRefresh", "<", "apimanager", ".", "maxRefresh", ")", "{", "interval", "=", "apimanager", ".", "startupRefresh", ";", "apimanager", ".", "startupRefresh", "*=", "2", ";", "}", "if", "(", "err", ")", "{", "if", "(", "populatedSnapshot", ")", "{", "releaseSnapshot", "(", "app", ",", "snapshotID", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "}", "process", ".", "send", "(", "{", "LOADED", ":", "false", "}", ")", ";", "}", ")", ";", "}", "else", "{", "process", ".", "send", "(", "{", "LOADED", ":", "false", "}", ")", ";", "}", "}", "else", "if", "(", "!", "apimanager", ".", "host", "||", "http", "||", "https", ")", "{", "process", ".", "send", "(", "{", "LOADED", ":", "true", ",", "https", ":", "https", "}", ")", ";", "}", "setImmediate", "(", "scheduleLoadData", ",", "app", ",", "interval", ",", "apimanager", ",", "models", ")", ";", "}", ")", ";", "}" ]
Loads the data into models, and periodically refreshes the data @param {???} app - loopback application @param {Object} config - configuration pointing to APIm server @param {Array} models - instances of ModelType to populate with data @param {bool} reload - set a timer to trigger a future reload
[ "Loads", "the", "data", "into", "models", "and", "periodically", "refreshes", "the", "data" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/server/boot/load-model.js#L207-L292
train
strongloop/microgateway-datastore
server/boot/load-model.js
function(callback) { populatedSnapshot = true; loadConfig(app, apimanager, models, currdir, snapdir, snapshotID, callback); }
javascript
function(callback) { populatedSnapshot = true; loadConfig(app, apimanager, models, currdir, snapdir, snapshotID, callback); }
[ "function", "(", "callback", ")", "{", "populatedSnapshot", "=", "true", ";", "loadConfig", "(", "app", ",", "apimanager", ",", "models", ",", "currdir", ",", "snapdir", ",", "snapshotID", ",", "callback", ")", ";", "}" ]
load current config
[ "load", "current", "config" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/server/boot/load-model.js#L240-L249
train
strongloop/microgateway-datastore
server/boot/load-model.js
stageModels
function stageModels(app, models, cb) { logger.debug('stageModels entry'); async.forEach(models, function(model, callback) { app.dataSources.db.automigrate( model.name, function(err) { callback(err); } ); }, function(err) { logger.debug('stageModels exit'); cb(err); } ); }
javascript
function stageModels(app, models, cb) { logger.debug('stageModels entry'); async.forEach(models, function(model, callback) { app.dataSources.db.automigrate( model.name, function(err) { callback(err); } ); }, function(err) { logger.debug('stageModels exit'); cb(err); } ); }
[ "function", "stageModels", "(", "app", ",", "models", ",", "cb", ")", "{", "logger", ".", "debug", "(", "'stageModels entry'", ")", ";", "async", ".", "forEach", "(", "models", ",", "function", "(", "model", ",", "callback", ")", "{", "app", ".", "dataSources", ".", "db", ".", "automigrate", "(", "model", ".", "name", ",", "function", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", ")", ";", "}", ",", "function", "(", "err", ")", "{", "logger", ".", "debug", "(", "'stageModels exit'", ")", ";", "cb", "(", "err", ")", ";", "}", ")", ";", "}" ]
Stages the models for use by subsequent functions @param {???} app - loopback application @param {Array} models - instances of ModelType to populate with data @param {callback} cb - callback that handles the error or successful completion
[ "Stages", "the", "models", "for", "use", "by", "subsequent", "functions" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/server/boot/load-model.js#L308-L324
train
strongloop/microgateway-datastore
server/boot/load-model.js
addSignatureHeaders
function addSignatureHeaders(body, headers, keyId, private_key) { var sign = function(str, private_key) { var sign = Crypto.createSign('RSA-SHA256'); sign.update(str); return sign.sign(private_key, 'base64'); }; var sha256 = function(str, encoding) { var bodyStr = JSON.stringify(str); var hash = Crypto.createHash('sha256'); hash.update(bodyStr); return hash.digest(encoding); }; if (!headers) { headers = {}; } if (!headers.date) { headers.date = (new Date()).toUTCString(); } if (!headers.digest) { headers.digest = 'SHA256=' + sha256(body, 'base64'); } var combine = function(names, headers) { var parts = []; names.forEach(function(e) { parts.push(e + ': ' + headers[e]); }); return parts.join('\n'); }; headers.authorization = 'Signature ' + 'keyId="' + keyId + '", ' + 'headers="date digest", ' + 'algorithm="rsa-sha256", ' + 'signature="' + sign(combine([ 'date', 'digest' ], headers), private_key) + '"'; return headers; }
javascript
function addSignatureHeaders(body, headers, keyId, private_key) { var sign = function(str, private_key) { var sign = Crypto.createSign('RSA-SHA256'); sign.update(str); return sign.sign(private_key, 'base64'); }; var sha256 = function(str, encoding) { var bodyStr = JSON.stringify(str); var hash = Crypto.createHash('sha256'); hash.update(bodyStr); return hash.digest(encoding); }; if (!headers) { headers = {}; } if (!headers.date) { headers.date = (new Date()).toUTCString(); } if (!headers.digest) { headers.digest = 'SHA256=' + sha256(body, 'base64'); } var combine = function(names, headers) { var parts = []; names.forEach(function(e) { parts.push(e + ': ' + headers[e]); }); return parts.join('\n'); }; headers.authorization = 'Signature ' + 'keyId="' + keyId + '", ' + 'headers="date digest", ' + 'algorithm="rsa-sha256", ' + 'signature="' + sign(combine([ 'date', 'digest' ], headers), private_key) + '"'; return headers; }
[ "function", "addSignatureHeaders", "(", "body", ",", "headers", ",", "keyId", ",", "private_key", ")", "{", "var", "sign", "=", "function", "(", "str", ",", "private_key", ")", "{", "var", "sign", "=", "Crypto", ".", "createSign", "(", "'RSA-SHA256'", ")", ";", "sign", ".", "update", "(", "str", ")", ";", "return", "sign", ".", "sign", "(", "private_key", ",", "'base64'", ")", ";", "}", ";", "var", "sha256", "=", "function", "(", "str", ",", "encoding", ")", "{", "var", "bodyStr", "=", "JSON", ".", "stringify", "(", "str", ")", ";", "var", "hash", "=", "Crypto", ".", "createHash", "(", "'sha256'", ")", ";", "hash", ".", "update", "(", "bodyStr", ")", ";", "return", "hash", ".", "digest", "(", "encoding", ")", ";", "}", ";", "if", "(", "!", "headers", ")", "{", "headers", "=", "{", "}", ";", "}", "if", "(", "!", "headers", ".", "date", ")", "{", "headers", ".", "date", "=", "(", "new", "Date", "(", ")", ")", ".", "toUTCString", "(", ")", ";", "}", "if", "(", "!", "headers", ".", "digest", ")", "{", "headers", ".", "digest", "=", "'SHA256='", "+", "sha256", "(", "body", ",", "'base64'", ")", ";", "}", "var", "combine", "=", "function", "(", "names", ",", "headers", ")", "{", "var", "parts", "=", "[", "]", ";", "names", ".", "forEach", "(", "function", "(", "e", ")", "{", "parts", ".", "push", "(", "e", "+", "': '", "+", "headers", "[", "e", "]", ")", ";", "}", ")", ";", "return", "parts", ".", "join", "(", "'\\n'", ")", ";", "}", ";", "\\n", "headers", ".", "authorization", "=", "'Signature '", "+", "'keyId=\"'", "+", "keyId", "+", "'\", '", "+", "'headers=\"date digest\", '", "+", "'algorithm=\"rsa-sha256\", '", "+", "'signature=\"'", "+", "sign", "(", "combine", "(", "[", "'date'", ",", "'digest'", "]", ",", "headers", ")", ",", "private_key", ")", "+", "'\"'", ";", "}" ]
Compute the signature headers "date", "digest", and "authorization" headers according to IETF I-D draft-cavage-http-signatures-05 using rsa-sha256 algorithm If the `date` header already exists in the input, it's used as-is If the `digest` header already exists in the input, it's used as-is (which means that body is ignored) @param body (String): Message body (ignored if there is already a digest header) @param headers (Object): Contains the existing list of headers @param keyId (String): Identifier for the private key, ends up in the "keyId" param of the authorization header @param private_key (String): RSA Private key to be used for the signature @returns {*}
[ "Compute", "the", "signature", "headers", "date", "digest", "and", "authorization", "headers", "according", "to", "IETF", "I", "-", "D", "draft", "-", "cavage", "-", "http", "-", "signatures", "-", "05", "using", "rsa", "-", "sha256", "algorithm" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/server/boot/load-model.js#L341-L383
train
strongloop/microgateway-datastore
server/boot/load-model.js
handshakeWithAPIm
function handshakeWithAPIm(app, apimanager, private_key, cb) { logger.debug('handshakeWithAPIm entry'); async.series([ function(callback) { var body = JSON.stringify({ gatewayVersion: version }); var headers = { 'content-type': 'application/json' }; addSignatureHeaders(body, headers, 'micro-gw-catalog/' + apimanager.catalog, private_key); if (logger.debug()) { logger.debug(JSON.stringify(headers, null, 2)); } var apimHandshakeUrlObj = { protocol: 'https', hostname: apimanager.host, port: apimanager.port, pathname: '/v1/catalogs/' + apimanager.catalog + '/handshake/' }; var apimHandshakeUrl = url.format(apimHandshakeUrlObj); Request( { url: apimHandshakeUrl, method: 'POST', json: body, headers: headers, agentOptions: { //FIXME: need to eventually remove this rejectUnauthorized: false } }, function(err, res, body) { if (err) { logger.error('Failed to communicate with %s: %s ', apimHandshakeUrl, err); return callback(err); } logger.debug('statusCode: ' + res.statusCode); if (res.statusCode !== 200) { logger.error(apimHandshakeUrl, ' failed with: ', res.statusCode); return callback(new Error(apimHandshakeUrl + ' failed with: ' + res.statusCode)); } var json = decryptAPIMResponse(body, private_key); //sensitive data //if (logger.debug()) { // logger.debug(JSON.stringify(json, null, 2)); //} if (!json.microGateway) { return callback(new Error(apimHandshakeUrl + ' response did not contain "microGateway" section')); } var ugw = json.microGateway; apimanager.clicert = ugw.cert; apimanager.clikey = ugw.key; apimanager.clientid = ugw.clientID; //sensitive data //if (logger.debug()) { // logger.debug('apimanager: %s', JSON.stringify(apimanager, null, 2)); //} callback(null); }); } ], function(err) { if (err) { apimanager.handshakeOk = false; logger.error('Unsuccessful handshake with API Connect server'); } else { apimanager.handshakeOk = true; logger.info('Successful handshake with API Connect server'); } logger.debug('handshakeWithAPIm exit'); cb(err); }); }
javascript
function handshakeWithAPIm(app, apimanager, private_key, cb) { logger.debug('handshakeWithAPIm entry'); async.series([ function(callback) { var body = JSON.stringify({ gatewayVersion: version }); var headers = { 'content-type': 'application/json' }; addSignatureHeaders(body, headers, 'micro-gw-catalog/' + apimanager.catalog, private_key); if (logger.debug()) { logger.debug(JSON.stringify(headers, null, 2)); } var apimHandshakeUrlObj = { protocol: 'https', hostname: apimanager.host, port: apimanager.port, pathname: '/v1/catalogs/' + apimanager.catalog + '/handshake/' }; var apimHandshakeUrl = url.format(apimHandshakeUrlObj); Request( { url: apimHandshakeUrl, method: 'POST', json: body, headers: headers, agentOptions: { //FIXME: need to eventually remove this rejectUnauthorized: false } }, function(err, res, body) { if (err) { logger.error('Failed to communicate with %s: %s ', apimHandshakeUrl, err); return callback(err); } logger.debug('statusCode: ' + res.statusCode); if (res.statusCode !== 200) { logger.error(apimHandshakeUrl, ' failed with: ', res.statusCode); return callback(new Error(apimHandshakeUrl + ' failed with: ' + res.statusCode)); } var json = decryptAPIMResponse(body, private_key); //sensitive data //if (logger.debug()) { // logger.debug(JSON.stringify(json, null, 2)); //} if (!json.microGateway) { return callback(new Error(apimHandshakeUrl + ' response did not contain "microGateway" section')); } var ugw = json.microGateway; apimanager.clicert = ugw.cert; apimanager.clikey = ugw.key; apimanager.clientid = ugw.clientID; //sensitive data //if (logger.debug()) { // logger.debug('apimanager: %s', JSON.stringify(apimanager, null, 2)); //} callback(null); }); } ], function(err) { if (err) { apimanager.handshakeOk = false; logger.error('Unsuccessful handshake with API Connect server'); } else { apimanager.handshakeOk = true; logger.info('Successful handshake with API Connect server'); } logger.debug('handshakeWithAPIm exit'); cb(err); }); }
[ "function", "handshakeWithAPIm", "(", "app", ",", "apimanager", ",", "private_key", ",", "cb", ")", "{", "logger", ".", "debug", "(", "'handshakeWithAPIm entry'", ")", ";", "async", ".", "series", "(", "[", "function", "(", "callback", ")", "{", "var", "body", "=", "JSON", ".", "stringify", "(", "{", "gatewayVersion", ":", "version", "}", ")", ";", "var", "headers", "=", "{", "'content-type'", ":", "'application/json'", "}", ";", "addSignatureHeaders", "(", "body", ",", "headers", ",", "'micro-gw-catalog/'", "+", "apimanager", ".", "catalog", ",", "private_key", ")", ";", "if", "(", "logger", ".", "debug", "(", ")", ")", "{", "logger", ".", "debug", "(", "JSON", ".", "stringify", "(", "headers", ",", "null", ",", "2", ")", ")", ";", "}", "var", "apimHandshakeUrlObj", "=", "{", "protocol", ":", "'https'", ",", "hostname", ":", "apimanager", ".", "host", ",", "port", ":", "apimanager", ".", "port", ",", "pathname", ":", "'/v1/catalogs/'", "+", "apimanager", ".", "catalog", "+", "'/handshake/'", "}", ";", "var", "apimHandshakeUrl", "=", "url", ".", "format", "(", "apimHandshakeUrlObj", ")", ";", "Request", "(", "{", "url", ":", "apimHandshakeUrl", ",", "method", ":", "'POST'", ",", "json", ":", "body", ",", "headers", ":", "headers", ",", "agentOptions", ":", "{", "rejectUnauthorized", ":", "false", "}", "}", ",", "function", "(", "err", ",", "res", ",", "body", ")", "{", "if", "(", "err", ")", "{", "logger", ".", "error", "(", "'Failed to communicate with %s: %s '", ",", "apimHandshakeUrl", ",", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "logger", ".", "debug", "(", "'statusCode: '", "+", "res", ".", "statusCode", ")", ";", "if", "(", "res", ".", "statusCode", "!==", "200", ")", "{", "logger", ".", "error", "(", "apimHandshakeUrl", ",", "' failed with: '", ",", "res", ".", "statusCode", ")", ";", "return", "callback", "(", "new", "Error", "(", "apimHandshakeUrl", "+", "' failed with: '", "+", "res", ".", "statusCode", ")", ")", ";", "}", "var", "json", "=", "decryptAPIMResponse", "(", "body", ",", "private_key", ")", ";", "if", "(", "!", "json", ".", "microGateway", ")", "{", "return", "callback", "(", "new", "Error", "(", "apimHandshakeUrl", "+", "' response did not contain \"microGateway\" section'", ")", ")", ";", "}", "var", "ugw", "=", "json", ".", "microGateway", ";", "apimanager", ".", "clicert", "=", "ugw", ".", "cert", ";", "apimanager", ".", "clikey", "=", "ugw", ".", "key", ";", "apimanager", ".", "clientid", "=", "ugw", ".", "clientID", ";", "callback", "(", "null", ")", ";", "}", ")", ";", "}", "]", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "apimanager", ".", "handshakeOk", "=", "false", ";", "logger", ".", "error", "(", "'Unsuccessful handshake with API Connect server'", ")", ";", "}", "else", "{", "apimanager", ".", "handshakeOk", "=", "true", ";", "logger", ".", "info", "(", "'Successful handshake with API Connect server'", ")", ";", "}", "logger", ".", "debug", "(", "'handshakeWithAPIm exit'", ")", ";", "cb", "(", "err", ")", ";", "}", ")", ";", "}" ]
Attempt to handshake from APIm server @param {???} app - loopback application @param {Object} apimanager - configuration pointing to APIm server @param {string} privatekey - private key to be used for handshake @param {callback} cb - callback that handles error
[ "Attempt", "to", "handshake", "from", "APIm", "server" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/server/boot/load-model.js#L541-L615
train
strongloop/microgateway-datastore
server/boot/load-model.js
pullFromAPIm
function pullFromAPIm(apimanager, currdir, uid, cb) { logger.debug('pullFromAPIm entry'); // Have an APIm, grab latest if we can.. var snapdir = path.join(process.env.ROOTCONFIGDIR, uid); fs.mkdirs(snapdir, function(err) { if (err) { logger.warn('Failed to create snapshot directory'); logger.debug('pullFromAPIm exit(1)'); cb(err, ''); return; } /* var options = { host: host of APIm port: port of APIm timeout: opts.timeout * 1000 || 30 * 1000, clikey: opts.clikey ? opts.clikey : null, clicert: opts.clicert ? opts.clicert : null, clientid: opts.clientid || '1111-1111', outdir: opts.outdir || 'apim' }; */ var options = {}; options.host = apimanager.host; options.port = apimanager.port; options.clikey = apimanager.clikey; options.clicert = apimanager.clicert; options.clientid = apimanager.clientid; options.indir = currdir; options.outdir = snapdir; logger.debug('apimpull start'); apimpull(options, function(err, response) { if (err) { logger.error(err); try { fs.removeSync(snapdir); } catch (e) { logger.error(e); //continue } snapdir = ''; // falling through // try loading from local files } else { logger.info('Successfully pulled snapshot from API Connect server'); } logger.debug(response); logger.debug('pullFromAPIm exit(2)'); cb(err, snapdir); }); }); }
javascript
function pullFromAPIm(apimanager, currdir, uid, cb) { logger.debug('pullFromAPIm entry'); // Have an APIm, grab latest if we can.. var snapdir = path.join(process.env.ROOTCONFIGDIR, uid); fs.mkdirs(snapdir, function(err) { if (err) { logger.warn('Failed to create snapshot directory'); logger.debug('pullFromAPIm exit(1)'); cb(err, ''); return; } /* var options = { host: host of APIm port: port of APIm timeout: opts.timeout * 1000 || 30 * 1000, clikey: opts.clikey ? opts.clikey : null, clicert: opts.clicert ? opts.clicert : null, clientid: opts.clientid || '1111-1111', outdir: opts.outdir || 'apim' }; */ var options = {}; options.host = apimanager.host; options.port = apimanager.port; options.clikey = apimanager.clikey; options.clicert = apimanager.clicert; options.clientid = apimanager.clientid; options.indir = currdir; options.outdir = snapdir; logger.debug('apimpull start'); apimpull(options, function(err, response) { if (err) { logger.error(err); try { fs.removeSync(snapdir); } catch (e) { logger.error(e); //continue } snapdir = ''; // falling through // try loading from local files } else { logger.info('Successfully pulled snapshot from API Connect server'); } logger.debug(response); logger.debug('pullFromAPIm exit(2)'); cb(err, snapdir); }); }); }
[ "function", "pullFromAPIm", "(", "apimanager", ",", "currdir", ",", "uid", ",", "cb", ")", "{", "logger", ".", "debug", "(", "'pullFromAPIm entry'", ")", ";", "var", "snapdir", "=", "path", ".", "join", "(", "process", ".", "env", ".", "ROOTCONFIGDIR", ",", "uid", ")", ";", "fs", ".", "mkdirs", "(", "snapdir", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "logger", ".", "warn", "(", "'Failed to create snapshot directory'", ")", ";", "logger", ".", "debug", "(", "'pullFromAPIm exit(1)'", ")", ";", "cb", "(", "err", ",", "''", ")", ";", "return", ";", "}", "var", "options", "=", "{", "}", ";", "options", ".", "host", "=", "apimanager", ".", "host", ";", "options", ".", "port", "=", "apimanager", ".", "port", ";", "options", ".", "clikey", "=", "apimanager", ".", "clikey", ";", "options", ".", "clicert", "=", "apimanager", ".", "clicert", ";", "options", ".", "clientid", "=", "apimanager", ".", "clientid", ";", "options", ".", "indir", "=", "currdir", ";", "options", ".", "outdir", "=", "snapdir", ";", "logger", ".", "debug", "(", "'apimpull start'", ")", ";", "apimpull", "(", "options", ",", "function", "(", "err", ",", "response", ")", "{", "if", "(", "err", ")", "{", "logger", ".", "error", "(", "err", ")", ";", "try", "{", "fs", ".", "removeSync", "(", "snapdir", ")", ";", "}", "catch", "(", "e", ")", "{", "logger", ".", "error", "(", "e", ")", ";", "}", "snapdir", "=", "''", ";", "}", "else", "{", "logger", ".", "info", "(", "'Successfully pulled snapshot from API Connect server'", ")", ";", "}", "logger", ".", "debug", "(", "response", ")", ";", "logger", ".", "debug", "(", "'pullFromAPIm exit(2)'", ")", ";", "cb", "(", "err", ",", "snapdir", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Attempt to request data from APIm server and persist to disk @param {Object} config - configuration pointing to APIm server @param {string} currdir - current snapshot symbolic link path @param {string} uid - snapshot identifier @param {callback} cb - callback that handles error or path to snapshot directory
[ "Attempt", "to", "request", "data", "from", "APIm", "server", "and", "persist", "to", "disk" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/server/boot/load-model.js#L625-L678
train
strongloop/microgateway-datastore
server/boot/load-model.js
loadConfig
function loadConfig(app, apimanager, models, currdir, snapdir, uid, cb) { logger.debug('loadConfig entry'); var dirToLoad = (snapdir === '') ? currdir : snapdir; loadConfigFromFS(app, apimanager, models, dirToLoad, uid, function(err) { if (err) { logger.error(err); logger.debug('loadConfig error(1)'); cb(err); return; } else if (mixedProtocols) { logger.debug('loadConfig error(2)'); cb(new Error('mixed protocols')); return; } else { // update current snapshot pointer updateSnapshot(app, uid, function(err) { if (err) { logger.debug('loadConfig error(3)'); cb(err); return; } // only update pointer to latest configuration // when latest configuration successful loaded if (snapdir === dirToLoad) { process.env[CONFIGDIR] = snapdir; setPreviousSnapshotDir(snapdir); } logger.debug('loadConfig exit'); cb(); }); } }); }
javascript
function loadConfig(app, apimanager, models, currdir, snapdir, uid, cb) { logger.debug('loadConfig entry'); var dirToLoad = (snapdir === '') ? currdir : snapdir; loadConfigFromFS(app, apimanager, models, dirToLoad, uid, function(err) { if (err) { logger.error(err); logger.debug('loadConfig error(1)'); cb(err); return; } else if (mixedProtocols) { logger.debug('loadConfig error(2)'); cb(new Error('mixed protocols')); return; } else { // update current snapshot pointer updateSnapshot(app, uid, function(err) { if (err) { logger.debug('loadConfig error(3)'); cb(err); return; } // only update pointer to latest configuration // when latest configuration successful loaded if (snapdir === dirToLoad) { process.env[CONFIGDIR] = snapdir; setPreviousSnapshotDir(snapdir); } logger.debug('loadConfig exit'); cb(); }); } }); }
[ "function", "loadConfig", "(", "app", ",", "apimanager", ",", "models", ",", "currdir", ",", "snapdir", ",", "uid", ",", "cb", ")", "{", "logger", ".", "debug", "(", "'loadConfig entry'", ")", ";", "var", "dirToLoad", "=", "(", "snapdir", "===", "''", ")", "?", "currdir", ":", "snapdir", ";", "loadConfigFromFS", "(", "app", ",", "apimanager", ",", "models", ",", "dirToLoad", ",", "uid", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "logger", ".", "error", "(", "err", ")", ";", "logger", ".", "debug", "(", "'loadConfig error(1)'", ")", ";", "cb", "(", "err", ")", ";", "return", ";", "}", "else", "if", "(", "mixedProtocols", ")", "{", "logger", ".", "debug", "(", "'loadConfig error(2)'", ")", ";", "cb", "(", "new", "Error", "(", "'mixed protocols'", ")", ")", ";", "return", ";", "}", "else", "{", "updateSnapshot", "(", "app", ",", "uid", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "logger", ".", "debug", "(", "'loadConfig error(3)'", ")", ";", "cb", "(", "err", ")", ";", "return", ";", "}", "if", "(", "snapdir", "===", "dirToLoad", ")", "{", "process", ".", "env", "[", "CONFIGDIR", "]", "=", "snapdir", ";", "setPreviousSnapshotDir", "(", "snapdir", ")", ";", "}", "logger", ".", "debug", "(", "'loadConfig exit'", ")", ";", "cb", "(", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
Loads persisted data from disk and populates models and updates 'current snapshot' @param {???} app - loopback application @param {Array} models - instances of ModelType to populate with data @param {string} currdir - current snapshot symbolic link path @param {string} snapdir - path to directory containing persisted data to load @param {string} uid - snapshot identifier @param {callback} cb - callback that handles error or successful completion
[ "Loads", "persisted", "data", "from", "disk", "and", "populates", "models", "and", "updates", "current", "snapshot" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/server/boot/load-model.js#L690-L725
train
strongloop/microgateway-datastore
server/boot/load-model.js
loadConfigFromFS
function loadConfigFromFS(app, apimanager, models, dir, uid, cb) { // clear out existing files from model structure models.forEach( function(model) { model.files = []; } ); if (apimanager.host) { var files = []; logger.debug('loadConfigFromFS entry'); try { if (dir !== '') { files = fs.readdirSync(dir); } } catch (e) { logger.error('Failed to read directory: ', dir); cb(e); return; } logger.debug('files: ', files); var jsonFile = new RegExp(/.*\.json$/); // correlate files with appropriate model files.forEach( function(file) { logger.debug('file match jsonFile: ', file.match(jsonFile)); if (file.match(jsonFile)) { for (var i = 0; i < models.length; i++) { if (file.indexOf(models[i].prefix) > -1) { logger.debug('%s file: %s', models[i].name, file); models[i].files.push(file); break; } } } } ); // populate data-store models with the file contents populateModelsWithAPImData(app, models, dir, uid, cb); } else { var YAMLfiles = []; logger.debug('dir: ', dir); //read the apic settings var cfg = readApicConfig(dir); //read the YAML files project.loadProject(dir).then(function(artifacts) { logger.debug('%j', artifacts); artifacts.forEach( function(artifact) { if (artifact.type === 'swagger') { YAMLfiles.push(artifact.filePath); } }); // populate data-store models with the file contents populateModelsWithLocalData(app, YAMLfiles, cfg, dir, uid, cb); }); } }
javascript
function loadConfigFromFS(app, apimanager, models, dir, uid, cb) { // clear out existing files from model structure models.forEach( function(model) { model.files = []; } ); if (apimanager.host) { var files = []; logger.debug('loadConfigFromFS entry'); try { if (dir !== '') { files = fs.readdirSync(dir); } } catch (e) { logger.error('Failed to read directory: ', dir); cb(e); return; } logger.debug('files: ', files); var jsonFile = new RegExp(/.*\.json$/); // correlate files with appropriate model files.forEach( function(file) { logger.debug('file match jsonFile: ', file.match(jsonFile)); if (file.match(jsonFile)) { for (var i = 0; i < models.length; i++) { if (file.indexOf(models[i].prefix) > -1) { logger.debug('%s file: %s', models[i].name, file); models[i].files.push(file); break; } } } } ); // populate data-store models with the file contents populateModelsWithAPImData(app, models, dir, uid, cb); } else { var YAMLfiles = []; logger.debug('dir: ', dir); //read the apic settings var cfg = readApicConfig(dir); //read the YAML files project.loadProject(dir).then(function(artifacts) { logger.debug('%j', artifacts); artifacts.forEach( function(artifact) { if (artifact.type === 'swagger') { YAMLfiles.push(artifact.filePath); } }); // populate data-store models with the file contents populateModelsWithLocalData(app, YAMLfiles, cfg, dir, uid, cb); }); } }
[ "function", "loadConfigFromFS", "(", "app", ",", "apimanager", ",", "models", ",", "dir", ",", "uid", ",", "cb", ")", "{", "models", ".", "forEach", "(", "function", "(", "model", ")", "{", "model", ".", "files", "=", "[", "]", ";", "}", ")", ";", "if", "(", "apimanager", ".", "host", ")", "{", "var", "files", "=", "[", "]", ";", "logger", ".", "debug", "(", "'loadConfigFromFS entry'", ")", ";", "try", "{", "if", "(", "dir", "!==", "''", ")", "{", "files", "=", "fs", ".", "readdirSync", "(", "dir", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "logger", ".", "error", "(", "'Failed to read directory: '", ",", "dir", ")", ";", "cb", "(", "e", ")", ";", "return", ";", "}", "logger", ".", "debug", "(", "'files: '", ",", "files", ")", ";", "var", "jsonFile", "=", "new", "RegExp", "(", "/", ".*\\.json$", "/", ")", ";", "files", ".", "forEach", "(", "function", "(", "file", ")", "{", "logger", ".", "debug", "(", "'file match jsonFile: '", ",", "file", ".", "match", "(", "jsonFile", ")", ")", ";", "if", "(", "file", ".", "match", "(", "jsonFile", ")", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "models", ".", "length", ";", "i", "++", ")", "{", "if", "(", "file", ".", "indexOf", "(", "models", "[", "i", "]", ".", "prefix", ")", ">", "-", "1", ")", "{", "logger", ".", "debug", "(", "'%s file: %s'", ",", "models", "[", "i", "]", ".", "name", ",", "file", ")", ";", "models", "[", "i", "]", ".", "files", ".", "push", "(", "file", ")", ";", "break", ";", "}", "}", "}", "}", ")", ";", "populateModelsWithAPImData", "(", "app", ",", "models", ",", "dir", ",", "uid", ",", "cb", ")", ";", "}", "else", "{", "var", "YAMLfiles", "=", "[", "]", ";", "logger", ".", "debug", "(", "'dir: '", ",", "dir", ")", ";", "var", "cfg", "=", "readApicConfig", "(", "dir", ")", ";", "project", ".", "loadProject", "(", "dir", ")", ".", "then", "(", "function", "(", "artifacts", ")", "{", "logger", ".", "debug", "(", "'%j'", ",", "artifacts", ")", ";", "artifacts", ".", "forEach", "(", "function", "(", "artifact", ")", "{", "if", "(", "artifact", ".", "type", "===", "'swagger'", ")", "{", "YAMLfiles", ".", "push", "(", "artifact", ".", "filePath", ")", ";", "}", "}", ")", ";", "populateModelsWithLocalData", "(", "app", ",", "YAMLfiles", ",", "cfg", ",", "dir", ",", "uid", ",", "cb", ")", ";", "}", ")", ";", "}", "}" ]
Loads persisted data from disk and populates models @param {???} app - loopback application @param {Array} models - instances of ModelType to populate with data @param {string} dir - path to directory containing persisted data to load @param {string} uid - snapshot identifier @param {callback} cb - callback that handles error or successful completion
[ "Loads", "persisted", "data", "from", "disk", "and", "populates", "models" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/server/boot/load-model.js#L735-L796
train
strongloop/microgateway-datastore
server/boot/load-model.js
function(seriesCallback) { async.forEach(YAMLfiles, function(file, fileCallback) { logger.debug('Loading data from %s', file); var readfile; try { // read the content of the files into memory and parse as JSON readfile = YAML.load(fs.readFileSync(file, 'utf8')); } catch (e) { fileCallback(e); return; } var model = {}; var entry = {}; // looks like a product if (readfile.product) { logger.debug('product found: skipping'); } // looks like an API if (readfile.swagger) { entry.id = createAPIID(readfile); entry.document = expandAPIData(readfile, dir); if (entry.document) { model.name = 'api'; if (entry.document.info['x-ibm-name']) { apis[entry.document.info['x-ibm-name']] = entry.document; } else { apis[entry.document.info['title']] = entry.document; } } } if (model.name) { // no catalog entry.catalog = {}; entry['snapshot-id'] = uid; app.models[model.name].create( entry, function(err, mymodel) { if (err) { logger.error(err); fileCallback(err); return; } logger.debug('%s created: %j', model.name, mymodel); fileCallback(); }); } else { fileCallback(); } }, function(err) { if (err) { /* suppress eslint handle-callback-err */ } } ); seriesCallback(); }
javascript
function(seriesCallback) { async.forEach(YAMLfiles, function(file, fileCallback) { logger.debug('Loading data from %s', file); var readfile; try { // read the content of the files into memory and parse as JSON readfile = YAML.load(fs.readFileSync(file, 'utf8')); } catch (e) { fileCallback(e); return; } var model = {}; var entry = {}; // looks like a product if (readfile.product) { logger.debug('product found: skipping'); } // looks like an API if (readfile.swagger) { entry.id = createAPIID(readfile); entry.document = expandAPIData(readfile, dir); if (entry.document) { model.name = 'api'; if (entry.document.info['x-ibm-name']) { apis[entry.document.info['x-ibm-name']] = entry.document; } else { apis[entry.document.info['title']] = entry.document; } } } if (model.name) { // no catalog entry.catalog = {}; entry['snapshot-id'] = uid; app.models[model.name].create( entry, function(err, mymodel) { if (err) { logger.error(err); fileCallback(err); return; } logger.debug('%s created: %j', model.name, mymodel); fileCallback(); }); } else { fileCallback(); } }, function(err) { if (err) { /* suppress eslint handle-callback-err */ } } ); seriesCallback(); }
[ "function", "(", "seriesCallback", ")", "{", "async", ".", "forEach", "(", "YAMLfiles", ",", "function", "(", "file", ",", "fileCallback", ")", "{", "logger", ".", "debug", "(", "'Loading data from %s'", ",", "file", ")", ";", "var", "readfile", ";", "try", "{", "readfile", "=", "YAML", ".", "load", "(", "fs", ".", "readFileSync", "(", "file", ",", "'utf8'", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "fileCallback", "(", "e", ")", ";", "return", ";", "}", "var", "model", "=", "{", "}", ";", "var", "entry", "=", "{", "}", ";", "if", "(", "readfile", ".", "product", ")", "{", "logger", ".", "debug", "(", "'product found: skipping'", ")", ";", "}", "if", "(", "readfile", ".", "swagger", ")", "{", "entry", ".", "id", "=", "createAPIID", "(", "readfile", ")", ";", "entry", ".", "document", "=", "expandAPIData", "(", "readfile", ",", "dir", ")", ";", "if", "(", "entry", ".", "document", ")", "{", "model", ".", "name", "=", "'api'", ";", "if", "(", "entry", ".", "document", ".", "info", "[", "'x-ibm-name'", "]", ")", "{", "apis", "[", "entry", ".", "document", ".", "info", "[", "'x-ibm-name'", "]", "]", "=", "entry", ".", "document", ";", "}", "else", "{", "apis", "[", "entry", ".", "document", ".", "info", "[", "'title'", "]", "]", "=", "entry", ".", "document", ";", "}", "}", "}", "if", "(", "model", ".", "name", ")", "{", "entry", ".", "catalog", "=", "{", "}", ";", "entry", "[", "'snapshot-id'", "]", "=", "uid", ";", "app", ".", "models", "[", "model", ".", "name", "]", ".", "create", "(", "entry", ",", "function", "(", "err", ",", "mymodel", ")", "{", "if", "(", "err", ")", "{", "logger", ".", "error", "(", "err", ")", ";", "fileCallback", "(", "err", ")", ";", "return", ";", "}", "logger", ".", "debug", "(", "'%s created: %j'", ",", "model", ".", "name", ",", "mymodel", ")", ";", "fileCallback", "(", ")", ";", "}", ")", ";", "}", "else", "{", "fileCallback", "(", ")", ";", "}", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "}", "}", ")", ";", "seriesCallback", "(", ")", ";", "}" ]
1. create the "api" instances
[ "1", ".", "create", "the", "api", "instances" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/server/boot/load-model.js#L837-L894
train
strongloop/microgateway-datastore
server/boot/load-model.js
function(seriesCallback) { defaultCatalog['snapshot-id'] = uid; app.models['catalog'].create( defaultCatalog, function(err, mymodel) { if (err) { logger.error(err); seriesCallback(err); return; } logger.debug('%s created: %j', 'catalog', mymodel); seriesCallback(); }); }
javascript
function(seriesCallback) { defaultCatalog['snapshot-id'] = uid; app.models['catalog'].create( defaultCatalog, function(err, mymodel) { if (err) { logger.error(err); seriesCallback(err); return; } logger.debug('%s created: %j', 'catalog', mymodel); seriesCallback(); }); }
[ "function", "(", "seriesCallback", ")", "{", "defaultCatalog", "[", "'snapshot-id'", "]", "=", "uid", ";", "app", ".", "models", "[", "'catalog'", "]", ".", "create", "(", "defaultCatalog", ",", "function", "(", "err", ",", "mymodel", ")", "{", "if", "(", "err", ")", "{", "logger", ".", "error", "(", "err", ")", ";", "seriesCallback", "(", "err", ")", ";", "return", ";", "}", "logger", ".", "debug", "(", "'%s created: %j'", ",", "'catalog'", ",", "mymodel", ")", ";", "seriesCallback", "(", ")", ";", "}", ")", ";", "}" ]
2. create the "catalog" instances
[ "2", ".", "create", "the", "catalog", "instances" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/server/boot/load-model.js#L896-L909
train
strongloop/microgateway-datastore
server/boot/load-model.js
function(seriesCallback) { var entry = {}; // add catalog entry.catalog = defaultCatalog; entry['snapshot-id'] = uid; entry.document = { product: '1.0.0', info: { name: 'static-product', version: '1.0.0', title: 'static-product' }, visibility: { view: { type: 'public' }, subscribe: { type: 'authenticated' } }, apis: apis }; var rateLimit = '100/hour'; if (process.env[LAPTOP_RATELIMIT]) { rateLimit = process.env[LAPTOP_RATELIMIT]; } if (apicCfg && apicCfg.plans && apicCfg.applications) { //add the configured plans entry.document.plans = {}; //add plan and its APIs for (var p in apicCfg.plans) { var plan = apicCfg.plans[p]; if (typeof plan === 'object') { var planApis = {}; for (var i in plan.apis) { var name = plan.apis[i]; //add the api to plan if only if the api does exist if (apis[name]) { planApis[name] = {}; } else { logger.warn('Cannot add the invalid api "%s" to plan "%s"', name, p); } } entry.document.plans[p] = { apis: planApis, 'rate-limit': { value: plan['rate-limit'] || rateLimit, 'hard-limit': plan['hard-limit'] } }; } } } else { //the default plan entry.document.plans = { default: { apis: apis, 'rate-limit': { value: rateLimit, 'hard-limit': true } } }; } if (logger.debug()) { logger.debug('creating static product and attaching apis to plans: %s', JSON.stringify(entry, null, 2)); } app.models.product.create( entry, function(err, mymodel) { if (err) { logger.error(err); seriesCallback(err); return; } logger.debug('%s created: %j', 'product', mymodel); seriesCallback(); }); }
javascript
function(seriesCallback) { var entry = {}; // add catalog entry.catalog = defaultCatalog; entry['snapshot-id'] = uid; entry.document = { product: '1.0.0', info: { name: 'static-product', version: '1.0.0', title: 'static-product' }, visibility: { view: { type: 'public' }, subscribe: { type: 'authenticated' } }, apis: apis }; var rateLimit = '100/hour'; if (process.env[LAPTOP_RATELIMIT]) { rateLimit = process.env[LAPTOP_RATELIMIT]; } if (apicCfg && apicCfg.plans && apicCfg.applications) { //add the configured plans entry.document.plans = {}; //add plan and its APIs for (var p in apicCfg.plans) { var plan = apicCfg.plans[p]; if (typeof plan === 'object') { var planApis = {}; for (var i in plan.apis) { var name = plan.apis[i]; //add the api to plan if only if the api does exist if (apis[name]) { planApis[name] = {}; } else { logger.warn('Cannot add the invalid api "%s" to plan "%s"', name, p); } } entry.document.plans[p] = { apis: planApis, 'rate-limit': { value: plan['rate-limit'] || rateLimit, 'hard-limit': plan['hard-limit'] } }; } } } else { //the default plan entry.document.plans = { default: { apis: apis, 'rate-limit': { value: rateLimit, 'hard-limit': true } } }; } if (logger.debug()) { logger.debug('creating static product and attaching apis to plans: %s', JSON.stringify(entry, null, 2)); } app.models.product.create( entry, function(err, mymodel) { if (err) { logger.error(err); seriesCallback(err); return; } logger.debug('%s created: %j', 'product', mymodel); seriesCallback(); }); }
[ "function", "(", "seriesCallback", ")", "{", "var", "entry", "=", "{", "}", ";", "entry", ".", "catalog", "=", "defaultCatalog", ";", "entry", "[", "'snapshot-id'", "]", "=", "uid", ";", "entry", ".", "document", "=", "{", "product", ":", "'1.0.0'", ",", "info", ":", "{", "name", ":", "'static-product'", ",", "version", ":", "'1.0.0'", ",", "title", ":", "'static-product'", "}", ",", "visibility", ":", "{", "view", ":", "{", "type", ":", "'public'", "}", ",", "subscribe", ":", "{", "type", ":", "'authenticated'", "}", "}", ",", "apis", ":", "apis", "}", ";", "var", "rateLimit", "=", "'100/hour'", ";", "if", "(", "process", ".", "env", "[", "LAPTOP_RATELIMIT", "]", ")", "{", "rateLimit", "=", "process", ".", "env", "[", "LAPTOP_RATELIMIT", "]", ";", "}", "if", "(", "apicCfg", "&&", "apicCfg", ".", "plans", "&&", "apicCfg", ".", "applications", ")", "{", "entry", ".", "document", ".", "plans", "=", "{", "}", ";", "for", "(", "var", "p", "in", "apicCfg", ".", "plans", ")", "{", "var", "plan", "=", "apicCfg", ".", "plans", "[", "p", "]", ";", "if", "(", "typeof", "plan", "===", "'object'", ")", "{", "var", "planApis", "=", "{", "}", ";", "for", "(", "var", "i", "in", "plan", ".", "apis", ")", "{", "var", "name", "=", "plan", ".", "apis", "[", "i", "]", ";", "if", "(", "apis", "[", "name", "]", ")", "{", "planApis", "[", "name", "]", "=", "{", "}", ";", "}", "else", "{", "logger", ".", "warn", "(", "'Cannot add the invalid api \"%s\" to plan \"%s\"'", ",", "name", ",", "p", ")", ";", "}", "}", "entry", ".", "document", ".", "plans", "[", "p", "]", "=", "{", "apis", ":", "planApis", ",", "'rate-limit'", ":", "{", "value", ":", "plan", "[", "'rate-limit'", "]", "||", "rateLimit", ",", "'hard-limit'", ":", "plan", "[", "'hard-limit'", "]", "}", "}", ";", "}", "}", "}", "else", "{", "entry", ".", "document", ".", "plans", "=", "{", "default", ":", "{", "apis", ":", "apis", ",", "'rate-limit'", ":", "{", "value", ":", "rateLimit", ",", "'hard-limit'", ":", "true", "}", "}", "}", ";", "}", "if", "(", "logger", ".", "debug", "(", ")", ")", "{", "logger", ".", "debug", "(", "'creating static product and attaching apis to plans: %s'", ",", "JSON", ".", "stringify", "(", "entry", ",", "null", ",", "2", ")", ")", ";", "}", "app", ".", "models", ".", "product", ".", "create", "(", "entry", ",", "function", "(", "err", ",", "mymodel", ")", "{", "if", "(", "err", ")", "{", "logger", ".", "error", "(", "err", ")", ";", "seriesCallback", "(", "err", ")", ";", "return", ";", "}", "logger", ".", "debug", "(", "'%s created: %j'", ",", "'product'", ",", "mymodel", ")", ";", "seriesCallback", "(", ")", ";", "}", ")", ";", "}" ]
3. create one "product" with all the apis defined
[ "3", ".", "create", "one", "product", "with", "all", "the", "apis", "defined" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/server/boot/load-model.js#L911-L986
train
strongloop/microgateway-datastore
server/boot/load-model.js
function(seriesCallback) { var subscriptions = []; if (apicCfg && apicCfg.plans && apicCfg.applications) { //add the configured plans var idx = 0; for (var k in apicCfg.applications) { var theApp = apicCfg.applications[k]; //An application can subscribe only one plan in a given product. Since //we have only one product defined for local data, the subscription of //an app should be a string instead of array! if (theApp && (!theApp.subscription || typeof theApp.subscription !== 'string')) { logger.warn('The app "%s" does not subscribe a plan?', k); } else if (typeof theApp === 'object') { subscriptions[idx] = { 'snapshot-id': uid, organization: defaultOrg, 'developer-organization': defaultOrg, catalog: defaultCatalog, id: 'defaultSubsID-' + k + '-static-product', application: { id: 'defaultAppID-' + k, title: 'defaultAppTitle-' + idx, 'oauth-redirection-uri': (theApp['oauth-redirection-uri'] || 'https://localhost'), 'app-credentials': [ { 'client-id': k, 'client-secret': (theApp['client-secret'] || 'dummy') } ] }, 'plan-registration': { id: ('static-product:1.0.0:' + theApp.subscription) } }; } idx++; } } else { //the default subscription subscriptions[0] = { 'snapshot-id': uid, organization: defaultOrg, 'developer-organization': defaultOrg, catalog: defaultCatalog, id: 'defaultSubsID', application: { id: 'defaultAppID', title: 'defaultAppTitle', 'oauth-redirection-uri': 'https://localhost', 'app-credentials': [ { 'client-id': 'default', 'client-secret': 'CRexOpCRkV1UtjNvRZCVOczkUrNmGyHzhkGKJXiDswo=' } ] }, 'plan-registration': { id: 'ALLPLANS' } }; } async.forEach( subscriptions, function(subscription, subsCallback) { var modelname = 'subscription'; app.models[modelname].create( subscription, function(err, mymodel) { if (err) { logger.error(err); subsCallback(err); return; } logger.debug('%s created: %j', modelname, mymodel); subsCallback(); }); }); seriesCallback(); }
javascript
function(seriesCallback) { var subscriptions = []; if (apicCfg && apicCfg.plans && apicCfg.applications) { //add the configured plans var idx = 0; for (var k in apicCfg.applications) { var theApp = apicCfg.applications[k]; //An application can subscribe only one plan in a given product. Since //we have only one product defined for local data, the subscription of //an app should be a string instead of array! if (theApp && (!theApp.subscription || typeof theApp.subscription !== 'string')) { logger.warn('The app "%s" does not subscribe a plan?', k); } else if (typeof theApp === 'object') { subscriptions[idx] = { 'snapshot-id': uid, organization: defaultOrg, 'developer-organization': defaultOrg, catalog: defaultCatalog, id: 'defaultSubsID-' + k + '-static-product', application: { id: 'defaultAppID-' + k, title: 'defaultAppTitle-' + idx, 'oauth-redirection-uri': (theApp['oauth-redirection-uri'] || 'https://localhost'), 'app-credentials': [ { 'client-id': k, 'client-secret': (theApp['client-secret'] || 'dummy') } ] }, 'plan-registration': { id: ('static-product:1.0.0:' + theApp.subscription) } }; } idx++; } } else { //the default subscription subscriptions[0] = { 'snapshot-id': uid, organization: defaultOrg, 'developer-organization': defaultOrg, catalog: defaultCatalog, id: 'defaultSubsID', application: { id: 'defaultAppID', title: 'defaultAppTitle', 'oauth-redirection-uri': 'https://localhost', 'app-credentials': [ { 'client-id': 'default', 'client-secret': 'CRexOpCRkV1UtjNvRZCVOczkUrNmGyHzhkGKJXiDswo=' } ] }, 'plan-registration': { id: 'ALLPLANS' } }; } async.forEach( subscriptions, function(subscription, subsCallback) { var modelname = 'subscription'; app.models[modelname].create( subscription, function(err, mymodel) { if (err) { logger.error(err); subsCallback(err); return; } logger.debug('%s created: %j', modelname, mymodel); subsCallback(); }); }); seriesCallback(); }
[ "function", "(", "seriesCallback", ")", "{", "var", "subscriptions", "=", "[", "]", ";", "if", "(", "apicCfg", "&&", "apicCfg", ".", "plans", "&&", "apicCfg", ".", "applications", ")", "{", "var", "idx", "=", "0", ";", "for", "(", "var", "k", "in", "apicCfg", ".", "applications", ")", "{", "var", "theApp", "=", "apicCfg", ".", "applications", "[", "k", "]", ";", "if", "(", "theApp", "&&", "(", "!", "theApp", ".", "subscription", "||", "typeof", "theApp", ".", "subscription", "!==", "'string'", ")", ")", "{", "logger", ".", "warn", "(", "'The app \"%s\" does not subscribe a plan?'", ",", "k", ")", ";", "}", "else", "if", "(", "typeof", "theApp", "===", "'object'", ")", "{", "subscriptions", "[", "idx", "]", "=", "{", "'snapshot-id'", ":", "uid", ",", "organization", ":", "defaultOrg", ",", "'developer-organization'", ":", "defaultOrg", ",", "catalog", ":", "defaultCatalog", ",", "id", ":", "'defaultSubsID-'", "+", "k", "+", "'-static-product'", ",", "application", ":", "{", "id", ":", "'defaultAppID-'", "+", "k", ",", "title", ":", "'defaultAppTitle-'", "+", "idx", ",", "'oauth-redirection-uri'", ":", "(", "theApp", "[", "'oauth-redirection-uri'", "]", "||", "'https://localhost'", ")", ",", "'app-credentials'", ":", "[", "{", "'client-id'", ":", "k", ",", "'client-secret'", ":", "(", "theApp", "[", "'client-secret'", "]", "||", "'dummy'", ")", "}", "]", "}", ",", "'plan-registration'", ":", "{", "id", ":", "(", "'static-product:1.0.0:'", "+", "theApp", ".", "subscription", ")", "}", "}", ";", "}", "idx", "++", ";", "}", "}", "else", "{", "subscriptions", "[", "0", "]", "=", "{", "'snapshot-id'", ":", "uid", ",", "organization", ":", "defaultOrg", ",", "'developer-organization'", ":", "defaultOrg", ",", "catalog", ":", "defaultCatalog", ",", "id", ":", "'defaultSubsID'", ",", "application", ":", "{", "id", ":", "'defaultAppID'", ",", "title", ":", "'defaultAppTitle'", ",", "'oauth-redirection-uri'", ":", "'https://localhost'", ",", "'app-credentials'", ":", "[", "{", "'client-id'", ":", "'default'", ",", "'client-secret'", ":", "'CRexOpCRkV1UtjNvRZCVOczkUrNmGyHzhkGKJXiDswo='", "}", "]", "}", ",", "'plan-registration'", ":", "{", "id", ":", "'ALLPLANS'", "}", "}", ";", "}", "async", ".", "forEach", "(", "subscriptions", ",", "function", "(", "subscription", ",", "subsCallback", ")", "{", "var", "modelname", "=", "'subscription'", ";", "app", ".", "models", "[", "modelname", "]", ".", "create", "(", "subscription", ",", "function", "(", "err", ",", "mymodel", ")", "{", "if", "(", "err", ")", "{", "logger", ".", "error", "(", "err", ")", ";", "subsCallback", "(", "err", ")", ";", "return", ";", "}", "logger", ".", "debug", "(", "'%s created: %j'", ",", "modelname", ",", "mymodel", ")", ";", "subsCallback", "(", ")", ";", "}", ")", ";", "}", ")", ";", "seriesCallback", "(", ")", ";", "}" ]
4. create the "subscriptions" instances
[ "4", ".", "create", "the", "subscriptions", "instances" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/server/boot/load-model.js#L988-L1055
train
strongloop/microgateway-datastore
server/boot/load-model.js
function(seriesCallback) { var modelname = 'tlsprofile'; async.forEachOf( apicCfg['tls-profiles'], function(profile, name, asyncCB) { var instance = { 'snapshot-id': uid, 'org-id': defaultOrg.id, id: 'defaultTlsProfile-' + name, name: name, public: false, ciphers: [ 'SSL_RSA_WITH_AES_256_CBC_SHA', 'SSL_RSA_WITH_AES_128_CBC_SHA', 'SSL_RSA_WITH_3DES_EDE_CBC_SHA', 'SSL_RSA_WITH_RCA_128_SHA', 'SSL_RSA_WITH_RCA_128_MD5' ], protocols: [ 'TLSv11', 'TLSv12' ], certs: [], 'mutual-auth': false }; if (profile.rejectUnauthorized === true) { instance['mutual-auth'] = true; } if (Array.isArray(profile.secureProtocols)) { instance.protocols = []; profile.secureProtocols.forEach(function(protocol) { switch (protocol) { case 'TLSv1_method': instance.protocols.push('TLSv1'); break; case 'TLSv1_1_method': instance.protocols.push('TLSv11'); break; case 'TLSv1_2_method': instance.protocols.push('TLSv12'); break; } }); } if (typeof profile.key === 'object') { instance['private-key'] = profile.key.content; } if (typeof profile.cert === 'object') { instance.certs.push({ name: profile.cert.name, cert: profile.cert.content, 'cert-type': 'INTERMEDIATE', 'cert-id': name + '-cert-' + profile.cert.name }); } if (Array.isArray(profile.ca)) { profile.ca.forEach(function(ca) { if (typeof ca === 'object') { instance.certs.push({ name: ca.name, cert: ca.content, 'cert-type': 'CLIENT', 'cert-id': name + '-ca-cert-' + ca.name }); } }); } app.models[modelname].create( instance, function(err, mymodel) { if (err) { logger.error('Failed to populate a tls-profile:', err); } else { logger.debug('%s created: %j', modelname, mymodel); } asyncCB(); }); }); seriesCallback(); }
javascript
function(seriesCallback) { var modelname = 'tlsprofile'; async.forEachOf( apicCfg['tls-profiles'], function(profile, name, asyncCB) { var instance = { 'snapshot-id': uid, 'org-id': defaultOrg.id, id: 'defaultTlsProfile-' + name, name: name, public: false, ciphers: [ 'SSL_RSA_WITH_AES_256_CBC_SHA', 'SSL_RSA_WITH_AES_128_CBC_SHA', 'SSL_RSA_WITH_3DES_EDE_CBC_SHA', 'SSL_RSA_WITH_RCA_128_SHA', 'SSL_RSA_WITH_RCA_128_MD5' ], protocols: [ 'TLSv11', 'TLSv12' ], certs: [], 'mutual-auth': false }; if (profile.rejectUnauthorized === true) { instance['mutual-auth'] = true; } if (Array.isArray(profile.secureProtocols)) { instance.protocols = []; profile.secureProtocols.forEach(function(protocol) { switch (protocol) { case 'TLSv1_method': instance.protocols.push('TLSv1'); break; case 'TLSv1_1_method': instance.protocols.push('TLSv11'); break; case 'TLSv1_2_method': instance.protocols.push('TLSv12'); break; } }); } if (typeof profile.key === 'object') { instance['private-key'] = profile.key.content; } if (typeof profile.cert === 'object') { instance.certs.push({ name: profile.cert.name, cert: profile.cert.content, 'cert-type': 'INTERMEDIATE', 'cert-id': name + '-cert-' + profile.cert.name }); } if (Array.isArray(profile.ca)) { profile.ca.forEach(function(ca) { if (typeof ca === 'object') { instance.certs.push({ name: ca.name, cert: ca.content, 'cert-type': 'CLIENT', 'cert-id': name + '-ca-cert-' + ca.name }); } }); } app.models[modelname].create( instance, function(err, mymodel) { if (err) { logger.error('Failed to populate a tls-profile:', err); } else { logger.debug('%s created: %j', modelname, mymodel); } asyncCB(); }); }); seriesCallback(); }
[ "function", "(", "seriesCallback", ")", "{", "var", "modelname", "=", "'tlsprofile'", ";", "async", ".", "forEachOf", "(", "apicCfg", "[", "'tls-profiles'", "]", ",", "function", "(", "profile", ",", "name", ",", "asyncCB", ")", "{", "var", "instance", "=", "{", "'snapshot-id'", ":", "uid", ",", "'org-id'", ":", "defaultOrg", ".", "id", ",", "id", ":", "'defaultTlsProfile-'", "+", "name", ",", "name", ":", "name", ",", "public", ":", "false", ",", "ciphers", ":", "[", "'SSL_RSA_WITH_AES_256_CBC_SHA'", ",", "'SSL_RSA_WITH_AES_128_CBC_SHA'", ",", "'SSL_RSA_WITH_3DES_EDE_CBC_SHA'", ",", "'SSL_RSA_WITH_RCA_128_SHA'", ",", "'SSL_RSA_WITH_RCA_128_MD5'", "]", ",", "protocols", ":", "[", "'TLSv11'", ",", "'TLSv12'", "]", ",", "certs", ":", "[", "]", ",", "'mutual-auth'", ":", "false", "}", ";", "if", "(", "profile", ".", "rejectUnauthorized", "===", "true", ")", "{", "instance", "[", "'mutual-auth'", "]", "=", "true", ";", "}", "if", "(", "Array", ".", "isArray", "(", "profile", ".", "secureProtocols", ")", ")", "{", "instance", ".", "protocols", "=", "[", "]", ";", "profile", ".", "secureProtocols", ".", "forEach", "(", "function", "(", "protocol", ")", "{", "switch", "(", "protocol", ")", "{", "case", "'TLSv1_method'", ":", "instance", ".", "protocols", ".", "push", "(", "'TLSv1'", ")", ";", "break", ";", "case", "'TLSv1_1_method'", ":", "instance", ".", "protocols", ".", "push", "(", "'TLSv11'", ")", ";", "break", ";", "case", "'TLSv1_2_method'", ":", "instance", ".", "protocols", ".", "push", "(", "'TLSv12'", ")", ";", "break", ";", "}", "}", ")", ";", "}", "if", "(", "typeof", "profile", ".", "key", "===", "'object'", ")", "{", "instance", "[", "'private-key'", "]", "=", "profile", ".", "key", ".", "content", ";", "}", "if", "(", "typeof", "profile", ".", "cert", "===", "'object'", ")", "{", "instance", ".", "certs", ".", "push", "(", "{", "name", ":", "profile", ".", "cert", ".", "name", ",", "cert", ":", "profile", ".", "cert", ".", "content", ",", "'cert-type'", ":", "'INTERMEDIATE'", ",", "'cert-id'", ":", "name", "+", "'-cert-'", "+", "profile", ".", "cert", ".", "name", "}", ")", ";", "}", "if", "(", "Array", ".", "isArray", "(", "profile", ".", "ca", ")", ")", "{", "profile", ".", "ca", ".", "forEach", "(", "function", "(", "ca", ")", "{", "if", "(", "typeof", "ca", "===", "'object'", ")", "{", "instance", ".", "certs", ".", "push", "(", "{", "name", ":", "ca", ".", "name", ",", "cert", ":", "ca", ".", "content", ",", "'cert-type'", ":", "'CLIENT'", ",", "'cert-id'", ":", "name", "+", "'-ca-cert-'", "+", "ca", ".", "name", "}", ")", ";", "}", "}", ")", ";", "}", "app", ".", "models", "[", "modelname", "]", ".", "create", "(", "instance", ",", "function", "(", "err", ",", "mymodel", ")", "{", "if", "(", "err", ")", "{", "logger", ".", "error", "(", "'Failed to populate a tls-profile:'", ",", "err", ")", ";", "}", "else", "{", "logger", ".", "debug", "(", "'%s created: %j'", ",", "modelname", ",", "mymodel", ")", ";", "}", "asyncCB", "(", ")", ";", "}", ")", ";", "}", ")", ";", "seriesCallback", "(", ")", ";", "}" ]
5. create the "tls-profile" instances
[ "5", ".", "create", "the", "tls", "-", "profile", "instances" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/server/boot/load-model.js#L1058-L1137
train
strongloop/microgateway-datastore
server/boot/load-model.js
populateSnapshot
function populateSnapshot(app, uid, cb) { logger.debug('populateSnapshot entry'); app.models.snapshot.create( { id: uid, refcount: '1', current: 'false' }, function(err, mymodel) { if (err) { logger.error('populateSnapshot error'); cb(err); return; } logger.debug('populateSnapshot exit: %j', mymodel); cb(); }); }
javascript
function populateSnapshot(app, uid, cb) { logger.debug('populateSnapshot entry'); app.models.snapshot.create( { id: uid, refcount: '1', current: 'false' }, function(err, mymodel) { if (err) { logger.error('populateSnapshot error'); cb(err); return; } logger.debug('populateSnapshot exit: %j', mymodel); cb(); }); }
[ "function", "populateSnapshot", "(", "app", ",", "uid", ",", "cb", ")", "{", "logger", ".", "debug", "(", "'populateSnapshot entry'", ")", ";", "app", ".", "models", ".", "snapshot", ".", "create", "(", "{", "id", ":", "uid", ",", "refcount", ":", "'1'", ",", "current", ":", "'false'", "}", ",", "function", "(", "err", ",", "mymodel", ")", "{", "if", "(", "err", ")", "{", "logger", ".", "error", "(", "'populateSnapshot error'", ")", ";", "cb", "(", "err", ")", ";", "return", ";", "}", "logger", ".", "debug", "(", "'populateSnapshot exit: %j'", ",", "mymodel", ")", ";", "cb", "(", ")", ";", "}", ")", ";", "}" ]
Initializes new snapshot instance in snapshot model @param {???} app - loopback application @param {string} uid - snapshot identifier @param {callback} cb - callback that handles error or successful completion
[ "Initializes", "new", "snapshot", "instance", "in", "snapshot", "model" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/server/boot/load-model.js#L1418-L1434
train
strongloop/microgateway-datastore
server/boot/load-model.js
releaseSnapshot
function releaseSnapshot(app, uid, cb) { logger.debug('releaseSnapshot entry'); app.models.snapshot.release(uid, function(err) { if (err) { logger.error(err); } logger.debug('releaseSnapshot exit'); if (cb) { cb(err); } }); }
javascript
function releaseSnapshot(app, uid, cb) { logger.debug('releaseSnapshot entry'); app.models.snapshot.release(uid, function(err) { if (err) { logger.error(err); } logger.debug('releaseSnapshot exit'); if (cb) { cb(err); } }); }
[ "function", "releaseSnapshot", "(", "app", ",", "uid", ",", "cb", ")", "{", "logger", ".", "debug", "(", "'releaseSnapshot entry'", ")", ";", "app", ".", "models", ".", "snapshot", ".", "release", "(", "uid", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "logger", ".", "error", "(", "err", ")", ";", "}", "logger", ".", "debug", "(", "'releaseSnapshot exit'", ")", ";", "if", "(", "cb", ")", "{", "cb", "(", "err", ")", ";", "}", "}", ")", ";", "}" ]
Releases reference on snapshot instance in snapshot model @param {???} app - loopback application @param {string} uid - snapshot identifier
[ "Releases", "reference", "on", "snapshot", "instance", "in", "snapshot", "model" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/server/boot/load-model.js#L1441-L1454
train
strongloop/microgateway-datastore
server/boot/load-model.js
updateSnapshot
function updateSnapshot(app, uid, cb) { logger.debug('updateSnapshot entry'); app.models.snapshot.findOne( { where: { current: 'true' } }, function(err, instance) { if (err) { // fall through assuming there was no current } else if (instance) { instance.updateAttributes( { current: 'false' }, function(err, instance) { if (err) { // fall through assuming instance was deleted } }); releaseSnapshot(app, instance.id); } }); app.models.snapshot.findById(uid, function(err, instance) { if (err) { logger.debug('updateSnapshot error(1)'); cb(err); return; } instance.updateAttributes( { current: 'true' }, function(err, instance) { if (err) { logger.debug('updateSnapshot error(2)'); cb(err); return; } logger.debug('updateSnapshot exit'); cb(); }); }); }
javascript
function updateSnapshot(app, uid, cb) { logger.debug('updateSnapshot entry'); app.models.snapshot.findOne( { where: { current: 'true' } }, function(err, instance) { if (err) { // fall through assuming there was no current } else if (instance) { instance.updateAttributes( { current: 'false' }, function(err, instance) { if (err) { // fall through assuming instance was deleted } }); releaseSnapshot(app, instance.id); } }); app.models.snapshot.findById(uid, function(err, instance) { if (err) { logger.debug('updateSnapshot error(1)'); cb(err); return; } instance.updateAttributes( { current: 'true' }, function(err, instance) { if (err) { logger.debug('updateSnapshot error(2)'); cb(err); return; } logger.debug('updateSnapshot exit'); cb(); }); }); }
[ "function", "updateSnapshot", "(", "app", ",", "uid", ",", "cb", ")", "{", "logger", ".", "debug", "(", "'updateSnapshot entry'", ")", ";", "app", ".", "models", ".", "snapshot", ".", "findOne", "(", "{", "where", ":", "{", "current", ":", "'true'", "}", "}", ",", "function", "(", "err", ",", "instance", ")", "{", "if", "(", "err", ")", "{", "}", "else", "if", "(", "instance", ")", "{", "instance", ".", "updateAttributes", "(", "{", "current", ":", "'false'", "}", ",", "function", "(", "err", ",", "instance", ")", "{", "if", "(", "err", ")", "{", "}", "}", ")", ";", "releaseSnapshot", "(", "app", ",", "instance", ".", "id", ")", ";", "}", "}", ")", ";", "app", ".", "models", ".", "snapshot", ".", "findById", "(", "uid", ",", "function", "(", "err", ",", "instance", ")", "{", "if", "(", "err", ")", "{", "logger", ".", "debug", "(", "'updateSnapshot error(1)'", ")", ";", "cb", "(", "err", ")", ";", "return", ";", "}", "instance", ".", "updateAttributes", "(", "{", "current", ":", "'true'", "}", ",", "function", "(", "err", ",", "instance", ")", "{", "if", "(", "err", ")", "{", "logger", ".", "debug", "(", "'updateSnapshot error(2)'", ")", ";", "cb", "(", "err", ")", ";", "return", ";", "}", "logger", ".", "debug", "(", "'updateSnapshot exit'", ")", ";", "cb", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Updates snapshot instance in snapshot model to reflect 'current' @param {???} app - loopback application @param {string} uid - snapshot identifier @param {callback} cb - callback that handles error or successful completion
[ "Updates", "snapshot", "instance", "in", "snapshot", "model", "to", "reflect", "current" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/server/boot/load-model.js#L1462-L1501
train
strongloop/microgateway-datastore
common/models/optimizedData.js
getOpParams
function getOpParams(pathParams, opParams) { var unionParams = _.unionWith(opParams, pathParams, opParamComparator); return unionParams; }
javascript
function getOpParams(pathParams, opParams) { var unionParams = _.unionWith(opParams, pathParams, opParamComparator); return unionParams; }
[ "function", "getOpParams", "(", "pathParams", ",", "opParams", ")", "{", "var", "unionParams", "=", "_", ".", "unionWith", "(", "opParams", ",", "pathParams", ",", "opParamComparator", ")", ";", "return", "unionParams", ";", "}" ]
Returns a Object that denotes the parameters associated with the operation @param {Array} pathParams path-level parameters in the swagger @param {Array} opParams op-level perameters in the swagger
[ "Returns", "a", "Object", "that", "denotes", "the", "parameters", "associated", "with", "the", "operation" ]
cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7
https://github.com/strongloop/microgateway-datastore/blob/cd41b8b43fd6128e2e9eeab831c84c35c9cc64d7/common/models/optimizedData.js#L811-L814
train
berlinonline/converjon
lib/lock.js
free
function free(key) { if (locks[key]) { delete locks[key]; stats.lock_remove(); } tick(key); }
javascript
function free(key) { if (locks[key]) { delete locks[key]; stats.lock_remove(); } tick(key); }
[ "function", "free", "(", "key", ")", "{", "if", "(", "locks", "[", "key", "]", ")", "{", "delete", "locks", "[", "key", "]", ";", "stats", ".", "lock_remove", "(", ")", ";", "}", "tick", "(", "key", ")", ";", "}" ]
release a lock on a resource
[ "release", "a", "lock", "on", "a", "resource" ]
ace8c1b8ff0c3077919b73d3d7604c60a60f37f3
https://github.com/berlinonline/converjon/blob/ace8c1b8ff0c3077919b73d3d7604c60a60f37f3/lib/lock.js#L16-L22
train
berlinonline/converjon
lib/lock.js
tick
function tick(key) { var next; if (waiting[key]) { //there's somone waiting for this resource if (!locks[key]) { locks[key] = true; stats.lock_add(); next = waiting[key].shift(); if (waiting[key].length === 0) { //nobody is waiting for this resource anymore, clean it up delete waiting[key]; } next(key); } } }
javascript
function tick(key) { var next; if (waiting[key]) { //there's somone waiting for this resource if (!locks[key]) { locks[key] = true; stats.lock_add(); next = waiting[key].shift(); if (waiting[key].length === 0) { //nobody is waiting for this resource anymore, clean it up delete waiting[key]; } next(key); } } }
[ "function", "tick", "(", "key", ")", "{", "var", "next", ";", "if", "(", "waiting", "[", "key", "]", ")", "{", "if", "(", "!", "locks", "[", "key", "]", ")", "{", "locks", "[", "key", "]", "=", "true", ";", "stats", ".", "lock_add", "(", ")", ";", "next", "=", "waiting", "[", "key", "]", ".", "shift", "(", ")", ";", "if", "(", "waiting", "[", "key", "]", ".", "length", "===", "0", ")", "{", "delete", "waiting", "[", "key", "]", ";", "}", "next", "(", "key", ")", ";", "}", "}", "}" ]
cycle the waiting list for one resource
[ "cycle", "the", "waiting", "list", "for", "one", "resource" ]
ace8c1b8ff0c3077919b73d3d7604c60a60f37f3
https://github.com/berlinonline/converjon/blob/ace8c1b8ff0c3077919b73d3d7604c60a60f37f3/lib/lock.js#L27-L42
train
berlinonline/converjon
lib/lock.js
wait
function wait(key, cb) { if (!waiting[key]) { waiting[key] = []; } waiting[key].push(cb); }
javascript
function wait(key, cb) { if (!waiting[key]) { waiting[key] = []; } waiting[key].push(cb); }
[ "function", "wait", "(", "key", ",", "cb", ")", "{", "if", "(", "!", "waiting", "[", "key", "]", ")", "{", "waiting", "[", "key", "]", "=", "[", "]", ";", "}", "waiting", "[", "key", "]", ".", "push", "(", "cb", ")", ";", "}" ]
register a handler for a resource the handler will be called when nobody before it is waiting for that resoruce
[ "register", "a", "handler", "for", "a", "resource", "the", "handler", "will", "be", "called", "when", "nobody", "before", "it", "is", "waiting", "for", "that", "resoruce" ]
ace8c1b8ff0c3077919b73d3d7604c60a60f37f3
https://github.com/berlinonline/converjon/blob/ace8c1b8ff0c3077919b73d3d7604c60a60f37f3/lib/lock.js#L49-L55
train
berlinonline/converjon
lib/lock.js
lock
function lock(key) { var promise = new Promise(function(resolve, reject) { wait(key, function(key) { var released = false; var lock = function() { if (!released) { free(key); released = true; } }; lock.key = key; resolve(lock); }); }); tick(key); return promise; }
javascript
function lock(key) { var promise = new Promise(function(resolve, reject) { wait(key, function(key) { var released = false; var lock = function() { if (!released) { free(key); released = true; } }; lock.key = key; resolve(lock); }); }); tick(key); return promise; }
[ "function", "lock", "(", "key", ")", "{", "var", "promise", "=", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "wait", "(", "key", ",", "function", "(", "key", ")", "{", "var", "released", "=", "false", ";", "var", "lock", "=", "function", "(", ")", "{", "if", "(", "!", "released", ")", "{", "free", "(", "key", ")", ";", "released", "=", "true", ";", "}", "}", ";", "lock", ".", "key", "=", "key", ";", "resolve", "(", "lock", ")", ";", "}", ")", ";", "}", ")", ";", "tick", "(", "key", ")", ";", "return", "promise", ";", "}" ]
Returns a promise for a resource lock that resolves into a function to release that lock again. Usage: var l1 = lock("foo"); l1.then(function(l) { // do your work // l.key contains the key of the locked_item l(); /release the lock }); @param {string} identifier for a resource to be locked @returns {Promise} A Promise that resolves when the lock is obtained
[ "Returns", "a", "promise", "for", "a", "resource", "lock", "that", "resolves", "into", "a", "function", "to", "release", "that", "lock", "again", "." ]
ace8c1b8ff0c3077919b73d3d7604c60a60f37f3
https://github.com/berlinonline/converjon/blob/ace8c1b8ff0c3077919b73d3d7604c60a60f37f3/lib/lock.js#L72-L92
train
al66/imicros-flow
dev/flow.middleware.kafka.js
check
async function check(){ if (broker.emitter.open <= 0) return true; else { this.logger.warn("Event queue not empty... waiting", {queue: broker.emitter.open}); throw "Retry"; } }
javascript
async function check(){ if (broker.emitter.open <= 0) return true; else { this.logger.warn("Event queue not empty... waiting", {queue: broker.emitter.open}); throw "Retry"; } }
[ "async", "function", "check", "(", ")", "{", "if", "(", "broker", ".", "emitter", ".", "open", "<=", "0", ")", "return", "true", ";", "else", "{", "this", ".", "logger", ".", "warn", "(", "\"Event queue not empty... waiting\"", ",", "{", "queue", ":", "broker", ".", "emitter", ".", "open", "}", ")", ";", "throw", "\"Retry\"", ";", "}", "}" ]
Wait for empty queue
[ "Wait", "for", "empty", "queue" ]
5998e3b88fb7d6a892c791162ad8b49aeefcfb31
https://github.com/al66/imicros-flow/blob/5998e3b88fb7d6a892c791162ad8b49aeefcfb31/dev/flow.middleware.kafka.js#L402-L408
train
tomarad/JSON-Schema-Instantiator
dist/scripts/scripts.js
isPropertyRequired
function isPropertyRequired(property, requiredArray) { var found = false; requiredArray = requiredArray || []; requiredArray.forEach(function(requiredProperty) { if (requiredProperty === property) { found = true; } }); return found; }
javascript
function isPropertyRequired(property, requiredArray) { var found = false; requiredArray = requiredArray || []; requiredArray.forEach(function(requiredProperty) { if (requiredProperty === property) { found = true; } }); return found; }
[ "function", "isPropertyRequired", "(", "property", ",", "requiredArray", ")", "{", "var", "found", "=", "false", ";", "requiredArray", "=", "requiredArray", "||", "[", "]", ";", "requiredArray", ".", "forEach", "(", "function", "(", "requiredProperty", ")", "{", "if", "(", "requiredProperty", "===", "property", ")", "{", "found", "=", "true", ";", "}", "}", ")", ";", "return", "found", ";", "}" ]
Checks whether a property is on required array. @param property - the property to check. @param requiredArray - the required array @returns {boolean}
[ "Checks", "whether", "a", "property", "is", "on", "required", "array", "." ]
04c35c5dd452f51a9a4d2f04d11bad57d7a5cba3
https://github.com/tomarad/JSON-Schema-Instantiator/blob/04c35c5dd452f51a9a4d2f04d11bad57d7a5cba3/dist/scripts/scripts.js#L30-L39
train
tomarad/JSON-Schema-Instantiator
dist/scripts/scripts.js
instantiatePrimitive
function instantiatePrimitive(val) { var type = val.type; // Support for default values in the JSON Schema. if (val.hasOwnProperty('default')) { return val.default; } return typesInstantiator[type]; }
javascript
function instantiatePrimitive(val) { var type = val.type; // Support for default values in the JSON Schema. if (val.hasOwnProperty('default')) { return val.default; } return typesInstantiator[type]; }
[ "function", "instantiatePrimitive", "(", "val", ")", "{", "var", "type", "=", "val", ".", "type", ";", "if", "(", "val", ".", "hasOwnProperty", "(", "'default'", ")", ")", "{", "return", "val", ".", "default", ";", "}", "return", "typesInstantiator", "[", "type", "]", ";", "}" ]
Instantiate a primitive. @param val - The object that represents the primitive. @returns {*}
[ "Instantiate", "a", "primitive", "." ]
04c35c5dd452f51a9a4d2f04d11bad57d7a5cba3
https://github.com/tomarad/JSON-Schema-Instantiator/blob/04c35c5dd452f51a9a4d2f04d11bad57d7a5cba3/dist/scripts/scripts.js#L51-L60
train
tomarad/JSON-Schema-Instantiator
dist/scripts/scripts.js
getObjectType
function getObjectType(obj) { // Check if type is array of types. if (isArray(obj.type)) { obj.type = obj.type[0]; } return obj.type; }
javascript
function getObjectType(obj) { // Check if type is array of types. if (isArray(obj.type)) { obj.type = obj.type[0]; } return obj.type; }
[ "function", "getObjectType", "(", "obj", ")", "{", "if", "(", "isArray", "(", "obj", ".", "type", ")", ")", "{", "obj", ".", "type", "=", "obj", ".", "type", "[", "0", "]", ";", "}", "return", "obj", ".", "type", ";", "}" ]
Extracts the type of the object. If the type is an array, set type to first in list of types. If obj.type is not overridden, it will fail the isPrimitive check. Which internally also checks obj.type. @param obj - An object.
[ "Extracts", "the", "type", "of", "the", "object", ".", "If", "the", "type", "is", "an", "array", "set", "type", "to", "first", "in", "list", "of", "types", ".", "If", "obj", ".", "type", "is", "not", "overridden", "it", "will", "fail", "the", "isPrimitive", "check", ".", "Which", "internally", "also", "checks", "obj", ".", "type", "." ]
04c35c5dd452f51a9a4d2f04d11bad57d7a5cba3
https://github.com/tomarad/JSON-Schema-Instantiator/blob/04c35c5dd452f51a9a4d2f04d11bad57d7a5cba3/dist/scripts/scripts.js#L87-L94
train
tomarad/JSON-Schema-Instantiator
dist/scripts/scripts.js
findDefinition
function findDefinition(schema, ref) { var propertyPath = ref.split('/').slice(1); // Ignore the #/uri at the beginning. var currentProperty = propertyPath.splice(0, 1)[0]; var currentValue = schema; while (currentProperty) { currentValue = currentValue[currentProperty]; currentProperty = propertyPath.splice(0, 1)[0]; } return currentValue; }
javascript
function findDefinition(schema, ref) { var propertyPath = ref.split('/').slice(1); // Ignore the #/uri at the beginning. var currentProperty = propertyPath.splice(0, 1)[0]; var currentValue = schema; while (currentProperty) { currentValue = currentValue[currentProperty]; currentProperty = propertyPath.splice(0, 1)[0]; } return currentValue; }
[ "function", "findDefinition", "(", "schema", ",", "ref", ")", "{", "var", "propertyPath", "=", "ref", ".", "split", "(", "'/'", ")", ".", "slice", "(", "1", ")", ";", "var", "currentProperty", "=", "propertyPath", ".", "splice", "(", "0", ",", "1", ")", "[", "0", "]", ";", "var", "currentValue", "=", "schema", ";", "while", "(", "currentProperty", ")", "{", "currentValue", "=", "currentValue", "[", "currentProperty", "]", ";", "currentProperty", "=", "propertyPath", ".", "splice", "(", "0", ",", "1", ")", "[", "0", "]", ";", "}", "return", "currentValue", ";", "}" ]
Finds a definition in a schema. Useful for finding references. @param schema The full schema object. @param ref The reference to find. @return {*} The object representing the ref.
[ "Finds", "a", "definition", "in", "a", "schema", ".", "Useful", "for", "finding", "references", "." ]
04c35c5dd452f51a9a4d2f04d11bad57d7a5cba3
https://github.com/tomarad/JSON-Schema-Instantiator/blob/04c35c5dd452f51a9a4d2f04d11bad57d7a5cba3/dist/scripts/scripts.js#L120-L132
train
tomarad/JSON-Schema-Instantiator
dist/scripts/scripts.js
instantiate
function instantiate(schema, options) { options = options || {}; /** * Visits each sub-object using recursion. * If it reaches a primitive, instantiate it. * @param obj - The object that represents the schema. * @param name - The name of the current object. * @param data - The instance data that represents the current object. */ function visit(obj, name, data) { if (!obj) { return; } var i; var type = getObjectType(obj); // We want non-primitives objects (primitive === object w/o properties). if (type === 'object' && obj.properties) { data[name] = data[name] || { }; // Visit each property. for (var property in obj.properties) { if (obj.properties.hasOwnProperty(property)) { if (shouldVisit(property, obj, options)) { visit(obj.properties[property], property, data[name]); } } } } else if (obj.allOf) { for (i = 0; i < obj.allOf.length; i++) { visit(obj.allOf[i], name, data); } } else if (obj.$ref) { obj = findDefinition(schema, obj.$ref); visit(obj, name, data); } else if (type === 'array') { data[name] = []; var len = 0; if (obj.minItems || obj.minItems > 0) { len = obj.minItems; } // Instantiate 'len' items. for (i = 0; i < len; i++) { visit(obj.items, i, data[name]); } } else if (isEnum(obj)) { data[name] = instantiateEnum(obj); } else if (isPrimitive(obj)) { data[name] = instantiatePrimitive(obj); } } var data = {}; visit(schema, 'kek', data); return data['kek']; }
javascript
function instantiate(schema, options) { options = options || {}; /** * Visits each sub-object using recursion. * If it reaches a primitive, instantiate it. * @param obj - The object that represents the schema. * @param name - The name of the current object. * @param data - The instance data that represents the current object. */ function visit(obj, name, data) { if (!obj) { return; } var i; var type = getObjectType(obj); // We want non-primitives objects (primitive === object w/o properties). if (type === 'object' && obj.properties) { data[name] = data[name] || { }; // Visit each property. for (var property in obj.properties) { if (obj.properties.hasOwnProperty(property)) { if (shouldVisit(property, obj, options)) { visit(obj.properties[property], property, data[name]); } } } } else if (obj.allOf) { for (i = 0; i < obj.allOf.length; i++) { visit(obj.allOf[i], name, data); } } else if (obj.$ref) { obj = findDefinition(schema, obj.$ref); visit(obj, name, data); } else if (type === 'array') { data[name] = []; var len = 0; if (obj.minItems || obj.minItems > 0) { len = obj.minItems; } // Instantiate 'len' items. for (i = 0; i < len; i++) { visit(obj.items, i, data[name]); } } else if (isEnum(obj)) { data[name] = instantiateEnum(obj); } else if (isPrimitive(obj)) { data[name] = instantiatePrimitive(obj); } } var data = {}; visit(schema, 'kek', data); return data['kek']; }
[ "function", "instantiate", "(", "schema", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "function", "visit", "(", "obj", ",", "name", ",", "data", ")", "{", "if", "(", "!", "obj", ")", "{", "return", ";", "}", "var", "i", ";", "var", "type", "=", "getObjectType", "(", "obj", ")", ";", "if", "(", "type", "===", "'object'", "&&", "obj", ".", "properties", ")", "{", "data", "[", "name", "]", "=", "data", "[", "name", "]", "||", "{", "}", ";", "for", "(", "var", "property", "in", "obj", ".", "properties", ")", "{", "if", "(", "obj", ".", "properties", ".", "hasOwnProperty", "(", "property", ")", ")", "{", "if", "(", "shouldVisit", "(", "property", ",", "obj", ",", "options", ")", ")", "{", "visit", "(", "obj", ".", "properties", "[", "property", "]", ",", "property", ",", "data", "[", "name", "]", ")", ";", "}", "}", "}", "}", "else", "if", "(", "obj", ".", "allOf", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "obj", ".", "allOf", ".", "length", ";", "i", "++", ")", "{", "visit", "(", "obj", ".", "allOf", "[", "i", "]", ",", "name", ",", "data", ")", ";", "}", "}", "else", "if", "(", "obj", ".", "$ref", ")", "{", "obj", "=", "findDefinition", "(", "schema", ",", "obj", ".", "$ref", ")", ";", "visit", "(", "obj", ",", "name", ",", "data", ")", ";", "}", "else", "if", "(", "type", "===", "'array'", ")", "{", "data", "[", "name", "]", "=", "[", "]", ";", "var", "len", "=", "0", ";", "if", "(", "obj", ".", "minItems", "||", "obj", ".", "minItems", ">", "0", ")", "{", "len", "=", "obj", ".", "minItems", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "visit", "(", "obj", ".", "items", ",", "i", ",", "data", "[", "name", "]", ")", ";", "}", "}", "else", "if", "(", "isEnum", "(", "obj", ")", ")", "{", "data", "[", "name", "]", "=", "instantiateEnum", "(", "obj", ")", ";", "}", "else", "if", "(", "isPrimitive", "(", "obj", ")", ")", "{", "data", "[", "name", "]", "=", "instantiatePrimitive", "(", "obj", ")", ";", "}", "}", "var", "data", "=", "{", "}", ";", "visit", "(", "schema", ",", "'kek'", ",", "data", ")", ";", "return", "data", "[", "'kek'", "]", ";", "}" ]
The main function. Calls sub-objects recursively, depth first, using the sub-function 'visit'. @param schema - The schema to instantiate. @returns {*}
[ "The", "main", "function", ".", "Calls", "sub", "-", "objects", "recursively", "depth", "first", "using", "the", "sub", "-", "function", "visit", "." ]
04c35c5dd452f51a9a4d2f04d11bad57d7a5cba3
https://github.com/tomarad/JSON-Schema-Instantiator/blob/04c35c5dd452f51a9a4d2f04d11bad57d7a5cba3/dist/scripts/scripts.js#L140-L198
train
joecohens/laravel-elixir-webpack
index.js
function(options) { if (config.sourcemaps) { options = _.defaults( options, { devtool: '#source-map' } ); } if (config.production) { var currPlugins = _.isArray(options.plugins) ? options.plugins : []; options.plugins = currPlugins.concat([new UglifyJsPlugin({ sourceMap: false })]); } return options; }
javascript
function(options) { if (config.sourcemaps) { options = _.defaults( options, { devtool: '#source-map' } ); } if (config.production) { var currPlugins = _.isArray(options.plugins) ? options.plugins : []; options.plugins = currPlugins.concat([new UglifyJsPlugin({ sourceMap: false })]); } return options; }
[ "function", "(", "options", ")", "{", "if", "(", "config", ".", "sourcemaps", ")", "{", "options", "=", "_", ".", "defaults", "(", "options", ",", "{", "devtool", ":", "'#source-map'", "}", ")", ";", "}", "if", "(", "config", ".", "production", ")", "{", "var", "currPlugins", "=", "_", ".", "isArray", "(", "options", ".", "plugins", ")", "?", "options", ".", "plugins", ":", "[", "]", ";", "options", ".", "plugins", "=", "currPlugins", ".", "concat", "(", "[", "new", "UglifyJsPlugin", "(", "{", "sourceMap", ":", "false", "}", ")", "]", ")", ";", "}", "return", "options", ";", "}" ]
Add sensitive default values to webpack options such as sourcemaps and minification. @param {object} options @return {object}
[ "Add", "sensitive", "default", "values", "to", "webpack", "options", "such", "as", "sourcemaps", "and", "minification", "." ]
d56e06bbd854f16304387f737414889d3846be3b
https://github.com/joecohens/laravel-elixir-webpack/blob/d56e06bbd854f16304387f737414889d3846be3b/index.js#L65-L79
train
Peakfijn/Conventions
packages/cz-changelog-peakfijn/commitlint-utils.js
getRule
function getRule(commitlintConfig, ruleName) { const rule = commitlintConfig.rules[ruleName]; if (rule) { return { raw: rule, level: rule[0], applicable: rule[1], value: rule[2], }; } }
javascript
function getRule(commitlintConfig, ruleName) { const rule = commitlintConfig.rules[ruleName]; if (rule) { return { raw: rule, level: rule[0], applicable: rule[1], value: rule[2], }; } }
[ "function", "getRule", "(", "commitlintConfig", ",", "ruleName", ")", "{", "const", "rule", "=", "commitlintConfig", ".", "rules", "[", "ruleName", "]", ";", "if", "(", "rule", ")", "{", "return", "{", "raw", ":", "rule", ",", "level", ":", "rule", "[", "0", "]", ",", "applicable", ":", "rule", "[", "1", "]", ",", "value", ":", "rule", "[", "2", "]", ",", "}", ";", "}", "}" ]
Get information from the loaded commitlint config. This will return an object containing the basic information for this rule. @param {Object} commitlintConfig @param {Object} ruleName @return {Object?}
[ "Get", "information", "from", "the", "loaded", "commitlint", "config", ".", "This", "will", "return", "an", "object", "containing", "the", "basic", "information", "for", "this", "rule", "." ]
09ac205ec93d18d0721517ccc80af5e22031de4b
https://github.com/Peakfijn/Conventions/blob/09ac205ec93d18d0721517ccc80af5e22031de4b/packages/cz-changelog-peakfijn/commitlint-utils.js#L11-L22
train
Peakfijn/Conventions
packages/cz-changelog-peakfijn/commitlint-utils.js
reportIsValid
function reportIsValid(report = {}) { return report.valid && report.errors.length === 0 && report.warnings.length === 0; }
javascript
function reportIsValid(report = {}) { return report.valid && report.errors.length === 0 && report.warnings.length === 0; }
[ "function", "reportIsValid", "(", "report", "=", "{", "}", ")", "{", "return", "report", ".", "valid", "&&", "report", ".", "errors", ".", "length", "===", "0", "&&", "report", ".", "warnings", ".", "length", "===", "0", ";", "}" ]
Determine if the report is valid and doesn't contain errors or warnings. @param {Object} report @return {boolean}
[ "Determine", "if", "the", "report", "is", "valid", "and", "doesn", "t", "contain", "errors", "or", "warnings", "." ]
09ac205ec93d18d0721517ccc80af5e22031de4b
https://github.com/Peakfijn/Conventions/blob/09ac205ec93d18d0721517ccc80af5e22031de4b/packages/cz-changelog-peakfijn/commitlint-utils.js#L51-L53
train
Peakfijn/Conventions
packages/cz-changelog-peakfijn/commitlint-utils.js
reportSummary
function reportSummary(report = {}) { if (reportIsValid(report)) { return ''; } const countErrors = report.errors.length; const countWarnings = report.warnings.length; const color = countErrors > 0 ? 'red' : 'yellow'; const summaries = []; const issues = []; if (countErrors > 0) { summaries.push(chalk`{red ${countErrors}} ${countErrors === 1 ? 'error' : 'errors'}`); report.errors.forEach(error => { issues.push(chalk` {bold.red -} ${error.message} {dim ${error.name}}`); }); } if (countWarnings > 0) { summaries.push(chalk`{yellow ${countWarnings}} ${countWarnings === 1 ? 'warning' : 'warnings'}`); report.warnings.forEach(warning => { issues.push(chalk` {bold.yellow -} ${warning.message} {dim ${warning.name}}`); }); } const summary = summaries.length > 0 ? chalk`{dim ${summaries.join(', ')}}` : ''; const header = chalk`{bold.${color} !} {bold Final commit violates conventions} ${summary}`; const footer = chalk`{dim aborted commit}`; return `${header}\n${issues.join('\n')}\n\n ${footer}`; }
javascript
function reportSummary(report = {}) { if (reportIsValid(report)) { return ''; } const countErrors = report.errors.length; const countWarnings = report.warnings.length; const color = countErrors > 0 ? 'red' : 'yellow'; const summaries = []; const issues = []; if (countErrors > 0) { summaries.push(chalk`{red ${countErrors}} ${countErrors === 1 ? 'error' : 'errors'}`); report.errors.forEach(error => { issues.push(chalk` {bold.red -} ${error.message} {dim ${error.name}}`); }); } if (countWarnings > 0) { summaries.push(chalk`{yellow ${countWarnings}} ${countWarnings === 1 ? 'warning' : 'warnings'}`); report.warnings.forEach(warning => { issues.push(chalk` {bold.yellow -} ${warning.message} {dim ${warning.name}}`); }); } const summary = summaries.length > 0 ? chalk`{dim ${summaries.join(', ')}}` : ''; const header = chalk`{bold.${color} !} {bold Final commit violates conventions} ${summary}`; const footer = chalk`{dim aborted commit}`; return `${header}\n${issues.join('\n')}\n\n ${footer}`; }
[ "function", "reportSummary", "(", "report", "=", "{", "}", ")", "{", "if", "(", "reportIsValid", "(", "report", ")", ")", "{", "return", "''", ";", "}", "const", "countErrors", "=", "report", ".", "errors", ".", "length", ";", "const", "countWarnings", "=", "report", ".", "warnings", ".", "length", ";", "const", "color", "=", "countErrors", ">", "0", "?", "'red'", ":", "'yellow'", ";", "const", "summaries", "=", "[", "]", ";", "const", "issues", "=", "[", "]", ";", "if", "(", "countErrors", ">", "0", ")", "{", "summaries", ".", "push", "(", "chalk", "`", "${", "countErrors", "}", "${", "countErrors", "===", "1", "?", "'error'", ":", "'errors'", "}", "`", ")", ";", "report", ".", "errors", ".", "forEach", "(", "error", "=>", "{", "issues", ".", "push", "(", "chalk", "`", "${", "error", ".", "message", "}", "${", "error", ".", "name", "}", "`", ")", ";", "}", ")", ";", "}", "if", "(", "countWarnings", ">", "0", ")", "{", "summaries", ".", "push", "(", "chalk", "`", "${", "countWarnings", "}", "${", "countWarnings", "===", "1", "?", "'warning'", ":", "'warnings'", "}", "`", ")", ";", "report", ".", "warnings", ".", "forEach", "(", "warning", "=>", "{", "issues", ".", "push", "(", "chalk", "`", "${", "warning", ".", "message", "}", "${", "warning", ".", "name", "}", "`", ")", ";", "}", ")", ";", "}", "const", "summary", "=", "summaries", ".", "length", ">", "0", "?", "chalk", "`", "${", "summaries", ".", "join", "(", "', '", ")", "}", "`", ":", "''", ";", "const", "header", "=", "chalk", "`", "${", "color", "}", "${", "summary", "}", "`", ";", "const", "footer", "=", "chalk", "`", "`", ";", "return", "`", "${", "header", "}", "\\n", "${", "issues", ".", "join", "(", "'\\n'", ")", "}", "\\n", "\\n", "\\n", "`", ";", "}" ]
Log the provided lint report to the console. It should contain all information for the user to understand a possible rejection. @param {Object} report @return {string}
[ "Log", "the", "provided", "lint", "report", "to", "the", "console", ".", "It", "should", "contain", "all", "information", "for", "the", "user", "to", "understand", "a", "possible", "rejection", "." ]
09ac205ec93d18d0721517ccc80af5e22031de4b
https://github.com/Peakfijn/Conventions/blob/09ac205ec93d18d0721517ccc80af5e22031de4b/packages/cz-changelog-peakfijn/commitlint-utils.js#L62-L93
train
ufukomer/node-impala
lib/node-impala.js
connect
function connect() { var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var callback = arguments[1]; this.host = props.host || '127.0.0.1'; this.port = props.port || 21000; this.resultType = props.resultType || null; this.timeout = props.timeout || 1000; this.transport = props.transport || _thrift2.default.TBufferedTransport; this.protocol = props.protocol || _thrift2.default.TBinaryProtocol; this.options = { transport: this.transport, protocol: this.protocol, timeout: this.timeout }; var deferred = _thrift.Q.defer(); var connection = _thrift2.default.createConnection(this.host, this.port, this.options); var client = _thrift2.default.createClient(_ImpalaService2.default, connection); connection.on('error', ImpalaClient.onErrorDeferred(deferred)); connection.on('connect', function () { deferred.resolve('Connection is established.'); }); this.client = client; this.connection = connection; deferred.promise.nodeify(callback); return deferred.promise; }
javascript
function connect() { var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var callback = arguments[1]; this.host = props.host || '127.0.0.1'; this.port = props.port || 21000; this.resultType = props.resultType || null; this.timeout = props.timeout || 1000; this.transport = props.transport || _thrift2.default.TBufferedTransport; this.protocol = props.protocol || _thrift2.default.TBinaryProtocol; this.options = { transport: this.transport, protocol: this.protocol, timeout: this.timeout }; var deferred = _thrift.Q.defer(); var connection = _thrift2.default.createConnection(this.host, this.port, this.options); var client = _thrift2.default.createClient(_ImpalaService2.default, connection); connection.on('error', ImpalaClient.onErrorDeferred(deferred)); connection.on('connect', function () { deferred.resolve('Connection is established.'); }); this.client = client; this.connection = connection; deferred.promise.nodeify(callback); return deferred.promise; }
[ "function", "connect", "(", ")", "{", "var", "props", "=", "arguments", ".", "length", ">", "0", "&&", "arguments", "[", "0", "]", "!==", "undefined", "?", "arguments", "[", "0", "]", ":", "{", "}", ";", "var", "callback", "=", "arguments", "[", "1", "]", ";", "this", ".", "host", "=", "props", ".", "host", "||", "'127.0.0.1'", ";", "this", ".", "port", "=", "props", ".", "port", "||", "21000", ";", "this", ".", "resultType", "=", "props", ".", "resultType", "||", "null", ";", "this", ".", "timeout", "=", "props", ".", "timeout", "||", "1000", ";", "this", ".", "transport", "=", "props", ".", "transport", "||", "_thrift2", ".", "default", ".", "TBufferedTransport", ";", "this", ".", "protocol", "=", "props", ".", "protocol", "||", "_thrift2", ".", "default", ".", "TBinaryProtocol", ";", "this", ".", "options", "=", "{", "transport", ":", "this", ".", "transport", ",", "protocol", ":", "this", ".", "protocol", ",", "timeout", ":", "this", ".", "timeout", "}", ";", "var", "deferred", "=", "_thrift", ".", "Q", ".", "defer", "(", ")", ";", "var", "connection", "=", "_thrift2", ".", "default", ".", "createConnection", "(", "this", ".", "host", ",", "this", ".", "port", ",", "this", ".", "options", ")", ";", "var", "client", "=", "_thrift2", ".", "default", ".", "createClient", "(", "_ImpalaService2", ".", "default", ",", "connection", ")", ";", "connection", ".", "on", "(", "'error'", ",", "ImpalaClient", ".", "onErrorDeferred", "(", "deferred", ")", ")", ";", "connection", ".", "on", "(", "'connect'", ",", "function", "(", ")", "{", "deferred", ".", "resolve", "(", "'Connection is established.'", ")", ";", "}", ")", ";", "this", ".", "client", "=", "client", ";", "this", ".", "connection", "=", "connection", ";", "deferred", ".", "promise", ".", "nodeify", "(", "callback", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Creates connection using given props. @param props {object} @param callback {function} @returns {function|promise}
[ "Creates", "connection", "using", "given", "props", "." ]
6d82c7bac101c18f4ee77051e832be2168ca73df
https://github.com/ufukomer/node-impala/blob/6d82c7bac101c18f4ee77051e832be2168ca73df/lib/node-impala.js#L53-L85
train
bpedro/node-fs
lib/fs.js
mkdir_p
function mkdir_p (path, mode, callback, position) { var parts = require('path').normalize(path).split(osSep); mode = mode || process.umask(); position = position || 0; if (position >= parts.length) { return callback(); } var directory = parts.slice(0, position + 1).join(osSep) || osSep; fs.stat(directory, function(err) { if (err === null) { mkdir_p(path, mode, callback, position + 1); } else { mkdirOrig(directory, mode, function (err) { if (err && err.code != 'EEXIST') { return callback(err); } else { mkdir_p(path, mode, callback, position + 1); } }); } }); }
javascript
function mkdir_p (path, mode, callback, position) { var parts = require('path').normalize(path).split(osSep); mode = mode || process.umask(); position = position || 0; if (position >= parts.length) { return callback(); } var directory = parts.slice(0, position + 1).join(osSep) || osSep; fs.stat(directory, function(err) { if (err === null) { mkdir_p(path, mode, callback, position + 1); } else { mkdirOrig(directory, mode, function (err) { if (err && err.code != 'EEXIST') { return callback(err); } else { mkdir_p(path, mode, callback, position + 1); } }); } }); }
[ "function", "mkdir_p", "(", "path", ",", "mode", ",", "callback", ",", "position", ")", "{", "var", "parts", "=", "require", "(", "'path'", ")", ".", "normalize", "(", "path", ")", ".", "split", "(", "osSep", ")", ";", "mode", "=", "mode", "||", "process", ".", "umask", "(", ")", ";", "position", "=", "position", "||", "0", ";", "if", "(", "position", ">=", "parts", ".", "length", ")", "{", "return", "callback", "(", ")", ";", "}", "var", "directory", "=", "parts", ".", "slice", "(", "0", ",", "position", "+", "1", ")", ".", "join", "(", "osSep", ")", "||", "osSep", ";", "fs", ".", "stat", "(", "directory", ",", "function", "(", "err", ")", "{", "if", "(", "err", "===", "null", ")", "{", "mkdir_p", "(", "path", ",", "mode", ",", "callback", ",", "position", "+", "1", ")", ";", "}", "else", "{", "mkdirOrig", "(", "directory", ",", "mode", ",", "function", "(", "err", ")", "{", "if", "(", "err", "&&", "err", ".", "code", "!=", "'EEXIST'", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "else", "{", "mkdir_p", "(", "path", ",", "mode", ",", "callback", ",", "position", "+", "1", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}" ]
Offers functionality similar to mkdir -p Asynchronous operation. No arguments other than a possible exception are given to the completion callback.
[ "Offers", "functionality", "similar", "to", "mkdir", "-", "p" ]
a03dad5b9389ece9fe47affe83f227baeab0ce2c
https://github.com/bpedro/node-fs/blob/a03dad5b9389ece9fe47affe83f227baeab0ce2c/lib/fs.js#L15-L39
train
npm/npm-remote-ls
lib/remote-ls.js
RemoteLS
function RemoteLS (opts) { var _this = this _.extend(this, { logger: console, development: true, // include dev dependencies. optional: true, // include optional dependencies. peer: false, // include peer dependencies. verbose: false, registry: require('registry-url')(), // URL of registry to ls. queue: async.queue(function (task, done) { _this._loadPackageJson(task, done) }, 8), tree: {}, flat: {} }, require('./config')(), opts) this.queue.pause() }
javascript
function RemoteLS (opts) { var _this = this _.extend(this, { logger: console, development: true, // include dev dependencies. optional: true, // include optional dependencies. peer: false, // include peer dependencies. verbose: false, registry: require('registry-url')(), // URL of registry to ls. queue: async.queue(function (task, done) { _this._loadPackageJson(task, done) }, 8), tree: {}, flat: {} }, require('./config')(), opts) this.queue.pause() }
[ "function", "RemoteLS", "(", "opts", ")", "{", "var", "_this", "=", "this", "_", ".", "extend", "(", "this", ",", "{", "logger", ":", "console", ",", "development", ":", "true", ",", "optional", ":", "true", ",", "peer", ":", "false", ",", "verbose", ":", "false", ",", "registry", ":", "require", "(", "'registry-url'", ")", "(", ")", ",", "queue", ":", "async", ".", "queue", "(", "function", "(", "task", ",", "done", ")", "{", "_this", ".", "_loadPackageJson", "(", "task", ",", "done", ")", "}", ",", "8", ")", ",", "tree", ":", "{", "}", ",", "flat", ":", "{", "}", "}", ",", "require", "(", "'./config'", ")", "(", ")", ",", "opts", ")", "this", ".", "queue", ".", "pause", "(", ")", "}" ]
perform a recursive walk of a remote npm package and determine its dependency tree.
[ "perform", "a", "recursive", "walk", "of", "a", "remote", "npm", "package", "and", "determine", "its", "dependency", "tree", "." ]
bc233b6e15364c3868362030d5b00aa43cc48696
https://github.com/npm/npm-remote-ls/blob/bc233b6e15364c3868362030d5b00aa43cc48696/lib/remote-ls.js#L11-L29
train
joyent/kang
examples/webconsole/resources/js/jquery/jquery.dataTables.js
_fnAddColumn
function _fnAddColumn( oSettings, nTh ) { var oDefaults = DataTable.defaults.columns; var iCol = oSettings.aoColumns.length; var oCol = $.extend( {}, DataTable.models.oColumn, oDefaults, { "sSortingClass": oSettings.oClasses.sSortable, "sSortingClassJUI": oSettings.oClasses.sSortJUI, "nTh": nTh ? nTh : document.createElement('th'), "sTitle": oDefaults.sTitle ? oDefaults.sTitle : nTh ? nTh.innerHTML : '', "aDataSort": oDefaults.aDataSort ? oDefaults.aDataSort : [iCol], "mDataProp": oDefaults.mDataProp ? oDefaults.oDefaults : iCol } ); oSettings.aoColumns.push( oCol ); /* Add a column specific filter */ if ( oSettings.aoPreSearchCols[ iCol ] === undefined || oSettings.aoPreSearchCols[ iCol ] === null ) { oSettings.aoPreSearchCols[ iCol ] = $.extend( {}, DataTable.models.oSearch ); } else { var oPre = oSettings.aoPreSearchCols[ iCol ]; /* Don't require that the user must specify bRegex, bSmart or bCaseInsensitive */ if ( oPre.bRegex === undefined ) { oPre.bRegex = true; } if ( oPre.bSmart === undefined ) { oPre.bSmart = true; } if ( oPre.bCaseInsensitive === undefined ) { oPre.bCaseInsensitive = true; } } /* Use the column options function to initialise classes etc */ _fnColumnOptions( oSettings, iCol, null ); }
javascript
function _fnAddColumn( oSettings, nTh ) { var oDefaults = DataTable.defaults.columns; var iCol = oSettings.aoColumns.length; var oCol = $.extend( {}, DataTable.models.oColumn, oDefaults, { "sSortingClass": oSettings.oClasses.sSortable, "sSortingClassJUI": oSettings.oClasses.sSortJUI, "nTh": nTh ? nTh : document.createElement('th'), "sTitle": oDefaults.sTitle ? oDefaults.sTitle : nTh ? nTh.innerHTML : '', "aDataSort": oDefaults.aDataSort ? oDefaults.aDataSort : [iCol], "mDataProp": oDefaults.mDataProp ? oDefaults.oDefaults : iCol } ); oSettings.aoColumns.push( oCol ); /* Add a column specific filter */ if ( oSettings.aoPreSearchCols[ iCol ] === undefined || oSettings.aoPreSearchCols[ iCol ] === null ) { oSettings.aoPreSearchCols[ iCol ] = $.extend( {}, DataTable.models.oSearch ); } else { var oPre = oSettings.aoPreSearchCols[ iCol ]; /* Don't require that the user must specify bRegex, bSmart or bCaseInsensitive */ if ( oPre.bRegex === undefined ) { oPre.bRegex = true; } if ( oPre.bSmart === undefined ) { oPre.bSmart = true; } if ( oPre.bCaseInsensitive === undefined ) { oPre.bCaseInsensitive = true; } } /* Use the column options function to initialise classes etc */ _fnColumnOptions( oSettings, iCol, null ); }
[ "function", "_fnAddColumn", "(", "oSettings", ",", "nTh", ")", "{", "var", "oDefaults", "=", "DataTable", ".", "defaults", ".", "columns", ";", "var", "iCol", "=", "oSettings", ".", "aoColumns", ".", "length", ";", "var", "oCol", "=", "$", ".", "extend", "(", "{", "}", ",", "DataTable", ".", "models", ".", "oColumn", ",", "oDefaults", ",", "{", "\"sSortingClass\"", ":", "oSettings", ".", "oClasses", ".", "sSortable", ",", "\"sSortingClassJUI\"", ":", "oSettings", ".", "oClasses", ".", "sSortJUI", ",", "\"nTh\"", ":", "nTh", "?", "nTh", ":", "document", ".", "createElement", "(", "'th'", ")", ",", "\"sTitle\"", ":", "oDefaults", ".", "sTitle", "?", "oDefaults", ".", "sTitle", ":", "nTh", "?", "nTh", ".", "innerHTML", ":", "''", ",", "\"aDataSort\"", ":", "oDefaults", ".", "aDataSort", "?", "oDefaults", ".", "aDataSort", ":", "[", "iCol", "]", ",", "\"mDataProp\"", ":", "oDefaults", ".", "mDataProp", "?", "oDefaults", ".", "oDefaults", ":", "iCol", "}", ")", ";", "oSettings", ".", "aoColumns", ".", "push", "(", "oCol", ")", ";", "if", "(", "oSettings", ".", "aoPreSearchCols", "[", "iCol", "]", "===", "undefined", "||", "oSettings", ".", "aoPreSearchCols", "[", "iCol", "]", "===", "null", ")", "{", "oSettings", ".", "aoPreSearchCols", "[", "iCol", "]", "=", "$", ".", "extend", "(", "{", "}", ",", "DataTable", ".", "models", ".", "oSearch", ")", ";", "}", "else", "{", "var", "oPre", "=", "oSettings", ".", "aoPreSearchCols", "[", "iCol", "]", ";", "if", "(", "oPre", ".", "bRegex", "===", "undefined", ")", "{", "oPre", ".", "bRegex", "=", "true", ";", "}", "if", "(", "oPre", ".", "bSmart", "===", "undefined", ")", "{", "oPre", ".", "bSmart", "=", "true", ";", "}", "if", "(", "oPre", ".", "bCaseInsensitive", "===", "undefined", ")", "{", "oPre", ".", "bCaseInsensitive", "=", "true", ";", "}", "}", "_fnColumnOptions", "(", "oSettings", ",", "iCol", ",", "null", ")", ";", "}" ]
Add a column to the list used for the table with default values @param {object} oSettings dataTables settings object @param {node} nTh The th element for this column @memberof DataTable#oApi
[ "Add", "a", "column", "to", "the", "list", "used", "for", "the", "table", "with", "default", "values" ]
9b138f2b4fb7873b9b0f271516daf36e20c9c037
https://github.com/joyent/kang/blob/9b138f2b4fb7873b9b0f271516daf36e20c9c037/examples/webconsole/resources/js/jquery/jquery.dataTables.js#L69-L111
train
joyent/kang
examples/webconsole/resources/js/jquery/jquery.dataTables.js
_fnVisbleColumns
function _fnVisbleColumns( oS ) { var iVis = 0; for ( var i=0 ; i<oS.aoColumns.length ; i++ ) { if ( oS.aoColumns[i].bVisible === true ) { iVis++; } } return iVis; }
javascript
function _fnVisbleColumns( oS ) { var iVis = 0; for ( var i=0 ; i<oS.aoColumns.length ; i++ ) { if ( oS.aoColumns[i].bVisible === true ) { iVis++; } } return iVis; }
[ "function", "_fnVisbleColumns", "(", "oS", ")", "{", "var", "iVis", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "oS", ".", "aoColumns", ".", "length", ";", "i", "++", ")", "{", "if", "(", "oS", ".", "aoColumns", "[", "i", "]", ".", "bVisible", "===", "true", ")", "{", "iVis", "++", ";", "}", "}", "return", "iVis", ";", "}" ]
Get the number of visible columns @returns {int} i the number of visible columns @param {object} oS dataTables settings object @memberof DataTable#oApi
[ "Get", "the", "number", "of", "visible", "columns" ]
9b138f2b4fb7873b9b0f271516daf36e20c9c037
https://github.com/joyent/kang/blob/9b138f2b4fb7873b9b0f271516daf36e20c9c037/examples/webconsole/resources/js/jquery/jquery.dataTables.js#L268-L279
train
joyent/kang
examples/webconsole/resources/js/jquery/jquery.dataTables.js
_fnDetectType
function _fnDetectType( sData ) { var aTypes = DataTable.ext.aTypes; var iLen = aTypes.length; for ( var i=0 ; i<iLen ; i++ ) { var sType = aTypes[i]( sData ); if ( sType !== null ) { return sType; } } return 'string'; }
javascript
function _fnDetectType( sData ) { var aTypes = DataTable.ext.aTypes; var iLen = aTypes.length; for ( var i=0 ; i<iLen ; i++ ) { var sType = aTypes[i]( sData ); if ( sType !== null ) { return sType; } } return 'string'; }
[ "function", "_fnDetectType", "(", "sData", ")", "{", "var", "aTypes", "=", "DataTable", ".", "ext", ".", "aTypes", ";", "var", "iLen", "=", "aTypes", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "iLen", ";", "i", "++", ")", "{", "var", "sType", "=", "aTypes", "[", "i", "]", "(", "sData", ")", ";", "if", "(", "sType", "!==", "null", ")", "{", "return", "sType", ";", "}", "}", "return", "'string'", ";", "}" ]
Get the sort type based on an input string @param {string} sData data we wish to know the type of @returns {string} type (defaults to 'string' if no type can be detected) @memberof DataTable#oApi
[ "Get", "the", "sort", "type", "based", "on", "an", "input", "string" ]
9b138f2b4fb7873b9b0f271516daf36e20c9c037
https://github.com/joyent/kang/blob/9b138f2b4fb7873b9b0f271516daf36e20c9c037/examples/webconsole/resources/js/jquery/jquery.dataTables.js#L288-L303
train
joyent/kang
examples/webconsole/resources/js/jquery/jquery.dataTables.js
_fnReOrderIndex
function _fnReOrderIndex ( oSettings, sColumns ) { var aColumns = sColumns.split(','); var aiReturn = []; for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { for ( var j=0 ; j<iLen ; j++ ) { if ( oSettings.aoColumns[i].sName == aColumns[j] ) { aiReturn.push( j ); break; } } } return aiReturn; }
javascript
function _fnReOrderIndex ( oSettings, sColumns ) { var aColumns = sColumns.split(','); var aiReturn = []; for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { for ( var j=0 ; j<iLen ; j++ ) { if ( oSettings.aoColumns[i].sName == aColumns[j] ) { aiReturn.push( j ); break; } } } return aiReturn; }
[ "function", "_fnReOrderIndex", "(", "oSettings", ",", "sColumns", ")", "{", "var", "aColumns", "=", "sColumns", ".", "split", "(", "','", ")", ";", "var", "aiReturn", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "iLen", "=", "oSettings", ".", "aoColumns", ".", "length", ";", "i", "<", "iLen", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "iLen", ";", "j", "++", ")", "{", "if", "(", "oSettings", ".", "aoColumns", "[", "i", "]", ".", "sName", "==", "aColumns", "[", "j", "]", ")", "{", "aiReturn", ".", "push", "(", "j", ")", ";", "break", ";", "}", "}", "}", "return", "aiReturn", ";", "}" ]
Figure out how to reorder a display list @param {object} oSettings dataTables settings object @returns array {int} aiReturn index list for reordering @memberof DataTable#oApi
[ "Figure", "out", "how", "to", "reorder", "a", "display", "list" ]
9b138f2b4fb7873b9b0f271516daf36e20c9c037
https://github.com/joyent/kang/blob/9b138f2b4fb7873b9b0f271516daf36e20c9c037/examples/webconsole/resources/js/jquery/jquery.dataTables.js#L312-L330
train
joyent/kang
examples/webconsole/resources/js/jquery/jquery.dataTables.js
_fnColumnOrdering
function _fnColumnOrdering ( oSettings ) { var sNames = ''; for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { sNames += oSettings.aoColumns[i].sName+','; } if ( sNames.length == iLen ) { return ""; } return sNames.slice(0, -1); }
javascript
function _fnColumnOrdering ( oSettings ) { var sNames = ''; for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { sNames += oSettings.aoColumns[i].sName+','; } if ( sNames.length == iLen ) { return ""; } return sNames.slice(0, -1); }
[ "function", "_fnColumnOrdering", "(", "oSettings", ")", "{", "var", "sNames", "=", "''", ";", "for", "(", "var", "i", "=", "0", ",", "iLen", "=", "oSettings", ".", "aoColumns", ".", "length", ";", "i", "<", "iLen", ";", "i", "++", ")", "{", "sNames", "+=", "oSettings", ".", "aoColumns", "[", "i", "]", ".", "sName", "+", "','", ";", "}", "if", "(", "sNames", ".", "length", "==", "iLen", ")", "{", "return", "\"\"", ";", "}", "return", "sNames", ".", "slice", "(", "0", ",", "-", "1", ")", ";", "}" ]
Get the column ordering that DataTables expects @param {object} oSettings dataTables settings object @returns {string} comma separated list of names @memberof DataTable#oApi
[ "Get", "the", "column", "ordering", "that", "DataTables", "expects" ]
9b138f2b4fb7873b9b0f271516daf36e20c9c037
https://github.com/joyent/kang/blob/9b138f2b4fb7873b9b0f271516daf36e20c9c037/examples/webconsole/resources/js/jquery/jquery.dataTables.js#L339-L351
train
joyent/kang
examples/webconsole/resources/js/jquery/jquery.dataTables.js
_fnGetRowData
function _fnGetRowData( oSettings, iRow, sSpecific ) { var out = []; for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { out.push( _fnGetCellData( oSettings, iRow, i, sSpecific ) ); } return out; }
javascript
function _fnGetRowData( oSettings, iRow, sSpecific ) { var out = []; for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { out.push( _fnGetCellData( oSettings, iRow, i, sSpecific ) ); } return out; }
[ "function", "_fnGetRowData", "(", "oSettings", ",", "iRow", ",", "sSpecific", ")", "{", "var", "out", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "iLen", "=", "oSettings", ".", "aoColumns", ".", "length", ";", "i", "<", "iLen", ";", "i", "++", ")", "{", "out", ".", "push", "(", "_fnGetCellData", "(", "oSettings", ",", "iRow", ",", "i", ",", "sSpecific", ")", ")", ";", "}", "return", "out", ";", "}" ]
Get an array of data for a given row from the internal data cache @param {object} oSettings dataTables settings object @param {int} iRow aoData row id @param {string} sSpecific data get type ('type' 'filter' 'sort') @returns {array} Data array @memberof DataTable#oApi
[ "Get", "an", "array", "of", "data", "for", "a", "given", "row", "from", "the", "internal", "data", "cache" ]
9b138f2b4fb7873b9b0f271516daf36e20c9c037
https://github.com/joyent/kang/blob/9b138f2b4fb7873b9b0f271516daf36e20c9c037/examples/webconsole/resources/js/jquery/jquery.dataTables.js#L714-L722
train
joyent/kang
examples/webconsole/resources/js/jquery/jquery.dataTables.js
_fnSetCellData
function _fnSetCellData( oSettings, iRow, iCol, val ) { var oCol = oSettings.aoColumns[iCol]; var oData = oSettings.aoData[iRow]._aData; oCol.fnSetData( oData, val ); }
javascript
function _fnSetCellData( oSettings, iRow, iCol, val ) { var oCol = oSettings.aoColumns[iCol]; var oData = oSettings.aoData[iRow]._aData; oCol.fnSetData( oData, val ); }
[ "function", "_fnSetCellData", "(", "oSettings", ",", "iRow", ",", "iCol", ",", "val", ")", "{", "var", "oCol", "=", "oSettings", ".", "aoColumns", "[", "iCol", "]", ";", "var", "oData", "=", "oSettings", ".", "aoData", "[", "iRow", "]", ".", "_aData", ";", "oCol", ".", "fnSetData", "(", "oData", ",", "val", ")", ";", "}" ]
Set the value for a specific cell, into the internal data cache @param {object} oSettings dataTables settings object @param {int} iRow aoData row id @param {int} iCol Column index @param {*} val Value to set @memberof DataTable#oApi
[ "Set", "the", "value", "for", "a", "specific", "cell", "into", "the", "internal", "data", "cache" ]
9b138f2b4fb7873b9b0f271516daf36e20c9c037
https://github.com/joyent/kang/blob/9b138f2b4fb7873b9b0f271516daf36e20c9c037/examples/webconsole/resources/js/jquery/jquery.dataTables.js#L779-L785
train
joyent/kang
examples/webconsole/resources/js/jquery/jquery.dataTables.js
_fnGetDataMaster
function _fnGetDataMaster ( oSettings ) { var aData = []; var iLen = oSettings.aoData.length; for ( var i=0 ; i<iLen; i++ ) { aData.push( oSettings.aoData[i]._aData ); } return aData; }
javascript
function _fnGetDataMaster ( oSettings ) { var aData = []; var iLen = oSettings.aoData.length; for ( var i=0 ; i<iLen; i++ ) { aData.push( oSettings.aoData[i]._aData ); } return aData; }
[ "function", "_fnGetDataMaster", "(", "oSettings", ")", "{", "var", "aData", "=", "[", "]", ";", "var", "iLen", "=", "oSettings", ".", "aoData", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "iLen", ";", "i", "++", ")", "{", "aData", ".", "push", "(", "oSettings", ".", "aoData", "[", "i", "]", ".", "_aData", ")", ";", "}", "return", "aData", ";", "}" ]
Return an array with the full table data @param {object} oSettings dataTables settings object @returns array {array} aData Master data array @memberof DataTable#oApi
[ "Return", "an", "array", "with", "the", "full", "table", "data" ]
9b138f2b4fb7873b9b0f271516daf36e20c9c037
https://github.com/joyent/kang/blob/9b138f2b4fb7873b9b0f271516daf36e20c9c037/examples/webconsole/resources/js/jquery/jquery.dataTables.js#L893-L902
train
joyent/kang
examples/webconsole/resources/js/jquery/jquery.dataTables.js
_fnGetUniqueThs
function _fnGetUniqueThs ( oSettings, nHeader, aLayout ) { var aReturn = []; if ( !aLayout ) { aLayout = oSettings.aoHeader; if ( nHeader ) { aLayout = []; _fnDetectHeader( aLayout, nHeader ); } } for ( var i=0, iLen=aLayout.length ; i<iLen ; i++ ) { for ( var j=0, jLen=aLayout[i].length ; j<jLen ; j++ ) { if ( aLayout[i][j].unique && (!aReturn[j] || !oSettings.bSortCellsTop) ) { aReturn[j] = aLayout[i][j].cell; } } } return aReturn; }
javascript
function _fnGetUniqueThs ( oSettings, nHeader, aLayout ) { var aReturn = []; if ( !aLayout ) { aLayout = oSettings.aoHeader; if ( nHeader ) { aLayout = []; _fnDetectHeader( aLayout, nHeader ); } } for ( var i=0, iLen=aLayout.length ; i<iLen ; i++ ) { for ( var j=0, jLen=aLayout[i].length ; j<jLen ; j++ ) { if ( aLayout[i][j].unique && (!aReturn[j] || !oSettings.bSortCellsTop) ) { aReturn[j] = aLayout[i][j].cell; } } } return aReturn; }
[ "function", "_fnGetUniqueThs", "(", "oSettings", ",", "nHeader", ",", "aLayout", ")", "{", "var", "aReturn", "=", "[", "]", ";", "if", "(", "!", "aLayout", ")", "{", "aLayout", "=", "oSettings", ".", "aoHeader", ";", "if", "(", "nHeader", ")", "{", "aLayout", "=", "[", "]", ";", "_fnDetectHeader", "(", "aLayout", ",", "nHeader", ")", ";", "}", "}", "for", "(", "var", "i", "=", "0", ",", "iLen", "=", "aLayout", ".", "length", ";", "i", "<", "iLen", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "0", ",", "jLen", "=", "aLayout", "[", "i", "]", ".", "length", ";", "j", "<", "jLen", ";", "j", "++", ")", "{", "if", "(", "aLayout", "[", "i", "]", "[", "j", "]", ".", "unique", "&&", "(", "!", "aReturn", "[", "j", "]", "||", "!", "oSettings", ".", "bSortCellsTop", ")", ")", "{", "aReturn", "[", "j", "]", "=", "aLayout", "[", "i", "]", "[", "j", "]", ".", "cell", ";", "}", "}", "}", "return", "aReturn", ";", "}" ]
Get an array of unique th elements, one for each column @param {object} oSettings dataTables settings object @param {node} nHeader automatically detect the layout from this node - optional @param {array} aLayout thead/tfoot layout from _fnDetectHeader - optional @returns array {node} aReturn list of unique ths @memberof DataTable#oApi
[ "Get", "an", "array", "of", "unique", "th", "elements", "one", "for", "each", "column" ]
9b138f2b4fb7873b9b0f271516daf36e20c9c037
https://github.com/joyent/kang/blob/9b138f2b4fb7873b9b0f271516daf36e20c9c037/examples/webconsole/resources/js/jquery/jquery.dataTables.js#L1731-L1757
train
joyent/kang
examples/webconsole/resources/js/jquery/jquery.dataTables.js
_fnBuildSearchArray
function _fnBuildSearchArray ( oSettings, iMaster ) { if ( !oSettings.oFeatures.bServerSide ) { /* Clear out the old data */ oSettings.asDataSearch.splice( 0, oSettings.asDataSearch.length ); var aArray = (iMaster && iMaster===1) ? oSettings.aiDisplayMaster : oSettings.aiDisplay; for ( var i=0, iLen=aArray.length ; i<iLen ; i++ ) { oSettings.asDataSearch[i] = _fnBuildSearchRow( oSettings, _fnGetRowData( oSettings, aArray[i], 'filter' ) ); } } }
javascript
function _fnBuildSearchArray ( oSettings, iMaster ) { if ( !oSettings.oFeatures.bServerSide ) { /* Clear out the old data */ oSettings.asDataSearch.splice( 0, oSettings.asDataSearch.length ); var aArray = (iMaster && iMaster===1) ? oSettings.aiDisplayMaster : oSettings.aiDisplay; for ( var i=0, iLen=aArray.length ; i<iLen ; i++ ) { oSettings.asDataSearch[i] = _fnBuildSearchRow( oSettings, _fnGetRowData( oSettings, aArray[i], 'filter' ) ); } } }
[ "function", "_fnBuildSearchArray", "(", "oSettings", ",", "iMaster", ")", "{", "if", "(", "!", "oSettings", ".", "oFeatures", ".", "bServerSide", ")", "{", "oSettings", ".", "asDataSearch", ".", "splice", "(", "0", ",", "oSettings", ".", "asDataSearch", ".", "length", ")", ";", "var", "aArray", "=", "(", "iMaster", "&&", "iMaster", "===", "1", ")", "?", "oSettings", ".", "aiDisplayMaster", ":", "oSettings", ".", "aiDisplay", ";", "for", "(", "var", "i", "=", "0", ",", "iLen", "=", "aArray", ".", "length", ";", "i", "<", "iLen", ";", "i", "++", ")", "{", "oSettings", ".", "asDataSearch", "[", "i", "]", "=", "_fnBuildSearchRow", "(", "oSettings", ",", "_fnGetRowData", "(", "oSettings", ",", "aArray", "[", "i", "]", ",", "'filter'", ")", ")", ";", "}", "}", "}" ]
Create an array which can be quickly search through @param {object} oSettings dataTables settings object @param {int} iMaster use the master data array - optional @memberof DataTable#oApi
[ "Create", "an", "array", "which", "can", "be", "quickly", "search", "through" ]
9b138f2b4fb7873b9b0f271516daf36e20c9c037
https://github.com/joyent/kang/blob/9b138f2b4fb7873b9b0f271516daf36e20c9c037/examples/webconsole/resources/js/jquery/jquery.dataTables.js#L2221-L2237
train
joyent/kang
examples/webconsole/resources/js/jquery/jquery.dataTables.js
_fnBuildSearchRow
function _fnBuildSearchRow( oSettings, aData ) { var sSearch = ''; if ( oSettings.__nTmpFilter === undefined ) { oSettings.__nTmpFilter = document.createElement('div'); } var nTmp = oSettings.__nTmpFilter; for ( var j=0, jLen=oSettings.aoColumns.length ; j<jLen ; j++ ) { if ( oSettings.aoColumns[j].bSearchable ) { var sData = aData[j]; sSearch += _fnDataToSearch( sData, oSettings.aoColumns[j].sType )+' '; } } /* If it looks like there is an HTML entity in the string, attempt to decode it */ if ( sSearch.indexOf('&') !== -1 ) { nTmp.innerHTML = sSearch; sSearch = nTmp.textContent ? nTmp.textContent : nTmp.innerText; /* IE and Opera appear to put an newline where there is a <br> tag - remove it */ sSearch = sSearch.replace(/\n/g," ").replace(/\r/g,""); } return sSearch; }
javascript
function _fnBuildSearchRow( oSettings, aData ) { var sSearch = ''; if ( oSettings.__nTmpFilter === undefined ) { oSettings.__nTmpFilter = document.createElement('div'); } var nTmp = oSettings.__nTmpFilter; for ( var j=0, jLen=oSettings.aoColumns.length ; j<jLen ; j++ ) { if ( oSettings.aoColumns[j].bSearchable ) { var sData = aData[j]; sSearch += _fnDataToSearch( sData, oSettings.aoColumns[j].sType )+' '; } } /* If it looks like there is an HTML entity in the string, attempt to decode it */ if ( sSearch.indexOf('&') !== -1 ) { nTmp.innerHTML = sSearch; sSearch = nTmp.textContent ? nTmp.textContent : nTmp.innerText; /* IE and Opera appear to put an newline where there is a <br> tag - remove it */ sSearch = sSearch.replace(/\n/g," ").replace(/\r/g,""); } return sSearch; }
[ "function", "_fnBuildSearchRow", "(", "oSettings", ",", "aData", ")", "{", "var", "sSearch", "=", "''", ";", "if", "(", "oSettings", ".", "__nTmpFilter", "===", "undefined", ")", "{", "oSettings", ".", "__nTmpFilter", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "}", "var", "nTmp", "=", "oSettings", ".", "__nTmpFilter", ";", "for", "(", "var", "j", "=", "0", ",", "jLen", "=", "oSettings", ".", "aoColumns", ".", "length", ";", "j", "<", "jLen", ";", "j", "++", ")", "{", "if", "(", "oSettings", ".", "aoColumns", "[", "j", "]", ".", "bSearchable", ")", "{", "var", "sData", "=", "aData", "[", "j", "]", ";", "sSearch", "+=", "_fnDataToSearch", "(", "sData", ",", "oSettings", ".", "aoColumns", "[", "j", "]", ".", "sType", ")", "+", "' '", ";", "}", "}", "if", "(", "sSearch", ".", "indexOf", "(", "'&'", ")", "!==", "-", "1", ")", "{", "nTmp", ".", "innerHTML", "=", "sSearch", ";", "sSearch", "=", "nTmp", ".", "textContent", "?", "nTmp", ".", "textContent", ":", "nTmp", ".", "innerText", ";", "sSearch", "=", "sSearch", ".", "replace", "(", "/", "\\n", "/", "g", ",", "\" \"", ")", ".", "replace", "(", "/", "\\r", "/", "g", ",", "\"\"", ")", ";", "}", "return", "sSearch", ";", "}" ]
Create a searchable string from a single data row @param {object} oSettings dataTables settings object @param {array} aData Row data array to use for the data to search @memberof DataTable#oApi
[ "Create", "a", "searchable", "string", "from", "a", "single", "data", "row" ]
9b138f2b4fb7873b9b0f271516daf36e20c9c037
https://github.com/joyent/kang/blob/9b138f2b4fb7873b9b0f271516daf36e20c9c037/examples/webconsole/resources/js/jquery/jquery.dataTables.js#L2246-L2275
train
joyent/kang
examples/webconsole/resources/js/jquery/jquery.dataTables.js
_fnDataToSearch
function _fnDataToSearch ( sData, sType ) { if ( typeof DataTable.ext.ofnSearch[sType] === "function" ) { return DataTable.ext.ofnSearch[sType]( sData ); } else if ( sData === null ) { return ''; } else if ( sType == "html" ) { return sData.replace(/[\r\n]/g," ").replace( /<.*?>/g, "" ); } else if ( typeof sData === "string" ) { return sData.replace(/[\r\n]/g," "); } return sData; }
javascript
function _fnDataToSearch ( sData, sType ) { if ( typeof DataTable.ext.ofnSearch[sType] === "function" ) { return DataTable.ext.ofnSearch[sType]( sData ); } else if ( sData === null ) { return ''; } else if ( sType == "html" ) { return sData.replace(/[\r\n]/g," ").replace( /<.*?>/g, "" ); } else if ( typeof sData === "string" ) { return sData.replace(/[\r\n]/g," "); } return sData; }
[ "function", "_fnDataToSearch", "(", "sData", ",", "sType", ")", "{", "if", "(", "typeof", "DataTable", ".", "ext", ".", "ofnSearch", "[", "sType", "]", "===", "\"function\"", ")", "{", "return", "DataTable", ".", "ext", ".", "ofnSearch", "[", "sType", "]", "(", "sData", ")", ";", "}", "else", "if", "(", "sData", "===", "null", ")", "{", "return", "''", ";", "}", "else", "if", "(", "sType", "==", "\"html\"", ")", "{", "return", "sData", ".", "replace", "(", "/", "[\\r\\n]", "/", "g", ",", "\" \"", ")", ".", "replace", "(", "/", "<.*?>", "/", "g", ",", "\"\"", ")", ";", "}", "else", "if", "(", "typeof", "sData", "===", "\"string\"", ")", "{", "return", "sData", ".", "replace", "(", "/", "[\\r\\n]", "/", "g", ",", "\" \"", ")", ";", "}", "return", "sData", ";", "}" ]
Convert raw data into something that the user can search on @param {string} sData data to be modified @param {string} sType data type @returns {string} search string @memberof DataTable#oApi
[ "Convert", "raw", "data", "into", "something", "that", "the", "user", "can", "search", "on" ]
9b138f2b4fb7873b9b0f271516daf36e20c9c037
https://github.com/joyent/kang/blob/9b138f2b4fb7873b9b0f271516daf36e20c9c037/examples/webconsole/resources/js/jquery/jquery.dataTables.js#L2314-L2333
train
joyent/kang
examples/webconsole/resources/js/jquery/jquery.dataTables.js
_fnEscapeRegex
function _fnEscapeRegex ( sVal ) { var acEscape = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\', '$', '^' ]; var reReplace = new RegExp( '(\\' + acEscape.join('|\\') + ')', 'g' ); return sVal.replace(reReplace, '\\$1'); }
javascript
function _fnEscapeRegex ( sVal ) { var acEscape = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\', '$', '^' ]; var reReplace = new RegExp( '(\\' + acEscape.join('|\\') + ')', 'g' ); return sVal.replace(reReplace, '\\$1'); }
[ "function", "_fnEscapeRegex", "(", "sVal", ")", "{", "var", "acEscape", "=", "[", "'/'", ",", "'.'", ",", "'*'", ",", "'+'", ",", "'?'", ",", "'|'", ",", "'('", ",", "')'", ",", "'['", ",", "']'", ",", "'{'", ",", "'}'", ",", "'\\\\'", ",", "\\\\", ",", "'$'", "]", ";", "'^'", "var", "reReplace", "=", "new", "RegExp", "(", "'(\\\\'", "+", "\\\\", "+", "acEscape", ".", "join", "(", "'|\\\\'", ")", ",", "\\\\", ")", ";", "}" ]
scape a string stuch that it can be used in a regular expression @param {string} sVal string to escape @returns {string} escaped string @memberof DataTable#oApi
[ "scape", "a", "string", "stuch", "that", "it", "can", "be", "used", "in", "a", "regular", "expression" ]
9b138f2b4fb7873b9b0f271516daf36e20c9c037
https://github.com/joyent/kang/blob/9b138f2b4fb7873b9b0f271516daf36e20c9c037/examples/webconsole/resources/js/jquery/jquery.dataTables.js#L2342-L2347
train
joyent/kang
examples/webconsole/resources/js/jquery/jquery.dataTables.js
_fnCalculateEnd
function _fnCalculateEnd( oSettings ) { if ( oSettings.oFeatures.bPaginate === false ) { oSettings._iDisplayEnd = oSettings.aiDisplay.length; } else { /* Set the end point of the display - based on how many elements there are * still to display */ if ( oSettings._iDisplayStart + oSettings._iDisplayLength > oSettings.aiDisplay.length || oSettings._iDisplayLength == -1 ) { oSettings._iDisplayEnd = oSettings.aiDisplay.length; } else { oSettings._iDisplayEnd = oSettings._iDisplayStart + oSettings._iDisplayLength; } } }
javascript
function _fnCalculateEnd( oSettings ) { if ( oSettings.oFeatures.bPaginate === false ) { oSettings._iDisplayEnd = oSettings.aiDisplay.length; } else { /* Set the end point of the display - based on how many elements there are * still to display */ if ( oSettings._iDisplayStart + oSettings._iDisplayLength > oSettings.aiDisplay.length || oSettings._iDisplayLength == -1 ) { oSettings._iDisplayEnd = oSettings.aiDisplay.length; } else { oSettings._iDisplayEnd = oSettings._iDisplayStart + oSettings._iDisplayLength; } } }
[ "function", "_fnCalculateEnd", "(", "oSettings", ")", "{", "if", "(", "oSettings", ".", "oFeatures", ".", "bPaginate", "===", "false", ")", "{", "oSettings", ".", "_iDisplayEnd", "=", "oSettings", ".", "aiDisplay", ".", "length", ";", "}", "else", "{", "if", "(", "oSettings", ".", "_iDisplayStart", "+", "oSettings", ".", "_iDisplayLength", ">", "oSettings", ".", "aiDisplay", ".", "length", "||", "oSettings", ".", "_iDisplayLength", "==", "-", "1", ")", "{", "oSettings", ".", "_iDisplayEnd", "=", "oSettings", ".", "aiDisplay", ".", "length", ";", "}", "else", "{", "oSettings", ".", "_iDisplayEnd", "=", "oSettings", ".", "_iDisplayStart", "+", "oSettings", ".", "_iDisplayLength", ";", "}", "}", "}" ]
Rcalculate the end point based on the start point @param {object} oSettings dataTables settings object @memberof DataTable#oApi
[ "Rcalculate", "the", "end", "point", "based", "on", "the", "start", "point" ]
9b138f2b4fb7873b9b0f271516daf36e20c9c037
https://github.com/joyent/kang/blob/9b138f2b4fb7873b9b0f271516daf36e20c9c037/examples/webconsole/resources/js/jquery/jquery.dataTables.js#L2718-L2739
train
joyent/kang
examples/webconsole/resources/js/jquery/jquery.dataTables.js
_fnScrollingWidthAdjust
function _fnScrollingWidthAdjust ( oSettings, n ) { if ( oSettings.oScroll.sX === "" && oSettings.oScroll.sY !== "" ) { /* When y-scrolling only, we want to remove the width of the scroll bar so the table * + scroll bar will fit into the area avaialble. */ var iOrigWidth = $(n).width(); n.style.width = _fnStringToCss( $(n).outerWidth()-oSettings.oScroll.iBarWidth ); } else if ( oSettings.oScroll.sX !== "" ) { /* When x-scrolling both ways, fix the table at it's current size, without adjusting */ n.style.width = _fnStringToCss( $(n).outerWidth() ); } }
javascript
function _fnScrollingWidthAdjust ( oSettings, n ) { if ( oSettings.oScroll.sX === "" && oSettings.oScroll.sY !== "" ) { /* When y-scrolling only, we want to remove the width of the scroll bar so the table * + scroll bar will fit into the area avaialble. */ var iOrigWidth = $(n).width(); n.style.width = _fnStringToCss( $(n).outerWidth()-oSettings.oScroll.iBarWidth ); } else if ( oSettings.oScroll.sX !== "" ) { /* When x-scrolling both ways, fix the table at it's current size, without adjusting */ n.style.width = _fnStringToCss( $(n).outerWidth() ); } }
[ "function", "_fnScrollingWidthAdjust", "(", "oSettings", ",", "n", ")", "{", "if", "(", "oSettings", ".", "oScroll", ".", "sX", "===", "\"\"", "&&", "oSettings", ".", "oScroll", ".", "sY", "!==", "\"\"", ")", "{", "var", "iOrigWidth", "=", "$", "(", "n", ")", ".", "width", "(", ")", ";", "n", ".", "style", ".", "width", "=", "_fnStringToCss", "(", "$", "(", "n", ")", ".", "outerWidth", "(", ")", "-", "oSettings", ".", "oScroll", ".", "iBarWidth", ")", ";", "}", "else", "if", "(", "oSettings", ".", "oScroll", ".", "sX", "!==", "\"\"", ")", "{", "n", ".", "style", ".", "width", "=", "_fnStringToCss", "(", "$", "(", "n", ")", ".", "outerWidth", "(", ")", ")", ";", "}", "}" ]
Adjust a table's width to take account of scrolling @param {object} oSettings dataTables settings object @param {node} n table node @memberof DataTable#oApi
[ "Adjust", "a", "table", "s", "width", "to", "take", "account", "of", "scrolling" ]
9b138f2b4fb7873b9b0f271516daf36e20c9c037
https://github.com/joyent/kang/blob/9b138f2b4fb7873b9b0f271516daf36e20c9c037/examples/webconsole/resources/js/jquery/jquery.dataTables.js#L3663-L3678
train
joyent/kang
examples/webconsole/resources/js/jquery/jquery.dataTables.js
_fnSaveState
function _fnSaveState ( oSettings ) { if ( !oSettings.oFeatures.bStateSave || oSettings.bDestroying ) { return; } /* Store the interesting variables */ var i, iLen, bInfinite=oSettings.oScroll.bInfinite; var oState = { "iCreate": new Date().getTime(), "iStart": (bInfinite ? 0 : oSettings._iDisplayStart), "iEnd": (bInfinite ? oSettings._iDisplayLength : oSettings._iDisplayEnd), "iLength": oSettings._iDisplayLength, "aaSorting": $.extend( true, [], oSettings.aaSorting ), "oSearch": $.extend( true, {}, oSettings.oPreviousSearch ), "aoSearchCols": $.extend( true, [], oSettings.aoPreSearchCols ), "abVisCols": [] }; for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { oState.abVisCols.push( oSettings.aoColumns[i].bVisible ); } _fnCallbackFire( oSettings, "aoStateSaveParams", 'stateSaveParams', [oSettings, oState] ); oSettings.fnStateSave.call( oSettings.oInstance, oSettings, oState ); }
javascript
function _fnSaveState ( oSettings ) { if ( !oSettings.oFeatures.bStateSave || oSettings.bDestroying ) { return; } /* Store the interesting variables */ var i, iLen, bInfinite=oSettings.oScroll.bInfinite; var oState = { "iCreate": new Date().getTime(), "iStart": (bInfinite ? 0 : oSettings._iDisplayStart), "iEnd": (bInfinite ? oSettings._iDisplayLength : oSettings._iDisplayEnd), "iLength": oSettings._iDisplayLength, "aaSorting": $.extend( true, [], oSettings.aaSorting ), "oSearch": $.extend( true, {}, oSettings.oPreviousSearch ), "aoSearchCols": $.extend( true, [], oSettings.aoPreSearchCols ), "abVisCols": [] }; for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { oState.abVisCols.push( oSettings.aoColumns[i].bVisible ); } _fnCallbackFire( oSettings, "aoStateSaveParams", 'stateSaveParams', [oSettings, oState] ); oSettings.fnStateSave.call( oSettings.oInstance, oSettings, oState ); }
[ "function", "_fnSaveState", "(", "oSettings", ")", "{", "if", "(", "!", "oSettings", ".", "oFeatures", ".", "bStateSave", "||", "oSettings", ".", "bDestroying", ")", "{", "return", ";", "}", "var", "i", ",", "iLen", ",", "bInfinite", "=", "oSettings", ".", "oScroll", ".", "bInfinite", ";", "var", "oState", "=", "{", "\"iCreate\"", ":", "new", "Date", "(", ")", ".", "getTime", "(", ")", ",", "\"iStart\"", ":", "(", "bInfinite", "?", "0", ":", "oSettings", ".", "_iDisplayStart", ")", ",", "\"iEnd\"", ":", "(", "bInfinite", "?", "oSettings", ".", "_iDisplayLength", ":", "oSettings", ".", "_iDisplayEnd", ")", ",", "\"iLength\"", ":", "oSettings", ".", "_iDisplayLength", ",", "\"aaSorting\"", ":", "$", ".", "extend", "(", "true", ",", "[", "]", ",", "oSettings", ".", "aaSorting", ")", ",", "\"oSearch\"", ":", "$", ".", "extend", "(", "true", ",", "{", "}", ",", "oSettings", ".", "oPreviousSearch", ")", ",", "\"aoSearchCols\"", ":", "$", ".", "extend", "(", "true", ",", "[", "]", ",", "oSettings", ".", "aoPreSearchCols", ")", ",", "\"abVisCols\"", ":", "[", "]", "}", ";", "for", "(", "i", "=", "0", ",", "iLen", "=", "oSettings", ".", "aoColumns", ".", "length", ";", "i", "<", "iLen", ";", "i", "++", ")", "{", "oState", ".", "abVisCols", ".", "push", "(", "oSettings", ".", "aoColumns", "[", "i", "]", ".", "bVisible", ")", ";", "}", "_fnCallbackFire", "(", "oSettings", ",", "\"aoStateSaveParams\"", ",", "'stateSaveParams'", ",", "[", "oSettings", ",", "oState", "]", ")", ";", "oSettings", ".", "fnStateSave", ".", "call", "(", "oSettings", ".", "oInstance", ",", "oSettings", ",", "oState", ")", ";", "}" ]
Save the state of a table in a cookie such that the page can be reloaded @param {object} oSettings dataTables settings object @memberof DataTable#oApi
[ "Save", "the", "state", "of", "a", "table", "in", "a", "cookie", "such", "that", "the", "page", "can", "be", "reloaded" ]
9b138f2b4fb7873b9b0f271516daf36e20c9c037
https://github.com/joyent/kang/blob/9b138f2b4fb7873b9b0f271516daf36e20c9c037/examples/webconsole/resources/js/jquery/jquery.dataTables.js#L4271-L4299
train
joyent/kang
examples/webconsole/resources/js/jquery/jquery.dataTables.js
_fnLoadState
function _fnLoadState ( oSettings, oInit ) { if ( !oSettings.oFeatures.bStateSave ) { return; } var oData = oSettings.fnStateLoad.call( oSettings.oInstance, oSettings ); if ( !oData ) { return; } /* Allow custom and plug-in manipulation functions to alter the saved data set and * cancelling of loading by returning false */ var abStateLoad = _fnCallbackFire( oSettings, 'aoStateLoadParams', 'stateLoadParams', [oSettings, oData] ); if ( $.inArray( false, abStateLoad ) !== -1 ) { return; } /* Store the saved state so it might be accessed at any time */ oSettings.oLoadedState = $.extend( true, {}, oData ); /* Restore key features */ oSettings._iDisplayStart = oData.iStart; oSettings.iInitDisplayStart = oData.iStart; oSettings._iDisplayEnd = oData.iEnd; oSettings._iDisplayLength = oData.iLength; oSettings.aaSorting = oData.aaSorting.slice(); oSettings.saved_aaSorting = oData.aaSorting.slice(); /* Search filtering */ $.extend( oSettings.oPreviousSearch, oData.oSearch ); $.extend( true, oSettings.aoPreSearchCols, oData.aoSearchCols ); /* Column visibility state * Pass back visibiliy settings to the init handler, but to do not here override * the init object that the user might have passed in */ oInit.saved_aoColumns = []; for ( var i=0 ; i<oData.abVisCols.length ; i++ ) { oInit.saved_aoColumns[i] = {}; oInit.saved_aoColumns[i].bVisible = oData.abVisCols[i]; } _fnCallbackFire( oSettings, 'aoStateLoaded', 'stateLoaded', [oSettings, oData] ); }
javascript
function _fnLoadState ( oSettings, oInit ) { if ( !oSettings.oFeatures.bStateSave ) { return; } var oData = oSettings.fnStateLoad.call( oSettings.oInstance, oSettings ); if ( !oData ) { return; } /* Allow custom and plug-in manipulation functions to alter the saved data set and * cancelling of loading by returning false */ var abStateLoad = _fnCallbackFire( oSettings, 'aoStateLoadParams', 'stateLoadParams', [oSettings, oData] ); if ( $.inArray( false, abStateLoad ) !== -1 ) { return; } /* Store the saved state so it might be accessed at any time */ oSettings.oLoadedState = $.extend( true, {}, oData ); /* Restore key features */ oSettings._iDisplayStart = oData.iStart; oSettings.iInitDisplayStart = oData.iStart; oSettings._iDisplayEnd = oData.iEnd; oSettings._iDisplayLength = oData.iLength; oSettings.aaSorting = oData.aaSorting.slice(); oSettings.saved_aaSorting = oData.aaSorting.slice(); /* Search filtering */ $.extend( oSettings.oPreviousSearch, oData.oSearch ); $.extend( true, oSettings.aoPreSearchCols, oData.aoSearchCols ); /* Column visibility state * Pass back visibiliy settings to the init handler, but to do not here override * the init object that the user might have passed in */ oInit.saved_aoColumns = []; for ( var i=0 ; i<oData.abVisCols.length ; i++ ) { oInit.saved_aoColumns[i] = {}; oInit.saved_aoColumns[i].bVisible = oData.abVisCols[i]; } _fnCallbackFire( oSettings, 'aoStateLoaded', 'stateLoaded', [oSettings, oData] ); }
[ "function", "_fnLoadState", "(", "oSettings", ",", "oInit", ")", "{", "if", "(", "!", "oSettings", ".", "oFeatures", ".", "bStateSave", ")", "{", "return", ";", "}", "var", "oData", "=", "oSettings", ".", "fnStateLoad", ".", "call", "(", "oSettings", ".", "oInstance", ",", "oSettings", ")", ";", "if", "(", "!", "oData", ")", "{", "return", ";", "}", "var", "abStateLoad", "=", "_fnCallbackFire", "(", "oSettings", ",", "'aoStateLoadParams'", ",", "'stateLoadParams'", ",", "[", "oSettings", ",", "oData", "]", ")", ";", "if", "(", "$", ".", "inArray", "(", "false", ",", "abStateLoad", ")", "!==", "-", "1", ")", "{", "return", ";", "}", "oSettings", ".", "oLoadedState", "=", "$", ".", "extend", "(", "true", ",", "{", "}", ",", "oData", ")", ";", "oSettings", ".", "_iDisplayStart", "=", "oData", ".", "iStart", ";", "oSettings", ".", "iInitDisplayStart", "=", "oData", ".", "iStart", ";", "oSettings", ".", "_iDisplayEnd", "=", "oData", ".", "iEnd", ";", "oSettings", ".", "_iDisplayLength", "=", "oData", ".", "iLength", ";", "oSettings", ".", "aaSorting", "=", "oData", ".", "aaSorting", ".", "slice", "(", ")", ";", "oSettings", ".", "saved_aaSorting", "=", "oData", ".", "aaSorting", ".", "slice", "(", ")", ";", "$", ".", "extend", "(", "oSettings", ".", "oPreviousSearch", ",", "oData", ".", "oSearch", ")", ";", "$", ".", "extend", "(", "true", ",", "oSettings", ".", "aoPreSearchCols", ",", "oData", ".", "aoSearchCols", ")", ";", "oInit", ".", "saved_aoColumns", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "oData", ".", "abVisCols", ".", "length", ";", "i", "++", ")", "{", "oInit", ".", "saved_aoColumns", "[", "i", "]", "=", "{", "}", ";", "oInit", ".", "saved_aoColumns", "[", "i", "]", ".", "bVisible", "=", "oData", ".", "abVisCols", "[", "i", "]", ";", "}", "_fnCallbackFire", "(", "oSettings", ",", "'aoStateLoaded'", ",", "'stateLoaded'", ",", "[", "oSettings", ",", "oData", "]", ")", ";", "}" ]
Attempt to load a saved table state from a cookie @param {object} oSettings dataTables settings object @param {object} oInit DataTables init object so we can override settings @memberof DataTable#oApi
[ "Attempt", "to", "load", "a", "saved", "table", "state", "from", "a", "cookie" ]
9b138f2b4fb7873b9b0f271516daf36e20c9c037
https://github.com/joyent/kang/blob/9b138f2b4fb7873b9b0f271516daf36e20c9c037/examples/webconsole/resources/js/jquery/jquery.dataTables.js#L4308-L4357
train
joyent/kang
examples/webconsole/resources/js/jquery/jquery.dataTables.js
_fnCreateCookie
function _fnCreateCookie ( sName, sValue, iSecs, sBaseName, fnCallback ) { var date = new Date(); date.setTime( date.getTime()+(iSecs*1000) ); /* * Shocking but true - it would appear IE has major issues with having the path not having * a trailing slash on it. We need the cookie to be available based on the path, so we * have to append the file name to the cookie name. Appalling. Thanks to vex for adding the * patch to use at least some of the path */ var aParts = window.location.pathname.split('/'); var sNameFile = sName + '_' + aParts.pop().replace(/[\/:]/g,"").toLowerCase(); var sFullCookie, oData; if ( fnCallback !== null ) { oData = (typeof $.parseJSON === 'function') ? $.parseJSON( sValue ) : eval( '('+sValue+')' ); sFullCookie = fnCallback( sNameFile, oData, date.toGMTString(), aParts.join('/')+"/" ); } else { sFullCookie = sNameFile + "=" + encodeURIComponent(sValue) + "; expires=" + date.toGMTString() +"; path=" + aParts.join('/')+"/"; } /* Are we going to go over the cookie limit of 4KiB? If so, try to delete a cookies * belonging to DataTables. This is FAR from bullet proof */ var sOldName="", iOldTime=9999999999999; var iLength = _fnReadCookie( sNameFile )!==null ? document.cookie.length : sFullCookie.length + document.cookie.length; if ( iLength+10 > 4096 ) /* Magic 10 for padding */ { var aCookies =document.cookie.split(';'); for ( var i=0, iLen=aCookies.length ; i<iLen ; i++ ) { if ( aCookies[i].indexOf( sBaseName ) != -1 ) { /* It's a DataTables cookie, so eval it and check the time stamp */ var aSplitCookie = aCookies[i].split('='); try { oData = eval( '('+decodeURIComponent(aSplitCookie[1])+')' ); } catch( e ) { continue; } if ( oData.iCreate && oData.iCreate < iOldTime ) { sOldName = aSplitCookie[0]; iOldTime = oData.iCreate; } } } if ( sOldName !== "" ) { document.cookie = sOldName+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path="+ aParts.join('/') + "/"; } } document.cookie = sFullCookie; }
javascript
function _fnCreateCookie ( sName, sValue, iSecs, sBaseName, fnCallback ) { var date = new Date(); date.setTime( date.getTime()+(iSecs*1000) ); /* * Shocking but true - it would appear IE has major issues with having the path not having * a trailing slash on it. We need the cookie to be available based on the path, so we * have to append the file name to the cookie name. Appalling. Thanks to vex for adding the * patch to use at least some of the path */ var aParts = window.location.pathname.split('/'); var sNameFile = sName + '_' + aParts.pop().replace(/[\/:]/g,"").toLowerCase(); var sFullCookie, oData; if ( fnCallback !== null ) { oData = (typeof $.parseJSON === 'function') ? $.parseJSON( sValue ) : eval( '('+sValue+')' ); sFullCookie = fnCallback( sNameFile, oData, date.toGMTString(), aParts.join('/')+"/" ); } else { sFullCookie = sNameFile + "=" + encodeURIComponent(sValue) + "; expires=" + date.toGMTString() +"; path=" + aParts.join('/')+"/"; } /* Are we going to go over the cookie limit of 4KiB? If so, try to delete a cookies * belonging to DataTables. This is FAR from bullet proof */ var sOldName="", iOldTime=9999999999999; var iLength = _fnReadCookie( sNameFile )!==null ? document.cookie.length : sFullCookie.length + document.cookie.length; if ( iLength+10 > 4096 ) /* Magic 10 for padding */ { var aCookies =document.cookie.split(';'); for ( var i=0, iLen=aCookies.length ; i<iLen ; i++ ) { if ( aCookies[i].indexOf( sBaseName ) != -1 ) { /* It's a DataTables cookie, so eval it and check the time stamp */ var aSplitCookie = aCookies[i].split('='); try { oData = eval( '('+decodeURIComponent(aSplitCookie[1])+')' ); } catch( e ) { continue; } if ( oData.iCreate && oData.iCreate < iOldTime ) { sOldName = aSplitCookie[0]; iOldTime = oData.iCreate; } } } if ( sOldName !== "" ) { document.cookie = sOldName+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path="+ aParts.join('/') + "/"; } } document.cookie = sFullCookie; }
[ "function", "_fnCreateCookie", "(", "sName", ",", "sValue", ",", "iSecs", ",", "sBaseName", ",", "fnCallback", ")", "{", "var", "date", "=", "new", "Date", "(", ")", ";", "date", ".", "setTime", "(", "date", ".", "getTime", "(", ")", "+", "(", "iSecs", "*", "1000", ")", ")", ";", "var", "aParts", "=", "window", ".", "location", ".", "pathname", ".", "split", "(", "'/'", ")", ";", "var", "sNameFile", "=", "sName", "+", "'_'", "+", "aParts", ".", "pop", "(", ")", ".", "replace", "(", "/", "[\\/:]", "/", "g", ",", "\"\"", ")", ".", "toLowerCase", "(", ")", ";", "var", "sFullCookie", ",", "oData", ";", "if", "(", "fnCallback", "!==", "null", ")", "{", "oData", "=", "(", "typeof", "$", ".", "parseJSON", "===", "'function'", ")", "?", "$", ".", "parseJSON", "(", "sValue", ")", ":", "eval", "(", "'('", "+", "sValue", "+", "')'", ")", ";", "sFullCookie", "=", "fnCallback", "(", "sNameFile", ",", "oData", ",", "date", ".", "toGMTString", "(", ")", ",", "aParts", ".", "join", "(", "'/'", ")", "+", "\"/\"", ")", ";", "}", "else", "{", "sFullCookie", "=", "sNameFile", "+", "\"=\"", "+", "encodeURIComponent", "(", "sValue", ")", "+", "\"; expires=\"", "+", "date", ".", "toGMTString", "(", ")", "+", "\"; path=\"", "+", "aParts", ".", "join", "(", "'/'", ")", "+", "\"/\"", ";", "}", "var", "sOldName", "=", "\"\"", ",", "iOldTime", "=", "9999999999999", ";", "var", "iLength", "=", "_fnReadCookie", "(", "sNameFile", ")", "!==", "null", "?", "document", ".", "cookie", ".", "length", ":", "sFullCookie", ".", "length", "+", "document", ".", "cookie", ".", "length", ";", "if", "(", "iLength", "+", "10", ">", "4096", ")", "{", "var", "aCookies", "=", "document", ".", "cookie", ".", "split", "(", "';'", ")", ";", "for", "(", "var", "i", "=", "0", ",", "iLen", "=", "aCookies", ".", "length", ";", "i", "<", "iLen", ";", "i", "++", ")", "{", "if", "(", "aCookies", "[", "i", "]", ".", "indexOf", "(", "sBaseName", ")", "!=", "-", "1", ")", "{", "var", "aSplitCookie", "=", "aCookies", "[", "i", "]", ".", "split", "(", "'='", ")", ";", "try", "{", "oData", "=", "eval", "(", "'('", "+", "decodeURIComponent", "(", "aSplitCookie", "[", "1", "]", ")", "+", "')'", ")", ";", "}", "catch", "(", "e", ")", "{", "continue", ";", "}", "if", "(", "oData", ".", "iCreate", "&&", "oData", ".", "iCreate", "<", "iOldTime", ")", "{", "sOldName", "=", "aSplitCookie", "[", "0", "]", ";", "iOldTime", "=", "oData", ".", "iCreate", ";", "}", "}", "}", "if", "(", "sOldName", "!==", "\"\"", ")", "{", "document", ".", "cookie", "=", "sOldName", "+", "\"=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=\"", "+", "aParts", ".", "join", "(", "'/'", ")", "+", "\"/\"", ";", "}", "}", "document", ".", "cookie", "=", "sFullCookie", ";", "}" ]
Create a new cookie with a value to store the state of a table @param {string} sName name of the cookie to create @param {string} sValue the value the cookie should take @param {int} iSecs duration of the cookie @param {string} sBaseName sName is made up of the base + file name - this is the base @param {function} fnCallback User definable function to modify the cookie @memberof DataTable#oApi
[ "Create", "a", "new", "cookie", "with", "a", "value", "to", "store", "the", "state", "of", "a", "table" ]
9b138f2b4fb7873b9b0f271516daf36e20c9c037
https://github.com/joyent/kang/blob/9b138f2b4fb7873b9b0f271516daf36e20c9c037/examples/webconsole/resources/js/jquery/jquery.dataTables.js#L4369-L4432
train
joyent/kang
examples/webconsole/resources/js/jquery/jquery.dataTables.js
_fnReadCookie
function _fnReadCookie ( sName ) { var aParts = window.location.pathname.split('/'), sNameEQ = sName + '_' + aParts[aParts.length-1].replace(/[\/:]/g,"").toLowerCase() + '=', sCookieContents = document.cookie.split(';'); for( var i=0 ; i<sCookieContents.length ; i++ ) { var c = sCookieContents[i]; while (c.charAt(0)==' ') { c = c.substring(1,c.length); } if (c.indexOf(sNameEQ) === 0) { return decodeURIComponent( c.substring(sNameEQ.length,c.length) ); } } return null; }
javascript
function _fnReadCookie ( sName ) { var aParts = window.location.pathname.split('/'), sNameEQ = sName + '_' + aParts[aParts.length-1].replace(/[\/:]/g,"").toLowerCase() + '=', sCookieContents = document.cookie.split(';'); for( var i=0 ; i<sCookieContents.length ; i++ ) { var c = sCookieContents[i]; while (c.charAt(0)==' ') { c = c.substring(1,c.length); } if (c.indexOf(sNameEQ) === 0) { return decodeURIComponent( c.substring(sNameEQ.length,c.length) ); } } return null; }
[ "function", "_fnReadCookie", "(", "sName", ")", "{", "var", "aParts", "=", "window", ".", "location", ".", "pathname", ".", "split", "(", "'/'", ")", ",", "sNameEQ", "=", "sName", "+", "'_'", "+", "aParts", "[", "aParts", ".", "length", "-", "1", "]", ".", "replace", "(", "/", "[\\/:]", "/", "g", ",", "\"\"", ")", ".", "toLowerCase", "(", ")", "+", "'='", ",", "sCookieContents", "=", "document", ".", "cookie", ".", "split", "(", "';'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "sCookieContents", ".", "length", ";", "i", "++", ")", "{", "var", "c", "=", "sCookieContents", "[", "i", "]", ";", "while", "(", "c", ".", "charAt", "(", "0", ")", "==", "' '", ")", "{", "c", "=", "c", ".", "substring", "(", "1", ",", "c", ".", "length", ")", ";", "}", "if", "(", "c", ".", "indexOf", "(", "sNameEQ", ")", "===", "0", ")", "{", "return", "decodeURIComponent", "(", "c", ".", "substring", "(", "sNameEQ", ".", "length", ",", "c", ".", "length", ")", ")", ";", "}", "}", "return", "null", ";", "}" ]
Read an old cookie to get a cookie with an old table state @param {string} sName name of the cookie to read @returns {string} contents of the cookie - or null if no cookie with that name found @memberof DataTable#oApi
[ "Read", "an", "old", "cookie", "to", "get", "a", "cookie", "with", "an", "old", "table", "state" ]
9b138f2b4fb7873b9b0f271516daf36e20c9c037
https://github.com/joyent/kang/blob/9b138f2b4fb7873b9b0f271516daf36e20c9c037/examples/webconsole/resources/js/jquery/jquery.dataTables.js#L4441-L4463
train
joyent/kang
examples/webconsole/resources/js/jquery/jquery.dataTables.js
_fnGetTrNodes
function _fnGetTrNodes ( oSettings ) { var aNodes = []; var aoData = oSettings.aoData; for ( var i=0, iLen=aoData.length ; i<iLen ; i++ ) { if ( aoData[i].nTr !== null ) { aNodes.push( aoData[i].nTr ); } } return aNodes; }
javascript
function _fnGetTrNodes ( oSettings ) { var aNodes = []; var aoData = oSettings.aoData; for ( var i=0, iLen=aoData.length ; i<iLen ; i++ ) { if ( aoData[i].nTr !== null ) { aNodes.push( aoData[i].nTr ); } } return aNodes; }
[ "function", "_fnGetTrNodes", "(", "oSettings", ")", "{", "var", "aNodes", "=", "[", "]", ";", "var", "aoData", "=", "oSettings", ".", "aoData", ";", "for", "(", "var", "i", "=", "0", ",", "iLen", "=", "aoData", ".", "length", ";", "i", "<", "iLen", ";", "i", "++", ")", "{", "if", "(", "aoData", "[", "i", "]", ".", "nTr", "!==", "null", ")", "{", "aNodes", ".", "push", "(", "aoData", "[", "i", "]", ".", "nTr", ")", ";", "}", "}", "return", "aNodes", ";", "}" ]
Return an array with the TR nodes for the table @param {object} oSettings dataTables settings object @returns {array} TR array @memberof DataTable#oApi
[ "Return", "an", "array", "with", "the", "TR", "nodes", "for", "the", "table" ]
9b138f2b4fb7873b9b0f271516daf36e20c9c037
https://github.com/joyent/kang/blob/9b138f2b4fb7873b9b0f271516daf36e20c9c037/examples/webconsole/resources/js/jquery/jquery.dataTables.js#L4493-L4505
train
joyent/kang
examples/webconsole/resources/js/jquery/jquery.dataTables.js
_fnGetTdNodes
function _fnGetTdNodes ( oSettings, iIndividualRow ) { var anReturn = []; var iCorrector; var anTds; var iRow, iRows=oSettings.aoData.length, iColumn, iColumns, oData, sNodeName, iStart=0, iEnd=iRows; /* Allow the collection to be limited to just one row */ if ( iIndividualRow !== undefined ) { iStart = iIndividualRow; iEnd = iIndividualRow+1; } for ( iRow=iStart ; iRow<iEnd ; iRow++ ) { oData = oSettings.aoData[iRow]; if ( oData.nTr !== null ) { /* get the TD child nodes - taking into account text etc nodes */ anTds = []; for ( iColumn=0, iColumns=oData.nTr.childNodes.length ; iColumn<iColumns ; iColumn++ ) { sNodeName = oData.nTr.childNodes[iColumn].nodeName.toLowerCase(); if ( sNodeName == 'td' || sNodeName == 'th' ) { anTds.push( oData.nTr.childNodes[iColumn] ); } } iCorrector = 0; for ( iColumn=0, iColumns=oSettings.aoColumns.length ; iColumn<iColumns ; iColumn++ ) { if ( oSettings.aoColumns[iColumn].bVisible ) { anReturn.push( anTds[iColumn-iCorrector] ); } else { anReturn.push( oData._anHidden[iColumn] ); iCorrector++; } } } } return anReturn; }
javascript
function _fnGetTdNodes ( oSettings, iIndividualRow ) { var anReturn = []; var iCorrector; var anTds; var iRow, iRows=oSettings.aoData.length, iColumn, iColumns, oData, sNodeName, iStart=0, iEnd=iRows; /* Allow the collection to be limited to just one row */ if ( iIndividualRow !== undefined ) { iStart = iIndividualRow; iEnd = iIndividualRow+1; } for ( iRow=iStart ; iRow<iEnd ; iRow++ ) { oData = oSettings.aoData[iRow]; if ( oData.nTr !== null ) { /* get the TD child nodes - taking into account text etc nodes */ anTds = []; for ( iColumn=0, iColumns=oData.nTr.childNodes.length ; iColumn<iColumns ; iColumn++ ) { sNodeName = oData.nTr.childNodes[iColumn].nodeName.toLowerCase(); if ( sNodeName == 'td' || sNodeName == 'th' ) { anTds.push( oData.nTr.childNodes[iColumn] ); } } iCorrector = 0; for ( iColumn=0, iColumns=oSettings.aoColumns.length ; iColumn<iColumns ; iColumn++ ) { if ( oSettings.aoColumns[iColumn].bVisible ) { anReturn.push( anTds[iColumn-iCorrector] ); } else { anReturn.push( oData._anHidden[iColumn] ); iCorrector++; } } } } return anReturn; }
[ "function", "_fnGetTdNodes", "(", "oSettings", ",", "iIndividualRow", ")", "{", "var", "anReturn", "=", "[", "]", ";", "var", "iCorrector", ";", "var", "anTds", ";", "var", "iRow", ",", "iRows", "=", "oSettings", ".", "aoData", ".", "length", ",", "iColumn", ",", "iColumns", ",", "oData", ",", "sNodeName", ",", "iStart", "=", "0", ",", "iEnd", "=", "iRows", ";", "if", "(", "iIndividualRow", "!==", "undefined", ")", "{", "iStart", "=", "iIndividualRow", ";", "iEnd", "=", "iIndividualRow", "+", "1", ";", "}", "for", "(", "iRow", "=", "iStart", ";", "iRow", "<", "iEnd", ";", "iRow", "++", ")", "{", "oData", "=", "oSettings", ".", "aoData", "[", "iRow", "]", ";", "if", "(", "oData", ".", "nTr", "!==", "null", ")", "{", "anTds", "=", "[", "]", ";", "for", "(", "iColumn", "=", "0", ",", "iColumns", "=", "oData", ".", "nTr", ".", "childNodes", ".", "length", ";", "iColumn", "<", "iColumns", ";", "iColumn", "++", ")", "{", "sNodeName", "=", "oData", ".", "nTr", ".", "childNodes", "[", "iColumn", "]", ".", "nodeName", ".", "toLowerCase", "(", ")", ";", "if", "(", "sNodeName", "==", "'td'", "||", "sNodeName", "==", "'th'", ")", "{", "anTds", ".", "push", "(", "oData", ".", "nTr", ".", "childNodes", "[", "iColumn", "]", ")", ";", "}", "}", "iCorrector", "=", "0", ";", "for", "(", "iColumn", "=", "0", ",", "iColumns", "=", "oSettings", ".", "aoColumns", ".", "length", ";", "iColumn", "<", "iColumns", ";", "iColumn", "++", ")", "{", "if", "(", "oSettings", ".", "aoColumns", "[", "iColumn", "]", ".", "bVisible", ")", "{", "anReturn", ".", "push", "(", "anTds", "[", "iColumn", "-", "iCorrector", "]", ")", ";", "}", "else", "{", "anReturn", ".", "push", "(", "oData", ".", "_anHidden", "[", "iColumn", "]", ")", ";", "iCorrector", "++", ";", "}", "}", "}", "}", "return", "anReturn", ";", "}" ]
Return an flat array with all TD nodes for the table, or row @param {object} oSettings dataTables settings object @param {int} [iIndividualRow] aoData index to get the nodes for - optional if not given then the return array will contain all nodes for the table @returns {array} TD array @memberof DataTable#oApi
[ "Return", "an", "flat", "array", "with", "all", "TD", "nodes", "for", "the", "table", "or", "row" ]
9b138f2b4fb7873b9b0f271516daf36e20c9c037
https://github.com/joyent/kang/blob/9b138f2b4fb7873b9b0f271516daf36e20c9c037/examples/webconsole/resources/js/jquery/jquery.dataTables.js#L4516-L4564
train