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
C2FO/patio
lib/dataset/actions.js
function (column, cb) { var ret = new Promise(); this.__aggregateDataset() .select(sql.min(this.stringToIdentifier(column)).as("v1"), sql.max(this.stringToIdentifier(column)).as("v2")) .first() .chain(function (r) { ret.callback(r.v1, r.v2); }, ret.errback); return ret.classic(cb).promise(); }
javascript
function (column, cb) { var ret = new Promise(); this.__aggregateDataset() .select(sql.min(this.stringToIdentifier(column)).as("v1"), sql.max(this.stringToIdentifier(column)).as("v2")) .first() .chain(function (r) { ret.callback(r.v1, r.v2); }, ret.errback); return ret.classic(cb).promise(); }
[ "function", "(", "column", ",", "cb", ")", "{", "var", "ret", "=", "new", "Promise", "(", ")", ";", "this", ".", "__aggregateDataset", "(", ")", ".", "select", "(", "sql", ".", "min", "(", "this", ".", "stringToIdentifier", "(", "column", ")", ")", ".", "as", "(", "\"v1\"", ")", ",", "sql", ".", "max", "(", "this", ".", "stringToIdentifier", "(", "column", ")", ")", ".", "as", "(", "\"v2\"", ")", ")", ".", "first", "(", ")", ".", "chain", "(", "function", "(", "r", ")", "{", "ret", ".", "callback", "(", "r", ".", "v1", ",", "r", ".", "v2", ")", ";", "}", ",", "ret", ".", "errback", ")", ";", "return", "ret", ".", "classic", "(", "cb", ")", ".", "promise", "(", ")", ";", "}" ]
Returns a promise resolved with a range from the minimum and maximum values for the given column. @example // SELECT max(id) AS v1, min(id) AS v2 FROM table LIMIT 1 DB.from("table").range("id").chain(function(min, max){ //e.g min === 1 AND max === 10 }); @param {String|patio.sql.Identifier} column the column to find the min and max value for. @param {Function} [cb] the callback to invoke when the action is done. @return {comb.Promise} a promise that is resolved with the min and max value, as the first and second args respectively.
[ "Returns", "a", "promise", "resolved", "with", "a", "range", "from", "the", "minimum", "and", "maximum", "values", "for", "the", "given", "column", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/actions.js#L804-L813
train
C2FO/patio
lib/dataset/actions.js
function (includeColumnTitles, cb) { var n = this.naked(); if (isFunction(includeColumnTitles)) { cb = includeColumnTitles; includeColumnTitles = true; } includeColumnTitles = isBoolean(includeColumnTitles) ? includeColumnTitles : true; return n.columns.chain(function (cols) { var vals = []; if (includeColumnTitles) { vals.push(cols.join(", ")); } return n.forEach(function (r) { vals.push(cols.map(function (c) { return r[c] || ""; }).join(", ")); }).chain(function () { return vals.join("\r\n") + "\r\n"; }); }.bind(this)).classic(cb).promise(); }
javascript
function (includeColumnTitles, cb) { var n = this.naked(); if (isFunction(includeColumnTitles)) { cb = includeColumnTitles; includeColumnTitles = true; } includeColumnTitles = isBoolean(includeColumnTitles) ? includeColumnTitles : true; return n.columns.chain(function (cols) { var vals = []; if (includeColumnTitles) { vals.push(cols.join(", ")); } return n.forEach(function (r) { vals.push(cols.map(function (c) { return r[c] || ""; }).join(", ")); }).chain(function () { return vals.join("\r\n") + "\r\n"; }); }.bind(this)).classic(cb).promise(); }
[ "function", "(", "includeColumnTitles", ",", "cb", ")", "{", "var", "n", "=", "this", ".", "naked", "(", ")", ";", "if", "(", "isFunction", "(", "includeColumnTitles", ")", ")", "{", "cb", "=", "includeColumnTitles", ";", "includeColumnTitles", "=", "true", ";", "}", "includeColumnTitles", "=", "isBoolean", "(", "includeColumnTitles", ")", "?", "includeColumnTitles", ":", "true", ";", "return", "n", ".", "columns", ".", "chain", "(", "function", "(", "cols", ")", "{", "var", "vals", "=", "[", "]", ";", "if", "(", "includeColumnTitles", ")", "{", "vals", ".", "push", "(", "cols", ".", "join", "(", "\", \"", ")", ")", ";", "}", "return", "n", ".", "forEach", "(", "function", "(", "r", ")", "{", "vals", ".", "push", "(", "cols", ".", "map", "(", "function", "(", "c", ")", "{", "return", "r", "[", "c", "]", "||", "\"\"", ";", "}", ")", ".", "join", "(", "\", \"", ")", ")", ";", "}", ")", ".", "chain", "(", "function", "(", ")", "{", "return", "vals", ".", "join", "(", "\"\\r\\n\"", ")", "+", "\\r", ";", "}", ")", ";", "}", ".", "\\n", "\"\\r\\n\"", ")", ".", "\\r", "\\n", ".", "bind", "(", "this", ")", ";", "}" ]
Returns a promise resolved with a string in CSV format containing the dataset records. By default the CSV representation includes the column titles in the first line. You can turn that off by passing false as the includeColumnTitles argument. <p> <b>NOTE:</b> This does not use a CSV library or handle quoting of values in any way. If any values in any of the rows could include commas or line endings, you shouldn't use this. </p> @example // SELECT * FROM table DB.from("table").toCsv().chain(function(csv){ console.log(csv); //outputs id,name 1,Jim 2,Bob }); // SELECT * FROM table DB.from("table").toCsv(false).chain(function(csv){ console.log(csv); //outputs 1,Jim 2,Bob }); @param {Boolean} [includeColumnTitles=true] Set to false to prevent the printing of the column titles as the first line. @param {Function} [cb] the callback to invoke when the action is done. @return {comb.Promise} a promise that will be resolved with the CSV string of the results of the query.
[ "Returns", "a", "promise", "resolved", "with", "a", "string", "in", "CSV", "format", "containing", "the", "dataset", "records", ".", "By", "default", "the", "CSV", "representation", "includes", "the", "column", "titles", "in", "the", "first", "line", ".", "You", "can", "turn", "that", "off", "by", "passing", "false", "as", "the", "includeColumnTitles", "argument", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/actions.js#L1007-L1027
train
C2FO/patio
lib/ConnectionPool.js
function () { var fc = this.freeCount, def, defQueue = this.__deferredQueue; while (fc-- >= 0 && defQueue.count) { def = defQueue.dequeue(); var conn = this.getObject(); if (conn) { def.callback(conn); } else { throw new Error("UNEXPECTED ERROR"); } fc--; } }
javascript
function () { var fc = this.freeCount, def, defQueue = this.__deferredQueue; while (fc-- >= 0 && defQueue.count) { def = defQueue.dequeue(); var conn = this.getObject(); if (conn) { def.callback(conn); } else { throw new Error("UNEXPECTED ERROR"); } fc--; } }
[ "function", "(", ")", "{", "var", "fc", "=", "this", ".", "freeCount", ",", "def", ",", "defQueue", "=", "this", ".", "__deferredQueue", ";", "while", "(", "fc", "--", ">=", "0", "&&", "defQueue", ".", "count", ")", "{", "def", "=", "defQueue", ".", "dequeue", "(", ")", ";", "var", "conn", "=", "this", ".", "getObject", "(", ")", ";", "if", "(", "conn", ")", "{", "def", ".", "callback", "(", "conn", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"UNEXPECTED ERROR\"", ")", ";", "}", "fc", "--", ";", "}", "}" ]
Checks all deferred connection requests.
[ "Checks", "all", "deferred", "connection", "requests", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/ConnectionPool.js#L41-L53
train
C2FO/patio
lib/ConnectionPool.js
function () { var ret = new Promise(), conn; if (this.count > this.__maxObjects) { this.__deferredQueue.enqueue(ret); } else { //todo override getObject to make async so creating a connetion can execute setup sql conn = this.getObject(); if (!conn) { //we need to deffer it this.__deferredQueue.enqueue(ret); } else { ret.callback(conn); } } if (this.count > this.__maxObjects && !conn) { ret.errback(new Error("Unexpected ConnectionPool error")); } return ret.promise(); }
javascript
function () { var ret = new Promise(), conn; if (this.count > this.__maxObjects) { this.__deferredQueue.enqueue(ret); } else { //todo override getObject to make async so creating a connetion can execute setup sql conn = this.getObject(); if (!conn) { //we need to deffer it this.__deferredQueue.enqueue(ret); } else { ret.callback(conn); } } if (this.count > this.__maxObjects && !conn) { ret.errback(new Error("Unexpected ConnectionPool error")); } return ret.promise(); }
[ "function", "(", ")", "{", "var", "ret", "=", "new", "Promise", "(", ")", ",", "conn", ";", "if", "(", "this", ".", "count", ">", "this", ".", "__maxObjects", ")", "{", "this", ".", "__deferredQueue", ".", "enqueue", "(", "ret", ")", ";", "}", "else", "{", "conn", "=", "this", ".", "getObject", "(", ")", ";", "if", "(", "!", "conn", ")", "{", "this", ".", "__deferredQueue", ".", "enqueue", "(", "ret", ")", ";", "}", "else", "{", "ret", ".", "callback", "(", "conn", ")", ";", "}", "}", "if", "(", "this", ".", "count", ">", "this", ".", "__maxObjects", "&&", "!", "conn", ")", "{", "ret", ".", "errback", "(", "new", "Error", "(", "\"Unexpected ConnectionPool error\"", ")", ")", ";", "}", "return", "ret", ".", "promise", "(", ")", ";", "}" ]
Performs a query on one of the connection in this Pool. @return {comb.Promise} A promise to called back with a connection.
[ "Performs", "a", "query", "on", "one", "of", "the", "connection", "in", "this", "Pool", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/ConnectionPool.js#L60-L78
train
C2FO/patio
lib/ConnectionPool.js
function (obj) { var self = this; this.validate(obj).chain(function (valid) { var index; if (self.count <= self.__maxObjects && valid && (index = self.__inUseObjects.indexOf(obj)) > -1) { self.__inUseObjects.splice(index, 1); self.__freeObjects.enqueue(obj); self.__checkQueries(); } else { self.removeObject(obj); } }); }
javascript
function (obj) { var self = this; this.validate(obj).chain(function (valid) { var index; if (self.count <= self.__maxObjects && valid && (index = self.__inUseObjects.indexOf(obj)) > -1) { self.__inUseObjects.splice(index, 1); self.__freeObjects.enqueue(obj); self.__checkQueries(); } else { self.removeObject(obj); } }); }
[ "function", "(", "obj", ")", "{", "var", "self", "=", "this", ";", "this", ".", "validate", "(", "obj", ")", ".", "chain", "(", "function", "(", "valid", ")", "{", "var", "index", ";", "if", "(", "self", ".", "count", "<=", "self", ".", "__maxObjects", "&&", "valid", "&&", "(", "index", "=", "self", ".", "__inUseObjects", ".", "indexOf", "(", "obj", ")", ")", ">", "-", "1", ")", "{", "self", ".", "__inUseObjects", ".", "splice", "(", "index", ",", "1", ")", ";", "self", ".", "__freeObjects", ".", "enqueue", "(", "obj", ")", ";", "self", ".", "__checkQueries", "(", ")", ";", "}", "else", "{", "self", ".", "removeObject", "(", "obj", ")", ";", "}", "}", ")", ";", "}" ]
Override comb.collections.Pool to allow async validation to allow pools to do any calls to reset a connection if it needs to be done. @param {*} connection the connection to return.
[ "Override", "comb", ".", "collections", ".", "Pool", "to", "allow", "async", "validation", "to", "allow", "pools", "to", "do", "any", "calls", "to", "reset", "a", "connection", "if", "it", "needs", "to", "be", "done", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/ConnectionPool.js#L87-L99
train
C2FO/patio
lib/ConnectionPool.js
function () { this.__ending = true; var conn, fQueue = this.__freeObjects, count = this.count, ps = []; while ((conn = this.__freeObjects.dequeue()) !== undefined) { ps.push(this.closeConnection(conn)); } var inUse = this.__inUseObjects; for (var i = inUse.length - 1; i >= 0; i--) { ps.push(this.closeConnection(inUse[i])); } this.__inUseObjects.length = 0; return new PromiseList(ps).promise(); }
javascript
function () { this.__ending = true; var conn, fQueue = this.__freeObjects, count = this.count, ps = []; while ((conn = this.__freeObjects.dequeue()) !== undefined) { ps.push(this.closeConnection(conn)); } var inUse = this.__inUseObjects; for (var i = inUse.length - 1; i >= 0; i--) { ps.push(this.closeConnection(inUse[i])); } this.__inUseObjects.length = 0; return new PromiseList(ps).promise(); }
[ "function", "(", ")", "{", "this", ".", "__ending", "=", "true", ";", "var", "conn", ",", "fQueue", "=", "this", ".", "__freeObjects", ",", "count", "=", "this", ".", "count", ",", "ps", "=", "[", "]", ";", "while", "(", "(", "conn", "=", "this", ".", "__freeObjects", ".", "dequeue", "(", ")", ")", "!==", "undefined", ")", "{", "ps", ".", "push", "(", "this", ".", "closeConnection", "(", "conn", ")", ")", ";", "}", "var", "inUse", "=", "this", ".", "__inUseObjects", ";", "for", "(", "var", "i", "=", "inUse", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "ps", ".", "push", "(", "this", ".", "closeConnection", "(", "inUse", "[", "i", "]", ")", ")", ";", "}", "this", ".", "__inUseObjects", ".", "length", "=", "0", ";", "return", "new", "PromiseList", "(", "ps", ")", ".", "promise", "(", ")", ";", "}" ]
Override to implement the closing of all connections. @return {comb.Promise} called when all connections are closed.
[ "Override", "to", "implement", "the", "closing", "of", "all", "connections", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/ConnectionPool.js#L130-L142
train
C2FO/patio
lib/ConnectionPool.js
function (conn) { if (!this.__validateConnectionCB) { var ret = new Promise(); ret.callback(true); return ret; } else { return this.__validateConnectionCB(conn); } }
javascript
function (conn) { if (!this.__validateConnectionCB) { var ret = new Promise(); ret.callback(true); return ret; } else { return this.__validateConnectionCB(conn); } }
[ "function", "(", "conn", ")", "{", "if", "(", "!", "this", ".", "__validateConnectionCB", ")", "{", "var", "ret", "=", "new", "Promise", "(", ")", ";", "ret", ".", "callback", "(", "true", ")", ";", "return", "ret", ";", "}", "else", "{", "return", "this", ".", "__validateConnectionCB", "(", "conn", ")", ";", "}", "}" ]
Override to provide any additional validation. By default the promise is called back with true. @param {*} connection the conneciton to validate. @return {comb.Promise} called back with a valid or invalid state.
[ "Override", "to", "provide", "any", "additional", "validation", ".", "By", "default", "the", "promise", "is", "called", "back", "with", "true", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/ConnectionPool.js#L152-L160
train
C2FO/patio
lib/dataset/index.js
function (s) { var ret, m; if ((m = s.match(this._static.COLUMN_REF_RE1)) !== null) { ret = m.slice(1); } else if ((m = s.match(this._static.COLUMN_REF_RE2)) !== null) { ret = [null, m[1], m[2]]; } else if ((m = s.match(this._static.COLUMN_REF_RE3)) !== null) { ret = [m[1], m[2], null]; } else { ret = [null, s, null]; } return ret; }
javascript
function (s) { var ret, m; if ((m = s.match(this._static.COLUMN_REF_RE1)) !== null) { ret = m.slice(1); } else if ((m = s.match(this._static.COLUMN_REF_RE2)) !== null) { ret = [null, m[1], m[2]]; } else if ((m = s.match(this._static.COLUMN_REF_RE3)) !== null) { ret = [m[1], m[2], null]; } else { ret = [null, s, null]; } return ret; }
[ "function", "(", "s", ")", "{", "var", "ret", ",", "m", ";", "if", "(", "(", "m", "=", "s", ".", "match", "(", "this", ".", "_static", ".", "COLUMN_REF_RE1", ")", ")", "!==", "null", ")", "{", "ret", "=", "m", ".", "slice", "(", "1", ")", ";", "}", "else", "if", "(", "(", "m", "=", "s", ".", "match", "(", "this", ".", "_static", ".", "COLUMN_REF_RE2", ")", ")", "!==", "null", ")", "{", "ret", "=", "[", "null", ",", "m", "[", "1", "]", ",", "m", "[", "2", "]", "]", ";", "}", "else", "if", "(", "(", "m", "=", "s", ".", "match", "(", "this", ".", "_static", ".", "COLUMN_REF_RE3", ")", ")", "!==", "null", ")", "{", "ret", "=", "[", "m", "[", "1", "]", ",", "m", "[", "2", "]", ",", "null", "]", ";", "}", "else", "{", "ret", "=", "[", "null", ",", "s", ",", "null", "]", ";", "}", "return", "ret", ";", "}" ]
Can either be a string or null. @example //columns table__column___alias //=> table.column as alias table__column //=> table.column //tables schema__table___alias //=> schema.table as alias schema__table //=> schema.table //name and alias columnOrTable___alias //=> columnOrTable as alias @return {String[]} an array with the elements being: <ul> <li>For columns :[table, column, alias].</li> <li>For tables : [schema, table, alias].</li> </ul>
[ "Can", "either", "be", "a", "string", "or", "null", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/dataset/index.js#L348-L363
train
C2FO/patio
lib/associations/oneToMany.js
function () { var model; try { model = this["__model__"] || (this["__model__"] = this.patio.getModel(this._model, this.parent.db)); } catch (e) { model = this["__model__"] = this.patio.getModel(this.name, this.parent.db); } return model; }
javascript
function () { var model; try { model = this["__model__"] || (this["__model__"] = this.patio.getModel(this._model, this.parent.db)); } catch (e) { model = this["__model__"] = this.patio.getModel(this.name, this.parent.db); } return model; }
[ "function", "(", ")", "{", "var", "model", ";", "try", "{", "model", "=", "this", "[", "\"__model__\"", "]", "||", "(", "this", "[", "\"__model__\"", "]", "=", "this", ".", "patio", ".", "getModel", "(", "this", ".", "_model", ",", "this", ".", "parent", ".", "db", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "model", "=", "this", "[", "\"__model__\"", "]", "=", "this", ".", "patio", ".", "getModel", "(", "this", ".", "name", ",", "this", ".", "parent", ".", "db", ")", ";", "}", "return", "model", ";", "}" ]
Returns our model
[ "Returns", "our", "model" ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/associations/oneToMany.js#L355-L363
train
C2FO/patio
lib/associations/manyToMany.js
function () { if (!this.__joinTableDataset) { var ds = this.__joinTableDataset = this.model.dataset.db.from(this.joinTableName), model = this.model, options = this.__opts; var identifierInputMethod = isUndefined(options.identifierInputMethod) ? model.identifierInputMethod : options.identifierInputMethod, identifierOutputMethod = isUndefined(options.identifierOutputMethod) ? model.identifierOutputMethod : options.identifierOutputMethod; if (identifierInputMethod) { ds.identifierInputMethod = identifierInputMethod; } if (identifierOutputMethod) { ds.identifierOutputMethod = identifierOutputMethod; } } return this.__joinTableDataset; }
javascript
function () { if (!this.__joinTableDataset) { var ds = this.__joinTableDataset = this.model.dataset.db.from(this.joinTableName), model = this.model, options = this.__opts; var identifierInputMethod = isUndefined(options.identifierInputMethod) ? model.identifierInputMethod : options.identifierInputMethod, identifierOutputMethod = isUndefined(options.identifierOutputMethod) ? model.identifierOutputMethod : options.identifierOutputMethod; if (identifierInputMethod) { ds.identifierInputMethod = identifierInputMethod; } if (identifierOutputMethod) { ds.identifierOutputMethod = identifierOutputMethod; } } return this.__joinTableDataset; }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "__joinTableDataset", ")", "{", "var", "ds", "=", "this", ".", "__joinTableDataset", "=", "this", ".", "model", ".", "dataset", ".", "db", ".", "from", "(", "this", ".", "joinTableName", ")", ",", "model", "=", "this", ".", "model", ",", "options", "=", "this", ".", "__opts", ";", "var", "identifierInputMethod", "=", "isUndefined", "(", "options", ".", "identifierInputMethod", ")", "?", "model", ".", "identifierInputMethod", ":", "options", ".", "identifierInputMethod", ",", "identifierOutputMethod", "=", "isUndefined", "(", "options", ".", "identifierOutputMethod", ")", "?", "model", ".", "identifierOutputMethod", ":", "options", ".", "identifierOutputMethod", ";", "if", "(", "identifierInputMethod", ")", "{", "ds", ".", "identifierInputMethod", "=", "identifierInputMethod", ";", "}", "if", "(", "identifierOutputMethod", ")", "{", "ds", ".", "identifierOutputMethod", "=", "identifierOutputMethod", ";", "}", "}", "return", "this", ".", "__joinTableDataset", ";", "}" ]
returns our join table model
[ "returns", "our", "join", "table", "model" ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/associations/manyToMany.js#L279-L292
train
C2FO/patio
lib/plugins/validation.js
function () { this.errors = {}; return flatten(this._static.validators.map(function runValidator(validator) { var col = validator.col, val = this.__values[validator.col], ret = validator.validate(val); this.errors[col] = ret; return ret; }, this)); }
javascript
function () { this.errors = {}; return flatten(this._static.validators.map(function runValidator(validator) { var col = validator.col, val = this.__values[validator.col], ret = validator.validate(val); this.errors[col] = ret; return ret; }, this)); }
[ "function", "(", ")", "{", "this", ".", "errors", "=", "{", "}", ";", "return", "flatten", "(", "this", ".", "_static", ".", "validators", ".", "map", "(", "function", "runValidator", "(", "validator", ")", "{", "var", "col", "=", "validator", ".", "col", ",", "val", "=", "this", ".", "__values", "[", "validator", ".", "col", "]", ",", "ret", "=", "validator", ".", "validate", "(", "val", ")", ";", "this", ".", "errors", "[", "col", "]", "=", "ret", ";", "return", "ret", ";", "}", ",", "this", ")", ")", ";", "}" ]
Validates a model, returning an array of error messages for each invalid property. @return {String[]} an array of error messages for each invalid property.
[ "Validates", "a", "model", "returning", "an", "array", "of", "error", "messages", "for", "each", "invalid", "property", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/plugins/validation.js#L416-L423
train
C2FO/patio
lib/plugins/validation.js
function (name) { this.__initValidation(); var ret; if (isFunction(name)) { name.call(this, this.__getValidator.bind(this)); ret = this; } else if (isString(name)) { ret = this.__getValidator(name); } else { throw new ModelError("name is must be a string or function when validating"); } return ret; }
javascript
function (name) { this.__initValidation(); var ret; if (isFunction(name)) { name.call(this, this.__getValidator.bind(this)); ret = this; } else if (isString(name)) { ret = this.__getValidator(name); } else { throw new ModelError("name is must be a string or function when validating"); } return ret; }
[ "function", "(", "name", ")", "{", "this", ".", "__initValidation", "(", ")", ";", "var", "ret", ";", "if", "(", "isFunction", "(", "name", ")", ")", "{", "name", ".", "call", "(", "this", ",", "this", ".", "__getValidator", ".", "bind", "(", "this", ")", ")", ";", "ret", "=", "this", ";", "}", "else", "if", "(", "isString", "(", "name", ")", ")", "{", "ret", "=", "this", ".", "__getValidator", "(", "name", ")", ";", "}", "else", "{", "throw", "new", "ModelError", "(", "\"name is must be a string or function when validating\"", ")", ";", "}", "return", "ret", ";", "}" ]
Sets up validation for a model. To do single col validation {@code var Model = patio.addModel("validator", { plugins:[ValidatorPlugin] }); //this ensures column assignment Model.validate("col1").isDefined().isAlphaNumeric().hasLength(1, 10); //col2 does not have to be assigned but if it is it must match /hello/ig. Model.validate("col2").like(/hello/ig); //Ensures that the emailAddress column is a valid email address. Model.validate("emailAddress").isEmailAddress(); } Or you can do a mass validation through a callback. {@code var Model = patio.addModel("validator", { plugins:[ValidatorPlugin] }); Model.validate(function(validate){ //this ensures column assignment validate("col1").isDefined().isAlphaNumeric().hasLength(1, 10); //col2 does not have to be assigned but if it is it must match /hello/ig. validate("col2").isLike(/hello/ig); //Ensures that the emailAddress column is a valid email address. validate("emailAddress").isEmail(); }); } @param {String|Function} name the name of the column, or a callback that accepts a function to create validators. @throws {patio.ModelError} if name is not a function or string. @return {patio.Model|Validator} returns a validator if name is a string, other wise returns this for chaining.
[ "Sets", "up", "validation", "for", "a", "model", "." ]
6dba197e468d36189cd74846c0cdbf0755a0ff8d
https://github.com/C2FO/patio/blob/6dba197e468d36189cd74846c0cdbf0755a0ff8d/lib/plugins/validation.js#L508-L520
train
donejs/done-ssr
zones/requests/xhr-cookies.js
function(httpMethod, xhrURL){ var cookie = headers["cookie"] || ""; // Monkey patch URL onto xhr for cookie origin checking in the send method. var reqURL = url.parse(xhrURL); this.__url = reqURL; if (options.auth && cookie) { var domainIsApproved = options.auth.domains.reduce(function(prev, domain){ return prev || reqURL.host.indexOf(domain) >= 0; }, false); } // fix: if proxy is specified, use proxy-hostname instead of request-hostname for xhrURL var args = Array.prototype.slice.call(arguments); if ( options && options.proxy && options.proxyTo && (xhrURL.indexOf(options.proxyTo) === 0) ) { args[1] = url.resolve(options.proxy, xhrURL); } var res = oldOpen.apply(this, args); // If on an approved domain copy the jwt from a cookie to the request headers. if (domainIsApproved) { var jwtCookie = cookieReg.exec(cookie); if(jwtCookie && !this.getRequestHeader('authorization')){ this.setRequestHeader('authorization', 'Bearer ' + jwtCookie[1]); } } return res; }
javascript
function(httpMethod, xhrURL){ var cookie = headers["cookie"] || ""; // Monkey patch URL onto xhr for cookie origin checking in the send method. var reqURL = url.parse(xhrURL); this.__url = reqURL; if (options.auth && cookie) { var domainIsApproved = options.auth.domains.reduce(function(prev, domain){ return prev || reqURL.host.indexOf(domain) >= 0; }, false); } // fix: if proxy is specified, use proxy-hostname instead of request-hostname for xhrURL var args = Array.prototype.slice.call(arguments); if ( options && options.proxy && options.proxyTo && (xhrURL.indexOf(options.proxyTo) === 0) ) { args[1] = url.resolve(options.proxy, xhrURL); } var res = oldOpen.apply(this, args); // If on an approved domain copy the jwt from a cookie to the request headers. if (domainIsApproved) { var jwtCookie = cookieReg.exec(cookie); if(jwtCookie && !this.getRequestHeader('authorization')){ this.setRequestHeader('authorization', 'Bearer ' + jwtCookie[1]); } } return res; }
[ "function", "(", "httpMethod", ",", "xhrURL", ")", "{", "var", "cookie", "=", "headers", "[", "\"cookie\"", "]", "||", "\"\"", ";", "var", "reqURL", "=", "url", ".", "parse", "(", "xhrURL", ")", ";", "this", ".", "__url", "=", "reqURL", ";", "if", "(", "options", ".", "auth", "&&", "cookie", ")", "{", "var", "domainIsApproved", "=", "options", ".", "auth", ".", "domains", ".", "reduce", "(", "function", "(", "prev", ",", "domain", ")", "{", "return", "prev", "||", "reqURL", ".", "host", ".", "indexOf", "(", "domain", ")", ">=", "0", ";", "}", ",", "false", ")", ";", "}", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "if", "(", "options", "&&", "options", ".", "proxy", "&&", "options", ".", "proxyTo", "&&", "(", "xhrURL", ".", "indexOf", "(", "options", ".", "proxyTo", ")", "===", "0", ")", ")", "{", "args", "[", "1", "]", "=", "url", ".", "resolve", "(", "options", ".", "proxy", ",", "xhrURL", ")", ";", "}", "var", "res", "=", "oldOpen", ".", "apply", "(", "this", ",", "args", ")", ";", "if", "(", "domainIsApproved", ")", "{", "var", "jwtCookie", "=", "cookieReg", ".", "exec", "(", "cookie", ")", ";", "if", "(", "jwtCookie", "&&", "!", "this", ".", "getRequestHeader", "(", "'authorization'", ")", ")", "{", "this", ".", "setRequestHeader", "(", "'authorization'", ",", "'Bearer '", "+", "jwtCookie", "[", "1", "]", ")", ";", "}", "}", "return", "res", ";", "}" ]
Override open to attach auth header if the domain is approved.
[ "Override", "open", "to", "attach", "auth", "header", "if", "the", "domain", "is", "approved", "." ]
2cdc7213c0fc5f17752132363df3c2f2dd5436f1
https://github.com/donejs/done-ssr/blob/2cdc7213c0fc5f17752132363df3c2f2dd5436f1/zones/requests/xhr-cookies.js#L18-L52
train
donejs/done-ssr
lib/util/resolve_url.js
resolveUrl
function resolveUrl(headers, relativeURL) { var path = headers[":path"] || ""; var baseUri = headers[":scheme"] + "://" + headers[":authority"] + path; var outURL; if (relativeURL && !fullUrlExp.test(relativeURL) ) { outURL = url.resolve(baseUri, relativeURL); } else { outURL = relativeURL; } return outURL; }
javascript
function resolveUrl(headers, relativeURL) { var path = headers[":path"] || ""; var baseUri = headers[":scheme"] + "://" + headers[":authority"] + path; var outURL; if (relativeURL && !fullUrlExp.test(relativeURL) ) { outURL = url.resolve(baseUri, relativeURL); } else { outURL = relativeURL; } return outURL; }
[ "function", "resolveUrl", "(", "headers", ",", "relativeURL", ")", "{", "var", "path", "=", "headers", "[", "\":path\"", "]", "||", "\"\"", ";", "var", "baseUri", "=", "headers", "[", "\":scheme\"", "]", "+", "\"://\"", "+", "headers", "[", "\":authority\"", "]", "+", "path", ";", "var", "outURL", ";", "if", "(", "relativeURL", "&&", "!", "fullUrlExp", ".", "test", "(", "relativeURL", ")", ")", "{", "outURL", "=", "url", ".", "resolve", "(", "baseUri", ",", "relativeURL", ")", ";", "}", "else", "{", "outURL", "=", "relativeURL", ";", "}", "return", "outURL", ";", "}" ]
Resolve a URL to be a full URL relative to the requested page.
[ "Resolve", "a", "URL", "to", "be", "a", "full", "URL", "relative", "to", "the", "requested", "page", "." ]
2cdc7213c0fc5f17752132363df3c2f2dd5436f1
https://github.com/donejs/done-ssr/blob/2cdc7213c0fc5f17752132363df3c2f2dd5436f1/lib/util/resolve_url.js#L7-L18
train
ethereumjs/ethashjs
index.js
findLastSeed
function findLastSeed (epoc, cb2) { if (epoc === 0) { return cb2(ethUtil.zeros(32), 0) } self.cacheDB.get(epoc, self.dbOpts, function (err, data) { if (!err) { cb2(data.seed, epoc) } else { findLastSeed(epoc - 1, cb2) } }) }
javascript
function findLastSeed (epoc, cb2) { if (epoc === 0) { return cb2(ethUtil.zeros(32), 0) } self.cacheDB.get(epoc, self.dbOpts, function (err, data) { if (!err) { cb2(data.seed, epoc) } else { findLastSeed(epoc - 1, cb2) } }) }
[ "function", "findLastSeed", "(", "epoc", ",", "cb2", ")", "{", "if", "(", "epoc", "===", "0", ")", "{", "return", "cb2", "(", "ethUtil", ".", "zeros", "(", "32", ")", ",", "0", ")", "}", "self", ".", "cacheDB", ".", "get", "(", "epoc", ",", "self", ".", "dbOpts", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "!", "err", ")", "{", "cb2", "(", "data", ".", "seed", ",", "epoc", ")", "}", "else", "{", "findLastSeed", "(", "epoc", "-", "1", ",", "cb2", ")", "}", "}", ")", "}" ]
gives the seed the first epoc found
[ "gives", "the", "seed", "the", "first", "epoc", "found" ]
f88973ec6ca9954dc7b67bca13e74bf10f19dba6
https://github.com/ethereumjs/ethashjs/blob/f88973ec6ca9954dc7b67bca13e74bf10f19dba6/index.js#L110-L122
train
nimiq/keyguard-next
tools/functions.js
listDirectories
function listDirectories(dirPath) { return fs.readdirSync(dirPath).filter( /** * @param {string} file * @returns {boolean} * */ file => fs.statSync(path.join(dirPath, file)).isDirectory(), ); }
javascript
function listDirectories(dirPath) { return fs.readdirSync(dirPath).filter( /** * @param {string} file * @returns {boolean} * */ file => fs.statSync(path.join(dirPath, file)).isDirectory(), ); }
[ "function", "listDirectories", "(", "dirPath", ")", "{", "return", "fs", ".", "readdirSync", "(", "dirPath", ")", ".", "filter", "(", "file", "=>", "fs", ".", "statSync", "(", "path", ".", "join", "(", "dirPath", ",", "file", ")", ")", ".", "isDirectory", "(", ")", ",", ")", ";", "}" ]
List directories in a directory @param {string} dirPath - Directory to search @returns {string[]}
[ "List", "directories", "in", "a", "directory" ]
5e0aaca8b6cec2058b4e2b26a8dda00ba63b141a
https://github.com/nimiq/keyguard-next/blob/5e0aaca8b6cec2058b4e2b26a8dda00ba63b141a/tools/functions.js#L10-L18
train
nimiq/keyguard-next
tools/functions.js
findDependencies
function findDependencies(startFile, class2Path, deps) { // Create a new regex object to reset the readIndex const depRegEx = /global ([a-zA-Z0-9,\s]+) \*/g; // Get global variable const contents = fs.readFileSync(startFile).toString(); /** @type {string[]} */ let fileDeps = []; let fileDepMatch; while ((fileDepMatch = depRegEx.exec(contents)) !== null) { // eslint-disable-line no-cond-assign const fileDep = fileDepMatch[1]; fileDeps = fileDeps.concat(fileDep.split(/,\s*/g)); } fileDeps.forEach(dep => { // CustomError classes if (dep.slice(-5) === 'Error') dep = 'errors'; if (dep === 'runKeyguard' || dep === 'loadNimiq') dep = 'common'; if (deps.indexOf(dep) > -1) return; deps.push(dep); if (dep === 'Nimiq') return; const depPath = class2Path.get(dep); if (!depPath) throw new Error(`Unknown dependency ${dep} referenced from ${startFile}`); // deps are passed by reference findDependencies(depPath, class2Path, deps); // recurse }); return deps; }
javascript
function findDependencies(startFile, class2Path, deps) { // Create a new regex object to reset the readIndex const depRegEx = /global ([a-zA-Z0-9,\s]+) \*/g; // Get global variable const contents = fs.readFileSync(startFile).toString(); /** @type {string[]} */ let fileDeps = []; let fileDepMatch; while ((fileDepMatch = depRegEx.exec(contents)) !== null) { // eslint-disable-line no-cond-assign const fileDep = fileDepMatch[1]; fileDeps = fileDeps.concat(fileDep.split(/,\s*/g)); } fileDeps.forEach(dep => { // CustomError classes if (dep.slice(-5) === 'Error') dep = 'errors'; if (dep === 'runKeyguard' || dep === 'loadNimiq') dep = 'common'; if (deps.indexOf(dep) > -1) return; deps.push(dep); if (dep === 'Nimiq') return; const depPath = class2Path.get(dep); if (!depPath) throw new Error(`Unknown dependency ${dep} referenced from ${startFile}`); // deps are passed by reference findDependencies(depPath, class2Path, deps); // recurse }); return deps; }
[ "function", "findDependencies", "(", "startFile", ",", "class2Path", ",", "deps", ")", "{", "const", "depRegEx", "=", "/", "global ([a-zA-Z0-9,\\s]+) \\*", "/", "g", ";", "const", "contents", "=", "fs", ".", "readFileSync", "(", "startFile", ")", ".", "toString", "(", ")", ";", "let", "fileDeps", "=", "[", "]", ";", "let", "fileDepMatch", ";", "while", "(", "(", "fileDepMatch", "=", "depRegEx", ".", "exec", "(", "contents", ")", ")", "!==", "null", ")", "{", "const", "fileDep", "=", "fileDepMatch", "[", "1", "]", ";", "fileDeps", "=", "fileDeps", ".", "concat", "(", "fileDep", ".", "split", "(", "/", ",\\s*", "/", "g", ")", ")", ";", "}", "fileDeps", ".", "forEach", "(", "dep", "=>", "{", "if", "(", "dep", ".", "slice", "(", "-", "5", ")", "===", "'Error'", ")", "dep", "=", "'errors'", ";", "if", "(", "dep", "===", "'runKeyguard'", "||", "dep", "===", "'loadNimiq'", ")", "dep", "=", "'common'", ";", "if", "(", "deps", ".", "indexOf", "(", "dep", ")", ">", "-", "1", ")", "return", ";", "deps", ".", "push", "(", "dep", ")", ";", "if", "(", "dep", "===", "'Nimiq'", ")", "return", ";", "const", "depPath", "=", "class2Path", ".", "get", "(", "dep", ")", ";", "if", "(", "!", "depPath", ")", "throw", "new", "Error", "(", "`", "${", "dep", "}", "${", "startFile", "}", "`", ")", ";", "findDependencies", "(", "depPath", ",", "class2Path", ",", "deps", ")", ";", "}", ")", ";", "return", "deps", ";", "}" ]
Recursively collect class dependencies from files' global definitions. @param {string} startFile @param {object} class2Path @param {string[]} deps @returns {string[]}
[ "Recursively", "collect", "class", "dependencies", "from", "files", "global", "definitions", "." ]
5e0aaca8b6cec2058b4e2b26a8dda00ba63b141a
https://github.com/nimiq/keyguard-next/blob/5e0aaca8b6cec2058b4e2b26a8dda00ba63b141a/tools/functions.js#L68-L101
train
nimiq/keyguard-next
tools/functions.js
findScripts
function findScripts(indexPath) { const scriptRegEx = /<script.+src="(.+)".*?>/g; const contents = fs.readFileSync(indexPath).toString(); /** @type {string[]} */ const scripts = []; let scriptMatch; while ((scriptMatch = scriptRegEx.exec(contents)) !== null) { // eslint-disable-line no-cond-assign const scriptPath = scriptMatch[1]; scripts.push(scriptPath); } return scripts; }
javascript
function findScripts(indexPath) { const scriptRegEx = /<script.+src="(.+)".*?>/g; const contents = fs.readFileSync(indexPath).toString(); /** @type {string[]} */ const scripts = []; let scriptMatch; while ((scriptMatch = scriptRegEx.exec(contents)) !== null) { // eslint-disable-line no-cond-assign const scriptPath = scriptMatch[1]; scripts.push(scriptPath); } return scripts; }
[ "function", "findScripts", "(", "indexPath", ")", "{", "const", "scriptRegEx", "=", "/", "<script.+src=\"(.+)\".*?>", "/", "g", ";", "const", "contents", "=", "fs", ".", "readFileSync", "(", "indexPath", ")", ".", "toString", "(", ")", ";", "const", "scripts", "=", "[", "]", ";", "let", "scriptMatch", ";", "while", "(", "(", "scriptMatch", "=", "scriptRegEx", ".", "exec", "(", "contents", ")", ")", "!==", "null", ")", "{", "const", "scriptPath", "=", "scriptMatch", "[", "1", "]", ";", "scripts", ".", "push", "(", "scriptPath", ")", ";", "}", "return", "scripts", ";", "}" ]
Retrieve all script pathes from an HTML file @param {string} indexPath @returns {string[]}
[ "Retrieve", "all", "script", "pathes", "from", "an", "HTML", "file" ]
5e0aaca8b6cec2058b4e2b26a8dda00ba63b141a
https://github.com/nimiq/keyguard-next/blob/5e0aaca8b6cec2058b4e2b26a8dda00ba63b141a/tools/functions.js#L109-L123
train
GitbookIO/plugin-exercises
assets/exercises.js
function(data, eventType) { switch(eventType) { case 'progress': // Update UI loading bar break; case 'timeout': finish(new Error(data)); break; case 'result': finish(null, { value: data, type: 'result' }); break; case 'error': if(ready) { return finish(null, { value: data, type: 'error' }); } return finish(new Error(data)); break case 'ready': // We're good to get results and stuff back now ready = true; // Eval our code now that the runtime is ready repl.eval(code); break; default: console.log('Unhandled event =', eventType, 'data =', data); } }
javascript
function(data, eventType) { switch(eventType) { case 'progress': // Update UI loading bar break; case 'timeout': finish(new Error(data)); break; case 'result': finish(null, { value: data, type: 'result' }); break; case 'error': if(ready) { return finish(null, { value: data, type: 'error' }); } return finish(new Error(data)); break case 'ready': // We're good to get results and stuff back now ready = true; // Eval our code now that the runtime is ready repl.eval(code); break; default: console.log('Unhandled event =', eventType, 'data =', data); } }
[ "function", "(", "data", ",", "eventType", ")", "{", "switch", "(", "eventType", ")", "{", "case", "'progress'", ":", "break", ";", "case", "'timeout'", ":", "finish", "(", "new", "Error", "(", "data", ")", ")", ";", "break", ";", "case", "'result'", ":", "finish", "(", "null", ",", "{", "value", ":", "data", ",", "type", ":", "'result'", "}", ")", ";", "break", ";", "case", "'error'", ":", "if", "(", "ready", ")", "{", "return", "finish", "(", "null", ",", "{", "value", ":", "data", ",", "type", ":", "'error'", "}", ")", ";", "}", "return", "finish", "(", "new", "Error", "(", "data", ")", ")", ";", "break", "case", "'ready'", ":", "ready", "=", "true", ";", "repl", ".", "eval", "(", "code", ")", ";", "break", ";", "default", ":", "console", ".", "log", "(", "'Unhandled event ='", ",", "eventType", ",", "'data ='", ",", "data", ")", ";", "}", "}" ]
Handles all our events
[ "Handles", "all", "our", "events" ]
b29094b2794a6dff5b2f77d99299244284b7cb92
https://github.com/GitbookIO/plugin-exercises/blob/b29094b2794a6dff5b2f77d99299244284b7cb92/assets/exercises.js#L28-L60
train
GitbookIO/plugin-exercises
assets/exercises.js
function($exercise) { var codeSolution = $exercise.find(".code-solution").text(); var codeValidation = $exercise.find(".code-validation").text(); var codeContext = $exercise.find(".code-context").text(); var editor = ace.edit($exercise.find(".editor").get(0)); editor.setTheme("ace/theme/tomorrow"); editor.getSession().setUseWorker(false); editor.getSession().setMode("ace/mode/javascript"); editor.commands.addCommand({ name: "submit", bindKey: "Ctrl-Return|Cmd-Return", exec: function() { $exercise.find(".action-submit").click(); } }); // Submit: test code $exercise.find(".action-submit").click(function(e) { e.preventDefault(); gitbook.events.trigger("exercise.submit", {type: "code"}); execute("javascript", editor.getValue(), codeValidation, codeContext, function(err, result) { $exercise.toggleClass("return-error", err != null); $exercise.toggleClass("return-success", err == null); if (err) $exercise.find(".alert-danger").text(err.message || err); }); }); // Set solution $exercise.find(".action-solution").click(function(e) { e.preventDefault(); editor.setValue(codeSolution); editor.gotoLine(0); }); }
javascript
function($exercise) { var codeSolution = $exercise.find(".code-solution").text(); var codeValidation = $exercise.find(".code-validation").text(); var codeContext = $exercise.find(".code-context").text(); var editor = ace.edit($exercise.find(".editor").get(0)); editor.setTheme("ace/theme/tomorrow"); editor.getSession().setUseWorker(false); editor.getSession().setMode("ace/mode/javascript"); editor.commands.addCommand({ name: "submit", bindKey: "Ctrl-Return|Cmd-Return", exec: function() { $exercise.find(".action-submit").click(); } }); // Submit: test code $exercise.find(".action-submit").click(function(e) { e.preventDefault(); gitbook.events.trigger("exercise.submit", {type: "code"}); execute("javascript", editor.getValue(), codeValidation, codeContext, function(err, result) { $exercise.toggleClass("return-error", err != null); $exercise.toggleClass("return-success", err == null); if (err) $exercise.find(".alert-danger").text(err.message || err); }); }); // Set solution $exercise.find(".action-solution").click(function(e) { e.preventDefault(); editor.setValue(codeSolution); editor.gotoLine(0); }); }
[ "function", "(", "$exercise", ")", "{", "var", "codeSolution", "=", "$exercise", ".", "find", "(", "\".code-solution\"", ")", ".", "text", "(", ")", ";", "var", "codeValidation", "=", "$exercise", ".", "find", "(", "\".code-validation\"", ")", ".", "text", "(", ")", ";", "var", "codeContext", "=", "$exercise", ".", "find", "(", "\".code-context\"", ")", ".", "text", "(", ")", ";", "var", "editor", "=", "ace", ".", "edit", "(", "$exercise", ".", "find", "(", "\".editor\"", ")", ".", "get", "(", "0", ")", ")", ";", "editor", ".", "setTheme", "(", "\"ace/theme/tomorrow\"", ")", ";", "editor", ".", "getSession", "(", ")", ".", "setUseWorker", "(", "false", ")", ";", "editor", ".", "getSession", "(", ")", ".", "setMode", "(", "\"ace/mode/javascript\"", ")", ";", "editor", ".", "commands", ".", "addCommand", "(", "{", "name", ":", "\"submit\"", ",", "bindKey", ":", "\"Ctrl-Return|Cmd-Return\"", ",", "exec", ":", "function", "(", ")", "{", "$exercise", ".", "find", "(", "\".action-submit\"", ")", ".", "click", "(", ")", ";", "}", "}", ")", ";", "$exercise", ".", "find", "(", "\".action-submit\"", ")", ".", "click", "(", "function", "(", "e", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "gitbook", ".", "events", ".", "trigger", "(", "\"exercise.submit\"", ",", "{", "type", ":", "\"code\"", "}", ")", ";", "execute", "(", "\"javascript\"", ",", "editor", ".", "getValue", "(", ")", ",", "codeValidation", ",", "codeContext", ",", "function", "(", "err", ",", "result", ")", "{", "$exercise", ".", "toggleClass", "(", "\"return-error\"", ",", "err", "!=", "null", ")", ";", "$exercise", ".", "toggleClass", "(", "\"return-success\"", ",", "err", "==", "null", ")", ";", "if", "(", "err", ")", "$exercise", ".", "find", "(", "\".alert-danger\"", ")", ".", "text", "(", "err", ".", "message", "||", "err", ")", ";", "}", ")", ";", "}", ")", ";", "$exercise", ".", "find", "(", "\".action-solution\"", ")", ".", "click", "(", "function", "(", "e", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "editor", ".", "setValue", "(", "codeSolution", ")", ";", "editor", ".", "gotoLine", "(", "0", ")", ";", "}", ")", ";", "}" ]
Bind an exercise Add code editor, bind interractions
[ "Bind", "an", "exercise", "Add", "code", "editor", "bind", "interractions" ]
b29094b2794a6dff5b2f77d99299244284b7cb92
https://github.com/GitbookIO/plugin-exercises/blob/b29094b2794a6dff5b2f77d99299244284b7cb92/assets/exercises.js#L101-L139
train
nimiq/keyguard-next
src/lib/QrScannerWorker.js
reorderFinderPatterns
function reorderFinderPatterns(pattern1, pattern2, pattern3) { // Find distances between pattern centers const oneTwoDistance = distance(pattern1, pattern2); const twoThreeDistance = distance(pattern2, pattern3); const oneThreeDistance = distance(pattern1, pattern3); let bottomLeft; let topLeft; let topRight; // Assume one closest to other two is B; A and C will just be guesses at first if (twoThreeDistance >= oneTwoDistance && twoThreeDistance >= oneThreeDistance) { [bottomLeft, topLeft, topRight] = [pattern2, pattern1, pattern3]; } else if (oneThreeDistance >= twoThreeDistance && oneThreeDistance >= oneTwoDistance) { [bottomLeft, topLeft, topRight] = [pattern1, pattern2, pattern3]; } else { [bottomLeft, topLeft, topRight] = [pattern1, pattern3, pattern2]; } // Use cross product to figure out whether bottomLeft (A) and topRight (C) are correct or flipped in relation to topLeft (B) // This asks whether BC x BA has a positive z component, which is the arrangement we want. If it's negative, then // we've got it flipped around and should swap topRight and bottomLeft. if (((topRight.x - topLeft.x) * (bottomLeft.y - topLeft.y)) - ((topRight.y - topLeft.y) * (bottomLeft.x - topLeft.x)) < 0) { [bottomLeft, topRight] = [topRight, bottomLeft]; } return { bottomLeft, topLeft, topRight }; }
javascript
function reorderFinderPatterns(pattern1, pattern2, pattern3) { // Find distances between pattern centers const oneTwoDistance = distance(pattern1, pattern2); const twoThreeDistance = distance(pattern2, pattern3); const oneThreeDistance = distance(pattern1, pattern3); let bottomLeft; let topLeft; let topRight; // Assume one closest to other two is B; A and C will just be guesses at first if (twoThreeDistance >= oneTwoDistance && twoThreeDistance >= oneThreeDistance) { [bottomLeft, topLeft, topRight] = [pattern2, pattern1, pattern3]; } else if (oneThreeDistance >= twoThreeDistance && oneThreeDistance >= oneTwoDistance) { [bottomLeft, topLeft, topRight] = [pattern1, pattern2, pattern3]; } else { [bottomLeft, topLeft, topRight] = [pattern1, pattern3, pattern2]; } // Use cross product to figure out whether bottomLeft (A) and topRight (C) are correct or flipped in relation to topLeft (B) // This asks whether BC x BA has a positive z component, which is the arrangement we want. If it's negative, then // we've got it flipped around and should swap topRight and bottomLeft. if (((topRight.x - topLeft.x) * (bottomLeft.y - topLeft.y)) - ((topRight.y - topLeft.y) * (bottomLeft.x - topLeft.x)) < 0) { [bottomLeft, topRight] = [topRight, bottomLeft]; } return { bottomLeft, topLeft, topRight }; }
[ "function", "reorderFinderPatterns", "(", "pattern1", ",", "pattern2", ",", "pattern3", ")", "{", "const", "oneTwoDistance", "=", "distance", "(", "pattern1", ",", "pattern2", ")", ";", "const", "twoThreeDistance", "=", "distance", "(", "pattern2", ",", "pattern3", ")", ";", "const", "oneThreeDistance", "=", "distance", "(", "pattern1", ",", "pattern3", ")", ";", "let", "bottomLeft", ";", "let", "topLeft", ";", "let", "topRight", ";", "if", "(", "twoThreeDistance", ">=", "oneTwoDistance", "&&", "twoThreeDistance", ">=", "oneThreeDistance", ")", "{", "[", "bottomLeft", ",", "topLeft", ",", "topRight", "]", "=", "[", "pattern2", ",", "pattern1", ",", "pattern3", "]", ";", "}", "else", "if", "(", "oneThreeDistance", ">=", "twoThreeDistance", "&&", "oneThreeDistance", ">=", "oneTwoDistance", ")", "{", "[", "bottomLeft", ",", "topLeft", ",", "topRight", "]", "=", "[", "pattern1", ",", "pattern2", ",", "pattern3", "]", ";", "}", "else", "{", "[", "bottomLeft", ",", "topLeft", ",", "topRight", "]", "=", "[", "pattern1", ",", "pattern3", ",", "pattern2", "]", ";", "}", "if", "(", "(", "(", "topRight", ".", "x", "-", "topLeft", ".", "x", ")", "*", "(", "bottomLeft", ".", "y", "-", "topLeft", ".", "y", ")", ")", "-", "(", "(", "topRight", ".", "y", "-", "topLeft", ".", "y", ")", "*", "(", "bottomLeft", ".", "x", "-", "topLeft", ".", "x", ")", ")", "<", "0", ")", "{", "[", "bottomLeft", ",", "topRight", "]", "=", "[", "topRight", ",", "bottomLeft", "]", ";", "}", "return", "{", "bottomLeft", ",", "topLeft", ",", "topRight", "}", ";", "}" ]
Takes three finder patterns and organizes them into topLeft, topRight, etc
[ "Takes", "three", "finder", "patterns", "and", "organizes", "them", "into", "topLeft", "topRight", "etc" ]
5e0aaca8b6cec2058b4e2b26a8dda00ba63b141a
https://github.com/nimiq/keyguard-next/blob/5e0aaca8b6cec2058b4e2b26a8dda00ba63b141a/src/lib/QrScannerWorker.js#L2456-L2481
train
nimiq/keyguard-next
src/lib/QrScannerWorker.js
countBlackWhiteRun
function countBlackWhiteRun(origin, end, matrix, length) { const rise = end.y - origin.y; const run = end.x - origin.x; const towardsEnd = countBlackWhiteRunTowardsPoint(origin, end, matrix, Math.ceil(length / 2)); const awayFromEnd = countBlackWhiteRunTowardsPoint(origin, { x: origin.x - run, y: origin.y - rise }, matrix, Math.ceil(length / 2)); const middleValue = towardsEnd.shift() + awayFromEnd.shift() - 1; // Substract one so we don't double count a pixel return awayFromEnd.concat(middleValue).concat(...towardsEnd); }
javascript
function countBlackWhiteRun(origin, end, matrix, length) { const rise = end.y - origin.y; const run = end.x - origin.x; const towardsEnd = countBlackWhiteRunTowardsPoint(origin, end, matrix, Math.ceil(length / 2)); const awayFromEnd = countBlackWhiteRunTowardsPoint(origin, { x: origin.x - run, y: origin.y - rise }, matrix, Math.ceil(length / 2)); const middleValue = towardsEnd.shift() + awayFromEnd.shift() - 1; // Substract one so we don't double count a pixel return awayFromEnd.concat(middleValue).concat(...towardsEnd); }
[ "function", "countBlackWhiteRun", "(", "origin", ",", "end", ",", "matrix", ",", "length", ")", "{", "const", "rise", "=", "end", ".", "y", "-", "origin", ".", "y", ";", "const", "run", "=", "end", ".", "x", "-", "origin", ".", "x", ";", "const", "towardsEnd", "=", "countBlackWhiteRunTowardsPoint", "(", "origin", ",", "end", ",", "matrix", ",", "Math", ".", "ceil", "(", "length", "/", "2", ")", ")", ";", "const", "awayFromEnd", "=", "countBlackWhiteRunTowardsPoint", "(", "origin", ",", "{", "x", ":", "origin", ".", "x", "-", "run", ",", "y", ":", "origin", ".", "y", "-", "rise", "}", ",", "matrix", ",", "Math", ".", "ceil", "(", "length", "/", "2", ")", ")", ";", "const", "middleValue", "=", "towardsEnd", ".", "shift", "(", ")", "+", "awayFromEnd", ".", "shift", "(", ")", "-", "1", ";", "return", "awayFromEnd", ".", "concat", "(", "middleValue", ")", ".", "concat", "(", "...", "towardsEnd", ")", ";", "}" ]
Takes an origin point and an end point and counts the sizes of the black white run in the origin point along the line that intersects with the end point. Returns an array of elements, representing the pixel sizes of the black white run. Takes a length which represents the number of switches from black to white to look for.
[ "Takes", "an", "origin", "point", "and", "an", "end", "point", "and", "counts", "the", "sizes", "of", "the", "black", "white", "run", "in", "the", "origin", "point", "along", "the", "line", "that", "intersects", "with", "the", "end", "point", ".", "Returns", "an", "array", "of", "elements", "representing", "the", "pixel", "sizes", "of", "the", "black", "white", "run", ".", "Takes", "a", "length", "which", "represents", "the", "number", "of", "switches", "from", "black", "to", "white", "to", "look", "for", "." ]
5e0aaca8b6cec2058b4e2b26a8dda00ba63b141a
https://github.com/nimiq/keyguard-next/blob/5e0aaca8b6cec2058b4e2b26a8dda00ba63b141a/src/lib/QrScannerWorker.js#L2569-L2576
train
nimiq/keyguard-next
src/lib/QrScannerWorker.js
scoreBlackWhiteRun
function scoreBlackWhiteRun(sequence, ratios) { const averageSize = sum(sequence) / sum(ratios); let error = 0; ratios.forEach((ratio, i) => { error += Math.pow((sequence[i] - ratio * averageSize), 2); }); return { averageSize, error }; }
javascript
function scoreBlackWhiteRun(sequence, ratios) { const averageSize = sum(sequence) / sum(ratios); let error = 0; ratios.forEach((ratio, i) => { error += Math.pow((sequence[i] - ratio * averageSize), 2); }); return { averageSize, error }; }
[ "function", "scoreBlackWhiteRun", "(", "sequence", ",", "ratios", ")", "{", "const", "averageSize", "=", "sum", "(", "sequence", ")", "/", "sum", "(", "ratios", ")", ";", "let", "error", "=", "0", ";", "ratios", ".", "forEach", "(", "(", "ratio", ",", "i", ")", "=>", "{", "error", "+=", "Math", ".", "pow", "(", "(", "sequence", "[", "i", "]", "-", "ratio", "*", "averageSize", ")", ",", "2", ")", ";", "}", ")", ";", "return", "{", "averageSize", ",", "error", "}", ";", "}" ]
Takes in a black white run and an array of expected ratios. Returns the average size of the run as well as the "error" - that is the amount the run diverges from the expected ratio
[ "Takes", "in", "a", "black", "white", "run", "and", "an", "array", "of", "expected", "ratios", ".", "Returns", "the", "average", "size", "of", "the", "run", "as", "well", "as", "the", "error", "-", "that", "is", "the", "amount", "the", "run", "diverges", "from", "the", "expected", "ratio" ]
5e0aaca8b6cec2058b4e2b26a8dda00ba63b141a
https://github.com/nimiq/keyguard-next/blob/5e0aaca8b6cec2058b4e2b26a8dda00ba63b141a/src/lib/QrScannerWorker.js#L2579-L2586
train
ChaosGroup/json-ws
lib/client/index.js
RpcTunnel
function RpcTunnel(url, sslSettings) { var self = this; if (! (this instanceof RpcTunnel)) { return new RpcTunnel(url, sslSettings); } this.transports = {}; if (!url) { throw new Error('Missing url parameter, which should be either a URL or client transport.') } var transport = null; if (typeof url === 'string') { var HttpTransport = require('./transports/http'); transport = new HttpTransport(url, sslSettings); // As a special case when adding an HTTP transport, set up the WebSocket transport // It is lazy-loaded, so the WebSocket connection is only created if/when the transport is used Object.defineProperty(this.transports, 'ws', { enumerable: true, // JSWS-47 ensure we can discover the ws transport get: (function () { var webSocketTransport; var WebSocketTransport = require('./transports/ws'); return function () { if (!webSocketTransport) { webSocketTransport = new WebSocketTransport(url, sslSettings); webSocketTransport.on('event', function (e) { self.emit('event', e); }); } return webSocketTransport; }; }()) }); } else { transport = url; transport.on('event', function (e) { self.emit('event', e); }); } transport.on('error', function(err) { self.emit('error', err); }); this.url = transport.url; this.transports[transport.name] = transport; }
javascript
function RpcTunnel(url, sslSettings) { var self = this; if (! (this instanceof RpcTunnel)) { return new RpcTunnel(url, sslSettings); } this.transports = {}; if (!url) { throw new Error('Missing url parameter, which should be either a URL or client transport.') } var transport = null; if (typeof url === 'string') { var HttpTransport = require('./transports/http'); transport = new HttpTransport(url, sslSettings); // As a special case when adding an HTTP transport, set up the WebSocket transport // It is lazy-loaded, so the WebSocket connection is only created if/when the transport is used Object.defineProperty(this.transports, 'ws', { enumerable: true, // JSWS-47 ensure we can discover the ws transport get: (function () { var webSocketTransport; var WebSocketTransport = require('./transports/ws'); return function () { if (!webSocketTransport) { webSocketTransport = new WebSocketTransport(url, sslSettings); webSocketTransport.on('event', function (e) { self.emit('event', e); }); } return webSocketTransport; }; }()) }); } else { transport = url; transport.on('event', function (e) { self.emit('event', e); }); } transport.on('error', function(err) { self.emit('error', err); }); this.url = transport.url; this.transports[transport.name] = transport; }
[ "function", "RpcTunnel", "(", "url", ",", "sslSettings", ")", "{", "var", "self", "=", "this", ";", "if", "(", "!", "(", "this", "instanceof", "RpcTunnel", ")", ")", "{", "return", "new", "RpcTunnel", "(", "url", ",", "sslSettings", ")", ";", "}", "this", ".", "transports", "=", "{", "}", ";", "if", "(", "!", "url", ")", "{", "throw", "new", "Error", "(", "'Missing url parameter, which should be either a URL or client transport.'", ")", "}", "var", "transport", "=", "null", ";", "if", "(", "typeof", "url", "===", "'string'", ")", "{", "var", "HttpTransport", "=", "require", "(", "'./transports/http'", ")", ";", "transport", "=", "new", "HttpTransport", "(", "url", ",", "sslSettings", ")", ";", "Object", ".", "defineProperty", "(", "this", ".", "transports", ",", "'ws'", ",", "{", "enumerable", ":", "true", ",", "get", ":", "(", "function", "(", ")", "{", "var", "webSocketTransport", ";", "var", "WebSocketTransport", "=", "require", "(", "'./transports/ws'", ")", ";", "return", "function", "(", ")", "{", "if", "(", "!", "webSocketTransport", ")", "{", "webSocketTransport", "=", "new", "WebSocketTransport", "(", "url", ",", "sslSettings", ")", ";", "webSocketTransport", ".", "on", "(", "'event'", ",", "function", "(", "e", ")", "{", "self", ".", "emit", "(", "'event'", ",", "e", ")", ";", "}", ")", ";", "}", "return", "webSocketTransport", ";", "}", ";", "}", "(", ")", ")", "}", ")", ";", "}", "else", "{", "transport", "=", "url", ";", "transport", ".", "on", "(", "'event'", ",", "function", "(", "e", ")", "{", "self", ".", "emit", "(", "'event'", ",", "e", ")", ";", "}", ")", ";", "}", "transport", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "self", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", ")", ";", "this", ".", "url", "=", "transport", ".", "url", ";", "this", ".", "transports", "[", "transport", ".", "name", "]", "=", "transport", ";", "}" ]
Client RPC tunnel
[ "Client", "RPC", "tunnel" ]
26609fba655f053ad4d014ef92e5d901a9a6b6fa
https://github.com/ChaosGroup/json-ws/blob/26609fba655f053ad4d014ef92e5d901a9a6b6fa/lib/client/index.js#L22-L71
train
webgme/webgme-cli
src/mixins/Enableable/RemoveFromPlugin/RemoveFromPlugin.js
function () { // Call base class' constructor. PluginBase.call(this); this.pluginMetadata = { name: 'ComponentDisabler', version: '2.0.0', configStructure: [ { name: 'field', displayName: 'Field', description: 'Field of root node to add to', value: null, valueType: 'string', readOnly: false }, { name: 'attribute', displayName: 'Attribute', description: 'Attribute to add to field', value: '', valueType: 'string', readOnly: false } ] }; }
javascript
function () { // Call base class' constructor. PluginBase.call(this); this.pluginMetadata = { name: 'ComponentDisabler', version: '2.0.0', configStructure: [ { name: 'field', displayName: 'Field', description: 'Field of root node to add to', value: null, valueType: 'string', readOnly: false }, { name: 'attribute', displayName: 'Attribute', description: 'Attribute to add to field', value: '', valueType: 'string', readOnly: false } ] }; }
[ "function", "(", ")", "{", "PluginBase", ".", "call", "(", "this", ")", ";", "this", ".", "pluginMetadata", "=", "{", "name", ":", "'ComponentDisabler'", ",", "version", ":", "'2.0.0'", ",", "configStructure", ":", "[", "{", "name", ":", "'field'", ",", "displayName", ":", "'Field'", ",", "description", ":", "'Field of root node to add to'", ",", "value", ":", "null", ",", "valueType", ":", "'string'", ",", "readOnly", ":", "false", "}", ",", "{", "name", ":", "'attribute'", ",", "displayName", ":", "'Attribute'", ",", "description", ":", "'Attribute to add to field'", ",", "value", ":", "''", ",", "valueType", ":", "'string'", ",", "readOnly", ":", "false", "}", "]", "}", ";", "}" ]
Initializes a new instance of RemoveFromPlugin. @class @augments {PluginBase} @classdesc This class represents the plugin RemoveFromPlugin. @constructor
[ "Initializes", "a", "new", "instance", "of", "RemoveFromPlugin", "." ]
a2f587ab050f50856692eae1167b9fbdf0da003c
https://github.com/webgme/webgme-cli/blob/a2f587ab050f50856692eae1167b9fbdf0da003c/src/mixins/Enableable/RemoveFromPlugin/RemoveFromPlugin.js#L22-L43
train
ChaosGroup/json-ws
lib/get-language-proxy.js
getLanguageProxy
function getLanguageProxy(options) { // Try and find if one is available const proxyScript = path.resolve(__dirname, '..', 'proxies', options.language + '.ejs'); return new Promise(function(resolve, reject) { fs.stat(proxyScript, function(err) { if (err) { return reject(err); } ejs.renderFile( proxyScript, { metadata: options.serviceInstance.metadata, localName: options.localName || 'Proxy', _: _, }, { _with: false }, function(err, html) { if (err) { return reject(err); } resolve(html); } ); }); }); }
javascript
function getLanguageProxy(options) { // Try and find if one is available const proxyScript = path.resolve(__dirname, '..', 'proxies', options.language + '.ejs'); return new Promise(function(resolve, reject) { fs.stat(proxyScript, function(err) { if (err) { return reject(err); } ejs.renderFile( proxyScript, { metadata: options.serviceInstance.metadata, localName: options.localName || 'Proxy', _: _, }, { _with: false }, function(err, html) { if (err) { return reject(err); } resolve(html); } ); }); }); }
[ "function", "getLanguageProxy", "(", "options", ")", "{", "const", "proxyScript", "=", "path", ".", "resolve", "(", "__dirname", ",", "'..'", ",", "'proxies'", ",", "options", ".", "language", "+", "'.ejs'", ")", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "fs", ".", "stat", "(", "proxyScript", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "reject", "(", "err", ")", ";", "}", "ejs", ".", "renderFile", "(", "proxyScript", ",", "{", "metadata", ":", "options", ".", "serviceInstance", ".", "metadata", ",", "localName", ":", "options", ".", "localName", "||", "'Proxy'", ",", "_", ":", "_", ",", "}", ",", "{", "_with", ":", "false", "}", ",", "function", "(", "err", ",", "html", ")", "{", "if", "(", "err", ")", "{", "return", "reject", "(", "err", ")", ";", "}", "resolve", "(", "html", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Return a language proxy for the specified service instance and @param options @param options.serviceInstance {object} JSON-WS service instance @param options.language {string} target language, e.g. "JavaScript" or "Python" @param [options.localName] {string} the name of the proxy class. Defaults to "Proxy" @returns {object} Promise
[ "Return", "a", "language", "proxy", "for", "the", "specified", "service", "instance", "and" ]
26609fba655f053ad4d014ef92e5d901a9a6b6fa
https://github.com/ChaosGroup/json-ws/blob/26609fba655f053ad4d014ef92e5d901a9a6b6fa/lib/get-language-proxy.js#L16-L44
train
nodules/luster
lib/configuration/check.js
checkConfiguration
function checkConfiguration(conf) { let failedChecks = 0; for (const path of Object.keys(CHECKS)) { // @todo avoid try..catch try { checkProperty(path, get(conf, path), CHECKS[path]); } catch (error) { LusterConfigurationError.ensureError(error).log(); ++failedChecks; } } return failedChecks; }
javascript
function checkConfiguration(conf) { let failedChecks = 0; for (const path of Object.keys(CHECKS)) { // @todo avoid try..catch try { checkProperty(path, get(conf, path), CHECKS[path]); } catch (error) { LusterConfigurationError.ensureError(error).log(); ++failedChecks; } } return failedChecks; }
[ "function", "checkConfiguration", "(", "conf", ")", "{", "let", "failedChecks", "=", "0", ";", "for", "(", "const", "path", "of", "Object", ".", "keys", "(", "CHECKS", ")", ")", "{", "try", "{", "checkProperty", "(", "path", ",", "get", "(", "conf", ",", "path", ")", ",", "CHECKS", "[", "path", "]", ")", ";", "}", "catch", "(", "error", ")", "{", "LusterConfigurationError", ".", "ensureError", "(", "error", ")", ".", "log", "(", ")", ";", "++", "failedChecks", ";", "}", "}", "return", "failedChecks", ";", "}" ]
Validate configuration object using descriptions from CHECKS const @param {Object} conf configuration object @returns {Number} of failed checks
[ "Validate", "configuration", "object", "using", "descriptions", "from", "CHECKS", "const" ]
420afc09fdc63872e42e6a38c51e0cf9946d75c7
https://github.com/nodules/luster/blob/420afc09fdc63872e42e6a38c51e0cf9946d75c7/lib/configuration/check.js#L84-L98
train
nodules/luster
lib/cluster_process.js
extendResolvePath
function extendResolvePath(basedir) { // using module internals isn't good, but restarting with corrected NODE_PATH looks more ugly, IMO module.paths.push(basedir); const _basedir = basedir.split('/'), size = basedir.length; let i = 0; while (size > i++) { const modulesPath = _basedir.slice(0, i).join('/') + '/node_modules'; if (module.paths.indexOf(modulesPath) === -1) { module.paths.push(modulesPath); } } }
javascript
function extendResolvePath(basedir) { // using module internals isn't good, but restarting with corrected NODE_PATH looks more ugly, IMO module.paths.push(basedir); const _basedir = basedir.split('/'), size = basedir.length; let i = 0; while (size > i++) { const modulesPath = _basedir.slice(0, i).join('/') + '/node_modules'; if (module.paths.indexOf(modulesPath) === -1) { module.paths.push(modulesPath); } } }
[ "function", "extendResolvePath", "(", "basedir", ")", "{", "module", ".", "paths", ".", "push", "(", "basedir", ")", ";", "const", "_basedir", "=", "basedir", ".", "split", "(", "'/'", ")", ",", "size", "=", "basedir", ".", "length", ";", "let", "i", "=", "0", ";", "while", "(", "size", ">", "i", "++", ")", "{", "const", "modulesPath", "=", "_basedir", ".", "slice", "(", "0", ",", "i", ")", ".", "join", "(", "'/'", ")", "+", "'/node_modules'", ";", "if", "(", "module", ".", "paths", ".", "indexOf", "(", "modulesPath", ")", "===", "-", "1", ")", "{", "module", ".", "paths", ".", "push", "(", "modulesPath", ")", ";", "}", "}", "}" ]
Add `basedir`, `node_modules` contained in the `basedir` and its ancestors to `module.paths` @param {String} basedir
[ "Add", "basedir", "node_modules", "contained", "in", "the", "basedir", "and", "its", "ancestors", "to", "module", ".", "paths" ]
420afc09fdc63872e42e6a38c51e0cf9946d75c7
https://github.com/nodules/luster/blob/420afc09fdc63872e42e6a38c51e0cf9946d75c7/lib/cluster_process.js#L23-L38
train
multiformats/js-multihashing-async
src/index.js
Multihashing
async function Multihashing (buf, alg, length) { const digest = await Multihashing.digest(buf, alg, length) return multihash.encode(digest, alg, length) }
javascript
async function Multihashing (buf, alg, length) { const digest = await Multihashing.digest(buf, alg, length) return multihash.encode(digest, alg, length) }
[ "async", "function", "Multihashing", "(", "buf", ",", "alg", ",", "length", ")", "{", "const", "digest", "=", "await", "Multihashing", ".", "digest", "(", "buf", ",", "alg", ",", "length", ")", "return", "multihash", ".", "encode", "(", "digest", ",", "alg", ",", "length", ")", "}" ]
Hash the given `buf` using the algorithm specified by `alg`. @param {Buffer} buf - The value to hash. @param {number|string} alg - The algorithm to use eg 'sha1' @param {number} [length] - Optionally trim the result to this length. @returns {Promise<Buffer>}
[ "Hash", "the", "given", "buf", "using", "the", "algorithm", "specified", "by", "alg", "." ]
865e9caf9dcdbcdf12d0008129e3b062528317d5
https://github.com/multiformats/js-multihashing-async/blob/865e9caf9dcdbcdf12d0008129e3b062528317d5/src/index.js#L15-L18
train
edx/frontend-auth
src/AuthenticatedAPIClient/axiosConfig.js
applyAxiosDefaults
function applyAxiosDefaults(authenticatedAPIClient) { /* eslint-disable no-param-reassign */ authenticatedAPIClient.defaults.withCredentials = true; authenticatedAPIClient.defaults.headers.common['USE-JWT-COOKIE'] = true; /* eslint-enable no-param-reassign */ }
javascript
function applyAxiosDefaults(authenticatedAPIClient) { /* eslint-disable no-param-reassign */ authenticatedAPIClient.defaults.withCredentials = true; authenticatedAPIClient.defaults.headers.common['USE-JWT-COOKIE'] = true; /* eslint-enable no-param-reassign */ }
[ "function", "applyAxiosDefaults", "(", "authenticatedAPIClient", ")", "{", "authenticatedAPIClient", ".", "defaults", ".", "withCredentials", "=", "true", ";", "authenticatedAPIClient", ".", "defaults", ".", "headers", ".", "common", "[", "'USE-JWT-COOKIE'", "]", "=", "true", ";", "}" ]
Apply default configuration options to the Axios HTTP client.
[ "Apply", "default", "configuration", "options", "to", "the", "Axios", "HTTP", "client", "." ]
e64a48d45373f299b7899a58050dcd82cb76ee55
https://github.com/edx/frontend-auth/blob/e64a48d45373f299b7899a58050dcd82cb76ee55/src/AuthenticatedAPIClient/axiosConfig.js#L13-L18
train
edx/frontend-auth
src/AuthenticatedAPIClient/axiosConfig.js
ensureCsrfToken
function ensureCsrfToken(request) { const originalRequest = request; const method = request.method.toUpperCase(); const isCsrfExempt = authenticatedAPIClient.isCsrfExempt(originalRequest.url); if (!isCsrfExempt && CSRF_PROTECTED_METHODS.includes(method)) { const url = new Url(request.url); const { protocol } = url; const { host } = url; const csrfToken = csrfTokens[host]; if (csrfToken) { request.headers[CSRF_HEADER_NAME] = csrfToken; } else { if (!queueRequests) { queueRequests = true; authenticatedAPIClient.getCsrfToken(protocol, host) .then((response) => { queueRequests = false; PubSub.publishSync(CSRF_TOKEN_REFRESH, response.data.csrfToken); }); } return new Promise((resolve) => { logInfo(`Queuing API request ${originalRequest.url} while CSRF token is retrieved`); PubSub.subscribeOnce(CSRF_TOKEN_REFRESH, (msg, token) => { logInfo(`Resolving queued API request ${originalRequest.url}`); csrfTokens[host] = token; originalRequest.headers[CSRF_HEADER_NAME] = token; resolve(originalRequest); }); }); } } return request; }
javascript
function ensureCsrfToken(request) { const originalRequest = request; const method = request.method.toUpperCase(); const isCsrfExempt = authenticatedAPIClient.isCsrfExempt(originalRequest.url); if (!isCsrfExempt && CSRF_PROTECTED_METHODS.includes(method)) { const url = new Url(request.url); const { protocol } = url; const { host } = url; const csrfToken = csrfTokens[host]; if (csrfToken) { request.headers[CSRF_HEADER_NAME] = csrfToken; } else { if (!queueRequests) { queueRequests = true; authenticatedAPIClient.getCsrfToken(protocol, host) .then((response) => { queueRequests = false; PubSub.publishSync(CSRF_TOKEN_REFRESH, response.data.csrfToken); }); } return new Promise((resolve) => { logInfo(`Queuing API request ${originalRequest.url} while CSRF token is retrieved`); PubSub.subscribeOnce(CSRF_TOKEN_REFRESH, (msg, token) => { logInfo(`Resolving queued API request ${originalRequest.url}`); csrfTokens[host] = token; originalRequest.headers[CSRF_HEADER_NAME] = token; resolve(originalRequest); }); }); } } return request; }
[ "function", "ensureCsrfToken", "(", "request", ")", "{", "const", "originalRequest", "=", "request", ";", "const", "method", "=", "request", ".", "method", ".", "toUpperCase", "(", ")", ";", "const", "isCsrfExempt", "=", "authenticatedAPIClient", ".", "isCsrfExempt", "(", "originalRequest", ".", "url", ")", ";", "if", "(", "!", "isCsrfExempt", "&&", "CSRF_PROTECTED_METHODS", ".", "includes", "(", "method", ")", ")", "{", "const", "url", "=", "new", "Url", "(", "request", ".", "url", ")", ";", "const", "{", "protocol", "}", "=", "url", ";", "const", "{", "host", "}", "=", "url", ";", "const", "csrfToken", "=", "csrfTokens", "[", "host", "]", ";", "if", "(", "csrfToken", ")", "{", "request", ".", "headers", "[", "CSRF_HEADER_NAME", "]", "=", "csrfToken", ";", "}", "else", "{", "if", "(", "!", "queueRequests", ")", "{", "queueRequests", "=", "true", ";", "authenticatedAPIClient", ".", "getCsrfToken", "(", "protocol", ",", "host", ")", ".", "then", "(", "(", "response", ")", "=>", "{", "queueRequests", "=", "false", ";", "PubSub", ".", "publishSync", "(", "CSRF_TOKEN_REFRESH", ",", "response", ".", "data", ".", "csrfToken", ")", ";", "}", ")", ";", "}", "return", "new", "Promise", "(", "(", "resolve", ")", "=>", "{", "logInfo", "(", "`", "${", "originalRequest", ".", "url", "}", "`", ")", ";", "PubSub", ".", "subscribeOnce", "(", "CSRF_TOKEN_REFRESH", ",", "(", "msg", ",", "token", ")", "=>", "{", "logInfo", "(", "`", "${", "originalRequest", ".", "url", "}", "`", ")", ";", "csrfTokens", "[", "host", "]", "=", "token", ";", "originalRequest", ".", "headers", "[", "CSRF_HEADER_NAME", "]", "=", "token", ";", "resolve", "(", "originalRequest", ")", ";", "}", ")", ";", "}", ")", ";", "}", "}", "return", "request", ";", "}" ]
Ensure we have a CSRF token header when making POST, PUT, and DELETE requests.
[ "Ensure", "we", "have", "a", "CSRF", "token", "header", "when", "making", "POST", "PUT", "and", "DELETE", "requests", "." ]
e64a48d45373f299b7899a58050dcd82cb76ee55
https://github.com/edx/frontend-auth/blob/e64a48d45373f299b7899a58050dcd82cb76ee55/src/AuthenticatedAPIClient/axiosConfig.js#L25-L58
train
edx/frontend-auth
src/AuthenticatedAPIClient/axiosConfig.js
ensureValidJWTCookie
function ensureValidJWTCookie(request) { const originalRequest = request; const isAuthUrl = authenticatedAPIClient.isAuthUrl(originalRequest.url); const accessToken = authenticatedAPIClient.getDecodedAccessToken(); const tokenExpired = authenticatedAPIClient.isAccessTokenExpired(accessToken); if (isAuthUrl || !tokenExpired) { return request; } if (!queueRequests) { queueRequests = true; authenticatedAPIClient.refreshAccessToken() .then(() => { queueRequests = false; PubSub.publishSync(ACCESS_TOKEN_REFRESH, { success: true }); }) .catch((error) => { // If no callback is supplied frontend-auth will (ultimately) redirect the user to login. // The user is redirected to logout to ensure authentication clean-up, which in turn // redirects to login. if (authenticatedAPIClient.handleRefreshAccessTokenFailure) { authenticatedAPIClient.handleRefreshAccessTokenFailure(error); } else { authenticatedAPIClient.logout(); } PubSub.publishSync(ACCESS_TOKEN_REFRESH, { success: false }); }); } return new Promise((resolve, reject) => { logInfo(`Queuing API request ${originalRequest.url} while access token is refreshed`); PubSub.subscribeOnce(ACCESS_TOKEN_REFRESH, (msg, { success }) => { if (success) { logInfo(`Resolving queued API request ${originalRequest.url}`); resolve(originalRequest); } else { reject(originalRequest); } }); }); }
javascript
function ensureValidJWTCookie(request) { const originalRequest = request; const isAuthUrl = authenticatedAPIClient.isAuthUrl(originalRequest.url); const accessToken = authenticatedAPIClient.getDecodedAccessToken(); const tokenExpired = authenticatedAPIClient.isAccessTokenExpired(accessToken); if (isAuthUrl || !tokenExpired) { return request; } if (!queueRequests) { queueRequests = true; authenticatedAPIClient.refreshAccessToken() .then(() => { queueRequests = false; PubSub.publishSync(ACCESS_TOKEN_REFRESH, { success: true }); }) .catch((error) => { // If no callback is supplied frontend-auth will (ultimately) redirect the user to login. // The user is redirected to logout to ensure authentication clean-up, which in turn // redirects to login. if (authenticatedAPIClient.handleRefreshAccessTokenFailure) { authenticatedAPIClient.handleRefreshAccessTokenFailure(error); } else { authenticatedAPIClient.logout(); } PubSub.publishSync(ACCESS_TOKEN_REFRESH, { success: false }); }); } return new Promise((resolve, reject) => { logInfo(`Queuing API request ${originalRequest.url} while access token is refreshed`); PubSub.subscribeOnce(ACCESS_TOKEN_REFRESH, (msg, { success }) => { if (success) { logInfo(`Resolving queued API request ${originalRequest.url}`); resolve(originalRequest); } else { reject(originalRequest); } }); }); }
[ "function", "ensureValidJWTCookie", "(", "request", ")", "{", "const", "originalRequest", "=", "request", ";", "const", "isAuthUrl", "=", "authenticatedAPIClient", ".", "isAuthUrl", "(", "originalRequest", ".", "url", ")", ";", "const", "accessToken", "=", "authenticatedAPIClient", ".", "getDecodedAccessToken", "(", ")", ";", "const", "tokenExpired", "=", "authenticatedAPIClient", ".", "isAccessTokenExpired", "(", "accessToken", ")", ";", "if", "(", "isAuthUrl", "||", "!", "tokenExpired", ")", "{", "return", "request", ";", "}", "if", "(", "!", "queueRequests", ")", "{", "queueRequests", "=", "true", ";", "authenticatedAPIClient", ".", "refreshAccessToken", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "queueRequests", "=", "false", ";", "PubSub", ".", "publishSync", "(", "ACCESS_TOKEN_REFRESH", ",", "{", "success", ":", "true", "}", ")", ";", "}", ")", ".", "catch", "(", "(", "error", ")", "=>", "{", "if", "(", "authenticatedAPIClient", ".", "handleRefreshAccessTokenFailure", ")", "{", "authenticatedAPIClient", ".", "handleRefreshAccessTokenFailure", "(", "error", ")", ";", "}", "else", "{", "authenticatedAPIClient", ".", "logout", "(", ")", ";", "}", "PubSub", ".", "publishSync", "(", "ACCESS_TOKEN_REFRESH", ",", "{", "success", ":", "false", "}", ")", ";", "}", ")", ";", "}", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "logInfo", "(", "`", "${", "originalRequest", ".", "url", "}", "`", ")", ";", "PubSub", ".", "subscribeOnce", "(", "ACCESS_TOKEN_REFRESH", ",", "(", "msg", ",", "{", "success", "}", ")", "=>", "{", "if", "(", "success", ")", "{", "logInfo", "(", "`", "${", "originalRequest", ".", "url", "}", "`", ")", ";", "resolve", "(", "originalRequest", ")", ";", "}", "else", "{", "reject", "(", "originalRequest", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Ensure the browser has an unexpired JWT cookie before making API requests. This will attempt to refresh the JWT cookie if a valid refresh token cookie exists.
[ "Ensure", "the", "browser", "has", "an", "unexpired", "JWT", "cookie", "before", "making", "API", "requests", "." ]
e64a48d45373f299b7899a58050dcd82cb76ee55
https://github.com/edx/frontend-auth/blob/e64a48d45373f299b7899a58050dcd82cb76ee55/src/AuthenticatedAPIClient/axiosConfig.js#L65-L105
train
edx/frontend-auth
src/AuthenticatedAPIClient/axiosConfig.js
handleUnauthorizedAPIResponse
function handleUnauthorizedAPIResponse(error) { const response = error && error.response; const errorStatus = response && response.status; const requestUrl = response && response.config && response.config.url; const requestIsTokenRefresh = requestUrl === authenticatedAPIClient.refreshAccessTokenEndpoint; switch (errorStatus) { // eslint-disable-line default-case case 401: if (requestIsTokenRefresh) { logInfo(`Unauthorized token refresh response from ${requestUrl}. This is expected if the user is not yet logged in.`); } else { logInfo(`Unauthorized API response from ${requestUrl}`); } break; case 403: logInfo(`Forbidden API response from ${requestUrl}`); break; } return Promise.reject(error); }
javascript
function handleUnauthorizedAPIResponse(error) { const response = error && error.response; const errorStatus = response && response.status; const requestUrl = response && response.config && response.config.url; const requestIsTokenRefresh = requestUrl === authenticatedAPIClient.refreshAccessTokenEndpoint; switch (errorStatus) { // eslint-disable-line default-case case 401: if (requestIsTokenRefresh) { logInfo(`Unauthorized token refresh response from ${requestUrl}. This is expected if the user is not yet logged in.`); } else { logInfo(`Unauthorized API response from ${requestUrl}`); } break; case 403: logInfo(`Forbidden API response from ${requestUrl}`); break; } return Promise.reject(error); }
[ "function", "handleUnauthorizedAPIResponse", "(", "error", ")", "{", "const", "response", "=", "error", "&&", "error", ".", "response", ";", "const", "errorStatus", "=", "response", "&&", "response", ".", "status", ";", "const", "requestUrl", "=", "response", "&&", "response", ".", "config", "&&", "response", ".", "config", ".", "url", ";", "const", "requestIsTokenRefresh", "=", "requestUrl", "===", "authenticatedAPIClient", ".", "refreshAccessTokenEndpoint", ";", "switch", "(", "errorStatus", ")", "{", "case", "401", ":", "if", "(", "requestIsTokenRefresh", ")", "{", "logInfo", "(", "`", "${", "requestUrl", "}", "`", ")", ";", "}", "else", "{", "logInfo", "(", "`", "${", "requestUrl", "}", "`", ")", ";", "}", "break", ";", "case", "403", ":", "logInfo", "(", "`", "${", "requestUrl", "}", "`", ")", ";", "break", ";", "}", "return", "Promise", ".", "reject", "(", "error", ")", ";", "}" ]
Log errors and info for unauthorized API responses
[ "Log", "errors", "and", "info", "for", "unauthorized", "API", "responses" ]
e64a48d45373f299b7899a58050dcd82cb76ee55
https://github.com/edx/frontend-auth/blob/e64a48d45373f299b7899a58050dcd82cb76ee55/src/AuthenticatedAPIClient/axiosConfig.js#L108-L128
train
PerimeterX/perimeterx-node-core
lib/pxapi.js
callServer
function callServer(ctx, config, callback) { const ip = ctx.ip; const fullUrl = ctx.fullUrl; const vid = ctx.vid || ''; const pxhd = ctx.pxhd || ''; const vidSource = ctx.vidSource || ''; const uuid = ctx.uuid || ''; const uri = ctx.uri || '/'; const headers = pxUtil.formatHeaders(ctx.headers, config.SENSITIVE_HEADERS); const httpVersion = ctx.httpVersion; const riskMode = config.MODULE_MODE === config.MONITOR_MODE.MONITOR ? 'monitor' : 'active_blocking'; const data = { request: { ip: ip, headers: headers, url: fullUrl, uri: uri, firstParty: config.FIRST_PARTY_ENABLED }, additional: { s2s_call_reason: ctx.s2sCallReason, http_version: httpVersion, http_method: ctx.httpMethod, risk_mode: riskMode, module_version: config.MODULE_VERSION, cookie_origin: ctx.cookieOrigin, request_cookie_names: ctx.requestCookieNames } }; if (ctx.s2sCallReason === 'cookie_decryption_failed') { data.additional.px_orig_cookie = ctx.getCookie(); //No need strigify, already a string } if (ctx.s2sCallReason === 'cookie_expired' || ctx.s2sCallReason === 'cookie_validation_failed') { data.additional.px_cookie = JSON.stringify(ctx.decodedCookie); } pxUtil.prepareCustomParams(config, data.additional); const reqHeaders = { Authorization: 'Bearer ' + config.AUTH_TOKEN, 'Content-Type': 'application/json' }; if (vid) { data.vid = vid; } if (uuid) { data.uuid = uuid; } if (pxhd) { data.pxhd = pxhd; } if (vidSource) { data.vid_source = vidSource; } if (pxhd && data.additional.s2s_call_reason === 'no_cookie') { data.additional.s2s_call_reason = 'no_cookie_w_vid'; } if (ctx.originalUuid) { data.additional['original_uuid'] = ctx.originalUuid; } if (ctx.originalTokenError) { data.additional['original_token_error'] = ctx.originalTokenError; } if (ctx.originalToken) { data.additional['original_token'] = ctx.originalToken; } if (ctx.decodedOriginalToken) { data.additional['px_decoded_original_token'] = ctx.decodedOriginalToken; } if(ctx.hmac) { data.additional['px_cookie_hmac'] = ctx.hmac; } ctx.hasMadeServerCall = true; return pxHttpc.callServer(data, reqHeaders, config.SERVER_TO_SERVER_API_URI, 'query', config, callback); }
javascript
function callServer(ctx, config, callback) { const ip = ctx.ip; const fullUrl = ctx.fullUrl; const vid = ctx.vid || ''; const pxhd = ctx.pxhd || ''; const vidSource = ctx.vidSource || ''; const uuid = ctx.uuid || ''; const uri = ctx.uri || '/'; const headers = pxUtil.formatHeaders(ctx.headers, config.SENSITIVE_HEADERS); const httpVersion = ctx.httpVersion; const riskMode = config.MODULE_MODE === config.MONITOR_MODE.MONITOR ? 'monitor' : 'active_blocking'; const data = { request: { ip: ip, headers: headers, url: fullUrl, uri: uri, firstParty: config.FIRST_PARTY_ENABLED }, additional: { s2s_call_reason: ctx.s2sCallReason, http_version: httpVersion, http_method: ctx.httpMethod, risk_mode: riskMode, module_version: config.MODULE_VERSION, cookie_origin: ctx.cookieOrigin, request_cookie_names: ctx.requestCookieNames } }; if (ctx.s2sCallReason === 'cookie_decryption_failed') { data.additional.px_orig_cookie = ctx.getCookie(); //No need strigify, already a string } if (ctx.s2sCallReason === 'cookie_expired' || ctx.s2sCallReason === 'cookie_validation_failed') { data.additional.px_cookie = JSON.stringify(ctx.decodedCookie); } pxUtil.prepareCustomParams(config, data.additional); const reqHeaders = { Authorization: 'Bearer ' + config.AUTH_TOKEN, 'Content-Type': 'application/json' }; if (vid) { data.vid = vid; } if (uuid) { data.uuid = uuid; } if (pxhd) { data.pxhd = pxhd; } if (vidSource) { data.vid_source = vidSource; } if (pxhd && data.additional.s2s_call_reason === 'no_cookie') { data.additional.s2s_call_reason = 'no_cookie_w_vid'; } if (ctx.originalUuid) { data.additional['original_uuid'] = ctx.originalUuid; } if (ctx.originalTokenError) { data.additional['original_token_error'] = ctx.originalTokenError; } if (ctx.originalToken) { data.additional['original_token'] = ctx.originalToken; } if (ctx.decodedOriginalToken) { data.additional['px_decoded_original_token'] = ctx.decodedOriginalToken; } if(ctx.hmac) { data.additional['px_cookie_hmac'] = ctx.hmac; } ctx.hasMadeServerCall = true; return pxHttpc.callServer(data, reqHeaders, config.SERVER_TO_SERVER_API_URI, 'query', config, callback); }
[ "function", "callServer", "(", "ctx", ",", "config", ",", "callback", ")", "{", "const", "ip", "=", "ctx", ".", "ip", ";", "const", "fullUrl", "=", "ctx", ".", "fullUrl", ";", "const", "vid", "=", "ctx", ".", "vid", "||", "''", ";", "const", "pxhd", "=", "ctx", ".", "pxhd", "||", "''", ";", "const", "vidSource", "=", "ctx", ".", "vidSource", "||", "''", ";", "const", "uuid", "=", "ctx", ".", "uuid", "||", "''", ";", "const", "uri", "=", "ctx", ".", "uri", "||", "'/'", ";", "const", "headers", "=", "pxUtil", ".", "formatHeaders", "(", "ctx", ".", "headers", ",", "config", ".", "SENSITIVE_HEADERS", ")", ";", "const", "httpVersion", "=", "ctx", ".", "httpVersion", ";", "const", "riskMode", "=", "config", ".", "MODULE_MODE", "===", "config", ".", "MONITOR_MODE", ".", "MONITOR", "?", "'monitor'", ":", "'active_blocking'", ";", "const", "data", "=", "{", "request", ":", "{", "ip", ":", "ip", ",", "headers", ":", "headers", ",", "url", ":", "fullUrl", ",", "uri", ":", "uri", ",", "firstParty", ":", "config", ".", "FIRST_PARTY_ENABLED", "}", ",", "additional", ":", "{", "s2s_call_reason", ":", "ctx", ".", "s2sCallReason", ",", "http_version", ":", "httpVersion", ",", "http_method", ":", "ctx", ".", "httpMethod", ",", "risk_mode", ":", "riskMode", ",", "module_version", ":", "config", ".", "MODULE_VERSION", ",", "cookie_origin", ":", "ctx", ".", "cookieOrigin", ",", "request_cookie_names", ":", "ctx", ".", "requestCookieNames", "}", "}", ";", "if", "(", "ctx", ".", "s2sCallReason", "===", "'cookie_decryption_failed'", ")", "{", "data", ".", "additional", ".", "px_orig_cookie", "=", "ctx", ".", "getCookie", "(", ")", ";", "}", "if", "(", "ctx", ".", "s2sCallReason", "===", "'cookie_expired'", "||", "ctx", ".", "s2sCallReason", "===", "'cookie_validation_failed'", ")", "{", "data", ".", "additional", ".", "px_cookie", "=", "JSON", ".", "stringify", "(", "ctx", ".", "decodedCookie", ")", ";", "}", "pxUtil", ".", "prepareCustomParams", "(", "config", ",", "data", ".", "additional", ")", ";", "const", "reqHeaders", "=", "{", "Authorization", ":", "'Bearer '", "+", "config", ".", "AUTH_TOKEN", ",", "'Content-Type'", ":", "'application/json'", "}", ";", "if", "(", "vid", ")", "{", "data", ".", "vid", "=", "vid", ";", "}", "if", "(", "uuid", ")", "{", "data", ".", "uuid", "=", "uuid", ";", "}", "if", "(", "pxhd", ")", "{", "data", ".", "pxhd", "=", "pxhd", ";", "}", "if", "(", "vidSource", ")", "{", "data", ".", "vid_source", "=", "vidSource", ";", "}", "if", "(", "pxhd", "&&", "data", ".", "additional", ".", "s2s_call_reason", "===", "'no_cookie'", ")", "{", "data", ".", "additional", ".", "s2s_call_reason", "=", "'no_cookie_w_vid'", ";", "}", "if", "(", "ctx", ".", "originalUuid", ")", "{", "data", ".", "additional", "[", "'original_uuid'", "]", "=", "ctx", ".", "originalUuid", ";", "}", "if", "(", "ctx", ".", "originalTokenError", ")", "{", "data", ".", "additional", "[", "'original_token_error'", "]", "=", "ctx", ".", "originalTokenError", ";", "}", "if", "(", "ctx", ".", "originalToken", ")", "{", "data", ".", "additional", "[", "'original_token'", "]", "=", "ctx", ".", "originalToken", ";", "}", "if", "(", "ctx", ".", "decodedOriginalToken", ")", "{", "data", ".", "additional", "[", "'px_decoded_original_token'", "]", "=", "ctx", ".", "decodedOriginalToken", ";", "}", "if", "(", "ctx", ".", "hmac", ")", "{", "data", ".", "additional", "[", "'px_cookie_hmac'", "]", "=", "ctx", ".", "hmac", ";", "}", "ctx", ".", "hasMadeServerCall", "=", "true", ";", "return", "pxHttpc", ".", "callServer", "(", "data", ",", "reqHeaders", ",", "config", ".", "SERVER_TO_SERVER_API_URI", ",", "'query'", ",", "config", ",", "callback", ")", ";", "}" ]
callServer - call the perimeterx api server to receive a score for a given user. @param {Object} ctx - current request context @param {Function} callback - callback function.
[ "callServer", "-", "call", "the", "perimeterx", "api", "server", "to", "receive", "a", "score", "for", "a", "given", "user", "." ]
281815ffe8913ffdd0916ed507323c88e29f3896
https://github.com/PerimeterX/perimeterx-node-core/blob/281815ffe8913ffdd0916ed507323c88e29f3896/lib/pxapi.js#L13-L96
train
PerimeterX/perimeterx-node-core
lib/pxapi.js
evalByServerCall
function evalByServerCall(ctx, config, callback) { if (!ctx.ip || !ctx.headers) { config.logger.error('perimeterx score evaluation failed. bad parameters.'); return callback(config.SCORE_EVALUATE_ACTION.UNEXPECTED_RESULT); } config.logger.debug(`Evaluating Risk API request, call reason: ${ctx.s2sCallReason}`); callServer(ctx, config, (err, res) => { if (err) { if (err === 'timeout') { ctx.passReason = config.PASS_REASON.S2S_TIMEOUT; return callback(config.SCORE_EVALUATE_ACTION.S2S_TIMEOUT_PASS); } config.logger.error(`Unexpected exception while evaluating Risk API. ${err}`); ctx.passReason = config.PASS_REASON.REQUEST_FAILED; return callback(config.SCORE_EVALUATE_ACTION.UNEXPECTED_RESULT); } ctx.pxhd = res.pxhd; const action = isBadRiskScore(res, ctx, config); /* score response invalid - pass traffic */ if (action === -1) { config.logger.error('perimeterx server query response is invalid'); return callback(config.SCORE_EVALUATE_ACTION.UNEXPECTED_RESULT); } /* score did not cross threshold - pass traffic */ if (action === 1) { return callback(config.SCORE_EVALUATE_ACTION.GOOD_SCORE); } /* score crossed threshold - block traffic */ if (action === 0) { ctx.uuid = res.uuid || ''; return callback(config.SCORE_EVALUATE_ACTION.BAD_SCORE); } /* This shouldn't be called - if it did - we pass the traffic */ return callback(config.SCORE_EVALUATE_ACTION.UNEXPECTED_RESULT); }); }
javascript
function evalByServerCall(ctx, config, callback) { if (!ctx.ip || !ctx.headers) { config.logger.error('perimeterx score evaluation failed. bad parameters.'); return callback(config.SCORE_EVALUATE_ACTION.UNEXPECTED_RESULT); } config.logger.debug(`Evaluating Risk API request, call reason: ${ctx.s2sCallReason}`); callServer(ctx, config, (err, res) => { if (err) { if (err === 'timeout') { ctx.passReason = config.PASS_REASON.S2S_TIMEOUT; return callback(config.SCORE_EVALUATE_ACTION.S2S_TIMEOUT_PASS); } config.logger.error(`Unexpected exception while evaluating Risk API. ${err}`); ctx.passReason = config.PASS_REASON.REQUEST_FAILED; return callback(config.SCORE_EVALUATE_ACTION.UNEXPECTED_RESULT); } ctx.pxhd = res.pxhd; const action = isBadRiskScore(res, ctx, config); /* score response invalid - pass traffic */ if (action === -1) { config.logger.error('perimeterx server query response is invalid'); return callback(config.SCORE_EVALUATE_ACTION.UNEXPECTED_RESULT); } /* score did not cross threshold - pass traffic */ if (action === 1) { return callback(config.SCORE_EVALUATE_ACTION.GOOD_SCORE); } /* score crossed threshold - block traffic */ if (action === 0) { ctx.uuid = res.uuid || ''; return callback(config.SCORE_EVALUATE_ACTION.BAD_SCORE); } /* This shouldn't be called - if it did - we pass the traffic */ return callback(config.SCORE_EVALUATE_ACTION.UNEXPECTED_RESULT); }); }
[ "function", "evalByServerCall", "(", "ctx", ",", "config", ",", "callback", ")", "{", "if", "(", "!", "ctx", ".", "ip", "||", "!", "ctx", ".", "headers", ")", "{", "config", ".", "logger", ".", "error", "(", "'perimeterx score evaluation failed. bad parameters.'", ")", ";", "return", "callback", "(", "config", ".", "SCORE_EVALUATE_ACTION", ".", "UNEXPECTED_RESULT", ")", ";", "}", "config", ".", "logger", ".", "debug", "(", "`", "${", "ctx", ".", "s2sCallReason", "}", "`", ")", ";", "callServer", "(", "ctx", ",", "config", ",", "(", "err", ",", "res", ")", "=>", "{", "if", "(", "err", ")", "{", "if", "(", "err", "===", "'timeout'", ")", "{", "ctx", ".", "passReason", "=", "config", ".", "PASS_REASON", ".", "S2S_TIMEOUT", ";", "return", "callback", "(", "config", ".", "SCORE_EVALUATE_ACTION", ".", "S2S_TIMEOUT_PASS", ")", ";", "}", "config", ".", "logger", ".", "error", "(", "`", "${", "err", "}", "`", ")", ";", "ctx", ".", "passReason", "=", "config", ".", "PASS_REASON", ".", "REQUEST_FAILED", ";", "return", "callback", "(", "config", ".", "SCORE_EVALUATE_ACTION", ".", "UNEXPECTED_RESULT", ")", ";", "}", "ctx", ".", "pxhd", "=", "res", ".", "pxhd", ";", "const", "action", "=", "isBadRiskScore", "(", "res", ",", "ctx", ",", "config", ")", ";", "if", "(", "action", "===", "-", "1", ")", "{", "config", ".", "logger", ".", "error", "(", "'perimeterx server query response is invalid'", ")", ";", "return", "callback", "(", "config", ".", "SCORE_EVALUATE_ACTION", ".", "UNEXPECTED_RESULT", ")", ";", "}", "if", "(", "action", "===", "1", ")", "{", "return", "callback", "(", "config", ".", "SCORE_EVALUATE_ACTION", ".", "GOOD_SCORE", ")", ";", "}", "if", "(", "action", "===", "0", ")", "{", "ctx", ".", "uuid", "=", "res", ".", "uuid", "||", "''", ";", "return", "callback", "(", "config", ".", "SCORE_EVALUATE_ACTION", ".", "BAD_SCORE", ")", ";", "}", "return", "callback", "(", "config", ".", "SCORE_EVALUATE_ACTION", ".", "UNEXPECTED_RESULT", ")", ";", "}", ")", ";", "}" ]
evalByServerCall - main server to server function, execute a server call for score and process its value to make blocking decisions. ' @param {Object} ctx - current request context. @param {Function} callback - callback function.
[ "evalByServerCall", "-", "main", "server", "to", "server", "function", "execute", "a", "server", "call", "for", "score", "and", "process", "its", "value", "to", "make", "blocking", "decisions", "." ]
281815ffe8913ffdd0916ed507323c88e29f3896
https://github.com/PerimeterX/perimeterx-node-core/blob/281815ffe8913ffdd0916ed507323c88e29f3896/lib/pxapi.js#L104-L142
train
PerimeterX/perimeterx-node-core
lib/pxapi.js
isBadRiskScore
function isBadRiskScore(res, ctx, config) { if (!res || !pxUtil.verifyDefined(res.score) || !res.action) { ctx.passReason = config.PASS_REASON.INVALID_RESPONSE; return -1; } const score = res.score; ctx.score = score; ctx.uuid = res.uuid; if (score >= config.BLOCKING_SCORE) { ctx.blockAction = res.action; if (res.action === 'j' && res.action_data && res.action_data.body) { ctx.blockActionData = res.action_data.body; } return 0; } else { ctx.passReason = config.PASS_REASON.S2S; return 1; } }
javascript
function isBadRiskScore(res, ctx, config) { if (!res || !pxUtil.verifyDefined(res.score) || !res.action) { ctx.passReason = config.PASS_REASON.INVALID_RESPONSE; return -1; } const score = res.score; ctx.score = score; ctx.uuid = res.uuid; if (score >= config.BLOCKING_SCORE) { ctx.blockAction = res.action; if (res.action === 'j' && res.action_data && res.action_data.body) { ctx.blockActionData = res.action_data.body; } return 0; } else { ctx.passReason = config.PASS_REASON.S2S; return 1; } }
[ "function", "isBadRiskScore", "(", "res", ",", "ctx", ",", "config", ")", "{", "if", "(", "!", "res", "||", "!", "pxUtil", ".", "verifyDefined", "(", "res", ".", "score", ")", "||", "!", "res", ".", "action", ")", "{", "ctx", ".", "passReason", "=", "config", ".", "PASS_REASON", ".", "INVALID_RESPONSE", ";", "return", "-", "1", ";", "}", "const", "score", "=", "res", ".", "score", ";", "ctx", ".", "score", "=", "score", ";", "ctx", ".", "uuid", "=", "res", ".", "uuid", ";", "if", "(", "score", ">=", "config", ".", "BLOCKING_SCORE", ")", "{", "ctx", ".", "blockAction", "=", "res", ".", "action", ";", "if", "(", "res", ".", "action", "===", "'j'", "&&", "res", ".", "action_data", "&&", "res", ".", "action_data", ".", "body", ")", "{", "ctx", ".", "blockActionData", "=", "res", ".", "action_data", ".", "body", ";", "}", "return", "0", ";", "}", "else", "{", "ctx", ".", "passReason", "=", "config", ".", "PASS_REASON", ".", "S2S", ";", "return", "1", ";", "}", "}" ]
isBadRiskScore - processing response score and return a block indicator. @param {object} res - perimeterx response object. @param {object} ctx - current request context. @return {Number} indicator to the validity of the cookie. -1 response object is not valid 0 response valid with bad score 1 response valid with good score
[ "isBadRiskScore", "-", "processing", "response", "score", "and", "return", "a", "block", "indicator", "." ]
281815ffe8913ffdd0916ed507323c88e29f3896
https://github.com/PerimeterX/perimeterx-node-core/blob/281815ffe8913ffdd0916ed507323c88e29f3896/lib/pxapi.js#L156-L174
train
PerimeterX/perimeterx-node-core
lib/pxcookie.js
pxCookieFactory
function pxCookieFactory(ctx, config) { if (ctx.cookieOrigin === 'cookie') { return (ctx.cookies['_px3'] ? new CookieV3(ctx, config, config.logger) : new CookieV1(ctx, config, config.logger)); } else { return (ctx.cookies['_px3'] ? new TokenV3(ctx, config, ctx.cookies['_px3'], config.logger) : new TokenV1(ctx, config, ctx.cookies['_px'], config.logger)); } }
javascript
function pxCookieFactory(ctx, config) { if (ctx.cookieOrigin === 'cookie') { return (ctx.cookies['_px3'] ? new CookieV3(ctx, config, config.logger) : new CookieV1(ctx, config, config.logger)); } else { return (ctx.cookies['_px3'] ? new TokenV3(ctx, config, ctx.cookies['_px3'], config.logger) : new TokenV1(ctx, config, ctx.cookies['_px'], config.logger)); } }
[ "function", "pxCookieFactory", "(", "ctx", ",", "config", ")", "{", "if", "(", "ctx", ".", "cookieOrigin", "===", "'cookie'", ")", "{", "return", "(", "ctx", ".", "cookies", "[", "'_px3'", "]", "?", "new", "CookieV3", "(", "ctx", ",", "config", ",", "config", ".", "logger", ")", ":", "new", "CookieV1", "(", "ctx", ",", "config", ",", "config", ".", "logger", ")", ")", ";", "}", "else", "{", "return", "(", "ctx", ".", "cookies", "[", "'_px3'", "]", "?", "new", "TokenV3", "(", "ctx", ",", "config", ",", "ctx", ".", "cookies", "[", "'_px3'", "]", ",", "config", ".", "logger", ")", ":", "new", "TokenV1", "(", "ctx", ",", "config", ",", "ctx", ".", "cookies", "[", "'_px'", "]", ",", "config", ".", "logger", ")", ")", ";", "}", "}" ]
Factory method for creating PX Cookie object according to cookie version and type found on the request
[ "Factory", "method", "for", "creating", "PX", "Cookie", "object", "according", "to", "cookie", "version", "and", "type", "found", "on", "the", "request" ]
281815ffe8913ffdd0916ed507323c88e29f3896
https://github.com/PerimeterX/perimeterx-node-core/blob/281815ffe8913ffdd0916ed507323c88e29f3896/lib/pxcookie.js#L98-L104
train
PerimeterX/perimeterx-node-core
lib/pxutil.js
prepareCustomParams
function prepareCustomParams(config, dict) { const customParams = { 'custom_param1': '', 'custom_param2': '', 'custom_param3': '', 'custom_param4': '', 'custom_param5': '', 'custom_param6': '', 'custom_param7': '', 'custom_param8': '', 'custom_param9': '', 'custom_param10': '' }; if (config.ENRICH_CUSTOM_PARAMETERS) { const enrichedCustomParams = config.ENRICH_CUSTOM_PARAMETERS(customParams); for (const param in enrichedCustomParams) { if (param.match(/^custom_param([1-9]|10)$/) && enrichedCustomParams[param] !== '') { dict[param] = enrichedCustomParams[param]; } } } }
javascript
function prepareCustomParams(config, dict) { const customParams = { 'custom_param1': '', 'custom_param2': '', 'custom_param3': '', 'custom_param4': '', 'custom_param5': '', 'custom_param6': '', 'custom_param7': '', 'custom_param8': '', 'custom_param9': '', 'custom_param10': '' }; if (config.ENRICH_CUSTOM_PARAMETERS) { const enrichedCustomParams = config.ENRICH_CUSTOM_PARAMETERS(customParams); for (const param in enrichedCustomParams) { if (param.match(/^custom_param([1-9]|10)$/) && enrichedCustomParams[param] !== '') { dict[param] = enrichedCustomParams[param]; } } } }
[ "function", "prepareCustomParams", "(", "config", ",", "dict", ")", "{", "const", "customParams", "=", "{", "'custom_param1'", ":", "''", ",", "'custom_param2'", ":", "''", ",", "'custom_param3'", ":", "''", ",", "'custom_param4'", ":", "''", ",", "'custom_param5'", ":", "''", ",", "'custom_param6'", ":", "''", ",", "'custom_param7'", ":", "''", ",", "'custom_param8'", ":", "''", ",", "'custom_param9'", ":", "''", ",", "'custom_param10'", ":", "''", "}", ";", "if", "(", "config", ".", "ENRICH_CUSTOM_PARAMETERS", ")", "{", "const", "enrichedCustomParams", "=", "config", ".", "ENRICH_CUSTOM_PARAMETERS", "(", "customParams", ")", ";", "for", "(", "const", "param", "in", "enrichedCustomParams", ")", "{", "if", "(", "param", ".", "match", "(", "/", "^custom_param([1-9]|10)$", "/", ")", "&&", "enrichedCustomParams", "[", "param", "]", "!==", "''", ")", "{", "dict", "[", "param", "]", "=", "enrichedCustomParams", "[", "param", "]", ";", "}", "}", "}", "}" ]
prepareCustomParams - if there's a enrich custom params handler configured on startup, it will populate to @dict with the proper custom params @param {pxconfig} config - The config object of the application @param {object} dict - the object that should be populated with the custom params
[ "prepareCustomParams", "-", "if", "there", "s", "a", "enrich", "custom", "params", "handler", "configured", "on", "startup", "it", "will", "populate", "to" ]
281815ffe8913ffdd0916ed507323c88e29f3896
https://github.com/PerimeterX/perimeterx-node-core/blob/281815ffe8913ffdd0916ed507323c88e29f3896/lib/pxutil.js#L143-L164
train
PerimeterX/perimeterx-node-core
lib/pxproxy.js
getCaptcha
function getCaptcha(req, config, ip, reversePrefix, cb) { let res = {}; if (!config.FIRST_PARTY_ENABLED) { res = { status: 200, header: {key: 'Content-Type', value:'application/javascript'}, body: '' }; return cb(null, res); } else { const searchMask = `/${reversePrefix}${config.FIRST_PARTY_CAPTCHA_PATH}`; const regEx = new RegExp(searchMask, 'ig'); const pxRequestUri = `/${config.PX_APP_ID}${req.originalUrl.replace(regEx, '')}`; config.logger.debug(`Forwarding request from ${req.originalUrl} to xhr at ${config.CAPTCHA_HOST}${pxRequestUri}`); const callData = { url: `https://${config.CAPTCHA_HOST}${pxRequestUri}`, headers: pxUtil.filterSensitiveHeaders(req.headers, config.SENSITIVE_HEADERS), timeout: config.API_TIMEOUT_MS }; callData.headers['host'] = config.CAPTCHA_HOST; callData.headers[config.ENFORCER_TRUE_IP_HEADER] = ip; callData.headers[config.FIRST_PARTY_HEADER] = 1; request.get(callData, config, (error, response) => { if (error || !response) { config.logger.error(`Error while fetching first party captcha: ${error}`); } response = response || {statusCode: 200, headers: {}}; res = { status: response.statusCode, headers: response.headers, body: response.body || '' }; return cb(null, res); }); } return; }
javascript
function getCaptcha(req, config, ip, reversePrefix, cb) { let res = {}; if (!config.FIRST_PARTY_ENABLED) { res = { status: 200, header: {key: 'Content-Type', value:'application/javascript'}, body: '' }; return cb(null, res); } else { const searchMask = `/${reversePrefix}${config.FIRST_PARTY_CAPTCHA_PATH}`; const regEx = new RegExp(searchMask, 'ig'); const pxRequestUri = `/${config.PX_APP_ID}${req.originalUrl.replace(regEx, '')}`; config.logger.debug(`Forwarding request from ${req.originalUrl} to xhr at ${config.CAPTCHA_HOST}${pxRequestUri}`); const callData = { url: `https://${config.CAPTCHA_HOST}${pxRequestUri}`, headers: pxUtil.filterSensitiveHeaders(req.headers, config.SENSITIVE_HEADERS), timeout: config.API_TIMEOUT_MS }; callData.headers['host'] = config.CAPTCHA_HOST; callData.headers[config.ENFORCER_TRUE_IP_HEADER] = ip; callData.headers[config.FIRST_PARTY_HEADER] = 1; request.get(callData, config, (error, response) => { if (error || !response) { config.logger.error(`Error while fetching first party captcha: ${error}`); } response = response || {statusCode: 200, headers: {}}; res = { status: response.statusCode, headers: response.headers, body: response.body || '' }; return cb(null, res); }); } return; }
[ "function", "getCaptcha", "(", "req", ",", "config", ",", "ip", ",", "reversePrefix", ",", "cb", ")", "{", "let", "res", "=", "{", "}", ";", "if", "(", "!", "config", ".", "FIRST_PARTY_ENABLED", ")", "{", "res", "=", "{", "status", ":", "200", ",", "header", ":", "{", "key", ":", "'Content-Type'", ",", "value", ":", "'application/javascript'", "}", ",", "body", ":", "''", "}", ";", "return", "cb", "(", "null", ",", "res", ")", ";", "}", "else", "{", "const", "searchMask", "=", "`", "${", "reversePrefix", "}", "${", "config", ".", "FIRST_PARTY_CAPTCHA_PATH", "}", "`", ";", "const", "regEx", "=", "new", "RegExp", "(", "searchMask", ",", "'ig'", ")", ";", "const", "pxRequestUri", "=", "`", "${", "config", ".", "PX_APP_ID", "}", "${", "req", ".", "originalUrl", ".", "replace", "(", "regEx", ",", "''", ")", "}", "`", ";", "config", ".", "logger", ".", "debug", "(", "`", "${", "req", ".", "originalUrl", "}", "${", "config", ".", "CAPTCHA_HOST", "}", "${", "pxRequestUri", "}", "`", ")", ";", "const", "callData", "=", "{", "url", ":", "`", "${", "config", ".", "CAPTCHA_HOST", "}", "${", "pxRequestUri", "}", "`", ",", "headers", ":", "pxUtil", ".", "filterSensitiveHeaders", "(", "req", ".", "headers", ",", "config", ".", "SENSITIVE_HEADERS", ")", ",", "timeout", ":", "config", ".", "API_TIMEOUT_MS", "}", ";", "callData", ".", "headers", "[", "'host'", "]", "=", "config", ".", "CAPTCHA_HOST", ";", "callData", ".", "headers", "[", "config", ".", "ENFORCER_TRUE_IP_HEADER", "]", "=", "ip", ";", "callData", ".", "headers", "[", "config", ".", "FIRST_PARTY_HEADER", "]", "=", "1", ";", "request", ".", "get", "(", "callData", ",", "config", ",", "(", "error", ",", "response", ")", "=>", "{", "if", "(", "error", "||", "!", "response", ")", "{", "config", ".", "logger", ".", "error", "(", "`", "${", "error", "}", "`", ")", ";", "}", "response", "=", "response", "||", "{", "statusCode", ":", "200", ",", "headers", ":", "{", "}", "}", ";", "res", "=", "{", "status", ":", "response", ".", "statusCode", ",", "headers", ":", "response", ".", "headers", ",", "body", ":", "response", ".", "body", "||", "''", "}", ";", "return", "cb", "(", "null", ",", "res", ")", ";", "}", ")", ";", "}", "return", ";", "}" ]
getClient - process the proxy request to get the captcha script file from PX servers. @param {object} req - the request object. @param {object} config - the PerimeterX config object. @param {string} ip - the ip that initiated the call. @param {string} reversePrefix - the prefix of the xhr request. @param {function} cb - the callback function to call at the end of the process. @return {function} the callback function passed as param with the server response (captcha file) or error.
[ "getClient", "-", "process", "the", "proxy", "request", "to", "get", "the", "captcha", "script", "file", "from", "PX", "servers", "." ]
281815ffe8913ffdd0916ed507323c88e29f3896
https://github.com/PerimeterX/perimeterx-node-core/blob/281815ffe8913ffdd0916ed507323c88e29f3896/lib/pxproxy.js#L18-L55
train
PerimeterX/perimeterx-node-core
lib/pxproxy.js
getClient
function getClient(req, config, ip, cb) { let res = {}; if (!config.FIRST_PARTY_ENABLED) { res = { status: 200, header: {key: 'Content-Type', value:'application/javascript'}, body: '' }; return cb(null, res); } else { const clientRequestUri = `/${config.PX_APP_ID}/main.min.js`; config.logger.debug(`Forwarding request from ${req.originalUrl.toLowerCase()} to client at ${config.CLIENT_HOST}${clientRequestUri}`); const callData = { url: `https://${config.CLIENT_HOST}${clientRequestUri}`, headers: pxUtil.filterSensitiveHeaders(req.headers, config.SENSITIVE_HEADERS), timeout: config.API_TIMEOUT_MS }; callData.headers['host'] = config.CLIENT_HOST; callData.headers[config.ENFORCER_TRUE_IP_HEADER] = ip; callData.headers[config.FIRST_PARTY_HEADER] = 1; request.get(callData, config, (error, response) => { if (error || !response) { config.logger.error(`Error while fetching first party client: ${error}`); } response = response || {statusCode: 200, headers: {}}; res = { status: response.statusCode, headers: response.headers, body: response.body || '' }; return cb(null, res); }); } return; }
javascript
function getClient(req, config, ip, cb) { let res = {}; if (!config.FIRST_PARTY_ENABLED) { res = { status: 200, header: {key: 'Content-Type', value:'application/javascript'}, body: '' }; return cb(null, res); } else { const clientRequestUri = `/${config.PX_APP_ID}/main.min.js`; config.logger.debug(`Forwarding request from ${req.originalUrl.toLowerCase()} to client at ${config.CLIENT_HOST}${clientRequestUri}`); const callData = { url: `https://${config.CLIENT_HOST}${clientRequestUri}`, headers: pxUtil.filterSensitiveHeaders(req.headers, config.SENSITIVE_HEADERS), timeout: config.API_TIMEOUT_MS }; callData.headers['host'] = config.CLIENT_HOST; callData.headers[config.ENFORCER_TRUE_IP_HEADER] = ip; callData.headers[config.FIRST_PARTY_HEADER] = 1; request.get(callData, config, (error, response) => { if (error || !response) { config.logger.error(`Error while fetching first party client: ${error}`); } response = response || {statusCode: 200, headers: {}}; res = { status: response.statusCode, headers: response.headers, body: response.body || '' }; return cb(null, res); }); } return; }
[ "function", "getClient", "(", "req", ",", "config", ",", "ip", ",", "cb", ")", "{", "let", "res", "=", "{", "}", ";", "if", "(", "!", "config", ".", "FIRST_PARTY_ENABLED", ")", "{", "res", "=", "{", "status", ":", "200", ",", "header", ":", "{", "key", ":", "'Content-Type'", ",", "value", ":", "'application/javascript'", "}", ",", "body", ":", "''", "}", ";", "return", "cb", "(", "null", ",", "res", ")", ";", "}", "else", "{", "const", "clientRequestUri", "=", "`", "${", "config", ".", "PX_APP_ID", "}", "`", ";", "config", ".", "logger", ".", "debug", "(", "`", "${", "req", ".", "originalUrl", ".", "toLowerCase", "(", ")", "}", "${", "config", ".", "CLIENT_HOST", "}", "${", "clientRequestUri", "}", "`", ")", ";", "const", "callData", "=", "{", "url", ":", "`", "${", "config", ".", "CLIENT_HOST", "}", "${", "clientRequestUri", "}", "`", ",", "headers", ":", "pxUtil", ".", "filterSensitiveHeaders", "(", "req", ".", "headers", ",", "config", ".", "SENSITIVE_HEADERS", ")", ",", "timeout", ":", "config", ".", "API_TIMEOUT_MS", "}", ";", "callData", ".", "headers", "[", "'host'", "]", "=", "config", ".", "CLIENT_HOST", ";", "callData", ".", "headers", "[", "config", ".", "ENFORCER_TRUE_IP_HEADER", "]", "=", "ip", ";", "callData", ".", "headers", "[", "config", ".", "FIRST_PARTY_HEADER", "]", "=", "1", ";", "request", ".", "get", "(", "callData", ",", "config", ",", "(", "error", ",", "response", ")", "=>", "{", "if", "(", "error", "||", "!", "response", ")", "{", "config", ".", "logger", ".", "error", "(", "`", "${", "error", "}", "`", ")", ";", "}", "response", "=", "response", "||", "{", "statusCode", ":", "200", ",", "headers", ":", "{", "}", "}", ";", "res", "=", "{", "status", ":", "response", ".", "statusCode", ",", "headers", ":", "response", ".", "headers", ",", "body", ":", "response", ".", "body", "||", "''", "}", ";", "return", "cb", "(", "null", ",", "res", ")", ";", "}", ")", ";", "}", "return", ";", "}" ]
getClient - process the proxy request to get the client file from PX servers. @param {object} req - the request object. @param {object} config - the PerimeterX config object. @param {string} ip - the ip that initiated the call. @param {function} cb - the callback function to call at the end of the process. @return {function} the callback function passed as param with the server response (client file) or error.
[ "getClient", "-", "process", "the", "proxy", "request", "to", "get", "the", "client", "file", "from", "PX", "servers", "." ]
281815ffe8913ffdd0916ed507323c88e29f3896
https://github.com/PerimeterX/perimeterx-node-core/blob/281815ffe8913ffdd0916ed507323c88e29f3896/lib/pxproxy.js#L68-L103
train
PerimeterX/perimeterx-node-core
lib/pxhttpc.js
callServer
function callServer(data, headers, uri, callType, config, callback) { callback = callback || ((err) => { err && config.logger.debug(`callServer default callback. Error: ${err}`); }); const callData = { 'url': `https://${config.SERVER_HOST}${uri}`, 'data': JSON.stringify(data), 'headers': headers }; callData.timeout = callType === 'query' ? config.API_TIMEOUT_MS : config.ACTIVITIES_TIMEOUT; try { request.post(callData, config, function (err, response) { let data; if (err) { if (err === 'Error: Timeout has been reached.' || err === 'Error: Timeout reached') { return callback('timeout'); } else { return callback(`perimeterx server did not return a valid response. Error: ${err}`); } } if (typeof(response.body) !== 'undefined' && response.body !== null) { data = response.body.toString(); } if (response && response.statusCode === 200) { try { if (typeof data === 'object') { return callback(null, data); } else { return callback(null, JSON.parse(data)); } } catch (e) { return callback('could not parse perimeterx api server response'); } } if (data) { try { return callback(`perimeterx server query failed. ${JSON.parse(data).message}`); } catch (e) { } } return callback('perimeterx server did not return a valid response'); }); } catch (e) { return callback('error while calling perimeterx servers'); } }
javascript
function callServer(data, headers, uri, callType, config, callback) { callback = callback || ((err) => { err && config.logger.debug(`callServer default callback. Error: ${err}`); }); const callData = { 'url': `https://${config.SERVER_HOST}${uri}`, 'data': JSON.stringify(data), 'headers': headers }; callData.timeout = callType === 'query' ? config.API_TIMEOUT_MS : config.ACTIVITIES_TIMEOUT; try { request.post(callData, config, function (err, response) { let data; if (err) { if (err === 'Error: Timeout has been reached.' || err === 'Error: Timeout reached') { return callback('timeout'); } else { return callback(`perimeterx server did not return a valid response. Error: ${err}`); } } if (typeof(response.body) !== 'undefined' && response.body !== null) { data = response.body.toString(); } if (response && response.statusCode === 200) { try { if (typeof data === 'object') { return callback(null, data); } else { return callback(null, JSON.parse(data)); } } catch (e) { return callback('could not parse perimeterx api server response'); } } if (data) { try { return callback(`perimeterx server query failed. ${JSON.parse(data).message}`); } catch (e) { } } return callback('perimeterx server did not return a valid response'); }); } catch (e) { return callback('error while calling perimeterx servers'); } }
[ "function", "callServer", "(", "data", ",", "headers", ",", "uri", ",", "callType", ",", "config", ",", "callback", ")", "{", "callback", "=", "callback", "||", "(", "(", "err", ")", "=>", "{", "err", "&&", "config", ".", "logger", ".", "debug", "(", "`", "${", "err", "}", "`", ")", ";", "}", ")", ";", "const", "callData", "=", "{", "'url'", ":", "`", "${", "config", ".", "SERVER_HOST", "}", "${", "uri", "}", "`", ",", "'data'", ":", "JSON", ".", "stringify", "(", "data", ")", ",", "'headers'", ":", "headers", "}", ";", "callData", ".", "timeout", "=", "callType", "===", "'query'", "?", "config", ".", "API_TIMEOUT_MS", ":", "config", ".", "ACTIVITIES_TIMEOUT", ";", "try", "{", "request", ".", "post", "(", "callData", ",", "config", ",", "function", "(", "err", ",", "response", ")", "{", "let", "data", ";", "if", "(", "err", ")", "{", "if", "(", "err", "===", "'Error: Timeout has been reached.'", "||", "err", "===", "'Error: Timeout reached'", ")", "{", "return", "callback", "(", "'timeout'", ")", ";", "}", "else", "{", "return", "callback", "(", "`", "${", "err", "}", "`", ")", ";", "}", "}", "if", "(", "typeof", "(", "response", ".", "body", ")", "!==", "'undefined'", "&&", "response", ".", "body", "!==", "null", ")", "{", "data", "=", "response", ".", "body", ".", "toString", "(", ")", ";", "}", "if", "(", "response", "&&", "response", ".", "statusCode", "===", "200", ")", "{", "try", "{", "if", "(", "typeof", "data", "===", "'object'", ")", "{", "return", "callback", "(", "null", ",", "data", ")", ";", "}", "else", "{", "return", "callback", "(", "null", ",", "JSON", ".", "parse", "(", "data", ")", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "return", "callback", "(", "'could not parse perimeterx api server response'", ")", ";", "}", "}", "if", "(", "data", ")", "{", "try", "{", "return", "callback", "(", "`", "${", "JSON", ".", "parse", "(", "data", ")", ".", "message", "}", "`", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "}", "return", "callback", "(", "'perimeterx server did not return a valid response'", ")", ";", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "callback", "(", "'error while calling perimeterx servers'", ")", ";", "}", "}" ]
callServer - call the perimeterx servers. @param {Object} data - data object to pass as POST body @param {Object} headers - http request headers @param {string} uri - px servers endpoint uri @param {string} callType - indication for a query or activities sending @param {Function} callback - callback function.
[ "callServer", "-", "call", "the", "perimeterx", "servers", "." ]
281815ffe8913ffdd0916ed507323c88e29f3896
https://github.com/PerimeterX/perimeterx-node-core/blob/281815ffe8913ffdd0916ed507323c88e29f3896/lib/pxhttpc.js#L18-L63
train
blackbaud/skyux-cli
lib/npm-install.js
npmInstall
function npmInstall(settings) { const message = logger.promise('Running npm install (can take several minutes)'); const installArgs = {}; if (settings) { if (settings.path) { installArgs.cwd = settings.path; } if (settings.stdio) { installArgs.stdio = settings.stdio; } } const npmProcess = spawn('npm', ['install'], installArgs); return new Promise((resolve, reject) => { npmProcess.on('exit', (code) => { if (code !== 0) { message.fail(); reject('npm install failed.'); return; } message.succeed(); resolve(); }); }); }
javascript
function npmInstall(settings) { const message = logger.promise('Running npm install (can take several minutes)'); const installArgs = {}; if (settings) { if (settings.path) { installArgs.cwd = settings.path; } if (settings.stdio) { installArgs.stdio = settings.stdio; } } const npmProcess = spawn('npm', ['install'], installArgs); return new Promise((resolve, reject) => { npmProcess.on('exit', (code) => { if (code !== 0) { message.fail(); reject('npm install failed.'); return; } message.succeed(); resolve(); }); }); }
[ "function", "npmInstall", "(", "settings", ")", "{", "const", "message", "=", "logger", ".", "promise", "(", "'Running npm install (can take several minutes)'", ")", ";", "const", "installArgs", "=", "{", "}", ";", "if", "(", "settings", ")", "{", "if", "(", "settings", ".", "path", ")", "{", "installArgs", ".", "cwd", "=", "settings", ".", "path", ";", "}", "if", "(", "settings", ".", "stdio", ")", "{", "installArgs", ".", "stdio", "=", "settings", ".", "stdio", ";", "}", "}", "const", "npmProcess", "=", "spawn", "(", "'npm'", ",", "[", "'install'", "]", ",", "installArgs", ")", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "npmProcess", ".", "on", "(", "'exit'", ",", "(", "code", ")", "=>", "{", "if", "(", "code", "!==", "0", ")", "{", "message", ".", "fail", "(", ")", ";", "reject", "(", "'npm install failed.'", ")", ";", "return", ";", "}", "message", ".", "succeed", "(", ")", ";", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Runs npm install for a specific package @name npmInstall
[ "Runs", "npm", "install", "for", "a", "specific", "package" ]
c579986da0cfebbe74d584781d2db9dc9524d7d2
https://github.com/blackbaud/skyux-cli/blob/c579986da0cfebbe74d584781d2db9dc9524d7d2/lib/npm-install.js#L11-L40
train
omrilotan/mono
packages/eslint-plugin-log/spec.js
mock
function mock(_module, _exports) { delete require.cache[require.resolve(_module)]; require(_module); _exports && (require.cache[require.resolve(_module)].exports = _exports); return require(_module); }
javascript
function mock(_module, _exports) { delete require.cache[require.resolve(_module)]; require(_module); _exports && (require.cache[require.resolve(_module)].exports = _exports); return require(_module); }
[ "function", "mock", "(", "_module", ",", "_exports", ")", "{", "delete", "require", ".", "cache", "[", "require", ".", "resolve", "(", "_module", ")", "]", ";", "require", "(", "_module", ")", ";", "_exports", "&&", "(", "require", ".", "cache", "[", "require", ".", "resolve", "(", "_module", ")", "]", ".", "exports", "=", "_exports", ")", ";", "return", "require", "(", "_module", ")", ";", "}" ]
Mock e module's exports @param {String} _module Module route @param {Any} _exports Anything you'd like that module to export @return {Any} The module's exports
[ "Mock", "e", "module", "s", "exports" ]
16c37c9584167f556d3d449cd1eeea4511278bf7
https://github.com/omrilotan/mono/blob/16c37c9584167f556d3d449cd1eeea4511278bf7/packages/eslint-plugin-log/spec.js#L10-L15
train
omrilotan/mono
packages/upgradable/lib/start/index.js
later
function later (info) { process.stdin.resume(); const action = start.bind(null, info); process.on('SIGINT', action); process.on('SIGTERM', action); (function wait () { if (beenthere) { return; } setTimeout(wait, EVENT_LOOP); }()); }
javascript
function later (info) { process.stdin.resume(); const action = start.bind(null, info); process.on('SIGINT', action); process.on('SIGTERM', action); (function wait () { if (beenthere) { return; } setTimeout(wait, EVENT_LOOP); }()); }
[ "function", "later", "(", "info", ")", "{", "process", ".", "stdin", ".", "resume", "(", ")", ";", "const", "action", "=", "start", ".", "bind", "(", "null", ",", "info", ")", ";", "process", ".", "on", "(", "'SIGINT'", ",", "action", ")", ";", "process", ".", "on", "(", "'SIGTERM'", ",", "action", ")", ";", "(", "function", "wait", "(", ")", "{", "if", "(", "beenthere", ")", "{", "return", ";", "}", "setTimeout", "(", "wait", ",", "EVENT_LOOP", ")", ";", "}", "(", ")", ")", ";", "}" ]
Perform the checks paralelly, only inform user on signal interrupt @param {Info} info Information about the package @return {undefined} no return value
[ "Perform", "the", "checks", "paralelly", "only", "inform", "user", "on", "signal", "interrupt" ]
16c37c9584167f556d3d449cd1eeea4511278bf7
https://github.com/omrilotan/mono/blob/16c37c9584167f556d3d449cd1eeea4511278bf7/packages/upgradable/lib/start/index.js#L78-L91
train
omrilotan/mono
packages/upgradable/lib/start/index.js
start
async function start ({latest, message, name, version}) { if (beenthere) { return; } beenthere = true; console.log( // eslint-disable-line no-console box({ latest, message, name, version, }) ); const Confirm = require('prompt-confirm'); const confirmed = await new Confirm( `install ${name.yellow} version ${latest.yellow} globally?` ).run(); if (!confirmed) { process.exit(); // eslint-disable-line no-process-exit } await require('../install-latest')(name); process.exit(); // eslint-disable-line no-process-exit }
javascript
async function start ({latest, message, name, version}) { if (beenthere) { return; } beenthere = true; console.log( // eslint-disable-line no-console box({ latest, message, name, version, }) ); const Confirm = require('prompt-confirm'); const confirmed = await new Confirm( `install ${name.yellow} version ${latest.yellow} globally?` ).run(); if (!confirmed) { process.exit(); // eslint-disable-line no-process-exit } await require('../install-latest')(name); process.exit(); // eslint-disable-line no-process-exit }
[ "async", "function", "start", "(", "{", "latest", ",", "message", ",", "name", ",", "version", "}", ")", "{", "if", "(", "beenthere", ")", "{", "return", ";", "}", "beenthere", "=", "true", ";", "console", ".", "log", "(", "box", "(", "{", "latest", ",", "message", ",", "name", ",", "version", ",", "}", ")", ")", ";", "const", "Confirm", "=", "require", "(", "'prompt-confirm'", ")", ";", "const", "confirmed", "=", "await", "new", "Confirm", "(", "`", "${", "name", ".", "yellow", "}", "${", "latest", ".", "yellow", "}", "`", ")", ".", "run", "(", ")", ";", "if", "(", "!", "confirmed", ")", "{", "process", ".", "exit", "(", ")", ";", "}", "await", "require", "(", "'../install-latest'", ")", "(", "name", ")", ";", "process", ".", "exit", "(", ")", ";", "}" ]
Start checking for upgrades @param {Info} info Information about the package @returns {undefined} No return value
[ "Start", "checking", "for", "upgrades" ]
16c37c9584167f556d3d449cd1eeea4511278bf7
https://github.com/omrilotan/mono/blob/16c37c9584167f556d3d449cd1eeea4511278bf7/packages/upgradable/lib/start/index.js#L98-L125
train
omrilotan/mono
packages/upgradable/lib/start/index.js
box
function box ({latest, message, name, version}) { const lines = [ `You are running ${name.yellow} version ${version.yellow}`, `The latest version is ${latest.green}`, ]; if (message) { lines.push(message.bold.italic); } return boxt( lines.join('\n'), { 'align': 'left', 'theme': 'round', } ); }
javascript
function box ({latest, message, name, version}) { const lines = [ `You are running ${name.yellow} version ${version.yellow}`, `The latest version is ${latest.green}`, ]; if (message) { lines.push(message.bold.italic); } return boxt( lines.join('\n'), { 'align': 'left', 'theme': 'round', } ); }
[ "function", "box", "(", "{", "latest", ",", "message", ",", "name", ",", "version", "}", ")", "{", "const", "lines", "=", "[", "`", "${", "name", ".", "yellow", "}", "${", "version", ".", "yellow", "}", "`", ",", "`", "${", "latest", ".", "green", "}", "`", ",", "]", ";", "if", "(", "message", ")", "{", "lines", ".", "push", "(", "message", ".", "bold", ".", "italic", ")", ";", "}", "return", "boxt", "(", "lines", ".", "join", "(", "'\\n'", ")", ",", "\\n", ")", ";", "}" ]
A "boxed" message to user letting them know of our upgrade intentions @param {Info} info Information about the package @return {String} Message to user
[ "A", "boxed", "message", "to", "user", "letting", "them", "know", "of", "our", "upgrade", "intentions" ]
16c37c9584167f556d3d449cd1eeea4511278bf7
https://github.com/omrilotan/mono/blob/16c37c9584167f556d3d449cd1eeea4511278bf7/packages/upgradable/lib/start/index.js#L132-L149
train
omrilotan/mono
packages/chunkalyse/bin/chunkalyse.js
getStats
function getStats({_: [file]} = {}) { const route = resolve(process.cwd(), file); try { return require(route); } catch (error) { console.error(`The file "${route}" could not be properly parsed.`); process.exit(1); } }
javascript
function getStats({_: [file]} = {}) { const route = resolve(process.cwd(), file); try { return require(route); } catch (error) { console.error(`The file "${route}" could not be properly parsed.`); process.exit(1); } }
[ "function", "getStats", "(", "{", "_", ":", "[", "file", "]", "}", "=", "{", "}", ")", "{", "const", "route", "=", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "file", ")", ";", "try", "{", "return", "require", "(", "route", ")", ";", "}", "catch", "(", "error", ")", "{", "console", ".", "error", "(", "`", "${", "route", "}", "`", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", "}" ]
Read stats json file @param {String[]} options._[file] stats file @return {Object}
[ "Read", "stats", "json", "file" ]
16c37c9584167f556d3d449cd1eeea4511278bf7
https://github.com/omrilotan/mono/blob/16c37c9584167f556d3d449cd1eeea4511278bf7/packages/chunkalyse/bin/chunkalyse.js#L50-L59
train
omrilotan/mono
packages/chunkalyse/bin/chunkalyse.js
start
function start(stats, {f, format = 'human'} = {}) { try { const result = chunkalyse(stats); let output; switch (f || format) { case 'json': output = JSON.stringify(result, null, 2); break; case 'human': default: output = require('../lib/humanise')(result); } console.log(output); } catch (error) { console.log('I\'ve had trouble finding the chunks\n'); throw error; } }
javascript
function start(stats, {f, format = 'human'} = {}) { try { const result = chunkalyse(stats); let output; switch (f || format) { case 'json': output = JSON.stringify(result, null, 2); break; case 'human': default: output = require('../lib/humanise')(result); } console.log(output); } catch (error) { console.log('I\'ve had trouble finding the chunks\n'); throw error; } }
[ "function", "start", "(", "stats", ",", "{", "f", ",", "format", "=", "'human'", "}", "=", "{", "}", ")", "{", "try", "{", "const", "result", "=", "chunkalyse", "(", "stats", ")", ";", "let", "output", ";", "switch", "(", "f", "||", "format", ")", "{", "case", "'json'", ":", "output", "=", "JSON", ".", "stringify", "(", "result", ",", "null", ",", "2", ")", ";", "break", ";", "case", "'human'", ":", "default", ":", "output", "=", "require", "(", "'../lib/humanise'", ")", "(", "result", ")", ";", "}", "console", ".", "log", "(", "output", ")", ";", "}", "catch", "(", "error", ")", "{", "console", ".", "log", "(", "'I\\'ve had trouble finding the chunks\\n'", ")", ";", "\\'", "}", "}" ]
Get the chunks and print them @param {Object} stats no return value
[ "Get", "the", "chunks", "and", "print", "them" ]
16c37c9584167f556d3d449cd1eeea4511278bf7
https://github.com/omrilotan/mono/blob/16c37c9584167f556d3d449cd1eeea4511278bf7/packages/chunkalyse/bin/chunkalyse.js#L66-L85
train
omrilotan/mono
packages/dangerfile/index.js
create
async function create(sourcedir) { const target = join(sourcedir, FILENAME); const exists = await exist(target); const source = exists ? target : join(__dirname, FILENAME) ; const content = await readFile(source); await writeFile(primed, content.toString()); return exists ? 'Creating a new Dangerfile' : 'Creating a default Dangerfile' ; }
javascript
async function create(sourcedir) { const target = join(sourcedir, FILENAME); const exists = await exist(target); const source = exists ? target : join(__dirname, FILENAME) ; const content = await readFile(source); await writeFile(primed, content.toString()); return exists ? 'Creating a new Dangerfile' : 'Creating a default Dangerfile' ; }
[ "async", "function", "create", "(", "sourcedir", ")", "{", "const", "target", "=", "join", "(", "sourcedir", ",", "FILENAME", ")", ";", "const", "exists", "=", "await", "exist", "(", "target", ")", ";", "const", "source", "=", "exists", "?", "target", ":", "join", "(", "__dirname", ",", "FILENAME", ")", ";", "const", "content", "=", "await", "readFile", "(", "source", ")", ";", "await", "writeFile", "(", "primed", ",", "content", ".", "toString", "(", ")", ")", ";", "return", "exists", "?", "'Creating a new Dangerfile'", ":", "'Creating a default Dangerfile'", ";", "}" ]
Create a dangerfile @param {String} target [description] @return {[type]} [description]
[ "Create", "a", "dangerfile" ]
16c37c9584167f556d3d449cd1eeea4511278bf7
https://github.com/omrilotan/mono/blob/16c37c9584167f556d3d449cd1eeea4511278bf7/packages/dangerfile/index.js#L42-L58
train
omrilotan/mono
packages/dangerfile/index.js
run
async function run() { try { await execute('./node_modules/.bin/danger ci', { pipe: true }); return false; } catch (error) { // don't throw yet } await execute('npm i danger --no-save', { pipe: true }); await execute('./node_modules/.bin/danger ci', { pipe: true }); return true; }
javascript
async function run() { try { await execute('./node_modules/.bin/danger ci', { pipe: true }); return false; } catch (error) { // don't throw yet } await execute('npm i danger --no-save', { pipe: true }); await execute('./node_modules/.bin/danger ci', { pipe: true }); return true; }
[ "async", "function", "run", "(", ")", "{", "try", "{", "await", "execute", "(", "'./node_modules/.bin/danger ci'", ",", "{", "pipe", ":", "true", "}", ")", ";", "return", "false", ";", "}", "catch", "(", "error", ")", "{", "}", "await", "execute", "(", "'npm i danger --no-save'", ",", "{", "pipe", ":", "true", "}", ")", ";", "await", "execute", "(", "'./node_modules/.bin/danger ci'", ",", "{", "pipe", ":", "true", "}", ")", ";", "return", "true", ";", "}" ]
Install danger and run it @return {Boolean}
[ "Install", "danger", "and", "run", "it" ]
16c37c9584167f556d3d449cd1eeea4511278bf7
https://github.com/omrilotan/mono/blob/16c37c9584167f556d3d449cd1eeea4511278bf7/packages/dangerfile/index.js#L64-L75
train
omrilotan/mono
packages/paraphrase/index.js
replace
function replace(haystack, needle) { const replacement = options.resolve ? notate(data, needle.trim()) : data[needle.trim()]; return VALID_RESULT_TYPES.includes(typeof replacement) ? replacement : options.clean ? '' : haystack; }
javascript
function replace(haystack, needle) { const replacement = options.resolve ? notate(data, needle.trim()) : data[needle.trim()]; return VALID_RESULT_TYPES.includes(typeof replacement) ? replacement : options.clean ? '' : haystack; }
[ "function", "replace", "(", "haystack", ",", "needle", ")", "{", "const", "replacement", "=", "options", ".", "resolve", "?", "notate", "(", "data", ",", "needle", ".", "trim", "(", ")", ")", ":", "data", "[", "needle", ".", "trim", "(", ")", "]", ";", "return", "VALID_RESULT_TYPES", ".", "includes", "(", "typeof", "replacement", ")", "?", "replacement", ":", "options", ".", "clean", "?", "''", ":", "haystack", ";", "}" ]
Replace method build with internal reference to the passed in data structure @param {String} haystack The full string match @param {String} needle The content to identify as data member @return {String} Found value
[ "Replace", "method", "build", "with", "internal", "reference", "to", "the", "passed", "in", "data", "structure" ]
16c37c9584167f556d3d449cd1eeea4511278bf7
https://github.com/omrilotan/mono/blob/16c37c9584167f556d3d449cd1eeea4511278bf7/packages/paraphrase/index.js#L63-L67
train
blackbaud/skyux-cli
lib/help.js
getHelpTopic
function getHelpTopic(topic) { let filename = getFilename(topic); if (!fs.existsSync(filename)) { filename = getFilename('help'); } return fs.readFileSync(filename).toString(); }
javascript
function getHelpTopic(topic) { let filename = getFilename(topic); if (!fs.existsSync(filename)) { filename = getFilename('help'); } return fs.readFileSync(filename).toString(); }
[ "function", "getHelpTopic", "(", "topic", ")", "{", "let", "filename", "=", "getFilename", "(", "topic", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "filename", ")", ")", "{", "filename", "=", "getFilename", "(", "'help'", ")", ";", "}", "return", "fs", ".", "readFileSync", "(", "filename", ")", ".", "toString", "(", ")", ";", "}" ]
Returns the corresponding help text for a given topic.
[ "Returns", "the", "corresponding", "help", "text", "for", "a", "given", "topic", "." ]
c579986da0cfebbe74d584781d2db9dc9524d7d2
https://github.com/blackbaud/skyux-cli/blob/c579986da0cfebbe74d584781d2db9dc9524d7d2/lib/help.js#L15-L23
train
blackbaud/skyux-cli
lib/help.js
getHelp
function getHelp(argv) { const version = require('./version').getVersion(); logger.info(` *********************************************************************** * SKY UX App Builder ${version} * * Usage: skyux [command] [options] * * Help: skyux help or skyux help [command] * * https://developer.blackbaud.com/skyux2/learn/reference/cli-commands * *********************************************************************** `); logger.info(getHelpTopic(argv._[1])); }
javascript
function getHelp(argv) { const version = require('./version').getVersion(); logger.info(` *********************************************************************** * SKY UX App Builder ${version} * * Usage: skyux [command] [options] * * Help: skyux help or skyux help [command] * * https://developer.blackbaud.com/skyux2/learn/reference/cli-commands * *********************************************************************** `); logger.info(getHelpTopic(argv._[1])); }
[ "function", "getHelp", "(", "argv", ")", "{", "const", "version", "=", "require", "(", "'./version'", ")", ".", "getVersion", "(", ")", ";", "logger", ".", "info", "(", "`", "${", "version", "}", "`", ")", ";", "logger", ".", "info", "(", "getHelpTopic", "(", "argv", ".", "_", "[", "1", "]", ")", ")", ";", "}" ]
Displays the help information. @name getHelp
[ "Displays", "the", "help", "information", "." ]
c579986da0cfebbe74d584781d2db9dc9524d7d2
https://github.com/blackbaud/skyux-cli/blob/c579986da0cfebbe74d584781d2db9dc9524d7d2/lib/help.js#L29-L43
train
omrilotan/mono
packages/abuser/index.js
clean
function clean(route) { // Resolve module location from given path const filename = _require.resolve(route); // Escape if this module is not present in cache if (!_require.cache[filename]) { return; } // Remove all children from memory, recursively shidu(filename); // Remove module from memory as well delete _require.cache[filename]; }
javascript
function clean(route) { // Resolve module location from given path const filename = _require.resolve(route); // Escape if this module is not present in cache if (!_require.cache[filename]) { return; } // Remove all children from memory, recursively shidu(filename); // Remove module from memory as well delete _require.cache[filename]; }
[ "function", "clean", "(", "route", ")", "{", "const", "filename", "=", "_require", ".", "resolve", "(", "route", ")", ";", "if", "(", "!", "_require", ".", "cache", "[", "filename", "]", ")", "{", "return", ";", "}", "shidu", "(", "filename", ")", ";", "delete", "_require", ".", "cache", "[", "filename", "]", ";", "}" ]
Clean up a module from cache @param {String} route @return {undefined}
[ "Clean", "up", "a", "module", "from", "cache" ]
16c37c9584167f556d3d449cd1eeea4511278bf7
https://github.com/omrilotan/mono/blob/16c37c9584167f556d3d449cd1eeea4511278bf7/packages/abuser/index.js#L16-L30
train
omrilotan/mono
packages/abuser/index.js
override
function override(route, thing) { // Resolve module location from given path const filename = _require.resolve(route); // Load it into memory _require(filename); // Override exports with new value _require.cache[filename].exports = thing; // Return exports value return _require(filename); }
javascript
function override(route, thing) { // Resolve module location from given path const filename = _require.resolve(route); // Load it into memory _require(filename); // Override exports with new value _require.cache[filename].exports = thing; // Return exports value return _require(filename); }
[ "function", "override", "(", "route", ",", "thing", ")", "{", "const", "filename", "=", "_require", ".", "resolve", "(", "route", ")", ";", "_require", "(", "filename", ")", ";", "_require", ".", "cache", "[", "filename", "]", ".", "exports", "=", "thing", ";", "return", "_require", "(", "filename", ")", ";", "}" ]
Override a module with any given thing @param {String} route @param {Any} thing @return {Any} New exports of the module
[ "Override", "a", "module", "with", "any", "given", "thing" ]
16c37c9584167f556d3d449cd1eeea4511278bf7
https://github.com/omrilotan/mono/blob/16c37c9584167f556d3d449cd1eeea4511278bf7/packages/abuser/index.js#L38-L51
train
omrilotan/mono
packages/abuser/index.js
reset
function reset(route) { // Resolve module location from given path const filename = _require.resolve(route); // Load it into memory _require(filename); // Remove all children from memory, recursively shidu(filename); // Remove module from memory as well delete _require.cache[filename]; // Return exports value return _require(filename); }
javascript
function reset(route) { // Resolve module location from given path const filename = _require.resolve(route); // Load it into memory _require(filename); // Remove all children from memory, recursively shidu(filename); // Remove module from memory as well delete _require.cache[filename]; // Return exports value return _require(filename); }
[ "function", "reset", "(", "route", ")", "{", "const", "filename", "=", "_require", ".", "resolve", "(", "route", ")", ";", "_require", "(", "filename", ")", ";", "shidu", "(", "filename", ")", ";", "delete", "_require", ".", "cache", "[", "filename", "]", ";", "return", "_require", "(", "filename", ")", ";", "}" ]
Reset a module @param {String} route @return {Any}
[ "Reset", "a", "module" ]
16c37c9584167f556d3d449cd1eeea4511278bf7
https://github.com/omrilotan/mono/blob/16c37c9584167f556d3d449cd1eeea4511278bf7/packages/abuser/index.js#L58-L74
train
omrilotan/mono
packages/abuser/index.js
shidu
function shidu(filename) { const parent = require.cache[filename]; if (!parent) { return; } // If there are children - iterate over them parent.children .map( ({filename}) => filename ) .forEach( child => { // Load child to memory require(child); // Remove all of its children from memory, recursively shidu(child); // Remove it from memory delete require.cache[child]; } ); }
javascript
function shidu(filename) { const parent = require.cache[filename]; if (!parent) { return; } // If there are children - iterate over them parent.children .map( ({filename}) => filename ) .forEach( child => { // Load child to memory require(child); // Remove all of its children from memory, recursively shidu(child); // Remove it from memory delete require.cache[child]; } ); }
[ "function", "shidu", "(", "filename", ")", "{", "const", "parent", "=", "require", ".", "cache", "[", "filename", "]", ";", "if", "(", "!", "parent", ")", "{", "return", ";", "}", "parent", ".", "children", ".", "map", "(", "(", "{", "filename", "}", ")", "=>", "filename", ")", ".", "forEach", "(", "child", "=>", "{", "require", "(", "child", ")", ";", "shidu", "(", "child", ")", ";", "delete", "require", ".", "cache", "[", "child", "]", ";", "}", ")", ";", "}" ]
Remove all children from cache as well @param {String} parent @return {undefined}
[ "Remove", "all", "children", "from", "cache", "as", "well" ]
16c37c9584167f556d3d449cd1eeea4511278bf7
https://github.com/omrilotan/mono/blob/16c37c9584167f556d3d449cd1eeea4511278bf7/packages/abuser/index.js#L84-L109
train
blackbaud/skyux-cli
index.js
getGlobs
function getGlobs() { // Look globally and locally for matching glob pattern const dirs = [ `${process.cwd()}/node_modules/`, // local (where they ran the command from) `${__dirname}/..`, // global, if scoped package (where this code exists) `${__dirname}/../..`, // global, if not scoped package ]; let globs = []; dirs.forEach(dir => { const legacyPattern = path.join(dir, '*/skyux-builder*/package.json'); const newPattern = path.join(dir, '@skyux-sdk/builder*/package.json'); logger.verbose(`Looking for modules in ${legacyPattern} and ${newPattern}`); globs = globs.concat([ ...glob.sync(legacyPattern), ...glob.sync(newPattern) ]); }); return globs; }
javascript
function getGlobs() { // Look globally and locally for matching glob pattern const dirs = [ `${process.cwd()}/node_modules/`, // local (where they ran the command from) `${__dirname}/..`, // global, if scoped package (where this code exists) `${__dirname}/../..`, // global, if not scoped package ]; let globs = []; dirs.forEach(dir => { const legacyPattern = path.join(dir, '*/skyux-builder*/package.json'); const newPattern = path.join(dir, '@skyux-sdk/builder*/package.json'); logger.verbose(`Looking for modules in ${legacyPattern} and ${newPattern}`); globs = globs.concat([ ...glob.sync(legacyPattern), ...glob.sync(newPattern) ]); }); return globs; }
[ "function", "getGlobs", "(", ")", "{", "const", "dirs", "=", "[", "`", "${", "process", ".", "cwd", "(", ")", "}", "`", ",", "`", "${", "__dirname", "}", "`", ",", "`", "${", "__dirname", "}", "`", ",", "]", ";", "let", "globs", "=", "[", "]", ";", "dirs", ".", "forEach", "(", "dir", "=>", "{", "const", "legacyPattern", "=", "path", ".", "join", "(", "dir", ",", "'*/skyux-builder*/package.json'", ")", ";", "const", "newPattern", "=", "path", ".", "join", "(", "dir", ",", "'@skyux-sdk/builder*/package.json'", ")", ";", "logger", ".", "verbose", "(", "`", "${", "legacyPattern", "}", "${", "newPattern", "}", "`", ")", ";", "globs", "=", "globs", ".", "concat", "(", "[", "...", "glob", ".", "sync", "(", "legacyPattern", ")", ",", "...", "glob", ".", "sync", "(", "newPattern", ")", "]", ")", ";", "}", ")", ";", "return", "globs", ";", "}" ]
Returns results of glob.sync from specified directory and our glob pattern. @returns {Array} Array of matching patterns
[ "Returns", "results", "of", "glob", ".", "sync", "from", "specified", "directory", "and", "our", "glob", "pattern", "." ]
c579986da0cfebbe74d584781d2db9dc9524d7d2
https://github.com/blackbaud/skyux-cli/blob/c579986da0cfebbe74d584781d2db9dc9524d7d2/index.js#L13-L37
train
blackbaud/skyux-cli
index.js
getModulesAnswered
function getModulesAnswered(command, argv, globs) { let modulesCalled = {}; let modulesAnswered = []; globs.forEach(pkg => { const dirName = path.dirname(pkg); let pkgJson = {}; let module; try { module = require(dirName); pkgJson = require(pkg); } catch (err) { logger.verbose(`Error loading module: ${pkg}`); } if (module && typeof module.runCommand === 'function') { const pkgName = pkgJson.name || dirName; if (modulesCalled[pkgName]) { logger.verbose(`Multiple instances found. Skipping passing command to ${pkgName}`); } else { logger.verbose(`Passing command to ${pkgName}`); modulesCalled[pkgName] = true; if (module.runCommand(command, argv)) { modulesAnswered.push(pkgName); } } } }); return modulesAnswered; }
javascript
function getModulesAnswered(command, argv, globs) { let modulesCalled = {}; let modulesAnswered = []; globs.forEach(pkg => { const dirName = path.dirname(pkg); let pkgJson = {}; let module; try { module = require(dirName); pkgJson = require(pkg); } catch (err) { logger.verbose(`Error loading module: ${pkg}`); } if (module && typeof module.runCommand === 'function') { const pkgName = pkgJson.name || dirName; if (modulesCalled[pkgName]) { logger.verbose(`Multiple instances found. Skipping passing command to ${pkgName}`); } else { logger.verbose(`Passing command to ${pkgName}`); modulesCalled[pkgName] = true; if (module.runCommand(command, argv)) { modulesAnswered.push(pkgName); } } } }); return modulesAnswered; }
[ "function", "getModulesAnswered", "(", "command", ",", "argv", ",", "globs", ")", "{", "let", "modulesCalled", "=", "{", "}", ";", "let", "modulesAnswered", "=", "[", "]", ";", "globs", ".", "forEach", "(", "pkg", "=>", "{", "const", "dirName", "=", "path", ".", "dirname", "(", "pkg", ")", ";", "let", "pkgJson", "=", "{", "}", ";", "let", "module", ";", "try", "{", "module", "=", "require", "(", "dirName", ")", ";", "pkgJson", "=", "require", "(", "pkg", ")", ";", "}", "catch", "(", "err", ")", "{", "logger", ".", "verbose", "(", "`", "${", "pkg", "}", "`", ")", ";", "}", "if", "(", "module", "&&", "typeof", "module", ".", "runCommand", "===", "'function'", ")", "{", "const", "pkgName", "=", "pkgJson", ".", "name", "||", "dirName", ";", "if", "(", "modulesCalled", "[", "pkgName", "]", ")", "{", "logger", ".", "verbose", "(", "`", "${", "pkgName", "}", "`", ")", ";", "}", "else", "{", "logger", ".", "verbose", "(", "`", "${", "pkgName", "}", "`", ")", ";", "modulesCalled", "[", "pkgName", "]", "=", "true", ";", "if", "(", "module", ".", "runCommand", "(", "command", ",", "argv", ")", ")", "{", "modulesAnswered", ".", "push", "(", "pkgName", ")", ";", "}", "}", "}", "}", ")", ";", "return", "modulesAnswered", ";", "}" ]
Iterates over the given modules. @param {string} command @param {Object} argv @param {Array} globs @returns {Array} modulesAnswered
[ "Iterates", "over", "the", "given", "modules", "." ]
c579986da0cfebbe74d584781d2db9dc9524d7d2
https://github.com/blackbaud/skyux-cli/blob/c579986da0cfebbe74d584781d2db9dc9524d7d2/index.js#L46-L80
train
blackbaud/skyux-cli
index.js
invokeCommandError
function invokeCommandError(command, isInternalCommand) { if (isInternalCommand) { return; } const cwd = process.cwd(); logger.error(`No modules found for ${command}`); if (cwd.indexOf('skyux-spa') === -1) { logger.error(`Are you in a SKY UX SPA directory?`); } else if (!fs.existsSync('./node_modules')) { logger.error(`Have you ran 'npm install'?`); } process.exit(1); }
javascript
function invokeCommandError(command, isInternalCommand) { if (isInternalCommand) { return; } const cwd = process.cwd(); logger.error(`No modules found for ${command}`); if (cwd.indexOf('skyux-spa') === -1) { logger.error(`Are you in a SKY UX SPA directory?`); } else if (!fs.existsSync('./node_modules')) { logger.error(`Have you ran 'npm install'?`); } process.exit(1); }
[ "function", "invokeCommandError", "(", "command", ",", "isInternalCommand", ")", "{", "if", "(", "isInternalCommand", ")", "{", "return", ";", "}", "const", "cwd", "=", "process", ".", "cwd", "(", ")", ";", "logger", ".", "error", "(", "`", "${", "command", "}", "`", ")", ";", "if", "(", "cwd", ".", "indexOf", "(", "'skyux-spa'", ")", "===", "-", "1", ")", "{", "logger", ".", "error", "(", "`", "`", ")", ";", "}", "else", "if", "(", "!", "fs", ".", "existsSync", "(", "'./node_modules'", ")", ")", "{", "logger", ".", "error", "(", "`", "`", ")", ";", "}", "process", ".", "exit", "(", "1", ")", ";", "}" ]
Log fatal error and exit. This method is called even for internal commands. In those cases, there isn't actually an error. @param {string} command @param {boolean} isInternalCommand
[ "Log", "fatal", "error", "and", "exit", ".", "This", "method", "is", "called", "even", "for", "internal", "commands", ".", "In", "those", "cases", "there", "isn", "t", "actually", "an", "error", "." ]
c579986da0cfebbe74d584781d2db9dc9524d7d2
https://github.com/blackbaud/skyux-cli/blob/c579986da0cfebbe74d584781d2db9dc9524d7d2/index.js#L89-L105
train
blackbaud/skyux-cli
index.js
invokeCommand
function invokeCommand(command, argv, isInternalCommand) { const globs = getGlobs(); if (globs.length === 0) { return invokeCommandError(command, isInternalCommand); } const modulesAnswered = getModulesAnswered(command, argv, globs); const modulesAnsweredLength = modulesAnswered.length; if (modulesAnsweredLength === 0) { return invokeCommandError(command, isInternalCommand); } const modulesAnsweredPlural = modulesAnsweredLength === 1 ? 'module' : 'modules'; logger.verbose( `Successfully passed ${command} to ${modulesAnsweredLength} ${modulesAnsweredPlural}:` ); logger.verbose(modulesAnswered.join(', ')); }
javascript
function invokeCommand(command, argv, isInternalCommand) { const globs = getGlobs(); if (globs.length === 0) { return invokeCommandError(command, isInternalCommand); } const modulesAnswered = getModulesAnswered(command, argv, globs); const modulesAnsweredLength = modulesAnswered.length; if (modulesAnsweredLength === 0) { return invokeCommandError(command, isInternalCommand); } const modulesAnsweredPlural = modulesAnsweredLength === 1 ? 'module' : 'modules'; logger.verbose( `Successfully passed ${command} to ${modulesAnsweredLength} ${modulesAnsweredPlural}:` ); logger.verbose(modulesAnswered.join(', ')); }
[ "function", "invokeCommand", "(", "command", ",", "argv", ",", "isInternalCommand", ")", "{", "const", "globs", "=", "getGlobs", "(", ")", ";", "if", "(", "globs", ".", "length", "===", "0", ")", "{", "return", "invokeCommandError", "(", "command", ",", "isInternalCommand", ")", ";", "}", "const", "modulesAnswered", "=", "getModulesAnswered", "(", "command", ",", "argv", ",", "globs", ")", ";", "const", "modulesAnsweredLength", "=", "modulesAnswered", ".", "length", ";", "if", "(", "modulesAnsweredLength", "===", "0", ")", "{", "return", "invokeCommandError", "(", "command", ",", "isInternalCommand", ")", ";", "}", "const", "modulesAnsweredPlural", "=", "modulesAnsweredLength", "===", "1", "?", "'module'", ":", "'modules'", ";", "logger", ".", "verbose", "(", "`", "${", "command", "}", "${", "modulesAnsweredLength", "}", "${", "modulesAnsweredPlural", "}", "`", ")", ";", "logger", ".", "verbose", "(", "modulesAnswered", ".", "join", "(", "', '", ")", ")", ";", "}" ]
search for a command in the modules and invoke it if found. If not found, log a fatal error. @param {string} command @param {Object} argv @param {boolean} isInternalCommand
[ "search", "for", "a", "command", "in", "the", "modules", "and", "invoke", "it", "if", "found", ".", "If", "not", "found", "log", "a", "fatal", "error", "." ]
c579986da0cfebbe74d584781d2db9dc9524d7d2
https://github.com/blackbaud/skyux-cli/blob/c579986da0cfebbe74d584781d2db9dc9524d7d2/index.js#L114-L135
train
blackbaud/skyux-cli
index.js
getCommand
function getCommand(argv) { let command = argv._[0] || 'help'; // Allow shorthand "-v" for version if (argv.v) { command = 'version'; } // Allow shorthand "-h" for help if (argv.h) { command = 'help'; } return command; }
javascript
function getCommand(argv) { let command = argv._[0] || 'help'; // Allow shorthand "-v" for version if (argv.v) { command = 'version'; } // Allow shorthand "-h" for help if (argv.h) { command = 'help'; } return command; }
[ "function", "getCommand", "(", "argv", ")", "{", "let", "command", "=", "argv", ".", "_", "[", "0", "]", "||", "'help'", ";", "if", "(", "argv", ".", "v", ")", "{", "command", "=", "'version'", ";", "}", "if", "(", "argv", ".", "h", ")", "{", "command", "=", "'help'", ";", "}", "return", "command", ";", "}" ]
Determines the correct command based on the argv param. @param {Object} argv
[ "Determines", "the", "correct", "command", "based", "on", "the", "argv", "param", "." ]
c579986da0cfebbe74d584781d2db9dc9524d7d2
https://github.com/blackbaud/skyux-cli/blob/c579986da0cfebbe74d584781d2db9dc9524d7d2/index.js#L141-L155
train
blackbaud/skyux-cli
index.js
processArgv
function processArgv(argv) { let command = getCommand(argv); let isInternalCommand = true; logger.info(`SKY UX processing command ${command}`); switch (command) { case 'version': require('./lib/version').logVersion(argv); break; case 'new': require('./lib/new')(argv); break; case 'help': require('./lib/help')(argv); break; case 'install': require('./lib/install')(argv); break; default: isInternalCommand = false; } invokeCommand(command, argv, isInternalCommand); }
javascript
function processArgv(argv) { let command = getCommand(argv); let isInternalCommand = true; logger.info(`SKY UX processing command ${command}`); switch (command) { case 'version': require('./lib/version').logVersion(argv); break; case 'new': require('./lib/new')(argv); break; case 'help': require('./lib/help')(argv); break; case 'install': require('./lib/install')(argv); break; default: isInternalCommand = false; } invokeCommand(command, argv, isInternalCommand); }
[ "function", "processArgv", "(", "argv", ")", "{", "let", "command", "=", "getCommand", "(", "argv", ")", ";", "let", "isInternalCommand", "=", "true", ";", "logger", ".", "info", "(", "`", "${", "command", "}", "`", ")", ";", "switch", "(", "command", ")", "{", "case", "'version'", ":", "require", "(", "'./lib/version'", ")", ".", "logVersion", "(", "argv", ")", ";", "break", ";", "case", "'new'", ":", "require", "(", "'./lib/new'", ")", "(", "argv", ")", ";", "break", ";", "case", "'help'", ":", "require", "(", "'./lib/help'", ")", "(", "argv", ")", ";", "break", ";", "case", "'install'", ":", "require", "(", "'./lib/install'", ")", "(", "argv", ")", ";", "break", ";", "default", ":", "isInternalCommand", "=", "false", ";", "}", "invokeCommand", "(", "command", ",", "argv", ",", "isInternalCommand", ")", ";", "}" ]
Processes an argv object. Reads package.json if it exists. @name processArgv @param [Object] argv
[ "Processes", "an", "argv", "object", ".", "Reads", "package", ".", "json", "if", "it", "exists", "." ]
c579986da0cfebbe74d584781d2db9dc9524d7d2
https://github.com/blackbaud/skyux-cli/blob/c579986da0cfebbe74d584781d2db9dc9524d7d2/index.js#L163-L187
train
omrilotan/mono
packages/selenium-chrome-clear-cache/index.js
getSlot
function getSlot(name) { const main = document.querySelector('settings-ui').shadowRoot.children.container.children.main; const settings = findTag(main.shadowRoot.children, 'SETTINGS-BASIC-PAGE'); const advancedPage = settings.shadowRoot.children.advancedPage; const [page] = [...advancedPage.children].find(i => i.section === 'privacy').children; const dialog = findTag(page.shadowRoot.children, 'SETTINGS-CLEAR-BROWSING-DATA-DIALOG'); return dialog.shadowRoot.children.clearBrowsingDataDialog.querySelector(`[slot="${name}"]`); }
javascript
function getSlot(name) { const main = document.querySelector('settings-ui').shadowRoot.children.container.children.main; const settings = findTag(main.shadowRoot.children, 'SETTINGS-BASIC-PAGE'); const advancedPage = settings.shadowRoot.children.advancedPage; const [page] = [...advancedPage.children].find(i => i.section === 'privacy').children; const dialog = findTag(page.shadowRoot.children, 'SETTINGS-CLEAR-BROWSING-DATA-DIALOG'); return dialog.shadowRoot.children.clearBrowsingDataDialog.querySelector(`[slot="${name}"]`); }
[ "function", "getSlot", "(", "name", ")", "{", "const", "main", "=", "document", ".", "querySelector", "(", "'settings-ui'", ")", ".", "shadowRoot", ".", "children", ".", "container", ".", "children", ".", "main", ";", "const", "settings", "=", "findTag", "(", "main", ".", "shadowRoot", ".", "children", ",", "'SETTINGS-BASIC-PAGE'", ")", ";", "const", "advancedPage", "=", "settings", ".", "shadowRoot", ".", "children", ".", "advancedPage", ";", "const", "[", "page", "]", "=", "[", "...", "advancedPage", ".", "children", "]", ".", "find", "(", "i", "=>", "i", ".", "section", "===", "'privacy'", ")", ".", "children", ";", "const", "dialog", "=", "findTag", "(", "page", ".", "shadowRoot", ".", "children", ",", "'SETTINGS-CLEAR-BROWSING-DATA-DIALOG'", ")", ";", "return", "dialog", ".", "shadowRoot", ".", "children", ".", "clearBrowsingDataDialog", ".", "querySelector", "(", "`", "${", "name", "}", "`", ")", ";", "}" ]
Find UI "slot" @param {String} name @return {DOMElement}
[ "Find", "UI", "slot" ]
16c37c9584167f556d3d449cd1eeea4511278bf7
https://github.com/omrilotan/mono/blob/16c37c9584167f556d3d449cd1eeea4511278bf7/packages/selenium-chrome-clear-cache/index.js#L46-L54
train
omrilotan/mono
packages/stdline/index.js
update
function update(message) { clearLine(stdout, 0); // Clear current STDOUT line cursorTo(stdout, 0); // Place cursor at the start stdout.write(message.toString()); }
javascript
function update(message) { clearLine(stdout, 0); // Clear current STDOUT line cursorTo(stdout, 0); // Place cursor at the start stdout.write(message.toString()); }
[ "function", "update", "(", "message", ")", "{", "clearLine", "(", "stdout", ",", "0", ")", ";", "cursorTo", "(", "stdout", ",", "0", ")", ";", "stdout", ".", "write", "(", "message", ".", "toString", "(", ")", ")", ";", "}" ]
Update current STDOUT line @param {String} message no return value
[ "Update", "current", "STDOUT", "line" ]
16c37c9584167f556d3d449cd1eeea4511278bf7
https://github.com/omrilotan/mono/blob/16c37c9584167f556d3d449cd1eeea4511278bf7/packages/stdline/index.js#L22-L26
train
queicherius/gw2api-client
src/endpoints/account-blob.js
accountGuilds
function accountGuilds (client) { return client.account().get().then(account => { if (!account.guild_leader) { return [] } let requests = account.guild_leader.map(id => wrap(() => guildData(id))) return flow.parallel(requests) }) function guildData (id) { let requests = { data: wrap(() => client.guild().get(id)), members: wrap(() => client.guild(id).members().get()), ranks: wrap(() => client.guild(id).ranks().get()), stash: wrap(() => client.guild(id).stash().get()), teams: wrap(() => Promise.resolve(null)), treasury: wrap(() => client.guild(id).treasury().get()), upgrades: wrap(() => client.guild(id).upgrades().get()) } return flow.parallel(requests) } }
javascript
function accountGuilds (client) { return client.account().get().then(account => { if (!account.guild_leader) { return [] } let requests = account.guild_leader.map(id => wrap(() => guildData(id))) return flow.parallel(requests) }) function guildData (id) { let requests = { data: wrap(() => client.guild().get(id)), members: wrap(() => client.guild(id).members().get()), ranks: wrap(() => client.guild(id).ranks().get()), stash: wrap(() => client.guild(id).stash().get()), teams: wrap(() => Promise.resolve(null)), treasury: wrap(() => client.guild(id).treasury().get()), upgrades: wrap(() => client.guild(id).upgrades().get()) } return flow.parallel(requests) } }
[ "function", "accountGuilds", "(", "client", ")", "{", "return", "client", ".", "account", "(", ")", ".", "get", "(", ")", ".", "then", "(", "account", "=>", "{", "if", "(", "!", "account", ".", "guild_leader", ")", "{", "return", "[", "]", "}", "let", "requests", "=", "account", ".", "guild_leader", ".", "map", "(", "id", "=>", "wrap", "(", "(", ")", "=>", "guildData", "(", "id", ")", ")", ")", "return", "flow", ".", "parallel", "(", "requests", ")", "}", ")", "function", "guildData", "(", "id", ")", "{", "let", "requests", "=", "{", "data", ":", "wrap", "(", "(", ")", "=>", "client", ".", "guild", "(", ")", ".", "get", "(", "id", ")", ")", ",", "members", ":", "wrap", "(", "(", ")", "=>", "client", ".", "guild", "(", "id", ")", ".", "members", "(", ")", ".", "get", "(", ")", ")", ",", "ranks", ":", "wrap", "(", "(", ")", "=>", "client", ".", "guild", "(", "id", ")", ".", "ranks", "(", ")", ".", "get", "(", ")", ")", ",", "stash", ":", "wrap", "(", "(", ")", "=>", "client", ".", "guild", "(", "id", ")", ".", "stash", "(", ")", ".", "get", "(", ")", ")", ",", "teams", ":", "wrap", "(", "(", ")", "=>", "Promise", ".", "resolve", "(", "null", ")", ")", ",", "treasury", ":", "wrap", "(", "(", ")", "=>", "client", ".", "guild", "(", "id", ")", ".", "treasury", "(", ")", ".", "get", "(", ")", ")", ",", "upgrades", ":", "wrap", "(", "(", ")", "=>", "client", ".", "guild", "(", "id", ")", ".", "upgrades", "(", ")", ".", "get", "(", ")", ")", "}", "return", "flow", ".", "parallel", "(", "requests", ")", "}", "}" ]
Get the guild data accessible for the account
[ "Get", "the", "guild", "data", "accessible", "for", "the", "account" ]
a5a2f6bab89425bbbcf33eec73b7440cec5f312f
https://github.com/queicherius/gw2api-client/blob/a5a2f6bab89425bbbcf33eec73b7440cec5f312f/src/endpoints/account-blob.js#L51-L74
train
queicherius/gw2api-client
src/endpoints/account-blob.js
filterBetaCharacters
function filterBetaCharacters (characters) { /* istanbul ignore next */ if (!characters) { return null } return characters.filter(x => !x.flags || !x.flags.includes('Beta')) }
javascript
function filterBetaCharacters (characters) { /* istanbul ignore next */ if (!characters) { return null } return characters.filter(x => !x.flags || !x.flags.includes('Beta')) }
[ "function", "filterBetaCharacters", "(", "characters", ")", "{", "if", "(", "!", "characters", ")", "{", "return", "null", "}", "return", "characters", ".", "filter", "(", "x", "=>", "!", "x", ".", "flags", "||", "!", "x", ".", "flags", ".", "includes", "(", "'Beta'", ")", ")", "}" ]
Filter out beta characters from the total account blob, since they are technically not part of the actual live account and live on a different server
[ "Filter", "out", "beta", "characters", "from", "the", "total", "account", "blob", "since", "they", "are", "technically", "not", "part", "of", "the", "actual", "live", "account", "and", "live", "on", "a", "different", "server" ]
a5a2f6bab89425bbbcf33eec73b7440cec5f312f
https://github.com/queicherius/gw2api-client/blob/a5a2f6bab89425bbbcf33eec73b7440cec5f312f/src/endpoints/account-blob.js#L78-L85
train
queicherius/gw2api-client
src/endpoints/account-blob.js
unflatten
function unflatten (object) { let result = {} for (let key in object) { _set(result, key, object[key]) } return result }
javascript
function unflatten (object) { let result = {} for (let key in object) { _set(result, key, object[key]) } return result }
[ "function", "unflatten", "(", "object", ")", "{", "let", "result", "=", "{", "}", "for", "(", "let", "key", "in", "object", ")", "{", "_set", "(", "result", ",", "key", ",", "object", "[", "key", "]", ")", "}", "return", "result", "}" ]
Unflatten an object with keys describing a nested structure
[ "Unflatten", "an", "object", "with", "keys", "describing", "a", "nested", "structure" ]
a5a2f6bab89425bbbcf33eec73b7440cec5f312f
https://github.com/queicherius/gw2api-client/blob/a5a2f6bab89425bbbcf33eec73b7440cec5f312f/src/endpoints/account-blob.js#L109-L117
train
ShuyunFF2E/ccms-components
src/common/utils/style-helper/index.js
adjustTop
function adjustTop(placements, containerPosition, initialHeight, currentHeight) { if (placements.indexOf('top') !== -1 && initialHeight !== currentHeight) { return { top: containerPosition.top - currentHeight }; } }
javascript
function adjustTop(placements, containerPosition, initialHeight, currentHeight) { if (placements.indexOf('top') !== -1 && initialHeight !== currentHeight) { return { top: containerPosition.top - currentHeight }; } }
[ "function", "adjustTop", "(", "placements", ",", "containerPosition", ",", "initialHeight", ",", "currentHeight", ")", "{", "if", "(", "placements", ".", "indexOf", "(", "'top'", ")", "!==", "-", "1", "&&", "initialHeight", "!==", "currentHeight", ")", "{", "return", "{", "top", ":", "containerPosition", ".", "top", "-", "currentHeight", "}", ";", "}", "}" ]
Provides a way to adjust the top positioning after first render to correctly align element to top after content rendering causes resized element height @param {array} placements - The array of strings of classes element should have. @param {object} containerPosition - The object with container position information @param {number} initialHeight - The initial height for the elem. @param {number} currentHeight - The current height for the elem.
[ "Provides", "a", "way", "to", "adjust", "the", "top", "positioning", "after", "first", "render", "to", "correctly", "align", "element", "to", "top", "after", "content", "rendering", "causes", "resized", "element", "height" ]
a20faae817661e3da0f84b8856894891255e4a8e
https://github.com/ShuyunFF2E/ccms-components/blob/a20faae817661e3da0f84b8856894891255e4a8e/src/common/utils/style-helper/index.js#L238-L244
train
vmarchaud/pm2-githook
index.js
function (opts) { if (!(this instanceof Worker)) { return new Worker(opts); } this.opts = opts; this.port = this.opts.port || 8888; this.apps = opts.apps; if (typeof (this.apps) !== 'object') { this.apps = JSON.parse(this.apps); } this.server = http.createServer(this._handleHttp.bind(this)); return this; }
javascript
function (opts) { if (!(this instanceof Worker)) { return new Worker(opts); } this.opts = opts; this.port = this.opts.port || 8888; this.apps = opts.apps; if (typeof (this.apps) !== 'object') { this.apps = JSON.parse(this.apps); } this.server = http.createServer(this._handleHttp.bind(this)); return this; }
[ "function", "(", "opts", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Worker", ")", ")", "{", "return", "new", "Worker", "(", "opts", ")", ";", "}", "this", ".", "opts", "=", "opts", ";", "this", ".", "port", "=", "this", ".", "opts", ".", "port", "||", "8888", ";", "this", ".", "apps", "=", "opts", ".", "apps", ";", "if", "(", "typeof", "(", "this", ".", "apps", ")", "!==", "'object'", ")", "{", "this", ".", "apps", "=", "JSON", ".", "parse", "(", "this", ".", "apps", ")", ";", "}", "this", ".", "server", "=", "http", ".", "createServer", "(", "this", ".", "_handleHttp", ".", "bind", "(", "this", ")", ")", ";", "return", "this", ";", "}" ]
Constructor of our worker @param {object} opts The options @returns {Worker} The instance of our worker @constructor
[ "Constructor", "of", "our", "worker" ]
101dcbbff20216678fc456862bff0f8c1788c068
https://github.com/vmarchaud/pm2-githook/blob/101dcbbff20216678fc456862bff0f8c1788c068/index.js#L38-L53
train
vmarchaud/pm2-githook
index.js
logCallback
function logCallback(cb, message) { var wrappedArgs = Array.prototype.slice.call(arguments); return function (err, data) { if (err) return cb(err); wrappedArgs.shift(); console.log.apply(console, wrappedArgs); cb(); } }
javascript
function logCallback(cb, message) { var wrappedArgs = Array.prototype.slice.call(arguments); return function (err, data) { if (err) return cb(err); wrappedArgs.shift(); console.log.apply(console, wrappedArgs); cb(); } }
[ "function", "logCallback", "(", "cb", ",", "message", ")", "{", "var", "wrappedArgs", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "return", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "wrappedArgs", ".", "shift", "(", ")", ";", "console", ".", "log", ".", "apply", "(", "console", ",", "wrappedArgs", ")", ";", "cb", "(", ")", ";", "}", "}" ]
Executes the callback, but in case of success shows a message. Also accepts extra arguments to pass to console.log. Example: logCallback(next, '% worked perfect', appName) @param {Function} cb The callback to be called @param {string} message The message to show if success @returns {Function} The callback wrapped
[ "Executes", "the", "callback", "but", "in", "case", "of", "success", "shows", "a", "message", ".", "Also", "accepts", "extra", "arguments", "to", "pass", "to", "console", ".", "log", "." ]
101dcbbff20216678fc456862bff0f8c1788c068
https://github.com/vmarchaud/pm2-githook/blob/101dcbbff20216678fc456862bff0f8c1788c068/index.js#L286-L295
train
vmarchaud/pm2-githook
index.js
reqToAppName
function reqToAppName(req) { var targetName = null; try { targetName = req.url.split('/').pop(); } catch (e) {} return targetName || null; }
javascript
function reqToAppName(req) { var targetName = null; try { targetName = req.url.split('/').pop(); } catch (e) {} return targetName || null; }
[ "function", "reqToAppName", "(", "req", ")", "{", "var", "targetName", "=", "null", ";", "try", "{", "targetName", "=", "req", ".", "url", ".", "split", "(", "'/'", ")", ".", "pop", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "return", "targetName", "||", "null", ";", "}" ]
Given a request, returns the name of the target App. Example: Call to 34.23.34.54:3000/api-2 Will return 'api-2' @param req The request to be analysed @returns {string|null} The name of the app, or null if not found.
[ "Given", "a", "request", "returns", "the", "name", "of", "the", "target", "App", "." ]
101dcbbff20216678fc456862bff0f8c1788c068
https://github.com/vmarchaud/pm2-githook/blob/101dcbbff20216678fc456862bff0f8c1788c068/index.js#L307-L313
train
queicherius/gw2api-client
src/endpoints/account.js
isStaleDailyData
async function isStaleDailyData (endpointInstance) { const account = await new AccountEndpoint(endpointInstance).schema('2019-03-26').get() return new Date(account.last_modified) < resetTime.getLastDailyReset() }
javascript
async function isStaleDailyData (endpointInstance) { const account = await new AccountEndpoint(endpointInstance).schema('2019-03-26').get() return new Date(account.last_modified) < resetTime.getLastDailyReset() }
[ "async", "function", "isStaleDailyData", "(", "endpointInstance", ")", "{", "const", "account", "=", "await", "new", "AccountEndpoint", "(", "endpointInstance", ")", ".", "schema", "(", "'2019-03-26'", ")", ".", "get", "(", ")", "return", "new", "Date", "(", "account", ".", "last_modified", ")", "<", "resetTime", ".", "getLastDailyReset", "(", ")", "}" ]
Stale data can happen if the last account update was before the last daily reset
[ "Stale", "data", "can", "happen", "if", "the", "last", "account", "update", "was", "before", "the", "last", "daily", "reset" ]
a5a2f6bab89425bbbcf33eec73b7440cec5f312f
https://github.com/queicherius/gw2api-client/blob/a5a2f6bab89425bbbcf33eec73b7440cec5f312f/src/endpoints/account.js#L424-L427
train
queicherius/gw2api-client
src/endpoints/account.js
isStaleWeeklyData
async function isStaleWeeklyData (endpointInstance) { const account = await new AccountEndpoint(endpointInstance).schema('2019-03-26').get() return new Date(account.last_modified) < resetTime.getLastWeeklyReset() }
javascript
async function isStaleWeeklyData (endpointInstance) { const account = await new AccountEndpoint(endpointInstance).schema('2019-03-26').get() return new Date(account.last_modified) < resetTime.getLastWeeklyReset() }
[ "async", "function", "isStaleWeeklyData", "(", "endpointInstance", ")", "{", "const", "account", "=", "await", "new", "AccountEndpoint", "(", "endpointInstance", ")", ".", "schema", "(", "'2019-03-26'", ")", ".", "get", "(", ")", "return", "new", "Date", "(", "account", ".", "last_modified", ")", "<", "resetTime", ".", "getLastWeeklyReset", "(", ")", "}" ]
Stale data can happen if the last account update was before the last weekly reset
[ "Stale", "data", "can", "happen", "if", "the", "last", "account", "update", "was", "before", "the", "last", "weekly", "reset" ]
a5a2f6bab89425bbbcf33eec73b7440cec5f312f
https://github.com/queicherius/gw2api-client/blob/a5a2f6bab89425bbbcf33eec73b7440cec5f312f/src/endpoints/account.js#L430-L433
train
canjs/can-component
can-component.js
createViewModel
function createViewModel(initialData, hasDataBinding, bindingState) { if(bindingState && bindingState.isSettingOnViewModel === true) { // If we are setting a value like `x:from="y"`, // we need to make a variable scope. newScope = tagData.scope.addLetContext(initialData); return newScope._context; } else { // If we are setting the ViewModel itself, we // stick the value in an observable: `this:from="value"`. return vm = new SimpleObservable(initialData); } }
javascript
function createViewModel(initialData, hasDataBinding, bindingState) { if(bindingState && bindingState.isSettingOnViewModel === true) { // If we are setting a value like `x:from="y"`, // we need to make a variable scope. newScope = tagData.scope.addLetContext(initialData); return newScope._context; } else { // If we are setting the ViewModel itself, we // stick the value in an observable: `this:from="value"`. return vm = new SimpleObservable(initialData); } }
[ "function", "createViewModel", "(", "initialData", ",", "hasDataBinding", ",", "bindingState", ")", "{", "if", "(", "bindingState", "&&", "bindingState", ".", "isSettingOnViewModel", "===", "true", ")", "{", "newScope", "=", "tagData", ".", "scope", ".", "addLetContext", "(", "initialData", ")", ";", "return", "newScope", ".", "_context", ";", "}", "else", "{", "return", "vm", "=", "new", "SimpleObservable", "(", "initialData", ")", ";", "}", "}" ]
`createViewModel` is used to create the ViewModel that the bindings will operate on.
[ "createViewModel", "is", "used", "to", "create", "the", "ViewModel", "that", "the", "bindings", "will", "operate", "on", "." ]
bd4595ff2b7c6f2310750a5a4fa676768cf07c81
https://github.com/canjs/can-component/blob/bd4595ff2b7c6f2310750a5a4fa676768cf07c81/can-component.js#L86-L99
train
Travix-International/ui
packages/travix-ui-kit/components/spinner/spinner.js
Spinner
function Spinner(props) { warnAboutDeprecatedProp(props.mods, 'mods', 'className'); const { className, size } = props; const mods = props.mods ? props.mods.slice() : []; mods.push(`size_${size}`); const classes = classnames(getClassNamesWithMods('ui-spinner', mods), className); /* eslint-disable max-len */ return ( <div className={classes}> <svg version="1.1" viewBox="0 0 80 80" x="0px" xlinkHref="http://www.w3.org/1999/xlink" xmlSpace="preserve" xmlns="http://www.w3.org/2000/svg" y="0px" > <g> <g> <circle clipRule="evenodd" cx="40" cy="40" fillRule="evenodd" r="34.3" /> <path className="ui-spinner_darker" clipRule="evenodd" d="M39.9,33.1c0.5-5.4-1.5-10.4-5.2-14.9c6.1-2.1,7.6-1.5,8.6,3.8c0.5,2.9,0.4,6,0.1,9c-0.1,0.9-0.3,1.8-0.7,2.7c-0.8-0.3-1.8-0.6-2.7-0.6H39.9z" fillRule="evenodd" /> <path className="ui-spinner_dark" clipRule="evenodd" d="M46.6,41.9c5.3,2,10.6,2.1,16-0.3c0.8,5.6-0.3,7-5.4,6.9c-4.6,0-8.5-1.6-12-4.1C45.9,43.7,46.3,42.8,46.6,41.9z" fillRule="evenodd" /> <path className="ui-spinner_dark" clipRule="evenodd" d="M44.3,45.4c3.1,4.5,7.2,7.7,13.2,8.9c-3.2,5.1-5.1,5.5-9.2,2.1c-3.2-2.6-5.3-5.9-6.5-9.8C42.7,46.4,43.5,46,44.3,45.4z" fillRule="evenodd" /> <path className="ui-spinner_dark" clipRule="evenodd" d="M40.1,46.9c-0.1,5.6,1.3,10.4,5.3,14.5c-5.6,2.6-7.2,2-8.6-3.3c-0.5-1.8-0.8-3.7-0.6-5.6c0.2-2,0.6-4.1,1.1-6.2c0.8,0.3,1.7,0.5,2.7,0.5H40.1z" fillRule="evenodd" /> <path className="ui-spinner_dark" clipRule="evenodd" d="M36,45.5c-3.5,4.3-5,9.2-4.7,14.8c-5.7-1.2-6.8-2.7-4.9-7.3c1.1-2.5,2.6-4.8,4.4-6.8c0.9-1,2-1.9,3.3-2.8C34.6,44.3,35.2,45,36,45.5z" fillRule="evenodd" /> <path className="ui-spinner_dark" clipRule="evenodd" d="M33.5,42.1c-5.6,1.5-9.8,4.5-12.8,9.5c-4-4.2-3.9-6.4,0.6-9.1c1.6-1,3.4-1.9,5.2-2.2c2.2-0.4,4.4-0.6,6.6-0.8l0,0.5C33.1,40.7,33.2,41.5,33.5,42.1z" fillRule="evenodd" /> <path className="ui-spinner_darker" clipRule="evenodd" d="M33.5,37.9c-3.7-1.5-7.1-1.4-16,0c-1-4.9,0.3-6.5,5-6.6c4.7,0,8.8,1.6,12.4,4.1C34.2,36.2,33.8,37,33.5,37.9z" fillRule="evenodd" /> <path className="ui-spinner_darker" clipRule="evenodd" d="M35.8,34.6c-3-4.7-7.3-7.8-13.2-9c3.4-5.2,5.2-5.5,9.5-1.9c3.2,2.6,5.2,5.9,6.5,9.6C37.5,33.5,36.6,34,35.8,34.6z" fillRule="evenodd" /> <path className="ui-spinner_dark" clipRule="evenodd" d="M48,34.8c-0.5,0.7-1.4,1.1-2.1,1.6c-0.5-0.8-1.1-1.5-1.8-2c3.5-4.4,5.2-9.2,4.6-14.9c5.7,0.8,7.1,2.7,5.1,7.1C52.3,29.6,50,32.2,48,34.8z" fillRule="evenodd" /> <path className="ui-spinner_dark" clipRule="evenodd" d="M46.9,40c0-0.8-0.1-1.5-0.4-2.2c5.8-1.6,10-4.7,13.1-9.6c4.4,6.1,3.2,6.4-1.3,9.5c-1.5,1-3.3,1.7-5,2c-2.1,0.4-4.2,0.6-6.4,0.8L46.9,40z" fillRule="evenodd" /> </g> <circle className="ui-spinner_lighter" clipRule="evenodd" cx="40" cy="40" fillRule="evenodd" r="36" strokeLinecap="round" strokeLinejoin="round" strokeMiterlimit="10" strokeWidth="8" /> </g> </svg> </div> ); /* eslint-enable max-len */ }
javascript
function Spinner(props) { warnAboutDeprecatedProp(props.mods, 'mods', 'className'); const { className, size } = props; const mods = props.mods ? props.mods.slice() : []; mods.push(`size_${size}`); const classes = classnames(getClassNamesWithMods('ui-spinner', mods), className); /* eslint-disable max-len */ return ( <div className={classes}> <svg version="1.1" viewBox="0 0 80 80" x="0px" xlinkHref="http://www.w3.org/1999/xlink" xmlSpace="preserve" xmlns="http://www.w3.org/2000/svg" y="0px" > <g> <g> <circle clipRule="evenodd" cx="40" cy="40" fillRule="evenodd" r="34.3" /> <path className="ui-spinner_darker" clipRule="evenodd" d="M39.9,33.1c0.5-5.4-1.5-10.4-5.2-14.9c6.1-2.1,7.6-1.5,8.6,3.8c0.5,2.9,0.4,6,0.1,9c-0.1,0.9-0.3,1.8-0.7,2.7c-0.8-0.3-1.8-0.6-2.7-0.6H39.9z" fillRule="evenodd" /> <path className="ui-spinner_dark" clipRule="evenodd" d="M46.6,41.9c5.3,2,10.6,2.1,16-0.3c0.8,5.6-0.3,7-5.4,6.9c-4.6,0-8.5-1.6-12-4.1C45.9,43.7,46.3,42.8,46.6,41.9z" fillRule="evenodd" /> <path className="ui-spinner_dark" clipRule="evenodd" d="M44.3,45.4c3.1,4.5,7.2,7.7,13.2,8.9c-3.2,5.1-5.1,5.5-9.2,2.1c-3.2-2.6-5.3-5.9-6.5-9.8C42.7,46.4,43.5,46,44.3,45.4z" fillRule="evenodd" /> <path className="ui-spinner_dark" clipRule="evenodd" d="M40.1,46.9c-0.1,5.6,1.3,10.4,5.3,14.5c-5.6,2.6-7.2,2-8.6-3.3c-0.5-1.8-0.8-3.7-0.6-5.6c0.2-2,0.6-4.1,1.1-6.2c0.8,0.3,1.7,0.5,2.7,0.5H40.1z" fillRule="evenodd" /> <path className="ui-spinner_dark" clipRule="evenodd" d="M36,45.5c-3.5,4.3-5,9.2-4.7,14.8c-5.7-1.2-6.8-2.7-4.9-7.3c1.1-2.5,2.6-4.8,4.4-6.8c0.9-1,2-1.9,3.3-2.8C34.6,44.3,35.2,45,36,45.5z" fillRule="evenodd" /> <path className="ui-spinner_dark" clipRule="evenodd" d="M33.5,42.1c-5.6,1.5-9.8,4.5-12.8,9.5c-4-4.2-3.9-6.4,0.6-9.1c1.6-1,3.4-1.9,5.2-2.2c2.2-0.4,4.4-0.6,6.6-0.8l0,0.5C33.1,40.7,33.2,41.5,33.5,42.1z" fillRule="evenodd" /> <path className="ui-spinner_darker" clipRule="evenodd" d="M33.5,37.9c-3.7-1.5-7.1-1.4-16,0c-1-4.9,0.3-6.5,5-6.6c4.7,0,8.8,1.6,12.4,4.1C34.2,36.2,33.8,37,33.5,37.9z" fillRule="evenodd" /> <path className="ui-spinner_darker" clipRule="evenodd" d="M35.8,34.6c-3-4.7-7.3-7.8-13.2-9c3.4-5.2,5.2-5.5,9.5-1.9c3.2,2.6,5.2,5.9,6.5,9.6C37.5,33.5,36.6,34,35.8,34.6z" fillRule="evenodd" /> <path className="ui-spinner_dark" clipRule="evenodd" d="M48,34.8c-0.5,0.7-1.4,1.1-2.1,1.6c-0.5-0.8-1.1-1.5-1.8-2c3.5-4.4,5.2-9.2,4.6-14.9c5.7,0.8,7.1,2.7,5.1,7.1C52.3,29.6,50,32.2,48,34.8z" fillRule="evenodd" /> <path className="ui-spinner_dark" clipRule="evenodd" d="M46.9,40c0-0.8-0.1-1.5-0.4-2.2c5.8-1.6,10-4.7,13.1-9.6c4.4,6.1,3.2,6.4-1.3,9.5c-1.5,1-3.3,1.7-5,2c-2.1,0.4-4.2,0.6-6.4,0.8L46.9,40z" fillRule="evenodd" /> </g> <circle className="ui-spinner_lighter" clipRule="evenodd" cx="40" cy="40" fillRule="evenodd" r="36" strokeLinecap="round" strokeLinejoin="round" strokeMiterlimit="10" strokeWidth="8" /> </g> </svg> </div> ); /* eslint-enable max-len */ }
[ "function", "Spinner", "(", "props", ")", "{", "warnAboutDeprecatedProp", "(", "props", ".", "mods", ",", "'mods'", ",", "'className'", ")", ";", "const", "{", "className", ",", "size", "}", "=", "props", ";", "const", "mods", "=", "props", ".", "mods", "?", "props", ".", "mods", ".", "slice", "(", ")", ":", "[", "]", ";", "mods", ".", "push", "(", "`", "${", "size", "}", "`", ")", ";", "const", "classes", "=", "classnames", "(", "getClassNamesWithMods", "(", "'ui-spinner'", ",", "mods", ")", ",", "className", ")", ";", "return", "(", "<", "div", "className", "=", "{", "classes", "}", ">", " ", "<", "svg", "version", "=", "\"1.1\"", "viewBox", "=", "\"0 0 80 80\"", "x", "=", "\"0px\"", "xlinkHref", "=", "\"http://www.w3.org/1999/xlink\"", "xmlSpace", "=", "\"preserve\"", "xmlns", "=", "\"http://www.w3.org/2000/svg\"", "y", "=", "\"0px\"", ">", " ", "<", "g", ">", " ", "<", "g", ">", " ", "<", "circle", "clipRule", "=", "\"evenodd\"", "cx", "=", "\"40\"", "cy", "=", "\"40\"", "fillRule", "=", "\"evenodd\"", "r", "=", "\"34.3\"", "/", ">", " ", "<", "path", "className", "=", "\"ui-spinner_darker\"", "clipRule", "=", "\"evenodd\"", "d", "=", "\"M39.9,33.1c0.5-5.4-1.5-10.4-5.2-14.9c6.1-2.1,7.6-1.5,8.6,3.8c0.5,2.9,0.4,6,0.1,9c-0.1,0.9-0.3,1.8-0.7,2.7c-0.8-0.3-1.8-0.6-2.7-0.6H39.9z\"", "fillRule", "=", "\"evenodd\"", "/", ">", " ", "<", "path", "className", "=", "\"ui-spinner_dark\"", "clipRule", "=", "\"evenodd\"", "d", "=", "\"M46.6,41.9c5.3,2,10.6,2.1,16-0.3c0.8,5.6-0.3,7-5.4,6.9c-4.6,0-8.5-1.6-12-4.1C45.9,43.7,46.3,42.8,46.6,41.9z\"", "fillRule", "=", "\"evenodd\"", "/", ">", " ", "<", "path", "className", "=", "\"ui-spinner_dark\"", "clipRule", "=", "\"evenodd\"", "d", "=", "\"M44.3,45.4c3.1,4.5,7.2,7.7,13.2,8.9c-3.2,5.1-5.1,5.5-9.2,2.1c-3.2-2.6-5.3-5.9-6.5-9.8C42.7,46.4,43.5,46,44.3,45.4z\"", "fillRule", "=", "\"evenodd\"", "/", ">", " ", "<", "path", "className", "=", "\"ui-spinner_dark\"", "clipRule", "=", "\"evenodd\"", "d", "=", "\"M40.1,46.9c-0.1,5.6,1.3,10.4,5.3,14.5c-5.6,2.6-7.2,2-8.6-3.3c-0.5-1.8-0.8-3.7-0.6-5.6c0.2-2,0.6-4.1,1.1-6.2c0.8,0.3,1.7,0.5,2.7,0.5H40.1z\"", "fillRule", "=", "\"evenodd\"", "/", ">", " ", "<", "path", "className", "=", "\"ui-spinner_dark\"", "clipRule", "=", "\"evenodd\"", "d", "=", "\"M36,45.5c-3.5,4.3-5,9.2-4.7,14.8c-5.7-1.2-6.8-2.7-4.9-7.3c1.1-2.5,2.6-4.8,4.4-6.8c0.9-1,2-1.9,3.3-2.8C34.6,44.3,35.2,45,36,45.5z\"", "fillRule", "=", "\"evenodd\"", "/", ">", " ", "<", "path", "className", "=", "\"ui-spinner_dark\"", "clipRule", "=", "\"evenodd\"", "d", "=", "\"M33.5,42.1c-5.6,1.5-9.8,4.5-12.8,9.5c-4-4.2-3.9-6.4,0.6-9.1c1.6-1,3.4-1.9,5.2-2.2c2.2-0.4,4.4-0.6,6.6-0.8l0,0.5C33.1,40.7,33.2,41.5,33.5,42.1z\"", "fillRule", "=", "\"evenodd\"", "/", ">", " ", "<", "path", "className", "=", "\"ui-spinner_darker\"", "clipRule", "=", "\"evenodd\"", "d", "=", "\"M33.5,37.9c-3.7-1.5-7.1-1.4-16,0c-1-4.9,0.3-6.5,5-6.6c4.7,0,8.8,1.6,12.4,4.1C34.2,36.2,33.8,37,33.5,37.9z\"", "fillRule", "=", "\"evenodd\"", "/", ">", " ", "<", "path", "className", "=", "\"ui-spinner_darker\"", "clipRule", "=", "\"evenodd\"", "d", "=", "\"M35.8,34.6c-3-4.7-7.3-7.8-13.2-9c3.4-5.2,5.2-5.5,9.5-1.9c3.2,2.6,5.2,5.9,6.5,9.6C37.5,33.5,36.6,34,35.8,34.6z\"", "fillRule", "=", "\"evenodd\"", "/", ">", " ", "<", "path", "className", "=", "\"ui-spinner_dark\"", "clipRule", "=", "\"evenodd\"", "d", "=", "\"M48,34.8c-0.5,0.7-1.4,1.1-2.1,1.6c-0.5-0.8-1.1-1.5-1.8-2c3.5-4.4,5.2-9.2,4.6-14.9c5.7,0.8,7.1,2.7,5.1,7.1C52.3,29.6,50,32.2,48,34.8z\"", "fillRule", "=", "\"evenodd\"", "/", ">", " ", "<", "path", "className", "=", "\"ui-spinner_dark\"", "clipRule", "=", "\"evenodd\"", "d", "=", "\"M46.9,40c0-0.8-0.1-1.5-0.4-2.2c5.8-1.6,10-4.7,13.1-9.6c4.4,6.1,3.2,6.4-1.3,9.5c-1.5,1-3.3,1.7-5,2c-2.1,0.4-4.2,0.6-6.4,0.8L46.9,40z\"", "fillRule", "=", "\"evenodd\"", "/", ">", " ", "<", "/", "g", ">", " ", "<", "circle", "className", "=", "\"ui-spinner_lighter\"", "clipRule", "=", "\"evenodd\"", "cx", "=", "\"40\"", "cy", "=", "\"40\"", "fillRule", "=", "\"evenodd\"", "r", "=", "\"36\"", "strokeLinecap", "=", "\"round\"", "strokeLinejoin", "=", "\"round\"", "strokeMiterlimit", "=", "\"10\"", "strokeWidth", "=", "\"8\"", "/", ">", " ", "<", "/", "g", ">", " ", "<", "/", "svg", ">", " ", "<", "/", "div", ">", ")", ";", "}" ]
General Spinner component.
[ "General", "Spinner", "component", "." ]
f5a4446c10c039c726393ac3256183b1ecac85d1
https://github.com/Travix-International/ui/blob/f5a4446c10c039c726393ac3256183b1ecac85d1/packages/travix-ui-kit/components/spinner/spinner.js#L9-L118
train
Travix-International/ui
packages/travix-ui-kit/components/button/button.js
Button
function Button(props) { warnAboutDeprecatedProp(props.mods, 'mods', 'className'); const { children, className, dataAttrs = {}, disabled, href, id, onClick, onMouseUp, size, type, variation, } = props; const restProps = getDataAttributes(dataAttrs); const mods = props.mods ? props.mods.slice() : []; /** This props have default values */ mods.push(`size_${size}`); mods.push(`variation_${variation}`); if (disabled) { mods.push(`disabled_true`); } const classes = classnames( getClassNamesWithMods('ui-button', mods), className ); if (type === 'link') { if (!href) { console.warn('Missing href'); // eslint-disable-line no-console return null; } return ( <a {...restProps} className={classes} href={href} id={id} onMouseUp={onMouseUp} > {children} </a> ); } if (type === 'submit' || type === 'reset') { return ( <button {...restProps} className={classes} disabled={disabled} id={id} onMouseUp={onMouseUp} type={type} > {children} </button> ); } return ( <button {...restProps} className={classes} disabled={disabled} id={id} onClick={onClick} onMouseUp={onMouseUp} type="button" > {children} </button> ); }
javascript
function Button(props) { warnAboutDeprecatedProp(props.mods, 'mods', 'className'); const { children, className, dataAttrs = {}, disabled, href, id, onClick, onMouseUp, size, type, variation, } = props; const restProps = getDataAttributes(dataAttrs); const mods = props.mods ? props.mods.slice() : []; /** This props have default values */ mods.push(`size_${size}`); mods.push(`variation_${variation}`); if (disabled) { mods.push(`disabled_true`); } const classes = classnames( getClassNamesWithMods('ui-button', mods), className ); if (type === 'link') { if (!href) { console.warn('Missing href'); // eslint-disable-line no-console return null; } return ( <a {...restProps} className={classes} href={href} id={id} onMouseUp={onMouseUp} > {children} </a> ); } if (type === 'submit' || type === 'reset') { return ( <button {...restProps} className={classes} disabled={disabled} id={id} onMouseUp={onMouseUp} type={type} > {children} </button> ); } return ( <button {...restProps} className={classes} disabled={disabled} id={id} onClick={onClick} onMouseUp={onMouseUp} type="button" > {children} </button> ); }
[ "function", "Button", "(", "props", ")", "{", "warnAboutDeprecatedProp", "(", "props", ".", "mods", ",", "'mods'", ",", "'className'", ")", ";", "const", "{", "children", ",", "className", ",", "dataAttrs", "=", "{", "}", ",", "disabled", ",", "href", ",", "id", ",", "onClick", ",", "onMouseUp", ",", "size", ",", "type", ",", "variation", ",", "}", "=", "props", ";", "const", "restProps", "=", "getDataAttributes", "(", "dataAttrs", ")", ";", "const", "mods", "=", "props", ".", "mods", "?", "props", ".", "mods", ".", "slice", "(", ")", ":", "[", "]", ";", "mods", ".", "push", "(", "`", "${", "size", "}", "`", ")", ";", "mods", ".", "push", "(", "`", "${", "variation", "}", "`", ")", ";", "if", "(", "disabled", ")", "{", "mods", ".", "push", "(", "`", "`", ")", ";", "}", "const", "classes", "=", "classnames", "(", "getClassNamesWithMods", "(", "'ui-button'", ",", "mods", ")", ",", "className", ")", ";", "if", "(", "type", "===", "'link'", ")", "{", "if", "(", "!", "href", ")", "{", "console", ".", "warn", "(", "'Missing href'", ")", ";", "return", "null", ";", "}", "return", "(", "<", "a", "{", "...", "restProps", "}", "className", "=", "{", "classes", "}", "href", "=", "{", "href", "}", "id", "=", "{", "id", "}", "onMouseUp", "=", "{", "onMouseUp", "}", ">", " ", "{", "children", "}", " ", "<", "/", "a", ">", ")", ";", "}", "if", "(", "type", "===", "'submit'", "||", "type", "===", "'reset'", ")", "{", "return", "(", "<", "button", "{", "...", "restProps", "}", "className", "=", "{", "classes", "}", "disabled", "=", "{", "disabled", "}", "id", "=", "{", "id", "}", "onMouseUp", "=", "{", "onMouseUp", "}", "type", "=", "{", "type", "}", ">", " ", "{", "children", "}", " ", "<", "/", "button", ">", ")", ";", "}", "return", "(", "<", "button", "{", "...", "restProps", "}", "className", "=", "{", "classes", "}", "disabled", "=", "{", "disabled", "}", "id", "=", "{", "id", "}", "onClick", "=", "{", "onClick", "}", "onMouseUp", "=", "{", "onMouseUp", "}", "type", "=", "\"button\"", ">", " ", "{", "children", "}", " ", "<", "/", "button", ">", ")", ";", "}" ]
General Button component. Use when you need button or a link that looks like button
[ "General", "Button", "component", ".", "Use", "when", "you", "need", "button", "or", "a", "link", "that", "looks", "like", "button" ]
f5a4446c10c039c726393ac3256183b1ecac85d1
https://github.com/Travix-International/ui/blob/f5a4446c10c039c726393ac3256183b1ecac85d1/packages/travix-ui-kit/components/button/button.js#L15-L94
train
Travix-International/ui
packages/themes/index.js
getThemeFiles
function getThemeFiles({ brand, affiliate }) { return [ path.join(__dirname, '/themes/_default.yaml'), path.join(__dirname, `/themes/${brand}/_default.yaml`), path.join(__dirname, `/themes/${brand}/${affiliate.toUpperCase()}/_default.yaml`) ].filter(fs.existsSync); }
javascript
function getThemeFiles({ brand, affiliate }) { return [ path.join(__dirname, '/themes/_default.yaml'), path.join(__dirname, `/themes/${brand}/_default.yaml`), path.join(__dirname, `/themes/${brand}/${affiliate.toUpperCase()}/_default.yaml`) ].filter(fs.existsSync); }
[ "function", "getThemeFiles", "(", "{", "brand", ",", "affiliate", "}", ")", "{", "return", "[", "path", ".", "join", "(", "__dirname", ",", "'/themes/_default.yaml'", ")", ",", "path", ".", "join", "(", "__dirname", ",", "`", "${", "brand", "}", "`", ")", ",", "path", ".", "join", "(", "__dirname", ",", "`", "${", "brand", "}", "${", "affiliate", ".", "toUpperCase", "(", ")", "}", "`", ")", "]", ".", "filter", "(", "fs", ".", "existsSync", ")", ";", "}" ]
Get theme files in YAML format @param {Object} options @param {string} options.brand - cheaptickets @param {string} options.affiliate - NL @return {String}
[ "Get", "theme", "files", "in", "YAML", "format" ]
f5a4446c10c039c726393ac3256183b1ecac85d1
https://github.com/Travix-International/ui/blob/f5a4446c10c039c726393ac3256183b1ecac85d1/packages/themes/index.js#L11-L17
train
Travix-International/ui
packages/travix-ui-kit/components/calendar/calendar.js
processProps
function processProps(props) { const { initialDates, maxDate, minDate, selectionType, multiplemode } = props; const maxLimit = maxDate ? normalizeDate(getUTCDate(maxDate), 23, 59, 59, 999) : null; let renderDate = (initialDates && initialDates.length && initialDates[0]) ? getUTCDate(initialDates[0]) : new Date(); normalizeDate(renderDate); let minLimit = minDate ? normalizeDate(getUTCDate(minDate)) : null; let selectedDates = [null, null]; if (initialDates) { selectedDates = selectedDates.map((item, idx) => { if (!initialDates[idx]) { return null; } return normalizeDate(getUTCDate(initialDates[idx])); }); } /** * If a minDate or a maxDate is set, let's check if any selectedDates are outside of the boundaries. * If so, resets the selectedDates. */ if (minLimit || maxLimit) { const isAnyDateOutOfLimit = selectedDates.some(item => ( item && ( (minLimit && (minLimit.getTime() > item.getTime())) || (maxLimit && (maxLimit.getTime() < item.getTime())) ) )); if (isAnyDateOutOfLimit) { selectedDates = [null, null]; console.warn(`A calendar instance contains a selectedDate outside of the minDate and maxDate boundaries`); // eslint-disable-line } } /** If initialDates is defined and we have a start date, we want to set it as the minLimit */ if (selectedDates[0] && (selectionType === CALENDAR_SELECTION_TYPE_RANGE && !multiplemode)) { minLimit = selectedDates[0]; } /** If the renderDate is not between any of the minLimit and/or maxDate, we need to redefine it. */ if (minLimit && (renderDate.getTime() < minLimit.getTime())) { renderDate = minLimit; } else if (maxLimit && (renderDate.getTime() > maxLimit.getTime())) { renderDate = maxLimit; } return { maxLimit, minLimit, renderDate, selectedDates, }; }
javascript
function processProps(props) { const { initialDates, maxDate, minDate, selectionType, multiplemode } = props; const maxLimit = maxDate ? normalizeDate(getUTCDate(maxDate), 23, 59, 59, 999) : null; let renderDate = (initialDates && initialDates.length && initialDates[0]) ? getUTCDate(initialDates[0]) : new Date(); normalizeDate(renderDate); let minLimit = minDate ? normalizeDate(getUTCDate(minDate)) : null; let selectedDates = [null, null]; if (initialDates) { selectedDates = selectedDates.map((item, idx) => { if (!initialDates[idx]) { return null; } return normalizeDate(getUTCDate(initialDates[idx])); }); } /** * If a minDate or a maxDate is set, let's check if any selectedDates are outside of the boundaries. * If so, resets the selectedDates. */ if (minLimit || maxLimit) { const isAnyDateOutOfLimit = selectedDates.some(item => ( item && ( (minLimit && (minLimit.getTime() > item.getTime())) || (maxLimit && (maxLimit.getTime() < item.getTime())) ) )); if (isAnyDateOutOfLimit) { selectedDates = [null, null]; console.warn(`A calendar instance contains a selectedDate outside of the minDate and maxDate boundaries`); // eslint-disable-line } } /** If initialDates is defined and we have a start date, we want to set it as the minLimit */ if (selectedDates[0] && (selectionType === CALENDAR_SELECTION_TYPE_RANGE && !multiplemode)) { minLimit = selectedDates[0]; } /** If the renderDate is not between any of the minLimit and/or maxDate, we need to redefine it. */ if (minLimit && (renderDate.getTime() < minLimit.getTime())) { renderDate = minLimit; } else if (maxLimit && (renderDate.getTime() > maxLimit.getTime())) { renderDate = maxLimit; } return { maxLimit, minLimit, renderDate, selectedDates, }; }
[ "function", "processProps", "(", "props", ")", "{", "const", "{", "initialDates", ",", "maxDate", ",", "minDate", ",", "selectionType", ",", "multiplemode", "}", "=", "props", ";", "const", "maxLimit", "=", "maxDate", "?", "normalizeDate", "(", "getUTCDate", "(", "maxDate", ")", ",", "23", ",", "59", ",", "59", ",", "999", ")", ":", "null", ";", "let", "renderDate", "=", "(", "initialDates", "&&", "initialDates", ".", "length", "&&", "initialDates", "[", "0", "]", ")", "?", "getUTCDate", "(", "initialDates", "[", "0", "]", ")", ":", "new", "Date", "(", ")", ";", "normalizeDate", "(", "renderDate", ")", ";", "let", "minLimit", "=", "minDate", "?", "normalizeDate", "(", "getUTCDate", "(", "minDate", ")", ")", ":", "null", ";", "let", "selectedDates", "=", "[", "null", ",", "null", "]", ";", "if", "(", "initialDates", ")", "{", "selectedDates", "=", "selectedDates", ".", "map", "(", "(", "item", ",", "idx", ")", "=>", "{", "if", "(", "!", "initialDates", "[", "idx", "]", ")", "{", "return", "null", ";", "}", "return", "normalizeDate", "(", "getUTCDate", "(", "initialDates", "[", "idx", "]", ")", ")", ";", "}", ")", ";", "}", "if", "(", "minLimit", "||", "maxLimit", ")", "{", "const", "isAnyDateOutOfLimit", "=", "selectedDates", ".", "some", "(", "item", "=>", "(", "item", "&&", "(", "(", "minLimit", "&&", "(", "minLimit", ".", "getTime", "(", ")", ">", "item", ".", "getTime", "(", ")", ")", ")", "||", "(", "maxLimit", "&&", "(", "maxLimit", ".", "getTime", "(", ")", "<", "item", ".", "getTime", "(", ")", ")", ")", ")", ")", ")", ";", "if", "(", "isAnyDateOutOfLimit", ")", "{", "selectedDates", "=", "[", "null", ",", "null", "]", ";", "console", ".", "warn", "(", "`", "`", ")", ";", "}", "}", "if", "(", "selectedDates", "[", "0", "]", "&&", "(", "selectionType", "===", "CALENDAR_SELECTION_TYPE_RANGE", "&&", "!", "multiplemode", ")", ")", "{", "minLimit", "=", "selectedDates", "[", "0", "]", ";", "}", "if", "(", "minLimit", "&&", "(", "renderDate", ".", "getTime", "(", ")", "<", "minLimit", ".", "getTime", "(", ")", ")", ")", "{", "renderDate", "=", "minLimit", ";", "}", "else", "if", "(", "maxLimit", "&&", "(", "renderDate", ".", "getTime", "(", ")", ">", "maxLimit", ".", "getTime", "(", ")", ")", ")", "{", "renderDate", "=", "maxLimit", ";", "}", "return", "{", "maxLimit", ",", "minLimit", ",", "renderDate", ",", "selectedDates", ",", "}", ";", "}" ]
Processes the given props and the existing state and returns a new state. @function processProps @param {Object} props Props to base the new state on. @param {Object} state (Existing) state to be based on for the existing values. @return {Object} New state to be set/used. @static
[ "Processes", "the", "given", "props", "and", "the", "existing", "state", "and", "returns", "a", "new", "state", "." ]
f5a4446c10c039c726393ac3256183b1ecac85d1
https://github.com/Travix-International/ui/blob/f5a4446c10c039c726393ac3256183b1ecac85d1/packages/travix-ui-kit/components/calendar/calendar.js#L31-L87
train
Travix-International/ui
packages/theme-builder/src/processors/js.js
parseExpressions
function parseExpressions(obj, proto) { const parsedObj = Object.assign(Object.create(proto), obj); Object.keys(obj).forEach((key) => { const value = obj[key]; const fn = isObject(value) ? parseExpressions : applyTransforms; try { parsedObj[key] = fn(value, parsedObj); } catch (err) { throwDescriptiveError({ err, key, value }); } }); return parsedObj; }
javascript
function parseExpressions(obj, proto) { const parsedObj = Object.assign(Object.create(proto), obj); Object.keys(obj).forEach((key) => { const value = obj[key]; const fn = isObject(value) ? parseExpressions : applyTransforms; try { parsedObj[key] = fn(value, parsedObj); } catch (err) { throwDescriptiveError({ err, key, value }); } }); return parsedObj; }
[ "function", "parseExpressions", "(", "obj", ",", "proto", ")", "{", "const", "parsedObj", "=", "Object", ".", "assign", "(", "Object", ".", "create", "(", "proto", ")", ",", "obj", ")", ";", "Object", ".", "keys", "(", "obj", ")", ".", "forEach", "(", "(", "key", ")", "=>", "{", "const", "value", "=", "obj", "[", "key", "]", ";", "const", "fn", "=", "isObject", "(", "value", ")", "?", "parseExpressions", ":", "applyTransforms", ";", "try", "{", "parsedObj", "[", "key", "]", "=", "fn", "(", "value", ",", "parsedObj", ")", ";", "}", "catch", "(", "err", ")", "{", "throwDescriptiveError", "(", "{", "err", ",", "key", ",", "value", "}", ")", ";", "}", "}", ")", ";", "return", "parsedObj", ";", "}" ]
This function will walk a object tree and apply transformations on it @param {Object} obj @param {Object} the parent object
[ "This", "function", "will", "walk", "a", "object", "tree", "and", "apply", "transformations", "on", "it" ]
f5a4446c10c039c726393ac3256183b1ecac85d1
https://github.com/Travix-International/ui/blob/f5a4446c10c039c726393ac3256183b1ecac85d1/packages/theme-builder/src/processors/js.js#L37-L50
train
Travix-International/ui
packages/travix-ui-kit/components/_helpers.js
getDataAttributes
function getDataAttributes(attributes) { if (!attributes) { return {}; } return Object.keys(attributes).reduce((ret, key) => { ret[`data-${key.toLowerCase()}`] = attributes[key]; return ret; }, {}); }
javascript
function getDataAttributes(attributes) { if (!attributes) { return {}; } return Object.keys(attributes).reduce((ret, key) => { ret[`data-${key.toLowerCase()}`] = attributes[key]; return ret; }, {}); }
[ "function", "getDataAttributes", "(", "attributes", ")", "{", "if", "(", "!", "attributes", ")", "{", "return", "{", "}", ";", "}", "return", "Object", ".", "keys", "(", "attributes", ")", ".", "reduce", "(", "(", "ret", ",", "key", ")", "=>", "{", "ret", "[", "`", "${", "key", ".", "toLowerCase", "(", ")", "}", "`", "]", "=", "attributes", "[", "key", "]", ";", "return", "ret", ";", "}", ",", "{", "}", ")", ";", "}" ]
Creates an object of data-attributes based on another given attributes' object. @param {Object} attributes Attributes to be added to a component as a data-* @return {Object} Returns an object with the attributes properly prefixed with 'data-'
[ "Creates", "an", "object", "of", "data", "-", "attributes", "based", "on", "another", "given", "attributes", "object", "." ]
f5a4446c10c039c726393ac3256183b1ecac85d1
https://github.com/Travix-International/ui/blob/f5a4446c10c039c726393ac3256183b1ecac85d1/packages/travix-ui-kit/components/_helpers.js#L29-L38
train
Travix-International/ui
packages/travix-ui-kit/components/_helpers.js
normalizeDate
function normalizeDate(dateObject, hours = 0, minutes = 0, seconds = 0, milliseconds = 0) { dateObject.setHours(hours); dateObject.setMinutes(minutes); dateObject.setSeconds(seconds); dateObject.setMilliseconds(milliseconds); return dateObject; }
javascript
function normalizeDate(dateObject, hours = 0, minutes = 0, seconds = 0, milliseconds = 0) { dateObject.setHours(hours); dateObject.setMinutes(minutes); dateObject.setSeconds(seconds); dateObject.setMilliseconds(milliseconds); return dateObject; }
[ "function", "normalizeDate", "(", "dateObject", ",", "hours", "=", "0", ",", "minutes", "=", "0", ",", "seconds", "=", "0", ",", "milliseconds", "=", "0", ")", "{", "dateObject", ".", "setHours", "(", "hours", ")", ";", "dateObject", ".", "setMinutes", "(", "minutes", ")", ";", "dateObject", ".", "setSeconds", "(", "seconds", ")", ";", "dateObject", ".", "setMilliseconds", "(", "milliseconds", ")", ";", "return", "dateObject", ";", "}" ]
Receives a date object and normalizes it to the proper hours, minutes, seconds and milliseconds. @method normalizeDate @param {Date} dateObject Date object to be normalized. @param {Number} hours Value to set the hours to. Defaults to 0 @param {Number} minutes Value to set the minutes to. Defaults to 0 @param {Number} seconds Value to set the seconds to. Defaults to 0 @param {Number} milliseconds Value to set the milliseconds to. Defaults to 0 @return {Date} The normalized date object.
[ "Receives", "a", "date", "object", "and", "normalizes", "it", "to", "the", "proper", "hours", "minutes", "seconds", "and", "milliseconds", "." ]
f5a4446c10c039c726393ac3256183b1ecac85d1
https://github.com/Travix-International/ui/blob/f5a4446c10c039c726393ac3256183b1ecac85d1/packages/travix-ui-kit/components/_helpers.js#L66-L72
train
Travix-International/ui
packages/travix-ui-kit/components/_helpers.js
ejectOtherProps
function ejectOtherProps(props, propTypes) { const propTypesKeys = Object.keys(propTypes); return Object.keys(props) .filter(x => propTypesKeys.indexOf(x) === -1) .reduce((prev, item) => { return { ...prev, [item]: props[item] }; }, {}); }
javascript
function ejectOtherProps(props, propTypes) { const propTypesKeys = Object.keys(propTypes); return Object.keys(props) .filter(x => propTypesKeys.indexOf(x) === -1) .reduce((prev, item) => { return { ...prev, [item]: props[item] }; }, {}); }
[ "function", "ejectOtherProps", "(", "props", ",", "propTypes", ")", "{", "const", "propTypesKeys", "=", "Object", ".", "keys", "(", "propTypes", ")", ";", "return", "Object", ".", "keys", "(", "props", ")", ".", "filter", "(", "x", "=>", "propTypesKeys", ".", "indexOf", "(", "x", ")", "===", "-", "1", ")", ".", "reduce", "(", "(", "prev", ",", "item", ")", "=>", "{", "return", "{", "...", "prev", ",", "[", "item", "]", ":", "props", "[", "item", "]", "}", ";", "}", ",", "{", "}", ")", ";", "}" ]
Eject real custom users props from props @method ejectOtherProps @param {Object} props conponent props. @param {Object} propTypes conponent props types. @return {Object} custom props.
[ "Eject", "real", "custom", "users", "props", "from", "props" ]
f5a4446c10c039c726393ac3256183b1ecac85d1
https://github.com/Travix-International/ui/blob/f5a4446c10c039c726393ac3256183b1ecac85d1/packages/travix-ui-kit/components/_helpers.js#L82-L89
train
Travix-International/ui
packages/travix-ui-kit/components/_helpers.js
warnAboutDeprecatedProp
function warnAboutDeprecatedProp(propValue, oldPropName, newPropName) { if (propValue !== undefined) { console.warn(`[DEPRECATED] the property "${oldPropName}" has been deprecated, use "${newPropName}" instead`); } }
javascript
function warnAboutDeprecatedProp(propValue, oldPropName, newPropName) { if (propValue !== undefined) { console.warn(`[DEPRECATED] the property "${oldPropName}" has been deprecated, use "${newPropName}" instead`); } }
[ "function", "warnAboutDeprecatedProp", "(", "propValue", ",", "oldPropName", ",", "newPropName", ")", "{", "if", "(", "propValue", "!==", "undefined", ")", "{", "console", ".", "warn", "(", "`", "${", "oldPropName", "}", "${", "newPropName", "}", "`", ")", ";", "}", "}" ]
Warn about usage of deprecated prop @method warnAboutDeprecatedProp @param {Any} propValue value of deprecated prop. @param {String} oldPropName deprecated prop name. @param {String} newPropName new prop name.
[ "Warn", "about", "usage", "of", "deprecated", "prop" ]
f5a4446c10c039c726393ac3256183b1ecac85d1
https://github.com/Travix-International/ui/blob/f5a4446c10c039c726393ac3256183b1ecac85d1/packages/travix-ui-kit/components/_helpers.js#L99-L103
train
Travix-International/ui
packages/travix-ui-kit/components/list/list.js
List
function List(props) { warnAboutDeprecatedProp(props.mods, 'mods', 'className'); const { align, className, dataAttrs, hideBullets, items, } = props; const mods = props.mods ? props.mods.slice() : []; mods.push(`align_${align}`); if (hideBullets) { mods.push("no-bullets"); } const listClasses = classNames(getClassNamesWithMods('ui-list', mods), className); const itemsBlock = items.filter(Boolean).map((item, index) => ( <li className="ui-list__item" key={index}> {item} </li> )); return ( <ul className={listClasses} {...getDataAttributes(dataAttrs)}> {itemsBlock} </ul> ); }
javascript
function List(props) { warnAboutDeprecatedProp(props.mods, 'mods', 'className'); const { align, className, dataAttrs, hideBullets, items, } = props; const mods = props.mods ? props.mods.slice() : []; mods.push(`align_${align}`); if (hideBullets) { mods.push("no-bullets"); } const listClasses = classNames(getClassNamesWithMods('ui-list', mods), className); const itemsBlock = items.filter(Boolean).map((item, index) => ( <li className="ui-list__item" key={index}> {item} </li> )); return ( <ul className={listClasses} {...getDataAttributes(dataAttrs)}> {itemsBlock} </ul> ); }
[ "function", "List", "(", "props", ")", "{", "warnAboutDeprecatedProp", "(", "props", ".", "mods", ",", "'mods'", ",", "'className'", ")", ";", "const", "{", "align", ",", "className", ",", "dataAttrs", ",", "hideBullets", ",", "items", ",", "}", "=", "props", ";", "const", "mods", "=", "props", ".", "mods", "?", "props", ".", "mods", ".", "slice", "(", ")", ":", "[", "]", ";", "mods", ".", "push", "(", "`", "${", "align", "}", "`", ")", ";", "if", "(", "hideBullets", ")", "{", "mods", ".", "push", "(", "\"no-bullets\"", ")", ";", "}", "const", "listClasses", "=", "classNames", "(", "getClassNamesWithMods", "(", "'ui-list'", ",", "mods", ")", ",", "className", ")", ";", "const", "itemsBlock", "=", "items", ".", "filter", "(", "Boolean", ")", ".", "map", "(", "(", "item", ",", "index", ")", "=>", "(", "<", "li", "className", "=", "\"ui-list__item\"", "key", "=", "{", "index", "}", ">", " ", "{", "item", "}", " ", "<", "/", "li", ">", ")", ")", ";", "return", "(", "<", "ul", "className", "=", "{", "listClasses", "}", "{", "...", "getDataAttributes", "(", "dataAttrs", ")", "}", ">", " ", "{", "itemsBlock", "}", " ", "<", "/", "ul", ">", ")", ";", "}" ]
General List component. Use when you need to display array of elements
[ "General", "List", "component", ".", "Use", "when", "you", "need", "to", "display", "array", "of", "elements" ]
f5a4446c10c039c726393ac3256183b1ecac85d1
https://github.com/Travix-International/ui/blob/f5a4446c10c039c726393ac3256183b1ecac85d1/packages/travix-ui-kit/components/list/list.js#L10-L42
train
Travix-International/ui
packages/travix-ui-kit/components/checkbox/checkbox.js
Checkbox
function Checkbox(props) { warnAboutDeprecatedProp(props.mods, 'mods', 'className'); const { checked, children, className, dataAttrs = {}, disabled, inputDataAttrs = {}, name, onChange, } = props; const dataAttributes = getDataAttributes(dataAttrs); const inputDataAttributes = getDataAttributes(inputDataAttrs); const mods = props.mods ? props.mods.slice() : []; disabled && mods.push('is-disabled'); const classNames = classnames(getClassNamesWithMods('ui-checkbox', mods), className); return ( <label {...dataAttributes} className={classNames} htmlFor={name} > <input {...inputDataAttributes} aria-checked={checked} checked={checked} disabled={disabled} id={name} onChange={onChange} readOnly={!onChange} role="radio" type="checkbox" /> <span className="ui-checkbox__text"> {children} </span> </label> ); }
javascript
function Checkbox(props) { warnAboutDeprecatedProp(props.mods, 'mods', 'className'); const { checked, children, className, dataAttrs = {}, disabled, inputDataAttrs = {}, name, onChange, } = props; const dataAttributes = getDataAttributes(dataAttrs); const inputDataAttributes = getDataAttributes(inputDataAttrs); const mods = props.mods ? props.mods.slice() : []; disabled && mods.push('is-disabled'); const classNames = classnames(getClassNamesWithMods('ui-checkbox', mods), className); return ( <label {...dataAttributes} className={classNames} htmlFor={name} > <input {...inputDataAttributes} aria-checked={checked} checked={checked} disabled={disabled} id={name} onChange={onChange} readOnly={!onChange} role="radio" type="checkbox" /> <span className="ui-checkbox__text"> {children} </span> </label> ); }
[ "function", "Checkbox", "(", "props", ")", "{", "warnAboutDeprecatedProp", "(", "props", ".", "mods", ",", "'mods'", ",", "'className'", ")", ";", "const", "{", "checked", ",", "children", ",", "className", ",", "dataAttrs", "=", "{", "}", ",", "disabled", ",", "inputDataAttrs", "=", "{", "}", ",", "name", ",", "onChange", ",", "}", "=", "props", ";", "const", "dataAttributes", "=", "getDataAttributes", "(", "dataAttrs", ")", ";", "const", "inputDataAttributes", "=", "getDataAttributes", "(", "inputDataAttrs", ")", ";", "const", "mods", "=", "props", ".", "mods", "?", "props", ".", "mods", ".", "slice", "(", ")", ":", "[", "]", ";", "disabled", "&&", "mods", ".", "push", "(", "'is-disabled'", ")", ";", "const", "classNames", "=", "classnames", "(", "getClassNamesWithMods", "(", "'ui-checkbox'", ",", "mods", ")", ",", "className", ")", ";", "return", "(", "<", "label", "{", "...", "dataAttributes", "}", "className", "=", "{", "classNames", "}", "htmlFor", "=", "{", "name", "}", ">", " ", "<", "input", "{", "...", "inputDataAttributes", "}", "aria-checked", "=", "{", "checked", "}", "checked", "=", "{", "checked", "}", "disabled", "=", "{", "disabled", "}", "id", "=", "{", "name", "}", "onChange", "=", "{", "onChange", "}", "readOnly", "=", "{", "!", "onChange", "}", "role", "=", "\"radio\"", "type", "=", "\"checkbox\"", "/", ">", " ", "<", "span", "className", "=", "\"ui-checkbox__text\"", ">", " ", "{", "children", "}", " ", "<", "/", "span", ">", " ", "<", "/", "label", ">", ")", ";", "}" ]
Checkbox component.
[ "Checkbox", "component", "." ]
f5a4446c10c039c726393ac3256183b1ecac85d1
https://github.com/Travix-International/ui/blob/f5a4446c10c039c726393ac3256183b1ecac85d1/packages/travix-ui-kit/components/checkbox/checkbox.js#L11-L53
train
Travix-International/ui
packages/css-themes-polyfill/src/index.js
parseExternalLink
function parseExternalLink(elem) { var path = elem.href; elem.setAttribute('data-parsed', true); var rawFile = new XMLHttpRequest(); rawFile.open('GET', path, true); rawFile.onreadystatechange = function processStylesFile() { if (rawFile.readyState === 4 && (rawFile.status === 200 || rawFile.status === 0)) { var styleEl = document.createElement('style'); document.head.appendChild(styleEl); styleEl.innerText = window.cssThemeService(rawFile.responseText); } }; rawFile.send(null); }
javascript
function parseExternalLink(elem) { var path = elem.href; elem.setAttribute('data-parsed', true); var rawFile = new XMLHttpRequest(); rawFile.open('GET', path, true); rawFile.onreadystatechange = function processStylesFile() { if (rawFile.readyState === 4 && (rawFile.status === 200 || rawFile.status === 0)) { var styleEl = document.createElement('style'); document.head.appendChild(styleEl); styleEl.innerText = window.cssThemeService(rawFile.responseText); } }; rawFile.send(null); }
[ "function", "parseExternalLink", "(", "elem", ")", "{", "var", "path", "=", "elem", ".", "href", ";", "elem", ".", "setAttribute", "(", "'data-parsed'", ",", "true", ")", ";", "var", "rawFile", "=", "new", "XMLHttpRequest", "(", ")", ";", "rawFile", ".", "open", "(", "'GET'", ",", "path", ",", "true", ")", ";", "rawFile", ".", "onreadystatechange", "=", "function", "processStylesFile", "(", ")", "{", "if", "(", "rawFile", ".", "readyState", "===", "4", "&&", "(", "rawFile", ".", "status", "===", "200", "||", "rawFile", ".", "status", "===", "0", ")", ")", "{", "var", "styleEl", "=", "document", ".", "createElement", "(", "'style'", ")", ";", "document", ".", "head", ".", "appendChild", "(", "styleEl", ")", ";", "styleEl", ".", "innerText", "=", "window", ".", "cssThemeService", "(", "rawFile", ".", "responseText", ")", ";", "}", "}", ";", "rawFile", ".", "send", "(", "null", ")", ";", "}" ]
Load and parse external Link tags
[ "Load", "and", "parse", "external", "Link", "tags" ]
f5a4446c10c039c726393ac3256183b1ecac85d1
https://github.com/Travix-International/ui/blob/f5a4446c10c039c726393ac3256183b1ecac85d1/packages/css-themes-polyfill/src/index.js#L19-L33
train
cozy/cozy-bar
src/lib/realtime.js
initializeRealtime
async function initializeRealtime({ getApp, onCreate, onDelete, url, token }) { const realtimeConfig = { token, url } try { realtime .subscribe(realtimeConfig, APPS_DOCTYPE) .onCreate(async app => { // Fetch directly the app to get attributes `related` as well. let fullApp try { fullApp = await getApp(app.slug) } catch (error) { throw new Error(`Cannot fetch app ${app.slug}: ${error.message}`) } if (typeof onCreate === 'function') { onCreate(fullApp) } }) .onDelete(app => { if (typeof onDelete === 'function') { onDelete(app) } }) } catch (error) { console.warn(`Cannot initialize realtime in Cozy-bar: ${error.message}`) } }
javascript
async function initializeRealtime({ getApp, onCreate, onDelete, url, token }) { const realtimeConfig = { token, url } try { realtime .subscribe(realtimeConfig, APPS_DOCTYPE) .onCreate(async app => { // Fetch directly the app to get attributes `related` as well. let fullApp try { fullApp = await getApp(app.slug) } catch (error) { throw new Error(`Cannot fetch app ${app.slug}: ${error.message}`) } if (typeof onCreate === 'function') { onCreate(fullApp) } }) .onDelete(app => { if (typeof onDelete === 'function') { onDelete(app) } }) } catch (error) { console.warn(`Cannot initialize realtime in Cozy-bar: ${error.message}`) } }
[ "async", "function", "initializeRealtime", "(", "{", "getApp", ",", "onCreate", ",", "onDelete", ",", "url", ",", "token", "}", ")", "{", "const", "realtimeConfig", "=", "{", "token", ",", "url", "}", "try", "{", "realtime", ".", "subscribe", "(", "realtimeConfig", ",", "APPS_DOCTYPE", ")", ".", "onCreate", "(", "async", "app", "=>", "{", "let", "fullApp", "try", "{", "fullApp", "=", "await", "getApp", "(", "app", ".", "slug", ")", "}", "catch", "(", "error", ")", "{", "throw", "new", "Error", "(", "`", "${", "app", ".", "slug", "}", "${", "error", ".", "message", "}", "`", ")", "}", "if", "(", "typeof", "onCreate", "===", "'function'", ")", "{", "onCreate", "(", "fullApp", ")", "}", "}", ")", ".", "onDelete", "(", "app", "=>", "{", "if", "(", "typeof", "onDelete", "===", "'function'", ")", "{", "onDelete", "(", "app", ")", "}", "}", ")", "}", "catch", "(", "error", ")", "{", "console", ".", "warn", "(", "`", "${", "error", ".", "message", "}", "`", ")", "}", "}" ]
Initialize realtime sockets @private @param {object} @returns {Promise}
[ "Initialize", "realtime", "sockets" ]
0db02c97cada3f11193a95a250587eda4f284df1
https://github.com/cozy/cozy-bar/blob/0db02c97cada3f11193a95a250587eda4f284df1/src/lib/realtime.js#L12-L39
train
cozy/cozy-bar
src/lib/stack-internal.js
cozyFetchJSON
function cozyFetchJSON(cozy, method, path, body) { const requestOptions = Object.assign({}, fetchOptions(), { method }) requestOptions.headers['Accept'] = 'application/json' if (method !== 'GET' && method !== 'HEAD' && body !== undefined) { if (requestOptions.headers['Content-Type']) { requestOptions.body = body } else { requestOptions.headers['Content-Type'] = 'application/json' requestOptions.body = JSON.stringify(body) } } return fetchJSON(`${COZY_URL}${path}`, requestOptions).then(json => { const responseData = Object.assign({}, json.data) if (responseData.id) responseData._id = responseData.id return Promise.resolve(responseData) }) }
javascript
function cozyFetchJSON(cozy, method, path, body) { const requestOptions = Object.assign({}, fetchOptions(), { method }) requestOptions.headers['Accept'] = 'application/json' if (method !== 'GET' && method !== 'HEAD' && body !== undefined) { if (requestOptions.headers['Content-Type']) { requestOptions.body = body } else { requestOptions.headers['Content-Type'] = 'application/json' requestOptions.body = JSON.stringify(body) } } return fetchJSON(`${COZY_URL}${path}`, requestOptions).then(json => { const responseData = Object.assign({}, json.data) if (responseData.id) responseData._id = responseData.id return Promise.resolve(responseData) }) }
[ "function", "cozyFetchJSON", "(", "cozy", ",", "method", ",", "path", ",", "body", ")", "{", "const", "requestOptions", "=", "Object", ".", "assign", "(", "{", "}", ",", "fetchOptions", "(", ")", ",", "{", "method", "}", ")", "requestOptions", ".", "headers", "[", "'Accept'", "]", "=", "'application/json'", "if", "(", "method", "!==", "'GET'", "&&", "method", "!==", "'HEAD'", "&&", "body", "!==", "undefined", ")", "{", "if", "(", "requestOptions", ".", "headers", "[", "'Content-Type'", "]", ")", "{", "requestOptions", ".", "body", "=", "body", "}", "else", "{", "requestOptions", ".", "headers", "[", "'Content-Type'", "]", "=", "'application/json'", "requestOptions", ".", "body", "=", "JSON", ".", "stringify", "(", "body", ")", "}", "}", "return", "fetchJSON", "(", "`", "${", "COZY_URL", "}", "${", "path", "}", "`", ",", "requestOptions", ")", ".", "then", "(", "json", "=>", "{", "const", "responseData", "=", "Object", ".", "assign", "(", "{", "}", ",", "json", ".", "data", ")", "if", "(", "responseData", ".", "id", ")", "responseData", ".", "_id", "=", "responseData", ".", "id", "return", "Promise", ".", "resolve", "(", "responseData", ")", "}", ")", "}" ]
fetch function with the same interface than in cozy-client-js
[ "fetch", "function", "with", "the", "same", "interface", "than", "in", "cozy", "-", "client", "-", "js" ]
0db02c97cada3f11193a95a250587eda4f284df1
https://github.com/cozy/cozy-bar/blob/0db02c97cada3f11193a95a250587eda4f284df1/src/lib/stack-internal.js#L62-L80
train
mongodb-js/connection-model
lib/model.js
function(attrs) { if (!attrs.ssl || includes(['NONE', 'UNVALIDATED', 'IFAVAILABLE', 'SYSTEMCA'], attrs.ssl)) { return; } if (attrs.ssl === 'SERVER' && !attrs.ssl_ca) { throw new TypeError('ssl_ca is required when ssl is SERVER.'); } else if (attrs.ssl === 'ALL') { if (!attrs.ssl_ca) { throw new TypeError('ssl_ca is required when ssl is ALL.'); } if (!attrs.ssl_private_key) { throw new TypeError('ssl_private_key is required when ssl is ALL.'); } if (!attrs.ssl_certificate) { throw new TypeError('ssl_certificate is required when ssl is ALL.'); } } }
javascript
function(attrs) { if (!attrs.ssl || includes(['NONE', 'UNVALIDATED', 'IFAVAILABLE', 'SYSTEMCA'], attrs.ssl)) { return; } if (attrs.ssl === 'SERVER' && !attrs.ssl_ca) { throw new TypeError('ssl_ca is required when ssl is SERVER.'); } else if (attrs.ssl === 'ALL') { if (!attrs.ssl_ca) { throw new TypeError('ssl_ca is required when ssl is ALL.'); } if (!attrs.ssl_private_key) { throw new TypeError('ssl_private_key is required when ssl is ALL.'); } if (!attrs.ssl_certificate) { throw new TypeError('ssl_certificate is required when ssl is ALL.'); } } }
[ "function", "(", "attrs", ")", "{", "if", "(", "!", "attrs", ".", "ssl", "||", "includes", "(", "[", "'NONE'", ",", "'UNVALIDATED'", ",", "'IFAVAILABLE'", ",", "'SYSTEMCA'", "]", ",", "attrs", ".", "ssl", ")", ")", "{", "return", ";", "}", "if", "(", "attrs", ".", "ssl", "===", "'SERVER'", "&&", "!", "attrs", ".", "ssl_ca", ")", "{", "throw", "new", "TypeError", "(", "'ssl_ca is required when ssl is SERVER.'", ")", ";", "}", "else", "if", "(", "attrs", ".", "ssl", "===", "'ALL'", ")", "{", "if", "(", "!", "attrs", ".", "ssl_ca", ")", "{", "throw", "new", "TypeError", "(", "'ssl_ca is required when ssl is ALL.'", ")", ";", "}", "if", "(", "!", "attrs", ".", "ssl_private_key", ")", "{", "throw", "new", "TypeError", "(", "'ssl_private_key is required when ssl is ALL.'", ")", ";", "}", "if", "(", "!", "attrs", ".", "ssl_certificate", ")", "{", "throw", "new", "TypeError", "(", "'ssl_certificate is required when ssl is ALL.'", ")", ";", "}", "}", "}" ]
Enforce constraints for SSL. @param {Object} attrs - Incoming attributes.
[ "Enforce", "constraints", "for", "SSL", "." ]
1e58ed4da67c44acd0f631881bffceb2d4d614e6
https://github.com/mongodb-js/connection-model/blob/1e58ed4da67c44acd0f631881bffceb2d4d614e6/lib/model.js#L928-L947
train
mongodb-js/connection-model
lib/model.js
function(attrs) { if (attrs.authentication !== 'KERBEROS') { if (attrs.kerberos_service_name) { throw new TypeError(format( 'The kerberos_service_name field does not apply when ' + 'using %s for authentication.', attrs.authentication)); } if (attrs.kerberos_principal) { throw new TypeError(format( 'The kerberos_principal field does not apply when ' + 'using %s for authentication.', attrs.authentication)); } if (attrs.kerberos_password) { throw new TypeError(format( 'The kerberos_password field does not apply when ' + 'using %s for authentication.', attrs.authentication)); } } if (attrs.authentication === 'KERBEROS') { if (!attrs.kerberos_principal) { throw new TypeError(format( 'The kerberos_principal field is required when ' + 'using KERBEROS for authentication.')); } } }
javascript
function(attrs) { if (attrs.authentication !== 'KERBEROS') { if (attrs.kerberos_service_name) { throw new TypeError(format( 'The kerberos_service_name field does not apply when ' + 'using %s for authentication.', attrs.authentication)); } if (attrs.kerberos_principal) { throw new TypeError(format( 'The kerberos_principal field does not apply when ' + 'using %s for authentication.', attrs.authentication)); } if (attrs.kerberos_password) { throw new TypeError(format( 'The kerberos_password field does not apply when ' + 'using %s for authentication.', attrs.authentication)); } } if (attrs.authentication === 'KERBEROS') { if (!attrs.kerberos_principal) { throw new TypeError(format( 'The kerberos_principal field is required when ' + 'using KERBEROS for authentication.')); } } }
[ "function", "(", "attrs", ")", "{", "if", "(", "attrs", ".", "authentication", "!==", "'KERBEROS'", ")", "{", "if", "(", "attrs", ".", "kerberos_service_name", ")", "{", "throw", "new", "TypeError", "(", "format", "(", "'The kerberos_service_name field does not apply when '", "+", "'using %s for authentication.'", ",", "attrs", ".", "authentication", ")", ")", ";", "}", "if", "(", "attrs", ".", "kerberos_principal", ")", "{", "throw", "new", "TypeError", "(", "format", "(", "'The kerberos_principal field does not apply when '", "+", "'using %s for authentication.'", ",", "attrs", ".", "authentication", ")", ")", ";", "}", "if", "(", "attrs", ".", "kerberos_password", ")", "{", "throw", "new", "TypeError", "(", "format", "(", "'The kerberos_password field does not apply when '", "+", "'using %s for authentication.'", ",", "attrs", ".", "authentication", ")", ")", ";", "}", "}", "if", "(", "attrs", ".", "authentication", "===", "'KERBEROS'", ")", "{", "if", "(", "!", "attrs", ".", "kerberos_principal", ")", "{", "throw", "new", "TypeError", "(", "format", "(", "'The kerberos_principal field is required when '", "+", "'using KERBEROS for authentication.'", ")", ")", ";", "}", "}", "}" ]
Enforce constraints for Kerberos. @param {Object} attrs - Incoming attributes.
[ "Enforce", "constraints", "for", "Kerberos", "." ]
1e58ed4da67c44acd0f631881bffceb2d4d614e6
https://github.com/mongodb-js/connection-model/blob/1e58ed4da67c44acd0f631881bffceb2d4d614e6/lib/model.js#L967-L993
train
mongodb-js/connection-model
lib/connect.js
validateURL
function validateURL(model, done) { var url = model.driver_url; parseURL(url, {}, function(err, result) { // URL parsing errors are just generic `Error` instances // so overwrite name so mongodb-js-server will know // the message is safe to display. if (err) { err.name = 'MongoError'; } done(err, result); }); }
javascript
function validateURL(model, done) { var url = model.driver_url; parseURL(url, {}, function(err, result) { // URL parsing errors are just generic `Error` instances // so overwrite name so mongodb-js-server will know // the message is safe to display. if (err) { err.name = 'MongoError'; } done(err, result); }); }
[ "function", "validateURL", "(", "model", ",", "done", ")", "{", "var", "url", "=", "model", ".", "driver_url", ";", "parseURL", "(", "url", ",", "{", "}", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "err", ".", "name", "=", "'MongoError'", ";", "}", "done", "(", "err", ",", "result", ")", ";", "}", ")", ";", "}" ]
Make sure the driver doesn't puke on the URL and cause an uncaughtException. @param {Connection} model @param {Function} done
[ "Make", "sure", "the", "driver", "doesn", "t", "puke", "on", "the", "URL", "and", "cause", "an", "uncaughtException", "." ]
1e58ed4da67c44acd0f631881bffceb2d4d614e6
https://github.com/mongodb-js/connection-model/blob/1e58ed4da67c44acd0f631881bffceb2d4d614e6/lib/connect.js#L74-L85
train
ihh/bracery
lambda/bracery-util.js
httpsRequest
async function httpsRequest (opts, formData) { return new Promise ((resolve, reject) => { let req = https.request (opts, (res) => { let data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { resolve ([res, data]); }); }); if (formData) req.write (formData); req.end(); }); }
javascript
async function httpsRequest (opts, formData) { return new Promise ((resolve, reject) => { let req = https.request (opts, (res) => { let data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { resolve ([res, data]); }); }); if (formData) req.write (formData); req.end(); }); }
[ "async", "function", "httpsRequest", "(", "opts", ",", "formData", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "let", "req", "=", "https", ".", "request", "(", "opts", ",", "(", "res", ")", "=>", "{", "let", "data", "=", "''", ";", "res", ".", "on", "(", "'data'", ",", "(", "chunk", ")", "=>", "{", "data", "+=", "chunk", ";", "}", ")", ";", "res", ".", "on", "(", "'end'", ",", "(", ")", "=>", "{", "resolve", "(", "[", "res", ",", "data", "]", ")", ";", "}", ")", ";", "}", ")", ";", "if", "(", "formData", ")", "req", ".", "write", "(", "formData", ")", ";", "req", ".", "end", "(", ")", ";", "}", ")", ";", "}" ]
async https.request
[ "async", "https", ".", "request" ]
ad52f4be347b5c0c07da38b647f9fd2854aee96a
https://github.com/ihh/bracery/blob/ad52f4be347b5c0c07da38b647f9fd2854aee96a/lambda/bracery-util.js#L119-L133
train
ihh/bracery
src/parsetree.js
makeFuncArgTree
function makeFuncArgTree (pt, args, makeSymbolName, forceBraces, allowNakedSymbol) { var noBraces = !forceBraces && args.length === 1 && (args[0].type === 'func' || args[0].type === 'lookup' || args[0].type === 'alt' || (allowNakedSymbol && isPlainSymExpr(args[0]))) return [noBraces ? '' : leftBraceChar, pt.makeRhsTree (args, makeSymbolName), noBraces ? '' : rightBraceChar] }
javascript
function makeFuncArgTree (pt, args, makeSymbolName, forceBraces, allowNakedSymbol) { var noBraces = !forceBraces && args.length === 1 && (args[0].type === 'func' || args[0].type === 'lookup' || args[0].type === 'alt' || (allowNakedSymbol && isPlainSymExpr(args[0]))) return [noBraces ? '' : leftBraceChar, pt.makeRhsTree (args, makeSymbolName), noBraces ? '' : rightBraceChar] }
[ "function", "makeFuncArgTree", "(", "pt", ",", "args", ",", "makeSymbolName", ",", "forceBraces", ",", "allowNakedSymbol", ")", "{", "var", "noBraces", "=", "!", "forceBraces", "&&", "args", ".", "length", "===", "1", "&&", "(", "args", "[", "0", "]", ".", "type", "===", "'func'", "||", "args", "[", "0", "]", ".", "type", "===", "'lookup'", "||", "args", "[", "0", "]", ".", "type", "===", "'alt'", "||", "(", "allowNakedSymbol", "&&", "isPlainSymExpr", "(", "args", "[", "0", "]", ")", ")", ")", "return", "[", "noBraces", "?", "''", ":", "leftBraceChar", ",", "pt", ".", "makeRhsTree", "(", "args", ",", "makeSymbolName", ")", ",", "noBraces", "?", "''", ":", "rightBraceChar", "]", "}" ]
Misc text rendering
[ "Misc", "text", "rendering" ]
ad52f4be347b5c0c07da38b647f9fd2854aee96a
https://github.com/ihh/bracery/blob/ad52f4be347b5c0c07da38b647f9fd2854aee96a/src/parsetree.js#L647-L650
train
ihh/bracery
src/parsetree.js
function (next) { // next can be a function or another thenable if (typeof(next.then) === 'function') // thenable? return next // next is a function, so call it var nextResult = next.apply (next, result) if (nextResult && typeof(nextResult.then) !== 'undefined') // thenable? return nextResult // create a Promise-like wrapper for the result return syncPromiseResolve (nextResult) }
javascript
function (next) { // next can be a function or another thenable if (typeof(next.then) === 'function') // thenable? return next // next is a function, so call it var nextResult = next.apply (next, result) if (nextResult && typeof(nextResult.then) !== 'undefined') // thenable? return nextResult // create a Promise-like wrapper for the result return syncPromiseResolve (nextResult) }
[ "function", "(", "next", ")", "{", "if", "(", "typeof", "(", "next", ".", "then", ")", "===", "'function'", ")", "return", "next", "var", "nextResult", "=", "next", ".", "apply", "(", "next", ",", "result", ")", "if", "(", "nextResult", "&&", "typeof", "(", "nextResult", ".", "then", ")", "!==", "'undefined'", ")", "return", "nextResult", "return", "syncPromiseResolve", "(", "nextResult", ")", "}" ]
for debugging inspection
[ "for", "debugging", "inspection" ]
ad52f4be347b5c0c07da38b647f9fd2854aee96a
https://github.com/ihh/bracery/blob/ad52f4be347b5c0c07da38b647f9fd2854aee96a/src/parsetree.js#L902-L911
train
ihh/bracery
src/parsetree.js
makeRhsExpansionPromise
function makeRhsExpansionPromise (config) { var pt = this var rhs = config.rhs || this.sampleParseTree (config.parsedRhsText || parseRhs (config.rhsText), config) var resolve = config.sync ? syncPromiseResolve : Promise.resolve.bind(Promise) var maxLength = config.maxLength || pt.maxLength var maxNodes = config.maxNodes || pt.maxNodes var reduce = config.reduce || textReducer var makeExpansionPromise = config.makeExpansionPromise || pt.makeExpansionPromise var init = extend ({ text: '', vars: config.vars, tree: [], nodes: 0 }, config.init) return rhs.reduce (function (promise, child) { return promise.then (function (expansion) { if ((expansion.text && expansion.text.length >= maxLength) || (expansion.nodes && expansion.nodes >= maxNodes)) { return expansion } return makeExpansionPromise.call (pt, extend ({}, config, { node: child, vars: expansion.vars })) .then (function (childExpansion) { return reduce.call (pt, expansion, childExpansion, config) }) }) }, resolve (init)) }
javascript
function makeRhsExpansionPromise (config) { var pt = this var rhs = config.rhs || this.sampleParseTree (config.parsedRhsText || parseRhs (config.rhsText), config) var resolve = config.sync ? syncPromiseResolve : Promise.resolve.bind(Promise) var maxLength = config.maxLength || pt.maxLength var maxNodes = config.maxNodes || pt.maxNodes var reduce = config.reduce || textReducer var makeExpansionPromise = config.makeExpansionPromise || pt.makeExpansionPromise var init = extend ({ text: '', vars: config.vars, tree: [], nodes: 0 }, config.init) return rhs.reduce (function (promise, child) { return promise.then (function (expansion) { if ((expansion.text && expansion.text.length >= maxLength) || (expansion.nodes && expansion.nodes >= maxNodes)) { return expansion } return makeExpansionPromise.call (pt, extend ({}, config, { node: child, vars: expansion.vars })) .then (function (childExpansion) { return reduce.call (pt, expansion, childExpansion, config) }) }) }, resolve (init)) }
[ "function", "makeRhsExpansionPromise", "(", "config", ")", "{", "var", "pt", "=", "this", "var", "rhs", "=", "config", ".", "rhs", "||", "this", ".", "sampleParseTree", "(", "config", ".", "parsedRhsText", "||", "parseRhs", "(", "config", ".", "rhsText", ")", ",", "config", ")", "var", "resolve", "=", "config", ".", "sync", "?", "syncPromiseResolve", ":", "Promise", ".", "resolve", ".", "bind", "(", "Promise", ")", "var", "maxLength", "=", "config", ".", "maxLength", "||", "pt", ".", "maxLength", "var", "maxNodes", "=", "config", ".", "maxNodes", "||", "pt", ".", "maxNodes", "var", "reduce", "=", "config", ".", "reduce", "||", "textReducer", "var", "makeExpansionPromise", "=", "config", ".", "makeExpansionPromise", "||", "pt", ".", "makeExpansionPromise", "var", "init", "=", "extend", "(", "{", "text", ":", "''", ",", "vars", ":", "config", ".", "vars", ",", "tree", ":", "[", "]", ",", "nodes", ":", "0", "}", ",", "config", ".", "init", ")", "return", "rhs", ".", "reduce", "(", "function", "(", "promise", ",", "child", ")", "{", "return", "promise", ".", "then", "(", "function", "(", "expansion", ")", "{", "if", "(", "(", "expansion", ".", "text", "&&", "expansion", ".", "text", ".", "length", ">=", "maxLength", ")", "||", "(", "expansion", ".", "nodes", "&&", "expansion", ".", "nodes", ">=", "maxNodes", ")", ")", "{", "return", "expansion", "}", "return", "makeExpansionPromise", ".", "call", "(", "pt", ",", "extend", "(", "{", "}", ",", "config", ",", "{", "node", ":", "child", ",", "vars", ":", "expansion", ".", "vars", "}", ")", ")", ".", "then", "(", "function", "(", "childExpansion", ")", "{", "return", "reduce", ".", "call", "(", "pt", ",", "expansion", ",", "childExpansion", ",", "config", ")", "}", ")", "}", ")", "}", ",", "resolve", "(", "init", ")", ")", "}" ]
makeRhsExpansionPromise is the main method for asynchronously expanding a template that may already have been partially expanded using sampleParseTree.
[ "makeRhsExpansionPromise", "is", "the", "main", "method", "for", "asynchronously", "expanding", "a", "template", "that", "may", "already", "have", "been", "partially", "expanded", "using", "sampleParseTree", "." ]
ad52f4be347b5c0c07da38b647f9fd2854aee96a
https://github.com/ihh/bracery/blob/ad52f4be347b5c0c07da38b647f9fd2854aee96a/src/parsetree.js#L1069-L1098
train
ihh/bracery
src/parsetree.js
pseudoRotateArray
function pseudoRotateArray (a, rng) { var halfLen = a.length / 2, insertAfter = Math.ceil(halfLen) + Math.floor (rng() * Math.floor(halfLen)) var result = a.slice(1) result.splice (insertAfter, 0, a[0]) return result }
javascript
function pseudoRotateArray (a, rng) { var halfLen = a.length / 2, insertAfter = Math.ceil(halfLen) + Math.floor (rng() * Math.floor(halfLen)) var result = a.slice(1) result.splice (insertAfter, 0, a[0]) return result }
[ "function", "pseudoRotateArray", "(", "a", ",", "rng", ")", "{", "var", "halfLen", "=", "a", ".", "length", "/", "2", ",", "insertAfter", "=", "Math", ".", "ceil", "(", "halfLen", ")", "+", "Math", ".", "floor", "(", "rng", "(", ")", "*", "Math", ".", "floor", "(", "halfLen", ")", ")", "var", "result", "=", "a", ".", "slice", "(", "1", ")", "result", ".", "splice", "(", "insertAfter", ",", "0", ",", "a", "[", "0", "]", ")", "return", "result", "}" ]
pseudoRotateArray moves first item to somewhere in the back half
[ "pseudoRotateArray", "moves", "first", "item", "to", "somewhere", "in", "the", "back", "half" ]
ad52f4be347b5c0c07da38b647f9fd2854aee96a
https://github.com/ihh/bracery/blob/ad52f4be347b5c0c07da38b647f9fd2854aee96a/src/parsetree.js#L1214-L1219
train
ihh/bracery
src/parsetree.js
capitalize
function capitalize (text) { return text .replace (/^([^A-Za-z]*)([a-z])/, function (m, g1, g2) { return g1 + g2.toUpperCase() }) .replace (/([\.\!\?]\s*)([a-z])/g, function (m, g1, g2) { return g1 + g2.toUpperCase() }) }
javascript
function capitalize (text) { return text .replace (/^([^A-Za-z]*)([a-z])/, function (m, g1, g2) { return g1 + g2.toUpperCase() }) .replace (/([\.\!\?]\s*)([a-z])/g, function (m, g1, g2) { return g1 + g2.toUpperCase() }) }
[ "function", "capitalize", "(", "text", ")", "{", "return", "text", ".", "replace", "(", "/", "^([^A-Za-z]*)([a-z])", "/", ",", "function", "(", "m", ",", "g1", ",", "g2", ")", "{", "return", "g1", "+", "g2", ".", "toUpperCase", "(", ")", "}", ")", ".", "replace", "(", "/", "([\\.\\!\\?]\\s*)([a-z])", "/", "g", ",", "function", "(", "m", ",", "g1", ",", "g2", ")", "{", "return", "g1", "+", "g2", ".", "toUpperCase", "(", ")", "}", ")", "}" ]
Capitalization of first letters in sentences
[ "Capitalization", "of", "first", "letters", "in", "sentences" ]
ad52f4be347b5c0c07da38b647f9fd2854aee96a
https://github.com/ihh/bracery/blob/ad52f4be347b5c0c07da38b647f9fd2854aee96a/src/parsetree.js#L2462-L2466
train
ihh/bracery
src/parsetree.js
textToWords
function textToWords (text) { return text.toLowerCase() .replace(/[^a-z\s]/g,'') // these are the phoneme characters we keep .replace(/\s+/g,' ').replace(/^ /,'').replace(/ $/,'') // collapse all runs of space & remove start/end space .split(' '); }
javascript
function textToWords (text) { return text.toLowerCase() .replace(/[^a-z\s]/g,'') // these are the phoneme characters we keep .replace(/\s+/g,' ').replace(/^ /,'').replace(/ $/,'') // collapse all runs of space & remove start/end space .split(' '); }
[ "function", "textToWords", "(", "text", ")", "{", "return", "text", ".", "toLowerCase", "(", ")", ".", "replace", "(", "/", "[^a-z\\s]", "/", "g", ",", "''", ")", ".", "replace", "(", "/", "\\s+", "/", "g", ",", "' '", ")", ".", "replace", "(", "/", "^ ", "/", ",", "''", ")", ".", "replace", "(", "/", " $", "/", ",", "''", ")", ".", "split", "(", "' '", ")", ";", "}" ]
Text to words
[ "Text", "to", "words" ]
ad52f4be347b5c0c07da38b647f9fd2854aee96a
https://github.com/ihh/bracery/blob/ad52f4be347b5c0c07da38b647f9fd2854aee96a/src/parsetree.js#L2485-L2490
train
nodules/susanin
dist/susanin.js
function(params, sep, eq) { var query = '', value, typeOf, tmpArray, i, size, key; if ( ! params) { return query; } sep || (sep = '&'); eq || (eq = '='); for (key in params) { if (hasOwnProp.call(params, key)) { tmpArray = [].concat(params[key]); for (i = 0, size = tmpArray.length; i < size; ++i) { typeOf = typeof tmpArray[i]; if (typeOf === 'object' || typeOf === 'undefined') { value = ''; } else { value = encodeURIComponent(tmpArray[i]); } query += sep + encodeURIComponent(key) + eq + value; } } } return query.substr(sep.length); }
javascript
function(params, sep, eq) { var query = '', value, typeOf, tmpArray, i, size, key; if ( ! params) { return query; } sep || (sep = '&'); eq || (eq = '='); for (key in params) { if (hasOwnProp.call(params, key)) { tmpArray = [].concat(params[key]); for (i = 0, size = tmpArray.length; i < size; ++i) { typeOf = typeof tmpArray[i]; if (typeOf === 'object' || typeOf === 'undefined') { value = ''; } else { value = encodeURIComponent(tmpArray[i]); } query += sep + encodeURIComponent(key) + eq + value; } } } return query.substr(sep.length); }
[ "function", "(", "params", ",", "sep", ",", "eq", ")", "{", "var", "query", "=", "''", ",", "value", ",", "typeOf", ",", "tmpArray", ",", "i", ",", "size", ",", "key", ";", "if", "(", "!", "params", ")", "{", "return", "query", ";", "}", "sep", "||", "(", "sep", "=", "'&'", ")", ";", "eq", "||", "(", "eq", "=", "'='", ")", ";", "for", "(", "key", "in", "params", ")", "{", "if", "(", "hasOwnProp", ".", "call", "(", "params", ",", "key", ")", ")", "{", "tmpArray", "=", "[", "]", ".", "concat", "(", "params", "[", "key", "]", ")", ";", "for", "(", "i", "=", "0", ",", "size", "=", "tmpArray", ".", "length", ";", "i", "<", "size", ";", "++", "i", ")", "{", "typeOf", "=", "typeof", "tmpArray", "[", "i", "]", ";", "if", "(", "typeOf", "===", "'object'", "||", "typeOf", "===", "'undefined'", ")", "{", "value", "=", "''", ";", "}", "else", "{", "value", "=", "encodeURIComponent", "(", "tmpArray", "[", "i", "]", ")", ";", "}", "query", "+=", "sep", "+", "encodeURIComponent", "(", "key", ")", "+", "eq", "+", "value", ";", "}", "}", "}", "return", "query", ".", "substr", "(", "sep", ".", "length", ")", ";", "}" ]
Build querystring from object @link http://nodejs.org/api/querystring.html#querystring_querystring_stringify_obj_sep_eq @param {Object} params @param {String} [sep='&'] @param {String} [eq='='] @returns {String}
[ "Build", "querystring", "from", "object" ]
3023be76df0b6be130bfe968d346d388ef37c715
https://github.com/nodules/susanin/blob/3023be76df0b6be130bfe968d346d388ef37c715/dist/susanin.js#L96-L128
train