id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
46,300
io-monad/line-column
lib/line-column.js
LineColumnFinder
function LineColumnFinder(str, options) { if (!(this instanceof LineColumnFinder)) { if (typeof options === "number") { return (new LineColumnFinder(str)).fromIndex(options); } return new LineColumnFinder(str, options); } this.str = str || ""; this.lineToIndex = buildLineToIndex(this.str); options = options || {}; this.origin = typeof options.origin === "undefined" ? 1 : options.origin; }
javascript
function LineColumnFinder(str, options) { if (!(this instanceof LineColumnFinder)) { if (typeof options === "number") { return (new LineColumnFinder(str)).fromIndex(options); } return new LineColumnFinder(str, options); } this.str = str || ""; this.lineToIndex = buildLineToIndex(this.str); options = options || {}; this.origin = typeof options.origin === "undefined" ? 1 : options.origin; }
[ "function", "LineColumnFinder", "(", "str", ",", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "LineColumnFinder", ")", ")", "{", "if", "(", "typeof", "options", "===", "\"number\"", ")", "{", "return", "(", "new", "LineColumnFinder", "(", "str", ")", ")", ".", "fromIndex", "(", "options", ")", ";", "}", "return", "new", "LineColumnFinder", "(", "str", ",", "options", ")", ";", "}", "this", ".", "str", "=", "str", "||", "\"\"", ";", "this", ".", "lineToIndex", "=", "buildLineToIndex", "(", "this", ".", "str", ")", ";", "options", "=", "options", "||", "{", "}", ";", "this", ".", "origin", "=", "typeof", "options", ".", "origin", "===", "\"undefined\"", "?", "1", ":", "options", ".", "origin", ";", "}" ]
Finder for index and line-column from given string. You can call this without `new` operator as it returns an instance anyway. @class @param {string} str - A string to be parsed. @param {Object|number} [options] - Options. This can be an index in the string for shorthand of `lineColumn(str, index)`. @param {number} [options.origin=1] - The origin value of line and column.
[ "Finder", "for", "index", "and", "line", "-", "column", "from", "given", "string", "." ]
a7a2b4cb6ca58f0d36b900c8e60bf9428aa0bb4e
https://github.com/io-monad/line-column/blob/a7a2b4cb6ca58f0d36b900c8e60bf9428aa0bb4e/lib/line-column.js#L25-L38
46,301
io-monad/line-column
lib/line-column.js
buildLineToIndex
function buildLineToIndex(str) { var lines = str.split("\n"), lineToIndex = new Array(lines.length), index = 0; for (var i = 0, l = lines.length; i < l; i++) { lineToIndex[i] = index; index += lines[i].length + /* "\n".length */ 1; } return lineToIndex; }
javascript
function buildLineToIndex(str) { var lines = str.split("\n"), lineToIndex = new Array(lines.length), index = 0; for (var i = 0, l = lines.length; i < l; i++) { lineToIndex[i] = index; index += lines[i].length + /* "\n".length */ 1; } return lineToIndex; }
[ "function", "buildLineToIndex", "(", "str", ")", "{", "var", "lines", "=", "str", ".", "split", "(", "\"\\n\"", ")", ",", "lineToIndex", "=", "new", "Array", "(", "lines", ".", "length", ")", ",", "index", "=", "0", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "lines", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "lineToIndex", "[", "i", "]", "=", "index", ";", "index", "+=", "lines", "[", "i", "]", ".", "length", "+", "/* \"\\n\".length */", "1", ";", "}", "return", "lineToIndex", ";", "}" ]
Build an array of indexes of each line from a string. @private @param str {string} An input string. @return {number[]} Built array of indexes. The key is line number.
[ "Build", "an", "array", "of", "indexes", "of", "each", "line", "from", "a", "string", "." ]
a7a2b4cb6ca58f0d36b900c8e60bf9428aa0bb4e
https://github.com/io-monad/line-column/blob/a7a2b4cb6ca58f0d36b900c8e60bf9428aa0bb4e/lib/line-column.js#L112-L122
46,302
io-monad/line-column
lib/line-column.js
findLowerIndexInRangeArray
function findLowerIndexInRangeArray(value, arr) { if (value >= arr[arr.length - 1]) { return arr.length - 1; } var min = 0, max = arr.length - 2, mid; while (min < max) { mid = min + ((max - min) >> 1); if (value < arr[mid]) { max = mid - 1; } else if (value >= arr[mid + 1]) { min = mid + 1; } else { // value >= arr[mid] && value < arr[mid + 1] min = mid; break; } } return min; }
javascript
function findLowerIndexInRangeArray(value, arr) { if (value >= arr[arr.length - 1]) { return arr.length - 1; } var min = 0, max = arr.length - 2, mid; while (min < max) { mid = min + ((max - min) >> 1); if (value < arr[mid]) { max = mid - 1; } else if (value >= arr[mid + 1]) { min = mid + 1; } else { // value >= arr[mid] && value < arr[mid + 1] min = mid; break; } } return min; }
[ "function", "findLowerIndexInRangeArray", "(", "value", ",", "arr", ")", "{", "if", "(", "value", ">=", "arr", "[", "arr", ".", "length", "-", "1", "]", ")", "{", "return", "arr", ".", "length", "-", "1", ";", "}", "var", "min", "=", "0", ",", "max", "=", "arr", ".", "length", "-", "2", ",", "mid", ";", "while", "(", "min", "<", "max", ")", "{", "mid", "=", "min", "+", "(", "(", "max", "-", "min", ")", ">>", "1", ")", ";", "if", "(", "value", "<", "arr", "[", "mid", "]", ")", "{", "max", "=", "mid", "-", "1", ";", "}", "else", "if", "(", "value", ">=", "arr", "[", "mid", "+", "1", "]", ")", "{", "min", "=", "mid", "+", "1", ";", "}", "else", "{", "// value >= arr[mid] && value < arr[mid + 1]", "min", "=", "mid", ";", "break", ";", "}", "}", "return", "min", ";", "}" ]
Find a lower-bound index of a value in a sorted array of ranges. Assume `arr = [0, 5, 10, 15, 20]` and this returns `1` for `value = 7` (5 <= value < 10), and returns `3` for `value = 18` (15 <= value < 20). @private @param arr {number[]} An array of values representing ranges. @param value {number} A value to be searched. @return {number} Found index. If not found `-1`.
[ "Find", "a", "lower", "-", "bound", "index", "of", "a", "value", "in", "a", "sorted", "array", "of", "ranges", "." ]
a7a2b4cb6ca58f0d36b900c8e60bf9428aa0bb4e
https://github.com/io-monad/line-column/blob/a7a2b4cb6ca58f0d36b900c8e60bf9428aa0bb4e/lib/line-column.js#L136-L155
46,303
AndiDittrich/Node.fs-magic
lib/scandir.js
scandir
async function scandir(dir, recursive=true, absolutePaths=false){ // get absolute path const absPath = _path.resolve(dir); // stats command executable ? dir/file exists const stats = await _fs.stat(absPath); // check if its a directory if (!stats.isDirectory()){ throw new Error('Requested directory <' + absPath + '> is not of type directory'); } // use absolute paths ? if (absolutePaths){ dir = absPath; } // stack of directories to scan const dirstack = [dir]; // list of files const files = []; // list of directories const directories = []; // iterative scan files while (dirstack.length > 0){ // get current directory const currentDir = dirstack.pop(); // get current dir items const itemNames = await _fs.readdir(currentDir); // get item stats (parallel) const itemStats = await Promise.all(itemNames.map((item) => _fs.stat(_path.join(currentDir, item)))); // process item stats for (let i=0;i<itemNames.length;i++){ // prepend current path const currentItem = _path.join(currentDir, itemNames[i]); // directory ? push to stack and directory list if (itemStats[i].isDirectory()){ // recursive mode ? if (recursive){ dirstack.push(currentItem); } // store dir entry directories.push(currentItem); // file, socket, symlink, device.. }else{ // push to filelist files.push(currentItem); } } } // return file and directory list return [files, directories]; }
javascript
async function scandir(dir, recursive=true, absolutePaths=false){ // get absolute path const absPath = _path.resolve(dir); // stats command executable ? dir/file exists const stats = await _fs.stat(absPath); // check if its a directory if (!stats.isDirectory()){ throw new Error('Requested directory <' + absPath + '> is not of type directory'); } // use absolute paths ? if (absolutePaths){ dir = absPath; } // stack of directories to scan const dirstack = [dir]; // list of files const files = []; // list of directories const directories = []; // iterative scan files while (dirstack.length > 0){ // get current directory const currentDir = dirstack.pop(); // get current dir items const itemNames = await _fs.readdir(currentDir); // get item stats (parallel) const itemStats = await Promise.all(itemNames.map((item) => _fs.stat(_path.join(currentDir, item)))); // process item stats for (let i=0;i<itemNames.length;i++){ // prepend current path const currentItem = _path.join(currentDir, itemNames[i]); // directory ? push to stack and directory list if (itemStats[i].isDirectory()){ // recursive mode ? if (recursive){ dirstack.push(currentItem); } // store dir entry directories.push(currentItem); // file, socket, symlink, device.. }else{ // push to filelist files.push(currentItem); } } } // return file and directory list return [files, directories]; }
[ "async", "function", "scandir", "(", "dir", ",", "recursive", "=", "true", ",", "absolutePaths", "=", "false", ")", "{", "// get absolute path", "const", "absPath", "=", "_path", ".", "resolve", "(", "dir", ")", ";", "// stats command executable ? dir/file exists", "const", "stats", "=", "await", "_fs", ".", "stat", "(", "absPath", ")", ";", "// check if its a directory", "if", "(", "!", "stats", ".", "isDirectory", "(", ")", ")", "{", "throw", "new", "Error", "(", "'Requested directory <'", "+", "absPath", "+", "'> is not of type directory'", ")", ";", "}", "// use absolute paths ?", "if", "(", "absolutePaths", ")", "{", "dir", "=", "absPath", ";", "}", "// stack of directories to scan", "const", "dirstack", "=", "[", "dir", "]", ";", "// list of files", "const", "files", "=", "[", "]", ";", "// list of directories", "const", "directories", "=", "[", "]", ";", "// iterative scan files", "while", "(", "dirstack", ".", "length", ">", "0", ")", "{", "// get current directory", "const", "currentDir", "=", "dirstack", ".", "pop", "(", ")", ";", "// get current dir items", "const", "itemNames", "=", "await", "_fs", ".", "readdir", "(", "currentDir", ")", ";", "// get item stats (parallel)", "const", "itemStats", "=", "await", "Promise", ".", "all", "(", "itemNames", ".", "map", "(", "(", "item", ")", "=>", "_fs", ".", "stat", "(", "_path", ".", "join", "(", "currentDir", ",", "item", ")", ")", ")", ")", ";", "// process item stats", "for", "(", "let", "i", "=", "0", ";", "i", "<", "itemNames", ".", "length", ";", "i", "++", ")", "{", "// prepend current path", "const", "currentItem", "=", "_path", ".", "join", "(", "currentDir", ",", "itemNames", "[", "i", "]", ")", ";", "// directory ? push to stack and directory list", "if", "(", "itemStats", "[", "i", "]", ".", "isDirectory", "(", ")", ")", "{", "// recursive mode ?", "if", "(", "recursive", ")", "{", "dirstack", ".", "push", "(", "currentItem", ")", ";", "}", "// store dir entry", "directories", ".", "push", "(", "currentItem", ")", ";", "// file, socket, symlink, device..", "}", "else", "{", "// push to filelist", "files", ".", "push", "(", "currentItem", ")", ";", "}", "}", "}", "// return file and directory list", "return", "[", "files", ",", "directories", "]", ";", "}" ]
list files and directories of a given directory
[ "list", "files", "and", "directories", "of", "a", "given", "directory" ]
5e685a550fd956b5b422a0f21c359952e9be114b
https://github.com/AndiDittrich/Node.fs-magic/blob/5e685a550fd956b5b422a0f21c359952e9be114b/lib/scandir.js#L5-L67
46,304
Lergin/hive-api
CacheFetch_web.js
fetch
function fetch(request, maxCacheAge) { if (maxCacheAge === void 0) { maxCacheAge = 60 * 60 * 1000; } return tslib_1.__awaiter(this, void 0, void 0, function () { var promise; return tslib_1.__generator(this, function (_a) { switch (_a.label) { case 0: if (!(!cache.has(request) || cache.get(request)[1].getTime() + maxCacheAge - new Date().getTime() < 0)) return [3 /*break*/, 2]; promise = window.fetch(request).then(function(res){return res.json()}).catch(function(err){return window.fetch(`https://lergin.de/api/cors/${request}`).then(function(res){return res.json()})}); cache.set(request, [promise, new Date()]); return [4 /*yield*/, promise]; case 1: return [2 /*return*/, _a.sent()]; case 2: return [4 /*yield*/, cache.get(request)[0]]; case 3: return [2 /*return*/, _a.sent()]; } }); }); }
javascript
function fetch(request, maxCacheAge) { if (maxCacheAge === void 0) { maxCacheAge = 60 * 60 * 1000; } return tslib_1.__awaiter(this, void 0, void 0, function () { var promise; return tslib_1.__generator(this, function (_a) { switch (_a.label) { case 0: if (!(!cache.has(request) || cache.get(request)[1].getTime() + maxCacheAge - new Date().getTime() < 0)) return [3 /*break*/, 2]; promise = window.fetch(request).then(function(res){return res.json()}).catch(function(err){return window.fetch(`https://lergin.de/api/cors/${request}`).then(function(res){return res.json()})}); cache.set(request, [promise, new Date()]); return [4 /*yield*/, promise]; case 1: return [2 /*return*/, _a.sent()]; case 2: return [4 /*yield*/, cache.get(request)[0]]; case 3: return [2 /*return*/, _a.sent()]; } }); }); }
[ "function", "fetch", "(", "request", ",", "maxCacheAge", ")", "{", "if", "(", "maxCacheAge", "===", "void", "0", ")", "{", "maxCacheAge", "=", "60", "*", "60", "*", "1000", ";", "}", "return", "tslib_1", ".", "__awaiter", "(", "this", ",", "void", "0", ",", "void", "0", ",", "function", "(", ")", "{", "var", "promise", ";", "return", "tslib_1", ".", "__generator", "(", "this", ",", "function", "(", "_a", ")", "{", "switch", "(", "_a", ".", "label", ")", "{", "case", "0", ":", "if", "(", "!", "(", "!", "cache", ".", "has", "(", "request", ")", "||", "cache", ".", "get", "(", "request", ")", "[", "1", "]", ".", "getTime", "(", ")", "+", "maxCacheAge", "-", "new", "Date", "(", ")", ".", "getTime", "(", ")", "<", "0", ")", ")", "return", "[", "3", "/*break*/", ",", "2", "]", ";", "promise", "=", "window", ".", "fetch", "(", "request", ")", ".", "then", "(", "function", "(", "res", ")", "{", "return", "res", ".", "json", "(", ")", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "return", "window", ".", "fetch", "(", "`", "${", "request", "}", "`", ")", ".", "then", "(", "function", "(", "res", ")", "{", "return", "res", ".", "json", "(", ")", "}", ")", "}", ")", ";", "cache", ".", "set", "(", "request", ",", "[", "promise", ",", "new", "Date", "(", ")", "]", ")", ";", "return", "[", "4", "/*yield*/", ",", "promise", "]", ";", "case", "1", ":", "return", "[", "2", "/*return*/", ",", "_a", ".", "sent", "(", ")", "]", ";", "case", "2", ":", "return", "[", "4", "/*yield*/", ",", "cache", ".", "get", "(", "request", ")", "[", "0", "]", "]", ";", "case", "3", ":", "return", "[", "2", "/*return*/", ",", "_a", ".", "sent", "(", ")", "]", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
fetches the request with node-fetch and caches the result. Also only allows one request every 200ms and will put all other into a waiting query
[ "fetches", "the", "request", "with", "node", "-", "fetch", "and", "caches", "the", "result", ".", "Also", "only", "allows", "one", "request", "every", "200ms", "and", "will", "put", "all", "other", "into", "a", "waiting", "query" ]
e514824610c20417ee681982f7ad09abaa9a0572
https://github.com/Lergin/hive-api/blob/e514824610c20417ee681982f7ad09abaa9a0572/CacheFetch_web.js#L10-L27
46,305
twolfson/grunt-fontsmith
tasks/grunt-fontsmith.js
expandToObject
function expandToObject(input) { // If the input is a string, encapsulate it as an array var retObj = input; if (typeof retObj === 'string') { retObj = [input]; } // If the retObj is an array if (Array.isArray(retObj)) { // Collect the inputs into an object var inputArr = retObj; retObj = {}; // Iterate over the inputs inputArr.forEach(function (inputStr) { // Break down any brace exapansions var inputPaths = braceExpand(inputStr); // Iterate over the paths inputPaths.forEach(function (filepath) { // Grab the extension and save it under its key // TODO: Deal with observer pattern here. // TODO: Will probably go `classical` here var ext = path.extname(filepath).slice(1); retObj[ext] = filepath; }); }); } // Return the objectified src return retObj; }
javascript
function expandToObject(input) { // If the input is a string, encapsulate it as an array var retObj = input; if (typeof retObj === 'string') { retObj = [input]; } // If the retObj is an array if (Array.isArray(retObj)) { // Collect the inputs into an object var inputArr = retObj; retObj = {}; // Iterate over the inputs inputArr.forEach(function (inputStr) { // Break down any brace exapansions var inputPaths = braceExpand(inputStr); // Iterate over the paths inputPaths.forEach(function (filepath) { // Grab the extension and save it under its key // TODO: Deal with observer pattern here. // TODO: Will probably go `classical` here var ext = path.extname(filepath).slice(1); retObj[ext] = filepath; }); }); } // Return the objectified src return retObj; }
[ "function", "expandToObject", "(", "input", ")", "{", "// If the input is a string, encapsulate it as an array", "var", "retObj", "=", "input", ";", "if", "(", "typeof", "retObj", "===", "'string'", ")", "{", "retObj", "=", "[", "input", "]", ";", "}", "// If the retObj is an array", "if", "(", "Array", ".", "isArray", "(", "retObj", ")", ")", "{", "// Collect the inputs into an object", "var", "inputArr", "=", "retObj", ";", "retObj", "=", "{", "}", ";", "// Iterate over the inputs", "inputArr", ".", "forEach", "(", "function", "(", "inputStr", ")", "{", "// Break down any brace exapansions", "var", "inputPaths", "=", "braceExpand", "(", "inputStr", ")", ";", "// Iterate over the paths", "inputPaths", ".", "forEach", "(", "function", "(", "filepath", ")", "{", "// Grab the extension and save it under its key", "// TODO: Deal with observer pattern here.", "// TODO: Will probably go `classical` here", "var", "ext", "=", "path", ".", "extname", "(", "filepath", ")", ".", "slice", "(", "1", ")", ";", "retObj", "[", "ext", "]", "=", "filepath", ";", "}", ")", ";", "}", ")", ";", "}", "// Return the objectified src", "return", "retObj", ";", "}" ]
Helper function for objectifying src into type-first
[ "Helper", "function", "for", "objectifying", "src", "into", "type", "-", "first" ]
49a42b2fd603214f3ba740e85531e4e3aa692ea7
https://github.com/twolfson/grunt-fontsmith/blob/49a42b2fd603214f3ba740e85531e4e3aa692ea7/tasks/grunt-fontsmith.js#L18-L49
46,306
AndiDittrich/Node.fs-magic
lib/exists.js
exists
function exists(filedir){ // promise wrapper return new Promise(function(resolve){ // try to stat the file _fs.stat(filedir, function(err){ resolve(!err) }); }); }
javascript
function exists(filedir){ // promise wrapper return new Promise(function(resolve){ // try to stat the file _fs.stat(filedir, function(err){ resolve(!err) }); }); }
[ "function", "exists", "(", "filedir", ")", "{", "// promise wrapper", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "// try to stat the file", "_fs", ".", "stat", "(", "filedir", ",", "function", "(", "err", ")", "{", "resolve", "(", "!", "err", ")", "}", ")", ";", "}", ")", ";", "}" ]
"modern" exists implmentation
[ "modern", "exists", "implmentation" ]
5e685a550fd956b5b422a0f21c359952e9be114b
https://github.com/AndiDittrich/Node.fs-magic/blob/5e685a550fd956b5b422a0f21c359952e9be114b/lib/exists.js#L4-L12
46,307
AntonioMA/swagger-boilerplate
lib/shared/utils.js
trace
function trace() { var args = Array.prototype.slice.call(arguments); var traceLevel = args.shift(); if (traceLevel.level & enabledLevels) { args.unshift('[' + traceLevel.name + '] ' + new Date().toISOString() + ' - ' + aName + ':'); console.log.apply(console, args); } }
javascript
function trace() { var args = Array.prototype.slice.call(arguments); var traceLevel = args.shift(); if (traceLevel.level & enabledLevels) { args.unshift('[' + traceLevel.name + '] ' + new Date().toISOString() + ' - ' + aName + ':'); console.log.apply(console, args); } }
[ "function", "trace", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "var", "traceLevel", "=", "args", ".", "shift", "(", ")", ";", "if", "(", "traceLevel", ".", "level", "&", "enabledLevels", ")", "{", "args", ".", "unshift", "(", "'['", "+", "traceLevel", ".", "name", "+", "'] '", "+", "new", "Date", "(", ")", ".", "toISOString", "(", ")", "+", "' - '", "+", "aName", "+", "':'", ")", ";", "console", ".", "log", ".", "apply", "(", "console", ",", "args", ")", ";", "}", "}" ]
The first argument is the level, the rest what we want to log
[ "The", "first", "argument", "is", "the", "level", "the", "rest", "what", "we", "want", "to", "log" ]
ce6980060c8194b993b3ab3ed750a25d02e9d66a
https://github.com/AntonioMA/swagger-boilerplate/blob/ce6980060c8194b993b3ab3ed750a25d02e9d66a/lib/shared/utils.js#L20-L27
46,308
AXErunners/axecore-p2p
lib/messages/commands/filterload.js
FilterloadMessage
function FilterloadMessage(arg, options) { Message.call(this, options); this.command = 'filterload'; $.checkArgument( _.isUndefined(arg) || arg instanceof BloomFilter, 'An instance of BloomFilter or undefined is expected' ); this.filter = arg; }
javascript
function FilterloadMessage(arg, options) { Message.call(this, options); this.command = 'filterload'; $.checkArgument( _.isUndefined(arg) || arg instanceof BloomFilter, 'An instance of BloomFilter or undefined is expected' ); this.filter = arg; }
[ "function", "FilterloadMessage", "(", "arg", ",", "options", ")", "{", "Message", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "command", "=", "'filterload'", ";", "$", ".", "checkArgument", "(", "_", ".", "isUndefined", "(", "arg", ")", "||", "arg", "instanceof", "BloomFilter", ",", "'An instance of BloomFilter or undefined is expected'", ")", ";", "this", ".", "filter", "=", "arg", ";", "}" ]
Request peer to send inv messages based on a bloom filter @param {BloomFilter=} arg - An instance of BloomFilter @param {Object} options @extends Message @constructor
[ "Request", "peer", "to", "send", "inv", "messages", "based", "on", "a", "bloom", "filter" ]
c06d0e1d7b9ed44b7ee3061feb394d3896240da9
https://github.com/AXErunners/axecore-p2p/blob/c06d0e1d7b9ed44b7ee3061feb394d3896240da9/lib/messages/commands/filterload.js#L18-L26
46,309
simonepri/restify-errors-options
index.js
extendErrorBody
function extendErrorBody(ctor) { /** * Parse errror's arguments to extract the 'options' object. * Extracted from https://github.com/restify/errors/blob/master/lib/helpers.js#L30 * @param {} ctorArgs Arguments of the error. */ function parseOptions(ctorArgs) { function parse() { let options = null; if (_.isPlainObject(arguments[0])) { // See https://github.com/restify/errors#new-erroroptions--printf-args options = arguments[0] || {}; } else if ( arguments[0] instanceof Error && _.isPlainObject(arguments[1]) ) { // See https://github.com/restify/errors#new-errorpriorerr-options--printf-args options = arguments[1] || {}; } return options; } // Calls constructor args. return parse.apply(null, ctorArgs); } /** * Dynamically create a constructor. * Must be anonymous fn. * @constructor */ // Use an object because otherwise the variable name is shown as function name. const anonymous = {}; anonymous.hook = function() { const options = parseOptions(arguments) || {}; // Calls the parent constructor with itself as scope. ctor.apply(this, arguments); // Adds custom options to itself patchErrorBody(this, options); }; // Inherits from the original error. // Is that necessary?? util.inherits(anonymous.hook, ctor); // Make the prototype an instance of the old class. anonymous.hook.prototype = ctor.prototype; // Assign display name anonymous.hook.displayName = ctor.displayName + 'Hook'; return anonymous.hook; }
javascript
function extendErrorBody(ctor) { /** * Parse errror's arguments to extract the 'options' object. * Extracted from https://github.com/restify/errors/blob/master/lib/helpers.js#L30 * @param {} ctorArgs Arguments of the error. */ function parseOptions(ctorArgs) { function parse() { let options = null; if (_.isPlainObject(arguments[0])) { // See https://github.com/restify/errors#new-erroroptions--printf-args options = arguments[0] || {}; } else if ( arguments[0] instanceof Error && _.isPlainObject(arguments[1]) ) { // See https://github.com/restify/errors#new-errorpriorerr-options--printf-args options = arguments[1] || {}; } return options; } // Calls constructor args. return parse.apply(null, ctorArgs); } /** * Dynamically create a constructor. * Must be anonymous fn. * @constructor */ // Use an object because otherwise the variable name is shown as function name. const anonymous = {}; anonymous.hook = function() { const options = parseOptions(arguments) || {}; // Calls the parent constructor with itself as scope. ctor.apply(this, arguments); // Adds custom options to itself patchErrorBody(this, options); }; // Inherits from the original error. // Is that necessary?? util.inherits(anonymous.hook, ctor); // Make the prototype an instance of the old class. anonymous.hook.prototype = ctor.prototype; // Assign display name anonymous.hook.displayName = ctor.displayName + 'Hook'; return anonymous.hook; }
[ "function", "extendErrorBody", "(", "ctor", ")", "{", "/**\n * Parse errror's arguments to extract the 'options' object.\n * Extracted from https://github.com/restify/errors/blob/master/lib/helpers.js#L30\n * @param {} ctorArgs Arguments of the error.\n */", "function", "parseOptions", "(", "ctorArgs", ")", "{", "function", "parse", "(", ")", "{", "let", "options", "=", "null", ";", "if", "(", "_", ".", "isPlainObject", "(", "arguments", "[", "0", "]", ")", ")", "{", "// See https://github.com/restify/errors#new-erroroptions--printf-args", "options", "=", "arguments", "[", "0", "]", "||", "{", "}", ";", "}", "else", "if", "(", "arguments", "[", "0", "]", "instanceof", "Error", "&&", "_", ".", "isPlainObject", "(", "arguments", "[", "1", "]", ")", ")", "{", "// See https://github.com/restify/errors#new-errorpriorerr-options--printf-args", "options", "=", "arguments", "[", "1", "]", "||", "{", "}", ";", "}", "return", "options", ";", "}", "// Calls constructor args.", "return", "parse", ".", "apply", "(", "null", ",", "ctorArgs", ")", ";", "}", "/**\n * Dynamically create a constructor.\n * Must be anonymous fn.\n * @constructor\n */", "// Use an object because otherwise the variable name is shown as function name.", "const", "anonymous", "=", "{", "}", ";", "anonymous", ".", "hook", "=", "function", "(", ")", "{", "const", "options", "=", "parseOptions", "(", "arguments", ")", "||", "{", "}", ";", "// Calls the parent constructor with itself as scope.", "ctor", ".", "apply", "(", "this", ",", "arguments", ")", ";", "// Adds custom options to itself", "patchErrorBody", "(", "this", ",", "options", ")", ";", "}", ";", "// Inherits from the original error.", "// Is that necessary??", "util", ".", "inherits", "(", "anonymous", ".", "hook", ",", "ctor", ")", ";", "// Make the prototype an instance of the old class.", "anonymous", ".", "hook", ".", "prototype", "=", "ctor", ".", "prototype", ";", "// Assign display name", "anonymous", ".", "hook", ".", "displayName", "=", "ctor", ".", "displayName", "+", "'Hook'", ";", "return", "anonymous", ".", "hook", ";", "}" ]
Adds cuostom options to the error body. @param {function} ctor Original Cnstructor of the error. @return {function} Hooked constructor of the error.
[ "Adds", "cuostom", "options", "to", "the", "error", "body", "." ]
f8412de9ba67ece3a1632f3935bea1c778666b9e
https://github.com/simonepri/restify-errors-options/blob/f8412de9ba67ece3a1632f3935bea1c778666b9e/index.js#L25-L77
46,310
simonepri/restify-errors-options
index.js
patchErrorBody
function patchErrorBody(err, options) { // Gets the current toJSON to be extended. const json = err.toJSON(); Object.keys(customOptions).forEach(optName => { let value = options[optName]; if (value === undefined) { value = err.body[optName]; if (value === '' || value === undefined) { value = customOptions[optName]( err.body.code, err.statusCode, err.body.message ); } } if (value !== undefined) { // Adds the option to the body of the error. err.body[optName] = value; // Adds the option to the json representation of the error. json[optName] = value; } }); // Patchs the toJSON method. err.toJSON = () => json; }
javascript
function patchErrorBody(err, options) { // Gets the current toJSON to be extended. const json = err.toJSON(); Object.keys(customOptions).forEach(optName => { let value = options[optName]; if (value === undefined) { value = err.body[optName]; if (value === '' || value === undefined) { value = customOptions[optName]( err.body.code, err.statusCode, err.body.message ); } } if (value !== undefined) { // Adds the option to the body of the error. err.body[optName] = value; // Adds the option to the json representation of the error. json[optName] = value; } }); // Patchs the toJSON method. err.toJSON = () => json; }
[ "function", "patchErrorBody", "(", "err", ",", "options", ")", "{", "// Gets the current toJSON to be extended.", "const", "json", "=", "err", ".", "toJSON", "(", ")", ";", "Object", ".", "keys", "(", "customOptions", ")", ".", "forEach", "(", "optName", "=>", "{", "let", "value", "=", "options", "[", "optName", "]", ";", "if", "(", "value", "===", "undefined", ")", "{", "value", "=", "err", ".", "body", "[", "optName", "]", ";", "if", "(", "value", "===", "''", "||", "value", "===", "undefined", ")", "{", "value", "=", "customOptions", "[", "optName", "]", "(", "err", ".", "body", ".", "code", ",", "err", ".", "statusCode", ",", "err", ".", "body", ".", "message", ")", ";", "}", "}", "if", "(", "value", "!==", "undefined", ")", "{", "// Adds the option to the body of the error.", "err", ".", "body", "[", "optName", "]", "=", "value", ";", "// Adds the option to the json representation of the error.", "json", "[", "optName", "]", "=", "value", ";", "}", "}", ")", ";", "// Patchs the toJSON method.", "err", ".", "toJSON", "=", "(", ")", "=>", "json", ";", "}" ]
Monkey patch the error object after his creation. @param {object} err Error to patch. @param {object} options Options given by the user.
[ "Monkey", "patch", "the", "error", "object", "after", "his", "creation", "." ]
f8412de9ba67ece3a1632f3935bea1c778666b9e
https://github.com/simonepri/restify-errors-options/blob/f8412de9ba67ece3a1632f3935bea1c778666b9e/index.js#L84-L110
46,311
simonepri/restify-errors-options
index.js
patchMakeConstructor
function patchMakeConstructor() { const func = errors.makeConstructor; function makeConstructorHook() { func.apply(null, arguments); patchError(arguments[0]); } errors.makeConstructor = makeConstructorHook; }
javascript
function patchMakeConstructor() { const func = errors.makeConstructor; function makeConstructorHook() { func.apply(null, arguments); patchError(arguments[0]); } errors.makeConstructor = makeConstructorHook; }
[ "function", "patchMakeConstructor", "(", ")", "{", "const", "func", "=", "errors", ".", "makeConstructor", ";", "function", "makeConstructorHook", "(", ")", "{", "func", ".", "apply", "(", "null", ",", "arguments", ")", ";", "patchError", "(", "arguments", "[", "0", "]", ")", ";", "}", "errors", ".", "makeConstructor", "=", "makeConstructorHook", ";", "}" ]
Adds an hook to the makeConstructor method,
[ "Adds", "an", "hook", "to", "the", "makeConstructor", "method" ]
f8412de9ba67ece3a1632f3935bea1c778666b9e
https://github.com/simonepri/restify-errors-options/blob/f8412de9ba67ece3a1632f3935bea1c778666b9e/index.js#L115-L122
46,312
simonepri/restify-errors-options
index.js
patchMakeErrFromCode
function patchMakeErrFromCode() { const func = errors.makeErrFromCode; function makeErrFromCodeHook() { const err = func.apply(null, arguments); patchErrorBody(err, {}); return err; } errors.makeErrFromCode = makeErrFromCodeHook; // Deprecated. // See https://github.com/restify/errors/blob/master/lib/index.js#L126 errors.codeToHttpError = makeErrFromCodeHook; }
javascript
function patchMakeErrFromCode() { const func = errors.makeErrFromCode; function makeErrFromCodeHook() { const err = func.apply(null, arguments); patchErrorBody(err, {}); return err; } errors.makeErrFromCode = makeErrFromCodeHook; // Deprecated. // See https://github.com/restify/errors/blob/master/lib/index.js#L126 errors.codeToHttpError = makeErrFromCodeHook; }
[ "function", "patchMakeErrFromCode", "(", ")", "{", "const", "func", "=", "errors", ".", "makeErrFromCode", ";", "function", "makeErrFromCodeHook", "(", ")", "{", "const", "err", "=", "func", ".", "apply", "(", "null", ",", "arguments", ")", ";", "patchErrorBody", "(", "err", ",", "{", "}", ")", ";", "return", "err", ";", "}", "errors", ".", "makeErrFromCode", "=", "makeErrFromCodeHook", ";", "// Deprecated.", "// See https://github.com/restify/errors/blob/master/lib/index.js#L126", "errors", ".", "codeToHttpError", "=", "makeErrFromCodeHook", ";", "}" ]
Adds an hook to the makeErrFromCode method.
[ "Adds", "an", "hook", "to", "the", "makeErrFromCode", "method", "." ]
f8412de9ba67ece3a1632f3935bea1c778666b9e
https://github.com/simonepri/restify-errors-options/blob/f8412de9ba67ece3a1632f3935bea1c778666b9e/index.js#L127-L139
46,313
simonepri/restify-errors-options
index.js
addOption
function addOption(optName, optDefault) { if (typeof optDefault !== 'function') { const val = optDefault; optDefault = () => val; } customOptions[optName] = optDefault; }
javascript
function addOption(optName, optDefault) { if (typeof optDefault !== 'function') { const val = optDefault; optDefault = () => val; } customOptions[optName] = optDefault; }
[ "function", "addOption", "(", "optName", ",", "optDefault", ")", "{", "if", "(", "typeof", "optDefault", "!==", "'function'", ")", "{", "const", "val", "=", "optDefault", ";", "optDefault", "=", "(", ")", "=>", "val", ";", "}", "customOptions", "[", "optName", "]", "=", "optDefault", ";", "}" ]
Adds custom options to errors' body. @param {string} optName Name of the option key to add. @param {} [optDefault] Default value for the option. If a function is provided it will be called with (errorCode, errorHttpCode, errorMessage) as parameters. You can use this behaviour to provide different default for each error.
[ "Adds", "custom", "options", "to", "errors", "body", "." ]
f8412de9ba67ece3a1632f3935bea1c778666b9e
https://github.com/simonepri/restify-errors-options/blob/f8412de9ba67ece3a1632f3935bea1c778666b9e/index.js#L158-L164
46,314
heapsource/mongoose-attachments-localfs
lib/localfs-provider.js
LocalfsStorageAttachments
function LocalfsStorageAttachments(options) { if(options.removePrefix) { this.prefix = options.removePrefix; } attachments.StorageProvider.call(this, options); }
javascript
function LocalfsStorageAttachments(options) { if(options.removePrefix) { this.prefix = options.removePrefix; } attachments.StorageProvider.call(this, options); }
[ "function", "LocalfsStorageAttachments", "(", "options", ")", "{", "if", "(", "options", ".", "removePrefix", ")", "{", "this", ".", "prefix", "=", "options", ".", "removePrefix", ";", "}", "attachments", ".", "StorageProvider", ".", "call", "(", "this", ",", "options", ")", ";", "}" ]
create constructor and inherit
[ "create", "constructor", "and", "inherit" ]
f00fb1f2d7e28b40f842917f8c41a261e982ea23
https://github.com/heapsource/mongoose-attachments-localfs/blob/f00fb1f2d7e28b40f842917f8c41a261e982ea23/lib/localfs-provider.js#L27-L32
46,315
LI-NA/optipng.js
demo/js/optipng.js
getMemory
function getMemory(size) { if (!staticSealed) return staticAlloc(size); if (!runtimeInitialized) return dynamicAlloc(size); return _malloc(size); }
javascript
function getMemory(size) { if (!staticSealed) return staticAlloc(size); if (!runtimeInitialized) return dynamicAlloc(size); return _malloc(size); }
[ "function", "getMemory", "(", "size", ")", "{", "if", "(", "!", "staticSealed", ")", "return", "staticAlloc", "(", "size", ")", ";", "if", "(", "!", "runtimeInitialized", ")", "return", "dynamicAlloc", "(", "size", ")", ";", "return", "_malloc", "(", "size", ")", ";", "}" ]
Allocate memory during any stage of startup - static memory early on, dynamic memory later, malloc when ready
[ "Allocate", "memory", "during", "any", "stage", "of", "startup", "-", "static", "memory", "early", "on", "dynamic", "memory", "later", "malloc", "when", "ready" ]
9657fe80a9135e58e20c858515f049c6c76a08e7
https://github.com/LI-NA/optipng.js/blob/9657fe80a9135e58e20c858515f049c6c76a08e7/demo/js/optipng.js#L691-L695
46,316
LI-NA/optipng.js
demo/js/optipng.js
isDataURI
function isDataURI(filename) { return String.prototype.startsWith ? filename.startsWith(dataURIPrefix) : filename.indexOf(dataURIPrefix) === 0; }
javascript
function isDataURI(filename) { return String.prototype.startsWith ? filename.startsWith(dataURIPrefix) : filename.indexOf(dataURIPrefix) === 0; }
[ "function", "isDataURI", "(", "filename", ")", "{", "return", "String", ".", "prototype", ".", "startsWith", "?", "filename", ".", "startsWith", "(", "dataURIPrefix", ")", ":", "filename", ".", "indexOf", "(", "dataURIPrefix", ")", "===", "0", ";", "}" ]
Indicates whether filename is a base64 data URI.
[ "Indicates", "whether", "filename", "is", "a", "base64", "data", "URI", "." ]
9657fe80a9135e58e20c858515f049c6c76a08e7
https://github.com/LI-NA/optipng.js/blob/9657fe80a9135e58e20c858515f049c6c76a08e7/demo/js/optipng.js#L1513-L1517
46,317
LI-NA/optipng.js
demo/js/optipng.js
useRequest
function useRequest() { var request = Module['memoryInitializerRequest']; var response = request.response; if (request.status !== 200 && request.status !== 0) { var data = tryParseAsDataURI(Module['memoryInitializerRequestURL']); if (data) { response = data.buffer; } else { // If you see this warning, the issue may be that you are using locateFile or memoryInitializerPrefixURL, and defining them in JS. That // means that the HTML file doesn't know about them, and when it tries to create the mem init request early, does it to the wrong place. // Look in your browser's devtools network console to see what's going on. console.warn('a problem seems to have happened with Module.memoryInitializerRequest, status: ' + request.status + ', retrying ' + memoryInitializer); doBrowserLoad(); return; } } applyMemoryInitializer(response); }
javascript
function useRequest() { var request = Module['memoryInitializerRequest']; var response = request.response; if (request.status !== 200 && request.status !== 0) { var data = tryParseAsDataURI(Module['memoryInitializerRequestURL']); if (data) { response = data.buffer; } else { // If you see this warning, the issue may be that you are using locateFile or memoryInitializerPrefixURL, and defining them in JS. That // means that the HTML file doesn't know about them, and when it tries to create the mem init request early, does it to the wrong place. // Look in your browser's devtools network console to see what's going on. console.warn('a problem seems to have happened with Module.memoryInitializerRequest, status: ' + request.status + ', retrying ' + memoryInitializer); doBrowserLoad(); return; } } applyMemoryInitializer(response); }
[ "function", "useRequest", "(", ")", "{", "var", "request", "=", "Module", "[", "'memoryInitializerRequest'", "]", ";", "var", "response", "=", "request", ".", "response", ";", "if", "(", "request", ".", "status", "!==", "200", "&&", "request", ".", "status", "!==", "0", ")", "{", "var", "data", "=", "tryParseAsDataURI", "(", "Module", "[", "'memoryInitializerRequestURL'", "]", ")", ";", "if", "(", "data", ")", "{", "response", "=", "data", ".", "buffer", ";", "}", "else", "{", "// If you see this warning, the issue may be that you are using locateFile or memoryInitializerPrefixURL, and defining them in JS. That", "// means that the HTML file doesn't know about them, and when it tries to create the mem init request early, does it to the wrong place.", "// Look in your browser's devtools network console to see what's going on.", "console", ".", "warn", "(", "'a problem seems to have happened with Module.memoryInitializerRequest, status: '", "+", "request", ".", "status", "+", "', retrying '", "+", "memoryInitializer", ")", ";", "doBrowserLoad", "(", ")", ";", "return", ";", "}", "}", "applyMemoryInitializer", "(", "response", ")", ";", "}" ]
a network request has already been created, just use that
[ "a", "network", "request", "has", "already", "been", "created", "just", "use", "that" ]
9657fe80a9135e58e20c858515f049c6c76a08e7
https://github.com/LI-NA/optipng.js/blob/9657fe80a9135e58e20c858515f049c6c76a08e7/demo/js/optipng.js#L66452-L66469
46,318
nagarajanchinnasamy/simpledimple
lib/dimple/dimple.v2.1.4.js
function (axis, row) { var returnField = []; if (axis !== null) { if (axis._hasTimeField()) { returnField.push(axis._parseDate(row[axis.timeField])); } else if (axis._hasCategories()) { axis.categoryFields.forEach(function (cat) { returnField.push(row[cat]); }, this); } } return returnField; }
javascript
function (axis, row) { var returnField = []; if (axis !== null) { if (axis._hasTimeField()) { returnField.push(axis._parseDate(row[axis.timeField])); } else if (axis._hasCategories()) { axis.categoryFields.forEach(function (cat) { returnField.push(row[cat]); }, this); } } return returnField; }
[ "function", "(", "axis", ",", "row", ")", "{", "var", "returnField", "=", "[", "]", ";", "if", "(", "axis", "!==", "null", ")", "{", "if", "(", "axis", ".", "_hasTimeField", "(", ")", ")", "{", "returnField", ".", "push", "(", "axis", ".", "_parseDate", "(", "row", "[", "axis", ".", "timeField", "]", ")", ")", ";", "}", "else", "if", "(", "axis", ".", "_hasCategories", "(", ")", ")", "{", "axis", ".", "categoryFields", ".", "forEach", "(", "function", "(", "cat", ")", "{", "returnField", ".", "push", "(", "row", "[", "cat", "]", ")", ";", "}", ",", "this", ")", ";", "}", "}", "return", "returnField", ";", "}" ]
The data for this series
[ "The", "data", "for", "this", "series" ]
f0ed2797661c2bfeee7ba0696e367051353fd078
https://github.com/nagarajanchinnasamy/simpledimple/blob/f0ed2797661c2bfeee7ba0696e367051353fd078/lib/dimple/dimple.v2.1.4.js#L736-L748
46,319
nagarajanchinnasamy/simpledimple
lib/dimple/dimple.v2.1.4.js
function (d, chart, series) { var returnCx = 0; if (series.x.measure !== null && series.x.measure !== undefined) { returnCx = series.x._scale(d.cx); } else if (series.x._hasCategories() && series.x.categoryFields.length >= 2) { returnCx = series.x._scale(d.cx) + dimple._helpers.xGap(chart, series) + ((d.xOffset + 0.5) * (((chart._widthPixels() / series.x._max) - 2 * dimple._helpers.xGap(chart, series)) * d.width)); } else { returnCx = series.x._scale(d.cx) + ((chart._widthPixels() / series.x._max) / 2); } return returnCx; }
javascript
function (d, chart, series) { var returnCx = 0; if (series.x.measure !== null && series.x.measure !== undefined) { returnCx = series.x._scale(d.cx); } else if (series.x._hasCategories() && series.x.categoryFields.length >= 2) { returnCx = series.x._scale(d.cx) + dimple._helpers.xGap(chart, series) + ((d.xOffset + 0.5) * (((chart._widthPixels() / series.x._max) - 2 * dimple._helpers.xGap(chart, series)) * d.width)); } else { returnCx = series.x._scale(d.cx) + ((chart._widthPixels() / series.x._max) / 2); } return returnCx; }
[ "function", "(", "d", ",", "chart", ",", "series", ")", "{", "var", "returnCx", "=", "0", ";", "if", "(", "series", ".", "x", ".", "measure", "!==", "null", "&&", "series", ".", "x", ".", "measure", "!==", "undefined", ")", "{", "returnCx", "=", "series", ".", "x", ".", "_scale", "(", "d", ".", "cx", ")", ";", "}", "else", "if", "(", "series", ".", "x", ".", "_hasCategories", "(", ")", "&&", "series", ".", "x", ".", "categoryFields", ".", "length", ">=", "2", ")", "{", "returnCx", "=", "series", ".", "x", ".", "_scale", "(", "d", ".", "cx", ")", "+", "dimple", ".", "_helpers", ".", "xGap", "(", "chart", ",", "series", ")", "+", "(", "(", "d", ".", "xOffset", "+", "0.5", ")", "*", "(", "(", "(", "chart", ".", "_widthPixels", "(", ")", "/", "series", ".", "x", ".", "_max", ")", "-", "2", "*", "dimple", ".", "_helpers", ".", "xGap", "(", "chart", ",", "series", ")", ")", "*", "d", ".", "width", ")", ")", ";", "}", "else", "{", "returnCx", "=", "series", ".", "x", ".", "_scale", "(", "d", ".", "cx", ")", "+", "(", "(", "chart", ".", "_widthPixels", "(", ")", "/", "series", ".", "x", ".", "_max", ")", "/", "2", ")", ";", "}", "return", "returnCx", ";", "}" ]
Calculate the centre x position
[ "Calculate", "the", "centre", "x", "position" ]
f0ed2797661c2bfeee7ba0696e367051353fd078
https://github.com/nagarajanchinnasamy/simpledimple/blob/f0ed2797661c2bfeee7ba0696e367051353fd078/lib/dimple/dimple.v2.1.4.js#L4601-L4611
46,320
nagarajanchinnasamy/simpledimple
lib/dimple/dimple.v2.1.4.js
function (d, chart, series) { var returnCy = 0; if (series.y.measure !== null && series.y.measure !== undefined) { returnCy = series.y._scale(d.cy); } else if (series.y.categoryFields !== null && series.y.categoryFields !== undefined && series.y.categoryFields.length >= 2) { returnCy = (series.y._scale(d.cy) - (chart._heightPixels() / series.y._max)) + dimple._helpers.yGap(chart, series) + ((d.yOffset + 0.5) * (((chart._heightPixels() / series.y._max) - 2 * dimple._helpers.yGap(chart, series)) * d.height)); } else { returnCy = series.y._scale(d.cy) - ((chart._heightPixels() / series.y._max) / 2); } return returnCy; }
javascript
function (d, chart, series) { var returnCy = 0; if (series.y.measure !== null && series.y.measure !== undefined) { returnCy = series.y._scale(d.cy); } else if (series.y.categoryFields !== null && series.y.categoryFields !== undefined && series.y.categoryFields.length >= 2) { returnCy = (series.y._scale(d.cy) - (chart._heightPixels() / series.y._max)) + dimple._helpers.yGap(chart, series) + ((d.yOffset + 0.5) * (((chart._heightPixels() / series.y._max) - 2 * dimple._helpers.yGap(chart, series)) * d.height)); } else { returnCy = series.y._scale(d.cy) - ((chart._heightPixels() / series.y._max) / 2); } return returnCy; }
[ "function", "(", "d", ",", "chart", ",", "series", ")", "{", "var", "returnCy", "=", "0", ";", "if", "(", "series", ".", "y", ".", "measure", "!==", "null", "&&", "series", ".", "y", ".", "measure", "!==", "undefined", ")", "{", "returnCy", "=", "series", ".", "y", ".", "_scale", "(", "d", ".", "cy", ")", ";", "}", "else", "if", "(", "series", ".", "y", ".", "categoryFields", "!==", "null", "&&", "series", ".", "y", ".", "categoryFields", "!==", "undefined", "&&", "series", ".", "y", ".", "categoryFields", ".", "length", ">=", "2", ")", "{", "returnCy", "=", "(", "series", ".", "y", ".", "_scale", "(", "d", ".", "cy", ")", "-", "(", "chart", ".", "_heightPixels", "(", ")", "/", "series", ".", "y", ".", "_max", ")", ")", "+", "dimple", ".", "_helpers", ".", "yGap", "(", "chart", ",", "series", ")", "+", "(", "(", "d", ".", "yOffset", "+", "0.5", ")", "*", "(", "(", "(", "chart", ".", "_heightPixels", "(", ")", "/", "series", ".", "y", ".", "_max", ")", "-", "2", "*", "dimple", ".", "_helpers", ".", "yGap", "(", "chart", ",", "series", ")", ")", "*", "d", ".", "height", ")", ")", ";", "}", "else", "{", "returnCy", "=", "series", ".", "y", ".", "_scale", "(", "d", ".", "cy", ")", "-", "(", "(", "chart", ".", "_heightPixels", "(", ")", "/", "series", ".", "y", ".", "_max", ")", "/", "2", ")", ";", "}", "return", "returnCy", ";", "}" ]
Calculate the centre y position
[ "Calculate", "the", "centre", "y", "position" ]
f0ed2797661c2bfeee7ba0696e367051353fd078
https://github.com/nagarajanchinnasamy/simpledimple/blob/f0ed2797661c2bfeee7ba0696e367051353fd078/lib/dimple/dimple.v2.1.4.js#L4614-L4624
46,321
nagarajanchinnasamy/simpledimple
lib/dimple/dimple.v2.1.4.js
function (chart, series) { var returnXGap = 0; if ((series.x.measure === null || series.x.measure === undefined) && series.barGap > 0) { returnXGap = ((chart._widthPixels() / series.x._max) * (series.barGap > 0.99 ? 0.99 : series.barGap)) / 2; } return returnXGap; }
javascript
function (chart, series) { var returnXGap = 0; if ((series.x.measure === null || series.x.measure === undefined) && series.barGap > 0) { returnXGap = ((chart._widthPixels() / series.x._max) * (series.barGap > 0.99 ? 0.99 : series.barGap)) / 2; } return returnXGap; }
[ "function", "(", "chart", ",", "series", ")", "{", "var", "returnXGap", "=", "0", ";", "if", "(", "(", "series", ".", "x", ".", "measure", "===", "null", "||", "series", ".", "x", ".", "measure", "===", "undefined", ")", "&&", "series", ".", "barGap", ">", "0", ")", "{", "returnXGap", "=", "(", "(", "chart", ".", "_widthPixels", "(", ")", "/", "series", ".", "x", ".", "_max", ")", "*", "(", "series", ".", "barGap", ">", "0.99", "?", "0.99", ":", "series", ".", "barGap", ")", ")", "/", "2", ";", "}", "return", "returnXGap", ";", "}" ]
Calculate the x gap for bar type charts
[ "Calculate", "the", "x", "gap", "for", "bar", "type", "charts" ]
f0ed2797661c2bfeee7ba0696e367051353fd078
https://github.com/nagarajanchinnasamy/simpledimple/blob/f0ed2797661c2bfeee7ba0696e367051353fd078/lib/dimple/dimple.v2.1.4.js#L4646-L4652
46,322
nagarajanchinnasamy/simpledimple
lib/dimple/dimple.v2.1.4.js
function (d, chart, series) { var returnXClusterGap = 0; if (series.x.categoryFields !== null && series.x.categoryFields !== undefined && series.x.categoryFields.length >= 2 && series.clusterBarGap > 0 && !series.x._hasMeasure()) { returnXClusterGap = (d.width * ((chart._widthPixels() / series.x._max) - (dimple._helpers.xGap(chart, series) * 2)) * (series.clusterBarGap > 0.99 ? 0.99 : series.clusterBarGap)) / 2; } return returnXClusterGap; }
javascript
function (d, chart, series) { var returnXClusterGap = 0; if (series.x.categoryFields !== null && series.x.categoryFields !== undefined && series.x.categoryFields.length >= 2 && series.clusterBarGap > 0 && !series.x._hasMeasure()) { returnXClusterGap = (d.width * ((chart._widthPixels() / series.x._max) - (dimple._helpers.xGap(chart, series) * 2)) * (series.clusterBarGap > 0.99 ? 0.99 : series.clusterBarGap)) / 2; } return returnXClusterGap; }
[ "function", "(", "d", ",", "chart", ",", "series", ")", "{", "var", "returnXClusterGap", "=", "0", ";", "if", "(", "series", ".", "x", ".", "categoryFields", "!==", "null", "&&", "series", ".", "x", ".", "categoryFields", "!==", "undefined", "&&", "series", ".", "x", ".", "categoryFields", ".", "length", ">=", "2", "&&", "series", ".", "clusterBarGap", ">", "0", "&&", "!", "series", ".", "x", ".", "_hasMeasure", "(", ")", ")", "{", "returnXClusterGap", "=", "(", "d", ".", "width", "*", "(", "(", "chart", ".", "_widthPixels", "(", ")", "/", "series", ".", "x", ".", "_max", ")", "-", "(", "dimple", ".", "_helpers", ".", "xGap", "(", "chart", ",", "series", ")", "*", "2", ")", ")", "*", "(", "series", ".", "clusterBarGap", ">", "0.99", "?", "0.99", ":", "series", ".", "clusterBarGap", ")", ")", "/", "2", ";", "}", "return", "returnXClusterGap", ";", "}" ]
Calculate the x gap for clusters within bar type charts
[ "Calculate", "the", "x", "gap", "for", "clusters", "within", "bar", "type", "charts" ]
f0ed2797661c2bfeee7ba0696e367051353fd078
https://github.com/nagarajanchinnasamy/simpledimple/blob/f0ed2797661c2bfeee7ba0696e367051353fd078/lib/dimple/dimple.v2.1.4.js#L4655-L4661
46,323
nagarajanchinnasamy/simpledimple
lib/dimple/dimple.v2.1.4.js
function (chart, series) { var returnYGap = 0; if ((series.y.measure === null || series.y.measure === undefined) && series.barGap > 0) { returnYGap = ((chart._heightPixels() / series.y._max) * (series.barGap > 0.99 ? 0.99 : series.barGap)) / 2; } return returnYGap; }
javascript
function (chart, series) { var returnYGap = 0; if ((series.y.measure === null || series.y.measure === undefined) && series.barGap > 0) { returnYGap = ((chart._heightPixels() / series.y._max) * (series.barGap > 0.99 ? 0.99 : series.barGap)) / 2; } return returnYGap; }
[ "function", "(", "chart", ",", "series", ")", "{", "var", "returnYGap", "=", "0", ";", "if", "(", "(", "series", ".", "y", ".", "measure", "===", "null", "||", "series", ".", "y", ".", "measure", "===", "undefined", ")", "&&", "series", ".", "barGap", ">", "0", ")", "{", "returnYGap", "=", "(", "(", "chart", ".", "_heightPixels", "(", ")", "/", "series", ".", "y", ".", "_max", ")", "*", "(", "series", ".", "barGap", ">", "0.99", "?", "0.99", ":", "series", ".", "barGap", ")", ")", "/", "2", ";", "}", "return", "returnYGap", ";", "}" ]
Calculate the y gap for bar type charts
[ "Calculate", "the", "y", "gap", "for", "bar", "type", "charts" ]
f0ed2797661c2bfeee7ba0696e367051353fd078
https://github.com/nagarajanchinnasamy/simpledimple/blob/f0ed2797661c2bfeee7ba0696e367051353fd078/lib/dimple/dimple.v2.1.4.js#L4664-L4670
46,324
nagarajanchinnasamy/simpledimple
lib/dimple/dimple.v2.1.4.js
function (d, chart, series) { var returnYClusterGap = 0; if (series.y.categoryFields !== null && series.y.categoryFields !== undefined && series.y.categoryFields.length >= 2 && series.clusterBarGap > 0 && !series.y._hasMeasure()) { returnYClusterGap = (d.height * ((chart._heightPixels() / series.y._max) - (dimple._helpers.yGap(chart, series) * 2)) * (series.clusterBarGap > 0.99 ? 0.99 : series.clusterBarGap)) / 2; } return returnYClusterGap; }
javascript
function (d, chart, series) { var returnYClusterGap = 0; if (series.y.categoryFields !== null && series.y.categoryFields !== undefined && series.y.categoryFields.length >= 2 && series.clusterBarGap > 0 && !series.y._hasMeasure()) { returnYClusterGap = (d.height * ((chart._heightPixels() / series.y._max) - (dimple._helpers.yGap(chart, series) * 2)) * (series.clusterBarGap > 0.99 ? 0.99 : series.clusterBarGap)) / 2; } return returnYClusterGap; }
[ "function", "(", "d", ",", "chart", ",", "series", ")", "{", "var", "returnYClusterGap", "=", "0", ";", "if", "(", "series", ".", "y", ".", "categoryFields", "!==", "null", "&&", "series", ".", "y", ".", "categoryFields", "!==", "undefined", "&&", "series", ".", "y", ".", "categoryFields", ".", "length", ">=", "2", "&&", "series", ".", "clusterBarGap", ">", "0", "&&", "!", "series", ".", "y", ".", "_hasMeasure", "(", ")", ")", "{", "returnYClusterGap", "=", "(", "d", ".", "height", "*", "(", "(", "chart", ".", "_heightPixels", "(", ")", "/", "series", ".", "y", ".", "_max", ")", "-", "(", "dimple", ".", "_helpers", ".", "yGap", "(", "chart", ",", "series", ")", "*", "2", ")", ")", "*", "(", "series", ".", "clusterBarGap", ">", "0.99", "?", "0.99", ":", "series", ".", "clusterBarGap", ")", ")", "/", "2", ";", "}", "return", "returnYClusterGap", ";", "}" ]
Calculate the y gap for clusters within bar type charts
[ "Calculate", "the", "y", "gap", "for", "clusters", "within", "bar", "type", "charts" ]
f0ed2797661c2bfeee7ba0696e367051353fd078
https://github.com/nagarajanchinnasamy/simpledimple/blob/f0ed2797661c2bfeee7ba0696e367051353fd078/lib/dimple/dimple.v2.1.4.js#L4673-L4679
46,325
nagarajanchinnasamy/simpledimple
lib/dimple/dimple.v2.1.4.js
function (d, chart, series) { var returnX = 0; if (series.x._hasTimeField()) { returnX = series.x._scale(d.x) - (dimple._helpers.width(d, chart, series) / 2); } else if (series.x.measure !== null && series.x.measure !== undefined) { returnX = series.x._scale(d.x); } else { returnX = series.x._scale(d.x) + dimple._helpers.xGap(chart, series) + (d.xOffset * (dimple._helpers.width(d, chart, series) + 2 * dimple._helpers.xClusterGap(d, chart, series))) + dimple._helpers.xClusterGap(d, chart, series); } return returnX; }
javascript
function (d, chart, series) { var returnX = 0; if (series.x._hasTimeField()) { returnX = series.x._scale(d.x) - (dimple._helpers.width(d, chart, series) / 2); } else if (series.x.measure !== null && series.x.measure !== undefined) { returnX = series.x._scale(d.x); } else { returnX = series.x._scale(d.x) + dimple._helpers.xGap(chart, series) + (d.xOffset * (dimple._helpers.width(d, chart, series) + 2 * dimple._helpers.xClusterGap(d, chart, series))) + dimple._helpers.xClusterGap(d, chart, series); } return returnX; }
[ "function", "(", "d", ",", "chart", ",", "series", ")", "{", "var", "returnX", "=", "0", ";", "if", "(", "series", ".", "x", ".", "_hasTimeField", "(", ")", ")", "{", "returnX", "=", "series", ".", "x", ".", "_scale", "(", "d", ".", "x", ")", "-", "(", "dimple", ".", "_helpers", ".", "width", "(", "d", ",", "chart", ",", "series", ")", "/", "2", ")", ";", "}", "else", "if", "(", "series", ".", "x", ".", "measure", "!==", "null", "&&", "series", ".", "x", ".", "measure", "!==", "undefined", ")", "{", "returnX", "=", "series", ".", "x", ".", "_scale", "(", "d", ".", "x", ")", ";", "}", "else", "{", "returnX", "=", "series", ".", "x", ".", "_scale", "(", "d", ".", "x", ")", "+", "dimple", ".", "_helpers", ".", "xGap", "(", "chart", ",", "series", ")", "+", "(", "d", ".", "xOffset", "*", "(", "dimple", ".", "_helpers", ".", "width", "(", "d", ",", "chart", ",", "series", ")", "+", "2", "*", "dimple", ".", "_helpers", ".", "xClusterGap", "(", "d", ",", "chart", ",", "series", ")", ")", ")", "+", "dimple", ".", "_helpers", ".", "xClusterGap", "(", "d", ",", "chart", ",", "series", ")", ";", "}", "return", "returnX", ";", "}" ]
Calculate the top left x position for bar type charts
[ "Calculate", "the", "top", "left", "x", "position", "for", "bar", "type", "charts" ]
f0ed2797661c2bfeee7ba0696e367051353fd078
https://github.com/nagarajanchinnasamy/simpledimple/blob/f0ed2797661c2bfeee7ba0696e367051353fd078/lib/dimple/dimple.v2.1.4.js#L4682-L4692
46,326
nagarajanchinnasamy/simpledimple
lib/dimple/dimple.v2.1.4.js
function (d, chart, series) { var returnY = 0; if (series.y._hasTimeField()) { returnY = series.y._scale(d.y) - (dimple._helpers.height(d, chart, series) / 2); } else if (series.y.measure !== null && series.y.measure !== undefined) { returnY = series.y._scale(d.y); } else { returnY = (series.y._scale(d.y) - (chart._heightPixels() / series.y._max)) + dimple._helpers.yGap(chart, series) + (d.yOffset * (dimple._helpers.height(d, chart, series) + 2 * dimple._helpers.yClusterGap(d, chart, series))) + dimple._helpers.yClusterGap(d, chart, series); } return returnY; }
javascript
function (d, chart, series) { var returnY = 0; if (series.y._hasTimeField()) { returnY = series.y._scale(d.y) - (dimple._helpers.height(d, chart, series) / 2); } else if (series.y.measure !== null && series.y.measure !== undefined) { returnY = series.y._scale(d.y); } else { returnY = (series.y._scale(d.y) - (chart._heightPixels() / series.y._max)) + dimple._helpers.yGap(chart, series) + (d.yOffset * (dimple._helpers.height(d, chart, series) + 2 * dimple._helpers.yClusterGap(d, chart, series))) + dimple._helpers.yClusterGap(d, chart, series); } return returnY; }
[ "function", "(", "d", ",", "chart", ",", "series", ")", "{", "var", "returnY", "=", "0", ";", "if", "(", "series", ".", "y", ".", "_hasTimeField", "(", ")", ")", "{", "returnY", "=", "series", ".", "y", ".", "_scale", "(", "d", ".", "y", ")", "-", "(", "dimple", ".", "_helpers", ".", "height", "(", "d", ",", "chart", ",", "series", ")", "/", "2", ")", ";", "}", "else", "if", "(", "series", ".", "y", ".", "measure", "!==", "null", "&&", "series", ".", "y", ".", "measure", "!==", "undefined", ")", "{", "returnY", "=", "series", ".", "y", ".", "_scale", "(", "d", ".", "y", ")", ";", "}", "else", "{", "returnY", "=", "(", "series", ".", "y", ".", "_scale", "(", "d", ".", "y", ")", "-", "(", "chart", ".", "_heightPixels", "(", ")", "/", "series", ".", "y", ".", "_max", ")", ")", "+", "dimple", ".", "_helpers", ".", "yGap", "(", "chart", ",", "series", ")", "+", "(", "d", ".", "yOffset", "*", "(", "dimple", ".", "_helpers", ".", "height", "(", "d", ",", "chart", ",", "series", ")", "+", "2", "*", "dimple", ".", "_helpers", ".", "yClusterGap", "(", "d", ",", "chart", ",", "series", ")", ")", ")", "+", "dimple", ".", "_helpers", ".", "yClusterGap", "(", "d", ",", "chart", ",", "series", ")", ";", "}", "return", "returnY", ";", "}" ]
Calculate the top left y position for bar type charts
[ "Calculate", "the", "top", "left", "y", "position", "for", "bar", "type", "charts" ]
f0ed2797661c2bfeee7ba0696e367051353fd078
https://github.com/nagarajanchinnasamy/simpledimple/blob/f0ed2797661c2bfeee7ba0696e367051353fd078/lib/dimple/dimple.v2.1.4.js#L4695-L4705
46,327
nagarajanchinnasamy/simpledimple
lib/dimple/dimple.v2.1.4.js
function (d, chart, series) { var returnWidth = 0; if (series.x.measure !== null && series.x.measure !== undefined) { returnWidth = Math.abs(series.x._scale((d.x < 0 ? d.x - d.width : d.x + d.width)) - series.x._scale(d.x)); } else if (series.x._hasTimeField()) { returnWidth = series.x.floatingBarWidth; } else { returnWidth = d.width * ((chart._widthPixels() / series.x._max) - (dimple._helpers.xGap(chart, series) * 2)) - (dimple._helpers.xClusterGap(d, chart, series) * 2); } return returnWidth; }
javascript
function (d, chart, series) { var returnWidth = 0; if (series.x.measure !== null && series.x.measure !== undefined) { returnWidth = Math.abs(series.x._scale((d.x < 0 ? d.x - d.width : d.x + d.width)) - series.x._scale(d.x)); } else if (series.x._hasTimeField()) { returnWidth = series.x.floatingBarWidth; } else { returnWidth = d.width * ((chart._widthPixels() / series.x._max) - (dimple._helpers.xGap(chart, series) * 2)) - (dimple._helpers.xClusterGap(d, chart, series) * 2); } return returnWidth; }
[ "function", "(", "d", ",", "chart", ",", "series", ")", "{", "var", "returnWidth", "=", "0", ";", "if", "(", "series", ".", "x", ".", "measure", "!==", "null", "&&", "series", ".", "x", ".", "measure", "!==", "undefined", ")", "{", "returnWidth", "=", "Math", ".", "abs", "(", "series", ".", "x", ".", "_scale", "(", "(", "d", ".", "x", "<", "0", "?", "d", ".", "x", "-", "d", ".", "width", ":", "d", ".", "x", "+", "d", ".", "width", ")", ")", "-", "series", ".", "x", ".", "_scale", "(", "d", ".", "x", ")", ")", ";", "}", "else", "if", "(", "series", ".", "x", ".", "_hasTimeField", "(", ")", ")", "{", "returnWidth", "=", "series", ".", "x", ".", "floatingBarWidth", ";", "}", "else", "{", "returnWidth", "=", "d", ".", "width", "*", "(", "(", "chart", ".", "_widthPixels", "(", ")", "/", "series", ".", "x", ".", "_max", ")", "-", "(", "dimple", ".", "_helpers", ".", "xGap", "(", "chart", ",", "series", ")", "*", "2", ")", ")", "-", "(", "dimple", ".", "_helpers", ".", "xClusterGap", "(", "d", ",", "chart", ",", "series", ")", "*", "2", ")", ";", "}", "return", "returnWidth", ";", "}" ]
Calculate the width for bar type charts
[ "Calculate", "the", "width", "for", "bar", "type", "charts" ]
f0ed2797661c2bfeee7ba0696e367051353fd078
https://github.com/nagarajanchinnasamy/simpledimple/blob/f0ed2797661c2bfeee7ba0696e367051353fd078/lib/dimple/dimple.v2.1.4.js#L4708-L4718
46,328
nagarajanchinnasamy/simpledimple
lib/dimple/dimple.v2.1.4.js
function (d, chart, series) { var returnHeight = 0; if (series.y._hasTimeField()) { returnHeight = series.y.floatingBarWidth; } else if (series.y.measure !== null && series.y.measure !== undefined) { returnHeight = Math.abs(series.y._scale(d.y) - series.y._scale((d.y <= 0 ? d.y + d.height : d.y - d.height))); } else { returnHeight = d.height * ((chart._heightPixels() / series.y._max) - (dimple._helpers.yGap(chart, series) * 2)) - (dimple._helpers.yClusterGap(d, chart, series) * 2); } return returnHeight; }
javascript
function (d, chart, series) { var returnHeight = 0; if (series.y._hasTimeField()) { returnHeight = series.y.floatingBarWidth; } else if (series.y.measure !== null && series.y.measure !== undefined) { returnHeight = Math.abs(series.y._scale(d.y) - series.y._scale((d.y <= 0 ? d.y + d.height : d.y - d.height))); } else { returnHeight = d.height * ((chart._heightPixels() / series.y._max) - (dimple._helpers.yGap(chart, series) * 2)) - (dimple._helpers.yClusterGap(d, chart, series) * 2); } return returnHeight; }
[ "function", "(", "d", ",", "chart", ",", "series", ")", "{", "var", "returnHeight", "=", "0", ";", "if", "(", "series", ".", "y", ".", "_hasTimeField", "(", ")", ")", "{", "returnHeight", "=", "series", ".", "y", ".", "floatingBarWidth", ";", "}", "else", "if", "(", "series", ".", "y", ".", "measure", "!==", "null", "&&", "series", ".", "y", ".", "measure", "!==", "undefined", ")", "{", "returnHeight", "=", "Math", ".", "abs", "(", "series", ".", "y", ".", "_scale", "(", "d", ".", "y", ")", "-", "series", ".", "y", ".", "_scale", "(", "(", "d", ".", "y", "<=", "0", "?", "d", ".", "y", "+", "d", ".", "height", ":", "d", ".", "y", "-", "d", ".", "height", ")", ")", ")", ";", "}", "else", "{", "returnHeight", "=", "d", ".", "height", "*", "(", "(", "chart", ".", "_heightPixels", "(", ")", "/", "series", ".", "y", ".", "_max", ")", "-", "(", "dimple", ".", "_helpers", ".", "yGap", "(", "chart", ",", "series", ")", "*", "2", ")", ")", "-", "(", "dimple", ".", "_helpers", ".", "yClusterGap", "(", "d", ",", "chart", ",", "series", ")", "*", "2", ")", ";", "}", "return", "returnHeight", ";", "}" ]
Calculate the height for bar type charts
[ "Calculate", "the", "height", "for", "bar", "type", "charts" ]
f0ed2797661c2bfeee7ba0696e367051353fd078
https://github.com/nagarajanchinnasamy/simpledimple/blob/f0ed2797661c2bfeee7ba0696e367051353fd078/lib/dimple/dimple.v2.1.4.js#L4721-L4731
46,329
nagarajanchinnasamy/simpledimple
lib/dimple/dimple.v2.1.4.js
function (d, chart, series) { var returnOpacity = 0; if (series.c !== null && series.c !== undefined) { returnOpacity = d.opacity; } else { returnOpacity = chart.getColor(d.aggField.slice(-1)[0]).opacity; } return returnOpacity; }
javascript
function (d, chart, series) { var returnOpacity = 0; if (series.c !== null && series.c !== undefined) { returnOpacity = d.opacity; } else { returnOpacity = chart.getColor(d.aggField.slice(-1)[0]).opacity; } return returnOpacity; }
[ "function", "(", "d", ",", "chart", ",", "series", ")", "{", "var", "returnOpacity", "=", "0", ";", "if", "(", "series", ".", "c", "!==", "null", "&&", "series", ".", "c", "!==", "undefined", ")", "{", "returnOpacity", "=", "d", ".", "opacity", ";", "}", "else", "{", "returnOpacity", "=", "chart", ".", "getColor", "(", "d", ".", "aggField", ".", "slice", "(", "-", "1", ")", "[", "0", "]", ")", ".", "opacity", ";", "}", "return", "returnOpacity", ";", "}" ]
Calculate the opacity for series
[ "Calculate", "the", "opacity", "for", "series" ]
f0ed2797661c2bfeee7ba0696e367051353fd078
https://github.com/nagarajanchinnasamy/simpledimple/blob/f0ed2797661c2bfeee7ba0696e367051353fd078/lib/dimple/dimple.v2.1.4.js#L4734-L4742
46,330
nagarajanchinnasamy/simpledimple
lib/dimple/dimple.v2.1.4.js
function (d, chart, series) { var returnFill = 0; if (series.c !== null && series.c !== undefined) { returnFill = d.fill; } else { returnFill = chart.getColor(d.aggField.slice(-1)[0]).fill; } return returnFill; }
javascript
function (d, chart, series) { var returnFill = 0; if (series.c !== null && series.c !== undefined) { returnFill = d.fill; } else { returnFill = chart.getColor(d.aggField.slice(-1)[0]).fill; } return returnFill; }
[ "function", "(", "d", ",", "chart", ",", "series", ")", "{", "var", "returnFill", "=", "0", ";", "if", "(", "series", ".", "c", "!==", "null", "&&", "series", ".", "c", "!==", "undefined", ")", "{", "returnFill", "=", "d", ".", "fill", ";", "}", "else", "{", "returnFill", "=", "chart", ".", "getColor", "(", "d", ".", "aggField", ".", "slice", "(", "-", "1", ")", "[", "0", "]", ")", ".", "fill", ";", "}", "return", "returnFill", ";", "}" ]
Calculate the fill coloring for series
[ "Calculate", "the", "fill", "coloring", "for", "series" ]
f0ed2797661c2bfeee7ba0696e367051353fd078
https://github.com/nagarajanchinnasamy/simpledimple/blob/f0ed2797661c2bfeee7ba0696e367051353fd078/lib/dimple/dimple.v2.1.4.js#L4745-L4753
46,331
nagarajanchinnasamy/simpledimple
lib/dimple/dimple.v2.1.4.js
function (d, chart, series) { var stroke = 0; if (series.c !== null && series.c !== undefined) { stroke = d.stroke; } else { stroke = chart.getColor(d.aggField.slice(-1)[0]).stroke; } return stroke; }
javascript
function (d, chart, series) { var stroke = 0; if (series.c !== null && series.c !== undefined) { stroke = d.stroke; } else { stroke = chart.getColor(d.aggField.slice(-1)[0]).stroke; } return stroke; }
[ "function", "(", "d", ",", "chart", ",", "series", ")", "{", "var", "stroke", "=", "0", ";", "if", "(", "series", ".", "c", "!==", "null", "&&", "series", ".", "c", "!==", "undefined", ")", "{", "stroke", "=", "d", ".", "stroke", ";", "}", "else", "{", "stroke", "=", "chart", ".", "getColor", "(", "d", ".", "aggField", ".", "slice", "(", "-", "1", ")", "[", "0", "]", ")", ".", "stroke", ";", "}", "return", "stroke", ";", "}" ]
Calculate the stroke coloring for series
[ "Calculate", "the", "stroke", "coloring", "for", "series" ]
f0ed2797661c2bfeee7ba0696e367051353fd078
https://github.com/nagarajanchinnasamy/simpledimple/blob/f0ed2797661c2bfeee7ba0696e367051353fd078/lib/dimple/dimple.v2.1.4.js#L4756-L4764
46,332
nagarajanchinnasamy/simpledimple
lib/dimple/dimple.v2.1.4.js
function (x, y) { var matrix = selectedShape.node().getCTM(), position = chart.svg.node().createSVGPoint(); position.x = x || 0; position.y = y || 0; return position.matrixTransform(matrix); }
javascript
function (x, y) { var matrix = selectedShape.node().getCTM(), position = chart.svg.node().createSVGPoint(); position.x = x || 0; position.y = y || 0; return position.matrixTransform(matrix); }
[ "function", "(", "x", ",", "y", ")", "{", "var", "matrix", "=", "selectedShape", ".", "node", "(", ")", ".", "getCTM", "(", ")", ",", "position", "=", "chart", ".", "svg", ".", "node", "(", ")", ".", "createSVGPoint", "(", ")", ";", "position", ".", "x", "=", "x", "||", "0", ";", "position", ".", "y", "=", "y", "||", "0", ";", "return", "position", ".", "matrixTransform", "(", "matrix", ")", ";", "}" ]
The margin between the text and the box
[ "The", "margin", "between", "the", "text", "and", "the", "box" ]
f0ed2797661c2bfeee7ba0696e367051353fd078
https://github.com/nagarajanchinnasamy/simpledimple/blob/f0ed2797661c2bfeee7ba0696e367051353fd078/lib/dimple/dimple.v2.1.4.js#L5012-L5018
46,333
linkedin/insframe
InsFrame.js
function() { // locale InsFrame root folder homeFolder = __dirname; console.log(" info -".cyan, "InsFrame root".yellow, homeFolder); // express config app.set("view engine", "ejs"); app.set("views", homeFolder + "/views"); app.set("views"); app.set("view options", { layout: null }); // static resources app.use("/js", express.static(homeFolder + "/js")); app.use("/css", express.static(homeFolder + "/css")); app.use("/images", express.static(homeFolder + "/images")); // port port = this.port || parseInt(process.argv[2]) || PORT; // Timer to send close requests when timeout occurs. setInterval(function() { for (var id in urlData) { urlData[id].timeout -= CHECK_INTERVAL; if (urlData[id].timeout <= 0) { io.sockets.emit("close", { id: id, url: urlData[id].url }); console.log(" info -".cyan, "close/timeout".yellow, JSON.stringify(urlData[id])); delete urlData[id]; } } }, CHECK_INTERVAL); }
javascript
function() { // locale InsFrame root folder homeFolder = __dirname; console.log(" info -".cyan, "InsFrame root".yellow, homeFolder); // express config app.set("view engine", "ejs"); app.set("views", homeFolder + "/views"); app.set("views"); app.set("view options", { layout: null }); // static resources app.use("/js", express.static(homeFolder + "/js")); app.use("/css", express.static(homeFolder + "/css")); app.use("/images", express.static(homeFolder + "/images")); // port port = this.port || parseInt(process.argv[2]) || PORT; // Timer to send close requests when timeout occurs. setInterval(function() { for (var id in urlData) { urlData[id].timeout -= CHECK_INTERVAL; if (urlData[id].timeout <= 0) { io.sockets.emit("close", { id: id, url: urlData[id].url }); console.log(" info -".cyan, "close/timeout".yellow, JSON.stringify(urlData[id])); delete urlData[id]; } } }, CHECK_INTERVAL); }
[ "function", "(", ")", "{", "// locale InsFrame root folder", "homeFolder", "=", "__dirname", ";", "console", ".", "log", "(", "\" info -\"", ".", "cyan", ",", "\"InsFrame root\"", ".", "yellow", ",", "homeFolder", ")", ";", "// express config", "app", ".", "set", "(", "\"view engine\"", ",", "\"ejs\"", ")", ";", "app", ".", "set", "(", "\"views\"", ",", "homeFolder", "+", "\"/views\"", ")", ";", "app", ".", "set", "(", "\"views\"", ")", ";", "app", ".", "set", "(", "\"view options\"", ",", "{", "layout", ":", "null", "}", ")", ";", "// static resources", "app", ".", "use", "(", "\"/js\"", ",", "express", ".", "static", "(", "homeFolder", "+", "\"/js\"", ")", ")", ";", "app", ".", "use", "(", "\"/css\"", ",", "express", ".", "static", "(", "homeFolder", "+", "\"/css\"", ")", ")", ";", "app", ".", "use", "(", "\"/images\"", ",", "express", ".", "static", "(", "homeFolder", "+", "\"/images\"", ")", ")", ";", "// port", "port", "=", "this", ".", "port", "||", "parseInt", "(", "process", ".", "argv", "[", "2", "]", ")", "||", "PORT", ";", "// Timer to send close requests when timeout occurs.", "setInterval", "(", "function", "(", ")", "{", "for", "(", "var", "id", "in", "urlData", ")", "{", "urlData", "[", "id", "]", ".", "timeout", "-=", "CHECK_INTERVAL", ";", "if", "(", "urlData", "[", "id", "]", ".", "timeout", "<=", "0", ")", "{", "io", ".", "sockets", ".", "emit", "(", "\"close\"", ",", "{", "id", ":", "id", ",", "url", ":", "urlData", "[", "id", "]", ".", "url", "}", ")", ";", "console", ".", "log", "(", "\" info -\"", ".", "cyan", ",", "\"close/timeout\"", ".", "yellow", ",", "JSON", ".", "stringify", "(", "urlData", "[", "id", "]", ")", ")", ";", "delete", "urlData", "[", "id", "]", ";", "}", "}", "}", ",", "CHECK_INTERVAL", ")", ";", "}" ]
Setting up environment
[ "Setting", "up", "environment" ]
1799f0b64f9ce77553bc6ca0e9caa08a79787edc
https://github.com/linkedin/insframe/blob/1799f0b64f9ce77553bc6ca0e9caa08a79787edc/InsFrame.js#L53-L83
46,334
linkedin/insframe
InsFrame.js
function() { io = io.listen(app); io.set("log level", 1); io.sockets.on("connection", function(socket) { connections += 1; console.log(" info -".cyan, ("new connection. Connections: " + connections).yellow); socket.on("disconnect", function() { connections -= 1; console.log(" info -".cyan, ("connection closed. Connections: " + connections).yellow); }); socket.on("iframe-loaded", function(data) { urlData[data.id].counter--; console.log(" info -".cyan, ("client sends event iframe-loaded").yellow, JSON.stringify(data)); }); }); }
javascript
function() { io = io.listen(app); io.set("log level", 1); io.sockets.on("connection", function(socket) { connections += 1; console.log(" info -".cyan, ("new connection. Connections: " + connections).yellow); socket.on("disconnect", function() { connections -= 1; console.log(" info -".cyan, ("connection closed. Connections: " + connections).yellow); }); socket.on("iframe-loaded", function(data) { urlData[data.id].counter--; console.log(" info -".cyan, ("client sends event iframe-loaded").yellow, JSON.stringify(data)); }); }); }
[ "function", "(", ")", "{", "io", "=", "io", ".", "listen", "(", "app", ")", ";", "io", ".", "set", "(", "\"log level\"", ",", "1", ")", ";", "io", ".", "sockets", ".", "on", "(", "\"connection\"", ",", "function", "(", "socket", ")", "{", "connections", "+=", "1", ";", "console", ".", "log", "(", "\" info -\"", ".", "cyan", ",", "(", "\"new connection. Connections: \"", "+", "connections", ")", ".", "yellow", ")", ";", "socket", ".", "on", "(", "\"disconnect\"", ",", "function", "(", ")", "{", "connections", "-=", "1", ";", "console", ".", "log", "(", "\" info -\"", ".", "cyan", ",", "(", "\"connection closed. Connections: \"", "+", "connections", ")", ".", "yellow", ")", ";", "}", ")", ";", "socket", ".", "on", "(", "\"iframe-loaded\"", ",", "function", "(", "data", ")", "{", "urlData", "[", "data", ".", "id", "]", ".", "counter", "--", ";", "console", ".", "log", "(", "\" info -\"", ".", "cyan", ",", "(", "\"client sends event iframe-loaded\"", ")", ".", "yellow", ",", "JSON", ".", "stringify", "(", "data", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Socket io initialization
[ "Socket", "io", "initialization" ]
1799f0b64f9ce77553bc6ca0e9caa08a79787edc
https://github.com/linkedin/insframe/blob/1799f0b64f9ce77553bc6ca0e9caa08a79787edc/InsFrame.js#L173-L190
46,335
AXErunners/axecore-p2p
lib/messages/commands/pong.js
PongMessage
function PongMessage(arg, options) { Message.call(this, options); this.command = 'pong'; $.checkArgument( _.isUndefined(arg) || (BufferUtil.isBuffer(arg) && arg.length === 8), 'First argument is expected to be an 8 byte buffer' ); this.nonce = arg || utils.getNonce(); }
javascript
function PongMessage(arg, options) { Message.call(this, options); this.command = 'pong'; $.checkArgument( _.isUndefined(arg) || (BufferUtil.isBuffer(arg) && arg.length === 8), 'First argument is expected to be an 8 byte buffer' ); this.nonce = arg || utils.getNonce(); }
[ "function", "PongMessage", "(", "arg", ",", "options", ")", "{", "Message", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "command", "=", "'pong'", ";", "$", ".", "checkArgument", "(", "_", ".", "isUndefined", "(", "arg", ")", "||", "(", "BufferUtil", ".", "isBuffer", "(", "arg", ")", "&&", "arg", ".", "length", "===", "8", ")", ",", "'First argument is expected to be an 8 byte buffer'", ")", ";", "this", ".", "nonce", "=", "arg", "||", "utils", ".", "getNonce", "(", ")", ";", "}" ]
A message in response to a ping message. @param {Number} arg - A nonce for the Pong message @param {Object=} options @extends Message @constructor
[ "A", "message", "in", "response", "to", "a", "ping", "message", "." ]
c06d0e1d7b9ed44b7ee3061feb394d3896240da9
https://github.com/AXErunners/axecore-p2p/blob/c06d0e1d7b9ed44b7ee3061feb394d3896240da9/lib/messages/commands/pong.js#L19-L27
46,336
c5f7c9/llkp
core.js
txt
function txt(text) { var name = '"' + text.replace(/"/gm, '\\"') + '"'; return new Pattern(name, function (str, pos) { if (str.substr(pos, text.length) == text) return { res: text, end: pos + text.length }; }); }
javascript
function txt(text) { var name = '"' + text.replace(/"/gm, '\\"') + '"'; return new Pattern(name, function (str, pos) { if (str.substr(pos, text.length) == text) return { res: text, end: pos + text.length }; }); }
[ "function", "txt", "(", "text", ")", "{", "var", "name", "=", "'\"'", "+", "text", ".", "replace", "(", "/", "\"", "/", "gm", ",", "'\\\\\"'", ")", "+", "'\"'", ";", "return", "new", "Pattern", "(", "name", ",", "function", "(", "str", ",", "pos", ")", "{", "if", "(", "str", ".", "substr", "(", "pos", ",", "text", ".", "length", ")", "==", "text", ")", "return", "{", "res", ":", "text", ",", "end", ":", "pos", "+", "text", ".", "length", "}", ";", "}", ")", ";", "}" ]
parses a known text
[ "parses", "a", "known", "text" ]
211799a3781cab541fb4d36ffdfaf7524fcc6e02
https://github.com/c5f7c9/llkp/blob/211799a3781cab541fb4d36ffdfaf7524fcc6e02/core.js#L27-L33
46,337
c5f7c9/llkp
core.js
rgx
function rgx(regexp) { return new Pattern(regexp + '', function (str, pos) { var m = regexp.exec(str.slice(pos)); if (m && m.index === 0) // regex must match at the beginning, so index must be 0 return { res: m[0], end: pos + m[0].length }; }); }
javascript
function rgx(regexp) { return new Pattern(regexp + '', function (str, pos) { var m = regexp.exec(str.slice(pos)); if (m && m.index === 0) // regex must match at the beginning, so index must be 0 return { res: m[0], end: pos + m[0].length }; }); }
[ "function", "rgx", "(", "regexp", ")", "{", "return", "new", "Pattern", "(", "regexp", "+", "''", ",", "function", "(", "str", ",", "pos", ")", "{", "var", "m", "=", "regexp", ".", "exec", "(", "str", ".", "slice", "(", "pos", ")", ")", ";", "if", "(", "m", "&&", "m", ".", "index", "===", "0", ")", "// regex must match at the beginning, so index must be 0", "return", "{", "res", ":", "m", "[", "0", "]", ",", "end", ":", "pos", "+", "m", "[", "0", "]", ".", "length", "}", ";", "}", ")", ";", "}" ]
parses a regular expression
[ "parses", "a", "regular", "expression" ]
211799a3781cab541fb4d36ffdfaf7524fcc6e02
https://github.com/c5f7c9/llkp/blob/211799a3781cab541fb4d36ffdfaf7524fcc6e02/core.js#L36-L42
46,338
c5f7c9/llkp
core.js
opt
function opt(pattern, defval) { return new Pattern(pattern + '?', function (str, pos) { return pattern.exec(str, pos) || { res: defval, end: pos }; }); }
javascript
function opt(pattern, defval) { return new Pattern(pattern + '?', function (str, pos) { return pattern.exec(str, pos) || { res: defval, end: pos }; }); }
[ "function", "opt", "(", "pattern", ",", "defval", ")", "{", "return", "new", "Pattern", "(", "pattern", "+", "'?'", ",", "function", "(", "str", ",", "pos", ")", "{", "return", "pattern", ".", "exec", "(", "str", ",", "pos", ")", "||", "{", "res", ":", "defval", ",", "end", ":", "pos", "}", ";", "}", ")", ";", "}" ]
parses an optional pattern
[ "parses", "an", "optional", "pattern" ]
211799a3781cab541fb4d36ffdfaf7524fcc6e02
https://github.com/c5f7c9/llkp/blob/211799a3781cab541fb4d36ffdfaf7524fcc6e02/core.js#L45-L49
46,339
c5f7c9/llkp
core.js
exc
function exc(pattern, except) { var name = pattern + ' ~ ' + except; return new Pattern(name, function (str, pos) { return !except.exec(str, pos) && pattern.exec(str, pos); }); }
javascript
function exc(pattern, except) { var name = pattern + ' ~ ' + except; return new Pattern(name, function (str, pos) { return !except.exec(str, pos) && pattern.exec(str, pos); }); }
[ "function", "exc", "(", "pattern", ",", "except", ")", "{", "var", "name", "=", "pattern", "+", "' ~ '", "+", "except", ";", "return", "new", "Pattern", "(", "name", ",", "function", "(", "str", ",", "pos", ")", "{", "return", "!", "except", ".", "exec", "(", "str", ",", "pos", ")", "&&", "pattern", ".", "exec", "(", "str", ",", "pos", ")", ";", "}", ")", ";", "}" ]
parses a pattern if it doesn't match another pattern
[ "parses", "a", "pattern", "if", "it", "doesn", "t", "match", "another", "pattern" ]
211799a3781cab541fb4d36ffdfaf7524fcc6e02
https://github.com/c5f7c9/llkp/blob/211799a3781cab541fb4d36ffdfaf7524fcc6e02/core.js#L52-L57
46,340
c5f7c9/llkp
core.js
any
function any(/* patterns... */) { var patterns = [].slice.call(arguments, 0); var name = '(' + patterns.join(' | ') + ')'; return new Pattern(name, function (str, pos) { var r, i; for (i = 0; i < patterns.length && !r; i++) r = patterns[i].exec(str, pos); return r; }); }
javascript
function any(/* patterns... */) { var patterns = [].slice.call(arguments, 0); var name = '(' + patterns.join(' | ') + ')'; return new Pattern(name, function (str, pos) { var r, i; for (i = 0; i < patterns.length && !r; i++) r = patterns[i].exec(str, pos); return r; }); }
[ "function", "any", "(", "/* patterns... */", ")", "{", "var", "patterns", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ";", "var", "name", "=", "'('", "+", "patterns", ".", "join", "(", "' | '", ")", "+", "')'", ";", "return", "new", "Pattern", "(", "name", ",", "function", "(", "str", ",", "pos", ")", "{", "var", "r", ",", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "patterns", ".", "length", "&&", "!", "r", ";", "i", "++", ")", "r", "=", "patterns", "[", "i", "]", ".", "exec", "(", "str", ",", "pos", ")", ";", "return", "r", ";", "}", ")", ";", "}" ]
parses any of the given patterns
[ "parses", "any", "of", "the", "given", "patterns" ]
211799a3781cab541fb4d36ffdfaf7524fcc6e02
https://github.com/c5f7c9/llkp/blob/211799a3781cab541fb4d36ffdfaf7524fcc6e02/core.js#L60-L70
46,341
c5f7c9/llkp
core.js
seq
function seq(/* patterns... */) { var patterns = [].slice.call(arguments, 0); var name = '(' + patterns.join(' ') + ')'; return new Pattern(name, function (str, pos) { var i, r, end = pos, res = []; for (i = 0; i < patterns.length; i++) { r = patterns[i].exec(str, end); if (!r) return; res.push(r.res); end = r.end; } return { res: res, end: end }; }); }
javascript
function seq(/* patterns... */) { var patterns = [].slice.call(arguments, 0); var name = '(' + patterns.join(' ') + ')'; return new Pattern(name, function (str, pos) { var i, r, end = pos, res = []; for (i = 0; i < patterns.length; i++) { r = patterns[i].exec(str, end); if (!r) return; res.push(r.res); end = r.end; } return { res: res, end: end }; }); }
[ "function", "seq", "(", "/* patterns... */", ")", "{", "var", "patterns", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ";", "var", "name", "=", "'('", "+", "patterns", ".", "join", "(", "' '", ")", "+", "')'", ";", "return", "new", "Pattern", "(", "name", ",", "function", "(", "str", ",", "pos", ")", "{", "var", "i", ",", "r", ",", "end", "=", "pos", ",", "res", "=", "[", "]", ";", "for", "(", "i", "=", "0", ";", "i", "<", "patterns", ".", "length", ";", "i", "++", ")", "{", "r", "=", "patterns", "[", "i", "]", ".", "exec", "(", "str", ",", "end", ")", ";", "if", "(", "!", "r", ")", "return", ";", "res", ".", "push", "(", "r", ".", "res", ")", ";", "end", "=", "r", ".", "end", ";", "}", "return", "{", "res", ":", "res", ",", "end", ":", "end", "}", ";", "}", ")", ";", "}" ]
parses a sequence of patterns
[ "parses", "a", "sequence", "of", "patterns" ]
211799a3781cab541fb4d36ffdfaf7524fcc6e02
https://github.com/c5f7c9/llkp/blob/211799a3781cab541fb4d36ffdfaf7524fcc6e02/core.js#L73-L89
46,342
AXErunners/axecore-p2p
lib/messages/commands/getblocks.js
GetblocksMessage
function GetblocksMessage(arg, options) { Message.call(this, options); this.command = 'getblocks'; this.version = options.protocolVersion; if (!arg) { arg = {}; } arg = utils.sanitizeStartStop(arg); this.starts = arg.starts; this.stop = arg.stop; }
javascript
function GetblocksMessage(arg, options) { Message.call(this, options); this.command = 'getblocks'; this.version = options.protocolVersion; if (!arg) { arg = {}; } arg = utils.sanitizeStartStop(arg); this.starts = arg.starts; this.stop = arg.stop; }
[ "function", "GetblocksMessage", "(", "arg", ",", "options", ")", "{", "Message", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "command", "=", "'getblocks'", ";", "this", ".", "version", "=", "options", ".", "protocolVersion", ";", "if", "(", "!", "arg", ")", "{", "arg", "=", "{", "}", ";", "}", "arg", "=", "utils", ".", "sanitizeStartStop", "(", "arg", ")", ";", "this", ".", "starts", "=", "arg", ".", "starts", ";", "this", ".", "stop", "=", "arg", ".", "stop", ";", "}" ]
Query another peer about blocks. It can query for multiple block hashes, and the response will contain all the chains of blocks starting from those hashes. @param {Object=} arg @param {Array=} arg.starts - Array of buffers or strings with the starting block hashes @param {Buffer=} arg.stop - Hash of the last block @param {Object} options @extends Message @constructor
[ "Query", "another", "peer", "about", "blocks", ".", "It", "can", "query", "for", "multiple", "block", "hashes", "and", "the", "response", "will", "contain", "all", "the", "chains", "of", "blocks", "starting", "from", "those", "hashes", "." ]
c06d0e1d7b9ed44b7ee3061feb394d3896240da9
https://github.com/AXErunners/axecore-p2p/blob/c06d0e1d7b9ed44b7ee3061feb394d3896240da9/lib/messages/commands/getblocks.js#L22-L32
46,343
AXErunners/axecore-p2p
lib/messages/commands/mnlistdiff.js
MnListDiffMessage
function MnListDiffMessage(arg, options) { Message.call(this, options); this.MnListDiff = options.MnListDiff; this.command = 'mnlistdiff'; $.checkArgument( _.isUndefined(arg) || arg instanceof this.MnListDiff, 'An instance of MnListDiff or undefined is expected' ); this.mnlistdiff = arg; }
javascript
function MnListDiffMessage(arg, options) { Message.call(this, options); this.MnListDiff = options.MnListDiff; this.command = 'mnlistdiff'; $.checkArgument( _.isUndefined(arg) || arg instanceof this.MnListDiff, 'An instance of MnListDiff or undefined is expected' ); this.mnlistdiff = arg; }
[ "function", "MnListDiffMessage", "(", "arg", ",", "options", ")", "{", "Message", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "MnListDiff", "=", "options", ".", "MnListDiff", ";", "this", ".", "command", "=", "'mnlistdiff'", ";", "$", ".", "checkArgument", "(", "_", ".", "isUndefined", "(", "arg", ")", "||", "arg", "instanceof", "this", ".", "MnListDiff", ",", "'An instance of MnListDiff or undefined is expected'", ")", ";", "this", ".", "mnlistdiff", "=", "arg", ";", "}" ]
Contains information about a MnListDiff @param {MnListDiff} arg - An instance of MnListDiff @param {Object=} options @param {Function} options.MnListDiff - a MnListDiff constructor @extends Message @constructor
[ "Contains", "information", "about", "a", "MnListDiff" ]
c06d0e1d7b9ed44b7ee3061feb394d3896240da9
https://github.com/AXErunners/axecore-p2p/blob/c06d0e1d7b9ed44b7ee3061feb394d3896240da9/lib/messages/commands/mnlistdiff.js#L17-L26
46,344
AXErunners/axecore-p2p
lib/pool.js
Pool
function Pool(options) { /* jshint maxcomplexity: 10 */ /* jshint maxstatements: 20 */ var self = this; options = options || {}; this.keepalive = false; this._connectedPeers = {}; this._addrs = []; this.listenAddr = options.listenAddr !== false; this.dnsSeed = options.dnsSeed !== false; this.maxSize = options.maxSize || Pool.MaxConnectedPeers; this.messages = options.messages; this.network = Networks.get(options.network) || Networks.defaultNetwork; this.relay = options.relay === false ? false : true; if (options.addrs) { for(var i = 0; i < options.addrs.length; i++) { this._addAddr(options.addrs[i]); } } if (this.listenAddr) { this.on('peeraddr', function peerAddrEvent(peer, message) { var addrs = message.addresses; var length = addrs.length; for (var i = 0; i < length; i++) { var addr = addrs[i]; var future = new Date().getTime() + (10 * 60 * 1000); if (addr.time.getTime() <= 100000000000 || addr.time.getTime() > future) { // In case of an invalid time, assume "5 days ago" var past = new Date(new Date().getTime() - 5 * 24 * 60 * 60 * 1000); addr.time = past; } this._addAddr(addr); } }); } this.on('seed', function seedEvent(ips) { ips.forEach(function(ip) { self._addAddr({ ip: { v4: ip } }); }); if (self.keepalive) { self._fillConnections(); } }); this.on('peerdisconnect', function peerDisconnectEvent(peer, addr) { self._deprioritizeAddr(addr); self._removeConnectedPeer(addr); if (self.keepalive) { self._fillConnections(); } }); return this; }
javascript
function Pool(options) { /* jshint maxcomplexity: 10 */ /* jshint maxstatements: 20 */ var self = this; options = options || {}; this.keepalive = false; this._connectedPeers = {}; this._addrs = []; this.listenAddr = options.listenAddr !== false; this.dnsSeed = options.dnsSeed !== false; this.maxSize = options.maxSize || Pool.MaxConnectedPeers; this.messages = options.messages; this.network = Networks.get(options.network) || Networks.defaultNetwork; this.relay = options.relay === false ? false : true; if (options.addrs) { for(var i = 0; i < options.addrs.length; i++) { this._addAddr(options.addrs[i]); } } if (this.listenAddr) { this.on('peeraddr', function peerAddrEvent(peer, message) { var addrs = message.addresses; var length = addrs.length; for (var i = 0; i < length; i++) { var addr = addrs[i]; var future = new Date().getTime() + (10 * 60 * 1000); if (addr.time.getTime() <= 100000000000 || addr.time.getTime() > future) { // In case of an invalid time, assume "5 days ago" var past = new Date(new Date().getTime() - 5 * 24 * 60 * 60 * 1000); addr.time = past; } this._addAddr(addr); } }); } this.on('seed', function seedEvent(ips) { ips.forEach(function(ip) { self._addAddr({ ip: { v4: ip } }); }); if (self.keepalive) { self._fillConnections(); } }); this.on('peerdisconnect', function peerDisconnectEvent(peer, addr) { self._deprioritizeAddr(addr); self._removeConnectedPeer(addr); if (self.keepalive) { self._fillConnections(); } }); return this; }
[ "function", "Pool", "(", "options", ")", "{", "/* jshint maxcomplexity: 10 */", "/* jshint maxstatements: 20 */", "var", "self", "=", "this", ";", "options", "=", "options", "||", "{", "}", ";", "this", ".", "keepalive", "=", "false", ";", "this", ".", "_connectedPeers", "=", "{", "}", ";", "this", ".", "_addrs", "=", "[", "]", ";", "this", ".", "listenAddr", "=", "options", ".", "listenAddr", "!==", "false", ";", "this", ".", "dnsSeed", "=", "options", ".", "dnsSeed", "!==", "false", ";", "this", ".", "maxSize", "=", "options", ".", "maxSize", "||", "Pool", ".", "MaxConnectedPeers", ";", "this", ".", "messages", "=", "options", ".", "messages", ";", "this", ".", "network", "=", "Networks", ".", "get", "(", "options", ".", "network", ")", "||", "Networks", ".", "defaultNetwork", ";", "this", ".", "relay", "=", "options", ".", "relay", "===", "false", "?", "false", ":", "true", ";", "if", "(", "options", ".", "addrs", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "options", ".", "addrs", ".", "length", ";", "i", "++", ")", "{", "this", ".", "_addAddr", "(", "options", ".", "addrs", "[", "i", "]", ")", ";", "}", "}", "if", "(", "this", ".", "listenAddr", ")", "{", "this", ".", "on", "(", "'peeraddr'", ",", "function", "peerAddrEvent", "(", "peer", ",", "message", ")", "{", "var", "addrs", "=", "message", ".", "addresses", ";", "var", "length", "=", "addrs", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "var", "addr", "=", "addrs", "[", "i", "]", ";", "var", "future", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", "+", "(", "10", "*", "60", "*", "1000", ")", ";", "if", "(", "addr", ".", "time", ".", "getTime", "(", ")", "<=", "100000000000", "||", "addr", ".", "time", ".", "getTime", "(", ")", ">", "future", ")", "{", "// In case of an invalid time, assume \"5 days ago\"", "var", "past", "=", "new", "Date", "(", "new", "Date", "(", ")", ".", "getTime", "(", ")", "-", "5", "*", "24", "*", "60", "*", "60", "*", "1000", ")", ";", "addr", ".", "time", "=", "past", ";", "}", "this", ".", "_addAddr", "(", "addr", ")", ";", "}", "}", ")", ";", "}", "this", ".", "on", "(", "'seed'", ",", "function", "seedEvent", "(", "ips", ")", "{", "ips", ".", "forEach", "(", "function", "(", "ip", ")", "{", "self", ".", "_addAddr", "(", "{", "ip", ":", "{", "v4", ":", "ip", "}", "}", ")", ";", "}", ")", ";", "if", "(", "self", ".", "keepalive", ")", "{", "self", ".", "_fillConnections", "(", ")", ";", "}", "}", ")", ";", "this", ".", "on", "(", "'peerdisconnect'", ",", "function", "peerDisconnectEvent", "(", "peer", ",", "addr", ")", "{", "self", ".", "_deprioritizeAddr", "(", "addr", ")", ";", "self", ".", "_removeConnectedPeer", "(", "addr", ")", ";", "if", "(", "self", ".", "keepalive", ")", "{", "self", ".", "_fillConnections", "(", ")", ";", "}", "}", ")", ";", "return", "this", ";", "}" ]
A pool is a collection of Peers. A pool will discover peers from DNS seeds, and collect information about new peers in the network. When a peer disconnects the pool will connect to others that are available to maintain a max number of ongoing peer connections. Peer events are relayed to the pool. @example ```javascript var pool = new Pool({network: Networks.livenet}); pool.on('peerinv', function(peer, message) { // do something with the inventory announcement }); pool.connect(); ``` @param {Object=} options @param {Network=} options.network - The network configuration @param {Boolean=} options.listenAddr - Prevent new peers being added from addr messages @param {Boolean=} options.dnsSeed - Prevent seeding with DNS discovered known peers @param {Boolean=} options.relay - Prevent inventory announcements until a filter is loaded @param {Number=} options.maxSize - The max number of peers @returns {Pool} @constructor
[ "A", "pool", "is", "a", "collection", "of", "Peers", ".", "A", "pool", "will", "discover", "peers", "from", "DNS", "seeds", "and", "collect", "information", "about", "new", "peers", "in", "the", "network", ".", "When", "a", "peer", "disconnects", "the", "pool", "will", "connect", "to", "others", "that", "are", "available", "to", "maintain", "a", "max", "number", "of", "ongoing", "peer", "connections", ".", "Peer", "events", "are", "relayed", "to", "the", "pool", "." ]
c06d0e1d7b9ed44b7ee3061feb394d3896240da9
https://github.com/AXErunners/axecore-p2p/blob/c06d0e1d7b9ed44b7ee3061feb394d3896240da9/lib/pool.js#L41-L106
46,345
nbeach/keycoder
dist/keycoder.js
function (keyData) { this.shift = {}; this.names = Util.clone(Util.whenUndefined(keyData.names, [])); this.character = Util.whenUndefined(keyData.char, null); this.shift.character = Util.whenUndefined(keyData.shift, Util.whenUndefined(keyData.char, null)); this.keyCode = { ie: keyData.ie, mozilla: Util.whenUndefined(keyData.moz, keyData.ie) }; this.charCode = null; this.shift.charCode = null; if (!Util.isUndefined(keyData.ascii)) { this.charCode = Util.whenUndefined(keyData.ascii.norm, null); this.shift.charCode = Util.whenUndefined(keyData.ascii.shift, Util.whenUndefined(keyData.ascii.norm, null)); } }
javascript
function (keyData) { this.shift = {}; this.names = Util.clone(Util.whenUndefined(keyData.names, [])); this.character = Util.whenUndefined(keyData.char, null); this.shift.character = Util.whenUndefined(keyData.shift, Util.whenUndefined(keyData.char, null)); this.keyCode = { ie: keyData.ie, mozilla: Util.whenUndefined(keyData.moz, keyData.ie) }; this.charCode = null; this.shift.charCode = null; if (!Util.isUndefined(keyData.ascii)) { this.charCode = Util.whenUndefined(keyData.ascii.norm, null); this.shift.charCode = Util.whenUndefined(keyData.ascii.shift, Util.whenUndefined(keyData.ascii.norm, null)); } }
[ "function", "(", "keyData", ")", "{", "this", ".", "shift", "=", "{", "}", ";", "this", ".", "names", "=", "Util", ".", "clone", "(", "Util", ".", "whenUndefined", "(", "keyData", ".", "names", ",", "[", "]", ")", ")", ";", "this", ".", "character", "=", "Util", ".", "whenUndefined", "(", "keyData", ".", "char", ",", "null", ")", ";", "this", ".", "shift", ".", "character", "=", "Util", ".", "whenUndefined", "(", "keyData", ".", "shift", ",", "Util", ".", "whenUndefined", "(", "keyData", ".", "char", ",", "null", ")", ")", ";", "this", ".", "keyCode", "=", "{", "ie", ":", "keyData", ".", "ie", ",", "mozilla", ":", "Util", ".", "whenUndefined", "(", "keyData", ".", "moz", ",", "keyData", ".", "ie", ")", "}", ";", "this", ".", "charCode", "=", "null", ";", "this", ".", "shift", ".", "charCode", "=", "null", ";", "if", "(", "!", "Util", ".", "isUndefined", "(", "keyData", ".", "ascii", ")", ")", "{", "this", ".", "charCode", "=", "Util", ".", "whenUndefined", "(", "keyData", ".", "ascii", ".", "norm", ",", "null", ")", ";", "this", ".", "shift", ".", "charCode", "=", "Util", ".", "whenUndefined", "(", "keyData", ".", "ascii", ".", "shift", ",", "Util", ".", "whenUndefined", "(", "keyData", ".", "ascii", ".", "norm", ",", "null", ")", ")", ";", "}", "}" ]
A representation of a keyboard key. This class cannot be instantiated manually. All instances are generated by the Keycoder module. @Class Key @internal @property {string[]} names - Names that the key is called. Ex. "BACKSPACE", "INSERT" @property {number} keyCode.ie - IE key code @property {number} keyCode.mozilla - Mozillia key code @property {string|null} character - Key character @property {number|null} charCode - ASCII character code @property {string|null} shift.character Key shift character @property {number|null} shift.charCode Shift ASCII character code
[ "A", "representation", "of", "a", "keyboard", "key", ".", "This", "class", "cannot", "be", "instantiated", "manually", ".", "All", "instances", "are", "generated", "by", "the", "Keycoder", "module", "." ]
ad61e2ff8c1580c4000786ea80adb8d5c081c531
https://github.com/nbeach/keycoder/blob/ad61e2ff8c1580c4000786ea80adb8d5c081c531/dist/keycoder.js#L724-L739
46,346
morganherlocker/clipsy
index.js
Barrett
function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); Int128.ONE.dlShiftTo(2 * m.t, this.r2); this.mu = this.r2.divide(m); this.m = m; }
javascript
function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); Int128.ONE.dlShiftTo(2 * m.t, this.r2); this.mu = this.r2.divide(m); this.m = m; }
[ "function", "Barrett", "(", "m", ")", "{", "// setup Barrett", "this", ".", "r2", "=", "nbi", "(", ")", ";", "this", ".", "q3", "=", "nbi", "(", ")", ";", "Int128", ".", "ONE", ".", "dlShiftTo", "(", "2", "*", "m", ".", "t", ",", "this", ".", "r2", ")", ";", "this", ".", "mu", "=", "this", ".", "r2", ".", "divide", "(", "m", ")", ";", "this", ".", "m", "=", "m", ";", "}" ]
Barrett modular reduction
[ "Barrett", "modular", "reduction" ]
9e07c276a82f7eac41024fd2222884e4165a54d4
https://github.com/morganherlocker/clipsy/blob/9e07c276a82f7eac41024fd2222884e4165a54d4/index.js#L1297-L1305
46,347
AXErunners/axecore-p2p
lib/messages/index.js
Messages
function Messages(options) { this.builder = Messages.builder(options); // map message constructors by name for(var key in this.builder.commandsMap) { var name = this.builder.commandsMap[key]; this[name] = this.builder.commands[key]; } if (!options) { options = {}; } this.network = options.network || axecore.Networks.defaultNetwork; }
javascript
function Messages(options) { this.builder = Messages.builder(options); // map message constructors by name for(var key in this.builder.commandsMap) { var name = this.builder.commandsMap[key]; this[name] = this.builder.commands[key]; } if (!options) { options = {}; } this.network = options.network || axecore.Networks.defaultNetwork; }
[ "function", "Messages", "(", "options", ")", "{", "this", ".", "builder", "=", "Messages", ".", "builder", "(", "options", ")", ";", "// map message constructors by name", "for", "(", "var", "key", "in", "this", ".", "builder", ".", "commandsMap", ")", "{", "var", "name", "=", "this", ".", "builder", ".", "commandsMap", "[", "key", "]", ";", "this", "[", "name", "]", "=", "this", ".", "builder", ".", "commands", "[", "key", "]", ";", "}", "if", "(", "!", "options", ")", "{", "options", "=", "{", "}", ";", "}", "this", ".", "network", "=", "options", ".", "network", "||", "axecore", ".", "Networks", ".", "defaultNetwork", ";", "}" ]
A factory to build Bitcoin protocol messages. @param {Object=} options @param {Network=} options.network @param {Function=} options.Block - A block constructor @param {Function=} options.BlockHeader - A block header constructor @param {Function=} options.MerkleBlock - A merkle block constructor @param {Function=} options.Transaction - A transaction constructor @param {Function=} options.MnListDiff - A masternode difference list constructor @constructor
[ "A", "factory", "to", "build", "Bitcoin", "protocol", "messages", "." ]
c06d0e1d7b9ed44b7ee3061feb394d3896240da9
https://github.com/AXErunners/axecore-p2p/blob/c06d0e1d7b9ed44b7ee3061feb394d3896240da9/lib/messages/index.js#L19-L32
46,348
NiklasGollenstede/web-ext-utils
utils/index.js
showExtensionTab
async function showExtensionTab(url, match = url) { match = extension.getURL(match || url); url = extension.getURL(url); for (const view of extension.getViews({ type: 'tab', })) { if (view && (typeof match === 'string' ? view.location.href === match : match.test(view.location.href)) && view.tabId != null) { const tab = (await new Promise(got => (view.browser || view.chrome).tabs.getCurrent(got))); if (tab) { (await Tabs.update(tab.id, { active: true, })); (await Windows.update(tab.windowId, { focused: true, })); return tab; } } } return Tabs.create({ url, }); }
javascript
async function showExtensionTab(url, match = url) { match = extension.getURL(match || url); url = extension.getURL(url); for (const view of extension.getViews({ type: 'tab', })) { if (view && (typeof match === 'string' ? view.location.href === match : match.test(view.location.href)) && view.tabId != null) { const tab = (await new Promise(got => (view.browser || view.chrome).tabs.getCurrent(got))); if (tab) { (await Tabs.update(tab.id, { active: true, })); (await Windows.update(tab.windowId, { focused: true, })); return tab; } } } return Tabs.create({ url, }); }
[ "async", "function", "showExtensionTab", "(", "url", ",", "match", "=", "url", ")", "{", "match", "=", "extension", ".", "getURL", "(", "match", "||", "url", ")", ";", "url", "=", "extension", ".", "getURL", "(", "url", ")", ";", "for", "(", "const", "view", "of", "extension", ".", "getViews", "(", "{", "type", ":", "'tab'", ",", "}", ")", ")", "{", "if", "(", "view", "&&", "(", "typeof", "match", "===", "'string'", "?", "view", ".", "location", ".", "href", "===", "match", ":", "match", ".", "test", "(", "view", ".", "location", ".", "href", ")", ")", "&&", "view", ".", "tabId", "!=", "null", ")", "{", "const", "tab", "=", "(", "await", "new", "Promise", "(", "got", "=>", "(", "view", ".", "browser", "||", "view", ".", "chrome", ")", ".", "tabs", ".", "getCurrent", "(", "got", ")", ")", ")", ";", "if", "(", "tab", ")", "{", "(", "await", "Tabs", ".", "update", "(", "tab", ".", "id", ",", "{", "active", ":", "true", ",", "}", ")", ")", ";", "(", "await", "Windows", ".", "update", "(", "tab", ".", "windowId", ",", "{", "focused", ":", "true", ",", "}", ")", ")", ";", "return", "tab", ";", "}", "}", "}", "return", "Tabs", ".", "create", "(", "{", "url", ",", "}", ")", ";", "}" ]
Shows or opens a tab containing an extension page. Shows the fist tab whose .pathname equals 'match' and that has a window.tabId set, or opens a new tab containing 'url' if no such tab is found. @param {string} url The url to open in the new tab if no existing tab was found. @param {string} match Optional value of window.location.pathname a existing tab must have to be focused. @return {Promise<Tab>} The chrome.tabs.Tab that is now the active tab in the focused window.
[ "Shows", "or", "opens", "a", "tab", "containing", "an", "extension", "page", ".", "Shows", "the", "fist", "tab", "whose", ".", "pathname", "equals", "match", "and", "that", "has", "a", "window", ".", "tabId", "set", "or", "opens", "a", "new", "tab", "containing", "url", "if", "no", "such", "tab", "is", "found", "." ]
395698c633da88db86377d583b9b4eac6d9cc299
https://github.com/NiklasGollenstede/web-ext-utils/blob/395698c633da88db86377d583b9b4eac6d9cc299/utils/index.js#L79-L88
46,349
AXErunners/axecore-p2p
lib/inventory.js
Inventory
function Inventory(obj) { this.type = obj.type; if (!BufferUtil.isBuffer(obj.hash)) { throw new TypeError('Unexpected hash, expected to be a buffer'); } this.hash = obj.hash; }
javascript
function Inventory(obj) { this.type = obj.type; if (!BufferUtil.isBuffer(obj.hash)) { throw new TypeError('Unexpected hash, expected to be a buffer'); } this.hash = obj.hash; }
[ "function", "Inventory", "(", "obj", ")", "{", "this", ".", "type", "=", "obj", ".", "type", ";", "if", "(", "!", "BufferUtil", ".", "isBuffer", "(", "obj", ".", "hash", ")", ")", "{", "throw", "new", "TypeError", "(", "'Unexpected hash, expected to be a buffer'", ")", ";", "}", "this", ".", "hash", "=", "obj", ".", "hash", ";", "}" ]
A constructor for inventory related Bitcoin messages such as "getdata", "inv" and "notfound". @param {Object} obj @param {Number} obj.type - Inventory.TYPE @param {Buffer} obj.hash - The hash for the inventory @constructor
[ "A", "constructor", "for", "inventory", "related", "Bitcoin", "messages", "such", "as", "getdata", "inv", "and", "notfound", "." ]
c06d0e1d7b9ed44b7ee3061feb394d3896240da9
https://github.com/AXErunners/axecore-p2p/blob/c06d0e1d7b9ed44b7ee3061feb394d3896240da9/lib/inventory.js#L18-L24
46,350
hlapp/wirelesstags-js
lib/util.js
defineLinkedProperty
function defineLinkedProperty(obj, prop, srcProp, readOnly) { let propName, srcKey; if (Array.isArray(prop)) { propName = prop[0]; srcKey = prop[1]; } else { propName = srcKey = prop; } if (typeof srcProp === 'boolean') { readOnly = srcProp; srcProp = undefined; } if (! srcProp) srcProp = 'data'; let descriptor = { enumerable: true, get: function() { return obj[srcProp][srcKey] } }; if (! readOnly) { descriptor.set = function(val) { let oldVal = obj[srcProp][srcKey]; if (! deepEqual(val, oldVal)) { obj[srcKey][srcKey] = val; if (obj instanceof EventEmitter) { obj.emit('update', obj, propName, val); } } }; } Object.defineProperty(obj, propName, descriptor); }
javascript
function defineLinkedProperty(obj, prop, srcProp, readOnly) { let propName, srcKey; if (Array.isArray(prop)) { propName = prop[0]; srcKey = prop[1]; } else { propName = srcKey = prop; } if (typeof srcProp === 'boolean') { readOnly = srcProp; srcProp = undefined; } if (! srcProp) srcProp = 'data'; let descriptor = { enumerable: true, get: function() { return obj[srcProp][srcKey] } }; if (! readOnly) { descriptor.set = function(val) { let oldVal = obj[srcProp][srcKey]; if (! deepEqual(val, oldVal)) { obj[srcKey][srcKey] = val; if (obj instanceof EventEmitter) { obj.emit('update', obj, propName, val); } } }; } Object.defineProperty(obj, propName, descriptor); }
[ "function", "defineLinkedProperty", "(", "obj", ",", "prop", ",", "srcProp", ",", "readOnly", ")", "{", "let", "propName", ",", "srcKey", ";", "if", "(", "Array", ".", "isArray", "(", "prop", ")", ")", "{", "propName", "=", "prop", "[", "0", "]", ";", "srcKey", "=", "prop", "[", "1", "]", ";", "}", "else", "{", "propName", "=", "srcKey", "=", "prop", ";", "}", "if", "(", "typeof", "srcProp", "===", "'boolean'", ")", "{", "readOnly", "=", "srcProp", ";", "srcProp", "=", "undefined", ";", "}", "if", "(", "!", "srcProp", ")", "srcProp", "=", "'data'", ";", "let", "descriptor", "=", "{", "enumerable", ":", "true", ",", "get", ":", "function", "(", ")", "{", "return", "obj", "[", "srcProp", "]", "[", "srcKey", "]", "}", "}", ";", "if", "(", "!", "readOnly", ")", "{", "descriptor", ".", "set", "=", "function", "(", "val", ")", "{", "let", "oldVal", "=", "obj", "[", "srcProp", "]", "[", "srcKey", "]", ";", "if", "(", "!", "deepEqual", "(", "val", ",", "oldVal", ")", ")", "{", "obj", "[", "srcKey", "]", "[", "srcKey", "]", "=", "val", ";", "if", "(", "obj", "instanceof", "EventEmitter", ")", "{", "obj", ".", "emit", "(", "'update'", ",", "obj", ",", "propName", ",", "val", ")", ";", "}", "}", "}", ";", "}", "Object", ".", "defineProperty", "(", "obj", ",", "propName", ",", "descriptor", ")", ";", "}" ]
Defines a property on the given object whose value will be linked to that of the property of another object. If the object is an event emitter, a property set that changes the value will emit an 'update' event for the object with 3 parameters, the object, the name of the property, and the new value. @param {object} obj - the object for which to define the property @param {string|string[]} prop - the name of the property to define, or an array of two elements, namely the name of the property to define, and the name of the property to link to @param {string} [srcProp] - the name of the property that stores the source object (from which values will be linked). Default is 'data'. @param {boolean} [readOnly] - whether the property is to be read-only, defaults to `false`. @memberof module:lib/util @since 0.7.0
[ "Defines", "a", "property", "on", "the", "given", "object", "whose", "value", "will", "be", "linked", "to", "that", "of", "the", "property", "of", "another", "object", ".", "If", "the", "object", "is", "an", "event", "emitter", "a", "property", "set", "that", "changes", "the", "value", "will", "emit", "an", "update", "event", "for", "the", "object", "with", "3", "parameters", "the", "object", "the", "name", "of", "the", "property", "and", "the", "new", "value", "." ]
ce63485ce37b33f552ceb2939740a40957a416f3
https://github.com/hlapp/wirelesstags-js/blob/ce63485ce37b33f552ceb2939740a40957a416f3/lib/util.js#L75-L104
46,351
hlapp/wirelesstags-js
lib/util.js
createFilter
function createFilter(jsonQuery) { if ('function' === typeof jsonQuery) return jsonQuery; if ((!jsonQuery) || (Object.keys(jsonQuery).length === 0)) { return () => true; } jsonQuery = Object.assign({}, jsonQuery); // protect against side effects return function(obj) { for (let key of Object.keys(jsonQuery)) { if (! Object.is(obj[key], jsonQuery[key])) return false; } return true; }; }
javascript
function createFilter(jsonQuery) { if ('function' === typeof jsonQuery) return jsonQuery; if ((!jsonQuery) || (Object.keys(jsonQuery).length === 0)) { return () => true; } jsonQuery = Object.assign({}, jsonQuery); // protect against side effects return function(obj) { for (let key of Object.keys(jsonQuery)) { if (! Object.is(obj[key], jsonQuery[key])) return false; } return true; }; }
[ "function", "createFilter", "(", "jsonQuery", ")", "{", "if", "(", "'function'", "===", "typeof", "jsonQuery", ")", "return", "jsonQuery", ";", "if", "(", "(", "!", "jsonQuery", ")", "||", "(", "Object", ".", "keys", "(", "jsonQuery", ")", ".", "length", "===", "0", ")", ")", "{", "return", "(", ")", "=>", "true", ";", "}", "jsonQuery", "=", "Object", ".", "assign", "(", "{", "}", ",", "jsonQuery", ")", ";", "// protect against side effects", "return", "function", "(", "obj", ")", "{", "for", "(", "let", "key", "of", "Object", ".", "keys", "(", "jsonQuery", ")", ")", "{", "if", "(", "!", "Object", ".", "is", "(", "obj", "[", "key", "]", ",", "jsonQuery", "[", "key", "]", ")", ")", "return", "false", ";", "}", "return", "true", ";", "}", ";", "}" ]
Turns the given JSON object into a filter function. @param {object} [jsonQuery] - An object specifying properties and values that an object has to match in order to pass the filter. If omitted, or if the object has no keys, any object will pass the generated filter. @returns {function} the generated filter function, accepts an object as argument and returns true if it passes the filter and false otherwise. @memberof module:lib/util
[ "Turns", "the", "given", "JSON", "object", "into", "a", "filter", "function", "." ]
ce63485ce37b33f552ceb2939740a40957a416f3
https://github.com/hlapp/wirelesstags-js/blob/ce63485ce37b33f552ceb2939740a40957a416f3/lib/util.js#L236-L248
46,352
arafato/funcy-azure
lib/utils/env.js
envToObject
function envToObject(fullPath) { return fs.readFileAsync(fullPath) .then((file) => { let envVars = {}; file = file.toString('utf8'); file = file.replace(/ /g, ""); let keyvals = file.split(os.EOL) for (let i = 0; i <= keyvals.length - 1; ++i) { let line = keyvals[i]; let value = line.substring(line.indexOf('=')+1); let key = keyvals[i].split('=')[0]; if(key !== '') { envVars[key] = value; } } return envVars }); }
javascript
function envToObject(fullPath) { return fs.readFileAsync(fullPath) .then((file) => { let envVars = {}; file = file.toString('utf8'); file = file.replace(/ /g, ""); let keyvals = file.split(os.EOL) for (let i = 0; i <= keyvals.length - 1; ++i) { let line = keyvals[i]; let value = line.substring(line.indexOf('=')+1); let key = keyvals[i].split('=')[0]; if(key !== '') { envVars[key] = value; } } return envVars }); }
[ "function", "envToObject", "(", "fullPath", ")", "{", "return", "fs", ".", "readFileAsync", "(", "fullPath", ")", ".", "then", "(", "(", "file", ")", "=>", "{", "let", "envVars", "=", "{", "}", ";", "file", "=", "file", ".", "toString", "(", "'utf8'", ")", ";", "file", "=", "file", ".", "replace", "(", "/", " ", "/", "g", ",", "\"\"", ")", ";", "let", "keyvals", "=", "file", ".", "split", "(", "os", ".", "EOL", ")", "for", "(", "let", "i", "=", "0", ";", "i", "<=", "keyvals", ".", "length", "-", "1", ";", "++", "i", ")", "{", "let", "line", "=", "keyvals", "[", "i", "]", ";", "let", "value", "=", "line", ".", "substring", "(", "line", ".", "indexOf", "(", "'='", ")", "+", "1", ")", ";", "let", "key", "=", "keyvals", "[", "i", "]", ".", "split", "(", "'='", ")", "[", "0", "]", ";", "if", "(", "key", "!==", "''", ")", "{", "envVars", "[", "key", "]", "=", "value", ";", "}", "}", "return", "envVars", "}", ")", ";", "}" ]
The CLI needs to be invoked from the project folder
[ "The", "CLI", "needs", "to", "be", "invoked", "from", "the", "project", "folder" ]
e2ed1965a2e9da6421b0eefa3a340b38c1ed4eec
https://github.com/arafato/funcy-azure/blob/e2ed1965a2e9da6421b0eefa3a340b38c1ed4eec/lib/utils/env.js#L11-L28
46,353
guileen/node-rts
lib/rts.js
setValue
function setValue(name, stat, value, gran, timestamp, callback) { if(typeof gran == 'string') { gran = util.getUnitDesc(gran) } var key = getGranKey(name, gran, timestamp); redis.hset(key, stat, value, callback) }
javascript
function setValue(name, stat, value, gran, timestamp, callback) { if(typeof gran == 'string') { gran = util.getUnitDesc(gran) } var key = getGranKey(name, gran, timestamp); redis.hset(key, stat, value, callback) }
[ "function", "setValue", "(", "name", ",", "stat", ",", "value", ",", "gran", ",", "timestamp", ",", "callback", ")", "{", "if", "(", "typeof", "gran", "==", "'string'", ")", "{", "gran", "=", "util", ".", "getUnitDesc", "(", "gran", ")", "}", "var", "key", "=", "getGranKey", "(", "name", ",", "gran", ",", "timestamp", ")", ";", "redis", ".", "hset", "(", "key", ",", "stat", ",", "value", ",", "callback", ")", "}" ]
some thing's some statics value in some granularity at some time
[ "some", "thing", "s", "some", "statics", "value", "in", "some", "granularity", "at", "some", "time" ]
22b88c9b81a26e0b7a6e65bf815318fa60f21e55
https://github.com/guileen/node-rts/blob/22b88c9b81a26e0b7a6e65bf815318fa60f21e55/lib/rts.js#L102-L108
46,354
guileen/node-rts
lib/rts.js
recordUnique
function recordUnique(name, uniqueId, statistics, aggregations, timestamp, callback) { timestamp = timestamp || Date.now(); // normal record if(statistics) { var num = Array.isArray(uniqueId) ? uniqueId.length : 1; record(name, num, statistics, aggregations, timestamp); } // record unique var multi = redis.multi(); granularities.forEach(function(gran) { var key = getGranKey(name, gran, timestamp); var expireTime = util.getExpireTime(gran, timestamp); var pfkey = key + ':pf'; multi.hset(keyPFKeys, pfkey, expireTime); if(Array.isArray(uniqueId)) { multi.pfadd.apply(multi, [pfkey].concat(uniqueId)); } else { multi.pfadd(pfkey, uniqueId); } // recordStats(key); var unitPeriod = gran[0]; multi.hincrby(key, 'uni', 0); multi.expire(key, points * unitPeriod / 1000); }); multi.exec(callback || log); }
javascript
function recordUnique(name, uniqueId, statistics, aggregations, timestamp, callback) { timestamp = timestamp || Date.now(); // normal record if(statistics) { var num = Array.isArray(uniqueId) ? uniqueId.length : 1; record(name, num, statistics, aggregations, timestamp); } // record unique var multi = redis.multi(); granularities.forEach(function(gran) { var key = getGranKey(name, gran, timestamp); var expireTime = util.getExpireTime(gran, timestamp); var pfkey = key + ':pf'; multi.hset(keyPFKeys, pfkey, expireTime); if(Array.isArray(uniqueId)) { multi.pfadd.apply(multi, [pfkey].concat(uniqueId)); } else { multi.pfadd(pfkey, uniqueId); } // recordStats(key); var unitPeriod = gran[0]; multi.hincrby(key, 'uni', 0); multi.expire(key, points * unitPeriod / 1000); }); multi.exec(callback || log); }
[ "function", "recordUnique", "(", "name", ",", "uniqueId", ",", "statistics", ",", "aggregations", ",", "timestamp", ",", "callback", ")", "{", "timestamp", "=", "timestamp", "||", "Date", ".", "now", "(", ")", ";", "// normal record", "if", "(", "statistics", ")", "{", "var", "num", "=", "Array", ".", "isArray", "(", "uniqueId", ")", "?", "uniqueId", ".", "length", ":", "1", ";", "record", "(", "name", ",", "num", ",", "statistics", ",", "aggregations", ",", "timestamp", ")", ";", "}", "// record unique", "var", "multi", "=", "redis", ".", "multi", "(", ")", ";", "granularities", ".", "forEach", "(", "function", "(", "gran", ")", "{", "var", "key", "=", "getGranKey", "(", "name", ",", "gran", ",", "timestamp", ")", ";", "var", "expireTime", "=", "util", ".", "getExpireTime", "(", "gran", ",", "timestamp", ")", ";", "var", "pfkey", "=", "key", "+", "':pf'", ";", "multi", ".", "hset", "(", "keyPFKeys", ",", "pfkey", ",", "expireTime", ")", ";", "if", "(", "Array", ".", "isArray", "(", "uniqueId", ")", ")", "{", "multi", ".", "pfadd", ".", "apply", "(", "multi", ",", "[", "pfkey", "]", ".", "concat", "(", "uniqueId", ")", ")", ";", "}", "else", "{", "multi", ".", "pfadd", "(", "pfkey", ",", "uniqueId", ")", ";", "}", "// recordStats(key);", "var", "unitPeriod", "=", "gran", "[", "0", "]", ";", "multi", ".", "hincrby", "(", "key", ",", "'uni'", ",", "0", ")", ";", "multi", ".", "expire", "(", "key", ",", "points", "*", "unitPeriod", "/", "1000", ")", ";", "}", ")", ";", "multi", ".", "exec", "(", "callback", "||", "log", ")", ";", "}" ]
record unique access, like unique user of a period time. @param {string | Array} uniqueId one or some uniqueId to be stats
[ "record", "unique", "access", "like", "unique", "user", "of", "a", "period", "time", "." ]
22b88c9b81a26e0b7a6e65bf815318fa60f21e55
https://github.com/guileen/node-rts/blob/22b88c9b81a26e0b7a6e65bf815318fa60f21e55/lib/rts.js#L158-L183
46,355
guileen/node-rts
lib/rts.js
getStat
function getStat(type, name, granCode, fromDate, toDate, callback) { if(!granCode) throw new Error('granCode is required'); if(!callback && typeof toDate == 'function') { callback = toDate; toDate = Date.now(); } var gran = granMap[granCode] || util.getUnitDesc(granCode); if(!gran) throw new Error('Granualrity is not defined ' + granCode); if(fromDate instanceof Date) fromDate = fromDate.getTime(); if(toDate instanceof Date) toDate = toDate.getTime(); toDate = toDate || Date.now() fromDate = fromDate || (toDate - util.getTimePeriod(gran, points)); var unitPeriod = gran[0]; var multi = redis.multi(); var _points = []; for(var d = fromDate; d <= toDate; d += unitPeriod) { var key = getGranKey(name, gran, d); _points.push(util.getKeyTime(gran, d)); multi.hget(key, type); } multi.exec(function(err, results) { if(err) return callback(err); var merged = []; for (var i = 0, l = _points.length, p; i < l; i ++) { p = _points[i]; merged[i] = [p, Number(results[i])]; } callback(null, { step: unitPeriod , unitType: gran[3] , data: merged }); }); }
javascript
function getStat(type, name, granCode, fromDate, toDate, callback) { if(!granCode) throw new Error('granCode is required'); if(!callback && typeof toDate == 'function') { callback = toDate; toDate = Date.now(); } var gran = granMap[granCode] || util.getUnitDesc(granCode); if(!gran) throw new Error('Granualrity is not defined ' + granCode); if(fromDate instanceof Date) fromDate = fromDate.getTime(); if(toDate instanceof Date) toDate = toDate.getTime(); toDate = toDate || Date.now() fromDate = fromDate || (toDate - util.getTimePeriod(gran, points)); var unitPeriod = gran[0]; var multi = redis.multi(); var _points = []; for(var d = fromDate; d <= toDate; d += unitPeriod) { var key = getGranKey(name, gran, d); _points.push(util.getKeyTime(gran, d)); multi.hget(key, type); } multi.exec(function(err, results) { if(err) return callback(err); var merged = []; for (var i = 0, l = _points.length, p; i < l; i ++) { p = _points[i]; merged[i] = [p, Number(results[i])]; } callback(null, { step: unitPeriod , unitType: gran[3] , data: merged }); }); }
[ "function", "getStat", "(", "type", ",", "name", ",", "granCode", ",", "fromDate", ",", "toDate", ",", "callback", ")", "{", "if", "(", "!", "granCode", ")", "throw", "new", "Error", "(", "'granCode is required'", ")", ";", "if", "(", "!", "callback", "&&", "typeof", "toDate", "==", "'function'", ")", "{", "callback", "=", "toDate", ";", "toDate", "=", "Date", ".", "now", "(", ")", ";", "}", "var", "gran", "=", "granMap", "[", "granCode", "]", "||", "util", ".", "getUnitDesc", "(", "granCode", ")", ";", "if", "(", "!", "gran", ")", "throw", "new", "Error", "(", "'Granualrity is not defined '", "+", "granCode", ")", ";", "if", "(", "fromDate", "instanceof", "Date", ")", "fromDate", "=", "fromDate", ".", "getTime", "(", ")", ";", "if", "(", "toDate", "instanceof", "Date", ")", "toDate", "=", "toDate", ".", "getTime", "(", ")", ";", "toDate", "=", "toDate", "||", "Date", ".", "now", "(", ")", "fromDate", "=", "fromDate", "||", "(", "toDate", "-", "util", ".", "getTimePeriod", "(", "gran", ",", "points", ")", ")", ";", "var", "unitPeriod", "=", "gran", "[", "0", "]", ";", "var", "multi", "=", "redis", ".", "multi", "(", ")", ";", "var", "_points", "=", "[", "]", ";", "for", "(", "var", "d", "=", "fromDate", ";", "d", "<=", "toDate", ";", "d", "+=", "unitPeriod", ")", "{", "var", "key", "=", "getGranKey", "(", "name", ",", "gran", ",", "d", ")", ";", "_points", ".", "push", "(", "util", ".", "getKeyTime", "(", "gran", ",", "d", ")", ")", ";", "multi", ".", "hget", "(", "key", ",", "type", ")", ";", "}", "multi", ".", "exec", "(", "function", "(", "err", ",", "results", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "var", "merged", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "_points", ".", "length", ",", "p", ";", "i", "<", "l", ";", "i", "++", ")", "{", "p", "=", "_points", "[", "i", "]", ";", "merged", "[", "i", "]", "=", "[", "p", ",", "Number", "(", "results", "[", "i", "]", ")", "]", ";", "}", "callback", "(", "null", ",", "{", "step", ":", "unitPeriod", ",", "unitType", ":", "gran", "[", "3", "]", ",", "data", ":", "merged", "}", ")", ";", "}", ")", ";", "}" ]
get results of the stats @param {String} type sum, min, max, avg, count, uni
[ "get", "results", "of", "the", "stats" ]
22b88c9b81a26e0b7a6e65bf815318fa60f21e55
https://github.com/guileen/node-rts/blob/22b88c9b81a26e0b7a6e65bf815318fa60f21e55/lib/rts.js#L190-L225
46,356
AXErunners/axecore-p2p
lib/messages/commands/reject.js
RejectMessage
function RejectMessage(arg, options) { if (!arg) { arg = {}; } Message.call(this, options); this.command = 'reject'; this.message = arg.message; this.ccode = arg.ccode; this.reason = arg.reason; this.data = arg.data; }
javascript
function RejectMessage(arg, options) { if (!arg) { arg = {}; } Message.call(this, options); this.command = 'reject'; this.message = arg.message; this.ccode = arg.ccode; this.reason = arg.reason; this.data = arg.data; }
[ "function", "RejectMessage", "(", "arg", ",", "options", ")", "{", "if", "(", "!", "arg", ")", "{", "arg", "=", "{", "}", ";", "}", "Message", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "command", "=", "'reject'", ";", "this", ".", "message", "=", "arg", ".", "message", ";", "this", ".", "ccode", "=", "arg", ".", "ccode", ";", "this", ".", "reason", "=", "arg", ".", "reason", ";", "this", ".", "data", "=", "arg", ".", "data", ";", "}" ]
The reject message is sent when messages are rejected. @see https://en.bitcoin.it/wiki/Protocol_documentation#reject @param {Object=} arg - properties for the reject message @param {String=} arg.message - type of message rejected @param {Number=} arg.ccode - code relating to rejected message @param {String=} arg.reason - text version of reason for rejection @param {Buffer=} arg.data - Optional extra data provided by some errors. @param {Object} options @extends Message @constructor
[ "The", "reject", "message", "is", "sent", "when", "messages", "are", "rejected", "." ]
c06d0e1d7b9ed44b7ee3061feb394d3896240da9
https://github.com/AXErunners/axecore-p2p/blob/c06d0e1d7b9ed44b7ee3061feb394d3896240da9/lib/messages/commands/reject.js#L23-L33
46,357
kesuiket/path.js
path.js
join
function join() { var path = ''; var args = slice.call(arguments, 0); if (arguments.length <= 1) args.unshift(cwd()); for (var i = 0; i < args.length; i += 1) { var segment = args[i]; if (!isString(segment)) { throw new TypeError ('Arguemnts to path.join must be strings'); } if (segment) { if (!path) { path += segment; } else { path += '/' + segment; } } } return normalize(path); }
javascript
function join() { var path = ''; var args = slice.call(arguments, 0); if (arguments.length <= 1) args.unshift(cwd()); for (var i = 0; i < args.length; i += 1) { var segment = args[i]; if (!isString(segment)) { throw new TypeError ('Arguemnts to path.join must be strings'); } if (segment) { if (!path) { path += segment; } else { path += '/' + segment; } } } return normalize(path); }
[ "function", "join", "(", ")", "{", "var", "path", "=", "''", ";", "var", "args", "=", "slice", ".", "call", "(", "arguments", ",", "0", ")", ";", "if", "(", "arguments", ".", "length", "<=", "1", ")", "args", ".", "unshift", "(", "cwd", "(", ")", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "args", ".", "length", ";", "i", "+=", "1", ")", "{", "var", "segment", "=", "args", "[", "i", "]", ";", "if", "(", "!", "isString", "(", "segment", ")", ")", "{", "throw", "new", "TypeError", "(", "'Arguemnts to path.join must be strings'", ")", ";", "}", "if", "(", "segment", ")", "{", "if", "(", "!", "path", ")", "{", "path", "+=", "segment", ";", "}", "else", "{", "path", "+=", "'/'", "+", "segment", ";", "}", "}", "}", "return", "normalize", "(", "path", ")", ";", "}" ]
join the pathes @param {String} [path1, path2, path3...] @return {String} joined path
[ "join", "the", "pathes" ]
6f885627aadd589c2784288726f2a4a812d07822
https://github.com/kesuiket/path.js/blob/6f885627aadd589c2784288726f2a4a812d07822/path.js#L152-L172
46,358
NatLibFi/marc-record-merge-js
lib/main.js
makeSubfieldPairs
function makeSubfieldPairs(subfields1, subfields2, fn_comparator) { var pairs = []; if (subfields1.length === subfields2.length) { subfields2.forEach(function(subfield2) { return subfields1.some(function(subfield1) { if (fn_comparator(subfield1, subfield2)) { pairs.push([subfield1, subfield2]); return true; } }); }); } else { throw new Error('Number of subfields are not equal'); } return pairs; }
javascript
function makeSubfieldPairs(subfields1, subfields2, fn_comparator) { var pairs = []; if (subfields1.length === subfields2.length) { subfields2.forEach(function(subfield2) { return subfields1.some(function(subfield1) { if (fn_comparator(subfield1, subfield2)) { pairs.push([subfield1, subfield2]); return true; } }); }); } else { throw new Error('Number of subfields are not equal'); } return pairs; }
[ "function", "makeSubfieldPairs", "(", "subfields1", ",", "subfields2", ",", "fn_comparator", ")", "{", "var", "pairs", "=", "[", "]", ";", "if", "(", "subfields1", ".", "length", "===", "subfields2", ".", "length", ")", "{", "subfields2", ".", "forEach", "(", "function", "(", "subfield2", ")", "{", "return", "subfields1", ".", "some", "(", "function", "(", "subfield1", ")", "{", "if", "(", "fn_comparator", "(", "subfield1", ",", "subfield2", ")", ")", "{", "pairs", ".", "push", "(", "[", "subfield1", ",", "subfield2", "]", ")", ";", "return", "true", ";", "}", "}", ")", ";", "}", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Number of subfields are not equal'", ")", ";", "}", "return", "pairs", ";", "}" ]
Try to make a list of equal pairs from both subfield arrays using a comparator function
[ "Try", "to", "make", "a", "list", "of", "equal", "pairs", "from", "both", "subfield", "arrays", "using", "a", "comparator", "function" ]
e15d84deeb8a5cdc299d248bac135dc2a79f3fe3
https://github.com/NatLibFi/marc-record-merge-js/blob/e15d84deeb8a5cdc299d248bac135dc2a79f3fe3/lib/main.js#L288-L311
46,359
alphagov/openregister-picker-engine
src/index.js
addWeight
function addWeight (canonicalNodeWithPath, query) { const cnwp = canonicalNodeWithPath const name = presentableName(cnwp.node, preferredLocale) const synonym = cnwp.path .map(pathNode => presentableName(pathNode.node, pathNode.locale)) .map(nameInPath => nameInPath.toLowerCase()) .pop() const indexOfQuery = indexOfLowerCase(name, query) const isUk = name === 'United Kingdom' const isUs = name === 'United States' // Temporary country weighting const ukBias = 2 const usBias = 1.5 const defaultCountryBias = 1 const isExactMatchToCanonicalName = name.toLowerCase() === query.toLowerCase() const canonicalNameStartsWithQuery = indexOfQuery === 0 const wordInCanonicalNameStartsWithQuery = name .split(' ') .filter(w => w.toLowerCase().indexOf(query.toLowerCase()) === 0) .length > 0 // TODO: make these const var synonymIsExactMatch = false var synonymStartsWithQuery = false var wordInSynonymStartsWith = false var indexOfSynonymQuery = false var synonymContainsQuery = false if (synonym) { synonymIsExactMatch = synonym === query.toLowerCase() synonymStartsWithQuery = synonym .indexOf(query.toLowerCase()) === 0 wordInSynonymStartsWith = synonym .split(' ') .filter(w => w.toLowerCase().indexOf(query.toLowerCase()) === 0) .length > 0 indexOfSynonymQuery = indexOfLowerCase(synonym, query) } // TODO: Contains consts don't work const canonicalNameContainsQuery = indexOfQuery > 0 synonymContainsQuery = indexOfSynonymQuery > 0 // Canonical name matches if (isExactMatchToCanonicalName) { cnwp.weight = 100 } else if (canonicalNameStartsWithQuery) { cnwp.weight = 76 } else if (wordInCanonicalNameStartsWithQuery) { cnwp.weight = 60 } else if (synonymIsExactMatch) { // Synonmn matches cnwp.weight = 50 } else if (synonymStartsWithQuery) { cnwp.weight = 45 } else if (wordInSynonymStartsWith) { cnwp.weight = 37 } else if (canonicalNameContainsQuery) { // Contains (DOES NOT WORK YET) cnwp.weight = 25 } else if (synonymContainsQuery) { cnwp.weight = 22 } else { // Not sure if else is possible cnwp.weight = 15 } // Longer paths mean canonical node is further from matched synonym, so rank it lower. // TODO - pruning multiple matches should happen elsewhere cnwp.weight -= cnwp.path.length var countryBias = isUk ? ukBias : defaultCountryBias countryBias = isUs ? usBias : countryBias cnwp.weight *= countryBias return cnwp }
javascript
function addWeight (canonicalNodeWithPath, query) { const cnwp = canonicalNodeWithPath const name = presentableName(cnwp.node, preferredLocale) const synonym = cnwp.path .map(pathNode => presentableName(pathNode.node, pathNode.locale)) .map(nameInPath => nameInPath.toLowerCase()) .pop() const indexOfQuery = indexOfLowerCase(name, query) const isUk = name === 'United Kingdom' const isUs = name === 'United States' // Temporary country weighting const ukBias = 2 const usBias = 1.5 const defaultCountryBias = 1 const isExactMatchToCanonicalName = name.toLowerCase() === query.toLowerCase() const canonicalNameStartsWithQuery = indexOfQuery === 0 const wordInCanonicalNameStartsWithQuery = name .split(' ') .filter(w => w.toLowerCase().indexOf(query.toLowerCase()) === 0) .length > 0 // TODO: make these const var synonymIsExactMatch = false var synonymStartsWithQuery = false var wordInSynonymStartsWith = false var indexOfSynonymQuery = false var synonymContainsQuery = false if (synonym) { synonymIsExactMatch = synonym === query.toLowerCase() synonymStartsWithQuery = synonym .indexOf(query.toLowerCase()) === 0 wordInSynonymStartsWith = synonym .split(' ') .filter(w => w.toLowerCase().indexOf(query.toLowerCase()) === 0) .length > 0 indexOfSynonymQuery = indexOfLowerCase(synonym, query) } // TODO: Contains consts don't work const canonicalNameContainsQuery = indexOfQuery > 0 synonymContainsQuery = indexOfSynonymQuery > 0 // Canonical name matches if (isExactMatchToCanonicalName) { cnwp.weight = 100 } else if (canonicalNameStartsWithQuery) { cnwp.weight = 76 } else if (wordInCanonicalNameStartsWithQuery) { cnwp.weight = 60 } else if (synonymIsExactMatch) { // Synonmn matches cnwp.weight = 50 } else if (synonymStartsWithQuery) { cnwp.weight = 45 } else if (wordInSynonymStartsWith) { cnwp.weight = 37 } else if (canonicalNameContainsQuery) { // Contains (DOES NOT WORK YET) cnwp.weight = 25 } else if (synonymContainsQuery) { cnwp.weight = 22 } else { // Not sure if else is possible cnwp.weight = 15 } // Longer paths mean canonical node is further from matched synonym, so rank it lower. // TODO - pruning multiple matches should happen elsewhere cnwp.weight -= cnwp.path.length var countryBias = isUk ? ukBias : defaultCountryBias countryBias = isUs ? usBias : countryBias cnwp.weight *= countryBias return cnwp }
[ "function", "addWeight", "(", "canonicalNodeWithPath", ",", "query", ")", "{", "const", "cnwp", "=", "canonicalNodeWithPath", "const", "name", "=", "presentableName", "(", "cnwp", ".", "node", ",", "preferredLocale", ")", "const", "synonym", "=", "cnwp", ".", "path", ".", "map", "(", "pathNode", "=>", "presentableName", "(", "pathNode", ".", "node", ",", "pathNode", ".", "locale", ")", ")", ".", "map", "(", "nameInPath", "=>", "nameInPath", ".", "toLowerCase", "(", ")", ")", ".", "pop", "(", ")", "const", "indexOfQuery", "=", "indexOfLowerCase", "(", "name", ",", "query", ")", "const", "isUk", "=", "name", "===", "'United Kingdom'", "const", "isUs", "=", "name", "===", "'United States'", "// Temporary country weighting", "const", "ukBias", "=", "2", "const", "usBias", "=", "1.5", "const", "defaultCountryBias", "=", "1", "const", "isExactMatchToCanonicalName", "=", "name", ".", "toLowerCase", "(", ")", "===", "query", ".", "toLowerCase", "(", ")", "const", "canonicalNameStartsWithQuery", "=", "indexOfQuery", "===", "0", "const", "wordInCanonicalNameStartsWithQuery", "=", "name", ".", "split", "(", "' '", ")", ".", "filter", "(", "w", "=>", "w", ".", "toLowerCase", "(", ")", ".", "indexOf", "(", "query", ".", "toLowerCase", "(", ")", ")", "===", "0", ")", ".", "length", ">", "0", "// TODO: make these const", "var", "synonymIsExactMatch", "=", "false", "var", "synonymStartsWithQuery", "=", "false", "var", "wordInSynonymStartsWith", "=", "false", "var", "indexOfSynonymQuery", "=", "false", "var", "synonymContainsQuery", "=", "false", "if", "(", "synonym", ")", "{", "synonymIsExactMatch", "=", "synonym", "===", "query", ".", "toLowerCase", "(", ")", "synonymStartsWithQuery", "=", "synonym", ".", "indexOf", "(", "query", ".", "toLowerCase", "(", ")", ")", "===", "0", "wordInSynonymStartsWith", "=", "synonym", ".", "split", "(", "' '", ")", ".", "filter", "(", "w", "=>", "w", ".", "toLowerCase", "(", ")", ".", "indexOf", "(", "query", ".", "toLowerCase", "(", ")", ")", "===", "0", ")", ".", "length", ">", "0", "indexOfSynonymQuery", "=", "indexOfLowerCase", "(", "synonym", ",", "query", ")", "}", "// TODO: Contains consts don't work", "const", "canonicalNameContainsQuery", "=", "indexOfQuery", ">", "0", "synonymContainsQuery", "=", "indexOfSynonymQuery", ">", "0", "// Canonical name matches", "if", "(", "isExactMatchToCanonicalName", ")", "{", "cnwp", ".", "weight", "=", "100", "}", "else", "if", "(", "canonicalNameStartsWithQuery", ")", "{", "cnwp", ".", "weight", "=", "76", "}", "else", "if", "(", "wordInCanonicalNameStartsWithQuery", ")", "{", "cnwp", ".", "weight", "=", "60", "}", "else", "if", "(", "synonymIsExactMatch", ")", "{", "// Synonmn matches", "cnwp", ".", "weight", "=", "50", "}", "else", "if", "(", "synonymStartsWithQuery", ")", "{", "cnwp", ".", "weight", "=", "45", "}", "else", "if", "(", "wordInSynonymStartsWith", ")", "{", "cnwp", ".", "weight", "=", "37", "}", "else", "if", "(", "canonicalNameContainsQuery", ")", "{", "// Contains (DOES NOT WORK YET)", "cnwp", ".", "weight", "=", "25", "}", "else", "if", "(", "synonymContainsQuery", ")", "{", "cnwp", ".", "weight", "=", "22", "}", "else", "{", "// Not sure if else is possible", "cnwp", ".", "weight", "=", "15", "}", "// Longer paths mean canonical node is further from matched synonym, so rank it lower.", "// TODO - pruning multiple matches should happen elsewhere", "cnwp", ".", "weight", "-=", "cnwp", ".", "path", ".", "length", "var", "countryBias", "=", "isUk", "?", "ukBias", ":", "defaultCountryBias", "countryBias", "=", "isUs", "?", "usBias", ":", "countryBias", "cnwp", ".", "weight", "*=", "countryBias", "return", "cnwp", "}" ]
Takes a canonical node with the path to reach it, and the typed in query. Returns the same node and path, with added weight based on a number of criteria. Higher weight means higher priority, so it should be ranked higher in the list.
[ "Takes", "a", "canonical", "node", "with", "the", "path", "to", "reach", "it", "and", "the", "typed", "in", "query", ".", "Returns", "the", "same", "node", "and", "path", "with", "added", "weight", "based", "on", "a", "number", "of", "criteria", ".", "Higher", "weight", "means", "higher", "priority", "so", "it", "should", "be", "ranked", "higher", "in", "the", "list", "." ]
fed0cc61aab3e8c174fe65ea84ca12674e5cd520
https://github.com/alphagov/openregister-picker-engine/blob/fed0cc61aab3e8c174fe65ea84ca12674e5cd520/src/index.js#L72-L157
46,360
alphagov/openregister-picker-engine
src/index.js
presentResults
function presentResults (graph, reverseMap, rawResults, query) { var nodesWithLocales = rawResults.map(r => reverseMap[r]) var canonicalNodesWithPaths = nodesWithLocales.reduce((canonicalNodes, nwl) => { return canonicalNodes.concat(findCanonicalNodeWithPath(graph, nwl.node, nwl.locale, [])) }, []) const canonicalNodesWithPathsAndWeights = canonicalNodesWithPaths.map(cnwp => addWeight(cnwp, query)) canonicalNodesWithPathsAndWeights.sort(byWeightAndThenAlphabetically) const uniqueNodesWithPathsAndWeights = uniqBy(canonicalNodesWithPathsAndWeights, (cnwp) => { return presentableName(cnwp.node, preferredLocale) }) uniqueNodesWithPathsAndWeights.sort(byWeightAndThenAlphabetically) var presentableNodes = uniqueNodesWithPathsAndWeights.map(cnwp => { var canonicalName = presentableName(cnwp.node, preferredLocale) var pathToName = '' if (showPaths && cnwp.path.length) { var stableNamesInPath = cnwp.path .filter(pathNode => pathNode.node.meta['stable-name']) .map(pathNode => presentableName(pathNode.node, pathNode.locale)) var lastNode = stableNamesInPath.pop() if (lastNode) { pathToName = lastNode } } return { name: canonicalName, path: pathToName } }) return presentableNodes }
javascript
function presentResults (graph, reverseMap, rawResults, query) { var nodesWithLocales = rawResults.map(r => reverseMap[r]) var canonicalNodesWithPaths = nodesWithLocales.reduce((canonicalNodes, nwl) => { return canonicalNodes.concat(findCanonicalNodeWithPath(graph, nwl.node, nwl.locale, [])) }, []) const canonicalNodesWithPathsAndWeights = canonicalNodesWithPaths.map(cnwp => addWeight(cnwp, query)) canonicalNodesWithPathsAndWeights.sort(byWeightAndThenAlphabetically) const uniqueNodesWithPathsAndWeights = uniqBy(canonicalNodesWithPathsAndWeights, (cnwp) => { return presentableName(cnwp.node, preferredLocale) }) uniqueNodesWithPathsAndWeights.sort(byWeightAndThenAlphabetically) var presentableNodes = uniqueNodesWithPathsAndWeights.map(cnwp => { var canonicalName = presentableName(cnwp.node, preferredLocale) var pathToName = '' if (showPaths && cnwp.path.length) { var stableNamesInPath = cnwp.path .filter(pathNode => pathNode.node.meta['stable-name']) .map(pathNode => presentableName(pathNode.node, pathNode.locale)) var lastNode = stableNamesInPath.pop() if (lastNode) { pathToName = lastNode } } return { name: canonicalName, path: pathToName } }) return presentableNodes }
[ "function", "presentResults", "(", "graph", ",", "reverseMap", ",", "rawResults", ",", "query", ")", "{", "var", "nodesWithLocales", "=", "rawResults", ".", "map", "(", "r", "=>", "reverseMap", "[", "r", "]", ")", "var", "canonicalNodesWithPaths", "=", "nodesWithLocales", ".", "reduce", "(", "(", "canonicalNodes", ",", "nwl", ")", "=>", "{", "return", "canonicalNodes", ".", "concat", "(", "findCanonicalNodeWithPath", "(", "graph", ",", "nwl", ".", "node", ",", "nwl", ".", "locale", ",", "[", "]", ")", ")", "}", ",", "[", "]", ")", "const", "canonicalNodesWithPathsAndWeights", "=", "canonicalNodesWithPaths", ".", "map", "(", "cnwp", "=>", "addWeight", "(", "cnwp", ",", "query", ")", ")", "canonicalNodesWithPathsAndWeights", ".", "sort", "(", "byWeightAndThenAlphabetically", ")", "const", "uniqueNodesWithPathsAndWeights", "=", "uniqBy", "(", "canonicalNodesWithPathsAndWeights", ",", "(", "cnwp", ")", "=>", "{", "return", "presentableName", "(", "cnwp", ".", "node", ",", "preferredLocale", ")", "}", ")", "uniqueNodesWithPathsAndWeights", ".", "sort", "(", "byWeightAndThenAlphabetically", ")", "var", "presentableNodes", "=", "uniqueNodesWithPathsAndWeights", ".", "map", "(", "cnwp", "=>", "{", "var", "canonicalName", "=", "presentableName", "(", "cnwp", ".", "node", ",", "preferredLocale", ")", "var", "pathToName", "=", "''", "if", "(", "showPaths", "&&", "cnwp", ".", "path", ".", "length", ")", "{", "var", "stableNamesInPath", "=", "cnwp", ".", "path", ".", "filter", "(", "pathNode", "=>", "pathNode", ".", "node", ".", "meta", "[", "'stable-name'", "]", ")", ".", "map", "(", "pathNode", "=>", "presentableName", "(", "pathNode", ".", "node", ",", "pathNode", ".", "locale", ")", ")", "var", "lastNode", "=", "stableNamesInPath", ".", "pop", "(", ")", "if", "(", "lastNode", ")", "{", "pathToName", "=", "lastNode", "}", "}", "return", "{", "name", ":", "canonicalName", ",", "path", ":", "pathToName", "}", "}", ")", "return", "presentableNodes", "}" ]
Engine gives us back a list of results that includes synonyms, typos, endonyms and other things we don't want the user to see. This function transforms those into a list of stable canonical country names.
[ "Engine", "gives", "us", "back", "a", "list", "of", "results", "that", "includes", "synonyms", "typos", "endonyms", "and", "other", "things", "we", "don", "t", "want", "the", "user", "to", "see", ".", "This", "function", "transforms", "those", "into", "a", "list", "of", "stable", "canonical", "country", "names", "." ]
fed0cc61aab3e8c174fe65ea84ca12674e5cd520
https://github.com/alphagov/openregister-picker-engine/blob/fed0cc61aab3e8c174fe65ea84ca12674e5cd520/src/index.js#L177-L213
46,361
mhart/dynamo-table
index.js
checkTable
function checkTable(count) { // Make sure we don't go into an infinite loop if (++count > 1000) return cb(new Error('Wait limit exceeded')) self.describeTable(function(err, data) { if (err) return cb(err) if (data.TableStatus !== 'ACTIVE' || (data.GlobalSecondaryIndexes && !data.GlobalSecondaryIndexes.every(function (idx) {return idx.IndexStatus === 'ACTIVE'}))) { return setTimeout(checkTable, 1000, count) } // If the table is ACTIVE then return cb(null, data) }) }
javascript
function checkTable(count) { // Make sure we don't go into an infinite loop if (++count > 1000) return cb(new Error('Wait limit exceeded')) self.describeTable(function(err, data) { if (err) return cb(err) if (data.TableStatus !== 'ACTIVE' || (data.GlobalSecondaryIndexes && !data.GlobalSecondaryIndexes.every(function (idx) {return idx.IndexStatus === 'ACTIVE'}))) { return setTimeout(checkTable, 1000, count) } // If the table is ACTIVE then return cb(null, data) }) }
[ "function", "checkTable", "(", "count", ")", "{", "// Make sure we don't go into an infinite loop", "if", "(", "++", "count", ">", "1000", ")", "return", "cb", "(", "new", "Error", "(", "'Wait limit exceeded'", ")", ")", "self", ".", "describeTable", "(", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", "if", "(", "data", ".", "TableStatus", "!==", "'ACTIVE'", "||", "(", "data", ".", "GlobalSecondaryIndexes", "&&", "!", "data", ".", "GlobalSecondaryIndexes", ".", "every", "(", "function", "(", "idx", ")", "{", "return", "idx", ".", "IndexStatus", "===", "'ACTIVE'", "}", ")", ")", ")", "{", "return", "setTimeout", "(", "checkTable", ",", "1000", ",", "count", ")", "}", "// If the table is ACTIVE then return", "cb", "(", "null", ",", "data", ")", "}", ")", "}" ]
check whether the update has in fact been applied
[ "check", "whether", "the", "update", "has", "in", "fact", "been", "applied" ]
b5c3ef80db8d90fa92c233ae9811e6751469cfc6
https://github.com/mhart/dynamo-table/blob/b5c3ef80db8d90fa92c233ae9811e6751469cfc6/index.js#L673-L687
46,362
nfroidure/streamfilter
src/index.js
createReadStreamBackpressureManager
function createReadStreamBackpressureManager(readableStream) { const manager = { waitPush: true, programmedPushs: [], programPush: function programPush(chunk, encoding, done) { // Store the current write manager.programmedPushs.push([chunk, encoding, done]); // Need to be async to avoid nested push attempts // Programm a push attempt setImmediate(manager.attemptPush); // Let's say we're ready for a read readableStream.emit('readable'); readableStream.emit('drain'); }, attemptPush: function attemptPush() { let nextPush; if (manager.waitPush) { if (manager.programmedPushs.length) { nextPush = manager.programmedPushs.shift(); manager.waitPush = readableStream.push(nextPush[0], nextPush[1]); nextPush[2](); } } else { setImmediate(() => { // Need to be async to avoid nested push attempts readableStream.emit('readable'); }); } }, }; // Patch the readable stream to manage reads readableStream._read = function streamFilterRestoreRead() { manager.waitPush = true; // Need to be async to avoid nested push attempts setImmediate(manager.attemptPush); }; return manager; }
javascript
function createReadStreamBackpressureManager(readableStream) { const manager = { waitPush: true, programmedPushs: [], programPush: function programPush(chunk, encoding, done) { // Store the current write manager.programmedPushs.push([chunk, encoding, done]); // Need to be async to avoid nested push attempts // Programm a push attempt setImmediate(manager.attemptPush); // Let's say we're ready for a read readableStream.emit('readable'); readableStream.emit('drain'); }, attemptPush: function attemptPush() { let nextPush; if (manager.waitPush) { if (manager.programmedPushs.length) { nextPush = manager.programmedPushs.shift(); manager.waitPush = readableStream.push(nextPush[0], nextPush[1]); nextPush[2](); } } else { setImmediate(() => { // Need to be async to avoid nested push attempts readableStream.emit('readable'); }); } }, }; // Patch the readable stream to manage reads readableStream._read = function streamFilterRestoreRead() { manager.waitPush = true; // Need to be async to avoid nested push attempts setImmediate(manager.attemptPush); }; return manager; }
[ "function", "createReadStreamBackpressureManager", "(", "readableStream", ")", "{", "const", "manager", "=", "{", "waitPush", ":", "true", ",", "programmedPushs", ":", "[", "]", ",", "programPush", ":", "function", "programPush", "(", "chunk", ",", "encoding", ",", "done", ")", "{", "// Store the current write", "manager", ".", "programmedPushs", ".", "push", "(", "[", "chunk", ",", "encoding", ",", "done", "]", ")", ";", "// Need to be async to avoid nested push attempts", "// Programm a push attempt", "setImmediate", "(", "manager", ".", "attemptPush", ")", ";", "// Let's say we're ready for a read", "readableStream", ".", "emit", "(", "'readable'", ")", ";", "readableStream", ".", "emit", "(", "'drain'", ")", ";", "}", ",", "attemptPush", ":", "function", "attemptPush", "(", ")", "{", "let", "nextPush", ";", "if", "(", "manager", ".", "waitPush", ")", "{", "if", "(", "manager", ".", "programmedPushs", ".", "length", ")", "{", "nextPush", "=", "manager", ".", "programmedPushs", ".", "shift", "(", ")", ";", "manager", ".", "waitPush", "=", "readableStream", ".", "push", "(", "nextPush", "[", "0", "]", ",", "nextPush", "[", "1", "]", ")", ";", "nextPush", "[", "2", "]", "(", ")", ";", "}", "}", "else", "{", "setImmediate", "(", "(", ")", "=>", "{", "// Need to be async to avoid nested push attempts", "readableStream", ".", "emit", "(", "'readable'", ")", ";", "}", ")", ";", "}", "}", ",", "}", ";", "// Patch the readable stream to manage reads", "readableStream", ".", "_read", "=", "function", "streamFilterRestoreRead", "(", ")", "{", "manager", ".", "waitPush", "=", "true", ";", "// Need to be async to avoid nested push attempts", "setImmediate", "(", "manager", ".", "attemptPush", ")", ";", "}", ";", "return", "manager", ";", "}" ]
Utils to manage readable stream backpressure
[ "Utils", "to", "manage", "readable", "stream", "backpressure" ]
373da8fa746a054f501ab34bb9feba74da226a84
https://github.com/nfroidure/streamfilter/blob/373da8fa746a054f501ab34bb9feba74da226a84/src/index.js#L112-L152
46,363
damirkusar/generator-leptir-angular-material
generators/app/templates/public/modules/core/js/services/menus.service.js
function (menuId, menuItemId, menuItemTitle, menuItemUiState, menuItemType, position) { this.validateMenuExistance(menuId); // Push new menu item menus[menuId].items.push({ id: menuItemId, title: menuItemTitle, uiState: menuItemUiState, class: menuItemType, position: position || 0, items: [] }); // Return the menu object return menus[menuId]; }
javascript
function (menuId, menuItemId, menuItemTitle, menuItemUiState, menuItemType, position) { this.validateMenuExistance(menuId); // Push new menu item menus[menuId].items.push({ id: menuItemId, title: menuItemTitle, uiState: menuItemUiState, class: menuItemType, position: position || 0, items: [] }); // Return the menu object return menus[menuId]; }
[ "function", "(", "menuId", ",", "menuItemId", ",", "menuItemTitle", ",", "menuItemUiState", ",", "menuItemType", ",", "position", ")", "{", "this", ".", "validateMenuExistance", "(", "menuId", ")", ";", "// Push new menu item", "menus", "[", "menuId", "]", ".", "items", ".", "push", "(", "{", "id", ":", "menuItemId", ",", "title", ":", "menuItemTitle", ",", "uiState", ":", "menuItemUiState", ",", "class", ":", "menuItemType", ",", "position", ":", "position", "||", "0", ",", "items", ":", "[", "]", "}", ")", ";", "// Return the menu object", "return", "menus", "[", "menuId", "]", ";", "}" ]
Add menu item object
[ "Add", "menu", "item", "object" ]
ef5e0a2c8bbad386687e7a609d17587e075fc43b
https://github.com/damirkusar/generator-leptir-angular-material/blob/ef5e0a2c8bbad386687e7a609d17587e075fc43b/generators/app/templates/public/modules/core/js/services/menus.service.js#L43-L58
46,364
NiklasGollenstede/web-ext-utils
utils/notify.js
notify
async function notify({ title, message, icon = 'default', timeout, }) { try { if (!Notifications) { console.info('notify', arguments[0]); return false; } const create = !open; open = true; const options = { type: 'basic', title, message, iconUrl: (/^\w+$/).test(icon) ? (await getIcon(icon)) : icon, }; !isGecko && (options.requireInteraction = true); try { (await Notifications[create || isGecko ? 'create' : 'update']( 'web-ext-utils:notice', options, )); } catch (_) { open = false; throw _; } clearNotice(timeout == null ? -1 : typeof timeout === 'number' && timeout > 1e3 && timeout < 30 ** 2 ? timeout : 5000); onhide && onhide(); onclick = onhide = null; return new Promise(done => { onclick = () => done(true); onhide = () => done(false); }); } catch (_) { try { console.error(`failed to show notification`, arguments[0], _); } catch (_) { } } return false; }
javascript
async function notify({ title, message, icon = 'default', timeout, }) { try { if (!Notifications) { console.info('notify', arguments[0]); return false; } const create = !open; open = true; const options = { type: 'basic', title, message, iconUrl: (/^\w+$/).test(icon) ? (await getIcon(icon)) : icon, }; !isGecko && (options.requireInteraction = true); try { (await Notifications[create || isGecko ? 'create' : 'update']( 'web-ext-utils:notice', options, )); } catch (_) { open = false; throw _; } clearNotice(timeout == null ? -1 : typeof timeout === 'number' && timeout > 1e3 && timeout < 30 ** 2 ? timeout : 5000); onhide && onhide(); onclick = onhide = null; return new Promise(done => { onclick = () => done(true); onhide = () => done(false); }); } catch (_) { try { console.error(`failed to show notification`, arguments[0], _); } catch (_) { } } return false; }
[ "async", "function", "notify", "(", "{", "title", ",", "message", ",", "icon", "=", "'default'", ",", "timeout", ",", "}", ")", "{", "try", "{", "if", "(", "!", "Notifications", ")", "{", "console", ".", "info", "(", "'notify'", ",", "arguments", "[", "0", "]", ")", ";", "return", "false", ";", "}", "const", "create", "=", "!", "open", ";", "open", "=", "true", ";", "const", "options", "=", "{", "type", ":", "'basic'", ",", "title", ",", "message", ",", "iconUrl", ":", "(", "/", "^\\w+$", "/", ")", ".", "test", "(", "icon", ")", "?", "(", "await", "getIcon", "(", "icon", ")", ")", ":", "icon", ",", "}", ";", "!", "isGecko", "&&", "(", "options", ".", "requireInteraction", "=", "true", ")", ";", "try", "{", "(", "await", "Notifications", "[", "create", "||", "isGecko", "?", "'create'", ":", "'update'", "]", "(", "'web-ext-utils:notice'", ",", "options", ",", ")", ")", ";", "}", "catch", "(", "_", ")", "{", "open", "=", "false", ";", "throw", "_", ";", "}", "clearNotice", "(", "timeout", "==", "null", "?", "-", "1", ":", "typeof", "timeout", "===", "'number'", "&&", "timeout", ">", "1e3", "&&", "timeout", "<", "30", "**", "2", "?", "timeout", ":", "5000", ")", ";", "onhide", "&&", "onhide", "(", ")", ";", "onclick", "=", "onhide", "=", "null", ";", "return", "new", "Promise", "(", "done", "=>", "{", "onclick", "=", "(", ")", "=>", "done", "(", "true", ")", ";", "onhide", "=", "(", ")", "=>", "done", "(", "false", ")", ";", "}", ")", ";", "}", "catch", "(", "_", ")", "{", "try", "{", "console", ".", "error", "(", "`", "`", ",", "arguments", "[", "0", "]", ",", "_", ")", ";", "}", "catch", "(", "_", ")", "{", "}", "}", "return", "false", ";", "}" ]
Displays a basic notification to the user. @param {string} .title Notification title. @param {string} .message Notification body text. @param {string} .icon Notification icon URL or one of [ 'default', 'info', 'warn', 'error', 'success', ] to choose and/or generate an icon automatically. @param {natural?} .timeout Timeout in ms after which to clear the notification. @return {boolean} Whether the notification was clicked or closed (incl. timeout).
[ "Displays", "a", "basic", "notification", "to", "the", "user", "." ]
395698c633da88db86377d583b9b4eac6d9cc299
https://github.com/NiklasGollenstede/web-ext-utils/blob/395698c633da88db86377d583b9b4eac6d9cc299/utils/notify.js#L15-L29
46,365
peerigon/batch-replace
lib/replace.js
runModules
function runModules(str, modules) { var replacements = [], module; if (Array.isArray(modules) === false) { modules = [modules]; } modules.forEach(function forEachModule(module) { if (!module) { throw new Error("Unknown module '" + module + "'"); } runModule(module, str, replacements); }); return replacements; }
javascript
function runModules(str, modules) { var replacements = [], module; if (Array.isArray(modules) === false) { modules = [modules]; } modules.forEach(function forEachModule(module) { if (!module) { throw new Error("Unknown module '" + module + "'"); } runModule(module, str, replacements); }); return replacements; }
[ "function", "runModules", "(", "str", ",", "modules", ")", "{", "var", "replacements", "=", "[", "]", ",", "module", ";", "if", "(", "Array", ".", "isArray", "(", "modules", ")", "===", "false", ")", "{", "modules", "=", "[", "modules", "]", ";", "}", "modules", ".", "forEach", "(", "function", "forEachModule", "(", "module", ")", "{", "if", "(", "!", "module", ")", "{", "throw", "new", "Error", "(", "\"Unknown module '\"", "+", "module", "+", "\"'\"", ")", ";", "}", "runModule", "(", "module", ",", "str", ",", "replacements", ")", ";", "}", ")", ";", "return", "replacements", ";", "}" ]
Runs the given modules on the text and returns the insertions. @private @param {String} str @param {Array<String|ReplacementModule>} modules @returns {Array<Array>}
[ "Runs", "the", "given", "modules", "on", "the", "text", "and", "returns", "the", "insertions", "." ]
218feaba2c618386e101b1c659240fcd9f42329a
https://github.com/peerigon/batch-replace/blob/218feaba2c618386e101b1c659240fcd9f42329a/lib/replace.js#L167-L184
46,366
peerigon/batch-replace
lib/replace.js
runModule
function runModule(module, str, replacements) { var pattern = module.pattern, replace = module.replace, match; // Reset the pattern so we can re-use it pattern.lastIndex = 0; while ((match = pattern.exec(str)) !== null) { replacements[match.index] = { oldStr: match[0], newStr: typeof replace === "function"? replace(match) : replace }; if (pattern.global === false) { // if the search isn't global we need to break manually // because pattern.exec() will always return something break; } } }
javascript
function runModule(module, str, replacements) { var pattern = module.pattern, replace = module.replace, match; // Reset the pattern so we can re-use it pattern.lastIndex = 0; while ((match = pattern.exec(str)) !== null) { replacements[match.index] = { oldStr: match[0], newStr: typeof replace === "function"? replace(match) : replace }; if (pattern.global === false) { // if the search isn't global we need to break manually // because pattern.exec() will always return something break; } } }
[ "function", "runModule", "(", "module", ",", "str", ",", "replacements", ")", "{", "var", "pattern", "=", "module", ".", "pattern", ",", "replace", "=", "module", ".", "replace", ",", "match", ";", "// Reset the pattern so we can re-use it", "pattern", ".", "lastIndex", "=", "0", ";", "while", "(", "(", "match", "=", "pattern", ".", "exec", "(", "str", ")", ")", "!==", "null", ")", "{", "replacements", "[", "match", ".", "index", "]", "=", "{", "oldStr", ":", "match", "[", "0", "]", ",", "newStr", ":", "typeof", "replace", "===", "\"function\"", "?", "replace", "(", "match", ")", ":", "replace", "}", ";", "if", "(", "pattern", ".", "global", "===", "false", ")", "{", "// if the search isn't global we need to break manually", "// because pattern.exec() will always return something", "break", ";", "}", "}", "}" ]
Matches the module's pattern against the string and stores the scheduled replacement under the corresponding array index. @private @param {ReplacementModule} module @param {String} str @param {Array<Replacement>} replacements
[ "Matches", "the", "module", "s", "pattern", "against", "the", "string", "and", "stores", "the", "scheduled", "replacement", "under", "the", "corresponding", "array", "index", "." ]
218feaba2c618386e101b1c659240fcd9f42329a
https://github.com/peerigon/batch-replace/blob/218feaba2c618386e101b1c659240fcd9f42329a/lib/replace.js#L195-L214
46,367
peerigon/batch-replace
lib/replace.js
applyReplacements
function applyReplacements(str, replacements) { var result = "", replacement, i; for (i = 0; i < replacements.length; i++) { replacement = replacements[i]; if (replacement) { result += replacement.newStr; i += replacement.oldStr.length - 1; } else { result += str.charAt(i); } } result += str.substr(i, str.length); return result; }
javascript
function applyReplacements(str, replacements) { var result = "", replacement, i; for (i = 0; i < replacements.length; i++) { replacement = replacements[i]; if (replacement) { result += replacement.newStr; i += replacement.oldStr.length - 1; } else { result += str.charAt(i); } } result += str.substr(i, str.length); return result; }
[ "function", "applyReplacements", "(", "str", ",", "replacements", ")", "{", "var", "result", "=", "\"\"", ",", "replacement", ",", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "replacements", ".", "length", ";", "i", "++", ")", "{", "replacement", "=", "replacements", "[", "i", "]", ";", "if", "(", "replacement", ")", "{", "result", "+=", "replacement", ".", "newStr", ";", "i", "+=", "replacement", ".", "oldStr", ".", "length", "-", "1", ";", "}", "else", "{", "result", "+=", "str", ".", "charAt", "(", "i", ")", ";", "}", "}", "result", "+=", "str", ".", "substr", "(", "i", ",", "str", ".", "length", ")", ";", "return", "result", ";", "}" ]
Applies all replacements on the given string. @private @param {String} str @param {Array<Replacement>} replacements @returns {string}
[ "Applies", "all", "replacements", "on", "the", "given", "string", "." ]
218feaba2c618386e101b1c659240fcd9f42329a
https://github.com/peerigon/batch-replace/blob/218feaba2c618386e101b1c659240fcd9f42329a/lib/replace.js#L224-L242
46,368
doowb/paginationator
lib/pages.js
decorate
function decorate(pages, page) { Object.defineProperties(page, { first: { enumerable: true, set: function() {}, get: function() { return pages.first && pages.first.current; } }, current: { enumerable: true, set: function() {}, get: function() { return this.idx + 1; } }, last: { enumerable: true, set: function() {}, get: function() { return pages.last && pages.last.current; } }, total: { enumerable: true, set: function() {}, get: function() { return pages.total; } } }); var prev = pages.last; var idx = pages.total; page.idx = idx; if (prev) { page.prev = prev.current; prev.next = page.current; } return page; }
javascript
function decorate(pages, page) { Object.defineProperties(page, { first: { enumerable: true, set: function() {}, get: function() { return pages.first && pages.first.current; } }, current: { enumerable: true, set: function() {}, get: function() { return this.idx + 1; } }, last: { enumerable: true, set: function() {}, get: function() { return pages.last && pages.last.current; } }, total: { enumerable: true, set: function() {}, get: function() { return pages.total; } } }); var prev = pages.last; var idx = pages.total; page.idx = idx; if (prev) { page.prev = prev.current; prev.next = page.current; } return page; }
[ "function", "decorate", "(", "pages", ",", "page", ")", "{", "Object", ".", "defineProperties", "(", "page", ",", "{", "first", ":", "{", "enumerable", ":", "true", ",", "set", ":", "function", "(", ")", "{", "}", ",", "get", ":", "function", "(", ")", "{", "return", "pages", ".", "first", "&&", "pages", ".", "first", ".", "current", ";", "}", "}", ",", "current", ":", "{", "enumerable", ":", "true", ",", "set", ":", "function", "(", ")", "{", "}", ",", "get", ":", "function", "(", ")", "{", "return", "this", ".", "idx", "+", "1", ";", "}", "}", ",", "last", ":", "{", "enumerable", ":", "true", ",", "set", ":", "function", "(", ")", "{", "}", ",", "get", ":", "function", "(", ")", "{", "return", "pages", ".", "last", "&&", "pages", ".", "last", ".", "current", ";", "}", "}", ",", "total", ":", "{", "enumerable", ":", "true", ",", "set", ":", "function", "(", ")", "{", "}", ",", "get", ":", "function", "(", ")", "{", "return", "pages", ".", "total", ";", "}", "}", "}", ")", ";", "var", "prev", "=", "pages", ".", "last", ";", "var", "idx", "=", "pages", ".", "total", ";", "page", ".", "idx", "=", "idx", ";", "if", "(", "prev", ")", "{", "page", ".", "prev", "=", "prev", ".", "current", ";", "prev", ".", "next", "=", "page", ".", "current", ";", "}", "return", "page", ";", "}" ]
Decorates a page with additional properties. @param {Object} `page` Instance of page to decorate @return {Object} Returns the decorated page to be added to the list
[ "Decorates", "a", "page", "with", "additional", "properties", "." ]
e8c1f1d7ea0a39a2f23e6838a9a73a05c30c7b16
https://github.com/doowb/paginationator/blob/e8c1f1d7ea0a39a2f23e6838a9a73a05c30c7b16/lib/pages.js#L69-L112
46,369
creationix/bodec
bodec-browser.js
toHex
function toHex(binary, start, end) { var hex = ""; if (end === undefined) { end = binary.length; if (start === undefined) start = 0; } for (var i = start; i < end; i++) { var byte = binary[i]; hex += String.fromCharCode(nibbleToCode(byte >> 4)) + String.fromCharCode(nibbleToCode(byte & 0xf)); } return hex; }
javascript
function toHex(binary, start, end) { var hex = ""; if (end === undefined) { end = binary.length; if (start === undefined) start = 0; } for (var i = start; i < end; i++) { var byte = binary[i]; hex += String.fromCharCode(nibbleToCode(byte >> 4)) + String.fromCharCode(nibbleToCode(byte & 0xf)); } return hex; }
[ "function", "toHex", "(", "binary", ",", "start", ",", "end", ")", "{", "var", "hex", "=", "\"\"", ";", "if", "(", "end", "===", "undefined", ")", "{", "end", "=", "binary", ".", "length", ";", "if", "(", "start", "===", "undefined", ")", "start", "=", "0", ";", "}", "for", "(", "var", "i", "=", "start", ";", "i", "<", "end", ";", "i", "++", ")", "{", "var", "byte", "=", "binary", "[", "i", "]", ";", "hex", "+=", "String", ".", "fromCharCode", "(", "nibbleToCode", "(", "byte", ">>", "4", ")", ")", "+", "String", ".", "fromCharCode", "(", "nibbleToCode", "(", "byte", "&", "0xf", ")", ")", ";", "}", "return", "hex", ";", "}" ]
Like slice, but encode as a hex string
[ "Like", "slice", "but", "encode", "as", "a", "hex", "string" ]
19f94a638f1ab3454b759ff4baf61ee09e8b3ae5
https://github.com/creationix/bodec/blob/19f94a638f1ab3454b759ff4baf61ee09e8b3ae5/bodec-browser.js#L94-L106
46,370
chrahunt/tagpro-navmesh
src/pathfinder.js
nodeValue
function nodeValue(node1, node2) { return (node1.dist + heuristic(node1.point)) - (node2.dist + heuristic(node2.point)); }
javascript
function nodeValue(node1, node2) { return (node1.dist + heuristic(node1.point)) - (node2.dist + heuristic(node2.point)); }
[ "function", "nodeValue", "(", "node1", ",", "node2", ")", "{", "return", "(", "node1", ".", "dist", "+", "heuristic", "(", "node1", ".", "point", ")", ")", "-", "(", "node2", ".", "dist", "+", "heuristic", "(", "node2", ".", "point", ")", ")", ";", "}" ]
Compares the value of two nodes.
[ "Compares", "the", "value", "of", "two", "nodes", "." ]
b50fbdad1061fb4760ac22ee756f34ab3e177539
https://github.com/chrahunt/tagpro-navmesh/blob/b50fbdad1061fb4760ac22ee756f34ab3e177539/src/pathfinder.js#L35-L37
46,371
Levino/coindesk-api-node
index.js
function (currency, callback) { // Call an asynchronous function, often a save() to DB self.getPricesForSingleCurrency(from, to, currency, function (err, result) { if (err) { callback(err) } else { ratesWithTimes[currency] = result callback() } }) }
javascript
function (currency, callback) { // Call an asynchronous function, often a save() to DB self.getPricesForSingleCurrency(from, to, currency, function (err, result) { if (err) { callback(err) } else { ratesWithTimes[currency] = result callback() } }) }
[ "function", "(", "currency", ",", "callback", ")", "{", "// Call an asynchronous function, often a save() to DB", "self", ".", "getPricesForSingleCurrency", "(", "from", ",", "to", ",", "currency", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "callback", "(", "err", ")", "}", "else", "{", "ratesWithTimes", "[", "currency", "]", "=", "result", "callback", "(", ")", "}", "}", ")", "}" ]
2nd param is the function that each item is passed to
[ "2nd", "param", "is", "the", "function", "that", "each", "item", "is", "passed", "to" ]
a477ac65e76fbcf31644055758cdb60d45fea04a
https://github.com/Levino/coindesk-api-node/blob/a477ac65e76fbcf31644055758cdb60d45fea04a/index.js#L69-L79
46,372
Levino/coindesk-api-node
index.js
function (err) { if (err) { callback(err, null) } _.each(ratesWithTimes, function (rates, currency) { rates.forEach(function (timeratepair) { var newEntry = {} newEntry[currency] = timeratepair.rate if (allRates[timeratepair.time]) { allRates[timeratepair.time].push(newEntry) } else { allRates[timeratepair.time] = [newEntry] } }) }) var allRatesNice = [] _.each(allRates, function (rates, time) { var ratesNice = {} _.each(rates, function (currencyratepair) { _.each(currencyratepair, function (rate, currency) { ratesNice[currency] = rate }) }) allRatesNice.push({time: time, rates: ratesNice}) }) callback(null, allRatesNice) }
javascript
function (err) { if (err) { callback(err, null) } _.each(ratesWithTimes, function (rates, currency) { rates.forEach(function (timeratepair) { var newEntry = {} newEntry[currency] = timeratepair.rate if (allRates[timeratepair.time]) { allRates[timeratepair.time].push(newEntry) } else { allRates[timeratepair.time] = [newEntry] } }) }) var allRatesNice = [] _.each(allRates, function (rates, time) { var ratesNice = {} _.each(rates, function (currencyratepair) { _.each(currencyratepair, function (rate, currency) { ratesNice[currency] = rate }) }) allRatesNice.push({time: time, rates: ratesNice}) }) callback(null, allRatesNice) }
[ "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "callback", "(", "err", ",", "null", ")", "}", "_", ".", "each", "(", "ratesWithTimes", ",", "function", "(", "rates", ",", "currency", ")", "{", "rates", ".", "forEach", "(", "function", "(", "timeratepair", ")", "{", "var", "newEntry", "=", "{", "}", "newEntry", "[", "currency", "]", "=", "timeratepair", ".", "rate", "if", "(", "allRates", "[", "timeratepair", ".", "time", "]", ")", "{", "allRates", "[", "timeratepair", ".", "time", "]", ".", "push", "(", "newEntry", ")", "}", "else", "{", "allRates", "[", "timeratepair", ".", "time", "]", "=", "[", "newEntry", "]", "}", "}", ")", "}", ")", "var", "allRatesNice", "=", "[", "]", "_", ".", "each", "(", "allRates", ",", "function", "(", "rates", ",", "time", ")", "{", "var", "ratesNice", "=", "{", "}", "_", ".", "each", "(", "rates", ",", "function", "(", "currencyratepair", ")", "{", "_", ".", "each", "(", "currencyratepair", ",", "function", "(", "rate", ",", "currency", ")", "{", "ratesNice", "[", "currency", "]", "=", "rate", "}", ")", "}", ")", "allRatesNice", ".", "push", "(", "{", "time", ":", "time", ",", "rates", ":", "ratesNice", "}", ")", "}", ")", "callback", "(", "null", ",", "allRatesNice", ")", "}" ]
3rd param is the function to call when everything's done
[ "3rd", "param", "is", "the", "function", "to", "call", "when", "everything", "s", "done" ]
a477ac65e76fbcf31644055758cdb60d45fea04a
https://github.com/Levino/coindesk-api-node/blob/a477ac65e76fbcf31644055758cdb60d45fea04a/index.js#L81-L107
46,373
axetroy/redux-zero-logger
index.js
logger
function logger(config = {}) { // return an middleware return store => next => action => { const prevState = store.getState(); const r = next(action); function prinf(prev, action, next) { console.group(action, "@" + new Date().toISOString()); console.log("%cprev state", "color:#9E9E9E", prev); console.log("%caction", "color:#2196F3", action); console.log("%cnext state", "color:#4CAF50", next); console.groupEnd(); } if (r && typeof r.then === "function") { return next(action).then( d => prinf(prevState, action.name, store.getState()) && Promise.resolve(d) ); } else { prinf(prevState, action.name, store.getState()); return r; } }; }
javascript
function logger(config = {}) { // return an middleware return store => next => action => { const prevState = store.getState(); const r = next(action); function prinf(prev, action, next) { console.group(action, "@" + new Date().toISOString()); console.log("%cprev state", "color:#9E9E9E", prev); console.log("%caction", "color:#2196F3", action); console.log("%cnext state", "color:#4CAF50", next); console.groupEnd(); } if (r && typeof r.then === "function") { return next(action).then( d => prinf(prevState, action.name, store.getState()) && Promise.resolve(d) ); } else { prinf(prevState, action.name, store.getState()); return r; } }; }
[ "function", "logger", "(", "config", "=", "{", "}", ")", "{", "// return an middleware", "return", "store", "=>", "next", "=>", "action", "=>", "{", "const", "prevState", "=", "store", ".", "getState", "(", ")", ";", "const", "r", "=", "next", "(", "action", ")", ";", "function", "prinf", "(", "prev", ",", "action", ",", "next", ")", "{", "console", ".", "group", "(", "action", ",", "\"@\"", "+", "new", "Date", "(", ")", ".", "toISOString", "(", ")", ")", ";", "console", ".", "log", "(", "\"%cprev state\"", ",", "\"color:#9E9E9E\"", ",", "prev", ")", ";", "console", ".", "log", "(", "\"%caction\"", ",", "\"color:#2196F3\"", ",", "action", ")", ";", "console", ".", "log", "(", "\"%cnext state\"", ",", "\"color:#4CAF50\"", ",", "next", ")", ";", "console", ".", "groupEnd", "(", ")", ";", "}", "if", "(", "r", "&&", "typeof", "r", ".", "then", "===", "\"function\"", ")", "{", "return", "next", "(", "action", ")", ".", "then", "(", "d", "=>", "prinf", "(", "prevState", ",", "action", ".", "name", ",", "store", ".", "getState", "(", ")", ")", "&&", "Promise", ".", "resolve", "(", "d", ")", ")", ";", "}", "else", "{", "prinf", "(", "prevState", ",", "action", ".", "name", ",", "store", ".", "getState", "(", ")", ")", ";", "return", "r", ";", "}", "}", ";", "}" ]
The logger middleware for redux-zero @param config @returns {function(*): function(*): function(*=)}
[ "The", "logger", "middleware", "for", "redux", "-", "zero" ]
6f97f15b9e6af9663c137a9002e0bde3dead7453
https://github.com/axetroy/redux-zero-logger/blob/6f97f15b9e6af9663c137a9002e0bde3dead7453/index.js#L6-L30
46,374
winkerVSbecks/draper
src/build.js
toRems
function toRems(rem, type) { return R.compose( R.objOf(type), R.map(R.multiply(rem)), R.prop(type) ); }
javascript
function toRems(rem, type) { return R.compose( R.objOf(type), R.map(R.multiply(rem)), R.prop(type) ); }
[ "function", "toRems", "(", "rem", ",", "type", ")", "{", "return", "R", ".", "compose", "(", "R", ".", "objOf", "(", "type", ")", ",", "R", ".", "map", "(", "R", ".", "multiply", "(", "rem", ")", ")", ",", "R", ".", "prop", "(", "type", ")", ")", ";", "}" ]
Converts a scale to rems
[ "Converts", "a", "scale", "to", "rems" ]
1648dce7c2252a8beea9e8a7faecc7b4129f2244
https://github.com/winkerVSbecks/draper/blob/1648dce7c2252a8beea9e8a7faecc7b4129f2244/src/build.js#L51-L57
46,375
NiklasGollenstede/web-ext-utils
options/editor/index.js
sanitize
function sanitize(html) { const parts = (html ? html +'' : '').split(rTag); return parts.map((s, i) => i % 2 ? s : s.replace(rEsc, c => oEsc[c])).join(''); }
javascript
function sanitize(html) { const parts = (html ? html +'' : '').split(rTag); return parts.map((s, i) => i % 2 ? s : s.replace(rEsc, c => oEsc[c])).join(''); }
[ "function", "sanitize", "(", "html", ")", "{", "const", "parts", "=", "(", "html", "?", "html", "+", "''", ":", "''", ")", ".", "split", "(", "rTag", ")", ";", "return", "parts", ".", "map", "(", "(", "s", ",", "i", ")", "=>", "i", "%", "2", "?", "s", ":", "s", ".", "replace", "(", "rEsc", ",", "c", "=>", "oEsc", "[", "c", "]", ")", ")", ".", "join", "(", "''", ")", ";", "}" ]
Sanitizes untrusted HTML by escaping everything that is not recognized as a whitelisted tag or entity. @param {string} html Untrusted HTML input. @return {string} Sanitized HTML that won't contain any tags but those whitelisted by `rTag` below. @author Niklas Gollenstede @license MIT
[ "Sanitizes", "untrusted", "HTML", "by", "escaping", "everything", "that", "is", "not", "recognized", "as", "a", "whitelisted", "tag", "or", "entity", "." ]
395698c633da88db86377d583b9b4eac6d9cc299
https://github.com/NiklasGollenstede/web-ext-utils/blob/395698c633da88db86377d583b9b4eac6d9cc299/options/editor/index.js#L329-L332
46,376
chrahunt/tagpro-navmesh
src/parse-map.js
generateContourGrid
function generateContourGrid(arr) { // Generate grid for holding values. var contour_grid = new Array(arr.length - 1); for (var n = 0; n < contour_grid.length; n++) { contour_grid[n] = new Array(arr[0].length - 1); } var corners = [1.1, 1.2, 1.3, 1.4]; // Specifies the resulting values for the above corner values. The index // of the objects in this array corresponds to the proper values for the // quadrant of the same index. var corner_values = [ {1.1: 3, 1.2: 0, 1.3: 2, 1.4: 1}, {1.1: 0, 1.2: 3, 1.3: 1, 1.4: 2}, {1.1: 3, 1.2: 1, 1.3: 2, 1.4: 0}, {1.1: 1, 1.2: 3, 1.3: 0, 1.4: 2} ]; for (var i = 0; i < (arr.length - 1); i++) { for (var j = 0; j < (arr[0].length - 1); j++) { var cell = [arr[i][j], arr[i][j+1], arr[i+1][j+1], arr[i+1][j]]; // Convert corner tiles to appropriate representation. cell.forEach(function(val, i, cell) { if (corners.indexOf(val) !== -1) { cell[i] = corner_values[i][val]; } }); contour_grid[i][j] = cell; } } return contour_grid; }
javascript
function generateContourGrid(arr) { // Generate grid for holding values. var contour_grid = new Array(arr.length - 1); for (var n = 0; n < contour_grid.length; n++) { contour_grid[n] = new Array(arr[0].length - 1); } var corners = [1.1, 1.2, 1.3, 1.4]; // Specifies the resulting values for the above corner values. The index // of the objects in this array corresponds to the proper values for the // quadrant of the same index. var corner_values = [ {1.1: 3, 1.2: 0, 1.3: 2, 1.4: 1}, {1.1: 0, 1.2: 3, 1.3: 1, 1.4: 2}, {1.1: 3, 1.2: 1, 1.3: 2, 1.4: 0}, {1.1: 1, 1.2: 3, 1.3: 0, 1.4: 2} ]; for (var i = 0; i < (arr.length - 1); i++) { for (var j = 0; j < (arr[0].length - 1); j++) { var cell = [arr[i][j], arr[i][j+1], arr[i+1][j+1], arr[i+1][j]]; // Convert corner tiles to appropriate representation. cell.forEach(function(val, i, cell) { if (corners.indexOf(val) !== -1) { cell[i] = corner_values[i][val]; } }); contour_grid[i][j] = cell; } } return contour_grid; }
[ "function", "generateContourGrid", "(", "arr", ")", "{", "// Generate grid for holding values.", "var", "contour_grid", "=", "new", "Array", "(", "arr", ".", "length", "-", "1", ")", ";", "for", "(", "var", "n", "=", "0", ";", "n", "<", "contour_grid", ".", "length", ";", "n", "++", ")", "{", "contour_grid", "[", "n", "]", "=", "new", "Array", "(", "arr", "[", "0", "]", ".", "length", "-", "1", ")", ";", "}", "var", "corners", "=", "[", "1.1", ",", "1.2", ",", "1.3", ",", "1.4", "]", ";", "// Specifies the resulting values for the above corner values. The index", "// of the objects in this array corresponds to the proper values for the", "// quadrant of the same index.", "var", "corner_values", "=", "[", "{", "1.1", ":", "3", ",", "1.2", ":", "0", ",", "1.3", ":", "2", ",", "1.4", ":", "1", "}", ",", "{", "1.1", ":", "0", ",", "1.2", ":", "3", ",", "1.3", ":", "1", ",", "1.4", ":", "2", "}", ",", "{", "1.1", ":", "3", ",", "1.2", ":", "1", ",", "1.3", ":", "2", ",", "1.4", ":", "0", "}", ",", "{", "1.1", ":", "1", ",", "1.2", ":", "3", ",", "1.3", ":", "0", ",", "1.4", ":", "2", "}", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "(", "arr", ".", "length", "-", "1", ")", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "(", "arr", "[", "0", "]", ".", "length", "-", "1", ")", ";", "j", "++", ")", "{", "var", "cell", "=", "[", "arr", "[", "i", "]", "[", "j", "]", ",", "arr", "[", "i", "]", "[", "j", "+", "1", "]", ",", "arr", "[", "i", "+", "1", "]", "[", "j", "+", "1", "]", ",", "arr", "[", "i", "+", "1", "]", "[", "j", "]", "]", ";", "// Convert corner tiles to appropriate representation.", "cell", ".", "forEach", "(", "function", "(", "val", ",", "i", ",", "cell", ")", "{", "if", "(", "corners", ".", "indexOf", "(", "val", ")", "!==", "-", "1", ")", "{", "cell", "[", "i", "]", "=", "corner_values", "[", "i", "]", "[", "val", "]", ";", "}", "}", ")", ";", "contour_grid", "[", "i", "]", "[", "j", "]", "=", "cell", ";", "}", "}", "return", "contour_grid", ";", "}" ]
Converts the provided array into its equivalent representation using cells. @private @param {MapTiles} arr - @param {Array.<Array.<Cell>>} - The converted array.
[ "Converts", "the", "provided", "array", "into", "its", "equivalent", "representation", "using", "cells", "." ]
b50fbdad1061fb4760ac22ee756f34ab3e177539
https://github.com/chrahunt/tagpro-navmesh/blob/b50fbdad1061fb4760ac22ee756f34ab3e177539/src/parse-map.js#L127-L157
46,377
chrahunt/tagpro-navmesh
src/parse-map.js
find
function find(arr, obj, cmp) { if (typeof cmp !== 'undefined') { for (var i = 0; i < arr.length; i++) { if (cmp(arr[i], obj)) { return i; } } return -1; } }
javascript
function find(arr, obj, cmp) { if (typeof cmp !== 'undefined') { for (var i = 0; i < arr.length; i++) { if (cmp(arr[i], obj)) { return i; } } return -1; } }
[ "function", "find", "(", "arr", ",", "obj", ",", "cmp", ")", "{", "if", "(", "typeof", "cmp", "!==", "'undefined'", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arr", ".", "length", ";", "i", "++", ")", "{", "if", "(", "cmp", "(", "arr", "[", "i", "]", ",", "obj", ")", ")", "{", "return", "i", ";", "}", "}", "return", "-", "1", ";", "}", "}" ]
Callback function for testing equality of items. @private @callback comparisonCallback @param {*} - The first item. @param {*} - The second item. @return {boolean} - Whether or not the items are equal. Returns the location of obj in arr with equality determined by cmp. @private @param {Array.<*>} arr - The array to be searched. @param {*} obj - The item to find a match for. @param {comparisonCallback} cmp - The callback that defines whether `obj` matches. @return {integer} - The index of the first element to match `obj`, or -1 if no such element was located.
[ "Callback", "function", "for", "testing", "equality", "of", "items", "." ]
b50fbdad1061fb4760ac22ee756f34ab3e177539
https://github.com/chrahunt/tagpro-navmesh/blob/b50fbdad1061fb4760ac22ee756f34ab3e177539/src/parse-map.js#L178-L187
46,378
chrahunt/tagpro-navmesh
src/parse-map.js
nextNeighbor
function nextNeighbor(elt, dir) { var drow = 0, dcol = 0; if (dir == "none") { return null; } else { var offset = directions[dir]; return {r: elt.r + offset[0], c: elt.c + offset[1]}; } }
javascript
function nextNeighbor(elt, dir) { var drow = 0, dcol = 0; if (dir == "none") { return null; } else { var offset = directions[dir]; return {r: elt.r + offset[0], c: elt.c + offset[1]}; } }
[ "function", "nextNeighbor", "(", "elt", ",", "dir", ")", "{", "var", "drow", "=", "0", ",", "dcol", "=", "0", ";", "if", "(", "dir", "==", "\"none\"", ")", "{", "return", "null", ";", "}", "else", "{", "var", "offset", "=", "directions", "[", "dir", "]", ";", "return", "{", "r", ":", "elt", ".", "r", "+", "offset", "[", "0", "]", ",", "c", ":", "elt", ".", "c", "+", "offset", "[", "1", "]", "}", ";", "}", "}" ]
Takes the current location and direction at this point and returns the next location to check. Returns null if this cell is not part of a shape.
[ "Takes", "the", "current", "location", "and", "direction", "at", "this", "point", "and", "returns", "the", "next", "location", "to", "check", ".", "Returns", "null", "if", "this", "cell", "is", "not", "part", "of", "a", "shape", "." ]
b50fbdad1061fb4760ac22ee756f34ab3e177539
https://github.com/chrahunt/tagpro-navmesh/blob/b50fbdad1061fb4760ac22ee756f34ab3e177539/src/parse-map.js#L226-L234
46,379
chrahunt/tagpro-navmesh
src/parse-map.js
nextCell
function nextCell(elt) { if (elt.c + 1 < actionInfo[elt.r].length) { return {r: elt.r, c: elt.c + 1}; } else if (elt.r + 1 < actionInfo.length) { return {r: elt.r + 1, c: 0}; } return null; }
javascript
function nextCell(elt) { if (elt.c + 1 < actionInfo[elt.r].length) { return {r: elt.r, c: elt.c + 1}; } else if (elt.r + 1 < actionInfo.length) { return {r: elt.r + 1, c: 0}; } return null; }
[ "function", "nextCell", "(", "elt", ")", "{", "if", "(", "elt", ".", "c", "+", "1", "<", "actionInfo", "[", "elt", ".", "r", "]", ".", "length", ")", "{", "return", "{", "r", ":", "elt", ".", "r", ",", "c", ":", "elt", ".", "c", "+", "1", "}", ";", "}", "else", "if", "(", "elt", ".", "r", "+", "1", "<", "actionInfo", ".", "length", ")", "{", "return", "{", "r", ":", "elt", ".", "r", "+", "1", ",", "c", ":", "0", "}", ";", "}", "return", "null", ";", "}" ]
Get the next cell, from left to right, top to bottom. Returns null if last element in array reached.
[ "Get", "the", "next", "cell", "from", "left", "to", "right", "top", "to", "bottom", ".", "Returns", "null", "if", "last", "element", "in", "array", "reached", "." ]
b50fbdad1061fb4760ac22ee756f34ab3e177539
https://github.com/chrahunt/tagpro-navmesh/blob/b50fbdad1061fb4760ac22ee756f34ab3e177539/src/parse-map.js#L238-L245
46,380
chrahunt/tagpro-navmesh
src/parse-map.js
getCoordinates
function getCoordinates(location) { var tile_width = 40; var x = location.r * tile_width; var y = location.c * tile_width; return {x: x, y: y}; }
javascript
function getCoordinates(location) { var tile_width = 40; var x = location.r * tile_width; var y = location.c * tile_width; return {x: x, y: y}; }
[ "function", "getCoordinates", "(", "location", ")", "{", "var", "tile_width", "=", "40", ";", "var", "x", "=", "location", ".", "r", "*", "tile_width", ";", "var", "y", "=", "location", ".", "c", "*", "tile_width", ";", "return", "{", "x", ":", "x", ",", "y", ":", "y", "}", ";", "}" ]
Convert an array location to a point representing the top-left corner of the tile in global coordinates. @private @param {ArrayLoc} location - The array location to get the coordinates for. @return {MPPoint} - The coordinates of the tile.
[ "Convert", "an", "array", "location", "to", "a", "point", "representing", "the", "top", "-", "left", "corner", "of", "the", "tile", "in", "global", "coordinates", "." ]
b50fbdad1061fb4760ac22ee756f34ab3e177539
https://github.com/chrahunt/tagpro-navmesh/blob/b50fbdad1061fb4760ac22ee756f34ab3e177539/src/parse-map.js#L392-L397
46,381
chrahunt/tagpro-navmesh
src/parse-map.js
convertShapesToCoords
function convertShapesToCoords(shapes) { var tile_width = 40; var new_shapes = map2d(shapes, function(loc) { // It would be loc.r + 1 and loc.c + 1 but that has been removed // to account for the one-tile width of padding added in doParse. var row = loc.r * tile_width; var col = loc.c * tile_width; return {x: row, y: col} }); return new_shapes; }
javascript
function convertShapesToCoords(shapes) { var tile_width = 40; var new_shapes = map2d(shapes, function(loc) { // It would be loc.r + 1 and loc.c + 1 but that has been removed // to account for the one-tile width of padding added in doParse. var row = loc.r * tile_width; var col = loc.c * tile_width; return {x: row, y: col} }); return new_shapes; }
[ "function", "convertShapesToCoords", "(", "shapes", ")", "{", "var", "tile_width", "=", "40", ";", "var", "new_shapes", "=", "map2d", "(", "shapes", ",", "function", "(", "loc", ")", "{", "// It would be loc.r + 1 and loc.c + 1 but that has been removed", "// to account for the one-tile width of padding added in doParse.", "var", "row", "=", "loc", ".", "r", "*", "tile_width", ";", "var", "col", "=", "loc", ".", "c", "*", "tile_width", ";", "return", "{", "x", ":", "row", ",", "y", ":", "col", "}", "}", ")", ";", "return", "new_shapes", ";", "}" ]
Takes in an array of shapes and converts from contour grid layout to actual coordinates. @private @param {Array.<Array.<ArrayLoc>>} shapes - output from generateShapes @return {Array.<Array.<{{x: number, y: number}}>>}
[ "Takes", "in", "an", "array", "of", "shapes", "and", "converts", "from", "contour", "grid", "layout", "to", "actual", "coordinates", "." ]
b50fbdad1061fb4760ac22ee756f34ab3e177539
https://github.com/chrahunt/tagpro-navmesh/blob/b50fbdad1061fb4760ac22ee756f34ab3e177539/src/parse-map.js#L406-L417
46,382
shd101wyy/lisp2js
lisp2js.js
validateName
function validateName(var_name) { var o = ""; for (var i = 0; i < var_name.length; i++) { var code = var_name.charCodeAt(i); if ((code > 47 && code < 58) || // numeric (0-9) (code > 64 && code < 91) || // upper alpha (A-Z) (code > 96 && code < 123) || // lower alpha (a-z) var_name[i] === "$" || var_name[i] === "_" || var_name[i] === "." || var_name[i] === "&" || code > 255 // utf ) { o += var_name[i]; } else { o += "_$" + code + "_"; } } if (!isNaN(o[0])) o = "_" + o ; // first letter is number, add _ ahead. return o; }
javascript
function validateName(var_name) { var o = ""; for (var i = 0; i < var_name.length; i++) { var code = var_name.charCodeAt(i); if ((code > 47 && code < 58) || // numeric (0-9) (code > 64 && code < 91) || // upper alpha (A-Z) (code > 96 && code < 123) || // lower alpha (a-z) var_name[i] === "$" || var_name[i] === "_" || var_name[i] === "." || var_name[i] === "&" || code > 255 // utf ) { o += var_name[i]; } else { o += "_$" + code + "_"; } } if (!isNaN(o[0])) o = "_" + o ; // first letter is number, add _ ahead. return o; }
[ "function", "validateName", "(", "var_name", ")", "{", "var", "o", "=", "\"\"", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "var_name", ".", "length", ";", "i", "++", ")", "{", "var", "code", "=", "var_name", ".", "charCodeAt", "(", "i", ")", ";", "if", "(", "(", "code", ">", "47", "&&", "code", "<", "58", ")", "||", "// numeric (0-9)", "(", "code", ">", "64", "&&", "code", "<", "91", ")", "||", "// upper alpha (A-Z)", "(", "code", ">", "96", "&&", "code", "<", "123", ")", "||", "// lower alpha (a-z)", "var_name", "[", "i", "]", "===", "\"$\"", "||", "var_name", "[", "i", "]", "===", "\"_\"", "||", "var_name", "[", "i", "]", "===", "\".\"", "||", "var_name", "[", "i", "]", "===", "\"&\"", "||", "code", ">", "255", "// utf", ")", "{", "o", "+=", "var_name", "[", "i", "]", ";", "}", "else", "{", "o", "+=", "\"_$\"", "+", "code", "+", "\"_\"", ";", "}", "}", "if", "(", "!", "isNaN", "(", "o", "[", "0", "]", ")", ")", "o", "=", "\"_\"", "+", "o", ";", "// first letter is number, add _ ahead.", "return", "o", ";", "}" ]
validate variable name.
[ "validate", "variable", "name", "." ]
6cf8bb199e565152e3d6461f94040c464ba441b4
https://github.com/shd101wyy/lisp2js/blob/6cf8bb199e565152e3d6461f94040c464ba441b4/lisp2js.js#L603-L623
46,383
winkerVSbecks/draper
dist/absolute.js
absolute
function absolute(rem){return{abs:{position:'absolute'}, top0:{top:0}, right0:{right:0}, bottom0:{bottom:0}, left0:{left:0}, top1:{top:1*rem}, right1:{right:1*rem}, bottom1:{bottom:1*rem}, left1:{left:1*rem}, top2:{top:2*rem}, right2:{right:2*rem}, bottom2:{bottom:2*rem}, left2:{left:2*rem}, top3:{top:3*rem}, right3:{right:3*rem}, bottom3:{bottom:3*rem}, left3:{left:3*rem}, top4:{top:4*rem}, right4:{right:4*rem}, bottom4:{bottom:4*rem}, left4:{left:4*rem}, z1:{zIndex:1,elevation:1}, z2:{zIndex:2,elevation:2}, z3:{zIndex:4,elevation:4}, z4:{zIndex:8,elevation:8}}; }
javascript
function absolute(rem){return{abs:{position:'absolute'}, top0:{top:0}, right0:{right:0}, bottom0:{bottom:0}, left0:{left:0}, top1:{top:1*rem}, right1:{right:1*rem}, bottom1:{bottom:1*rem}, left1:{left:1*rem}, top2:{top:2*rem}, right2:{right:2*rem}, bottom2:{bottom:2*rem}, left2:{left:2*rem}, top3:{top:3*rem}, right3:{right:3*rem}, bottom3:{bottom:3*rem}, left3:{left:3*rem}, top4:{top:4*rem}, right4:{right:4*rem}, bottom4:{bottom:4*rem}, left4:{left:4*rem}, z1:{zIndex:1,elevation:1}, z2:{zIndex:2,elevation:2}, z3:{zIndex:4,elevation:4}, z4:{zIndex:8,elevation:8}}; }
[ "function", "absolute", "(", "rem", ")", "{", "return", "{", "abs", ":", "{", "position", ":", "'absolute'", "}", ",", "top0", ":", "{", "top", ":", "0", "}", ",", "right0", ":", "{", "right", ":", "0", "}", ",", "bottom0", ":", "{", "bottom", ":", "0", "}", ",", "left0", ":", "{", "left", ":", "0", "}", ",", "top1", ":", "{", "top", ":", "1", "*", "rem", "}", ",", "right1", ":", "{", "right", ":", "1", "*", "rem", "}", ",", "bottom1", ":", "{", "bottom", ":", "1", "*", "rem", "}", ",", "left1", ":", "{", "left", ":", "1", "*", "rem", "}", ",", "top2", ":", "{", "top", ":", "2", "*", "rem", "}", ",", "right2", ":", "{", "right", ":", "2", "*", "rem", "}", ",", "bottom2", ":", "{", "bottom", ":", "2", "*", "rem", "}", ",", "left2", ":", "{", "left", ":", "2", "*", "rem", "}", ",", "top3", ":", "{", "top", ":", "3", "*", "rem", "}", ",", "right3", ":", "{", "right", ":", "3", "*", "rem", "}", ",", "bottom3", ":", "{", "bottom", ":", "3", "*", "rem", "}", ",", "left3", ":", "{", "left", ":", "3", "*", "rem", "}", ",", "top4", ":", "{", "top", ":", "4", "*", "rem", "}", ",", "right4", ":", "{", "right", ":", "4", "*", "rem", "}", ",", "bottom4", ":", "{", "bottom", ":", "4", "*", "rem", "}", ",", "left4", ":", "{", "left", ":", "4", "*", "rem", "}", ",", "z1", ":", "{", "zIndex", ":", "1", ",", "elevation", ":", "1", "}", ",", "z2", ":", "{", "zIndex", ":", "2", ",", "elevation", ":", "2", "}", ",", "z3", ":", "{", "zIndex", ":", "4", ",", "elevation", ":", "4", "}", ",", "z4", ":", "{", "zIndex", ":", "8", ",", "elevation", ":", "8", "}", "}", ";", "}" ]
Generate absolute position classes
[ "Generate", "absolute", "position", "classes" ]
1648dce7c2252a8beea9e8a7faecc7b4129f2244
https://github.com/winkerVSbecks/draper/blob/1648dce7c2252a8beea9e8a7faecc7b4129f2244/dist/absolute.js#L6-L37
46,384
hlapp/wirelesstags-js
plugins/polling-updater.js
PollingTagUpdater
function PollingTagUpdater(platform, options) { EventEmitter.call(this); this.tagsByUUID = {}; this.options = Object.assign({}, options); if (! this.options.wsdl_url) { let apiBaseURI; if (platform) apiBaseURI = platform.apiBaseURI; if (options && options.apiBaseURI) apiBaseURI = options.apiBaseURI; if (! apiBaseURI) apiBaseURI = API_BASE_URI; this.options.wsdl_url = apiBaseURI + WSDL_URL_PATH; } /** * @name discoveryMode * @type {boolean} * @memberof module:plugins/polling-updater~PollingTagUpdater# */ Object.defineProperty(this, "discoveryMode", { enumerable: true, get: function() { return this.options.discoveryMode }, set: function(v) { this.options.discoveryMode = v } }); let h = this.stopUpdateLoop.bind(this); /** * @name platform * @type {WirelessTagPlatform} * @memberof module:plugins/polling-updater~PollingTagUpdater# */ Object.defineProperty(this, "platform", { enumerable: true, get: function() { return this._platform }, set: function(p) { if (this._platform && this._platform !== p) { this._platform.removeListener('disconnect', h); if (this.options.log === this._platform.log) { this.options.log = undefined; } } this._platform = p; if (p) { if (! this.options.log) this.options.log = p.log; p.on('disconnect', h); } } }); this.platform = platform; /** @member {WirelessTagPlatform~factory} */ this.factory = this.options.factory; }
javascript
function PollingTagUpdater(platform, options) { EventEmitter.call(this); this.tagsByUUID = {}; this.options = Object.assign({}, options); if (! this.options.wsdl_url) { let apiBaseURI; if (platform) apiBaseURI = platform.apiBaseURI; if (options && options.apiBaseURI) apiBaseURI = options.apiBaseURI; if (! apiBaseURI) apiBaseURI = API_BASE_URI; this.options.wsdl_url = apiBaseURI + WSDL_URL_PATH; } /** * @name discoveryMode * @type {boolean} * @memberof module:plugins/polling-updater~PollingTagUpdater# */ Object.defineProperty(this, "discoveryMode", { enumerable: true, get: function() { return this.options.discoveryMode }, set: function(v) { this.options.discoveryMode = v } }); let h = this.stopUpdateLoop.bind(this); /** * @name platform * @type {WirelessTagPlatform} * @memberof module:plugins/polling-updater~PollingTagUpdater# */ Object.defineProperty(this, "platform", { enumerable: true, get: function() { return this._platform }, set: function(p) { if (this._platform && this._platform !== p) { this._platform.removeListener('disconnect', h); if (this.options.log === this._platform.log) { this.options.log = undefined; } } this._platform = p; if (p) { if (! this.options.log) this.options.log = p.log; p.on('disconnect', h); } } }); this.platform = platform; /** @member {WirelessTagPlatform~factory} */ this.factory = this.options.factory; }
[ "function", "PollingTagUpdater", "(", "platform", ",", "options", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "tagsByUUID", "=", "{", "}", ";", "this", ".", "options", "=", "Object", ".", "assign", "(", "{", "}", ",", "options", ")", ";", "if", "(", "!", "this", ".", "options", ".", "wsdl_url", ")", "{", "let", "apiBaseURI", ";", "if", "(", "platform", ")", "apiBaseURI", "=", "platform", ".", "apiBaseURI", ";", "if", "(", "options", "&&", "options", ".", "apiBaseURI", ")", "apiBaseURI", "=", "options", ".", "apiBaseURI", ";", "if", "(", "!", "apiBaseURI", ")", "apiBaseURI", "=", "API_BASE_URI", ";", "this", ".", "options", ".", "wsdl_url", "=", "apiBaseURI", "+", "WSDL_URL_PATH", ";", "}", "/**\n * @name discoveryMode\n * @type {boolean}\n * @memberof module:plugins/polling-updater~PollingTagUpdater#\n */", "Object", ".", "defineProperty", "(", "this", ",", "\"discoveryMode\"", ",", "{", "enumerable", ":", "true", ",", "get", ":", "function", "(", ")", "{", "return", "this", ".", "options", ".", "discoveryMode", "}", ",", "set", ":", "function", "(", "v", ")", "{", "this", ".", "options", ".", "discoveryMode", "=", "v", "}", "}", ")", ";", "let", "h", "=", "this", ".", "stopUpdateLoop", ".", "bind", "(", "this", ")", ";", "/**\n * @name platform\n * @type {WirelessTagPlatform}\n * @memberof module:plugins/polling-updater~PollingTagUpdater#\n */", "Object", ".", "defineProperty", "(", "this", ",", "\"platform\"", ",", "{", "enumerable", ":", "true", ",", "get", ":", "function", "(", ")", "{", "return", "this", ".", "_platform", "}", ",", "set", ":", "function", "(", "p", ")", "{", "if", "(", "this", ".", "_platform", "&&", "this", ".", "_platform", "!==", "p", ")", "{", "this", ".", "_platform", ".", "removeListener", "(", "'disconnect'", ",", "h", ")", ";", "if", "(", "this", ".", "options", ".", "log", "===", "this", ".", "_platform", ".", "log", ")", "{", "this", ".", "options", ".", "log", "=", "undefined", ";", "}", "}", "this", ".", "_platform", "=", "p", ";", "if", "(", "p", ")", "{", "if", "(", "!", "this", ".", "options", ".", "log", ")", "this", ".", "options", ".", "log", "=", "p", ".", "log", ";", "p", ".", "on", "(", "'disconnect'", ",", "h", ")", ";", "}", "}", "}", ")", ";", "this", ".", "platform", "=", "platform", ";", "/** @member {WirelessTagPlatform~factory} */", "this", ".", "factory", "=", "this", ".", "options", ".", "factory", ";", "}" ]
Creates the updater instance. @param {WirelessTagPlatform} [platform] - Platform object through which tags to be updated were (or are going to be) found (or created in discovery mode). In normal mode, this is only used to possibly override configuration options, specifically the base URI for the cloud API endpoints. For discovery mode to work, either this or `options.factory` must be provided. @param {object} [options] - overriding configuration options @param {string} [options.wsdl_url] - the full path for obtaining the WSDL for the SOAP service to be polled (default: [WSDL_URL_PATH]{@link module:plugins/polling-updater~WSDL_URL_PATH}) @param {string} [options.apiBaseURI] - the base URI to use for API endpoints (default: [API_BASE_URI]{@link module:plugins/polling-updater~API_BASE_URI}) @param {boolean} [options.discoveryMode] - whether to run in discovery mode or not. Defaults to `false`. @param {WirelessTagPlatform~factory} [options.factory] - the tag and tag manager object factory to use in discovery mode. Either this, or the `platform` parameter must be provided for discovery mode to work. @constructor
[ "Creates", "the", "updater", "instance", "." ]
ce63485ce37b33f552ceb2939740a40957a416f3
https://github.com/hlapp/wirelesstags-js/blob/ce63485ce37b33f552ceb2939740a40957a416f3/plugins/polling-updater.js#L99-L149
46,385
hlapp/wirelesstags-js
plugins/polling-updater.js
updateTag
function updateTag(tag, tagData) { // if not a valid object for receiving updates, we are done if (! tag) return; // check that this is the current tag manager if (tagData.mac && (tag.wirelessTagManager.mac !== tagData.mac)) { throw new Error("expected tag " + tag.uuid + " to be with tag manager " + tag.mac + " but is reported to be with " + tagData.mac); } // we don't currently have anything more to do for the extra properties // identifying the tag manager, so simply get rid of them managerProps.forEach((k) => { delete tagData[k] }); // almost done tag.data = tagData; }
javascript
function updateTag(tag, tagData) { // if not a valid object for receiving updates, we are done if (! tag) return; // check that this is the current tag manager if (tagData.mac && (tag.wirelessTagManager.mac !== tagData.mac)) { throw new Error("expected tag " + tag.uuid + " to be with tag manager " + tag.mac + " but is reported to be with " + tagData.mac); } // we don't currently have anything more to do for the extra properties // identifying the tag manager, so simply get rid of them managerProps.forEach((k) => { delete tagData[k] }); // almost done tag.data = tagData; }
[ "function", "updateTag", "(", "tag", ",", "tagData", ")", "{", "// if not a valid object for receiving updates, we are done", "if", "(", "!", "tag", ")", "return", ";", "// check that this is the current tag manager", "if", "(", "tagData", ".", "mac", "&&", "(", "tag", ".", "wirelessTagManager", ".", "mac", "!==", "tagData", ".", "mac", ")", ")", "{", "throw", "new", "Error", "(", "\"expected tag \"", "+", "tag", ".", "uuid", "+", "\" to be with tag manager \"", "+", "tag", ".", "mac", "+", "\" but is reported to be with \"", "+", "tagData", ".", "mac", ")", ";", "}", "// we don't currently have anything more to do for the extra properties", "// identifying the tag manager, so simply get rid of them", "managerProps", ".", "forEach", "(", "(", "k", ")", "=>", "{", "delete", "tagData", "[", "k", "]", "}", ")", ";", "// almost done", "tag", ".", "data", "=", "tagData", ";", "}" ]
Updates the tag corresponding to the given tag data. Does nothing if the respective tag is undefined or null. @param {WirelessTag} tag - the tag object to be updated @param {object} tagData - the data to update the tag object with; this is normally returned from the API endpoint @private
[ "Updates", "the", "tag", "corresponding", "to", "the", "given", "tag", "data", ".", "Does", "nothing", "if", "the", "respective", "tag", "is", "undefined", "or", "null", "." ]
ce63485ce37b33f552ceb2939740a40957a416f3
https://github.com/hlapp/wirelesstags-js/blob/ce63485ce37b33f552ceb2939740a40957a416f3/plugins/polling-updater.js#L338-L352
46,386
hlapp/wirelesstags-js
plugins/polling-updater.js
createTag
function createTag(tagData, platform, factory) { let mgrData = {}; managerProps.forEach((k) => { let mk = k.replace(/^manager([A-Z])/, '$1'); if (mk !== k) mk = mk.toLowerCase(); mgrData[mk] = tagData[k]; delete tagData[k]; }); if (! platform) platform = {}; if (! factory) factory = platform.factory; if (! factory) throw new TypeError("must have valid platform object or " + "object factory in discovery mode"); let mgrProm = platform.findTagManager ? platform.findTagManager(mgrData.mac) : Promise.resolve(factory.createTagManager(mgrData)); return mgrProm.then((mgr) => { if (! mgr) throw new Error("no such tag manager: " + mgrData.mac); return factory.createTag(mgr, tagData); }); }
javascript
function createTag(tagData, platform, factory) { let mgrData = {}; managerProps.forEach((k) => { let mk = k.replace(/^manager([A-Z])/, '$1'); if (mk !== k) mk = mk.toLowerCase(); mgrData[mk] = tagData[k]; delete tagData[k]; }); if (! platform) platform = {}; if (! factory) factory = platform.factory; if (! factory) throw new TypeError("must have valid platform object or " + "object factory in discovery mode"); let mgrProm = platform.findTagManager ? platform.findTagManager(mgrData.mac) : Promise.resolve(factory.createTagManager(mgrData)); return mgrProm.then((mgr) => { if (! mgr) throw new Error("no such tag manager: " + mgrData.mac); return factory.createTag(mgr, tagData); }); }
[ "function", "createTag", "(", "tagData", ",", "platform", ",", "factory", ")", "{", "let", "mgrData", "=", "{", "}", ";", "managerProps", ".", "forEach", "(", "(", "k", ")", "=>", "{", "let", "mk", "=", "k", ".", "replace", "(", "/", "^manager([A-Z])", "/", ",", "'$1'", ")", ";", "if", "(", "mk", "!==", "k", ")", "mk", "=", "mk", ".", "toLowerCase", "(", ")", ";", "mgrData", "[", "mk", "]", "=", "tagData", "[", "k", "]", ";", "delete", "tagData", "[", "k", "]", ";", "}", ")", ";", "if", "(", "!", "platform", ")", "platform", "=", "{", "}", ";", "if", "(", "!", "factory", ")", "factory", "=", "platform", ".", "factory", ";", "if", "(", "!", "factory", ")", "throw", "new", "TypeError", "(", "\"must have valid platform object or \"", "+", "\"object factory in discovery mode\"", ")", ";", "let", "mgrProm", "=", "platform", ".", "findTagManager", "?", "platform", ".", "findTagManager", "(", "mgrData", ".", "mac", ")", ":", "Promise", ".", "resolve", "(", "factory", ".", "createTagManager", "(", "mgrData", ")", ")", ";", "return", "mgrProm", ".", "then", "(", "(", "mgr", ")", "=>", "{", "if", "(", "!", "mgr", ")", "throw", "new", "Error", "(", "\"no such tag manager: \"", "+", "mgrData", ".", "mac", ")", ";", "return", "factory", ".", "createTag", "(", "mgr", ",", "tagData", ")", ";", "}", ")", ";", "}" ]
Creates a tag object from the given attribute data object, and returns it. @param {object} tagData - the attribute data object as returned by the polling API endpoint @param {WirelessTagPlatform} platform - the platform instance for creating tag and tag manager objects. If the value does not provide a factory, `factory` must be provided. @param {WirelessTagPlatform~factory} [factory] - the tag and tag manager object factory to use @returns {WirelessTag} @private
[ "Creates", "a", "tag", "object", "from", "the", "given", "attribute", "data", "object", "and", "returns", "it", "." ]
ce63485ce37b33f552ceb2939740a40957a416f3
https://github.com/hlapp/wirelesstags-js/blob/ce63485ce37b33f552ceb2939740a40957a416f3/plugins/polling-updater.js#L367-L386
46,387
hlapp/wirelesstags-js
plugins/polling-updater.js
createSoapClient
function createSoapClient(opts) { let wsdl = opts && opts.wsdl_url ? opts.wsdl_url : API_BASE_URI + WSDL_URL_PATH; let clientOpts = { request: request.defaults({ jar: true, gzip: true }) }; return new Promise((resolve, reject) => { soap.createClient(wsdl, clientOpts, (err, client) => { if (err) return reject(err); resolve(client); }); }); }
javascript
function createSoapClient(opts) { let wsdl = opts && opts.wsdl_url ? opts.wsdl_url : API_BASE_URI + WSDL_URL_PATH; let clientOpts = { request: request.defaults({ jar: true, gzip: true }) }; return new Promise((resolve, reject) => { soap.createClient(wsdl, clientOpts, (err, client) => { if (err) return reject(err); resolve(client); }); }); }
[ "function", "createSoapClient", "(", "opts", ")", "{", "let", "wsdl", "=", "opts", "&&", "opts", ".", "wsdl_url", "?", "opts", ".", "wsdl_url", ":", "API_BASE_URI", "+", "WSDL_URL_PATH", ";", "let", "clientOpts", "=", "{", "request", ":", "request", ".", "defaults", "(", "{", "jar", ":", "true", ",", "gzip", ":", "true", "}", ")", "}", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "soap", ".", "createClient", "(", "wsdl", ",", "clientOpts", ",", "(", "err", ",", "client", ")", "=>", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "resolve", "(", "client", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Creates the SOAP client, using the supplied options for locating the WSDL document for the endpoint. @param {object} [opts] - WSDL and SOAP endpoint options @param {string} [opts.wsdl_url] - the URL from which to fetch the WSDL document; defaults to the concatenation of [API_BASE_URI]{@link module:plugins/polling-updater~API_BASE_URI} and [WSDL_URL_PATH]{@link module:plugins/polling-updater~WSDL_URL_PATH} @returns {Promise} On success, resolves to the created SOAP client object @private
[ "Creates", "the", "SOAP", "client", "using", "the", "supplied", "options", "for", "locating", "the", "WSDL", "document", "for", "the", "endpoint", "." ]
ce63485ce37b33f552ceb2939740a40957a416f3
https://github.com/hlapp/wirelesstags-js/blob/ce63485ce37b33f552ceb2939740a40957a416f3/plugins/polling-updater.js#L403-L413
46,388
hlapp/wirelesstags-js
plugins/polling-updater.js
pollForNextUpdate
function pollForNextUpdate(client, tagManager, callback) { let req = new Promise((resolve, reject) => { let methodName = tagManager ? "GetNextUpdateForAllManagersOnDB" : "GetNextUpdateForAllManagers"; let soapMethod = client[methodName]; let args = {}; if (tagManager) args.dbid = tagManager.dbid; soapMethod(args, function(err, result) { if (err) return reject(err); let tagDataList = JSON.parse(result[methodName + "Result"]); try { if (callback) callback(null, { object: tagManager, value: tagDataList }); } catch (e) { logError(console, e); // no good reason to escalate an error thrown by callback } resolve(tagDataList); }); }); if (callback) { req = req.catch((err) => { callback(err); throw err; }); } return req; }
javascript
function pollForNextUpdate(client, tagManager, callback) { let req = new Promise((resolve, reject) => { let methodName = tagManager ? "GetNextUpdateForAllManagersOnDB" : "GetNextUpdateForAllManagers"; let soapMethod = client[methodName]; let args = {}; if (tagManager) args.dbid = tagManager.dbid; soapMethod(args, function(err, result) { if (err) return reject(err); let tagDataList = JSON.parse(result[methodName + "Result"]); try { if (callback) callback(null, { object: tagManager, value: tagDataList }); } catch (e) { logError(console, e); // no good reason to escalate an error thrown by callback } resolve(tagDataList); }); }); if (callback) { req = req.catch((err) => { callback(err); throw err; }); } return req; }
[ "function", "pollForNextUpdate", "(", "client", ",", "tagManager", ",", "callback", ")", "{", "let", "req", "=", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "let", "methodName", "=", "tagManager", "?", "\"GetNextUpdateForAllManagersOnDB\"", ":", "\"GetNextUpdateForAllManagers\"", ";", "let", "soapMethod", "=", "client", "[", "methodName", "]", ";", "let", "args", "=", "{", "}", ";", "if", "(", "tagManager", ")", "args", ".", "dbid", "=", "tagManager", ".", "dbid", ";", "soapMethod", "(", "args", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "let", "tagDataList", "=", "JSON", ".", "parse", "(", "result", "[", "methodName", "+", "\"Result\"", "]", ")", ";", "try", "{", "if", "(", "callback", ")", "callback", "(", "null", ",", "{", "object", ":", "tagManager", ",", "value", ":", "tagDataList", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "logError", "(", "console", ",", "e", ")", ";", "// no good reason to escalate an error thrown by callback", "}", "resolve", "(", "tagDataList", ")", ";", "}", ")", ";", "}", ")", ";", "if", "(", "callback", ")", "{", "req", "=", "req", ".", "catch", "(", "(", "err", ")", "=>", "{", "callback", "(", "err", ")", ";", "throw", "err", ";", "}", ")", ";", "}", "return", "req", ";", "}" ]
Polls the API endpoint for available updates and returns them. @param {object} client - the SOAP client object @param {WirelessTagManager} [tagManager] - the tag manager to which to restrict updates @param {module:wirelesstags~apiCallback} [callback] - if provided, the `tagManager` parameter must be provided too (even if as undefined or null) @returns {Promise} On success, resolves to an array of tag data objects @private
[ "Polls", "the", "API", "endpoint", "for", "available", "updates", "and", "returns", "them", "." ]
ce63485ce37b33f552ceb2939740a40957a416f3
https://github.com/hlapp/wirelesstags-js/blob/ce63485ce37b33f552ceb2939740a40957a416f3/plugins/polling-updater.js#L429-L457
46,389
hlapp/wirelesstags-js
plugins/polling-updater.js
logError
function logError(log, err) { let debug = log.debug || log.trace || log.log; if (err.Fault) { log.error(err.Fault); if (err.response && err.response.request) { log.error("URL: " + err.response.request.href); } if (err.body) debug(err.body); } else { log.error(err.stack ? err.stack : err); } }
javascript
function logError(log, err) { let debug = log.debug || log.trace || log.log; if (err.Fault) { log.error(err.Fault); if (err.response && err.response.request) { log.error("URL: " + err.response.request.href); } if (err.body) debug(err.body); } else { log.error(err.stack ? err.stack : err); } }
[ "function", "logError", "(", "log", ",", "err", ")", "{", "let", "debug", "=", "log", ".", "debug", "||", "log", ".", "trace", "||", "log", ".", "log", ";", "if", "(", "err", ".", "Fault", ")", "{", "log", ".", "error", "(", "err", ".", "Fault", ")", ";", "if", "(", "err", ".", "response", "&&", "err", ".", "response", ".", "request", ")", "{", "log", ".", "error", "(", "\"URL: \"", "+", "err", ".", "response", ".", "request", ".", "href", ")", ";", "}", "if", "(", "err", ".", "body", ")", "debug", "(", "err", ".", "body", ")", ";", "}", "else", "{", "log", ".", "error", "(", "err", ".", "stack", "?", "err", ".", "stack", ":", "err", ")", ";", "}", "}" ]
Logs the given error to the given log facility. @private
[ "Logs", "the", "given", "error", "to", "the", "given", "log", "facility", "." ]
ce63485ce37b33f552ceb2939740a40957a416f3
https://github.com/hlapp/wirelesstags-js/blob/ce63485ce37b33f552ceb2939740a40957a416f3/plugins/polling-updater.js#L464-L475
46,390
cristidraghici/sync-sql
lib/worker.js
function (connectionInfo, query, params) { var connection, client = new pg.Client(connectionInfo); client.connect(function (err) { if (err) { return respond({ success: false, data: { err: err, query: query, connection: connectionInfo } }); } // execute a query on our database client.query(query, params, function (err, result) { // close the client client.end(); // treat the error if (err) { return respond({ success: false, data: { err: err, query: query, connection: connectionInfo } }); } // Return the respose return respond({ success: true, data: result }); }); }); }
javascript
function (connectionInfo, query, params) { var connection, client = new pg.Client(connectionInfo); client.connect(function (err) { if (err) { return respond({ success: false, data: { err: err, query: query, connection: connectionInfo } }); } // execute a query on our database client.query(query, params, function (err, result) { // close the client client.end(); // treat the error if (err) { return respond({ success: false, data: { err: err, query: query, connection: connectionInfo } }); } // Return the respose return respond({ success: true, data: result }); }); }); }
[ "function", "(", "connectionInfo", ",", "query", ",", "params", ")", "{", "var", "connection", ",", "client", "=", "new", "pg", ".", "Client", "(", "connectionInfo", ")", ";", "client", ".", "connect", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "respond", "(", "{", "success", ":", "false", ",", "data", ":", "{", "err", ":", "err", ",", "query", ":", "query", ",", "connection", ":", "connectionInfo", "}", "}", ")", ";", "}", "// execute a query on our database", "client", ".", "query", "(", "query", ",", "params", ",", "function", "(", "err", ",", "result", ")", "{", "// close the client", "client", ".", "end", "(", ")", ";", "// treat the error", "if", "(", "err", ")", "{", "return", "respond", "(", "{", "success", ":", "false", ",", "data", ":", "{", "err", ":", "err", ",", "query", ":", "query", ",", "connection", ":", "connectionInfo", "}", "}", ")", ";", "}", "// Return the respose", "return", "respond", "(", "{", "success", ":", "true", ",", "data", ":", "result", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Execute postresql query @param {object} connectionInfo Object containing information about the connection @param {string} query The query to execute @param {Array} params Params to use in the query @returns {mixed} Void
[ "Execute", "postresql", "query" ]
1fa5d16aa9d47f81802f8796c8255452ece73804
https://github.com/cristidraghici/sync-sql/blob/1fa5d16aa9d47f81802f8796c8255452ece73804/lib/worker.js#L27-L67
46,391
cristidraghici/sync-sql
lib/worker.js
function (connectionInfo, query, params) { var connection; // Connection validation if (typeof connectionInfo.host !== 'string' || connectionInfo.host.length === 0) { return respond({ success: false, data: { err: 'Bad hostname provided.', query: query, connection: connectionInfo } }); } if (typeof connectionInfo.user !== 'string' || connectionInfo.user.length === 0) { return respond({ success: false, data: { err: 'Bad username provided.', query: query, connection: connectionInfo } }); } if (typeof connectionInfo.password !== 'string') { return respond({ success: false, data: { err: 'Bad password provided.', query: query, connection: connectionInfo } }); } if (typeof connectionInfo.database !== 'string' || connectionInfo.database.length === 0) { return respond({ success: false, data: { err: 'Bad database provided.', query: query, connection: connectionInfo } }); } // Return if no sql query specified if (query.length === 0) { return respond({ success: false, data: { err: 'No SQL query specified.' } }); } // Create the connection to the database connection = mysql.createConnection(connectionInfo); // Connect to the database connection.connect(); // Do the query connection.query(query, params, function (err, rows, fields) { // End the connection connection.end(); // Return the error and stop if (err) { return respond({ success: false, data: { err: err, query: query, connection: connectionInfo } }); } // Do the callback respond({ success: true, data: { rows: rows, fields: fields } }); }); }
javascript
function (connectionInfo, query, params) { var connection; // Connection validation if (typeof connectionInfo.host !== 'string' || connectionInfo.host.length === 0) { return respond({ success: false, data: { err: 'Bad hostname provided.', query: query, connection: connectionInfo } }); } if (typeof connectionInfo.user !== 'string' || connectionInfo.user.length === 0) { return respond({ success: false, data: { err: 'Bad username provided.', query: query, connection: connectionInfo } }); } if (typeof connectionInfo.password !== 'string') { return respond({ success: false, data: { err: 'Bad password provided.', query: query, connection: connectionInfo } }); } if (typeof connectionInfo.database !== 'string' || connectionInfo.database.length === 0) { return respond({ success: false, data: { err: 'Bad database provided.', query: query, connection: connectionInfo } }); } // Return if no sql query specified if (query.length === 0) { return respond({ success: false, data: { err: 'No SQL query specified.' } }); } // Create the connection to the database connection = mysql.createConnection(connectionInfo); // Connect to the database connection.connect(); // Do the query connection.query(query, params, function (err, rows, fields) { // End the connection connection.end(); // Return the error and stop if (err) { return respond({ success: false, data: { err: err, query: query, connection: connectionInfo } }); } // Do the callback respond({ success: true, data: { rows: rows, fields: fields } }); }); }
[ "function", "(", "connectionInfo", ",", "query", ",", "params", ")", "{", "var", "connection", ";", "// Connection validation", "if", "(", "typeof", "connectionInfo", ".", "host", "!==", "'string'", "||", "connectionInfo", ".", "host", ".", "length", "===", "0", ")", "{", "return", "respond", "(", "{", "success", ":", "false", ",", "data", ":", "{", "err", ":", "'Bad hostname provided.'", ",", "query", ":", "query", ",", "connection", ":", "connectionInfo", "}", "}", ")", ";", "}", "if", "(", "typeof", "connectionInfo", ".", "user", "!==", "'string'", "||", "connectionInfo", ".", "user", ".", "length", "===", "0", ")", "{", "return", "respond", "(", "{", "success", ":", "false", ",", "data", ":", "{", "err", ":", "'Bad username provided.'", ",", "query", ":", "query", ",", "connection", ":", "connectionInfo", "}", "}", ")", ";", "}", "if", "(", "typeof", "connectionInfo", ".", "password", "!==", "'string'", ")", "{", "return", "respond", "(", "{", "success", ":", "false", ",", "data", ":", "{", "err", ":", "'Bad password provided.'", ",", "query", ":", "query", ",", "connection", ":", "connectionInfo", "}", "}", ")", ";", "}", "if", "(", "typeof", "connectionInfo", ".", "database", "!==", "'string'", "||", "connectionInfo", ".", "database", ".", "length", "===", "0", ")", "{", "return", "respond", "(", "{", "success", ":", "false", ",", "data", ":", "{", "err", ":", "'Bad database provided.'", ",", "query", ":", "query", ",", "connection", ":", "connectionInfo", "}", "}", ")", ";", "}", "// Return if no sql query specified", "if", "(", "query", ".", "length", "===", "0", ")", "{", "return", "respond", "(", "{", "success", ":", "false", ",", "data", ":", "{", "err", ":", "'No SQL query specified.'", "}", "}", ")", ";", "}", "// Create the connection to the database", "connection", "=", "mysql", ".", "createConnection", "(", "connectionInfo", ")", ";", "// Connect to the database", "connection", ".", "connect", "(", ")", ";", "// Do the query", "connection", ".", "query", "(", "query", ",", "params", ",", "function", "(", "err", ",", "rows", ",", "fields", ")", "{", "// End the connection", "connection", ".", "end", "(", ")", ";", "// Return the error and stop", "if", "(", "err", ")", "{", "return", "respond", "(", "{", "success", ":", "false", ",", "data", ":", "{", "err", ":", "err", ",", "query", ":", "query", ",", "connection", ":", "connectionInfo", "}", "}", ")", ";", "}", "// Do the callback", "respond", "(", "{", "success", ":", "true", ",", "data", ":", "{", "rows", ":", "rows", ",", "fields", ":", "fields", "}", "}", ")", ";", "}", ")", ";", "}" ]
Execute mysql query @param {object} connectionInfo Object containing information about the connection @param {string} query The query to execute @param {Array} params Params to use in the query @returns {mixed} Void
[ "Execute", "mysql", "query" ]
1fa5d16aa9d47f81802f8796c8255452ece73804
https://github.com/cristidraghici/sync-sql/blob/1fa5d16aa9d47f81802f8796c8255452ece73804/lib/worker.js#L76-L166
46,392
NiklasGollenstede/web-ext-utils
utils/inject.js
injectAsync
function injectAsync(_function, ...args) { return new Promise((resolve, reject) => { if (typeof _function !== 'function') { throw new TypeError('Injecting a string is a form of eval()'); } const { document, } = (this || global); // call with an iframe.contentWindow as this to inject into its context const script = document.createElement('script'); script.dataset.args = JSON.stringify(args); script.dataset.source = _function +''; // get the functions source script.textContent = (`(`+ function (script) { const args = JSON.parse(script.dataset.args); const _function = new Function('return ('+ script.dataset.source +').apply(this, arguments);'); script.dataset.done = true; Promise.resolve().then(() => _function.apply(this, args)) // eslint-disable-line no-invalid-this .then(value => report('value', value)) .catch(error => report('error', error)); function report(type, value) { value = type === 'error' && (value instanceof Error) ? '$_ERROR_$'+ JSON.stringify({ name: value.name, message: value.message, stack: value.stack, }) : JSON.stringify(value); script.dispatchEvent(new this.CustomEvent(type, { detail: value, })); // eslint-disable-line no-invalid-this } } +`).call(this, document.currentScript)`); document.documentElement.appendChild(script).remove(); // evaluates .textContent synchronously in the page context if (!script.dataset.done) { throw new EvalError('Script was not executed at all'); // may fail due to sandboxing or CSP } function reported({ type, detail: value, }) { if (typeof value !== 'string') { throw new Error(`Unexpected event value type in injectAsync`); } switch (type) { case 'value': { resolve(JSON.parse(value)); } break; case 'error': { reject(parseError(value)); } break; default: { throw new Error(`Unexpected event "${ type }" in injectAsync`); } } script.removeEventListener('value', reported); script.removeEventListener('error', reported); } script.addEventListener('value', reported); script.addEventListener('error', reported); }); }
javascript
function injectAsync(_function, ...args) { return new Promise((resolve, reject) => { if (typeof _function !== 'function') { throw new TypeError('Injecting a string is a form of eval()'); } const { document, } = (this || global); // call with an iframe.contentWindow as this to inject into its context const script = document.createElement('script'); script.dataset.args = JSON.stringify(args); script.dataset.source = _function +''; // get the functions source script.textContent = (`(`+ function (script) { const args = JSON.parse(script.dataset.args); const _function = new Function('return ('+ script.dataset.source +').apply(this, arguments);'); script.dataset.done = true; Promise.resolve().then(() => _function.apply(this, args)) // eslint-disable-line no-invalid-this .then(value => report('value', value)) .catch(error => report('error', error)); function report(type, value) { value = type === 'error' && (value instanceof Error) ? '$_ERROR_$'+ JSON.stringify({ name: value.name, message: value.message, stack: value.stack, }) : JSON.stringify(value); script.dispatchEvent(new this.CustomEvent(type, { detail: value, })); // eslint-disable-line no-invalid-this } } +`).call(this, document.currentScript)`); document.documentElement.appendChild(script).remove(); // evaluates .textContent synchronously in the page context if (!script.dataset.done) { throw new EvalError('Script was not executed at all'); // may fail due to sandboxing or CSP } function reported({ type, detail: value, }) { if (typeof value !== 'string') { throw new Error(`Unexpected event value type in injectAsync`); } switch (type) { case 'value': { resolve(JSON.parse(value)); } break; case 'error': { reject(parseError(value)); } break; default: { throw new Error(`Unexpected event "${ type }" in injectAsync`); } } script.removeEventListener('value', reported); script.removeEventListener('error', reported); } script.addEventListener('value', reported); script.addEventListener('error', reported); }); }
[ "function", "injectAsync", "(", "_function", ",", "...", "args", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "typeof", "_function", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", "'Injecting a string is a form of eval()'", ")", ";", "}", "const", "{", "document", ",", "}", "=", "(", "this", "||", "global", ")", ";", "// call with an iframe.contentWindow as this to inject into its context", "const", "script", "=", "document", ".", "createElement", "(", "'script'", ")", ";", "script", ".", "dataset", ".", "args", "=", "JSON", ".", "stringify", "(", "args", ")", ";", "script", ".", "dataset", ".", "source", "=", "_function", "+", "''", ";", "// get the functions source", "script", ".", "textContent", "=", "(", "`", "`", "+", "function", "(", "script", ")", "{", "const", "args", "=", "JSON", ".", "parse", "(", "script", ".", "dataset", ".", "args", ")", ";", "const", "_function", "=", "new", "Function", "(", "'return ('", "+", "script", ".", "dataset", ".", "source", "+", "').apply(this, arguments);'", ")", ";", "script", ".", "dataset", ".", "done", "=", "true", ";", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "_function", ".", "apply", "(", "this", ",", "args", ")", ")", "// eslint-disable-line no-invalid-this", ".", "then", "(", "value", "=>", "report", "(", "'value'", ",", "value", ")", ")", ".", "catch", "(", "error", "=>", "report", "(", "'error'", ",", "error", ")", ")", ";", "function", "report", "(", "type", ",", "value", ")", "{", "value", "=", "type", "===", "'error'", "&&", "(", "value", "instanceof", "Error", ")", "?", "'$_ERROR_$'", "+", "JSON", ".", "stringify", "(", "{", "name", ":", "value", ".", "name", ",", "message", ":", "value", ".", "message", ",", "stack", ":", "value", ".", "stack", ",", "}", ")", ":", "JSON", ".", "stringify", "(", "value", ")", ";", "script", ".", "dispatchEvent", "(", "new", "this", ".", "CustomEvent", "(", "type", ",", "{", "detail", ":", "value", ",", "}", ")", ")", ";", "// eslint-disable-line no-invalid-this", "}", "}", "+", "`", "`", ")", ";", "document", ".", "documentElement", ".", "appendChild", "(", "script", ")", ".", "remove", "(", ")", ";", "// evaluates .textContent synchronously in the page context", "if", "(", "!", "script", ".", "dataset", ".", "done", ")", "{", "throw", "new", "EvalError", "(", "'Script was not executed at all'", ")", ";", "// may fail due to sandboxing or CSP", "}", "function", "reported", "(", "{", "type", ",", "detail", ":", "value", ",", "}", ")", "{", "if", "(", "typeof", "value", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "`", "`", ")", ";", "}", "switch", "(", "type", ")", "{", "case", "'value'", ":", "{", "resolve", "(", "JSON", ".", "parse", "(", "value", ")", ")", ";", "}", "break", ";", "case", "'error'", ":", "{", "reject", "(", "parseError", "(", "value", ")", ")", ";", "}", "break", ";", "default", ":", "{", "throw", "new", "Error", "(", "`", "${", "type", "}", "`", ")", ";", "}", "}", "script", ".", "removeEventListener", "(", "'value'", ",", "reported", ")", ";", "script", ".", "removeEventListener", "(", "'error'", ",", "reported", ")", ";", "}", "script", ".", "addEventListener", "(", "'value'", ",", "reported", ")", ";", "script", ".", "addEventListener", "(", "'error'", ",", "reported", ")", ";", "}", ")", ";", "}" ]
Same as `inject`, only that it executes `_function` asynchronously, allows `_function` to return a Promise, and that it returns a Promise to that value. The calling overhead is even greater than that of the synchronous `inject`. @this {Window}
[ "Same", "as", "inject", "only", "that", "it", "executes", "_function", "asynchronously", "allows", "_function", "to", "return", "a", "Promise", "and", "that", "it", "returns", "a", "Promise", "to", "that", "value", ".", "The", "calling", "overhead", "is", "even", "greater", "than", "that", "of", "the", "synchronous", "inject", "." ]
395698c633da88db86377d583b9b4eac6d9cc299
https://github.com/NiklasGollenstede/web-ext-utils/blob/395698c633da88db86377d583b9b4eac6d9cc299/utils/inject.js#L56-L101
46,393
winkerVSbecks/draper
dist/build.js
remScale
function remScale(config){ return R.compose( R.merge(config), R.converge(R.merge,[ toRems(config.rem,'scale'), toRems(config.rem,'typeScale')]))( config); }
javascript
function remScale(config){ return R.compose( R.merge(config), R.converge(R.merge,[ toRems(config.rem,'scale'), toRems(config.rem,'typeScale')]))( config); }
[ "function", "remScale", "(", "config", ")", "{", "return", "R", ".", "compose", "(", "R", ".", "merge", "(", "config", ")", ",", "R", ".", "converge", "(", "R", ".", "merge", ",", "[", "toRems", "(", "config", ".", "rem", ",", "'scale'", ")", ",", "toRems", "(", "config", ".", "rem", ",", "'typeScale'", ")", "]", ")", ")", "(", "config", ")", ";", "}" ]
Convert the scale and typescale to rems
[ "Convert", "the", "scale", "and", "typescale", "to", "rems" ]
1648dce7c2252a8beea9e8a7faecc7b4129f2244
https://github.com/winkerVSbecks/draper/blob/1648dce7c2252a8beea9e8a7faecc7b4129f2244/dist/build.js#L62-L70
46,394
winkerVSbecks/draper
dist/build.js
extendConfig
function extendConfig(options){ return R.mapObjIndexed(function(prop,type){return( prop(options[type]));},extendOps); }
javascript
function extendConfig(options){ return R.mapObjIndexed(function(prop,type){return( prop(options[type]));},extendOps); }
[ "function", "extendConfig", "(", "options", ")", "{", "return", "R", ".", "mapObjIndexed", "(", "function", "(", "prop", ",", "type", ")", "{", "return", "(", "prop", "(", "options", "[", "type", "]", ")", ")", ";", "}", ",", "extendOps", ")", ";", "}" ]
Customize base config
[ "Customize", "base", "config" ]
1648dce7c2252a8beea9e8a7faecc7b4129f2244
https://github.com/winkerVSbecks/draper/blob/1648dce7c2252a8beea9e8a7faecc7b4129f2244/dist/build.js#L75-L78
46,395
ericnishio/finnish-holidays-js
lib/date-utils.js
function(year, month, day) { var date = new Date(Date.UTC(year, month - 1, day)); return date; }
javascript
function(year, month, day) { var date = new Date(Date.UTC(year, month - 1, day)); return date; }
[ "function", "(", "year", ",", "month", ",", "day", ")", "{", "var", "date", "=", "new", "Date", "(", "Date", ".", "UTC", "(", "year", ",", "month", "-", "1", ",", "day", ")", ")", ";", "return", "date", ";", "}" ]
Creates a date. @param {number} year @param {number} month @param {number} day @return {Date}
[ "Creates", "a", "date", "." ]
33416bd96b18bf7b18c331c831212aefb2a6f9c2
https://github.com/ericnishio/finnish-holidays-js/blob/33416bd96b18bf7b18c331c831212aefb2a6f9c2/lib/date-utils.js#L13-L16
46,396
ericnishio/finnish-holidays-js
lib/date-utils.js
function(year, month, day) { var dayOfWeek = this.createDate(year, month, day).getDay(); return dayOfWeek === this.SATURDAY || dayOfWeek === this.SUNDAY; }
javascript
function(year, month, day) { var dayOfWeek = this.createDate(year, month, day).getDay(); return dayOfWeek === this.SATURDAY || dayOfWeek === this.SUNDAY; }
[ "function", "(", "year", ",", "month", ",", "day", ")", "{", "var", "dayOfWeek", "=", "this", ".", "createDate", "(", "year", ",", "month", ",", "day", ")", ".", "getDay", "(", ")", ";", "return", "dayOfWeek", "===", "this", ".", "SATURDAY", "||", "dayOfWeek", "===", "this", ".", "SUNDAY", ";", "}" ]
Checks if a date falls on a weekend. @param {number} year @param {number} month @param {number} day @return {boolean}
[ "Checks", "if", "a", "date", "falls", "on", "a", "weekend", "." ]
33416bd96b18bf7b18c331c831212aefb2a6f9c2
https://github.com/ericnishio/finnish-holidays-js/blob/33416bd96b18bf7b18c331c831212aefb2a6f9c2/lib/date-utils.js#L89-L92
46,397
ericnishio/finnish-holidays-js
lib/date-utils.js
function(year) { var a = year % 19; var b = Math.floor(year / 100); var c = year % 100; var d = Math.floor(b / 4); var e = b % 4; var f = Math.floor((b + 8) / 25); var g = Math.floor((b - f + 1) / 3); var h = (19 * a + b - d - g + 15) % 30; var i = Math.floor(c / 4); var k = c % 4; var l = (32 + 2 * e + 2 * i - h - k) % 7; var m = Math.floor((a + 11 * h + 22 * l) / 451); var n0 = h + l + 7 * m + 114; var n = Math.floor(n0 / 31) - 1; var p = n0 % 31 + 1; var date = this.createDate(year, n + 1, p); return date; }
javascript
function(year) { var a = year % 19; var b = Math.floor(year / 100); var c = year % 100; var d = Math.floor(b / 4); var e = b % 4; var f = Math.floor((b + 8) / 25); var g = Math.floor((b - f + 1) / 3); var h = (19 * a + b - d - g + 15) % 30; var i = Math.floor(c / 4); var k = c % 4; var l = (32 + 2 * e + 2 * i - h - k) % 7; var m = Math.floor((a + 11 * h + 22 * l) / 451); var n0 = h + l + 7 * m + 114; var n = Math.floor(n0 / 31) - 1; var p = n0 % 31 + 1; var date = this.createDate(year, n + 1, p); return date; }
[ "function", "(", "year", ")", "{", "var", "a", "=", "year", "%", "19", ";", "var", "b", "=", "Math", ".", "floor", "(", "year", "/", "100", ")", ";", "var", "c", "=", "year", "%", "100", ";", "var", "d", "=", "Math", ".", "floor", "(", "b", "/", "4", ")", ";", "var", "e", "=", "b", "%", "4", ";", "var", "f", "=", "Math", ".", "floor", "(", "(", "b", "+", "8", ")", "/", "25", ")", ";", "var", "g", "=", "Math", ".", "floor", "(", "(", "b", "-", "f", "+", "1", ")", "/", "3", ")", ";", "var", "h", "=", "(", "19", "*", "a", "+", "b", "-", "d", "-", "g", "+", "15", ")", "%", "30", ";", "var", "i", "=", "Math", ".", "floor", "(", "c", "/", "4", ")", ";", "var", "k", "=", "c", "%", "4", ";", "var", "l", "=", "(", "32", "+", "2", "*", "e", "+", "2", "*", "i", "-", "h", "-", "k", ")", "%", "7", ";", "var", "m", "=", "Math", ".", "floor", "(", "(", "a", "+", "11", "*", "h", "+", "22", "*", "l", ")", "/", "451", ")", ";", "var", "n0", "=", "h", "+", "l", "+", "7", "*", "m", "+", "114", ";", "var", "n", "=", "Math", ".", "floor", "(", "n0", "/", "31", ")", "-", "1", ";", "var", "p", "=", "n0", "%", "31", "+", "1", ";", "var", "date", "=", "this", ".", "createDate", "(", "year", ",", "n", "+", "1", ",", "p", ")", ";", "return", "date", ";", "}" ]
Determines the date of Easter Sunday. @param {number} year @return {Date}
[ "Determines", "the", "date", "of", "Easter", "Sunday", "." ]
33416bd96b18bf7b18c331c831212aefb2a6f9c2
https://github.com/ericnishio/finnish-holidays-js/blob/33416bd96b18bf7b18c331c831212aefb2a6f9c2/lib/date-utils.js#L99-L117
46,398
ericnishio/finnish-holidays-js
lib/date-utils.js
function(year) { var date = this.easterSunday(year); var y = date.getFullYear(); var m = date.getMonth() + 1; var d = date.getDate() + 1; return this.createDate(y, m, d); }
javascript
function(year) { var date = this.easterSunday(year); var y = date.getFullYear(); var m = date.getMonth() + 1; var d = date.getDate() + 1; return this.createDate(y, m, d); }
[ "function", "(", "year", ")", "{", "var", "date", "=", "this", ".", "easterSunday", "(", "year", ")", ";", "var", "y", "=", "date", ".", "getFullYear", "(", ")", ";", "var", "m", "=", "date", ".", "getMonth", "(", ")", "+", "1", ";", "var", "d", "=", "date", ".", "getDate", "(", ")", "+", "1", ";", "return", "this", ".", "createDate", "(", "y", ",", "m", ",", "d", ")", ";", "}" ]
Determines the date of Easter Monday. Day after Easter Sunday @param {number} year @return {Date}
[ "Determines", "the", "date", "of", "Easter", "Monday", ".", "Day", "after", "Easter", "Sunday" ]
33416bd96b18bf7b18c331c831212aefb2a6f9c2
https://github.com/ericnishio/finnish-holidays-js/blob/33416bd96b18bf7b18c331c831212aefb2a6f9c2/lib/date-utils.js#L125-L131
46,399
ericnishio/finnish-holidays-js
lib/date-utils.js
function(year) { var self = this; var date = this.easterSunday(year); var dayOfWeek = null; function resolveFriday() { if (dayOfWeek === self.FRIDAY) { return date; } else { date = self.subtractDays(date, 1); dayOfWeek = self.getDayOfWeek(date); return resolveFriday(); } } return resolveFriday(); }
javascript
function(year) { var self = this; var date = this.easterSunday(year); var dayOfWeek = null; function resolveFriday() { if (dayOfWeek === self.FRIDAY) { return date; } else { date = self.subtractDays(date, 1); dayOfWeek = self.getDayOfWeek(date); return resolveFriday(); } } return resolveFriday(); }
[ "function", "(", "year", ")", "{", "var", "self", "=", "this", ";", "var", "date", "=", "this", ".", "easterSunday", "(", "year", ")", ";", "var", "dayOfWeek", "=", "null", ";", "function", "resolveFriday", "(", ")", "{", "if", "(", "dayOfWeek", "===", "self", ".", "FRIDAY", ")", "{", "return", "date", ";", "}", "else", "{", "date", "=", "self", ".", "subtractDays", "(", "date", ",", "1", ")", ";", "dayOfWeek", "=", "self", ".", "getDayOfWeek", "(", "date", ")", ";", "return", "resolveFriday", "(", ")", ";", "}", "}", "return", "resolveFriday", "(", ")", ";", "}" ]
Determines the date of Good Friday. Friday before Easter Sunday @param {number} year @return {Date}
[ "Determines", "the", "date", "of", "Good", "Friday", ".", "Friday", "before", "Easter", "Sunday" ]
33416bd96b18bf7b18c331c831212aefb2a6f9c2
https://github.com/ericnishio/finnish-holidays-js/blob/33416bd96b18bf7b18c331c831212aefb2a6f9c2/lib/date-utils.js#L139-L155