id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
40,700
oscarmarinmiro/aframe-video-controls
index.js
function(){ var self = this; var camera = self.el.sceneEl.camera; if(camera) { var camera_rotation = camera.el.getAttribute("rotation"); var camera_yaw = camera_rotation.y; // Set position of menu based on camera yaw and data.pitch // Have to add 1.6m to camera.position.y (????) self.y_position = camera.position.y + 1.6; self.x_position = -self.data.distance * Math.sin(camera_yaw * Math.PI / 180.0); self.z_position = -self.data.distance * Math.cos(camera_yaw * Math.PI / 180.0); self.el.setAttribute("position", [self.x_position, self.y_position, self.z_position].join(" ")); // and now, make our controls rotate towards origin this.el.object3D.lookAt(new THREE.Vector3(camera.position.x, camera.position.y + 1.6, camera.position.z)); } }
javascript
function(){ var self = this; var camera = self.el.sceneEl.camera; if(camera) { var camera_rotation = camera.el.getAttribute("rotation"); var camera_yaw = camera_rotation.y; // Set position of menu based on camera yaw and data.pitch // Have to add 1.6m to camera.position.y (????) self.y_position = camera.position.y + 1.6; self.x_position = -self.data.distance * Math.sin(camera_yaw * Math.PI / 180.0); self.z_position = -self.data.distance * Math.cos(camera_yaw * Math.PI / 180.0); self.el.setAttribute("position", [self.x_position, self.y_position, self.z_position].join(" ")); // and now, make our controls rotate towards origin this.el.object3D.lookAt(new THREE.Vector3(camera.position.x, camera.position.y + 1.6, camera.position.z)); } }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "var", "camera", "=", "self", ".", "el", ".", "sceneEl", ".", "camera", ";", "if", "(", "camera", ")", "{", "var", "camera_rotation", "=", "camera", ".", "el", ".", "getAttribute", "(", "\"rotation\"", ")", ";", "var", "camera_yaw", "=", "camera_rotation", ".", "y", ";", "// Set position of menu based on camera yaw and data.pitch", "// Have to add 1.6m to camera.position.y (????)", "self", ".", "y_position", "=", "camera", ".", "position", ".", "y", "+", "1.6", ";", "self", ".", "x_position", "=", "-", "self", ".", "data", ".", "distance", "*", "Math", ".", "sin", "(", "camera_yaw", "*", "Math", ".", "PI", "/", "180.0", ")", ";", "self", ".", "z_position", "=", "-", "self", ".", "data", ".", "distance", "*", "Math", ".", "cos", "(", "camera_yaw", "*", "Math", ".", "PI", "/", "180.0", ")", ";", "self", ".", "el", ".", "setAttribute", "(", "\"position\"", ",", "[", "self", ".", "x_position", ",", "self", ".", "y_position", ",", "self", ".", "z_position", "]", ".", "join", "(", "\" \"", ")", ")", ";", "// and now, make our controls rotate towards origin", "this", ".", "el", ".", "object3D", ".", "lookAt", "(", "new", "THREE", ".", "Vector3", "(", "camera", ".", "position", ".", "x", ",", "camera", ".", "position", ".", "y", "+", "1.6", ",", "camera", ".", "position", ".", "z", ")", ")", ";", "}", "}" ]
Puts the control in from of the camera, at this.data.distance, facing it...
[ "Puts", "the", "control", "in", "from", "of", "the", "camera", "at", "this", ".", "data", ".", "distance", "facing", "it", "..." ]
c4a8b8ae05498e7b2e43a65746e9ef5511504032
https://github.com/oscarmarinmiro/aframe-video-controls/blob/c4a8b8ae05498e7b2e43a65746e9ef5511504032/index.js#L41-L69
40,701
triestpa/koa-joi-validate
index.js
validateObject
function validateObject (object = {}, label, schema, options) { // Skip validation if no schema is provided if (schema) { // Validate the object against the provided schema const { error, value } = joi.validate(object, schema, options) if (error) { // Throw error with custom message if validation failed throw new Error(`Invalid ${label} - ${error.message}`) } } }
javascript
function validateObject (object = {}, label, schema, options) { // Skip validation if no schema is provided if (schema) { // Validate the object against the provided schema const { error, value } = joi.validate(object, schema, options) if (error) { // Throw error with custom message if validation failed throw new Error(`Invalid ${label} - ${error.message}`) } } }
[ "function", "validateObject", "(", "object", "=", "{", "}", ",", "label", ",", "schema", ",", "options", ")", "{", "// Skip validation if no schema is provided", "if", "(", "schema", ")", "{", "// Validate the object against the provided schema", "const", "{", "error", ",", "value", "}", "=", "joi", ".", "validate", "(", "object", ",", "schema", ",", "options", ")", "if", "(", "error", ")", "{", "// Throw error with custom message if validation failed", "throw", "new", "Error", "(", "`", "${", "label", "}", "${", "error", ".", "message", "}", "`", ")", "}", "}", "}" ]
Helper function to validate an object against the provided schema, and to throw a custom error if object is not valid. @param {Object} object The object to be validated. @param {String} label The label to use in the error message. @param {JoiSchema} schema The Joi schema to validate the object against.
[ "Helper", "function", "to", "validate", "an", "object", "against", "the", "provided", "schema", "and", "to", "throw", "a", "custom", "error", "if", "object", "is", "not", "valid", "." ]
edc6bfe5b4889eddc78fe8c59ca75bb7209ae5d4
https://github.com/triestpa/koa-joi-validate/blob/edc6bfe5b4889eddc78fe8c59ca75bb7209ae5d4/index.js#L11-L21
40,702
triestpa/koa-joi-validate
index.js
validate
function validate (validationObj) { // Return a Koa middleware function return (ctx, next) => { try { // Validate each request data object in the Koa context object validateObject(ctx.headers, 'Headers', validationObj.headers, { allowUnknown: true }) validateObject(ctx.params, 'URL Parameters', validationObj.params) validateObject(ctx.query, 'URL Query', validationObj.query) if (ctx.request.body) { validateObject(ctx.request.body, 'Request Body', validationObj.body) } return next() } catch (err) { // If any of the objects fails validation, send an HTTP 400 response. ctx.throw(400, err.message) } } }
javascript
function validate (validationObj) { // Return a Koa middleware function return (ctx, next) => { try { // Validate each request data object in the Koa context object validateObject(ctx.headers, 'Headers', validationObj.headers, { allowUnknown: true }) validateObject(ctx.params, 'URL Parameters', validationObj.params) validateObject(ctx.query, 'URL Query', validationObj.query) if (ctx.request.body) { validateObject(ctx.request.body, 'Request Body', validationObj.body) } return next() } catch (err) { // If any of the objects fails validation, send an HTTP 400 response. ctx.throw(400, err.message) } } }
[ "function", "validate", "(", "validationObj", ")", "{", "// Return a Koa middleware function", "return", "(", "ctx", ",", "next", ")", "=>", "{", "try", "{", "// Validate each request data object in the Koa context object", "validateObject", "(", "ctx", ".", "headers", ",", "'Headers'", ",", "validationObj", ".", "headers", ",", "{", "allowUnknown", ":", "true", "}", ")", "validateObject", "(", "ctx", ".", "params", ",", "'URL Parameters'", ",", "validationObj", ".", "params", ")", "validateObject", "(", "ctx", ".", "query", ",", "'URL Query'", ",", "validationObj", ".", "query", ")", "if", "(", "ctx", ".", "request", ".", "body", ")", "{", "validateObject", "(", "ctx", ".", "request", ".", "body", ",", "'Request Body'", ",", "validationObj", ".", "body", ")", "}", "return", "next", "(", ")", "}", "catch", "(", "err", ")", "{", "// If any of the objects fails validation, send an HTTP 400 response.", "ctx", ".", "throw", "(", "400", ",", "err", ".", "message", ")", "}", "}", "}" ]
Generate a Koa middleware function to validate a request using the provided validation objects. @param {Object} validationObj @param {Object} validationObj.headers The request headers schema @param {Object} validationObj.params The request params schema @param {Object} validationObj.query The request query schema @param {Object} validationObj.body The request body schema @returns A validation middleware function.
[ "Generate", "a", "Koa", "middleware", "function", "to", "validate", "a", "request", "using", "the", "provided", "validation", "objects", "." ]
edc6bfe5b4889eddc78fe8c59ca75bb7209ae5d4
https://github.com/triestpa/koa-joi-validate/blob/edc6bfe5b4889eddc78fe8c59ca75bb7209ae5d4/index.js#L34-L53
40,703
qeesung/rocketchat-node
lib/rocket-chat.js
function (protocol, host, port, username, password, onConnected) { this.rocketChatClient = new RocketChatClient(protocol, host, port, username, password, onConnected); this.token = null; /** * login the rocket chat * @param callback after login the rocket chat , will invoke the callback function */ this.login = function (username, password, callback) { var self = this; this.rocketChatClient.authentication.login(username, password, function (err, body) { self.token = body.data; callback(null, body); }); }; }
javascript
function (protocol, host, port, username, password, onConnected) { this.rocketChatClient = new RocketChatClient(protocol, host, port, username, password, onConnected); this.token = null; /** * login the rocket chat * @param callback after login the rocket chat , will invoke the callback function */ this.login = function (username, password, callback) { var self = this; this.rocketChatClient.authentication.login(username, password, function (err, body) { self.token = body.data; callback(null, body); }); }; }
[ "function", "(", "protocol", ",", "host", ",", "port", ",", "username", ",", "password", ",", "onConnected", ")", "{", "this", ".", "rocketChatClient", "=", "new", "RocketChatClient", "(", "protocol", ",", "host", ",", "port", ",", "username", ",", "password", ",", "onConnected", ")", ";", "this", ".", "token", "=", "null", ";", "/**\n * login the rocket chat\n * @param callback after login the rocket chat , will invoke the callback function\n */", "this", ".", "login", "=", "function", "(", "username", ",", "password", ",", "callback", ")", "{", "var", "self", "=", "this", ";", "this", ".", "rocketChatClient", ".", "authentication", ".", "login", "(", "username", ",", "password", ",", "function", "(", "err", ",", "body", ")", "{", "self", ".", "token", "=", "body", ".", "data", ";", "callback", "(", "null", ",", "body", ")", ";", "}", ")", ";", "}", ";", "}" ]
Rocket Chat Api constructor @param protocol rocket chat protocol @param host rocket chat host , default is https://demo.rocket.chat @param port rocket chat port , default is 80 @param username rocket chat username @param password rocket chat password @param onConnected callback that is invoked when connection is open @constructor
[ "Rocket", "Chat", "Api", "constructor" ]
3fb76139968e8d95fc6db19411955e11b31fa7cc
https://github.com/qeesung/rocketchat-node/blob/3fb76139968e8d95fc6db19411955e11b31fa7cc/lib/rocket-chat.js#L27-L43
40,704
weihanchen/angular-d3-word-cloud
docs/js/controllers/app.js
resizeWordsCloud
function resizeWordsCloud() { $timeout(function() { var element = document.getElementById('wordsCloud'); var height = $window.innerHeight * 0.75; element.style.height = height + 'px'; var width = element.getBoundingClientRect().width; var maxCount = originWords[0].count; var minCount = originWords[originWords.length - 1].count; var maxWordSize = width * 0.15; var minWordSize = maxWordSize / 5; var spread = maxCount - minCount; if (spread <= 0) spread = 1; var step = (maxWordSize - minWordSize) / spread; self.words = originWords.map(function(word) { return { text: word.text, size: Math.round(maxWordSize - ((maxCount - word.count) * step)), color: self.customColor, tooltipText: word.text + ' tooltip' }; }); self.width = width; self.height = height; self.padding = self.editPadding; self.rotate = self.editRotate; }); }
javascript
function resizeWordsCloud() { $timeout(function() { var element = document.getElementById('wordsCloud'); var height = $window.innerHeight * 0.75; element.style.height = height + 'px'; var width = element.getBoundingClientRect().width; var maxCount = originWords[0].count; var minCount = originWords[originWords.length - 1].count; var maxWordSize = width * 0.15; var minWordSize = maxWordSize / 5; var spread = maxCount - minCount; if (spread <= 0) spread = 1; var step = (maxWordSize - minWordSize) / spread; self.words = originWords.map(function(word) { return { text: word.text, size: Math.round(maxWordSize - ((maxCount - word.count) * step)), color: self.customColor, tooltipText: word.text + ' tooltip' }; }); self.width = width; self.height = height; self.padding = self.editPadding; self.rotate = self.editRotate; }); }
[ "function", "resizeWordsCloud", "(", ")", "{", "$timeout", "(", "function", "(", ")", "{", "var", "element", "=", "document", ".", "getElementById", "(", "'wordsCloud'", ")", ";", "var", "height", "=", "$window", ".", "innerHeight", "*", "0.75", ";", "element", ".", "style", ".", "height", "=", "height", "+", "'px'", ";", "var", "width", "=", "element", ".", "getBoundingClientRect", "(", ")", ".", "width", ";", "var", "maxCount", "=", "originWords", "[", "0", "]", ".", "count", ";", "var", "minCount", "=", "originWords", "[", "originWords", ".", "length", "-", "1", "]", ".", "count", ";", "var", "maxWordSize", "=", "width", "*", "0.15", ";", "var", "minWordSize", "=", "maxWordSize", "/", "5", ";", "var", "spread", "=", "maxCount", "-", "minCount", ";", "if", "(", "spread", "<=", "0", ")", "spread", "=", "1", ";", "var", "step", "=", "(", "maxWordSize", "-", "minWordSize", ")", "/", "spread", ";", "self", ".", "words", "=", "originWords", ".", "map", "(", "function", "(", "word", ")", "{", "return", "{", "text", ":", "word", ".", "text", ",", "size", ":", "Math", ".", "round", "(", "maxWordSize", "-", "(", "(", "maxCount", "-", "word", ".", "count", ")", "*", "step", ")", ")", ",", "color", ":", "self", ".", "customColor", ",", "tooltipText", ":", "word", ".", "text", "+", "' tooltip'", "}", ";", "}", ")", ";", "self", ".", "width", "=", "width", ";", "self", ".", "height", "=", "height", ";", "self", ".", "padding", "=", "self", ".", "editPadding", ";", "self", ".", "rotate", "=", "self", ".", "editRotate", ";", "}", ")", ";", "}" ]
adjust words size base on width
[ "adjust", "words", "size", "base", "on", "width" ]
66464ea8e33ff6b03cca608c55a552e76922bf67
https://github.com/weihanchen/angular-d3-word-cloud/blob/66464ea8e33ff6b03cca608c55a552e76922bf67/docs/js/controllers/app.js#L39-L65
40,705
wmira/react-datatable
src/js/datasource.js
function(records,config) { //the hell is this doing here this.id = new Date(); if ( records instanceof Array ) { this.records = records; } else { var dataField = records.data; var data = records.datasource; this.records = data[dataField]; } this.config = config; if ( this.config ) { this.propertyConfigMap = {}; this.config.cols.forEach( col => { this.propertyConfigMap[col.property] = col; }); } //indexRecords.call(this); }
javascript
function(records,config) { //the hell is this doing here this.id = new Date(); if ( records instanceof Array ) { this.records = records; } else { var dataField = records.data; var data = records.datasource; this.records = data[dataField]; } this.config = config; if ( this.config ) { this.propertyConfigMap = {}; this.config.cols.forEach( col => { this.propertyConfigMap[col.property] = col; }); } //indexRecords.call(this); }
[ "function", "(", "records", ",", "config", ")", "{", "//the hell is this doing here", "this", ".", "id", "=", "new", "Date", "(", ")", ";", "if", "(", "records", "instanceof", "Array", ")", "{", "this", ".", "records", "=", "records", ";", "}", "else", "{", "var", "dataField", "=", "records", ".", "data", ";", "var", "data", "=", "records", ".", "datasource", ";", "this", ".", "records", "=", "data", "[", "dataField", "]", ";", "}", "this", ".", "config", "=", "config", ";", "if", "(", "this", ".", "config", ")", "{", "this", ".", "propertyConfigMap", "=", "{", "}", ";", "this", ".", "config", ".", "cols", ".", "forEach", "(", "col", "=>", "{", "this", ".", "propertyConfigMap", "[", "col", ".", "property", "]", "=", "col", ";", "}", ")", ";", "}", "//indexRecords.call(this);", "}" ]
Create a new datasource using records array as a backing dataset @param records @constructor
[ "Create", "a", "new", "datasource", "using", "records", "array", "as", "a", "backing", "dataset" ]
81647701093a14d9f58a1cd016169a2534f012be
https://github.com/wmira/react-datatable/blob/81647701093a14d9f58a1cd016169a2534f012be/src/js/datasource.js#L48-L69
40,706
michaelkrone/generator-material-app
generators/app/templates/server/api/user(auth)/user.controller.js
function (req, res) { // check for a user id if (!req[this.paramName]._id) { return res.badRequest(); } req[this.paramName].password = req.body.password; delete req.body.password; req[this.paramName].save(function (err) { if (err) { return res.handleError(err); } return res.noContent(); }); }
javascript
function (req, res) { // check for a user id if (!req[this.paramName]._id) { return res.badRequest(); } req[this.paramName].password = req.body.password; delete req.body.password; req[this.paramName].save(function (err) { if (err) { return res.handleError(err); } return res.noContent(); }); }
[ "function", "(", "req", ",", "res", ")", "{", "// check for a user id", "if", "(", "!", "req", "[", "this", ".", "paramName", "]", ".", "_id", ")", "{", "return", "res", ".", "badRequest", "(", ")", ";", "}", "req", "[", "this", ".", "paramName", "]", ".", "password", "=", "req", ".", "body", ".", "password", ";", "delete", "req", ".", "body", ".", "password", ";", "req", "[", "this", ".", "paramName", "]", ".", "save", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "res", ".", "handleError", "(", "err", ")", ";", "}", "return", "res", ".", "noContent", "(", ")", ";", "}", ")", ";", "}" ]
README Replaces an existing user password in the DB using the request body property named 'password'. Should be an admin only route. @param {IncomingMessage} req - The request message object @param {ServerResponse} res - The outgoing response object @returns {ServerResponse} The updated document or NOT FOUND if no document has been found
[ "README", "Replaces", "an", "existing", "user", "password", "in", "the", "DB", "using", "the", "request", "body", "property", "named", "password", ".", "Should", "be", "an", "admin", "only", "route", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/api/user(auth)/user.controller.js#L54-L69
40,707
michaelkrone/generator-material-app
generators/app/templates/server/api/user(auth)/user.controller.js
function (req, res, next) { var userId = req[this.paramName]._id; var oldPass = String(req.body.oldPassword); var newPass = String(req.body.newPassword); this.model.findOne({'_id': userId}, function (err, user) { if (user.authenticate(oldPass)) { user.password = newPass; user.save(function (err) { if (err) { return res.handleError(err); } return res.noContent(); }); } else { res.forbidden(); } }); }
javascript
function (req, res, next) { var userId = req[this.paramName]._id; var oldPass = String(req.body.oldPassword); var newPass = String(req.body.newPassword); this.model.findOne({'_id': userId}, function (err, user) { if (user.authenticate(oldPass)) { user.password = newPass; user.save(function (err) { if (err) { return res.handleError(err); } return res.noContent(); }); } else { res.forbidden(); } }); }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "var", "userId", "=", "req", "[", "this", ".", "paramName", "]", ".", "_id", ";", "var", "oldPass", "=", "String", "(", "req", ".", "body", ".", "oldPassword", ")", ";", "var", "newPass", "=", "String", "(", "req", ".", "body", ".", "newPassword", ")", ";", "this", ".", "model", ".", "findOne", "(", "{", "'_id'", ":", "userId", "}", ",", "function", "(", "err", ",", "user", ")", "{", "if", "(", "user", ".", "authenticate", "(", "oldPass", ")", ")", "{", "user", ".", "password", "=", "newPass", ";", "user", ".", "save", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "res", ".", "handleError", "(", "err", ")", ";", "}", "return", "res", ".", "noContent", "(", ")", ";", "}", ")", ";", "}", "else", "{", "res", ".", "forbidden", "(", ")", ";", "}", "}", ")", ";", "}" ]
Change the password of a user in the DB. The 'oldPassword' and 'newPassword' property of the request body are used. @param {IncomingMessage} req - The request message object containing the 'oldPassword' and 'newPassword' property @param {ServerResponse} res - The outgoing response object @param {function} next - The next handler function @returns {ServerResponse} The response status OK or FORBIDDEN if an error occurs
[ "Change", "the", "password", "of", "a", "user", "in", "the", "DB", ".", "The", "oldPassword", "and", "newPassword", "property", "of", "the", "request", "body", "are", "used", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/api/user(auth)/user.controller.js#L79-L98
40,708
michaelkrone/generator-material-app
generators/app/templates/server/api/user(auth)/user.controller.js
function (req, res, next) { if (!req.userInfo) { return res.unauthorized(); } return res.ok(req.userInfo.profile); }
javascript
function (req, res, next) { if (!req.userInfo) { return res.unauthorized(); } return res.ok(req.userInfo.profile); }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "!", "req", ".", "userInfo", ")", "{", "return", "res", ".", "unauthorized", "(", ")", ";", "}", "return", "res", ".", "ok", "(", "req", ".", "userInfo", ".", "profile", ")", ";", "}" ]
Get the authenticated user for the current request. The requested user id is read from the userInfo parameter of the request object. @param {IncomingMessage} req - The request message object the user object is read from @param {ServerResponse} res - The outgoing response object @param {function} next - The next handler function @returns {ServerResponse} The virtual 'profile' of this user or UNAUTHORIZED if no document has been found
[ "Get", "the", "authenticated", "user", "for", "the", "current", "request", ".", "The", "requested", "user", "id", "is", "read", "from", "the", "userInfo", "parameter", "of", "the", "request", "object", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/api/user(auth)/user.controller.js#L108-L114
40,709
michaelkrone/generator-material-app
generators/app/templates/server/lib/responses/errors.js
handleError
function handleError(err, options) { // jshint validthis: true // Get access to response object var res = this.res; var statusCode; console.log('handleError', err, options); if (err.name && err.name === 'ValidationError') { return res.badRequest(err); } try { statusCode = err.status || 500; // set the status as a default res.status(statusCode); if (statusCode !== 500 && typeof res[statusCode] === 'function') { return res[statusCode](err); } } catch (e) { console.log('Exception while handling error: %s', e); } return res.serverError(err); }
javascript
function handleError(err, options) { // jshint validthis: true // Get access to response object var res = this.res; var statusCode; console.log('handleError', err, options); if (err.name && err.name === 'ValidationError') { return res.badRequest(err); } try { statusCode = err.status || 500; // set the status as a default res.status(statusCode); if (statusCode !== 500 && typeof res[statusCode] === 'function') { return res[statusCode](err); } } catch (e) { console.log('Exception while handling error: %s', e); } return res.serverError(err); }
[ "function", "handleError", "(", "err", ",", "options", ")", "{", "// jshint validthis: true", "// Get access to response object", "var", "res", "=", "this", ".", "res", ";", "var", "statusCode", ";", "console", ".", "log", "(", "'handleError'", ",", "err", ",", "options", ")", ";", "if", "(", "err", ".", "name", "&&", "err", ".", "name", "===", "'ValidationError'", ")", "{", "return", "res", ".", "badRequest", "(", "err", ")", ";", "}", "try", "{", "statusCode", "=", "err", ".", "status", "||", "500", ";", "// set the status as a default", "res", ".", "status", "(", "statusCode", ")", ";", "if", "(", "statusCode", "!==", "500", "&&", "typeof", "res", "[", "statusCode", "]", "===", "'function'", ")", "{", "return", "res", "[", "statusCode", "]", "(", "err", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "'Exception while handling error: %s'", ",", "e", ")", ";", "}", "return", "res", ".", "serverError", "(", "err", ")", ";", "}" ]
Handle generic errors on requests. Set status 'Internal Server Error' @param {http.ServerResponse} res - The outgoing response object @param {Error} [err] - The error that occurred during the request @return The given Response with a error status code set (defaults to 500) and the error object set as response body.
[ "Handle", "generic", "errors", "on", "requests", ".", "Set", "status", "Internal", "Server", "Error" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/responses/errors.js#L251-L276
40,710
michaelkrone/generator-material-app
generators/app/templates/server/api/user(auth)/user.model.js
validateUniqueName
function validateUniqueName(value, respond) { // jshint validthis: true var self = this; // check for uniqueness of user name this.constructor.findOne({name: value}, function (err, user) { if (err) { throw err; } if (user) { // the searched name is my name or a duplicate return respond(self.id === user.id); } respond(true); }); }
javascript
function validateUniqueName(value, respond) { // jshint validthis: true var self = this; // check for uniqueness of user name this.constructor.findOne({name: value}, function (err, user) { if (err) { throw err; } if (user) { // the searched name is my name or a duplicate return respond(self.id === user.id); } respond(true); }); }
[ "function", "validateUniqueName", "(", "value", ",", "respond", ")", "{", "// jshint validthis: true", "var", "self", "=", "this", ";", "// check for uniqueness of user name", "this", ".", "constructor", ".", "findOne", "(", "{", "name", ":", "value", "}", ",", "function", "(", "err", ",", "user", ")", "{", "if", "(", "err", ")", "{", "throw", "err", ";", "}", "if", "(", "user", ")", "{", "// the searched name is my name or a duplicate", "return", "respond", "(", "self", ".", "id", "===", "user", ".", "id", ")", ";", "}", "respond", "(", "true", ")", ";", "}", ")", ";", "}" ]
Validate the uniqueness of the given username @api private @param {String} value - The username to check for uniqueness @param {Function} respond - The callback function
[ "Validate", "the", "uniqueness", "of", "the", "given", "username" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/api/user(auth)/user.model.js#L259-L276
40,711
michaelkrone/generator-material-app
generators/app/templates/server/api/user(auth)/user.model.js
preSave
function preSave(next) { // jshint validthis: true var self = this; if (this.isNew && !validatePresenceOf(this.hashedPassword)) { return next(new MongooseError.ValidationError('Missing password')); } // check if the root user should be updated // return an error if some not root tries to touch the root document self.constructor.getRoot(function (err, rootUser) { if (err) { throw err; } // will we update the root user? if (rootUser && self.id === rootUser.id) { // delete the role to prevent loosing the root status delete self.role; // get the user role to check if a root user will perform the update var userRole = contextService.getContext('request:acl.user.role'); if (!userRole) { // no user role - no root user check return next(); } if (!auth.roles.isRoot(userRole)) { // return error, only root can update root return next(new MongooseError.ValidationError('Forbidden root update request')); } } // normal user update return next(); }); }
javascript
function preSave(next) { // jshint validthis: true var self = this; if (this.isNew && !validatePresenceOf(this.hashedPassword)) { return next(new MongooseError.ValidationError('Missing password')); } // check if the root user should be updated // return an error if some not root tries to touch the root document self.constructor.getRoot(function (err, rootUser) { if (err) { throw err; } // will we update the root user? if (rootUser && self.id === rootUser.id) { // delete the role to prevent loosing the root status delete self.role; // get the user role to check if a root user will perform the update var userRole = contextService.getContext('request:acl.user.role'); if (!userRole) { // no user role - no root user check return next(); } if (!auth.roles.isRoot(userRole)) { // return error, only root can update root return next(new MongooseError.ValidationError('Forbidden root update request')); } } // normal user update return next(); }); }
[ "function", "preSave", "(", "next", ")", "{", "// jshint validthis: true", "var", "self", "=", "this", ";", "if", "(", "this", ".", "isNew", "&&", "!", "validatePresenceOf", "(", "this", ".", "hashedPassword", ")", ")", "{", "return", "next", "(", "new", "MongooseError", ".", "ValidationError", "(", "'Missing password'", ")", ")", ";", "}", "// check if the root user should be updated", "// return an error if some not root tries to touch the root document", "self", ".", "constructor", ".", "getRoot", "(", "function", "(", "err", ",", "rootUser", ")", "{", "if", "(", "err", ")", "{", "throw", "err", ";", "}", "// will we update the root user?", "if", "(", "rootUser", "&&", "self", ".", "id", "===", "rootUser", ".", "id", ")", "{", "// delete the role to prevent loosing the root status", "delete", "self", ".", "role", ";", "// get the user role to check if a root user will perform the update", "var", "userRole", "=", "contextService", ".", "getContext", "(", "'request:acl.user.role'", ")", ";", "if", "(", "!", "userRole", ")", "{", "// no user role - no root user check", "return", "next", "(", ")", ";", "}", "if", "(", "!", "auth", ".", "roles", ".", "isRoot", "(", "userRole", ")", ")", "{", "// return error, only root can update root", "return", "next", "(", "new", "MongooseError", ".", "ValidationError", "(", "'Forbidden root update request'", ")", ")", ";", "}", "}", "// normal user update", "return", "next", "(", ")", ";", "}", ")", ";", "}" ]
Pre save hook for the User model. Validates the existence of the hashedPassword property if the document is saved for the first time. Ensure that only the root user can update itself. @api private @param {Function} next - The mongoose middleware callback @returns {*} If an error occurs the passed callback with an Error as its argument is called
[ "Pre", "save", "hook", "for", "the", "User", "model", ".", "Validates", "the", "existence", "of", "the", "hashedPassword", "property", "if", "the", "document", "is", "saved", "for", "the", "first", "time", ".", "Ensure", "that", "only", "the", "root", "user", "can", "update", "itself", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/api/user(auth)/user.model.js#L321-L357
40,712
michaelkrone/generator-material-app
generators/app/templates/server/api/user(auth)/user.model.js
preRemove
function preRemove(next) { // jshint validthis: true if (auth.roles.isRoot(this.role)) { return next(new MongooseError.ValidationError(auth.roles.getMaxRole() + ' role cannot be deleted')); } return next(); }
javascript
function preRemove(next) { // jshint validthis: true if (auth.roles.isRoot(this.role)) { return next(new MongooseError.ValidationError(auth.roles.getMaxRole() + ' role cannot be deleted')); } return next(); }
[ "function", "preRemove", "(", "next", ")", "{", "// jshint validthis: true", "if", "(", "auth", ".", "roles", ".", "isRoot", "(", "this", ".", "role", ")", ")", "{", "return", "next", "(", "new", "MongooseError", ".", "ValidationError", "(", "auth", ".", "roles", ".", "getMaxRole", "(", ")", "+", "' role cannot be deleted'", ")", ")", ";", "}", "return", "next", "(", ")", ";", "}" ]
Pre remove hook for the User model. Validates that the root user cannot be deleted. @api private @param {Function} next - The mongoose middleware callback @returns {*} If an error occurs the passed callback with an Error as its argument is called
[ "Pre", "remove", "hook", "for", "the", "User", "model", ".", "Validates", "that", "the", "root", "user", "cannot", "be", "deleted", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/api/user(auth)/user.model.js#L367-L374
40,713
michaelkrone/generator-material-app
generators/app/templates/server/lib/auth(auth)/local/passport.js
getAuthentication
function getAuthentication(authModel, config) { /** * @name authenticate * @function * @memberOf getAuthentication * Authenticate the user. * @param {String} name - The name used to authenticate the user * @param {String} password - The hashed password * @param {function} done - The callback function called with an error or the valid user object */ function authenticate(name, password, done) { authModel.findOne({name: name, active: true}, function (err, user) { if (err) { return done(err); } if (!user) { return done(null, false, {message: 'Unknown user'}); } if (!user.authenticate(password)) { return done(null, false, {message: 'Wrong password'}); } return done(null, user); }); } return authenticate; }
javascript
function getAuthentication(authModel, config) { /** * @name authenticate * @function * @memberOf getAuthentication * Authenticate the user. * @param {String} name - The name used to authenticate the user * @param {String} password - The hashed password * @param {function} done - The callback function called with an error or the valid user object */ function authenticate(name, password, done) { authModel.findOne({name: name, active: true}, function (err, user) { if (err) { return done(err); } if (!user) { return done(null, false, {message: 'Unknown user'}); } if (!user.authenticate(password)) { return done(null, false, {message: 'Wrong password'}); } return done(null, user); }); } return authenticate; }
[ "function", "getAuthentication", "(", "authModel", ",", "config", ")", "{", "/**\n * @name authenticate\n * @function\n * @memberOf getAuthentication\n * Authenticate the user.\n * @param {String} name - The name used to authenticate the user\n * @param {String} password - The hashed password\n * @param {function} done - The callback function called with an error or the valid user object\n */", "function", "authenticate", "(", "name", ",", "password", ",", "done", ")", "{", "authModel", ".", "findOne", "(", "{", "name", ":", "name", ",", "active", ":", "true", "}", ",", "function", "(", "err", ",", "user", ")", "{", "if", "(", "err", ")", "{", "return", "done", "(", "err", ")", ";", "}", "if", "(", "!", "user", ")", "{", "return", "done", "(", "null", ",", "false", ",", "{", "message", ":", "'Unknown user'", "}", ")", ";", "}", "if", "(", "!", "user", ".", "authenticate", "(", "password", ")", ")", "{", "return", "done", "(", "null", ",", "false", ",", "{", "message", ":", "'Wrong password'", "}", ")", ";", "}", "return", "done", "(", "null", ",", "user", ")", ";", "}", ")", ";", "}", "return", "authenticate", ";", "}" ]
Return a function that authenticates the user. The user is identified by email. The hashed password is passed to the User model for authentication. @param {Model} authModel - The mongoose model used to authenticate the user @param {Object} [config] - The application configuration, may be passed to the service some day @returns {function} - The authentication function to use with the given authModel
[ "Return", "a", "function", "that", "authenticates", "the", "user", ".", "The", "user", "is", "identified", "by", "email", ".", "The", "hashed", "password", "is", "passed", "to", "the", "User", "model", "for", "authentication", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/auth(auth)/local/passport.js#L42-L72
40,714
michaelkrone/generator-material-app
generators/app/templates/server/lib/auth(auth)/local/index.js
authenticate
function authenticate(req, res, next) { var callback = _.bind(authCallback, {req: req, res: res}); passport.authenticate('local', callback)(req, res, next) }
javascript
function authenticate(req, res, next) { var callback = _.bind(authCallback, {req: req, res: res}); passport.authenticate('local', callback)(req, res, next) }
[ "function", "authenticate", "(", "req", ",", "res", ",", "next", ")", "{", "var", "callback", "=", "_", ".", "bind", "(", "authCallback", ",", "{", "req", ":", "req", ",", "res", ":", "res", "}", ")", ";", "passport", ".", "authenticate", "(", "'local'", ",", "callback", ")", "(", "req", ",", "res", ",", "next", ")", "}" ]
Authenticate a request and sign a token. @param {http.IncomingMessage} req - The request message object @param {http.ServerResponse} res - The outgoing response object @param {function} next - The next handler callback @return {http.ServerResponse} The result of calling the [callback function]{@link auth:local~authCallback}
[ "Authenticate", "a", "request", "and", "sign", "a", "token", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/auth(auth)/local/index.js#L29-L32
40,715
michaelkrone/generator-material-app
generators/app/templates/server/lib/controllers/crud.controller.js
CrudController
function CrudController(model, idName) { // call super constructor BaseController.call(this); // set the model instance to work on this.model = model; // set id name if defined, defaults to 'id' if (idName) { this.idName = String(idName); } }
javascript
function CrudController(model, idName) { // call super constructor BaseController.call(this); // set the model instance to work on this.model = model; // set id name if defined, defaults to 'id' if (idName) { this.idName = String(idName); } }
[ "function", "CrudController", "(", "model", ",", "idName", ")", "{", "// call super constructor", "BaseController", ".", "call", "(", "this", ")", ";", "// set the model instance to work on", "this", ".", "model", "=", "model", ";", "// set id name if defined, defaults to 'id'", "if", "(", "idName", ")", "{", "this", ".", "idName", "=", "String", "(", "idName", ")", ";", "}", "}" ]
Constructor function for CrudController. @classdesc Controller for basic CRUD operations on mongoose models. Uses the passed id name as the request parameter id to identify models. @constructor @inherits BaseController @param {Model} model - The mongoose model to operate on @param {String} [idName] - The name of the id request parameter to use
[ "Constructor", "function", "for", "CrudController", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/controllers/crud.controller.js#L21-L32
40,716
michaelkrone/generator-material-app
generators/app/templates/server/lib/controllers/crud.controller.js
function (req, res) { var query = req.query; if (this.omit.length) { query = _.omit(query, this.omit); } query = this.model.find(query); if (this.lean) { query.lean(); } if (this.select.length) { query.select(this.select.join(' ')); } this.populateQuery(query, this.filterPopulations('index')); query.exec(function (err, documents) { if (err) { return res.handleError(err); } return res.ok(documents); }); }
javascript
function (req, res) { var query = req.query; if (this.omit.length) { query = _.omit(query, this.omit); } query = this.model.find(query); if (this.lean) { query.lean(); } if (this.select.length) { query.select(this.select.join(' ')); } this.populateQuery(query, this.filterPopulations('index')); query.exec(function (err, documents) { if (err) { return res.handleError(err); } return res.ok(documents); }); }
[ "function", "(", "req", ",", "res", ")", "{", "var", "query", "=", "req", ".", "query", ";", "if", "(", "this", ".", "omit", ".", "length", ")", "{", "query", "=", "_", ".", "omit", "(", "query", ",", "this", ".", "omit", ")", ";", "}", "query", "=", "this", ".", "model", ".", "find", "(", "query", ")", ";", "if", "(", "this", ".", "lean", ")", "{", "query", ".", "lean", "(", ")", ";", "}", "if", "(", "this", ".", "select", ".", "length", ")", "{", "query", ".", "select", "(", "this", ".", "select", ".", "join", "(", "' '", ")", ")", ";", "}", "this", ".", "populateQuery", "(", "query", ",", "this", ".", "filterPopulations", "(", "'index'", ")", ")", ";", "query", ".", "exec", "(", "function", "(", "err", ",", "documents", ")", "{", "if", "(", "err", ")", "{", "return", "res", ".", "handleError", "(", "err", ")", ";", "}", "return", "res", ".", "ok", "(", "documents", ")", ";", "}", ")", ";", "}" ]
Get a list of documents. If a request query is passed it is used as the query object for the find method. @param {IncomingMessage} req - The request message object @param {ServerResponse} res - The outgoing response object the result is set to @returns {ServerResponse} Array of all documents for the {@link CrudController#model} model or the empty Array if no documents have been found
[ "Get", "a", "list", "of", "documents", ".", "If", "a", "request", "query", "is", "passed", "it", "is", "used", "as", "the", "query", "object", "for", "the", "find", "method", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/controllers/crud.controller.js#L106-L131
40,717
michaelkrone/generator-material-app
generators/app/templates/server/lib/controllers/crud.controller.js
function (req, res) { var self = this; var populations = self.filterPopulations('create'); this.model.populate(req.body, populations, function (err, populated) { if (err) { return res.handleError(err); } self.model.create(populated, function (err, document) { if (err) { return res.handleError(err); } populated._id = document._id; return res.created(self.getResponseObject(populated)); }) }); }
javascript
function (req, res) { var self = this; var populations = self.filterPopulations('create'); this.model.populate(req.body, populations, function (err, populated) { if (err) { return res.handleError(err); } self.model.create(populated, function (err, document) { if (err) { return res.handleError(err); } populated._id = document._id; return res.created(self.getResponseObject(populated)); }) }); }
[ "function", "(", "req", ",", "res", ")", "{", "var", "self", "=", "this", ";", "var", "populations", "=", "self", ".", "filterPopulations", "(", "'create'", ")", ";", "this", ".", "model", ".", "populate", "(", "req", ".", "body", ",", "populations", ",", "function", "(", "err", ",", "populated", ")", "{", "if", "(", "err", ")", "{", "return", "res", ".", "handleError", "(", "err", ")", ";", "}", "self", ".", "model", ".", "create", "(", "populated", ",", "function", "(", "err", ",", "document", ")", "{", "if", "(", "err", ")", "{", "return", "res", ".", "handleError", "(", "err", ")", ";", "}", "populated", ".", "_id", "=", "document", ".", "_id", ";", "return", "res", ".", "created", "(", "self", ".", "getResponseObject", "(", "populated", ")", ")", ";", "}", ")", "}", ")", ";", "}" ]
Creates a new document in the DB. @param {IncomingMessage} req - The request message object containing the json document data @param {ServerResponse} res - The outgoing response object @returns {ServerResponse} The response status 201 CREATED or an error response
[ "Creates", "a", "new", "document", "in", "the", "DB", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/controllers/crud.controller.js#L166-L185
40,718
michaelkrone/generator-material-app
generators/app/templates/client/app/components/mongoose-error/mongoose-error.directive.js
setResponseErrors
function setResponseErrors(err, obj) { /* jshint validthis: true */ var self = this; obj = obj || {}; if (err.data && err.data.errors) { err = err.data.errors; } if (err.errors) { err = err.errors; } angular.forEach(err, function (error, field) { if (self[field]) { self[field].$setValidity('mongoose', false); } obj[field] = error.type; }); }
javascript
function setResponseErrors(err, obj) { /* jshint validthis: true */ var self = this; obj = obj || {}; if (err.data && err.data.errors) { err = err.data.errors; } if (err.errors) { err = err.errors; } angular.forEach(err, function (error, field) { if (self[field]) { self[field].$setValidity('mongoose', false); } obj[field] = error.type; }); }
[ "function", "setResponseErrors", "(", "err", ",", "obj", ")", "{", "/* jshint validthis: true */", "var", "self", "=", "this", ";", "obj", "=", "obj", "||", "{", "}", ";", "if", "(", "err", ".", "data", "&&", "err", ".", "data", ".", "errors", ")", "{", "err", "=", "err", ".", "data", ".", "errors", ";", "}", "if", "(", "err", ".", "errors", ")", "{", "err", "=", "err", ".", "errors", ";", "}", "angular", ".", "forEach", "(", "err", ",", "function", "(", "error", ",", "field", ")", "{", "if", "(", "self", "[", "field", "]", ")", "{", "self", "[", "field", "]", ".", "$setValidity", "(", "'mongoose'", ",", "false", ")", ";", "}", "obj", "[", "field", "]", "=", "error", ".", "type", ";", "}", ")", ";", "}" ]
Update validity of form fields that match the mongoose errors @param {Object} errors - The errors object to look for property names on @param {Object} [obj] - Object to attach all errors to @return {Object} An object with all fields mapped to the corresponding error
[ "Update", "validity", "of", "form", "fields", "that", "match", "the", "mongoose", "errors" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/components/mongoose-error/mongoose-error.directive.js#L123-L142
40,719
jillix/medium-editor-custom-html
src/custom-html.js
CustomHtml
function CustomHtml(options) { this.button = document.createElement('button'); this.button.className = 'medium-editor-action'; if (this.button.innerText) { this.button.innerText = options.buttonText || "</>"; } else { this.button.textContent = options.buttonText || "</>"; } this.button.onclick = this.onClick.bind(this); this.options = options; }
javascript
function CustomHtml(options) { this.button = document.createElement('button'); this.button.className = 'medium-editor-action'; if (this.button.innerText) { this.button.innerText = options.buttonText || "</>"; } else { this.button.textContent = options.buttonText || "</>"; } this.button.onclick = this.onClick.bind(this); this.options = options; }
[ "function", "CustomHtml", "(", "options", ")", "{", "this", ".", "button", "=", "document", ".", "createElement", "(", "'button'", ")", ";", "this", ".", "button", ".", "className", "=", "'medium-editor-action'", ";", "if", "(", "this", ".", "button", ".", "innerText", ")", "{", "this", ".", "button", ".", "innerText", "=", "options", ".", "buttonText", "||", "\"</>\"", ";", "}", "else", "{", "this", ".", "button", ".", "textContent", "=", "options", ".", "buttonText", "||", "\"</>\"", ";", "}", "this", ".", "button", ".", "onclick", "=", "this", ".", "onClick", ".", "bind", "(", "this", ")", ";", "this", ".", "options", "=", "options", ";", "}" ]
CustomHtml Creates a new instance of CustomHtml extension. Licensed under the MIT license. Copyright (c) 2014 jillix @name CustomHtml @function @param {Object} options An object containing the extension configuration. The following fields should be provided: - buttonText: the text of the button (default: `</>`) - htmlToInsert: the HTML code that should be inserted
[ "CustomHtml", "Creates", "a", "new", "instance", "of", "CustomHtml", "extension", "." ]
d49a40979c2b5fb0fa58c8b6a0d1875dbf4da6ca
https://github.com/jillix/medium-editor-custom-html/blob/d49a40979c2b5fb0fa58c8b6a0d1875dbf4da6ca/src/custom-html.js#L16-L26
40,720
michaelkrone/generator-material-app
generators/app/templates/server/api/clientModelDoc(demo)/clientModelDoc.socket.js
registerClientModelDocSockets
function registerClientModelDocSockets(socket) { ClientModelDoc.schema.post('save', function (doc) { onSave(socket, doc); }); ClientModelDoc.schema.post('remove', function (doc) { onRemove(socket, doc); }); }
javascript
function registerClientModelDocSockets(socket) { ClientModelDoc.schema.post('save', function (doc) { onSave(socket, doc); }); ClientModelDoc.schema.post('remove', function (doc) { onRemove(socket, doc); }); }
[ "function", "registerClientModelDocSockets", "(", "socket", ")", "{", "ClientModelDoc", ".", "schema", ".", "post", "(", "'save'", ",", "function", "(", "doc", ")", "{", "onSave", "(", "socket", ",", "doc", ")", ";", "}", ")", ";", "ClientModelDoc", ".", "schema", ".", "post", "(", "'remove'", ",", "function", "(", "doc", ")", "{", "onRemove", "(", "socket", ",", "doc", ")", ";", "}", ")", ";", "}" ]
Register ClientModelDoc model change events on the passed socket @param {socket.io} socket - The socket object to register the ClientModelDoc model events on
[ "Register", "ClientModelDoc", "model", "change", "events", "on", "the", "passed", "socket" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/api/clientModelDoc(demo)/clientModelDoc.socket.js#L24-L32
40,721
michaelkrone/generator-material-app
generators/app/templates/client/app/clientModelDoc(demo)/list/edit/edit.controller.js
update
function update(form) { // refuse to work with invalid data if (!vm.clientModelDoc._id || form && !form.$valid) { return; } ClientModelDocService.update(vm.clientModelDoc) .then(updateClientModelDocSuccess) .catch(updateClientModelDocCatch); function updateClientModelDocSuccess(updatedClientModelDoc) { // update the display name after successful save vm.displayName = updatedClientModelDoc.name; Toast.show({text: 'ClientModelDoc ' + vm.displayName + ' updated'}); if (form) { form.$setPristine(); } } function updateClientModelDocCatch(err) { Toast.show({ type: 'warn', text: 'Error while updating ClientModelDoc ' + vm.displayName, link: {state: $state.$current, params: $stateParams} }); if (form && err) { form.setResponseErrors(err.data); } } }
javascript
function update(form) { // refuse to work with invalid data if (!vm.clientModelDoc._id || form && !form.$valid) { return; } ClientModelDocService.update(vm.clientModelDoc) .then(updateClientModelDocSuccess) .catch(updateClientModelDocCatch); function updateClientModelDocSuccess(updatedClientModelDoc) { // update the display name after successful save vm.displayName = updatedClientModelDoc.name; Toast.show({text: 'ClientModelDoc ' + vm.displayName + ' updated'}); if (form) { form.$setPristine(); } } function updateClientModelDocCatch(err) { Toast.show({ type: 'warn', text: 'Error while updating ClientModelDoc ' + vm.displayName, link: {state: $state.$current, params: $stateParams} }); if (form && err) { form.setResponseErrors(err.data); } } }
[ "function", "update", "(", "form", ")", "{", "// refuse to work with invalid data", "if", "(", "!", "vm", ".", "clientModelDoc", ".", "_id", "||", "form", "&&", "!", "form", ".", "$valid", ")", "{", "return", ";", "}", "ClientModelDocService", ".", "update", "(", "vm", ".", "clientModelDoc", ")", ".", "then", "(", "updateClientModelDocSuccess", ")", ".", "catch", "(", "updateClientModelDocCatch", ")", ";", "function", "updateClientModelDocSuccess", "(", "updatedClientModelDoc", ")", "{", "// update the display name after successful save", "vm", ".", "displayName", "=", "updatedClientModelDoc", ".", "name", ";", "Toast", ".", "show", "(", "{", "text", ":", "'ClientModelDoc '", "+", "vm", ".", "displayName", "+", "' updated'", "}", ")", ";", "if", "(", "form", ")", "{", "form", ".", "$setPristine", "(", ")", ";", "}", "}", "function", "updateClientModelDocCatch", "(", "err", ")", "{", "Toast", ".", "show", "(", "{", "type", ":", "'warn'", ",", "text", ":", "'Error while updating ClientModelDoc '", "+", "vm", ".", "displayName", ",", "link", ":", "{", "state", ":", "$state", ".", "$current", ",", "params", ":", "$stateParams", "}", "}", ")", ";", "if", "(", "form", "&&", "err", ")", "{", "form", ".", "setResponseErrors", "(", "err", ".", "data", ")", ";", "}", "}", "}" ]
Updates a clientModelDoc by using the ClientModelDocService save method @param {Form} [form]
[ "Updates", "a", "clientModelDoc", "by", "using", "the", "ClientModelDocService", "save", "method" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/clientModelDoc(demo)/list/edit/edit.controller.js#L66-L96
40,722
michaelkrone/generator-material-app
generators/app/templates/client/app/clientModelDoc(demo)/list/edit/edit.controller.js
remove
function remove(form, ev) { var confirm = $mdDialog.confirm() .title('Delete clientModelDoc ' + vm.displayName + '?') .content('Do you really want to delete clientModelDoc ' + vm.displayName + '?') .ariaLabel('Delete clientModelDoc') .ok('Delete clientModelDoc') .cancel('Cancel') .targetEvent(ev); $mdDialog.show(confirm) .then(performRemove); /** * Removes a clientModelDoc by using the ClientModelDocService remove method * @api private */ function performRemove() { ClientModelDocService.remove(vm.clientModelDoc) .then(deleteClientModelDocSuccess) .catch(deleteClientModelDocCatch); function deleteClientModelDocSuccess() { Toast.show({type: 'success', text: 'ClientModelDoc ' + vm.displayName + ' deleted'}); vm.showList(); } function deleteClientModelDocCatch(err) { Toast.show({ type: 'warn', text: 'Error while deleting clientModelDoc ' + vm.displayName, link: {state: $state.$current, params: $stateParams} }); if (form && err) { form.setResponseErrors(err, vm.errors); } } } }
javascript
function remove(form, ev) { var confirm = $mdDialog.confirm() .title('Delete clientModelDoc ' + vm.displayName + '?') .content('Do you really want to delete clientModelDoc ' + vm.displayName + '?') .ariaLabel('Delete clientModelDoc') .ok('Delete clientModelDoc') .cancel('Cancel') .targetEvent(ev); $mdDialog.show(confirm) .then(performRemove); /** * Removes a clientModelDoc by using the ClientModelDocService remove method * @api private */ function performRemove() { ClientModelDocService.remove(vm.clientModelDoc) .then(deleteClientModelDocSuccess) .catch(deleteClientModelDocCatch); function deleteClientModelDocSuccess() { Toast.show({type: 'success', text: 'ClientModelDoc ' + vm.displayName + ' deleted'}); vm.showList(); } function deleteClientModelDocCatch(err) { Toast.show({ type: 'warn', text: 'Error while deleting clientModelDoc ' + vm.displayName, link: {state: $state.$current, params: $stateParams} }); if (form && err) { form.setResponseErrors(err, vm.errors); } } } }
[ "function", "remove", "(", "form", ",", "ev", ")", "{", "var", "confirm", "=", "$mdDialog", ".", "confirm", "(", ")", ".", "title", "(", "'Delete clientModelDoc '", "+", "vm", ".", "displayName", "+", "'?'", ")", ".", "content", "(", "'Do you really want to delete clientModelDoc '", "+", "vm", ".", "displayName", "+", "'?'", ")", ".", "ariaLabel", "(", "'Delete clientModelDoc'", ")", ".", "ok", "(", "'Delete clientModelDoc'", ")", ".", "cancel", "(", "'Cancel'", ")", ".", "targetEvent", "(", "ev", ")", ";", "$mdDialog", ".", "show", "(", "confirm", ")", ".", "then", "(", "performRemove", ")", ";", "/**\n * Removes a clientModelDoc by using the ClientModelDocService remove method\n * @api private\n */", "function", "performRemove", "(", ")", "{", "ClientModelDocService", ".", "remove", "(", "vm", ".", "clientModelDoc", ")", ".", "then", "(", "deleteClientModelDocSuccess", ")", ".", "catch", "(", "deleteClientModelDocCatch", ")", ";", "function", "deleteClientModelDocSuccess", "(", ")", "{", "Toast", ".", "show", "(", "{", "type", ":", "'success'", ",", "text", ":", "'ClientModelDoc '", "+", "vm", ".", "displayName", "+", "' deleted'", "}", ")", ";", "vm", ".", "showList", "(", ")", ";", "}", "function", "deleteClientModelDocCatch", "(", "err", ")", "{", "Toast", ".", "show", "(", "{", "type", ":", "'warn'", ",", "text", ":", "'Error while deleting clientModelDoc '", "+", "vm", ".", "displayName", ",", "link", ":", "{", "state", ":", "$state", ".", "$current", ",", "params", ":", "$stateParams", "}", "}", ")", ";", "if", "(", "form", "&&", "err", ")", "{", "form", ".", "setResponseErrors", "(", "err", ",", "vm", ".", "errors", ")", ";", "}", "}", "}", "}" ]
Show a dialog to ask the clientModelDoc if she wants to delete the current selected clientModelDoc. @param {AngularForm} form - The form to pass to the remove handler @param {$event} ev - The event to pass to the dialog service
[ "Show", "a", "dialog", "to", "ask", "the", "clientModelDoc", "if", "she", "wants", "to", "delete", "the", "current", "selected", "clientModelDoc", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/clientModelDoc(demo)/list/edit/edit.controller.js#L103-L141
40,723
michaelkrone/generator-material-app
generators/app/templates/client/app/clientModelDoc(demo)/list/edit/edit.controller.js
performRemove
function performRemove() { ClientModelDocService.remove(vm.clientModelDoc) .then(deleteClientModelDocSuccess) .catch(deleteClientModelDocCatch); function deleteClientModelDocSuccess() { Toast.show({type: 'success', text: 'ClientModelDoc ' + vm.displayName + ' deleted'}); vm.showList(); } function deleteClientModelDocCatch(err) { Toast.show({ type: 'warn', text: 'Error while deleting clientModelDoc ' + vm.displayName, link: {state: $state.$current, params: $stateParams} }); if (form && err) { form.setResponseErrors(err, vm.errors); } } }
javascript
function performRemove() { ClientModelDocService.remove(vm.clientModelDoc) .then(deleteClientModelDocSuccess) .catch(deleteClientModelDocCatch); function deleteClientModelDocSuccess() { Toast.show({type: 'success', text: 'ClientModelDoc ' + vm.displayName + ' deleted'}); vm.showList(); } function deleteClientModelDocCatch(err) { Toast.show({ type: 'warn', text: 'Error while deleting clientModelDoc ' + vm.displayName, link: {state: $state.$current, params: $stateParams} }); if (form && err) { form.setResponseErrors(err, vm.errors); } } }
[ "function", "performRemove", "(", ")", "{", "ClientModelDocService", ".", "remove", "(", "vm", ".", "clientModelDoc", ")", ".", "then", "(", "deleteClientModelDocSuccess", ")", ".", "catch", "(", "deleteClientModelDocCatch", ")", ";", "function", "deleteClientModelDocSuccess", "(", ")", "{", "Toast", ".", "show", "(", "{", "type", ":", "'success'", ",", "text", ":", "'ClientModelDoc '", "+", "vm", ".", "displayName", "+", "' deleted'", "}", ")", ";", "vm", ".", "showList", "(", ")", ";", "}", "function", "deleteClientModelDocCatch", "(", "err", ")", "{", "Toast", ".", "show", "(", "{", "type", ":", "'warn'", ",", "text", ":", "'Error while deleting clientModelDoc '", "+", "vm", ".", "displayName", ",", "link", ":", "{", "state", ":", "$state", ".", "$current", ",", "params", ":", "$stateParams", "}", "}", ")", ";", "if", "(", "form", "&&", "err", ")", "{", "form", ".", "setResponseErrors", "(", "err", ",", "vm", ".", "errors", ")", ";", "}", "}", "}" ]
Removes a clientModelDoc by using the ClientModelDocService remove method @api private
[ "Removes", "a", "clientModelDoc", "by", "using", "the", "ClientModelDocService", "remove", "method" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/clientModelDoc(demo)/list/edit/edit.controller.js#L119-L140
40,724
michaelkrone/generator-material-app
generators/app/templates/server/lib/controllers/param.controller.js
ParamController
function ParamController(model, idName, paramName, router) { var modelName = model.modelName.toLowerCase(); // make idName and paramName arguments optional (v0.1.1) if (typeof idName === 'function') { router = idName; idName = modelName + 'Id'; } if (typeof paramName === 'function') { router = paramName; paramName = modelName + 'Param'; } // call super constructor CrudController.call(this, model, idName); // only set param if it is set, will default to 'id' if (!paramName) { paramName = modelName + 'Param'; } this.paramName = String(paramName); this.paramString = ':' + this.paramName; // register param name route parameter router.param(this.paramName, this.registerRequestParameter); }
javascript
function ParamController(model, idName, paramName, router) { var modelName = model.modelName.toLowerCase(); // make idName and paramName arguments optional (v0.1.1) if (typeof idName === 'function') { router = idName; idName = modelName + 'Id'; } if (typeof paramName === 'function') { router = paramName; paramName = modelName + 'Param'; } // call super constructor CrudController.call(this, model, idName); // only set param if it is set, will default to 'id' if (!paramName) { paramName = modelName + 'Param'; } this.paramName = String(paramName); this.paramString = ':' + this.paramName; // register param name route parameter router.param(this.paramName, this.registerRequestParameter); }
[ "function", "ParamController", "(", "model", ",", "idName", ",", "paramName", ",", "router", ")", "{", "var", "modelName", "=", "model", ".", "modelName", ".", "toLowerCase", "(", ")", ";", "// make idName and paramName arguments optional (v0.1.1)", "if", "(", "typeof", "idName", "===", "'function'", ")", "{", "router", "=", "idName", ";", "idName", "=", "modelName", "+", "'Id'", ";", "}", "if", "(", "typeof", "paramName", "===", "'function'", ")", "{", "router", "=", "paramName", ";", "paramName", "=", "modelName", "+", "'Param'", ";", "}", "// call super constructor", "CrudController", ".", "call", "(", "this", ",", "model", ",", "idName", ")", ";", "// only set param if it is set, will default to 'id'", "if", "(", "!", "paramName", ")", "{", "paramName", "=", "modelName", "+", "'Param'", ";", "}", "this", ".", "paramName", "=", "String", "(", "paramName", ")", ";", "this", ".", "paramString", "=", "':'", "+", "this", ".", "paramName", ";", "// register param name route parameter", "router", ".", "param", "(", "this", ".", "paramName", ",", "this", ".", "registerRequestParameter", ")", ";", "}" ]
Constructor function for ParamController. @classdesc Controller for basic CRUD operations on mongoose models. Using a route parameter object (request property) if possible. The parameter name is passed as the third argument. @constructor @inherits CrudController @param {Object} model - The mongoose model to operate on @param {String} [idName] - The name of the id request parameter to use, defaults to the lowercase model name with 'Id' appended. @param {String} [paramName] - The name of the request property to use, defaults to the lowercase model name with 'Param' appended. @param {Object} router - The express router to attach the param function to
[ "Constructor", "function", "for", "ParamController", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/controllers/param.controller.js#L28-L55
40,725
michaelkrone/generator-material-app
generators/app/templates/server/lib/controllers/param.controller.js
function (req, res, next, id) { var self = this; // check if a custom id is used, when not only process a valid object id if (this.mongoId && !ObjectID.isValid(id)) { res.badRequest(); return next(); } // attach the document as this.paramName to the request this.model.findOne({'_id': id}, function (err, doc) { if (err) { return next(err); } if (!doc) { res.notFound(); return next('route'); } req[self.paramName] = doc; return next(); }); }
javascript
function (req, res, next, id) { var self = this; // check if a custom id is used, when not only process a valid object id if (this.mongoId && !ObjectID.isValid(id)) { res.badRequest(); return next(); } // attach the document as this.paramName to the request this.model.findOne({'_id': id}, function (err, doc) { if (err) { return next(err); } if (!doc) { res.notFound(); return next('route'); } req[self.paramName] = doc; return next(); }); }
[ "function", "(", "req", ",", "res", ",", "next", ",", "id", ")", "{", "var", "self", "=", "this", ";", "// check if a custom id is used, when not only process a valid object id", "if", "(", "this", ".", "mongoId", "&&", "!", "ObjectID", ".", "isValid", "(", "id", ")", ")", "{", "res", ".", "badRequest", "(", ")", ";", "return", "next", "(", ")", ";", "}", "// attach the document as this.paramName to the request", "this", ".", "model", ".", "findOne", "(", "{", "'_id'", ":", "id", "}", ",", "function", "(", "err", ",", "doc", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", ";", "}", "if", "(", "!", "doc", ")", "{", "res", ".", "notFound", "(", ")", ";", "return", "next", "(", "'route'", ")", ";", "}", "req", "[", "self", ".", "paramName", "]", "=", "doc", ";", "return", "next", "(", ")", ";", "}", ")", ";", "}" ]
Register the default id parameter for route requests. Add a property to the current request which is the document returned by the controller Model for the param configures paramter name available in the processed request. @param {http.IncomingMessage} req - The request message object @param {http.ServerResponse} res - The outgoing response object @param next {function} - The next handler function to call when done @param id {String} - The id parameter parsed from the current request @returns {function} This function sets a status of 400 for malformed MongoDB id's and a status of 404 if no document has been found for the passed parameter value. Calls the passed next function when done.
[ "Register", "the", "default", "id", "parameter", "for", "route", "requests", ".", "Add", "a", "property", "to", "the", "current", "request", "which", "is", "the", "document", "returned", "by", "the", "controller", "Model", "for", "the", "param", "configures", "paramter", "name", "available", "in", "the", "processed", "request", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/controllers/param.controller.js#L173-L196
40,726
michaelkrone/generator-material-app
generators/app/templates/client/app/components/toggle-component/toggle-component.service.js
ToggleComponentService
function ToggleComponentService($mdComponentRegistry, $log, $q) { return function (contentHandle) { var errorMsg = "ToggleComponent '" + contentHandle + "' is not available!"; var instance = $mdComponentRegistry.get(contentHandle); if (!instance) { $log.error('No content-switch found for handle ' + contentHandle); } return { isOpen: isOpen, toggle: toggle, open: open, close: close }; function isOpen() { return instance && instance.isOpen(); } function toggle() { return instance ? instance.toggle() : $q.reject(errorMsg); } function open() { return instance ? instance.open() : $q.reject(errorMsg); } function close() { return instance ? instance.close() : $q.reject(errorMsg); } }; }
javascript
function ToggleComponentService($mdComponentRegistry, $log, $q) { return function (contentHandle) { var errorMsg = "ToggleComponent '" + contentHandle + "' is not available!"; var instance = $mdComponentRegistry.get(contentHandle); if (!instance) { $log.error('No content-switch found for handle ' + contentHandle); } return { isOpen: isOpen, toggle: toggle, open: open, close: close }; function isOpen() { return instance && instance.isOpen(); } function toggle() { return instance ? instance.toggle() : $q.reject(errorMsg); } function open() { return instance ? instance.open() : $q.reject(errorMsg); } function close() { return instance ? instance.close() : $q.reject(errorMsg); } }; }
[ "function", "ToggleComponentService", "(", "$mdComponentRegistry", ",", "$log", ",", "$q", ")", "{", "return", "function", "(", "contentHandle", ")", "{", "var", "errorMsg", "=", "\"ToggleComponent '\"", "+", "contentHandle", "+", "\"' is not available!\"", ";", "var", "instance", "=", "$mdComponentRegistry", ".", "get", "(", "contentHandle", ")", ";", "if", "(", "!", "instance", ")", "{", "$log", ".", "error", "(", "'No content-switch found for handle '", "+", "contentHandle", ")", ";", "}", "return", "{", "isOpen", ":", "isOpen", ",", "toggle", ":", "toggle", ",", "open", ":", "open", ",", "close", ":", "close", "}", ";", "function", "isOpen", "(", ")", "{", "return", "instance", "&&", "instance", ".", "isOpen", "(", ")", ";", "}", "function", "toggle", "(", ")", "{", "return", "instance", "?", "instance", ".", "toggle", "(", ")", ":", "$q", ".", "reject", "(", "errorMsg", ")", ";", "}", "function", "open", "(", ")", "{", "return", "instance", "?", "instance", ".", "open", "(", ")", ":", "$q", ".", "reject", "(", "errorMsg", ")", ";", "}", "function", "close", "(", ")", "{", "return", "instance", "?", "instance", ".", "close", "(", ")", ":", "$q", ".", "reject", "(", "errorMsg", ")", ";", "}", "}", ";", "}" ]
ToggleComponent constructor AngularJS will instantiate a singleton by calling "new" on this function @ngdoc controller @name ToggleComponentService @module <%= scriptAppName %>.toggleComponent @returns {Object} The service definition for the ToggleComponent Service
[ "ToggleComponent", "constructor", "AngularJS", "will", "instantiate", "a", "singleton", "by", "calling", "new", "on", "this", "function" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/components/toggle-component/toggle-component.service.js#L26-L58
40,727
michaelkrone/generator-material-app
generators/app/templates/server/lib/auth(auth)/auth.service.js
isAuthenticated
function isAuthenticated() { return compose() // Validate jwt .use(function (req, res, next) { // allow access_token to be passed through query parameter as well if (req.query && req.query.hasOwnProperty('access_token')) { req.headers.authorization = 'Bearer ' + req.query.access_token; } validateJwt(req, res, next); }) .use(function (req, res, next) { // Attach userInfo to request // return if this request has already been authorized if (req.hasOwnProperty('userInfo')) { return next(); } // load user model on demand var User = require('../../api/user/user.model').model; // read the user id from the token information provided in req.user User.findOne({_id: req.user._id, active: true}, function (err, user) { if (err) { return next(err); } if (!user) { res.unauthorized(); return next(); } // set the requests userInfo object as the authenticated user req.userInfo = user; next(); }); }); }
javascript
function isAuthenticated() { return compose() // Validate jwt .use(function (req, res, next) { // allow access_token to be passed through query parameter as well if (req.query && req.query.hasOwnProperty('access_token')) { req.headers.authorization = 'Bearer ' + req.query.access_token; } validateJwt(req, res, next); }) .use(function (req, res, next) { // Attach userInfo to request // return if this request has already been authorized if (req.hasOwnProperty('userInfo')) { return next(); } // load user model on demand var User = require('../../api/user/user.model').model; // read the user id from the token information provided in req.user User.findOne({_id: req.user._id, active: true}, function (err, user) { if (err) { return next(err); } if (!user) { res.unauthorized(); return next(); } // set the requests userInfo object as the authenticated user req.userInfo = user; next(); }); }); }
[ "function", "isAuthenticated", "(", ")", "{", "return", "compose", "(", ")", "// Validate jwt", ".", "use", "(", "function", "(", "req", ",", "res", ",", "next", ")", "{", "// allow access_token to be passed through query parameter as well", "if", "(", "req", ".", "query", "&&", "req", ".", "query", ".", "hasOwnProperty", "(", "'access_token'", ")", ")", "{", "req", ".", "headers", ".", "authorization", "=", "'Bearer '", "+", "req", ".", "query", ".", "access_token", ";", "}", "validateJwt", "(", "req", ",", "res", ",", "next", ")", ";", "}", ")", ".", "use", "(", "function", "(", "req", ",", "res", ",", "next", ")", "{", "// Attach userInfo to request", "// return if this request has already been authorized", "if", "(", "req", ".", "hasOwnProperty", "(", "'userInfo'", ")", ")", "{", "return", "next", "(", ")", ";", "}", "// load user model on demand", "var", "User", "=", "require", "(", "'../../api/user/user.model'", ")", ".", "model", ";", "// read the user id from the token information provided in req.user", "User", ".", "findOne", "(", "{", "_id", ":", "req", ".", "user", ".", "_id", ",", "active", ":", "true", "}", ",", "function", "(", "err", ",", "user", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", ";", "}", "if", "(", "!", "user", ")", "{", "res", ".", "unauthorized", "(", ")", ";", "return", "next", "(", ")", ";", "}", "// set the requests userInfo object as the authenticated user", "req", ".", "userInfo", "=", "user", ";", "next", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Attaches the user object to the request if authenticated otherwise returns 403 @return {express.middleware}
[ "Attaches", "the", "user", "object", "to", "the", "request", "if", "authenticated", "otherwise", "returns", "403" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/auth(auth)/auth.service.js#L64-L101
40,728
michaelkrone/generator-material-app
generators/app/templates/server/lib/auth(auth)/auth.service.js
hasRole
function hasRole(roleRequired) { if (!roleRequired) { throw new Error('Required role needs to be set'); } return compose() .use(isAuthenticated()) .use(function meetsRequirements(req, res, next) { if (roles.hasRole(req.userInfo.role, roleRequired)) { next(); } else { res.forbidden(); } }); }
javascript
function hasRole(roleRequired) { if (!roleRequired) { throw new Error('Required role needs to be set'); } return compose() .use(isAuthenticated()) .use(function meetsRequirements(req, res, next) { if (roles.hasRole(req.userInfo.role, roleRequired)) { next(); } else { res.forbidden(); } }); }
[ "function", "hasRole", "(", "roleRequired", ")", "{", "if", "(", "!", "roleRequired", ")", "{", "throw", "new", "Error", "(", "'Required role needs to be set'", ")", ";", "}", "return", "compose", "(", ")", ".", "use", "(", "isAuthenticated", "(", ")", ")", ".", "use", "(", "function", "meetsRequirements", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "roles", ".", "hasRole", "(", "req", ".", "userInfo", ".", "role", ",", "roleRequired", ")", ")", "{", "next", "(", ")", ";", "}", "else", "{", "res", ".", "forbidden", "(", ")", ";", "}", "}", ")", ";", "}" ]
Checks if the user role meets the minimum requirements of the route, sets the response status to FORBIDDEN if the requirements do not match. @param {String} roleRequired - Name of the required role @return {ServerResponse}
[ "Checks", "if", "the", "user", "role", "meets", "the", "minimum", "requirements", "of", "the", "route", "sets", "the", "response", "status", "to", "FORBIDDEN", "if", "the", "requirements", "do", "not", "match", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/auth(auth)/auth.service.js#L109-L123
40,729
michaelkrone/generator-material-app
generators/app/templates/server/lib/auth(auth)/auth.service.js
signToken
function signToken(id, role) { return jwt.sign({_id: id, role: role}, config.secrets.session, {expiresInMinutes: 60 * 5}); }
javascript
function signToken(id, role) { return jwt.sign({_id: id, role: role}, config.secrets.session, {expiresInMinutes: 60 * 5}); }
[ "function", "signToken", "(", "id", ",", "role", ")", "{", "return", "jwt", ".", "sign", "(", "{", "_id", ":", "id", ",", "role", ":", "role", "}", ",", "config", ".", "secrets", ".", "session", ",", "{", "expiresInMinutes", ":", "60", "*", "5", "}", ")", ";", "}" ]
Returns a jwt token signed by the app secret @param {String} id - Id used to sign a token @return {String}
[ "Returns", "a", "jwt", "token", "signed", "by", "the", "app", "secret" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/auth(auth)/auth.service.js#L130-L132
40,730
michaelkrone/generator-material-app
generators/app/templates/server/lib/auth(auth)/auth.service.js
addAuthContext
function addAuthContext(namespace) { if (!namespace) { throw new Error('No context namespace specified!'); } return function addAuthContextMiddleWare(req, res, next) { contextService.setContext(namespace, req.userInfo); next(); }; }
javascript
function addAuthContext(namespace) { if (!namespace) { throw new Error('No context namespace specified!'); } return function addAuthContextMiddleWare(req, res, next) { contextService.setContext(namespace, req.userInfo); next(); }; }
[ "function", "addAuthContext", "(", "namespace", ")", "{", "if", "(", "!", "namespace", ")", "{", "throw", "new", "Error", "(", "'No context namespace specified!'", ")", ";", "}", "return", "function", "addAuthContextMiddleWare", "(", "req", ",", "res", ",", "next", ")", "{", "contextService", ".", "setContext", "(", "namespace", ",", "req", ".", "userInfo", ")", ";", "next", "(", ")", ";", "}", ";", "}" ]
Add the current user object to the request context as the given name @param {http.IncomingMessage} req - The request message object @param {ServerResponse} res - The outgoing response object @param {function} next - The next handler callback
[ "Add", "the", "current", "user", "object", "to", "the", "request", "context", "as", "the", "given", "name" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/auth(auth)/auth.service.js#L158-L167
40,731
michaelkrone/generator-material-app
generators/app/templates/client/app/components/auth(auth)/authinterceptor.service.js
request
function request(config) { config.headers = config.headers || {}; if ($cookieStore.get('token')) { config.headers.Authorization = 'Bearer ' + $cookieStore.get('token'); } return config; }
javascript
function request(config) { config.headers = config.headers || {}; if ($cookieStore.get('token')) { config.headers.Authorization = 'Bearer ' + $cookieStore.get('token'); } return config; }
[ "function", "request", "(", "config", ")", "{", "config", ".", "headers", "=", "config", ".", "headers", "||", "{", "}", ";", "if", "(", "$cookieStore", ".", "get", "(", "'token'", ")", ")", "{", "config", ".", "headers", ".", "Authorization", "=", "'Bearer '", "+", "$cookieStore", ".", "get", "(", "'token'", ")", ";", "}", "return", "config", ";", "}" ]
Add authorization token to headers
[ "Add", "authorization", "token", "to", "headers" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/components/auth(auth)/authinterceptor.service.js#L68-L74
40,732
michaelkrone/generator-material-app
generators/app/templates/client/app/components/auth(auth)/authinterceptor.service.js
responseError
function responseError(response) { if (response.status === 401) { // remove any stale tokens $cookieStore.remove('token'); // use timeout to perform location change // in the next digest cycle $timeout(function () { $location.path('/login'); }, 0); return $q.reject(response); } return $q.reject(response); }
javascript
function responseError(response) { if (response.status === 401) { // remove any stale tokens $cookieStore.remove('token'); // use timeout to perform location change // in the next digest cycle $timeout(function () { $location.path('/login'); }, 0); return $q.reject(response); } return $q.reject(response); }
[ "function", "responseError", "(", "response", ")", "{", "if", "(", "response", ".", "status", "===", "401", ")", "{", "// remove any stale tokens", "$cookieStore", ".", "remove", "(", "'token'", ")", ";", "// use timeout to perform location change", "// in the next digest cycle", "$timeout", "(", "function", "(", ")", "{", "$location", ".", "path", "(", "'/login'", ")", ";", "}", ",", "0", ")", ";", "return", "$q", ".", "reject", "(", "response", ")", ";", "}", "return", "$q", ".", "reject", "(", "response", ")", ";", "}" ]
Intercept 401s and redirect you to login
[ "Intercept", "401s", "and", "redirect", "you", "to", "login" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/components/auth(auth)/authinterceptor.service.js#L77-L91
40,733
michaelkrone/generator-material-app
generators/app/templates/server/config/express.js
initExpress
function initExpress(app) { var env = app.get('env'); var publicDir = path.join(config.root, config.publicDir); app.set('ip', config.ip); app.set('port', config.port); app.set('views', config.root + '/server/views'); app.engine('html', require('ejs').renderFile); app.set('view engine', 'html'); app.use(compression()); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(methodOverride()); app.use(cookieParser()); app.use(passport.initialize()); app.use(favicon(path.join(publicDir, 'favicon.ico'))); if ('production' === env) { app.use(express.static(publicDir)); app.set('appPath', publicDir); app.use(morgan('tiny')); } if ('development' === env || 'test' === env) { app.use(express.static(path.join(config.root, '.tmp'))); app.use(express.static(publicDir)); app.set('appPath', publicDir); app.use(morgan('dev')); // Error handler - has to be last app.use(errorHandler()); } }
javascript
function initExpress(app) { var env = app.get('env'); var publicDir = path.join(config.root, config.publicDir); app.set('ip', config.ip); app.set('port', config.port); app.set('views', config.root + '/server/views'); app.engine('html', require('ejs').renderFile); app.set('view engine', 'html'); app.use(compression()); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(methodOverride()); app.use(cookieParser()); app.use(passport.initialize()); app.use(favicon(path.join(publicDir, 'favicon.ico'))); if ('production' === env) { app.use(express.static(publicDir)); app.set('appPath', publicDir); app.use(morgan('tiny')); } if ('development' === env || 'test' === env) { app.use(express.static(path.join(config.root, '.tmp'))); app.use(express.static(publicDir)); app.set('appPath', publicDir); app.use(morgan('dev')); // Error handler - has to be last app.use(errorHandler()); } }
[ "function", "initExpress", "(", "app", ")", "{", "var", "env", "=", "app", ".", "get", "(", "'env'", ")", ";", "var", "publicDir", "=", "path", ".", "join", "(", "config", ".", "root", ",", "config", ".", "publicDir", ")", ";", "app", ".", "set", "(", "'ip'", ",", "config", ".", "ip", ")", ";", "app", ".", "set", "(", "'port'", ",", "config", ".", "port", ")", ";", "app", ".", "set", "(", "'views'", ",", "config", ".", "root", "+", "'/server/views'", ")", ";", "app", ".", "engine", "(", "'html'", ",", "require", "(", "'ejs'", ")", ".", "renderFile", ")", ";", "app", ".", "set", "(", "'view engine'", ",", "'html'", ")", ";", "app", ".", "use", "(", "compression", "(", ")", ")", ";", "app", ".", "use", "(", "bodyParser", ".", "urlencoded", "(", "{", "extended", ":", "false", "}", ")", ")", ";", "app", ".", "use", "(", "bodyParser", ".", "json", "(", ")", ")", ";", "app", ".", "use", "(", "methodOverride", "(", ")", ")", ";", "app", ".", "use", "(", "cookieParser", "(", ")", ")", ";", "app", ".", "use", "(", "passport", ".", "initialize", "(", ")", ")", ";", "app", ".", "use", "(", "favicon", "(", "path", ".", "join", "(", "publicDir", ",", "'favicon.ico'", ")", ")", ")", ";", "if", "(", "'production'", "===", "env", ")", "{", "app", ".", "use", "(", "express", ".", "static", "(", "publicDir", ")", ")", ";", "app", ".", "set", "(", "'appPath'", ",", "publicDir", ")", ";", "app", ".", "use", "(", "morgan", "(", "'tiny'", ")", ")", ";", "}", "if", "(", "'development'", "===", "env", "||", "'test'", "===", "env", ")", "{", "app", ".", "use", "(", "express", ".", "static", "(", "path", ".", "join", "(", "config", ".", "root", ",", "'.tmp'", ")", ")", ")", ";", "app", ".", "use", "(", "express", ".", "static", "(", "publicDir", ")", ")", ";", "app", ".", "set", "(", "'appPath'", ",", "publicDir", ")", ";", "app", ".", "use", "(", "morgan", "(", "'dev'", ")", ")", ";", "// Error handler - has to be last", "app", ".", "use", "(", "errorHandler", "(", ")", ")", ";", "}", "}" ]
Configure the express application by adding middleware and setting application variables. @param {express.app} app - The express application instance to configure
[ "Configure", "the", "express", "application", "by", "adding", "middleware", "and", "setting", "application", "variables", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/config/express.js#L29-L62
40,734
michaelkrone/generator-material-app
generators/app/templates/client/app/components/socket(socketio)/socket.service.js
syncUpdates
function syncUpdates(modelName, array, cb) { cb = cb || angular.noop; /** * Syncs item creation/updates on 'model:save' */ socket.on(modelName + ':save', function (item) { var index = _.findIndex(array, {_id: item._id}); var event = 'created'; // replace oldItem if it exists // otherwise just add item to the collection if (index !== -1) { array.splice(index, 1, item); event = 'updated'; } else { array.push(item); } cb(event, item, array); }); /** * Syncs removed items on 'model:remove' */ socket.on(modelName + ':remove', function (item) { var event = 'deleted'; _.remove(array, {_id: item._id}); cb(event, item, array); }); }
javascript
function syncUpdates(modelName, array, cb) { cb = cb || angular.noop; /** * Syncs item creation/updates on 'model:save' */ socket.on(modelName + ':save', function (item) { var index = _.findIndex(array, {_id: item._id}); var event = 'created'; // replace oldItem if it exists // otherwise just add item to the collection if (index !== -1) { array.splice(index, 1, item); event = 'updated'; } else { array.push(item); } cb(event, item, array); }); /** * Syncs removed items on 'model:remove' */ socket.on(modelName + ':remove', function (item) { var event = 'deleted'; _.remove(array, {_id: item._id}); cb(event, item, array); }); }
[ "function", "syncUpdates", "(", "modelName", ",", "array", ",", "cb", ")", "{", "cb", "=", "cb", "||", "angular", ".", "noop", ";", "/**\n * Syncs item creation/updates on 'model:save'\n */", "socket", ".", "on", "(", "modelName", "+", "':save'", ",", "function", "(", "item", ")", "{", "var", "index", "=", "_", ".", "findIndex", "(", "array", ",", "{", "_id", ":", "item", ".", "_id", "}", ")", ";", "var", "event", "=", "'created'", ";", "// replace oldItem if it exists", "// otherwise just add item to the collection", "if", "(", "index", "!==", "-", "1", ")", "{", "array", ".", "splice", "(", "index", ",", "1", ",", "item", ")", ";", "event", "=", "'updated'", ";", "}", "else", "{", "array", ".", "push", "(", "item", ")", ";", "}", "cb", "(", "event", ",", "item", ",", "array", ")", ";", "}", ")", ";", "/**\n * Syncs removed items on 'model:remove'\n */", "socket", ".", "on", "(", "modelName", "+", "':remove'", ",", "function", "(", "item", ")", "{", "var", "event", "=", "'deleted'", ";", "_", ".", "remove", "(", "array", ",", "{", "_id", ":", "item", ".", "_id", "}", ")", ";", "cb", "(", "event", ",", "item", ",", "array", ")", ";", "}", ")", ";", "}" ]
Register listeners to sync an array with updates on a model Takes the array we want to sync, the model name that socket updates are sent from, and an optional callback function after new items are updated. @param {String} modelName @param {Array} array @param {Function} cb
[ "Register", "listeners", "to", "sync", "an", "array", "with", "updates", "on", "a", "model" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/components/socket(socketio)/socket.service.js#L46-L76
40,735
michaelkrone/generator-material-app
generators/app/templates/server/api/user(auth)/user.socket(socketio).js
registerUserSockets
function registerUserSockets(socket) { User.schema.post('save', function (doc) { onSave(socket, doc); }); User.schema.post('remove', function (doc) { onRemove(socket, doc); }); }
javascript
function registerUserSockets(socket) { User.schema.post('save', function (doc) { onSave(socket, doc); }); User.schema.post('remove', function (doc) { onRemove(socket, doc); }); }
[ "function", "registerUserSockets", "(", "socket", ")", "{", "User", ".", "schema", ".", "post", "(", "'save'", ",", "function", "(", "doc", ")", "{", "onSave", "(", "socket", ",", "doc", ")", ";", "}", ")", ";", "User", ".", "schema", ".", "post", "(", "'remove'", ",", "function", "(", "doc", ")", "{", "onRemove", "(", "socket", ",", "doc", ")", ";", "}", ")", ";", "}" ]
Register User model change events on the passed socket @param {socket.io} socket - The socket object to register the User model events on
[ "Register", "User", "model", "change", "events", "on", "the", "passed", "socket" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/api/user(auth)/user.socket(socketio).js#L24-L32
40,736
michaelkrone/generator-material-app
generators/app/templates/client/app/admin(auth)/user/list/edit/edit.controller.js
update
function update(form) { // refuse to work with invalid data if (!vm.user._id || form && !form.$valid) { return; } UserService.update(vm.user) .then(updateUserSuccess) .catch(updateUserCatch); function updateUserSuccess(updatedUser) { // update the display name after successful save vm.displayName = updatedUser.name; Toast.show({text: 'User ' + updatedUser.name + ' updated'}); if (form) { form.$setPristine(); } } function updateUserCatch(err) { Toast.show({ type: 'warn', text: 'Error while updating user ' + vm.displayName, link: {state: $state.$current, params: $stateParams} }); if (form && err) { form.setResponseErrors(err.data); } } }
javascript
function update(form) { // refuse to work with invalid data if (!vm.user._id || form && !form.$valid) { return; } UserService.update(vm.user) .then(updateUserSuccess) .catch(updateUserCatch); function updateUserSuccess(updatedUser) { // update the display name after successful save vm.displayName = updatedUser.name; Toast.show({text: 'User ' + updatedUser.name + ' updated'}); if (form) { form.$setPristine(); } } function updateUserCatch(err) { Toast.show({ type: 'warn', text: 'Error while updating user ' + vm.displayName, link: {state: $state.$current, params: $stateParams} }); if (form && err) { form.setResponseErrors(err.data); } } }
[ "function", "update", "(", "form", ")", "{", "// refuse to work with invalid data", "if", "(", "!", "vm", ".", "user", ".", "_id", "||", "form", "&&", "!", "form", ".", "$valid", ")", "{", "return", ";", "}", "UserService", ".", "update", "(", "vm", ".", "user", ")", ".", "then", "(", "updateUserSuccess", ")", ".", "catch", "(", "updateUserCatch", ")", ";", "function", "updateUserSuccess", "(", "updatedUser", ")", "{", "// update the display name after successful save", "vm", ".", "displayName", "=", "updatedUser", ".", "name", ";", "Toast", ".", "show", "(", "{", "text", ":", "'User '", "+", "updatedUser", ".", "name", "+", "' updated'", "}", ")", ";", "if", "(", "form", ")", "{", "form", ".", "$setPristine", "(", ")", ";", "}", "}", "function", "updateUserCatch", "(", "err", ")", "{", "Toast", ".", "show", "(", "{", "type", ":", "'warn'", ",", "text", ":", "'Error while updating user '", "+", "vm", ".", "displayName", ",", "link", ":", "{", "state", ":", "$state", ".", "$current", ",", "params", ":", "$stateParams", "}", "}", ")", ";", "if", "(", "form", "&&", "err", ")", "{", "form", ".", "setResponseErrors", "(", "err", ".", "data", ")", ";", "}", "}", "}" ]
Updates a user by using the UserService save method @param {Form} [form]
[ "Updates", "a", "user", "by", "using", "the", "UserService", "save", "method" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/admin(auth)/user/list/edit/edit.controller.js#L72-L102
40,737
michaelkrone/generator-material-app
generators/app/templates/client/app/admin(auth)/user/list/edit/edit.controller.js
remove
function remove(form, ev) { var confirm = $mdDialog.confirm() .title('Delete user ' + vm.displayName + '?') .content('Do you really want to delete user ' + vm.displayName + '?') .ariaLabel('Delete user') .ok('Delete user') .cancel('Cancel') .targetEvent(ev); $mdDialog.show(confirm) .then(performRemove); /** * Removes a user by using the UserService remove method * @api private */ function performRemove() { UserService.remove(vm.user) .then(deleteUserSuccess) .catch(deleteUserCatch); function deleteUserSuccess() { Toast.show({type: 'success', text: 'User ' + vm.displayName + ' deleted'}); vm.showList(); } function deleteUserCatch(err) { Toast.show({ type: 'warn', text: 'Error while deleting user ' + vm.displayName, link: {state: $state.$current, params: $stateParams} }); if (form && err) { form.setResponseErrors(err, vm.errors); } } } }
javascript
function remove(form, ev) { var confirm = $mdDialog.confirm() .title('Delete user ' + vm.displayName + '?') .content('Do you really want to delete user ' + vm.displayName + '?') .ariaLabel('Delete user') .ok('Delete user') .cancel('Cancel') .targetEvent(ev); $mdDialog.show(confirm) .then(performRemove); /** * Removes a user by using the UserService remove method * @api private */ function performRemove() { UserService.remove(vm.user) .then(deleteUserSuccess) .catch(deleteUserCatch); function deleteUserSuccess() { Toast.show({type: 'success', text: 'User ' + vm.displayName + ' deleted'}); vm.showList(); } function deleteUserCatch(err) { Toast.show({ type: 'warn', text: 'Error while deleting user ' + vm.displayName, link: {state: $state.$current, params: $stateParams} }); if (form && err) { form.setResponseErrors(err, vm.errors); } } } }
[ "function", "remove", "(", "form", ",", "ev", ")", "{", "var", "confirm", "=", "$mdDialog", ".", "confirm", "(", ")", ".", "title", "(", "'Delete user '", "+", "vm", ".", "displayName", "+", "'?'", ")", ".", "content", "(", "'Do you really want to delete user '", "+", "vm", ".", "displayName", "+", "'?'", ")", ".", "ariaLabel", "(", "'Delete user'", ")", ".", "ok", "(", "'Delete user'", ")", ".", "cancel", "(", "'Cancel'", ")", ".", "targetEvent", "(", "ev", ")", ";", "$mdDialog", ".", "show", "(", "confirm", ")", ".", "then", "(", "performRemove", ")", ";", "/**\n * Removes a user by using the UserService remove method\n * @api private\n */", "function", "performRemove", "(", ")", "{", "UserService", ".", "remove", "(", "vm", ".", "user", ")", ".", "then", "(", "deleteUserSuccess", ")", ".", "catch", "(", "deleteUserCatch", ")", ";", "function", "deleteUserSuccess", "(", ")", "{", "Toast", ".", "show", "(", "{", "type", ":", "'success'", ",", "text", ":", "'User '", "+", "vm", ".", "displayName", "+", "' deleted'", "}", ")", ";", "vm", ".", "showList", "(", ")", ";", "}", "function", "deleteUserCatch", "(", "err", ")", "{", "Toast", ".", "show", "(", "{", "type", ":", "'warn'", ",", "text", ":", "'Error while deleting user '", "+", "vm", ".", "displayName", ",", "link", ":", "{", "state", ":", "$state", ".", "$current", ",", "params", ":", "$stateParams", "}", "}", ")", ";", "if", "(", "form", "&&", "err", ")", "{", "form", ".", "setResponseErrors", "(", "err", ",", "vm", ".", "errors", ")", ";", "}", "}", "}", "}" ]
Show a dialog to ask the user if she wants to delete the current selected user. @param {AngularForm} form - The form to pass to the remove handler @param {$event} ev - The event to pass to the dialog service
[ "Show", "a", "dialog", "to", "ask", "the", "user", "if", "she", "wants", "to", "delete", "the", "current", "selected", "user", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/admin(auth)/user/list/edit/edit.controller.js#L109-L147
40,738
michaelkrone/generator-material-app
generators/app/templates/client/app/admin(auth)/user/list/edit/edit.controller.js
performRemove
function performRemove() { UserService.remove(vm.user) .then(deleteUserSuccess) .catch(deleteUserCatch); function deleteUserSuccess() { Toast.show({type: 'success', text: 'User ' + vm.displayName + ' deleted'}); vm.showList(); } function deleteUserCatch(err) { Toast.show({ type: 'warn', text: 'Error while deleting user ' + vm.displayName, link: {state: $state.$current, params: $stateParams} }); if (form && err) { form.setResponseErrors(err, vm.errors); } } }
javascript
function performRemove() { UserService.remove(vm.user) .then(deleteUserSuccess) .catch(deleteUserCatch); function deleteUserSuccess() { Toast.show({type: 'success', text: 'User ' + vm.displayName + ' deleted'}); vm.showList(); } function deleteUserCatch(err) { Toast.show({ type: 'warn', text: 'Error while deleting user ' + vm.displayName, link: {state: $state.$current, params: $stateParams} }); if (form && err) { form.setResponseErrors(err, vm.errors); } } }
[ "function", "performRemove", "(", ")", "{", "UserService", ".", "remove", "(", "vm", ".", "user", ")", ".", "then", "(", "deleteUserSuccess", ")", ".", "catch", "(", "deleteUserCatch", ")", ";", "function", "deleteUserSuccess", "(", ")", "{", "Toast", ".", "show", "(", "{", "type", ":", "'success'", ",", "text", ":", "'User '", "+", "vm", ".", "displayName", "+", "' deleted'", "}", ")", ";", "vm", ".", "showList", "(", ")", ";", "}", "function", "deleteUserCatch", "(", "err", ")", "{", "Toast", ".", "show", "(", "{", "type", ":", "'warn'", ",", "text", ":", "'Error while deleting user '", "+", "vm", ".", "displayName", ",", "link", ":", "{", "state", ":", "$state", ".", "$current", ",", "params", ":", "$stateParams", "}", "}", ")", ";", "if", "(", "form", "&&", "err", ")", "{", "form", ".", "setResponseErrors", "(", "err", ",", "vm", ".", "errors", ")", ";", "}", "}", "}" ]
Removes a user by using the UserService remove method @api private
[ "Removes", "a", "user", "by", "using", "the", "UserService", "remove", "method" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/admin(auth)/user/list/edit/edit.controller.js#L125-L146
40,739
michaelkrone/generator-material-app
generators/app/templates/client/app/admin(auth)/user/list/edit/edit.controller.js
showChangePasswordDialog
function showChangePasswordDialog(event) { $mdDialog.show({ controller: 'EditPasswordController', controllerAs: 'password', templateUrl: 'app/admin/user/list/edit/edit-password/edit-password.html', targetEvent: event, locals: {user: vm.user}, bindToController: true, clickOutsideToClose: false }); }
javascript
function showChangePasswordDialog(event) { $mdDialog.show({ controller: 'EditPasswordController', controllerAs: 'password', templateUrl: 'app/admin/user/list/edit/edit-password/edit-password.html', targetEvent: event, locals: {user: vm.user}, bindToController: true, clickOutsideToClose: false }); }
[ "function", "showChangePasswordDialog", "(", "event", ")", "{", "$mdDialog", ".", "show", "(", "{", "controller", ":", "'EditPasswordController'", ",", "controllerAs", ":", "'password'", ",", "templateUrl", ":", "'app/admin/user/list/edit/edit-password/edit-password.html'", ",", "targetEvent", ":", "event", ",", "locals", ":", "{", "user", ":", "vm", ".", "user", "}", ",", "bindToController", ":", "true", ",", "clickOutsideToClose", ":", "false", "}", ")", ";", "}" ]
Show the dialog for changing the user password @param event
[ "Show", "the", "dialog", "for", "changing", "the", "user", "password" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/admin(auth)/user/list/edit/edit.controller.js#L153-L163
40,740
michaelkrone/generator-material-app
generators/app/templates/server/lib/responses/index.js
sendData
function sendData(data, options) { // jshint validthis: true var req = this.req; var res = this.res; // headers already sent, nothing to do here if (res.headersSent) { return; } // If appropriate, serve data as JSON if (req.xhr || req.accepts('application/json')) { return res.json(data); } // if a template string is given as the options param // use it to render a view var viewFilePath = (typeof options === 'string') ? options : options.view; // try to render the given template, fall back to json // if an error occurs while rendering the view file if (viewFilePath && req.accepts('html')) { res.render(viewFilePath, data, function (err, result) { if (err) { return res.json(data); } return res.send(result); }); } return res.json(data); }
javascript
function sendData(data, options) { // jshint validthis: true var req = this.req; var res = this.res; // headers already sent, nothing to do here if (res.headersSent) { return; } // If appropriate, serve data as JSON if (req.xhr || req.accepts('application/json')) { return res.json(data); } // if a template string is given as the options param // use it to render a view var viewFilePath = (typeof options === 'string') ? options : options.view; // try to render the given template, fall back to json // if an error occurs while rendering the view file if (viewFilePath && req.accepts('html')) { res.render(viewFilePath, data, function (err, result) { if (err) { return res.json(data); } return res.send(result); }); } return res.json(data); }
[ "function", "sendData", "(", "data", ",", "options", ")", "{", "// jshint validthis: true", "var", "req", "=", "this", ".", "req", ";", "var", "res", "=", "this", ".", "res", ";", "// headers already sent, nothing to do here", "if", "(", "res", ".", "headersSent", ")", "{", "return", ";", "}", "// If appropriate, serve data as JSON", "if", "(", "req", ".", "xhr", "||", "req", ".", "accepts", "(", "'application/json'", ")", ")", "{", "return", "res", ".", "json", "(", "data", ")", ";", "}", "// if a template string is given as the options param", "// use it to render a view", "var", "viewFilePath", "=", "(", "typeof", "options", "===", "'string'", ")", "?", "options", ":", "options", ".", "view", ";", "// try to render the given template, fall back to json", "// if an error occurs while rendering the view file", "if", "(", "viewFilePath", "&&", "req", ".", "accepts", "(", "'html'", ")", ")", "{", "res", ".", "render", "(", "viewFilePath", ",", "data", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "return", "res", ".", "json", "(", "data", ")", ";", "}", "return", "res", ".", "send", "(", "result", ")", ";", "}", ")", ";", "}", "return", "res", ".", "json", "(", "data", ")", ";", "}" ]
Default response output handler @param {mixed} data - The data that should be send to the client @param {Object|String} options - Response configuration object or view template name @return A Response with the given status set, a rendered view if a view template has been provided in the options paramter.
[ "Default", "response", "output", "handler" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/responses/index.js#L26-L57
40,741
michaelkrone/generator-material-app
generators/app/templates/client/app/components/toggle-component/toggle-component.directive.js
toggleOpen
function toggleOpen(isOpen) { if (scope.isOpen === isOpen) { return $q.when(true); } var deferred = $q.defer(); // Toggle value to force an async `updateIsOpen()` to run scope.isOpen = isOpen; $timeout(setElementFocus, 0, false); return deferred.promise; function setElementFocus() { // When the current `updateIsOpen()` animation finishes promise.then(function (result) { if (!scope.isOpen) { // reset focus to originating element (if available) upon close triggeringElement && triggeringElement.focus(); triggeringElement = null; } deferred.resolve(result); }); } }
javascript
function toggleOpen(isOpen) { if (scope.isOpen === isOpen) { return $q.when(true); } var deferred = $q.defer(); // Toggle value to force an async `updateIsOpen()` to run scope.isOpen = isOpen; $timeout(setElementFocus, 0, false); return deferred.promise; function setElementFocus() { // When the current `updateIsOpen()` animation finishes promise.then(function (result) { if (!scope.isOpen) { // reset focus to originating element (if available) upon close triggeringElement && triggeringElement.focus(); triggeringElement = null; } deferred.resolve(result); }); } }
[ "function", "toggleOpen", "(", "isOpen", ")", "{", "if", "(", "scope", ".", "isOpen", "===", "isOpen", ")", "{", "return", "$q", ".", "when", "(", "true", ")", ";", "}", "var", "deferred", "=", "$q", ".", "defer", "(", ")", ";", "// Toggle value to force an async `updateIsOpen()` to run", "scope", ".", "isOpen", "=", "isOpen", ";", "$timeout", "(", "setElementFocus", ",", "0", ",", "false", ")", ";", "return", "deferred", ".", "promise", ";", "function", "setElementFocus", "(", ")", "{", "// When the current `updateIsOpen()` animation finishes", "promise", ".", "then", "(", "function", "(", "result", ")", "{", "if", "(", "!", "scope", ".", "isOpen", ")", "{", "// reset focus to originating element (if available) upon close", "triggeringElement", "&&", "triggeringElement", ".", "focus", "(", ")", ";", "triggeringElement", "=", "null", ";", "}", "deferred", ".", "resolve", "(", "result", ")", ";", "}", ")", ";", "}", "}" ]
Toggle the toggleComponent view and publish a promise to be resolved when the view animation finishes. @param isOpen @returns {*}
[ "Toggle", "the", "toggleComponent", "view", "and", "publish", "a", "promise", "to", "be", "resolved", "when", "the", "view", "animation", "finishes", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/components/toggle-component/toggle-component.directive.js#L116-L139
40,742
michaelkrone/generator-material-app
generators/app/templates/client/app/clientModelDoc(demo)/clientModelDoc.service.js
ClientModelDocService
function ClientModelDocService(ClientModelDoc) { return { create: create, update: update, remove: remove }; /** * Save a new clientModelDoc * * @param {Object} clientModelDoc - clientModelDocData * @param {Function} callback - optional * @return {Promise} */ function create(clientModelDoc, callback) { var cb = callback || angular.noop; return ClientModelDoc.create(clientModelDoc, function (clientModelDoc) { return cb(clientModelDoc); }, function (err) { return cb(err); }).$promise; } /** * Remove a clientModelDoc * * @param {Object} clientModelDoc - clientModelDocData * @param {Function} callback - optional * @return {Promise} */ function remove(clientModelDoc, callback) { var cb = callback || angular.noop; return ClientModelDoc.remove({id: clientModelDoc._id}, function (clientModelDoc) { return cb(clientModelDoc); }, function (err) { return cb(err); }).$promise; } /** * Create a new clientModelDoc * * @param {Object} clientModelDoc - clientModelDocData * @param {Function} callback - optional * @return {Promise} */ function update(clientModelDoc, callback) { var cb = callback || angular.noop; return ClientModelDoc.update(clientModelDoc, function (clientModelDoc) { return cb(clientModelDoc); }, function (err) { return cb(err); }).$promise; } }
javascript
function ClientModelDocService(ClientModelDoc) { return { create: create, update: update, remove: remove }; /** * Save a new clientModelDoc * * @param {Object} clientModelDoc - clientModelDocData * @param {Function} callback - optional * @return {Promise} */ function create(clientModelDoc, callback) { var cb = callback || angular.noop; return ClientModelDoc.create(clientModelDoc, function (clientModelDoc) { return cb(clientModelDoc); }, function (err) { return cb(err); }).$promise; } /** * Remove a clientModelDoc * * @param {Object} clientModelDoc - clientModelDocData * @param {Function} callback - optional * @return {Promise} */ function remove(clientModelDoc, callback) { var cb = callback || angular.noop; return ClientModelDoc.remove({id: clientModelDoc._id}, function (clientModelDoc) { return cb(clientModelDoc); }, function (err) { return cb(err); }).$promise; } /** * Create a new clientModelDoc * * @param {Object} clientModelDoc - clientModelDocData * @param {Function} callback - optional * @return {Promise} */ function update(clientModelDoc, callback) { var cb = callback || angular.noop; return ClientModelDoc.update(clientModelDoc, function (clientModelDoc) { return cb(clientModelDoc); }, function (err) { return cb(err); }).$promise; } }
[ "function", "ClientModelDocService", "(", "ClientModelDoc", ")", "{", "return", "{", "create", ":", "create", ",", "update", ":", "update", ",", "remove", ":", "remove", "}", ";", "/**\n * Save a new clientModelDoc\n *\n * @param {Object} clientModelDoc - clientModelDocData\n * @param {Function} callback - optional\n * @return {Promise}\n */", "function", "create", "(", "clientModelDoc", ",", "callback", ")", "{", "var", "cb", "=", "callback", "||", "angular", ".", "noop", ";", "return", "ClientModelDoc", ".", "create", "(", "clientModelDoc", ",", "function", "(", "clientModelDoc", ")", "{", "return", "cb", "(", "clientModelDoc", ")", ";", "}", ",", "function", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", ")", ".", "$promise", ";", "}", "/**\n * Remove a clientModelDoc\n *\n * @param {Object} clientModelDoc - clientModelDocData\n * @param {Function} callback - optional\n * @return {Promise}\n */", "function", "remove", "(", "clientModelDoc", ",", "callback", ")", "{", "var", "cb", "=", "callback", "||", "angular", ".", "noop", ";", "return", "ClientModelDoc", ".", "remove", "(", "{", "id", ":", "clientModelDoc", ".", "_id", "}", ",", "function", "(", "clientModelDoc", ")", "{", "return", "cb", "(", "clientModelDoc", ")", ";", "}", ",", "function", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", ")", ".", "$promise", ";", "}", "/**\n * Create a new clientModelDoc\n *\n * @param {Object} clientModelDoc - clientModelDocData\n * @param {Function} callback - optional\n * @return {Promise}\n */", "function", "update", "(", "clientModelDoc", ",", "callback", ")", "{", "var", "cb", "=", "callback", "||", "angular", ".", "noop", ";", "return", "ClientModelDoc", ".", "update", "(", "clientModelDoc", ",", "function", "(", "clientModelDoc", ")", "{", "return", "cb", "(", "clientModelDoc", ")", ";", "}", ",", "function", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", ")", ".", "$promise", ";", "}", "}" ]
ClientModelDocService constructor AngularJS will instantiate a singleton by calling "new" on this function @param {$resource} ClientModelDoc The resource provided by <%= scriptAppName %>.clientModelDoc.resource @returns {Object} The service definition for the ClientModelDocService service
[ "ClientModelDocService", "constructor", "AngularJS", "will", "instantiate", "a", "singleton", "by", "calling", "new", "on", "this", "function" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/clientModelDoc(demo)/clientModelDoc.service.js#L40-L104
40,743
michaelkrone/generator-material-app
generators/app/templates/client/app/clientModelDoc(demo)/clientModelDoc.service.js
create
function create(clientModelDoc, callback) { var cb = callback || angular.noop; return ClientModelDoc.create(clientModelDoc, function (clientModelDoc) { return cb(clientModelDoc); }, function (err) { return cb(err); }).$promise; }
javascript
function create(clientModelDoc, callback) { var cb = callback || angular.noop; return ClientModelDoc.create(clientModelDoc, function (clientModelDoc) { return cb(clientModelDoc); }, function (err) { return cb(err); }).$promise; }
[ "function", "create", "(", "clientModelDoc", ",", "callback", ")", "{", "var", "cb", "=", "callback", "||", "angular", ".", "noop", ";", "return", "ClientModelDoc", ".", "create", "(", "clientModelDoc", ",", "function", "(", "clientModelDoc", ")", "{", "return", "cb", "(", "clientModelDoc", ")", ";", "}", ",", "function", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", ")", ".", "$promise", ";", "}" ]
Save a new clientModelDoc @param {Object} clientModelDoc - clientModelDocData @param {Function} callback - optional @return {Promise}
[ "Save", "a", "new", "clientModelDoc" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/clientModelDoc(demo)/clientModelDoc.service.js#L55-L65
40,744
michaelkrone/generator-material-app
generators/app/templates/client/app/clientModelDoc(demo)/clientModelDoc.service.js
remove
function remove(clientModelDoc, callback) { var cb = callback || angular.noop; return ClientModelDoc.remove({id: clientModelDoc._id}, function (clientModelDoc) { return cb(clientModelDoc); }, function (err) { return cb(err); }).$promise; }
javascript
function remove(clientModelDoc, callback) { var cb = callback || angular.noop; return ClientModelDoc.remove({id: clientModelDoc._id}, function (clientModelDoc) { return cb(clientModelDoc); }, function (err) { return cb(err); }).$promise; }
[ "function", "remove", "(", "clientModelDoc", ",", "callback", ")", "{", "var", "cb", "=", "callback", "||", "angular", ".", "noop", ";", "return", "ClientModelDoc", ".", "remove", "(", "{", "id", ":", "clientModelDoc", ".", "_id", "}", ",", "function", "(", "clientModelDoc", ")", "{", "return", "cb", "(", "clientModelDoc", ")", ";", "}", ",", "function", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", ")", ".", "$promise", ";", "}" ]
Remove a clientModelDoc @param {Object} clientModelDoc - clientModelDocData @param {Function} callback - optional @return {Promise}
[ "Remove", "a", "clientModelDoc" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/clientModelDoc(demo)/clientModelDoc.service.js#L74-L84
40,745
michaelkrone/generator-material-app
generators/app/templates/client/app/clientModelDoc(demo)/clientModelDoc.service.js
update
function update(clientModelDoc, callback) { var cb = callback || angular.noop; return ClientModelDoc.update(clientModelDoc, function (clientModelDoc) { return cb(clientModelDoc); }, function (err) { return cb(err); }).$promise; }
javascript
function update(clientModelDoc, callback) { var cb = callback || angular.noop; return ClientModelDoc.update(clientModelDoc, function (clientModelDoc) { return cb(clientModelDoc); }, function (err) { return cb(err); }).$promise; }
[ "function", "update", "(", "clientModelDoc", ",", "callback", ")", "{", "var", "cb", "=", "callback", "||", "angular", ".", "noop", ";", "return", "ClientModelDoc", ".", "update", "(", "clientModelDoc", ",", "function", "(", "clientModelDoc", ")", "{", "return", "cb", "(", "clientModelDoc", ")", ";", "}", ",", "function", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", ")", ".", "$promise", ";", "}" ]
Create a new clientModelDoc @param {Object} clientModelDoc - clientModelDocData @param {Function} callback - optional @return {Promise}
[ "Create", "a", "new", "clientModelDoc" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/client/app/clientModelDoc(demo)/clientModelDoc.service.js#L93-L103
40,746
michaelkrone/generator-material-app
generators/app/templates/server/app.js
startServer
function startServer() { var server = require('http').createServer(app); var socket = socketio(server, { serveClient: true, path: '/socket.io-client' }); // Setup SocketIO socketConfig(socket); return server; }
javascript
function startServer() { var server = require('http').createServer(app); var socket = socketio(server, { serveClient: true, path: '/socket.io-client' }); // Setup SocketIO socketConfig(socket); return server; }
[ "function", "startServer", "(", ")", "{", "var", "server", "=", "require", "(", "'http'", ")", ".", "createServer", "(", "app", ")", ";", "var", "socket", "=", "socketio", "(", "server", ",", "{", "serveClient", ":", "true", ",", "path", ":", "'/socket.io-client'", "}", ")", ";", "// Setup SocketIO", "socketConfig", "(", "socket", ")", ";", "return", "server", ";", "}" ]
Create an express http server and return it Config the socketio service to use this server @api private @return {}
[ "Create", "an", "express", "http", "server", "and", "return", "it", "Config", "the", "socketio", "service", "to", "use", "this", "server" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/app.js#L40-L49
40,747
isaacs/ssh-key-decrypt
index.js
passphraseToKey
function passphraseToKey(type, passphrase, salt) { debug('passphraseToKey', type, passphrase, salt); var nkey = keyBytes[type]; if (!nkey) { var allowed = Object.keys(keyBytes); throw new TypeError('Unsupported type. Allowed: ' + allowed); } var niv = salt.length; var saltLen = 8; if (salt.length !== saltLen) salt = salt.slice(0, saltLen); var mds = 16; var addmd = false; var md_buf; var key = new Buffer(nkey); var keyidx = 0; while (true) { debug('loop nkey=%d mds=%d', nkey, mds); var c = crypto.createHash('md5'); if (addmd) c.update(md_buf); else addmd = true; if (!Buffer.isBuffer(passphrase)) c.update(passphrase, 'ascii'); else c.update(passphrase); c.update(salt); md_buf = c.digest('buffer'); var i = 0; while (nkey && i < mds) { key[keyidx++] = md_buf[i]; nkey--; i++; } var steps = Math.min(niv, mds - i); niv -= steps; i += steps; if ((nkey == 0) && (niv == 0)) break; } return key }
javascript
function passphraseToKey(type, passphrase, salt) { debug('passphraseToKey', type, passphrase, salt); var nkey = keyBytes[type]; if (!nkey) { var allowed = Object.keys(keyBytes); throw new TypeError('Unsupported type. Allowed: ' + allowed); } var niv = salt.length; var saltLen = 8; if (salt.length !== saltLen) salt = salt.slice(0, saltLen); var mds = 16; var addmd = false; var md_buf; var key = new Buffer(nkey); var keyidx = 0; while (true) { debug('loop nkey=%d mds=%d', nkey, mds); var c = crypto.createHash('md5'); if (addmd) c.update(md_buf); else addmd = true; if (!Buffer.isBuffer(passphrase)) c.update(passphrase, 'ascii'); else c.update(passphrase); c.update(salt); md_buf = c.digest('buffer'); var i = 0; while (nkey && i < mds) { key[keyidx++] = md_buf[i]; nkey--; i++; } var steps = Math.min(niv, mds - i); niv -= steps; i += steps; if ((nkey == 0) && (niv == 0)) break; } return key }
[ "function", "passphraseToKey", "(", "type", ",", "passphrase", ",", "salt", ")", "{", "debug", "(", "'passphraseToKey'", ",", "type", ",", "passphrase", ",", "salt", ")", ";", "var", "nkey", "=", "keyBytes", "[", "type", "]", ";", "if", "(", "!", "nkey", ")", "{", "var", "allowed", "=", "Object", ".", "keys", "(", "keyBytes", ")", ";", "throw", "new", "TypeError", "(", "'Unsupported type. Allowed: '", "+", "allowed", ")", ";", "}", "var", "niv", "=", "salt", ".", "length", ";", "var", "saltLen", "=", "8", ";", "if", "(", "salt", ".", "length", "!==", "saltLen", ")", "salt", "=", "salt", ".", "slice", "(", "0", ",", "saltLen", ")", ";", "var", "mds", "=", "16", ";", "var", "addmd", "=", "false", ";", "var", "md_buf", ";", "var", "key", "=", "new", "Buffer", "(", "nkey", ")", ";", "var", "keyidx", "=", "0", ";", "while", "(", "true", ")", "{", "debug", "(", "'loop nkey=%d mds=%d'", ",", "nkey", ",", "mds", ")", ";", "var", "c", "=", "crypto", ".", "createHash", "(", "'md5'", ")", ";", "if", "(", "addmd", ")", "c", ".", "update", "(", "md_buf", ")", ";", "else", "addmd", "=", "true", ";", "if", "(", "!", "Buffer", ".", "isBuffer", "(", "passphrase", ")", ")", "c", ".", "update", "(", "passphrase", ",", "'ascii'", ")", ";", "else", "c", ".", "update", "(", "passphrase", ")", ";", "c", ".", "update", "(", "salt", ")", ";", "md_buf", "=", "c", ".", "digest", "(", "'buffer'", ")", ";", "var", "i", "=", "0", ";", "while", "(", "nkey", "&&", "i", "<", "mds", ")", "{", "key", "[", "keyidx", "++", "]", "=", "md_buf", "[", "i", "]", ";", "nkey", "--", ";", "i", "++", ";", "}", "var", "steps", "=", "Math", ".", "min", "(", "niv", ",", "mds", "-", "i", ")", ";", "niv", "-=", "steps", ";", "i", "+=", "steps", ";", "if", "(", "(", "nkey", "==", "0", ")", "&&", "(", "niv", "==", "0", ")", ")", "break", ";", "}", "return", "key", "}" ]
port of EVP_BytesToKey, as used when decrypting PEM keys
[ "port", "of", "EVP_BytesToKey", "as", "used", "when", "decrypting", "PEM", "keys" ]
36c53300549d44367979f657010948a2a3d369e0
https://github.com/isaacs/ssh-key-decrypt/blob/36c53300549d44367979f657010948a2a3d369e0/index.js#L100-L155
40,748
marcodave/protractor-http-client
server/auth-server.js
verifyToken
function verifyToken(token) { var decodedToken = jwt.decode(token) return userdb.users.filter(user => user.name == decodedToken).length > 0; }
javascript
function verifyToken(token) { var decodedToken = jwt.decode(token) return userdb.users.filter(user => user.name == decodedToken).length > 0; }
[ "function", "verifyToken", "(", "token", ")", "{", "var", "decodedToken", "=", "jwt", ".", "decode", "(", "token", ")", "return", "userdb", ".", "users", ".", "filter", "(", "user", "=>", "user", ".", "name", "==", "decodedToken", ")", ".", "length", ">", "0", ";", "}" ]
Verify the token
[ "Verify", "the", "token" ]
232d93ae5308bd858a0546b579e15e0c947dc3e9
https://github.com/marcodave/protractor-http-client/blob/232d93ae5308bd858a0546b579e15e0c947dc3e9/server/auth-server.js#L22-L25
40,749
Crunch/postcss-less
index.js
convertImports
function convertImports(imports) { for (var file in imports) { if (imports.hasOwnProperty(file)) { postCssInputs[file] = new Input(imports[file], file !== "input" ? { from: file } : undefined); } } }
javascript
function convertImports(imports) { for (var file in imports) { if (imports.hasOwnProperty(file)) { postCssInputs[file] = new Input(imports[file], file !== "input" ? { from: file } : undefined); } } }
[ "function", "convertImports", "(", "imports", ")", "{", "for", "(", "var", "file", "in", "imports", ")", "{", "if", "(", "imports", ".", "hasOwnProperty", "(", "file", ")", ")", "{", "postCssInputs", "[", "file", "]", "=", "new", "Input", "(", "imports", "[", "file", "]", ",", "file", "!==", "\"input\"", "?", "{", "from", ":", "file", "}", ":", "undefined", ")", ";", "}", "}", "}" ]
Less's importManager is like PostCSS's Input class. We need to convert our inputs to reference them later.
[ "Less", "s", "importManager", "is", "like", "PostCSS", "s", "Input", "class", ".", "We", "need", "to", "convert", "our", "inputs", "to", "reference", "them", "later", "." ]
69b2b81d10418c78977518330a752a17471a00c8
https://github.com/Crunch/postcss-less/blob/69b2b81d10418c78977518330a752a17471a00c8/index.js#L47-L53
40,750
Crunch/postcss-less
index.js
function(directive) { var filename = directive.path ? directive.path.currentFileInfo.filename : directive.currentFileInfo.filename; var val, node, nodeTmp = buildNodeObject(filename, directive.index); if(!directive.path) { if(directive.features) { val = getObject(directive.features, true).stringValue; } else { val = getObject(directive.value, true).stringValue; } } else { val = directive.path.quote + directive.path.value + directive.path.quote; } node = { type: "" }; if(directive.type === 'Media') { node.name = 'media'; } else if(directive.type === 'Import') { node.name = 'import'; } else { // Remove "@" for PostCSS node.name = directive.name.replace('@',''); } node.source = nodeTmp.source; node.params = val; var atrule = postcss.atRule(node); if(directive.rules) { atrule.nodes = []; processRules(atrule, directive.rules); } return atrule; }
javascript
function(directive) { var filename = directive.path ? directive.path.currentFileInfo.filename : directive.currentFileInfo.filename; var val, node, nodeTmp = buildNodeObject(filename, directive.index); if(!directive.path) { if(directive.features) { val = getObject(directive.features, true).stringValue; } else { val = getObject(directive.value, true).stringValue; } } else { val = directive.path.quote + directive.path.value + directive.path.quote; } node = { type: "" }; if(directive.type === 'Media') { node.name = 'media'; } else if(directive.type === 'Import') { node.name = 'import'; } else { // Remove "@" for PostCSS node.name = directive.name.replace('@',''); } node.source = nodeTmp.source; node.params = val; var atrule = postcss.atRule(node); if(directive.rules) { atrule.nodes = []; processRules(atrule, directive.rules); } return atrule; }
[ "function", "(", "directive", ")", "{", "var", "filename", "=", "directive", ".", "path", "?", "directive", ".", "path", ".", "currentFileInfo", ".", "filename", ":", "directive", ".", "currentFileInfo", ".", "filename", ";", "var", "val", ",", "node", ",", "nodeTmp", "=", "buildNodeObject", "(", "filename", ",", "directive", ".", "index", ")", ";", "if", "(", "!", "directive", ".", "path", ")", "{", "if", "(", "directive", ".", "features", ")", "{", "val", "=", "getObject", "(", "directive", ".", "features", ",", "true", ")", ".", "stringValue", ";", "}", "else", "{", "val", "=", "getObject", "(", "directive", ".", "value", ",", "true", ")", ".", "stringValue", ";", "}", "}", "else", "{", "val", "=", "directive", ".", "path", ".", "quote", "+", "directive", ".", "path", ".", "value", "+", "directive", ".", "path", ".", "quote", ";", "}", "node", "=", "{", "type", ":", "\"\"", "}", ";", "if", "(", "directive", ".", "type", "===", "'Media'", ")", "{", "node", ".", "name", "=", "'media'", ";", "}", "else", "if", "(", "directive", ".", "type", "===", "'Import'", ")", "{", "node", ".", "name", "=", "'import'", ";", "}", "else", "{", "// Remove \"@\" for PostCSS", "node", ".", "name", "=", "directive", ".", "name", ".", "replace", "(", "'@'", ",", "''", ")", ";", "}", "node", ".", "source", "=", "nodeTmp", ".", "source", ";", "node", ".", "params", "=", "val", ";", "var", "atrule", "=", "postcss", ".", "atRule", "(", "node", ")", ";", "if", "(", "directive", ".", "rules", ")", "{", "atrule", ".", "nodes", "=", "[", "]", ";", "processRules", "(", "atrule", ",", "directive", ".", "rules", ")", ";", "}", "return", "atrule", ";", "}" ]
PostCSS "at-rule"
[ "PostCSS", "at", "-", "rule" ]
69b2b81d10418c78977518330a752a17471a00c8
https://github.com/Crunch/postcss-less/blob/69b2b81d10418c78977518330a752a17471a00c8/index.js#L96-L140
40,751
arqex/react-json
src/validation.js
function( methodStr ){ var parts = methodStr.split('['), definition = { name: parts[0], args: [] }, args ; if( parts.length > 1 ){ args = parts[1]; if( args[ args.length - 1 ] == ']' ) args = args.slice(0, args.length - 1); definition.args = args.split(/\s*,\s*/); } return definition; }
javascript
function( methodStr ){ var parts = methodStr.split('['), definition = { name: parts[0], args: [] }, args ; if( parts.length > 1 ){ args = parts[1]; if( args[ args.length - 1 ] == ']' ) args = args.slice(0, args.length - 1); definition.args = args.split(/\s*,\s*/); } return definition; }
[ "function", "(", "methodStr", ")", "{", "var", "parts", "=", "methodStr", ".", "split", "(", "'['", ")", ",", "definition", "=", "{", "name", ":", "parts", "[", "0", "]", ",", "args", ":", "[", "]", "}", ",", "args", ";", "if", "(", "parts", ".", "length", ">", "1", ")", "{", "args", "=", "parts", "[", "1", "]", ";", "if", "(", "args", "[", "args", ".", "length", "-", "1", "]", "==", "']'", ")", "args", "=", "args", ".", "slice", "(", "0", ",", "args", ".", "length", "-", "1", ")", ";", "definition", ".", "args", "=", "args", ".", "split", "(", "/", "\\s*,\\s*", "/", ")", ";", "}", "return", "definition", ";", "}" ]
Parse a method call in the data-validation attribute. @param {String} methodStr A method call like method[arg1, arg2, ...] @return {Object} An object like {name: 'method', args: [arg1, arg2, ...]}
[ "Parse", "a", "method", "call", "in", "the", "data", "-", "validation", "attribute", "." ]
81bbeefacf9ceadbd9a7e92b9481f43608d266cd
https://github.com/arqex/react-json/blob/81bbeefacf9ceadbd9a7e92b9481f43608d266cd/src/validation.js#L126-L145
40,752
arqex/react-json
src/validation.js
function( field ){ var tagName = field.tagName.toLowerCase(); if( tagName == 'input' && field.type == 'checkbox' ){ return field.checked; } if( tagName == 'select' ){ return field.options[field.selectedIndex].value; } return field.value; }
javascript
function( field ){ var tagName = field.tagName.toLowerCase(); if( tagName == 'input' && field.type == 'checkbox' ){ return field.checked; } if( tagName == 'select' ){ return field.options[field.selectedIndex].value; } return field.value; }
[ "function", "(", "field", ")", "{", "var", "tagName", "=", "field", ".", "tagName", ".", "toLowerCase", "(", ")", ";", "if", "(", "tagName", "==", "'input'", "&&", "field", ".", "type", "==", "'checkbox'", ")", "{", "return", "field", ".", "checked", ";", "}", "if", "(", "tagName", "==", "'select'", ")", "{", "return", "field", ".", "options", "[", "field", ".", "selectedIndex", "]", ".", "value", ";", "}", "return", "field", ".", "value", ";", "}" ]
Get the value of a field node, hiding the differences among different type of inputs. @param {DOMElement} field The field. @return {String} The current value of the given field.
[ "Get", "the", "value", "of", "a", "field", "node", "hiding", "the", "differences", "among", "different", "type", "of", "inputs", "." ]
81bbeefacf9ceadbd9a7e92b9481f43608d266cd
https://github.com/arqex/react-json/blob/81bbeefacf9ceadbd9a7e92b9481f43608d266cd/src/validation.js#L154-L166
40,753
arqex/react-json
mixins/CompoundFieldMixin.js
function( key ){ var fields = this.state.fields; if( fields[ key ] && fields[ key ].settings.focus === true ){ fields = assign({}, fields); fields[key].settings.focus = false; this.setState( {fields: fields} ); } }
javascript
function( key ){ var fields = this.state.fields; if( fields[ key ] && fields[ key ].settings.focus === true ){ fields = assign({}, fields); fields[key].settings.focus = false; this.setState( {fields: fields} ); } }
[ "function", "(", "key", ")", "{", "var", "fields", "=", "this", ".", "state", ".", "fields", ";", "if", "(", "fields", "[", "key", "]", "&&", "fields", "[", "key", "]", ".", "settings", ".", "focus", "===", "true", ")", "{", "fields", "=", "assign", "(", "{", "}", ",", "fields", ")", ";", "fields", "[", "key", "]", ".", "settings", ".", "focus", "=", "false", ";", "this", ".", "setState", "(", "{", "fields", ":", "fields", "}", ")", ";", "}", "}" ]
Checks if the current key editing setting is true and set it to false. The editing setting is set to true when a new child is added to edit it automatically after is edited it loses the point. @param {String} key The child key
[ "Checks", "if", "the", "current", "key", "editing", "setting", "is", "true", "and", "set", "it", "to", "false", ".", "The", "editing", "setting", "is", "set", "to", "true", "when", "a", "new", "child", "is", "added", "to", "edit", "it", "automatically", "after", "is", "edited", "it", "loses", "the", "point", "." ]
81bbeefacf9ceadbd9a7e92b9481f43608d266cd
https://github.com/arqex/react-json/blob/81bbeefacf9ceadbd9a7e92b9481f43608d266cd/mixins/CompoundFieldMixin.js#L91-L98
40,754
OpenKieler/klayjs-d3
dist/klayjs-d3-ww.js
function(kgraph) { if (kgraph) { zoomToFit(kgraph); // assign coordinates to nodes kgraph.children.forEach(function(n) { var d3node = nodes[parseInt(n.id)]; copyProps(n, d3node); (n.ports || []).forEach(function(p, i) { copyProps(p, d3node.ports[i]); }); (n.labels || []).forEach(function(l, i) { copyProps(l, d3node.labels[i]); }); }); // edges kgraph.edges.forEach(function(e) { var l = links[parseInt(e.id) - nodes.length]; copyProps(e, l); copyProps(e.source, l.source); copyProps(e.target, l.target); // make sure the bendpoint array is valid l.bendPoints = e.bendPoints || []; }); } function copyProps(src, tgt, copyKeys) { var keys = kgraphKeys; if (copyKeys) { keys = copyKeys.reduce(function (p, c) {p[c] = 1; return p;}, {}); } for (var k in src) { if (keys[k]) { tgt[k] = src[k]; } } } // invoke the 'finish' event dispatch.finish({graph: kgraph}); }
javascript
function(kgraph) { if (kgraph) { zoomToFit(kgraph); // assign coordinates to nodes kgraph.children.forEach(function(n) { var d3node = nodes[parseInt(n.id)]; copyProps(n, d3node); (n.ports || []).forEach(function(p, i) { copyProps(p, d3node.ports[i]); }); (n.labels || []).forEach(function(l, i) { copyProps(l, d3node.labels[i]); }); }); // edges kgraph.edges.forEach(function(e) { var l = links[parseInt(e.id) - nodes.length]; copyProps(e, l); copyProps(e.source, l.source); copyProps(e.target, l.target); // make sure the bendpoint array is valid l.bendPoints = e.bendPoints || []; }); } function copyProps(src, tgt, copyKeys) { var keys = kgraphKeys; if (copyKeys) { keys = copyKeys.reduce(function (p, c) {p[c] = 1; return p;}, {}); } for (var k in src) { if (keys[k]) { tgt[k] = src[k]; } } } // invoke the 'finish' event dispatch.finish({graph: kgraph}); }
[ "function", "(", "kgraph", ")", "{", "if", "(", "kgraph", ")", "{", "zoomToFit", "(", "kgraph", ")", ";", "// assign coordinates to nodes", "kgraph", ".", "children", ".", "forEach", "(", "function", "(", "n", ")", "{", "var", "d3node", "=", "nodes", "[", "parseInt", "(", "n", ".", "id", ")", "]", ";", "copyProps", "(", "n", ",", "d3node", ")", ";", "(", "n", ".", "ports", "||", "[", "]", ")", ".", "forEach", "(", "function", "(", "p", ",", "i", ")", "{", "copyProps", "(", "p", ",", "d3node", ".", "ports", "[", "i", "]", ")", ";", "}", ")", ";", "(", "n", ".", "labels", "||", "[", "]", ")", ".", "forEach", "(", "function", "(", "l", ",", "i", ")", "{", "copyProps", "(", "l", ",", "d3node", ".", "labels", "[", "i", "]", ")", ";", "}", ")", ";", "}", ")", ";", "// edges", "kgraph", ".", "edges", ".", "forEach", "(", "function", "(", "e", ")", "{", "var", "l", "=", "links", "[", "parseInt", "(", "e", ".", "id", ")", "-", "nodes", ".", "length", "]", ";", "copyProps", "(", "e", ",", "l", ")", ";", "copyProps", "(", "e", ".", "source", ",", "l", ".", "source", ")", ";", "copyProps", "(", "e", ".", "target", ",", "l", ".", "target", ")", ";", "// make sure the bendpoint array is valid", "l", ".", "bendPoints", "=", "e", ".", "bendPoints", "||", "[", "]", ";", "}", ")", ";", "}", "function", "copyProps", "(", "src", ",", "tgt", ",", "copyKeys", ")", "{", "var", "keys", "=", "kgraphKeys", ";", "if", "(", "copyKeys", ")", "{", "keys", "=", "copyKeys", ".", "reduce", "(", "function", "(", "p", ",", "c", ")", "{", "p", "[", "c", "]", "=", "1", ";", "return", "p", ";", "}", ",", "{", "}", ")", ";", "}", "for", "(", "var", "k", "in", "src", ")", "{", "if", "(", "keys", "[", "k", "]", ")", "{", "tgt", "[", "k", "]", "=", "src", "[", "k", "]", ";", "}", "}", "}", "// invoke the 'finish' event", "dispatch", ".", "finish", "(", "{", "graph", ":", "kgraph", "}", ")", ";", "}" ]
Apply layout for d3 style. Copies properties of the layouted graph back to the original nodes and links.
[ "Apply", "layout", "for", "d3", "style", ".", "Copies", "properties", "of", "the", "layouted", "graph", "back", "to", "the", "original", "nodes", "and", "links", "." ]
23430feeb38be85e1c25a42f6c0e135f8455c4eb
https://github.com/OpenKieler/klayjs-d3/blob/23430feeb38be85e1c25a42f6c0e135f8455c4eb/dist/klayjs-d3-ww.js#L196-L233
40,755
OpenKieler/klayjs-d3
dist/klayjs-d3-ww.js
function(kgraph) { zoomToFit(kgraph); var nodeMap = {}; // convert to absolute positions toAbsolutePositions(kgraph, {x: 0, y:0}, nodeMap); toAbsolutePositionsEdges(kgraph, nodeMap); // invoke the 'finish' event dispatch.finish({graph: kgraph}); }
javascript
function(kgraph) { zoomToFit(kgraph); var nodeMap = {}; // convert to absolute positions toAbsolutePositions(kgraph, {x: 0, y:0}, nodeMap); toAbsolutePositionsEdges(kgraph, nodeMap); // invoke the 'finish' event dispatch.finish({graph: kgraph}); }
[ "function", "(", "kgraph", ")", "{", "zoomToFit", "(", "kgraph", ")", ";", "var", "nodeMap", "=", "{", "}", ";", "// convert to absolute positions", "toAbsolutePositions", "(", "kgraph", ",", "{", "x", ":", "0", ",", "y", ":", "0", "}", ",", "nodeMap", ")", ";", "toAbsolutePositionsEdges", "(", "kgraph", ",", "nodeMap", ")", ";", "// invoke the 'finish' event", "dispatch", ".", "finish", "(", "{", "graph", ":", "kgraph", "}", ")", ";", "}" ]
Apply layout for the kgraph style. Converts relative positions to absolute positions.
[ "Apply", "layout", "for", "the", "kgraph", "style", ".", "Converts", "relative", "positions", "to", "absolute", "positions", "." ]
23430feeb38be85e1c25a42f6c0e135f8455c4eb
https://github.com/OpenKieler/klayjs-d3/blob/23430feeb38be85e1c25a42f6c0e135f8455c4eb/dist/klayjs-d3-ww.js#L278-L286
40,756
OpenKieler/klayjs-d3
dist/klayjs-d3-ww.js
zoomToFit
function zoomToFit(kgraph) { // scale everything so that it fits the specified size var scale = width / kgraph.width || 1; var sh = height / kgraph.height || 1; if (sh < scale) { scale = sh; } // if a transformation group was specified we // perform a 'zoomToFit' if (transformGroup) { transformGroup.attr("transform", "scale(" + scale + ")"); } }
javascript
function zoomToFit(kgraph) { // scale everything so that it fits the specified size var scale = width / kgraph.width || 1; var sh = height / kgraph.height || 1; if (sh < scale) { scale = sh; } // if a transformation group was specified we // perform a 'zoomToFit' if (transformGroup) { transformGroup.attr("transform", "scale(" + scale + ")"); } }
[ "function", "zoomToFit", "(", "kgraph", ")", "{", "// scale everything so that it fits the specified size", "var", "scale", "=", "width", "/", "kgraph", ".", "width", "||", "1", ";", "var", "sh", "=", "height", "/", "kgraph", ".", "height", "||", "1", ";", "if", "(", "sh", "<", "scale", ")", "{", "scale", "=", "sh", ";", "}", "// if a transformation group was specified we", "// perform a 'zoomToFit'", "if", "(", "transformGroup", ")", "{", "transformGroup", ".", "attr", "(", "\"transform\"", ",", "\"scale(\"", "+", "scale", "+", "\")\"", ")", ";", "}", "}" ]
If a top level transform group is specified, we set the scale such that the available space is used to its maximum.
[ "If", "a", "top", "level", "transform", "group", "is", "specified", "we", "set", "the", "scale", "such", "that", "the", "available", "space", "is", "used", "to", "its", "maximum", "." ]
23430feeb38be85e1c25a42f6c0e135f8455c4eb
https://github.com/OpenKieler/klayjs-d3/blob/23430feeb38be85e1c25a42f6c0e135f8455c4eb/dist/klayjs-d3-ww.js#L358-L370
40,757
ljharb/String.prototype.matchAll
helpers/RegExpStringIterator.js
RegExpStringIterator
function RegExpStringIterator(R, S, global, fullUnicode) { if (ES.Type(S) !== 'String') { throw new TypeError('S must be a string'); } if (ES.Type(global) !== 'Boolean') { throw new TypeError('global must be a boolean'); } if (ES.Type(fullUnicode) !== 'Boolean') { throw new TypeError('fullUnicode must be a boolean'); } hidden.set(this, '[[IteratingRegExp]]', R); hidden.set(this, '[[IteratedString]]', S); hidden.set(this, '[[Global]]', global); hidden.set(this, '[[Unicode]]', fullUnicode); hidden.set(this, '[[Done]]', false); }
javascript
function RegExpStringIterator(R, S, global, fullUnicode) { if (ES.Type(S) !== 'String') { throw new TypeError('S must be a string'); } if (ES.Type(global) !== 'Boolean') { throw new TypeError('global must be a boolean'); } if (ES.Type(fullUnicode) !== 'Boolean') { throw new TypeError('fullUnicode must be a boolean'); } hidden.set(this, '[[IteratingRegExp]]', R); hidden.set(this, '[[IteratedString]]', S); hidden.set(this, '[[Global]]', global); hidden.set(this, '[[Unicode]]', fullUnicode); hidden.set(this, '[[Done]]', false); }
[ "function", "RegExpStringIterator", "(", "R", ",", "S", ",", "global", ",", "fullUnicode", ")", "{", "if", "(", "ES", ".", "Type", "(", "S", ")", "!==", "'String'", ")", "{", "throw", "new", "TypeError", "(", "'S must be a string'", ")", ";", "}", "if", "(", "ES", ".", "Type", "(", "global", ")", "!==", "'Boolean'", ")", "{", "throw", "new", "TypeError", "(", "'global must be a boolean'", ")", ";", "}", "if", "(", "ES", ".", "Type", "(", "fullUnicode", ")", "!==", "'Boolean'", ")", "{", "throw", "new", "TypeError", "(", "'fullUnicode must be a boolean'", ")", ";", "}", "hidden", ".", "set", "(", "this", ",", "'[[IteratingRegExp]]'", ",", "R", ")", ";", "hidden", ".", "set", "(", "this", ",", "'[[IteratedString]]'", ",", "S", ")", ";", "hidden", ".", "set", "(", "this", ",", "'[[Global]]'", ",", "global", ")", ";", "hidden", ".", "set", "(", "this", ",", "'[[Unicode]]'", ",", "fullUnicode", ")", ";", "hidden", ".", "set", "(", "this", ",", "'[[Done]]'", ",", "false", ")", ";", "}" ]
eslint-disable-line no-shadow-restricted-names
[ "eslint", "-", "disable", "-", "line", "no", "-", "shadow", "-", "restricted", "-", "names" ]
c645e62702342ce4839c899cd31357ea79d8d926
https://github.com/ljharb/String.prototype.matchAll/blob/c645e62702342ce4839c899cd31357ea79d8d926/helpers/RegExpStringIterator.js#L11-L26
40,758
wc-catalogue/blaze-elements
webpack.config.js
buildChunksSort
function buildChunksSort( order ) { return (a, b) => order.indexOf(a.names[0]) - order.indexOf(b.names[0]); }
javascript
function buildChunksSort( order ) { return (a, b) => order.indexOf(a.names[0]) - order.indexOf(b.names[0]); }
[ "function", "buildChunksSort", "(", "order", ")", "{", "return", "(", "a", ",", "b", ")", "=>", "order", ".", "indexOf", "(", "a", ".", "names", "[", "0", "]", ")", "-", "order", ".", "indexOf", "(", "b", ".", "names", "[", "0", "]", ")", ";", "}" ]
Build sort function for chunksSortMode from array
[ "Build", "sort", "function", "for", "chunksSortMode", "from", "array" ]
0b31ae793454bdaf51b9d1de0ade932a292df0ae
https://github.com/wc-catalogue/blaze-elements/blob/0b31ae793454bdaf51b9d1de0ade932a292df0ae/webpack.config.js#L249-L253
40,759
gwtw/js-avl-tree
src/avl-tree.js
minValueNode
function minValueNode(root) { var current = root; while (current.left) { current = current.left; } return current; }
javascript
function minValueNode(root) { var current = root; while (current.left) { current = current.left; } return current; }
[ "function", "minValueNode", "(", "root", ")", "{", "var", "current", "=", "root", ";", "while", "(", "current", ".", "left", ")", "{", "current", "=", "current", ".", "left", ";", "}", "return", "current", ";", "}" ]
Gets the minimum value node, rooted in a particular node. @private @param {Node} root The node to search. @return {Node} The node with the minimum key in the tree.
[ "Gets", "the", "minimum", "value", "node", "rooted", "in", "a", "particular", "node", "." ]
ff8b54693e86e5ea3c2f6df7f69599d4e64f93fe
https://github.com/gwtw/js-avl-tree/blob/ff8b54693e86e5ea3c2f6df7f69599d4e64f93fe/src/avl-tree.js#L262-L268
40,760
gwtw/js-avl-tree
src/avl-tree.js
maxValueNode
function maxValueNode(root) { var current = root; while (current.right) { current = current.right; } return current; }
javascript
function maxValueNode(root) { var current = root; while (current.right) { current = current.right; } return current; }
[ "function", "maxValueNode", "(", "root", ")", "{", "var", "current", "=", "root", ";", "while", "(", "current", ".", "right", ")", "{", "current", "=", "current", ".", "right", ";", "}", "return", "current", ";", "}" ]
Gets the maximum value node, rooted in a particular node. @private @param {Node} root The node to search. @return {Node} The node with the maximum key in the tree.
[ "Gets", "the", "maximum", "value", "node", "rooted", "in", "a", "particular", "node", "." ]
ff8b54693e86e5ea3c2f6df7f69599d4e64f93fe
https://github.com/gwtw/js-avl-tree/blob/ff8b54693e86e5ea3c2f6df7f69599d4e64f93fe/src/avl-tree.js#L284-L290
40,761
gwtw/js-avl-tree
src/avl-tree.js
getBalanceState
function getBalanceState(node) { var heightDifference = node.leftHeight() - node.rightHeight(); switch (heightDifference) { case -2: return BalanceState.UNBALANCED_RIGHT; case -1: return BalanceState.SLIGHTLY_UNBALANCED_RIGHT; case 1: return BalanceState.SLIGHTLY_UNBALANCED_LEFT; case 2: return BalanceState.UNBALANCED_LEFT; default: return BalanceState.BALANCED; } }
javascript
function getBalanceState(node) { var heightDifference = node.leftHeight() - node.rightHeight(); switch (heightDifference) { case -2: return BalanceState.UNBALANCED_RIGHT; case -1: return BalanceState.SLIGHTLY_UNBALANCED_RIGHT; case 1: return BalanceState.SLIGHTLY_UNBALANCED_LEFT; case 2: return BalanceState.UNBALANCED_LEFT; default: return BalanceState.BALANCED; } }
[ "function", "getBalanceState", "(", "node", ")", "{", "var", "heightDifference", "=", "node", ".", "leftHeight", "(", ")", "-", "node", ".", "rightHeight", "(", ")", ";", "switch", "(", "heightDifference", ")", "{", "case", "-", "2", ":", "return", "BalanceState", ".", "UNBALANCED_RIGHT", ";", "case", "-", "1", ":", "return", "BalanceState", ".", "SLIGHTLY_UNBALANCED_RIGHT", ";", "case", "1", ":", "return", "BalanceState", ".", "SLIGHTLY_UNBALANCED_LEFT", ";", "case", "2", ":", "return", "BalanceState", ".", "UNBALANCED_LEFT", ";", "default", ":", "return", "BalanceState", ".", "BALANCED", ";", "}", "}" ]
Gets the balance state of a node, indicating whether the left or right sub-trees are unbalanced. @private @param {Node} node The node to get the difference from. @return {BalanceState} The BalanceState of the node.
[ "Gets", "the", "balance", "state", "of", "a", "node", "indicating", "whether", "the", "left", "or", "right", "sub", "-", "trees", "are", "unbalanced", "." ]
ff8b54693e86e5ea3c2f6df7f69599d4e64f93fe
https://github.com/gwtw/js-avl-tree/blob/ff8b54693e86e5ea3c2f6df7f69599d4e64f93fe/src/avl-tree.js#L327-L336
40,762
jlidder/jswiremock
UrlParser.js
UrlNode
function UrlNode(data){ this.append = function(next){ this.next = next; }; this.getData = function(){ return this.data; }; this.setData = function(data){ this.data = data; } this.getNext = function(){ return this.next; }; this.setParams = function(params){ var queryParameters = params.split("&"); if(queryParameters != null){ this.params = []; for(var counter = 0; counter < queryParameters.length; counter++) { var keyValuePair = queryParameters[counter].split("="); this.params[keyValuePair[0]] = keyValuePair[1]; } } else{ queryParameters = null; } }; this.getParams = function(){ return this.params; }; //set var's for this object var queryParamSplit = data.split("?"); this.params = null; this.data = null; this.next = null; if(queryParamSplit != null && queryParamSplit.length > 1){ this.setData(queryParamSplit[0]); this.setParams(queryParamSplit[1]); } else{ this.setData(data); } }
javascript
function UrlNode(data){ this.append = function(next){ this.next = next; }; this.getData = function(){ return this.data; }; this.setData = function(data){ this.data = data; } this.getNext = function(){ return this.next; }; this.setParams = function(params){ var queryParameters = params.split("&"); if(queryParameters != null){ this.params = []; for(var counter = 0; counter < queryParameters.length; counter++) { var keyValuePair = queryParameters[counter].split("="); this.params[keyValuePair[0]] = keyValuePair[1]; } } else{ queryParameters = null; } }; this.getParams = function(){ return this.params; }; //set var's for this object var queryParamSplit = data.split("?"); this.params = null; this.data = null; this.next = null; if(queryParamSplit != null && queryParamSplit.length > 1){ this.setData(queryParamSplit[0]); this.setParams(queryParamSplit[1]); } else{ this.setData(data); } }
[ "function", "UrlNode", "(", "data", ")", "{", "this", ".", "append", "=", "function", "(", "next", ")", "{", "this", ".", "next", "=", "next", ";", "}", ";", "this", ".", "getData", "=", "function", "(", ")", "{", "return", "this", ".", "data", ";", "}", ";", "this", ".", "setData", "=", "function", "(", "data", ")", "{", "this", ".", "data", "=", "data", ";", "}", "this", ".", "getNext", "=", "function", "(", ")", "{", "return", "this", ".", "next", ";", "}", ";", "this", ".", "setParams", "=", "function", "(", "params", ")", "{", "var", "queryParameters", "=", "params", ".", "split", "(", "\"&\"", ")", ";", "if", "(", "queryParameters", "!=", "null", ")", "{", "this", ".", "params", "=", "[", "]", ";", "for", "(", "var", "counter", "=", "0", ";", "counter", "<", "queryParameters", ".", "length", ";", "counter", "++", ")", "{", "var", "keyValuePair", "=", "queryParameters", "[", "counter", "]", ".", "split", "(", "\"=\"", ")", ";", "this", ".", "params", "[", "keyValuePair", "[", "0", "]", "]", "=", "keyValuePair", "[", "1", "]", ";", "}", "}", "else", "{", "queryParameters", "=", "null", ";", "}", "}", ";", "this", ".", "getParams", "=", "function", "(", ")", "{", "return", "this", ".", "params", ";", "}", ";", "//set var's for this object", "var", "queryParamSplit", "=", "data", ".", "split", "(", "\"?\"", ")", ";", "this", ".", "params", "=", "null", ";", "this", ".", "data", "=", "null", ";", "this", ".", "next", "=", "null", ";", "if", "(", "queryParamSplit", "!=", "null", "&&", "queryParamSplit", ".", "length", ">", "1", ")", "{", "this", ".", "setData", "(", "queryParamSplit", "[", "0", "]", ")", ";", "this", ".", "setParams", "(", "queryParamSplit", "[", "1", "]", ")", ";", "}", "else", "{", "this", ".", "setData", "(", "data", ")", ";", "}", "}" ]
Created by jlidder on 15-07-18.
[ "Created", "by", "jlidder", "on", "15", "-", "07", "-", "18", "." ]
e5943005a6d9be09700502be165b9ca174049c82
https://github.com/jlidder/jswiremock/blob/e5943005a6d9be09700502be165b9ca174049c82/UrlParser.js#L5-L45
40,763
gwtw/js-avl-tree
src/node.js
function (key, value) { this.left = null; this.right = null; this.height = null; this.key = key; this.value = value; }
javascript
function (key, value) { this.left = null; this.right = null; this.height = null; this.key = key; this.value = value; }
[ "function", "(", "key", ",", "value", ")", "{", "this", ".", "left", "=", "null", ";", "this", ".", "right", "=", "null", ";", "this", ".", "height", "=", "null", ";", "this", ".", "key", "=", "key", ";", "this", ".", "value", "=", "value", ";", "}" ]
Creates a new AVL Tree node. @private @param {Object} key The key of the new node. @param {Object} value The value of the new node.
[ "Creates", "a", "new", "AVL", "Tree", "node", "." ]
ff8b54693e86e5ea3c2f6df7f69599d4e64f93fe
https://github.com/gwtw/js-avl-tree/blob/ff8b54693e86e5ea3c2f6df7f69599d4e64f93fe/src/node.js#L15-L21
40,764
wongatech/angular-http-loader
app/package/js/angular-http-loader.js
function (event, method) { if (methods.indexOf(method.toUpperCase()) !== -1) { showLoader = (event.name === 'loaderShow'); } else if (methods.length === 0) { showLoader = (event.name === 'loaderShow'); } if (ttl <= 0 || (!timeoutId && !showLoader)) { $scope.showLoader = showLoader; return; } if (timeoutId) { return; } $scope.showLoader = showLoader; timeoutId = $timeout(function () { if (!showLoader) { $scope.showLoader = showLoader; } timeoutId = undefined; }, ttl); }
javascript
function (event, method) { if (methods.indexOf(method.toUpperCase()) !== -1) { showLoader = (event.name === 'loaderShow'); } else if (methods.length === 0) { showLoader = (event.name === 'loaderShow'); } if (ttl <= 0 || (!timeoutId && !showLoader)) { $scope.showLoader = showLoader; return; } if (timeoutId) { return; } $scope.showLoader = showLoader; timeoutId = $timeout(function () { if (!showLoader) { $scope.showLoader = showLoader; } timeoutId = undefined; }, ttl); }
[ "function", "(", "event", ",", "method", ")", "{", "if", "(", "methods", ".", "indexOf", "(", "method", ".", "toUpperCase", "(", ")", ")", "!==", "-", "1", ")", "{", "showLoader", "=", "(", "event", ".", "name", "===", "'loaderShow'", ")", ";", "}", "else", "if", "(", "methods", ".", "length", "===", "0", ")", "{", "showLoader", "=", "(", "event", ".", "name", "===", "'loaderShow'", ")", ";", "}", "if", "(", "ttl", "<=", "0", "||", "(", "!", "timeoutId", "&&", "!", "showLoader", ")", ")", "{", "$scope", ".", "showLoader", "=", "showLoader", ";", "return", ";", "}", "if", "(", "timeoutId", ")", "{", "return", ";", "}", "$scope", ".", "showLoader", "=", "showLoader", ";", "timeoutId", "=", "$timeout", "(", "function", "(", ")", "{", "if", "(", "!", "showLoader", ")", "{", "$scope", ".", "showLoader", "=", "showLoader", ";", "}", "timeoutId", "=", "undefined", ";", "}", ",", "ttl", ")", ";", "}" ]
Toggle the show loader. Contains the logic to show or hide the loader depending on the passed method @param {object} event @param {string} method
[ "Toggle", "the", "show", "loader", ".", "Contains", "the", "logic", "to", "show", "or", "hide", "the", "loader", "depending", "on", "the", "passed", "method" ]
070ccf93eebe9cca714e77a5b788f3630d987af1
https://github.com/wongatech/angular-http-loader/blob/070ccf93eebe9cca714e77a5b788f3630d987af1/app/package/js/angular-http-loader.js#L98-L120
40,765
wongatech/angular-http-loader
app/package/js/angular-http-loader.js
function (url) { if (url.substring(0, 2) !== '//' && url.indexOf('://') === -1 && whitelistLocalRequests) { return true; } for (var i = domains.length; i--;) { if (url.indexOf(domains[i]) !== -1) { return true; } } return false; }
javascript
function (url) { if (url.substring(0, 2) !== '//' && url.indexOf('://') === -1 && whitelistLocalRequests) { return true; } for (var i = domains.length; i--;) { if (url.indexOf(domains[i]) !== -1) { return true; } } return false; }
[ "function", "(", "url", ")", "{", "if", "(", "url", ".", "substring", "(", "0", ",", "2", ")", "!==", "'//'", "&&", "url", ".", "indexOf", "(", "'://'", ")", "===", "-", "1", "&&", "whitelistLocalRequests", ")", "{", "return", "true", ";", "}", "for", "(", "var", "i", "=", "domains", ".", "length", ";", "i", "--", ";", ")", "{", "if", "(", "url", ".", "indexOf", "(", "domains", "[", "i", "]", ")", "!==", "-", "1", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check if the url domain is on the whitelist @param {string} url @returns {boolean}
[ "Check", "if", "the", "url", "domain", "is", "on", "the", "whitelist" ]
070ccf93eebe9cca714e77a5b788f3630d987af1
https://github.com/wongatech/angular-http-loader/blob/070ccf93eebe9cca714e77a5b788f3630d987af1/app/package/js/angular-http-loader.js#L171-L185
40,766
wongatech/angular-http-loader
app/package/js/angular-http-loader.js
function (config) { if (isUrlOnWhitelist(config.url)) { numLoadings++; $rootScope.$emit('loaderShow', config.method); } return config || $q.when(config); }
javascript
function (config) { if (isUrlOnWhitelist(config.url)) { numLoadings++; $rootScope.$emit('loaderShow', config.method); } return config || $q.when(config); }
[ "function", "(", "config", ")", "{", "if", "(", "isUrlOnWhitelist", "(", "config", ".", "url", ")", ")", "{", "numLoadings", "++", ";", "$rootScope", ".", "$emit", "(", "'loaderShow'", ",", "config", ".", "method", ")", ";", "}", "return", "config", "||", "$q", ".", "when", "(", "config", ")", ";", "}" ]
Broadcast the loader show event @param {object} config @returns {object|Promise}
[ "Broadcast", "the", "loader", "show", "event" ]
070ccf93eebe9cca714e77a5b788f3630d987af1
https://github.com/wongatech/angular-http-loader/blob/070ccf93eebe9cca714e77a5b788f3630d987af1/app/package/js/angular-http-loader.js#L208-L215
40,767
pubkey/solidity-cli
dist/src/output-files/index.js
outputPath
function outputPath(options, source) { var DEBUG = false; if (DEBUG) console.log('sourceFolder: ' + options.sourceFolder); var globBase = options.sourceFolder.replace(/\*.*/, ''); if (globBase.endsWith('.sol')) // single file globBase = path.join(globBase, '../'); if (DEBUG) console.log('globBase: ' + globBase); var optDestination = options.destinationFolder ? options.destinationFolder : globBase; if (DEBUG) console.log('optDestination: ' + optDestination); var destinationFolder = path.join(globBase, optDestination); if (optDestination === globBase) destinationFolder = globBase; if (DEBUG) console.log('destinationFolder: ' + destinationFolder); // destination-folder is absolut if (options.destinationFolder && options.destinationFolder.startsWith('/')) destinationFolder = path.join(options.destinationFolder, './'); var fileNameRelative = source.filename.replace(globBase, ''); if (DEBUG) console.log('fileNameRelative: ' + fileNameRelative); var goalPath = path.join(destinationFolder, fileNameRelative); return goalPath; }
javascript
function outputPath(options, source) { var DEBUG = false; if (DEBUG) console.log('sourceFolder: ' + options.sourceFolder); var globBase = options.sourceFolder.replace(/\*.*/, ''); if (globBase.endsWith('.sol')) // single file globBase = path.join(globBase, '../'); if (DEBUG) console.log('globBase: ' + globBase); var optDestination = options.destinationFolder ? options.destinationFolder : globBase; if (DEBUG) console.log('optDestination: ' + optDestination); var destinationFolder = path.join(globBase, optDestination); if (optDestination === globBase) destinationFolder = globBase; if (DEBUG) console.log('destinationFolder: ' + destinationFolder); // destination-folder is absolut if (options.destinationFolder && options.destinationFolder.startsWith('/')) destinationFolder = path.join(options.destinationFolder, './'); var fileNameRelative = source.filename.replace(globBase, ''); if (DEBUG) console.log('fileNameRelative: ' + fileNameRelative); var goalPath = path.join(destinationFolder, fileNameRelative); return goalPath; }
[ "function", "outputPath", "(", "options", ",", "source", ")", "{", "var", "DEBUG", "=", "false", ";", "if", "(", "DEBUG", ")", "console", ".", "log", "(", "'sourceFolder: '", "+", "options", ".", "sourceFolder", ")", ";", "var", "globBase", "=", "options", ".", "sourceFolder", ".", "replace", "(", "/", "\\*.*", "/", ",", "''", ")", ";", "if", "(", "globBase", ".", "endsWith", "(", "'.sol'", ")", ")", "// single file", "globBase", "=", "path", ".", "join", "(", "globBase", ",", "'../'", ")", ";", "if", "(", "DEBUG", ")", "console", ".", "log", "(", "'globBase: '", "+", "globBase", ")", ";", "var", "optDestination", "=", "options", ".", "destinationFolder", "?", "options", ".", "destinationFolder", ":", "globBase", ";", "if", "(", "DEBUG", ")", "console", ".", "log", "(", "'optDestination: '", "+", "optDestination", ")", ";", "var", "destinationFolder", "=", "path", ".", "join", "(", "globBase", ",", "optDestination", ")", ";", "if", "(", "optDestination", "===", "globBase", ")", "destinationFolder", "=", "globBase", ";", "if", "(", "DEBUG", ")", "console", ".", "log", "(", "'destinationFolder: '", "+", "destinationFolder", ")", ";", "// destination-folder is absolut", "if", "(", "options", ".", "destinationFolder", "&&", "options", ".", "destinationFolder", ".", "startsWith", "(", "'/'", ")", ")", "destinationFolder", "=", "path", ".", "join", "(", "options", ".", "destinationFolder", ",", "'./'", ")", ";", "var", "fileNameRelative", "=", "source", ".", "filename", ".", "replace", "(", "globBase", ",", "''", ")", ";", "if", "(", "DEBUG", ")", "console", ".", "log", "(", "'fileNameRelative: '", "+", "fileNameRelative", ")", ";", "var", "goalPath", "=", "path", ".", "join", "(", "destinationFolder", ",", "fileNameRelative", ")", ";", "return", "goalPath", ";", "}" ]
determines where the output should be written
[ "determines", "where", "the", "output", "should", "be", "written" ]
537f1ef9c3d62b488a771a4a5a67cfa2d74a4532
https://github.com/pubkey/solidity-cli/blob/537f1ef9c3d62b488a771a4a5a67cfa2d74a4532/dist/src/output-files/index.js#L81-L106
40,768
pubkey/solidity-cli
dist/src/index.js
generateOutput
function generateOutput(source) { return __awaiter(this, void 0, void 0, function () { var isCached, artifact, compiled, artifact, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, caching.has(source.codeHash)]; case 1: isCached = _b.sent(); if (!isCached) return [3 /*break*/, 3]; return [4 /*yield*/, caching.get(source.codeHash)]; case 2: artifact = _b.sent(); return [2 /*return*/, artifact]; case 3: return [4 /*yield*/, solc_install_1.installVersion(source.solcVersion)]; case 4: _b.sent(); return [4 /*yield*/, compile_1.default(source)]; case 5: compiled = _b.sent(); _a = { compiled: compiled }; return [4 /*yield*/, output_files_1.createJavascriptFile(source, compiled)]; case 6: _a.javascript = _b.sent(); return [4 /*yield*/, output_files_1.createTypescriptFile(source, compiled)]; case 7: artifact = (_a.typescript = _b.sent(), _a); return [4 /*yield*/, caching.set(source.codeHash, artifact)]; case 8: _b.sent(); return [2 /*return*/, artifact]; } }); }); }
javascript
function generateOutput(source) { return __awaiter(this, void 0, void 0, function () { var isCached, artifact, compiled, artifact, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, caching.has(source.codeHash)]; case 1: isCached = _b.sent(); if (!isCached) return [3 /*break*/, 3]; return [4 /*yield*/, caching.get(source.codeHash)]; case 2: artifact = _b.sent(); return [2 /*return*/, artifact]; case 3: return [4 /*yield*/, solc_install_1.installVersion(source.solcVersion)]; case 4: _b.sent(); return [4 /*yield*/, compile_1.default(source)]; case 5: compiled = _b.sent(); _a = { compiled: compiled }; return [4 /*yield*/, output_files_1.createJavascriptFile(source, compiled)]; case 6: _a.javascript = _b.sent(); return [4 /*yield*/, output_files_1.createTypescriptFile(source, compiled)]; case 7: artifact = (_a.typescript = _b.sent(), _a); return [4 /*yield*/, caching.set(source.codeHash, artifact)]; case 8: _b.sent(); return [2 /*return*/, artifact]; } }); }); }
[ "function", "generateOutput", "(", "source", ")", "{", "return", "__awaiter", "(", "this", ",", "void", "0", ",", "void", "0", ",", "function", "(", ")", "{", "var", "isCached", ",", "artifact", ",", "compiled", ",", "artifact", ",", "_a", ";", "return", "__generator", "(", "this", ",", "function", "(", "_b", ")", "{", "switch", "(", "_b", ".", "label", ")", "{", "case", "0", ":", "return", "[", "4", "/*yield*/", ",", "caching", ".", "has", "(", "source", ".", "codeHash", ")", "]", ";", "case", "1", ":", "isCached", "=", "_b", ".", "sent", "(", ")", ";", "if", "(", "!", "isCached", ")", "return", "[", "3", "/*break*/", ",", "3", "]", ";", "return", "[", "4", "/*yield*/", ",", "caching", ".", "get", "(", "source", ".", "codeHash", ")", "]", ";", "case", "2", ":", "artifact", "=", "_b", ".", "sent", "(", ")", ";", "return", "[", "2", "/*return*/", ",", "artifact", "]", ";", "case", "3", ":", "return", "[", "4", "/*yield*/", ",", "solc_install_1", ".", "installVersion", "(", "source", ".", "solcVersion", ")", "]", ";", "case", "4", ":", "_b", ".", "sent", "(", ")", ";", "return", "[", "4", "/*yield*/", ",", "compile_1", ".", "default", "(", "source", ")", "]", ";", "case", "5", ":", "compiled", "=", "_b", ".", "sent", "(", ")", ";", "_a", "=", "{", "compiled", ":", "compiled", "}", ";", "return", "[", "4", "/*yield*/", ",", "output_files_1", ".", "createJavascriptFile", "(", "source", ",", "compiled", ")", "]", ";", "case", "6", ":", "_a", ".", "javascript", "=", "_b", ".", "sent", "(", ")", ";", "return", "[", "4", "/*yield*/", ",", "output_files_1", ".", "createTypescriptFile", "(", "source", ",", "compiled", ")", "]", ";", "case", "7", ":", "artifact", "=", "(", "_a", ".", "typescript", "=", "_b", ".", "sent", "(", ")", ",", "_a", ")", ";", "return", "[", "4", "/*yield*/", ",", "caching", ".", "set", "(", "source", ".", "codeHash", ",", "artifact", ")", "]", ";", "case", "8", ":", "_b", ".", "sent", "(", ")", ";", "return", "[", "2", "/*return*/", ",", "artifact", "]", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
generates the output or retrieves it from cache
[ "generates", "the", "output", "or", "retrieves", "it", "from", "cache" ]
537f1ef9c3d62b488a771a4a5a67cfa2d74a4532
https://github.com/pubkey/solidity-cli/blob/537f1ef9c3d62b488a771a4a5a67cfa2d74a4532/dist/src/index.js#L54-L90
40,769
pubkey/solidity-cli
dist/src/read-code.js
getSourceCode
function getSourceCode(fileName) { return __awaiter(this, void 0, void 0, function () { var code, codeCommentsRegex, importsRegex, imports; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, readFile(fileName, 'utf-8')]; case 1: code = _a.sent(); codeCommentsRegex = /(\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\/)|(\/\/.*)/g; code = code.replace(codeCommentsRegex, ''); importsRegex = /import "([^"]*)";/g; imports = matches(importsRegex, code); return [4 /*yield*/, Promise.all(imports.map(function (match) { return __awaiter(_this, void 0, void 0, function () { var p, innerCode; return __generator(this, function (_a) { switch (_a.label) { case 0: p = path.resolve(fileName, '..', match.inner); return [4 /*yield*/, getSourceCode(p)]; case 1: innerCode = _a.sent(); // remove first line containing version innerCode = innerCode.replace(/^.*\n/, ''); code = code.replace(match.full, innerCode); return [2 /*return*/]; } }); }); }))]; case 2: _a.sent(); return [2 /*return*/, code]; } }); }); }
javascript
function getSourceCode(fileName) { return __awaiter(this, void 0, void 0, function () { var code, codeCommentsRegex, importsRegex, imports; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, readFile(fileName, 'utf-8')]; case 1: code = _a.sent(); codeCommentsRegex = /(\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\/)|(\/\/.*)/g; code = code.replace(codeCommentsRegex, ''); importsRegex = /import "([^"]*)";/g; imports = matches(importsRegex, code); return [4 /*yield*/, Promise.all(imports.map(function (match) { return __awaiter(_this, void 0, void 0, function () { var p, innerCode; return __generator(this, function (_a) { switch (_a.label) { case 0: p = path.resolve(fileName, '..', match.inner); return [4 /*yield*/, getSourceCode(p)]; case 1: innerCode = _a.sent(); // remove first line containing version innerCode = innerCode.replace(/^.*\n/, ''); code = code.replace(match.full, innerCode); return [2 /*return*/]; } }); }); }))]; case 2: _a.sent(); return [2 /*return*/, code]; } }); }); }
[ "function", "getSourceCode", "(", "fileName", ")", "{", "return", "__awaiter", "(", "this", ",", "void", "0", ",", "void", "0", ",", "function", "(", ")", "{", "var", "code", ",", "codeCommentsRegex", ",", "importsRegex", ",", "imports", ";", "var", "_this", "=", "this", ";", "return", "__generator", "(", "this", ",", "function", "(", "_a", ")", "{", "switch", "(", "_a", ".", "label", ")", "{", "case", "0", ":", "return", "[", "4", "/*yield*/", ",", "readFile", "(", "fileName", ",", "'utf-8'", ")", "]", ";", "case", "1", ":", "code", "=", "_a", ".", "sent", "(", ")", ";", "codeCommentsRegex", "=", "/", "(\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*+\\/)|(\\/\\/.*)", "/", "g", ";", "code", "=", "code", ".", "replace", "(", "codeCommentsRegex", ",", "''", ")", ";", "importsRegex", "=", "/", "import \"([^\"]*)\";", "/", "g", ";", "imports", "=", "matches", "(", "importsRegex", ",", "code", ")", ";", "return", "[", "4", "/*yield*/", ",", "Promise", ".", "all", "(", "imports", ".", "map", "(", "function", "(", "match", ")", "{", "return", "__awaiter", "(", "_this", ",", "void", "0", ",", "void", "0", ",", "function", "(", ")", "{", "var", "p", ",", "innerCode", ";", "return", "__generator", "(", "this", ",", "function", "(", "_a", ")", "{", "switch", "(", "_a", ".", "label", ")", "{", "case", "0", ":", "p", "=", "path", ".", "resolve", "(", "fileName", ",", "'..'", ",", "match", ".", "inner", ")", ";", "return", "[", "4", "/*yield*/", ",", "getSourceCode", "(", "p", ")", "]", ";", "case", "1", ":", "innerCode", "=", "_a", ".", "sent", "(", ")", ";", "// remove first line containing version", "innerCode", "=", "innerCode", ".", "replace", "(", "/", "^.*\\n", "/", ",", "''", ")", ";", "code", "=", "code", ".", "replace", "(", "match", ".", "full", ",", "innerCode", ")", ";", "return", "[", "2", "/*return*/", "]", ";", "}", "}", ")", ";", "}", ")", ";", "}", ")", ")", "]", ";", "case", "2", ":", "_a", ".", "sent", "(", ")", ";", "return", "[", "2", "/*return*/", ",", "code", "]", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
gets the source-code from the file and parses all imports
[ "gets", "the", "source", "-", "code", "from", "the", "file", "and", "parses", "all", "imports" ]
537f1ef9c3d62b488a771a4a5a67cfa2d74a4532
https://github.com/pubkey/solidity-cli/blob/537f1ef9c3d62b488a771a4a5a67cfa2d74a4532/dist/src/read-code.js#L67-L102
40,770
tschaub/authorized
lib/manager.js
Manager
function Manager(options) { this.roleGetters_ = {}; this.entityGetters_ = {}; this.actionDefs_ = {}; this.options = { pauseStream: true }; if (options) { for (var option in this.options) { if (options.hasOwnProperty(option)) { this.options[option] = options[option]; } } } }
javascript
function Manager(options) { this.roleGetters_ = {}; this.entityGetters_ = {}; this.actionDefs_ = {}; this.options = { pauseStream: true }; if (options) { for (var option in this.options) { if (options.hasOwnProperty(option)) { this.options[option] = options[option]; } } } }
[ "function", "Manager", "(", "options", ")", "{", "this", ".", "roleGetters_", "=", "{", "}", ";", "this", ".", "entityGetters_", "=", "{", "}", ";", "this", ".", "actionDefs_", "=", "{", "}", ";", "this", ".", "options", "=", "{", "pauseStream", ":", "true", "}", ";", "if", "(", "options", ")", "{", "for", "(", "var", "option", "in", "this", ".", "options", ")", "{", "if", "(", "options", ".", "hasOwnProperty", "(", "option", ")", ")", "{", "this", ".", "options", "[", "option", "]", "=", "options", "[", "option", "]", ";", "}", "}", "}", "}" ]
Create a new authorization manager. @param {Object} options Manager options. * pauseStream {boolean} Pause the request body stream while checking authorization (default is `true`). @constructor
[ "Create", "a", "new", "authorization", "manager", "." ]
999216db421f662dc9ca8b752eccd28bae017601
https://github.com/tschaub/authorized/blob/999216db421f662dc9ca8b752eccd28bae017601/lib/manager.js#L25-L39
40,771
Merri/react-tabbordion
src/lib/resize.js
triggerResize
function triggerResize(callback) { const { animateContent, checked } = callback.getState() if ((animateContent === 'height' && checked) || (animateContent === 'marginTop' && !checked)) { callback() } }
javascript
function triggerResize(callback) { const { animateContent, checked } = callback.getState() if ((animateContent === 'height' && checked) || (animateContent === 'marginTop' && !checked)) { callback() } }
[ "function", "triggerResize", "(", "callback", ")", "{", "const", "{", "animateContent", ",", "checked", "}", "=", "callback", ".", "getState", "(", ")", "if", "(", "(", "animateContent", "===", "'height'", "&&", "checked", ")", "||", "(", "animateContent", "===", "'marginTop'", "&&", "!", "checked", ")", ")", "{", "callback", "(", ")", "}", "}" ]
optimized only to be called on panels that actively can do transitions
[ "optimized", "only", "to", "be", "called", "on", "panels", "that", "actively", "can", "do", "transitions" ]
614a746ef4a062c1e13c563f7de7c83ee0715ac3
https://github.com/Merri/react-tabbordion/blob/614a746ef4a062c1e13c563f7de7c83ee0715ac3/src/lib/resize.js#L50-L55
40,772
gladeye/aframe-preloader-component
index.js
function () { if(this.data.debug){ console.log('Initialized preloader'); } if(this.data.type === 'bootstrap' && typeof $ === 'undefined'){ console.error('jQuery is not present, cannot instantiate Bootstrap modal for preloader!'); } document.querySelector('a-assets').addEventListener('loaded',function(){ if(this.data.debug){ console.info('All assets loaded'); } this.triggerProgressComplete(); }.bind(this)); var assetItems = document.querySelectorAll('a-assets a-asset-item,a-assets img,a-assets audio,a-assets video'); this.totalAssetCount = assetItems.length; this.watchPreloadProgress(assetItems); if(!this.data.target && this.data.autoInject){ if(this.data.debug){ console.info('No preloader html found, auto-injecting'); } this.injectHTML(); }else{ switch(this.data.type){ case 'bootstrap': this.initBootstrapModal($(this.data.target)); break; default: //do nothing break; } } if(this.data.disableVRModeUI){ this.sceneEl.setAttribute('vr-mode-ui','enabled','false'); } }
javascript
function () { if(this.data.debug){ console.log('Initialized preloader'); } if(this.data.type === 'bootstrap' && typeof $ === 'undefined'){ console.error('jQuery is not present, cannot instantiate Bootstrap modal for preloader!'); } document.querySelector('a-assets').addEventListener('loaded',function(){ if(this.data.debug){ console.info('All assets loaded'); } this.triggerProgressComplete(); }.bind(this)); var assetItems = document.querySelectorAll('a-assets a-asset-item,a-assets img,a-assets audio,a-assets video'); this.totalAssetCount = assetItems.length; this.watchPreloadProgress(assetItems); if(!this.data.target && this.data.autoInject){ if(this.data.debug){ console.info('No preloader html found, auto-injecting'); } this.injectHTML(); }else{ switch(this.data.type){ case 'bootstrap': this.initBootstrapModal($(this.data.target)); break; default: //do nothing break; } } if(this.data.disableVRModeUI){ this.sceneEl.setAttribute('vr-mode-ui','enabled','false'); } }
[ "function", "(", ")", "{", "if", "(", "this", ".", "data", ".", "debug", ")", "{", "console", ".", "log", "(", "'Initialized preloader'", ")", ";", "}", "if", "(", "this", ".", "data", ".", "type", "===", "'bootstrap'", "&&", "typeof", "$", "===", "'undefined'", ")", "{", "console", ".", "error", "(", "'jQuery is not present, cannot instantiate Bootstrap modal for preloader!'", ")", ";", "}", "document", ".", "querySelector", "(", "'a-assets'", ")", ".", "addEventListener", "(", "'loaded'", ",", "function", "(", ")", "{", "if", "(", "this", ".", "data", ".", "debug", ")", "{", "console", ".", "info", "(", "'All assets loaded'", ")", ";", "}", "this", ".", "triggerProgressComplete", "(", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "var", "assetItems", "=", "document", ".", "querySelectorAll", "(", "'a-assets a-asset-item,a-assets img,a-assets audio,a-assets video'", ")", ";", "this", ".", "totalAssetCount", "=", "assetItems", ".", "length", ";", "this", ".", "watchPreloadProgress", "(", "assetItems", ")", ";", "if", "(", "!", "this", ".", "data", ".", "target", "&&", "this", ".", "data", ".", "autoInject", ")", "{", "if", "(", "this", ".", "data", ".", "debug", ")", "{", "console", ".", "info", "(", "'No preloader html found, auto-injecting'", ")", ";", "}", "this", ".", "injectHTML", "(", ")", ";", "}", "else", "{", "switch", "(", "this", ".", "data", ".", "type", ")", "{", "case", "'bootstrap'", ":", "this", ".", "initBootstrapModal", "(", "$", "(", "this", ".", "data", ".", "target", ")", ")", ";", "break", ";", "default", ":", "//do nothing", "break", ";", "}", "}", "if", "(", "this", ".", "data", ".", "disableVRModeUI", ")", "{", "this", ".", "sceneEl", ".", "setAttribute", "(", "'vr-mode-ui'", ",", "'enabled'", ",", "'false'", ")", ";", "}", "}" ]
length of time to slow down preload finish if slowLoad is set to 'true' Called once when component is attached. Generally for initial setup.
[ "length", "of", "time", "to", "slow", "down", "preload", "finish", "if", "slowLoad", "is", "set", "to", "true", "Called", "once", "when", "component", "is", "attached", ".", "Generally", "for", "initial", "setup", "." ]
287f881d3aed160b463cb60513e706368ec2fe24
https://github.com/gladeye/aframe-preloader-component/blob/287f881d3aed160b463cb60513e706368ec2fe24/index.js#L63-L106
40,773
ukayani/restify-router
lib/router.js
getHandlersFromArgs
function getHandlersFromArgs(args, start) { assert.ok(args); args = Array.prototype.slice.call(args, start); function process(handlers, acc) { if (handlers.length === 0) { return acc; } var head = handlers.shift(); if (Array.isArray(head)) { return process(head.concat(handlers), acc); } else { assert.func(head, 'handler'); acc.push(head); return process(handlers, acc); } } return process(args, []); }
javascript
function getHandlersFromArgs(args, start) { assert.ok(args); args = Array.prototype.slice.call(args, start); function process(handlers, acc) { if (handlers.length === 0) { return acc; } var head = handlers.shift(); if (Array.isArray(head)) { return process(head.concat(handlers), acc); } else { assert.func(head, 'handler'); acc.push(head); return process(handlers, acc); } } return process(args, []); }
[ "function", "getHandlersFromArgs", "(", "args", ",", "start", ")", "{", "assert", ".", "ok", "(", "args", ")", ";", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "args", ",", "start", ")", ";", "function", "process", "(", "handlers", ",", "acc", ")", "{", "if", "(", "handlers", ".", "length", "===", "0", ")", "{", "return", "acc", ";", "}", "var", "head", "=", "handlers", ".", "shift", "(", ")", ";", "if", "(", "Array", ".", "isArray", "(", "head", ")", ")", "{", "return", "process", "(", "head", ".", "concat", "(", "handlers", ")", ",", "acc", ")", ";", "}", "else", "{", "assert", ".", "func", "(", "head", ",", "'handler'", ")", ";", "acc", ".", "push", "(", "head", ")", ";", "return", "process", "(", "handlers", ",", "acc", ")", ";", "}", "}", "return", "process", "(", "args", ",", "[", "]", ")", ";", "}" ]
Given a argument list, flatten the list @param args @param start point from which to slice the list @returns {Array}
[ "Given", "a", "argument", "list", "flatten", "the", "list" ]
07c68e49927e5f23f1cabcfeea7257b681caac66
https://github.com/ukayani/restify-router/blob/07c68e49927e5f23f1cabcfeea7257b681caac66/lib/router.js#L11-L32
40,774
ukayani/restify-router
lib/router.js
Router
function Router() { // Routes with all verbs var routes = {}; methods.forEach(function (method) { routes[method] = []; }); this.routes = routes; this.commonHandlers = []; this.routers = []; }
javascript
function Router() { // Routes with all verbs var routes = {}; methods.forEach(function (method) { routes[method] = []; }); this.routes = routes; this.commonHandlers = []; this.routers = []; }
[ "function", "Router", "(", ")", "{", "// Routes with all verbs", "var", "routes", "=", "{", "}", ";", "methods", ".", "forEach", "(", "function", "(", "method", ")", "{", "routes", "[", "method", "]", "=", "[", "]", ";", "}", ")", ";", "this", ".", "routes", "=", "routes", ";", "this", ".", "commonHandlers", "=", "[", "]", ";", "this", ".", "routers", "=", "[", "]", ";", "}" ]
Simple router that aggregates restify routes
[ "Simple", "router", "that", "aggregates", "restify", "routes" ]
07c68e49927e5f23f1cabcfeea7257b681caac66
https://github.com/ukayani/restify-router/blob/07c68e49927e5f23f1cabcfeea7257b681caac66/lib/router.js#L39-L50
40,775
generate/generate-gitignore
generator.js
tasks
function tasks(options) { options = options || {}; var fp = path.resolve(options.template); var tmpl = new utils.File({path: fp, contents: fs.readFileSync(fp)}); var data = {tasks: []}; return utils.through.obj(function(file, enc, next) { var description = options.description || file.stem; if (typeof description === 'function') { description = options.description(file); } data.tasks.push({ alias: 'gitignore', path: path.relative(path.resolve('generators'), file.path), name: file.stem.toLowerCase(), description: description, relative: file.relative, basename: '.gitignore' }); next(); }, function(next) { tmpl.data = data; this.push(tmpl); next(); }); }
javascript
function tasks(options) { options = options || {}; var fp = path.resolve(options.template); var tmpl = new utils.File({path: fp, contents: fs.readFileSync(fp)}); var data = {tasks: []}; return utils.through.obj(function(file, enc, next) { var description = options.description || file.stem; if (typeof description === 'function') { description = options.description(file); } data.tasks.push({ alias: 'gitignore', path: path.relative(path.resolve('generators'), file.path), name: file.stem.toLowerCase(), description: description, relative: file.relative, basename: '.gitignore' }); next(); }, function(next) { tmpl.data = data; this.push(tmpl); next(); }); }
[ "function", "tasks", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "fp", "=", "path", ".", "resolve", "(", "options", ".", "template", ")", ";", "var", "tmpl", "=", "new", "utils", ".", "File", "(", "{", "path", ":", "fp", ",", "contents", ":", "fs", ".", "readFileSync", "(", "fp", ")", "}", ")", ";", "var", "data", "=", "{", "tasks", ":", "[", "]", "}", ";", "return", "utils", ".", "through", ".", "obj", "(", "function", "(", "file", ",", "enc", ",", "next", ")", "{", "var", "description", "=", "options", ".", "description", "||", "file", ".", "stem", ";", "if", "(", "typeof", "description", "===", "'function'", ")", "{", "description", "=", "options", ".", "description", "(", "file", ")", ";", "}", "data", ".", "tasks", ".", "push", "(", "{", "alias", ":", "'gitignore'", ",", "path", ":", "path", ".", "relative", "(", "path", ".", "resolve", "(", "'generators'", ")", ",", "file", ".", "path", ")", ",", "name", ":", "file", ".", "stem", ".", "toLowerCase", "(", ")", ",", "description", ":", "description", ",", "relative", ":", "file", ".", "relative", ",", "basename", ":", "'.gitignore'", "}", ")", ";", "next", "(", ")", ";", "}", ",", "function", "(", "next", ")", "{", "tmpl", ".", "data", "=", "data", ";", "this", ".", "push", "(", "tmpl", ")", ";", "next", "(", ")", ";", "}", ")", ";", "}" ]
Plugin for generating individual gitignore tasks. The alternative would be to load in templates and create tasks on-the-fly, but this approach is much faster and results in a better user experience.
[ "Plugin", "for", "generating", "individual", "gitignore", "tasks", "." ]
69a0b7b0e66bf9f46a1cc59245b13d9eb346f9ff
https://github.com/generate/generate-gitignore/blob/69a0b7b0e66bf9f46a1cc59245b13d9eb346f9ff/generator.js#L111-L139
40,776
wmurphyrd/aframe-physics-extras
src/physics-sleepy.js
function (evt) { let state = this.data.holdState // api change in A-Frame v0.8.0 if (evt.detail === state || evt.detail.state === state) { this.el.body.allowSleep = false } }
javascript
function (evt) { let state = this.data.holdState // api change in A-Frame v0.8.0 if (evt.detail === state || evt.detail.state === state) { this.el.body.allowSleep = false } }
[ "function", "(", "evt", ")", "{", "let", "state", "=", "this", ".", "data", ".", "holdState", "// api change in A-Frame v0.8.0", "if", "(", "evt", ".", "detail", "===", "state", "||", "evt", ".", "detail", ".", "state", "===", "state", ")", "{", "this", ".", "el", ".", "body", ".", "allowSleep", "=", "false", "}", "}" ]
disble the sleeping during interactions because sleep will break constraints
[ "disble", "the", "sleeping", "during", "interactions", "because", "sleep", "will", "break", "constraints" ]
470c710f96e9aa5e7c0957378a2959bf3f100c8b
https://github.com/wmurphyrd/aframe-physics-extras/blob/470c710f96e9aa5e7c0957378a2959bf3f100c8b/src/physics-sleepy.js#L55-L61
40,777
koajs/trace
index.js
dispatch
function dispatch(context, event, args) { var date = new Date() for (var i = 0; i < listeners.length; i++) listeners[i](context, event, date, args) }
javascript
function dispatch(context, event, args) { var date = new Date() for (var i = 0; i < listeners.length; i++) listeners[i](context, event, date, args) }
[ "function", "dispatch", "(", "context", ",", "event", ",", "args", ")", "{", "var", "date", "=", "new", "Date", "(", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "listeners", ".", "length", ";", "i", "++", ")", "listeners", "[", "i", "]", "(", "context", ",", "event", ",", "date", ",", "args", ")", "}" ]
dispatch an event to all listeners
[ "dispatch", "an", "event", "to", "all", "listeners" ]
27cfae8bc7f1389124ffae37bd0f0d9a5506956f
https://github.com/koajs/trace/blob/27cfae8bc7f1389124ffae37bd0f0d9a5506956f/index.js#L60-L64
40,778
louisbl/cordova-plugin-gpslocation
www/GPSLocation.js
function (successCallback, errorCallback, options) { argscheck.checkArgs('fFO', 'GPSLocation.getCurrentPosition', arguments); options = parseParameters(options); var id = utils.createUUID(); // Tell device to get a position ASAP, and also retrieve a reference to the timeout timer generated in getCurrentPosition timers[id] = GPSLocation.getCurrentPosition(successCallback, errorCallback, options); var fail = function (e) { clearTimeout(timers[id].timer); var err = new PositionError(e.code, e.message); if (errorCallback) { errorCallback(err); } }; var win = function (p) { clearTimeout(timers[id].timer); if (options.timeout !== Infinity) { timers[id].timer = createTimeout(fail, options.timeout); } var pos = new Position({ latitude: p.latitude, longitude: p.longitude, altitude: p.altitude, accuracy: p.accuracy, heading: p.heading, velocity: p.velocity, altitudeAccuracy: p.altitudeAccuracy }, (p.timestamp === undefined ? new Date() : ((p.timestamp instanceof Date) ? p.timestamp : new Date(p.timestamp)))); GPSLocation.lastPosition = pos; successCallback(pos); }; exec(win, fail, "GPSLocation", "addWatch", [id]); return id; }
javascript
function (successCallback, errorCallback, options) { argscheck.checkArgs('fFO', 'GPSLocation.getCurrentPosition', arguments); options = parseParameters(options); var id = utils.createUUID(); // Tell device to get a position ASAP, and also retrieve a reference to the timeout timer generated in getCurrentPosition timers[id] = GPSLocation.getCurrentPosition(successCallback, errorCallback, options); var fail = function (e) { clearTimeout(timers[id].timer); var err = new PositionError(e.code, e.message); if (errorCallback) { errorCallback(err); } }; var win = function (p) { clearTimeout(timers[id].timer); if (options.timeout !== Infinity) { timers[id].timer = createTimeout(fail, options.timeout); } var pos = new Position({ latitude: p.latitude, longitude: p.longitude, altitude: p.altitude, accuracy: p.accuracy, heading: p.heading, velocity: p.velocity, altitudeAccuracy: p.altitudeAccuracy }, (p.timestamp === undefined ? new Date() : ((p.timestamp instanceof Date) ? p.timestamp : new Date(p.timestamp)))); GPSLocation.lastPosition = pos; successCallback(pos); }; exec(win, fail, "GPSLocation", "addWatch", [id]); return id; }
[ "function", "(", "successCallback", ",", "errorCallback", ",", "options", ")", "{", "argscheck", ".", "checkArgs", "(", "'fFO'", ",", "'GPSLocation.getCurrentPosition'", ",", "arguments", ")", ";", "options", "=", "parseParameters", "(", "options", ")", ";", "var", "id", "=", "utils", ".", "createUUID", "(", ")", ";", "// Tell device to get a position ASAP, and also retrieve a reference to the timeout timer generated in getCurrentPosition", "timers", "[", "id", "]", "=", "GPSLocation", ".", "getCurrentPosition", "(", "successCallback", ",", "errorCallback", ",", "options", ")", ";", "var", "fail", "=", "function", "(", "e", ")", "{", "clearTimeout", "(", "timers", "[", "id", "]", ".", "timer", ")", ";", "var", "err", "=", "new", "PositionError", "(", "e", ".", "code", ",", "e", ".", "message", ")", ";", "if", "(", "errorCallback", ")", "{", "errorCallback", "(", "err", ")", ";", "}", "}", ";", "var", "win", "=", "function", "(", "p", ")", "{", "clearTimeout", "(", "timers", "[", "id", "]", ".", "timer", ")", ";", "if", "(", "options", ".", "timeout", "!==", "Infinity", ")", "{", "timers", "[", "id", "]", ".", "timer", "=", "createTimeout", "(", "fail", ",", "options", ".", "timeout", ")", ";", "}", "var", "pos", "=", "new", "Position", "(", "{", "latitude", ":", "p", ".", "latitude", ",", "longitude", ":", "p", ".", "longitude", ",", "altitude", ":", "p", ".", "altitude", ",", "accuracy", ":", "p", ".", "accuracy", ",", "heading", ":", "p", ".", "heading", ",", "velocity", ":", "p", ".", "velocity", ",", "altitudeAccuracy", ":", "p", ".", "altitudeAccuracy", "}", ",", "(", "p", ".", "timestamp", "===", "undefined", "?", "new", "Date", "(", ")", ":", "(", "(", "p", ".", "timestamp", "instanceof", "Date", ")", "?", "p", ".", "timestamp", ":", "new", "Date", "(", "p", ".", "timestamp", ")", ")", ")", ")", ";", "GPSLocation", ".", "lastPosition", "=", "pos", ";", "successCallback", "(", "pos", ")", ";", "}", ";", "exec", "(", "win", ",", "fail", ",", "\"GPSLocation\"", ",", "\"addWatch\"", ",", "[", "id", "]", ")", ";", "return", "id", ";", "}" ]
Asynchronously watches the geolocation for changes to geolocation. When a change occurs, the successCallback is called with the new location. @param {Function} successCallback The function to call each time the location data is available @param {Function} errorCallback The function to call when there is an error getting the location data. (OPTIONAL) @param {PositionOptions} options The options for getting the location data such as frequency. (OPTIONAL) @return String The watch id that must be passed to #clearWatch to stop watching.
[ "Asynchronously", "watches", "the", "geolocation", "for", "changes", "to", "geolocation", ".", "When", "a", "change", "occurs", "the", "successCallback", "is", "called", "with", "the", "new", "location", "." ]
03b1b149b274aac863e8c1d69c104c99eb577a84
https://github.com/louisbl/cordova-plugin-gpslocation/blob/03b1b149b274aac863e8c1d69c104c99eb577a84/www/GPSLocation.js#L150-L188
40,779
ajgarn/CanvasImageUploader
canvas-image-uploader.js
base64toBlob
function base64toBlob(base64Data, contentType, sliceSize) { contentType = contentType || ''; sliceSize = sliceSize || 512; var byteCharacters = atob(base64Data); var byteArrays = []; for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) { var slice = byteCharacters.slice(offset, offset + sliceSize); var byteNumbers = new Array(slice.length); for (var i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } var byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } return new Blob(byteArrays, {type: contentType}); }
javascript
function base64toBlob(base64Data, contentType, sliceSize) { contentType = contentType || ''; sliceSize = sliceSize || 512; var byteCharacters = atob(base64Data); var byteArrays = []; for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) { var slice = byteCharacters.slice(offset, offset + sliceSize); var byteNumbers = new Array(slice.length); for (var i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } var byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } return new Blob(byteArrays, {type: contentType}); }
[ "function", "base64toBlob", "(", "base64Data", ",", "contentType", ",", "sliceSize", ")", "{", "contentType", "=", "contentType", "||", "''", ";", "sliceSize", "=", "sliceSize", "||", "512", ";", "var", "byteCharacters", "=", "atob", "(", "base64Data", ")", ";", "var", "byteArrays", "=", "[", "]", ";", "for", "(", "var", "offset", "=", "0", ";", "offset", "<", "byteCharacters", ".", "length", ";", "offset", "+=", "sliceSize", ")", "{", "var", "slice", "=", "byteCharacters", ".", "slice", "(", "offset", ",", "offset", "+", "sliceSize", ")", ";", "var", "byteNumbers", "=", "new", "Array", "(", "slice", ".", "length", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "slice", ".", "length", ";", "i", "++", ")", "{", "byteNumbers", "[", "i", "]", "=", "slice", ".", "charCodeAt", "(", "i", ")", ";", "}", "var", "byteArray", "=", "new", "Uint8Array", "(", "byteNumbers", ")", ";", "byteArrays", ".", "push", "(", "byteArray", ")", ";", "}", "return", "new", "Blob", "(", "byteArrays", ",", "{", "type", ":", "contentType", "}", ")", ";", "}" ]
Converts a base64 string to byte array.
[ "Converts", "a", "base64", "string", "to", "byte", "array", "." ]
c12ee96cb2757b39c6463a11c85f075657e829f8
https://github.com/ajgarn/CanvasImageUploader/blob/c12ee96cb2757b39c6463a11c85f075657e829f8/canvas-image-uploader.js#L40-L58
40,780
ajgarn/CanvasImageUploader
canvas-image-uploader.js
function(file, $canvas, callback) { this.newImage(); if (!file) return; var reader = new FileReader(); reader.onload = function (fileReaderEvent) { image.onload = function () { readImageToCanvasOnLoad(this, $canvas, callback); }; image.src = fileReaderEvent.target.result; // The URL from FileReader }; reader.readAsDataURL(file); }
javascript
function(file, $canvas, callback) { this.newImage(); if (!file) return; var reader = new FileReader(); reader.onload = function (fileReaderEvent) { image.onload = function () { readImageToCanvasOnLoad(this, $canvas, callback); }; image.src = fileReaderEvent.target.result; // The URL from FileReader }; reader.readAsDataURL(file); }
[ "function", "(", "file", ",", "$canvas", ",", "callback", ")", "{", "this", ".", "newImage", "(", ")", ";", "if", "(", "!", "file", ")", "return", ";", "var", "reader", "=", "new", "FileReader", "(", ")", ";", "reader", ".", "onload", "=", "function", "(", "fileReaderEvent", ")", "{", "image", ".", "onload", "=", "function", "(", ")", "{", "readImageToCanvasOnLoad", "(", "this", ",", "$canvas", ",", "callback", ")", ";", "}", ";", "image", ".", "src", "=", "fileReaderEvent", ".", "target", ".", "result", ";", "// The URL from FileReader", "}", ";", "reader", ".", "readAsDataURL", "(", "file", ")", ";", "}" ]
Draw an image from a file on a canvas. @param file The uploaded file. @param $canvas The canvas (jQuery) object to draw on. @param callback Function that is called when the operation has finished.
[ "Draw", "an", "image", "from", "a", "file", "on", "a", "canvas", "." ]
c12ee96cb2757b39c6463a11c85f075657e829f8
https://github.com/ajgarn/CanvasImageUploader/blob/c12ee96cb2757b39c6463a11c85f075657e829f8/canvas-image-uploader.js#L206-L218
40,781
forty2/hap-client
src/lib/encryption.js
encryptAndSeal
function encryptAndSeal(plainText, AAD, nonce, key) { const cipherText = Sodium .crypto_stream_chacha20_xor_ic(plainText, nonce, 1, key); const hmac = computePoly1305(cipherText, AAD, nonce, key); return [ cipherText, hmac ]; }
javascript
function encryptAndSeal(plainText, AAD, nonce, key) { const cipherText = Sodium .crypto_stream_chacha20_xor_ic(plainText, nonce, 1, key); const hmac = computePoly1305(cipherText, AAD, nonce, key); return [ cipherText, hmac ]; }
[ "function", "encryptAndSeal", "(", "plainText", ",", "AAD", ",", "nonce", ",", "key", ")", "{", "const", "cipherText", "=", "Sodium", ".", "crypto_stream_chacha20_xor_ic", "(", "plainText", ",", "nonce", ",", "1", ",", "key", ")", ";", "const", "hmac", "=", "computePoly1305", "(", "cipherText", ",", "AAD", ",", "nonce", ",", "key", ")", ";", "return", "[", "cipherText", ",", "hmac", "]", ";", "}" ]
See above about calling directly into libsodium.
[ "See", "above", "about", "calling", "directly", "into", "libsodium", "." ]
2e66a27462755759bdd28d574166bfd07b4a8665
https://github.com/forty2/hap-client/blob/2e66a27462755759bdd28d574166bfd07b4a8665/src/lib/encryption.js#L51-L60
40,782
webdriverio/webdriverrtc
lib/browser/url.js
function (param1, param2, param3) { var pc = new OriginalRTCPeerConnection(param1, param2, param3); window.webdriverRTCPeerConnectionBucket = pc; return pc; }
javascript
function (param1, param2, param3) { var pc = new OriginalRTCPeerConnection(param1, param2, param3); window.webdriverRTCPeerConnectionBucket = pc; return pc; }
[ "function", "(", "param1", ",", "param2", ",", "param3", ")", "{", "var", "pc", "=", "new", "OriginalRTCPeerConnection", "(", "param1", ",", "param2", ",", "param3", ")", ";", "window", ".", "webdriverRTCPeerConnectionBucket", "=", "pc", ";", "return", "pc", ";", "}" ]
method to masquerade RTCPeerConnection
[ "method", "to", "masquerade", "RTCPeerConnection" ]
dfc6731792c2c9a0d6bfdc4e361244acf46af3fc
https://github.com/webdriverio/webdriverrtc/blob/dfc6731792c2c9a0d6bfdc4e361244acf46af3fc/lib/browser/url.js#L7-L11
40,783
fredriks/cloud-functions-runtime-config
src/index.js
getVariables
function getVariables(configName, variableNames) { return Promise.all(variableNames.map(function(variableName) { return getVariable(configName, variableName); })); }
javascript
function getVariables(configName, variableNames) { return Promise.all(variableNames.map(function(variableName) { return getVariable(configName, variableName); })); }
[ "function", "getVariables", "(", "configName", ",", "variableNames", ")", "{", "return", "Promise", ".", "all", "(", "variableNames", ".", "map", "(", "function", "(", "variableName", ")", "{", "return", "getVariable", "(", "configName", ",", "variableName", ")", ";", "}", ")", ")", ";", "}" ]
runtimeConfig.getVariables @desc Reads a list of runtime config values @param {string} configName The config name of the variables to return @param {Array} variableNames The list of variable names to read @return {Promise} Promise that resolves an array of the variable values
[ "runtimeConfig", ".", "getVariables" ]
272eb48644df13939fcec458656b1f155f1b0f29
https://github.com/fredriks/cloud-functions-runtime-config/blob/272eb48644df13939fcec458656b1f155f1b0f29/src/index.js#L18-L22
40,784
fredriks/cloud-functions-runtime-config
src/index.js
getVariable
function getVariable(configName, variableName) { return new Promise(function(resolve, reject) { auth().then(function(authClient) { const projectId = process.env.GCLOUD_PROJECT; const fullyQualifiedName = 'projects/' + projectId + '/configs/' + configName + '/variables/' + variableName; runtimeConfig.projects.configs.variables.get({ auth: authClient, name: fullyQualifiedName, }, function(err, res) { if (err) { reject(err); return; } const variable = res.data; if (typeof variable.text !== 'undefined') { resolve(variable.text); } else if (typeof variable.value !== 'undefined') { resolve(Buffer.from(variable.value, 'base64').toString()); } else { reject(new Error('Property text or value not defined')); } }); }); }); }
javascript
function getVariable(configName, variableName) { return new Promise(function(resolve, reject) { auth().then(function(authClient) { const projectId = process.env.GCLOUD_PROJECT; const fullyQualifiedName = 'projects/' + projectId + '/configs/' + configName + '/variables/' + variableName; runtimeConfig.projects.configs.variables.get({ auth: authClient, name: fullyQualifiedName, }, function(err, res) { if (err) { reject(err); return; } const variable = res.data; if (typeof variable.text !== 'undefined') { resolve(variable.text); } else if (typeof variable.value !== 'undefined') { resolve(Buffer.from(variable.value, 'base64').toString()); } else { reject(new Error('Property text or value not defined')); } }); }); }); }
[ "function", "getVariable", "(", "configName", ",", "variableName", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "auth", "(", ")", ".", "then", "(", "function", "(", "authClient", ")", "{", "const", "projectId", "=", "process", ".", "env", ".", "GCLOUD_PROJECT", ";", "const", "fullyQualifiedName", "=", "'projects/'", "+", "projectId", "+", "'/configs/'", "+", "configName", "+", "'/variables/'", "+", "variableName", ";", "runtimeConfig", ".", "projects", ".", "configs", ".", "variables", ".", "get", "(", "{", "auth", ":", "authClient", ",", "name", ":", "fullyQualifiedName", ",", "}", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "return", ";", "}", "const", "variable", "=", "res", ".", "data", ";", "if", "(", "typeof", "variable", ".", "text", "!==", "'undefined'", ")", "{", "resolve", "(", "variable", ".", "text", ")", ";", "}", "else", "if", "(", "typeof", "variable", ".", "value", "!==", "'undefined'", ")", "{", "resolve", "(", "Buffer", ".", "from", "(", "variable", ".", "value", ",", "'base64'", ")", ".", "toString", "(", ")", ")", ";", "}", "else", "{", "reject", "(", "new", "Error", "(", "'Property text or value not defined'", ")", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
runtimeConfig.getVariable @desc Reads a runtime config value @param {string} configName The config name of the variable to return @param {string} variableName The variable name of the variable to return @return {Promise} Promise that resolves the variable value
[ "runtimeConfig", ".", "getVariable" ]
272eb48644df13939fcec458656b1f155f1b0f29
https://github.com/fredriks/cloud-functions-runtime-config/blob/272eb48644df13939fcec458656b1f155f1b0f29/src/index.js#L33-L61
40,785
Azure/azure-relay-node
hyco-ws/lib/HybridConnectionWebSocketServer.js
function() { // choose from the sub-protocols if (typeof self.options.handleProtocols == 'function') { var protList = (protocols || '').split(/, */); var callbackCalled = false; self.options.handleProtocols(protList, function(result, protocol) { callbackCalled = true; if (!result) abortConnection(socket, 401, 'Unauthorized'); else completeHybiUpgrade2(protocol); }); if (!callbackCalled) { // the handleProtocols handler never called our callback abortConnection(socket, 501, 'Could not process protocols'); } return; } else { if (typeof protocols !== 'undefined') { completeHybiUpgrade2(protocols.split(/, */)[0]); } else { completeHybiUpgrade2(); } } }
javascript
function() { // choose from the sub-protocols if (typeof self.options.handleProtocols == 'function') { var protList = (protocols || '').split(/, */); var callbackCalled = false; self.options.handleProtocols(protList, function(result, protocol) { callbackCalled = true; if (!result) abortConnection(socket, 401, 'Unauthorized'); else completeHybiUpgrade2(protocol); }); if (!callbackCalled) { // the handleProtocols handler never called our callback abortConnection(socket, 501, 'Could not process protocols'); } return; } else { if (typeof protocols !== 'undefined') { completeHybiUpgrade2(protocols.split(/, */)[0]); } else { completeHybiUpgrade2(); } } }
[ "function", "(", ")", "{", "// choose from the sub-protocols", "if", "(", "typeof", "self", ".", "options", ".", "handleProtocols", "==", "'function'", ")", "{", "var", "protList", "=", "(", "protocols", "||", "''", ")", ".", "split", "(", "/", ", *", "/", ")", ";", "var", "callbackCalled", "=", "false", ";", "self", ".", "options", ".", "handleProtocols", "(", "protList", ",", "function", "(", "result", ",", "protocol", ")", "{", "callbackCalled", "=", "true", ";", "if", "(", "!", "result", ")", "abortConnection", "(", "socket", ",", "401", ",", "'Unauthorized'", ")", ";", "else", "completeHybiUpgrade2", "(", "protocol", ")", ";", "}", ")", ";", "if", "(", "!", "callbackCalled", ")", "{", "// the handleProtocols handler never called our callback", "abortConnection", "(", "socket", ",", "501", ",", "'Could not process protocols'", ")", ";", "}", "return", ";", "}", "else", "{", "if", "(", "typeof", "protocols", "!==", "'undefined'", ")", "{", "completeHybiUpgrade2", "(", "protocols", ".", "split", "(", "/", ", *", "/", ")", "[", "0", "]", ")", ";", "}", "else", "{", "completeHybiUpgrade2", "(", ")", ";", "}", "}", "}" ]
optionally call external protocol selection handler before calling completeHybiUpgrade2
[ "optionally", "call", "external", "protocol", "selection", "handler", "before", "calling", "completeHybiUpgrade2" ]
3c996efc240aa556fa5d17e40fa9ba463a98a8d5
https://github.com/Azure/azure-relay-node/blob/3c996efc240aa556fa5d17e40fa9ba463a98a8d5/hyco-ws/lib/HybridConnectionWebSocketServer.js#L252-L275
40,786
Azure/azure-relay-node
hyco-https/lib/_hyco_errors.js
internalAssert
function internalAssert(condition, message) { if (!condition) { throw new AssertionError({ message, actual: false, expected: true, operator: '==' }); } }
javascript
function internalAssert(condition, message) { if (!condition) { throw new AssertionError({ message, actual: false, expected: true, operator: '==' }); } }
[ "function", "internalAssert", "(", "condition", ",", "message", ")", "{", "if", "(", "!", "condition", ")", "{", "throw", "new", "AssertionError", "(", "{", "message", ",", "actual", ":", "false", ",", "expected", ":", "true", ",", "operator", ":", "'=='", "}", ")", ";", "}", "}" ]
This is defined here instead of using the assert module to avoid a circular dependency. The effect is largely the same.
[ "This", "is", "defined", "here", "instead", "of", "using", "the", "assert", "module", "to", "avoid", "a", "circular", "dependency", ".", "The", "effect", "is", "largely", "the", "same", "." ]
3c996efc240aa556fa5d17e40fa9ba463a98a8d5
https://github.com/Azure/azure-relay-node/blob/3c996efc240aa556fa5d17e40fa9ba463a98a8d5/hyco-https/lib/_hyco_errors.js#L476-L485
40,787
Azure/azure-relay-node
hyco-https/lib/_hyco_errors.js
isStackOverflowError
function isStackOverflowError(err) { if (maxStack_ErrorMessage === undefined) { try { function overflowStack() { overflowStack(); } overflowStack(); } catch (err) { maxStack_ErrorMessage = err.message; maxStack_ErrorName = err.name; } } return err.name === maxStack_ErrorName && err.message === maxStack_ErrorMessage; }
javascript
function isStackOverflowError(err) { if (maxStack_ErrorMessage === undefined) { try { function overflowStack() { overflowStack(); } overflowStack(); } catch (err) { maxStack_ErrorMessage = err.message; maxStack_ErrorName = err.name; } } return err.name === maxStack_ErrorName && err.message === maxStack_ErrorMessage; }
[ "function", "isStackOverflowError", "(", "err", ")", "{", "if", "(", "maxStack_ErrorMessage", "===", "undefined", ")", "{", "try", "{", "function", "overflowStack", "(", ")", "{", "overflowStack", "(", ")", ";", "}", "overflowStack", "(", ")", ";", "}", "catch", "(", "err", ")", "{", "maxStack_ErrorMessage", "=", "err", ".", "message", ";", "maxStack_ErrorName", "=", "err", ".", "name", ";", "}", "}", "return", "err", ".", "name", "===", "maxStack_ErrorName", "&&", "err", ".", "message", "===", "maxStack_ErrorMessage", ";", "}" ]
Returns true if `err.name` and `err.message` are equal to engine-specific values indicating max call stack size has been exceeded. "Maximum call stack size exceeded" in V8. @param {Error} err @returns {boolean}
[ "Returns", "true", "if", "err", ".", "name", "and", "err", ".", "message", "are", "equal", "to", "engine", "-", "specific", "values", "indicating", "max", "call", "stack", "size", "has", "been", "exceeded", ".", "Maximum", "call", "stack", "size", "exceeded", "in", "V8", "." ]
3c996efc240aa556fa5d17e40fa9ba463a98a8d5
https://github.com/Azure/azure-relay-node/blob/3c996efc240aa556fa5d17e40fa9ba463a98a8d5/hyco-https/lib/_hyco_errors.js#L675-L688
40,788
adrianhall/winston-splunk-httplogger
index.js
function (config) { winston.Transport.call(this, config); /** @property {string} name - the name of the transport */ this.name = 'SplunkStreamEvent'; /** @property {string} level - the minimum level to log */ this.level = config.level || 'info'; // Verify that we actually have a splunk object and a token if (!config.splunk || !config.splunk.token) { throw new Error('Invalid Configuration: options.splunk is invalid'); } // If source/sourcetype are mentioned in the splunk object, then store the // defaults in this and delete from the splunk object this.defaultMetadata = { source: 'winston', sourcetype: 'winston-splunk-logger' }; if (config.splunk.source) { this.defaultMetadata.source = config.splunk.source; delete config.splunk.source; } if (config.splunk.sourcetype) { this.defaultMetadata.sourcetype = config.splunk.sourcetype; delete config.splunk.sourcetype; } // This gets around a problem with setting maxBatchCount config.splunk.maxBatchCount = 1; this.server = new SplunkLogger(config.splunk); // Override the default event formatter if (config.splunk.eventFormatter) { this.server.eventFormatter = config.splunk.eventFormatter; } }
javascript
function (config) { winston.Transport.call(this, config); /** @property {string} name - the name of the transport */ this.name = 'SplunkStreamEvent'; /** @property {string} level - the minimum level to log */ this.level = config.level || 'info'; // Verify that we actually have a splunk object and a token if (!config.splunk || !config.splunk.token) { throw new Error('Invalid Configuration: options.splunk is invalid'); } // If source/sourcetype are mentioned in the splunk object, then store the // defaults in this and delete from the splunk object this.defaultMetadata = { source: 'winston', sourcetype: 'winston-splunk-logger' }; if (config.splunk.source) { this.defaultMetadata.source = config.splunk.source; delete config.splunk.source; } if (config.splunk.sourcetype) { this.defaultMetadata.sourcetype = config.splunk.sourcetype; delete config.splunk.sourcetype; } // This gets around a problem with setting maxBatchCount config.splunk.maxBatchCount = 1; this.server = new SplunkLogger(config.splunk); // Override the default event formatter if (config.splunk.eventFormatter) { this.server.eventFormatter = config.splunk.eventFormatter; } }
[ "function", "(", "config", ")", "{", "winston", ".", "Transport", ".", "call", "(", "this", ",", "config", ")", ";", "/** @property {string} name - the name of the transport */", "this", ".", "name", "=", "'SplunkStreamEvent'", ";", "/** @property {string} level - the minimum level to log */", "this", ".", "level", "=", "config", ".", "level", "||", "'info'", ";", "// Verify that we actually have a splunk object and a token", "if", "(", "!", "config", ".", "splunk", "||", "!", "config", ".", "splunk", ".", "token", ")", "{", "throw", "new", "Error", "(", "'Invalid Configuration: options.splunk is invalid'", ")", ";", "}", "// If source/sourcetype are mentioned in the splunk object, then store the", "// defaults in this and delete from the splunk object", "this", ".", "defaultMetadata", "=", "{", "source", ":", "'winston'", ",", "sourcetype", ":", "'winston-splunk-logger'", "}", ";", "if", "(", "config", ".", "splunk", ".", "source", ")", "{", "this", ".", "defaultMetadata", ".", "source", "=", "config", ".", "splunk", ".", "source", ";", "delete", "config", ".", "splunk", ".", "source", ";", "}", "if", "(", "config", ".", "splunk", ".", "sourcetype", ")", "{", "this", ".", "defaultMetadata", ".", "sourcetype", "=", "config", ".", "splunk", ".", "sourcetype", ";", "delete", "config", ".", "splunk", ".", "sourcetype", ";", "}", "// This gets around a problem with setting maxBatchCount", "config", ".", "splunk", ".", "maxBatchCount", "=", "1", ";", "this", ".", "server", "=", "new", "SplunkLogger", "(", "config", ".", "splunk", ")", ";", "// Override the default event formatter", "if", "(", "config", ".", "splunk", ".", "eventFormatter", ")", "{", "this", ".", "server", ".", "eventFormatter", "=", "config", ".", "splunk", ".", "eventFormatter", ";", "}", "}" ]
A class that implements a Winston transport provider for Splunk HTTP Event Collector @param {object} config - Configuration settings for a new Winston transport @param {string} [config.level=info] - the minimum level to log @param {object} config.splunk - the Splunk Logger settings @param {string} config.splunk.token - the Splunk HTTP Event Collector token @param {string} [config.splunk.source=winston] - the source for the events sent to Splunk @param {string} [config.splunk.sourcetype=winston-splunk-logger] - the sourcetype for the events sent to Splunk @param {string} [config.splunk.host=localhost] - the Splunk HTTP Event Collector host @param {number} [config.splunk.maxRetries=0] - How many times to retry the splunk logger @param {number} [config.splunk.port=8088] - the Splunk HTTP Event Collector port @param {string} [config.splunk.path=/services/collector/event/1.0] - URL path to use @param {string} [config.splunk.protocol=https] - the protocol to use @param {string} [config.splunk.url] - URL string to pass to url.parse for the information @param {function} [config.splunk.eventFormatter] - Formats events, returning an event as a string, <code>function(message, severity)</code> @param {string} [config.level=info] - Logging level to use, will show up as the <code>severity</code> field of an event, see [SplunkLogger.levels]{@link SplunkLogger#levels} for common levels. @param {number} [config.batchInterval=0] - Automatically flush events after this many milliseconds. When set to a non-positive value, events will be sent one by one. This setting is ignored when non-positive. @param {number} [config.maxBatchSize=0] - Automatically flush events after the size of queued events exceeds this many bytes. This setting is ignored when non-positive. @param {number} [config.maxBatchCount=1] - Automatically flush events after this many events have been queued. Defaults to flush immediately on sending an event. This setting is ignored when non-positive. @constructor
[ "A", "class", "that", "implements", "a", "Winston", "transport", "provider", "for", "Splunk", "HTTP", "Event", "Collector" ]
58be3091b01f88b3230b2f21d6bdfe4055dd2017
https://github.com/adrianhall/winston-splunk-httplogger/blob/58be3091b01f88b3230b2f21d6bdfe4055dd2017/index.js#L59-L96
40,789
AoDev/css-byebye
lib/css-byebye.js
regexize
function regexize (rulesToRemove) { var rulesRegexes = [] for (var i = 0, l = rulesToRemove.length; i < l; i++) { if (typeof rulesToRemove[i] === 'string') { rulesRegexes.push(new RegExp('^\\s*' + escapeRegExp(rulesToRemove[i]) + '\\s*$')) } else { rulesRegexes.push(rulesToRemove[i]) } } return rulesRegexes }
javascript
function regexize (rulesToRemove) { var rulesRegexes = [] for (var i = 0, l = rulesToRemove.length; i < l; i++) { if (typeof rulesToRemove[i] === 'string') { rulesRegexes.push(new RegExp('^\\s*' + escapeRegExp(rulesToRemove[i]) + '\\s*$')) } else { rulesRegexes.push(rulesToRemove[i]) } } return rulesRegexes }
[ "function", "regexize", "(", "rulesToRemove", ")", "{", "var", "rulesRegexes", "=", "[", "]", "for", "(", "var", "i", "=", "0", ",", "l", "=", "rulesToRemove", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "typeof", "rulesToRemove", "[", "i", "]", "===", "'string'", ")", "{", "rulesRegexes", ".", "push", "(", "new", "RegExp", "(", "'^\\\\s*'", "+", "escapeRegExp", "(", "rulesToRemove", "[", "i", "]", ")", "+", "'\\\\s*$'", ")", ")", "}", "else", "{", "rulesRegexes", ".", "push", "(", "rulesToRemove", "[", "i", "]", ")", "}", "}", "return", "rulesRegexes", "}" ]
Turn strings from rules to remove into a regexp to concat them later @param {Mixed Array} rulesToRemove @return {RegExp Array}
[ "Turn", "strings", "from", "rules", "to", "remove", "into", "a", "regexp", "to", "concat", "them", "later" ]
ff8245ec596fdabd6cce4f5f3e4c36396359329a
https://github.com/AoDev/css-byebye/blob/ff8245ec596fdabd6cce4f5f3e4c36396359329a/lib/css-byebye.js#L21-L31
40,790
AoDev/css-byebye
lib/css-byebye.js
concatRegexes
function concatRegexes (regexes) { var rconcat = '' if (Array.isArray(regexes)) { for (var i = 0, l = regexes.length; i < l; i++) { rconcat += regexes[i].source + '|' } rconcat = rconcat.substr(0, rconcat.length - 1) return new RegExp(rconcat) } }
javascript
function concatRegexes (regexes) { var rconcat = '' if (Array.isArray(regexes)) { for (var i = 0, l = regexes.length; i < l; i++) { rconcat += regexes[i].source + '|' } rconcat = rconcat.substr(0, rconcat.length - 1) return new RegExp(rconcat) } }
[ "function", "concatRegexes", "(", "regexes", ")", "{", "var", "rconcat", "=", "''", "if", "(", "Array", ".", "isArray", "(", "regexes", ")", ")", "{", "for", "(", "var", "i", "=", "0", ",", "l", "=", "regexes", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "rconcat", "+=", "regexes", "[", "i", "]", ".", "source", "+", "'|'", "}", "rconcat", "=", "rconcat", ".", "substr", "(", "0", ",", "rconcat", ".", "length", "-", "1", ")", "return", "new", "RegExp", "(", "rconcat", ")", "}", "}" ]
Concat various regular expressions into one @param {RegExp Array} regexes @return {RegExp} concatanated regexp
[ "Concat", "various", "regular", "expressions", "into", "one" ]
ff8245ec596fdabd6cce4f5f3e4c36396359329a
https://github.com/AoDev/css-byebye/blob/ff8245ec596fdabd6cce4f5f3e4c36396359329a/lib/css-byebye.js#L38-L50
40,791
kimkha/loopback3-xTotalCount
index.js
function (ctx, next) { var filter; if (ctx.args && ctx.args.filter) { filter = ctx.args.filter.where; } if (!ctx.res._headerSent) { this.count(filter, function (err, count) { ctx.res.set('X-Total-Count', count); next(); }); } else { next(); } }
javascript
function (ctx, next) { var filter; if (ctx.args && ctx.args.filter) { filter = ctx.args.filter.where; } if (!ctx.res._headerSent) { this.count(filter, function (err, count) { ctx.res.set('X-Total-Count', count); next(); }); } else { next(); } }
[ "function", "(", "ctx", ",", "next", ")", "{", "var", "filter", ";", "if", "(", "ctx", ".", "args", "&&", "ctx", ".", "args", ".", "filter", ")", "{", "filter", "=", "ctx", ".", "args", ".", "filter", ".", "where", ";", "}", "if", "(", "!", "ctx", ".", "res", ".", "_headerSent", ")", "{", "this", ".", "count", "(", "filter", ",", "function", "(", "err", ",", "count", ")", "{", "ctx", ".", "res", ".", "set", "(", "'X-Total-Count'", ",", "count", ")", ";", "next", "(", ")", ";", "}", ")", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}" ]
Set X-Total-Count for all search requests
[ "Set", "X", "-", "Total", "-", "Count", "for", "all", "search", "requests" ]
61d45d74b0e767c6897859d347bc557a13c436cb
https://github.com/kimkha/loopback3-xTotalCount/blob/61d45d74b0e767c6897859d347bc557a13c436cb/index.js#L5-L19
40,792
bbc/slayer
lib/core.js
configureFilters
function configureFilters(config){ if (typeof config.minPeakHeight !== 'number' || isNaN(config.minPeakHeight)){ throw new TypeError('config.minPeakHeight should be a numeric value. Was: ' + String(config.minPeakHeight)); } this.filters.push(function minHeightFilter(item){ return item >= config.minPeakHeight; }); }
javascript
function configureFilters(config){ if (typeof config.minPeakHeight !== 'number' || isNaN(config.minPeakHeight)){ throw new TypeError('config.minPeakHeight should be a numeric value. Was: ' + String(config.minPeakHeight)); } this.filters.push(function minHeightFilter(item){ return item >= config.minPeakHeight; }); }
[ "function", "configureFilters", "(", "config", ")", "{", "if", "(", "typeof", "config", ".", "minPeakHeight", "!==", "'number'", "||", "isNaN", "(", "config", ".", "minPeakHeight", ")", ")", "{", "throw", "new", "TypeError", "(", "'config.minPeakHeight should be a numeric value. Was: '", "+", "String", "(", "config", ".", "minPeakHeight", ")", ")", ";", "}", "this", ".", "filters", ".", "push", "(", "function", "minHeightFilter", "(", "item", ")", "{", "return", "item", ">=", "config", ".", "minPeakHeight", ";", "}", ")", ";", "}" ]
Configures the internal filters of a slayer instance
[ "Configures", "the", "internal", "filters", "of", "a", "slayer", "instance" ]
4b0cdc5080f46f5940c89c081dbad16e2be4e021
https://github.com/bbc/slayer/blob/4b0cdc5080f46f5940c89c081dbad16e2be4e021/lib/core.js#L72-L80
40,793
bbc/slayer
lib/core.js
filterDataItem
function filterDataItem(item){ return this.filters.some(function(filter){ return filter.call(null, item); }) ? item : null; }
javascript
function filterDataItem(item){ return this.filters.some(function(filter){ return filter.call(null, item); }) ? item : null; }
[ "function", "filterDataItem", "(", "item", ")", "{", "return", "this", ".", "filters", ".", "some", "(", "function", "(", "filter", ")", "{", "return", "filter", ".", "call", "(", "null", ",", "item", ")", ";", "}", ")", "?", "item", ":", "null", ";", "}" ]
Filters out any time series value which does not satisfy the filter. @param item {Number} @returns {Boolean}
[ "Filters", "out", "any", "time", "series", "value", "which", "does", "not", "satisfy", "the", "filter", "." ]
4b0cdc5080f46f5940c89c081dbad16e2be4e021
https://github.com/bbc/slayer/blob/4b0cdc5080f46f5940c89c081dbad16e2be4e021/lib/core.js#L87-L91
40,794
medz/webpack-laravel-mix-manifest
src/main.js
WebpackLaravelMixManifest
function WebpackLaravelMixManifest({ filename = null, transform = null } = {}) { this.filename = filename ? filename : 'mix-manifest.json'; this.transform = transform instanceof Function ? transform : require('./transform'); }
javascript
function WebpackLaravelMixManifest({ filename = null, transform = null } = {}) { this.filename = filename ? filename : 'mix-manifest.json'; this.transform = transform instanceof Function ? transform : require('./transform'); }
[ "function", "WebpackLaravelMixManifest", "(", "{", "filename", "=", "null", ",", "transform", "=", "null", "}", "=", "{", "}", ")", "{", "this", ".", "filename", "=", "filename", "?", "filename", ":", "'mix-manifest.json'", ";", "this", ".", "transform", "=", "transform", "instanceof", "Function", "?", "transform", ":", "require", "(", "'./transform'", ")", ";", "}" ]
Create the plugin class. @param { filename: string|null, transform: Function|null } options
[ "Create", "the", "plugin", "class", "." ]
aaad90ebb30e8697dccf8ed2ae537af85fc635f4
https://github.com/medz/webpack-laravel-mix-manifest/blob/aaad90ebb30e8697dccf8ed2ae537af85fc635f4/src/main.js#L5-L8
40,795
bbc/slayer
lib/readers/_common.js
objectMapper
function objectMapper(originalData, y, i){ return this.getItem({ x: this.getValueX(originalData[i], i), y: y }, originalData[i], i); }
javascript
function objectMapper(originalData, y, i){ return this.getItem({ x: this.getValueX(originalData[i], i), y: y }, originalData[i], i); }
[ "function", "objectMapper", "(", "originalData", ",", "y", ",", "i", ")", "{", "return", "this", ".", "getItem", "(", "{", "x", ":", "this", ".", "getValueX", "(", "originalData", "[", "i", "]", ",", "i", ")", ",", "y", ":", "y", "}", ",", "originalData", "[", "i", "]", ",", "i", ")", ";", "}" ]
Remaps an initial item to a common working structure. It is intended to be bound to a slayer instance. @this {Slayer} @param originalData {Array} The original array of data @param y {Number} The value number detected as being a spike @param i {Number} The index location of `y` in `originalData` @returns {{x: *, y: Number}}
[ "Remaps", "an", "initial", "item", "to", "a", "common", "working", "structure", "." ]
4b0cdc5080f46f5940c89c081dbad16e2be4e021
https://github.com/bbc/slayer/blob/4b0cdc5080f46f5940c89c081dbad16e2be4e021/lib/readers/_common.js#L35-L40
40,796
andywer/postcss-debug
webdebugger/build/app.js
function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; process.env.NODE_ENV !== 'production' ? warning(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0; } return undefined; }
javascript
function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; process.env.NODE_ENV !== 'production' ? warning(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0; } return undefined; }
[ "function", "(", ")", "{", "if", "(", "!", "specialPropKeyWarningShown", ")", "{", "specialPropKeyWarningShown", "=", "true", ";", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", "?", "warning", "(", "false", ",", "'%s: `key` is not a prop. Trying to access it will result '", "+", "'in `undefined` being returned. If you need to access the same '", "+", "'value within the child component, you should pass it as a different '", "+", "'prop. (https://fb.me/react-special-props)'", ",", "displayName", ")", ":", "void", "0", ";", "}", "return", "undefined", ";", "}" ]
Create dummy `key` and `ref` property to `props` to warn users against its use
[ "Create", "dummy", "key", "and", "ref", "property", "to", "props", "to", "warn", "users", "against", "its", "use" ]
e245354e057b230c008f5b4a72096d134c2fe8cf
https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L1080-L1086
40,797
andywer/postcss-debug
webdebugger/build/app.js
function (transaction) { if (this._pendingElement != null) { ReactReconciler.receiveComponent(this, this._pendingElement, transaction, this._context); } else if (this._pendingStateQueue !== null || this._pendingForceUpdate) { this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context); } else { this._updateBatchNumber = null; } }
javascript
function (transaction) { if (this._pendingElement != null) { ReactReconciler.receiveComponent(this, this._pendingElement, transaction, this._context); } else if (this._pendingStateQueue !== null || this._pendingForceUpdate) { this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context); } else { this._updateBatchNumber = null; } }
[ "function", "(", "transaction", ")", "{", "if", "(", "this", ".", "_pendingElement", "!=", "null", ")", "{", "ReactReconciler", ".", "receiveComponent", "(", "this", ",", "this", ".", "_pendingElement", ",", "transaction", ",", "this", ".", "_context", ")", ";", "}", "else", "if", "(", "this", ".", "_pendingStateQueue", "!==", "null", "||", "this", ".", "_pendingForceUpdate", ")", "{", "this", ".", "updateComponent", "(", "transaction", ",", "this", ".", "_currentElement", ",", "this", ".", "_currentElement", ",", "this", ".", "_context", ",", "this", ".", "_context", ")", ";", "}", "else", "{", "this", ".", "_updateBatchNumber", "=", "null", ";", "}", "}" ]
If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate` is set, update the component. @param {ReactReconcileTransaction} transaction @internal
[ "If", "any", "of", "_pendingElement", "_pendingStateQueue", "or", "_pendingForceUpdate", "is", "set", "update", "the", "component", "." ]
e245354e057b230c008f5b4a72096d134c2fe8cf
https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L6091-L6099
40,798
andywer/postcss-debug
webdebugger/build/app.js
function (inst, registrationName) { var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } var bankForRegistrationName = listenerBank[registrationName]; // TODO: This should never be null -- when is it? if (bankForRegistrationName) { var key = getDictionaryKey(inst); delete bankForRegistrationName[key]; } }
javascript
function (inst, registrationName) { var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } var bankForRegistrationName = listenerBank[registrationName]; // TODO: This should never be null -- when is it? if (bankForRegistrationName) { var key = getDictionaryKey(inst); delete bankForRegistrationName[key]; } }
[ "function", "(", "inst", ",", "registrationName", ")", "{", "var", "PluginModule", "=", "EventPluginRegistry", ".", "registrationNameModules", "[", "registrationName", "]", ";", "if", "(", "PluginModule", "&&", "PluginModule", ".", "willDeleteListener", ")", "{", "PluginModule", ".", "willDeleteListener", "(", "inst", ",", "registrationName", ")", ";", "}", "var", "bankForRegistrationName", "=", "listenerBank", "[", "registrationName", "]", ";", "// TODO: This should never be null -- when is it?", "if", "(", "bankForRegistrationName", ")", "{", "var", "key", "=", "getDictionaryKey", "(", "inst", ")", ";", "delete", "bankForRegistrationName", "[", "key", "]", ";", "}", "}" ]
Deletes a listener from the registration bank. @param {object} inst The instance, which is the source of events. @param {string} registrationName Name of listener (e.g. `onClick`).
[ "Deletes", "a", "listener", "from", "the", "registration", "bank", "." ]
e245354e057b230c008f5b4a72096d134c2fe8cf
https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L9477-L9489
40,799
andywer/postcss-debug
webdebugger/build/app.js
function (inst) { var key = getDictionaryKey(inst); for (var registrationName in listenerBank) { if (!listenerBank.hasOwnProperty(registrationName)) { continue; } if (!listenerBank[registrationName][key]) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } delete listenerBank[registrationName][key]; } }
javascript
function (inst) { var key = getDictionaryKey(inst); for (var registrationName in listenerBank) { if (!listenerBank.hasOwnProperty(registrationName)) { continue; } if (!listenerBank[registrationName][key]) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } delete listenerBank[registrationName][key]; } }
[ "function", "(", "inst", ")", "{", "var", "key", "=", "getDictionaryKey", "(", "inst", ")", ";", "for", "(", "var", "registrationName", "in", "listenerBank", ")", "{", "if", "(", "!", "listenerBank", ".", "hasOwnProperty", "(", "registrationName", ")", ")", "{", "continue", ";", "}", "if", "(", "!", "listenerBank", "[", "registrationName", "]", "[", "key", "]", ")", "{", "continue", ";", "}", "var", "PluginModule", "=", "EventPluginRegistry", ".", "registrationNameModules", "[", "registrationName", "]", ";", "if", "(", "PluginModule", "&&", "PluginModule", ".", "willDeleteListener", ")", "{", "PluginModule", ".", "willDeleteListener", "(", "inst", ",", "registrationName", ")", ";", "}", "delete", "listenerBank", "[", "registrationName", "]", "[", "key", "]", ";", "}", "}" ]
Deletes all listeners for the DOM element with the supplied ID. @param {object} inst The instance, which is the source of events.
[ "Deletes", "all", "listeners", "for", "the", "DOM", "element", "with", "the", "supplied", "ID", "." ]
e245354e057b230c008f5b4a72096d134c2fe8cf
https://github.com/andywer/postcss-debug/blob/e245354e057b230c008f5b4a72096d134c2fe8cf/webdebugger/build/app.js#L9496-L9514