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
partition
stringclasses
1 value
tblobaum/rconsole
rconsole.js
formatIf
function formatIf (bool, format, arr, ref) { if (bool) { arr.unshift(format) return util.format.apply({}, arr) } else return ref }
javascript
function formatIf (bool, format, arr, ref) { if (bool) { arr.unshift(format) return util.format.apply({}, arr) } else return ref }
[ "function", "formatIf", "(", "bool", ",", "format", ",", "arr", ",", "ref", ")", "{", "if", "(", "bool", ")", "{", "arr", ".", "unshift", "(", "format", ")", "return", "util", ".", "format", ".", "apply", "(", "{", "}", ",", "arr", ")", "}", "else", "return", "ref", "}" ]
if bool is true then format
[ "if", "bool", "is", "true", "then", "format" ]
857b9af7b668976a976ac8197c8bd564ecf803bd
https://github.com/tblobaum/rconsole/blob/857b9af7b668976a976ac8197c8bd564ecf803bd/rconsole.js#L280-L287
train
tblobaum/rconsole
rconsole.js
prependUntilLength
function prependUntilLength (str, len, char) { if (str.length >= len) return str else return prependUntilLength(str=char+str, len, char) }
javascript
function prependUntilLength (str, len, char) { if (str.length >= len) return str else return prependUntilLength(str=char+str, len, char) }
[ "function", "prependUntilLength", "(", "str", ",", "len", ",", "char", ")", "{", "if", "(", "str", ".", "length", ">=", "len", ")", "return", "str", "else", "return", "prependUntilLength", "(", "str", "=", "char", "+", "str", ",", "len", ",", "char", ")", "}" ]
Prepends `char` to `str` until it's length is `len` @param {String} str @param {Number} len @param {String} char @return {String} @api private
[ "Prepends", "char", "to", "str", "until", "it", "s", "length", "is", "len" ]
857b9af7b668976a976ac8197c8bd564ecf803bd
https://github.com/tblobaum/rconsole/blob/857b9af7b668976a976ac8197c8bd564ecf803bd/rconsole.js#L299-L304
train
tblobaum/rconsole
rconsole.js
defined
function defined () { for (var i=0; i<arguments.length; i++) if (typeof arguments[i] !== 'undefined') return arguments[i] }
javascript
function defined () { for (var i=0; i<arguments.length; i++) if (typeof arguments[i] !== 'undefined') return arguments[i] }
[ "function", "defined", "(", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "if", "(", "typeof", "arguments", "[", "i", "]", "!==", "'undefined'", ")", "return", "arguments", "[", "i", "]", "}" ]
Return the first argument that is not undefined @api private
[ "Return", "the", "first", "argument", "that", "is", "not", "undefined" ]
857b9af7b668976a976ac8197c8bd564ecf803bd
https://github.com/tblobaum/rconsole/blob/857b9af7b668976a976ac8197c8bd564ecf803bd/rconsole.js#L312-L316
train
jaredhanson/node-jsonrpc-tcp
lib/jsonrpc-tcp/remote.js
Remote
function Remote(connection) { this.timeout = 5000; this._connection = connection; this._handlers = {}; this._requestID = 1; var self = this; this._connection.addListener('response', function(res) { if (res.id === null || res.id === undefined) { return; } var handler = self._handlers[res.id]; if (handler) { handler.call(self, res.error, res.result); } delete self._handlers[res.id]; }); }
javascript
function Remote(connection) { this.timeout = 5000; this._connection = connection; this._handlers = {}; this._requestID = 1; var self = this; this._connection.addListener('response', function(res) { if (res.id === null || res.id === undefined) { return; } var handler = self._handlers[res.id]; if (handler) { handler.call(self, res.error, res.result); } delete self._handlers[res.id]; }); }
[ "function", "Remote", "(", "connection", ")", "{", "this", ".", "timeout", "=", "5000", ";", "this", ".", "_connection", "=", "connection", ";", "this", ".", "_handlers", "=", "{", "}", ";", "this", ".", "_requestID", "=", "1", ";", "var", "self", "=", "this", ";", "this", ".", "_connection", ".", "addListener", "(", "'response'", ",", "function", "(", "res", ")", "{", "if", "(", "res", ".", "id", "===", "null", "||", "res", ".", "id", "===", "undefined", ")", "{", "return", ";", "}", "var", "handler", "=", "self", ".", "_handlers", "[", "res", ".", "id", "]", ";", "if", "(", "handler", ")", "{", "handler", ".", "call", "(", "self", ",", "res", ".", "error", ",", "res", ".", "result", ")", ";", "}", "delete", "self", ".", "_handlers", "[", "res", ".", "id", "]", ";", "}", ")", ";", "}" ]
Create a new remote JSON-RPC peer over `connection`. `Remote` provides a convienient abstraction over a JSON-RPC connection, allowing methods to be invoked and responses to be received asynchronously. A `Remote` instance will automatically be created for each connection. There is no need to do so manually. @api private
[ "Create", "a", "new", "remote", "JSON", "-", "RPC", "peer", "over", "connection", "." ]
d9dc271b8f50da9fb08ebb46c390fd4c57a89bfc
https://github.com/jaredhanson/node-jsonrpc-tcp/blob/d9dc271b8f50da9fb08ebb46c390fd4c57a89bfc/lib/jsonrpc-tcp/remote.js#L12-L25
train
jeffdonthemic/nforce-tooling
index.js
validate
function validate(args, required) { var result = { error: false, message: 'No errors' } // ensure required properties were passed in the arguments hash if (required) { var keys = _.keys(args); required.forEach(function(field) { if(!_.contains(keys, field)) { result.error = true; result.message = 'The following values must be passed: ' + required.join(', '); } }) } return result; }
javascript
function validate(args, required) { var result = { error: false, message: 'No errors' } // ensure required properties were passed in the arguments hash if (required) { var keys = _.keys(args); required.forEach(function(field) { if(!_.contains(keys, field)) { result.error = true; result.message = 'The following values must be passed: ' + required.join(', '); } }) } return result; }
[ "function", "validate", "(", "args", ",", "required", ")", "{", "var", "result", "=", "{", "error", ":", "false", ",", "message", ":", "'No errors'", "}", "if", "(", "required", ")", "{", "var", "keys", "=", "_", ".", "keys", "(", "args", ")", ";", "required", ".", "forEach", "(", "function", "(", "field", ")", "{", "if", "(", "!", "_", ".", "contains", "(", "keys", ",", "field", ")", ")", "{", "result", ".", "error", "=", "true", ";", "result", ".", "message", "=", "'The following values must be passed: '", "+", "required", ".", "join", "(", "', '", ")", ";", "}", "}", ")", "}", "return", "result", ";", "}" ]
utility method to validate inputs
[ "utility", "method", "to", "validate", "inputs" ]
5d9f4704e0ea520f1d9fc4f3ec272f09afaa2549
https://github.com/jeffdonthemic/nforce-tooling/blob/5d9f4704e0ea520f1d9fc4f3ec272f09afaa2549/index.js#L424-L443
train
googlearchive/appengine-nodejs
lib/index.js
makeLogLineProto
function makeLogLineProto(message, time, level) { var userAppLogLine = new apphosting.UserAppLogLine(); userAppLogLine.setTimestampUsec((time * 1000).toString()); userAppLogLine.setLevel(level); userAppLogLine.setMessage(message); return userAppLogLine; }
javascript
function makeLogLineProto(message, time, level) { var userAppLogLine = new apphosting.UserAppLogLine(); userAppLogLine.setTimestampUsec((time * 1000).toString()); userAppLogLine.setLevel(level); userAppLogLine.setMessage(message); return userAppLogLine; }
[ "function", "makeLogLineProto", "(", "message", ",", "time", ",", "level", ")", "{", "var", "userAppLogLine", "=", "new", "apphosting", ".", "UserAppLogLine", "(", ")", ";", "userAppLogLine", ".", "setTimestampUsec", "(", "(", "time", "*", "1000", ")", ".", "toString", "(", ")", ")", ";", "userAppLogLine", ".", "setLevel", "(", "level", ")", ";", "userAppLogLine", ".", "setMessage", "(", "message", ")", ";", "return", "userAppLogLine", ";", "}" ]
Return a log line proto. @param {!string} message the message to log @param {!Number} time the timestamp to use in milliseconds @param {!string} level the log level @return {!apphosting.UserAppLogLine} a log line proto
[ "Return", "a", "log", "line", "proto", "." ]
da3a5c7ff87c74eb3c8976f7d0b233f616765889
https://github.com/googlearchive/appengine-nodejs/blob/da3a5c7ff87c74eb3c8976f7d0b233f616765889/lib/index.js#L868-L874
train
googlearchive/appengine-nodejs
lib/index.js
makeMemcacheSetProto
function makeMemcacheSetProto(key, value) { var memcacheSetRequest = new apphosting.MemcacheSetRequest(); var item = new apphosting.MemcacheSetRequest.Item(); item.setKey(key); item.setValue(value); item.setSetPolicy(apphosting.MemcacheSetRequest.SetPolicy.SET); memcacheSetRequest.addItem(item); return memcacheSetRequest; }
javascript
function makeMemcacheSetProto(key, value) { var memcacheSetRequest = new apphosting.MemcacheSetRequest(); var item = new apphosting.MemcacheSetRequest.Item(); item.setKey(key); item.setValue(value); item.setSetPolicy(apphosting.MemcacheSetRequest.SetPolicy.SET); memcacheSetRequest.addItem(item); return memcacheSetRequest; }
[ "function", "makeMemcacheSetProto", "(", "key", ",", "value", ")", "{", "var", "memcacheSetRequest", "=", "new", "apphosting", ".", "MemcacheSetRequest", "(", ")", ";", "var", "item", "=", "new", "apphosting", ".", "MemcacheSetRequest", ".", "Item", "(", ")", ";", "item", ".", "setKey", "(", "key", ")", ";", "item", ".", "setValue", "(", "value", ")", ";", "item", ".", "setSetPolicy", "(", "apphosting", ".", "MemcacheSetRequest", ".", "SetPolicy", ".", "SET", ")", ";", "memcacheSetRequest", ".", "addItem", "(", "item", ")", ";", "return", "memcacheSetRequest", ";", "}" ]
Return a memcache set request proto. @param {!string} key key of the item to set @param {!string} value value of the item to set @return {apphosting.MemcacheSetRequest} a memcache set request proto
[ "Return", "a", "memcache", "set", "request", "proto", "." ]
da3a5c7ff87c74eb3c8976f7d0b233f616765889
https://github.com/googlearchive/appengine-nodejs/blob/da3a5c7ff87c74eb3c8976f7d0b233f616765889/lib/index.js#L895-L903
train
googlearchive/appengine-nodejs
lib/index.js
makeTaskqueueAddProto
function makeTaskqueueAddProto(taskOptions) { var taskqueueAddRequest = new apphosting.TaskQueueAddRequest(); taskqueueAddRequest.setUrl(taskOptions.url); taskqueueAddRequest.setQueueName(goog.isDefAndNotNull(taskOptions.queueName) ? taskOptions.queueName : 'default'); taskqueueAddRequest.setTaskName(goog.isDefAndNotNull(taskOptions.taskName) ? taskOptions.taskName : ''); taskqueueAddRequest.setEtaUsec(goog.isDefAndNotNull(taskOptions.etaUsec) ? taskOptions.etaUsec : '0'); var method = 'post'; if (goog.isDefAndNotNull(taskOptions.method)) { method = taskOptions.method; } taskqueueAddRequest.setMethod(methodToProtoMethod[method]); if (goog.isDefAndNotNull(taskOptions.body)) { taskqueueAddRequest.setBody(taskOptions.body); } if (goog.isDefAndNotNull(taskOptions.headers)) { goog.object.forEach(taskOptions.headers, function(value, key) { var header = new apphosting.TaskQueueAddRequest.Header(); header.setKey(key); header.setValue(value); taskqueueAddRequest.addHeader(header); }); } return taskqueueAddRequest; }
javascript
function makeTaskqueueAddProto(taskOptions) { var taskqueueAddRequest = new apphosting.TaskQueueAddRequest(); taskqueueAddRequest.setUrl(taskOptions.url); taskqueueAddRequest.setQueueName(goog.isDefAndNotNull(taskOptions.queueName) ? taskOptions.queueName : 'default'); taskqueueAddRequest.setTaskName(goog.isDefAndNotNull(taskOptions.taskName) ? taskOptions.taskName : ''); taskqueueAddRequest.setEtaUsec(goog.isDefAndNotNull(taskOptions.etaUsec) ? taskOptions.etaUsec : '0'); var method = 'post'; if (goog.isDefAndNotNull(taskOptions.method)) { method = taskOptions.method; } taskqueueAddRequest.setMethod(methodToProtoMethod[method]); if (goog.isDefAndNotNull(taskOptions.body)) { taskqueueAddRequest.setBody(taskOptions.body); } if (goog.isDefAndNotNull(taskOptions.headers)) { goog.object.forEach(taskOptions.headers, function(value, key) { var header = new apphosting.TaskQueueAddRequest.Header(); header.setKey(key); header.setValue(value); taskqueueAddRequest.addHeader(header); }); } return taskqueueAddRequest; }
[ "function", "makeTaskqueueAddProto", "(", "taskOptions", ")", "{", "var", "taskqueueAddRequest", "=", "new", "apphosting", ".", "TaskQueueAddRequest", "(", ")", ";", "taskqueueAddRequest", ".", "setUrl", "(", "taskOptions", ".", "url", ")", ";", "taskqueueAddRequest", ".", "setQueueName", "(", "goog", ".", "isDefAndNotNull", "(", "taskOptions", ".", "queueName", ")", "?", "taskOptions", ".", "queueName", ":", "'default'", ")", ";", "taskqueueAddRequest", ".", "setTaskName", "(", "goog", ".", "isDefAndNotNull", "(", "taskOptions", ".", "taskName", ")", "?", "taskOptions", ".", "taskName", ":", "''", ")", ";", "taskqueueAddRequest", ".", "setEtaUsec", "(", "goog", ".", "isDefAndNotNull", "(", "taskOptions", ".", "etaUsec", ")", "?", "taskOptions", ".", "etaUsec", ":", "'0'", ")", ";", "var", "method", "=", "'post'", ";", "if", "(", "goog", ".", "isDefAndNotNull", "(", "taskOptions", ".", "method", ")", ")", "{", "method", "=", "taskOptions", ".", "method", ";", "}", "taskqueueAddRequest", ".", "setMethod", "(", "methodToProtoMethod", "[", "method", "]", ")", ";", "if", "(", "goog", ".", "isDefAndNotNull", "(", "taskOptions", ".", "body", ")", ")", "{", "taskqueueAddRequest", ".", "setBody", "(", "taskOptions", ".", "body", ")", ";", "}", "if", "(", "goog", ".", "isDefAndNotNull", "(", "taskOptions", ".", "headers", ")", ")", "{", "goog", ".", "object", ".", "forEach", "(", "taskOptions", ".", "headers", ",", "function", "(", "value", ",", "key", ")", "{", "var", "header", "=", "new", "apphosting", ".", "TaskQueueAddRequest", ".", "Header", "(", ")", ";", "header", ".", "setKey", "(", "key", ")", ";", "header", ".", "setValue", "(", "value", ")", ";", "taskqueueAddRequest", ".", "addHeader", "(", "header", ")", ";", "}", ")", ";", "}", "return", "taskqueueAddRequest", ";", "}" ]
Return a taskqueue add request proto. The object representing the task options must satisfy the following contract. It must have the following (required) properties: url : a string, the url to dispatch the task request to It may have the following (optional) properties: queueName : a string, the name of the queue to add the task to (defaults to 'default') taskName : a string, the name of the task etaUsec: a string, the ETA in microseconds as a string method: a string among 'get', 'post', 'head', 'put', 'delete' (defaults to 'post') body: a string, the body of the request (for 'post' and 'put' only) headers: an object containing a property for each desired header in the request @param {!Object} the task options (see above) @return {apphosting.TaskQueueAddRequest} a taskqueue add request proto
[ "Return", "a", "taskqueue", "add", "request", "proto", "." ]
da3a5c7ff87c74eb3c8976f7d0b233f616765889
https://github.com/googlearchive/appengine-nodejs/blob/da3a5c7ff87c74eb3c8976f7d0b233f616765889/lib/index.js#L933-L959
train
googlearchive/appengine-nodejs
lib/index.js
makeBackgroundRequest
function makeBackgroundRequest(req, appId, moduleName, moduleVersion, moduleInstance, appengine) { var escapedAppId = appId.replace(/[:.]/g, '_'); var token = escapedAppId + '/' + moduleName + '.' + moduleVersion + '.' + moduleInstance; var result = { appengine: { devappserver: req.appengine.devappserver, appId: appId, moduleName: moduleName, moduleVersion: moduleVersion, moduleInstance: moduleInstance, logBuffer_: appengine.newLogBuffer_() } }; if (req.appengine.devappserver) { result.appengine.devRequestId = token; } else { result.appengine.apiTicket = token; } return result; }
javascript
function makeBackgroundRequest(req, appId, moduleName, moduleVersion, moduleInstance, appengine) { var escapedAppId = appId.replace(/[:.]/g, '_'); var token = escapedAppId + '/' + moduleName + '.' + moduleVersion + '.' + moduleInstance; var result = { appengine: { devappserver: req.appengine.devappserver, appId: appId, moduleName: moduleName, moduleVersion: moduleVersion, moduleInstance: moduleInstance, logBuffer_: appengine.newLogBuffer_() } }; if (req.appengine.devappserver) { result.appengine.devRequestId = token; } else { result.appengine.apiTicket = token; } return result; }
[ "function", "makeBackgroundRequest", "(", "req", ",", "appId", ",", "moduleName", ",", "moduleVersion", ",", "moduleInstance", ",", "appengine", ")", "{", "var", "escapedAppId", "=", "appId", ".", "replace", "(", "/", "[:.]", "/", "g", ",", "'_'", ")", ";", "var", "token", "=", "escapedAppId", "+", "'/'", "+", "moduleName", "+", "'.'", "+", "moduleVersion", "+", "'.'", "+", "moduleInstance", ";", "var", "result", "=", "{", "appengine", ":", "{", "devappserver", ":", "req", ".", "appengine", ".", "devappserver", ",", "appId", ":", "appId", ",", "moduleName", ":", "moduleName", ",", "moduleVersion", ":", "moduleVersion", ",", "moduleInstance", ":", "moduleInstance", ",", "logBuffer_", ":", "appengine", ".", "newLogBuffer_", "(", ")", "}", "}", ";", "if", "(", "req", ".", "appengine", ".", "devappserver", ")", "{", "result", ".", "appengine", ".", "devRequestId", "=", "token", ";", "}", "else", "{", "result", ".", "appengine", ".", "apiTicket", "=", "token", ";", "}", "return", "result", ";", "}" ]
Return a background request object. @param {!object} req request @param {!string} appId application id @param {!string} moduleName module name @param {!string} moduleVersion major module version @param {!string} moduleInstance instance id @param {!Object} appengine AppEngine instance @return {!Object} a request object suitable for making api calls
[ "Return", "a", "background", "request", "object", "." ]
da3a5c7ff87c74eb3c8976f7d0b233f616765889
https://github.com/googlearchive/appengine-nodejs/blob/da3a5c7ff87c74eb3c8976f7d0b233f616765889/lib/index.js#L972-L991
train
googlearchive/appengine-nodejs
lib/index.js
makeModulesGetHostnameProto
function makeModulesGetHostnameProto(module, version, instance) { var getHostnameRequest = new apphosting.GetHostnameRequest(); getHostnameRequest.setModule(module); getHostnameRequest.setVersion(version); getHostnameRequest.setInstance(instance); return getHostnameRequest; }
javascript
function makeModulesGetHostnameProto(module, version, instance) { var getHostnameRequest = new apphosting.GetHostnameRequest(); getHostnameRequest.setModule(module); getHostnameRequest.setVersion(version); getHostnameRequest.setInstance(instance); return getHostnameRequest; }
[ "function", "makeModulesGetHostnameProto", "(", "module", ",", "version", ",", "instance", ")", "{", "var", "getHostnameRequest", "=", "new", "apphosting", ".", "GetHostnameRequest", "(", ")", ";", "getHostnameRequest", ".", "setModule", "(", "module", ")", ";", "getHostnameRequest", ".", "setVersion", "(", "version", ")", ";", "getHostnameRequest", ".", "setInstance", "(", "instance", ")", ";", "return", "getHostnameRequest", ";", "}" ]
Return a modules get hostname proto. @param {!string} module module name @param {!string} version module version @param {!string} instance module instance @return {apphosting.GetHostnameRequest} a modules get hostname proto
[ "Return", "a", "modules", "get", "hostname", "proto", "." ]
da3a5c7ff87c74eb3c8976f7d0b233f616765889
https://github.com/googlearchive/appengine-nodejs/blob/da3a5c7ff87c74eb3c8976f7d0b233f616765889/lib/index.js#L1001-L1007
train
101100/pca9685
examples/servo.js
servoLoop
function servoLoop() { timer = setTimeout(servoLoop, 500); pwm.setPulseLength(steeringChannel, pulseLengths[nextPulse]); nextPulse = (nextPulse + 1) % pulseLengths.length; }
javascript
function servoLoop() { timer = setTimeout(servoLoop, 500); pwm.setPulseLength(steeringChannel, pulseLengths[nextPulse]); nextPulse = (nextPulse + 1) % pulseLengths.length; }
[ "function", "servoLoop", "(", ")", "{", "timer", "=", "setTimeout", "(", "servoLoop", ",", "500", ")", ";", "pwm", ".", "setPulseLength", "(", "steeringChannel", ",", "pulseLengths", "[", "nextPulse", "]", ")", ";", "nextPulse", "=", "(", "nextPulse", "+", "1", ")", "%", "pulseLengths", ".", "length", ";", "}" ]
loop to cycle through pulse lengths
[ "loop", "to", "cycle", "through", "pulse", "lengths" ]
37f14d08502848fa916f984c19a87eb1c7ccaa28
https://github.com/101100/pca9685/blob/37f14d08502848fa916f984c19a87eb1c7ccaa28/examples/servo.js#L41-L46
train
googlearchive/appengine-nodejs
lib/utils.js
numberArrayToString
function numberArrayToString(a) { var s = ''; for (var i in a) { s += String.fromCharCode(a[i]); } return s; }
javascript
function numberArrayToString(a) { var s = ''; for (var i in a) { s += String.fromCharCode(a[i]); } return s; }
[ "function", "numberArrayToString", "(", "a", ")", "{", "var", "s", "=", "''", ";", "for", "(", "var", "i", "in", "a", ")", "{", "s", "+=", "String", ".", "fromCharCode", "(", "a", "[", "i", "]", ")", ";", "}", "return", "s", ";", "}" ]
Convert an array of numbers to a string. @param {Array.<number>} a array to convert @return {!string} resulting string
[ "Convert", "an", "array", "of", "numbers", "to", "a", "string", "." ]
da3a5c7ff87c74eb3c8976f7d0b233f616765889
https://github.com/googlearchive/appengine-nodejs/blob/da3a5c7ff87c74eb3c8976f7d0b233f616765889/lib/utils.js#L29-L35
train
googlearchive/appengine-nodejs
lib/utils.js
stringToUint8Array
function stringToUint8Array(s) { var a = new Uint8Array(s.length); for(var i = 0, j = s.length; i < j; ++i) { a[i] = s.charCodeAt(i); } return a; }
javascript
function stringToUint8Array(s) { var a = new Uint8Array(s.length); for(var i = 0, j = s.length; i < j; ++i) { a[i] = s.charCodeAt(i); } return a; }
[ "function", "stringToUint8Array", "(", "s", ")", "{", "var", "a", "=", "new", "Uint8Array", "(", "s", ".", "length", ")", ";", "for", "(", "var", "i", "=", "0", ",", "j", "=", "s", ".", "length", ";", "i", "<", "j", ";", "++", "i", ")", "{", "a", "[", "i", "]", "=", "s", ".", "charCodeAt", "(", "i", ")", ";", "}", "return", "a", ";", "}" ]
Convert a string to a Uint8Array. @param {!string} s string to convert @return {UInt8Array} resulting array
[ "Convert", "a", "string", "to", "a", "Uint8Array", "." ]
da3a5c7ff87c74eb3c8976f7d0b233f616765889
https://github.com/googlearchive/appengine-nodejs/blob/da3a5c7ff87c74eb3c8976f7d0b233f616765889/lib/utils.js#L57-L63
train
jaredhanson/node-jsonrpc-tcp
lib/jsonrpc-tcp/server.js
Server
function Server(clientListener) { net.Server.call(this); this._services = []; if (clientListener) { this.addListener('client', clientListener); } var self = this; this.addListener('connection', function(socket) { var connection = new Connection(socket); connection.once('connect', function(remote) { self.emit('client', connection, remote); }); connection.on('error', function(err) { self.emit('clientError', err, this); }); // Services exposed on the server as a whole are propagated to each // connection. Flexibility exists to expose services on a per-connection // basis as well. self._services.forEach(function(service) { connection.expose(service.name, service.service) }); }); }
javascript
function Server(clientListener) { net.Server.call(this); this._services = []; if (clientListener) { this.addListener('client', clientListener); } var self = this; this.addListener('connection', function(socket) { var connection = new Connection(socket); connection.once('connect', function(remote) { self.emit('client', connection, remote); }); connection.on('error', function(err) { self.emit('clientError', err, this); }); // Services exposed on the server as a whole are propagated to each // connection. Flexibility exists to expose services on a per-connection // basis as well. self._services.forEach(function(service) { connection.expose(service.name, service.service) }); }); }
[ "function", "Server", "(", "clientListener", ")", "{", "net", ".", "Server", ".", "call", "(", "this", ")", ";", "this", ".", "_services", "=", "[", "]", ";", "if", "(", "clientListener", ")", "{", "this", ".", "addListener", "(", "'client'", ",", "clientListener", ")", ";", "}", "var", "self", "=", "this", ";", "this", ".", "addListener", "(", "'connection'", ",", "function", "(", "socket", ")", "{", "var", "connection", "=", "new", "Connection", "(", "socket", ")", ";", "connection", ".", "once", "(", "'connect'", ",", "function", "(", "remote", ")", "{", "self", ".", "emit", "(", "'client'", ",", "connection", ",", "remote", ")", ";", "}", ")", ";", "connection", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "self", ".", "emit", "(", "'clientError'", ",", "err", ",", "this", ")", ";", "}", ")", ";", "self", ".", "_services", ".", "forEach", "(", "function", "(", "service", ")", "{", "connection", ".", "expose", "(", "service", ".", "name", ",", "service", ".", "service", ")", "}", ")", ";", "}", ")", ";", "}" ]
Create a new JSON-RPC server. Creates a new JSON-RPC over TCP server. The optional `clientListener` argument is automatically set as a listener for the 'client' event. Events: Event: 'client' `function(client, remote) { }` Emitted when a client connects to the server. `client` is a `Connection`, exposing services which can be invoked by the client on the server. `remote` is a `Remote`, to be used for invoking remote methods on the client from the server. Examples: var server = new Server(); var server = new Server(function(client, remote) { remote.call('hello', 'Hello Client'); }); @param {Function} clientListener @return {Server} @api public
[ "Create", "a", "new", "JSON", "-", "RPC", "server", "." ]
d9dc271b8f50da9fb08ebb46c390fd4c57a89bfc
https://github.com/jaredhanson/node-jsonrpc-tcp/blob/d9dc271b8f50da9fb08ebb46c390fd4c57a89bfc/lib/jsonrpc-tcp/server.js#L38-L61
train
pelias/microservice-wrapper
service.js
synthesizeUrl
function synthesizeUrl(serviceConfig, req, res) { const parameters = _.map(serviceConfig.getParameters(req, res), (value, key) => { return `${key}=${value}`; }).join('&'); if (parameters) { return encodeURI(`${serviceConfig.getUrl(req)}?${parameters}`); } else { return serviceConfig.getUrl(req); } }
javascript
function synthesizeUrl(serviceConfig, req, res) { const parameters = _.map(serviceConfig.getParameters(req, res), (value, key) => { return `${key}=${value}`; }).join('&'); if (parameters) { return encodeURI(`${serviceConfig.getUrl(req)}?${parameters}`); } else { return serviceConfig.getUrl(req); } }
[ "function", "synthesizeUrl", "(", "serviceConfig", ",", "req", ",", "res", ")", "{", "const", "parameters", "=", "_", ".", "map", "(", "serviceConfig", ".", "getParameters", "(", "req", ",", "res", ")", ",", "(", "value", ",", "key", ")", "=>", "{", "return", "`", "${", "key", "}", "${", "value", "}", "`", ";", "}", ")", ".", "join", "(", "'&'", ")", ";", "if", "(", "parameters", ")", "{", "return", "encodeURI", "(", "`", "${", "serviceConfig", ".", "getUrl", "(", "req", ")", "}", "${", "parameters", "}", "`", ")", ";", "}", "else", "{", "return", "serviceConfig", ".", "getUrl", "(", "req", ")", ";", "}", "}" ]
superagent doesn't exposed the assembled GET request, so synthesize it
[ "superagent", "doesn", "t", "exposed", "the", "assembled", "GET", "request", "so", "synthesize", "it" ]
0f3e85138646db589b14cab1ac6861dc1a1f33ff
https://github.com/pelias/microservice-wrapper/blob/0f3e85138646db589b14cab1ac6861dc1a1f33ff/service.js#L16-L27
train
scravy/uuid-1345
index.js
parse
function parse(string) { var buffer = newBufferFromSize(16); var j = 0; for (var i = 0; i < 16; i++) { buffer[i] = hex2byte[string[j++] + string[j++]]; if (i === 3 || i === 5 || i === 7 || i === 9) { j += 1; } } return buffer; }
javascript
function parse(string) { var buffer = newBufferFromSize(16); var j = 0; for (var i = 0; i < 16; i++) { buffer[i] = hex2byte[string[j++] + string[j++]]; if (i === 3 || i === 5 || i === 7 || i === 9) { j += 1; } } return buffer; }
[ "function", "parse", "(", "string", ")", "{", "var", "buffer", "=", "newBufferFromSize", "(", "16", ")", ";", "var", "j", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "16", ";", "i", "++", ")", "{", "buffer", "[", "i", "]", "=", "hex2byte", "[", "string", "[", "j", "++", "]", "+", "string", "[", "j", "++", "]", "]", ";", "if", "(", "i", "===", "3", "||", "i", "===", "5", "||", "i", "===", "7", "||", "i", "===", "9", ")", "{", "j", "+=", "1", ";", "}", "}", "return", "buffer", ";", "}" ]
read stringified uuid into a Buffer
[ "read", "stringified", "uuid", "into", "a", "Buffer" ]
320cc3e5c350886ccfd9b717ec19d183667f9bbd
https://github.com/scravy/uuid-1345/blob/320cc3e5c350886ccfd9b717ec19d183667f9bbd/index.js#L132-L144
train
scravy/uuid-1345
index.js
uuidNamed
function uuidNamed(hashFunc, version, arg1, arg2) { var options = arg1 || {}; var callback = typeof arg1 === "function" ? arg1 : arg2; var namespace = options.namespace; var name = options.name; var hash = crypto.createHash(hashFunc); if (typeof namespace === "string") { if (!check(namespace)) { return error(invalidNamespace, callback); } namespace = parse(namespace); } else if (namespace instanceof UUID) { namespace = namespace.toBuffer(); } else if (!(namespace instanceof Buffer) || namespace.length !== 16) { return error(invalidNamespace, callback); } var nameIsNotAString = typeof name !== "string"; if (nameIsNotAString && !(name instanceof Buffer)) { return error(invalidName, callback); } hash.update(namespace); hash.update(options.name, nameIsNotAString ? "binary" : "utf8"); var buffer = hash.digest(); var result; switch (options.encoding && options.encoding[0]) { case "b": case "B": buffer[6] = (buffer[6] & 0x0f) | version; buffer[8] = (buffer[8] & 0x3f) | 0x80; result = buffer; break; case "o": case "U": buffer[6] = (buffer[6] & 0x0f) | version; buffer[8] = (buffer[8] & 0x3f) | 0x80; result = new UUID(buffer); break; default: result = byte2hex[buffer[0]] + byte2hex[buffer[1]] + byte2hex[buffer[2]] + byte2hex[buffer[3]] + "-" + byte2hex[buffer[4]] + byte2hex[buffer[5]] + "-" + byte2hex[(buffer[6] & 0x0f) | version] + byte2hex[buffer[7]] + "-" + byte2hex[(buffer[8] & 0x3f) | 0x80] + byte2hex[buffer[9]] + "-" + byte2hex[buffer[10]] + byte2hex[buffer[11]] + byte2hex[buffer[12]] + byte2hex[buffer[13]] + byte2hex[buffer[14]] + byte2hex[buffer[15]]; break; } if (callback) { setImmediate(function () { callback(null, result); }); } else { return result; } }
javascript
function uuidNamed(hashFunc, version, arg1, arg2) { var options = arg1 || {}; var callback = typeof arg1 === "function" ? arg1 : arg2; var namespace = options.namespace; var name = options.name; var hash = crypto.createHash(hashFunc); if (typeof namespace === "string") { if (!check(namespace)) { return error(invalidNamespace, callback); } namespace = parse(namespace); } else if (namespace instanceof UUID) { namespace = namespace.toBuffer(); } else if (!(namespace instanceof Buffer) || namespace.length !== 16) { return error(invalidNamespace, callback); } var nameIsNotAString = typeof name !== "string"; if (nameIsNotAString && !(name instanceof Buffer)) { return error(invalidName, callback); } hash.update(namespace); hash.update(options.name, nameIsNotAString ? "binary" : "utf8"); var buffer = hash.digest(); var result; switch (options.encoding && options.encoding[0]) { case "b": case "B": buffer[6] = (buffer[6] & 0x0f) | version; buffer[8] = (buffer[8] & 0x3f) | 0x80; result = buffer; break; case "o": case "U": buffer[6] = (buffer[6] & 0x0f) | version; buffer[8] = (buffer[8] & 0x3f) | 0x80; result = new UUID(buffer); break; default: result = byte2hex[buffer[0]] + byte2hex[buffer[1]] + byte2hex[buffer[2]] + byte2hex[buffer[3]] + "-" + byte2hex[buffer[4]] + byte2hex[buffer[5]] + "-" + byte2hex[(buffer[6] & 0x0f) | version] + byte2hex[buffer[7]] + "-" + byte2hex[(buffer[8] & 0x3f) | 0x80] + byte2hex[buffer[9]] + "-" + byte2hex[buffer[10]] + byte2hex[buffer[11]] + byte2hex[buffer[12]] + byte2hex[buffer[13]] + byte2hex[buffer[14]] + byte2hex[buffer[15]]; break; } if (callback) { setImmediate(function () { callback(null, result); }); } else { return result; } }
[ "function", "uuidNamed", "(", "hashFunc", ",", "version", ",", "arg1", ",", "arg2", ")", "{", "var", "options", "=", "arg1", "||", "{", "}", ";", "var", "callback", "=", "typeof", "arg1", "===", "\"function\"", "?", "arg1", ":", "arg2", ";", "var", "namespace", "=", "options", ".", "namespace", ";", "var", "name", "=", "options", ".", "name", ";", "var", "hash", "=", "crypto", ".", "createHash", "(", "hashFunc", ")", ";", "if", "(", "typeof", "namespace", "===", "\"string\"", ")", "{", "if", "(", "!", "check", "(", "namespace", ")", ")", "{", "return", "error", "(", "invalidNamespace", ",", "callback", ")", ";", "}", "namespace", "=", "parse", "(", "namespace", ")", ";", "}", "else", "if", "(", "namespace", "instanceof", "UUID", ")", "{", "namespace", "=", "namespace", ".", "toBuffer", "(", ")", ";", "}", "else", "if", "(", "!", "(", "namespace", "instanceof", "Buffer", ")", "||", "namespace", ".", "length", "!==", "16", ")", "{", "return", "error", "(", "invalidNamespace", ",", "callback", ")", ";", "}", "var", "nameIsNotAString", "=", "typeof", "name", "!==", "\"string\"", ";", "if", "(", "nameIsNotAString", "&&", "!", "(", "name", "instanceof", "Buffer", ")", ")", "{", "return", "error", "(", "invalidName", ",", "callback", ")", ";", "}", "hash", ".", "update", "(", "namespace", ")", ";", "hash", ".", "update", "(", "options", ".", "name", ",", "nameIsNotAString", "?", "\"binary\"", ":", "\"utf8\"", ")", ";", "var", "buffer", "=", "hash", ".", "digest", "(", ")", ";", "var", "result", ";", "switch", "(", "options", ".", "encoding", "&&", "options", ".", "encoding", "[", "0", "]", ")", "{", "case", "\"b\"", ":", "case", "\"B\"", ":", "buffer", "[", "6", "]", "=", "(", "buffer", "[", "6", "]", "&", "0x0f", ")", "|", "version", ";", "buffer", "[", "8", "]", "=", "(", "buffer", "[", "8", "]", "&", "0x3f", ")", "|", "0x80", ";", "result", "=", "buffer", ";", "break", ";", "case", "\"o\"", ":", "case", "\"U\"", ":", "buffer", "[", "6", "]", "=", "(", "buffer", "[", "6", "]", "&", "0x0f", ")", "|", "version", ";", "buffer", "[", "8", "]", "=", "(", "buffer", "[", "8", "]", "&", "0x3f", ")", "|", "0x80", ";", "result", "=", "new", "UUID", "(", "buffer", ")", ";", "break", ";", "default", ":", "result", "=", "byte2hex", "[", "buffer", "[", "0", "]", "]", "+", "byte2hex", "[", "buffer", "[", "1", "]", "]", "+", "byte2hex", "[", "buffer", "[", "2", "]", "]", "+", "byte2hex", "[", "buffer", "[", "3", "]", "]", "+", "\"-\"", "+", "byte2hex", "[", "buffer", "[", "4", "]", "]", "+", "byte2hex", "[", "buffer", "[", "5", "]", "]", "+", "\"-\"", "+", "byte2hex", "[", "(", "buffer", "[", "6", "]", "&", "0x0f", ")", "|", "version", "]", "+", "byte2hex", "[", "buffer", "[", "7", "]", "]", "+", "\"-\"", "+", "byte2hex", "[", "(", "buffer", "[", "8", "]", "&", "0x3f", ")", "|", "0x80", "]", "+", "byte2hex", "[", "buffer", "[", "9", "]", "]", "+", "\"-\"", "+", "byte2hex", "[", "buffer", "[", "10", "]", "]", "+", "byte2hex", "[", "buffer", "[", "11", "]", "]", "+", "byte2hex", "[", "buffer", "[", "12", "]", "]", "+", "byte2hex", "[", "buffer", "[", "13", "]", "]", "+", "byte2hex", "[", "buffer", "[", "14", "]", "]", "+", "byte2hex", "[", "buffer", "[", "15", "]", "]", ";", "break", ";", "}", "if", "(", "callback", ")", "{", "setImmediate", "(", "function", "(", ")", "{", "callback", "(", "null", ",", "result", ")", ";", "}", ")", ";", "}", "else", "{", "return", "result", ";", "}", "}" ]
v3 + v5
[ "v3", "+", "v5" ]
320cc3e5c350886ccfd9b717ec19d183667f9bbd
https://github.com/scravy/uuid-1345/blob/320cc3e5c350886ccfd9b717ec19d183667f9bbd/index.js#L288-L353
train
ma-ha/easy-web-app
index.js
async function( req, res, next ) { try { var csrfToken = 'default' if ( req.cookies && req.cookies[ 'pong-security' ] ) { var token = req.cookies[ 'pong-security' ] if ( gui.getCsrfTokenForUser ) { csrfToken = await gui.getCsrfTokenForUser( token ) } else if ( gui.userTokens[ token ] && gui.userTokens[ token ].csrfToken ) { csrfToken = gui.userTokens[ token ].csrfToken } } } catch ( exc ) { log.warn('easy-web-app CSRF token, exc') } res.header( 'X-Protect', csrfToken ); next(); }
javascript
async function( req, res, next ) { try { var csrfToken = 'default' if ( req.cookies && req.cookies[ 'pong-security' ] ) { var token = req.cookies[ 'pong-security' ] if ( gui.getCsrfTokenForUser ) { csrfToken = await gui.getCsrfTokenForUser( token ) } else if ( gui.userTokens[ token ] && gui.userTokens[ token ].csrfToken ) { csrfToken = gui.userTokens[ token ].csrfToken } } } catch ( exc ) { log.warn('easy-web-app CSRF token, exc') } res.header( 'X-Protect', csrfToken ); next(); }
[ "async", "function", "(", "req", ",", "res", ",", "next", ")", "{", "try", "{", "var", "csrfToken", "=", "'default'", "if", "(", "req", ".", "cookies", "&&", "req", ".", "cookies", "[", "'pong-security'", "]", ")", "{", "var", "token", "=", "req", ".", "cookies", "[", "'pong-security'", "]", "if", "(", "gui", ".", "getCsrfTokenForUser", ")", "{", "csrfToken", "=", "await", "gui", ".", "getCsrfTokenForUser", "(", "token", ")", "}", "else", "if", "(", "gui", ".", "userTokens", "[", "token", "]", "&&", "gui", ".", "userTokens", "[", "token", "]", ".", "csrfToken", ")", "{", "csrfToken", "=", "gui", ".", "userTokens", "[", "token", "]", ".", "csrfToken", "}", "}", "}", "catch", "(", "exc", ")", "{", "log", ".", "warn", "(", "'easy-web-app CSRF token, exc'", ")", "}", "res", ".", "header", "(", "'X-Protect'", ",", "csrfToken", ")", ";", "next", "(", ")", ";", "}" ]
inject CSRF token
[ "inject", "CSRF", "token" ]
f48ca9d06947e35d29a6188ece17f0f346e07c5e
https://github.com/ma-ha/easy-web-app/blob/f48ca9d06947e35d29a6188ece17f0f346e07c5e/index.js#L1038-L1052
train
sqrrrl/passport-google-plus
examples/offline/app.js
ensureAuthenticated
function ensureAuthenticated(req, res, next) { if (req.isAuthenticated()) { req.authClient = new googleapis.auth.OAuth2(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET); req.authClient.credentials = req.session.googleCredentials; return next(); } res.redirect('/'); }
javascript
function ensureAuthenticated(req, res, next) { if (req.isAuthenticated()) { req.authClient = new googleapis.auth.OAuth2(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET); req.authClient.credentials = req.session.googleCredentials; return next(); } res.redirect('/'); }
[ "function", "ensureAuthenticated", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "req", ".", "isAuthenticated", "(", ")", ")", "{", "req", ".", "authClient", "=", "new", "googleapis", ".", "auth", ".", "OAuth2", "(", "GOOGLE_CLIENT_ID", ",", "GOOGLE_CLIENT_SECRET", ")", ";", "req", ".", "authClient", ".", "credentials", "=", "req", ".", "session", ".", "googleCredentials", ";", "return", "next", "(", ")", ";", "}", "res", ".", "redirect", "(", "'/'", ")", ";", "}" ]
Simple route middleware to ensure user is authenticated, use on any protected resource. Also restores the user's Google oauth token from the session, available as req.authClient
[ "Simple", "route", "middleware", "to", "ensure", "user", "is", "authenticated", "use", "on", "any", "protected", "resource", ".", "Also", "restores", "the", "user", "s", "Google", "oauth", "token", "from", "the", "session", "available", "as", "req", ".", "authClient" ]
a1b95150f41f7ccc52c9cb221ab0ec0ccbd4bc08
https://github.com/sqrrrl/passport-google-plus/blob/a1b95150f41f7ccc52c9cb221ab0ec0ccbd4bc08/examples/offline/app.js#L96-L103
train
josemarluedke/ember-cli-segment
app/instance-initializers/segment.js
hasEmberVersion
function hasEmberVersion(major, minor) { const numbers = VERSION.split('-')[0].split('.'); const actualMajor = parseInt(numbers[0], 10); const actualMinor = parseInt(numbers[1], 10); return actualMajor > major || (actualMajor === major && actualMinor >= minor); }
javascript
function hasEmberVersion(major, minor) { const numbers = VERSION.split('-')[0].split('.'); const actualMajor = parseInt(numbers[0], 10); const actualMinor = parseInt(numbers[1], 10); return actualMajor > major || (actualMajor === major && actualMinor >= minor); }
[ "function", "hasEmberVersion", "(", "major", ",", "minor", ")", "{", "const", "numbers", "=", "VERSION", ".", "split", "(", "'-'", ")", "[", "0", "]", ".", "split", "(", "'.'", ")", ";", "const", "actualMajor", "=", "parseInt", "(", "numbers", "[", "0", "]", ",", "10", ")", ";", "const", "actualMinor", "=", "parseInt", "(", "numbers", "[", "1", "]", ",", "10", ")", ";", "return", "actualMajor", ">", "major", "||", "(", "actualMajor", "===", "major", "&&", "actualMinor", ">=", "minor", ")", ";", "}" ]
Taken from ember-test-helpers
[ "Taken", "from", "ember", "-", "test", "-", "helpers" ]
f40210974d0f5a29dd8aa7d0f5973e36a02ab348
https://github.com/josemarluedke/ember-cli-segment/blob/f40210974d0f5a29dd8aa7d0f5973e36a02ab348/app/instance-initializers/segment.js#L4-L9
train
monkeylearn/monkeylearn-node
lib/request.js
chain_requests
function chain_requests(ml, url) { return (batches) => { let promise = new Promise((resolve, reject) => resolve(new MonkeyLearnResponse())); // attach requests for all the batches sequentially to the original promise and return _that_ return batches.reduce((promise, batch) => promise.then((response) => request(ml, { url: url, method: 'POST', body: batch, parse_response: false }) .then(raw_response => { response._add_raw_response(raw_response); return response; }) .catch(error => { if (error.hasOwnProperty('response')) { response._add_raw_response(error.response); error.response = response; } else { // if it's not a MonkeyLearn Error (so, some other js runtime error), // return as-is but add the response // not the cleanest solution but I don't want the error to lose the context error.response = response; error.error_code = ''; } throw error; }) ) , promise) } }
javascript
function chain_requests(ml, url) { return (batches) => { let promise = new Promise((resolve, reject) => resolve(new MonkeyLearnResponse())); // attach requests for all the batches sequentially to the original promise and return _that_ return batches.reduce((promise, batch) => promise.then((response) => request(ml, { url: url, method: 'POST', body: batch, parse_response: false }) .then(raw_response => { response._add_raw_response(raw_response); return response; }) .catch(error => { if (error.hasOwnProperty('response')) { response._add_raw_response(error.response); error.response = response; } else { // if it's not a MonkeyLearn Error (so, some other js runtime error), // return as-is but add the response // not the cleanest solution but I don't want the error to lose the context error.response = response; error.error_code = ''; } throw error; }) ) , promise) } }
[ "function", "chain_requests", "(", "ml", ",", "url", ")", "{", "return", "(", "batches", ")", "=>", "{", "let", "promise", "=", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "resolve", "(", "new", "MonkeyLearnResponse", "(", ")", ")", ")", ";", "return", "batches", ".", "reduce", "(", "(", "promise", ",", "batch", ")", "=>", "promise", ".", "then", "(", "(", "response", ")", "=>", "request", "(", "ml", ",", "{", "url", ":", "url", ",", "method", ":", "'POST'", ",", "body", ":", "batch", ",", "parse_response", ":", "false", "}", ")", ".", "then", "(", "raw_response", "=>", "{", "response", ".", "_add_raw_response", "(", "raw_response", ")", ";", "return", "response", ";", "}", ")", ".", "catch", "(", "error", "=>", "{", "if", "(", "error", ".", "hasOwnProperty", "(", "'response'", ")", ")", "{", "response", ".", "_add_raw_response", "(", "error", ".", "response", ")", ";", "error", ".", "response", "=", "response", ";", "}", "else", "{", "error", ".", "response", "=", "response", ";", "error", ".", "error_code", "=", "''", ";", "}", "throw", "error", ";", "}", ")", ")", ",", "promise", ")", "}", "}" ]
returns a function that takes an array of batches and generates a request for each the requests are done sequentially
[ "returns", "a", "function", "that", "takes", "an", "array", "of", "batches", "and", "generates", "a", "request", "for", "each", "the", "requests", "are", "done", "sequentially" ]
330e87ca69e8ada160cc5c7eac4968d3400061fe
https://github.com/monkeylearn/monkeylearn-node/blob/330e87ca69e8ada160cc5c7eac4968d3400061fe/lib/request.js#L134-L170
train
bigpipe/pagelet
index.js
generator
function generator(n) { if (!n) return Date.now().toString(36).toUpperCase(); return Math.random().toString(36).substring(2, 10).toUpperCase(); }
javascript
function generator(n) { if (!n) return Date.now().toString(36).toUpperCase(); return Math.random().toString(36).substring(2, 10).toUpperCase(); }
[ "function", "generator", "(", "n", ")", "{", "if", "(", "!", "n", ")", "return", "Date", ".", "now", "(", ")", ".", "toString", "(", "36", ")", ".", "toUpperCase", "(", ")", ";", "return", "Math", ".", "random", "(", ")", ".", "toString", "(", "36", ")", ".", "substring", "(", "2", ",", "10", ")", ".", "toUpperCase", "(", ")", ";", "}" ]
Simple helper function to generate some what unique id's for given constructed pagelet. @returns {String} @api private
[ "Simple", "helper", "function", "to", "generate", "some", "what", "unique", "id", "s", "for", "given", "constructed", "pagelet", "." ]
0f39dfddfbeeec556cbd5cff1c2945a6bb334532
https://github.com/bigpipe/pagelet/blob/0f39dfddfbeeec556cbd5cff1c2945a6bb334532/index.js#L32-L35
train
bigpipe/pagelet
index.js
Pagelet
function Pagelet(options) { if (!this) return new Pagelet(options); this.fuse(); options = options || {}; // // Use the temper instance on Pipe if available. // if (options.bigpipe && options.bigpipe._temper) { options.temper = options.bigpipe._temper; } this.writable('_enabled', []); // Contains all enabled pagelets. this.writable('_disabled', []); // Contains all disable pagelets. this.writable('_active', null); // Are we active. this.writable('_req', options.req); // Incoming HTTP request. this.writable('_res', options.res); // Incoming HTTP response. this.writable('_params', options.params); // Params extracted from the route. this.writable('_temper', options.temper); // Attach the Temper instance. this.writable('_bigpipe', options.bigpipe); // Actual pipe instance. this.writable('_bootstrap', options.bootstrap); // Reference to bootstrap Pagelet. this.writable('_append', options.append || false); // Append content client-side. this.writable('debug', debug('pagelet:'+ this.name)); // Namespaced debug method // // Allow overriding the reference to parent pagelet. // A reference to the parent is normally set on the // constructor prototype by optimize. // if (options.parent) this.writable('_parent', options.parent); }
javascript
function Pagelet(options) { if (!this) return new Pagelet(options); this.fuse(); options = options || {}; // // Use the temper instance on Pipe if available. // if (options.bigpipe && options.bigpipe._temper) { options.temper = options.bigpipe._temper; } this.writable('_enabled', []); // Contains all enabled pagelets. this.writable('_disabled', []); // Contains all disable pagelets. this.writable('_active', null); // Are we active. this.writable('_req', options.req); // Incoming HTTP request. this.writable('_res', options.res); // Incoming HTTP response. this.writable('_params', options.params); // Params extracted from the route. this.writable('_temper', options.temper); // Attach the Temper instance. this.writable('_bigpipe', options.bigpipe); // Actual pipe instance. this.writable('_bootstrap', options.bootstrap); // Reference to bootstrap Pagelet. this.writable('_append', options.append || false); // Append content client-side. this.writable('debug', debug('pagelet:'+ this.name)); // Namespaced debug method // // Allow overriding the reference to parent pagelet. // A reference to the parent is normally set on the // constructor prototype by optimize. // if (options.parent) this.writable('_parent', options.parent); }
[ "function", "Pagelet", "(", "options", ")", "{", "if", "(", "!", "this", ")", "return", "new", "Pagelet", "(", "options", ")", ";", "this", ".", "fuse", "(", ")", ";", "options", "=", "options", "||", "{", "}", ";", "if", "(", "options", ".", "bigpipe", "&&", "options", ".", "bigpipe", ".", "_temper", ")", "{", "options", ".", "temper", "=", "options", ".", "bigpipe", ".", "_temper", ";", "}", "this", ".", "writable", "(", "'_enabled'", ",", "[", "]", ")", ";", "this", ".", "writable", "(", "'_disabled'", ",", "[", "]", ")", ";", "this", ".", "writable", "(", "'_active'", ",", "null", ")", ";", "this", ".", "writable", "(", "'_req'", ",", "options", ".", "req", ")", ";", "this", ".", "writable", "(", "'_res'", ",", "options", ".", "res", ")", ";", "this", ".", "writable", "(", "'_params'", ",", "options", ".", "params", ")", ";", "this", ".", "writable", "(", "'_temper'", ",", "options", ".", "temper", ")", ";", "this", ".", "writable", "(", "'_bigpipe'", ",", "options", ".", "bigpipe", ")", ";", "this", ".", "writable", "(", "'_bootstrap'", ",", "options", ".", "bootstrap", ")", ";", "this", ".", "writable", "(", "'_append'", ",", "options", ".", "append", "||", "false", ")", ";", "this", ".", "writable", "(", "'debug'", ",", "debug", "(", "'pagelet:'", "+", "this", ".", "name", ")", ")", ";", "if", "(", "options", ".", "parent", ")", "this", ".", "writable", "(", "'_parent'", ",", "options", ".", "parent", ")", ";", "}" ]
A pagelet is the representation of an item, section, column or widget. It's basically a small sandboxed application within your application. @constructor @param {Object} options Optional configuration. @api public
[ "A", "pagelet", "is", "the", "representation", "of", "an", "item", "section", "column", "or", "widget", ".", "It", "s", "basically", "a", "small", "sandboxed", "application", "within", "your", "application", "." ]
0f39dfddfbeeec556cbd5cff1c2945a6bb334532
https://github.com/bigpipe/pagelet/blob/0f39dfddfbeeec556cbd5cff1c2945a6bb334532/index.js#L45-L77
train
bigpipe/pagelet
index.js
fragment
function fragment(content) { var active = pagelet.active; if (!active) content = ''; if (mode === 'sync') return fn.call(context, undefined, content); data.id = data.id || pagelet.id; // Pagelet id. data.path = data.path || pagelet.path; // Reference to the path. data.mode = data.mode || pagelet.mode; // Pagelet render mode. data.remove = active ? false : pagelet.remove; // Remove from DOM. data.parent = pagelet._parent; // Send parent name along. data.append = pagelet._append; // Content should be appended. data.remaining = pagelet.bootstrap.length; // Remaining pagelets number. data.hash = { // Temper md5's for template ref error: temper.fetch(pagelet.error).hash.client, client: temper.fetch(pagelet.view).hash.client }; fn.call(context, undefined, framework.get('fragment', { template: content.replace(/<!--(.|\s)*?-->/, ''), name: pagelet.name, id: pagelet.id, state: state, data: data })); return pagelet; }
javascript
function fragment(content) { var active = pagelet.active; if (!active) content = ''; if (mode === 'sync') return fn.call(context, undefined, content); data.id = data.id || pagelet.id; // Pagelet id. data.path = data.path || pagelet.path; // Reference to the path. data.mode = data.mode || pagelet.mode; // Pagelet render mode. data.remove = active ? false : pagelet.remove; // Remove from DOM. data.parent = pagelet._parent; // Send parent name along. data.append = pagelet._append; // Content should be appended. data.remaining = pagelet.bootstrap.length; // Remaining pagelets number. data.hash = { // Temper md5's for template ref error: temper.fetch(pagelet.error).hash.client, client: temper.fetch(pagelet.view).hash.client }; fn.call(context, undefined, framework.get('fragment', { template: content.replace(/<!--(.|\s)*?-->/, ''), name: pagelet.name, id: pagelet.id, state: state, data: data })); return pagelet; }
[ "function", "fragment", "(", "content", ")", "{", "var", "active", "=", "pagelet", ".", "active", ";", "if", "(", "!", "active", ")", "content", "=", "''", ";", "if", "(", "mode", "===", "'sync'", ")", "return", "fn", ".", "call", "(", "context", ",", "undefined", ",", "content", ")", ";", "data", ".", "id", "=", "data", ".", "id", "||", "pagelet", ".", "id", ";", "data", ".", "path", "=", "data", ".", "path", "||", "pagelet", ".", "path", ";", "data", ".", "mode", "=", "data", ".", "mode", "||", "pagelet", ".", "mode", ";", "data", ".", "remove", "=", "active", "?", "false", ":", "pagelet", ".", "remove", ";", "data", ".", "parent", "=", "pagelet", ".", "_parent", ";", "data", ".", "append", "=", "pagelet", ".", "_append", ";", "data", ".", "remaining", "=", "pagelet", ".", "bootstrap", ".", "length", ";", "data", ".", "hash", "=", "{", "error", ":", "temper", ".", "fetch", "(", "pagelet", ".", "error", ")", ".", "hash", ".", "client", ",", "client", ":", "temper", ".", "fetch", "(", "pagelet", ".", "view", ")", ".", "hash", ".", "client", "}", ";", "fn", ".", "call", "(", "context", ",", "undefined", ",", "framework", ".", "get", "(", "'fragment'", ",", "{", "template", ":", "content", ".", "replace", "(", "/", "<!--(.|\\s)*?", "/", ",", "''", ")", ",", "name", ":", "pagelet", ".", "name", ",", "id", ":", "pagelet", ".", "id", ",", "state", ":", "state", ",", "data", ":", "data", "}", ")", ")", ";", "return", "pagelet", ";", "}" ]
Write the fragmented data. @param {String} content The content to respond with. @returns {Pagelet} @api private
[ "Write", "the", "fragmented", "data", "." ]
0f39dfddfbeeec556cbd5cff1c2945a6bb334532
https://github.com/bigpipe/pagelet/blob/0f39dfddfbeeec556cbd5cff1c2945a6bb334532/index.js#L796-L823
train
bigpipe/pagelet
index.js
optimizer
function optimizer(Pagelet, next) { var prototype = Pagelet.prototype , method = prototype.method , status = prototype.status , router = prototype.path , name = prototype.name , view = prototype.view , log = debug('pagelet:'+ name); // // Generate a unique ID used for real time connection lookups. // prototype.id = options.id || [0, 1, 1, 1].map(generator).join('-'); // // Parse the methods to an array of accepted HTTP methods. We'll only accept // these requests and should deny every other possible method. // log('Optimizing pagelet'); if (!Array.isArray(method)) method = method.split(/[\s\,]+?/); Pagelet.method = method.filter(Boolean).map(function transformation(method) { return method.toUpperCase(); }); // // Add the actual HTTP route and available HTTP methods. // if (router) { log('Instantiating router for path %s', router); Pagelet.router = new Route(router); } // // Prefetch the template if a view is available. The view property is // mandatory for all pagelets except the bootstrap Pagelet or if the // Pagelet is just doing a redirect. We can resolve this edge case by // checking if statusCode is in the 300~ range. // if (!view && name !== 'bootstrap' && !(status >= 300 && status < 400)) return next( new Error('The '+ name +' pagelet should have a .view property.') ); // // Resolve the view to ensure the path is correct and prefetch // the template through Temper. // if (view) { prototype.view = view = path.resolve(prototype.directory, view); temper.prefetch(view, prototype.engine); } // // Ensure we have a custom error pagelet when we fail to render this fragment. // if (prototype.error) { temper.prefetch(prototype.error, path.extname(prototype.error).slice(1)); } // // Map all dependencies to an absolute path or URL. // helpers.resolve(Pagelet, ['css', 'js', 'dependencies']); // // Find all child pagelets and optimize the found children. // async.map(Pagelet.children(name), function map(Child, step) { if (Array.isArray(Child)) return async.map(Child, map, step); Child.optimize({ temper: temper, bigpipe: bigpipe, transform: { before: bigpipe.emits && bigpipe.emits('transform:pagelet:before'), after: bigpipe.emits && bigpipe.emits('transform:pagelet:after') } }, step); }, function optimized(error, children) { log('optimized all %d child pagelets', children.length); if (error) return next(error); // // Store the optimized children on the prototype, wrapping the Pagelet // in an array makes it a lot easier to work with conditional Pagelets. // prototype._children = children.map(function map(Pagelet) { return Array.isArray(Pagelet) ? Pagelet : [Pagelet]; }); // // Always return a reference to the parent Pagelet. // Otherwise the stack of parents would be infested // with children returned by this async.map. // next(null, Pagelet); }); }
javascript
function optimizer(Pagelet, next) { var prototype = Pagelet.prototype , method = prototype.method , status = prototype.status , router = prototype.path , name = prototype.name , view = prototype.view , log = debug('pagelet:'+ name); // // Generate a unique ID used for real time connection lookups. // prototype.id = options.id || [0, 1, 1, 1].map(generator).join('-'); // // Parse the methods to an array of accepted HTTP methods. We'll only accept // these requests and should deny every other possible method. // log('Optimizing pagelet'); if (!Array.isArray(method)) method = method.split(/[\s\,]+?/); Pagelet.method = method.filter(Boolean).map(function transformation(method) { return method.toUpperCase(); }); // // Add the actual HTTP route and available HTTP methods. // if (router) { log('Instantiating router for path %s', router); Pagelet.router = new Route(router); } // // Prefetch the template if a view is available. The view property is // mandatory for all pagelets except the bootstrap Pagelet or if the // Pagelet is just doing a redirect. We can resolve this edge case by // checking if statusCode is in the 300~ range. // if (!view && name !== 'bootstrap' && !(status >= 300 && status < 400)) return next( new Error('The '+ name +' pagelet should have a .view property.') ); // // Resolve the view to ensure the path is correct and prefetch // the template through Temper. // if (view) { prototype.view = view = path.resolve(prototype.directory, view); temper.prefetch(view, prototype.engine); } // // Ensure we have a custom error pagelet when we fail to render this fragment. // if (prototype.error) { temper.prefetch(prototype.error, path.extname(prototype.error).slice(1)); } // // Map all dependencies to an absolute path or URL. // helpers.resolve(Pagelet, ['css', 'js', 'dependencies']); // // Find all child pagelets and optimize the found children. // async.map(Pagelet.children(name), function map(Child, step) { if (Array.isArray(Child)) return async.map(Child, map, step); Child.optimize({ temper: temper, bigpipe: bigpipe, transform: { before: bigpipe.emits && bigpipe.emits('transform:pagelet:before'), after: bigpipe.emits && bigpipe.emits('transform:pagelet:after') } }, step); }, function optimized(error, children) { log('optimized all %d child pagelets', children.length); if (error) return next(error); // // Store the optimized children on the prototype, wrapping the Pagelet // in an array makes it a lot easier to work with conditional Pagelets. // prototype._children = children.map(function map(Pagelet) { return Array.isArray(Pagelet) ? Pagelet : [Pagelet]; }); // // Always return a reference to the parent Pagelet. // Otherwise the stack of parents would be infested // with children returned by this async.map. // next(null, Pagelet); }); }
[ "function", "optimizer", "(", "Pagelet", ",", "next", ")", "{", "var", "prototype", "=", "Pagelet", ".", "prototype", ",", "method", "=", "prototype", ".", "method", ",", "status", "=", "prototype", ".", "status", ",", "router", "=", "prototype", ".", "path", ",", "name", "=", "prototype", ".", "name", ",", "view", "=", "prototype", ".", "view", ",", "log", "=", "debug", "(", "'pagelet:'", "+", "name", ")", ";", "prototype", ".", "id", "=", "options", ".", "id", "||", "[", "0", ",", "1", ",", "1", ",", "1", "]", ".", "map", "(", "generator", ")", ".", "join", "(", "'-'", ")", ";", "log", "(", "'Optimizing pagelet'", ")", ";", "if", "(", "!", "Array", ".", "isArray", "(", "method", ")", ")", "method", "=", "method", ".", "split", "(", "/", "[\\s\\,]+?", "/", ")", ";", "Pagelet", ".", "method", "=", "method", ".", "filter", "(", "Boolean", ")", ".", "map", "(", "function", "transformation", "(", "method", ")", "{", "return", "method", ".", "toUpperCase", "(", ")", ";", "}", ")", ";", "if", "(", "router", ")", "{", "log", "(", "'Instantiating router for path %s'", ",", "router", ")", ";", "Pagelet", ".", "router", "=", "new", "Route", "(", "router", ")", ";", "}", "if", "(", "!", "view", "&&", "name", "!==", "'bootstrap'", "&&", "!", "(", "status", ">=", "300", "&&", "status", "<", "400", ")", ")", "return", "next", "(", "new", "Error", "(", "'The '", "+", "name", "+", "' pagelet should have a .view property.'", ")", ")", ";", "if", "(", "view", ")", "{", "prototype", ".", "view", "=", "view", "=", "path", ".", "resolve", "(", "prototype", ".", "directory", ",", "view", ")", ";", "temper", ".", "prefetch", "(", "view", ",", "prototype", ".", "engine", ")", ";", "}", "if", "(", "prototype", ".", "error", ")", "{", "temper", ".", "prefetch", "(", "prototype", ".", "error", ",", "path", ".", "extname", "(", "prototype", ".", "error", ")", ".", "slice", "(", "1", ")", ")", ";", "}", "helpers", ".", "resolve", "(", "Pagelet", ",", "[", "'css'", ",", "'js'", ",", "'dependencies'", "]", ")", ";", "async", ".", "map", "(", "Pagelet", ".", "children", "(", "name", ")", ",", "function", "map", "(", "Child", ",", "step", ")", "{", "if", "(", "Array", ".", "isArray", "(", "Child", ")", ")", "return", "async", ".", "map", "(", "Child", ",", "map", ",", "step", ")", ";", "Child", ".", "optimize", "(", "{", "temper", ":", "temper", ",", "bigpipe", ":", "bigpipe", ",", "transform", ":", "{", "before", ":", "bigpipe", ".", "emits", "&&", "bigpipe", ".", "emits", "(", "'transform:pagelet:before'", ")", ",", "after", ":", "bigpipe", ".", "emits", "&&", "bigpipe", ".", "emits", "(", "'transform:pagelet:after'", ")", "}", "}", ",", "step", ")", ";", "}", ",", "function", "optimized", "(", "error", ",", "children", ")", "{", "log", "(", "'optimized all %d child pagelets'", ",", "children", ".", "length", ")", ";", "if", "(", "error", ")", "return", "next", "(", "error", ")", ";", "prototype", ".", "_children", "=", "children", ".", "map", "(", "function", "map", "(", "Pagelet", ")", "{", "return", "Array", ".", "isArray", "(", "Pagelet", ")", "?", "Pagelet", ":", "[", "Pagelet", "]", ";", "}", ")", ";", "next", "(", "null", ",", "Pagelet", ")", ";", "}", ")", ";", "}" ]
Optimize the pagelet. This function is called by default as part of the async stack. @param {Function} next Completion callback @api private
[ "Optimize", "the", "pagelet", ".", "This", "function", "is", "called", "by", "default", "as", "part", "of", "the", "async", "stack", "." ]
0f39dfddfbeeec556cbd5cff1c2945a6bb334532
https://github.com/bigpipe/pagelet/blob/0f39dfddfbeeec556cbd5cff1c2945a6bb334532/index.js#L1098-L1195
train
demipel8/craftymatter
src/debug.js
worldDebug
function worldDebug() { Crafty.e( RenderingMode + ', Color' ) .attr( { x: engine.world.bounds.min.x, y: engine.world.bounds.min.y, w: engine.world.bounds.max.x - engine.world.bounds.min.x, h: engine.world.bounds.max.y - engine.world.bounds.min.y, alpha: 0.5 } ) .color( 'green' ); }
javascript
function worldDebug() { Crafty.e( RenderingMode + ', Color' ) .attr( { x: engine.world.bounds.min.x, y: engine.world.bounds.min.y, w: engine.world.bounds.max.x - engine.world.bounds.min.x, h: engine.world.bounds.max.y - engine.world.bounds.min.y, alpha: 0.5 } ) .color( 'green' ); }
[ "function", "worldDebug", "(", ")", "{", "Crafty", ".", "e", "(", "RenderingMode", "+", "', Color'", ")", ".", "attr", "(", "{", "x", ":", "engine", ".", "world", ".", "bounds", ".", "min", ".", "x", ",", "y", ":", "engine", ".", "world", ".", "bounds", ".", "min", ".", "y", ",", "w", ":", "engine", ".", "world", ".", "bounds", ".", "max", ".", "x", "-", "engine", ".", "world", ".", "bounds", ".", "min", ".", "x", ",", "h", ":", "engine", ".", "world", ".", "bounds", ".", "max", ".", "y", "-", "engine", ".", "world", ".", "bounds", ".", "min", ".", "y", ",", "alpha", ":", "0.5", "}", ")", ".", "color", "(", "'green'", ")", ";", "}" ]
Creates a rectangle filling the Matter world area
[ "Creates", "a", "rectangle", "filling", "the", "Matter", "world", "area" ]
1e05a855f5993e4eb234d811620f634ef94ab2b0
https://github.com/demipel8/craftymatter/blob/1e05a855f5993e4eb234d811620f634ef94ab2b0/src/debug.js#L6-L16
train
demipel8/craftymatter
build/craftymatter.js
function( options, part, isSleeping ) { var entity = part.entity; if ( options.showSleeping && isSleeping ) { entity.alpha = 0.5; } if ( entity._x !== part.position.x - ( entity._w / 2 ) ) { entity.matterMoved = true; entity.x = part.position.x - ( entity._w / 2 ); } if ( entity._y !== part.position.y - ( entity._h / 2 ) ) { entity.matterMoved = true; entity.y = part.position.y - ( entity._h / 2 ); } debug.moveEntity( entity ); _rotateEntity( entity, part.angle ); }
javascript
function( options, part, isSleeping ) { var entity = part.entity; if ( options.showSleeping && isSleeping ) { entity.alpha = 0.5; } if ( entity._x !== part.position.x - ( entity._w / 2 ) ) { entity.matterMoved = true; entity.x = part.position.x - ( entity._w / 2 ); } if ( entity._y !== part.position.y - ( entity._h / 2 ) ) { entity.matterMoved = true; entity.y = part.position.y - ( entity._h / 2 ); } debug.moveEntity( entity ); _rotateEntity( entity, part.angle ); }
[ "function", "(", "options", ",", "part", ",", "isSleeping", ")", "{", "var", "entity", "=", "part", ".", "entity", ";", "if", "(", "options", ".", "showSleeping", "&&", "isSleeping", ")", "{", "entity", ".", "alpha", "=", "0.5", ";", "}", "if", "(", "entity", ".", "_x", "!==", "part", ".", "position", ".", "x", "-", "(", "entity", ".", "_w", "/", "2", ")", ")", "{", "entity", ".", "matterMoved", "=", "true", ";", "entity", ".", "x", "=", "part", ".", "position", ".", "x", "-", "(", "entity", ".", "_w", "/", "2", ")", ";", "}", "if", "(", "entity", ".", "_y", "!==", "part", ".", "position", ".", "y", "-", "(", "entity", ".", "_h", "/", "2", ")", ")", "{", "entity", ".", "matterMoved", "=", "true", ";", "entity", ".", "y", "=", "part", ".", "position", ".", "y", "-", "(", "entity", ".", "_h", "/", "2", ")", ";", "}", "debug", ".", "moveEntity", "(", "entity", ")", ";", "_rotateEntity", "(", "entity", ",", "part", ".", "angle", ")", ";", "}" ]
Moves an entity according to matter calculations @param {object} options engine.options @param {object} part part to be moved @param {Boolean} isSleeping
[ "Moves", "an", "entity", "according", "to", "matter", "calculations" ]
1e05a855f5993e4eb234d811620f634ef94ab2b0
https://github.com/demipel8/craftymatter/blob/1e05a855f5993e4eb234d811620f634ef94ab2b0/build/craftymatter.js#L364-L385
train
demipel8/craftymatter
build/craftymatter.js
function( entity, angle ) { var angleFixed = Crafty.math.radToDeg( angle ).toFixed( 3 ); if ( angle === 0 || entity._rotation === angleFixed ) { return; } entity.matterMoved = true; entity.rotation = angleFixed; debug.rotateEntity( [ entity, angleFixed ] ); }
javascript
function( entity, angle ) { var angleFixed = Crafty.math.radToDeg( angle ).toFixed( 3 ); if ( angle === 0 || entity._rotation === angleFixed ) { return; } entity.matterMoved = true; entity.rotation = angleFixed; debug.rotateEntity( [ entity, angleFixed ] ); }
[ "function", "(", "entity", ",", "angle", ")", "{", "var", "angleFixed", "=", "Crafty", ".", "math", ".", "radToDeg", "(", "angle", ")", ".", "toFixed", "(", "3", ")", ";", "if", "(", "angle", "===", "0", "||", "entity", ".", "_rotation", "===", "angleFixed", ")", "{", "return", ";", "}", "entity", ".", "matterMoved", "=", "true", ";", "entity", ".", "rotation", "=", "angleFixed", ";", "debug", ".", "rotateEntity", "(", "[", "entity", ",", "angleFixed", "]", ")", ";", "}" ]
Initial support only for center origin
[ "Initial", "support", "only", "for", "center", "origin" ]
1e05a855f5993e4eb234d811620f634ef94ab2b0
https://github.com/demipel8/craftymatter/blob/1e05a855f5993e4eb234d811620f634ef94ab2b0/build/craftymatter.js#L388-L400
train
demipel8/craftymatter
build/craftymatter.js
function( pointA, pointB ) { var vector = _getVector( pointA, pointB ); return -Crafty.math.radToDeg( Math.atan2( vector.y, vector.x ) ).toFixed( 3 ); }
javascript
function( pointA, pointB ) { var vector = _getVector( pointA, pointB ); return -Crafty.math.radToDeg( Math.atan2( vector.y, vector.x ) ).toFixed( 3 ); }
[ "function", "(", "pointA", ",", "pointB", ")", "{", "var", "vector", "=", "_getVector", "(", "pointA", ",", "pointB", ")", ";", "return", "-", "Crafty", ".", "math", ".", "radToDeg", "(", "Math", ".", "atan2", "(", "vector", ".", "y", ",", "vector", ".", "x", ")", ")", ".", "toFixed", "(", "3", ")", ";", "}" ]
Calculate the angle between a vector and the x axis @param {Vector} pointA - vector origin @param {Vector} pointB - vector point @return {number} angle between the vector and the x axis
[ "Calculate", "the", "angle", "between", "a", "vector", "and", "the", "x", "axis" ]
1e05a855f5993e4eb234d811620f634ef94ab2b0
https://github.com/demipel8/craftymatter/blob/1e05a855f5993e4eb234d811620f634ef94ab2b0/build/craftymatter.js#L420-L424
train
demipel8/craftymatter
build/craftymatter.js
function( pointA, pointB ) { return { x: pointB.x - pointA.x, y: -( pointB.y - pointA.y ) }; }
javascript
function( pointA, pointB ) { return { x: pointB.x - pointA.x, y: -( pointB.y - pointA.y ) }; }
[ "function", "(", "pointA", ",", "pointB", ")", "{", "return", "{", "x", ":", "pointB", ".", "x", "-", "pointA", ".", "x", ",", "y", ":", "-", "(", "pointB", ".", "y", "-", "pointA", ".", "y", ")", "}", ";", "}" ]
Creates a vector given its origin and destiny points @param {Vector} pointA - vector origin @param {Vector} pointB - vector point @return {Vector} Resulting vector
[ "Creates", "a", "vector", "given", "its", "origin", "and", "destiny", "points" ]
1e05a855f5993e4eb234d811620f634ef94ab2b0
https://github.com/demipel8/craftymatter/blob/1e05a855f5993e4eb234d811620f634ef94ab2b0/build/craftymatter.js#L432-L435
train
monkeylearn/monkeylearn-node
lib/models.js
Models
function Models(ml, base_url) { this.ml = ml; this.base_url = base_url; if (includes(base_url, 'classifiers')) { this.run_action = 'classify'; } else if (includes(base_url, 'extractors')) { this.run_action = 'extract'; } else { this.run_action = undefined; } }
javascript
function Models(ml, base_url) { this.ml = ml; this.base_url = base_url; if (includes(base_url, 'classifiers')) { this.run_action = 'classify'; } else if (includes(base_url, 'extractors')) { this.run_action = 'extract'; } else { this.run_action = undefined; } }
[ "function", "Models", "(", "ml", ",", "base_url", ")", "{", "this", ".", "ml", "=", "ml", ";", "this", ".", "base_url", "=", "base_url", ";", "if", "(", "includes", "(", "base_url", ",", "'classifiers'", ")", ")", "{", "this", ".", "run_action", "=", "'classify'", ";", "}", "else", "if", "(", "includes", "(", "base_url", ",", "'extractors'", ")", ")", "{", "this", ".", "run_action", "=", "'extract'", ";", "}", "else", "{", "this", ".", "run_action", "=", "undefined", ";", "}", "}" ]
base class for endpoints that are in extractors, classifiers and workflows
[ "base", "class", "for", "endpoints", "that", "are", "in", "extractors", "classifiers", "and", "workflows" ]
330e87ca69e8ada160cc5c7eac4968d3400061fe
https://github.com/monkeylearn/monkeylearn-node/blob/330e87ca69e8ada160cc5c7eac4968d3400061fe/lib/models.js#L19-L30
train
josdejong/rws
lib/ReconnectingWebSocket.js
ReconnectingWebSocket
function ReconnectingWebSocket (url, options) { var me = this; this.id = options && options.id || randomUUID(); this.url = url + '/?id=' + this.id; this.socket = null; this.opened = false; this.closed = false; this.options = { reconnectTimeout: Infinity, // ms reconnectInterval: 5000 // ms //reconnectDecay: 2 // TODO: reconnect decay }; // copy the options if (options) { if ('reconnectTimeout' in options) this.options.reconnectTimeout = options.reconnectTimeout; if ('reconnectInterval' in options) this.options.reconnectInterval = options.reconnectInterval; } this.queue = []; this.attempts = 0; this.reconnectTimer = null; function connect() { me.socket = new WebSocket(me.url); me.socket.onmessage = function (event) { me.onmessage(event); }; me.socket.onerror = function (error) { if (me.socket.readyState === WebSocket.OPEN) { me.onerror(error); } else { reconnect(); } }; me.socket.onopen = function (event) { // reset the number of connection attempts me.attempts = 0; // emit events if (!me.opened) { me.onopen(event); me.opened = true; } else { me.onreconnect(event); } // flush all messages in the queue (if any) //console.log('flush messages ' + me.queue); while (me.queue.length > 0) { var data = me.queue.shift(); me.socket.send(data); } }; me.socket.onclose = function (event) { if (me.closed) { me.onclose(event); } else { // start auto-reconnect attempts reconnect(); } } } function reconnect() { // check whether already reconnecting if (me.reconnectTimer) { return; } me.attempts++; if (me.attempts < me.options.reconnectTimeout / me.options.reconnectInterval) { me.reconnectTimer = setTimeout(function () { me.reconnectTimer = null; connect(); }, me.options.reconnectInterval); } else { // no luck, let's give up... me.close(); } } connect(); }
javascript
function ReconnectingWebSocket (url, options) { var me = this; this.id = options && options.id || randomUUID(); this.url = url + '/?id=' + this.id; this.socket = null; this.opened = false; this.closed = false; this.options = { reconnectTimeout: Infinity, // ms reconnectInterval: 5000 // ms //reconnectDecay: 2 // TODO: reconnect decay }; // copy the options if (options) { if ('reconnectTimeout' in options) this.options.reconnectTimeout = options.reconnectTimeout; if ('reconnectInterval' in options) this.options.reconnectInterval = options.reconnectInterval; } this.queue = []; this.attempts = 0; this.reconnectTimer = null; function connect() { me.socket = new WebSocket(me.url); me.socket.onmessage = function (event) { me.onmessage(event); }; me.socket.onerror = function (error) { if (me.socket.readyState === WebSocket.OPEN) { me.onerror(error); } else { reconnect(); } }; me.socket.onopen = function (event) { // reset the number of connection attempts me.attempts = 0; // emit events if (!me.opened) { me.onopen(event); me.opened = true; } else { me.onreconnect(event); } // flush all messages in the queue (if any) //console.log('flush messages ' + me.queue); while (me.queue.length > 0) { var data = me.queue.shift(); me.socket.send(data); } }; me.socket.onclose = function (event) { if (me.closed) { me.onclose(event); } else { // start auto-reconnect attempts reconnect(); } } } function reconnect() { // check whether already reconnecting if (me.reconnectTimer) { return; } me.attempts++; if (me.attempts < me.options.reconnectTimeout / me.options.reconnectInterval) { me.reconnectTimer = setTimeout(function () { me.reconnectTimer = null; connect(); }, me.options.reconnectInterval); } else { // no luck, let's give up... me.close(); } } connect(); }
[ "function", "ReconnectingWebSocket", "(", "url", ",", "options", ")", "{", "var", "me", "=", "this", ";", "this", ".", "id", "=", "options", "&&", "options", ".", "id", "||", "randomUUID", "(", ")", ";", "this", ".", "url", "=", "url", "+", "'/?id='", "+", "this", ".", "id", ";", "this", ".", "socket", "=", "null", ";", "this", ".", "opened", "=", "false", ";", "this", ".", "closed", "=", "false", ";", "this", ".", "options", "=", "{", "reconnectTimeout", ":", "Infinity", ",", "reconnectInterval", ":", "5000", "}", ";", "if", "(", "options", ")", "{", "if", "(", "'reconnectTimeout'", "in", "options", ")", "this", ".", "options", ".", "reconnectTimeout", "=", "options", ".", "reconnectTimeout", ";", "if", "(", "'reconnectInterval'", "in", "options", ")", "this", ".", "options", ".", "reconnectInterval", "=", "options", ".", "reconnectInterval", ";", "}", "this", ".", "queue", "=", "[", "]", ";", "this", ".", "attempts", "=", "0", ";", "this", ".", "reconnectTimer", "=", "null", ";", "function", "connect", "(", ")", "{", "me", ".", "socket", "=", "new", "WebSocket", "(", "me", ".", "url", ")", ";", "me", ".", "socket", ".", "onmessage", "=", "function", "(", "event", ")", "{", "me", ".", "onmessage", "(", "event", ")", ";", "}", ";", "me", ".", "socket", ".", "onerror", "=", "function", "(", "error", ")", "{", "if", "(", "me", ".", "socket", ".", "readyState", "===", "WebSocket", ".", "OPEN", ")", "{", "me", ".", "onerror", "(", "error", ")", ";", "}", "else", "{", "reconnect", "(", ")", ";", "}", "}", ";", "me", ".", "socket", ".", "onopen", "=", "function", "(", "event", ")", "{", "me", ".", "attempts", "=", "0", ";", "if", "(", "!", "me", ".", "opened", ")", "{", "me", ".", "onopen", "(", "event", ")", ";", "me", ".", "opened", "=", "true", ";", "}", "else", "{", "me", ".", "onreconnect", "(", "event", ")", ";", "}", "while", "(", "me", ".", "queue", ".", "length", ">", "0", ")", "{", "var", "data", "=", "me", ".", "queue", ".", "shift", "(", ")", ";", "me", ".", "socket", ".", "send", "(", "data", ")", ";", "}", "}", ";", "me", ".", "socket", ".", "onclose", "=", "function", "(", "event", ")", "{", "if", "(", "me", ".", "closed", ")", "{", "me", ".", "onclose", "(", "event", ")", ";", "}", "else", "{", "reconnect", "(", ")", ";", "}", "}", "}", "function", "reconnect", "(", ")", "{", "if", "(", "me", ".", "reconnectTimer", ")", "{", "return", ";", "}", "me", ".", "attempts", "++", ";", "if", "(", "me", ".", "attempts", "<", "me", ".", "options", ".", "reconnectTimeout", "/", "me", ".", "options", ".", "reconnectInterval", ")", "{", "me", ".", "reconnectTimer", "=", "setTimeout", "(", "function", "(", ")", "{", "me", ".", "reconnectTimer", "=", "null", ";", "connect", "(", ")", ";", "}", ",", "me", ".", "options", ".", "reconnectInterval", ")", ";", "}", "else", "{", "me", ".", "close", "(", ")", ";", "}", "}", "connect", "(", ")", ";", "}" ]
An automatically reconnecting WebSocket connection @param {string} url @param {Object} options Available options: - id: number | string An optional identifier for the server to be able to identify clients. After connection, the client will send a message {method: 'greeting', id: id} - reconnectInterval: number Reconnect interval in milliseconds - reconnectInterval: number Reconnect interval in milliseconds @constructor
[ "An", "automatically", "reconnecting", "WebSocket", "connection" ]
9ff4af1073ce4d03ff939ba32c2f6dae16dc7e59
https://github.com/josdejong/rws/blob/9ff4af1073ce4d03ff939ba32c2f6dae16dc7e59/lib/ReconnectingWebSocket.js#L15-L110
train
sqrrrl/passport-google-plus
lib/jwt.js
function(jwt) { try { var segments = jwt.split('.'); this.signature = segments.pop(); this.signatureBase = segments.join('.'); this.header = decodeSegment(segments.shift()); this.payload = decodeSegment(segments.shift()); } catch (e) { throw new Error("Unable to parse JWT"); } }
javascript
function(jwt) { try { var segments = jwt.split('.'); this.signature = segments.pop(); this.signatureBase = segments.join('.'); this.header = decodeSegment(segments.shift()); this.payload = decodeSegment(segments.shift()); } catch (e) { throw new Error("Unable to parse JWT"); } }
[ "function", "(", "jwt", ")", "{", "try", "{", "var", "segments", "=", "jwt", ".", "split", "(", "'.'", ")", ";", "this", ".", "signature", "=", "segments", ".", "pop", "(", ")", ";", "this", ".", "signatureBase", "=", "segments", ".", "join", "(", "'.'", ")", ";", "this", ".", "header", "=", "decodeSegment", "(", "segments", ".", "shift", "(", ")", ")", ";", "this", ".", "payload", "=", "decodeSegment", "(", "segments", ".", "shift", "(", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "Error", "(", "\"Unable to parse JWT\"", ")", ";", "}", "}" ]
Parse an encoded JWT. Does not ensure validaty of the token. @constructor @param {String} jwt Encoded JWT
[ "Parse", "an", "encoded", "JWT", ".", "Does", "not", "ensure", "validaty", "of", "the", "token", "." ]
a1b95150f41f7ccc52c9cb221ab0ec0ccbd4bc08
https://github.com/sqrrrl/passport-google-plus/blob/a1b95150f41f7ccc52c9cb221ab0ec0ccbd4bc08/lib/jwt.js#L37-L47
train
zont/gulp-bower
index.js
gulpBower
function gulpBower(opts, cmdArguments) { opts = parseOptions(opts); log.info('Using cwd: ' + opts.cwd); log.info('Using bower dir: ' + opts.directory); cmdArguments = createCmdArguments(cmdArguments, opts); var bowerCommand = getBowerCommand(cmd); var stream = through.obj(function (file, enc, callback) { this.push(file); callback(); }); bowerCommand.apply(bower.commands, cmdArguments) .on('log', function (result) { log.info(['bower', colors.cyan(result.id), result.message].join(' ')); }) .on('prompt', function (prompts, callback) { if (enablePrompt === true) { inquirer.prompt(prompts, callback); } else { var error = 'Can\'t resolve suitable dependency version.'; log.error(error); log.error('Set option { interactive: true } to select.'); throw new PluginError(PLUGIN_NAME, error); } }) .on('error', function (error) { stream.emit('error', new PluginError(PLUGIN_NAME, error)); stream.emit('end'); }) .on('end', function () { writeStreamToFs(opts, stream); }); return stream; }
javascript
function gulpBower(opts, cmdArguments) { opts = parseOptions(opts); log.info('Using cwd: ' + opts.cwd); log.info('Using bower dir: ' + opts.directory); cmdArguments = createCmdArguments(cmdArguments, opts); var bowerCommand = getBowerCommand(cmd); var stream = through.obj(function (file, enc, callback) { this.push(file); callback(); }); bowerCommand.apply(bower.commands, cmdArguments) .on('log', function (result) { log.info(['bower', colors.cyan(result.id), result.message].join(' ')); }) .on('prompt', function (prompts, callback) { if (enablePrompt === true) { inquirer.prompt(prompts, callback); } else { var error = 'Can\'t resolve suitable dependency version.'; log.error(error); log.error('Set option { interactive: true } to select.'); throw new PluginError(PLUGIN_NAME, error); } }) .on('error', function (error) { stream.emit('error', new PluginError(PLUGIN_NAME, error)); stream.emit('end'); }) .on('end', function () { writeStreamToFs(opts, stream); }); return stream; }
[ "function", "gulpBower", "(", "opts", ",", "cmdArguments", ")", "{", "opts", "=", "parseOptions", "(", "opts", ")", ";", "log", ".", "info", "(", "'Using cwd: '", "+", "opts", ".", "cwd", ")", ";", "log", ".", "info", "(", "'Using bower dir: '", "+", "opts", ".", "directory", ")", ";", "cmdArguments", "=", "createCmdArguments", "(", "cmdArguments", ",", "opts", ")", ";", "var", "bowerCommand", "=", "getBowerCommand", "(", "cmd", ")", ";", "var", "stream", "=", "through", ".", "obj", "(", "function", "(", "file", ",", "enc", ",", "callback", ")", "{", "this", ".", "push", "(", "file", ")", ";", "callback", "(", ")", ";", "}", ")", ";", "bowerCommand", ".", "apply", "(", "bower", ".", "commands", ",", "cmdArguments", ")", ".", "on", "(", "'log'", ",", "function", "(", "result", ")", "{", "log", ".", "info", "(", "[", "'bower'", ",", "colors", ".", "cyan", "(", "result", ".", "id", ")", ",", "result", ".", "message", "]", ".", "join", "(", "' '", ")", ")", ";", "}", ")", ".", "on", "(", "'prompt'", ",", "function", "(", "prompts", ",", "callback", ")", "{", "if", "(", "enablePrompt", "===", "true", ")", "{", "inquirer", ".", "prompt", "(", "prompts", ",", "callback", ")", ";", "}", "else", "{", "var", "error", "=", "'Can\\'t resolve suitable dependency version.'", ";", "\\'", "log", ".", "error", "(", "error", ")", ";", "log", ".", "error", "(", "'Set option { interactive: true } to select.'", ")", ";", "}", "}", ")", ".", "throw", "new", "PluginError", "(", "PLUGIN_NAME", ",", "error", ")", ";", "on", ".", "(", "'error'", ",", "function", "(", "error", ")", "{", "stream", ".", "emit", "(", "'error'", ",", "new", "PluginError", "(", "PLUGIN_NAME", ",", "error", ")", ")", ";", "stream", ".", "emit", "(", "'end'", ")", ";", "}", ")", "on", ";", "(", "'end'", ",", "function", "(", ")", "{", "writeStreamToFs", "(", "opts", ",", "stream", ")", ";", "}", ")", "}" ]
Gulp bower plugin @param {(object | string)} opts options object or directory string, see opts.directory @param {string} opts.cmd bower command (default: install) @param {string} opts.cwd current working directory (default: process.cwd()) @param {string} opts.directory bower components directory (default: .bowerrc config or 'bower_components') @param {boolean} opts.interactive enable prompting from bower (default: false) @param {number} opts.verbosity set logging level from 0 (no output) to 2 for info (default: 2)
[ "Gulp", "bower", "plugin" ]
48c31b718ee5d9ab5c9dac58d100bb662a99173a
https://github.com/zont/gulp-bower/blob/48c31b718ee5d9ab5c9dac58d100bb662a99173a/index.js#L56-L93
train
zont/gulp-bower
index.js
parseOptions
function parseOptions(opts) { opts = opts || {}; if (toString.call(opts) === '[object String]') { opts = { directory: opts }; } opts.cwd = opts.cwd || process.cwd(); log.verbosity = toString.call(opts.verbosity) === '[object Number]' ? opts.verbosity : DEFAULT_VERBOSITY; delete (opts.verbosity); cmd = opts.cmd || DEFAULT_CMD; delete (opts.cmd); // enable bower prompting but ignore the actual prompt if interactive == false enablePrompt = opts.interactive || DEFAULT_INTERACTIVE; opts.interactive = true; if (!opts.directory) { opts.directory = getDirectoryFromBowerRc(opts.cwd) || DEFAULT_DIRECTORY; } return opts; }
javascript
function parseOptions(opts) { opts = opts || {}; if (toString.call(opts) === '[object String]') { opts = { directory: opts }; } opts.cwd = opts.cwd || process.cwd(); log.verbosity = toString.call(opts.verbosity) === '[object Number]' ? opts.verbosity : DEFAULT_VERBOSITY; delete (opts.verbosity); cmd = opts.cmd || DEFAULT_CMD; delete (opts.cmd); // enable bower prompting but ignore the actual prompt if interactive == false enablePrompt = opts.interactive || DEFAULT_INTERACTIVE; opts.interactive = true; if (!opts.directory) { opts.directory = getDirectoryFromBowerRc(opts.cwd) || DEFAULT_DIRECTORY; } return opts; }
[ "function", "parseOptions", "(", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "if", "(", "toString", ".", "call", "(", "opts", ")", "===", "'[object String]'", ")", "{", "opts", "=", "{", "directory", ":", "opts", "}", ";", "}", "opts", ".", "cwd", "=", "opts", ".", "cwd", "||", "process", ".", "cwd", "(", ")", ";", "log", ".", "verbosity", "=", "toString", ".", "call", "(", "opts", ".", "verbosity", ")", "===", "'[object Number]'", "?", "opts", ".", "verbosity", ":", "DEFAULT_VERBOSITY", ";", "delete", "(", "opts", ".", "verbosity", ")", ";", "cmd", "=", "opts", ".", "cmd", "||", "DEFAULT_CMD", ";", "delete", "(", "opts", ".", "cmd", ")", ";", "enablePrompt", "=", "opts", ".", "interactive", "||", "DEFAULT_INTERACTIVE", ";", "opts", ".", "interactive", "=", "true", ";", "if", "(", "!", "opts", ".", "directory", ")", "{", "opts", ".", "directory", "=", "getDirectoryFromBowerRc", "(", "opts", ".", "cwd", ")", "||", "DEFAULT_DIRECTORY", ";", "}", "return", "opts", ";", "}" ]
Parse plugin options @param {object | string} opts options object or directory string
[ "Parse", "plugin", "options" ]
48c31b718ee5d9ab5c9dac58d100bb662a99173a
https://github.com/zont/gulp-bower/blob/48c31b718ee5d9ab5c9dac58d100bb662a99173a/index.js#L100-L125
train
zont/gulp-bower
index.js
getDirectoryFromBowerRc
function getDirectoryFromBowerRc(cwd) { var bowerrc = path.join(cwd, '.bowerrc'); if (!fs.existsSync(bowerrc)) { return ''; } var bower_config = {}; try { bower_config = JSON.parse(fs.readFileSync(bowerrc)); } catch (err) { return ''; } return bower_config.directory; }
javascript
function getDirectoryFromBowerRc(cwd) { var bowerrc = path.join(cwd, '.bowerrc'); if (!fs.existsSync(bowerrc)) { return ''; } var bower_config = {}; try { bower_config = JSON.parse(fs.readFileSync(bowerrc)); } catch (err) { return ''; } return bower_config.directory; }
[ "function", "getDirectoryFromBowerRc", "(", "cwd", ")", "{", "var", "bowerrc", "=", "path", ".", "join", "(", "cwd", ",", "'.bowerrc'", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "bowerrc", ")", ")", "{", "return", "''", ";", "}", "var", "bower_config", "=", "{", "}", ";", "try", "{", "bower_config", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "bowerrc", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "''", ";", "}", "return", "bower_config", ".", "directory", ";", "}" ]
Detect .bowerrc file and read directory from file @param {string} cwd current working directory @returns {string} found directory or empty string
[ "Detect", ".", "bowerrc", "file", "and", "read", "directory", "from", "file" ]
48c31b718ee5d9ab5c9dac58d100bb662a99173a
https://github.com/zont/gulp-bower/blob/48c31b718ee5d9ab5c9dac58d100bb662a99173a/index.js#L133-L148
train
zont/gulp-bower
index.js
createCmdArguments
function createCmdArguments(cmdArguments, opts) { if (toString.call(cmdArguments) !== '[object Array]') { cmdArguments = []; } if (toString.call(cmdArguments[0]) !== '[object Array]') { cmdArguments[0] = []; } cmdArguments[1] = cmdArguments[1] || {}; cmdArguments[2] = opts; return cmdArguments; }
javascript
function createCmdArguments(cmdArguments, opts) { if (toString.call(cmdArguments) !== '[object Array]') { cmdArguments = []; } if (toString.call(cmdArguments[0]) !== '[object Array]') { cmdArguments[0] = []; } cmdArguments[1] = cmdArguments[1] || {}; cmdArguments[2] = opts; return cmdArguments; }
[ "function", "createCmdArguments", "(", "cmdArguments", ",", "opts", ")", "{", "if", "(", "toString", ".", "call", "(", "cmdArguments", ")", "!==", "'[object Array]'", ")", "{", "cmdArguments", "=", "[", "]", ";", "}", "if", "(", "toString", ".", "call", "(", "cmdArguments", "[", "0", "]", ")", "!==", "'[object Array]'", ")", "{", "cmdArguments", "[", "0", "]", "=", "[", "]", ";", "}", "cmdArguments", "[", "1", "]", "=", "cmdArguments", "[", "1", "]", "||", "{", "}", ";", "cmdArguments", "[", "2", "]", "=", "opts", ";", "return", "cmdArguments", ";", "}" ]
Create command arguments @param {any} cmdArguments @param {object} opts options object
[ "Create", "command", "arguments" ]
48c31b718ee5d9ab5c9dac58d100bb662a99173a
https://github.com/zont/gulp-bower/blob/48c31b718ee5d9ab5c9dac58d100bb662a99173a/index.js#L156-L167
train
zont/gulp-bower
index.js
getBowerCommand
function getBowerCommand(cmd) { // bower has some commands that are provided in a nested object structure, e.g. `bower cache clean`. var bowerCommand; // clean up the command given, to avoid unnecessary errors cmd = cmd.trim(); var nestedCommand = cmd.split(' '); if (nestedCommand.length > 1) { // To enable that kind of nested commands, we try to resolve those commands, before passing them to bower. for (var commandPos = 0; commandPos < nestedCommand.length; commandPos++) { if (bowerCommand) { // when the root command is already there, walk into the depth. bowerCommand = bowerCommand[nestedCommand[commandPos]]; } else { // the first time we look for the "root" commands available in bower bowerCommand = bower.commands[nestedCommand[commandPos]]; } } } else { // if the command isn't nested, just go ahead as usual bowerCommand = bower.commands[cmd]; } // try to give a good error description to the user when a bad command was passed if (bowerCommand === undefined) { throw new PluginError(PLUGIN_NAME, 'The command \'' + cmd + '\' is not available in the bower commands'); } return bowerCommand; }
javascript
function getBowerCommand(cmd) { // bower has some commands that are provided in a nested object structure, e.g. `bower cache clean`. var bowerCommand; // clean up the command given, to avoid unnecessary errors cmd = cmd.trim(); var nestedCommand = cmd.split(' '); if (nestedCommand.length > 1) { // To enable that kind of nested commands, we try to resolve those commands, before passing them to bower. for (var commandPos = 0; commandPos < nestedCommand.length; commandPos++) { if (bowerCommand) { // when the root command is already there, walk into the depth. bowerCommand = bowerCommand[nestedCommand[commandPos]]; } else { // the first time we look for the "root" commands available in bower bowerCommand = bower.commands[nestedCommand[commandPos]]; } } } else { // if the command isn't nested, just go ahead as usual bowerCommand = bower.commands[cmd]; } // try to give a good error description to the user when a bad command was passed if (bowerCommand === undefined) { throw new PluginError(PLUGIN_NAME, 'The command \'' + cmd + '\' is not available in the bower commands'); } return bowerCommand; }
[ "function", "getBowerCommand", "(", "cmd", ")", "{", "var", "bowerCommand", ";", "cmd", "=", "cmd", ".", "trim", "(", ")", ";", "var", "nestedCommand", "=", "cmd", ".", "split", "(", "' '", ")", ";", "if", "(", "nestedCommand", ".", "length", ">", "1", ")", "{", "for", "(", "var", "commandPos", "=", "0", ";", "commandPos", "<", "nestedCommand", ".", "length", ";", "commandPos", "++", ")", "{", "if", "(", "bowerCommand", ")", "{", "bowerCommand", "=", "bowerCommand", "[", "nestedCommand", "[", "commandPos", "]", "]", ";", "}", "else", "{", "bowerCommand", "=", "bower", ".", "commands", "[", "nestedCommand", "[", "commandPos", "]", "]", ";", "}", "}", "}", "else", "{", "bowerCommand", "=", "bower", ".", "commands", "[", "cmd", "]", ";", "}", "if", "(", "bowerCommand", "===", "undefined", ")", "{", "throw", "new", "PluginError", "(", "PLUGIN_NAME", ",", "'The command \\''", "+", "\\'", "+", "cmd", ")", ";", "}", "'\\' is not available in the bower commands'", "}" ]
Get bower command instance @param {string} cmd bower commands, e.g. 'install' | 'update' | 'cache clean' etc. @returns {object} bower instance initialised with commands
[ "Get", "bower", "command", "instance" ]
48c31b718ee5d9ab5c9dac58d100bb662a99173a
https://github.com/zont/gulp-bower/blob/48c31b718ee5d9ab5c9dac58d100bb662a99173a/index.js#L175-L206
train
zont/gulp-bower
index.js
writeStreamToFs
function writeStreamToFs(opts, stream) { var baseDir = path.join(opts.cwd, opts.directory); var walker = walk.walk(baseDir); walker.on('errors', function (root, stats, next) { stream.emit('error', new PluginError(PLUGIN_NAME, stats.error)); next(); }); walker.on('directory', function (root, stats, next) { next(); }); walker.on('file', function (root, stats, next) { var filePath = path.resolve(root, stats.name); fs.readFile(filePath, function (error, data) { if (error) { stream.emit('error', new PluginError(PLUGIN_NAME, error)); } else { stream.write(new Vinyl({ path: path.relative(baseDir, filePath), contents: data })); } next(); }); }); walker.on('end', function () { stream.emit('end'); stream.emit('finish'); }); }
javascript
function writeStreamToFs(opts, stream) { var baseDir = path.join(opts.cwd, opts.directory); var walker = walk.walk(baseDir); walker.on('errors', function (root, stats, next) { stream.emit('error', new PluginError(PLUGIN_NAME, stats.error)); next(); }); walker.on('directory', function (root, stats, next) { next(); }); walker.on('file', function (root, stats, next) { var filePath = path.resolve(root, stats.name); fs.readFile(filePath, function (error, data) { if (error) { stream.emit('error', new PluginError(PLUGIN_NAME, error)); } else { stream.write(new Vinyl({ path: path.relative(baseDir, filePath), contents: data })); } next(); }); }); walker.on('end', function () { stream.emit('end'); stream.emit('finish'); }); }
[ "function", "writeStreamToFs", "(", "opts", ",", "stream", ")", "{", "var", "baseDir", "=", "path", ".", "join", "(", "opts", ".", "cwd", ",", "opts", ".", "directory", ")", ";", "var", "walker", "=", "walk", ".", "walk", "(", "baseDir", ")", ";", "walker", ".", "on", "(", "'errors'", ",", "function", "(", "root", ",", "stats", ",", "next", ")", "{", "stream", ".", "emit", "(", "'error'", ",", "new", "PluginError", "(", "PLUGIN_NAME", ",", "stats", ".", "error", ")", ")", ";", "next", "(", ")", ";", "}", ")", ";", "walker", ".", "on", "(", "'directory'", ",", "function", "(", "root", ",", "stats", ",", "next", ")", "{", "next", "(", ")", ";", "}", ")", ";", "walker", ".", "on", "(", "'file'", ",", "function", "(", "root", ",", "stats", ",", "next", ")", "{", "var", "filePath", "=", "path", ".", "resolve", "(", "root", ",", "stats", ".", "name", ")", ";", "fs", ".", "readFile", "(", "filePath", ",", "function", "(", "error", ",", "data", ")", "{", "if", "(", "error", ")", "{", "stream", ".", "emit", "(", "'error'", ",", "new", "PluginError", "(", "PLUGIN_NAME", ",", "error", ")", ")", ";", "}", "else", "{", "stream", ".", "write", "(", "new", "Vinyl", "(", "{", "path", ":", "path", ".", "relative", "(", "baseDir", ",", "filePath", ")", ",", "contents", ":", "data", "}", ")", ")", ";", "}", "next", "(", ")", ";", "}", ")", ";", "}", ")", ";", "walker", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "stream", ".", "emit", "(", "'end'", ")", ";", "stream", ".", "emit", "(", "'finish'", ")", ";", "}", ")", ";", "}" ]
Write stream to filesystem @param {object} opts options object @param {object} stream file stream
[ "Write", "stream", "to", "filesystem" ]
48c31b718ee5d9ab5c9dac58d100bb662a99173a
https://github.com/zont/gulp-bower/blob/48c31b718ee5d9ab5c9dac58d100bb662a99173a/index.js#L214-L247
train
sqrrrl/passport-google-plus
lib/strategy.js
function(options, authorizationCode, idToken, accessToken) { this.options = options; this.authorizationCode = authorizationCode; this.profile = {}; this.credentials = { id_token: idToken, access_token: accessToken }; this.now = Date.now(); this.apiKey = options.apiKey; this.clientId = options.clientId; this.clientSecret = options.clientSecret; this.redirectUri = options.redirectUri; this.fetchProfile = !options.skipProfile; this.authorizedPresenters = options.presenters; this.passReqToCallback = options.passReqToCallback; if (options.noRedirectUri) { this.redirectUri = undefined; } }
javascript
function(options, authorizationCode, idToken, accessToken) { this.options = options; this.authorizationCode = authorizationCode; this.profile = {}; this.credentials = { id_token: idToken, access_token: accessToken }; this.now = Date.now(); this.apiKey = options.apiKey; this.clientId = options.clientId; this.clientSecret = options.clientSecret; this.redirectUri = options.redirectUri; this.fetchProfile = !options.skipProfile; this.authorizedPresenters = options.presenters; this.passReqToCallback = options.passReqToCallback; if (options.noRedirectUri) { this.redirectUri = undefined; } }
[ "function", "(", "options", ",", "authorizationCode", ",", "idToken", ",", "accessToken", ")", "{", "this", ".", "options", "=", "options", ";", "this", ".", "authorizationCode", "=", "authorizationCode", ";", "this", ".", "profile", "=", "{", "}", ";", "this", ".", "credentials", "=", "{", "id_token", ":", "idToken", ",", "access_token", ":", "accessToken", "}", ";", "this", ".", "now", "=", "Date", ".", "now", "(", ")", ";", "this", ".", "apiKey", "=", "options", ".", "apiKey", ";", "this", ".", "clientId", "=", "options", ".", "clientId", ";", "this", ".", "clientSecret", "=", "options", ".", "clientSecret", ";", "this", ".", "redirectUri", "=", "options", ".", "redirectUri", ";", "this", ".", "fetchProfile", "=", "!", "options", ".", "skipProfile", ";", "this", ".", "authorizedPresenters", "=", "options", ".", "presenters", ";", "this", ".", "passReqToCallback", "=", "options", ".", "passReqToCallback", ";", "if", "(", "options", ".", "noRedirectUri", ")", "{", "this", ".", "redirectUri", "=", "undefined", ";", "}", "}" ]
Internal state during various phases of exchanging tokens & fetching profiles. Either an authorization code or ID token needs to be set. @constructor @param {Object} options Request-specific options @param {String} authorizationCode Authorization code to exchange, if available @Param {String} idToken ID token to verify, if available @Param {String} accessToken Access token to verify, if available
[ "Internal", "state", "during", "various", "phases", "of", "exchanging", "tokens", "&", "fetching", "profiles", ".", "Either", "an", "authorization", "code", "or", "ID", "token", "needs", "to", "be", "set", "." ]
a1b95150f41f7ccc52c9cb221ab0ec0ccbd4bc08
https://github.com/sqrrrl/passport-google-plus/blob/a1b95150f41f7ccc52c9cb221ab0ec0ccbd4bc08/lib/strategy.js#L100-L120
train
christkv/require_optional
index.js
function(location) { var found = false; while(!found) { if (exists(location + '/package.json')) { found = location; } else if (location !== '/') { location = path.dirname(location); } else { return false; } } return location; }
javascript
function(location) { var found = false; while(!found) { if (exists(location + '/package.json')) { found = location; } else if (location !== '/') { location = path.dirname(location); } else { return false; } } return location; }
[ "function", "(", "location", ")", "{", "var", "found", "=", "false", ";", "while", "(", "!", "found", ")", "{", "if", "(", "exists", "(", "location", "+", "'/package.json'", ")", ")", "{", "found", "=", "location", ";", "}", "else", "if", "(", "location", "!==", "'/'", ")", "{", "location", "=", "path", ".", "dirname", "(", "location", ")", ";", "}", "else", "{", "return", "false", ";", "}", "}", "return", "location", ";", "}" ]
Find the location of a package.json file near or above the given location
[ "Find", "the", "location", "of", "a", "package", ".", "json", "file", "near", "or", "above", "the", "given", "location" ]
c11c4ec54c29d9f5b8a335db379a4670ceeb6cfb
https://github.com/christkv/require_optional/blob/c11c4ec54c29d9f5b8a335db379a4670ceeb6cfb/index.js#L10-L24
train
christkv/require_optional
index.js
function(name) { // Walk up the module call tree until we find a module containing name in its peerOptionalDependencies var currentModule = module; var found = false; while (currentModule) { // Check currentModule has a package.json location = currentModule.filename; var location = find_package_json(location) if (!location) { currentModule = get_parent_module(currentModule); continue; } // Read the package.json file var object = JSON.parse(fs.readFileSync(f('%s/package.json', location))); // Is the name defined by interal file references var parts = name.split(/\//); // Check whether this package.json contains peerOptionalDependencies containing the name we're searching for if (!object.peerOptionalDependencies || (object.peerOptionalDependencies && !object.peerOptionalDependencies[parts[0]])) { currentModule = get_parent_module(currentModule); continue; } found = true; break; } // Check whether name has been found in currentModule's peerOptionalDependencies if (!found) { throw new Error(f('no optional dependency [%s] defined in peerOptionalDependencies in any package.json', parts[0])); } return { object: object, parts: parts } }
javascript
function(name) { // Walk up the module call tree until we find a module containing name in its peerOptionalDependencies var currentModule = module; var found = false; while (currentModule) { // Check currentModule has a package.json location = currentModule.filename; var location = find_package_json(location) if (!location) { currentModule = get_parent_module(currentModule); continue; } // Read the package.json file var object = JSON.parse(fs.readFileSync(f('%s/package.json', location))); // Is the name defined by interal file references var parts = name.split(/\//); // Check whether this package.json contains peerOptionalDependencies containing the name we're searching for if (!object.peerOptionalDependencies || (object.peerOptionalDependencies && !object.peerOptionalDependencies[parts[0]])) { currentModule = get_parent_module(currentModule); continue; } found = true; break; } // Check whether name has been found in currentModule's peerOptionalDependencies if (!found) { throw new Error(f('no optional dependency [%s] defined in peerOptionalDependencies in any package.json', parts[0])); } return { object: object, parts: parts } }
[ "function", "(", "name", ")", "{", "var", "currentModule", "=", "module", ";", "var", "found", "=", "false", ";", "while", "(", "currentModule", ")", "{", "location", "=", "currentModule", ".", "filename", ";", "var", "location", "=", "find_package_json", "(", "location", ")", "if", "(", "!", "location", ")", "{", "currentModule", "=", "get_parent_module", "(", "currentModule", ")", ";", "continue", ";", "}", "var", "object", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "f", "(", "'%s/package.json'", ",", "location", ")", ")", ")", ";", "var", "parts", "=", "name", ".", "split", "(", "/", "\\/", "/", ")", ";", "if", "(", "!", "object", ".", "peerOptionalDependencies", "||", "(", "object", ".", "peerOptionalDependencies", "&&", "!", "object", ".", "peerOptionalDependencies", "[", "parts", "[", "0", "]", "]", ")", ")", "{", "currentModule", "=", "get_parent_module", "(", "currentModule", ")", ";", "continue", ";", "}", "found", "=", "true", ";", "break", ";", "}", "if", "(", "!", "found", ")", "{", "throw", "new", "Error", "(", "f", "(", "'no optional dependency [%s] defined in peerOptionalDependencies in any package.json'", ",", "parts", "[", "0", "]", ")", ")", ";", "}", "return", "{", "object", ":", "object", ",", "parts", ":", "parts", "}", "}" ]
Find the package.json object of the module closest up the module call tree that contains name in that module's peerOptionalDependencies
[ "Find", "the", "package", ".", "json", "object", "of", "the", "module", "closest", "up", "the", "module", "call", "tree", "that", "contains", "name", "in", "that", "module", "s", "peerOptionalDependencies" ]
c11c4ec54c29d9f5b8a335db379a4670ceeb6cfb
https://github.com/christkv/require_optional/blob/c11c4ec54c29d9f5b8a335db379a4670ceeb6cfb/index.js#L32-L68
train
josdejong/rws
lib/Connection.js
ReconnectingConnection
function ReconnectingConnection(id, connection) { this.id = id; this.connection = null; this.closed = false; this.queue = []; this.setConnection(connection); }
javascript
function ReconnectingConnection(id, connection) { this.id = id; this.connection = null; this.closed = false; this.queue = []; this.setConnection(connection); }
[ "function", "ReconnectingConnection", "(", "id", ",", "connection", ")", "{", "this", ".", "id", "=", "id", ";", "this", ".", "connection", "=", "null", ";", "this", ".", "closed", "=", "false", ";", "this", ".", "queue", "=", "[", "]", ";", "this", ".", "setConnection", "(", "connection", ")", ";", "}" ]
Create a reconnecting connection @param {number | string} id Identifier for this connection @param {WebSocket} [connection] A client connection @constructor
[ "Create", "a", "reconnecting", "connection" ]
9ff4af1073ce4d03ff939ba32c2f6dae16dc7e59
https://github.com/josdejong/rws/blob/9ff4af1073ce4d03ff939ba32c2f6dae16dc7e59/lib/Connection.js#L9-L16
train
josdejong/rws
lib/ReconnectingWebSocketServer.js
ReconnectingWebSocketServer
function ReconnectingWebSocketServer (options, callback) { var me = this; this.port = options && options.port || null; this.server = new WebSocketServer({port: this.port}, callback); this.connections = {}; this.server.on('connection', function (conn) { var urlParts = url.parse(conn.upgradeReq.url, true); var id = urlParts.query.id; if (id) { // create a connection with id var rConn = me.connections[id]; if (rConn) { // update existing connection // TODO: test for conflicts, if the connection or rConn is still opened by another client with the same id rConn.setConnection(conn); } else { // create a new connection rConn = new Connection(id, conn); me.connections[id] = rConn; me.emit('connection', rConn); } } else { // create an anonymous connection (no support for restoring client connection) // TODO: create an option anonymousConnections=true|false rConn = new Connection(null, conn); me.emit('connection', rConn); } }); this.server.on('error', function (err) { me.onerror(err); }); }
javascript
function ReconnectingWebSocketServer (options, callback) { var me = this; this.port = options && options.port || null; this.server = new WebSocketServer({port: this.port}, callback); this.connections = {}; this.server.on('connection', function (conn) { var urlParts = url.parse(conn.upgradeReq.url, true); var id = urlParts.query.id; if (id) { // create a connection with id var rConn = me.connections[id]; if (rConn) { // update existing connection // TODO: test for conflicts, if the connection or rConn is still opened by another client with the same id rConn.setConnection(conn); } else { // create a new connection rConn = new Connection(id, conn); me.connections[id] = rConn; me.emit('connection', rConn); } } else { // create an anonymous connection (no support for restoring client connection) // TODO: create an option anonymousConnections=true|false rConn = new Connection(null, conn); me.emit('connection', rConn); } }); this.server.on('error', function (err) { me.onerror(err); }); }
[ "function", "ReconnectingWebSocketServer", "(", "options", ",", "callback", ")", "{", "var", "me", "=", "this", ";", "this", ".", "port", "=", "options", "&&", "options", ".", "port", "||", "null", ";", "this", ".", "server", "=", "new", "WebSocketServer", "(", "{", "port", ":", "this", ".", "port", "}", ",", "callback", ")", ";", "this", ".", "connections", "=", "{", "}", ";", "this", ".", "server", ".", "on", "(", "'connection'", ",", "function", "(", "conn", ")", "{", "var", "urlParts", "=", "url", ".", "parse", "(", "conn", ".", "upgradeReq", ".", "url", ",", "true", ")", ";", "var", "id", "=", "urlParts", ".", "query", ".", "id", ";", "if", "(", "id", ")", "{", "var", "rConn", "=", "me", ".", "connections", "[", "id", "]", ";", "if", "(", "rConn", ")", "{", "rConn", ".", "setConnection", "(", "conn", ")", ";", "}", "else", "{", "rConn", "=", "new", "Connection", "(", "id", ",", "conn", ")", ";", "me", ".", "connections", "[", "id", "]", "=", "rConn", ";", "me", ".", "emit", "(", "'connection'", ",", "rConn", ")", ";", "}", "}", "else", "{", "rConn", "=", "new", "Connection", "(", "null", ",", "conn", ")", ";", "me", ".", "emit", "(", "'connection'", ",", "rConn", ")", ";", "}", "}", ")", ";", "this", ".", "server", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "me", ".", "onerror", "(", "err", ")", ";", "}", ")", ";", "}" ]
An automatically reconnecting WebSocket server. @param {Object} options Available options: - port: number Port number for the server - reconnectInterval: number Reconnect interval in milliseconds - reconnectInterval: number Reconnect interval in milliseconds @param {function} [callback] Callback invoked when the server is ready @constructor
[ "An", "automatically", "reconnecting", "WebSocket", "server", "." ]
9ff4af1073ce4d03ff939ba32c2f6dae16dc7e59
https://github.com/josdejong/rws/blob/9ff4af1073ce4d03ff939ba32c2f6dae16dc7e59/lib/ReconnectingWebSocketServer.js#L16-L53
train
jonschlinkert/esprima-extract-comments
index.js
extract
function extract(str, options) { const defaults = { tolerant: true, comment: true, tokens: true, range: true, loc: true }; const tokens = esprima.tokenize(str, Object.assign({}, defaults, options)); const comments = []; for (let i = 0; i < tokens.length; i++) { let n = i + 1; const token = tokens[i]; let next = tokens[n]; if (isComment(token)) { if (token.type === 'BlockComment') { while (next && /comment/i.test(next.type)) next = tokens[++n]; token.codeStart = next && !/(comment|punc)/i.test(next.type) ? next.range[0] : null; } comments.push(token); } } return comments; }
javascript
function extract(str, options) { const defaults = { tolerant: true, comment: true, tokens: true, range: true, loc: true }; const tokens = esprima.tokenize(str, Object.assign({}, defaults, options)); const comments = []; for (let i = 0; i < tokens.length; i++) { let n = i + 1; const token = tokens[i]; let next = tokens[n]; if (isComment(token)) { if (token.type === 'BlockComment') { while (next && /comment/i.test(next.type)) next = tokens[++n]; token.codeStart = next && !/(comment|punc)/i.test(next.type) ? next.range[0] : null; } comments.push(token); } } return comments; }
[ "function", "extract", "(", "str", ",", "options", ")", "{", "const", "defaults", "=", "{", "tolerant", ":", "true", ",", "comment", ":", "true", ",", "tokens", ":", "true", ",", "range", ":", "true", ",", "loc", ":", "true", "}", ";", "const", "tokens", "=", "esprima", ".", "tokenize", "(", "str", ",", "Object", ".", "assign", "(", "{", "}", ",", "defaults", ",", "options", ")", ")", ";", "const", "comments", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "tokens", ".", "length", ";", "i", "++", ")", "{", "let", "n", "=", "i", "+", "1", ";", "const", "token", "=", "tokens", "[", "i", "]", ";", "let", "next", "=", "tokens", "[", "n", "]", ";", "if", "(", "isComment", "(", "token", ")", ")", "{", "if", "(", "token", ".", "type", "===", "'BlockComment'", ")", "{", "while", "(", "next", "&&", "/", "comment", "/", "i", ".", "test", "(", "next", ".", "type", ")", ")", "next", "=", "tokens", "[", "++", "n", "]", ";", "token", ".", "codeStart", "=", "next", "&&", "!", "/", "(comment|punc)", "/", "i", ".", "test", "(", "next", ".", "type", ")", "?", "next", ".", "range", "[", "0", "]", ":", "null", ";", "}", "comments", ".", "push", "(", "token", ")", ";", "}", "}", "return", "comments", ";", "}" ]
Extract line and block comments from a string of JavaScript. ```js console.log(extract('// this is a line comment')); // [ { type: 'Line', // value: ' this is a line comment', // range: [ 0, 25 ], // loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 25 } } } ] ``` @param {String} `string` @param {Object} `options` Options to pass to [esprima][]. @return {Array} Array of code comment objects. @api public
[ "Extract", "line", "and", "block", "comments", "from", "a", "string", "of", "JavaScript", "." ]
b42674ed3c2c8b237d7a94af37666e0f20e8f930
https://github.com/jonschlinkert/esprima-extract-comments/blob/b42674ed3c2c8b237d7a94af37666e0f20e8f930/index.js#L30-L49
train
idanwe/meteor-client-side
dist/meteor-client-side.bundle.js
function (count, fn) { // 55 var self = this; // 56 var timeout = self._timeout(count); // 57 if (self.retryTimer) // 58 clearTimeout(self.retryTimer); // 59 self.retryTimer = Meteor.setTimeout(fn, timeout); // 60 return timeout; // 61 }
javascript
function (count, fn) { // 55 var self = this; // 56 var timeout = self._timeout(count); // 57 if (self.retryTimer) // 58 clearTimeout(self.retryTimer); // 59 self.retryTimer = Meteor.setTimeout(fn, timeout); // 60 return timeout; // 61 }
[ "function", "(", "count", ",", "fn", ")", "{", "var", "self", "=", "this", ";", "var", "timeout", "=", "self", ".", "_timeout", "(", "count", ")", ";", "if", "(", "self", ".", "retryTimer", ")", "clearTimeout", "(", "self", ".", "retryTimer", ")", ";", "self", ".", "retryTimer", "=", "Meteor", ".", "setTimeout", "(", "fn", ",", "timeout", ")", ";", "return", "timeout", ";", "}" ]
52 53 Call `fn` after a delay, based on the `count` of which retry this is.
[ "52", "53", "Call", "fn", "after", "a", "delay", "based", "on", "the", "count", "of", "which", "retry", "this", "is", "." ]
f065bb3f11afa8248ee376075f2e44b4c124b083
https://github.com/idanwe/meteor-client-side/blob/f065bb3f11afa8248ee376075f2e44b4c124b083/dist/meteor-client-side.bundle.js#L11122-L11129
train
BorisKozo/node-async-locks
lib/reset-event.js
function (isSignaled, options) { this.queue = []; this.isSignaled = Boolean(isSignaled); this.options = _.extend({}, ResetEvent.defaultOptions, options); }
javascript
function (isSignaled, options) { this.queue = []; this.isSignaled = Boolean(isSignaled); this.options = _.extend({}, ResetEvent.defaultOptions, options); }
[ "function", "(", "isSignaled", ",", "options", ")", "{", "this", ".", "queue", "=", "[", "]", ";", "this", ".", "isSignaled", "=", "Boolean", "(", "isSignaled", ")", ";", "this", ".", "options", "=", "_", ".", "extend", "(", "{", "}", ",", "ResetEvent", ".", "defaultOptions", ",", "options", ")", ";", "}" ]
A Reset Event. @constructor @param {boolean} isSignaled - if true then the reset event starts signaled (all calls to wait will pass through) @param {object} options - optional set of options for this reset event
[ "A", "Reset", "Event", "." ]
ba0e5c998a06612527d510233d179b123129f84a
https://github.com/BorisKozo/node-async-locks/blob/ba0e5c998a06612527d510233d179b123129f84a/lib/reset-event.js#L22-L26
train
MostlyJS/mostly-node
src/handlers.js
onClientPostRequestHandler
function onClientPostRequestHandler (ctx, err) { // extension error if (err) { let error = null; if (err instanceof SuperError) { error = err.rootCause || err.cause || err; } else { error = err; } const internalError = new Errors.MostlyError(Constants.EXTENSION_ERROR, ctx.errorDetails).causedBy(err); ctx.log.error(internalError); ctx.emit('clientResponseError', error); ctx._execute(error); return; } if (ctx._response.payload.error) { debug('act:response.payload.error', ctx._response.payload.error); let error = Errio.fromObject(ctx._response.payload.error); const internalError = new Errors.BusinessError(Constants.BUSINESS_ERROR, ctx.errorDetails).causedBy(error); ctx.log.error(internalError); ctx.emit('clientResponseError', error); ctx._execute(error); return; } ctx._execute(null, ctx._response.payload.result); }
javascript
function onClientPostRequestHandler (ctx, err) { // extension error if (err) { let error = null; if (err instanceof SuperError) { error = err.rootCause || err.cause || err; } else { error = err; } const internalError = new Errors.MostlyError(Constants.EXTENSION_ERROR, ctx.errorDetails).causedBy(err); ctx.log.error(internalError); ctx.emit('clientResponseError', error); ctx._execute(error); return; } if (ctx._response.payload.error) { debug('act:response.payload.error', ctx._response.payload.error); let error = Errio.fromObject(ctx._response.payload.error); const internalError = new Errors.BusinessError(Constants.BUSINESS_ERROR, ctx.errorDetails).causedBy(error); ctx.log.error(internalError); ctx.emit('clientResponseError', error); ctx._execute(error); return; } ctx._execute(null, ctx._response.payload.result); }
[ "function", "onClientPostRequestHandler", "(", "ctx", ",", "err", ")", "{", "if", "(", "err", ")", "{", "let", "error", "=", "null", ";", "if", "(", "err", "instanceof", "SuperError", ")", "{", "error", "=", "err", ".", "rootCause", "||", "err", ".", "cause", "||", "err", ";", "}", "else", "{", "error", "=", "err", ";", "}", "const", "internalError", "=", "new", "Errors", ".", "MostlyError", "(", "Constants", ".", "EXTENSION_ERROR", ",", "ctx", ".", "errorDetails", ")", ".", "causedBy", "(", "err", ")", ";", "ctx", ".", "log", ".", "error", "(", "internalError", ")", ";", "ctx", ".", "emit", "(", "'clientResponseError'", ",", "error", ")", ";", "ctx", ".", "_execute", "(", "error", ")", ";", "return", ";", "}", "if", "(", "ctx", ".", "_response", ".", "payload", ".", "error", ")", "{", "debug", "(", "'act:response.payload.error'", ",", "ctx", ".", "_response", ".", "payload", ".", "error", ")", ";", "let", "error", "=", "Errio", ".", "fromObject", "(", "ctx", ".", "_response", ".", "payload", ".", "error", ")", ";", "const", "internalError", "=", "new", "Errors", ".", "BusinessError", "(", "Constants", ".", "BUSINESS_ERROR", ",", "ctx", ".", "errorDetails", ")", ".", "causedBy", "(", "error", ")", ";", "ctx", ".", "log", ".", "error", "(", "internalError", ")", ";", "ctx", ".", "emit", "(", "'clientResponseError'", ",", "error", ")", ";", "ctx", ".", "_execute", "(", "error", ")", ";", "return", ";", "}", "ctx", ".", "_execute", "(", "null", ",", "ctx", ".", "_response", ".", "payload", ".", "result", ")", ";", "}" ]
Is called after the client has received and decoded the request
[ "Is", "called", "after", "the", "client", "has", "received", "and", "decoded", "the", "request" ]
694b1d44bf089a48a183f239e90e5ca7b7b921b8
https://github.com/MostlyJS/mostly-node/blob/694b1d44bf089a48a183f239e90e5ca7b7b921b8/src/handlers.js#L14-L46
train
MostlyJS/mostly-node
src/handlers.js
onClientTimeoutPostRequestHandler
function onClientTimeoutPostRequestHandler (ctx, err) { if (err) { let error = null; if (err instanceof SuperError) { error = err.rootCause || err.cause || err; } else { error = err; } let internalError = new Errors.MostlyError(Constants.EXTENSION_ERROR).causedBy(err); ctx.log.error(internalError); ctx._response.error = error; ctx.emit('clientResponseError', error); } try { ctx._execute(ctx._response.error); } catch(err) { let error = null; if (err instanceof SuperError) { error = err.rootCause || err.cause || err; } else { error = err; } let internalError = new Errors.FatalError(Constants.FATAL_ERROR, ctx.errorDetails).causedBy(err); ctx.log.fatal(internalError); ctx.emit('clientResponseError', error); // let it crash if (ctx._config.crashOnFatal) { ctx.fatal(); } } }
javascript
function onClientTimeoutPostRequestHandler (ctx, err) { if (err) { let error = null; if (err instanceof SuperError) { error = err.rootCause || err.cause || err; } else { error = err; } let internalError = new Errors.MostlyError(Constants.EXTENSION_ERROR).causedBy(err); ctx.log.error(internalError); ctx._response.error = error; ctx.emit('clientResponseError', error); } try { ctx._execute(ctx._response.error); } catch(err) { let error = null; if (err instanceof SuperError) { error = err.rootCause || err.cause || err; } else { error = err; } let internalError = new Errors.FatalError(Constants.FATAL_ERROR, ctx.errorDetails).causedBy(err); ctx.log.fatal(internalError); ctx.emit('clientResponseError', error); // let it crash if (ctx._config.crashOnFatal) { ctx.fatal(); } } }
[ "function", "onClientTimeoutPostRequestHandler", "(", "ctx", ",", "err", ")", "{", "if", "(", "err", ")", "{", "let", "error", "=", "null", ";", "if", "(", "err", "instanceof", "SuperError", ")", "{", "error", "=", "err", ".", "rootCause", "||", "err", ".", "cause", "||", "err", ";", "}", "else", "{", "error", "=", "err", ";", "}", "let", "internalError", "=", "new", "Errors", ".", "MostlyError", "(", "Constants", ".", "EXTENSION_ERROR", ")", ".", "causedBy", "(", "err", ")", ";", "ctx", ".", "log", ".", "error", "(", "internalError", ")", ";", "ctx", ".", "_response", ".", "error", "=", "error", ";", "ctx", ".", "emit", "(", "'clientResponseError'", ",", "error", ")", ";", "}", "try", "{", "ctx", ".", "_execute", "(", "ctx", ".", "_response", ".", "error", ")", ";", "}", "catch", "(", "err", ")", "{", "let", "error", "=", "null", ";", "if", "(", "err", "instanceof", "SuperError", ")", "{", "error", "=", "err", ".", "rootCause", "||", "err", ".", "cause", "||", "err", ";", "}", "else", "{", "error", "=", "err", ";", "}", "let", "internalError", "=", "new", "Errors", ".", "FatalError", "(", "Constants", ".", "FATAL_ERROR", ",", "ctx", ".", "errorDetails", ")", ".", "causedBy", "(", "err", ")", ";", "ctx", ".", "log", ".", "fatal", "(", "internalError", ")", ";", "ctx", ".", "emit", "(", "'clientResponseError'", ",", "error", ")", ";", "if", "(", "ctx", ".", "_config", ".", "crashOnFatal", ")", "{", "ctx", ".", "fatal", "(", ")", ";", "}", "}", "}" ]
Is called after the client request timeout
[ "Is", "called", "after", "the", "client", "request", "timeout" ]
694b1d44bf089a48a183f239e90e5ca7b7b921b8
https://github.com/MostlyJS/mostly-node/blob/694b1d44bf089a48a183f239e90e5ca7b7b921b8/src/handlers.js#L51-L87
train
MostlyJS/mostly-node
src/handlers.js
onPreRequestHandler
function onPreRequestHandler (ctx, err) { let m = ctx._encoderPipeline.run(ctx._message, ctx); // encoding issue if (m.error) { let error = new Errors.ParseError(Constants.PAYLOAD_PARSING_ERROR).causedBy(m.error); ctx.log.error(error); ctx.emit('clientResponseError', error); ctx._execute(error); return; } if (err) { let error = null; if (err instanceof SuperError) { error = err.rootCause || err.cause || err; } else { error = err; } const internalError = new Errors.MostlyError(Constants.EXTENSION_ERROR).causedBy(err); ctx.log.error(internalError); ctx.emit('clientResponseError', error); ctx._execute(error); return; } ctx._request.payload = m.value; ctx._request.error = m.error; // use simple publish mechanism instead of request/reply if (ctx._pattern.pubsub$ === true) { if (ctx._actCallback) { ctx.log.info(Constants.PUB_CALLBACK_REDUNDANT); } ctx._transport.send(ctx._pattern.topic, ctx._request.payload); } else { const optOptions = {}; // limit on the number of responses the requestor may receive if (ctx._pattern.maxMessages$ > 0) { optOptions.max = ctx._pattern.maxMessages$; } else if (ctx._pattern.maxMessages$ !== -1) { optOptions.max = 1; } // else unlimited messages // send request ctx._sid = ctx._transport.sendRequest(ctx._pattern.topic, ctx._request.payload, optOptions, ctx._sendRequestHandler.bind(ctx)); // handle timeout ctx.handleTimeout(); } }
javascript
function onPreRequestHandler (ctx, err) { let m = ctx._encoderPipeline.run(ctx._message, ctx); // encoding issue if (m.error) { let error = new Errors.ParseError(Constants.PAYLOAD_PARSING_ERROR).causedBy(m.error); ctx.log.error(error); ctx.emit('clientResponseError', error); ctx._execute(error); return; } if (err) { let error = null; if (err instanceof SuperError) { error = err.rootCause || err.cause || err; } else { error = err; } const internalError = new Errors.MostlyError(Constants.EXTENSION_ERROR).causedBy(err); ctx.log.error(internalError); ctx.emit('clientResponseError', error); ctx._execute(error); return; } ctx._request.payload = m.value; ctx._request.error = m.error; // use simple publish mechanism instead of request/reply if (ctx._pattern.pubsub$ === true) { if (ctx._actCallback) { ctx.log.info(Constants.PUB_CALLBACK_REDUNDANT); } ctx._transport.send(ctx._pattern.topic, ctx._request.payload); } else { const optOptions = {}; // limit on the number of responses the requestor may receive if (ctx._pattern.maxMessages$ > 0) { optOptions.max = ctx._pattern.maxMessages$; } else if (ctx._pattern.maxMessages$ !== -1) { optOptions.max = 1; } // else unlimited messages // send request ctx._sid = ctx._transport.sendRequest(ctx._pattern.topic, ctx._request.payload, optOptions, ctx._sendRequestHandler.bind(ctx)); // handle timeout ctx.handleTimeout(); } }
[ "function", "onPreRequestHandler", "(", "ctx", ",", "err", ")", "{", "let", "m", "=", "ctx", ".", "_encoderPipeline", ".", "run", "(", "ctx", ".", "_message", ",", "ctx", ")", ";", "if", "(", "m", ".", "error", ")", "{", "let", "error", "=", "new", "Errors", ".", "ParseError", "(", "Constants", ".", "PAYLOAD_PARSING_ERROR", ")", ".", "causedBy", "(", "m", ".", "error", ")", ";", "ctx", ".", "log", ".", "error", "(", "error", ")", ";", "ctx", ".", "emit", "(", "'clientResponseError'", ",", "error", ")", ";", "ctx", ".", "_execute", "(", "error", ")", ";", "return", ";", "}", "if", "(", "err", ")", "{", "let", "error", "=", "null", ";", "if", "(", "err", "instanceof", "SuperError", ")", "{", "error", "=", "err", ".", "rootCause", "||", "err", ".", "cause", "||", "err", ";", "}", "else", "{", "error", "=", "err", ";", "}", "const", "internalError", "=", "new", "Errors", ".", "MostlyError", "(", "Constants", ".", "EXTENSION_ERROR", ")", ".", "causedBy", "(", "err", ")", ";", "ctx", ".", "log", ".", "error", "(", "internalError", ")", ";", "ctx", ".", "emit", "(", "'clientResponseError'", ",", "error", ")", ";", "ctx", ".", "_execute", "(", "error", ")", ";", "return", ";", "}", "ctx", ".", "_request", ".", "payload", "=", "m", ".", "value", ";", "ctx", ".", "_request", ".", "error", "=", "m", ".", "error", ";", "if", "(", "ctx", ".", "_pattern", ".", "pubsub$", "===", "true", ")", "{", "if", "(", "ctx", ".", "_actCallback", ")", "{", "ctx", ".", "log", ".", "info", "(", "Constants", ".", "PUB_CALLBACK_REDUNDANT", ")", ";", "}", "ctx", ".", "_transport", ".", "send", "(", "ctx", ".", "_pattern", ".", "topic", ",", "ctx", ".", "_request", ".", "payload", ")", ";", "}", "else", "{", "const", "optOptions", "=", "{", "}", ";", "if", "(", "ctx", ".", "_pattern", ".", "maxMessages$", ">", "0", ")", "{", "optOptions", ".", "max", "=", "ctx", ".", "_pattern", ".", "maxMessages$", ";", "}", "else", "if", "(", "ctx", ".", "_pattern", ".", "maxMessages$", "!==", "-", "1", ")", "{", "optOptions", ".", "max", "=", "1", ";", "}", "ctx", ".", "_sid", "=", "ctx", ".", "_transport", ".", "sendRequest", "(", "ctx", ".", "_pattern", ".", "topic", ",", "ctx", ".", "_request", ".", "payload", ",", "optOptions", ",", "ctx", ".", "_sendRequestHandler", ".", "bind", "(", "ctx", ")", ")", ";", "ctx", ".", "handleTimeout", "(", ")", ";", "}", "}" ]
Is called before the client has send the request to NATS
[ "Is", "called", "before", "the", "client", "has", "send", "the", "request", "to", "NATS" ]
694b1d44bf089a48a183f239e90e5ca7b7b921b8
https://github.com/MostlyJS/mostly-node/blob/694b1d44bf089a48a183f239e90e5ca7b7b921b8/src/handlers.js#L92-L148
train
MostlyJS/mostly-node
src/handlers.js
onServerPreHandler
function onServerPreHandler (ctx, err, value) { if (err) { if (err instanceof SuperError) { ctx._response.error = err.rootCause || err.cause || err; } else { ctx._response.error = err; } const internalError = new Errors.MostlyError( Constants.EXTENSION_ERROR, ctx.errorDetails).causedBy(err); ctx.log.error(internalError); return ctx.finish(); } // reply value from extension if (value) { ctx._response.payload = value; return ctx.finish(); } try { let action = ctx._actMeta.action.bind(ctx); // execute add middlewares ctx._actMeta.dispatch(ctx._request, ctx._response, (err) => { // middleware error if (err) { if (err instanceof SuperError) { ctx._response.error = err.rootCause || err.cause || err; } else { ctx._response.error = err; } let internalError = new Errors.MostlyError( Constants.ADD_MIDDLEWARE_ERROR, ctx.errorDetails).causedBy(err); ctx.log.error(internalError); return ctx.finish(); } // if request type is 'pubsub' we dont have to reply back if (ctx._request.payload.request.type === Constants.REQUEST_TYPE_PUBSUB) { action(ctx._request.payload.pattern); return ctx.finish(); } // execute RPC action if (ctx._actMeta.isPromisable) { action(ctx._request.payload.pattern) .then(x => ctx._actionHandler(null, x)) .catch(e => ctx._actionHandler(e)); } else { action(ctx._request.payload.pattern, ctx._actionHandler.bind(ctx)); } }); } catch (err) { if (err instanceof SuperError) { ctx._response.error = err.rootCause || err.cause || err; } else { ctx._response.error = err; } // service should exit ctx._shouldCrash = true; ctx.finish(); } }
javascript
function onServerPreHandler (ctx, err, value) { if (err) { if (err instanceof SuperError) { ctx._response.error = err.rootCause || err.cause || err; } else { ctx._response.error = err; } const internalError = new Errors.MostlyError( Constants.EXTENSION_ERROR, ctx.errorDetails).causedBy(err); ctx.log.error(internalError); return ctx.finish(); } // reply value from extension if (value) { ctx._response.payload = value; return ctx.finish(); } try { let action = ctx._actMeta.action.bind(ctx); // execute add middlewares ctx._actMeta.dispatch(ctx._request, ctx._response, (err) => { // middleware error if (err) { if (err instanceof SuperError) { ctx._response.error = err.rootCause || err.cause || err; } else { ctx._response.error = err; } let internalError = new Errors.MostlyError( Constants.ADD_MIDDLEWARE_ERROR, ctx.errorDetails).causedBy(err); ctx.log.error(internalError); return ctx.finish(); } // if request type is 'pubsub' we dont have to reply back if (ctx._request.payload.request.type === Constants.REQUEST_TYPE_PUBSUB) { action(ctx._request.payload.pattern); return ctx.finish(); } // execute RPC action if (ctx._actMeta.isPromisable) { action(ctx._request.payload.pattern) .then(x => ctx._actionHandler(null, x)) .catch(e => ctx._actionHandler(e)); } else { action(ctx._request.payload.pattern, ctx._actionHandler.bind(ctx)); } }); } catch (err) { if (err instanceof SuperError) { ctx._response.error = err.rootCause || err.cause || err; } else { ctx._response.error = err; } // service should exit ctx._shouldCrash = true; ctx.finish(); } }
[ "function", "onServerPreHandler", "(", "ctx", ",", "err", ",", "value", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", "instanceof", "SuperError", ")", "{", "ctx", ".", "_response", ".", "error", "=", "err", ".", "rootCause", "||", "err", ".", "cause", "||", "err", ";", "}", "else", "{", "ctx", ".", "_response", ".", "error", "=", "err", ";", "}", "const", "internalError", "=", "new", "Errors", ".", "MostlyError", "(", "Constants", ".", "EXTENSION_ERROR", ",", "ctx", ".", "errorDetails", ")", ".", "causedBy", "(", "err", ")", ";", "ctx", ".", "log", ".", "error", "(", "internalError", ")", ";", "return", "ctx", ".", "finish", "(", ")", ";", "}", "if", "(", "value", ")", "{", "ctx", ".", "_response", ".", "payload", "=", "value", ";", "return", "ctx", ".", "finish", "(", ")", ";", "}", "try", "{", "let", "action", "=", "ctx", ".", "_actMeta", ".", "action", ".", "bind", "(", "ctx", ")", ";", "ctx", ".", "_actMeta", ".", "dispatch", "(", "ctx", ".", "_request", ",", "ctx", ".", "_response", ",", "(", "err", ")", "=>", "{", "if", "(", "err", ")", "{", "if", "(", "err", "instanceof", "SuperError", ")", "{", "ctx", ".", "_response", ".", "error", "=", "err", ".", "rootCause", "||", "err", ".", "cause", "||", "err", ";", "}", "else", "{", "ctx", ".", "_response", ".", "error", "=", "err", ";", "}", "let", "internalError", "=", "new", "Errors", ".", "MostlyError", "(", "Constants", ".", "ADD_MIDDLEWARE_ERROR", ",", "ctx", ".", "errorDetails", ")", ".", "causedBy", "(", "err", ")", ";", "ctx", ".", "log", ".", "error", "(", "internalError", ")", ";", "return", "ctx", ".", "finish", "(", ")", ";", "}", "if", "(", "ctx", ".", "_request", ".", "payload", ".", "request", ".", "type", "===", "Constants", ".", "REQUEST_TYPE_PUBSUB", ")", "{", "action", "(", "ctx", ".", "_request", ".", "payload", ".", "pattern", ")", ";", "return", "ctx", ".", "finish", "(", ")", ";", "}", "if", "(", "ctx", ".", "_actMeta", ".", "isPromisable", ")", "{", "action", "(", "ctx", ".", "_request", ".", "payload", ".", "pattern", ")", ".", "then", "(", "x", "=>", "ctx", ".", "_actionHandler", "(", "null", ",", "x", ")", ")", ".", "catch", "(", "e", "=>", "ctx", ".", "_actionHandler", "(", "e", ")", ")", ";", "}", "else", "{", "action", "(", "ctx", ".", "_request", ".", "payload", ".", "pattern", ",", "ctx", ".", "_actionHandler", ".", "bind", "(", "ctx", ")", ")", ";", "}", "}", ")", ";", "}", "catch", "(", "err", ")", "{", "if", "(", "err", "instanceof", "SuperError", ")", "{", "ctx", ".", "_response", ".", "error", "=", "err", ".", "rootCause", "||", "err", ".", "cause", "||", "err", ";", "}", "else", "{", "ctx", ".", "_response", ".", "error", "=", "err", ";", "}", "ctx", ".", "_shouldCrash", "=", "true", ";", "ctx", ".", "finish", "(", ")", ";", "}", "}" ]
Is called before the server action is executed
[ "Is", "called", "before", "the", "server", "action", "is", "executed" ]
694b1d44bf089a48a183f239e90e5ca7b7b921b8
https://github.com/MostlyJS/mostly-node/blob/694b1d44bf089a48a183f239e90e5ca7b7b921b8/src/handlers.js#L153-L221
train
MostlyJS/mostly-node
src/handlers.js
onServerPreRequestHandler
function onServerPreRequestHandler (ctx, err, value) { if (err) { if (err instanceof SuperError) { ctx._response.error = err.rootCause || err.cause || err; } else { ctx._response.error = err; } return ctx.finish(); } // reply value from extension if (value) { ctx._response.payload = value; return ctx.finish(); } // check if a handler is registered with this pattern if (ctx._actMeta) { ctx._extensions.onServerPreHandler.dispatch(ctx, (err, val) => { return onServerPreHandler(ctx, err, val); }); } else { const internalError = new Errors.PatternNotFound(Constants.PATTERN_NOT_FOUND, ctx.errorDetails); ctx.log.error(internalError); ctx._response.error = internalError; // send error back to callee ctx.finish(); } }
javascript
function onServerPreRequestHandler (ctx, err, value) { if (err) { if (err instanceof SuperError) { ctx._response.error = err.rootCause || err.cause || err; } else { ctx._response.error = err; } return ctx.finish(); } // reply value from extension if (value) { ctx._response.payload = value; return ctx.finish(); } // check if a handler is registered with this pattern if (ctx._actMeta) { ctx._extensions.onServerPreHandler.dispatch(ctx, (err, val) => { return onServerPreHandler(ctx, err, val); }); } else { const internalError = new Errors.PatternNotFound(Constants.PATTERN_NOT_FOUND, ctx.errorDetails); ctx.log.error(internalError); ctx._response.error = internalError; // send error back to callee ctx.finish(); } }
[ "function", "onServerPreRequestHandler", "(", "ctx", ",", "err", ",", "value", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", "instanceof", "SuperError", ")", "{", "ctx", ".", "_response", ".", "error", "=", "err", ".", "rootCause", "||", "err", ".", "cause", "||", "err", ";", "}", "else", "{", "ctx", ".", "_response", ".", "error", "=", "err", ";", "}", "return", "ctx", ".", "finish", "(", ")", ";", "}", "if", "(", "value", ")", "{", "ctx", ".", "_response", ".", "payload", "=", "value", ";", "return", "ctx", ".", "finish", "(", ")", ";", "}", "if", "(", "ctx", ".", "_actMeta", ")", "{", "ctx", ".", "_extensions", ".", "onServerPreHandler", ".", "dispatch", "(", "ctx", ",", "(", "err", ",", "val", ")", "=>", "{", "return", "onServerPreHandler", "(", "ctx", ",", "err", ",", "val", ")", ";", "}", ")", ";", "}", "else", "{", "const", "internalError", "=", "new", "Errors", ".", "PatternNotFound", "(", "Constants", ".", "PATTERN_NOT_FOUND", ",", "ctx", ".", "errorDetails", ")", ";", "ctx", ".", "log", ".", "error", "(", "internalError", ")", ";", "ctx", ".", "_response", ".", "error", "=", "internalError", ";", "ctx", ".", "finish", "(", ")", ";", "}", "}" ]
Is called before the server has received the request
[ "Is", "called", "before", "the", "server", "has", "received", "the", "request" ]
694b1d44bf089a48a183f239e90e5ca7b7b921b8
https://github.com/MostlyJS/mostly-node/blob/694b1d44bf089a48a183f239e90e5ca7b7b921b8/src/handlers.js#L226-L256
train
MostlyJS/mostly-node
src/handlers.js
onServerPreResponseHandler
function onServerPreResponseHandler (ctx, err, value) { // check if an error was already wrapped if (ctx._response.error) { ctx.emit('serverResponseError', ctx._response.error); ctx.log.error(ctx._response.error); } else if (err) { // check for an extension error if (err instanceof SuperError) { ctx._response.error = err.rootCause || err.cause || err; } else { ctx._response.error = err; } const internalError = new Errors.MostlyError( Constants.EXTENSION_ERROR, ctx.errorDetails).causedBy(err); ctx.log.error(internalError); ctx.emit('serverResponseError', ctx._response.error); } // reply value from extension if (value) { ctx._response.payload = value; } // create message payload ctx._buildMessage(); // indicates that an error occurs and that the program should exit if (ctx._shouldCrash) { // only when we have an inbox othwerwise exit the service immediately if (ctx._replyTo) { // send error back to callee return ctx._transport.send(ctx._replyTo, ctx._message, () => { // let it crash if (ctx._config.crashOnFatal) { ctx.fatal(); } }); } else if (ctx._config.crashOnFatal) { return ctx.fatal(); } } // reply only when we have an inbox if (ctx._replyTo) { return ctx._transport.send(ctx._replyTo, ctx._message); } }
javascript
function onServerPreResponseHandler (ctx, err, value) { // check if an error was already wrapped if (ctx._response.error) { ctx.emit('serverResponseError', ctx._response.error); ctx.log.error(ctx._response.error); } else if (err) { // check for an extension error if (err instanceof SuperError) { ctx._response.error = err.rootCause || err.cause || err; } else { ctx._response.error = err; } const internalError = new Errors.MostlyError( Constants.EXTENSION_ERROR, ctx.errorDetails).causedBy(err); ctx.log.error(internalError); ctx.emit('serverResponseError', ctx._response.error); } // reply value from extension if (value) { ctx._response.payload = value; } // create message payload ctx._buildMessage(); // indicates that an error occurs and that the program should exit if (ctx._shouldCrash) { // only when we have an inbox othwerwise exit the service immediately if (ctx._replyTo) { // send error back to callee return ctx._transport.send(ctx._replyTo, ctx._message, () => { // let it crash if (ctx._config.crashOnFatal) { ctx.fatal(); } }); } else if (ctx._config.crashOnFatal) { return ctx.fatal(); } } // reply only when we have an inbox if (ctx._replyTo) { return ctx._transport.send(ctx._replyTo, ctx._message); } }
[ "function", "onServerPreResponseHandler", "(", "ctx", ",", "err", ",", "value", ")", "{", "if", "(", "ctx", ".", "_response", ".", "error", ")", "{", "ctx", ".", "emit", "(", "'serverResponseError'", ",", "ctx", ".", "_response", ".", "error", ")", ";", "ctx", ".", "log", ".", "error", "(", "ctx", ".", "_response", ".", "error", ")", ";", "}", "else", "if", "(", "err", ")", "{", "if", "(", "err", "instanceof", "SuperError", ")", "{", "ctx", ".", "_response", ".", "error", "=", "err", ".", "rootCause", "||", "err", ".", "cause", "||", "err", ";", "}", "else", "{", "ctx", ".", "_response", ".", "error", "=", "err", ";", "}", "const", "internalError", "=", "new", "Errors", ".", "MostlyError", "(", "Constants", ".", "EXTENSION_ERROR", ",", "ctx", ".", "errorDetails", ")", ".", "causedBy", "(", "err", ")", ";", "ctx", ".", "log", ".", "error", "(", "internalError", ")", ";", "ctx", ".", "emit", "(", "'serverResponseError'", ",", "ctx", ".", "_response", ".", "error", ")", ";", "}", "if", "(", "value", ")", "{", "ctx", ".", "_response", ".", "payload", "=", "value", ";", "}", "ctx", ".", "_buildMessage", "(", ")", ";", "if", "(", "ctx", ".", "_shouldCrash", ")", "{", "if", "(", "ctx", ".", "_replyTo", ")", "{", "return", "ctx", ".", "_transport", ".", "send", "(", "ctx", ".", "_replyTo", ",", "ctx", ".", "_message", ",", "(", ")", "=>", "{", "if", "(", "ctx", ".", "_config", ".", "crashOnFatal", ")", "{", "ctx", ".", "fatal", "(", ")", ";", "}", "}", ")", ";", "}", "else", "if", "(", "ctx", ".", "_config", ".", "crashOnFatal", ")", "{", "return", "ctx", ".", "fatal", "(", ")", ";", "}", "}", "if", "(", "ctx", ".", "_replyTo", ")", "{", "return", "ctx", ".", "_transport", ".", "send", "(", "ctx", ".", "_replyTo", ",", "ctx", ".", "_message", ")", ";", "}", "}" ]
Is called before the server has replied and build the message
[ "Is", "called", "before", "the", "server", "has", "replied", "and", "build", "the", "message" ]
694b1d44bf089a48a183f239e90e5ca7b7b921b8
https://github.com/MostlyJS/mostly-node/blob/694b1d44bf089a48a183f239e90e5ca7b7b921b8/src/handlers.js#L261-L307
train
MostlyJS/mostly-node
src/handlers.js
onClose
function onClose (ctx, err, val, cb) { // no callback no queue processing if (!_.isFunction(cb)) { ctx._heavy.stop(); ctx._transport.close(); if (err) { ctx.log.fatal(err); ctx.emit('error', err); } return; } // unsubscribe all active subscriptions ctx.removeAll(); // wait until the client has flush all messages to nats ctx._transport.flush(() => { ctx._heavy.stop(); // close NATS ctx._transport.close(); if (err) { ctx.log.error(err); ctx.emit('error', err); if (_.isFunction(cb)) { cb(err); } } else { ctx.log.info(Constants.GRACEFULLY_SHUTDOWN); if (_.isFunction(cb)) { cb(null, val); } } }); }
javascript
function onClose (ctx, err, val, cb) { // no callback no queue processing if (!_.isFunction(cb)) { ctx._heavy.stop(); ctx._transport.close(); if (err) { ctx.log.fatal(err); ctx.emit('error', err); } return; } // unsubscribe all active subscriptions ctx.removeAll(); // wait until the client has flush all messages to nats ctx._transport.flush(() => { ctx._heavy.stop(); // close NATS ctx._transport.close(); if (err) { ctx.log.error(err); ctx.emit('error', err); if (_.isFunction(cb)) { cb(err); } } else { ctx.log.info(Constants.GRACEFULLY_SHUTDOWN); if (_.isFunction(cb)) { cb(null, val); } } }); }
[ "function", "onClose", "(", "ctx", ",", "err", ",", "val", ",", "cb", ")", "{", "if", "(", "!", "_", ".", "isFunction", "(", "cb", ")", ")", "{", "ctx", ".", "_heavy", ".", "stop", "(", ")", ";", "ctx", ".", "_transport", ".", "close", "(", ")", ";", "if", "(", "err", ")", "{", "ctx", ".", "log", ".", "fatal", "(", "err", ")", ";", "ctx", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", "return", ";", "}", "ctx", ".", "removeAll", "(", ")", ";", "ctx", ".", "_transport", ".", "flush", "(", "(", ")", "=>", "{", "ctx", ".", "_heavy", ".", "stop", "(", ")", ";", "ctx", ".", "_transport", ".", "close", "(", ")", ";", "if", "(", "err", ")", "{", "ctx", ".", "log", ".", "error", "(", "err", ")", ";", "ctx", ".", "emit", "(", "'error'", ",", "err", ")", ";", "if", "(", "_", ".", "isFunction", "(", "cb", ")", ")", "{", "cb", "(", "err", ")", ";", "}", "}", "else", "{", "ctx", ".", "log", ".", "info", "(", "Constants", ".", "GRACEFULLY_SHUTDOWN", ")", ";", "if", "(", "_", ".", "isFunction", "(", "cb", ")", ")", "{", "cb", "(", "null", ",", "val", ")", ";", "}", "}", "}", ")", ";", "}" ]
Is called after all onClose extensions have been called
[ "Is", "called", "after", "all", "onClose", "extensions", "have", "been", "called" ]
694b1d44bf089a48a183f239e90e5ca7b7b921b8
https://github.com/MostlyJS/mostly-node/blob/694b1d44bf089a48a183f239e90e5ca7b7b921b8/src/handlers.js#L312-L346
train
MostlyJS/mostly-node
src/check-plugin.js
checkPlugin
function checkPlugin (fn, version) { if (typeof fn !== 'function') { throw new TypeError(`mostly-plugin expects a function, instead got a '${typeof fn}'`); } if (version) { if (typeof version !== 'string') { throw new TypeError(`mostly-plugin expects a version string as second parameter, instead got '${typeof version}'`); } const mostlyVersion = require('mostly-node/package.json').version; if (!semver.satisfies(mostlyVersion, version)) { throw new Error(`mostly-plugin - expected '${version}' mostly-node version, '${mostlyVersion}' is installed`); } } return fn; }
javascript
function checkPlugin (fn, version) { if (typeof fn !== 'function') { throw new TypeError(`mostly-plugin expects a function, instead got a '${typeof fn}'`); } if (version) { if (typeof version !== 'string') { throw new TypeError(`mostly-plugin expects a version string as second parameter, instead got '${typeof version}'`); } const mostlyVersion = require('mostly-node/package.json').version; if (!semver.satisfies(mostlyVersion, version)) { throw new Error(`mostly-plugin - expected '${version}' mostly-node version, '${mostlyVersion}' is installed`); } } return fn; }
[ "function", "checkPlugin", "(", "fn", ",", "version", ")", "{", "if", "(", "typeof", "fn", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", "`", "${", "typeof", "fn", "}", "`", ")", ";", "}", "if", "(", "version", ")", "{", "if", "(", "typeof", "version", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "`", "${", "typeof", "version", "}", "`", ")", ";", "}", "const", "mostlyVersion", "=", "require", "(", "'mostly-node/package.json'", ")", ".", "version", ";", "if", "(", "!", "semver", ".", "satisfies", "(", "mostlyVersion", ",", "version", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "version", "}", "${", "mostlyVersion", "}", "`", ")", ";", "}", "}", "return", "fn", ";", "}" ]
Check the bare-minimum version of mostly-node Provide consistent interface to register plugins even when the api is changed
[ "Check", "the", "bare", "-", "minimum", "version", "of", "mostly", "-", "node", "Provide", "consistent", "interface", "to", "register", "plugins", "even", "when", "the", "api", "is", "changed" ]
694b1d44bf089a48a183f239e90e5ca7b7b921b8
https://github.com/MostlyJS/mostly-node/blob/694b1d44bf089a48a183f239e90e5ca7b7b921b8/src/check-plugin.js#L5-L22
train
ioBroker/adapter-core
build/utils.js
getControllerDir
function getControllerDir(isInstall) { // Find the js-controller location const possibilities = ["iobroker.js-controller", "ioBroker.js-controller"]; let controllerPath; for (const pkg of possibilities) { try { const possiblePath = require.resolve(pkg); if (fs.existsSync(possiblePath)) { controllerPath = possiblePath; break; } } catch (_a) { /* not found */ } } // Apparently, checking vs null/undefined may miss the odd case of controllerPath being "" // Thus we check for falsyness, which includes failing on an empty path if (!controllerPath) { if (!isInstall) { console.log("Cannot find js-controller"); return process.exit(10); } else { return process.exit(); } } // we found the controller return path.dirname(controllerPath); }
javascript
function getControllerDir(isInstall) { // Find the js-controller location const possibilities = ["iobroker.js-controller", "ioBroker.js-controller"]; let controllerPath; for (const pkg of possibilities) { try { const possiblePath = require.resolve(pkg); if (fs.existsSync(possiblePath)) { controllerPath = possiblePath; break; } } catch (_a) { /* not found */ } } // Apparently, checking vs null/undefined may miss the odd case of controllerPath being "" // Thus we check for falsyness, which includes failing on an empty path if (!controllerPath) { if (!isInstall) { console.log("Cannot find js-controller"); return process.exit(10); } else { return process.exit(); } } // we found the controller return path.dirname(controllerPath); }
[ "function", "getControllerDir", "(", "isInstall", ")", "{", "const", "possibilities", "=", "[", "\"iobroker.js-controller\"", ",", "\"ioBroker.js-controller\"", "]", ";", "let", "controllerPath", ";", "for", "(", "const", "pkg", "of", "possibilities", ")", "{", "try", "{", "const", "possiblePath", "=", "require", ".", "resolve", "(", "pkg", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "possiblePath", ")", ")", "{", "controllerPath", "=", "possiblePath", ";", "break", ";", "}", "}", "catch", "(", "_a", ")", "{", "}", "}", "if", "(", "!", "controllerPath", ")", "{", "if", "(", "!", "isInstall", ")", "{", "console", ".", "log", "(", "\"Cannot find js-controller\"", ")", ";", "return", "process", ".", "exit", "(", "10", ")", ";", "}", "else", "{", "return", "process", ".", "exit", "(", ")", ";", "}", "}", "return", "path", ".", "dirname", "(", "controllerPath", ")", ";", "}" ]
Resolves the root directory of JS-Controller and returns it or exits the process @param isInstall Whether the adapter is run in "install" mode or if it should execute normally
[ "Resolves", "the", "root", "directory", "of", "JS", "-", "Controller", "and", "returns", "it", "or", "exits", "the", "process" ]
6ee9f41b2cefd6d1dcd953e5d3936dac8d9fc2e7
https://github.com/ioBroker/adapter-core/blob/6ee9f41b2cefd6d1dcd953e5d3936dac8d9fc2e7/build/utils.js#L9-L38
train
cesardeazevedo/sails-hook-sequelize-blueprints
actions/add.js
function (cb) { Model.findById(parentPk, { include: [{ all : true }]}).then(function(parentRecord) { if (!parentRecord) return cb({status: 404}); if (!parentRecord[relation]) { return cb({status: 404}); } cb(null, parentRecord); }).catch(function(err){ return cb(err); }); }
javascript
function (cb) { Model.findById(parentPk, { include: [{ all : true }]}).then(function(parentRecord) { if (!parentRecord) return cb({status: 404}); if (!parentRecord[relation]) { return cb({status: 404}); } cb(null, parentRecord); }).catch(function(err){ return cb(err); }); }
[ "function", "(", "cb", ")", "{", "Model", ".", "findById", "(", "parentPk", ",", "{", "include", ":", "[", "{", "all", ":", "true", "}", "]", "}", ")", ".", "then", "(", "function", "(", "parentRecord", ")", "{", "if", "(", "!", "parentRecord", ")", "return", "cb", "(", "{", "status", ":", "404", "}", ")", ";", "if", "(", "!", "parentRecord", "[", "relation", "]", ")", "{", "return", "cb", "(", "{", "status", ":", "404", "}", ")", ";", "}", "cb", "(", "null", ",", "parentRecord", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", ")", ";", "}" ]
Look up the parent record
[ "Look", "up", "the", "parent", "record" ]
d0e6ac217ad285c82cdaa39c9198efdb59837d6e
https://github.com/cesardeazevedo/sails-hook-sequelize-blueprints/blob/d0e6ac217ad285c82cdaa39c9198efdb59837d6e/actions/add.js#L84-L92
train
cesardeazevedo/sails-hook-sequelize-blueprints
actions/add.js
createChild
function createChild(customCb) { ChildModel.create(child).then(function(newChildRecord){ if (req._sails.hooks.pubsub) { if (req.isSocket) { ChildModel.subscribe(req, newChildRecord); ChildModel.introduce(newChildRecord); } ChildModel.publishCreate(newChildRecord, !req.options.mirror && req); } // in case we have to create a child and link it to parent(M-M through scenario) // createChild function should return the instance to be linked // in the through model => customCb return (typeof customCb === 'function') ? customCb(null, newChildRecord[childPkAttr]) : cb(null, newChildRecord[childPkAttr]); }).catch(function(err){ return cb(err); }); }
javascript
function createChild(customCb) { ChildModel.create(child).then(function(newChildRecord){ if (req._sails.hooks.pubsub) { if (req.isSocket) { ChildModel.subscribe(req, newChildRecord); ChildModel.introduce(newChildRecord); } ChildModel.publishCreate(newChildRecord, !req.options.mirror && req); } // in case we have to create a child and link it to parent(M-M through scenario) // createChild function should return the instance to be linked // in the through model => customCb return (typeof customCb === 'function') ? customCb(null, newChildRecord[childPkAttr]) : cb(null, newChildRecord[childPkAttr]); }).catch(function(err){ return cb(err); }); }
[ "function", "createChild", "(", "customCb", ")", "{", "ChildModel", ".", "create", "(", "child", ")", ".", "then", "(", "function", "(", "newChildRecord", ")", "{", "if", "(", "req", ".", "_sails", ".", "hooks", ".", "pubsub", ")", "{", "if", "(", "req", ".", "isSocket", ")", "{", "ChildModel", ".", "subscribe", "(", "req", ",", "newChildRecord", ")", ";", "ChildModel", ".", "introduce", "(", "newChildRecord", ")", ";", "}", "ChildModel", ".", "publishCreate", "(", "newChildRecord", ",", "!", "req", ".", "options", ".", "mirror", "&&", "req", ")", ";", "}", "return", "(", "typeof", "customCb", "===", "'function'", ")", "?", "customCb", "(", "null", ",", "newChildRecord", "[", "childPkAttr", "]", ")", ":", "cb", "(", "null", ",", "newChildRecord", "[", "childPkAttr", "]", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", ")", ";", "}" ]
Create a new instance and send out any required pubsub messages.
[ "Create", "a", "new", "instance", "and", "send", "out", "any", "required", "pubsub", "messages", "." ]
d0e6ac217ad285c82cdaa39c9198efdb59837d6e
https://github.com/cesardeazevedo/sails-hook-sequelize-blueprints/blob/d0e6ac217ad285c82cdaa39c9198efdb59837d6e/actions/add.js#L163-L182
train
bracketclub/bracket-generator
index.js
function () { if (_uniq(matchup, true).length < 2) return 1 return matchup.indexOf(Math.max.apply(Math, matchup)) }
javascript
function () { if (_uniq(matchup, true).length < 2) return 1 return matchup.indexOf(Math.max.apply(Math, matchup)) }
[ "function", "(", ")", "{", "if", "(", "_uniq", "(", "matchup", ",", "true", ")", ".", "length", "<", "2", ")", "return", "1", "return", "matchup", ".", "indexOf", "(", "Math", ".", "max", ".", "apply", "(", "Math", ",", "matchup", ")", ")", "}" ]
Higher means higher seed OR if seeds are the same 2nd team
[ "Higher", "means", "higher", "seed", "OR", "if", "seeds", "are", "the", "same", "2nd", "team" ]
f986dbf3cc257a9412c1cb4212a20795132f1904
https://github.com/bracketclub/bracket-generator/blob/f986dbf3cc257a9412c1cb4212a20795132f1904/index.js#L55-L58
train
bracketclub/bracket-generator
index.js
function () { if (_uniq(matchup, true).length < 2) return 0 return matchup.indexOf(Math.min.apply(Math, matchup)) }
javascript
function () { if (_uniq(matchup, true).length < 2) return 0 return matchup.indexOf(Math.min.apply(Math, matchup)) }
[ "function", "(", ")", "{", "if", "(", "_uniq", "(", "matchup", ",", "true", ")", ".", "length", "<", "2", ")", "return", "0", "return", "matchup", ".", "indexOf", "(", "Math", ".", "min", ".", "apply", "(", "Math", ",", "matchup", ")", ")", "}" ]
Lower means lower seed OR if seeds are the same 1st team
[ "Lower", "means", "lower", "seed", "OR", "if", "seeds", "are", "the", "same", "1st", "team" ]
f986dbf3cc257a9412c1cb4212a20795132f1904
https://github.com/bracketclub/bracket-generator/blob/f986dbf3cc257a9412c1cb4212a20795132f1904/index.js#L60-L63
train
hexus/phaser-slopes
src/Matter/World.js
isIrrelevant
function isIrrelevant(tile) { return !tile || !tile.physics || !tile.physics.matterBody || !tile.physics.matterBody.body || !tile.physics.matterBody.body.vertices || !tile.physics.slopes || !tile.physics.slopes.neighbours || !tile.physics.slopes.edges; }
javascript
function isIrrelevant(tile) { return !tile || !tile.physics || !tile.physics.matterBody || !tile.physics.matterBody.body || !tile.physics.matterBody.body.vertices || !tile.physics.slopes || !tile.physics.slopes.neighbours || !tile.physics.slopes.edges; }
[ "function", "isIrrelevant", "(", "tile", ")", "{", "return", "!", "tile", "||", "!", "tile", ".", "physics", "||", "!", "tile", ".", "physics", ".", "matterBody", "||", "!", "tile", ".", "physics", ".", "matterBody", ".", "body", "||", "!", "tile", ".", "physics", ".", "matterBody", ".", "body", ".", "vertices", "||", "!", "tile", ".", "physics", ".", "slopes", "||", "!", "tile", ".", "physics", ".", "slopes", ".", "neighbours", "||", "!", "tile", ".", "physics", ".", "slopes", ".", "edges", ";", "}" ]
Determine whether a tile is irrelevant to the plugin's edge processing. @param {Phaser.Tilemaps.Tile} tile @return {boolean}
[ "Determine", "whether", "a", "tile", "is", "irrelevant", "to", "the", "plugin", "s", "edge", "processing", "." ]
1ef1137ea4cdea920dc312f760000e2463ef40af
https://github.com/hexus/phaser-slopes/blob/1ef1137ea4cdea920dc312f760000e2463ef40af/src/Matter/World.js#L13-L22
train
hexus/phaser-slopes
src/Matter/World.js
containsNormal
function containsNormal(normal, normals) { let n; for (n = 0; n < normals.length; n++) { if (!normals[n].ignore && Vector.dot(normal, normals[n]) === 1) { return true; } } return false; }
javascript
function containsNormal(normal, normals) { let n; for (n = 0; n < normals.length; n++) { if (!normals[n].ignore && Vector.dot(normal, normals[n]) === 1) { return true; } } return false; }
[ "function", "containsNormal", "(", "normal", ",", "normals", ")", "{", "let", "n", ";", "for", "(", "n", "=", "0", ";", "n", "<", "normals", ".", "length", ";", "n", "++", ")", "{", "if", "(", "!", "normals", "[", "n", "]", ".", "ignore", "&&", "Vector", ".", "dot", "(", "normal", ",", "normals", "[", "n", "]", ")", "===", "1", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Determine whether a normal is contained in a set of normals. Skips over ignored normals. @param {Object} normal - The normal to look for. @param {Object[]} normals - The normals to search. @return {boolean} Whether the normal is in the list of normals.
[ "Determine", "whether", "a", "normal", "is", "contained", "in", "a", "set", "of", "normals", "." ]
1ef1137ea4cdea920dc312f760000e2463ef40af
https://github.com/hexus/phaser-slopes/blob/1ef1137ea4cdea920dc312f760000e2463ef40af/src/Matter/World.js#L44-L54
train
hexus/phaser-slopes
src/Matter/World.js
buildEdgeVertex
function buildEdgeVertex(index, x, y, tileBody, isGhost) { let vertex = { x: x, y: y, index: index, body: tileBody, isInternal: false, isGhost: isGhost, contact: null }; vertex.contact = { vertex: vertex, normalImpulse: 0, tangentImpulse: 0 }; return vertex; }
javascript
function buildEdgeVertex(index, x, y, tileBody, isGhost) { let vertex = { x: x, y: y, index: index, body: tileBody, isInternal: false, isGhost: isGhost, contact: null }; vertex.contact = { vertex: vertex, normalImpulse: 0, tangentImpulse: 0 }; return vertex; }
[ "function", "buildEdgeVertex", "(", "index", ",", "x", ",", "y", ",", "tileBody", ",", "isGhost", ")", "{", "let", "vertex", "=", "{", "x", ":", "x", ",", "y", ":", "y", ",", "index", ":", "index", ",", "body", ":", "tileBody", ",", "isInternal", ":", "false", ",", "isGhost", ":", "isGhost", ",", "contact", ":", "null", "}", ";", "vertex", ".", "contact", "=", "{", "vertex", ":", "vertex", ",", "normalImpulse", ":", "0", ",", "tangentImpulse", ":", "0", "}", ";", "return", "vertex", ";", "}" ]
Build a vertex for an edge. @param {int} index @param {number} x @param {number} y @param {Object} tileBody @param {boolean} [isGhost]
[ "Build", "a", "vertex", "for", "an", "edge", "." ]
1ef1137ea4cdea920dc312f760000e2463ef40af
https://github.com/hexus/phaser-slopes/blob/1ef1137ea4cdea920dc312f760000e2463ef40af/src/Matter/World.js#L65-L83
train
hexus/phaser-slopes
src/Matter/World.js
buildEdge
function buildEdge(vertex1, vertex2, tileBody, vertex0, vertex3) { vertex0 = vertex0 || null; vertex3 = vertex3 || null; let vertices = []; // Build the vertices vertices.push( vertex0 ? buildEdgeVertex(0, vertex0.x, vertex0.y, tileBody, true) : null, buildEdgeVertex(1, vertex1.x, vertex1.y, tileBody), buildEdgeVertex(2, vertex2.x, vertex2.y, tileBody), vertex3 ? buildEdgeVertex(3, vertex3.x, vertex3.y, tileBody, true) : null ); // Build the edge let edge = { vertices: vertices, normals: null }; // Calculate normals edge.normals = Axes.fromVertices(edge.vertices); // Calculate position edge.position = Vector.create( (vertex1.x + vertex2.x) / 2, (vertex1.y + vertex2.y) / 2 ); edge.index = vertex1.index; return edge; }
javascript
function buildEdge(vertex1, vertex2, tileBody, vertex0, vertex3) { vertex0 = vertex0 || null; vertex3 = vertex3 || null; let vertices = []; // Build the vertices vertices.push( vertex0 ? buildEdgeVertex(0, vertex0.x, vertex0.y, tileBody, true) : null, buildEdgeVertex(1, vertex1.x, vertex1.y, tileBody), buildEdgeVertex(2, vertex2.x, vertex2.y, tileBody), vertex3 ? buildEdgeVertex(3, vertex3.x, vertex3.y, tileBody, true) : null ); // Build the edge let edge = { vertices: vertices, normals: null }; // Calculate normals edge.normals = Axes.fromVertices(edge.vertices); // Calculate position edge.position = Vector.create( (vertex1.x + vertex2.x) / 2, (vertex1.y + vertex2.y) / 2 ); edge.index = vertex1.index; return edge; }
[ "function", "buildEdge", "(", "vertex1", ",", "vertex2", ",", "tileBody", ",", "vertex0", ",", "vertex3", ")", "{", "vertex0", "=", "vertex0", "||", "null", ";", "vertex3", "=", "vertex3", "||", "null", ";", "let", "vertices", "=", "[", "]", ";", "vertices", ".", "push", "(", "vertex0", "?", "buildEdgeVertex", "(", "0", ",", "vertex0", ".", "x", ",", "vertex0", ".", "y", ",", "tileBody", ",", "true", ")", ":", "null", ",", "buildEdgeVertex", "(", "1", ",", "vertex1", ".", "x", ",", "vertex1", ".", "y", ",", "tileBody", ")", ",", "buildEdgeVertex", "(", "2", ",", "vertex2", ".", "x", ",", "vertex2", ".", "y", ",", "tileBody", ")", ",", "vertex3", "?", "buildEdgeVertex", "(", "3", ",", "vertex3", ".", "x", ",", "vertex3", ".", "y", ",", "tileBody", ",", "true", ")", ":", "null", ")", ";", "let", "edge", "=", "{", "vertices", ":", "vertices", ",", "normals", ":", "null", "}", ";", "edge", ".", "normals", "=", "Axes", ".", "fromVertices", "(", "edge", ".", "vertices", ")", ";", "edge", ".", "position", "=", "Vector", ".", "create", "(", "(", "vertex1", ".", "x", "+", "vertex2", ".", "x", ")", "/", "2", ",", "(", "vertex1", ".", "y", "+", "vertex2", ".", "y", ")", "/", "2", ")", ";", "edge", ".", "index", "=", "vertex1", ".", "index", ";", "return", "edge", ";", "}" ]
Build a ghost edge for a tile body. @param {Object} vertex1 - The first vertex of the central edge. @param {Object} vertex2 - The second vertex of the central edge. @param {Object} tileBody - The tile body the ghost edge belongs to. @param {Object} [vertex0] - The vertex of the leading ghost edge. @param {Object} [vertex3] - The vertex of the trailing ghost edge.
[ "Build", "a", "ghost", "edge", "for", "a", "tile", "body", "." ]
1ef1137ea4cdea920dc312f760000e2463ef40af
https://github.com/hexus/phaser-slopes/blob/1ef1137ea4cdea920dc312f760000e2463ef40af/src/Matter/World.js#L94-L126
train
hexus/phaser-slopes
src/Matter/World.js
isAxisAligned
function isAxisAligned(vector) { for (let d in Constants.Directions) { let direction = Constants.Directions[d]; if (Vector.dot(direction, vector) === 1) { return true; } } return false; }
javascript
function isAxisAligned(vector) { for (let d in Constants.Directions) { let direction = Constants.Directions[d]; if (Vector.dot(direction, vector) === 1) { return true; } } return false; }
[ "function", "isAxisAligned", "(", "vector", ")", "{", "for", "(", "let", "d", "in", "Constants", ".", "Directions", ")", "{", "let", "direction", "=", "Constants", ".", "Directions", "[", "d", "]", ";", "if", "(", "Vector", ".", "dot", "(", "direction", ",", "vector", ")", "===", "1", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Determine whether a vector is aligned with a 2D axis. @param {Object} vector @returns {boolean}
[ "Determine", "whether", "a", "vector", "is", "aligned", "with", "a", "2D", "axis", "." ]
1ef1137ea4cdea920dc312f760000e2463ef40af
https://github.com/hexus/phaser-slopes/blob/1ef1137ea4cdea920dc312f760000e2463ef40af/src/Matter/World.js#L276-L286
train
hexus/phaser-slopes
src/Matter/World.js
function (tilemapLayer, tiles) { let i, layerData = tilemapLayer.layer; // Pre-process the tiles for (i in tiles) { let tile = tiles[i]; tile.physics.slopes = tile.physics.slopes || {}; tile.physics.slopes = { neighbours: { up: GetTileAt(tile.x, tile.y - 1, true, layerData), down: GetTileAt(tile.x, tile.y + 1, true, layerData), left: GetTileAt(tile.x - 1, tile.y, true, layerData), right: GetTileAt(tile.x + 1, tile.y, true, layerData), topLeft: GetTileAt(tile.x - 1, tile.y - 1, true, layerData), topRight: GetTileAt(tile.x + 1, tile.y - 1, true, layerData), bottomLeft: GetTileAt(tile.x - 1, tile.y + 1, true, layerData), bottomRight: GetTileAt(tile.x + 1, tile.y + 1, true, layerData), }, edges: { top: Constants.INTERESTING, bottom: Constants.INTERESTING, left: Constants.INTERESTING, right: Constants.INTERESTING } }; } // Calculate boundary edges this.calculateBoundaryEdges(tiles); // Flag internal edges this.flagInternalEdges(tiles); // Build ghost edges and flag ignormals this.flagIgnormals(tiles); }
javascript
function (tilemapLayer, tiles) { let i, layerData = tilemapLayer.layer; // Pre-process the tiles for (i in tiles) { let tile = tiles[i]; tile.physics.slopes = tile.physics.slopes || {}; tile.physics.slopes = { neighbours: { up: GetTileAt(tile.x, tile.y - 1, true, layerData), down: GetTileAt(tile.x, tile.y + 1, true, layerData), left: GetTileAt(tile.x - 1, tile.y, true, layerData), right: GetTileAt(tile.x + 1, tile.y, true, layerData), topLeft: GetTileAt(tile.x - 1, tile.y - 1, true, layerData), topRight: GetTileAt(tile.x + 1, tile.y - 1, true, layerData), bottomLeft: GetTileAt(tile.x - 1, tile.y + 1, true, layerData), bottomRight: GetTileAt(tile.x + 1, tile.y + 1, true, layerData), }, edges: { top: Constants.INTERESTING, bottom: Constants.INTERESTING, left: Constants.INTERESTING, right: Constants.INTERESTING } }; } // Calculate boundary edges this.calculateBoundaryEdges(tiles); // Flag internal edges this.flagInternalEdges(tiles); // Build ghost edges and flag ignormals this.flagIgnormals(tiles); }
[ "function", "(", "tilemapLayer", ",", "tiles", ")", "{", "let", "i", ",", "layerData", "=", "tilemapLayer", ".", "layer", ";", "for", "(", "i", "in", "tiles", ")", "{", "let", "tile", "=", "tiles", "[", "i", "]", ";", "tile", ".", "physics", ".", "slopes", "=", "tile", ".", "physics", ".", "slopes", "||", "{", "}", ";", "tile", ".", "physics", ".", "slopes", "=", "{", "neighbours", ":", "{", "up", ":", "GetTileAt", "(", "tile", ".", "x", ",", "tile", ".", "y", "-", "1", ",", "true", ",", "layerData", ")", ",", "down", ":", "GetTileAt", "(", "tile", ".", "x", ",", "tile", ".", "y", "+", "1", ",", "true", ",", "layerData", ")", ",", "left", ":", "GetTileAt", "(", "tile", ".", "x", "-", "1", ",", "tile", ".", "y", ",", "true", ",", "layerData", ")", ",", "right", ":", "GetTileAt", "(", "tile", ".", "x", "+", "1", ",", "tile", ".", "y", ",", "true", ",", "layerData", ")", ",", "topLeft", ":", "GetTileAt", "(", "tile", ".", "x", "-", "1", ",", "tile", ".", "y", "-", "1", ",", "true", ",", "layerData", ")", ",", "topRight", ":", "GetTileAt", "(", "tile", ".", "x", "+", "1", ",", "tile", ".", "y", "-", "1", ",", "true", ",", "layerData", ")", ",", "bottomLeft", ":", "GetTileAt", "(", "tile", ".", "x", "-", "1", ",", "tile", ".", "y", "+", "1", ",", "true", ",", "layerData", ")", ",", "bottomRight", ":", "GetTileAt", "(", "tile", ".", "x", "+", "1", ",", "tile", ".", "y", "+", "1", ",", "true", ",", "layerData", ")", ",", "}", ",", "edges", ":", "{", "top", ":", "Constants", ".", "INTERESTING", ",", "bottom", ":", "Constants", ".", "INTERESTING", ",", "left", ":", "Constants", ".", "INTERESTING", ",", "right", ":", "Constants", ".", "INTERESTING", "}", "}", ";", "}", "this", ".", "calculateBoundaryEdges", "(", "tiles", ")", ";", "this", ".", "flagInternalEdges", "(", "tiles", ")", ";", "this", ".", "flagIgnormals", "(", "tiles", ")", ";", "}" ]
Process the edges of the given tiles. @param {Phaser.Tilemaps.DynamicTilemapLayer|Phaser.Tilemaps.StaticTilemapLayer} tilemapLayer - The layer the tiles belong to. @param {Phaser.Tilemaps.Tile[]} tiles - The tiles to process.
[ "Process", "the", "edges", "of", "the", "given", "tiles", "." ]
1ef1137ea4cdea920dc312f760000e2463ef40af
https://github.com/hexus/phaser-slopes/blob/1ef1137ea4cdea920dc312f760000e2463ef40af/src/Matter/World.js#L305-L342
train
hexus/phaser-slopes
src/Matter/World.js
function (firstEdge, secondEdge) { if (firstEdge === Constants.SOLID && secondEdge === Constants.SOLID) { return Constants.EMPTY; } if (firstEdge === Constants.SOLID && secondEdge === Constants.EMPTY) { return Constants.EMPTY; } return firstEdge; }
javascript
function (firstEdge, secondEdge) { if (firstEdge === Constants.SOLID && secondEdge === Constants.SOLID) { return Constants.EMPTY; } if (firstEdge === Constants.SOLID && secondEdge === Constants.EMPTY) { return Constants.EMPTY; } return firstEdge; }
[ "function", "(", "firstEdge", ",", "secondEdge", ")", "{", "if", "(", "firstEdge", "===", "Constants", ".", "SOLID", "&&", "secondEdge", "===", "Constants", ".", "SOLID", ")", "{", "return", "Constants", ".", "EMPTY", ";", "}", "if", "(", "firstEdge", "===", "Constants", ".", "SOLID", "&&", "secondEdge", "===", "Constants", ".", "EMPTY", ")", "{", "return", "Constants", ".", "EMPTY", ";", "}", "return", "firstEdge", ";", "}" ]
Resolve the given flags of two shared tile boundary edges. Returns the new flag to use for the first edge after comparing it with the second edge. If both edges are solid, or the first is solid and second is empty, then the empty edge flag is returned. Otherwise the first edge is returned. This compares boundary edges of each tile, not polygon edges. @method Phaser.Plugin.ArcadeSlopes.TileSlopeFactory#compareBoundaryEdges @param {int} firstEdge - The edge to resolve. @param {int} secondEdge - The edge to compare against. @return {int} - The resolved edge.
[ "Resolve", "the", "given", "flags", "of", "two", "shared", "tile", "boundary", "edges", "." ]
1ef1137ea4cdea920dc312f760000e2463ef40af
https://github.com/hexus/phaser-slopes/blob/1ef1137ea4cdea920dc312f760000e2463ef40af/src/Matter/World.js#L468-L478
train
hexus/phaser-slopes
src/Matter/World.js
function (tiles) { const maxDist = 5; const directNeighbours = ['up', 'down', 'left', 'right']; let t, tile, n, neighbour, i, j, tv, nv, tn, nn; for (t = 0; t < tiles.length; t++) { tile = tiles[t]; // Skip over irrelevant tiles if (isIrrelevant(tile)) { continue; } // Grab the tile's body and vertices to compare with its neighbours let tileBody = tile.physics.matterBody.body; let tileVertices = tileBody.vertices; // Iterate over each direct neighbour for (n in directNeighbours) { neighbour = tile.physics.slopes.neighbours[directNeighbours[n]]; // Skip over irrelevant neighbouring tiles if (isIrrelevant(neighbour)) { continue; } // Grab the neighbour's body and vertices let neighbourBody = neighbour.physics.matterBody.body; let neighbourVertices = neighbourBody.vertices; // Skip over tile-neighbour pairs that don't overlap if (!Bounds.overlaps(tileBody.bounds, neighbourBody.bounds)) { continue; } tv = tileVertices; nv = neighbourVertices; tn = tileBody.axes; nn = neighbourBody.axes; // Iterate over the vertices of both the tile and its neighbour for (i = 0; i < tv.length; i++) { for (j = 0; j < nv.length; j++) { // Find distances between the vertices let da = Vector.magnitudeSquared(Vector.sub(tv[(i + 1) % tv.length], nv[j])), db = Vector.magnitudeSquared(Vector.sub(tv[i], nv[(j + 1) % nv.length])); // If both vertices are very close, consider the edge coincident (internal) if (da < maxDist && db < maxDist) { tv[i].isInternal = true; nv[j].isInternal = true; tn[i].ignore = true; nn[j].ignore = true; } } } } } }
javascript
function (tiles) { const maxDist = 5; const directNeighbours = ['up', 'down', 'left', 'right']; let t, tile, n, neighbour, i, j, tv, nv, tn, nn; for (t = 0; t < tiles.length; t++) { tile = tiles[t]; // Skip over irrelevant tiles if (isIrrelevant(tile)) { continue; } // Grab the tile's body and vertices to compare with its neighbours let tileBody = tile.physics.matterBody.body; let tileVertices = tileBody.vertices; // Iterate over each direct neighbour for (n in directNeighbours) { neighbour = tile.physics.slopes.neighbours[directNeighbours[n]]; // Skip over irrelevant neighbouring tiles if (isIrrelevant(neighbour)) { continue; } // Grab the neighbour's body and vertices let neighbourBody = neighbour.physics.matterBody.body; let neighbourVertices = neighbourBody.vertices; // Skip over tile-neighbour pairs that don't overlap if (!Bounds.overlaps(tileBody.bounds, neighbourBody.bounds)) { continue; } tv = tileVertices; nv = neighbourVertices; tn = tileBody.axes; nn = neighbourBody.axes; // Iterate over the vertices of both the tile and its neighbour for (i = 0; i < tv.length; i++) { for (j = 0; j < nv.length; j++) { // Find distances between the vertices let da = Vector.magnitudeSquared(Vector.sub(tv[(i + 1) % tv.length], nv[j])), db = Vector.magnitudeSquared(Vector.sub(tv[i], nv[(j + 1) % nv.length])); // If both vertices are very close, consider the edge coincident (internal) if (da < maxDist && db < maxDist) { tv[i].isInternal = true; nv[j].isInternal = true; tn[i].ignore = true; nn[j].ignore = true; } } } } } }
[ "function", "(", "tiles", ")", "{", "const", "maxDist", "=", "5", ";", "const", "directNeighbours", "=", "[", "'up'", ",", "'down'", ",", "'left'", ",", "'right'", "]", ";", "let", "t", ",", "tile", ",", "n", ",", "neighbour", ",", "i", ",", "j", ",", "tv", ",", "nv", ",", "tn", ",", "nn", ";", "for", "(", "t", "=", "0", ";", "t", "<", "tiles", ".", "length", ";", "t", "++", ")", "{", "tile", "=", "tiles", "[", "t", "]", ";", "if", "(", "isIrrelevant", "(", "tile", ")", ")", "{", "continue", ";", "}", "let", "tileBody", "=", "tile", ".", "physics", ".", "matterBody", ".", "body", ";", "let", "tileVertices", "=", "tileBody", ".", "vertices", ";", "for", "(", "n", "in", "directNeighbours", ")", "{", "neighbour", "=", "tile", ".", "physics", ".", "slopes", ".", "neighbours", "[", "directNeighbours", "[", "n", "]", "]", ";", "if", "(", "isIrrelevant", "(", "neighbour", ")", ")", "{", "continue", ";", "}", "let", "neighbourBody", "=", "neighbour", ".", "physics", ".", "matterBody", ".", "body", ";", "let", "neighbourVertices", "=", "neighbourBody", ".", "vertices", ";", "if", "(", "!", "Bounds", ".", "overlaps", "(", "tileBody", ".", "bounds", ",", "neighbourBody", ".", "bounds", ")", ")", "{", "continue", ";", "}", "tv", "=", "tileVertices", ";", "nv", "=", "neighbourVertices", ";", "tn", "=", "tileBody", ".", "axes", ";", "nn", "=", "neighbourBody", ".", "axes", ";", "for", "(", "i", "=", "0", ";", "i", "<", "tv", ".", "length", ";", "i", "++", ")", "{", "for", "(", "j", "=", "0", ";", "j", "<", "nv", ".", "length", ";", "j", "++", ")", "{", "let", "da", "=", "Vector", ".", "magnitudeSquared", "(", "Vector", ".", "sub", "(", "tv", "[", "(", "i", "+", "1", ")", "%", "tv", ".", "length", "]", ",", "nv", "[", "j", "]", ")", ")", ",", "db", "=", "Vector", ".", "magnitudeSquared", "(", "Vector", ".", "sub", "(", "tv", "[", "i", "]", ",", "nv", "[", "(", "j", "+", "1", ")", "%", "nv", ".", "length", "]", ")", ")", ";", "if", "(", "da", "<", "maxDist", "&&", "db", "<", "maxDist", ")", "{", "tv", "[", "i", "]", ".", "isInternal", "=", "true", ";", "nv", "[", "j", "]", ".", "isInternal", "=", "true", ";", "tn", "[", "i", "]", ".", "ignore", "=", "true", ";", "nn", "[", "j", "]", ".", "ignore", "=", "true", ";", "}", "}", "}", "}", "}", "}" ]
Flag the internal edges of each tile. Compares the edges of the given tiles with their direct neighbours and flags those that match. Because the polygons are represented by a set of vertices, instead of actual edges, the first vector (assuming they are specified clockwise) of each edge is flagged instead. The same applies for edge normals, and these are also flagged to be ignored in line with their respective vertices. @param {Phaser.Tilemaps.Tile[]} tiles - The tiles to flag edges for.
[ "Flag", "the", "internal", "edges", "of", "each", "tile", "." ]
1ef1137ea4cdea920dc312f760000e2463ef40af
https://github.com/hexus/phaser-slopes/blob/1ef1137ea4cdea920dc312f760000e2463ef40af/src/Matter/World.js#L495-L554
train
MostlyJS/mostly-node
src/extensions.js
onClientPreRequestCircuitBreaker
function onClientPreRequestCircuitBreaker (ctx, next) { if (ctx._config.circuitBreaker.enabled) { // any pattern represent an own circuit breaker const circuitBreaker = ctx._circuitBreakerMap.get(ctx.trace$.method); if (!circuitBreaker) { const cb = new CircuitBreaker(ctx._config.circuitBreaker); ctx._circuitBreakerMap.set(ctx.trace$.method, cb); } else { if (!circuitBreaker.available()) { // trigger half-open timer circuitBreaker.record(); return next(new Errors.CircuitBreakerError( `Circuit breaker is ${circuitBreaker.state}`, { state: circuitBreaker.state, method: ctx.trace$.method, service: ctx.trace$.service })); } } next(); } else { next(); } }
javascript
function onClientPreRequestCircuitBreaker (ctx, next) { if (ctx._config.circuitBreaker.enabled) { // any pattern represent an own circuit breaker const circuitBreaker = ctx._circuitBreakerMap.get(ctx.trace$.method); if (!circuitBreaker) { const cb = new CircuitBreaker(ctx._config.circuitBreaker); ctx._circuitBreakerMap.set(ctx.trace$.method, cb); } else { if (!circuitBreaker.available()) { // trigger half-open timer circuitBreaker.record(); return next(new Errors.CircuitBreakerError( `Circuit breaker is ${circuitBreaker.state}`, { state: circuitBreaker.state, method: ctx.trace$.method, service: ctx.trace$.service })); } } next(); } else { next(); } }
[ "function", "onClientPreRequestCircuitBreaker", "(", "ctx", ",", "next", ")", "{", "if", "(", "ctx", ".", "_config", ".", "circuitBreaker", ".", "enabled", ")", "{", "const", "circuitBreaker", "=", "ctx", ".", "_circuitBreakerMap", ".", "get", "(", "ctx", ".", "trace$", ".", "method", ")", ";", "if", "(", "!", "circuitBreaker", ")", "{", "const", "cb", "=", "new", "CircuitBreaker", "(", "ctx", ".", "_config", ".", "circuitBreaker", ")", ";", "ctx", ".", "_circuitBreakerMap", ".", "set", "(", "ctx", ".", "trace$", ".", "method", ",", "cb", ")", ";", "}", "else", "{", "if", "(", "!", "circuitBreaker", ".", "available", "(", ")", ")", "{", "circuitBreaker", ".", "record", "(", ")", ";", "return", "next", "(", "new", "Errors", ".", "CircuitBreakerError", "(", "`", "${", "circuitBreaker", ".", "state", "}", "`", ",", "{", "state", ":", "circuitBreaker", ".", "state", ",", "method", ":", "ctx", ".", "trace$", ".", "method", ",", "service", ":", "ctx", ".", "trace$", ".", "service", "}", ")", ")", ";", "}", "}", "next", "(", ")", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}" ]
circuit breaker on client side
[ "circuit", "breaker", "on", "client", "side" ]
694b1d44bf089a48a183f239e90e5ca7b7b921b8
https://github.com/MostlyJS/mostly-node/blob/694b1d44bf089a48a183f239e90e5ca7b7b921b8/src/extensions.js#L75-L96
train
bojand/grpc-inspect
lib/util.js
function (namespace) { if (namespace) { if (!this.namespaces[namespace]) { return [] } return _.keys(this.namespaces[namespace].services) } else { const r = [] _.forOwn(this.namespaces, n => r.push(..._.keys(n.services))) return r } }
javascript
function (namespace) { if (namespace) { if (!this.namespaces[namespace]) { return [] } return _.keys(this.namespaces[namespace].services) } else { const r = [] _.forOwn(this.namespaces, n => r.push(..._.keys(n.services))) return r } }
[ "function", "(", "namespace", ")", "{", "if", "(", "namespace", ")", "{", "if", "(", "!", "this", ".", "namespaces", "[", "namespace", "]", ")", "{", "return", "[", "]", "}", "return", "_", ".", "keys", "(", "this", ".", "namespaces", "[", "namespace", "]", ".", "services", ")", "}", "else", "{", "const", "r", "=", "[", "]", "_", ".", "forOwn", "(", "this", ".", "namespaces", ",", "n", "=>", "r", ".", "push", "(", "...", "_", ".", "keys", "(", "n", ".", "services", ")", ")", ")", "return", "r", "}", "}" ]
Returns an array of service names @param {String} namespace Optional name of namespace to get services. If not present returns service names of all services within the definition. @return {Array} array of names @memberof descriptor @example const grpcinspect = require('grpc-inspect') const grpc = require('grpc') const pbpath = path.resolve(__dirname, './route_guide.proto') const proto = grpc.load(pbpath) const d = const grpcinspect(proto) console.log(d.serviceNames()) // ['RouteGuide']
[ "Returns", "an", "array", "of", "service", "names" ]
2f4e87f1cb39cde1a1561a83435baac5c316e279
https://github.com/bojand/grpc-inspect/blob/2f4e87f1cb39cde1a1561a83435baac5c316e279/lib/util.js#L51-L62
train
bojand/grpc-inspect
lib/util.js
function (service) { let s const ns = _.values(this.namespaces) if (!ns || !ns.length) { return s } for (let i = 0; i < ns.length; i++) { const n = ns[i] if (n.services[service]) { s = n.services[service] break } } return s }
javascript
function (service) { let s const ns = _.values(this.namespaces) if (!ns || !ns.length) { return s } for (let i = 0; i < ns.length; i++) { const n = ns[i] if (n.services[service]) { s = n.services[service] break } } return s }
[ "function", "(", "service", ")", "{", "let", "s", "const", "ns", "=", "_", ".", "values", "(", "this", ".", "namespaces", ")", "if", "(", "!", "ns", "||", "!", "ns", ".", "length", ")", "{", "return", "s", "}", "for", "(", "let", "i", "=", "0", ";", "i", "<", "ns", ".", "length", ";", "i", "++", ")", "{", "const", "n", "=", "ns", "[", "i", "]", "if", "(", "n", ".", "services", "[", "service", "]", ")", "{", "s", "=", "n", ".", "services", "[", "service", "]", "break", "}", "}", "return", "s", "}" ]
Returns the utility descriptor for the service given a servie name. Assumes there are no duplicate service names within the definition. @param {String} service name of the service @return {Object} service utility descriptor @memberof descriptor @example const grpcinspect = require('grpc-inspect') const grpc = require('grpc') const pbpath = path.resolve(__dirname, './route_guide.proto') const proto = grpc.load(pbpath) const d = grpcinspect(proto) console.dir(d.service('RouteGuide'))
[ "Returns", "the", "utility", "descriptor", "for", "the", "service", "given", "a", "servie", "name", ".", "Assumes", "there", "are", "no", "duplicate", "service", "names", "within", "the", "definition", "." ]
2f4e87f1cb39cde1a1561a83435baac5c316e279
https://github.com/bojand/grpc-inspect/blob/2f4e87f1cb39cde1a1561a83435baac5c316e279/lib/util.js#L78-L94
train
nodejitsu/godot
lib/godot/reactor/has-meta.js
hasKey
function hasKey(key) { return data.meta[key] !== undefined && (self.lookup[key] === null || self.lookup[key] === data.meta[key]); }
javascript
function hasKey(key) { return data.meta[key] !== undefined && (self.lookup[key] === null || self.lookup[key] === data.meta[key]); }
[ "function", "hasKey", "(", "key", ")", "{", "return", "data", ".", "meta", "[", "key", "]", "!==", "undefined", "&&", "(", "self", ".", "lookup", "[", "key", "]", "===", "null", "||", "self", ".", "lookup", "[", "key", "]", "===", "data", ".", "meta", "[", "key", "]", ")", ";", "}" ]
Helper function for checking a given `key`.
[ "Helper", "function", "for", "checking", "a", "given", "key", "." ]
fc2397c8282ad97de17a807b2ea4498a0365e77e
https://github.com/nodejitsu/godot/blob/fc2397c8282ad97de17a807b2ea4498a0365e77e/lib/godot/reactor/has-meta.js#L83-L87
train
jeremyben/nunjucks-cli
index.js
render
function render(file, data, outputDir) { if (!argv.unsafe && path.extname(file) === '.html') return console.error(chalk.red(file + ': To use .html as source files, add --unsafe/-u flag')) env.render(file, data, function(err, res) { if (err) return console.error(chalk.red(err)) var outputFile = file.replace(/\.\w+$/, '') + '.html' if (outputDir) { outputFile = path.resolve(outputDir, outputFile) mkdirp.sync(path.dirname(outputFile)) } console.log(chalk.blue('Rendering: ' + file)) fs.writeFileSync(outputFile, res) }) }
javascript
function render(file, data, outputDir) { if (!argv.unsafe && path.extname(file) === '.html') return console.error(chalk.red(file + ': To use .html as source files, add --unsafe/-u flag')) env.render(file, data, function(err, res) { if (err) return console.error(chalk.red(err)) var outputFile = file.replace(/\.\w+$/, '') + '.html' if (outputDir) { outputFile = path.resolve(outputDir, outputFile) mkdirp.sync(path.dirname(outputFile)) } console.log(chalk.blue('Rendering: ' + file)) fs.writeFileSync(outputFile, res) }) }
[ "function", "render", "(", "file", ",", "data", ",", "outputDir", ")", "{", "if", "(", "!", "argv", ".", "unsafe", "&&", "path", ".", "extname", "(", "file", ")", "===", "'.html'", ")", "return", "console", ".", "error", "(", "chalk", ".", "red", "(", "file", "+", "': To use .html as source files, add --unsafe/-u flag'", ")", ")", "env", ".", "render", "(", "file", ",", "data", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "return", "console", ".", "error", "(", "chalk", ".", "red", "(", "err", ")", ")", "var", "outputFile", "=", "file", ".", "replace", "(", "/", "\\.\\w+$", "/", ",", "''", ")", "+", "'.html'", "if", "(", "outputDir", ")", "{", "outputFile", "=", "path", ".", "resolve", "(", "outputDir", ",", "outputFile", ")", "mkdirp", ".", "sync", "(", "path", ".", "dirname", "(", "outputFile", ")", ")", "}", "console", ".", "log", "(", "chalk", ".", "blue", "(", "'Rendering: '", "+", "file", ")", ")", "fs", ".", "writeFileSync", "(", "outputFile", ",", "res", ")", "}", ")", "}" ]
Render one file
[ "Render", "one", "file" ]
2f0319072841de394fbd204031b2f3bbd4ccf2ed
https://github.com/jeremyben/nunjucks-cli/blob/2f0319072841de394fbd204031b2f3bbd4ccf2ed/index.js#L123-L138
train
jeremyben/nunjucks-cli
index.js
renderAll
function renderAll(files, data, outputDir) { for (var i = 0; i < files.length; i++) { render(files[i], data, outputDir) } }
javascript
function renderAll(files, data, outputDir) { for (var i = 0; i < files.length; i++) { render(files[i], data, outputDir) } }
[ "function", "renderAll", "(", "files", ",", "data", ",", "outputDir", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "files", ".", "length", ";", "i", "++", ")", "{", "render", "(", "files", "[", "i", "]", ",", "data", ",", "outputDir", ")", "}", "}" ]
Render multiple files
[ "Render", "multiple", "files" ]
2f0319072841de394fbd204031b2f3bbd4ccf2ed
https://github.com/jeremyben/nunjucks-cli/blob/2f0319072841de394fbd204031b2f3bbd4ccf2ed/index.js#L141-L147
train
jonschlinkert/yarn-api
index.js
yarn
function yarn(cmds, args, cb) { if (typeof args === 'function') { return yarn(cmds, [], args); } args = arrayify(cmds).concat(arrayify(args)); spawn('yarn', args, {cwd: cwd, stdio: 'inherit'}) .on('error', cb) .on('close', function(code, err) { cb(err, code); }); }
javascript
function yarn(cmds, args, cb) { if (typeof args === 'function') { return yarn(cmds, [], args); } args = arrayify(cmds).concat(arrayify(args)); spawn('yarn', args, {cwd: cwd, stdio: 'inherit'}) .on('error', cb) .on('close', function(code, err) { cb(err, code); }); }
[ "function", "yarn", "(", "cmds", ",", "args", ",", "cb", ")", "{", "if", "(", "typeof", "args", "===", "'function'", ")", "{", "return", "yarn", "(", "cmds", ",", "[", "]", ",", "args", ")", ";", "}", "args", "=", "arrayify", "(", "cmds", ")", ".", "concat", "(", "arrayify", "(", "args", ")", ")", ";", "spawn", "(", "'yarn'", ",", "args", ",", "{", "cwd", ":", "cwd", ",", "stdio", ":", "'inherit'", "}", ")", ".", "on", "(", "'error'", ",", "cb", ")", ".", "on", "(", "'close'", ",", "function", "(", "code", ",", "err", ")", "{", "cb", "(", "err", ",", "code", ")", ";", "}", ")", ";", "}" ]
Run `yarn` with the given `cmds`, `args` and callback. ```js yarn(['add', 'isobject'], function(err) { if (err) throw err; }); ``` @param {String|Array} `cmds` @param {String|Array} `args` @param {Function} `cb` Callback @details false @api public
[ "Run", "yarn", "with", "the", "given", "cmds", "args", "and", "callback", "." ]
d3ef806233844fc95afc1b6755bceb1941033387
https://github.com/jonschlinkert/yarn-api/blob/d3ef806233844fc95afc1b6755bceb1941033387/index.js#L33-L44
train
jonschlinkert/yarn-api
index.js
deps
function deps(type, flags, names, cb) { names = flatten([].slice.call(arguments, 2)); cb = names.pop(); if (type && names.length === 0) { names = keys(type); } if (!names.length) { cb(); return; } yarn.add(arrayify(flags).concat(names), cb); }
javascript
function deps(type, flags, names, cb) { names = flatten([].slice.call(arguments, 2)); cb = names.pop(); if (type && names.length === 0) { names = keys(type); } if (!names.length) { cb(); return; } yarn.add(arrayify(flags).concat(names), cb); }
[ "function", "deps", "(", "type", ",", "flags", ",", "names", ",", "cb", ")", "{", "names", "=", "flatten", "(", "[", "]", ".", "slice", ".", "call", "(", "arguments", ",", "2", ")", ")", ";", "cb", "=", "names", ".", "pop", "(", ")", ";", "if", "(", "type", "&&", "names", ".", "length", "===", "0", ")", "{", "names", "=", "keys", "(", "type", ")", ";", "}", "if", "(", "!", "names", ".", "length", ")", "{", "cb", "(", ")", ";", "return", ";", "}", "yarn", ".", "add", "(", "arrayify", "(", "flags", ")", ".", "concat", "(", "names", ")", ",", "cb", ")", ";", "}" ]
Install the given `type` of dependencies, with the specified `flags`
[ "Install", "the", "given", "type", "of", "dependencies", "with", "the", "specified", "flags" ]
d3ef806233844fc95afc1b6755bceb1941033387
https://github.com/jonschlinkert/yarn-api/blob/d3ef806233844fc95afc1b6755bceb1941033387/index.js#L298-L312
train
BorisKozo/node-async-locks
lib/async-lock.js
function (options) { this.queue = []; this.ownerTokenId = null; this.options = _.extend({}, AsyncLock.defaultOptions, options); }
javascript
function (options) { this.queue = []; this.ownerTokenId = null; this.options = _.extend({}, AsyncLock.defaultOptions, options); }
[ "function", "(", "options", ")", "{", "this", ".", "queue", "=", "[", "]", ";", "this", ".", "ownerTokenId", "=", "null", ";", "this", ".", "options", "=", "_", ".", "extend", "(", "{", "}", ",", "AsyncLock", ".", "defaultOptions", ",", "options", ")", ";", "}" ]
An asynchronous lock. @constructor @param {object} options - optional set of options for this lock
[ "An", "asynchronous", "lock", "." ]
ba0e5c998a06612527d510233d179b123129f84a
https://github.com/BorisKozo/node-async-locks/blob/ba0e5c998a06612527d510233d179b123129f84a/lib/async-lock.js#L22-L26
train
Jeff2Ma/postcss-lazysprite
index.js
applyGroupBy
function applyGroupBy(images, options) { return Promise.reduce(options.groupBy, function (images, group) { return Promise.map(images, function (image) { return Promise.resolve(group(image)).then(function (group) { if (group) { image.groups.push(group); } return image; }).catch(function (image) { return image; }); }); }, images).then(function (images) { return [images, options]; }); }
javascript
function applyGroupBy(images, options) { return Promise.reduce(options.groupBy, function (images, group) { return Promise.map(images, function (image) { return Promise.resolve(group(image)).then(function (group) { if (group) { image.groups.push(group); } return image; }).catch(function (image) { return image; }); }); }, images).then(function (images) { return [images, options]; }); }
[ "function", "applyGroupBy", "(", "images", ",", "options", ")", "{", "return", "Promise", ".", "reduce", "(", "options", ".", "groupBy", ",", "function", "(", "images", ",", "group", ")", "{", "return", "Promise", ".", "map", "(", "images", ",", "function", "(", "image", ")", "{", "return", "Promise", ".", "resolve", "(", "group", "(", "image", ")", ")", ".", "then", "(", "function", "(", "group", ")", "{", "if", "(", "group", ")", "{", "image", ".", "groups", ".", "push", "(", "group", ")", ";", "}", "return", "image", ";", "}", ")", ".", "catch", "(", "function", "(", "image", ")", "{", "return", "image", ";", "}", ")", ";", "}", ")", ";", "}", ",", "images", ")", ".", "then", "(", "function", "(", "images", ")", "{", "return", "[", "images", ",", "options", "]", ";", "}", ")", ";", "}" ]
Apply groupBy functions over collection of exported images. @param {Object} options @param {Array} images @return {Promise}
[ "Apply", "groupBy", "functions", "over", "collection", "of", "exported", "images", "." ]
96725425a6d67fdb0c79ce476c33af55337aea9b
https://github.com/Jeff2Ma/postcss-lazysprite/blob/96725425a6d67fdb0c79ce476c33af55337aea9b/index.js#L260-L275
train
Jeff2Ma/postcss-lazysprite
index.js
setTokens
function setTokens(images, options, css) { return new Promise(function (resolve) { css.walkAtRules('lazysprite', function (atRule) { // Get the directory of images from atRule value var params = space(atRule.params); var atRuleValue = getAtRuleValue(params); var sliceDir = atRuleValue[0]; var sliceDirname = sliceDir.split(path.sep).pop(); var atRuleParent = atRule.parent; var mediaAtRule2x = postcss.atRule({name: 'media', params: resolutions2x.join(', ')}); var mediaAtRule3x = postcss.atRule({name: 'media', params: resolutions3x.join(', ')}); // Tag flag var has2x = false; var has3x = false; if (options.outputExtralCSS) { var outputExtralCSSRule = postcss.rule({ selector: '.' + options.nameSpace + (atRuleValue[1] ? atRuleValue[1] : sliceDirname), source: atRule.source }); outputExtralCSSRule.append({prop: 'display', value: 'inline-block'}); outputExtralCSSRule.append({prop: 'overflow', value: 'hidden'}); outputExtralCSSRule.append({prop: 'font-size', value: '0'}); outputExtralCSSRule.append({prop: 'line-height', value: '0'}); atRule.before(outputExtralCSSRule); } // Foreach every image object _.forEach(images, function (image) { // Only work when equal to directory name if (sliceDirname === image.dir) { image.token = postcss.comment({ text: image.path, raws: { between: options.cloneRaws.between, after: options.cloneRaws.after, left: '@replace|', right: '' } }); // Add `source` argument for source map create. var singleRule = postcss.rule({ selector: '.' + options.nameSpace + image.selector, source: atRule.source }); singleRule.append(image.token); switch (image.ratio) { // @1x case 1: atRuleParent.insertBefore(atRule, singleRule); break; // @2x case 2: mediaAtRule2x.append(singleRule); has2x = true; break; // @3x case 3: mediaAtRule3x.append(singleRule); has3x = true; break; default: break; } } }); // @2x @3x media rule are last. if (has2x) { atRuleParent.insertBefore(atRule, mediaAtRule2x); } if (has3x) { atRuleParent.insertBefore(atRule, mediaAtRule3x); } atRule.remove(); }); resolve([images, options]); }); }
javascript
function setTokens(images, options, css) { return new Promise(function (resolve) { css.walkAtRules('lazysprite', function (atRule) { // Get the directory of images from atRule value var params = space(atRule.params); var atRuleValue = getAtRuleValue(params); var sliceDir = atRuleValue[0]; var sliceDirname = sliceDir.split(path.sep).pop(); var atRuleParent = atRule.parent; var mediaAtRule2x = postcss.atRule({name: 'media', params: resolutions2x.join(', ')}); var mediaAtRule3x = postcss.atRule({name: 'media', params: resolutions3x.join(', ')}); // Tag flag var has2x = false; var has3x = false; if (options.outputExtralCSS) { var outputExtralCSSRule = postcss.rule({ selector: '.' + options.nameSpace + (atRuleValue[1] ? atRuleValue[1] : sliceDirname), source: atRule.source }); outputExtralCSSRule.append({prop: 'display', value: 'inline-block'}); outputExtralCSSRule.append({prop: 'overflow', value: 'hidden'}); outputExtralCSSRule.append({prop: 'font-size', value: '0'}); outputExtralCSSRule.append({prop: 'line-height', value: '0'}); atRule.before(outputExtralCSSRule); } // Foreach every image object _.forEach(images, function (image) { // Only work when equal to directory name if (sliceDirname === image.dir) { image.token = postcss.comment({ text: image.path, raws: { between: options.cloneRaws.between, after: options.cloneRaws.after, left: '@replace|', right: '' } }); // Add `source` argument for source map create. var singleRule = postcss.rule({ selector: '.' + options.nameSpace + image.selector, source: atRule.source }); singleRule.append(image.token); switch (image.ratio) { // @1x case 1: atRuleParent.insertBefore(atRule, singleRule); break; // @2x case 2: mediaAtRule2x.append(singleRule); has2x = true; break; // @3x case 3: mediaAtRule3x.append(singleRule); has3x = true; break; default: break; } } }); // @2x @3x media rule are last. if (has2x) { atRuleParent.insertBefore(atRule, mediaAtRule2x); } if (has3x) { atRuleParent.insertBefore(atRule, mediaAtRule3x); } atRule.remove(); }); resolve([images, options]); }); }
[ "function", "setTokens", "(", "images", ",", "options", ",", "css", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "css", ".", "walkAtRules", "(", "'lazysprite'", ",", "function", "(", "atRule", ")", "{", "var", "params", "=", "space", "(", "atRule", ".", "params", ")", ";", "var", "atRuleValue", "=", "getAtRuleValue", "(", "params", ")", ";", "var", "sliceDir", "=", "atRuleValue", "[", "0", "]", ";", "var", "sliceDirname", "=", "sliceDir", ".", "split", "(", "path", ".", "sep", ")", ".", "pop", "(", ")", ";", "var", "atRuleParent", "=", "atRule", ".", "parent", ";", "var", "mediaAtRule2x", "=", "postcss", ".", "atRule", "(", "{", "name", ":", "'media'", ",", "params", ":", "resolutions2x", ".", "join", "(", "', '", ")", "}", ")", ";", "var", "mediaAtRule3x", "=", "postcss", ".", "atRule", "(", "{", "name", ":", "'media'", ",", "params", ":", "resolutions3x", ".", "join", "(", "', '", ")", "}", ")", ";", "var", "has2x", "=", "false", ";", "var", "has3x", "=", "false", ";", "if", "(", "options", ".", "outputExtralCSS", ")", "{", "var", "outputExtralCSSRule", "=", "postcss", ".", "rule", "(", "{", "selector", ":", "'.'", "+", "options", ".", "nameSpace", "+", "(", "atRuleValue", "[", "1", "]", "?", "atRuleValue", "[", "1", "]", ":", "sliceDirname", ")", ",", "source", ":", "atRule", ".", "source", "}", ")", ";", "outputExtralCSSRule", ".", "append", "(", "{", "prop", ":", "'display'", ",", "value", ":", "'inline-block'", "}", ")", ";", "outputExtralCSSRule", ".", "append", "(", "{", "prop", ":", "'overflow'", ",", "value", ":", "'hidden'", "}", ")", ";", "outputExtralCSSRule", ".", "append", "(", "{", "prop", ":", "'font-size'", ",", "value", ":", "'0'", "}", ")", ";", "outputExtralCSSRule", ".", "append", "(", "{", "prop", ":", "'line-height'", ",", "value", ":", "'0'", "}", ")", ";", "atRule", ".", "before", "(", "outputExtralCSSRule", ")", ";", "}", "_", ".", "forEach", "(", "images", ",", "function", "(", "image", ")", "{", "if", "(", "sliceDirname", "===", "image", ".", "dir", ")", "{", "image", ".", "token", "=", "postcss", ".", "comment", "(", "{", "text", ":", "image", ".", "path", ",", "raws", ":", "{", "between", ":", "options", ".", "cloneRaws", ".", "between", ",", "after", ":", "options", ".", "cloneRaws", ".", "after", ",", "left", ":", "'@replace|'", ",", "right", ":", "''", "}", "}", ")", ";", "var", "singleRule", "=", "postcss", ".", "rule", "(", "{", "selector", ":", "'.'", "+", "options", ".", "nameSpace", "+", "image", ".", "selector", ",", "source", ":", "atRule", ".", "source", "}", ")", ";", "singleRule", ".", "append", "(", "image", ".", "token", ")", ";", "switch", "(", "image", ".", "ratio", ")", "{", "case", "1", ":", "atRuleParent", ".", "insertBefore", "(", "atRule", ",", "singleRule", ")", ";", "break", ";", "case", "2", ":", "mediaAtRule2x", ".", "append", "(", "singleRule", ")", ";", "has2x", "=", "true", ";", "break", ";", "case", "3", ":", "mediaAtRule3x", ".", "append", "(", "singleRule", ")", ";", "has3x", "=", "true", ";", "break", ";", "default", ":", "break", ";", "}", "}", "}", ")", ";", "if", "(", "has2x", ")", "{", "atRuleParent", ".", "insertBefore", "(", "atRule", ",", "mediaAtRule2x", ")", ";", "}", "if", "(", "has3x", ")", "{", "atRuleParent", ".", "insertBefore", "(", "atRule", ",", "mediaAtRule3x", ")", ";", "}", "atRule", ".", "remove", "(", ")", ";", "}", ")", ";", "resolve", "(", "[", "images", ",", "options", "]", ")", ";", "}", ")", ";", "}" ]
Set the necessary tokens info to the background declarations. @param {Node} css @param {Object} options @param {Array} images @return {Promise}
[ "Set", "the", "necessary", "tokens", "info", "to", "the", "background", "declarations", "." ]
96725425a6d67fdb0c79ce476c33af55337aea9b
https://github.com/Jeff2Ma/postcss-lazysprite/blob/96725425a6d67fdb0c79ce476c33af55337aea9b/index.js#L284-L368
train
Jeff2Ma/postcss-lazysprite
index.js
saveSprites
function saveSprites(images, options, sprites) { return new Promise(function (resolve, reject) { if (!fs.existsSync(options.spritePath)) { mkdirp.sync(options.spritePath); } var all = _ .chain(sprites) .map(function (sprite) { sprite.path = makeSpritePath(options, sprite.groups); var deferred = Promise.pending(); // If this file is up to date if (sprite.isFromCache) { log(options.logLevel, 'lv3', ['Lazysprite:', colors.yellow(path.relative(process.cwd(), sprite.path)), 'unchanged.']); deferred.resolve(sprite); return deferred.promise; } // Save new file version return fs.writeFileAsync(sprite.path, Buffer.from(sprite.image, 'binary')) .then(function () { log(options.logLevel, 'lv2', ['Lazysprite:', colors.green(path.relative(process.cwd(), sprite.path)), 'generated.']); return sprite; }); }) .value(); Promise.all(all) .then(function (sprites) { resolve([images, options, sprites]); }) .catch(function (err) { if (err) { reject(err); } }); }); }
javascript
function saveSprites(images, options, sprites) { return new Promise(function (resolve, reject) { if (!fs.existsSync(options.spritePath)) { mkdirp.sync(options.spritePath); } var all = _ .chain(sprites) .map(function (sprite) { sprite.path = makeSpritePath(options, sprite.groups); var deferred = Promise.pending(); // If this file is up to date if (sprite.isFromCache) { log(options.logLevel, 'lv3', ['Lazysprite:', colors.yellow(path.relative(process.cwd(), sprite.path)), 'unchanged.']); deferred.resolve(sprite); return deferred.promise; } // Save new file version return fs.writeFileAsync(sprite.path, Buffer.from(sprite.image, 'binary')) .then(function () { log(options.logLevel, 'lv2', ['Lazysprite:', colors.green(path.relative(process.cwd(), sprite.path)), 'generated.']); return sprite; }); }) .value(); Promise.all(all) .then(function (sprites) { resolve([images, options, sprites]); }) .catch(function (err) { if (err) { reject(err); } }); }); }
[ "function", "saveSprites", "(", "images", ",", "options", ",", "sprites", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "options", ".", "spritePath", ")", ")", "{", "mkdirp", ".", "sync", "(", "options", ".", "spritePath", ")", ";", "}", "var", "all", "=", "_", ".", "chain", "(", "sprites", ")", ".", "map", "(", "function", "(", "sprite", ")", "{", "sprite", ".", "path", "=", "makeSpritePath", "(", "options", ",", "sprite", ".", "groups", ")", ";", "var", "deferred", "=", "Promise", ".", "pending", "(", ")", ";", "if", "(", "sprite", ".", "isFromCache", ")", "{", "log", "(", "options", ".", "logLevel", ",", "'lv3'", ",", "[", "'Lazysprite:'", ",", "colors", ".", "yellow", "(", "path", ".", "relative", "(", "process", ".", "cwd", "(", ")", ",", "sprite", ".", "path", ")", ")", ",", "'unchanged.'", "]", ")", ";", "deferred", ".", "resolve", "(", "sprite", ")", ";", "return", "deferred", ".", "promise", ";", "}", "return", "fs", ".", "writeFileAsync", "(", "sprite", ".", "path", ",", "Buffer", ".", "from", "(", "sprite", ".", "image", ",", "'binary'", ")", ")", ".", "then", "(", "function", "(", ")", "{", "log", "(", "options", ".", "logLevel", ",", "'lv2'", ",", "[", "'Lazysprite:'", ",", "colors", ".", "green", "(", "path", ".", "relative", "(", "process", ".", "cwd", "(", ")", ",", "sprite", ".", "path", ")", ")", ",", "'generated.'", "]", ")", ";", "return", "sprite", ";", "}", ")", ";", "}", ")", ".", "value", "(", ")", ";", "Promise", ".", "all", "(", "all", ")", ".", "then", "(", "function", "(", "sprites", ")", "{", "resolve", "(", "[", "images", ",", "options", ",", "sprites", "]", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Save the sprites to the target path. @param {Object} options @param {Array} images @param {Array} sprites @return {Promise}
[ "Save", "the", "sprites", "to", "the", "target", "path", "." ]
96725425a6d67fdb0c79ce476c33af55337aea9b
https://github.com/Jeff2Ma/postcss-lazysprite/blob/96725425a6d67fdb0c79ce476c33af55337aea9b/index.js#L525-L563
train
Jeff2Ma/postcss-lazysprite
index.js
mapSpritesProperties
function mapSpritesProperties(images, options, sprites) { return new Promise(function (resolve) { sprites = _.map(sprites, function (sprite) { return _.map(sprite.coordinates, function (coordinates, imagePath) { return _.merge(_.find(images, {path: imagePath}), { coordinates: coordinates, spritePath: sprite.path, properties: sprite.properties }); }); }); resolve([images, options, sprites]); }); }
javascript
function mapSpritesProperties(images, options, sprites) { return new Promise(function (resolve) { sprites = _.map(sprites, function (sprite) { return _.map(sprite.coordinates, function (coordinates, imagePath) { return _.merge(_.find(images, {path: imagePath}), { coordinates: coordinates, spritePath: sprite.path, properties: sprite.properties }); }); }); resolve([images, options, sprites]); }); }
[ "function", "mapSpritesProperties", "(", "images", ",", "options", ",", "sprites", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "sprites", "=", "_", ".", "map", "(", "sprites", ",", "function", "(", "sprite", ")", "{", "return", "_", ".", "map", "(", "sprite", ".", "coordinates", ",", "function", "(", "coordinates", ",", "imagePath", ")", "{", "return", "_", ".", "merge", "(", "_", ".", "find", "(", "images", ",", "{", "path", ":", "imagePath", "}", ")", ",", "{", "coordinates", ":", "coordinates", ",", "spritePath", ":", "sprite", ".", "path", ",", "properties", ":", "sprite", ".", "properties", "}", ")", ";", "}", ")", ";", "}", ")", ";", "resolve", "(", "[", "images", ",", "options", ",", "sprites", "]", ")", ";", "}", ")", ";", "}" ]
Map sprites props for every image. @param {Object} options @param {Array} images @param {Array} sprites @return {Promise}
[ "Map", "sprites", "props", "for", "every", "image", "." ]
96725425a6d67fdb0c79ce476c33af55337aea9b
https://github.com/Jeff2Ma/postcss-lazysprite/blob/96725425a6d67fdb0c79ce476c33af55337aea9b/index.js#L572-L585
train
Jeff2Ma/postcss-lazysprite
index.js
updateReferences
function updateReferences(images, options, sprites, css) { return new Promise(function (resolve) { css.walkComments(function (comment) { var rule, image, backgroundImage, backgroundPosition, backgroundSize; // Manipulate only token comments if (isToken(comment)) { // Match from the path with the tokens comments image = _.find(images, {path: comment.text}); if (image) { // 2x check even dimensions. if (image.ratio === 2 && (image.coordinates.width % 2 !== 0 || image.coordinates.height % 2 !== 0)) { throw log(options.logLevel, 'lv1', ['Lazysprite:', colors.red(path.relative(process.cwd(), image.path)), '`2x` image should have' + ' even dimensions.']); } // 3x check dimensions. if (image.ratio === 3 && (image.coordinates.width % 3 !== 0 || image.coordinates.height % 3 !== 0)) { throw log(options.logLevel, 'lv1', ['Lazysprite:', colors.red(path.relative(process.cwd(), image.path)), '`3x` image should have' + ' correct dimensions.']); } // Generate correct ref to the sprite image.spriteRef = path.relative(image.stylesheetRelative, image.spritePath); image.spriteRef = image.spriteRef.split(path.sep).join('/'); backgroundImage = postcss.decl({ prop: 'background-image', value: getBackgroundImageUrl(image) }); backgroundPosition = postcss.decl({ prop: 'background-position', value: getBackgroundPosition(image) }); // Replace the comment and append necessary properties. comment.replaceWith(backgroundImage); // Output the dimensions (only with 1x) if (options.outputDimensions && image.ratio === 1) { ['height', 'width'].forEach(function (prop) { backgroundImage.after( postcss.decl({ prop: prop, value: (image.ratio > 1 ? image.coordinates[prop] / image.ratio : image.coordinates[prop]) + 'px' }) ); }); } backgroundImage.after(backgroundPosition); if (image.ratio > 1) { backgroundSize = postcss.decl({ prop: 'background-size', value: getBackgroundSize(image) }); backgroundPosition.after(backgroundSize); } } } }); resolve([images, options, sprites, css]); }); }
javascript
function updateReferences(images, options, sprites, css) { return new Promise(function (resolve) { css.walkComments(function (comment) { var rule, image, backgroundImage, backgroundPosition, backgroundSize; // Manipulate only token comments if (isToken(comment)) { // Match from the path with the tokens comments image = _.find(images, {path: comment.text}); if (image) { // 2x check even dimensions. if (image.ratio === 2 && (image.coordinates.width % 2 !== 0 || image.coordinates.height % 2 !== 0)) { throw log(options.logLevel, 'lv1', ['Lazysprite:', colors.red(path.relative(process.cwd(), image.path)), '`2x` image should have' + ' even dimensions.']); } // 3x check dimensions. if (image.ratio === 3 && (image.coordinates.width % 3 !== 0 || image.coordinates.height % 3 !== 0)) { throw log(options.logLevel, 'lv1', ['Lazysprite:', colors.red(path.relative(process.cwd(), image.path)), '`3x` image should have' + ' correct dimensions.']); } // Generate correct ref to the sprite image.spriteRef = path.relative(image.stylesheetRelative, image.spritePath); image.spriteRef = image.spriteRef.split(path.sep).join('/'); backgroundImage = postcss.decl({ prop: 'background-image', value: getBackgroundImageUrl(image) }); backgroundPosition = postcss.decl({ prop: 'background-position', value: getBackgroundPosition(image) }); // Replace the comment and append necessary properties. comment.replaceWith(backgroundImage); // Output the dimensions (only with 1x) if (options.outputDimensions && image.ratio === 1) { ['height', 'width'].forEach(function (prop) { backgroundImage.after( postcss.decl({ prop: prop, value: (image.ratio > 1 ? image.coordinates[prop] / image.ratio : image.coordinates[prop]) + 'px' }) ); }); } backgroundImage.after(backgroundPosition); if (image.ratio > 1) { backgroundSize = postcss.decl({ prop: 'background-size', value: getBackgroundSize(image) }); backgroundPosition.after(backgroundSize); } } } }); resolve([images, options, sprites, css]); }); }
[ "function", "updateReferences", "(", "images", ",", "options", ",", "sprites", ",", "css", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "css", ".", "walkComments", "(", "function", "(", "comment", ")", "{", "var", "rule", ",", "image", ",", "backgroundImage", ",", "backgroundPosition", ",", "backgroundSize", ";", "if", "(", "isToken", "(", "comment", ")", ")", "{", "image", "=", "_", ".", "find", "(", "images", ",", "{", "path", ":", "comment", ".", "text", "}", ")", ";", "if", "(", "image", ")", "{", "if", "(", "image", ".", "ratio", "===", "2", "&&", "(", "image", ".", "coordinates", ".", "width", "%", "2", "!==", "0", "||", "image", ".", "coordinates", ".", "height", "%", "2", "!==", "0", ")", ")", "{", "throw", "log", "(", "options", ".", "logLevel", ",", "'lv1'", ",", "[", "'Lazysprite:'", ",", "colors", ".", "red", "(", "path", ".", "relative", "(", "process", ".", "cwd", "(", ")", ",", "image", ".", "path", ")", ")", ",", "'`2x` image should have'", "+", "' even dimensions.'", "]", ")", ";", "}", "if", "(", "image", ".", "ratio", "===", "3", "&&", "(", "image", ".", "coordinates", ".", "width", "%", "3", "!==", "0", "||", "image", ".", "coordinates", ".", "height", "%", "3", "!==", "0", ")", ")", "{", "throw", "log", "(", "options", ".", "logLevel", ",", "'lv1'", ",", "[", "'Lazysprite:'", ",", "colors", ".", "red", "(", "path", ".", "relative", "(", "process", ".", "cwd", "(", ")", ",", "image", ".", "path", ")", ")", ",", "'`3x` image should have'", "+", "' correct dimensions.'", "]", ")", ";", "}", "image", ".", "spriteRef", "=", "path", ".", "relative", "(", "image", ".", "stylesheetRelative", ",", "image", ".", "spritePath", ")", ";", "image", ".", "spriteRef", "=", "image", ".", "spriteRef", ".", "split", "(", "path", ".", "sep", ")", ".", "join", "(", "'/'", ")", ";", "backgroundImage", "=", "postcss", ".", "decl", "(", "{", "prop", ":", "'background-image'", ",", "value", ":", "getBackgroundImageUrl", "(", "image", ")", "}", ")", ";", "backgroundPosition", "=", "postcss", ".", "decl", "(", "{", "prop", ":", "'background-position'", ",", "value", ":", "getBackgroundPosition", "(", "image", ")", "}", ")", ";", "comment", ".", "replaceWith", "(", "backgroundImage", ")", ";", "if", "(", "options", ".", "outputDimensions", "&&", "image", ".", "ratio", "===", "1", ")", "{", "[", "'height'", ",", "'width'", "]", ".", "forEach", "(", "function", "(", "prop", ")", "{", "backgroundImage", ".", "after", "(", "postcss", ".", "decl", "(", "{", "prop", ":", "prop", ",", "value", ":", "(", "image", ".", "ratio", ">", "1", "?", "image", ".", "coordinates", "[", "prop", "]", "/", "image", ".", "ratio", ":", "image", ".", "coordinates", "[", "prop", "]", ")", "+", "'px'", "}", ")", ")", ";", "}", ")", ";", "}", "backgroundImage", ".", "after", "(", "backgroundPosition", ")", ";", "if", "(", "image", ".", "ratio", ">", "1", ")", "{", "backgroundSize", "=", "postcss", ".", "decl", "(", "{", "prop", ":", "'background-size'", ",", "value", ":", "getBackgroundSize", "(", "image", ")", "}", ")", ";", "backgroundPosition", ".", "after", "(", "backgroundSize", ")", ";", "}", "}", "}", "}", ")", ";", "resolve", "(", "[", "images", ",", "options", ",", "sprites", ",", "css", "]", ")", ";", "}", ")", ";", "}" ]
Updates the CSS references from the token info. @param {Node} css @param {Object} options @param {Array} images @param {Array} sprites @return {Promise}
[ "Updates", "the", "CSS", "references", "from", "the", "token", "info", "." ]
96725425a6d67fdb0c79ce476c33af55337aea9b
https://github.com/Jeff2Ma/postcss-lazysprite/blob/96725425a6d67fdb0c79ce476c33af55337aea9b/index.js#L595-L661
train
Jeff2Ma/postcss-lazysprite
index.js
makeSpritePath
function makeSpritePath(options, groups) { var base = options.spritePath; var file; // If is svg, do st if (groups.indexOf('GROUP_SVG_FLAG') > -1) { groups = _.filter(groups, function (item) { return item !== 'GROUP_SVG_FLAG'; }); file = path.resolve(base, groups.join('.') + '.svg'); } else { file = path.resolve(base, groups.join('.') + '.png'); } return file.replace('.@', options.retinaInfix); }
javascript
function makeSpritePath(options, groups) { var base = options.spritePath; var file; // If is svg, do st if (groups.indexOf('GROUP_SVG_FLAG') > -1) { groups = _.filter(groups, function (item) { return item !== 'GROUP_SVG_FLAG'; }); file = path.resolve(base, groups.join('.') + '.svg'); } else { file = path.resolve(base, groups.join('.') + '.png'); } return file.replace('.@', options.retinaInfix); }
[ "function", "makeSpritePath", "(", "options", ",", "groups", ")", "{", "var", "base", "=", "options", ".", "spritePath", ";", "var", "file", ";", "if", "(", "groups", ".", "indexOf", "(", "'GROUP_SVG_FLAG'", ")", ">", "-", "1", ")", "{", "groups", "=", "_", ".", "filter", "(", "groups", ",", "function", "(", "item", ")", "{", "return", "item", "!==", "'GROUP_SVG_FLAG'", ";", "}", ")", ";", "file", "=", "path", ".", "resolve", "(", "base", ",", "groups", ".", "join", "(", "'.'", ")", "+", "'.svg'", ")", ";", "}", "else", "{", "file", "=", "path", ".", "resolve", "(", "base", ",", "groups", ".", "join", "(", "'.'", ")", "+", "'.png'", ")", ";", "}", "return", "file", ".", "replace", "(", "'.@'", ",", "options", ".", "retinaInfix", ")", ";", "}" ]
Set the sprite file name form groups.
[ "Set", "the", "sprite", "file", "name", "form", "groups", "." ]
96725425a6d67fdb0c79ce476c33af55337aea9b
https://github.com/Jeff2Ma/postcss-lazysprite/blob/96725425a6d67fdb0c79ce476c33af55337aea9b/index.js#L703-L718
train
Jeff2Ma/postcss-lazysprite
index.js
getBackgroundPosition
function getBackgroundPosition(image) { var logicValue = image.isSVG ? 1 : -1; var x = logicValue * (image.ratio > 1 ? image.coordinates.x / image.ratio : image.coordinates.x); var y = logicValue * (image.ratio > 1 ? image.coordinates.y / image.ratio : image.coordinates.y); var template = _.template('<%= (x ? x + "px" : x) %> <%= (y ? y + "px" : y) %>'); return template({x: x, y: y}); }
javascript
function getBackgroundPosition(image) { var logicValue = image.isSVG ? 1 : -1; var x = logicValue * (image.ratio > 1 ? image.coordinates.x / image.ratio : image.coordinates.x); var y = logicValue * (image.ratio > 1 ? image.coordinates.y / image.ratio : image.coordinates.y); var template = _.template('<%= (x ? x + "px" : x) %> <%= (y ? y + "px" : y) %>'); return template({x: x, y: y}); }
[ "function", "getBackgroundPosition", "(", "image", ")", "{", "var", "logicValue", "=", "image", ".", "isSVG", "?", "1", ":", "-", "1", ";", "var", "x", "=", "logicValue", "*", "(", "image", ".", "ratio", ">", "1", "?", "image", ".", "coordinates", ".", "x", "/", "image", ".", "ratio", ":", "image", ".", "coordinates", ".", "x", ")", ";", "var", "y", "=", "logicValue", "*", "(", "image", ".", "ratio", ">", "1", "?", "image", ".", "coordinates", ".", "y", "/", "image", ".", "ratio", ":", "image", ".", "coordinates", ".", "y", ")", ";", "var", "template", "=", "_", ".", "template", "(", "'<%= (x ? x + \"px\" : x) %> <%= (y ? y + \"px\" : y) %>'", ")", ";", "return", "template", "(", "{", "x", ":", "x", ",", "y", ":", "y", "}", ")", ";", "}" ]
Return the value for background-position property
[ "Return", "the", "value", "for", "background", "-", "position", "property" ]
96725425a6d67fdb0c79ce476c33af55337aea9b
https://github.com/Jeff2Ma/postcss-lazysprite/blob/96725425a6d67fdb0c79ce476c33af55337aea9b/index.js#L741-L747
train
Jeff2Ma/postcss-lazysprite
index.js
getBackgroundPositionInPercent
function getBackgroundPositionInPercent(image) { var x = 100 * (image.coordinates.x) / (image.properties.width - image.coordinates.width); var y = 100 * (image.coordinates.y) / (image.properties.height - image.coordinates.height); var template = _.template('<%= (x ? x + "%" : x) %> <%= (y ? y + "%" : y) %>'); return template({x: x, y: y}); }
javascript
function getBackgroundPositionInPercent(image) { var x = 100 * (image.coordinates.x) / (image.properties.width - image.coordinates.width); var y = 100 * (image.coordinates.y) / (image.properties.height - image.coordinates.height); var template = _.template('<%= (x ? x + "%" : x) %> <%= (y ? y + "%" : y) %>'); return template({x: x, y: y}); }
[ "function", "getBackgroundPositionInPercent", "(", "image", ")", "{", "var", "x", "=", "100", "*", "(", "image", ".", "coordinates", ".", "x", ")", "/", "(", "image", ".", "properties", ".", "width", "-", "image", ".", "coordinates", ".", "width", ")", ";", "var", "y", "=", "100", "*", "(", "image", ".", "coordinates", ".", "y", ")", "/", "(", "image", ".", "properties", ".", "height", "-", "image", ".", "coordinates", ".", "height", ")", ";", "var", "template", "=", "_", ".", "template", "(", "'<%= (x ? x + \"%\" : x) %> <%= (y ? y + \"%\" : y) %>'", ")", ";", "return", "template", "(", "{", "x", ":", "x", ",", "y", ":", "y", "}", ")", ";", "}" ]
Return the pencentage value for background-position property
[ "Return", "the", "pencentage", "value", "for", "background", "-", "position", "property" ]
96725425a6d67fdb0c79ce476c33af55337aea9b
https://github.com/Jeff2Ma/postcss-lazysprite/blob/96725425a6d67fdb0c79ce476c33af55337aea9b/index.js#L750-L755
train
Jeff2Ma/postcss-lazysprite
index.js
getBackgroundSize
function getBackgroundSize(image) { var x = image.properties.width / image.ratio; var y = image.properties.height / image.ratio; var template = _.template('<%= x %>px <%= y %>px'); return template({x: x, y: y}); }
javascript
function getBackgroundSize(image) { var x = image.properties.width / image.ratio; var y = image.properties.height / image.ratio; var template = _.template('<%= x %>px <%= y %>px'); return template({x: x, y: y}); }
[ "function", "getBackgroundSize", "(", "image", ")", "{", "var", "x", "=", "image", ".", "properties", ".", "width", "/", "image", ".", "ratio", ";", "var", "y", "=", "image", ".", "properties", ".", "height", "/", "image", ".", "ratio", ";", "var", "template", "=", "_", ".", "template", "(", "'<%= x %>px <%= y %>px'", ")", ";", "return", "template", "(", "{", "x", ":", "x", ",", "y", ":", "y", "}", ")", ";", "}" ]
Return the value for background-size property.
[ "Return", "the", "value", "for", "background", "-", "size", "property", "." ]
96725425a6d67fdb0c79ce476c33af55337aea9b
https://github.com/Jeff2Ma/postcss-lazysprite/blob/96725425a6d67fdb0c79ce476c33af55337aea9b/index.js#L758-L764
train
Jeff2Ma/postcss-lazysprite
index.js
getRetinaRatio
function getRetinaRatio(url) { var matches = /[@_](\d)x\.[a-z]{3,4}$/gi.exec(url); if (!matches) { return 1; } var ratio = _.parseInt(matches[1]); return ratio; }
javascript
function getRetinaRatio(url) { var matches = /[@_](\d)x\.[a-z]{3,4}$/gi.exec(url); if (!matches) { return 1; } var ratio = _.parseInt(matches[1]); return ratio; }
[ "function", "getRetinaRatio", "(", "url", ")", "{", "var", "matches", "=", "/", "[@_](\\d)x\\.[a-z]{3,4}$", "/", "gi", ".", "exec", "(", "url", ")", ";", "if", "(", "!", "matches", ")", "{", "return", "1", ";", "}", "var", "ratio", "=", "_", ".", "parseInt", "(", "matches", "[", "1", "]", ")", ";", "return", "ratio", ";", "}" ]
Return the value of retina ratio.
[ "Return", "the", "value", "of", "retina", "ratio", "." ]
96725425a6d67fdb0c79ce476c33af55337aea9b
https://github.com/Jeff2Ma/postcss-lazysprite/blob/96725425a6d67fdb0c79ce476c33af55337aea9b/index.js#L785-L792
train
Jeff2Ma/postcss-lazysprite
index.js
log
function log(logLevel, level, content) { var output = true; switch (logLevel) { case 'slient': if (level !== 'lv1') { output = false; } break; case 'info': if (level === 'lv3') { output = false; } break; default: output = true; } if (output) { var data = Array.prototype.slice.call(content); fancyLog.apply(false, data); } }
javascript
function log(logLevel, level, content) { var output = true; switch (logLevel) { case 'slient': if (level !== 'lv1') { output = false; } break; case 'info': if (level === 'lv3') { output = false; } break; default: output = true; } if (output) { var data = Array.prototype.slice.call(content); fancyLog.apply(false, data); } }
[ "function", "log", "(", "logLevel", ",", "level", ",", "content", ")", "{", "var", "output", "=", "true", ";", "switch", "(", "logLevel", ")", "{", "case", "'slient'", ":", "if", "(", "level", "!==", "'lv1'", ")", "{", "output", "=", "false", ";", "}", "break", ";", "case", "'info'", ":", "if", "(", "level", "===", "'lv3'", ")", "{", "output", "=", "false", ";", "}", "break", ";", "default", ":", "output", "=", "true", ";", "}", "if", "(", "output", ")", "{", "var", "data", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "content", ")", ";", "fancyLog", ".", "apply", "(", "false", ",", "data", ")", ";", "}", "}" ]
Log with same stylesheet and level control.
[ "Log", "with", "same", "stylesheet", "and", "level", "control", "." ]
96725425a6d67fdb0c79ce476c33af55337aea9b
https://github.com/Jeff2Ma/postcss-lazysprite/blob/96725425a6d67fdb0c79ce476c33af55337aea9b/index.js#L811-L832
train
Jeff2Ma/postcss-lazysprite
index.js
debug
function debug() { var data = Array.prototype.slice.call(arguments); fancyLog.apply(false, data); }
javascript
function debug() { var data = Array.prototype.slice.call(arguments); fancyLog.apply(false, data); }
[ "function", "debug", "(", ")", "{", "var", "data", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "fancyLog", ".", "apply", "(", "false", ",", "data", ")", ";", "}" ]
Log for debug
[ "Log", "for", "debug" ]
96725425a6d67fdb0c79ce476c33af55337aea9b
https://github.com/Jeff2Ma/postcss-lazysprite/blob/96725425a6d67fdb0c79ce476c33af55337aea9b/index.js#L835-L838
train
twolfson/gmsmith
lib/engine.js
Gmsmith
function Gmsmith(options) { options = options || {}; this.gm = _gm; var useImageMagick = options.hasOwnProperty('imagemagick') ? options.imagemagick : !gmExists; if (useImageMagick) { this.gm = _gm.subClass({imageMagick: true}); } }
javascript
function Gmsmith(options) { options = options || {}; this.gm = _gm; var useImageMagick = options.hasOwnProperty('imagemagick') ? options.imagemagick : !gmExists; if (useImageMagick) { this.gm = _gm.subClass({imageMagick: true}); } }
[ "function", "Gmsmith", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "gm", "=", "_gm", ";", "var", "useImageMagick", "=", "options", ".", "hasOwnProperty", "(", "'imagemagick'", ")", "?", "options", ".", "imagemagick", ":", "!", "gmExists", ";", "if", "(", "useImageMagick", ")", "{", "this", ".", "gm", "=", "_gm", ".", "subClass", "(", "{", "imageMagick", ":", "true", "}", ")", ";", "}", "}" ]
Define our engine constructor
[ "Define", "our", "engine", "constructor" ]
2bc44e50a9b562691745f5cb5261e85debeefd7e
https://github.com/twolfson/gmsmith/blob/2bc44e50a9b562691745f5cb5261e85debeefd7e/lib/engine.js#L16-L23
train
MatteoGabriele/storage-helper
dist/storage-helper.js
setItem
function setItem(key, value) { storage[key] = typeof value === 'string' ? value : JSON.stringify(value); }
javascript
function setItem(key, value) { storage[key] = typeof value === 'string' ? value : JSON.stringify(value); }
[ "function", "setItem", "(", "key", ",", "value", ")", "{", "storage", "[", "key", "]", "=", "typeof", "value", "===", "'string'", "?", "value", ":", "JSON", ".", "stringify", "(", "value", ")", ";", "}" ]
Add item in out session storage @param {String} key @param {String} value
[ "Add", "item", "in", "out", "session", "storage" ]
72d4e773811cf52091019aa98f2990c0eb7546e4
https://github.com/MatteoGabriele/storage-helper/blob/72d4e773811cf52091019aa98f2990c0eb7546e4/dist/storage-helper.js#L27-L29
train
MatteoGabriele/storage-helper
dist/storage-helper.js
log
function log(text) { var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'success'; var debug$$1 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (!debug$$1) { return; } var success = 'padding: 2px; background: #219621; color: #ffffff'; var warning = 'padding: 2px; background: #f1e05a; color: #333333'; var error = 'padding: 2px; background: #b9090b; color: #ffffff'; var types = { error: error, success: success, warning: warning }; console.log('%c [Storage Helper] ' + text + ' ', types[type]); }
javascript
function log(text) { var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'success'; var debug$$1 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (!debug$$1) { return; } var success = 'padding: 2px; background: #219621; color: #ffffff'; var warning = 'padding: 2px; background: #f1e05a; color: #333333'; var error = 'padding: 2px; background: #b9090b; color: #ffffff'; var types = { error: error, success: success, warning: warning }; console.log('%c [Storage Helper] ' + text + ' ', types[type]); }
[ "function", "log", "(", "text", ")", "{", "var", "type", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "'success'", ";", "var", "debug$$1", "=", "arguments", ".", "length", ">", "2", "&&", "arguments", "[", "2", "]", "!==", "undefined", "?", "arguments", "[", "2", "]", ":", "false", ";", "if", "(", "!", "debug$$1", ")", "{", "return", ";", "}", "var", "success", "=", "'padding: 2px; background: #219621; color: #ffffff'", ";", "var", "warning", "=", "'padding: 2px; background: #f1e05a; color: #333333'", ";", "var", "error", "=", "'padding: 2px; background: #b9090b; color: #ffffff'", ";", "var", "types", "=", "{", "error", ":", "error", ",", "success", ":", "success", ",", "warning", ":", "warning", "}", ";", "console", ".", "log", "(", "'%c [Storage Helper] '", "+", "text", "+", "' '", ",", "types", "[", "type", "]", ")", ";", "}" ]
Logger for different type of messages. @param {String} text @param {String} [type='success']
[ "Logger", "for", "different", "type", "of", "messages", "." ]
72d4e773811cf52091019aa98f2990c0eb7546e4
https://github.com/MatteoGabriele/storage-helper/blob/72d4e773811cf52091019aa98f2990c0eb7546e4/dist/storage-helper.js#L77-L91
train
MatteoGabriele/storage-helper
dist/storage-helper.js
parse
function parse(data) { try { return JSON.parse(data); } catch (e) { log('Oops! Some problems parsing this ' + (typeof data === 'undefined' ? 'undefined' : _typeof(data)) + '.', 'error', debug); } return null; }
javascript
function parse(data) { try { return JSON.parse(data); } catch (e) { log('Oops! Some problems parsing this ' + (typeof data === 'undefined' ? 'undefined' : _typeof(data)) + '.', 'error', debug); } return null; }
[ "function", "parse", "(", "data", ")", "{", "try", "{", "return", "JSON", ".", "parse", "(", "data", ")", ";", "}", "catch", "(", "e", ")", "{", "log", "(", "'Oops! Some problems parsing this '", "+", "(", "typeof", "data", "===", "'undefined'", "?", "'undefined'", ":", "_typeof", "(", "data", ")", ")", "+", "'.'", ",", "'error'", ",", "debug", ")", ";", "}", "return", "null", ";", "}" ]
JSON parse with error @param {String} data @return {String|null}
[ "JSON", "parse", "with", "error" ]
72d4e773811cf52091019aa98f2990c0eb7546e4
https://github.com/MatteoGabriele/storage-helper/blob/72d4e773811cf52091019aa98f2990c0eb7546e4/dist/storage-helper.js#L98-L106
train
MatteoGabriele/storage-helper
dist/storage-helper.js
setItem
function setItem(key, value) { var expires = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; if (!isCookieEnabled) { session.setItem(key, value); log('I\'ve saved "' + key + '" in a plain object :)', 'warning', debug); return; } cookie.set(key, value, { expires: expires }); log('I\'ve saved "' + key + '" in a cookie :)', 'warning', debug); }
javascript
function setItem(key, value) { var expires = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; if (!isCookieEnabled) { session.setItem(key, value); log('I\'ve saved "' + key + '" in a plain object :)', 'warning', debug); return; } cookie.set(key, value, { expires: expires }); log('I\'ve saved "' + key + '" in a cookie :)', 'warning', debug); }
[ "function", "setItem", "(", "key", ",", "value", ")", "{", "var", "expires", "=", "arguments", ".", "length", ">", "2", "&&", "arguments", "[", "2", "]", "!==", "undefined", "?", "arguments", "[", "2", "]", ":", "1", ";", "if", "(", "!", "isCookieEnabled", ")", "{", "session", ".", "setItem", "(", "key", ",", "value", ")", ";", "log", "(", "'I\\'ve saved \"'", "+", "\\'", "+", "key", ",", "'\" in a plain object :)'", ",", "'warning'", ")", ";", "debug", "}", "return", ";", "cookie", ".", "set", "(", "key", ",", "value", ",", "{", "expires", ":", "expires", "}", ")", ";", "}" ]
Set the item in the cookies if possible, otherwise is going to store it inside a plain object @param {String} key @param {String} value @param {Number} [expires=1]
[ "Set", "the", "item", "in", "the", "cookies", "if", "possible", "otherwise", "is", "going", "to", "store", "it", "inside", "a", "plain", "object" ]
72d4e773811cf52091019aa98f2990c0eb7546e4
https://github.com/MatteoGabriele/storage-helper/blob/72d4e773811cf52091019aa98f2990c0eb7546e4/dist/storage-helper.js#L130-L141
train
MatteoGabriele/storage-helper
dist/storage-helper.js
clear
function clear() { var cookies = isBrowser && document.cookie.split(';'); if (!cookies.length) { return; } for (var i = 0, l = cookies.length; i < l; i++) { var item = cookies[i]; var key = item.split('=')[0]; cookie.remove(key); } }
javascript
function clear() { var cookies = isBrowser && document.cookie.split(';'); if (!cookies.length) { return; } for (var i = 0, l = cookies.length; i < l; i++) { var item = cookies[i]; var key = item.split('=')[0]; cookie.remove(key); } }
[ "function", "clear", "(", ")", "{", "var", "cookies", "=", "isBrowser", "&&", "document", ".", "cookie", ".", "split", "(", "';'", ")", ";", "if", "(", "!", "cookies", ".", "length", ")", "{", "return", ";", "}", "for", "(", "var", "i", "=", "0", ",", "l", "=", "cookies", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "var", "item", "=", "cookies", "[", "i", "]", ";", "var", "key", "=", "item", ".", "split", "(", "'='", ")", "[", "0", "]", ";", "cookie", ".", "remove", "(", "key", ")", ";", "}", "}" ]
Remove all cookies
[ "Remove", "all", "cookies" ]
72d4e773811cf52091019aa98f2990c0eb7546e4
https://github.com/MatteoGabriele/storage-helper/blob/72d4e773811cf52091019aa98f2990c0eb7546e4/dist/storage-helper.js#L163-L176
train
MatteoGabriele/storage-helper
dist/storage-helper.js
hasLocalStorage
function hasLocalStorage() { if (!localstorage) { return false; } try { localstorage.setItem('0', ''); localstorage.removeItem('0'); return true; } catch (error) { return false; } }
javascript
function hasLocalStorage() { if (!localstorage) { return false; } try { localstorage.setItem('0', ''); localstorage.removeItem('0'); return true; } catch (error) { return false; } }
[ "function", "hasLocalStorage", "(", ")", "{", "if", "(", "!", "localstorage", ")", "{", "return", "false", ";", "}", "try", "{", "localstorage", ".", "setItem", "(", "'0'", ",", "''", ")", ";", "localstorage", ".", "removeItem", "(", "'0'", ")", ";", "return", "true", ";", "}", "catch", "(", "error", ")", "{", "return", "false", ";", "}", "}" ]
Check if the browser has localStorage @return {Boolean}
[ "Check", "if", "the", "browser", "has", "localStorage" ]
72d4e773811cf52091019aa98f2990c0eb7546e4
https://github.com/MatteoGabriele/storage-helper/blob/72d4e773811cf52091019aa98f2990c0eb7546e4/dist/storage-helper.js#L192-L204
train
MatteoGabriele/storage-helper
dist/storage-helper.js
getItem
function getItem(key) { var parsed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var fallbackValue = arguments[2]; var result = void 0; var cookieItem = cookie$1.getItem(key); var sessionItem = session.getItem(key); if (!hasLocalStorage()) { result = cookieItem || sessionItem; } else { result = localstorage.getItem(key) || cookieItem || sessionItem; } var item = parsed ? parse(result) : result; if ((typeof item === 'undefined' || item === null) && typeof fallbackValue !== 'undefined') { return fallbackValue; } return item; }
javascript
function getItem(key) { var parsed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var fallbackValue = arguments[2]; var result = void 0; var cookieItem = cookie$1.getItem(key); var sessionItem = session.getItem(key); if (!hasLocalStorage()) { result = cookieItem || sessionItem; } else { result = localstorage.getItem(key) || cookieItem || sessionItem; } var item = parsed ? parse(result) : result; if ((typeof item === 'undefined' || item === null) && typeof fallbackValue !== 'undefined') { return fallbackValue; } return item; }
[ "function", "getItem", "(", "key", ")", "{", "var", "parsed", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "false", ";", "var", "fallbackValue", "=", "arguments", "[", "2", "]", ";", "var", "result", "=", "void", "0", ";", "var", "cookieItem", "=", "cookie$1", ".", "getItem", "(", "key", ")", ";", "var", "sessionItem", "=", "session", ".", "getItem", "(", "key", ")", ";", "if", "(", "!", "hasLocalStorage", "(", ")", ")", "{", "result", "=", "cookieItem", "||", "sessionItem", ";", "}", "else", "{", "result", "=", "localstorage", ".", "getItem", "(", "key", ")", "||", "cookieItem", "||", "sessionItem", ";", "}", "var", "item", "=", "parsed", "?", "parse", "(", "result", ")", ":", "result", ";", "if", "(", "(", "typeof", "item", "===", "'undefined'", "||", "item", "===", "null", ")", "&&", "typeof", "fallbackValue", "!==", "'undefined'", ")", "{", "return", "fallbackValue", ";", "}", "return", "item", ";", "}" ]
Get the item Here the object is taken from the localStorage, if it was available, or from the object @param {String} key @param {Boolean} [parsed=false] @return {any}
[ "Get", "the", "item", "Here", "the", "object", "is", "taken", "from", "the", "localStorage", "if", "it", "was", "available", "or", "from", "the", "object" ]
72d4e773811cf52091019aa98f2990c0eb7546e4
https://github.com/MatteoGabriele/storage-helper/blob/72d4e773811cf52091019aa98f2990c0eb7546e4/dist/storage-helper.js#L255-L277
train
MatteoGabriele/storage-helper
dist/storage-helper.js
removeItem
function removeItem(key) { cookie$1.removeItem(key); session.removeItem(key); if (!hasLocalStorage()) { return; } localstorage.removeItem(key); }
javascript
function removeItem(key) { cookie$1.removeItem(key); session.removeItem(key); if (!hasLocalStorage()) { return; } localstorage.removeItem(key); }
[ "function", "removeItem", "(", "key", ")", "{", "cookie$1", ".", "removeItem", "(", "key", ")", ";", "session", ".", "removeItem", "(", "key", ")", ";", "if", "(", "!", "hasLocalStorage", "(", ")", ")", "{", "return", ";", "}", "localstorage", ".", "removeItem", "(", "key", ")", ";", "}" ]
Remove a single item from the storage @param {String} key
[ "Remove", "a", "single", "item", "from", "the", "storage" ]
72d4e773811cf52091019aa98f2990c0eb7546e4
https://github.com/MatteoGabriele/storage-helper/blob/72d4e773811cf52091019aa98f2990c0eb7546e4/dist/storage-helper.js#L297-L306
train
kaola-fed/foxman
packages/foxman-plugin-server/lib/client/js/builtin/eventbus.js
off
function off(type, handler) { if (all[type]) { all[type].splice(all[type].indexOf(handler) >>> 0, 1); } }
javascript
function off(type, handler) { if (all[type]) { all[type].splice(all[type].indexOf(handler) >>> 0, 1); } }
[ "function", "off", "(", "type", ",", "handler", ")", "{", "if", "(", "all", "[", "type", "]", ")", "{", "all", "[", "type", "]", ".", "splice", "(", "all", "[", "type", "]", ".", "indexOf", "(", "handler", ")", ">>>", "0", ",", "1", ")", ";", "}", "}" ]
Remove an event handler for the given type. @param {String} type Type of event to unregister `handler` from, or `"*"` @param {Function} handler Handler function to remove @memberOf mitt
[ "Remove", "an", "event", "handler", "for", "the", "given", "type", "." ]
e444c0908fabbfe49908ae4ccc3d6619a22dec57
https://github.com/kaola-fed/foxman/blob/e444c0908fabbfe49908ae4ccc3d6619a22dec57/packages/foxman-plugin-server/lib/client/js/builtin/eventbus.js#L41-L45
train
nodejitsu/godot
lib/godot/net/client.js
defaultify
function defaultify (obj) { return Object.keys(self.defaults).reduce(function (acc, key) { if (!acc[key]) { acc[key] = self.defaults[key] } return acc; }, obj); }
javascript
function defaultify (obj) { return Object.keys(self.defaults).reduce(function (acc, key) { if (!acc[key]) { acc[key] = self.defaults[key] } return acc; }, obj); }
[ "function", "defaultify", "(", "obj", ")", "{", "return", "Object", ".", "keys", "(", "self", ".", "defaults", ")", ".", "reduce", "(", "function", "(", "acc", ",", "key", ")", "{", "if", "(", "!", "acc", "[", "key", "]", ")", "{", "acc", "[", "key", "]", "=", "self", ".", "defaults", "[", "key", "]", "}", "return", "acc", ";", "}", ",", "obj", ")", ";", "}" ]
Add defaults to each object where a value does not already exist
[ "Add", "defaults", "to", "each", "object", "where", "a", "value", "does", "not", "already", "exist" ]
fc2397c8282ad97de17a807b2ea4498a0365e77e
https://github.com/nodejitsu/godot/blob/fc2397c8282ad97de17a807b2ea4498a0365e77e/lib/godot/net/client.js#L151-L156
train