id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
54,400
operandom/ProtoTyper
lib/prototyper.js
isProperty
function isProperty(name, value) { currentProperty = name; updateDescriptor({ 'value': value, 'writable': true, 'enumerable': true, 'configurable': true }); return this; }
javascript
function isProperty(name, value) { currentProperty = name; updateDescriptor({ 'value': value, 'writable': true, 'enumerable': true, 'configurable': true }); return this; }
[ "function", "isProperty", "(", "name", ",", "value", ")", "{", "currentProperty", "=", "name", ";", "updateDescriptor", "(", "{", "'value'", ":", "value", ",", "'writable'", ":", "true", ",", "'enumerable'", ":", "true", ",", "'configurable'", ":", "true", "}", ")", ";", "return", "this", ";", "}" ]
Define a new property @param {String} name The name of the property to be defined or modified. @param {String} value The value associated with the property. Can be any valid JavaScript value. Defaults to undefined.
[ "Define", "a", "new", "property" ]
2e826e1871e049e063cafcc4eb5f7d96e9728c6a
https://github.com/operandom/ProtoTyper/blob/2e826e1871e049e063cafcc4eb5f7d96e9728c6a/lib/prototyper.js#L188-L197
54,401
soldair/pinoccio-serial
index.js
function(cb){ serialport.list(function (err, ports) { if(err) return cb(err); var pinoccios = []; ports.forEach(function(port) { var pnpId = port.pnpId||port.manufacturer||""; if(pnpId.indexOf('Pinoccio') > -1){ pinoccios.push(port.comName); } }); cb(false,pinoccios,ports); }); }
javascript
function(cb){ serialport.list(function (err, ports) { if(err) return cb(err); var pinoccios = []; ports.forEach(function(port) { var pnpId = port.pnpId||port.manufacturer||""; if(pnpId.indexOf('Pinoccio') > -1){ pinoccios.push(port.comName); } }); cb(false,pinoccios,ports); }); }
[ "function", "(", "cb", ")", "{", "serialport", ".", "list", "(", "function", "(", "err", ",", "ports", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "var", "pinoccios", "=", "[", "]", ";", "ports", ".", "forEach", "(", "function", "(", "port", ")", "{", "var", "pnpId", "=", "port", ".", "pnpId", "||", "port", ".", "manufacturer", "||", "\"\"", ";", "if", "(", "pnpId", ".", "indexOf", "(", "'Pinoccio'", ")", ">", "-", "1", ")", "{", "pinoccios", ".", "push", "(", "port", ".", "comName", ")", ";", "}", "}", ")", ";", "cb", "(", "false", ",", "pinoccios", ",", "ports", ")", ";", "}", ")", ";", "}" ]
look for connected pinoccios
[ "look", "for", "connected", "pinoccios" ]
7a93a663ed51deb13d07d16ce7d185092127d4bf
https://github.com/soldair/pinoccio-serial/blob/7a93a663ed51deb13d07d16ce7d185092127d4bf/index.js#L13-L25
54,402
torworx/ovy
ovy.functions.js
function(fn, args, scope) { if (!ovy.isArray(args)) { if (ovy.isIterable(args)) { args = arrays.clone(args); } else { args = args !== undefined ? [args] : []; } } return function() { var fnArgs = [].concat(args); fnArgs.push.apply(fnArgs, arguments); return fn.apply(scope || this, fnArgs); }; }
javascript
function(fn, args, scope) { if (!ovy.isArray(args)) { if (ovy.isIterable(args)) { args = arrays.clone(args); } else { args = args !== undefined ? [args] : []; } } return function() { var fnArgs = [].concat(args); fnArgs.push.apply(fnArgs, arguments); return fn.apply(scope || this, fnArgs); }; }
[ "function", "(", "fn", ",", "args", ",", "scope", ")", "{", "if", "(", "!", "ovy", ".", "isArray", "(", "args", ")", ")", "{", "if", "(", "ovy", ".", "isIterable", "(", "args", ")", ")", "{", "args", "=", "arrays", ".", "clone", "(", "args", ")", ";", "}", "else", "{", "args", "=", "args", "!==", "undefined", "?", "[", "args", "]", ":", "[", "]", ";", "}", "}", "return", "function", "(", ")", "{", "var", "fnArgs", "=", "[", "]", ".", "concat", "(", "args", ")", ";", "fnArgs", ".", "push", ".", "apply", "(", "fnArgs", ",", "arguments", ")", ";", "return", "fn", ".", "apply", "(", "scope", "||", "this", ",", "fnArgs", ")", ";", "}", ";", "}" ]
Create a new function from the provided `fn`, the arguments of which are pre-set to `args`. New arguments passed to the newly created callback when it's invoked are appended after the pre-set ones. This is especially useful when creating callbacks. For example: var originalFunction = function(){ alert(ovy.arrays.from(arguments).join(' ')); }; var callback = ovy.functions.pass(originalFunction, ['Hello', 'World']); callback(); // alerts 'Hello World' callback('by Me'); // alerts 'Hello World by Me' {@link ovy#pass ovy.pass} is alias for {@link ovy.functions#pass ovy.functions.pass} @param {Function} fn The original function @param {Array} args The arguments to pass to new callback @param {Object} scope (optional) The scope (`this` reference) in which the function is executed. @return {Function} The new callback function
[ "Create", "a", "new", "function", "from", "the", "provided", "fn", "the", "arguments", "of", "which", "are", "pre", "-", "set", "to", "args", ".", "New", "arguments", "passed", "to", "the", "newly", "created", "callback", "when", "it", "s", "invoked", "are", "appended", "after", "the", "pre", "-", "set", "ones", ".", "This", "is", "especially", "useful", "when", "creating", "callbacks", "." ]
18e9727305ab37acee1954a3facdd65b3a3526ab
https://github.com/torworx/ovy/blob/18e9727305ab37acee1954a3facdd65b3a3526ab/ovy.functions.js#L122-L136
54,403
doowb/layout-stack
index.js
assertLayout
function assertLayout(value, defaultLayout) { var isFalsey = require('falsey'); if (value === false || (value && isFalsey(value))) { return null; } else if (!value || value === true) { return defaultLayout || null; } else { return value; } }
javascript
function assertLayout(value, defaultLayout) { var isFalsey = require('falsey'); if (value === false || (value && isFalsey(value))) { return null; } else if (!value || value === true) { return defaultLayout || null; } else { return value; } }
[ "function", "assertLayout", "(", "value", ",", "defaultLayout", ")", "{", "var", "isFalsey", "=", "require", "(", "'falsey'", ")", ";", "if", "(", "value", "===", "false", "||", "(", "value", "&&", "isFalsey", "(", "value", ")", ")", ")", "{", "return", "null", ";", "}", "else", "if", "(", "!", "value", "||", "value", "===", "true", ")", "{", "return", "defaultLayout", "||", "null", ";", "}", "else", "{", "return", "value", ";", "}", "}" ]
Assert whether or not a layout should be used based on the given `value`. If a layout should be used, the name of the layout is returned, if not `null` is returned. @param {*} `value` @return {String|Null} Returns `true` or `null`. @api private
[ "Assert", "whether", "or", "not", "a", "layout", "should", "be", "used", "based", "on", "the", "given", "value", ".", "If", "a", "layout", "should", "be", "used", "the", "name", "of", "the", "layout", "is", "returned", "if", "not", "null", "is", "returned", "." ]
147d592edbcbaf5e37da91b89a99c080456f7bf9
https://github.com/doowb/layout-stack/blob/147d592edbcbaf5e37da91b89a99c080456f7bf9/index.js#L48-L57
54,404
goddyZhao/message-go
lib/message-go.js
go
function go(from, to){ var toStream; Step( function checkParams(){ _checkParams(from, to, this) }, function(err, checkResult){ var checkResultOfFrom; var checkResultOfTo; if(err){ log.error('invalid options'); throw err; return; } checkResultOfFrom = checkResult.from; checkResultOfTo = checkResult.to; if(!checkResultOfTo.isFile){ throw new Error('-t should specify a file but not a directory'); } Step( function resolveFrom(){ if(checkResultOfFrom.isFile){ return [checkResultOfFrom.path]; }else if(checkResultOfFrom.isDirectory){ utils.walk(checkResultOfFrom.path, function(file){ return path.extname(file) === '.js'; }, this); } }, function action(err, files){ var group; if(err){ throw err; } group = this.group(); toStream = fs.createWriteStream(to, {flags: 'a'}); for(var i = 0, l = files.length; i < l; i++){ goByFile(files[i], toStream, group()); } }, function showStats(err, numbers){ var totally = 0; if(err){ throw err; } toStream.end(); numbers.forEach(function(number){ totally = totally + number; }); if(totally > 0){ console.log('--------'); console.log('Totally ' + clc.red(totally) + ' messages have gone to ' + clc.green(to)); }else{ console.log(clc.red('No') + ' messages found in ' + clc.cyan(from)); } } ); } ) }
javascript
function go(from, to){ var toStream; Step( function checkParams(){ _checkParams(from, to, this) }, function(err, checkResult){ var checkResultOfFrom; var checkResultOfTo; if(err){ log.error('invalid options'); throw err; return; } checkResultOfFrom = checkResult.from; checkResultOfTo = checkResult.to; if(!checkResultOfTo.isFile){ throw new Error('-t should specify a file but not a directory'); } Step( function resolveFrom(){ if(checkResultOfFrom.isFile){ return [checkResultOfFrom.path]; }else if(checkResultOfFrom.isDirectory){ utils.walk(checkResultOfFrom.path, function(file){ return path.extname(file) === '.js'; }, this); } }, function action(err, files){ var group; if(err){ throw err; } group = this.group(); toStream = fs.createWriteStream(to, {flags: 'a'}); for(var i = 0, l = files.length; i < l; i++){ goByFile(files[i], toStream, group()); } }, function showStats(err, numbers){ var totally = 0; if(err){ throw err; } toStream.end(); numbers.forEach(function(number){ totally = totally + number; }); if(totally > 0){ console.log('--------'); console.log('Totally ' + clc.red(totally) + ' messages have gone to ' + clc.green(to)); }else{ console.log(clc.red('No') + ' messages found in ' + clc.cyan(from)); } } ); } ) }
[ "function", "go", "(", "from", ",", "to", ")", "{", "var", "toStream", ";", "Step", "(", "function", "checkParams", "(", ")", "{", "_checkParams", "(", "from", ",", "to", ",", "this", ")", "}", ",", "function", "(", "err", ",", "checkResult", ")", "{", "var", "checkResultOfFrom", ";", "var", "checkResultOfTo", ";", "if", "(", "err", ")", "{", "log", ".", "error", "(", "'invalid options'", ")", ";", "throw", "err", ";", "return", ";", "}", "checkResultOfFrom", "=", "checkResult", ".", "from", ";", "checkResultOfTo", "=", "checkResult", ".", "to", ";", "if", "(", "!", "checkResultOfTo", ".", "isFile", ")", "{", "throw", "new", "Error", "(", "'-t should specify a file but not a directory'", ")", ";", "}", "Step", "(", "function", "resolveFrom", "(", ")", "{", "if", "(", "checkResultOfFrom", ".", "isFile", ")", "{", "return", "[", "checkResultOfFrom", ".", "path", "]", ";", "}", "else", "if", "(", "checkResultOfFrom", ".", "isDirectory", ")", "{", "utils", ".", "walk", "(", "checkResultOfFrom", ".", "path", ",", "function", "(", "file", ")", "{", "return", "path", ".", "extname", "(", "file", ")", "===", "'.js'", ";", "}", ",", "this", ")", ";", "}", "}", ",", "function", "action", "(", "err", ",", "files", ")", "{", "var", "group", ";", "if", "(", "err", ")", "{", "throw", "err", ";", "}", "group", "=", "this", ".", "group", "(", ")", ";", "toStream", "=", "fs", ".", "createWriteStream", "(", "to", ",", "{", "flags", ":", "'a'", "}", ")", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "files", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "goByFile", "(", "files", "[", "i", "]", ",", "toStream", ",", "group", "(", ")", ")", ";", "}", "}", ",", "function", "showStats", "(", "err", ",", "numbers", ")", "{", "var", "totally", "=", "0", ";", "if", "(", "err", ")", "{", "throw", "err", ";", "}", "toStream", ".", "end", "(", ")", ";", "numbers", ".", "forEach", "(", "function", "(", "number", ")", "{", "totally", "=", "totally", "+", "number", ";", "}", ")", ";", "if", "(", "totally", ">", "0", ")", "{", "console", ".", "log", "(", "'--------'", ")", ";", "console", ".", "log", "(", "'Totally '", "+", "clc", ".", "red", "(", "totally", ")", "+", "' messages have gone to '", "+", "clc", ".", "green", "(", "to", ")", ")", ";", "}", "else", "{", "console", ".", "log", "(", "clc", ".", "red", "(", "'No'", ")", "+", "' messages found in '", "+", "clc", ".", "cyan", "(", "from", ")", ")", ";", "}", "}", ")", ";", "}", ")", "}" ]
Let messages go from FROM to TO @param {String} from directory or file the messages come from @param {String} to file the message go to
[ "Let", "messages", "go", "from", "FROM", "to", "TO" ]
bb84ca5b92ce8668ea835d765adbc35aacece402
https://github.com/goddyZhao/message-go/blob/bb84ca5b92ce8668ea835d765adbc35aacece402/lib/message-go.js#L15-L88
54,405
huafu/ember-dev-fixtures
private/initializers/dev-fixtures.js
readOverlay
function readOverlay(application) { var possibleValues, value; if (Ember.testing) { // when in test mode, use the overlay specified in the application value = {from: 'test:startApp()', name: application.get('devFixtures.overlay')}; } else { // else try many locations possibleValues = []; location.href.replace(/(?:\?|&)FIXTURES_OVERLAY(?:=([^&#$]*))?(?:&|#|$)/, function (dummy, value) { value = value ? decodeURIComponent(value) : null; possibleValues.push({from: 'location.search:FIXTURES_OVERLAY', name: value}); }); possibleValues.push({ from: 'file:config/environment.js', name: application.get('devFixtures.overlay') }); possibleValues.push({ from: 'localStorage:' + STORAGE_KEY, name: window.localStorage.getItem(STORAGE_KEY) }); // grabbing the first one not undefined value = Ember.A(possibleValues).find(function (value) { return value !== undefined; }); // saving it in the localStorage if (value && value.name) { window.localStorage.setItem(STORAGE_KEY, value.name); } else { window.localStorage.removeItem(STORAGE_KEY); } } // no overlay found anywhere if (!value) { value = {from: 'default', name: null}; } return value; }
javascript
function readOverlay(application) { var possibleValues, value; if (Ember.testing) { // when in test mode, use the overlay specified in the application value = {from: 'test:startApp()', name: application.get('devFixtures.overlay')}; } else { // else try many locations possibleValues = []; location.href.replace(/(?:\?|&)FIXTURES_OVERLAY(?:=([^&#$]*))?(?:&|#|$)/, function (dummy, value) { value = value ? decodeURIComponent(value) : null; possibleValues.push({from: 'location.search:FIXTURES_OVERLAY', name: value}); }); possibleValues.push({ from: 'file:config/environment.js', name: application.get('devFixtures.overlay') }); possibleValues.push({ from: 'localStorage:' + STORAGE_KEY, name: window.localStorage.getItem(STORAGE_KEY) }); // grabbing the first one not undefined value = Ember.A(possibleValues).find(function (value) { return value !== undefined; }); // saving it in the localStorage if (value && value.name) { window.localStorage.setItem(STORAGE_KEY, value.name); } else { window.localStorage.removeItem(STORAGE_KEY); } } // no overlay found anywhere if (!value) { value = {from: 'default', name: null}; } return value; }
[ "function", "readOverlay", "(", "application", ")", "{", "var", "possibleValues", ",", "value", ";", "if", "(", "Ember", ".", "testing", ")", "{", "// when in test mode, use the overlay specified in the application", "value", "=", "{", "from", ":", "'test:startApp()'", ",", "name", ":", "application", ".", "get", "(", "'devFixtures.overlay'", ")", "}", ";", "}", "else", "{", "// else try many locations", "possibleValues", "=", "[", "]", ";", "location", ".", "href", ".", "replace", "(", "/", "(?:\\?|&)FIXTURES_OVERLAY(?:=([^&#$]*))?(?:&|#|$)", "/", ",", "function", "(", "dummy", ",", "value", ")", "{", "value", "=", "value", "?", "decodeURIComponent", "(", "value", ")", ":", "null", ";", "possibleValues", ".", "push", "(", "{", "from", ":", "'location.search:FIXTURES_OVERLAY'", ",", "name", ":", "value", "}", ")", ";", "}", ")", ";", "possibleValues", ".", "push", "(", "{", "from", ":", "'file:config/environment.js'", ",", "name", ":", "application", ".", "get", "(", "'devFixtures.overlay'", ")", "}", ")", ";", "possibleValues", ".", "push", "(", "{", "from", ":", "'localStorage:'", "+", "STORAGE_KEY", ",", "name", ":", "window", ".", "localStorage", ".", "getItem", "(", "STORAGE_KEY", ")", "}", ")", ";", "// grabbing the first one not undefined", "value", "=", "Ember", ".", "A", "(", "possibleValues", ")", ".", "find", "(", "function", "(", "value", ")", "{", "return", "value", "!==", "undefined", ";", "}", ")", ";", "// saving it in the localStorage", "if", "(", "value", "&&", "value", ".", "name", ")", "{", "window", ".", "localStorage", ".", "setItem", "(", "STORAGE_KEY", ",", "value", ".", "name", ")", ";", "}", "else", "{", "window", ".", "localStorage", ".", "removeItem", "(", "STORAGE_KEY", ")", ";", "}", "}", "// no overlay found anywhere", "if", "(", "!", "value", ")", "{", "value", "=", "{", "from", ":", "'default'", ",", "name", ":", "null", "}", ";", "}", "return", "value", ";", "}" ]
Reads and save the overlay @function readOverlay @param {Ember.Application} application @return {{from: string, name: string|null}}
[ "Reads", "and", "save", "the", "overlay" ]
811ed4d339c2dc840d5b297b5b244726cf1339ca
https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/initializers/dev-fixtures.js#L26-L64
54,406
frisb/fdboost
lib/enhance/rangereader.js
RangeReader
function RangeReader(options) { RangeReader.__super__.constructor.call(this); this.begin = options.begin; this.end = options.end; this.marker = null; this.limit = options.limit; this.reverse = options.reverse; this.streamingMode = options.streamingMode; this.nonTransactional = options.nonTransactional || false; this.snapshot = options.snapshot || false; debug(function(writer) { if (options.begin) { writer.buffer('begin', resolveKey(options.begin).toString('utf8')); } if (options.end) { writer.buffer('end', resolveKey(options.end).toString('utf8')); } writer.buffer('limit', options.limit); writer.buffer('reverse', options.reverse); writer.buffer('streamingMode', options.streamingMode); writer.buffer('nonTransactional', options.nonTransactional); return writer.buffer('snapshot', options.snapshot); }); this.on('data', (function(_this) { return function(data) { var kv, _i, _len; if (data instanceof Array) { for (_i = 0, _len = data.length; _i < _len; _i++) { kv = data[_i]; _this.marker = kv.key; } } else { _this.marker = data.key; } }; })(this)); }
javascript
function RangeReader(options) { RangeReader.__super__.constructor.call(this); this.begin = options.begin; this.end = options.end; this.marker = null; this.limit = options.limit; this.reverse = options.reverse; this.streamingMode = options.streamingMode; this.nonTransactional = options.nonTransactional || false; this.snapshot = options.snapshot || false; debug(function(writer) { if (options.begin) { writer.buffer('begin', resolveKey(options.begin).toString('utf8')); } if (options.end) { writer.buffer('end', resolveKey(options.end).toString('utf8')); } writer.buffer('limit', options.limit); writer.buffer('reverse', options.reverse); writer.buffer('streamingMode', options.streamingMode); writer.buffer('nonTransactional', options.nonTransactional); return writer.buffer('snapshot', options.snapshot); }); this.on('data', (function(_this) { return function(data) { var kv, _i, _len; if (data instanceof Array) { for (_i = 0, _len = data.length; _i < _len; _i++) { kv = data[_i]; _this.marker = kv.key; } } else { _this.marker = data.key; } }; })(this)); }
[ "function", "RangeReader", "(", "options", ")", "{", "RangeReader", ".", "__super__", ".", "constructor", ".", "call", "(", "this", ")", ";", "this", ".", "begin", "=", "options", ".", "begin", ";", "this", ".", "end", "=", "options", ".", "end", ";", "this", ".", "marker", "=", "null", ";", "this", ".", "limit", "=", "options", ".", "limit", ";", "this", ".", "reverse", "=", "options", ".", "reverse", ";", "this", ".", "streamingMode", "=", "options", ".", "streamingMode", ";", "this", ".", "nonTransactional", "=", "options", ".", "nonTransactional", "||", "false", ";", "this", ".", "snapshot", "=", "options", ".", "snapshot", "||", "false", ";", "debug", "(", "function", "(", "writer", ")", "{", "if", "(", "options", ".", "begin", ")", "{", "writer", ".", "buffer", "(", "'begin'", ",", "resolveKey", "(", "options", ".", "begin", ")", ".", "toString", "(", "'utf8'", ")", ")", ";", "}", "if", "(", "options", ".", "end", ")", "{", "writer", ".", "buffer", "(", "'end'", ",", "resolveKey", "(", "options", ".", "end", ")", ".", "toString", "(", "'utf8'", ")", ")", ";", "}", "writer", ".", "buffer", "(", "'limit'", ",", "options", ".", "limit", ")", ";", "writer", ".", "buffer", "(", "'reverse'", ",", "options", ".", "reverse", ")", ";", "writer", ".", "buffer", "(", "'streamingMode'", ",", "options", ".", "streamingMode", ")", ";", "writer", ".", "buffer", "(", "'nonTransactional'", ",", "options", ".", "nonTransactional", ")", ";", "return", "writer", ".", "buffer", "(", "'snapshot'", ",", "options", ".", "snapshot", ")", ";", "}", ")", ";", "this", ".", "on", "(", "'data'", ",", "(", "function", "(", "_this", ")", "{", "return", "function", "(", "data", ")", "{", "var", "kv", ",", "_i", ",", "_len", ";", "if", "(", "data", "instanceof", "Array", ")", "{", "for", "(", "_i", "=", "0", ",", "_len", "=", "data", ".", "length", ";", "_i", "<", "_len", ";", "_i", "++", ")", "{", "kv", "=", "data", "[", "_i", "]", ";", "_this", ".", "marker", "=", "kv", ".", "key", ";", "}", "}", "else", "{", "_this", ".", "marker", "=", "data", ".", "key", ";", "}", "}", ";", "}", ")", "(", "this", ")", ")", ";", "}" ]
Creates a new Reader instance @class @param {object} options Settings. @param {(Buffer|fdb.KeySelector)} [options.begin] First key in the reader range. @param {(Buffer|fdb.KeySelector)}} [options.end=undefined] Last key in the reader range. @param {number} [options.limit=undefined] Only the first limit keys (and their values) in the range will be returned. @param {boolean} [options.reverse=undefined] Specified if the keys in the range will be returned in reverse order @param {(iterator|want_all|small|medium|large|serial|exact)} [options.streamingMode=undefined] fdb.streamingMode property that permits the API client to customize performance tradeoff by providing extra information about how the iterator will be used. @param {boolean} [options.nonTransactional=false] Reset transaction on expiry and start. @param {boolean} [options.snapshot=false] Defines whether range reads should be snapshot reads. @property {array} instances Collection of Document Layer db instances. @property {number} index Current index of the instances collection. @property {(Buffer|fdb.KeySelector)}} begin First key in the reader range. @property {(Buffer|fdb.KeySelector)}} end Last key in the reader range. @property {Buffer} marker Marker key for transaction expiration continuation point. @property {number} limit Only the first limit keys (and their values) in the range will be returned. @property {boolean} reverse Specified if the keys in the range will be returned in reverse order @property {(iterator|want_all|small|medium|large|serial|exact)} streamingMode fdb.streamingMode property that permits the API client to customize performance tradeoff by providing extra information about how the iterator will be used. @property {boolean} nonTransactional Reset transaction on expiry and start. @property {boolean} snapshot Defines whether range reads should be snapshot reads. @return {Reader} a Reader instance.
[ "Creates", "a", "new", "Reader", "instance" ]
66cfb6552940aa92f35dbb1cf4d0695d842205c2
https://github.com/frisb/fdboost/blob/66cfb6552940aa92f35dbb1cf4d0695d842205c2/lib/enhance/rangereader.js#L108-L144
54,407
Pocketbrain/native-ads-web-ad-library
src/util/resolveToken.js
resolveToken
function resolveToken(callback) { var crossDomainStorageAvailable = crossDomainStorage.isAvailable(); logger.info('Resolving token from OfferEngine'); if (crossDomainStorageAvailable) { initXDomainStorage(function () { crossDomainStorage.getItem(appSettings.tokenCookieKey, function (data) { if (data.value) { logger.info('Retrieved existing token: ' + data.value); callback(data.value); } else { setCrossDomainToken(callback); } }); }); } else { // If there is no cross domain storage, we just generate a random token. // In reality, cross domain storage will be available on pretty much all devices // Because they all support localStorage now var token = utils.generateToken(); callback(token); } }
javascript
function resolveToken(callback) { var crossDomainStorageAvailable = crossDomainStorage.isAvailable(); logger.info('Resolving token from OfferEngine'); if (crossDomainStorageAvailable) { initXDomainStorage(function () { crossDomainStorage.getItem(appSettings.tokenCookieKey, function (data) { if (data.value) { logger.info('Retrieved existing token: ' + data.value); callback(data.value); } else { setCrossDomainToken(callback); } }); }); } else { // If there is no cross domain storage, we just generate a random token. // In reality, cross domain storage will be available on pretty much all devices // Because they all support localStorage now var token = utils.generateToken(); callback(token); } }
[ "function", "resolveToken", "(", "callback", ")", "{", "var", "crossDomainStorageAvailable", "=", "crossDomainStorage", ".", "isAvailable", "(", ")", ";", "logger", ".", "info", "(", "'Resolving token from OfferEngine'", ")", ";", "if", "(", "crossDomainStorageAvailable", ")", "{", "initXDomainStorage", "(", "function", "(", ")", "{", "crossDomainStorage", ".", "getItem", "(", "appSettings", ".", "tokenCookieKey", ",", "function", "(", "data", ")", "{", "if", "(", "data", ".", "value", ")", "{", "logger", ".", "info", "(", "'Retrieved existing token: '", "+", "data", ".", "value", ")", ";", "callback", "(", "data", ".", "value", ")", ";", "}", "else", "{", "setCrossDomainToken", "(", "callback", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", "else", "{", "// If there is no cross domain storage, we just generate a random token.", "// In reality, cross domain storage will be available on pretty much all devices", "// Because they all support localStorage now", "var", "token", "=", "utils", ".", "generateToken", "(", ")", ";", "callback", "(", "token", ")", ";", "}", "}" ]
Resolve the token for the user visiting the page @param callback - The callback that is executed when the token is resolved
[ "Resolve", "the", "token", "for", "the", "user", "visiting", "the", "page" ]
aafee1c42e0569ee77f334fc2c4eb71eb146957e
https://github.com/Pocketbrain/native-ads-web-ad-library/blob/aafee1c42e0569ee77f334fc2c4eb71eb146957e/src/util/resolveToken.js#L10-L32
54,408
taoyuan/amqper
lib/routify/router.js
handleMessage
function handleMessage(data) { const message = data; message.params = that.parser.parse(data); message.channel = ch; message.ack = ack; // Ack method for the msg function ack() { debug('ack delivery', data.fields.deliveryTag); ch.ack(data); } if (Array.isArray(message)) { that.options.handler(message[0]); } else { that.options.handler(message); } debug('queue', that.options.queue); if (that.options.autoAck) { debug('autoAck', 'true'); ack(); } }
javascript
function handleMessage(data) { const message = data; message.params = that.parser.parse(data); message.channel = ch; message.ack = ack; // Ack method for the msg function ack() { debug('ack delivery', data.fields.deliveryTag); ch.ack(data); } if (Array.isArray(message)) { that.options.handler(message[0]); } else { that.options.handler(message); } debug('queue', that.options.queue); if (that.options.autoAck) { debug('autoAck', 'true'); ack(); } }
[ "function", "handleMessage", "(", "data", ")", "{", "const", "message", "=", "data", ";", "message", ".", "params", "=", "that", ".", "parser", ".", "parse", "(", "data", ")", ";", "message", ".", "channel", "=", "ch", ";", "message", ".", "ack", "=", "ack", ";", "// Ack method for the msg", "function", "ack", "(", ")", "{", "debug", "(", "'ack delivery'", ",", "data", ".", "fields", ".", "deliveryTag", ")", ";", "ch", ".", "ack", "(", "data", ")", ";", "}", "if", "(", "Array", ".", "isArray", "(", "message", ")", ")", "{", "that", ".", "options", ".", "handler", "(", "message", "[", "0", "]", ")", ";", "}", "else", "{", "that", ".", "options", ".", "handler", "(", "message", ")", ";", "}", "debug", "(", "'queue'", ",", "that", ".", "options", ".", "queue", ")", ";", "if", "(", "that", ".", "options", ".", "autoAck", ")", "{", "debug", "(", "'autoAck'", ",", "'true'", ")", ";", "ack", "(", ")", ";", "}", "}" ]
callback which is invoked each time a message matches the configured route.
[ "callback", "which", "is", "invoked", "each", "time", "a", "message", "matches", "the", "configured", "route", "." ]
7d099e9c238c217aa4d1a6ae3970427c94830180
https://github.com/taoyuan/amqper/blob/7d099e9c238c217aa4d1a6ae3970427c94830180/lib/routify/router.js#L46-L71
54,409
serebano/bitbox
src/bitbox/resolve.js
proxy
function proxy(target, mapping) { return new Proxy(mapping, { get(map, key) { if (Reflect.has(map, key)) { return resolve(target, Reflect.get(map, key)) } }, set(map, key, value) { if (Reflect.has(map, key)) { return resolve(target, Reflect.get(map, key), value) } } }) }
javascript
function proxy(target, mapping) { return new Proxy(mapping, { get(map, key) { if (Reflect.has(map, key)) { return resolve(target, Reflect.get(map, key)) } }, set(map, key, value) { if (Reflect.has(map, key)) { return resolve(target, Reflect.get(map, key), value) } } }) }
[ "function", "proxy", "(", "target", ",", "mapping", ")", "{", "return", "new", "Proxy", "(", "mapping", ",", "{", "get", "(", "map", ",", "key", ")", "{", "if", "(", "Reflect", ".", "has", "(", "map", ",", "key", ")", ")", "{", "return", "resolve", "(", "target", ",", "Reflect", ".", "get", "(", "map", ",", "key", ")", ")", "}", "}", ",", "set", "(", "map", ",", "key", ",", "value", ")", "{", "if", "(", "Reflect", ".", "has", "(", "map", ",", "key", ")", ")", "{", "return", "resolve", "(", "target", ",", "Reflect", ".", "get", "(", "map", ",", "key", ")", ",", "value", ")", "}", "}", "}", ")", "}" ]
bitbox.resolve @param {Object} target @param {Function|Array} box @param {Function} method @return {Any}
[ "bitbox", ".", "resolve" ]
3bca8d7078eca40ec32f654fe5f37d7b72f05d60
https://github.com/serebano/bitbox/blob/3bca8d7078eca40ec32f654fe5f37d7b72f05d60/src/bitbox/resolve.js#L12-L25
54,410
fernandojsg/useragent-info
index.js
splitPlatformInfo
function splitPlatformInfo(uaList) { for(var i = 0; i < uaList.length; ++i) { var item = uaList[i]; if (isEnclosedInParens(item)) { return removeEmptyElements(trimSpacesInEachElement(item.substr(1, item.length-2).split(';'))); } } }
javascript
function splitPlatformInfo(uaList) { for(var i = 0; i < uaList.length; ++i) { var item = uaList[i]; if (isEnclosedInParens(item)) { return removeEmptyElements(trimSpacesInEachElement(item.substr(1, item.length-2).split(';'))); } } }
[ "function", "splitPlatformInfo", "(", "uaList", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "uaList", ".", "length", ";", "++", "i", ")", "{", "var", "item", "=", "uaList", "[", "i", "]", ";", "if", "(", "isEnclosedInParens", "(", "item", ")", ")", "{", "return", "removeEmptyElements", "(", "trimSpacesInEachElement", "(", "item", ".", "substr", "(", "1", ",", "item", ".", "length", "-", "2", ")", ".", "split", "(", "';'", ")", ")", ")", ";", "}", "}", "}" ]
Finds the special token in the user agent token list that corresponds to the platform info. This is the first element contained in parentheses that has semicolon delimited elements. Returns the platform info as an array split by the semicolons.
[ "Finds", "the", "special", "token", "in", "the", "user", "agent", "token", "list", "that", "corresponds", "to", "the", "platform", "info", ".", "This", "is", "the", "first", "element", "contained", "in", "parentheses", "that", "has", "semicolon", "delimited", "elements", ".", "Returns", "the", "platform", "info", "as", "an", "array", "split", "by", "the", "semicolons", "." ]
2afa9d26906a74e8e34b1d54ab537aa9b4023499
https://github.com/fernandojsg/useragent-info/blob/2afa9d26906a74e8e34b1d54ab537aa9b4023499/index.js#L81-L88
54,411
fernandojsg/useragent-info
index.js
findOS
function findOS(uaPlatformInfo) { var oses = ['Android', 'BSD', 'Linux', 'Windows', 'iPhone OS', 'Mac OS', 'BSD', 'CrOS', 'Darwin', 'Dragonfly', 'Fedora', 'Gentoo', 'Ubuntu', 'debian', 'HP-UX', 'IRIX', 'SunOS', 'Macintosh', 'Win 9x', 'Win98', 'Win95', 'WinNT']; for(var os in oses) { for(var i in uaPlatformInfo) { var item = uaPlatformInfo[i]; if (contains(item, oses[os])) return item; } } return 'Other'; }
javascript
function findOS(uaPlatformInfo) { var oses = ['Android', 'BSD', 'Linux', 'Windows', 'iPhone OS', 'Mac OS', 'BSD', 'CrOS', 'Darwin', 'Dragonfly', 'Fedora', 'Gentoo', 'Ubuntu', 'debian', 'HP-UX', 'IRIX', 'SunOS', 'Macintosh', 'Win 9x', 'Win98', 'Win95', 'WinNT']; for(var os in oses) { for(var i in uaPlatformInfo) { var item = uaPlatformInfo[i]; if (contains(item, oses[os])) return item; } } return 'Other'; }
[ "function", "findOS", "(", "uaPlatformInfo", ")", "{", "var", "oses", "=", "[", "'Android'", ",", "'BSD'", ",", "'Linux'", ",", "'Windows'", ",", "'iPhone OS'", ",", "'Mac OS'", ",", "'BSD'", ",", "'CrOS'", ",", "'Darwin'", ",", "'Dragonfly'", ",", "'Fedora'", ",", "'Gentoo'", ",", "'Ubuntu'", ",", "'debian'", ",", "'HP-UX'", ",", "'IRIX'", ",", "'SunOS'", ",", "'Macintosh'", ",", "'Win 9x'", ",", "'Win98'", ",", "'Win95'", ",", "'WinNT'", "]", ";", "for", "(", "var", "os", "in", "oses", ")", "{", "for", "(", "var", "i", "in", "uaPlatformInfo", ")", "{", "var", "item", "=", "uaPlatformInfo", "[", "i", "]", ";", "if", "(", "contains", "(", "item", ",", "oses", "[", "os", "]", ")", ")", "return", "item", ";", "}", "}", "return", "'Other'", ";", "}" ]
Deduces the operating system from the user agent platform info token list.
[ "Deduces", "the", "operating", "system", "from", "the", "user", "agent", "platform", "info", "token", "list", "." ]
2afa9d26906a74e8e34b1d54ab537aa9b4023499
https://github.com/fernandojsg/useragent-info/blob/2afa9d26906a74e8e34b1d54ab537aa9b4023499/index.js#L91-L100
54,412
asleepinglion/ouro
lib/meta/class.js
function(filePath) { if( path.extname(filePath) === '.js' ) { filePath = path.dirname(filePath); } ////console.log(colors.gray('loading meta:'), filePath); this.filePath = filePath; var meta = require(filePath + '/meta'); //set the name of the class to the last name value this.name = meta.name; if( typeof this.meta === 'object' ) { this.meta = merge(meta, this.meta); } else { this.meta = meta; } }
javascript
function(filePath) { if( path.extname(filePath) === '.js' ) { filePath = path.dirname(filePath); } ////console.log(colors.gray('loading meta:'), filePath); this.filePath = filePath; var meta = require(filePath + '/meta'); //set the name of the class to the last name value this.name = meta.name; if( typeof this.meta === 'object' ) { this.meta = merge(meta, this.meta); } else { this.meta = meta; } }
[ "function", "(", "filePath", ")", "{", "if", "(", "path", ".", "extname", "(", "filePath", ")", "===", "'.js'", ")", "{", "filePath", "=", "path", ".", "dirname", "(", "filePath", ")", ";", "}", "////console.log(colors.gray('loading meta:'), filePath);", "this", ".", "filePath", "=", "filePath", ";", "var", "meta", "=", "require", "(", "filePath", "+", "'/meta'", ")", ";", "//set the name of the class to the last name value", "this", ".", "name", "=", "meta", ".", "name", ";", "if", "(", "typeof", "this", ".", "meta", "===", "'object'", ")", "{", "this", ".", "meta", "=", "merge", "(", "meta", ",", "this", ".", "meta", ")", ";", "}", "else", "{", "this", ".", "meta", "=", "meta", ";", "}", "}" ]
load a meta file and merge on top of current meta data
[ "load", "a", "meta", "file", "and", "merge", "on", "top", "of", "current", "meta", "data" ]
b2956e45790d739b85d51bbd9899698aebc132ba
https://github.com/asleepinglion/ouro/blob/b2956e45790d739b85d51bbd9899698aebc132ba/lib/meta/class.js#L34-L54
54,413
asleepinglion/ouro
lib/meta/class.js
function() { //if the name was not set by the last meta file set it based on the file path if( (!this.name || this.name === 'Class') && typeof this.filePath === 'string' ) { this.name = path.basename(this.filePath); } //make sure the meta object exists if( typeof this.meta !== 'object' ) { console.log(colors.gray('class meta:'), 'not found!'); this.meta = {}; } //make sure the meta methods object exists if( typeof this.meta.methods !== 'object' ) { console.log(colors.yellow('class meta:'), 'missing methods object!'); this.meta.methods = {}; } //loop through methods in the meta object for( var method in this.meta.methods ) { //delete any method from meta that does not actually exist on the class if( !(method in this) ) { console.log(colors.yellow('class missing method:'), {class: this.name, method: method}); delete this.meta.methods[method]; } } /* //loop through methods in the class for( var method in this ) { if( typeof this[method] === 'function' ) { //alert about methods missing from the meta data if (!(method in this.meta.methods)) { console.log(colors.yellow('meta missing method:'), {class: this.name, method: method}); } } } //*/ }
javascript
function() { //if the name was not set by the last meta file set it based on the file path if( (!this.name || this.name === 'Class') && typeof this.filePath === 'string' ) { this.name = path.basename(this.filePath); } //make sure the meta object exists if( typeof this.meta !== 'object' ) { console.log(colors.gray('class meta:'), 'not found!'); this.meta = {}; } //make sure the meta methods object exists if( typeof this.meta.methods !== 'object' ) { console.log(colors.yellow('class meta:'), 'missing methods object!'); this.meta.methods = {}; } //loop through methods in the meta object for( var method in this.meta.methods ) { //delete any method from meta that does not actually exist on the class if( !(method in this) ) { console.log(colors.yellow('class missing method:'), {class: this.name, method: method}); delete this.meta.methods[method]; } } /* //loop through methods in the class for( var method in this ) { if( typeof this[method] === 'function' ) { //alert about methods missing from the meta data if (!(method in this.meta.methods)) { console.log(colors.yellow('meta missing method:'), {class: this.name, method: method}); } } } //*/ }
[ "function", "(", ")", "{", "//if the name was not set by the last meta file set it based on the file path", "if", "(", "(", "!", "this", ".", "name", "||", "this", ".", "name", "===", "'Class'", ")", "&&", "typeof", "this", ".", "filePath", "===", "'string'", ")", "{", "this", ".", "name", "=", "path", ".", "basename", "(", "this", ".", "filePath", ")", ";", "}", "//make sure the meta object exists", "if", "(", "typeof", "this", ".", "meta", "!==", "'object'", ")", "{", "console", ".", "log", "(", "colors", ".", "gray", "(", "'class meta:'", ")", ",", "'not found!'", ")", ";", "this", ".", "meta", "=", "{", "}", ";", "}", "//make sure the meta methods object exists", "if", "(", "typeof", "this", ".", "meta", ".", "methods", "!==", "'object'", ")", "{", "console", ".", "log", "(", "colors", ".", "yellow", "(", "'class meta:'", ")", ",", "'missing methods object!'", ")", ";", "this", ".", "meta", ".", "methods", "=", "{", "}", ";", "}", "//loop through methods in the meta object", "for", "(", "var", "method", "in", "this", ".", "meta", ".", "methods", ")", "{", "//delete any method from meta that does not actually exist on the class", "if", "(", "!", "(", "method", "in", "this", ")", ")", "{", "console", ".", "log", "(", "colors", ".", "yellow", "(", "'class missing method:'", ")", ",", "{", "class", ":", "this", ".", "name", ",", "method", ":", "method", "}", ")", ";", "delete", "this", ".", "meta", ".", "methods", "[", "method", "]", ";", "}", "}", "/*\n //loop through methods in the class\n for( var method in this ) {\n\n if( typeof this[method] === 'function' ) {\n\n //alert about methods missing from the meta data\n if (!(method in this.meta.methods)) {\n console.log(colors.yellow('meta missing method:'), {class: this.name, method: method});\n }\n\n }\n }\n //*/", "}" ]
process & sanitize meta data
[ "process", "&", "sanitize", "meta", "data" ]
b2956e45790d739b85d51bbd9899698aebc132ba
https://github.com/asleepinglion/ouro/blob/b2956e45790d739b85d51bbd9899698aebc132ba/lib/meta/class.js#L57-L102
54,414
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/clipboard/plugin.js
addListenersToEditable
function addListenersToEditable() { var editable = editor.editable(); // We'll be catching all pasted content in one line, regardless of whether // it's introduced by a document command execution (e.g. toolbar buttons) or // user paste behaviors (e.g. CTRL+V). editable.on( mainPasteEvent, function( evt ) { if ( CKEDITOR.env.ie && preventBeforePasteEvent ) return; // If you've just asked yourself why preventPasteEventNow() is not here, but // in listener for CTRL+V and exec method of 'paste' command // you've asked the same question we did. // // THE ANSWER: // // First thing to notice - this answer makes sense only for IE, // because other browsers don't listen for 'paste' event. // // What would happen if we move preventPasteEventNow() here? // For: // * CTRL+V - IE fires 'beforepaste', so we prevent 'paste' and pasteDataFromClipboard(). OK. // * editor.execCommand( 'paste' ) - we fire 'beforepaste', so we prevent // 'paste' and pasteDataFromClipboard() and doc.execCommand( 'Paste' ). OK. // * native context menu - IE fires 'beforepaste', so we prevent 'paste', but unfortunately // on IE we fail with pasteDataFromClipboard() here, because of... we don't know why, but // we just fail, so... we paste nothing. FAIL. // * native menu bar - the same as for native context menu. // // But don't you know any way to distinguish first two cases from last two? // Only one - special flag set in CTRL+V handler and exec method of 'paste' // command. And that's what we did using preventPasteEventNow(). pasteDataFromClipboard( evt ); } ); // It's not possible to clearly handle all four paste methods (ctrl+v, native menu bar // native context menu, editor's command) in one 'paste/beforepaste' event in IE. // // For ctrl+v & editor's command it's easy to handle pasting in 'beforepaste' listener, // so we do this. For another two methods it's better to use 'paste' event. // // 'paste' is always being fired after 'beforepaste' (except of weird one on opening native // context menu), so for two methods handled in 'beforepaste' we're canceling 'paste' // using preventPasteEvent state. // // 'paste' event in IE is being fired before getClipboardDataByPastebin executes its callback. // // QUESTION: Why didn't you handle all 4 paste methods in handler for 'paste'? // Wouldn't this just be simpler? // ANSWER: Then we would have to evt.data.preventDefault() only for native // context menu and menu bar pastes. The same with execIECommand(). // That would force us to mark CTRL+V and editor's paste command with // special flag, other than preventPasteEvent. But we still would have to // have preventPasteEvent for the second event fired by execIECommand. // Code would be longer and not cleaner. CKEDITOR.env.ie && editable.on( 'paste', function( evt ) { if ( preventPasteEvent ) return; // Cancel next 'paste' event fired by execIECommand( 'paste' ) // at the end of this callback. preventPasteEventNow(); // Prevent native paste. evt.data.preventDefault(); pasteDataFromClipboard( evt ); // Force IE to paste content into pastebin so pasteDataFromClipboard will work. if ( !execIECommand( 'paste' ) ) editor.openDialog( 'paste' ); } ); // [IE] Dismiss the (wrong) 'beforepaste' event fired on context/toolbar menu open. (#7953) if ( CKEDITOR.env.ie ) { editable.on( 'contextmenu', preventBeforePasteEventNow, null, null, 0 ); editable.on( 'beforepaste', function( evt ) { // Do not prevent event on CTRL+V and SHIFT+INS because it blocks paste (#11970). if ( evt.data && !evt.data.$.ctrlKey && !evt.data.$.shiftKey ) preventBeforePasteEventNow(); }, null, null, 0 ); } editable.on( 'beforecut', function() { !preventBeforePasteEvent && fixCut( editor ); } ); var mouseupTimeout; // Use editor.document instead of editable in non-IEs for observing mouseup // since editable won't fire the event if selection process started within // iframe and ended out of the editor (#9851). editable.attachListener( CKEDITOR.env.ie ? editable : editor.document.getDocumentElement(), 'mouseup', function() { mouseupTimeout = setTimeout( function() { setToolbarStates(); }, 0 ); } ); // Make sure that deferred mouseup callback isn't executed after editor instance // had been destroyed. This may happen when editor.destroy() is called in parallel // with mouseup event (i.e. a button with onclick callback) (#10219). editor.on( 'destroy', function() { clearTimeout( mouseupTimeout ); } ); editable.on( 'keyup', setToolbarStates ); }
javascript
function addListenersToEditable() { var editable = editor.editable(); // We'll be catching all pasted content in one line, regardless of whether // it's introduced by a document command execution (e.g. toolbar buttons) or // user paste behaviors (e.g. CTRL+V). editable.on( mainPasteEvent, function( evt ) { if ( CKEDITOR.env.ie && preventBeforePasteEvent ) return; // If you've just asked yourself why preventPasteEventNow() is not here, but // in listener for CTRL+V and exec method of 'paste' command // you've asked the same question we did. // // THE ANSWER: // // First thing to notice - this answer makes sense only for IE, // because other browsers don't listen for 'paste' event. // // What would happen if we move preventPasteEventNow() here? // For: // * CTRL+V - IE fires 'beforepaste', so we prevent 'paste' and pasteDataFromClipboard(). OK. // * editor.execCommand( 'paste' ) - we fire 'beforepaste', so we prevent // 'paste' and pasteDataFromClipboard() and doc.execCommand( 'Paste' ). OK. // * native context menu - IE fires 'beforepaste', so we prevent 'paste', but unfortunately // on IE we fail with pasteDataFromClipboard() here, because of... we don't know why, but // we just fail, so... we paste nothing. FAIL. // * native menu bar - the same as for native context menu. // // But don't you know any way to distinguish first two cases from last two? // Only one - special flag set in CTRL+V handler and exec method of 'paste' // command. And that's what we did using preventPasteEventNow(). pasteDataFromClipboard( evt ); } ); // It's not possible to clearly handle all four paste methods (ctrl+v, native menu bar // native context menu, editor's command) in one 'paste/beforepaste' event in IE. // // For ctrl+v & editor's command it's easy to handle pasting in 'beforepaste' listener, // so we do this. For another two methods it's better to use 'paste' event. // // 'paste' is always being fired after 'beforepaste' (except of weird one on opening native // context menu), so for two methods handled in 'beforepaste' we're canceling 'paste' // using preventPasteEvent state. // // 'paste' event in IE is being fired before getClipboardDataByPastebin executes its callback. // // QUESTION: Why didn't you handle all 4 paste methods in handler for 'paste'? // Wouldn't this just be simpler? // ANSWER: Then we would have to evt.data.preventDefault() only for native // context menu and menu bar pastes. The same with execIECommand(). // That would force us to mark CTRL+V and editor's paste command with // special flag, other than preventPasteEvent. But we still would have to // have preventPasteEvent for the second event fired by execIECommand. // Code would be longer and not cleaner. CKEDITOR.env.ie && editable.on( 'paste', function( evt ) { if ( preventPasteEvent ) return; // Cancel next 'paste' event fired by execIECommand( 'paste' ) // at the end of this callback. preventPasteEventNow(); // Prevent native paste. evt.data.preventDefault(); pasteDataFromClipboard( evt ); // Force IE to paste content into pastebin so pasteDataFromClipboard will work. if ( !execIECommand( 'paste' ) ) editor.openDialog( 'paste' ); } ); // [IE] Dismiss the (wrong) 'beforepaste' event fired on context/toolbar menu open. (#7953) if ( CKEDITOR.env.ie ) { editable.on( 'contextmenu', preventBeforePasteEventNow, null, null, 0 ); editable.on( 'beforepaste', function( evt ) { // Do not prevent event on CTRL+V and SHIFT+INS because it blocks paste (#11970). if ( evt.data && !evt.data.$.ctrlKey && !evt.data.$.shiftKey ) preventBeforePasteEventNow(); }, null, null, 0 ); } editable.on( 'beforecut', function() { !preventBeforePasteEvent && fixCut( editor ); } ); var mouseupTimeout; // Use editor.document instead of editable in non-IEs for observing mouseup // since editable won't fire the event if selection process started within // iframe and ended out of the editor (#9851). editable.attachListener( CKEDITOR.env.ie ? editable : editor.document.getDocumentElement(), 'mouseup', function() { mouseupTimeout = setTimeout( function() { setToolbarStates(); }, 0 ); } ); // Make sure that deferred mouseup callback isn't executed after editor instance // had been destroyed. This may happen when editor.destroy() is called in parallel // with mouseup event (i.e. a button with onclick callback) (#10219). editor.on( 'destroy', function() { clearTimeout( mouseupTimeout ); } ); editable.on( 'keyup', setToolbarStates ); }
[ "function", "addListenersToEditable", "(", ")", "{", "var", "editable", "=", "editor", ".", "editable", "(", ")", ";", "// We'll be catching all pasted content in one line, regardless of whether\r", "// it's introduced by a document command execution (e.g. toolbar buttons) or\r", "// user paste behaviors (e.g. CTRL+V).\r", "editable", ".", "on", "(", "mainPasteEvent", ",", "function", "(", "evt", ")", "{", "if", "(", "CKEDITOR", ".", "env", ".", "ie", "&&", "preventBeforePasteEvent", ")", "return", ";", "// If you've just asked yourself why preventPasteEventNow() is not here, but\r", "// in listener for CTRL+V and exec method of 'paste' command\r", "// you've asked the same question we did.\r", "//\r", "// THE ANSWER:\r", "//\r", "// First thing to notice - this answer makes sense only for IE,\r", "// because other browsers don't listen for 'paste' event.\r", "//\r", "// What would happen if we move preventPasteEventNow() here?\r", "// For:\r", "// * CTRL+V - IE fires 'beforepaste', so we prevent 'paste' and pasteDataFromClipboard(). OK.\r", "// * editor.execCommand( 'paste' ) - we fire 'beforepaste', so we prevent\r", "//\t\t'paste' and pasteDataFromClipboard() and doc.execCommand( 'Paste' ). OK.\r", "// * native context menu - IE fires 'beforepaste', so we prevent 'paste', but unfortunately\r", "//\t\ton IE we fail with pasteDataFromClipboard() here, because of... we don't know why, but\r", "//\t\twe just fail, so... we paste nothing. FAIL.\r", "// * native menu bar - the same as for native context menu.\r", "//\r", "// But don't you know any way to distinguish first two cases from last two?\r", "// Only one - special flag set in CTRL+V handler and exec method of 'paste'\r", "// command. And that's what we did using preventPasteEventNow().\r", "pasteDataFromClipboard", "(", "evt", ")", ";", "}", ")", ";", "// It's not possible to clearly handle all four paste methods (ctrl+v, native menu bar\r", "// native context menu, editor's command) in one 'paste/beforepaste' event in IE.\r", "//\r", "// For ctrl+v & editor's command it's easy to handle pasting in 'beforepaste' listener,\r", "// so we do this. For another two methods it's better to use 'paste' event.\r", "//\r", "// 'paste' is always being fired after 'beforepaste' (except of weird one on opening native\r", "// context menu), so for two methods handled in 'beforepaste' we're canceling 'paste'\r", "// using preventPasteEvent state.\r", "//\r", "// 'paste' event in IE is being fired before getClipboardDataByPastebin executes its callback.\r", "//\r", "// QUESTION: Why didn't you handle all 4 paste methods in handler for 'paste'?\r", "//\t\tWouldn't this just be simpler?\r", "// ANSWER: Then we would have to evt.data.preventDefault() only for native\r", "//\t\tcontext menu and menu bar pastes. The same with execIECommand().\r", "//\t\tThat would force us to mark CTRL+V and editor's paste command with\r", "//\t\tspecial flag, other than preventPasteEvent. But we still would have to\r", "//\t\thave preventPasteEvent for the second event fired by execIECommand.\r", "//\t\tCode would be longer and not cleaner.\r", "CKEDITOR", ".", "env", ".", "ie", "&&", "editable", ".", "on", "(", "'paste'", ",", "function", "(", "evt", ")", "{", "if", "(", "preventPasteEvent", ")", "return", ";", "// Cancel next 'paste' event fired by execIECommand( 'paste' )\r", "// at the end of this callback.\r", "preventPasteEventNow", "(", ")", ";", "// Prevent native paste.\r", "evt", ".", "data", ".", "preventDefault", "(", ")", ";", "pasteDataFromClipboard", "(", "evt", ")", ";", "// Force IE to paste content into pastebin so pasteDataFromClipboard will work.\r", "if", "(", "!", "execIECommand", "(", "'paste'", ")", ")", "editor", ".", "openDialog", "(", "'paste'", ")", ";", "}", ")", ";", "// [IE] Dismiss the (wrong) 'beforepaste' event fired on context/toolbar menu open. (#7953)\r", "if", "(", "CKEDITOR", ".", "env", ".", "ie", ")", "{", "editable", ".", "on", "(", "'contextmenu'", ",", "preventBeforePasteEventNow", ",", "null", ",", "null", ",", "0", ")", ";", "editable", ".", "on", "(", "'beforepaste'", ",", "function", "(", "evt", ")", "{", "// Do not prevent event on CTRL+V and SHIFT+INS because it blocks paste (#11970).\r", "if", "(", "evt", ".", "data", "&&", "!", "evt", ".", "data", ".", "$", ".", "ctrlKey", "&&", "!", "evt", ".", "data", ".", "$", ".", "shiftKey", ")", "preventBeforePasteEventNow", "(", ")", ";", "}", ",", "null", ",", "null", ",", "0", ")", ";", "}", "editable", ".", "on", "(", "'beforecut'", ",", "function", "(", ")", "{", "!", "preventBeforePasteEvent", "&&", "fixCut", "(", "editor", ")", ";", "}", ")", ";", "var", "mouseupTimeout", ";", "// Use editor.document instead of editable in non-IEs for observing mouseup\r", "// since editable won't fire the event if selection process started within\r", "// iframe and ended out of the editor (#9851).\r", "editable", ".", "attachListener", "(", "CKEDITOR", ".", "env", ".", "ie", "?", "editable", ":", "editor", ".", "document", ".", "getDocumentElement", "(", ")", ",", "'mouseup'", ",", "function", "(", ")", "{", "mouseupTimeout", "=", "setTimeout", "(", "function", "(", ")", "{", "setToolbarStates", "(", ")", ";", "}", ",", "0", ")", ";", "}", ")", ";", "// Make sure that deferred mouseup callback isn't executed after editor instance\r", "// had been destroyed. This may happen when editor.destroy() is called in parallel\r", "// with mouseup event (i.e. a button with onclick callback) (#10219).\r", "editor", ".", "on", "(", "'destroy'", ",", "function", "(", ")", "{", "clearTimeout", "(", "mouseupTimeout", ")", ";", "}", ")", ";", "editable", ".", "on", "(", "'keyup'", ",", "setToolbarStates", ")", ";", "}" ]
Add events listeners to editable.
[ "Add", "events", "listeners", "to", "editable", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/clipboard/plugin.js#L393-L501
54,415
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/clipboard/plugin.js
createCutCopyCmd
function createCutCopyCmd( type ) { return { type: type, canUndo: type == 'cut', // We can't undo copy to clipboard. startDisabled: true, exec: function( data ) { // Attempts to execute the Cut and Copy operations. function tryToCutCopy( type ) { if ( CKEDITOR.env.ie ) return execIECommand( type ); // non-IEs part try { // Other browsers throw an error if the command is disabled. return editor.document.$.execCommand( type, false, null ); } catch ( e ) { return false; } } this.type == 'cut' && fixCut(); var success = tryToCutCopy( this.type ); if ( !success ) alert( editor.lang.clipboard[ this.type + 'Error' ] ); // Show cutError or copyError. return success; } }; }
javascript
function createCutCopyCmd( type ) { return { type: type, canUndo: type == 'cut', // We can't undo copy to clipboard. startDisabled: true, exec: function( data ) { // Attempts to execute the Cut and Copy operations. function tryToCutCopy( type ) { if ( CKEDITOR.env.ie ) return execIECommand( type ); // non-IEs part try { // Other browsers throw an error if the command is disabled. return editor.document.$.execCommand( type, false, null ); } catch ( e ) { return false; } } this.type == 'cut' && fixCut(); var success = tryToCutCopy( this.type ); if ( !success ) alert( editor.lang.clipboard[ this.type + 'Error' ] ); // Show cutError or copyError. return success; } }; }
[ "function", "createCutCopyCmd", "(", "type", ")", "{", "return", "{", "type", ":", "type", ",", "canUndo", ":", "type", "==", "'cut'", ",", "// We can't undo copy to clipboard.\r", "startDisabled", ":", "true", ",", "exec", ":", "function", "(", "data", ")", "{", "// Attempts to execute the Cut and Copy operations.\r", "function", "tryToCutCopy", "(", "type", ")", "{", "if", "(", "CKEDITOR", ".", "env", ".", "ie", ")", "return", "execIECommand", "(", "type", ")", ";", "// non-IEs part\r", "try", "{", "// Other browsers throw an error if the command is disabled.\r", "return", "editor", ".", "document", ".", "$", ".", "execCommand", "(", "type", ",", "false", ",", "null", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "}", "this", ".", "type", "==", "'cut'", "&&", "fixCut", "(", ")", ";", "var", "success", "=", "tryToCutCopy", "(", "this", ".", "type", ")", ";", "if", "(", "!", "success", ")", "alert", "(", "editor", ".", "lang", ".", "clipboard", "[", "this", ".", "type", "+", "'Error'", "]", ")", ";", "// Show cutError or copyError.\r", "return", "success", ";", "}", "}", ";", "}" ]
Create object representing Cut or Copy commands.
[ "Create", "object", "representing", "Cut", "or", "Copy", "commands", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/clipboard/plugin.js#L504-L534
54,416
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/clipboard/plugin.js
tryToCutCopy
function tryToCutCopy( type ) { if ( CKEDITOR.env.ie ) return execIECommand( type ); // non-IEs part try { // Other browsers throw an error if the command is disabled. return editor.document.$.execCommand( type, false, null ); } catch ( e ) { return false; } }
javascript
function tryToCutCopy( type ) { if ( CKEDITOR.env.ie ) return execIECommand( type ); // non-IEs part try { // Other browsers throw an error if the command is disabled. return editor.document.$.execCommand( type, false, null ); } catch ( e ) { return false; } }
[ "function", "tryToCutCopy", "(", "type", ")", "{", "if", "(", "CKEDITOR", ".", "env", ".", "ie", ")", "return", "execIECommand", "(", "type", ")", ";", "// non-IEs part\r", "try", "{", "// Other browsers throw an error if the command is disabled.\r", "return", "editor", ".", "document", ".", "$", ".", "execCommand", "(", "type", ",", "false", ",", "null", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "}" ]
Attempts to execute the Cut and Copy operations.
[ "Attempts", "to", "execute", "the", "Cut", "and", "Copy", "operations", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/clipboard/plugin.js#L511-L522
54,417
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/clipboard/plugin.js
execIECommand
function execIECommand( command ) { var doc = editor.document, body = doc.getBody(), enabled = false, onExec = function() { enabled = true; }; // The following seems to be the only reliable way to detect that // clipboard commands are enabled in IE. It will fire the // onpaste/oncut/oncopy events only if the security settings allowed // the command to execute. body.on( command, onExec ); // IE7: document.execCommand has problem to paste into positioned element. ( CKEDITOR.env.version > 7 ? doc.$ : doc.$.selection.createRange() )[ 'execCommand' ]( command ); body.removeListener( command, onExec ); return enabled; }
javascript
function execIECommand( command ) { var doc = editor.document, body = doc.getBody(), enabled = false, onExec = function() { enabled = true; }; // The following seems to be the only reliable way to detect that // clipboard commands are enabled in IE. It will fire the // onpaste/oncut/oncopy events only if the security settings allowed // the command to execute. body.on( command, onExec ); // IE7: document.execCommand has problem to paste into positioned element. ( CKEDITOR.env.version > 7 ? doc.$ : doc.$.selection.createRange() )[ 'execCommand' ]( command ); body.removeListener( command, onExec ); return enabled; }
[ "function", "execIECommand", "(", "command", ")", "{", "var", "doc", "=", "editor", ".", "document", ",", "body", "=", "doc", ".", "getBody", "(", ")", ",", "enabled", "=", "false", ",", "onExec", "=", "function", "(", ")", "{", "enabled", "=", "true", ";", "}", ";", "// The following seems to be the only reliable way to detect that\r", "// clipboard commands are enabled in IE. It will fire the\r", "// onpaste/oncut/oncopy events only if the security settings allowed\r", "// the command to execute.\r", "body", ".", "on", "(", "command", ",", "onExec", ")", ";", "// IE7: document.execCommand has problem to paste into positioned element.\r", "(", "CKEDITOR", ".", "env", ".", "version", ">", "7", "?", "doc", ".", "$", ":", "doc", ".", "$", ".", "selection", ".", "createRange", "(", ")", ")", "[", "'execCommand'", "]", "(", "command", ")", ";", "body", ".", "removeListener", "(", "command", ",", "onExec", ")", ";", "return", "enabled", ";", "}" ]
Tries to execute any of the paste, cut or copy commands in IE. Returns a boolean indicating that the operation succeeded. @param {String} command *LOWER CASED* name of command ('paste', 'cut', 'copy').
[ "Tries", "to", "execute", "any", "of", "the", "paste", "cut", "or", "copy", "commands", "in", "IE", ".", "Returns", "a", "boolean", "indicating", "that", "the", "operation", "succeeded", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/clipboard/plugin.js#L586-L606
54,418
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/clipboard/plugin.js
onKey
function onKey( event ) { if ( editor.mode != 'wysiwyg' ) return; switch ( event.data.keyCode ) { // Paste case CKEDITOR.CTRL + 86: // CTRL+V case CKEDITOR.SHIFT + 45: // SHIFT+INS var editable = editor.editable(); // Cancel 'paste' event because ctrl+v is for IE handled // by 'beforepaste'. preventPasteEventNow(); // Simulate 'beforepaste' event for all none-IEs. !CKEDITOR.env.ie && editable.fire( 'beforepaste' ); return; // Cut case CKEDITOR.CTRL + 88: // CTRL+X case CKEDITOR.SHIFT + 46: // SHIFT+DEL // Save Undo snapshot. editor.fire( 'saveSnapshot' ); // Save before cut setTimeout( function() { editor.fire( 'saveSnapshot' ); // Save after cut }, 50 ); // OSX is slow (#11416). } }
javascript
function onKey( event ) { if ( editor.mode != 'wysiwyg' ) return; switch ( event.data.keyCode ) { // Paste case CKEDITOR.CTRL + 86: // CTRL+V case CKEDITOR.SHIFT + 45: // SHIFT+INS var editable = editor.editable(); // Cancel 'paste' event because ctrl+v is for IE handled // by 'beforepaste'. preventPasteEventNow(); // Simulate 'beforepaste' event for all none-IEs. !CKEDITOR.env.ie && editable.fire( 'beforepaste' ); return; // Cut case CKEDITOR.CTRL + 88: // CTRL+X case CKEDITOR.SHIFT + 46: // SHIFT+DEL // Save Undo snapshot. editor.fire( 'saveSnapshot' ); // Save before cut setTimeout( function() { editor.fire( 'saveSnapshot' ); // Save after cut }, 50 ); // OSX is slow (#11416). } }
[ "function", "onKey", "(", "event", ")", "{", "if", "(", "editor", ".", "mode", "!=", "'wysiwyg'", ")", "return", ";", "switch", "(", "event", ".", "data", ".", "keyCode", ")", "{", "// Paste\r", "case", "CKEDITOR", ".", "CTRL", "+", "86", ":", "// CTRL+V\r", "case", "CKEDITOR", ".", "SHIFT", "+", "45", ":", "// SHIFT+INS\r", "var", "editable", "=", "editor", ".", "editable", "(", ")", ";", "// Cancel 'paste' event because ctrl+v is for IE handled\r", "// by 'beforepaste'.\r", "preventPasteEventNow", "(", ")", ";", "// Simulate 'beforepaste' event for all none-IEs.\r", "!", "CKEDITOR", ".", "env", ".", "ie", "&&", "editable", ".", "fire", "(", "'beforepaste'", ")", ";", "return", ";", "// Cut\r", "case", "CKEDITOR", ".", "CTRL", "+", "88", ":", "// CTRL+X\r", "case", "CKEDITOR", ".", "SHIFT", "+", "46", ":", "// SHIFT+DEL\r", "// Save Undo snapshot.\r", "editor", ".", "fire", "(", "'saveSnapshot'", ")", ";", "// Save before cut\r", "setTimeout", "(", "function", "(", ")", "{", "editor", ".", "fire", "(", "'saveSnapshot'", ")", ";", "// Save after cut\r", "}", ",", "50", ")", ";", "// OSX is slow (#11416).\r", "}", "}" ]
Listens for some clipboard related keystrokes, so they get customized. Needs to be bind to keydown event.
[ "Listens", "for", "some", "clipboard", "related", "keystrokes", "so", "they", "get", "customized", ".", "Needs", "to", "be", "bind", "to", "keydown", "event", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/clipboard/plugin.js#L854-L882
54,419
lipcoin/lipcore-p2p
lib/peer.js
Peer
function Peer(options) { /* jshint maxstatements: 26 */ /* jshint maxcomplexity: 8 */ if (!(this instanceof Peer)) { return new Peer(options); } if (options.socket) { this.socket = options.socket; this.host = this.socket.remoteAddress; this.port = this.socket.remotePort; this.status = Peer.STATUS.CONNECTED; this._addSocketEventHandlers(); } else { this.host = options.host || 'localhost'; this.status = Peer.STATUS.DISCONNECTED; this.port = options.port; } this.network = Networks.get(options.network) || Networks.defaultNetwork; if (!this.port) { this.port = this.network.port; } this.messages = options.messages || new Messages({ network: this.network, Block: bitcore.Block, Transaction: bitcore.Transaction }); this.dataBuffer = new Buffers(); this.version = 0; this.bestHeight = 0; this.subversion = null; this.relay = options.relay === false ? false : true; this.versionSent = false; // set message handlers var self = this; this.on('verack', function() { self.status = Peer.STATUS.READY; self.emit('ready'); }); this.on('version', function(message) { self.version = message.version; self.subversion = message.subversion; self.bestHeight = message.startHeight; var verackResponse = self.messages.VerAck(); self.sendMessage(verackResponse); if(!self.versionSent) { self._sendVersion(); } }); this.on('ping', function(message) { self._sendPong(message.nonce); }); return this; }
javascript
function Peer(options) { /* jshint maxstatements: 26 */ /* jshint maxcomplexity: 8 */ if (!(this instanceof Peer)) { return new Peer(options); } if (options.socket) { this.socket = options.socket; this.host = this.socket.remoteAddress; this.port = this.socket.remotePort; this.status = Peer.STATUS.CONNECTED; this._addSocketEventHandlers(); } else { this.host = options.host || 'localhost'; this.status = Peer.STATUS.DISCONNECTED; this.port = options.port; } this.network = Networks.get(options.network) || Networks.defaultNetwork; if (!this.port) { this.port = this.network.port; } this.messages = options.messages || new Messages({ network: this.network, Block: bitcore.Block, Transaction: bitcore.Transaction }); this.dataBuffer = new Buffers(); this.version = 0; this.bestHeight = 0; this.subversion = null; this.relay = options.relay === false ? false : true; this.versionSent = false; // set message handlers var self = this; this.on('verack', function() { self.status = Peer.STATUS.READY; self.emit('ready'); }); this.on('version', function(message) { self.version = message.version; self.subversion = message.subversion; self.bestHeight = message.startHeight; var verackResponse = self.messages.VerAck(); self.sendMessage(verackResponse); if(!self.versionSent) { self._sendVersion(); } }); this.on('ping', function(message) { self._sendPong(message.nonce); }); return this; }
[ "function", "Peer", "(", "options", ")", "{", "/* jshint maxstatements: 26 */", "/* jshint maxcomplexity: 8 */", "if", "(", "!", "(", "this", "instanceof", "Peer", ")", ")", "{", "return", "new", "Peer", "(", "options", ")", ";", "}", "if", "(", "options", ".", "socket", ")", "{", "this", ".", "socket", "=", "options", ".", "socket", ";", "this", ".", "host", "=", "this", ".", "socket", ".", "remoteAddress", ";", "this", ".", "port", "=", "this", ".", "socket", ".", "remotePort", ";", "this", ".", "status", "=", "Peer", ".", "STATUS", ".", "CONNECTED", ";", "this", ".", "_addSocketEventHandlers", "(", ")", ";", "}", "else", "{", "this", ".", "host", "=", "options", ".", "host", "||", "'localhost'", ";", "this", ".", "status", "=", "Peer", ".", "STATUS", ".", "DISCONNECTED", ";", "this", ".", "port", "=", "options", ".", "port", ";", "}", "this", ".", "network", "=", "Networks", ".", "get", "(", "options", ".", "network", ")", "||", "Networks", ".", "defaultNetwork", ";", "if", "(", "!", "this", ".", "port", ")", "{", "this", ".", "port", "=", "this", ".", "network", ".", "port", ";", "}", "this", ".", "messages", "=", "options", ".", "messages", "||", "new", "Messages", "(", "{", "network", ":", "this", ".", "network", ",", "Block", ":", "bitcore", ".", "Block", ",", "Transaction", ":", "bitcore", ".", "Transaction", "}", ")", ";", "this", ".", "dataBuffer", "=", "new", "Buffers", "(", ")", ";", "this", ".", "version", "=", "0", ";", "this", ".", "bestHeight", "=", "0", ";", "this", ".", "subversion", "=", "null", ";", "this", ".", "relay", "=", "options", ".", "relay", "===", "false", "?", "false", ":", "true", ";", "this", ".", "versionSent", "=", "false", ";", "// set message handlers", "var", "self", "=", "this", ";", "this", ".", "on", "(", "'verack'", ",", "function", "(", ")", "{", "self", ".", "status", "=", "Peer", ".", "STATUS", ".", "READY", ";", "self", ".", "emit", "(", "'ready'", ")", ";", "}", ")", ";", "this", ".", "on", "(", "'version'", ",", "function", "(", "message", ")", "{", "self", ".", "version", "=", "message", ".", "version", ";", "self", ".", "subversion", "=", "message", ".", "subversion", ";", "self", ".", "bestHeight", "=", "message", ".", "startHeight", ";", "var", "verackResponse", "=", "self", ".", "messages", ".", "VerAck", "(", ")", ";", "self", ".", "sendMessage", "(", "verackResponse", ")", ";", "if", "(", "!", "self", ".", "versionSent", ")", "{", "self", ".", "_sendVersion", "(", ")", ";", "}", "}", ")", ";", "this", ".", "on", "(", "'ping'", ",", "function", "(", "message", ")", "{", "self", ".", "_sendPong", "(", "message", ".", "nonce", ")", ";", "}", ")", ";", "return", "this", ";", "}" ]
The Peer constructor will create an instance of Peer to send and receive messages using the standard Bitcoin protocol. A Peer instance represents one connection on the Bitcoin network. To create a new peer connection provide the host and port options and then invoke the connect method. Additionally, a newly connected socket can be provided instead of host and port. @example ```javascript var peer = new Peer({host: '127.0.0.1'}).setProxy('127.0.0.1', 9050); peer.on('tx', function(tx) { console.log('New transaction: ', tx.id); }); peer.connect(); ``` @param {Object} options @param {String} options.host - IP address of the remote host @param {Number} options.port - Port number of the remote host @param {Network} options.network - The network configuration @param {Boolean=} options.relay - An option to disable automatic inventory relaying from the remote peer @param {Socket=} options.socket - An existing connected socket @returns {Peer} A new instance of Peer. @constructor
[ "The", "Peer", "constructor", "will", "create", "an", "instance", "of", "Peer", "to", "send", "and", "receive", "messages", "using", "the", "standard", "Bitcoin", "protocol", ".", "A", "Peer", "instance", "represents", "one", "connection", "on", "the", "Bitcoin", "network", ".", "To", "create", "a", "new", "peer", "connection", "provide", "the", "host", "and", "port", "options", "and", "then", "invoke", "the", "connect", "method", ".", "Additionally", "a", "newly", "connected", "socket", "can", "be", "provided", "instead", "of", "host", "and", "port", "." ]
d2000feb9ffdc6390a47981f1663c1ab71aa1de9
https://github.com/lipcoin/lipcore-p2p/blob/d2000feb9ffdc6390a47981f1663c1ab71aa1de9/lib/peer.js#L40-L107
54,420
rhyolight/github-data
lib/commit.js
Commit
function Commit(source, githubClient) { this.gh = githubClient; this.sha = source.sha; this.htmlUrl = source.html_url; this.author = source.author; this.committer = source.committer; this.message = source.message; this.treeSha = source.tree.sha; this.tree = undefined; }
javascript
function Commit(source, githubClient) { this.gh = githubClient; this.sha = source.sha; this.htmlUrl = source.html_url; this.author = source.author; this.committer = source.committer; this.message = source.message; this.treeSha = source.tree.sha; this.tree = undefined; }
[ "function", "Commit", "(", "source", ",", "githubClient", ")", "{", "this", ".", "gh", "=", "githubClient", ";", "this", ".", "sha", "=", "source", ".", "sha", ";", "this", ".", "htmlUrl", "=", "source", ".", "html_url", ";", "this", ".", "author", "=", "source", ".", "author", ";", "this", ".", "committer", "=", "source", ".", "committer", ";", "this", ".", "message", "=", "source", ".", "message", ";", "this", ".", "treeSha", "=", "source", ".", "tree", ".", "sha", ";", "this", ".", "tree", "=", "undefined", ";", "}" ]
A git commit object. Contains a tree. @class Commit @param source {Object} JSON response from API, used to build. @param githubClient {Object} GitHub API Client object. @constructor
[ "A", "git", "commit", "object", ".", "Contains", "a", "tree", "." ]
5d6a3fc0e7ecfeaec03e4815b0940c2d9ce07d64
https://github.com/rhyolight/github-data/blob/5d6a3fc0e7ecfeaec03e4815b0940c2d9ce07d64/lib/commit.js#L10-L19
54,421
rranauro/boxspringjs
helpers.js
function(obj, d) { var k; d = typeof d === 'undefined' ? 0 : d; d += 1; for (k in obj) { if (obj.hasOwnProperty(k) && _.isObject(obj[k])) { return depth(obj[k], d); } } return (d); }
javascript
function(obj, d) { var k; d = typeof d === 'undefined' ? 0 : d; d += 1; for (k in obj) { if (obj.hasOwnProperty(k) && _.isObject(obj[k])) { return depth(obj[k], d); } } return (d); }
[ "function", "(", "obj", ",", "d", ")", "{", "var", "k", ";", "d", "=", "typeof", "d", "===", "'undefined'", "?", "0", ":", "d", ";", "d", "+=", "1", ";", "for", "(", "k", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "k", ")", "&&", "_", ".", "isObject", "(", "obj", "[", "k", "]", ")", ")", "{", "return", "depth", "(", "obj", "[", "k", "]", ",", "d", ")", ";", "}", "}", "return", "(", "d", ")", ";", "}" ]
calculate the hierarchical depth of an object
[ "calculate", "the", "hierarchical", "depth", "of", "an", "object" ]
43fd13ae45ba5b16ba9144084b96748a1cd8c0ea
https://github.com/rranauro/boxspringjs/blob/43fd13ae45ba5b16ba9144084b96748a1cd8c0ea/helpers.js#L162-L173
54,422
rranauro/boxspringjs
helpers.js
function(year) { var yr; if (!year) { // initialize date "buckets" for year and month; year = [1900, 2100]; this._years = {}; for (yr = year[0]; yr <= year[1]; yr += 1) { this._years[yr] = new Year(yr); } } else { this.year = year; } return this; }
javascript
function(year) { var yr; if (!year) { // initialize date "buckets" for year and month; year = [1900, 2100]; this._years = {}; for (yr = year[0]; yr <= year[1]; yr += 1) { this._years[yr] = new Year(yr); } } else { this.year = year; } return this; }
[ "function", "(", "year", ")", "{", "var", "yr", ";", "if", "(", "!", "year", ")", "{", "// initialize date \"buckets\" for year and month;", "year", "=", "[", "1900", ",", "2100", "]", ";", "this", ".", "_years", "=", "{", "}", ";", "for", "(", "yr", "=", "year", "[", "0", "]", ";", "yr", "<=", "year", "[", "1", "]", ";", "yr", "+=", "1", ")", "{", "this", ".", "_years", "[", "yr", "]", "=", "new", "Year", "(", "yr", ")", ";", "}", "}", "else", "{", "this", ".", "year", "=", "year", ";", "}", "return", "this", ";", "}" ]
define an object for time buckets
[ "define", "an", "object", "for", "time", "buckets" ]
43fd13ae45ba5b16ba9144084b96748a1cd8c0ea
https://github.com/rranauro/boxspringjs/blob/43fd13ae45ba5b16ba9144084b96748a1cd8c0ea/helpers.js#L433-L448
54,423
rranauro/boxspringjs
helpers.js
function() { var _findYear = function(years) { return _.toInt( _.reduce(years, function(res, year) { return res || ((this._years[year].sum() > 0) ? year : undefined); }, undefined, this) ); }; if (!_findYear.call(this, _.keys(this._years))) { return []; } return _.range( _findYear.call(this, _.keys(this._years)), (_findYear.call(this, _.keys(this._years).reverse() )+1) ); }
javascript
function() { var _findYear = function(years) { return _.toInt( _.reduce(years, function(res, year) { return res || ((this._years[year].sum() > 0) ? year : undefined); }, undefined, this) ); }; if (!_findYear.call(this, _.keys(this._years))) { return []; } return _.range( _findYear.call(this, _.keys(this._years)), (_findYear.call(this, _.keys(this._years).reverse() )+1) ); }
[ "function", "(", ")", "{", "var", "_findYear", "=", "function", "(", "years", ")", "{", "return", "_", ".", "toInt", "(", "_", ".", "reduce", "(", "years", ",", "function", "(", "res", ",", "year", ")", "{", "return", "res", "||", "(", "(", "this", ".", "_years", "[", "year", "]", ".", "sum", "(", ")", ">", "0", ")", "?", "year", ":", "undefined", ")", ";", "}", ",", "undefined", ",", "this", ")", ")", ";", "}", ";", "if", "(", "!", "_findYear", ".", "call", "(", "this", ",", "_", ".", "keys", "(", "this", ".", "_years", ")", ")", ")", "{", "return", "[", "]", ";", "}", "return", "_", ".", "range", "(", "_findYear", ".", "call", "(", "this", ",", "_", ".", "keys", "(", "this", ".", "_years", ")", ")", ",", "(", "_findYear", ".", "call", "(", "this", ",", "_", ".", "keys", "(", "this", ".", "_years", ")", ".", "reverse", "(", ")", ")", "+", "1", ")", ")", ";", "}" ]
return the beginning of the range at the first accumulated value and the end of the range at the last accumulated value;
[ "return", "the", "beginning", "of", "the", "range", "at", "the", "first", "accumulated", "value", "and", "the", "end", "of", "the", "range", "at", "the", "last", "accumulated", "value", ";" ]
43fd13ae45ba5b16ba9144084b96748a1cd8c0ea
https://github.com/rranauro/boxspringjs/blob/43fd13ae45ba5b16ba9144084b96748a1cd8c0ea/helpers.js#L504-L515
54,424
rranauro/boxspringjs
helpers.js
function(hash) { return function(row) { var testValue = function(value, rowValue) { if (value === '*' || value === '' || !value) { return true; } if (_.isString(rowValue)) { return (rowValue.toLowerCase() === value.toLowerCase()); } if (_.isArray(rowValue)) { return (_.contains(_.map(rowValue, function(tag) { return _.isString(tag) && tag.toLowerCase(); }), value.toLowerCase()) && true); } return false; }; // _.all makes sure all members of the hash pass return _.all(hash, function(value, key) { var rowValue = row.getAlias(key); if (rowValue) { // if the filter value is an array, then the rowValue must also be an array if (_.isArray(value) && _.isArray(rowValue)) { // expression is true if rowValue intersects completely with requested value. return _.intersection(value, rowValue).length === value.length; } // if the value is an array, but not the rowValue, only test the first index; return testValue(_.isArray(value) ? value[0] : value, rowValue) } return false; }); }; }
javascript
function(hash) { return function(row) { var testValue = function(value, rowValue) { if (value === '*' || value === '' || !value) { return true; } if (_.isString(rowValue)) { return (rowValue.toLowerCase() === value.toLowerCase()); } if (_.isArray(rowValue)) { return (_.contains(_.map(rowValue, function(tag) { return _.isString(tag) && tag.toLowerCase(); }), value.toLowerCase()) && true); } return false; }; // _.all makes sure all members of the hash pass return _.all(hash, function(value, key) { var rowValue = row.getAlias(key); if (rowValue) { // if the filter value is an array, then the rowValue must also be an array if (_.isArray(value) && _.isArray(rowValue)) { // expression is true if rowValue intersects completely with requested value. return _.intersection(value, rowValue).length === value.length; } // if the value is an array, but not the rowValue, only test the first index; return testValue(_.isArray(value) ? value[0] : value, rowValue) } return false; }); }; }
[ "function", "(", "hash", ")", "{", "return", "function", "(", "row", ")", "{", "var", "testValue", "=", "function", "(", "value", ",", "rowValue", ")", "{", "if", "(", "value", "===", "'*'", "||", "value", "===", "''", "||", "!", "value", ")", "{", "return", "true", ";", "}", "if", "(", "_", ".", "isString", "(", "rowValue", ")", ")", "{", "return", "(", "rowValue", ".", "toLowerCase", "(", ")", "===", "value", ".", "toLowerCase", "(", ")", ")", ";", "}", "if", "(", "_", ".", "isArray", "(", "rowValue", ")", ")", "{", "return", "(", "_", ".", "contains", "(", "_", ".", "map", "(", "rowValue", ",", "function", "(", "tag", ")", "{", "return", "_", ".", "isString", "(", "tag", ")", "&&", "tag", ".", "toLowerCase", "(", ")", ";", "}", ")", ",", "value", ".", "toLowerCase", "(", ")", ")", "&&", "true", ")", ";", "}", "return", "false", ";", "}", ";", "// _.all makes sure all members of the hash pass", "return", "_", ".", "all", "(", "hash", ",", "function", "(", "value", ",", "key", ")", "{", "var", "rowValue", "=", "row", ".", "getAlias", "(", "key", ")", ";", "if", "(", "rowValue", ")", "{", "// if the filter value is an array, then the rowValue must also be an array", "if", "(", "_", ".", "isArray", "(", "value", ")", "&&", "_", ".", "isArray", "(", "rowValue", ")", ")", "{", "// expression is true if rowValue intersects completely with requested value.", "return", "_", ".", "intersection", "(", "value", ",", "rowValue", ")", ".", "length", "===", "value", ".", "length", ";", "}", "// if the value is an array, but not the rowValue, only test the first index;", "return", "testValue", "(", "_", ".", "isArray", "(", "value", ")", "?", "value", "[", "0", "]", ":", "value", ",", "rowValue", ")", "}", "return", "false", ";", "}", ")", ";", "}", ";", "}" ]
matcher returns a function based on the provided hash. The new function takes the query hash and returns true only if all property values in the query match each property value in the subject;
[ "matcher", "returns", "a", "function", "based", "on", "the", "provided", "hash", ".", "The", "new", "function", "takes", "the", "query", "hash", "and", "returns", "true", "only", "if", "all", "property", "values", "in", "the", "query", "match", "each", "property", "value", "in", "the", "subject", ";" ]
43fd13ae45ba5b16ba9144084b96748a1cd8c0ea
https://github.com/rranauro/boxspringjs/blob/43fd13ae45ba5b16ba9144084b96748a1cd8c0ea/helpers.js#L676-L712
54,425
rranauro/boxspringjs
helpers.js
function(json) { return({ values: json, depth: 1, // map over all rows to get the set of properties available in each document series_list: _.reduce(json, function(res, row, key) { return _.uniq( res.concat( _.plain( row ).keys().value() ) ); }, []) }); }
javascript
function(json) { return({ values: json, depth: 1, // map over all rows to get the set of properties available in each document series_list: _.reduce(json, function(res, row, key) { return _.uniq( res.concat( _.plain( row ).keys().value() ) ); }, []) }); }
[ "function", "(", "json", ")", "{", "return", "(", "{", "values", ":", "json", ",", "depth", ":", "1", ",", "// map over all rows to get the set of properties available in each document", "series_list", ":", "_", ".", "reduce", "(", "json", ",", "function", "(", "res", ",", "row", ",", "key", ")", "{", "return", "_", ".", "uniq", "(", "res", ".", "concat", "(", "_", ".", "plain", "(", "row", ")", ".", "keys", "(", ")", ".", "value", "(", ")", ")", ")", ";", "}", ",", "[", "]", ")", "}", ")", ";", "}" ]
format a collection of Rows into a json object compatible with the Google-Vis helper library.
[ "format", "a", "collection", "of", "Rows", "into", "a", "json", "object", "compatible", "with", "the", "Google", "-", "Vis", "helper", "library", "." ]
43fd13ae45ba5b16ba9144084b96748a1cd8c0ea
https://github.com/rranauro/boxspringjs/blob/43fd13ae45ba5b16ba9144084b96748a1cd8c0ea/helpers.js#L1017-L1027
54,426
gaiajs/gaiajs
lib/router/index.js
logRoute
function logRoute(routeConfig, filters) { filters = filters ? filters.join(', ') : ""; $log.info( '{method="%s", path="%s", filters="%s"} bind on controller %s#%s', routeConfig.method, routeConfig.path, filters, routeConfig.controller, routeConfig.action ); }
javascript
function logRoute(routeConfig, filters) { filters = filters ? filters.join(', ') : ""; $log.info( '{method="%s", path="%s", filters="%s"} bind on controller %s#%s', routeConfig.method, routeConfig.path, filters, routeConfig.controller, routeConfig.action ); }
[ "function", "logRoute", "(", "routeConfig", ",", "filters", ")", "{", "filters", "=", "filters", "?", "filters", ".", "join", "(", "', '", ")", ":", "\"\"", ";", "$log", ".", "info", "(", "'{method=\"%s\", path=\"%s\", filters=\"%s\"} bind on controller %s#%s'", ",", "routeConfig", ".", "method", ",", "routeConfig", ".", "path", ",", "filters", ",", "routeConfig", ".", "controller", ",", "routeConfig", ".", "action", ")", ";", "}" ]
helper for log route
[ "helper", "for", "log", "route" ]
a8ebc50274b83bed8bed007e691761bdc3b52eaa
https://github.com/gaiajs/gaiajs/blob/a8ebc50274b83bed8bed007e691761bdc3b52eaa/lib/router/index.js#L15-L25
54,427
gaiajs/gaiajs
lib/router/index.js
generateGenericControllers
function generateGenericControllers(controllers, models) { var genericControllers = {}, genericRoute = []; models.forEach(function(model) { var persistence = $database.getPersistenceOfModel(model); if (null == persistence) { throw new Error(''); } var defaultController = {}; var modelRest = model + "Rest"; if (controllers.hasOwnProperty(modelRest)) { defaultController = controllers[modelRest]; } else if (controllers.hasOwnProperty(utils.camelizePath(modelRest))) { defaultController = controllers[utils.camelizePath(modelRest)]; } var generatorController = persistence.generatorController; genericControllers[modelRest] = _.defaults({}, defaultController, generatorController.generate(persistence.repositories[model], true)); //create genericRoute.push({ method: 'post', controller: modelRest, action: 'create', path: '/' + model }); genericRoute.push({ method: 'get', controller: modelRest, action: 'createQuery', path: '/' + model + '/create' }); //Read genericRoute.push({ method: 'get', controller: modelRest, action: 'index', path: '/' + model }); genericRoute.push({ method: 'get', controller: modelRest, action: 'findById', path: '/' + model + '/:id' }); genericRoute.push({ method: 'get', controller: modelRest, action: 'find', path: '/' + model + '/find' }); //update genericRoute.push({ method: 'put', controller: modelRest, action: 'update', path: '/' + model + '/:id' }); genericRoute.push({ method: 'get', controller: modelRest, action: 'updateQuery', path: '/' + model + '/update/:id' }); //update genericRoute.push({ method: 'delete', controller: modelRest, action: 'delete', path: '/' + model + '/:id' }); genericRoute.push({ method: 'get', controller: modelRest, action: 'delete', path: '/' + model + '/delete/:id' }); }); return [genericControllers, genericRoute] }
javascript
function generateGenericControllers(controllers, models) { var genericControllers = {}, genericRoute = []; models.forEach(function(model) { var persistence = $database.getPersistenceOfModel(model); if (null == persistence) { throw new Error(''); } var defaultController = {}; var modelRest = model + "Rest"; if (controllers.hasOwnProperty(modelRest)) { defaultController = controllers[modelRest]; } else if (controllers.hasOwnProperty(utils.camelizePath(modelRest))) { defaultController = controllers[utils.camelizePath(modelRest)]; } var generatorController = persistence.generatorController; genericControllers[modelRest] = _.defaults({}, defaultController, generatorController.generate(persistence.repositories[model], true)); //create genericRoute.push({ method: 'post', controller: modelRest, action: 'create', path: '/' + model }); genericRoute.push({ method: 'get', controller: modelRest, action: 'createQuery', path: '/' + model + '/create' }); //Read genericRoute.push({ method: 'get', controller: modelRest, action: 'index', path: '/' + model }); genericRoute.push({ method: 'get', controller: modelRest, action: 'findById', path: '/' + model + '/:id' }); genericRoute.push({ method: 'get', controller: modelRest, action: 'find', path: '/' + model + '/find' }); //update genericRoute.push({ method: 'put', controller: modelRest, action: 'update', path: '/' + model + '/:id' }); genericRoute.push({ method: 'get', controller: modelRest, action: 'updateQuery', path: '/' + model + '/update/:id' }); //update genericRoute.push({ method: 'delete', controller: modelRest, action: 'delete', path: '/' + model + '/:id' }); genericRoute.push({ method: 'get', controller: modelRest, action: 'delete', path: '/' + model + '/delete/:id' }); }); return [genericControllers, genericRoute] }
[ "function", "generateGenericControllers", "(", "controllers", ",", "models", ")", "{", "var", "genericControllers", "=", "{", "}", ",", "genericRoute", "=", "[", "]", ";", "models", ".", "forEach", "(", "function", "(", "model", ")", "{", "var", "persistence", "=", "$database", ".", "getPersistenceOfModel", "(", "model", ")", ";", "if", "(", "null", "==", "persistence", ")", "{", "throw", "new", "Error", "(", "''", ")", ";", "}", "var", "defaultController", "=", "{", "}", ";", "var", "modelRest", "=", "model", "+", "\"Rest\"", ";", "if", "(", "controllers", ".", "hasOwnProperty", "(", "modelRest", ")", ")", "{", "defaultController", "=", "controllers", "[", "modelRest", "]", ";", "}", "else", "if", "(", "controllers", ".", "hasOwnProperty", "(", "utils", ".", "camelizePath", "(", "modelRest", ")", ")", ")", "{", "defaultController", "=", "controllers", "[", "utils", ".", "camelizePath", "(", "modelRest", ")", "]", ";", "}", "var", "generatorController", "=", "persistence", ".", "generatorController", ";", "genericControllers", "[", "modelRest", "]", "=", "_", ".", "defaults", "(", "{", "}", ",", "defaultController", ",", "generatorController", ".", "generate", "(", "persistence", ".", "repositories", "[", "model", "]", ",", "true", ")", ")", ";", "//create", "genericRoute", ".", "push", "(", "{", "method", ":", "'post'", ",", "controller", ":", "modelRest", ",", "action", ":", "'create'", ",", "path", ":", "'/'", "+", "model", "}", ")", ";", "genericRoute", ".", "push", "(", "{", "method", ":", "'get'", ",", "controller", ":", "modelRest", ",", "action", ":", "'createQuery'", ",", "path", ":", "'/'", "+", "model", "+", "'/create'", "}", ")", ";", "//Read", "genericRoute", ".", "push", "(", "{", "method", ":", "'get'", ",", "controller", ":", "modelRest", ",", "action", ":", "'index'", ",", "path", ":", "'/'", "+", "model", "}", ")", ";", "genericRoute", ".", "push", "(", "{", "method", ":", "'get'", ",", "controller", ":", "modelRest", ",", "action", ":", "'findById'", ",", "path", ":", "'/'", "+", "model", "+", "'/:id'", "}", ")", ";", "genericRoute", ".", "push", "(", "{", "method", ":", "'get'", ",", "controller", ":", "modelRest", ",", "action", ":", "'find'", ",", "path", ":", "'/'", "+", "model", "+", "'/find'", "}", ")", ";", "//update", "genericRoute", ".", "push", "(", "{", "method", ":", "'put'", ",", "controller", ":", "modelRest", ",", "action", ":", "'update'", ",", "path", ":", "'/'", "+", "model", "+", "'/:id'", "}", ")", ";", "genericRoute", ".", "push", "(", "{", "method", ":", "'get'", ",", "controller", ":", "modelRest", ",", "action", ":", "'updateQuery'", ",", "path", ":", "'/'", "+", "model", "+", "'/update/:id'", "}", ")", ";", "//update", "genericRoute", ".", "push", "(", "{", "method", ":", "'delete'", ",", "controller", ":", "modelRest", ",", "action", ":", "'delete'", ",", "path", ":", "'/'", "+", "model", "+", "'/:id'", "}", ")", ";", "genericRoute", ".", "push", "(", "{", "method", ":", "'get'", ",", "controller", ":", "modelRest", ",", "action", ":", "'delete'", ",", "path", ":", "'/'", "+", "model", "+", "'/delete/:id'", "}", ")", ";", "}", ")", ";", "return", "[", "genericControllers", ",", "genericRoute", "]", "}" ]
Generate genereic controllers
[ "Generate", "genereic", "controllers" ]
a8ebc50274b83bed8bed007e691761bdc3b52eaa
https://github.com/gaiajs/gaiajs/blob/a8ebc50274b83bed8bed007e691761bdc3b52eaa/lib/router/index.js#L61-L147
54,428
thlorenz/pdetail
pdetail.js
detailRange
function detailRange(cards) { if (cache.has(cards)) return cache.get(cards) var [ r1, r2, suitedness ] = cards if (r1 === r2) return addPairDetails(r1, new Set()) if (ranks.indexOf(r1) > ranks.indexOf(r2)) { const tmp = r1; r1 = r2; r2 = tmp } var res if (suitedness === 's') res = addSuitedDetails(r1, r2, new Set()) else if (suitedness === 'o') res = addOffsuitDetails(r1, r2, new Set()) else res = addOffsuitAndSuitedDetails(r1, r2, new Set()) cache.set(cards, res) return res }
javascript
function detailRange(cards) { if (cache.has(cards)) return cache.get(cards) var [ r1, r2, suitedness ] = cards if (r1 === r2) return addPairDetails(r1, new Set()) if (ranks.indexOf(r1) > ranks.indexOf(r2)) { const tmp = r1; r1 = r2; r2 = tmp } var res if (suitedness === 's') res = addSuitedDetails(r1, r2, new Set()) else if (suitedness === 'o') res = addOffsuitDetails(r1, r2, new Set()) else res = addOffsuitAndSuitedDetails(r1, r2, new Set()) cache.set(cards, res) return res }
[ "function", "detailRange", "(", "cards", ")", "{", "if", "(", "cache", ".", "has", "(", "cards", ")", ")", "return", "cache", ".", "get", "(", "cards", ")", "var", "[", "r1", ",", "r2", ",", "suitedness", "]", "=", "cards", "if", "(", "r1", "===", "r2", ")", "return", "addPairDetails", "(", "r1", ",", "new", "Set", "(", ")", ")", "if", "(", "ranks", ".", "indexOf", "(", "r1", ")", ">", "ranks", ".", "indexOf", "(", "r2", ")", ")", "{", "const", "tmp", "=", "r1", ";", "r1", "=", "r2", ";", "r2", "=", "tmp", "}", "var", "res", "if", "(", "suitedness", "===", "'s'", ")", "res", "=", "addSuitedDetails", "(", "r1", ",", "r2", ",", "new", "Set", "(", ")", ")", "else", "if", "(", "suitedness", "===", "'o'", ")", "res", "=", "addOffsuitDetails", "(", "r1", ",", "r2", ",", "new", "Set", "(", ")", ")", "else", "res", "=", "addOffsuitAndSuitedDetails", "(", "r1", ",", "r2", ",", "new", "Set", "(", ")", ")", "cache", ".", "set", "(", "cards", ",", "res", ")", "return", "res", "}" ]
Provides all possible combinations of a given part of a card range. ``` '99' => '9h9s', '9h9d', '9h9c', '9s9d', '9s9c', '9d9c' 'AKs' => 'AhKh', 'AsKs', 'AdKd', 'AcKc' 'KQo' => 'KhQs', 'KhQd', 'KhQc', 'KsQh', 'KsQd', 'KsQc', 'KdQh', 'KdQs', 'KdQc', 'KcQh', 'KcQs', 'KcQd' 'JT' => 'JhTh', 'JhTs', 'JhTd', 'JhTc', 'JsTh', 'JsTs', 'JsTd', 'JsTc', 'JdTh', 'JdTs', 'JdTd', 'JdTc', 'JcTh', 'JcTs', 'JcTd', 'JcTc' ``` @name detailRange @function @param {String} cards the cards for which to give a detailed combo range, i.e. 'AKs' Note: that AKs is considered the same as KAs and no duplicate combos will be included @return {Set} set of all possible combinations on how to hold the combo
[ "Provides", "all", "possible", "combinations", "of", "a", "given", "part", "of", "a", "card", "range", "." ]
ab2acfb3701fa2892689a1918cbd3b63f9b3feea
https://github.com/thlorenz/pdetail/blob/ab2acfb3701fa2892689a1918cbd3b63f9b3feea/pdetail.js#L118-L134
54,429
thlorenz/pdetail
pdetail.js
rangeFromDetail
function rangeFromDetail(set) { const pairs = new Map() const suiteds = new Map() const offsuits = new Map() function updateMap(map, key, val) { if (!map.has(key)) map.set(key, new Set()) map.get(key).add(val) } for (const cards of set) { var [ r1, s1, r2, s2 ] = cards if (r1 === r2) { updateMap(pairs, r1 + r2, cards) continue } if (ranks.indexOf(r1) > ranks.indexOf(r2)) { const tmp = r1; r1 = r2; r2 = tmp } if (s1 === s2) { updateMap(suiteds, r1 + r2 + 's', cards) continue } updateMap(offsuits, r1 + r2 + 'o', cards) } const complete = new Set() const incomplete = new Set() const all = new Set() for (const [ k, v ] of pairs) { if (v.size < 6) incomplete.add(k); else complete.add(k) all.add(k) } for (const [ k, v ] of suiteds) { if (v.size < 4) incomplete.add(k); else complete.add(k) all.add(k) } for (const [ k, v ] of offsuits) { if (v.size < 12) incomplete.add(k); else complete.add(k) all.add(k) } return { pairs, suiteds, offsuits, complete, incomplete, all } }
javascript
function rangeFromDetail(set) { const pairs = new Map() const suiteds = new Map() const offsuits = new Map() function updateMap(map, key, val) { if (!map.has(key)) map.set(key, new Set()) map.get(key).add(val) } for (const cards of set) { var [ r1, s1, r2, s2 ] = cards if (r1 === r2) { updateMap(pairs, r1 + r2, cards) continue } if (ranks.indexOf(r1) > ranks.indexOf(r2)) { const tmp = r1; r1 = r2; r2 = tmp } if (s1 === s2) { updateMap(suiteds, r1 + r2 + 's', cards) continue } updateMap(offsuits, r1 + r2 + 'o', cards) } const complete = new Set() const incomplete = new Set() const all = new Set() for (const [ k, v ] of pairs) { if (v.size < 6) incomplete.add(k); else complete.add(k) all.add(k) } for (const [ k, v ] of suiteds) { if (v.size < 4) incomplete.add(k); else complete.add(k) all.add(k) } for (const [ k, v ] of offsuits) { if (v.size < 12) incomplete.add(k); else complete.add(k) all.add(k) } return { pairs, suiteds, offsuits, complete, incomplete, all } }
[ "function", "rangeFromDetail", "(", "set", ")", "{", "const", "pairs", "=", "new", "Map", "(", ")", "const", "suiteds", "=", "new", "Map", "(", ")", "const", "offsuits", "=", "new", "Map", "(", ")", "function", "updateMap", "(", "map", ",", "key", ",", "val", ")", "{", "if", "(", "!", "map", ".", "has", "(", "key", ")", ")", "map", ".", "set", "(", "key", ",", "new", "Set", "(", ")", ")", "map", ".", "get", "(", "key", ")", ".", "add", "(", "val", ")", "}", "for", "(", "const", "cards", "of", "set", ")", "{", "var", "[", "r1", ",", "s1", ",", "r2", ",", "s2", "]", "=", "cards", "if", "(", "r1", "===", "r2", ")", "{", "updateMap", "(", "pairs", ",", "r1", "+", "r2", ",", "cards", ")", "continue", "}", "if", "(", "ranks", ".", "indexOf", "(", "r1", ")", ">", "ranks", ".", "indexOf", "(", "r2", ")", ")", "{", "const", "tmp", "=", "r1", ";", "r1", "=", "r2", ";", "r2", "=", "tmp", "}", "if", "(", "s1", "===", "s2", ")", "{", "updateMap", "(", "suiteds", ",", "r1", "+", "r2", "+", "'s'", ",", "cards", ")", "continue", "}", "updateMap", "(", "offsuits", ",", "r1", "+", "r2", "+", "'o'", ",", "cards", ")", "}", "const", "complete", "=", "new", "Set", "(", ")", "const", "incomplete", "=", "new", "Set", "(", ")", "const", "all", "=", "new", "Set", "(", ")", "for", "(", "const", "[", "k", ",", "v", "]", "of", "pairs", ")", "{", "if", "(", "v", ".", "size", "<", "6", ")", "incomplete", ".", "add", "(", "k", ")", ";", "else", "complete", ".", "add", "(", "k", ")", "all", ".", "add", "(", "k", ")", "}", "for", "(", "const", "[", "k", ",", "v", "]", "of", "suiteds", ")", "{", "if", "(", "v", ".", "size", "<", "4", ")", "incomplete", ".", "add", "(", "k", ")", ";", "else", "complete", ".", "add", "(", "k", ")", "all", ".", "add", "(", "k", ")", "}", "for", "(", "const", "[", "k", ",", "v", "]", "of", "offsuits", ")", "{", "if", "(", "v", ".", "size", "<", "12", ")", "incomplete", ".", "add", "(", "k", ")", ";", "else", "complete", ".", "add", "(", "k", ")", "all", ".", "add", "(", "k", ")", "}", "return", "{", "pairs", ",", "suiteds", ",", "offsuits", ",", "complete", ",", "incomplete", ",", "all", "}", "}" ]
Calculates a range from the detail combos, i.e. obtained via `detailRange`. @name rangeFromDetail @function @parm {Set} set of combinations to obtain a range for @return object with the following props: - {Map} pairs: all pairs found grouped, i.e. `AA: { AdAs, AdAc ... }` - {Map} suiteds: all suiteds found grouped, i.e. `AKs: { AdKd, AcKc ... }` - {Map} offsuits: all offsuits found grouped, i.e. `AKo: { AdKc, AcKs ... }` - {Set} incomplete: all incomplete ranges, i.e. `AA` if one possible AA combo was missing - {Set} complete: all complete ranges, i.e. `AA` if none possible AA combo was missing - {Set} all: union of incomplete and complete
[ "Calculates", "a", "range", "from", "the", "detail", "combos", "i", ".", "e", ".", "obtained", "via", "detailRange", "." ]
ab2acfb3701fa2892689a1918cbd3b63f9b3feea
https://github.com/thlorenz/pdetail/blob/ab2acfb3701fa2892689a1918cbd3b63f9b3feea/pdetail.js#L150-L194
54,430
eush77/cmpby
index.js
fixArgs
function fixArgs (callee) { return (options, fn) => { if (typeof fn != 'function' && typeof options == 'function') { fn = options; options = {}; } else { options = options || {}; } options.asc = options.asc || options.asc == null; return callee(options, fn); }; }
javascript
function fixArgs (callee) { return (options, fn) => { if (typeof fn != 'function' && typeof options == 'function') { fn = options; options = {}; } else { options = options || {}; } options.asc = options.asc || options.asc == null; return callee(options, fn); }; }
[ "function", "fixArgs", "(", "callee", ")", "{", "return", "(", "options", ",", "fn", ")", "=>", "{", "if", "(", "typeof", "fn", "!=", "'function'", "&&", "typeof", "options", "==", "'function'", ")", "{", "fn", "=", "options", ";", "options", "=", "{", "}", ";", "}", "else", "{", "options", "=", "options", "||", "{", "}", ";", "}", "options", ".", "asc", "=", "options", ".", "asc", "||", "options", ".", "asc", "==", "null", ";", "return", "callee", "(", "options", ",", "fn", ")", ";", "}", ";", "}" ]
Deal with missing arguments and default values.
[ "Deal", "with", "missing", "arguments", "and", "default", "values", "." ]
480afc8b513acb872fe09627ebf2876c1e51c63c
https://github.com/eush77/cmpby/blob/480afc8b513acb872fe09627ebf2876c1e51c63c/index.js#L39-L53
54,431
eush77/cmpby
index.js
compare
function compare (options, less, x, y) { const ifLess = options.asc ? -1 : 1; return less(x, y) ? ifLess : less(y, x) ? -ifLess : 0; }
javascript
function compare (options, less, x, y) { const ifLess = options.asc ? -1 : 1; return less(x, y) ? ifLess : less(y, x) ? -ifLess : 0; }
[ "function", "compare", "(", "options", ",", "less", ",", "x", ",", "y", ")", "{", "const", "ifLess", "=", "options", ".", "asc", "?", "-", "1", ":", "1", ";", "return", "less", "(", "x", ",", "y", ")", "?", "ifLess", ":", "less", "(", "y", ",", "x", ")", "?", "-", "ifLess", ":", "0", ";", "}" ]
Core comparator logic.
[ "Core", "comparator", "logic", "." ]
480afc8b513acb872fe09627ebf2876c1e51c63c
https://github.com/eush77/cmpby/blob/480afc8b513acb872fe09627ebf2876c1e51c63c/index.js#L57-L63
54,432
quorrajs/elixir
index.js
overrideConfig
function overrideConfig() { _.merge(Elixir.config, require(path.join(process.cwd(), 'elixirConfig.js'))); }
javascript
function overrideConfig() { _.merge(Elixir.config, require(path.join(process.cwd(), 'elixirConfig.js'))); }
[ "function", "overrideConfig", "(", ")", "{", "_", ".", "merge", "(", "Elixir", ".", "config", ",", "require", "(", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "'elixirConfig.js'", ")", ")", ")", ";", "}" ]
Allow for config overrides, via an elixirConfig.js file.
[ "Allow", "for", "config", "overrides", "via", "an", "elixirConfig", ".", "js", "file", "." ]
3390f81bc07c948b1d4295cb1963ec2a9ce2ca9a
https://github.com/quorrajs/elixir/blob/3390f81bc07c948b1d4295cb1963ec2a9ce2ca9a/index.js#L24-L26
54,433
quorrajs/elixir
index.js
overrideTasks
function overrideTasks() { function noop() { Elixir.log.heading.error('Quorra don\'t have php tests!') } Elixir.extend('phpSpec', noop); Elixir.extend('phpunit', noop); Elixir.extend('babel', function () { new Elixir.Task('babel', function () { Elixir.log.heading('Alert!').heading("'mix.babel()' is not supported in Quorra Elixir. " + "You'll want to instead call 'mix.rollup().'"); process.exit(1); }); }); }
javascript
function overrideTasks() { function noop() { Elixir.log.heading.error('Quorra don\'t have php tests!') } Elixir.extend('phpSpec', noop); Elixir.extend('phpunit', noop); Elixir.extend('babel', function () { new Elixir.Task('babel', function () { Elixir.log.heading('Alert!').heading("'mix.babel()' is not supported in Quorra Elixir. " + "You'll want to instead call 'mix.rollup().'"); process.exit(1); }); }); }
[ "function", "overrideTasks", "(", ")", "{", "function", "noop", "(", ")", "{", "Elixir", ".", "log", ".", "heading", ".", "error", "(", "'Quorra don\\'t have php tests!'", ")", "}", "Elixir", ".", "extend", "(", "'phpSpec'", ",", "noop", ")", ";", "Elixir", ".", "extend", "(", "'phpunit'", ",", "noop", ")", ";", "Elixir", ".", "extend", "(", "'babel'", ",", "function", "(", ")", "{", "new", "Elixir", ".", "Task", "(", "'babel'", ",", "function", "(", ")", "{", "Elixir", ".", "log", ".", "heading", "(", "'Alert!'", ")", ".", "heading", "(", "\"'mix.babel()' is not supported in Quorra Elixir. \"", "+", "\"You'll want to instead call 'mix.rollup().'\"", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Ovrride some of the tasks provided by the laravel-elixir module
[ "Ovrride", "some", "of", "the", "tasks", "provided", "by", "the", "laravel", "-", "elixir", "module" ]
3390f81bc07c948b1d4295cb1963ec2a9ce2ca9a
https://github.com/quorrajs/elixir/blob/3390f81bc07c948b1d4295cb1963ec2a9ce2ca9a/index.js#L31-L46
54,434
alessioalex/npm-dep-chain
index.js
getNpmData
function getNpmData(pkg, npmClient, callback) { callback = once(callback); // default to latest version if (!pkg.version || pkg.version === 'latest') { pkg.version = '*'; } npmClient.get(pkg.name, { staleOk: true }, errTo(callback, function(npmPackageInfo) { var version; version = semver.maxSatisfying(Object.keys(npmPackageInfo.versions), pkg.version); // if the version is not found, perhaps the cache is old, force load from registry if (!version) { npmClient.get(pkg.name, { staleOk: true }, errTo(callback, function(npmPackageInfo) { callback(null, npmPackageInfo.versions[version] || null); })); } else { callback(null, npmPackageInfo.versions[version] || null); } })); }
javascript
function getNpmData(pkg, npmClient, callback) { callback = once(callback); // default to latest version if (!pkg.version || pkg.version === 'latest') { pkg.version = '*'; } npmClient.get(pkg.name, { staleOk: true }, errTo(callback, function(npmPackageInfo) { var version; version = semver.maxSatisfying(Object.keys(npmPackageInfo.versions), pkg.version); // if the version is not found, perhaps the cache is old, force load from registry if (!version) { npmClient.get(pkg.name, { staleOk: true }, errTo(callback, function(npmPackageInfo) { callback(null, npmPackageInfo.versions[version] || null); })); } else { callback(null, npmPackageInfo.versions[version] || null); } })); }
[ "function", "getNpmData", "(", "pkg", ",", "npmClient", ",", "callback", ")", "{", "callback", "=", "once", "(", "callback", ")", ";", "// default to latest version", "if", "(", "!", "pkg", ".", "version", "||", "pkg", ".", "version", "===", "'latest'", ")", "{", "pkg", ".", "version", "=", "'*'", ";", "}", "npmClient", ".", "get", "(", "pkg", ".", "name", ",", "{", "staleOk", ":", "true", "}", ",", "errTo", "(", "callback", ",", "function", "(", "npmPackageInfo", ")", "{", "var", "version", ";", "version", "=", "semver", ".", "maxSatisfying", "(", "Object", ".", "keys", "(", "npmPackageInfo", ".", "versions", ")", ",", "pkg", ".", "version", ")", ";", "// if the version is not found, perhaps the cache is old, force load from registry", "if", "(", "!", "version", ")", "{", "npmClient", ".", "get", "(", "pkg", ".", "name", ",", "{", "staleOk", ":", "true", "}", ",", "errTo", "(", "callback", ",", "function", "(", "npmPackageInfo", ")", "{", "callback", "(", "null", ",", "npmPackageInfo", ".", "versions", "[", "version", "]", "||", "null", ")", ";", "}", ")", ")", ";", "}", "else", "{", "callback", "(", "null", ",", "npmPackageInfo", ".", "versions", "[", "version", "]", "||", "null", ")", ";", "}", "}", ")", ")", ";", "}" ]
Fetches data from the NPM registry for a package based on its name and version range. It will find the maximum version that satisfies the range. @param {Object} pkg - contains version and name of the package @param {Object} npmClient - instance of npm-pkginfo @param {Function} callback
[ "Fetches", "data", "from", "the", "NPM", "registry", "for", "a", "package", "based", "on", "its", "name", "and", "version", "range", ".", "It", "will", "find", "the", "maximum", "version", "that", "satisfies", "the", "range", "." ]
2ec7c18dc48fbdf1a997760321c75e984f73810c
https://github.com/alessioalex/npm-dep-chain/blob/2ec7c18dc48fbdf1a997760321c75e984f73810c/index.js#L24-L47
54,435
alessioalex/npm-dep-chain
index.js
getBulkNpmData
function getBulkNpmData(pkgs, collection, npmClient, callback) { var next, results; results = []; next = after(pkgs.length, function(err) { return callback(err, results); }); pkgs.forEach(function(pkg) { // make sure not to make unnecessary queries to the registry if (isDuplicate(collection[pkg.name], pkg.version)) { return next(null); } getNpmData(pkg, npmClient, errTo(callback, function(found) { if (found) { results.push(found); } next(null, results); })); }); }
javascript
function getBulkNpmData(pkgs, collection, npmClient, callback) { var next, results; results = []; next = after(pkgs.length, function(err) { return callback(err, results); }); pkgs.forEach(function(pkg) { // make sure not to make unnecessary queries to the registry if (isDuplicate(collection[pkg.name], pkg.version)) { return next(null); } getNpmData(pkg, npmClient, errTo(callback, function(found) { if (found) { results.push(found); } next(null, results); })); }); }
[ "function", "getBulkNpmData", "(", "pkgs", ",", "collection", ",", "npmClient", ",", "callback", ")", "{", "var", "next", ",", "results", ";", "results", "=", "[", "]", ";", "next", "=", "after", "(", "pkgs", ".", "length", ",", "function", "(", "err", ")", "{", "return", "callback", "(", "err", ",", "results", ")", ";", "}", ")", ";", "pkgs", ".", "forEach", "(", "function", "(", "pkg", ")", "{", "// make sure not to make unnecessary queries to the registry", "if", "(", "isDuplicate", "(", "collection", "[", "pkg", ".", "name", "]", ",", "pkg", ".", "version", ")", ")", "{", "return", "next", "(", "null", ")", ";", "}", "getNpmData", "(", "pkg", ",", "npmClient", ",", "errTo", "(", "callback", ",", "function", "(", "found", ")", "{", "if", "(", "found", ")", "{", "results", ".", "push", "(", "found", ")", ";", "}", "next", "(", "null", ",", "results", ")", ";", "}", ")", ")", ";", "}", ")", ";", "}" ]
Fetches data from the NPM registry for all the packages provided. @param {Array} pkgs - an array of packages objects containing the name && version props @param {Object} collection - collection of processed packages @param {Object} npmClient - instance of npm-registry-client @param {Function} callback
[ "Fetches", "data", "from", "the", "NPM", "registry", "for", "all", "the", "packages", "provided", "." ]
2ec7c18dc48fbdf1a997760321c75e984f73810c
https://github.com/alessioalex/npm-dep-chain/blob/2ec7c18dc48fbdf1a997760321c75e984f73810c/index.js#L57-L77
54,436
alessioalex/npm-dep-chain
index.js
mapDependencies
function mapDependencies(dependencies) { var deps; deps = (dependencies) ? Object.keys(dependencies) : []; return deps.map(function(name) { return { name: name, version: dependencies[name] }; }); }
javascript
function mapDependencies(dependencies) { var deps; deps = (dependencies) ? Object.keys(dependencies) : []; return deps.map(function(name) { return { name: name, version: dependencies[name] }; }); }
[ "function", "mapDependencies", "(", "dependencies", ")", "{", "var", "deps", ";", "deps", "=", "(", "dependencies", ")", "?", "Object", ".", "keys", "(", "dependencies", ")", ":", "[", "]", ";", "return", "deps", ".", "map", "(", "function", "(", "name", ")", "{", "return", "{", "name", ":", "name", ",", "version", ":", "dependencies", "[", "name", "]", "}", ";", "}", ")", ";", "}" ]
Map the dependencies object to an array containing name && value properties. @param {Object} dependencies @returns {Array}
[ "Map", "the", "dependencies", "object", "to", "an", "array", "containing", "name", "&&", "value", "properties", "." ]
2ec7c18dc48fbdf1a997760321c75e984f73810c
https://github.com/alessioalex/npm-dep-chain/blob/2ec7c18dc48fbdf1a997760321c75e984f73810c/index.js#L85-L96
54,437
alessioalex/npm-dep-chain
index.js
isDuplicate
function isDuplicate(pkg, version) { var versions; // no duplicates if (pkg) { versions = Object.keys(pkg); if (versions.length && semver.maxSatisfying(versions, version)) { return true; } } return false; }
javascript
function isDuplicate(pkg, version) { var versions; // no duplicates if (pkg) { versions = Object.keys(pkg); if (versions.length && semver.maxSatisfying(versions, version)) { return true; } } return false; }
[ "function", "isDuplicate", "(", "pkg", ",", "version", ")", "{", "var", "versions", ";", "// no duplicates", "if", "(", "pkg", ")", "{", "versions", "=", "Object", ".", "keys", "(", "pkg", ")", ";", "if", "(", "versions", ".", "length", "&&", "semver", ".", "maxSatisfying", "(", "versions", ",", "version", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check if a version of a package already exists @param {Object} pkg - an object with the keys representing the versions of a module @param {String} version - version range @returns {Array} TODO: refactor this, first arg should be versions instead
[ "Check", "if", "a", "version", "of", "a", "package", "already", "exists" ]
2ec7c18dc48fbdf1a997760321c75e984f73810c
https://github.com/alessioalex/npm-dep-chain/blob/2ec7c18dc48fbdf1a997760321c75e984f73810c/index.js#L106-L119
54,438
alessioalex/npm-dep-chain
index.js
addToQueue
function addToQueue(queue, packageInfo) { var exists; function matchesVersion(version, range) { var matches; try { matches = semver.satisfies(packageInfo.version, item.version); } catch (err) { matches = false; } return matches; } exists = queue.some(function(item) { var matches = false; if (item.name === packageInfo.name) { matches = matchesVersion(packageInfo.version, item.version); } return matches; }); if (!exists) { queue.push(packageInfo); } }
javascript
function addToQueue(queue, packageInfo) { var exists; function matchesVersion(version, range) { var matches; try { matches = semver.satisfies(packageInfo.version, item.version); } catch (err) { matches = false; } return matches; } exists = queue.some(function(item) { var matches = false; if (item.name === packageInfo.name) { matches = matchesVersion(packageInfo.version, item.version); } return matches; }); if (!exists) { queue.push(packageInfo); } }
[ "function", "addToQueue", "(", "queue", ",", "packageInfo", ")", "{", "var", "exists", ";", "function", "matchesVersion", "(", "version", ",", "range", ")", "{", "var", "matches", ";", "try", "{", "matches", "=", "semver", ".", "satisfies", "(", "packageInfo", ".", "version", ",", "item", ".", "version", ")", ";", "}", "catch", "(", "err", ")", "{", "matches", "=", "false", ";", "}", "return", "matches", ";", "}", "exists", "=", "queue", ".", "some", "(", "function", "(", "item", ")", "{", "var", "matches", "=", "false", ";", "if", "(", "item", ".", "name", "===", "packageInfo", ".", "name", ")", "{", "matches", "=", "matchesVersion", "(", "packageInfo", ".", "version", ",", "item", ".", "version", ")", ";", "}", "return", "matches", ";", "}", ")", ";", "if", "(", "!", "exists", ")", "{", "queue", ".", "push", "(", "packageInfo", ")", ";", "}", "}" ]
Add the package to the queue in case the name && version doen't exist or the version range isn't matched. @param {Object} queue - contains packages info from NPM registry @param {String} packageInfo - data retrieved from the NPM registry for a package
[ "Add", "the", "package", "to", "the", "queue", "in", "case", "the", "name", "&&", "version", "doen", "t", "exist", "or", "the", "version", "range", "isn", "t", "matched", "." ]
2ec7c18dc48fbdf1a997760321c75e984f73810c
https://github.com/alessioalex/npm-dep-chain/blob/2ec7c18dc48fbdf1a997760321c75e984f73810c/index.js#L154-L183
54,439
alessioalex/npm-dep-chain
index.js
processDeps
function processDeps(queue, collection, callback, errBack) { return errTo(errBack, function(packages) { var deps; packages.forEach(function(pkg) { // add the package to the collection of processed packages addPackage(collection, pkg); // if the module has dependencies, add them to the processing queue // unless they have been already processed mapDependencies(pkg.dependencies).forEach(function(dep) { if (!isDuplicate(collection[dep.name], dep.version)) { addToQueue(queue, dep); } }); }); callback(queue); }); }
javascript
function processDeps(queue, collection, callback, errBack) { return errTo(errBack, function(packages) { var deps; packages.forEach(function(pkg) { // add the package to the collection of processed packages addPackage(collection, pkg); // if the module has dependencies, add them to the processing queue // unless they have been already processed mapDependencies(pkg.dependencies).forEach(function(dep) { if (!isDuplicate(collection[dep.name], dep.version)) { addToQueue(queue, dep); } }); }); callback(queue); }); }
[ "function", "processDeps", "(", "queue", ",", "collection", ",", "callback", ",", "errBack", ")", "{", "return", "errTo", "(", "errBack", ",", "function", "(", "packages", ")", "{", "var", "deps", ";", "packages", ".", "forEach", "(", "function", "(", "pkg", ")", "{", "// add the package to the collection of processed packages", "addPackage", "(", "collection", ",", "pkg", ")", ";", "// if the module has dependencies, add them to the processing queue", "// unless they have been already processed", "mapDependencies", "(", "pkg", ".", "dependencies", ")", ".", "forEach", "(", "function", "(", "dep", ")", "{", "if", "(", "!", "isDuplicate", "(", "collection", "[", "dep", ".", "name", "]", ",", "dep", ".", "version", ")", ")", "{", "addToQueue", "(", "queue", ",", "dep", ")", ";", "}", "}", ")", ";", "}", ")", ";", "callback", "(", "queue", ")", ";", "}", ")", ";", "}" ]
Add the packages to the "results" collection and add their direct dependencies to the `queue` so they can be processed later. When all done, invoke callback. @param {Object} queue @param {Object} collection @param {Function} callback
[ "Add", "the", "packages", "to", "the", "results", "collection", "and", "add", "their", "direct", "dependencies", "to", "the", "queue", "so", "they", "can", "be", "processed", "later", ".", "When", "all", "done", "invoke", "callback", "." ]
2ec7c18dc48fbdf1a997760321c75e984f73810c
https://github.com/alessioalex/npm-dep-chain/blob/2ec7c18dc48fbdf1a997760321c75e984f73810c/index.js#L223-L242
54,440
sitegui/this-commit
index.js
getGitFolder
function getGitFolder() { // Based on logic in Module._nodeModulePaths at // https://github.com/joyent/node/blob/master/lib/module.js var from = path.resolve('.'), parts = from.split(process.platform === 'win32' ? /[\/\\]/ : /\//), tip, dir for (tip = parts.length - 1; tip >= 0; tip--) { dir = parts.slice(0, tip + 1).concat('.git').join(path.sep) try { if (fs.statSync(dir).isDirectory()) { // Found a valid .git directory return dir } } catch (e) { // Let 'for' iterate } } return '' }
javascript
function getGitFolder() { // Based on logic in Module._nodeModulePaths at // https://github.com/joyent/node/blob/master/lib/module.js var from = path.resolve('.'), parts = from.split(process.platform === 'win32' ? /[\/\\]/ : /\//), tip, dir for (tip = parts.length - 1; tip >= 0; tip--) { dir = parts.slice(0, tip + 1).concat('.git').join(path.sep) try { if (fs.statSync(dir).isDirectory()) { // Found a valid .git directory return dir } } catch (e) { // Let 'for' iterate } } return '' }
[ "function", "getGitFolder", "(", ")", "{", "// Based on logic in Module._nodeModulePaths at", "// https://github.com/joyent/node/blob/master/lib/module.js", "var", "from", "=", "path", ".", "resolve", "(", "'.'", ")", ",", "parts", "=", "from", ".", "split", "(", "process", ".", "platform", "===", "'win32'", "?", "/", "[\\/\\\\]", "/", ":", "/", "\\/", "/", ")", ",", "tip", ",", "dir", "for", "(", "tip", "=", "parts", ".", "length", "-", "1", ";", "tip", ">=", "0", ";", "tip", "--", ")", "{", "dir", "=", "parts", ".", "slice", "(", "0", ",", "tip", "+", "1", ")", ".", "concat", "(", "'.git'", ")", ".", "join", "(", "path", ".", "sep", ")", "try", "{", "if", "(", "fs", ".", "statSync", "(", "dir", ")", ".", "isDirectory", "(", ")", ")", "{", "// Found a valid .git directory", "return", "dir", "}", "}", "catch", "(", "e", ")", "{", "// Let 'for' iterate", "}", "}", "return", "''", "}" ]
Find the absolute path for the git folder @returns {string} - '' if not found
[ "Find", "the", "absolute", "path", "for", "the", "git", "folder" ]
46bce14f3c5625cb3c18ca958a0591c074d6698c
https://github.com/sitegui/this-commit/blob/46bce14f3c5625cb3c18ca958a0591c074d6698c/index.js#L43-L62
54,441
sitegui/this-commit
index.js
readRef
function readRef(gitFolder, refName) { var ref try { ref = fs.readFileSync(path.join(gitFolder, refName), 'utf8').trim() return isSHA1(ref) ? ref : '' } catch (e) { // Last chance: read from packed-refs return readPackedRef(gitFolder, refName) } }
javascript
function readRef(gitFolder, refName) { var ref try { ref = fs.readFileSync(path.join(gitFolder, refName), 'utf8').trim() return isSHA1(ref) ? ref : '' } catch (e) { // Last chance: read from packed-refs return readPackedRef(gitFolder, refName) } }
[ "function", "readRef", "(", "gitFolder", ",", "refName", ")", "{", "var", "ref", "try", "{", "ref", "=", "fs", ".", "readFileSync", "(", "path", ".", "join", "(", "gitFolder", ",", "refName", ")", ",", "'utf8'", ")", ".", "trim", "(", ")", "return", "isSHA1", "(", "ref", ")", "?", "ref", ":", "''", "}", "catch", "(", "e", ")", "{", "// Last chance: read from packed-refs", "return", "readPackedRef", "(", "gitFolder", ",", "refName", ")", "}", "}" ]
Return the commit name for the given ref name @param {string} gitFolder @param {string} refName @returns {string} - '' if not found
[ "Return", "the", "commit", "name", "for", "the", "given", "ref", "name" ]
46bce14f3c5625cb3c18ca958a0591c074d6698c
https://github.com/sitegui/this-commit/blob/46bce14f3c5625cb3c18ca958a0591c074d6698c/index.js#L70-L79
54,442
sitegui/this-commit
index.js
readPackedRef
function readPackedRef(gitFolder, refName) { var packedRefs, i, each, match try { packedRefs = fs.readFileSync(path.join(gitFolder, 'packed-refs'), 'utf8').split(/\r?\n/) } catch (e) { return '' } for (i = 0; i < packedRefs.length; i++) { each = packedRefs[i].trim() // Look for lines like: // 1d6f5f98a254578e19b5eb163077170d45448c26 refs/heads/master match = each.match(/^(.{40}) (.*)$/) if (match && match[2] === refName && isSHA1(match[1])) { return match[1] } } return '' }
javascript
function readPackedRef(gitFolder, refName) { var packedRefs, i, each, match try { packedRefs = fs.readFileSync(path.join(gitFolder, 'packed-refs'), 'utf8').split(/\r?\n/) } catch (e) { return '' } for (i = 0; i < packedRefs.length; i++) { each = packedRefs[i].trim() // Look for lines like: // 1d6f5f98a254578e19b5eb163077170d45448c26 refs/heads/master match = each.match(/^(.{40}) (.*)$/) if (match && match[2] === refName && isSHA1(match[1])) { return match[1] } } return '' }
[ "function", "readPackedRef", "(", "gitFolder", ",", "refName", ")", "{", "var", "packedRefs", ",", "i", ",", "each", ",", "match", "try", "{", "packedRefs", "=", "fs", ".", "readFileSync", "(", "path", ".", "join", "(", "gitFolder", ",", "'packed-refs'", ")", ",", "'utf8'", ")", ".", "split", "(", "/", "\\r?\\n", "/", ")", "}", "catch", "(", "e", ")", "{", "return", "''", "}", "for", "(", "i", "=", "0", ";", "i", "<", "packedRefs", ".", "length", ";", "i", "++", ")", "{", "each", "=", "packedRefs", "[", "i", "]", ".", "trim", "(", ")", "// Look for lines like:", "// 1d6f5f98a254578e19b5eb163077170d45448c26 refs/heads/master", "match", "=", "each", ".", "match", "(", "/", "^(.{40}) (.*)$", "/", ")", "if", "(", "match", "&&", "match", "[", "2", "]", "===", "refName", "&&", "isSHA1", "(", "match", "[", "1", "]", ")", ")", "{", "return", "match", "[", "1", "]", "}", "}", "return", "''", "}" ]
Return the commit name for the given ref name from packed-refs file @param {string} gitFolder @param {string} refName @returns {string} - '' if not found
[ "Return", "the", "commit", "name", "for", "the", "given", "ref", "name", "from", "packed", "-", "refs", "file" ]
46bce14f3c5625cb3c18ca958a0591c074d6698c
https://github.com/sitegui/this-commit/blob/46bce14f3c5625cb3c18ca958a0591c074d6698c/index.js#L87-L107
54,443
jl-/gulp-docy
docstrap/Gruntfile.js
jsdocCommand
function jsdocCommand( jsdoc ) { var cmd = []; cmd.unshift( jsdoc.options ); if ( jsdoc.tutorials.length > 0 ) { cmd.push( "-u " + path.resolve( jsdoc.tutorials ) ); } cmd.push( "-d " + path.resolve( jsdoc.dest ) ); cmd.push( "-t " + path.resolve( jsdoc.template ) ); cmd.push( "-c " + path.resolve( jsdoc.config ) ); sys.each( jsdoc.src, function ( src ) { cmd.push( path.resolve( src ) ); } ); cmd.unshift( path.resolve( "./node_modules/jsdoc/jsdoc" ) ); cmd.unshift( "node" ); return cmd.join( " " ); }
javascript
function jsdocCommand( jsdoc ) { var cmd = []; cmd.unshift( jsdoc.options ); if ( jsdoc.tutorials.length > 0 ) { cmd.push( "-u " + path.resolve( jsdoc.tutorials ) ); } cmd.push( "-d " + path.resolve( jsdoc.dest ) ); cmd.push( "-t " + path.resolve( jsdoc.template ) ); cmd.push( "-c " + path.resolve( jsdoc.config ) ); sys.each( jsdoc.src, function ( src ) { cmd.push( path.resolve( src ) ); } ); cmd.unshift( path.resolve( "./node_modules/jsdoc/jsdoc" ) ); cmd.unshift( "node" ); return cmd.join( " " ); }
[ "function", "jsdocCommand", "(", "jsdoc", ")", "{", "var", "cmd", "=", "[", "]", ";", "cmd", ".", "unshift", "(", "jsdoc", ".", "options", ")", ";", "if", "(", "jsdoc", ".", "tutorials", ".", "length", ">", "0", ")", "{", "cmd", ".", "push", "(", "\"-u \"", "+", "path", ".", "resolve", "(", "jsdoc", ".", "tutorials", ")", ")", ";", "}", "cmd", ".", "push", "(", "\"-d \"", "+", "path", ".", "resolve", "(", "jsdoc", ".", "dest", ")", ")", ";", "cmd", ".", "push", "(", "\"-t \"", "+", "path", ".", "resolve", "(", "jsdoc", ".", "template", ")", ")", ";", "cmd", ".", "push", "(", "\"-c \"", "+", "path", ".", "resolve", "(", "jsdoc", ".", "config", ")", ")", ";", "sys", ".", "each", "(", "jsdoc", ".", "src", ",", "function", "(", "src", ")", "{", "cmd", ".", "push", "(", "path", ".", "resolve", "(", "src", ")", ")", ";", "}", ")", ";", "cmd", ".", "unshift", "(", "path", ".", "resolve", "(", "\"./node_modules/jsdoc/jsdoc\"", ")", ")", ";", "cmd", ".", "unshift", "(", "\"node\"", ")", ";", "return", "cmd", ".", "join", "(", "\" \"", ")", ";", "}" ]
Normalizes all paths from a JSDoc task definition and and returns an executable string that can be passed to the shell. @param {object} jsdoc A JSDoc definition @returns {string}
[ "Normalizes", "all", "paths", "from", "a", "JSDoc", "task", "definition", "and", "and", "returns", "an", "executable", "string", "that", "can", "be", "passed", "to", "the", "shell", "." ]
40c2ba2da57c8ddb0a877340acc9a0604b1bafb4
https://github.com/jl-/gulp-docy/blob/40c2ba2da57c8ddb0a877340acc9a0604b1bafb4/docstrap/Gruntfile.js#L81-L97
54,444
jl-/gulp-docy
docstrap/Gruntfile.js
getBootSwatchList
function getBootSwatchList( done ) { var options = { hostname : 'api.bootswatch.com', port : 80, path : '/', method : 'GET' }; var body = ""; var req = http.request( options, function ( res ) { res.setEncoding( 'utf8' ); res.on( 'data', function ( chunk ) { body += chunk; } ); res.on( 'end', function () { done( null, JSON.parse( body ) ); } ); res.on( 'error', function ( e ) { done( 'problem with response: ' + e.message ); } ); } ); req.on( 'error', function ( e ) { done( 'problem with request: ' + e.message ); } ); req.end(); }
javascript
function getBootSwatchList( done ) { var options = { hostname : 'api.bootswatch.com', port : 80, path : '/', method : 'GET' }; var body = ""; var req = http.request( options, function ( res ) { res.setEncoding( 'utf8' ); res.on( 'data', function ( chunk ) { body += chunk; } ); res.on( 'end', function () { done( null, JSON.parse( body ) ); } ); res.on( 'error', function ( e ) { done( 'problem with response: ' + e.message ); } ); } ); req.on( 'error', function ( e ) { done( 'problem with request: ' + e.message ); } ); req.end(); }
[ "function", "getBootSwatchList", "(", "done", ")", "{", "var", "options", "=", "{", "hostname", ":", "'api.bootswatch.com'", ",", "port", ":", "80", ",", "path", ":", "'/'", ",", "method", ":", "'GET'", "}", ";", "var", "body", "=", "\"\"", ";", "var", "req", "=", "http", ".", "request", "(", "options", ",", "function", "(", "res", ")", "{", "res", ".", "setEncoding", "(", "'utf8'", ")", ";", "res", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "body", "+=", "chunk", ";", "}", ")", ";", "res", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "done", "(", "null", ",", "JSON", ".", "parse", "(", "body", ")", ")", ";", "}", ")", ";", "res", ".", "on", "(", "'error'", ",", "function", "(", "e", ")", "{", "done", "(", "'problem with response: '", "+", "e", ".", "message", ")", ";", "}", ")", ";", "}", ")", ";", "req", ".", "on", "(", "'error'", ",", "function", "(", "e", ")", "{", "done", "(", "'problem with request: '", "+", "e", ".", "message", ")", ";", "}", ")", ";", "req", ".", "end", "(", ")", ";", "}" ]
Gets the list of available Bootswatches from, well, Bootswatch. @see http://news.bootswatch.com/post/22193315172/bootswatch-api @param {function(err, responseBody)} done The callback when complete @param {?object} done.err If an error occurred, you will find it here. @param {object} done.responseBody This is a parsed edition of the bootswatch server's response. It's format it defined by the return message from [here](http://api.bootswatch.com/) @private
[ "Gets", "the", "list", "of", "available", "Bootswatches", "from", "well", "Bootswatch", "." ]
40c2ba2da57c8ddb0a877340acc9a0604b1bafb4
https://github.com/jl-/gulp-docy/blob/40c2ba2da57c8ddb0a877340acc9a0604b1bafb4/docstrap/Gruntfile.js#L362-L388
54,445
jl-/gulp-docy
docstrap/Gruntfile.js
getBootSwatchComponent
function getBootSwatchComponent( url, done ) { var body = ""; var req = http.request( url, function ( res ) { res.setEncoding( 'utf8' ); res.on( 'data', function ( chunk ) { body += chunk; } ); res.on( 'end', function () { done( null, body ); } ); res.on( 'error', function ( e ) { done( 'problem with response: ' + e.message ); } ); } ); req.on( 'error', function ( e ) { done( 'problem with request: ' + e.message ); } ); req.end(); }
javascript
function getBootSwatchComponent( url, done ) { var body = ""; var req = http.request( url, function ( res ) { res.setEncoding( 'utf8' ); res.on( 'data', function ( chunk ) { body += chunk; } ); res.on( 'end', function () { done( null, body ); } ); res.on( 'error', function ( e ) { done( 'problem with response: ' + e.message ); } ); } ); req.on( 'error', function ( e ) { done( 'problem with request: ' + e.message ); } ); req.end(); }
[ "function", "getBootSwatchComponent", "(", "url", ",", "done", ")", "{", "var", "body", "=", "\"\"", ";", "var", "req", "=", "http", ".", "request", "(", "url", ",", "function", "(", "res", ")", "{", "res", ".", "setEncoding", "(", "'utf8'", ")", ";", "res", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "body", "+=", "chunk", ";", "}", ")", ";", "res", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "done", "(", "null", ",", "body", ")", ";", "}", ")", ";", "res", ".", "on", "(", "'error'", ",", "function", "(", "e", ")", "{", "done", "(", "'problem with response: '", "+", "e", ".", "message", ")", ";", "}", ")", ";", "}", ")", ";", "req", ".", "on", "(", "'error'", ",", "function", "(", "e", ")", "{", "done", "(", "'problem with request: '", "+", "e", ".", "message", ")", ";", "}", ")", ";", "req", ".", "end", "(", ")", ";", "}" ]
This method will get one of the components from Bootswatch, which is generally a `less` file or a `lessVariables` file. @see http://news.bootswatch.com/post/22193315172/bootswatch-api @param {string} url The url to retreive from @param {function(err, responseText)} done The callback when complete @param {?object} done.err If an error occurred, you will find it here. @param {string} done.responseText The body of whatever was returned @private
[ "This", "method", "will", "get", "one", "of", "the", "components", "from", "Bootswatch", "which", "is", "generally", "a", "less", "file", "or", "a", "lessVariables", "file", "." ]
40c2ba2da57c8ddb0a877340acc9a0604b1bafb4
https://github.com/jl-/gulp-docy/blob/40c2ba2da57c8ddb0a877340acc9a0604b1bafb4/docstrap/Gruntfile.js#L400-L420
54,446
junmer/is-otf
index.js
getViewTag
function getViewTag(view, offset) { var tag = '', i; for (i = offset; i < offset + 4; i += 1) { tag += String.fromCharCode(view.getInt8(i)); } return tag; }
javascript
function getViewTag(view, offset) { var tag = '', i; for (i = offset; i < offset + 4; i += 1) { tag += String.fromCharCode(view.getInt8(i)); } return tag; }
[ "function", "getViewTag", "(", "view", ",", "offset", ")", "{", "var", "tag", "=", "''", ",", "i", ";", "for", "(", "i", "=", "offset", ";", "i", "<", "offset", "+", "4", ";", "i", "+=", "1", ")", "{", "tag", "+=", "String", ".", "fromCharCode", "(", "view", ".", "getInt8", "(", "i", ")", ")", ";", "}", "return", "tag", ";", "}" ]
Retrieve a 4-character tag from the DataView. @param {DataView} view DataView @param {number} strLen string length @param {number} byteOffset byteOffset @return {string} string
[ "Retrieve", "a", "4", "-", "character", "tag", "from", "the", "DataView", "." ]
c42b15e09602ce92ac1cc16c24b6fbd4a3f336d2
https://github.com/junmer/is-otf/blob/c42b15e09602ce92ac1cc16c24b6fbd4a3f336d2/index.js#L65-L71
54,447
andornaut/react-keybinding-mixin
index.js
function() { // The last component to be unmounted uninstalls the event listener. if (components.length == 0) { document.removeEventListener(EVENT_TYPE, dispatchEvent); } components.splice(components.indexOf(this), 1); }
javascript
function() { // The last component to be unmounted uninstalls the event listener. if (components.length == 0) { document.removeEventListener(EVENT_TYPE, dispatchEvent); } components.splice(components.indexOf(this), 1); }
[ "function", "(", ")", "{", "// The last component to be unmounted uninstalls the event listener.", "if", "(", "components", ".", "length", "==", "0", ")", "{", "document", ".", "removeEventListener", "(", "EVENT_TYPE", ",", "dispatchEvent", ")", ";", "}", "components", ".", "splice", "(", "components", ".", "indexOf", "(", "this", ")", ",", "1", ")", ";", "}" ]
Un-register for keyboard events.
[ "Un", "-", "register", "for", "keyboard", "events", "." ]
7429700964968bf82b69a6f45e3855b3d306e83e
https://github.com/andornaut/react-keybinding-mixin/blob/7429700964968bf82b69a6f45e3855b3d306e83e/index.js#L103-L109
54,448
andornaut/react-keybinding-mixin
index.js
function(key, callback, options) { var binding; key = key.charCodeAt ? key.toUpperCase().charCodeAt() : key; options = assign({}, DEFAULT_OPTIONS, options || {}); binding = { callback: callback, options: options }; if (!this.keyBindings[key]) { this.keyBindings[key] = [binding]; } else { this.keyBindings[key].push(binding); } }
javascript
function(key, callback, options) { var binding; key = key.charCodeAt ? key.toUpperCase().charCodeAt() : key; options = assign({}, DEFAULT_OPTIONS, options || {}); binding = { callback: callback, options: options }; if (!this.keyBindings[key]) { this.keyBindings[key] = [binding]; } else { this.keyBindings[key].push(binding); } }
[ "function", "(", "key", ",", "callback", ",", "options", ")", "{", "var", "binding", ";", "key", "=", "key", ".", "charCodeAt", "?", "key", ".", "toUpperCase", "(", ")", ".", "charCodeAt", "(", ")", ":", "key", ";", "options", "=", "assign", "(", "{", "}", ",", "DEFAULT_OPTIONS", ",", "options", "||", "{", "}", ")", ";", "binding", "=", "{", "callback", ":", "callback", ",", "options", ":", "options", "}", ";", "if", "(", "!", "this", ".", "keyBindings", "[", "key", "]", ")", "{", "this", ".", "keyBindings", "[", "key", "]", "=", "[", "binding", "]", ";", "}", "else", "{", "this", ".", "keyBindings", "[", "key", "]", ".", "push", "(", "binding", ")", ";", "}", "}" ]
Bind a callback to the keydown event for a particular key. The options argument may contain booleans which describe the modifier keys to which the key-binding should apply. If options.input is true, then the supplied callback will be invoked even if the keydown event is triggered on an input field or button. @param {!number|!string} key - A keyCode or single lowercase character. Set options.shift = true for uppercase. @param {!function} callback @param {{alt: boolean, ctrl: boolean, meta: boolean, shift: boolean, input: boolean}} options
[ "Bind", "a", "callback", "to", "the", "keydown", "event", "for", "a", "particular", "key", "." ]
7429700964968bf82b69a6f45e3855b3d306e83e
https://github.com/andornaut/react-keybinding-mixin/blob/7429700964968bf82b69a6f45e3855b3d306e83e/index.js#L125-L137
54,449
tunnckoCore/request-all
index.js
normalize
function normalize (url, opts, callback) { url = typeof url === 'string' ? {url: url} : url opts = extend(url, opts) if (typeof opts.url !== 'string') { throw new TypeError('request-all: missing request url') } if (typeof callback !== 'function') { throw new TypeError('request-all: expect a callback') } opts.url = normalizeUrl(opts.url) opts.json = typeof opts.json === 'boolean' ? opts.json : true opts.headers = extend({ 'accept': 'application/json', 'user-agent': 'https://github.com/tunnckoCore/request-all' }, opts.headers) return opts }
javascript
function normalize (url, opts, callback) { url = typeof url === 'string' ? {url: url} : url opts = extend(url, opts) if (typeof opts.url !== 'string') { throw new TypeError('request-all: missing request url') } if (typeof callback !== 'function') { throw new TypeError('request-all: expect a callback') } opts.url = normalizeUrl(opts.url) opts.json = typeof opts.json === 'boolean' ? opts.json : true opts.headers = extend({ 'accept': 'application/json', 'user-agent': 'https://github.com/tunnckoCore/request-all' }, opts.headers) return opts }
[ "function", "normalize", "(", "url", ",", "opts", ",", "callback", ")", "{", "url", "=", "typeof", "url", "===", "'string'", "?", "{", "url", ":", "url", "}", ":", "url", "opts", "=", "extend", "(", "url", ",", "opts", ")", "if", "(", "typeof", "opts", ".", "url", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'request-all: missing request url'", ")", "}", "if", "(", "typeof", "callback", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", "'request-all: expect a callback'", ")", "}", "opts", ".", "url", "=", "normalizeUrl", "(", "opts", ".", "url", ")", "opts", ".", "json", "=", "typeof", "opts", ".", "json", "===", "'boolean'", "?", "opts", ".", "json", ":", "true", "opts", ".", "headers", "=", "extend", "(", "{", "'accept'", ":", "'application/json'", ",", "'user-agent'", ":", "'https://github.com/tunnckoCore/request-all'", "}", ",", "opts", ".", "headers", ")", "return", "opts", "}" ]
> Normalize and validate arguments and options @param {String|Object} `url` @param {Object} `opts` @param {Function} `callback` @return {Object}
[ ">", "Normalize", "and", "validate", "arguments", "and", "options" ]
5cbdf42d7f0999742acdf4f7394ad530b7ff5655
https://github.com/tunnckoCore/request-all/blob/5cbdf42d7f0999742acdf4f7394ad530b7ff5655/index.js#L64-L83
54,450
tunnckoCore/request-all
index.js
normalizeUrl
function normalizeUrl (url) { if (!url || /per_page=/.test(url)) return url /* istanbul ignore next */ if ((/&/.test(url) && !/&$/.test(url)) || (!/\?$/.test(url) && /\?/.test(url))) { return url + '&per_page=100' } return /\?$/.test(url) ? url + 'per_page=100' : url + '?per_page=100' }
javascript
function normalizeUrl (url) { if (!url || /per_page=/.test(url)) return url /* istanbul ignore next */ if ((/&/.test(url) && !/&$/.test(url)) || (!/\?$/.test(url) && /\?/.test(url))) { return url + '&per_page=100' } return /\?$/.test(url) ? url + 'per_page=100' : url + '?per_page=100' }
[ "function", "normalizeUrl", "(", "url", ")", "{", "if", "(", "!", "url", "||", "/", "per_page=", "/", ".", "test", "(", "url", ")", ")", "return", "url", "/* istanbul ignore next */", "if", "(", "(", "/", "&", "/", ".", "test", "(", "url", ")", "&&", "!", "/", "&$", "/", ".", "test", "(", "url", ")", ")", "||", "(", "!", "/", "\\?$", "/", ".", "test", "(", "url", ")", "&&", "/", "\\?", "/", ".", "test", "(", "url", ")", ")", ")", "{", "return", "url", "+", "'&per_page=100'", "}", "return", "/", "\\?$", "/", ".", "test", "(", "url", ")", "?", "url", "+", "'per_page=100'", ":", "url", "+", "'?per_page=100'", "}" ]
> Normalize URL query @param {String} `url` @return {String}
[ ">", "Normalize", "URL", "query" ]
5cbdf42d7f0999742acdf4f7394ad530b7ff5655
https://github.com/tunnckoCore/request-all/blob/5cbdf42d7f0999742acdf4f7394ad530b7ff5655/index.js#L92-L99
54,451
tunnckoCore/request-all
index.js
tryParse
function tryParse (val) { var res = null try { res = JSON.parse(val.toString()) } catch (err) { res = err } return res }
javascript
function tryParse (val) { var res = null try { res = JSON.parse(val.toString()) } catch (err) { res = err } return res }
[ "function", "tryParse", "(", "val", ")", "{", "var", "res", "=", "null", "try", "{", "res", "=", "JSON", ".", "parse", "(", "val", ".", "toString", "(", ")", ")", "}", "catch", "(", "err", ")", "{", "res", "=", "err", "}", "return", "res", "}" ]
> Catch JSON parse errors @param {Buffer} `val` @return {String|Array|Error}
[ ">", "Catch", "JSON", "parse", "errors" ]
5cbdf42d7f0999742acdf4f7394ad530b7ff5655
https://github.com/tunnckoCore/request-all/blob/5cbdf42d7f0999742acdf4f7394ad530b7ff5655/index.js#L134-L142
54,452
gtriggiano/dnsmq-messagebus
src/SubConnection.js
connect
function connect (master) { if (_socket && _socket._master.name === master.name) { debug(`already connected to master ${master.name}`) return } if (_connectingMaster && _connectingMaster.name === master.name) { debug(`already connecting to master ${master.name}`) return } _connectingMaster = master let newSocket = _getSocket(master) debug(`connecting to ${master.name} at ${master.endpoint}`) let connectionStart = Date.now() const onSocketReceiving = timingoutCallback((err, ...args) => { newSocket.unmonitor() if ( err || !_connectingMaster || _connectingMaster.name === !master.name ) { newSocket.close() if (err) { debug(`failed to connect to ${master.name} at ${master.endpoint}`) disconnect() } return } _connectingMaster = null let previousSocket = _socket debug(`${previousSocket ? 'switched' : 'connected'} to ${master.name} at ${master.endpoint} in ${Date.now() - connectionStart} ms`) if (args.length) { _onSocketMessage(...args) } _socket = newSocket _socket.removeAllListeners() _subscribedChannels.forEach(channel => _socket.subscribe(channel)) _socket.on('message', _onSocketMessage) _lastHeartbeatReceivedTime = Date.now() _monitorHeartbeats() if (previousSocket) { setTimeout(() => { previousSocket.removeAllListeners() previousSocket.close() debug(`closed previous connection to ${previousSocket._master.name} at ${previousSocket._master.endpoint}`) }, 300) } else { connection.emit('connect') } }, 500) newSocket.once('connect', () => onSocketReceiving()) newSocket.once('message', (...args) => onSocketReceiving(null, ...args)) return connection }
javascript
function connect (master) { if (_socket && _socket._master.name === master.name) { debug(`already connected to master ${master.name}`) return } if (_connectingMaster && _connectingMaster.name === master.name) { debug(`already connecting to master ${master.name}`) return } _connectingMaster = master let newSocket = _getSocket(master) debug(`connecting to ${master.name} at ${master.endpoint}`) let connectionStart = Date.now() const onSocketReceiving = timingoutCallback((err, ...args) => { newSocket.unmonitor() if ( err || !_connectingMaster || _connectingMaster.name === !master.name ) { newSocket.close() if (err) { debug(`failed to connect to ${master.name} at ${master.endpoint}`) disconnect() } return } _connectingMaster = null let previousSocket = _socket debug(`${previousSocket ? 'switched' : 'connected'} to ${master.name} at ${master.endpoint} in ${Date.now() - connectionStart} ms`) if (args.length) { _onSocketMessage(...args) } _socket = newSocket _socket.removeAllListeners() _subscribedChannels.forEach(channel => _socket.subscribe(channel)) _socket.on('message', _onSocketMessage) _lastHeartbeatReceivedTime = Date.now() _monitorHeartbeats() if (previousSocket) { setTimeout(() => { previousSocket.removeAllListeners() previousSocket.close() debug(`closed previous connection to ${previousSocket._master.name} at ${previousSocket._master.endpoint}`) }, 300) } else { connection.emit('connect') } }, 500) newSocket.once('connect', () => onSocketReceiving()) newSocket.once('message', (...args) => onSocketReceiving(null, ...args)) return connection }
[ "function", "connect", "(", "master", ")", "{", "if", "(", "_socket", "&&", "_socket", ".", "_master", ".", "name", "===", "master", ".", "name", ")", "{", "debug", "(", "`", "${", "master", ".", "name", "}", "`", ")", "return", "}", "if", "(", "_connectingMaster", "&&", "_connectingMaster", ".", "name", "===", "master", ".", "name", ")", "{", "debug", "(", "`", "${", "master", ".", "name", "}", "`", ")", "return", "}", "_connectingMaster", "=", "master", "let", "newSocket", "=", "_getSocket", "(", "master", ")", "debug", "(", "`", "${", "master", ".", "name", "}", "${", "master", ".", "endpoint", "}", "`", ")", "let", "connectionStart", "=", "Date", ".", "now", "(", ")", "const", "onSocketReceiving", "=", "timingoutCallback", "(", "(", "err", ",", "...", "args", ")", "=>", "{", "newSocket", ".", "unmonitor", "(", ")", "if", "(", "err", "||", "!", "_connectingMaster", "||", "_connectingMaster", ".", "name", "===", "!", "master", ".", "name", ")", "{", "newSocket", ".", "close", "(", ")", "if", "(", "err", ")", "{", "debug", "(", "`", "${", "master", ".", "name", "}", "${", "master", ".", "endpoint", "}", "`", ")", "disconnect", "(", ")", "}", "return", "}", "_connectingMaster", "=", "null", "let", "previousSocket", "=", "_socket", "debug", "(", "`", "${", "previousSocket", "?", "'switched'", ":", "'connected'", "}", "${", "master", ".", "name", "}", "${", "master", ".", "endpoint", "}", "${", "Date", ".", "now", "(", ")", "-", "connectionStart", "}", "`", ")", "if", "(", "args", ".", "length", ")", "{", "_onSocketMessage", "(", "...", "args", ")", "}", "_socket", "=", "newSocket", "_socket", ".", "removeAllListeners", "(", ")", "_subscribedChannels", ".", "forEach", "(", "channel", "=>", "_socket", ".", "subscribe", "(", "channel", ")", ")", "_socket", ".", "on", "(", "'message'", ",", "_onSocketMessage", ")", "_lastHeartbeatReceivedTime", "=", "Date", ".", "now", "(", ")", "_monitorHeartbeats", "(", ")", "if", "(", "previousSocket", ")", "{", "setTimeout", "(", "(", ")", "=>", "{", "previousSocket", ".", "removeAllListeners", "(", ")", "previousSocket", ".", "close", "(", ")", "debug", "(", "`", "${", "previousSocket", ".", "_master", ".", "name", "}", "${", "previousSocket", ".", "_master", ".", "endpoint", "}", "`", ")", "}", ",", "300", ")", "}", "else", "{", "connection", ".", "emit", "(", "'connect'", ")", "}", "}", ",", "500", ")", "newSocket", ".", "once", "(", "'connect'", ",", "(", ")", "=>", "onSocketReceiving", "(", ")", ")", "newSocket", ".", "once", "(", "'message'", ",", "(", "...", "args", ")", "=>", "onSocketReceiving", "(", "null", ",", "...", "args", ")", ")", "return", "connection", "}" ]
creates a new sub socket and tries to connect it to the provided master; after connection the socket is used to receive messages from the bus and an eventual previous socket is closed @param {object} master @return {object} the subscribeConnection instance
[ "creates", "a", "new", "sub", "socket", "and", "tries", "to", "connect", "it", "to", "the", "provided", "master", ";", "after", "connection", "the", "socket", "is", "used", "to", "receive", "messages", "from", "the", "bus", "and", "an", "eventual", "previous", "socket", "is", "closed" ]
ab935cae537f8a7e61a6ed6fba247661281c9374
https://github.com/gtriggiano/dnsmq-messagebus/blob/ab935cae537f8a7e61a6ed6fba247661281c9374/src/SubConnection.js#L116-L178
54,453
gtriggiano/dnsmq-messagebus
src/SubConnection.js
subscribe
function subscribe (channels) { channels.forEach(channel => { if (~_subscribedChannels.indexOf(channel)) return _subscribedChannels.push(channel) if (_socket) _socket.subscribe(channel) }) return connection }
javascript
function subscribe (channels) { channels.forEach(channel => { if (~_subscribedChannels.indexOf(channel)) return _subscribedChannels.push(channel) if (_socket) _socket.subscribe(channel) }) return connection }
[ "function", "subscribe", "(", "channels", ")", "{", "channels", ".", "forEach", "(", "channel", "=>", "{", "if", "(", "~", "_subscribedChannels", ".", "indexOf", "(", "channel", ")", ")", "return", "_subscribedChannels", ".", "push", "(", "channel", ")", "if", "(", "_socket", ")", "_socket", ".", "subscribe", "(", "channel", ")", "}", ")", "return", "connection", "}" ]
subscribes the component to the passed channels @param {[string]} channels @return {object} the subscribeConnection instance
[ "subscribes", "the", "component", "to", "the", "passed", "channels" ]
ab935cae537f8a7e61a6ed6fba247661281c9374
https://github.com/gtriggiano/dnsmq-messagebus/blob/ab935cae537f8a7e61a6ed6fba247661281c9374/src/SubConnection.js#L199-L206
54,454
gtriggiano/dnsmq-messagebus
src/SubConnection.js
unsubscribe
function unsubscribe (channels) { pullAll(_subscribedChannels, channels) if (_socket) channels.forEach(channel => _socket.unsubscribe(channel)) return connection }
javascript
function unsubscribe (channels) { pullAll(_subscribedChannels, channels) if (_socket) channels.forEach(channel => _socket.unsubscribe(channel)) return connection }
[ "function", "unsubscribe", "(", "channels", ")", "{", "pullAll", "(", "_subscribedChannels", ",", "channels", ")", "if", "(", "_socket", ")", "channels", ".", "forEach", "(", "channel", "=>", "_socket", ".", "unsubscribe", "(", "channel", ")", ")", "return", "connection", "}" ]
unsubscribes the component from the passed channels @param {[string]} channels @return {object} the subscribeConnection instance
[ "unsubscribes", "the", "component", "from", "the", "passed", "channels" ]
ab935cae537f8a7e61a6ed6fba247661281c9374
https://github.com/gtriggiano/dnsmq-messagebus/blob/ab935cae537f8a7e61a6ed6fba247661281c9374/src/SubConnection.js#L212-L216
54,455
MiguelCastillo/roolio
src/matcher.js
matcher
function matcher(match) { if (match instanceof RegExp) { return function(criteria) { return match.test(criteria); }; } return function(criteria) { return criteria === match; }; }
javascript
function matcher(match) { if (match instanceof RegExp) { return function(criteria) { return match.test(criteria); }; } return function(criteria) { return criteria === match; }; }
[ "function", "matcher", "(", "match", ")", "{", "if", "(", "match", "instanceof", "RegExp", ")", "{", "return", "function", "(", "criteria", ")", "{", "return", "match", ".", "test", "(", "criteria", ")", ";", "}", ";", "}", "return", "function", "(", "criteria", ")", "{", "return", "criteria", "===", "match", ";", "}", ";", "}" ]
Default matching rule with strict comparison. Or if the match is a regex then the comparison is done by calling the `test` method on the regex. @param {*} match - If the input is a regex, then matches will be done using the regex itself. Otherwise, the comparison is done with strict comparison. @returns {boolean}
[ "Default", "matching", "rule", "with", "strict", "comparison", ".", "Or", "if", "the", "match", "is", "a", "regex", "then", "the", "comparison", "is", "done", "by", "calling", "the", "test", "method", "on", "the", "regex", "." ]
a62434e8f9622e1dbec3452f463b5e86913d49a8
https://github.com/MiguelCastillo/roolio/blob/a62434e8f9622e1dbec3452f463b5e86913d49a8/src/matcher.js#L10-L20
54,456
SBoudrias/gulp-validate-jsdoc
validate-jsdoc.js
analyzeFunction
function analyzeFunction(node) { var comment = node.leadingComments[0]; if (comment.type !== 'Block') { return; } var data = doctrine.parse(comment.value, { unwrap: true }); var params = []; data.tags.forEach(function (tag) { if (tag.title === 'param') { params.push(tag.name); } }); var missing = []; node.params.forEach(function (param) { if (params.indexOf(param.name) < 0) { missing.push(param.name); } }); if (missing.length > 0) { var msg = ''; msg += 'In function ' + chalk.cyan(node.id.name) + ' (Line ' + node.loc.start.line + '):\n'; missing.forEach(function (m) { msg += ' Parameter ' + chalk.cyan(m) + ' is not documented.'; }); throw new Error(msg); } }
javascript
function analyzeFunction(node) { var comment = node.leadingComments[0]; if (comment.type !== 'Block') { return; } var data = doctrine.parse(comment.value, { unwrap: true }); var params = []; data.tags.forEach(function (tag) { if (tag.title === 'param') { params.push(tag.name); } }); var missing = []; node.params.forEach(function (param) { if (params.indexOf(param.name) < 0) { missing.push(param.name); } }); if (missing.length > 0) { var msg = ''; msg += 'In function ' + chalk.cyan(node.id.name) + ' (Line ' + node.loc.start.line + '):\n'; missing.forEach(function (m) { msg += ' Parameter ' + chalk.cyan(m) + ' is not documented.'; }); throw new Error(msg); } }
[ "function", "analyzeFunction", "(", "node", ")", "{", "var", "comment", "=", "node", ".", "leadingComments", "[", "0", "]", ";", "if", "(", "comment", ".", "type", "!==", "'Block'", ")", "{", "return", ";", "}", "var", "data", "=", "doctrine", ".", "parse", "(", "comment", ".", "value", ",", "{", "unwrap", ":", "true", "}", ")", ";", "var", "params", "=", "[", "]", ";", "data", ".", "tags", ".", "forEach", "(", "function", "(", "tag", ")", "{", "if", "(", "tag", ".", "title", "===", "'param'", ")", "{", "params", ".", "push", "(", "tag", ".", "name", ")", ";", "}", "}", ")", ";", "var", "missing", "=", "[", "]", ";", "node", ".", "params", ".", "forEach", "(", "function", "(", "param", ")", "{", "if", "(", "params", ".", "indexOf", "(", "param", ".", "name", ")", "<", "0", ")", "{", "missing", ".", "push", "(", "param", ".", "name", ")", ";", "}", "}", ")", ";", "if", "(", "missing", ".", "length", ">", "0", ")", "{", "var", "msg", "=", "''", ";", "msg", "+=", "'In function '", "+", "chalk", ".", "cyan", "(", "node", ".", "id", ".", "name", ")", "+", "' (Line '", "+", "node", ".", "loc", ".", "start", ".", "line", "+", "'):\\n'", ";", "missing", ".", "forEach", "(", "function", "(", "m", ")", "{", "msg", "+=", "' Parameter '", "+", "chalk", ".", "cyan", "(", "m", ")", "+", "' is not documented.'", ";", "}", ")", ";", "throw", "new", "Error", "(", "msg", ")", ";", "}", "}" ]
Take a function node and analyze its JsDoc comments @param {FunctionDeclaration} node FunctionDeclaration esprima node @return {null} @throws {Error} Will throw when invalid JsDoc is encountered
[ "Take", "a", "function", "node", "and", "analyze", "its", "JsDoc", "comments" ]
23eae3f5b24310a93d546a40cc9a9e7ab4542d9a
https://github.com/SBoudrias/gulp-validate-jsdoc/blob/23eae3f5b24310a93d546a40cc9a9e7ab4542d9a/validate-jsdoc.js#L13-L41
54,457
SBoudrias/gulp-validate-jsdoc
validate-jsdoc.js
verify
function verify(node) { switch (node.type) { case esprima.Syntax.FunctionDeclaration: if (node.leadingComments && node.leadingComments.length === 1) { analyzeFunction(node); } break; default: break; } }
javascript
function verify(node) { switch (node.type) { case esprima.Syntax.FunctionDeclaration: if (node.leadingComments && node.leadingComments.length === 1) { analyzeFunction(node); } break; default: break; } }
[ "function", "verify", "(", "node", ")", "{", "switch", "(", "node", ".", "type", ")", "{", "case", "esprima", ".", "Syntax", ".", "FunctionDeclaration", ":", "if", "(", "node", ".", "leadingComments", "&&", "node", ".", "leadingComments", ".", "length", "===", "1", ")", "{", "analyzeFunction", "(", "node", ")", ";", "}", "break", ";", "default", ":", "break", ";", "}", "}" ]
Accept a node and analyze it if it's a function @param {Object} node Esprima node @return {null}
[ "Accept", "a", "node", "and", "analyze", "it", "if", "it", "s", "a", "function" ]
23eae3f5b24310a93d546a40cc9a9e7ab4542d9a
https://github.com/SBoudrias/gulp-validate-jsdoc/blob/23eae3f5b24310a93d546a40cc9a9e7ab4542d9a/validate-jsdoc.js#L48-L58
54,458
mastilver/node-annotation-router
index.js
pathParse
function pathParse(fullPath){ var parsedPath = { ext: path.extname(fullPath), dir: path.dirname(fullPath), full: fullPath, base: path.basename(fullPath), }; parsedPath.name = path.basename(fullPath, parsedPath.ext); return parsedPath; }
javascript
function pathParse(fullPath){ var parsedPath = { ext: path.extname(fullPath), dir: path.dirname(fullPath), full: fullPath, base: path.basename(fullPath), }; parsedPath.name = path.basename(fullPath, parsedPath.ext); return parsedPath; }
[ "function", "pathParse", "(", "fullPath", ")", "{", "var", "parsedPath", "=", "{", "ext", ":", "path", ".", "extname", "(", "fullPath", ")", ",", "dir", ":", "path", ".", "dirname", "(", "fullPath", ")", ",", "full", ":", "fullPath", ",", "base", ":", "path", ".", "basename", "(", "fullPath", ")", ",", "}", ";", "parsedPath", ".", "name", "=", "path", ".", "basename", "(", "fullPath", ",", "parsedPath", ".", "ext", ")", ";", "return", "parsedPath", ";", "}" ]
mimics the path.parse function
[ "mimics", "the", "path", ".", "parse", "function" ]
340eec100fca9faa7f4762ff6c937b619c04524f
https://github.com/mastilver/node-annotation-router/blob/340eec100fca9faa7f4762ff6c937b619c04524f/index.js#L182-L194
54,459
wilmoore/function-pipeline.js
index.js
pipe
function pipe () { var fns = [].slice.call(arguments) var end = fns.length var idx = -1 var out return function pipe (initialValue) { out = initialValue while (++idx < end) { out = fns[idx](out) } return out } }
javascript
function pipe () { var fns = [].slice.call(arguments) var end = fns.length var idx = -1 var out return function pipe (initialValue) { out = initialValue while (++idx < end) { out = fns[idx](out) } return out } }
[ "function", "pipe", "(", ")", "{", "var", "fns", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ")", "var", "end", "=", "fns", ".", "length", "var", "idx", "=", "-", "1", "var", "out", "return", "function", "pipe", "(", "initialValue", ")", "{", "out", "=", "initialValue", "while", "(", "++", "idx", "<", "end", ")", "{", "out", "=", "fns", "[", "idx", "]", "(", "out", ")", "}", "return", "out", "}", "}" ]
Similar to the Unix `|` operator; returns a function that invokes the given series of functions whose output is subsequently passed to the next function in the series. @param {…Function|Function[]} fns - Functions to apply as an argument list or array of arguments. @return {Function} Function that invokes the given series of functions.
[ "Similar", "to", "the", "Unix", "|", "operator", ";", "returns", "a", "function", "that", "invokes", "the", "given", "series", "of", "functions", "whose", "output", "is", "subsequently", "passed", "to", "the", "next", "function", "in", "the", "series", "." ]
f5dcd11d9e4fd7b819dd86ed4c0e3c30e5a73f4c
https://github.com/wilmoore/function-pipeline.js/blob/f5dcd11d9e4fd7b819dd86ed4c0e3c30e5a73f4c/index.js#L20-L35
54,460
mixdown/mixdown-cli
index.js
function() { if (_.keys(children).length == 0) { that.stop(process.exit); } else { setImmediate(checkExit); // keep polling for safe shutdown. } }
javascript
function() { if (_.keys(children).length == 0) { that.stop(process.exit); } else { setImmediate(checkExit); // keep polling for safe shutdown. } }
[ "function", "(", ")", "{", "if", "(", "_", ".", "keys", "(", "children", ")", ".", "length", "==", "0", ")", "{", "that", ".", "stop", "(", "process", ".", "exit", ")", ";", "}", "else", "{", "setImmediate", "(", "checkExit", ")", ";", "// keep polling for safe shutdown.", "}", "}" ]
create function to check that all workers are dead.
[ "create", "function", "to", "check", "that", "all", "workers", "are", "dead", "." ]
2792cd743ac4299d5aab0e88e87edf1231f5a9a2
https://github.com/mixdown/mixdown-cli/blob/2792cd743ac4299d5aab0e88e87edf1231f5a9a2/index.js#L113-L120
54,461
adiwidjaja/frontend-pagebuilder
js/tinymce/plugins/autoresize/plugin.js
resize
function resize(e) { var deltaSize, doc, body, docElm, resizeHeight, myHeight, marginTop, marginBottom, paddingTop, paddingBottom, borderTop, borderBottom; doc = editor.getDoc(); if (!doc) { return; } body = doc.body; docElm = doc.documentElement; resizeHeight = settings.autoresize_min_height; if (!body || (e && e.type === "setcontent" && e.initial) || isFullscreen()) { if (body && docElm) { body.style.overflowY = "auto"; docElm.style.overflowY = "auto"; // Old IE } return; } // Calculate outer height of the body element using CSS styles marginTop = editor.dom.getStyle(body, 'margin-top', true); marginBottom = editor.dom.getStyle(body, 'margin-bottom', true); paddingTop = editor.dom.getStyle(body, 'padding-top', true); paddingBottom = editor.dom.getStyle(body, 'padding-bottom', true); borderTop = editor.dom.getStyle(body, 'border-top-width', true); borderBottom = editor.dom.getStyle(body, 'border-bottom-width', true); myHeight = body.offsetHeight + parseInt(marginTop, 10) + parseInt(marginBottom, 10) + parseInt(paddingTop, 10) + parseInt(paddingBottom, 10) + parseInt(borderTop, 10) + parseInt(borderBottom, 10); // Make sure we have a valid height if (isNaN(myHeight) || myHeight <= 0) { // Get height differently depending on the browser used // eslint-disable-next-line no-nested-ternary myHeight = Env.ie ? body.scrollHeight : (Env.webkit && body.clientHeight === 0 ? 0 : body.offsetHeight); } // Don't make it smaller than the minimum height if (myHeight > settings.autoresize_min_height) { resizeHeight = myHeight; } // If a maximum height has been defined don't exceed this height if (settings.autoresize_max_height && myHeight > settings.autoresize_max_height) { resizeHeight = settings.autoresize_max_height; body.style.overflowY = "auto"; docElm.style.overflowY = "auto"; // Old IE } else { body.style.overflowY = "hidden"; docElm.style.overflowY = "hidden"; // Old IE body.scrollTop = 0; } // Resize content element if (resizeHeight !== oldSize) { deltaSize = resizeHeight - oldSize; DOM.setStyle(editor.iframeElement, 'height', resizeHeight + 'px'); oldSize = resizeHeight; // WebKit doesn't decrease the size of the body element until the iframe gets resized // So we need to continue to resize the iframe down until the size gets fixed if (Env.webKit && deltaSize < 0) { resize(e); } } }
javascript
function resize(e) { var deltaSize, doc, body, docElm, resizeHeight, myHeight, marginTop, marginBottom, paddingTop, paddingBottom, borderTop, borderBottom; doc = editor.getDoc(); if (!doc) { return; } body = doc.body; docElm = doc.documentElement; resizeHeight = settings.autoresize_min_height; if (!body || (e && e.type === "setcontent" && e.initial) || isFullscreen()) { if (body && docElm) { body.style.overflowY = "auto"; docElm.style.overflowY = "auto"; // Old IE } return; } // Calculate outer height of the body element using CSS styles marginTop = editor.dom.getStyle(body, 'margin-top', true); marginBottom = editor.dom.getStyle(body, 'margin-bottom', true); paddingTop = editor.dom.getStyle(body, 'padding-top', true); paddingBottom = editor.dom.getStyle(body, 'padding-bottom', true); borderTop = editor.dom.getStyle(body, 'border-top-width', true); borderBottom = editor.dom.getStyle(body, 'border-bottom-width', true); myHeight = body.offsetHeight + parseInt(marginTop, 10) + parseInt(marginBottom, 10) + parseInt(paddingTop, 10) + parseInt(paddingBottom, 10) + parseInt(borderTop, 10) + parseInt(borderBottom, 10); // Make sure we have a valid height if (isNaN(myHeight) || myHeight <= 0) { // Get height differently depending on the browser used // eslint-disable-next-line no-nested-ternary myHeight = Env.ie ? body.scrollHeight : (Env.webkit && body.clientHeight === 0 ? 0 : body.offsetHeight); } // Don't make it smaller than the minimum height if (myHeight > settings.autoresize_min_height) { resizeHeight = myHeight; } // If a maximum height has been defined don't exceed this height if (settings.autoresize_max_height && myHeight > settings.autoresize_max_height) { resizeHeight = settings.autoresize_max_height; body.style.overflowY = "auto"; docElm.style.overflowY = "auto"; // Old IE } else { body.style.overflowY = "hidden"; docElm.style.overflowY = "hidden"; // Old IE body.scrollTop = 0; } // Resize content element if (resizeHeight !== oldSize) { deltaSize = resizeHeight - oldSize; DOM.setStyle(editor.iframeElement, 'height', resizeHeight + 'px'); oldSize = resizeHeight; // WebKit doesn't decrease the size of the body element until the iframe gets resized // So we need to continue to resize the iframe down until the size gets fixed if (Env.webKit && deltaSize < 0) { resize(e); } } }
[ "function", "resize", "(", "e", ")", "{", "var", "deltaSize", ",", "doc", ",", "body", ",", "docElm", ",", "resizeHeight", ",", "myHeight", ",", "marginTop", ",", "marginBottom", ",", "paddingTop", ",", "paddingBottom", ",", "borderTop", ",", "borderBottom", ";", "doc", "=", "editor", ".", "getDoc", "(", ")", ";", "if", "(", "!", "doc", ")", "{", "return", ";", "}", "body", "=", "doc", ".", "body", ";", "docElm", "=", "doc", ".", "documentElement", ";", "resizeHeight", "=", "settings", ".", "autoresize_min_height", ";", "if", "(", "!", "body", "||", "(", "e", "&&", "e", ".", "type", "===", "\"setcontent\"", "&&", "e", ".", "initial", ")", "||", "isFullscreen", "(", ")", ")", "{", "if", "(", "body", "&&", "docElm", ")", "{", "body", ".", "style", ".", "overflowY", "=", "\"auto\"", ";", "docElm", ".", "style", ".", "overflowY", "=", "\"auto\"", ";", "// Old IE", "}", "return", ";", "}", "// Calculate outer height of the body element using CSS styles", "marginTop", "=", "editor", ".", "dom", ".", "getStyle", "(", "body", ",", "'margin-top'", ",", "true", ")", ";", "marginBottom", "=", "editor", ".", "dom", ".", "getStyle", "(", "body", ",", "'margin-bottom'", ",", "true", ")", ";", "paddingTop", "=", "editor", ".", "dom", ".", "getStyle", "(", "body", ",", "'padding-top'", ",", "true", ")", ";", "paddingBottom", "=", "editor", ".", "dom", ".", "getStyle", "(", "body", ",", "'padding-bottom'", ",", "true", ")", ";", "borderTop", "=", "editor", ".", "dom", ".", "getStyle", "(", "body", ",", "'border-top-width'", ",", "true", ")", ";", "borderBottom", "=", "editor", ".", "dom", ".", "getStyle", "(", "body", ",", "'border-bottom-width'", ",", "true", ")", ";", "myHeight", "=", "body", ".", "offsetHeight", "+", "parseInt", "(", "marginTop", ",", "10", ")", "+", "parseInt", "(", "marginBottom", ",", "10", ")", "+", "parseInt", "(", "paddingTop", ",", "10", ")", "+", "parseInt", "(", "paddingBottom", ",", "10", ")", "+", "parseInt", "(", "borderTop", ",", "10", ")", "+", "parseInt", "(", "borderBottom", ",", "10", ")", ";", "// Make sure we have a valid height", "if", "(", "isNaN", "(", "myHeight", ")", "||", "myHeight", "<=", "0", ")", "{", "// Get height differently depending on the browser used", "// eslint-disable-next-line no-nested-ternary", "myHeight", "=", "Env", ".", "ie", "?", "body", ".", "scrollHeight", ":", "(", "Env", ".", "webkit", "&&", "body", ".", "clientHeight", "===", "0", "?", "0", ":", "body", ".", "offsetHeight", ")", ";", "}", "// Don't make it smaller than the minimum height", "if", "(", "myHeight", ">", "settings", ".", "autoresize_min_height", ")", "{", "resizeHeight", "=", "myHeight", ";", "}", "// If a maximum height has been defined don't exceed this height", "if", "(", "settings", ".", "autoresize_max_height", "&&", "myHeight", ">", "settings", ".", "autoresize_max_height", ")", "{", "resizeHeight", "=", "settings", ".", "autoresize_max_height", ";", "body", ".", "style", ".", "overflowY", "=", "\"auto\"", ";", "docElm", ".", "style", ".", "overflowY", "=", "\"auto\"", ";", "// Old IE", "}", "else", "{", "body", ".", "style", ".", "overflowY", "=", "\"hidden\"", ";", "docElm", ".", "style", ".", "overflowY", "=", "\"hidden\"", ";", "// Old IE", "body", ".", "scrollTop", "=", "0", ";", "}", "// Resize content element", "if", "(", "resizeHeight", "!==", "oldSize", ")", "{", "deltaSize", "=", "resizeHeight", "-", "oldSize", ";", "DOM", ".", "setStyle", "(", "editor", ".", "iframeElement", ",", "'height'", ",", "resizeHeight", "+", "'px'", ")", ";", "oldSize", "=", "resizeHeight", ";", "// WebKit doesn't decrease the size of the body element until the iframe gets resized", "// So we need to continue to resize the iframe down until the size gets fixed", "if", "(", "Env", ".", "webKit", "&&", "deltaSize", "<", "0", ")", "{", "resize", "(", "e", ")", ";", "}", "}", "}" ]
This method gets executed each time the editor needs to resize.
[ "This", "method", "gets", "executed", "each", "time", "the", "editor", "needs", "to", "resize", "." ]
a08caa06cd9f919d575eb68f0d6b56fdedfb7d0f
https://github.com/adiwidjaja/frontend-pagebuilder/blob/a08caa06cd9f919d575eb68f0d6b56fdedfb7d0f/js/tinymce/plugins/autoresize/plugin.js#L208-L276
54,462
adiwidjaja/frontend-pagebuilder
js/tinymce/plugins/autoresize/plugin.js
wait
function wait(times, interval, callback) { Delay.setEditorTimeout(editor, function () { resize({}); if (times--) { wait(times, interval, callback); } else if (callback) { callback(); } }, interval); }
javascript
function wait(times, interval, callback) { Delay.setEditorTimeout(editor, function () { resize({}); if (times--) { wait(times, interval, callback); } else if (callback) { callback(); } }, interval); }
[ "function", "wait", "(", "times", ",", "interval", ",", "callback", ")", "{", "Delay", ".", "setEditorTimeout", "(", "editor", ",", "function", "(", ")", "{", "resize", "(", "{", "}", ")", ";", "if", "(", "times", "--", ")", "{", "wait", "(", "times", ",", "interval", ",", "callback", ")", ";", "}", "else", "if", "(", "callback", ")", "{", "callback", "(", ")", ";", "}", "}", ",", "interval", ")", ";", "}" ]
Calls the resize x times in 100ms intervals. We can't wait for load events since the CSS files might load async.
[ "Calls", "the", "resize", "x", "times", "in", "100ms", "intervals", ".", "We", "can", "t", "wait", "for", "load", "events", "since", "the", "CSS", "files", "might", "load", "async", "." ]
a08caa06cd9f919d575eb68f0d6b56fdedfb7d0f
https://github.com/adiwidjaja/frontend-pagebuilder/blob/a08caa06cd9f919d575eb68f0d6b56fdedfb7d0f/js/tinymce/plugins/autoresize/plugin.js#L282-L292
54,463
ArtOfCode-/nails
src/nails.js
lazy
function lazy(key, get) { const uninitialized = {}; let _val = uninitialized; Object.defineProperty(exports, key, { get() { if (_val === uninitialized) { _val = get(); } return _val; }, }); }
javascript
function lazy(key, get) { const uninitialized = {}; let _val = uninitialized; Object.defineProperty(exports, key, { get() { if (_val === uninitialized) { _val = get(); } return _val; }, }); }
[ "function", "lazy", "(", "key", ",", "get", ")", "{", "const", "uninitialized", "=", "{", "}", ";", "let", "_val", "=", "uninitialized", ";", "Object", ".", "defineProperty", "(", "exports", ",", "key", ",", "{", "get", "(", ")", "{", "if", "(", "_val", "===", "uninitialized", ")", "{", "_val", "=", "get", "(", ")", ";", "}", "return", "_val", ";", "}", ",", "}", ")", ";", "}" ]
Define a lazy property on `exports` that retrieves the value when accessed the first time @private @param {string} key The key to add @param {Function} get The function to generate the value
[ "Define", "a", "lazy", "property", "on", "exports", "that", "retrieves", "the", "value", "when", "accessed", "the", "first", "time" ]
1ba9158742ba72bc727ad5c881035ee9d99b700c
https://github.com/ArtOfCode-/nails/blob/1ba9158742ba72bc727ad5c881035ee9d99b700c/src/nails.js#L32-L43
54,464
tualo/tualo-imap
lib/imap.js
Connection
function Connection(options) { if (!(this instanceof Connection)){ return new Connection(options); } this.prefixCounter = 0; this.serverMessages = {}; this._options = { username: options.username || options.user || '', password: options.password || '', host: options.host || 'localhost', port: options.port || 143, secure: options.secure === true ? { // secure = true means default behavior rejectUnauthorized: false // Force pre-node-0.9.2 behavior } : (options.secure || false), timeout: options.timeout || 10000, // connection timeout in msecs xoauth: options.xoauth, xoauth2: options.xoauth2 }; this._messages = {}; this._messages = {}; if (options.debug===true){ this.debug = function(msg){ console.log(msg); } } if (options.chainDebug===true){ this.chainDebug = function(msg){ console.log(msg); } } this.socket = null; this._messages_prefix_key={}; this._messages_key_prefix={}; this._messages={}; this._msg_buffer = ''; this._resetChainCommands(); }
javascript
function Connection(options) { if (!(this instanceof Connection)){ return new Connection(options); } this.prefixCounter = 0; this.serverMessages = {}; this._options = { username: options.username || options.user || '', password: options.password || '', host: options.host || 'localhost', port: options.port || 143, secure: options.secure === true ? { // secure = true means default behavior rejectUnauthorized: false // Force pre-node-0.9.2 behavior } : (options.secure || false), timeout: options.timeout || 10000, // connection timeout in msecs xoauth: options.xoauth, xoauth2: options.xoauth2 }; this._messages = {}; this._messages = {}; if (options.debug===true){ this.debug = function(msg){ console.log(msg); } } if (options.chainDebug===true){ this.chainDebug = function(msg){ console.log(msg); } } this.socket = null; this._messages_prefix_key={}; this._messages_key_prefix={}; this._messages={}; this._msg_buffer = ''; this._resetChainCommands(); }
[ "function", "Connection", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Connection", ")", ")", "{", "return", "new", "Connection", "(", "options", ")", ";", "}", "this", ".", "prefixCounter", "=", "0", ";", "this", ".", "serverMessages", "=", "{", "}", ";", "this", ".", "_options", "=", "{", "username", ":", "options", ".", "username", "||", "options", ".", "user", "||", "''", ",", "password", ":", "options", ".", "password", "||", "''", ",", "host", ":", "options", ".", "host", "||", "'localhost'", ",", "port", ":", "options", ".", "port", "||", "143", ",", "secure", ":", "options", ".", "secure", "===", "true", "?", "{", "// secure = true means default behavior", "rejectUnauthorized", ":", "false", "// Force pre-node-0.9.2 behavior", "}", ":", "(", "options", ".", "secure", "||", "false", ")", ",", "timeout", ":", "options", ".", "timeout", "||", "10000", ",", "// connection timeout in msecs", "xoauth", ":", "options", ".", "xoauth", ",", "xoauth2", ":", "options", ".", "xoauth2", "}", ";", "this", ".", "_messages", "=", "{", "}", ";", "this", ".", "_messages", "=", "{", "}", ";", "if", "(", "options", ".", "debug", "===", "true", ")", "{", "this", ".", "debug", "=", "function", "(", "msg", ")", "{", "console", ".", "log", "(", "msg", ")", ";", "}", "}", "if", "(", "options", ".", "chainDebug", "===", "true", ")", "{", "this", ".", "chainDebug", "=", "function", "(", "msg", ")", "{", "console", ".", "log", "(", "msg", ")", ";", "}", "}", "this", ".", "socket", "=", "null", ";", "this", ".", "_messages_prefix_key", "=", "{", "}", ";", "this", ".", "_messages_key_prefix", "=", "{", "}", ";", "this", ".", "_messages", "=", "{", "}", ";", "this", ".", "_msg_buffer", "=", "''", ";", "this", ".", "_resetChainCommands", "(", ")", ";", "}" ]
Create a new instance of Connection. This instance inherits all functions of the EventEmitter. @constructor @this {Connection} @param {object} options
[ "Create", "a", "new", "instance", "of", "Connection", ".", "This", "instance", "inherits", "all", "functions", "of", "the", "EventEmitter", "." ]
948d9cb4693eb0d0e82530365ece36c1d8dbecf3
https://github.com/tualo/tualo-imap/blob/948d9cb4693eb0d0e82530365ece36c1d8dbecf3/lib/imap.js#L19-L66
54,465
tungtung-dev/common-helper
src/random/randomId.js
makeId
function makeId(length = RANDOM_CHARACTER_LENGTH) { let text = ""; for (let i = 0; i < length; i++) { text += RANDOM_CHARACTER_SOURCE.charAt(Math.floor(Math.random() * RANDOM_CHARACTER_SOURCE.length)); } return text; }
javascript
function makeId(length = RANDOM_CHARACTER_LENGTH) { let text = ""; for (let i = 0; i < length; i++) { text += RANDOM_CHARACTER_SOURCE.charAt(Math.floor(Math.random() * RANDOM_CHARACTER_SOURCE.length)); } return text; }
[ "function", "makeId", "(", "length", "=", "RANDOM_CHARACTER_LENGTH", ")", "{", "let", "text", "=", "\"\"", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "text", "+=", "RANDOM_CHARACTER_SOURCE", ".", "charAt", "(", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "RANDOM_CHARACTER_SOURCE", ".", "length", ")", ")", ";", "}", "return", "text", ";", "}" ]
Support generate random string with 5 characters @returns {string}
[ "Support", "generate", "random", "string", "with", "5", "characters" ]
94abeff34fee3b2366b308571e94f2da8b0db655
https://github.com/tungtung-dev/common-helper/blob/94abeff34fee3b2366b308571e94f2da8b0db655/src/random/randomId.js#L12-L19
54,466
HPSoftware/node-offline-debug
lib/config.js
merge_config
function merge_config(top_config, base_config) { for (var option in top_config) { if (Array.isArray(top_config[option])) // handle array elements in the same order { if (!Array.isArray(base_config[option])) base_config[option] = top_config[option]; else { for(var i=0;i<top_config[option].length;i++) { if (base_config[option].length <= i) base_config[option].push(top_config[option][i]); else merge_config(top_config[option][i],base_config[option][i]); } } } else if (typeof top_config[option] === "Object") // recurseively handle complex configurations { if (base_config[option] === undefined) base_config[option] = top_config[option]; else merge_config(top_config[option], base_config[option]); } else base_config[option] = top_config[option]; } }
javascript
function merge_config(top_config, base_config) { for (var option in top_config) { if (Array.isArray(top_config[option])) // handle array elements in the same order { if (!Array.isArray(base_config[option])) base_config[option] = top_config[option]; else { for(var i=0;i<top_config[option].length;i++) { if (base_config[option].length <= i) base_config[option].push(top_config[option][i]); else merge_config(top_config[option][i],base_config[option][i]); } } } else if (typeof top_config[option] === "Object") // recurseively handle complex configurations { if (base_config[option] === undefined) base_config[option] = top_config[option]; else merge_config(top_config[option], base_config[option]); } else base_config[option] = top_config[option]; } }
[ "function", "merge_config", "(", "top_config", ",", "base_config", ")", "{", "for", "(", "var", "option", "in", "top_config", ")", "{", "if", "(", "Array", ".", "isArray", "(", "top_config", "[", "option", "]", ")", ")", "// handle array elements in the same order", "{", "if", "(", "!", "Array", ".", "isArray", "(", "base_config", "[", "option", "]", ")", ")", "base_config", "[", "option", "]", "=", "top_config", "[", "option", "]", ";", "else", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "top_config", "[", "option", "]", ".", "length", ";", "i", "++", ")", "{", "if", "(", "base_config", "[", "option", "]", ".", "length", "<=", "i", ")", "base_config", "[", "option", "]", ".", "push", "(", "top_config", "[", "option", "]", "[", "i", "]", ")", ";", "else", "merge_config", "(", "top_config", "[", "option", "]", "[", "i", "]", ",", "base_config", "[", "option", "]", "[", "i", "]", ")", ";", "}", "}", "}", "else", "if", "(", "typeof", "top_config", "[", "option", "]", "===", "\"Object\"", ")", "// recurseively handle complex configurations", "{", "if", "(", "base_config", "[", "option", "]", "===", "undefined", ")", "base_config", "[", "option", "]", "=", "top_config", "[", "option", "]", ";", "else", "merge_config", "(", "top_config", "[", "option", "]", ",", "base_config", "[", "option", "]", ")", ";", "}", "else", "base_config", "[", "option", "]", "=", "top_config", "[", "option", "]", ";", "}", "}" ]
copy app_config configurations over package configurations
[ "copy", "app_config", "configurations", "over", "package", "configurations" ]
2b4638cfc568c6e82a6e4b6dcbbefef4215f27f1
https://github.com/HPSoftware/node-offline-debug/blob/2b4638cfc568c6e82a6e4b6dcbbefef4215f27f1/lib/config.js#L16-L46
54,467
wilmoore/rerun-script
index.js
getWatches
function getWatches (directory) { var package_path = resolve(directory || './') var pkg = read(package_path) var watches = extract(pkg) return Array.isArray(watches) ? watches : [] }
javascript
function getWatches (directory) { var package_path = resolve(directory || './') var pkg = read(package_path) var watches = extract(pkg) return Array.isArray(watches) ? watches : [] }
[ "function", "getWatches", "(", "directory", ")", "{", "var", "package_path", "=", "resolve", "(", "directory", "||", "'./'", ")", "var", "pkg", "=", "read", "(", "package_path", ")", "var", "watches", "=", "extract", "(", "pkg", ")", "return", "Array", ".", "isArray", "(", "watches", ")", "?", "watches", ":", "[", "]", "}" ]
Get package watches. @param {String} directory Package directory. @return {Array} Array of watches.
[ "Get", "package", "watches", "." ]
922e17baca2e53a55586e8b86a7c42f6571dc8c8
https://github.com/wilmoore/rerun-script/blob/922e17baca2e53a55586e8b86a7c42f6571dc8c8/index.js#L26-L31
54,468
sitegui/asynconnection-core
lib/Context.js
Context
function Context() { /** * @member {Object} * @property {Object} client * @property {Object<Call>} client.map - map from call name and call id * @property {Array<Call>} client.list * @property {Object} server * @property {Object<Call>} server.map - map from call name and call id * @property {Array<Call>} server.list * @private */ this._calls = { client: { map: Object.create(null), list: [] }, server: { map: Object.create(null), list: [] } } /** * @member {Object} * @property {Object} client * @property {Object<Message>} client.map - map from message name and message id * @property {Array<Message>} client.list * @property {Object} server * @property {Object<Message>} server.map - map from message name and message id * @property {Array<Message>} server.list * @private */ this._messages = { client: { map: Object.create(null), list: [] }, server: { map: Object.create(null), list: [] } } }
javascript
function Context() { /** * @member {Object} * @property {Object} client * @property {Object<Call>} client.map - map from call name and call id * @property {Array<Call>} client.list * @property {Object} server * @property {Object<Call>} server.map - map from call name and call id * @property {Array<Call>} server.list * @private */ this._calls = { client: { map: Object.create(null), list: [] }, server: { map: Object.create(null), list: [] } } /** * @member {Object} * @property {Object} client * @property {Object<Message>} client.map - map from message name and message id * @property {Array<Message>} client.list * @property {Object} server * @property {Object<Message>} server.map - map from message name and message id * @property {Array<Message>} server.list * @private */ this._messages = { client: { map: Object.create(null), list: [] }, server: { map: Object.create(null), list: [] } } }
[ "function", "Context", "(", ")", "{", "/**\n\t * @member {Object}\n\t * @property {Object} client\n\t * @property {Object<Call>} client.map - map from call name and call id\n\t * @property {Array<Call>} client.list\n\t * @property {Object} server\n\t * @property {Object<Call>} server.map - map from call name and call id\n\t * @property {Array<Call>} server.list\n\t * @private\n\t */", "this", ".", "_calls", "=", "{", "client", ":", "{", "map", ":", "Object", ".", "create", "(", "null", ")", ",", "list", ":", "[", "]", "}", ",", "server", ":", "{", "map", ":", "Object", ".", "create", "(", "null", ")", ",", "list", ":", "[", "]", "}", "}", "/**\n\t * @member {Object}\n\t * @property {Object} client\n\t * @property {Object<Message>} client.map - map from message name and message id\n\t * @property {Array<Message>} client.list\n\t * @property {Object} server\n\t * @property {Object<Message>} server.map - map from message name and message id\n\t * @property {Array<Message>} server.list\n\t * @private\n\t */", "this", ".", "_messages", "=", "{", "client", ":", "{", "map", ":", "Object", ".", "create", "(", "null", ")", ",", "list", ":", "[", "]", "}", ",", "server", ":", "{", "map", ":", "Object", ".", "create", "(", "null", ")", ",", "list", ":", "[", "]", "}", "}", "}" ]
A collection of registered calls and messages. Many `peers` can be linked to a context. @class
[ "A", "collection", "of", "registered", "calls", "and", "messages", ".", "Many", "peers", "can", "be", "linked", "to", "a", "context", "." ]
4db029d1d4f0aedacf6001986ae09f04c2a44dde
https://github.com/sitegui/asynconnection-core/blob/4db029d1d4f0aedacf6001986ae09f04c2a44dde/lib/Context.js#L8-L50
54,469
flitbit/oops
examples/example-simple.js
Person
function Person(firstname, lastname, middlenames) { Person.super_.call(this); var _priv = { first: firstname || '-unknown-', last: lastname || '-unknown-', middle: middlenames || '-unknown-' }; this.defines .value('_state', {}) .property('first_name', function() { return _priv.first; }, function(first) { first = first || '-unknown-'; if (first !== _priv.first) { var change = { what: 'first_name', from: _priv.first, to: first }; _priv.first = first; this.emit('property-changed', change); } }) .property('last_name', function() { return _priv.last; }, function(last) { last = last || '-unknown-'; if (last !== _priv.last) { var change = { what: 'last_name', from: _priv.last, to: last }; _priv.last = last; this.emit('property-changed', change); } }) .property('middle_names', function() { return _priv.middle; }, function(middle) { middle = middle || '-unknown-'; if (middle !== _priv.middle) { var change = { what: 'middle_names', from: _priv.middle, to: middle }; _priv.middle = middle; this.emit('property-changed', change); } }) ; }
javascript
function Person(firstname, lastname, middlenames) { Person.super_.call(this); var _priv = { first: firstname || '-unknown-', last: lastname || '-unknown-', middle: middlenames || '-unknown-' }; this.defines .value('_state', {}) .property('first_name', function() { return _priv.first; }, function(first) { first = first || '-unknown-'; if (first !== _priv.first) { var change = { what: 'first_name', from: _priv.first, to: first }; _priv.first = first; this.emit('property-changed', change); } }) .property('last_name', function() { return _priv.last; }, function(last) { last = last || '-unknown-'; if (last !== _priv.last) { var change = { what: 'last_name', from: _priv.last, to: last }; _priv.last = last; this.emit('property-changed', change); } }) .property('middle_names', function() { return _priv.middle; }, function(middle) { middle = middle || '-unknown-'; if (middle !== _priv.middle) { var change = { what: 'middle_names', from: _priv.middle, to: middle }; _priv.middle = middle; this.emit('property-changed', change); } }) ; }
[ "function", "Person", "(", "firstname", ",", "lastname", ",", "middlenames", ")", "{", "Person", ".", "super_", ".", "call", "(", "this", ")", ";", "var", "_priv", "=", "{", "first", ":", "firstname", "||", "'-unknown-'", ",", "last", ":", "lastname", "||", "'-unknown-'", ",", "middle", ":", "middlenames", "||", "'-unknown-'", "}", ";", "this", ".", "defines", ".", "value", "(", "'_state'", ",", "{", "}", ")", ".", "property", "(", "'first_name'", ",", "function", "(", ")", "{", "return", "_priv", ".", "first", ";", "}", ",", "function", "(", "first", ")", "{", "first", "=", "first", "||", "'-unknown-'", ";", "if", "(", "first", "!==", "_priv", ".", "first", ")", "{", "var", "change", "=", "{", "what", ":", "'first_name'", ",", "from", ":", "_priv", ".", "first", ",", "to", ":", "first", "}", ";", "_priv", ".", "first", "=", "first", ";", "this", ".", "emit", "(", "'property-changed'", ",", "change", ")", ";", "}", "}", ")", ".", "property", "(", "'last_name'", ",", "function", "(", ")", "{", "return", "_priv", ".", "last", ";", "}", ",", "function", "(", "last", ")", "{", "last", "=", "last", "||", "'-unknown-'", ";", "if", "(", "last", "!==", "_priv", ".", "last", ")", "{", "var", "change", "=", "{", "what", ":", "'last_name'", ",", "from", ":", "_priv", ".", "last", ",", "to", ":", "last", "}", ";", "_priv", ".", "last", "=", "last", ";", "this", ".", "emit", "(", "'property-changed'", ",", "change", ")", ";", "}", "}", ")", ".", "property", "(", "'middle_names'", ",", "function", "(", ")", "{", "return", "_priv", ".", "middle", ";", "}", ",", "function", "(", "middle", ")", "{", "middle", "=", "middle", "||", "'-unknown-'", ";", "if", "(", "middle", "!==", "_priv", ".", "middle", ")", "{", "var", "change", "=", "{", "what", ":", "'middle_names'", ",", "from", ":", "_priv", ".", "middle", ",", "to", ":", "middle", "}", ";", "_priv", ".", "middle", "=", "middle", ";", "this", ".", "emit", "(", "'property-changed'", ",", "change", ")", ";", "}", "}", ")", ";", "}" ]
Simple observable person object
[ "Simple", "observable", "person", "object" ]
73c36d459b98d1ac9485327ab3d6bf180c78d254
https://github.com/flitbit/oops/blob/73c36d459b98d1ac9485327ab3d6bf180c78d254/examples/example-simple.js#L9-L65
54,470
flitbit/oops
examples/example-simple.js
fullnameFormatter
function fullnameFormatter( first, last, middle ) { return ''.concat(first, (last) ? ' '.concat(last) : '', (middle) ? ' '.concat(middle) : ''); }
javascript
function fullnameFormatter( first, last, middle ) { return ''.concat(first, (last) ? ' '.concat(last) : '', (middle) ? ' '.concat(middle) : ''); }
[ "function", "fullnameFormatter", "(", "first", ",", "last", ",", "middle", ")", "{", "return", "''", ".", "concat", "(", "first", ",", "(", "last", ")", "?", "' '", ".", "concat", "(", "last", ")", ":", "''", ",", "(", "middle", ")", "?", "' '", ".", "concat", "(", "middle", ")", ":", "''", ")", ";", "}" ]
The default fullname formatter.
[ "The", "default", "fullname", "formatter", "." ]
73c36d459b98d1ac9485327ab3d6bf180c78d254
https://github.com/flitbit/oops/blob/73c36d459b98d1ac9485327ab3d6bf180c78d254/examples/example-simple.js#L71-L75
54,471
patrickarlt/grunt-acetate
tasks/acetate.js
printLogHeader
function printLogHeader (e) { if (e.show && logHeader) { logHeader = false; grunt.log.header('Task "acetate:' + target + '" running'); } }
javascript
function printLogHeader (e) { if (e.show && logHeader) { logHeader = false; grunt.log.header('Task "acetate:' + target + '" running'); } }
[ "function", "printLogHeader", "(", "e", ")", "{", "if", "(", "e", ".", "show", "&&", "logHeader", ")", "{", "logHeader", "=", "false", ";", "grunt", ".", "log", ".", "header", "(", "'Task \"acetate:'", "+", "target", "+", "'\" running'", ")", ";", "}", "}" ]
whenever we log anything spit out a header cleaner output when using grunt watch
[ "whenever", "we", "log", "anything", "spit", "out", "a", "header", "cleaner", "output", "when", "using", "grunt", "watch" ]
9464869fa47bb1639311d89fb9444a85aae83689
https://github.com/patrickarlt/grunt-acetate/blob/9464869fa47bb1639311d89fb9444a85aae83689/tasks/acetate.js#L34-L39
54,472
tgolen/skelenode-dispatcher
index.js
attached
function attached(context) { if (DEBUG_DISPATCHER) log.info('ATTACHED: ' + ((!!context.dispatcher) ? 'yes' : 'no')); if (!context) { return false; } return !!context.dispatcher; }
javascript
function attached(context) { if (DEBUG_DISPATCHER) log.info('ATTACHED: ' + ((!!context.dispatcher) ? 'yes' : 'no')); if (!context) { return false; } return !!context.dispatcher; }
[ "function", "attached", "(", "context", ")", "{", "if", "(", "DEBUG_DISPATCHER", ")", "log", ".", "info", "(", "'ATTACHED: '", "+", "(", "(", "!", "!", "context", ".", "dispatcher", ")", "?", "'yes'", ":", "'no'", ")", ")", ";", "if", "(", "!", "context", ")", "{", "return", "false", ";", "}", "return", "!", "!", "context", ".", "dispatcher", ";", "}" ]
Determines whether or not the dispatcher has been attached to the specified context. @param context An object that wants to subscribe to events sent through the dispatcher. @returns {boolean} Attached or not.
[ "Determines", "whether", "or", "not", "the", "dispatcher", "has", "been", "attached", "to", "the", "specified", "context", "." ]
fb64eb7a7f3390d6316f6a5b35ae3a5bea0761f6
https://github.com/tgolen/skelenode-dispatcher/blob/fb64eb7a7f3390d6316f6a5b35ae3a5bea0761f6/index.js#L94-L100
54,473
tgolen/skelenode-dispatcher
index.js
subscribe
function subscribe(event, callback) { /*jshint validthis: true */ if (DEBUG_DISPATCHER) log.info('SUBSCRIBE: ' + event); if (!event || !callback) { return this; } if (this._callbacks[event]) { this._callbacks[event].push(callback); } else { this._callbacks[event] = [ callback ]; } this._client.subscribe(event); return this; }
javascript
function subscribe(event, callback) { /*jshint validthis: true */ if (DEBUG_DISPATCHER) log.info('SUBSCRIBE: ' + event); if (!event || !callback) { return this; } if (this._callbacks[event]) { this._callbacks[event].push(callback); } else { this._callbacks[event] = [ callback ]; } this._client.subscribe(event); return this; }
[ "function", "subscribe", "(", "event", ",", "callback", ")", "{", "/*jshint validthis: true */", "if", "(", "DEBUG_DISPATCHER", ")", "log", ".", "info", "(", "'SUBSCRIBE: '", "+", "event", ")", ";", "if", "(", "!", "event", "||", "!", "callback", ")", "{", "return", "this", ";", "}", "if", "(", "this", ".", "_callbacks", "[", "event", "]", ")", "{", "this", ".", "_callbacks", "[", "event", "]", ".", "push", "(", "callback", ")", ";", "}", "else", "{", "this", ".", "_callbacks", "[", "event", "]", "=", "[", "callback", "]", ";", "}", "this", ".", "_client", ".", "subscribe", "(", "event", ")", ";", "return", "this", ";", "}" ]
Subscribes to a particular event. Anytime this event is published to a dispatcher, on any node in the system, the callback will be executed shortly thereafter. @param event A string name for an event, such as "org_14301" to be notified whenever that org is updated. @param callback A callback to be executed when the event is published. @returns {*} The context, for fluent calls.
[ "Subscribes", "to", "a", "particular", "event", ".", "Anytime", "this", "event", "is", "published", "to", "a", "dispatcher", "on", "any", "node", "in", "the", "system", "the", "callback", "will", "be", "executed", "shortly", "thereafter", "." ]
fb64eb7a7f3390d6316f6a5b35ae3a5bea0761f6
https://github.com/tgolen/skelenode-dispatcher/blob/fb64eb7a7f3390d6316f6a5b35ae3a5bea0761f6/index.js#L109-L125
54,474
tgolen/skelenode-dispatcher
index.js
publish
function publish(event) { /*jshint validthis: true */ if (DEBUG_DISPATCHER) log.info('PUBLISH: ' + event); if (!event) { return; } redisPublisher.publish(event, ''); return this; }
javascript
function publish(event) { /*jshint validthis: true */ if (DEBUG_DISPATCHER) log.info('PUBLISH: ' + event); if (!event) { return; } redisPublisher.publish(event, ''); return this; }
[ "function", "publish", "(", "event", ")", "{", "/*jshint validthis: true */", "if", "(", "DEBUG_DISPATCHER", ")", "log", ".", "info", "(", "'PUBLISH: '", "+", "event", ")", ";", "if", "(", "!", "event", ")", "{", "return", ";", "}", "redisPublisher", ".", "publish", "(", "event", ",", "''", ")", ";", "return", "this", ";", "}" ]
Publishes an event across the cluster. All dispatchers that are listening for this event will notify their attached contexts. @param event A string name for an event, such as "org_14301" to be notified whenever that org is updated. @returns {*} The dispatcher, for fluent calls.
[ "Publishes", "an", "event", "across", "the", "cluster", ".", "All", "dispatchers", "that", "are", "listening", "for", "this", "event", "will", "notify", "their", "attached", "contexts", "." ]
fb64eb7a7f3390d6316f6a5b35ae3a5bea0761f6
https://github.com/tgolen/skelenode-dispatcher/blob/fb64eb7a7f3390d6316f6a5b35ae3a5bea0761f6/index.js#L132-L140
54,475
tgolen/skelenode-dispatcher
index.js
handleMessage
function handleMessage(event, message) { /*jshint validthis: true */ if (DEBUG_DISPATCHER) log.info('MESSAGE: ' + event); if (!event) { return; } if (message && message !== '') { throw 'A message payload was sent across Redis. We intentionally do not support this to avoid security issues.'; } var callbacks = this.dispatcher._callbacks[event]; if (DEBUG_DISPATCHER) log.info('MESSAGE: CALLBACK LENGTH: ' + (callbacks && callbacks.length)); for (var i = 0, iL = callbacks && callbacks.length; i < iL; i++) { callbacks[i].call(this.dispatcher._context, event); } }
javascript
function handleMessage(event, message) { /*jshint validthis: true */ if (DEBUG_DISPATCHER) log.info('MESSAGE: ' + event); if (!event) { return; } if (message && message !== '') { throw 'A message payload was sent across Redis. We intentionally do not support this to avoid security issues.'; } var callbacks = this.dispatcher._callbacks[event]; if (DEBUG_DISPATCHER) log.info('MESSAGE: CALLBACK LENGTH: ' + (callbacks && callbacks.length)); for (var i = 0, iL = callbacks && callbacks.length; i < iL; i++) { callbacks[i].call(this.dispatcher._context, event); } }
[ "function", "handleMessage", "(", "event", ",", "message", ")", "{", "/*jshint validthis: true */", "if", "(", "DEBUG_DISPATCHER", ")", "log", ".", "info", "(", "'MESSAGE: '", "+", "event", ")", ";", "if", "(", "!", "event", ")", "{", "return", ";", "}", "if", "(", "message", "&&", "message", "!==", "''", ")", "{", "throw", "'A message payload was sent across Redis. We intentionally do not support this to avoid security issues.'", ";", "}", "var", "callbacks", "=", "this", ".", "dispatcher", ".", "_callbacks", "[", "event", "]", ";", "if", "(", "DEBUG_DISPATCHER", ")", "log", ".", "info", "(", "'MESSAGE: CALLBACK LENGTH: '", "+", "(", "callbacks", "&&", "callbacks", ".", "length", ")", ")", ";", "for", "(", "var", "i", "=", "0", ",", "iL", "=", "callbacks", "&&", "callbacks", ".", "length", ";", "i", "<", "iL", ";", "i", "++", ")", "{", "callbacks", "[", "i", "]", ".", "call", "(", "this", ".", "dispatcher", ".", "_context", ",", "event", ")", ";", "}", "}" ]
An internal method, called when a new message is received. It loops through all callbacks for the event, and executes them. @param event The string name for an event that was passed to the "publish" call. @param message A string payload sent with the publish.
[ "An", "internal", "method", "called", "when", "a", "new", "message", "is", "received", ".", "It", "loops", "through", "all", "callbacks", "for", "the", "event", "and", "executes", "them", "." ]
fb64eb7a7f3390d6316f6a5b35ae3a5bea0761f6
https://github.com/tgolen/skelenode-dispatcher/blob/fb64eb7a7f3390d6316f6a5b35ae3a5bea0761f6/index.js#L147-L162
54,476
tgolen/skelenode-dispatcher
index.js
unsubscribe
function unsubscribe(event, callback) { /*jshint validthis: true */ if (DEBUG_DISPATCHER) log.info('UNSUBSCRIBE: ' + event); if (!event || !callback) { return; } var callbacks = this._callbacks[event]; if (callbacks) { for (var i = callbacks.length - 1; i >= 0; i--) { if (callbacks[i] === callback) { callbacks.splice(i, 1); } } } if (!callbacks || callbacks.length === 0) { this._client.unsubscribe(event); } return this; }
javascript
function unsubscribe(event, callback) { /*jshint validthis: true */ if (DEBUG_DISPATCHER) log.info('UNSUBSCRIBE: ' + event); if (!event || !callback) { return; } var callbacks = this._callbacks[event]; if (callbacks) { for (var i = callbacks.length - 1; i >= 0; i--) { if (callbacks[i] === callback) { callbacks.splice(i, 1); } } } if (!callbacks || callbacks.length === 0) { this._client.unsubscribe(event); } return this; }
[ "function", "unsubscribe", "(", "event", ",", "callback", ")", "{", "/*jshint validthis: true */", "if", "(", "DEBUG_DISPATCHER", ")", "log", ".", "info", "(", "'UNSUBSCRIBE: '", "+", "event", ")", ";", "if", "(", "!", "event", "||", "!", "callback", ")", "{", "return", ";", "}", "var", "callbacks", "=", "this", ".", "_callbacks", "[", "event", "]", ";", "if", "(", "callbacks", ")", "{", "for", "(", "var", "i", "=", "callbacks", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "callbacks", "[", "i", "]", "===", "callback", ")", "{", "callbacks", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "}", "}", "if", "(", "!", "callbacks", "||", "callbacks", ".", "length", "===", "0", ")", "{", "this", ".", "_client", ".", "unsubscribe", "(", "event", ")", ";", "}", "return", "this", ";", "}" ]
Unsubscribes from a particular event. @param event The string name passed to the "subscribe" call. @param callback The callback passed to the "subscribe" call. @returns {*} The context, for fluent calls.
[ "Unsubscribes", "from", "a", "particular", "event", "." ]
fb64eb7a7f3390d6316f6a5b35ae3a5bea0761f6
https://github.com/tgolen/skelenode-dispatcher/blob/fb64eb7a7f3390d6316f6a5b35ae3a5bea0761f6/index.js#L170-L190
54,477
tgolen/skelenode-dispatcher
index.js
detach
function detach(context) { /*jshint validthis: true */ if (DEBUG_DISPATCHER) log.info('DETACHED.'); if (!context) { return; } if (!attached(context)) { return; } context.dispatcher._client.quit(); context.dispatcher._client.dispatcher = null; context.dispatcher = null; return this; }
javascript
function detach(context) { /*jshint validthis: true */ if (DEBUG_DISPATCHER) log.info('DETACHED.'); if (!context) { return; } if (!attached(context)) { return; } context.dispatcher._client.quit(); context.dispatcher._client.dispatcher = null; context.dispatcher = null; return this; }
[ "function", "detach", "(", "context", ")", "{", "/*jshint validthis: true */", "if", "(", "DEBUG_DISPATCHER", ")", "log", ".", "info", "(", "'DETACHED.'", ")", ";", "if", "(", "!", "context", ")", "{", "return", ";", "}", "if", "(", "!", "attached", "(", "context", ")", ")", "{", "return", ";", "}", "context", ".", "dispatcher", ".", "_client", ".", "quit", "(", ")", ";", "context", ".", "dispatcher", ".", "_client", ".", "dispatcher", "=", "null", ";", "context", ".", "dispatcher", "=", "null", ";", "return", "this", ";", "}" ]
Detaches the dispatcher from a particular context, remove the "dispatcher" namespace from it and stopping all subscriptions. @param context The object passed to the "attach" call. @returns {*} The dispatcher, for fluent calls.
[ "Detaches", "the", "dispatcher", "from", "a", "particular", "context", "remove", "the", "dispatcher", "namespace", "from", "it", "and", "stopping", "all", "subscriptions", "." ]
fb64eb7a7f3390d6316f6a5b35ae3a5bea0761f6
https://github.com/tgolen/skelenode-dispatcher/blob/fb64eb7a7f3390d6316f6a5b35ae3a5bea0761f6/index.js#L197-L212
54,478
airbrite/muni
controller.js
function(query) { var result = {}; if (!_.isObject(query) || _.isEmpty(query)) { return result; } // timestamp might be in `ms` or `s` _.forEach(query, function(timestamp, operator) { if (!_.includes(['gt', 'gte', 'lt', 'lte', 'ne'], operator)) { return; } // Timestamp must be an integer timestamp = _.parseInt(timestamp); if (_.isNaN(timestamp)) { return; } // Convert seconds to milliseconds timestamp = Mixins.isUnixTime(timestamp) ? timestamp * 1000 : timestamp; result['$' + operator] = timestamp; }); debug.info( '#_buildTimestampQuery with query: %s and result: %s', JSON.stringify(query), JSON.stringify(result) ); return result; }
javascript
function(query) { var result = {}; if (!_.isObject(query) || _.isEmpty(query)) { return result; } // timestamp might be in `ms` or `s` _.forEach(query, function(timestamp, operator) { if (!_.includes(['gt', 'gte', 'lt', 'lte', 'ne'], operator)) { return; } // Timestamp must be an integer timestamp = _.parseInt(timestamp); if (_.isNaN(timestamp)) { return; } // Convert seconds to milliseconds timestamp = Mixins.isUnixTime(timestamp) ? timestamp * 1000 : timestamp; result['$' + operator] = timestamp; }); debug.info( '#_buildTimestampQuery with query: %s and result: %s', JSON.stringify(query), JSON.stringify(result) ); return result; }
[ "function", "(", "query", ")", "{", "var", "result", "=", "{", "}", ";", "if", "(", "!", "_", ".", "isObject", "(", "query", ")", "||", "_", ".", "isEmpty", "(", "query", ")", ")", "{", "return", "result", ";", "}", "// timestamp might be in `ms` or `s`", "_", ".", "forEach", "(", "query", ",", "function", "(", "timestamp", ",", "operator", ")", "{", "if", "(", "!", "_", ".", "includes", "(", "[", "'gt'", ",", "'gte'", ",", "'lt'", ",", "'lte'", ",", "'ne'", "]", ",", "operator", ")", ")", "{", "return", ";", "}", "// Timestamp must be an integer", "timestamp", "=", "_", ".", "parseInt", "(", "timestamp", ")", ";", "if", "(", "_", ".", "isNaN", "(", "timestamp", ")", ")", "{", "return", ";", "}", "// Convert seconds to milliseconds", "timestamp", "=", "Mixins", ".", "isUnixTime", "(", "timestamp", ")", "?", "timestamp", "*", "1000", ":", "timestamp", ";", "result", "[", "'$'", "+", "operator", "]", "=", "timestamp", ";", "}", ")", ";", "debug", ".", "info", "(", "'#_buildTimestampQuery with query: %s and result: %s'", ",", "JSON", ".", "stringify", "(", "query", ")", ",", "JSON", ".", "stringify", "(", "result", ")", ")", ";", "return", "result", ";", "}" ]
Converts a url query object containing time range data into a Mongo compatible query Note: - timestamps can be either milliseconds or seconds - timestamps can be strings, they will be parsed into Integers Example: { gt: 1405494000, lt: 1431327600 } Possible Keys: - `gt` Greater than - `gte` Greather than or equal - `lt` Less than - `lte` Less than or equal - `ne` Not equal @param {Object} query @return {Object}
[ "Converts", "a", "url", "query", "object", "containing", "time", "range", "data", "into", "a", "Mongo", "compatible", "query" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/controller.js#L40-L70
54,479
airbrite/muni
controller.js
function(fields, data) { if (!_.isString(fields)) { return data; } // If a field is specified as `foo.bar` or `foo.bar.baz`, // Convert it to just `foo` var map = {}; _.forEach(fields.split(','), function(field) { map[field.split('.')[0]] = 1; }); var keys = _.keys(map); if (_.isArray(data)) { data = _.map(data, function(object) { return _.pick(object, keys); }); } else if (_.isObject(data)) { data = _.pick(data, keys); } return data; }
javascript
function(fields, data) { if (!_.isString(fields)) { return data; } // If a field is specified as `foo.bar` or `foo.bar.baz`, // Convert it to just `foo` var map = {}; _.forEach(fields.split(','), function(field) { map[field.split('.')[0]] = 1; }); var keys = _.keys(map); if (_.isArray(data)) { data = _.map(data, function(object) { return _.pick(object, keys); }); } else if (_.isObject(data)) { data = _.pick(data, keys); } return data; }
[ "function", "(", "fields", ",", "data", ")", "{", "if", "(", "!", "_", ".", "isString", "(", "fields", ")", ")", "{", "return", "data", ";", "}", "// If a field is specified as `foo.bar` or `foo.bar.baz`,", "// Convert it to just `foo`", "var", "map", "=", "{", "}", ";", "_", ".", "forEach", "(", "fields", ".", "split", "(", "','", ")", ",", "function", "(", "field", ")", "{", "map", "[", "field", ".", "split", "(", "'.'", ")", "[", "0", "]", "]", "=", "1", ";", "}", ")", ";", "var", "keys", "=", "_", ".", "keys", "(", "map", ")", ";", "if", "(", "_", ".", "isArray", "(", "data", ")", ")", "{", "data", "=", "_", ".", "map", "(", "data", ",", "function", "(", "object", ")", "{", "return", "_", ".", "pick", "(", "object", ",", "keys", ")", ";", "}", ")", ";", "}", "else", "if", "(", "_", ".", "isObject", "(", "data", ")", ")", "{", "data", "=", "_", ".", "pick", "(", "data", ",", "keys", ")", ";", "}", "return", "data", ";", "}" ]
Modify `data` to only contain keys that are specified in `fields` @param {Object} fields @param {Object|Array} data @return {Object|Array}
[ "Modify", "data", "to", "only", "contain", "keys", "that", "are", "specified", "in", "fields" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/controller.js#L80-L102
54,480
airbrite/muni
controller.js
function() { // Routes this.routes = { all: {}, get: {}, post: {}, put: {}, patch: {}, delete: {} }; // Middleware(s) this.pre = []; // run before route middleware this.before = []; // run after route middleware but before route handler this.after = []; // run after route handler // Setup middleware and route handlers this.setupPreMiddleware(); this.setupBeforeMiddleware(); this.setupRoutes(); this.setupAfterMiddleware(); // Response/error handler middleware this.after.push(this.successResponse); this.after.push(this.errorResponse); this.after.push(this.finalResponse); }
javascript
function() { // Routes this.routes = { all: {}, get: {}, post: {}, put: {}, patch: {}, delete: {} }; // Middleware(s) this.pre = []; // run before route middleware this.before = []; // run after route middleware but before route handler this.after = []; // run after route handler // Setup middleware and route handlers this.setupPreMiddleware(); this.setupBeforeMiddleware(); this.setupRoutes(); this.setupAfterMiddleware(); // Response/error handler middleware this.after.push(this.successResponse); this.after.push(this.errorResponse); this.after.push(this.finalResponse); }
[ "function", "(", ")", "{", "// Routes", "this", ".", "routes", "=", "{", "all", ":", "{", "}", ",", "get", ":", "{", "}", ",", "post", ":", "{", "}", ",", "put", ":", "{", "}", ",", "patch", ":", "{", "}", ",", "delete", ":", "{", "}", "}", ";", "// Middleware(s)", "this", ".", "pre", "=", "[", "]", ";", "// run before route middleware", "this", ".", "before", "=", "[", "]", ";", "// run after route middleware but before route handler", "this", ".", "after", "=", "[", "]", ";", "// run after route handler", "// Setup middleware and route handlers", "this", ".", "setupPreMiddleware", "(", ")", ";", "this", ".", "setupBeforeMiddleware", "(", ")", ";", "this", ".", "setupRoutes", "(", ")", ";", "this", ".", "setupAfterMiddleware", "(", ")", ";", "// Response/error handler middleware", "this", ".", "after", ".", "push", "(", "this", ".", "successResponse", ")", ";", "this", ".", "after", ".", "push", "(", "this", ".", "errorResponse", ")", ";", "this", ".", "after", ".", "push", "(", "this", ".", "finalResponse", ")", ";", "}" ]
Called after the constructor
[ "Called", "after", "the", "constructor" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/controller.js#L194-L220
54,481
airbrite/muni
controller.js
function(req, res, next) { return function(modelOrCollection) { this.prepareResponse(modelOrCollection, req, res, next); }.bind(this); }
javascript
function(req, res, next) { return function(modelOrCollection) { this.prepareResponse(modelOrCollection, req, res, next); }.bind(this); }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "return", "function", "(", "modelOrCollection", ")", "{", "this", ".", "prepareResponse", "(", "modelOrCollection", ",", "req", ",", "res", ",", "next", ")", ";", "}", ".", "bind", "(", "this", ")", ";", "}" ]
Convenience middleware to render a Model or Collection DEPRECATED 2015-06-08 @return {Function} A middleware handler
[ "Convenience", "middleware", "to", "render", "a", "Model", "or", "Collection" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/controller.js#L288-L292
54,482
airbrite/muni
controller.js
function(modelOrCollection, req, res, next) { if (!modelOrCollection) { return next(); } if (modelOrCollection instanceof Model) { // Data is a Model res.data = modelOrCollection.render(); } else if (modelOrCollection instanceof Collection) { // Data is a Collection res.data = modelOrCollection.render(); } else { // Data is raw res.data = modelOrCollection; } return next(); }
javascript
function(modelOrCollection, req, res, next) { if (!modelOrCollection) { return next(); } if (modelOrCollection instanceof Model) { // Data is a Model res.data = modelOrCollection.render(); } else if (modelOrCollection instanceof Collection) { // Data is a Collection res.data = modelOrCollection.render(); } else { // Data is raw res.data = modelOrCollection; } return next(); }
[ "function", "(", "modelOrCollection", ",", "req", ",", "res", ",", "next", ")", "{", "if", "(", "!", "modelOrCollection", ")", "{", "return", "next", "(", ")", ";", "}", "if", "(", "modelOrCollection", "instanceof", "Model", ")", "{", "// Data is a Model", "res", ".", "data", "=", "modelOrCollection", ".", "render", "(", ")", ";", "}", "else", "if", "(", "modelOrCollection", "instanceof", "Collection", ")", "{", "// Data is a Collection", "res", ".", "data", "=", "modelOrCollection", ".", "render", "(", ")", ";", "}", "else", "{", "// Data is raw", "res", ".", "data", "=", "modelOrCollection", ";", "}", "return", "next", "(", ")", ";", "}" ]
Attempt to render a Model or Collection If input is not a Model or Collection, pass it thru unmodified DEPRECATED 2015-06-08 @param {*} modelOrCollection
[ "Attempt", "to", "render", "a", "Model", "or", "Collection", "If", "input", "is", "not", "a", "Model", "or", "Collection", "pass", "it", "thru", "unmodified" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/controller.js#L303-L320
54,483
airbrite/muni
controller.js
function(req, res, next) { var data = res.data || null; var code = 200; if (_.isNumber(res.code)) { code = res.code; } var envelope = { meta: { code: code }, data: data }; // Optional paging meta if (res.paging) { envelope.meta.paging = res.paging; } // Set code and data res.code = code; if (res.code !== 204) { res.data = envelope; } return next(); }
javascript
function(req, res, next) { var data = res.data || null; var code = 200; if (_.isNumber(res.code)) { code = res.code; } var envelope = { meta: { code: code }, data: data }; // Optional paging meta if (res.paging) { envelope.meta.paging = res.paging; } // Set code and data res.code = code; if (res.code !== 204) { res.data = envelope; } return next(); }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "var", "data", "=", "res", ".", "data", "||", "null", ";", "var", "code", "=", "200", ";", "if", "(", "_", ".", "isNumber", "(", "res", ".", "code", ")", ")", "{", "code", "=", "res", ".", "code", ";", "}", "var", "envelope", "=", "{", "meta", ":", "{", "code", ":", "code", "}", ",", "data", ":", "data", "}", ";", "// Optional paging meta", "if", "(", "res", ".", "paging", ")", "{", "envelope", ".", "meta", ".", "paging", "=", "res", ".", "paging", ";", "}", "// Set code and data", "res", ".", "code", "=", "code", ";", "if", "(", "res", ".", "code", "!==", "204", ")", "{", "res", ".", "data", "=", "envelope", ";", "}", "return", "next", "(", ")", ";", "}" ]
Default middleware for handling successful responses
[ "Default", "middleware", "for", "handling", "successful", "responses" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/controller.js#L326-L351
54,484
airbrite/muni
controller.js
function(err, req, res, next) { err.message = err.message || 'Internal Server Error'; err.code = err.code || res.code || 500; if (!_.isNumber(err.code)) { err.code = 500; } try { err.line = err.stack.split('\n')[1].match(/\(.+\)/)[0]; } catch (e) { err.line = null; } var envelope = { meta: { code: err.code, error: { code: err.code, message: err.message, line: err.line } }, data: err.message }; // Set code and data res.code = err.code; res.data = envelope; return next(); }
javascript
function(err, req, res, next) { err.message = err.message || 'Internal Server Error'; err.code = err.code || res.code || 500; if (!_.isNumber(err.code)) { err.code = 500; } try { err.line = err.stack.split('\n')[1].match(/\(.+\)/)[0]; } catch (e) { err.line = null; } var envelope = { meta: { code: err.code, error: { code: err.code, message: err.message, line: err.line } }, data: err.message }; // Set code and data res.code = err.code; res.data = envelope; return next(); }
[ "function", "(", "err", ",", "req", ",", "res", ",", "next", ")", "{", "err", ".", "message", "=", "err", ".", "message", "||", "'Internal Server Error'", ";", "err", ".", "code", "=", "err", ".", "code", "||", "res", ".", "code", "||", "500", ";", "if", "(", "!", "_", ".", "isNumber", "(", "err", ".", "code", ")", ")", "{", "err", ".", "code", "=", "500", ";", "}", "try", "{", "err", ".", "line", "=", "err", ".", "stack", ".", "split", "(", "'\\n'", ")", "[", "1", "]", ".", "match", "(", "/", "\\(.+\\)", "/", ")", "[", "0", "]", ";", "}", "catch", "(", "e", ")", "{", "err", ".", "line", "=", "null", ";", "}", "var", "envelope", "=", "{", "meta", ":", "{", "code", ":", "err", ".", "code", ",", "error", ":", "{", "code", ":", "err", ".", "code", ",", "message", ":", "err", ".", "message", ",", "line", ":", "err", ".", "line", "}", "}", ",", "data", ":", "err", ".", "message", "}", ";", "// Set code and data", "res", ".", "code", "=", "err", ".", "code", ";", "res", ".", "data", "=", "envelope", ";", "return", "next", "(", ")", ";", "}" ]
Default middleware for handling error responses
[ "Default", "middleware", "for", "handling", "error", "responses" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/controller.js#L357-L387
54,485
airbrite/muni
controller.js
function(req, res, next) { // If we timed out before managing to respond, don't send the response if (res.headersSent) { return; } // Look for `.json` or `.xml` extension in path // And override request accept header if (/.json$/.test(req.path)) { req.headers.accept = 'application/json'; } else if (/.xml$/.test(req.path)) { req.headers.accept = 'application/xml'; } // Use request accept header to determine response content-type res.format({ json: function() { res.status(res.code).jsonp(res.data); }, xml: function() { var xml; try { var xmlData = JSON.parse(JSON.stringify(res.data)); xml = this.xmlBuilder.buildObject(xmlData); res.set('Content-Type', 'application/xml; charset=utf-8'); res.status(res.code).send(xml); } catch (e) { res.status(500).end(); } }.bind(this) }); }
javascript
function(req, res, next) { // If we timed out before managing to respond, don't send the response if (res.headersSent) { return; } // Look for `.json` or `.xml` extension in path // And override request accept header if (/.json$/.test(req.path)) { req.headers.accept = 'application/json'; } else if (/.xml$/.test(req.path)) { req.headers.accept = 'application/xml'; } // Use request accept header to determine response content-type res.format({ json: function() { res.status(res.code).jsonp(res.data); }, xml: function() { var xml; try { var xmlData = JSON.parse(JSON.stringify(res.data)); xml = this.xmlBuilder.buildObject(xmlData); res.set('Content-Type', 'application/xml; charset=utf-8'); res.status(res.code).send(xml); } catch (e) { res.status(500).end(); } }.bind(this) }); }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "// If we timed out before managing to respond, don't send the response", "if", "(", "res", ".", "headersSent", ")", "{", "return", ";", "}", "// Look for `.json` or `.xml` extension in path", "// And override request accept header", "if", "(", "/", ".json$", "/", ".", "test", "(", "req", ".", "path", ")", ")", "{", "req", ".", "headers", ".", "accept", "=", "'application/json'", ";", "}", "else", "if", "(", "/", ".xml$", "/", ".", "test", "(", "req", ".", "path", ")", ")", "{", "req", ".", "headers", ".", "accept", "=", "'application/xml'", ";", "}", "// Use request accept header to determine response content-type", "res", ".", "format", "(", "{", "json", ":", "function", "(", ")", "{", "res", ".", "status", "(", "res", ".", "code", ")", ".", "jsonp", "(", "res", ".", "data", ")", ";", "}", ",", "xml", ":", "function", "(", ")", "{", "var", "xml", ";", "try", "{", "var", "xmlData", "=", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "res", ".", "data", ")", ")", ";", "xml", "=", "this", ".", "xmlBuilder", ".", "buildObject", "(", "xmlData", ")", ";", "res", ".", "set", "(", "'Content-Type'", ",", "'application/xml; charset=utf-8'", ")", ";", "res", ".", "status", "(", "res", ".", "code", ")", ".", "send", "(", "xml", ")", ";", "}", "catch", "(", "e", ")", "{", "res", ".", "status", "(", "500", ")", ".", "end", "(", ")", ";", "}", "}", ".", "bind", "(", "this", ")", "}", ")", ";", "}" ]
Final middleware for handling all responses Server actually responds and terminates to the request here
[ "Final", "middleware", "for", "handling", "all", "responses", "Server", "actually", "responds", "and", "terminates", "to", "the", "request", "here" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/controller.js#L394-L425
54,486
airbrite/muni
controller.js
function(req) { var fields = {}; // Fields if (_.isString(req.query.fields)) { _.forEach(req.query.fields.split(','), function(field) { fields[field] = 1; }); } return fields; }
javascript
function(req) { var fields = {}; // Fields if (_.isString(req.query.fields)) { _.forEach(req.query.fields.split(','), function(field) { fields[field] = 1; }); } return fields; }
[ "function", "(", "req", ")", "{", "var", "fields", "=", "{", "}", ";", "// Fields", "if", "(", "_", ".", "isString", "(", "req", ".", "query", ".", "fields", ")", ")", "{", "_", ".", "forEach", "(", "req", ".", "query", ".", "fields", ".", "split", "(", "','", ")", ",", "function", "(", "field", ")", "{", "fields", "[", "field", "]", "=", "1", ";", "}", ")", ";", "}", "return", "fields", ";", "}" ]
Parses the request query string for `fields` Converse it into a Mongo friendly `fields` Object Example: `?fields=hello,world,foo.bar` @param {Object} req @return {Object}
[ "Parses", "the", "request", "query", "string", "for", "fields" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/controller.js#L438-L449
54,487
silverlight513/pengwyn-router
src/index.js
Link
function Link(props) { // Handle clicks of the link const onClick = e => { e.preventDefault(); routeTo(path); }; // If link is for a new tab if(props.openIn === 'new') { return ( <a href={props.to} target="_blank" rel="noopener noreferrer"> {props.children} </a> ); } return ( <a href={props.to} onClick={onClick}> {props.children} </a> ); }
javascript
function Link(props) { // Handle clicks of the link const onClick = e => { e.preventDefault(); routeTo(path); }; // If link is for a new tab if(props.openIn === 'new') { return ( <a href={props.to} target="_blank" rel="noopener noreferrer"> {props.children} </a> ); } return ( <a href={props.to} onClick={onClick}> {props.children} </a> ); }
[ "function", "Link", "(", "props", ")", "{", "// Handle clicks of the link", "const", "onClick", "=", "e", "=>", "{", "e", ".", "preventDefault", "(", ")", ";", "routeTo", "(", "path", ")", ";", "}", ";", "// If link is for a new tab", "if", "(", "props", ".", "openIn", "===", "'new'", ")", "{", "return", "(", "<", "a", "href", "=", "{", "props", ".", "to", "}", "target", "=", "\"_blank\"", "rel", "=", "\"noopener noreferrer\"", ">", "\n ", "{", "props", ".", "children", "}", "\n ", "<", "/", "a", ">", ")", ";", "}", "return", "(", "<", "a", "href", "=", "{", "props", ".", "to", "}", "onClick", "=", "{", "onClick", "}", ">", "\n ", "{", "props", ".", "children", "}", "\n ", "<", "/", "a", ">", ")", ";", "}" ]
Create the Link component
[ "Create", "the", "Link", "component" ]
aeea05f44ba93e0939ef279946000002d0147241
https://github.com/silverlight513/pengwyn-router/blob/aeea05f44ba93e0939ef279946000002d0147241/src/index.js#L36-L58
54,488
silverlight513/pengwyn-router
src/index.js
getQuery
function getQuery(path = '') { const query = {}; // Check if the path even has a query first if(!path.includes('?')) { return query; } const queryString = path.split('?')[1]; // Check if the query string has any values if(!queryString.includes('=')) { return query; } const values = queryString.split('&'); // Loop over the query string values and add to the query object for (let i = values.length - 1; i >= 0; i--) { // Check that the current query string section has a value if(!values[i].includes('=')) { continue; } // Get the key and value to add to the query object const [ key, value ] = values[i].split('='); query[key] = value; } return query; }
javascript
function getQuery(path = '') { const query = {}; // Check if the path even has a query first if(!path.includes('?')) { return query; } const queryString = path.split('?')[1]; // Check if the query string has any values if(!queryString.includes('=')) { return query; } const values = queryString.split('&'); // Loop over the query string values and add to the query object for (let i = values.length - 1; i >= 0; i--) { // Check that the current query string section has a value if(!values[i].includes('=')) { continue; } // Get the key and value to add to the query object const [ key, value ] = values[i].split('='); query[key] = value; } return query; }
[ "function", "getQuery", "(", "path", "=", "''", ")", "{", "const", "query", "=", "{", "}", ";", "// Check if the path even has a query first", "if", "(", "!", "path", ".", "includes", "(", "'?'", ")", ")", "{", "return", "query", ";", "}", "const", "queryString", "=", "path", ".", "split", "(", "'?'", ")", "[", "1", "]", ";", "// Check if the query string has any values", "if", "(", "!", "queryString", ".", "includes", "(", "'='", ")", ")", "{", "return", "query", ";", "}", "const", "values", "=", "queryString", ".", "split", "(", "'&'", ")", ";", "// Loop over the query string values and add to the query object", "for", "(", "let", "i", "=", "values", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "// Check that the current query string section has a value", "if", "(", "!", "values", "[", "i", "]", ".", "includes", "(", "'='", ")", ")", "{", "continue", ";", "}", "// Get the key and value to add to the query object", "const", "[", "key", ",", "value", "]", "=", "values", "[", "i", "]", ".", "split", "(", "'='", ")", ";", "query", "[", "key", "]", "=", "value", ";", "}", "return", "query", ";", "}" ]
Function to get the query object from a given path
[ "Function", "to", "get", "the", "query", "object", "from", "a", "given", "path" ]
aeea05f44ba93e0939ef279946000002d0147241
https://github.com/silverlight513/pengwyn-router/blob/aeea05f44ba93e0939ef279946000002d0147241/src/index.js#L63-L95
54,489
silverlight513/pengwyn-router
src/index.js
normalizePath
function normalizePath(path = '') { // Remove the trailing slash if one has been given if(path.length > 1 && path.endsWith('/')) { path = path.slice(0, -1); } // Remove the first slash if(path.startsWith('/')) { path = path.slice(1); } // Remove the query if it exists if(path.includes('?')) { path = path.split('?')[0]; } // Decode the url path = decodeURIComponent(path); return path; }
javascript
function normalizePath(path = '') { // Remove the trailing slash if one has been given if(path.length > 1 && path.endsWith('/')) { path = path.slice(0, -1); } // Remove the first slash if(path.startsWith('/')) { path = path.slice(1); } // Remove the query if it exists if(path.includes('?')) { path = path.split('?')[0]; } // Decode the url path = decodeURIComponent(path); return path; }
[ "function", "normalizePath", "(", "path", "=", "''", ")", "{", "// Remove the trailing slash if one has been given", "if", "(", "path", ".", "length", ">", "1", "&&", "path", ".", "endsWith", "(", "'/'", ")", ")", "{", "path", "=", "path", ".", "slice", "(", "0", ",", "-", "1", ")", ";", "}", "// Remove the first slash", "if", "(", "path", ".", "startsWith", "(", "'/'", ")", ")", "{", "path", "=", "path", ".", "slice", "(", "1", ")", ";", "}", "// Remove the query if it exists", "if", "(", "path", ".", "includes", "(", "'?'", ")", ")", "{", "path", "=", "path", ".", "split", "(", "'?'", ")", "[", "0", "]", ";", "}", "// Decode the url", "path", "=", "decodeURIComponent", "(", "path", ")", ";", "return", "path", ";", "}" ]
Function that normalizes a path string
[ "Function", "that", "normalizes", "a", "path", "string" ]
aeea05f44ba93e0939ef279946000002d0147241
https://github.com/silverlight513/pengwyn-router/blob/aeea05f44ba93e0939ef279946000002d0147241/src/index.js#L100-L121
54,490
silverlight513/pengwyn-router
src/index.js
match
function match(routes, path) { // Get the query object before it gets stripped by the normalizer const query = getQuery(path); const pathname = path; // Normalize the path path = normalizePath(path); // Loop over each route to find the match for (let i = 0; i < routes.length; i++) { // Normalize the current route const currentRoute = normalizePath(routes[i].route); // Create the params object const params = {}; // Check if it's a straight match first if(currentRoute === path) { return Object.assign({}, routes[i], {params, query, pathname, path}); } // If there are no dynamic/optional/match-all parts then this route cannot match if(!isDynamicRoute.test(routes[i].route)) { continue; } // Split up the route by it's slashes so that we may match by section const routeSections = currentRoute.split('/'); const pathSections = path.split('/'); // Loop over each section looking for a full match for (let j = routeSections.length - 1; j >= 0; j--) { // If the route is to match everything, then return if(j === 0 && routeSections[j] === '*') { return Object.assign({}, routes[i], {params, query, pathname, path}); } // If this section is optional if(optionalSectionRegex.test(routeSections[j])) { const currentSection = routeSections[j].replace(removeOptionalRegex, ''); // If it's a param, add it to the params if(paramRegex.test(currentSection)) { params[currentSection.replace(paramRegex, '')] = pathSections[j]; continue; } // If it's a star then skip to next if(currentSection === '*') { continue; } // If the optional section can possible be missing skip to next section if(routeSections.length === pathSections.length + 1) { continue; } // If the path and route sections have same number of sections and this does match, skip to next if(routeSections.length === pathSections.length && currentSection === pathSections[j]) { continue; } // Reject this route as the possible match to the path break; } // If it's a param, add it to the params if(paramRegex.test(routeSections[j])) { params[routeSections[j].replace(paramRegex, '')] = pathSections[j]; if(j === 0) { return Object.assign({}, routes[i], {params, query, pathname, path}); } continue; } // If it's a star then skip to next if(routeSections[j] === '*') { continue; } // If this doesn't match then go to next route if(routeSections[j] !== pathSections[j]) { break; } // If the last item matches strictly then return that match if(j === 0 && routeSections[j] === pathSections[j]) { return Object.assign({}, routes[i], {params, query, pathname, path}); } } } // No match found return {path: '', params: {}, query}; }
javascript
function match(routes, path) { // Get the query object before it gets stripped by the normalizer const query = getQuery(path); const pathname = path; // Normalize the path path = normalizePath(path); // Loop over each route to find the match for (let i = 0; i < routes.length; i++) { // Normalize the current route const currentRoute = normalizePath(routes[i].route); // Create the params object const params = {}; // Check if it's a straight match first if(currentRoute === path) { return Object.assign({}, routes[i], {params, query, pathname, path}); } // If there are no dynamic/optional/match-all parts then this route cannot match if(!isDynamicRoute.test(routes[i].route)) { continue; } // Split up the route by it's slashes so that we may match by section const routeSections = currentRoute.split('/'); const pathSections = path.split('/'); // Loop over each section looking for a full match for (let j = routeSections.length - 1; j >= 0; j--) { // If the route is to match everything, then return if(j === 0 && routeSections[j] === '*') { return Object.assign({}, routes[i], {params, query, pathname, path}); } // If this section is optional if(optionalSectionRegex.test(routeSections[j])) { const currentSection = routeSections[j].replace(removeOptionalRegex, ''); // If it's a param, add it to the params if(paramRegex.test(currentSection)) { params[currentSection.replace(paramRegex, '')] = pathSections[j]; continue; } // If it's a star then skip to next if(currentSection === '*') { continue; } // If the optional section can possible be missing skip to next section if(routeSections.length === pathSections.length + 1) { continue; } // If the path and route sections have same number of sections and this does match, skip to next if(routeSections.length === pathSections.length && currentSection === pathSections[j]) { continue; } // Reject this route as the possible match to the path break; } // If it's a param, add it to the params if(paramRegex.test(routeSections[j])) { params[routeSections[j].replace(paramRegex, '')] = pathSections[j]; if(j === 0) { return Object.assign({}, routes[i], {params, query, pathname, path}); } continue; } // If it's a star then skip to next if(routeSections[j] === '*') { continue; } // If this doesn't match then go to next route if(routeSections[j] !== pathSections[j]) { break; } // If the last item matches strictly then return that match if(j === 0 && routeSections[j] === pathSections[j]) { return Object.assign({}, routes[i], {params, query, pathname, path}); } } } // No match found return {path: '', params: {}, query}; }
[ "function", "match", "(", "routes", ",", "path", ")", "{", "// Get the query object before it gets stripped by the normalizer", "const", "query", "=", "getQuery", "(", "path", ")", ";", "const", "pathname", "=", "path", ";", "// Normalize the path", "path", "=", "normalizePath", "(", "path", ")", ";", "// Loop over each route to find the match", "for", "(", "let", "i", "=", "0", ";", "i", "<", "routes", ".", "length", ";", "i", "++", ")", "{", "// Normalize the current route", "const", "currentRoute", "=", "normalizePath", "(", "routes", "[", "i", "]", ".", "route", ")", ";", "// Create the params object", "const", "params", "=", "{", "}", ";", "// Check if it's a straight match first", "if", "(", "currentRoute", "===", "path", ")", "{", "return", "Object", ".", "assign", "(", "{", "}", ",", "routes", "[", "i", "]", ",", "{", "params", ",", "query", ",", "pathname", ",", "path", "}", ")", ";", "}", "// If there are no dynamic/optional/match-all parts then this route cannot match", "if", "(", "!", "isDynamicRoute", ".", "test", "(", "routes", "[", "i", "]", ".", "route", ")", ")", "{", "continue", ";", "}", "// Split up the route by it's slashes so that we may match by section", "const", "routeSections", "=", "currentRoute", ".", "split", "(", "'/'", ")", ";", "const", "pathSections", "=", "path", ".", "split", "(", "'/'", ")", ";", "// Loop over each section looking for a full match", "for", "(", "let", "j", "=", "routeSections", ".", "length", "-", "1", ";", "j", ">=", "0", ";", "j", "--", ")", "{", "// If the route is to match everything, then return", "if", "(", "j", "===", "0", "&&", "routeSections", "[", "j", "]", "===", "'*'", ")", "{", "return", "Object", ".", "assign", "(", "{", "}", ",", "routes", "[", "i", "]", ",", "{", "params", ",", "query", ",", "pathname", ",", "path", "}", ")", ";", "}", "// If this section is optional", "if", "(", "optionalSectionRegex", ".", "test", "(", "routeSections", "[", "j", "]", ")", ")", "{", "const", "currentSection", "=", "routeSections", "[", "j", "]", ".", "replace", "(", "removeOptionalRegex", ",", "''", ")", ";", "// If it's a param, add it to the params", "if", "(", "paramRegex", ".", "test", "(", "currentSection", ")", ")", "{", "params", "[", "currentSection", ".", "replace", "(", "paramRegex", ",", "''", ")", "]", "=", "pathSections", "[", "j", "]", ";", "continue", ";", "}", "// If it's a star then skip to next", "if", "(", "currentSection", "===", "'*'", ")", "{", "continue", ";", "}", "// If the optional section can possible be missing skip to next section", "if", "(", "routeSections", ".", "length", "===", "pathSections", ".", "length", "+", "1", ")", "{", "continue", ";", "}", "// If the path and route sections have same number of sections and this does match, skip to next", "if", "(", "routeSections", ".", "length", "===", "pathSections", ".", "length", "&&", "currentSection", "===", "pathSections", "[", "j", "]", ")", "{", "continue", ";", "}", "// Reject this route as the possible match to the path", "break", ";", "}", "// If it's a param, add it to the params", "if", "(", "paramRegex", ".", "test", "(", "routeSections", "[", "j", "]", ")", ")", "{", "params", "[", "routeSections", "[", "j", "]", ".", "replace", "(", "paramRegex", ",", "''", ")", "]", "=", "pathSections", "[", "j", "]", ";", "if", "(", "j", "===", "0", ")", "{", "return", "Object", ".", "assign", "(", "{", "}", ",", "routes", "[", "i", "]", ",", "{", "params", ",", "query", ",", "pathname", ",", "path", "}", ")", ";", "}", "continue", ";", "}", "// If it's a star then skip to next", "if", "(", "routeSections", "[", "j", "]", "===", "'*'", ")", "{", "continue", ";", "}", "// If this doesn't match then go to next route", "if", "(", "routeSections", "[", "j", "]", "!==", "pathSections", "[", "j", "]", ")", "{", "break", ";", "}", "// If the last item matches strictly then return that match", "if", "(", "j", "===", "0", "&&", "routeSections", "[", "j", "]", "===", "pathSections", "[", "j", "]", ")", "{", "return", "Object", ".", "assign", "(", "{", "}", ",", "routes", "[", "i", "]", ",", "{", "params", ",", "query", ",", "pathname", ",", "path", "}", ")", ";", "}", "}", "}", "// No match found", "return", "{", "path", ":", "''", ",", "params", ":", "{", "}", ",", "query", "}", ";", "}" ]
Function to determine what route matches the current path
[ "Function", "to", "determine", "what", "route", "matches", "the", "current", "path" ]
aeea05f44ba93e0939ef279946000002d0147241
https://github.com/silverlight513/pengwyn-router/blob/aeea05f44ba93e0939ef279946000002d0147241/src/index.js#L126-L226
54,491
danigb/music-gamut
operations.js
distances
function distances (tonic, gamut) { if (!tonic) { if (!gamut[0]) return [] tonic = gamut[0] } tonic = op.setDefaultOctave(0, tonic) return gamut.map(function (p) { return p ? op.subtract(tonic, op.setDefaultOctave(0, p)) : null }) }
javascript
function distances (tonic, gamut) { if (!tonic) { if (!gamut[0]) return [] tonic = gamut[0] } tonic = op.setDefaultOctave(0, tonic) return gamut.map(function (p) { return p ? op.subtract(tonic, op.setDefaultOctave(0, p)) : null }) }
[ "function", "distances", "(", "tonic", ",", "gamut", ")", "{", "if", "(", "!", "tonic", ")", "{", "if", "(", "!", "gamut", "[", "0", "]", ")", "return", "[", "]", "tonic", "=", "gamut", "[", "0", "]", "}", "tonic", "=", "op", ".", "setDefaultOctave", "(", "0", ",", "tonic", ")", "return", "gamut", ".", "map", "(", "function", "(", "p", ")", "{", "return", "p", "?", "op", ".", "subtract", "(", "tonic", ",", "op", ".", "setDefaultOctave", "(", "0", ",", "p", ")", ")", ":", "null", "}", ")", "}" ]
get distances from tonic to the rest of the notes
[ "get", "distances", "from", "tonic", "to", "the", "rest", "of", "the", "notes" ]
a59779316a2d68abc7aabbac21fbc00ef2941608
https://github.com/danigb/music-gamut/blob/a59779316a2d68abc7aabbac21fbc00ef2941608/operations.js#L22-L31
54,492
danigb/music-gamut
operations.js
uniq
function uniq (gamut) { var semitones = heights(gamut) return gamut.reduce(function (uniq, current, currentIndex) { if (current) { var index = semitones.indexOf(semitones[currentIndex]) if (index === currentIndex) uniq.push(current) } return uniq }, []) }
javascript
function uniq (gamut) { var semitones = heights(gamut) return gamut.reduce(function (uniq, current, currentIndex) { if (current) { var index = semitones.indexOf(semitones[currentIndex]) if (index === currentIndex) uniq.push(current) } return uniq }, []) }
[ "function", "uniq", "(", "gamut", ")", "{", "var", "semitones", "=", "heights", "(", "gamut", ")", "return", "gamut", ".", "reduce", "(", "function", "(", "uniq", ",", "current", ",", "currentIndex", ")", "{", "if", "(", "current", ")", "{", "var", "index", "=", "semitones", ".", "indexOf", "(", "semitones", "[", "currentIndex", "]", ")", "if", "(", "index", "===", "currentIndex", ")", "uniq", ".", "push", "(", "current", ")", "}", "return", "uniq", "}", ",", "[", "]", ")", "}" ]
remove duplicated notes AND nulls
[ "remove", "duplicated", "notes", "AND", "nulls" ]
a59779316a2d68abc7aabbac21fbc00ef2941608
https://github.com/danigb/music-gamut/blob/a59779316a2d68abc7aabbac21fbc00ef2941608/operations.js#L34-L43
54,493
raincatcher-beta/raincatcher-sync
lib/client/data-manager.js
getItemId
function getItemId(_existingItem) { if (_.has(_existingItem, 'id')) { itemToUpdate.id = _existingItem.id; return String(_existingItem.id); } else { return itemToUpdate._localuid; } }
javascript
function getItemId(_existingItem) { if (_.has(_existingItem, 'id')) { itemToUpdate.id = _existingItem.id; return String(_existingItem.id); } else { return itemToUpdate._localuid; } }
[ "function", "getItemId", "(", "_existingItem", ")", "{", "if", "(", "_", ".", "has", "(", "_existingItem", ",", "'id'", ")", ")", "{", "itemToUpdate", ".", "id", "=", "_existingItem", ".", "id", ";", "return", "String", "(", "_existingItem", ".", "id", ")", ";", "}", "else", "{", "return", "itemToUpdate", ".", "_localuid", ";", "}", "}" ]
Getting the unique ID of the item. If the existingItem has an ID assigned, then assign this to the item to update. The reason for this is that the "id" field of the record is assigned in the remote store. We must be able to relate the item saved locally (Using the _localuid field) to the remote identifier field (id) @param _existingItem @returns {*}
[ "Getting", "the", "unique", "ID", "of", "the", "item", "." ]
a51eeb8fdea30a6afdcd0587019bd1148bf30468
https://github.com/raincatcher-beta/raincatcher-sync/blob/a51eeb8fdea30a6afdcd0587019bd1148bf30468/lib/client/data-manager.js#L317-L324
54,494
shinuza/captain-core
lib/util/crypto.js
encode
function encode(password, cb) { var secret_key = conf.secret_key , iterations = conf.pbkdf2_iterations , keylen = conf.pbkdf2_keylen; crypto.pbkdf2(password, secret_key, iterations, keylen, function(err, derivedKey) { var str; if(err) { cb(err); } else { str = new Buffer(derivedKey).toString('base64'); cb(null, str); } }); }
javascript
function encode(password, cb) { var secret_key = conf.secret_key , iterations = conf.pbkdf2_iterations , keylen = conf.pbkdf2_keylen; crypto.pbkdf2(password, secret_key, iterations, keylen, function(err, derivedKey) { var str; if(err) { cb(err); } else { str = new Buffer(derivedKey).toString('base64'); cb(null, str); } }); }
[ "function", "encode", "(", "password", ",", "cb", ")", "{", "var", "secret_key", "=", "conf", ".", "secret_key", ",", "iterations", "=", "conf", ".", "pbkdf2_iterations", ",", "keylen", "=", "conf", ".", "pbkdf2_keylen", ";", "crypto", ".", "pbkdf2", "(", "password", ",", "secret_key", ",", "iterations", ",", "keylen", ",", "function", "(", "err", ",", "derivedKey", ")", "{", "var", "str", ";", "if", "(", "err", ")", "{", "cb", "(", "err", ")", ";", "}", "else", "{", "str", "=", "new", "Buffer", "(", "derivedKey", ")", ".", "toString", "(", "'base64'", ")", ";", "cb", "(", "null", ",", "str", ")", ";", "}", "}", ")", ";", "}" ]
Passes an encoded version of `password` to `cb` or and error @param password @param cb
[ "Passes", "an", "encoded", "version", "of", "password", "to", "cb", "or", "and", "error" ]
02f3a404cdfca608e8726bbacc33e32fec484b21
https://github.com/shinuza/captain-core/blob/02f3a404cdfca608e8726bbacc33e32fec484b21/lib/util/crypto.js#L20-L35
54,495
justinhelmer/vinyl-tasks
lib/pipeline.js
chain
function chain(tasks) { return function() { var pipeline = fullPipeline(); _.each(tasks, function(task) { pipeline = pipeline.pipe(task.callback(options)()); }); return pipeline; }; }
javascript
function chain(tasks) { return function() { var pipeline = fullPipeline(); _.each(tasks, function(task) { pipeline = pipeline.pipe(task.callback(options)()); }); return pipeline; }; }
[ "function", "chain", "(", "tasks", ")", "{", "return", "function", "(", ")", "{", "var", "pipeline", "=", "fullPipeline", "(", ")", ";", "_", ".", "each", "(", "tasks", ",", "function", "(", "task", ")", "{", "pipeline", "=", "pipeline", ".", "pipe", "(", "task", ".", "callback", "(", "options", ")", "(", ")", ")", ";", "}", ")", ";", "return", "pipeline", ";", "}", ";", "}" ]
Create the pipeline chain for the provided tasks. @name chain @param {Array} tasks - The list of task objects to chain callbacks. @return {Function} - A function that when invoked, runs the entire pipeline and returns the vinyl stream.
[ "Create", "the", "pipeline", "chain", "for", "the", "provided", "tasks", "." ]
eca1f79065a3653023896c4f546dc44dbac81e62
https://github.com/justinhelmer/vinyl-tasks/blob/eca1f79065a3653023896c4f546dc44dbac81e62/lib/pipeline.js#L72-L82
54,496
danmasta/env
lib/util.js
parse
function parse(str) { let res = {}; str.split(constants.REGEX.newline).map(line => { line = line.trim(); // ignore empty lines and comments if (!line || line[0] === '#') { return; } // replace variables that are not escaped line = line.replace(constants.REGEX.args, (match, $1, $2) => { let key = $1 !== undefined ? $1 : $2; if (match.slice(0, 2) === '\\\\') { return match.slice(2); } return process.env[key] !== undefined ? process.env[key] : res[key]; }); // find the line split index based on the first occurence of = sign let index = line.indexOf('=') > -1 ? line.indexOf('=') : line.length; // get key/val and trim whitespace let key = line.slice(0, index).trim(); let val = line.slice(index +1).trim(); val = parseComment(val).replace(constants.REGEX.quotes, ''); res[key] = unescape(val); }); return res; }
javascript
function parse(str) { let res = {}; str.split(constants.REGEX.newline).map(line => { line = line.trim(); // ignore empty lines and comments if (!line || line[0] === '#') { return; } // replace variables that are not escaped line = line.replace(constants.REGEX.args, (match, $1, $2) => { let key = $1 !== undefined ? $1 : $2; if (match.slice(0, 2) === '\\\\') { return match.slice(2); } return process.env[key] !== undefined ? process.env[key] : res[key]; }); // find the line split index based on the first occurence of = sign let index = line.indexOf('=') > -1 ? line.indexOf('=') : line.length; // get key/val and trim whitespace let key = line.slice(0, index).trim(); let val = line.slice(index +1).trim(); val = parseComment(val).replace(constants.REGEX.quotes, ''); res[key] = unescape(val); }); return res; }
[ "function", "parse", "(", "str", ")", "{", "let", "res", "=", "{", "}", ";", "str", ".", "split", "(", "constants", ".", "REGEX", ".", "newline", ")", ".", "map", "(", "line", "=>", "{", "line", "=", "line", ".", "trim", "(", ")", ";", "// ignore empty lines and comments", "if", "(", "!", "line", "||", "line", "[", "0", "]", "===", "'#'", ")", "{", "return", ";", "}", "// replace variables that are not escaped", "line", "=", "line", ".", "replace", "(", "constants", ".", "REGEX", ".", "args", ",", "(", "match", ",", "$1", ",", "$2", ")", "=>", "{", "let", "key", "=", "$1", "!==", "undefined", "?", "$1", ":", "$2", ";", "if", "(", "match", ".", "slice", "(", "0", ",", "2", ")", "===", "'\\\\\\\\'", ")", "{", "return", "match", ".", "slice", "(", "2", ")", ";", "}", "return", "process", ".", "env", "[", "key", "]", "!==", "undefined", "?", "process", ".", "env", "[", "key", "]", ":", "res", "[", "key", "]", ";", "}", ")", ";", "// find the line split index based on the first occurence of = sign", "let", "index", "=", "line", ".", "indexOf", "(", "'='", ")", ">", "-", "1", "?", "line", ".", "indexOf", "(", "'='", ")", ":", "line", ".", "length", ";", "// get key/val and trim whitespace", "let", "key", "=", "line", ".", "slice", "(", "0", ",", "index", ")", ".", "trim", "(", ")", ";", "let", "val", "=", "line", ".", "slice", "(", "index", "+", "1", ")", ".", "trim", "(", ")", ";", "val", "=", "parseComment", "(", "val", ")", ".", "replace", "(", "constants", ".", "REGEX", ".", "quotes", ",", "''", ")", ";", "res", "[", "key", "]", "=", "unescape", "(", "val", ")", ";", "}", ")", ";", "return", "res", ";", "}" ]
parse a string and return an env object
[ "parse", "a", "string", "and", "return", "an", "env", "object" ]
cd6df18f4f837797d47cd96bcfb125c0264685a7
https://github.com/danmasta/env/blob/cd6df18f4f837797d47cd96bcfb125c0264685a7/lib/util.js#L55-L96
54,497
mgesmundo/port-manager
lib/port-finder.js
checkPort
function checkPort(port, cb) { var server = new net.Server(); server.on('error', function (err) { server.removeAllListeners(); cb(err); }); server.listen(port, function () { server.on('close', function () { server.removeAllListeners(); cb(null, port); }); server.close(); }); }
javascript
function checkPort(port, cb) { var server = new net.Server(); server.on('error', function (err) { server.removeAllListeners(); cb(err); }); server.listen(port, function () { server.on('close', function () { server.removeAllListeners(); cb(null, port); }); server.close(); }); }
[ "function", "checkPort", "(", "port", ",", "cb", ")", "{", "var", "server", "=", "new", "net", ".", "Server", "(", ")", ";", "server", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "server", ".", "removeAllListeners", "(", ")", ";", "cb", "(", "err", ")", ";", "}", ")", ";", "server", ".", "listen", "(", "port", ",", "function", "(", ")", "{", "server", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "server", ".", "removeAllListeners", "(", ")", ";", "cb", "(", "null", ",", "port", ")", ";", "}", ")", ";", "server", ".", "close", "(", ")", ";", "}", ")", ";", "}" ]
Check if a port is available @param {Number} port The port to check if available @param {Function} cb Function called as result @param {Error} cb.err The error if occurred @param {Number} cb.port The port if available @private @ignore
[ "Check", "if", "a", "port", "is", "available" ]
a09356b9063c228616d0ffc56217b93c479f2604
https://github.com/mgesmundo/port-manager/blob/a09356b9063c228616d0ffc56217b93c479f2604/lib/port-finder.js#L16-L29
54,498
mgesmundo/port-manager
lib/port-finder.js
find
function find(ports, callback) { if (_.isEmpty(ports)) { callback(new Error('no free port available')); } else { var port = ports.shift(); checkPort(port, function (err, found) { if (!err) { callback(null, found); } else { find(ports, callback); } }); } }
javascript
function find(ports, callback) { if (_.isEmpty(ports)) { callback(new Error('no free port available')); } else { var port = ports.shift(); checkPort(port, function (err, found) { if (!err) { callback(null, found); } else { find(ports, callback); } }); } }
[ "function", "find", "(", "ports", ",", "callback", ")", "{", "if", "(", "_", ".", "isEmpty", "(", "ports", ")", ")", "{", "callback", "(", "new", "Error", "(", "'no free port available'", ")", ")", ";", "}", "else", "{", "var", "port", "=", "ports", ".", "shift", "(", ")", ";", "checkPort", "(", "port", ",", "function", "(", "err", ",", "found", ")", "{", "if", "(", "!", "err", ")", "{", "callback", "(", "null", ",", "found", ")", ";", "}", "else", "{", "find", "(", "ports", ",", "callback", ")", ";", "}", "}", ")", ";", "}", "}" ]
Find the first available port in a ports list @param {Array} ports The ports list to find the first available @param {Function} callback Function called as result @param {Error} callback.err The error if occurred @param {Number} callback.port The first port available @private @ignore
[ "Find", "the", "first", "available", "port", "in", "a", "ports", "list" ]
a09356b9063c228616d0ffc56217b93c479f2604
https://github.com/mgesmundo/port-manager/blob/a09356b9063c228616d0ffc56217b93c479f2604/lib/port-finder.js#L41-L54
54,499
jldec/pub-pkg-github-oauth
github-oauth.js
authenticate
function authenticate(req, cb) { request.post( 'https://github.com/login/oauth/access_token', { form: { client_id: process.env.GHID, // don't store credentials in opts client_secret: process.env.GHCS, // get them straight from process.env code: req.query.code } }, function(err, resp, body) { if (err) return cb(err); var result = qs.parse(body); getUser(req, result, function() { cb(null, result); }); } ); }
javascript
function authenticate(req, cb) { request.post( 'https://github.com/login/oauth/access_token', { form: { client_id: process.env.GHID, // don't store credentials in opts client_secret: process.env.GHCS, // get them straight from process.env code: req.query.code } }, function(err, resp, body) { if (err) return cb(err); var result = qs.parse(body); getUser(req, result, function() { cb(null, result); }); } ); }
[ "function", "authenticate", "(", "req", ",", "cb", ")", "{", "request", ".", "post", "(", "'https://github.com/login/oauth/access_token'", ",", "{", "form", ":", "{", "client_id", ":", "process", ".", "env", ".", "GHID", ",", "// don't store credentials in opts", "client_secret", ":", "process", ".", "env", ".", "GHCS", ",", "// get them straight from process.env", "code", ":", "req", ".", "query", ".", "code", "}", "}", ",", "function", "(", "err", ",", "resp", ",", "body", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "var", "result", "=", "qs", ".", "parse", "(", "body", ")", ";", "getUser", "(", "req", ",", "result", ",", "function", "(", ")", "{", "cb", "(", "null", ",", "result", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
get access token from github
[ "get", "access", "token", "from", "github" ]
bb97e18dd22b5165c402523bc7994dc14f9e34a2
https://github.com/jldec/pub-pkg-github-oauth/blob/bb97e18dd22b5165c402523bc7994dc14f9e34a2/github-oauth.js#L100-L115