id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
46,500
rask/gulp-yaml-data
index.js
function (file, enc, cb) { var yaml_files = options.src; if (typeof yaml_files === 'string') { yaml_files = [yaml_files]; } var yaml_data = {}; // Read all files in order, and override if later files contain same values. for (var i = 0; i < yaml_files.length; i++) { yaml_data = Object.assign(yaml_data, readYamlFile(yaml_files[i])); } var current_data = file[options.property]; var new_data = null; // Merge with possible previous data. if (options.override) { new_data = Object.assign(current_data, yaml_data); } else { new_data = Object.assign(yaml_data, current_data); } file[options.property] = new_data; cb(null, file); }
javascript
function (file, enc, cb) { var yaml_files = options.src; if (typeof yaml_files === 'string') { yaml_files = [yaml_files]; } var yaml_data = {}; // Read all files in order, and override if later files contain same values. for (var i = 0; i < yaml_files.length; i++) { yaml_data = Object.assign(yaml_data, readYamlFile(yaml_files[i])); } var current_data = file[options.property]; var new_data = null; // Merge with possible previous data. if (options.override) { new_data = Object.assign(current_data, yaml_data); } else { new_data = Object.assign(yaml_data, current_data); } file[options.property] = new_data; cb(null, file); }
[ "function", "(", "file", ",", "enc", ",", "cb", ")", "{", "var", "yaml_files", "=", "options", ".", "src", ";", "if", "(", "typeof", "yaml_files", "===", "'string'", ")", "{", "yaml_files", "=", "[", "yaml_files", "]", ";", "}", "var", "yaml_data", "=", "{", "}", ";", "// Read all files in order, and override if later files contain same values.", "for", "(", "var", "i", "=", "0", ";", "i", "<", "yaml_files", ".", "length", ";", "i", "++", ")", "{", "yaml_data", "=", "Object", ".", "assign", "(", "yaml_data", ",", "readYamlFile", "(", "yaml_files", "[", "i", "]", ")", ")", ";", "}", "var", "current_data", "=", "file", "[", "options", ".", "property", "]", ";", "var", "new_data", "=", "null", ";", "// Merge with possible previous data.", "if", "(", "options", ".", "override", ")", "{", "new_data", "=", "Object", ".", "assign", "(", "current_data", ",", "yaml_data", ")", ";", "}", "else", "{", "new_data", "=", "Object", ".", "assign", "(", "yaml_data", ",", "current_data", ")", ";", "}", "file", "[", "options", ".", "property", "]", "=", "new_data", ";", "cb", "(", "null", ",", "file", ")", ";", "}" ]
Transform current stream to include a YAML data file.
[ "Transform", "current", "stream", "to", "include", "a", "YAML", "data", "file", "." ]
c4a86a4ec4bed2f622a2267f23fdcdf58033ce1c
https://github.com/rask/gulp-yaml-data/blob/c4a86a4ec4bed2f622a2267f23fdcdf58033ce1c/index.js#L40-L67
46,501
looeee/npm-three-app
demo/module-import/js/vendor/GLTFLoader.js
GLTFDracoMeshCompressionExtension
function GLTFDracoMeshCompressionExtension( json, dracoLoader ) { if ( !dracoLoader ) { throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' ); } this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION; this.json = json; this.dracoLoader = dracoLoader; THREE.DRACOLoader.getDecoderModule(); }
javascript
function GLTFDracoMeshCompressionExtension( json, dracoLoader ) { if ( !dracoLoader ) { throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' ); } this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION; this.json = json; this.dracoLoader = dracoLoader; THREE.DRACOLoader.getDecoderModule(); }
[ "function", "GLTFDracoMeshCompressionExtension", "(", "json", ",", "dracoLoader", ")", "{", "if", "(", "!", "dracoLoader", ")", "{", "throw", "new", "Error", "(", "'THREE.GLTFLoader: No DRACOLoader instance provided.'", ")", ";", "}", "this", ".", "name", "=", "EXTENSIONS", ".", "KHR_DRACO_MESH_COMPRESSION", ";", "this", ".", "json", "=", "json", ";", "this", ".", "dracoLoader", "=", "dracoLoader", ";", "THREE", ".", "DRACOLoader", ".", "getDecoderModule", "(", ")", ";", "}" ]
DRACO Mesh Compression Extension Specification: https://github.com/KhronosGroup/glTF/pull/874
[ "DRACO", "Mesh", "Compression", "Extension" ]
439be8d3119bf0f00a7790f77a57ec76fc126580
https://github.com/looeee/npm-three-app/blob/439be8d3119bf0f00a7790f77a57ec76fc126580/demo/module-import/js/vendor/GLTFLoader.js#L501-L514
46,502
fin-hypergrid/rectangular
index.js
function(iteratee, context) { context = context || this; for (var x = this.origin.x, x2 = this.corner.x; x < x2; x++) { for (var y = this.origin.y, y2 = this.corner.y; y < y2; y++) { iteratee.call(context, x, y); } } }
javascript
function(iteratee, context) { context = context || this; for (var x = this.origin.x, x2 = this.corner.x; x < x2; x++) { for (var y = this.origin.y, y2 = this.corner.y; y < y2; y++) { iteratee.call(context, x, y); } } }
[ "function", "(", "iteratee", ",", "context", ")", "{", "context", "=", "context", "||", "this", ";", "for", "(", "var", "x", "=", "this", ".", "origin", ".", "x", ",", "x2", "=", "this", ".", "corner", ".", "x", ";", "x", "<", "x2", ";", "x", "++", ")", "{", "for", "(", "var", "y", "=", "this", ".", "origin", ".", "y", ",", "y2", "=", "this", ".", "corner", ".", "y", ";", "y", "<", "y2", ";", "y", "++", ")", "{", "iteratee", ".", "call", "(", "context", ",", "x", ",", "y", ")", ";", "}", "}", "}" ]
iterate over all points within this rect, invoking `iteratee` for each. @param {function(number,number)} iteratee - Function to call for each point. Bound to `context` when given; otherwise it is bound to this rect. Each invocation of `iteratee` is called with two arguments: the horizontal and vertical coordinates of the point. @param {object} [context=this] - Context to bind to `iteratee` (when not `this`). @memberOf Rectangle.prototype
[ "iterate", "over", "all", "points", "within", "this", "rect", "invoking", "iteratee", "for", "each", "." ]
da7517823973c847ddb18c4ba4c0d25f8e55f52f
https://github.com/fin-hypergrid/rectangular/blob/da7517823973c847ddb18c4ba4c0d25f8e55f52f/index.js#L493-L500
46,503
Yomguithereal/dolman
index.js
makeRouter
function makeRouter() { // Solving arguments var args = [].slice.call(arguments); var beforeMiddlewares = args.slice(0, -1), routes = args[args.length - 1]; var router = express.Router(); routes.forEach(function(route) { if (!route.url) throw Error('dolman.router: one route has no url: ' + util.inspect(route)); if (!route.action) throw Error('dolman.router: the route for url ' + route.url + ' has no action.'); var actions = [].concat(route.action); // Storing the route routesMap.set(actions[0], route); // Applying before middlewares var routeMiddlewares = beforeMiddlewares.slice(); // Validation if (route.validate) routeMiddlewares.push(middlewares.validate(types, route.validate)); // Mask if (route.mask) routeMiddlewares.push(middlewares.mask(route.mask)); // RAM cache if (route.cache) routeMiddlewares.push(middlewares.cache(cache, route.cache)); // HTTP cache if (route.httpCache) routeMiddlewares.push(middlewares.httpCache(route.httpCache)); // Determining the method var methods = [].concat(route.method || route.methods || 'ALL'); methods.forEach(function(method) { router[method.toLowerCase()].apply( router, [route.url] .concat(routeMiddlewares) .concat(actions) ); }); }); return router; }
javascript
function makeRouter() { // Solving arguments var args = [].slice.call(arguments); var beforeMiddlewares = args.slice(0, -1), routes = args[args.length - 1]; var router = express.Router(); routes.forEach(function(route) { if (!route.url) throw Error('dolman.router: one route has no url: ' + util.inspect(route)); if (!route.action) throw Error('dolman.router: the route for url ' + route.url + ' has no action.'); var actions = [].concat(route.action); // Storing the route routesMap.set(actions[0], route); // Applying before middlewares var routeMiddlewares = beforeMiddlewares.slice(); // Validation if (route.validate) routeMiddlewares.push(middlewares.validate(types, route.validate)); // Mask if (route.mask) routeMiddlewares.push(middlewares.mask(route.mask)); // RAM cache if (route.cache) routeMiddlewares.push(middlewares.cache(cache, route.cache)); // HTTP cache if (route.httpCache) routeMiddlewares.push(middlewares.httpCache(route.httpCache)); // Determining the method var methods = [].concat(route.method || route.methods || 'ALL'); methods.forEach(function(method) { router[method.toLowerCase()].apply( router, [route.url] .concat(routeMiddlewares) .concat(actions) ); }); }); return router; }
[ "function", "makeRouter", "(", ")", "{", "// Solving arguments", "var", "args", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ")", ";", "var", "beforeMiddlewares", "=", "args", ".", "slice", "(", "0", ",", "-", "1", ")", ",", "routes", "=", "args", "[", "args", ".", "length", "-", "1", "]", ";", "var", "router", "=", "express", ".", "Router", "(", ")", ";", "routes", ".", "forEach", "(", "function", "(", "route", ")", "{", "if", "(", "!", "route", ".", "url", ")", "throw", "Error", "(", "'dolman.router: one route has no url: '", "+", "util", ".", "inspect", "(", "route", ")", ")", ";", "if", "(", "!", "route", ".", "action", ")", "throw", "Error", "(", "'dolman.router: the route for url '", "+", "route", ".", "url", "+", "' has no action.'", ")", ";", "var", "actions", "=", "[", "]", ".", "concat", "(", "route", ".", "action", ")", ";", "// Storing the route", "routesMap", ".", "set", "(", "actions", "[", "0", "]", ",", "route", ")", ";", "// Applying before middlewares", "var", "routeMiddlewares", "=", "beforeMiddlewares", ".", "slice", "(", ")", ";", "// Validation", "if", "(", "route", ".", "validate", ")", "routeMiddlewares", ".", "push", "(", "middlewares", ".", "validate", "(", "types", ",", "route", ".", "validate", ")", ")", ";", "// Mask", "if", "(", "route", ".", "mask", ")", "routeMiddlewares", ".", "push", "(", "middlewares", ".", "mask", "(", "route", ".", "mask", ")", ")", ";", "// RAM cache", "if", "(", "route", ".", "cache", ")", "routeMiddlewares", ".", "push", "(", "middlewares", ".", "cache", "(", "cache", ",", "route", ".", "cache", ")", ")", ";", "// HTTP cache", "if", "(", "route", ".", "httpCache", ")", "routeMiddlewares", ".", "push", "(", "middlewares", ".", "httpCache", "(", "route", ".", "httpCache", ")", ")", ";", "// Determining the method", "var", "methods", "=", "[", "]", ".", "concat", "(", "route", ".", "method", "||", "route", ".", "methods", "||", "'ALL'", ")", ";", "methods", ".", "forEach", "(", "function", "(", "method", ")", "{", "router", "[", "method", ".", "toLowerCase", "(", ")", "]", ".", "apply", "(", "router", ",", "[", "route", ".", "url", "]", ".", "concat", "(", "routeMiddlewares", ")", ".", "concat", "(", "actions", ")", ")", ";", "}", ")", ";", "}", ")", ";", "return", "router", ";", "}" ]
Router function.
[ "Router", "function", "." ]
b0c5fe40fa43467ce39e064a5361d6b5b24ed58a
https://github.com/Yomguithereal/dolman/blob/b0c5fe40fa43467ce39e064a5361d6b5b24ed58a/index.js#L45-L100
46,504
Yomguithereal/dolman
index.js
specs
function specs() { var routes = {}; // Reducing the app's recursive stack function reduceStack(path, items, item) { var nextPath; if (item.handle && item.handle.stack) { nextPath = join(path, (item.path || helpers.unescapeRegex(item.regexp) || '')); return items.concat(item.handle.stack.reduce(reduceStack.bind(null, nextPath), [])); } if (item.route) { nextPath = join(path, (item.route.path || '')); return items.concat(item.route.stack.reduce(reduceStack.bind(null, nextPath), [])); } return items.concat({ handle: item.handle, path: path }); } // Filtering the actions coming from dolman app._router.stack .reduce(reduceStack.bind(null, ''), []) .map(function(item) { return { route: routesMap.get(item.handle), path: item.path }; }) .filter(function(item) { return item.route && item.route.name; }) .forEach(function(item) { var route = item.route, method = [].concat(route.method || route.methods)[0]; var routeData = { path: item.path, name: route.name, method: !method || method === 'ALL' ? 'GET' : method }; ['description'].forEach(function(k) { if (route[k]) routeData[k] = route[k]; }); routes[route.name] = routeData; }); return { formats: ['json'], methods: routes }; }
javascript
function specs() { var routes = {}; // Reducing the app's recursive stack function reduceStack(path, items, item) { var nextPath; if (item.handle && item.handle.stack) { nextPath = join(path, (item.path || helpers.unescapeRegex(item.regexp) || '')); return items.concat(item.handle.stack.reduce(reduceStack.bind(null, nextPath), [])); } if (item.route) { nextPath = join(path, (item.route.path || '')); return items.concat(item.route.stack.reduce(reduceStack.bind(null, nextPath), [])); } return items.concat({ handle: item.handle, path: path }); } // Filtering the actions coming from dolman app._router.stack .reduce(reduceStack.bind(null, ''), []) .map(function(item) { return { route: routesMap.get(item.handle), path: item.path }; }) .filter(function(item) { return item.route && item.route.name; }) .forEach(function(item) { var route = item.route, method = [].concat(route.method || route.methods)[0]; var routeData = { path: item.path, name: route.name, method: !method || method === 'ALL' ? 'GET' : method }; ['description'].forEach(function(k) { if (route[k]) routeData[k] = route[k]; }); routes[route.name] = routeData; }); return { formats: ['json'], methods: routes }; }
[ "function", "specs", "(", ")", "{", "var", "routes", "=", "{", "}", ";", "// Reducing the app's recursive stack", "function", "reduceStack", "(", "path", ",", "items", ",", "item", ")", "{", "var", "nextPath", ";", "if", "(", "item", ".", "handle", "&&", "item", ".", "handle", ".", "stack", ")", "{", "nextPath", "=", "join", "(", "path", ",", "(", "item", ".", "path", "||", "helpers", ".", "unescapeRegex", "(", "item", ".", "regexp", ")", "||", "''", ")", ")", ";", "return", "items", ".", "concat", "(", "item", ".", "handle", ".", "stack", ".", "reduce", "(", "reduceStack", ".", "bind", "(", "null", ",", "nextPath", ")", ",", "[", "]", ")", ")", ";", "}", "if", "(", "item", ".", "route", ")", "{", "nextPath", "=", "join", "(", "path", ",", "(", "item", ".", "route", ".", "path", "||", "''", ")", ")", ";", "return", "items", ".", "concat", "(", "item", ".", "route", ".", "stack", ".", "reduce", "(", "reduceStack", ".", "bind", "(", "null", ",", "nextPath", ")", ",", "[", "]", ")", ")", ";", "}", "return", "items", ".", "concat", "(", "{", "handle", ":", "item", ".", "handle", ",", "path", ":", "path", "}", ")", ";", "}", "// Filtering the actions coming from dolman", "app", ".", "_router", ".", "stack", ".", "reduce", "(", "reduceStack", ".", "bind", "(", "null", ",", "''", ")", ",", "[", "]", ")", ".", "map", "(", "function", "(", "item", ")", "{", "return", "{", "route", ":", "routesMap", ".", "get", "(", "item", ".", "handle", ")", ",", "path", ":", "item", ".", "path", "}", ";", "}", ")", ".", "filter", "(", "function", "(", "item", ")", "{", "return", "item", ".", "route", "&&", "item", ".", "route", ".", "name", ";", "}", ")", ".", "forEach", "(", "function", "(", "item", ")", "{", "var", "route", "=", "item", ".", "route", ",", "method", "=", "[", "]", ".", "concat", "(", "route", ".", "method", "||", "route", ".", "methods", ")", "[", "0", "]", ";", "var", "routeData", "=", "{", "path", ":", "item", ".", "path", ",", "name", ":", "route", ".", "name", ",", "method", ":", "!", "method", "||", "method", "===", "'ALL'", "?", "'GET'", ":", "method", "}", ";", "[", "'description'", "]", ".", "forEach", "(", "function", "(", "k", ")", "{", "if", "(", "route", "[", "k", "]", ")", "routeData", "[", "k", "]", "=", "route", "[", "k", "]", ";", "}", ")", ";", "routes", "[", "route", ".", "name", "]", "=", "routeData", ";", "}", ")", ";", "return", "{", "formats", ":", "[", "'json'", "]", ",", "methods", ":", "routes", "}", ";", "}" ]
Specifications functions.
[ "Specifications", "functions", "." ]
b0c5fe40fa43467ce39e064a5361d6b5b24ed58a
https://github.com/Yomguithereal/dolman/blob/b0c5fe40fa43467ce39e064a5361d6b5b24ed58a/index.js#L105-L162
46,505
Yomguithereal/dolman
index.js
reduceStack
function reduceStack(path, items, item) { var nextPath; if (item.handle && item.handle.stack) { nextPath = join(path, (item.path || helpers.unescapeRegex(item.regexp) || '')); return items.concat(item.handle.stack.reduce(reduceStack.bind(null, nextPath), [])); } if (item.route) { nextPath = join(path, (item.route.path || '')); return items.concat(item.route.stack.reduce(reduceStack.bind(null, nextPath), [])); } return items.concat({ handle: item.handle, path: path }); }
javascript
function reduceStack(path, items, item) { var nextPath; if (item.handle && item.handle.stack) { nextPath = join(path, (item.path || helpers.unescapeRegex(item.regexp) || '')); return items.concat(item.handle.stack.reduce(reduceStack.bind(null, nextPath), [])); } if (item.route) { nextPath = join(path, (item.route.path || '')); return items.concat(item.route.stack.reduce(reduceStack.bind(null, nextPath), [])); } return items.concat({ handle: item.handle, path: path }); }
[ "function", "reduceStack", "(", "path", ",", "items", ",", "item", ")", "{", "var", "nextPath", ";", "if", "(", "item", ".", "handle", "&&", "item", ".", "handle", ".", "stack", ")", "{", "nextPath", "=", "join", "(", "path", ",", "(", "item", ".", "path", "||", "helpers", ".", "unescapeRegex", "(", "item", ".", "regexp", ")", "||", "''", ")", ")", ";", "return", "items", ".", "concat", "(", "item", ".", "handle", ".", "stack", ".", "reduce", "(", "reduceStack", ".", "bind", "(", "null", ",", "nextPath", ")", ",", "[", "]", ")", ")", ";", "}", "if", "(", "item", ".", "route", ")", "{", "nextPath", "=", "join", "(", "path", ",", "(", "item", ".", "route", ".", "path", "||", "''", ")", ")", ";", "return", "items", ".", "concat", "(", "item", ".", "route", ".", "stack", ".", "reduce", "(", "reduceStack", ".", "bind", "(", "null", ",", "nextPath", ")", ",", "[", "]", ")", ")", ";", "}", "return", "items", ".", "concat", "(", "{", "handle", ":", "item", ".", "handle", ",", "path", ":", "path", "}", ")", ";", "}" ]
Reducing the app's recursive stack
[ "Reducing", "the", "app", "s", "recursive", "stack" ]
b0c5fe40fa43467ce39e064a5361d6b5b24ed58a
https://github.com/Yomguithereal/dolman/blob/b0c5fe40fa43467ce39e064a5361d6b5b24ed58a/index.js#L109-L126
46,506
codeactual/grunt-horde
lib/grunt-horde/index.js
GruntHorde
function GruntHorde(grunt) { this.cwd = process.cwd(); this.config = { initConfig: {}, loadNpmTasks: {}, loadTasks: {}, registerMultiTask: {}, registerTask: {} }; this.frozenConfig = {}; this.grunt = grunt; this.lootBatch = []; }
javascript
function GruntHorde(grunt) { this.cwd = process.cwd(); this.config = { initConfig: {}, loadNpmTasks: {}, loadTasks: {}, registerMultiTask: {}, registerTask: {} }; this.frozenConfig = {}; this.grunt = grunt; this.lootBatch = []; }
[ "function", "GruntHorde", "(", "grunt", ")", "{", "this", ".", "cwd", "=", "process", ".", "cwd", "(", ")", ";", "this", ".", "config", "=", "{", "initConfig", ":", "{", "}", ",", "loadNpmTasks", ":", "{", "}", ",", "loadTasks", ":", "{", "}", ",", "registerMultiTask", ":", "{", "}", ",", "registerTask", ":", "{", "}", "}", ";", "this", ".", "frozenConfig", "=", "{", "}", ";", "this", ".", "grunt", "=", "grunt", ";", "this", ".", "lootBatch", "=", "[", "]", ";", "}" ]
GruntHorde constructor. Usage: // Gruntfile.js module.exports = function(grunt) { require('grunt-horde') .create(grunt) .loot('my-base-config-module') .loot('./config/grunt') .attack(); }; Properties: - `{object} config` Gruntfile.js values indexed by `grunt` method name - `{object} initConfig` - `{object} loadNpmTasks` - `{object} loadTasks` - `{object} registerMultiTask` - `{object} registerTask` - `{object} frozenConfig` Track `config` keys set in `Gruntfile.js` - Allow client project to override defaults set in modules. - Keys: `config` key names, values: not used - `{string} [home=process.cwd]` Absolute path to project root dir w/out trailing slash - `{object} grunt` Instance injected into Gruntfile.js - `{array} lootBatch` Pending merge functions collected in Gruntfile.prototype.loot
[ "GruntHorde", "constructor", "." ]
6ddbb70972cc961988af9f2a8d39e60552903972
https://github.com/codeactual/grunt-horde/blob/6ddbb70972cc961988af9f2a8d39e60552903972/lib/grunt-horde/index.js#L68-L80
46,507
d-oliveros/isomorphine
src/server/router.js
createRouter
function createRouter(modules) { debug('Creating a new router. Modules: ' + JSON.stringify(modules, null, 3)); var router = express(); router.use(bodyParser.json()); // Map the requested entity path with the actual serverside entity router.use('/isomorphine', methodLoader(modules)); // Proxy request pipeline router.post('/isomorphine/*', getPayload, callEntityMethod, serve); return router; }
javascript
function createRouter(modules) { debug('Creating a new router. Modules: ' + JSON.stringify(modules, null, 3)); var router = express(); router.use(bodyParser.json()); // Map the requested entity path with the actual serverside entity router.use('/isomorphine', methodLoader(modules)); // Proxy request pipeline router.post('/isomorphine/*', getPayload, callEntityMethod, serve); return router; }
[ "function", "createRouter", "(", "modules", ")", "{", "debug", "(", "'Creating a new router. Modules: '", "+", "JSON", ".", "stringify", "(", "modules", ",", "null", ",", "3", ")", ")", ";", "var", "router", "=", "express", "(", ")", ";", "router", ".", "use", "(", "bodyParser", ".", "json", "(", ")", ")", ";", "// Map the requested entity path with the actual serverside entity", "router", ".", "use", "(", "'/isomorphine'", ",", "methodLoader", "(", "modules", ")", ")", ";", "// Proxy request pipeline", "router", ".", "post", "(", "'/isomorphine/*'", ",", "getPayload", ",", "callEntityMethod", ",", "serve", ")", ";", "return", "router", ";", "}" ]
Creates an express or connect-styled router, and exposes the provided modules in the router's API surface area. @param {Object} modules The entities to use. @returns {Function} An express app instance. @providesModule router
[ "Creates", "an", "express", "or", "connect", "-", "styled", "router", "and", "exposes", "the", "provided", "modules", "in", "the", "router", "s", "API", "surface", "area", "." ]
cb123d16b4be3bb7ec57758bd0b2e43767e91864
https://github.com/d-oliveros/isomorphine/blob/cb123d16b4be3bb7ec57758bd0b2e43767e91864/src/server/router.js#L23-L36
46,508
d-oliveros/isomorphine
src/server/router.js
methodLoader
function methodLoader(modules) { return function(req, res, next) { if (req.path === '/') return next(); var path = req.path.substr(1).split('/'); var currModule = modules; var isLastIndex, p, method; debug('Looking for isomorphine entity in: ' + path.join('.')); for (var i = 0, len = path.length; i < len; i++) { isLastIndex = i === (len - 1); p = path[i]; // Expect a function when last index if (isLastIndex && isES6Function(currModule[p])) { method = getES6Function(currModule[p]); } // Expect an object when not last index else if (!isLastIndex && isObject(currModule[p])) { currModule = currModule[p]; } // Return a 404 if the entity was not found else { return next(createError(404, 'No method found at this path')); } } // Reference the serverside method in req debug('Entity found'); req.serversideMethod = method; next(); }; }
javascript
function methodLoader(modules) { return function(req, res, next) { if (req.path === '/') return next(); var path = req.path.substr(1).split('/'); var currModule = modules; var isLastIndex, p, method; debug('Looking for isomorphine entity in: ' + path.join('.')); for (var i = 0, len = path.length; i < len; i++) { isLastIndex = i === (len - 1); p = path[i]; // Expect a function when last index if (isLastIndex && isES6Function(currModule[p])) { method = getES6Function(currModule[p]); } // Expect an object when not last index else if (!isLastIndex && isObject(currModule[p])) { currModule = currModule[p]; } // Return a 404 if the entity was not found else { return next(createError(404, 'No method found at this path')); } } // Reference the serverside method in req debug('Entity found'); req.serversideMethod = method; next(); }; }
[ "function", "methodLoader", "(", "modules", ")", "{", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "req", ".", "path", "===", "'/'", ")", "return", "next", "(", ")", ";", "var", "path", "=", "req", ".", "path", ".", "substr", "(", "1", ")", ".", "split", "(", "'/'", ")", ";", "var", "currModule", "=", "modules", ";", "var", "isLastIndex", ",", "p", ",", "method", ";", "debug", "(", "'Looking for isomorphine entity in: '", "+", "path", ".", "join", "(", "'.'", ")", ")", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "path", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "isLastIndex", "=", "i", "===", "(", "len", "-", "1", ")", ";", "p", "=", "path", "[", "i", "]", ";", "// Expect a function when last index", "if", "(", "isLastIndex", "&&", "isES6Function", "(", "currModule", "[", "p", "]", ")", ")", "{", "method", "=", "getES6Function", "(", "currModule", "[", "p", "]", ")", ";", "}", "// Expect an object when not last index", "else", "if", "(", "!", "isLastIndex", "&&", "isObject", "(", "currModule", "[", "p", "]", ")", ")", "{", "currModule", "=", "currModule", "[", "p", "]", ";", "}", "// Return a 404 if the entity was not found", "else", "{", "return", "next", "(", "createError", "(", "404", ",", "'No method found at this path'", ")", ")", ";", "}", "}", "// Reference the serverside method in req", "debug", "(", "'Entity found'", ")", ";", "req", ".", "serversideMethod", "=", "method", ";", "next", "(", ")", ";", "}", ";", "}" ]
Maps the parameter "entity" to the actual server-side entity. @param {Object} modules The entities available in this api. @returns {Function} Middleware function that maps the :entity param with the real entity, and exposes it in req.
[ "Maps", "the", "parameter", "entity", "to", "the", "actual", "server", "-", "side", "entity", "." ]
cb123d16b4be3bb7ec57758bd0b2e43767e91864
https://github.com/d-oliveros/isomorphine/blob/cb123d16b4be3bb7ec57758bd0b2e43767e91864/src/server/router.js#L45-L81
46,509
walbo/grunt-px-to-rem
tasks/px_to_rem.js
checkFallback
function checkFallback(obj) { var props = []; var hasFallback = []; var values = []; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { var pro = obj[prop].prop; if (obj[prop].type === 'comment') { continue; } if (props.indexOf(pro) === -1) { props.push(pro); values.push({prop: pro, val:obj[prop].value}); } else { var lookup = {}; for (var i = 0, len = values.length; i < len; i++) { lookup[values[i].prop] = values[i].val; } if (lookup[pro].search('px') === -1 && obj[prop].value.search('rem') === -1 || lookup[pro].search('rem') === -1 && obj[prop].value.search('px') === -1) { hasFallback.push(pro); } } } } return hasFallback; }
javascript
function checkFallback(obj) { var props = []; var hasFallback = []; var values = []; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { var pro = obj[prop].prop; if (obj[prop].type === 'comment') { continue; } if (props.indexOf(pro) === -1) { props.push(pro); values.push({prop: pro, val:obj[prop].value}); } else { var lookup = {}; for (var i = 0, len = values.length; i < len; i++) { lookup[values[i].prop] = values[i].val; } if (lookup[pro].search('px') === -1 && obj[prop].value.search('rem') === -1 || lookup[pro].search('rem') === -1 && obj[prop].value.search('px') === -1) { hasFallback.push(pro); } } } } return hasFallback; }
[ "function", "checkFallback", "(", "obj", ")", "{", "var", "props", "=", "[", "]", ";", "var", "hasFallback", "=", "[", "]", ";", "var", "values", "=", "[", "]", ";", "for", "(", "var", "prop", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "prop", ")", ")", "{", "var", "pro", "=", "obj", "[", "prop", "]", ".", "prop", ";", "if", "(", "obj", "[", "prop", "]", ".", "type", "===", "'comment'", ")", "{", "continue", ";", "}", "if", "(", "props", ".", "indexOf", "(", "pro", ")", "===", "-", "1", ")", "{", "props", ".", "push", "(", "pro", ")", ";", "values", ".", "push", "(", "{", "prop", ":", "pro", ",", "val", ":", "obj", "[", "prop", "]", ".", "value", "}", ")", ";", "}", "else", "{", "var", "lookup", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "values", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "lookup", "[", "values", "[", "i", "]", ".", "prop", "]", "=", "values", "[", "i", "]", ".", "val", ";", "}", "if", "(", "lookup", "[", "pro", "]", ".", "search", "(", "'px'", ")", "===", "-", "1", "&&", "obj", "[", "prop", "]", ".", "value", ".", "search", "(", "'rem'", ")", "===", "-", "1", "||", "lookup", "[", "pro", "]", ".", "search", "(", "'rem'", ")", "===", "-", "1", "&&", "obj", "[", "prop", "]", ".", "value", ".", "search", "(", "'px'", ")", "===", "-", "1", ")", "{", "hasFallback", ".", "push", "(", "pro", ")", ";", "}", "}", "}", "}", "return", "hasFallback", ";", "}" ]
Function to check if rem and px exist
[ "Function", "to", "check", "if", "rem", "and", "px", "exist" ]
6d14790e33dae9b9c37270c90249c80c17719f61
https://github.com/walbo/grunt-px-to-rem/blob/6d14790e33dae9b9c37270c90249c80c17719f61/tasks/px_to_rem.js#L149-L181
46,510
adityamukho/node-box-sdk
lib/connector.js
function () { if (this.auth_url) { return this.auth_url; } var self = this, destination = { protocol: 'https', host: 'www.box.com', pathname: '/api/oauth2/authorize', search: querystring.stringify({ response_type: 'code', client_id: self.client_id, state: self.csrf, redirect_uri: 'http://' + self.host + ':' + self.port + '/authorize?id=' + self.email }) }; self.auth_url = url.format(destination); return self.auth_url; }
javascript
function () { if (this.auth_url) { return this.auth_url; } var self = this, destination = { protocol: 'https', host: 'www.box.com', pathname: '/api/oauth2/authorize', search: querystring.stringify({ response_type: 'code', client_id: self.client_id, state: self.csrf, redirect_uri: 'http://' + self.host + ':' + self.port + '/authorize?id=' + self.email }) }; self.auth_url = url.format(destination); return self.auth_url; }
[ "function", "(", ")", "{", "if", "(", "this", ".", "auth_url", ")", "{", "return", "this", ".", "auth_url", ";", "}", "var", "self", "=", "this", ",", "destination", "=", "{", "protocol", ":", "'https'", ",", "host", ":", "'www.box.com'", ",", "pathname", ":", "'/api/oauth2/authorize'", ",", "search", ":", "querystring", ".", "stringify", "(", "{", "response_type", ":", "'code'", ",", "client_id", ":", "self", ".", "client_id", ",", "state", ":", "self", ".", "csrf", ",", "redirect_uri", ":", "'http://'", "+", "self", ".", "host", "+", "':'", "+", "self", ".", "port", "+", "'/authorize?id='", "+", "self", ".", "email", "}", ")", "}", ";", "self", ".", "auth_url", "=", "url", ".", "format", "(", "destination", ")", ";", "return", "self", ".", "auth_url", ";", "}" ]
The returned URL should be provided to the end user when running in standalone mode. @summary Get the authentication URL to manually navigate to. @returns {string} The authentication URL.
[ "The", "returned", "URL", "should", "be", "provided", "to", "the", "end", "user", "when", "running", "in", "standalone", "mode", "." ]
b8403df59d53ba4e8bed5de3675467544981a683
https://github.com/adityamukho/node-box-sdk/blob/b8403df59d53ba4e8bed5de3675467544981a683/lib/connector.js#L47-L66
46,511
freakimkaefig/musicjson2abc
index.js
getAbcKey
function getAbcKey(fifths, mode) { if (typeof mode === 'undefined' || mode === null) mode = 'major'; return circleOfFifths[mode][fifths]; }
javascript
function getAbcKey(fifths, mode) { if (typeof mode === 'undefined' || mode === null) mode = 'major'; return circleOfFifths[mode][fifths]; }
[ "function", "getAbcKey", "(", "fifths", ",", "mode", ")", "{", "if", "(", "typeof", "mode", "===", "'undefined'", "||", "mode", "===", "null", ")", "mode", "=", "'major'", ";", "return", "circleOfFifths", "[", "mode", "]", "[", "fifths", "]", ";", "}" ]
Returns the key for abc notation from given fifths @param {number} fifths - The position inside the circle of fifths @param {string|undefined} mode - The mode (major / minor) @returns {string}
[ "Returns", "the", "key", "for", "abc", "notation", "from", "given", "fifths" ]
c119c7927c3c9b6aa5f3558cc73990478472dfbb
https://github.com/freakimkaefig/musicjson2abc/blob/c119c7927c3c9b6aa5f3558cc73990478472dfbb/index.js#L281-L284
46,512
freakimkaefig/musicjson2abc
index.js
getJSONId
function getJSONId(data) { var lines = data.split('\n'); for (var i = 0; i < lines.length; i++) { if (lines[i].indexOf('T:') > -1) { return lines[i].substr(lines[i].indexOf(':') + 1, lines[i].length); } } throw new Error('Could not determine "T:" field'); }
javascript
function getJSONId(data) { var lines = data.split('\n'); for (var i = 0; i < lines.length; i++) { if (lines[i].indexOf('T:') > -1) { return lines[i].substr(lines[i].indexOf(':') + 1, lines[i].length); } } throw new Error('Could not determine "T:" field'); }
[ "function", "getJSONId", "(", "data", ")", "{", "var", "lines", "=", "data", ".", "split", "(", "'\\n'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "lines", ".", "length", ";", "i", "++", ")", "{", "if", "(", "lines", "[", "i", "]", ".", "indexOf", "(", "'T:'", ")", ">", "-", "1", ")", "{", "return", "lines", "[", "i", "]", ".", "substr", "(", "lines", "[", "i", "]", ".", "indexOf", "(", "':'", ")", "+", "1", ",", "lines", "[", "i", "]", ".", "length", ")", ";", "}", "}", "throw", "new", "Error", "(", "'Could not determine \"T:\" field'", ")", ";", "}" ]
Get id from abc string @param {String} data - The abc string @returns {string}
[ "Get", "id", "from", "abc", "string" ]
c119c7927c3c9b6aa5f3558cc73990478472dfbb
https://github.com/freakimkaefig/musicjson2abc/blob/c119c7927c3c9b6aa5f3558cc73990478472dfbb/index.js#L335-L343
46,513
freakimkaefig/musicjson2abc
index.js
function(tune) { var ret = { attributes: { divisions: 1 /tune.getBeatLength(), clef: { line: 2 }, key: {}, time: {} } }; var measures = []; var measureCounter = 0; var barlineCounter = 0; // parse lines for (var l = 0; l < tune.lines.length; l++) { for (var s = 0; s < tune.lines[l].staff.length; s++) { var staff = tune.lines[l].staff[s]; // parse default clef, key, meter if (l === 0 && s === 0) { ret.attributes.clef.sign = getKeyByValue(clefs, staff.clef.type); ret.attributes.clef.line = staff.clef.clefPos / 2; ret.attributes.key.fifths = parseInt(getKeyByValue(circleOfFifths, staff.key.root)); ret.attributes.time.beats = staff.meter.value[0].num; ret.attributes.time['beat-type'] = staff.meter.value[0].den; } for (var v = 0; v < staff.voices.length; v++) { for (var t = 0; t < staff.voices[v].length; t++) { var token = staff.voices[v][t]; // init measure if none exists if (measures[measureCounter] === undefined) { measures[measureCounter] = new Measure(); } switch (token.el_type) { case "note": measures[measureCounter].addNote(token, ret.attributes.divisions, ret.attributes.time['beat-type']); break; case "bar": if (token.type === 'bar_right_repeat') { measures[measureCounter].setRepeatRight(); } measureCounter++; if (measures[measureCounter] === undefined) { measures[measureCounter] = new Measure(); } if (token.type === 'bar_left_repeat') { measures[measureCounter].setRepeatLeft(); } break; default: console.log(token); break; } } } } } // put measures together ret.measures = []; for (var i = 0; i < measures.length; i++) { var measure = measures[i].get(); if (measure.notes.length > 0) { ret.measures.push(measure); } } return ret; }
javascript
function(tune) { var ret = { attributes: { divisions: 1 /tune.getBeatLength(), clef: { line: 2 }, key: {}, time: {} } }; var measures = []; var measureCounter = 0; var barlineCounter = 0; // parse lines for (var l = 0; l < tune.lines.length; l++) { for (var s = 0; s < tune.lines[l].staff.length; s++) { var staff = tune.lines[l].staff[s]; // parse default clef, key, meter if (l === 0 && s === 0) { ret.attributes.clef.sign = getKeyByValue(clefs, staff.clef.type); ret.attributes.clef.line = staff.clef.clefPos / 2; ret.attributes.key.fifths = parseInt(getKeyByValue(circleOfFifths, staff.key.root)); ret.attributes.time.beats = staff.meter.value[0].num; ret.attributes.time['beat-type'] = staff.meter.value[0].den; } for (var v = 0; v < staff.voices.length; v++) { for (var t = 0; t < staff.voices[v].length; t++) { var token = staff.voices[v][t]; // init measure if none exists if (measures[measureCounter] === undefined) { measures[measureCounter] = new Measure(); } switch (token.el_type) { case "note": measures[measureCounter].addNote(token, ret.attributes.divisions, ret.attributes.time['beat-type']); break; case "bar": if (token.type === 'bar_right_repeat') { measures[measureCounter].setRepeatRight(); } measureCounter++; if (measures[measureCounter] === undefined) { measures[measureCounter] = new Measure(); } if (token.type === 'bar_left_repeat') { measures[measureCounter].setRepeatLeft(); } break; default: console.log(token); break; } } } } } // put measures together ret.measures = []; for (var i = 0; i < measures.length; i++) { var measure = measures[i].get(); if (measure.notes.length > 0) { ret.measures.push(measure); } } return ret; }
[ "function", "(", "tune", ")", "{", "var", "ret", "=", "{", "attributes", ":", "{", "divisions", ":", "1", "/", "tune", ".", "getBeatLength", "(", ")", ",", "clef", ":", "{", "line", ":", "2", "}", ",", "key", ":", "{", "}", ",", "time", ":", "{", "}", "}", "}", ";", "var", "measures", "=", "[", "]", ";", "var", "measureCounter", "=", "0", ";", "var", "barlineCounter", "=", "0", ";", "// parse lines", "for", "(", "var", "l", "=", "0", ";", "l", "<", "tune", ".", "lines", ".", "length", ";", "l", "++", ")", "{", "for", "(", "var", "s", "=", "0", ";", "s", "<", "tune", ".", "lines", "[", "l", "]", ".", "staff", ".", "length", ";", "s", "++", ")", "{", "var", "staff", "=", "tune", ".", "lines", "[", "l", "]", ".", "staff", "[", "s", "]", ";", "// parse default clef, key, meter", "if", "(", "l", "===", "0", "&&", "s", "===", "0", ")", "{", "ret", ".", "attributes", ".", "clef", ".", "sign", "=", "getKeyByValue", "(", "clefs", ",", "staff", ".", "clef", ".", "type", ")", ";", "ret", ".", "attributes", ".", "clef", ".", "line", "=", "staff", ".", "clef", ".", "clefPos", "/", "2", ";", "ret", ".", "attributes", ".", "key", ".", "fifths", "=", "parseInt", "(", "getKeyByValue", "(", "circleOfFifths", ",", "staff", ".", "key", ".", "root", ")", ")", ";", "ret", ".", "attributes", ".", "time", ".", "beats", "=", "staff", ".", "meter", ".", "value", "[", "0", "]", ".", "num", ";", "ret", ".", "attributes", ".", "time", "[", "'beat-type'", "]", "=", "staff", ".", "meter", ".", "value", "[", "0", "]", ".", "den", ";", "}", "for", "(", "var", "v", "=", "0", ";", "v", "<", "staff", ".", "voices", ".", "length", ";", "v", "++", ")", "{", "for", "(", "var", "t", "=", "0", ";", "t", "<", "staff", ".", "voices", "[", "v", "]", ".", "length", ";", "t", "++", ")", "{", "var", "token", "=", "staff", ".", "voices", "[", "v", "]", "[", "t", "]", ";", "// init measure if none exists", "if", "(", "measures", "[", "measureCounter", "]", "===", "undefined", ")", "{", "measures", "[", "measureCounter", "]", "=", "new", "Measure", "(", ")", ";", "}", "switch", "(", "token", ".", "el_type", ")", "{", "case", "\"note\"", ":", "measures", "[", "measureCounter", "]", ".", "addNote", "(", "token", ",", "ret", ".", "attributes", ".", "divisions", ",", "ret", ".", "attributes", ".", "time", "[", "'beat-type'", "]", ")", ";", "break", ";", "case", "\"bar\"", ":", "if", "(", "token", ".", "type", "===", "'bar_right_repeat'", ")", "{", "measures", "[", "measureCounter", "]", ".", "setRepeatRight", "(", ")", ";", "}", "measureCounter", "++", ";", "if", "(", "measures", "[", "measureCounter", "]", "===", "undefined", ")", "{", "measures", "[", "measureCounter", "]", "=", "new", "Measure", "(", ")", ";", "}", "if", "(", "token", ".", "type", "===", "'bar_left_repeat'", ")", "{", "measures", "[", "measureCounter", "]", ".", "setRepeatLeft", "(", ")", ";", "}", "break", ";", "default", ":", "console", ".", "log", "(", "token", ")", ";", "break", ";", "}", "}", "}", "}", "}", "// put measures together", "ret", ".", "measures", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "measures", ".", "length", ";", "i", "++", ")", "{", "var", "measure", "=", "measures", "[", "i", "]", ".", "get", "(", ")", ";", "if", "(", "measure", ".", "notes", ".", "length", ">", "0", ")", "{", "ret", ".", "measures", ".", "push", "(", "measure", ")", ";", "}", "}", "return", "ret", ";", "}" ]
Creates json object from abc tunes object @param {object} tune - The parsed tune object @returns {object}
[ "Creates", "json", "object", "from", "abc", "tunes", "object" ]
c119c7927c3c9b6aa5f3558cc73990478472dfbb
https://github.com/freakimkaefig/musicjson2abc/blob/c119c7927c3c9b6aa5f3558cc73990478472dfbb/index.js#L350-L422
46,514
freakimkaefig/musicjson2abc
index.js
function() { var attributes = { repeat: { left: false, right: false } }; var notes = []; /** * Set repeat left for measure */ this.setRepeatLeft = function () { attributes.repeat.left = true; }; /** * Set repeat right for measure */ this.setRepeatRight = function () { attributes.repeat.right = true; }; /** * Add note to measure * @param {object} note - The note object * @param {Number} divisions - The calculated divisions * @param {Number} beatType - The beat type */ this.addNote = function(note, divisions, beatType) { var _note = {pitch:{}}; var _octave = 5, _step, _alter = 0; if (note.hasOwnProperty('pitches')) { _octave--; _step = note.pitches[0].pitch; while (_step > 6) { _octave++; _step -= 7; } while (_step < 0) { _octave--; _step +=7 } _note.pitch.step = pitches.abc[_step]; _note.rest = false; if (note.pitches[0].hasOwnProperty('accidental')) { _alter = accidental.abc[note.pitches[0].accidental]; _note.pitch.accidental = note.pitches[0].accidental; } } else { _note.pitch.step = "C"; _note.pitch.octave = 5; _note.rest = true; _note.pitch.alter = 0; } _note.pitch.octave = _octave; _note.pitch.alter = _alter; for (var i = 0; i < durations.length; i++) { if (typeof durations[i+1] !== 'undefined') { if (durations[i].duration > note.duration && durations[i+1].duration <= note.duration) { var diff = note.duration - durations[i+1].duration; _note.duration = durations[i+1].duration * divisions * beatType; _note.type = durations[i+1].type; if (diff > 0) { if ((diff / durations[i+1].duration) === 0.5) { _note.dot = true; } else { throw new Error('Unknown duration: ' + note.duration); } } break; } } else { throw new Error('Unknown duration: ' + note.duration); } } notes.push(_note); }; /** * Get measure object * @returns {{attributes: {repeat: {left: boolean, right: boolean}}, notes: Array}} */ this.get = function() { return { attributes: attributes, notes: notes }; }; }
javascript
function() { var attributes = { repeat: { left: false, right: false } }; var notes = []; /** * Set repeat left for measure */ this.setRepeatLeft = function () { attributes.repeat.left = true; }; /** * Set repeat right for measure */ this.setRepeatRight = function () { attributes.repeat.right = true; }; /** * Add note to measure * @param {object} note - The note object * @param {Number} divisions - The calculated divisions * @param {Number} beatType - The beat type */ this.addNote = function(note, divisions, beatType) { var _note = {pitch:{}}; var _octave = 5, _step, _alter = 0; if (note.hasOwnProperty('pitches')) { _octave--; _step = note.pitches[0].pitch; while (_step > 6) { _octave++; _step -= 7; } while (_step < 0) { _octave--; _step +=7 } _note.pitch.step = pitches.abc[_step]; _note.rest = false; if (note.pitches[0].hasOwnProperty('accidental')) { _alter = accidental.abc[note.pitches[0].accidental]; _note.pitch.accidental = note.pitches[0].accidental; } } else { _note.pitch.step = "C"; _note.pitch.octave = 5; _note.rest = true; _note.pitch.alter = 0; } _note.pitch.octave = _octave; _note.pitch.alter = _alter; for (var i = 0; i < durations.length; i++) { if (typeof durations[i+1] !== 'undefined') { if (durations[i].duration > note.duration && durations[i+1].duration <= note.duration) { var diff = note.duration - durations[i+1].duration; _note.duration = durations[i+1].duration * divisions * beatType; _note.type = durations[i+1].type; if (diff > 0) { if ((diff / durations[i+1].duration) === 0.5) { _note.dot = true; } else { throw new Error('Unknown duration: ' + note.duration); } } break; } } else { throw new Error('Unknown duration: ' + note.duration); } } notes.push(_note); }; /** * Get measure object * @returns {{attributes: {repeat: {left: boolean, right: boolean}}, notes: Array}} */ this.get = function() { return { attributes: attributes, notes: notes }; }; }
[ "function", "(", ")", "{", "var", "attributes", "=", "{", "repeat", ":", "{", "left", ":", "false", ",", "right", ":", "false", "}", "}", ";", "var", "notes", "=", "[", "]", ";", "/**\n * Set repeat left for measure\n */", "this", ".", "setRepeatLeft", "=", "function", "(", ")", "{", "attributes", ".", "repeat", ".", "left", "=", "true", ";", "}", ";", "/**\n * Set repeat right for measure\n */", "this", ".", "setRepeatRight", "=", "function", "(", ")", "{", "attributes", ".", "repeat", ".", "right", "=", "true", ";", "}", ";", "/**\n * Add note to measure\n * @param {object} note - The note object\n * @param {Number} divisions - The calculated divisions\n * @param {Number} beatType - The beat type\n */", "this", ".", "addNote", "=", "function", "(", "note", ",", "divisions", ",", "beatType", ")", "{", "var", "_note", "=", "{", "pitch", ":", "{", "}", "}", ";", "var", "_octave", "=", "5", ",", "_step", ",", "_alter", "=", "0", ";", "if", "(", "note", ".", "hasOwnProperty", "(", "'pitches'", ")", ")", "{", "_octave", "--", ";", "_step", "=", "note", ".", "pitches", "[", "0", "]", ".", "pitch", ";", "while", "(", "_step", ">", "6", ")", "{", "_octave", "++", ";", "_step", "-=", "7", ";", "}", "while", "(", "_step", "<", "0", ")", "{", "_octave", "--", ";", "_step", "+=", "7", "}", "_note", ".", "pitch", ".", "step", "=", "pitches", ".", "abc", "[", "_step", "]", ";", "_note", ".", "rest", "=", "false", ";", "if", "(", "note", ".", "pitches", "[", "0", "]", ".", "hasOwnProperty", "(", "'accidental'", ")", ")", "{", "_alter", "=", "accidental", ".", "abc", "[", "note", ".", "pitches", "[", "0", "]", ".", "accidental", "]", ";", "_note", ".", "pitch", ".", "accidental", "=", "note", ".", "pitches", "[", "0", "]", ".", "accidental", ";", "}", "}", "else", "{", "_note", ".", "pitch", ".", "step", "=", "\"C\"", ";", "_note", ".", "pitch", ".", "octave", "=", "5", ";", "_note", ".", "rest", "=", "true", ";", "_note", ".", "pitch", ".", "alter", "=", "0", ";", "}", "_note", ".", "pitch", ".", "octave", "=", "_octave", ";", "_note", ".", "pitch", ".", "alter", "=", "_alter", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "durations", ".", "length", ";", "i", "++", ")", "{", "if", "(", "typeof", "durations", "[", "i", "+", "1", "]", "!==", "'undefined'", ")", "{", "if", "(", "durations", "[", "i", "]", ".", "duration", ">", "note", ".", "duration", "&&", "durations", "[", "i", "+", "1", "]", ".", "duration", "<=", "note", ".", "duration", ")", "{", "var", "diff", "=", "note", ".", "duration", "-", "durations", "[", "i", "+", "1", "]", ".", "duration", ";", "_note", ".", "duration", "=", "durations", "[", "i", "+", "1", "]", ".", "duration", "*", "divisions", "*", "beatType", ";", "_note", ".", "type", "=", "durations", "[", "i", "+", "1", "]", ".", "type", ";", "if", "(", "diff", ">", "0", ")", "{", "if", "(", "(", "diff", "/", "durations", "[", "i", "+", "1", "]", ".", "duration", ")", "===", "0.5", ")", "{", "_note", ".", "dot", "=", "true", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Unknown duration: '", "+", "note", ".", "duration", ")", ";", "}", "}", "break", ";", "}", "}", "else", "{", "throw", "new", "Error", "(", "'Unknown duration: '", "+", "note", ".", "duration", ")", ";", "}", "}", "notes", ".", "push", "(", "_note", ")", ";", "}", ";", "/**\n * Get measure object\n * @returns {{attributes: {repeat: {left: boolean, right: boolean}}, notes: Array}}\n */", "this", ".", "get", "=", "function", "(", ")", "{", "return", "{", "attributes", ":", "attributes", ",", "notes", ":", "notes", "}", ";", "}", ";", "}" ]
Constructor for measure objects @constructor
[ "Constructor", "for", "measure", "objects" ]
c119c7927c3c9b6aa5f3558cc73990478472dfbb
https://github.com/freakimkaefig/musicjson2abc/blob/c119c7927c3c9b6aa5f3558cc73990478472dfbb/index.js#L428-L519
46,515
Hugo-ter-Doest/chart-parsers
lib/HeadCornerParser.js
HeadCornerChartParser
function HeadCornerChartParser(grammar) { this.grammar = grammar; this.grammar.computeHCRelation(); logger.debug("HeadCornerChartParser: " + JSON.stringify(grammar.hc)); }
javascript
function HeadCornerChartParser(grammar) { this.grammar = grammar; this.grammar.computeHCRelation(); logger.debug("HeadCornerChartParser: " + JSON.stringify(grammar.hc)); }
[ "function", "HeadCornerChartParser", "(", "grammar", ")", "{", "this", ".", "grammar", "=", "grammar", ";", "this", ".", "grammar", ".", "computeHCRelation", "(", ")", ";", "logger", ".", "debug", "(", "\"HeadCornerChartParser: \"", "+", "JSON", ".", "stringify", "(", "grammar", ".", "hc", ")", ")", ";", "}" ]
Constructor for the left-corner parser
[ "Constructor", "for", "the", "left", "-", "corner", "parser" ]
81be32f897f6dceeffebd2009ad865964da12c4b
https://github.com/Hugo-ter-Doest/chart-parsers/blob/81be32f897f6dceeffebd2009ad865964da12c4b/lib/HeadCornerParser.js#L181-L185
46,516
d-oliveros/isomorphine
src/server/factory.js
requireMethods
function requireMethods(dir) { if (!dir) dir = getCallerDirname(); var modules = {}; fs .readdirSync(dir) .filter(function(filename) { return filename !== 'index.js'; }) .forEach(function(filename) { var filePath = path.join(dir, filename); var Stats = fs.lstatSync(filePath); var isLink = Stats.isSymbolicLink(); var isDir = Stats.isDirectory(); var isFile = Stats.isFile(); var isJS = filename.indexOf('.js') > -1; if (!isLink && isDir) { modules[filename] = requireMethods(filePath); } else if (!isLink && isFile && isJS) { var entityName = filename.replace('.js', ''); modules[entityName] = require(filePath); var hasES6Default = isObject(modules[entityName]) && isFunction(modules[entityName].default); if (hasES6Default) { modules[entityName] = modules[entityName].default; } } }); return modules; }
javascript
function requireMethods(dir) { if (!dir) dir = getCallerDirname(); var modules = {}; fs .readdirSync(dir) .filter(function(filename) { return filename !== 'index.js'; }) .forEach(function(filename) { var filePath = path.join(dir, filename); var Stats = fs.lstatSync(filePath); var isLink = Stats.isSymbolicLink(); var isDir = Stats.isDirectory(); var isFile = Stats.isFile(); var isJS = filename.indexOf('.js') > -1; if (!isLink && isDir) { modules[filename] = requireMethods(filePath); } else if (!isLink && isFile && isJS) { var entityName = filename.replace('.js', ''); modules[entityName] = require(filePath); var hasES6Default = isObject(modules[entityName]) && isFunction(modules[entityName].default); if (hasES6Default) { modules[entityName] = modules[entityName].default; } } }); return modules; }
[ "function", "requireMethods", "(", "dir", ")", "{", "if", "(", "!", "dir", ")", "dir", "=", "getCallerDirname", "(", ")", ";", "var", "modules", "=", "{", "}", ";", "fs", ".", "readdirSync", "(", "dir", ")", ".", "filter", "(", "function", "(", "filename", ")", "{", "return", "filename", "!==", "'index.js'", ";", "}", ")", ".", "forEach", "(", "function", "(", "filename", ")", "{", "var", "filePath", "=", "path", ".", "join", "(", "dir", ",", "filename", ")", ";", "var", "Stats", "=", "fs", ".", "lstatSync", "(", "filePath", ")", ";", "var", "isLink", "=", "Stats", ".", "isSymbolicLink", "(", ")", ";", "var", "isDir", "=", "Stats", ".", "isDirectory", "(", ")", ";", "var", "isFile", "=", "Stats", ".", "isFile", "(", ")", ";", "var", "isJS", "=", "filename", ".", "indexOf", "(", "'.js'", ")", ">", "-", "1", ";", "if", "(", "!", "isLink", "&&", "isDir", ")", "{", "modules", "[", "filename", "]", "=", "requireMethods", "(", "filePath", ")", ";", "}", "else", "if", "(", "!", "isLink", "&&", "isFile", "&&", "isJS", ")", "{", "var", "entityName", "=", "filename", ".", "replace", "(", "'.js'", ",", "''", ")", ";", "modules", "[", "entityName", "]", "=", "require", "(", "filePath", ")", ";", "var", "hasES6Default", "=", "isObject", "(", "modules", "[", "entityName", "]", ")", "&&", "isFunction", "(", "modules", "[", "entityName", "]", ".", "default", ")", ";", "if", "(", "hasES6Default", ")", "{", "modules", "[", "entityName", "]", "=", "modules", "[", "entityName", "]", ".", "default", ";", "}", "}", "}", ")", ";", "return", "modules", ";", "}" ]
Recursively requires the modules in current dir. @param {String} dir The base directory to require entities from. @return {Object} An object with all the modules loaded.
[ "Recursively", "requires", "the", "modules", "in", "current", "dir", "." ]
cb123d16b4be3bb7ec57758bd0b2e43767e91864
https://github.com/d-oliveros/isomorphine/blob/cb123d16b4be3bb7ec57758bd0b2e43767e91864/src/server/factory.js#L50-L86
46,517
d-oliveros/isomorphine
src/server/factory.js
getCallerDirname
function getCallerDirname() { var orig = Error.prepareStackTrace; Error.prepareStackTrace = function(_, stack){ return stack; }; var err = new Error(); Error.captureStackTrace(err, arguments.callee); var stack = err.stack; Error.prepareStackTrace = orig; var requester = stack[2].getFileName(); return path.dirname(requester); }
javascript
function getCallerDirname() { var orig = Error.prepareStackTrace; Error.prepareStackTrace = function(_, stack){ return stack; }; var err = new Error(); Error.captureStackTrace(err, arguments.callee); var stack = err.stack; Error.prepareStackTrace = orig; var requester = stack[2].getFileName(); return path.dirname(requester); }
[ "function", "getCallerDirname", "(", ")", "{", "var", "orig", "=", "Error", ".", "prepareStackTrace", ";", "Error", ".", "prepareStackTrace", "=", "function", "(", "_", ",", "stack", ")", "{", "return", "stack", ";", "}", ";", "var", "err", "=", "new", "Error", "(", ")", ";", "Error", ".", "captureStackTrace", "(", "err", ",", "arguments", ".", "callee", ")", ";", "var", "stack", "=", "err", ".", "stack", ";", "Error", ".", "prepareStackTrace", "=", "orig", ";", "var", "requester", "=", "stack", "[", "2", "]", ".", "getFileName", "(", ")", ";", "return", "path", ".", "dirname", "(", "requester", ")", ";", "}" ]
Gets the dirname of the caller function that is calling this method. @return {String} Absolute path to the caller's directory.
[ "Gets", "the", "dirname", "of", "the", "caller", "function", "that", "is", "calling", "this", "method", "." ]
cb123d16b4be3bb7ec57758bd0b2e43767e91864
https://github.com/d-oliveros/isomorphine/blob/cb123d16b4be3bb7ec57758bd0b2e43767e91864/src/server/factory.js#L92-L102
46,518
adityamukho/node-box-sdk
lib/api/content/folders.js
function (name, parent_id, done, config) { if (!_.isString(name) || !_.isNumber(parseInt(parent_id, 10))) { return done(new Error('Invalid params. Required - name: string, parent_id: number')); } this._request(['folders'], 'POST', done, null, { name: name, parent: { id: parent_id.toString() } }, null, null, null, config); }
javascript
function (name, parent_id, done, config) { if (!_.isString(name) || !_.isNumber(parseInt(parent_id, 10))) { return done(new Error('Invalid params. Required - name: string, parent_id: number')); } this._request(['folders'], 'POST', done, null, { name: name, parent: { id: parent_id.toString() } }, null, null, null, config); }
[ "function", "(", "name", ",", "parent_id", ",", "done", ",", "config", ")", "{", "if", "(", "!", "_", ".", "isString", "(", "name", ")", "||", "!", "_", ".", "isNumber", "(", "parseInt", "(", "parent_id", ",", "10", ")", ")", ")", "{", "return", "done", "(", "new", "Error", "(", "'Invalid params. Required - name: string, parent_id: number'", ")", ")", ";", "}", "this", ".", "_request", "(", "[", "'folders'", "]", ",", "'POST'", ",", "done", ",", "null", ",", "{", "name", ":", "name", ",", "parent", ":", "{", "id", ":", "parent_id", ".", "toString", "(", ")", "}", "}", ",", "null", ",", "null", ",", "null", ",", "config", ")", ";", "}" ]
Used to create a new empty folder. The new folder will be created inside of the specified parent folder. @summary Create a New Folder. @see {@link https://developers.box.com/docs/#folders-create-a-new-folder} @param {string} name - The folder's name. @param {number} parent_id - The parent folder's ID. @param {requestCallback} done - The callback to invoke (with possible errors) when the request returns. @param {?RequestConfig} [config] - Configure the request behaviour.
[ "Used", "to", "create", "a", "new", "empty", "folder", ".", "The", "new", "folder", "will", "be", "created", "inside", "of", "the", "specified", "parent", "folder", "." ]
b8403df59d53ba4e8bed5de3675467544981a683
https://github.com/adityamukho/node-box-sdk/blob/b8403df59d53ba4e8bed5de3675467544981a683/lib/api/content/folders.js#L59-L69
46,519
svanderburg/nijs
lib/ast/NixAttrReference.js
NixAttrReference
function NixAttrReference(args) { this.attrSetExpr = args.attrSetExpr; this.refExpr = args.refExpr; this.orExpr = args.orExpr; }
javascript
function NixAttrReference(args) { this.attrSetExpr = args.attrSetExpr; this.refExpr = args.refExpr; this.orExpr = args.orExpr; }
[ "function", "NixAttrReference", "(", "args", ")", "{", "this", ".", "attrSetExpr", "=", "args", ".", "attrSetExpr", ";", "this", ".", "refExpr", "=", "args", ".", "refExpr", ";", "this", ".", "orExpr", "=", "args", ".", "orExpr", ";", "}" ]
Creates a new NixAttrReference instance. @class NixAttrReference @extends NixObject @classdesc Captures the abstract syntax of a Nix of an expression yielding an attribute set and an expression yielding an attribute name that references a member of the former attribute set. @constructor @param {Object} args Arguments to this function @param {Mixed} args.attrSetExpr An object representing an expression that yields an attribute set @param {Mixed} args.refExpr An object representing an expression that yields an attribute name @param {Mixed} args.orExpr An optional object representing an expression that gets evaluated if the reference does not exist.
[ "Creates", "a", "new", "NixAttrReference", "instance", "." ]
4e2738cbff3a43aba9297315ca5120cecf8dae3e
https://github.com/svanderburg/nijs/blob/4e2738cbff3a43aba9297315ca5120cecf8dae3e/lib/ast/NixAttrReference.js#L20-L24
46,520
ericprud/jsg
lib/json-grammar.js
throwUnexpected
function throwUnexpected (attr, obj) { var e = Unexpected(attr, obj); Error.captureStackTrace(e, throwUnexpected); throw e; }
javascript
function throwUnexpected (attr, obj) { var e = Unexpected(attr, obj); Error.captureStackTrace(e, throwUnexpected); throw e; }
[ "function", "throwUnexpected", "(", "attr", ",", "obj", ")", "{", "var", "e", "=", "Unexpected", "(", "attr", ",", "obj", ")", ";", "Error", ".", "captureStackTrace", "(", "e", ",", "throwUnexpected", ")", ";", "throw", "e", ";", "}" ]
thrower for inline conditionals
[ "thrower", "for", "inline", "conditionals" ]
0be3fcf487356c23c88117081214d00bb2fb3274
https://github.com/ericprud/jsg/blob/0be3fcf487356c23c88117081214d00bb2fb3274/lib/json-grammar.js#L21-L25
46,521
thlorenz/dockerify
index.js
targz
function targz(stream, opts) { return exports.tar(stream.pipe(zlib.createGunzip()), opts); }
javascript
function targz(stream, opts) { return exports.tar(stream.pipe(zlib.createGunzip()), opts); }
[ "function", "targz", "(", "stream", ",", "opts", ")", "{", "return", "exports", ".", "tar", "(", "stream", ".", "pipe", "(", "zlib", ".", "createGunzip", "(", ")", ")", ",", "opts", ")", ";", "}" ]
Gunzips the .tar.gz stream and passes it along to `tar`. @name targz @function @param {ReadableStream} stream .tar.gz stream @param {Object} opts @see `tar` @return {ReadableStream} the transformed tar stream
[ "Gunzips", "the", ".", "tar", ".", "gz", "stream", "and", "passes", "it", "along", "to", "tar", "." ]
5f769115c32782cc60db50c2ce4b3bbc7e5d68b5
https://github.com/thlorenz/dockerify/blob/5f769115c32782cc60db50c2ce4b3bbc7e5d68b5/index.js#L142-L144
46,522
deepstreamIO/deepstream.io-tools-react
src/deepstream-react.js
function( state ) { var key, clonedState = {}; for( key in state ) { if( key !== LOCAL ) { clonedState[ key ] = state[ key ]; } } return clonedState; }
javascript
function( state ) { var key, clonedState = {}; for( key in state ) { if( key !== LOCAL ) { clonedState[ key ] = state[ key ]; } } return clonedState; }
[ "function", "(", "state", ")", "{", "var", "key", ",", "clonedState", "=", "{", "}", ";", "for", "(", "key", "in", "state", ")", "{", "if", "(", "key", "!==", "LOCAL", ")", "{", "clonedState", "[", "key", "]", "=", "state", "[", "key", "]", ";", "}", "}", "return", "clonedState", ";", "}" ]
Creates a shallow copy of the state and omits the local namespace @param {Object} state a serializable component state @private @returns {Object} clonedState a serializable component state
[ "Creates", "a", "shallow", "copy", "of", "the", "state", "and", "omits", "the", "local", "namespace" ]
aec3b3fe3c9b12da0b05daf7a878173a3763e864
https://github.com/deepstreamIO/deepstream.io-tools-react/blob/aec3b3fe3c9b12da0b05daf7a878173a3763e864/src/deepstream-react.js#L143-L154
46,523
deepstreamIO/deepstream.io-tools-react
src/deepstream-react.js
function() { if( this.dsRecord && this.dsRecord.isReady && Object.keys( this.dsRecord.get() ).length === 0 && this.state ) { this.dsRecord.set( this.state ); } }
javascript
function() { if( this.dsRecord && this.dsRecord.isReady && Object.keys( this.dsRecord.get() ).length === 0 && this.state ) { this.dsRecord.set( this.state ); } }
[ "function", "(", ")", "{", "if", "(", "this", ".", "dsRecord", "&&", "this", ".", "dsRecord", ".", "isReady", "&&", "Object", ".", "keys", "(", "this", ".", "dsRecord", ".", "get", "(", ")", ")", ".", "length", "===", "0", "&&", "this", ".", "state", ")", "{", "this", ".", "dsRecord", ".", "set", "(", "this", ".", "state", ")", ";", "}", "}" ]
Set's the record's initial dataset, but only if the record is present, is empty and the state is populated. This would most likely be the case for new react components that expose a getInitialState method @private @returns {void}
[ "Set", "s", "the", "record", "s", "initial", "dataset", "but", "only", "if", "the", "record", "is", "present", "is", "empty", "and", "the", "state", "is", "populated", ".", "This", "would", "most", "likely", "be", "the", "case", "for", "new", "react", "components", "that", "expose", "a", "getInitialState", "method" ]
aec3b3fe3c9b12da0b05daf7a878173a3763e864
https://github.com/deepstreamIO/deepstream.io-tools-react/blob/aec3b3fe3c9b12da0b05daf7a878173a3763e864/src/deepstream-react.js#L164-L168
46,524
Liby99/keeling-js
lib/crypto.js
encrypt
function encrypt(salt, password) { var hash = crypto.createHash('sha256').update(salt + password).digest('base64'); return salt + hash; }
javascript
function encrypt(salt, password) { var hash = crypto.createHash('sha256').update(salt + password).digest('base64'); return salt + hash; }
[ "function", "encrypt", "(", "salt", ",", "password", ")", "{", "var", "hash", "=", "crypto", ".", "createHash", "(", "'sha256'", ")", ".", "update", "(", "salt", "+", "password", ")", ".", "digest", "(", "'base64'", ")", ";", "return", "salt", "+", "hash", ";", "}" ]
Encrypt the password with the salt @param salt @param password
[ "Encrypt", "the", "password", "with", "the", "salt" ]
a49d7669c9a5425185068554c0b013cf87fffe20
https://github.com/Liby99/keeling-js/blob/a49d7669c9a5425185068554c0b013cf87fffe20/lib/crypto.js#L51-L54
46,525
jub3i/node-mem-stat
index.js
_toCamelCase
function _toCamelCase(str) { var newString = ''; var insideParens = false; newString += str[0].toLowerCase(); for (var i = 1; i < str.length; i++) { var char = str[i]; switch (char) { case ')': case '_': break; case '(': insideParens = true; break; default: if (insideParens) { insideParens = false; newString += char.toUpperCase(); } else { newString += char; } break; } } return newString; }
javascript
function _toCamelCase(str) { var newString = ''; var insideParens = false; newString += str[0].toLowerCase(); for (var i = 1; i < str.length; i++) { var char = str[i]; switch (char) { case ')': case '_': break; case '(': insideParens = true; break; default: if (insideParens) { insideParens = false; newString += char.toUpperCase(); } else { newString += char; } break; } } return newString; }
[ "function", "_toCamelCase", "(", "str", ")", "{", "var", "newString", "=", "''", ";", "var", "insideParens", "=", "false", ";", "newString", "+=", "str", "[", "0", "]", ".", "toLowerCase", "(", ")", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "str", ".", "length", ";", "i", "++", ")", "{", "var", "char", "=", "str", "[", "i", "]", ";", "switch", "(", "char", ")", "{", "case", "')'", ":", "case", "'_'", ":", "break", ";", "case", "'('", ":", "insideParens", "=", "true", ";", "break", ";", "default", ":", "if", "(", "insideParens", ")", "{", "insideParens", "=", "false", ";", "newString", "+=", "char", ".", "toUpperCase", "(", ")", ";", "}", "else", "{", "newString", "+=", "char", ";", "}", "break", ";", "}", "}", "return", "newString", ";", "}" ]
quick dirty to handle parens and underscores
[ "quick", "dirty", "to", "handle", "parens", "and", "underscores" ]
8481e35560bfcdf73a76c9be4b869ed3eef2f009
https://github.com/jub3i/node-mem-stat/blob/8481e35560bfcdf73a76c9be4b869ed3eef2f009/index.js#L131-L156
46,526
doowb/githubbot
index.js
GithubBot
function GithubBot(options) { if (!(this instanceof GithubBot)) { return new GithubBot(options); } BaseBot.call(this, options); this.handlers(events); this.define('events', events); }
javascript
function GithubBot(options) { if (!(this instanceof GithubBot)) { return new GithubBot(options); } BaseBot.call(this, options); this.handlers(events); this.define('events', events); }
[ "function", "GithubBot", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "GithubBot", ")", ")", "{", "return", "new", "GithubBot", "(", "options", ")", ";", "}", "BaseBot", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "handlers", "(", "events", ")", ";", "this", ".", "define", "(", "'events'", ",", "events", ")", ";", "}" ]
Create a new instance of a GithubBot with provided options. ```js var bot = new GithubBot(); ``` @param {Object} `options` Options to configure the github bot. @api public
[ "Create", "a", "new", "instance", "of", "a", "GithubBot", "with", "provided", "options", "." ]
aa084bd2c432fa1edea58431db5d8ffee1f4da7c
https://github.com/doowb/githubbot/blob/aa084bd2c432fa1edea58431db5d8ffee1f4da7c/index.js#L24-L32
46,527
adityamukho/node-box-sdk
lib/api/content/events.js
function () { var self = this; async.waterfall([ function (next) { if (!self.events) { self.events = new Datastore(); self.events.ensureIndex({ fieldName: 'event_id', unique: true }); self.events.ensureIndex({ fieldName: 'recorded_at', sparse: true }); self.events.ensureIndex({ fieldName: 'created_at', }, next); } else { next(); } }, function (next) { if (!self.keepPolling) { self.keepPolling = true; async.whilst(function () { return self.keepPolling; }, _.bind(self._emit, self), _.noop); next(null, true); } else { next(null, false); } }, function (doLongPoll, next) { if (doLongPoll) { async.whilst(function () { return self.keepPolling; }, _.bind(self._longPoll, self), function (err) { if (err) { /** * Fires when an error occurs during long-polling. * @event Connection#"polling.error" * @type {Error} * @see {@link Connection#startLongPolling} */ self.emit('polling.error', err); } else if (!self.keepPolling) { /** * Fires when a running long-polling process ends. * @event Connection#"polling.end" * @see {@link Connection#stopLongPolling} */ self.emit('polling.end'); } }); } next(); } ], _.noop); }
javascript
function () { var self = this; async.waterfall([ function (next) { if (!self.events) { self.events = new Datastore(); self.events.ensureIndex({ fieldName: 'event_id', unique: true }); self.events.ensureIndex({ fieldName: 'recorded_at', sparse: true }); self.events.ensureIndex({ fieldName: 'created_at', }, next); } else { next(); } }, function (next) { if (!self.keepPolling) { self.keepPolling = true; async.whilst(function () { return self.keepPolling; }, _.bind(self._emit, self), _.noop); next(null, true); } else { next(null, false); } }, function (doLongPoll, next) { if (doLongPoll) { async.whilst(function () { return self.keepPolling; }, _.bind(self._longPoll, self), function (err) { if (err) { /** * Fires when an error occurs during long-polling. * @event Connection#"polling.error" * @type {Error} * @see {@link Connection#startLongPolling} */ self.emit('polling.error', err); } else if (!self.keepPolling) { /** * Fires when a running long-polling process ends. * @event Connection#"polling.end" * @see {@link Connection#stopLongPolling} */ self.emit('polling.end'); } }); } next(); } ], _.noop); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "async", ".", "waterfall", "(", "[", "function", "(", "next", ")", "{", "if", "(", "!", "self", ".", "events", ")", "{", "self", ".", "events", "=", "new", "Datastore", "(", ")", ";", "self", ".", "events", ".", "ensureIndex", "(", "{", "fieldName", ":", "'event_id'", ",", "unique", ":", "true", "}", ")", ";", "self", ".", "events", ".", "ensureIndex", "(", "{", "fieldName", ":", "'recorded_at'", ",", "sparse", ":", "true", "}", ")", ";", "self", ".", "events", ".", "ensureIndex", "(", "{", "fieldName", ":", "'created_at'", ",", "}", ",", "next", ")", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}", ",", "function", "(", "next", ")", "{", "if", "(", "!", "self", ".", "keepPolling", ")", "{", "self", ".", "keepPolling", "=", "true", ";", "async", ".", "whilst", "(", "function", "(", ")", "{", "return", "self", ".", "keepPolling", ";", "}", ",", "_", ".", "bind", "(", "self", ".", "_emit", ",", "self", ")", ",", "_", ".", "noop", ")", ";", "next", "(", "null", ",", "true", ")", ";", "}", "else", "{", "next", "(", "null", ",", "false", ")", ";", "}", "}", ",", "function", "(", "doLongPoll", ",", "next", ")", "{", "if", "(", "doLongPoll", ")", "{", "async", ".", "whilst", "(", "function", "(", ")", "{", "return", "self", ".", "keepPolling", ";", "}", ",", "_", ".", "bind", "(", "self", ".", "_longPoll", ",", "self", ")", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "/**\n * Fires when an error occurs during long-polling.\n * @event Connection#\"polling.error\"\n * @type {Error}\n * @see {@link Connection#startLongPolling}\n */", "self", ".", "emit", "(", "'polling.error'", ",", "err", ")", ";", "}", "else", "if", "(", "!", "self", ".", "keepPolling", ")", "{", "/**\n * Fires when a running long-polling process ends.\n * @event Connection#\"polling.end\"\n * @see {@link Connection#stopLongPolling}\n */", "self", ".", "emit", "(", "'polling.end'", ")", ";", "}", "}", ")", ";", "}", "next", "(", ")", ";", "}", "]", ",", "_", ".", "noop", ")", ";", "}" ]
Start long-polling for events. @see {@link https://developers.box.com/docs/#events-long-polling} @fires Connection#"polling.error" @fires Connection#"polling.end"
[ "Start", "long", "-", "polling", "for", "events", "." ]
b8403df59d53ba4e8bed5de3675467544981a683
https://github.com/adityamukho/node-box-sdk/blob/b8403df59d53ba4e8bed5de3675467544981a683/lib/api/content/events.js#L17-L79
46,528
adityamukho/node-box-sdk
lib/api/content/search.js
function (query, opts, done, config) { if (!_.isString(query)) { return done(new Error('query must be a string.')); } opts = opts || {}; opts.query = query; this._request(['search'], 'GET', done, opts, null, null, null, null, config); }
javascript
function (query, opts, done, config) { if (!_.isString(query)) { return done(new Error('query must be a string.')); } opts = opts || {}; opts.query = query; this._request(['search'], 'GET', done, opts, null, null, null, null, config); }
[ "function", "(", "query", ",", "opts", ",", "done", ",", "config", ")", "{", "if", "(", "!", "_", ".", "isString", "(", "query", ")", ")", "{", "return", "done", "(", "new", "Error", "(", "'query must be a string.'", ")", ")", ";", "}", "opts", "=", "opts", "||", "{", "}", ";", "opts", ".", "query", "=", "query", ";", "this", ".", "_request", "(", "[", "'search'", "]", ",", "'GET'", ",", "done", ",", "opts", ",", "null", ",", "null", ",", "null", ",", "null", ",", "config", ")", ";", "}" ]
Options and parameters for search. @typedef {Object} OptsSearch @property {string} [scope] - The scope for which you want to limit your search to. Can be {@linkcode user_content} for a search limited to only the current user or {@linkcode enterprise_content} for the entire enterprise. @property {string} [file_extensions] - Limit searches to specific file extensions like {@linkcode pdf,png,doc}. Requires one or a set of comma delimited file extensions. @property {external:ISO8601} [created_at_range] - The date for when the item was created. Specify the date range by using ISO-8601 variables separated by a comma: {@linkcode from_date,to_date}. Trailing {@linkcode from_date,} and leading {@linkcode ,to_date commas} are also accepted, where the current date and earliest known date will be designated respectively. @property {external:ISO8601} [updated_at_range] - The date for when the item was updated. Specify the date range by using ISO-8601 variables separated by a comma: {@linkcode from_date,to_date}. Trailing {@linkcode from_date,} and leading {@linkcode ,to_date commas} are also accepted, where the current date and earliest known date will be designated respectively. @property {number} [size_range] - Filter by a file size range. Specify the file size range in bytes separated by a comma: {@linkcode lower_bound_size,upper_bound_size}, where 1MB is equivalent to 1000000 bytes. Trailing {@linkcode lower_bound_size,} and leading {@linkcode ,upper_bound_size} commas are also accepted as parameters. @property {string} [owner_user_ids] - Search by item owners. Requires one or a set of comma delimited user_ids. @property {string} [ancestor_folder_ids] - Limit searches to specific parent folders. Requires one or a set of comma delimited folder_ids: {@linkcode folder_id_1,folder_id_2,...}. Parent folder results will also include items within subfolders. @property {string} [content_types] - Limit searches to specific Box designated content types. Can be {@linkcode name}, {@linkcode description}, {@linkcode file_content}, {@linkcode comments}, or {@linkcode tags}. Requires one or a set of comma delimited content_types. @property {string} [type] - The type you want to return in your search. Can be {@linkcode file}, {@linkcode folder}, or {@linkcode web_link}. @property {number} [limit] - Number of search results to return. Default: 30, Max :200. @property {number} [offset] - The search result at which to start the response. Default: 0. @see {@link https://developers.box.com/docs/#search} Provides a simple way of finding items that are accessible in a given user’s Box account. @summary Search a user's account. @see {@link https://developers.box.com/docs/#search} @param {string} query - The search keyword. @param {?OptsSearch} opts - Additional search options. @param {requestCallback} done - The callback to invoke (with possible errors) when the request returns. @param {?RequestConfig} [config] - Configure the request behaviour.
[ "Options", "and", "parameters", "for", "search", "." ]
b8403df59d53ba4e8bed5de3675467544981a683
https://github.com/adityamukho/node-box-sdk/blob/b8403df59d53ba4e8bed5de3675467544981a683/lib/api/content/search.js#L59-L68
46,529
paritytech/js-jsonrpc
scripts/build-rpc-markdown.js
hasExample
function hasExample ({ optional, example, details } = {}) { if (optional || example !== undefined) { return true; } if (details !== undefined) { const values = Object.keys(details).map((key) => details[key]); return values.every(hasExample); } return false; }
javascript
function hasExample ({ optional, example, details } = {}) { if (optional || example !== undefined) { return true; } if (details !== undefined) { const values = Object.keys(details).map((key) => details[key]); return values.every(hasExample); } return false; }
[ "function", "hasExample", "(", "{", "optional", ",", "example", ",", "details", "}", "=", "{", "}", ")", "{", "if", "(", "optional", "||", "example", "!==", "undefined", ")", "{", "return", "true", ";", "}", "if", "(", "details", "!==", "undefined", ")", "{", "const", "values", "=", "Object", ".", "keys", "(", "details", ")", ".", "map", "(", "(", "key", ")", "=>", "details", "[", "key", "]", ")", ";", "return", "values", ".", "every", "(", "hasExample", ")", ";", "}", "return", "false", ";", "}" ]
Checks if a field definition has an example, or describes an object with fields that recursively have examples of their own, or is optional.
[ "Checks", "if", "a", "field", "definition", "has", "an", "example", "or", "describes", "an", "object", "with", "fields", "that", "recursively", "have", "examples", "of", "their", "own", "or", "is", "optional", "." ]
045b8953926cbc0f663de328954f1ca4ba8a4e7c
https://github.com/paritytech/js-jsonrpc/blob/045b8953926cbc0f663de328954f1ca4ba8a4e7c/scripts/build-rpc-markdown.js#L88-L100
46,530
paritytech/js-jsonrpc
scripts/build-rpc-markdown.js
getExample
function getExample (obj) { if (isArray(obj)) { return removeOptionalWithoutExamples(obj).map(getExample); } const { example, details } = obj; if (example === undefined && details !== undefined) { const nested = {}; Object.keys(details).forEach((key) => { nested[key] = getExample(details[key]); }); return nested; } return example; }
javascript
function getExample (obj) { if (isArray(obj)) { return removeOptionalWithoutExamples(obj).map(getExample); } const { example, details } = obj; if (example === undefined && details !== undefined) { const nested = {}; Object.keys(details).forEach((key) => { nested[key] = getExample(details[key]); }); return nested; } return example; }
[ "function", "getExample", "(", "obj", ")", "{", "if", "(", "isArray", "(", "obj", ")", ")", "{", "return", "removeOptionalWithoutExamples", "(", "obj", ")", ".", "map", "(", "getExample", ")", ";", "}", "const", "{", "example", ",", "details", "}", "=", "obj", ";", "if", "(", "example", "===", "undefined", "&&", "details", "!==", "undefined", ")", "{", "const", "nested", "=", "{", "}", ";", "Object", ".", "keys", "(", "details", ")", ".", "forEach", "(", "(", "key", ")", "=>", "{", "nested", "[", "key", "]", "=", "getExample", "(", "details", "[", "key", "]", ")", ";", "}", ")", ";", "return", "nested", ";", "}", "return", "example", ";", "}" ]
Grabs JSON compatible
[ "Grabs", "JSON", "compatible" ]
045b8953926cbc0f663de328954f1ca4ba8a4e7c
https://github.com/paritytech/js-jsonrpc/blob/045b8953926cbc0f663de328954f1ca4ba8a4e7c/scripts/build-rpc-markdown.js#L110-L128
46,531
paritytech/js-jsonrpc
scripts/build-rpc-markdown.js
methodComparator
function methodComparator (a, b) { const sectionA = spec[a].section || ''; const sectionB = spec[b].section || ''; return sectionA.localeCompare(sectionB) || a.localeCompare(b); }
javascript
function methodComparator (a, b) { const sectionA = spec[a].section || ''; const sectionB = spec[b].section || ''; return sectionA.localeCompare(sectionB) || a.localeCompare(b); }
[ "function", "methodComparator", "(", "a", ",", "b", ")", "{", "const", "sectionA", "=", "spec", "[", "a", "]", ".", "section", "||", "''", ";", "const", "sectionB", "=", "spec", "[", "b", "]", ".", "section", "||", "''", ";", "return", "sectionA", ".", "localeCompare", "(", "sectionB", ")", "||", "a", ".", "localeCompare", "(", "b", ")", ";", "}" ]
Comparator that will sort by sections first, names second
[ "Comparator", "that", "will", "sort", "by", "sections", "first", "names", "second" ]
045b8953926cbc0f663de328954f1ca4ba8a4e7c
https://github.com/paritytech/js-jsonrpc/blob/045b8953926cbc0f663de328954f1ca4ba8a4e7c/scripts/build-rpc-markdown.js#L283-L288
46,532
quantmind/d3-visualize
src/transforms/aggregate.js
group
function group (frame) { let v, name, op; const entries = fields.map((field, index) => { name = ops[index]; op = scalar_operations.get('count'); if (name) { op = scalar_operations.get(name); if (!op) { op = scalar_operations.get('count'); warn(`Operation ${name} is not supported, use count`); } } return { field: field, as: as[index] || field, op: op }; }); return frame.dimension(groupby).group().reduce((o, record) => { return entries.reduce((oo, entry) => { v = 0; if (entry.as in oo) v = oo[entry.as]; oo[entry.as] = entry.op(v, record[entry.field]); return oo; }, o); }, null, Object).all().map(d => { d.value[groupby] = d.key; return d.value; }); }
javascript
function group (frame) { let v, name, op; const entries = fields.map((field, index) => { name = ops[index]; op = scalar_operations.get('count'); if (name) { op = scalar_operations.get(name); if (!op) { op = scalar_operations.get('count'); warn(`Operation ${name} is not supported, use count`); } } return { field: field, as: as[index] || field, op: op }; }); return frame.dimension(groupby).group().reduce((o, record) => { return entries.reduce((oo, entry) => { v = 0; if (entry.as in oo) v = oo[entry.as]; oo[entry.as] = entry.op(v, record[entry.field]); return oo; }, o); }, null, Object).all().map(d => { d.value[groupby] = d.key; return d.value; }); }
[ "function", "group", "(", "frame", ")", "{", "let", "v", ",", "name", ",", "op", ";", "const", "entries", "=", "fields", ".", "map", "(", "(", "field", ",", "index", ")", "=>", "{", "name", "=", "ops", "[", "index", "]", ";", "op", "=", "scalar_operations", ".", "get", "(", "'count'", ")", ";", "if", "(", "name", ")", "{", "op", "=", "scalar_operations", ".", "get", "(", "name", ")", ";", "if", "(", "!", "op", ")", "{", "op", "=", "scalar_operations", ".", "get", "(", "'count'", ")", ";", "warn", "(", "`", "${", "name", "}", "`", ")", ";", "}", "}", "return", "{", "field", ":", "field", ",", "as", ":", "as", "[", "index", "]", "||", "field", ",", "op", ":", "op", "}", ";", "}", ")", ";", "return", "frame", ".", "dimension", "(", "groupby", ")", ".", "group", "(", ")", ".", "reduce", "(", "(", "o", ",", "record", ")", "=>", "{", "return", "entries", ".", "reduce", "(", "(", "oo", ",", "entry", ")", "=>", "{", "v", "=", "0", ";", "if", "(", "entry", ".", "as", "in", "oo", ")", "v", "=", "oo", "[", "entry", ".", "as", "]", ";", "oo", "[", "entry", ".", "as", "]", "=", "entry", ".", "op", "(", "v", ",", "record", "[", "entry", ".", "field", "]", ")", ";", "return", "oo", ";", "}", ",", "o", ")", ";", "}", ",", "null", ",", "Object", ")", ".", "all", "(", ")", ".", "map", "(", "d", "=>", "{", "d", ".", "value", "[", "groupby", "]", "=", "d", ".", "key", ";", "return", "d", ".", "value", ";", "}", ")", ";", "}" ]
Perform aggregation with a set of data fields to group by
[ "Perform", "aggregation", "with", "a", "set", "of", "data", "fields", "to", "group", "by" ]
67dac5a3ea5146eb70eb975667b49cf3827a5df7
https://github.com/quantmind/d3-visualize/blob/67dac5a3ea5146eb70eb975667b49cf3827a5df7/src/transforms/aggregate.js#L93-L123
46,533
ralphv/zoran
index.js
function(func, name) { return proxy.createProxy(func, handlers.beforeFunc, handlers.afterFunc, {attachMonitor: true}, name); }
javascript
function(func, name) { return proxy.createProxy(func, handlers.beforeFunc, handlers.afterFunc, {attachMonitor: true}, name); }
[ "function", "(", "func", ",", "name", ")", "{", "return", "proxy", ".", "createProxy", "(", "func", ",", "handlers", ".", "beforeFunc", ",", "handlers", ".", "afterFunc", ",", "{", "attachMonitor", ":", "true", "}", ",", "name", ")", ";", "}" ]
Manually attach a monitor to a single function @param {function} func the function reference to monitor @param {string} name the name of the function, this will be the main identifier in the statistics produced @returns {function} the new function reference that should replace the passed in reference
[ "Manually", "attach", "a", "monitor", "to", "a", "single", "function" ]
b8f83d37e32ca496353b6e1981fa09e25de3cc35
https://github.com/ralphv/zoran/blob/b8f83d37e32ca496353b6e1981fa09e25de3cc35/index.js#L112-L114
46,534
ralphv/zoran
index.js
function(name, args) { var callInstance = {name: name}; handlers.beforeFunc({name: name}, null, args, callInstance); return callInstance; }
javascript
function(name, args) { var callInstance = {name: name}; handlers.beforeFunc({name: name}, null, args, callInstance); return callInstance; }
[ "function", "(", "name", ",", "args", ")", "{", "var", "callInstance", "=", "{", "name", ":", "name", "}", ";", "handlers", ".", "beforeFunc", "(", "{", "name", ":", "name", "}", ",", "null", ",", "args", ",", "callInstance", ")", ";", "return", "callInstance", ";", "}" ]
Manually call at the beginning of a certain operation you want to measure @param {string} name this will be the main identifier in the statistics produced @param {array} args arguments of arguments @returns {{}} the callInstance object, you must pass this to the matching end function
[ "Manually", "call", "at", "the", "beginning", "of", "a", "certain", "operation", "you", "want", "to", "measure" ]
b8f83d37e32ca496353b6e1981fa09e25de3cc35
https://github.com/ralphv/zoran/blob/b8f83d37e32ca496353b6e1981fa09e25de3cc35/index.js#L122-L126
46,535
ralphv/zoran
index.js
function(args, callInstance) { handlers.afterFunc({name: callInstance.name}, null, args, callInstance); }
javascript
function(args, callInstance) { handlers.afterFunc({name: callInstance.name}, null, args, callInstance); }
[ "function", "(", "args", ",", "callInstance", ")", "{", "handlers", ".", "afterFunc", "(", "{", "name", ":", "callInstance", ".", "name", "}", ",", "null", ",", "args", ",", "callInstance", ")", ";", "}" ]
Manually call at the end of a certain operation you want to measure @param {array} args args arguments of arguments @param callInstance the return value you got from begin function must be passed here
[ "Manually", "call", "at", "the", "end", "of", "a", "certain", "operation", "you", "want", "to", "measure" ]
b8f83d37e32ca496353b6e1981fa09e25de3cc35
https://github.com/ralphv/zoran/blob/b8f83d37e32ca496353b6e1981fa09e25de3cc35/index.js#L133-L135
46,536
reactbits/fiber
lib/message/uploadbutton.js
UploadButton
function UploadButton(props) { var onClick = function onClick() { var inputStyle = 'display:block;visibility:hidden;width:0;height:0'; var input = $('<input style="' + inputStyle + '" type="file" name="somename" size="chars">'); input.appendTo($('body')); input.change(function () { console.log('uploading...'); var files = input[0].files; console.log(files); var file = files[0]; input.remove(); uploadFile(file, function (data, err) { if (err) { if (_lodash2.default.isFunction(props.onError)) { props.onError(err); } return; } if (_lodash2.default.isFunction(props.onSuccess)) { props.onSuccess(data); } }); }); input.click(); }; var btnProps = { className: _style2.default.upload_button, title: 'Upload files', 'data-toggle': 'tooltip', onMouseDown: onClick }; return _react2.default.createElement( 'a', btnProps, _react2.default.createElement('i', { className: 'ion-camera' }) ); }
javascript
function UploadButton(props) { var onClick = function onClick() { var inputStyle = 'display:block;visibility:hidden;width:0;height:0'; var input = $('<input style="' + inputStyle + '" type="file" name="somename" size="chars">'); input.appendTo($('body')); input.change(function () { console.log('uploading...'); var files = input[0].files; console.log(files); var file = files[0]; input.remove(); uploadFile(file, function (data, err) { if (err) { if (_lodash2.default.isFunction(props.onError)) { props.onError(err); } return; } if (_lodash2.default.isFunction(props.onSuccess)) { props.onSuccess(data); } }); }); input.click(); }; var btnProps = { className: _style2.default.upload_button, title: 'Upload files', 'data-toggle': 'tooltip', onMouseDown: onClick }; return _react2.default.createElement( 'a', btnProps, _react2.default.createElement('i', { className: 'ion-camera' }) ); }
[ "function", "UploadButton", "(", "props", ")", "{", "var", "onClick", "=", "function", "onClick", "(", ")", "{", "var", "inputStyle", "=", "'display:block;visibility:hidden;width:0;height:0'", ";", "var", "input", "=", "$", "(", "'<input style=\"'", "+", "inputStyle", "+", "'\" type=\"file\" name=\"somename\" size=\"chars\">'", ")", ";", "input", ".", "appendTo", "(", "$", "(", "'body'", ")", ")", ";", "input", ".", "change", "(", "function", "(", ")", "{", "console", ".", "log", "(", "'uploading...'", ")", ";", "var", "files", "=", "input", "[", "0", "]", ".", "files", ";", "console", ".", "log", "(", "files", ")", ";", "var", "file", "=", "files", "[", "0", "]", ";", "input", ".", "remove", "(", ")", ";", "uploadFile", "(", "file", ",", "function", "(", "data", ",", "err", ")", "{", "if", "(", "err", ")", "{", "if", "(", "_lodash2", ".", "default", ".", "isFunction", "(", "props", ".", "onError", ")", ")", "{", "props", ".", "onError", "(", "err", ")", ";", "}", "return", ";", "}", "if", "(", "_lodash2", ".", "default", ".", "isFunction", "(", "props", ".", "onSuccess", ")", ")", "{", "props", ".", "onSuccess", "(", "data", ")", ";", "}", "}", ")", ";", "}", ")", ";", "input", ".", "click", "(", ")", ";", "}", ";", "var", "btnProps", "=", "{", "className", ":", "_style2", ".", "default", ".", "upload_button", ",", "title", ":", "'Upload files'", ",", "'data-toggle'", ":", "'tooltip'", ",", "onMouseDown", ":", "onClick", "}", ";", "return", "_react2", ".", "default", ".", "createElement", "(", "'a'", ",", "btnProps", ",", "_react2", ".", "default", ".", "createElement", "(", "'i'", ",", "{", "className", ":", "'ion-camera'", "}", ")", ")", ";", "}" ]
import Upload from 'component-upload';
[ "import", "Upload", "from", "component", "-", "upload", ";" ]
69704fc2083ac3cbd2246a326ee6b8e9c8f52074
https://github.com/reactbits/fiber/blob/69704fc2083ac3cbd2246a326ee6b8e9c8f52074/lib/message/uploadbutton.js#L63-L99
46,537
d-oliveros/isomorphine
src/client/factory.js
createProxies
function createProxies(config, map, parentPath) { parentPath = parentPath || []; var isBase = parentPath.length === 0; var proxies = {}; var path; for (var key in map) { if (map.hasOwnProperty(key)) { if (isObject(map[key])) { proxies[key] = createProxies(config, map[key], parentPath.concat([key])); } else if (isBoolean(map[key])) { path = parentPath.join('/') + (isBase ? '' : '/') + key; proxies[key] = createProxiedMethod(config, path); } } } return proxies; }
javascript
function createProxies(config, map, parentPath) { parentPath = parentPath || []; var isBase = parentPath.length === 0; var proxies = {}; var path; for (var key in map) { if (map.hasOwnProperty(key)) { if (isObject(map[key])) { proxies[key] = createProxies(config, map[key], parentPath.concat([key])); } else if (isBoolean(map[key])) { path = parentPath.join('/') + (isBase ? '' : '/') + key; proxies[key] = createProxiedMethod(config, path); } } } return proxies; }
[ "function", "createProxies", "(", "config", ",", "map", ",", "parentPath", ")", "{", "parentPath", "=", "parentPath", "||", "[", "]", ";", "var", "isBase", "=", "parentPath", ".", "length", "===", "0", ";", "var", "proxies", "=", "{", "}", ";", "var", "path", ";", "for", "(", "var", "key", "in", "map", ")", "{", "if", "(", "map", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "if", "(", "isObject", "(", "map", "[", "key", "]", ")", ")", "{", "proxies", "[", "key", "]", "=", "createProxies", "(", "config", ",", "map", "[", "key", "]", ",", "parentPath", ".", "concat", "(", "[", "key", "]", ")", ")", ";", "}", "else", "if", "(", "isBoolean", "(", "map", "[", "key", "]", ")", ")", "{", "path", "=", "parentPath", ".", "join", "(", "'/'", ")", "+", "(", "isBase", "?", "''", ":", "'/'", ")", "+", "key", ";", "proxies", "[", "key", "]", "=", "createProxiedMethod", "(", "config", ",", "path", ")", ";", "}", "}", "}", "return", "proxies", ";", "}" ]
Creates proxied methods using a provided map. If parentPath is provided, it will be used to build the proxied method's endpoint. @param {Object} map The entity map to use. @param {Array} parentPath The path to the parent entity.
[ "Creates", "proxied", "methods", "using", "a", "provided", "map", ".", "If", "parentPath", "is", "provided", "it", "will", "be", "used", "to", "build", "the", "proxied", "method", "s", "endpoint", "." ]
cb123d16b4be3bb7ec57758bd0b2e43767e91864
https://github.com/d-oliveros/isomorphine/blob/cb123d16b4be3bb7ec57758bd0b2e43767e91864/src/client/factory.js#L68-L88
46,538
d-oliveros/isomorphine
src/client/factory.js
getConfigFromBrowser
function getConfigFromBrowser() { var defaultLocation = { port: '80', hostname: 'localhost', protocol: 'http:' }; var wLocation = (global.location) ? global.location : defaultLocation; var location = { port: wLocation.port, host: wLocation.protocol + '//' + wLocation.hostname }; var config = { port: location.port, host: location.host, errorHandlers: [] }; return config; }
javascript
function getConfigFromBrowser() { var defaultLocation = { port: '80', hostname: 'localhost', protocol: 'http:' }; var wLocation = (global.location) ? global.location : defaultLocation; var location = { port: wLocation.port, host: wLocation.protocol + '//' + wLocation.hostname }; var config = { port: location.port, host: location.host, errorHandlers: [] }; return config; }
[ "function", "getConfigFromBrowser", "(", ")", "{", "var", "defaultLocation", "=", "{", "port", ":", "'80'", ",", "hostname", ":", "'localhost'", ",", "protocol", ":", "'http:'", "}", ";", "var", "wLocation", "=", "(", "global", ".", "location", ")", "?", "global", ".", "location", ":", "defaultLocation", ";", "var", "location", "=", "{", "port", ":", "wLocation", ".", "port", ",", "host", ":", "wLocation", ".", "protocol", "+", "'//'", "+", "wLocation", ".", "hostname", "}", ";", "var", "config", "=", "{", "port", ":", "location", ".", "port", ",", "host", ":", "location", ".", "host", ",", "errorHandlers", ":", "[", "]", "}", ";", "return", "config", ";", "}" ]
Gets the default configuration based on environmental variables @return {Object} Initial config
[ "Gets", "the", "default", "configuration", "based", "on", "environmental", "variables" ]
cb123d16b4be3bb7ec57758bd0b2e43767e91864
https://github.com/d-oliveros/isomorphine/blob/cb123d16b4be3bb7ec57758bd0b2e43767e91864/src/client/factory.js#L94-L117
46,539
paritytech/js-jsonrpc
src/helpers.js
withPreamble
function withPreamble (preamble, spec) { Object.defineProperty(spec, '_preamble', { value: preamble.trim(), enumerable: false }); return spec; }
javascript
function withPreamble (preamble, spec) { Object.defineProperty(spec, '_preamble', { value: preamble.trim(), enumerable: false }); return spec; }
[ "function", "withPreamble", "(", "preamble", ",", "spec", ")", "{", "Object", ".", "defineProperty", "(", "spec", ",", "'_preamble'", ",", "{", "value", ":", "preamble", ".", "trim", "(", ")", ",", "enumerable", ":", "false", "}", ")", ";", "return", "spec", ";", "}" ]
Enrich the API spec by additional markdown-formatted preamble
[ "Enrich", "the", "API", "spec", "by", "additional", "markdown", "-", "formatted", "preamble" ]
045b8953926cbc0f663de328954f1ca4ba8a4e7c
https://github.com/paritytech/js-jsonrpc/blob/045b8953926cbc0f663de328954f1ca4ba8a4e7c/src/helpers.js#L52-L59
46,540
paritytech/js-jsonrpc
src/helpers.js
withComment
function withComment (example, comment) { const constructor = example == null ? null : example.constructor; if (constructor === Object || constructor === Array) { Object.defineProperty(example, '_comment', { value: comment, enumerable: false }); return example; } // Convert primitives return new PrimitiveWithComment(example, comment); }
javascript
function withComment (example, comment) { const constructor = example == null ? null : example.constructor; if (constructor === Object || constructor === Array) { Object.defineProperty(example, '_comment', { value: comment, enumerable: false }); return example; } // Convert primitives return new PrimitiveWithComment(example, comment); }
[ "function", "withComment", "(", "example", ",", "comment", ")", "{", "const", "constructor", "=", "example", "==", "null", "?", "null", ":", "example", ".", "constructor", ";", "if", "(", "constructor", "===", "Object", "||", "constructor", "===", "Array", ")", "{", "Object", ".", "defineProperty", "(", "example", ",", "'_comment'", ",", "{", "value", ":", "comment", ",", "enumerable", ":", "false", "}", ")", ";", "return", "example", ";", "}", "// Convert primitives", "return", "new", "PrimitiveWithComment", "(", "example", ",", "comment", ")", ";", "}" ]
Enrich any example value with a comment to print in the docs
[ "Enrich", "any", "example", "value", "with", "a", "comment", "to", "print", "in", "the", "docs" ]
045b8953926cbc0f663de328954f1ca4ba8a4e7c
https://github.com/paritytech/js-jsonrpc/blob/045b8953926cbc0f663de328954f1ca4ba8a4e7c/src/helpers.js#L62-L76
46,541
vicanso/performance-nodejs
index.js
getDelay
function getDelay(start, interval) { const delta = process.hrtime(start); const nanosec = (delta[0] * 1e9) + delta[1]; /* eslint no-bitwise: ["error", { "int32Hint": true }] */ return Math.max((nanosec / 1e6 | 0) - interval, 0); }
javascript
function getDelay(start, interval) { const delta = process.hrtime(start); const nanosec = (delta[0] * 1e9) + delta[1]; /* eslint no-bitwise: ["error", { "int32Hint": true }] */ return Math.max((nanosec / 1e6 | 0) - interval, 0); }
[ "function", "getDelay", "(", "start", ",", "interval", ")", "{", "const", "delta", "=", "process", ".", "hrtime", "(", "start", ")", ";", "const", "nanosec", "=", "(", "delta", "[", "0", "]", "*", "1e9", ")", "+", "delta", "[", "1", "]", ";", "/* eslint no-bitwise: [\"error\", { \"int32Hint\": true }] */", "return", "Math", ".", "max", "(", "(", "nanosec", "/", "1e6", "|", "0", ")", "-", "interval", ",", "0", ")", ";", "}" ]
Get the dalay of interval @param {Array} start The start time @param {Number} interval The value of interval, ms @returns {Number} The dalay ms
[ "Get", "the", "dalay", "of", "interval" ]
8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca
https://github.com/vicanso/performance-nodejs/blob/8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca/index.js#L34-L39
46,542
vicanso/performance-nodejs
index.js
format
function format(value, unitInfo) { const unit = unitInfo.unit; const precision = unitInfo.precision || 0; let v = 0; switch (unit) { case 'GB': v = value / GB; break; case 'MB': v = value / MB; break; default: v = value; break; } v = parseFloat(Number(v).toFixed(precision)); return v; }
javascript
function format(value, unitInfo) { const unit = unitInfo.unit; const precision = unitInfo.precision || 0; let v = 0; switch (unit) { case 'GB': v = value / GB; break; case 'MB': v = value / MB; break; default: v = value; break; } v = parseFloat(Number(v).toFixed(precision)); return v; }
[ "function", "format", "(", "value", ",", "unitInfo", ")", "{", "const", "unit", "=", "unitInfo", ".", "unit", ";", "const", "precision", "=", "unitInfo", ".", "precision", "||", "0", ";", "let", "v", "=", "0", ";", "switch", "(", "unit", ")", "{", "case", "'GB'", ":", "v", "=", "value", "/", "GB", ";", "break", ";", "case", "'MB'", ":", "v", "=", "value", "/", "MB", ";", "break", ";", "default", ":", "v", "=", "value", ";", "break", ";", "}", "v", "=", "parseFloat", "(", "Number", "(", "v", ")", ".", "toFixed", "(", "precision", ")", ")", ";", "return", "v", ";", "}" ]
Format the bytes by unit @param {Number} value Bytes count @param {Object} unitInfo {unit: String, precision: Number} unit: 'GB', 'MB' or 'B' precision: the precision of size, default is 0 @returns {Number}
[ "Format", "the", "bytes", "by", "unit" ]
8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca
https://github.com/vicanso/performance-nodejs/blob/8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca/index.js#L49-L66
46,543
vicanso/performance-nodejs
index.js
getHeapStatistics
function getHeapStatistics(unitInfo) { const data = v8.getHeapStatistics(); const keys = Object.keys(data); const result = {}; keys.forEach((key) => { result[key] = format(data[key], unitInfo); }); return result; }
javascript
function getHeapStatistics(unitInfo) { const data = v8.getHeapStatistics(); const keys = Object.keys(data); const result = {}; keys.forEach((key) => { result[key] = format(data[key], unitInfo); }); return result; }
[ "function", "getHeapStatistics", "(", "unitInfo", ")", "{", "const", "data", "=", "v8", ".", "getHeapStatistics", "(", ")", ";", "const", "keys", "=", "Object", ".", "keys", "(", "data", ")", ";", "const", "result", "=", "{", "}", ";", "keys", ".", "forEach", "(", "(", "key", ")", "=>", "{", "result", "[", "key", "]", "=", "format", "(", "data", "[", "key", "]", ",", "unitInfo", ")", ";", "}", ")", ";", "return", "result", ";", "}" ]
Get the heap statistics @param {Object} unitInfo The unit format setting @returns {Object} The heap statistics
[ "Get", "the", "heap", "statistics" ]
8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca
https://github.com/vicanso/performance-nodejs/blob/8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca/index.js#L73-L81
46,544
vicanso/performance-nodejs
index.js
getHeapSpaceStatistics
function getHeapSpaceStatistics(unitInfo) { const arr = v8.getHeapSpaceStatistics(); const result = {}; arr.forEach((item) => { const data = {}; const keys = Object.keys(item); keys.forEach((key) => { if (key === 'space_name') { return; } // replace the space_ key prefix data[key.replace('space_', '')] = format(item[key], unitInfo); }); result[item.space_name] = data; }); return result; }
javascript
function getHeapSpaceStatistics(unitInfo) { const arr = v8.getHeapSpaceStatistics(); const result = {}; arr.forEach((item) => { const data = {}; const keys = Object.keys(item); keys.forEach((key) => { if (key === 'space_name') { return; } // replace the space_ key prefix data[key.replace('space_', '')] = format(item[key], unitInfo); }); result[item.space_name] = data; }); return result; }
[ "function", "getHeapSpaceStatistics", "(", "unitInfo", ")", "{", "const", "arr", "=", "v8", ".", "getHeapSpaceStatistics", "(", ")", ";", "const", "result", "=", "{", "}", ";", "arr", ".", "forEach", "(", "(", "item", ")", "=>", "{", "const", "data", "=", "{", "}", ";", "const", "keys", "=", "Object", ".", "keys", "(", "item", ")", ";", "keys", ".", "forEach", "(", "(", "key", ")", "=>", "{", "if", "(", "key", "===", "'space_name'", ")", "{", "return", ";", "}", "// replace the space_ key prefix", "data", "[", "key", ".", "replace", "(", "'space_'", ",", "''", ")", "]", "=", "format", "(", "item", "[", "key", "]", ",", "unitInfo", ")", ";", "}", ")", ";", "result", "[", "item", ".", "space_name", "]", "=", "data", ";", "}", ")", ";", "return", "result", ";", "}" ]
Get the heap space statistics @param {Object} unitInfo The unit format setting @returns {Object} The heap space statistics
[ "Get", "the", "heap", "space", "statistics" ]
8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca
https://github.com/vicanso/performance-nodejs/blob/8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca/index.js#L88-L104
46,545
vicanso/performance-nodejs
index.js
getMemoryUsage
function getMemoryUsage(unitInfo) { const data = process.memoryUsage(); const keys = Object.keys(data); const result = {}; keys.forEach((key) => { result[key] = format(data[key], unitInfo); }); return result; }
javascript
function getMemoryUsage(unitInfo) { const data = process.memoryUsage(); const keys = Object.keys(data); const result = {}; keys.forEach((key) => { result[key] = format(data[key], unitInfo); }); return result; }
[ "function", "getMemoryUsage", "(", "unitInfo", ")", "{", "const", "data", "=", "process", ".", "memoryUsage", "(", ")", ";", "const", "keys", "=", "Object", ".", "keys", "(", "data", ")", ";", "const", "result", "=", "{", "}", ";", "keys", ".", "forEach", "(", "(", "key", ")", "=>", "{", "result", "[", "key", "]", "=", "format", "(", "data", "[", "key", "]", ",", "unitInfo", ")", ";", "}", ")", ";", "return", "result", ";", "}" ]
Get the memory usage @param {Object} unitInfo The unit format setting @returns {Object} The memory usage
[ "Get", "the", "memory", "usage" ]
8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca
https://github.com/vicanso/performance-nodejs/blob/8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca/index.js#L111-L119
46,546
vicanso/performance-nodejs
index.js
get
function get(arr, filter, defaultValue) { let result; arr.forEach((tmp) => { if (tmp && filter(tmp)) { result = tmp; } }); return result || defaultValue; }
javascript
function get(arr, filter, defaultValue) { let result; arr.forEach((tmp) => { if (tmp && filter(tmp)) { result = tmp; } }); return result || defaultValue; }
[ "function", "get", "(", "arr", ",", "filter", ",", "defaultValue", ")", "{", "let", "result", ";", "arr", ".", "forEach", "(", "(", "tmp", ")", "=>", "{", "if", "(", "tmp", "&&", "filter", "(", "tmp", ")", ")", "{", "result", "=", "tmp", ";", "}", "}", ")", ";", "return", "result", "||", "defaultValue", ";", "}" ]
Get the value from array by filter @param {Array} arr The array to filter @param {Function} filter The filter function @param {any} defaultValue The default value for no value is valid @returns {any} The value of filter
[ "Get", "the", "value", "from", "array", "by", "filter" ]
8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca
https://github.com/vicanso/performance-nodejs/blob/8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca/index.js#L128-L136
46,547
vicanso/performance-nodejs
index.js
convertUnit
function convertUnit(str) { const reg = /\.\d*/; const result = reg.exec(str); if (result && result[0]) { return { precision: result[0].length - 1, unit: str.substring(result[0].length + 1), }; } return { unit: str, }; }
javascript
function convertUnit(str) { const reg = /\.\d*/; const result = reg.exec(str); if (result && result[0]) { return { precision: result[0].length - 1, unit: str.substring(result[0].length + 1), }; } return { unit: str, }; }
[ "function", "convertUnit", "(", "str", ")", "{", "const", "reg", "=", "/", "\\.\\d*", "/", ";", "const", "result", "=", "reg", ".", "exec", "(", "str", ")", ";", "if", "(", "result", "&&", "result", "[", "0", "]", ")", "{", "return", "{", "precision", ":", "result", "[", "0", "]", ".", "length", "-", "1", ",", "unit", ":", "str", ".", "substring", "(", "result", "[", "0", "]", ".", "length", "+", "1", ")", ",", "}", ";", "}", "return", "{", "unit", ":", "str", ",", "}", ";", "}" ]
Convert the unit info @param {String} str The unit info @returns {Object} The format unit info
[ "Convert", "the", "unit", "info" ]
8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca
https://github.com/vicanso/performance-nodejs/blob/8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca/index.js#L143-L155
46,548
vicanso/performance-nodejs
index.js
getCpuUsage
function getCpuUsage(previousValue, start) { if (!previousValue) { return null; } const usage = process.cpuUsage(previousValue); const delta = process.hrtime(start); const total = Math.ceil(((delta[0] * 1e9) + delta[1]) / 1000); const usedPercent = Math.round(((usage.user + usage.system) / total) * 100); usage.usedPercent = usedPercent; usage.userUsedPercent = Math.round((usage.user / total) * 100); usage.systemUsedPercent = Math.round((usage.system / total) * 100); usage.total = total; return usage; }
javascript
function getCpuUsage(previousValue, start) { if (!previousValue) { return null; } const usage = process.cpuUsage(previousValue); const delta = process.hrtime(start); const total = Math.ceil(((delta[0] * 1e9) + delta[1]) / 1000); const usedPercent = Math.round(((usage.user + usage.system) / total) * 100); usage.usedPercent = usedPercent; usage.userUsedPercent = Math.round((usage.user / total) * 100); usage.systemUsedPercent = Math.round((usage.system / total) * 100); usage.total = total; return usage; }
[ "function", "getCpuUsage", "(", "previousValue", ",", "start", ")", "{", "if", "(", "!", "previousValue", ")", "{", "return", "null", ";", "}", "const", "usage", "=", "process", ".", "cpuUsage", "(", "previousValue", ")", ";", "const", "delta", "=", "process", ".", "hrtime", "(", "start", ")", ";", "const", "total", "=", "Math", ".", "ceil", "(", "(", "(", "delta", "[", "0", "]", "*", "1e9", ")", "+", "delta", "[", "1", "]", ")", "/", "1000", ")", ";", "const", "usedPercent", "=", "Math", ".", "round", "(", "(", "(", "usage", ".", "user", "+", "usage", ".", "system", ")", "/", "total", ")", "*", "100", ")", ";", "usage", ".", "usedPercent", "=", "usedPercent", ";", "usage", ".", "userUsedPercent", "=", "Math", ".", "round", "(", "(", "usage", ".", "user", "/", "total", ")", "*", "100", ")", ";", "usage", ".", "systemUsedPercent", "=", "Math", ".", "round", "(", "(", "usage", ".", "system", "/", "total", ")", "*", "100", ")", ";", "usage", ".", "total", "=", "total", ";", "return", "usage", ";", "}" ]
Get the cpu usage @param {Object} previousValue The previous cpu usage @param {Array} start The previous process.hrtime @returns {Object} The cpu usage { user: Number, system: Number, usedPercent: Number, userUsedPercent: Number, systemUsedPercent: Number, total: total }
[ "Get", "the", "cpu", "usage" ]
8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca
https://github.com/vicanso/performance-nodejs/blob/8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca/index.js#L170-L183
46,549
vicanso/performance-nodejs
index.js
camelCaseData
function camelCaseData(data) { const result = {}; const keys = Object.keys(data); keys.forEach((k) => { const key = camelCase(k); const value = data[k]; if (isObject(value)) { result[key] = camelCaseData(value); } else { result[key] = value; } }); return result; }
javascript
function camelCaseData(data) { const result = {}; const keys = Object.keys(data); keys.forEach((k) => { const key = camelCase(k); const value = data[k]; if (isObject(value)) { result[key] = camelCaseData(value); } else { result[key] = value; } }); return result; }
[ "function", "camelCaseData", "(", "data", ")", "{", "const", "result", "=", "{", "}", ";", "const", "keys", "=", "Object", ".", "keys", "(", "data", ")", ";", "keys", ".", "forEach", "(", "(", "k", ")", "=>", "{", "const", "key", "=", "camelCase", "(", "k", ")", ";", "const", "value", "=", "data", "[", "k", "]", ";", "if", "(", "isObject", "(", "value", ")", ")", "{", "result", "[", "key", "]", "=", "camelCaseData", "(", "value", ")", ";", "}", "else", "{", "result", "[", "key", "]", "=", "value", ";", "}", "}", ")", ";", "return", "result", ";", "}" ]
Convert the data to camel case @param {Object} data @returns
[ "Convert", "the", "data", "to", "camel", "case" ]
8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca
https://github.com/vicanso/performance-nodejs/blob/8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca/index.js#L191-L204
46,550
vicanso/performance-nodejs
index.js
flatten
function flatten(data, pre) { const prefix = pre || ''; const keys = Object.keys(data); const result = {}; keys.forEach((k) => { const value = data[k]; const key = [prefix, k].join('-'); if (isObject(value)) { Object.assign(result, flatten(value, key)); } else { result[key] = value; } }); return result; }
javascript
function flatten(data, pre) { const prefix = pre || ''; const keys = Object.keys(data); const result = {}; keys.forEach((k) => { const value = data[k]; const key = [prefix, k].join('-'); if (isObject(value)) { Object.assign(result, flatten(value, key)); } else { result[key] = value; } }); return result; }
[ "function", "flatten", "(", "data", ",", "pre", ")", "{", "const", "prefix", "=", "pre", "||", "''", ";", "const", "keys", "=", "Object", ".", "keys", "(", "data", ")", ";", "const", "result", "=", "{", "}", ";", "keys", ".", "forEach", "(", "(", "k", ")", "=>", "{", "const", "value", "=", "data", "[", "k", "]", ";", "const", "key", "=", "[", "prefix", ",", "k", "]", ".", "join", "(", "'-'", ")", ";", "if", "(", "isObject", "(", "value", ")", ")", "{", "Object", ".", "assign", "(", "result", ",", "flatten", "(", "value", ",", "key", ")", ")", ";", "}", "else", "{", "result", "[", "key", "]", "=", "value", ";", "}", "}", ")", ";", "return", "result", ";", "}" ]
Flatten the data @param {Object} data @returns
[ "Flatten", "the", "data" ]
8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca
https://github.com/vicanso/performance-nodejs/blob/8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca/index.js#L212-L226
46,551
vicanso/performance-nodejs
index.js
performance
function performance() { /* eslint prefer-rest-params: 0 */ const args = Array.from(arguments); const interval = get(args, isNumber, 100); const fn = get(args, isFunction, noop); const unitInfo = convertUnit(get(args, isString, 'B').toUpperCase()); let start = process.hrtime(); let cpuUsage = process.cpuUsage && process.cpuUsage(); const timer = setInterval(() => { let result = { lag: getDelay(start, interval), heap: getHeapStatistics(unitInfo), memoryUsage: getMemoryUsage(unitInfo), }; if (cpuUsage) { result.cpuUsage = getCpuUsage(cpuUsage, start); } if (v8.getHeapSpaceStatistics) { result.heapSpace = getHeapSpaceStatistics(unitInfo); } if (performance.flatten) { result = flatten(result); } if (performance.camelCase) { result = camelCaseData(result); } fn(result); start = process.hrtime(); cpuUsage = process.cpuUsage && process.cpuUsage(); }, interval); timer.unref(); return timer; }
javascript
function performance() { /* eslint prefer-rest-params: 0 */ const args = Array.from(arguments); const interval = get(args, isNumber, 100); const fn = get(args, isFunction, noop); const unitInfo = convertUnit(get(args, isString, 'B').toUpperCase()); let start = process.hrtime(); let cpuUsage = process.cpuUsage && process.cpuUsage(); const timer = setInterval(() => { let result = { lag: getDelay(start, interval), heap: getHeapStatistics(unitInfo), memoryUsage: getMemoryUsage(unitInfo), }; if (cpuUsage) { result.cpuUsage = getCpuUsage(cpuUsage, start); } if (v8.getHeapSpaceStatistics) { result.heapSpace = getHeapSpaceStatistics(unitInfo); } if (performance.flatten) { result = flatten(result); } if (performance.camelCase) { result = camelCaseData(result); } fn(result); start = process.hrtime(); cpuUsage = process.cpuUsage && process.cpuUsage(); }, interval); timer.unref(); return timer; }
[ "function", "performance", "(", ")", "{", "/* eslint prefer-rest-params: 0 */", "const", "args", "=", "Array", ".", "from", "(", "arguments", ")", ";", "const", "interval", "=", "get", "(", "args", ",", "isNumber", ",", "100", ")", ";", "const", "fn", "=", "get", "(", "args", ",", "isFunction", ",", "noop", ")", ";", "const", "unitInfo", "=", "convertUnit", "(", "get", "(", "args", ",", "isString", ",", "'B'", ")", ".", "toUpperCase", "(", ")", ")", ";", "let", "start", "=", "process", ".", "hrtime", "(", ")", ";", "let", "cpuUsage", "=", "process", ".", "cpuUsage", "&&", "process", ".", "cpuUsage", "(", ")", ";", "const", "timer", "=", "setInterval", "(", "(", ")", "=>", "{", "let", "result", "=", "{", "lag", ":", "getDelay", "(", "start", ",", "interval", ")", ",", "heap", ":", "getHeapStatistics", "(", "unitInfo", ")", ",", "memoryUsage", ":", "getMemoryUsage", "(", "unitInfo", ")", ",", "}", ";", "if", "(", "cpuUsage", ")", "{", "result", ".", "cpuUsage", "=", "getCpuUsage", "(", "cpuUsage", ",", "start", ")", ";", "}", "if", "(", "v8", ".", "getHeapSpaceStatistics", ")", "{", "result", ".", "heapSpace", "=", "getHeapSpaceStatistics", "(", "unitInfo", ")", ";", "}", "if", "(", "performance", ".", "flatten", ")", "{", "result", "=", "flatten", "(", "result", ")", ";", "}", "if", "(", "performance", ".", "camelCase", ")", "{", "result", "=", "camelCaseData", "(", "result", ")", ";", "}", "fn", "(", "result", ")", ";", "start", "=", "process", ".", "hrtime", "(", ")", ";", "cpuUsage", "=", "process", ".", "cpuUsage", "&&", "process", ".", "cpuUsage", "(", ")", ";", "}", ",", "interval", ")", ";", "timer", ".", "unref", "(", ")", ";", "return", "timer", ";", "}" ]
Get the performance of node, include lag, heap, heapSpace, cpuUsage, memoryUsage @param {Function} fn The callback function of performance @param {Interval} interval The interval of get performance @returns {Timer} The setInterval timer
[ "Get", "the", "performance", "of", "node", "include", "lag", "heap", "heapSpace", "cpuUsage", "memoryUsage" ]
8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca
https://github.com/vicanso/performance-nodejs/blob/8c65a819c8cfef2cbe77c2abae3f8cb7d4373cca/index.js#L234-L266
46,552
epeli/node-clim
index.js
consoleProxy
function consoleProxy(ob){ // list from http://nodejs.org/api/stdio.html var methods = ["dir", "time", "timeEnd", "trace", "assert"]; methods.forEach(function(method){ if (ob[method]) return; ob[method] = function(){ return console[method].apply(console, arguments); }; }); }
javascript
function consoleProxy(ob){ // list from http://nodejs.org/api/stdio.html var methods = ["dir", "time", "timeEnd", "trace", "assert"]; methods.forEach(function(method){ if (ob[method]) return; ob[method] = function(){ return console[method].apply(console, arguments); }; }); }
[ "function", "consoleProxy", "(", "ob", ")", "{", "// list from http://nodejs.org/api/stdio.html", "var", "methods", "=", "[", "\"dir\"", ",", "\"time\"", ",", "\"timeEnd\"", ",", "\"trace\"", ",", "\"assert\"", "]", ";", "methods", ".", "forEach", "(", "function", "(", "method", ")", "{", "if", "(", "ob", "[", "method", "]", ")", "return", ";", "ob", "[", "method", "]", "=", "function", "(", ")", "{", "return", "console", "[", "method", "]", ".", "apply", "(", "console", ",", "arguments", ")", ";", "}", ";", "}", ")", ";", "}" ]
Just proxy methods we don't care about to original console object
[ "Just", "proxy", "methods", "we", "don", "t", "care", "about", "to", "original", "console", "object" ]
93a692976d4dda04992f729d4b6483af11394ad9
https://github.com/epeli/node-clim/blob/93a692976d4dda04992f729d4b6483af11394ad9/index.js#L65-L74
46,553
dunckr/retext-overuse
index.js
getOveruse
function getOveruse(duplicates, limit) { var duplicate; for (duplicate in duplicates) { if (duplicates[duplicate] < limit) { delete duplicates[duplicate] } } return keys(duplicates); }
javascript
function getOveruse(duplicates, limit) { var duplicate; for (duplicate in duplicates) { if (duplicates[duplicate] < limit) { delete duplicates[duplicate] } } return keys(duplicates); }
[ "function", "getOveruse", "(", "duplicates", ",", "limit", ")", "{", "var", "duplicate", ";", "for", "(", "duplicate", "in", "duplicates", ")", "{", "if", "(", "duplicates", "[", "duplicate", "]", "<", "limit", ")", "{", "delete", "duplicates", "[", "duplicate", "]", "}", "}", "return", "keys", "(", "duplicates", ")", ";", "}" ]
Get duplicates that are used too frequently. @param {Object} duplicates - Phrases to search for. @param {number} limit - Number of times phrase must have been used. @return {Array.<string>}
[ "Get", "duplicates", "that", "are", "used", "too", "frequently", "." ]
4fc1a408cf24c11976f65a88f7e958dc3f868198
https://github.com/dunckr/retext-overuse/blob/4fc1a408cf24c11976f65a88f7e958dc3f868198/index.js#L49-L57
46,554
thysultan/jsx.js
index.js
use
function use (filepath, destination) { var startTime = Date.now(); var text = read(filepath); if (text !== false) { fs.writeFile(destination, jsx(text), function (err) { if (err) { throw err; } var endTime = Date.now(); log('[Finished in ' + (endTime - startTime) + 'ms]'); }); } else { log('no such file exits, ' + filepath); } }
javascript
function use (filepath, destination) { var startTime = Date.now(); var text = read(filepath); if (text !== false) { fs.writeFile(destination, jsx(text), function (err) { if (err) { throw err; } var endTime = Date.now(); log('[Finished in ' + (endTime - startTime) + 'ms]'); }); } else { log('no such file exits, ' + filepath); } }
[ "function", "use", "(", "filepath", ",", "destination", ")", "{", "var", "startTime", "=", "Date", ".", "now", "(", ")", ";", "var", "text", "=", "read", "(", "filepath", ")", ";", "if", "(", "text", "!==", "false", ")", "{", "fs", ".", "writeFile", "(", "destination", ",", "jsx", "(", "text", ")", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "throw", "err", ";", "}", "var", "endTime", "=", "Date", ".", "now", "(", ")", ";", "log", "(", "'[Finished in '", "+", "(", "endTime", "-", "startTime", ")", "+", "'ms]'", ")", ";", "}", ")", ";", "}", "else", "{", "log", "(", "'no such file exits, '", "+", "filepath", ")", ";", "}", "}" ]
use the file to transpile
[ "use", "the", "file", "to", "transpile" ]
8bac10d311d30dd9f2eb9c5b853635518414782a
https://github.com/thysultan/jsx.js/blob/8bac10d311d30dd9f2eb9c5b853635518414782a/index.js#L36-L50
46,555
alexindigo/node-envar
index.js
envar
function envar(key) { var i, value; // be extra paranoid if (typeof key != 'string' || !key) return undefined; // lookup according to the order for (i=0; i<state.order.length; i++) { if ((value = lookup[state.order[i]](key)) !== undefined) { return value; } } // nothing found return undefined; }
javascript
function envar(key) { var i, value; // be extra paranoid if (typeof key != 'string' || !key) return undefined; // lookup according to the order for (i=0; i<state.order.length; i++) { if ((value = lookup[state.order[i]](key)) !== undefined) { return value; } } // nothing found return undefined; }
[ "function", "envar", "(", "key", ")", "{", "var", "i", ",", "value", ";", "// be extra paranoid", "if", "(", "typeof", "key", "!=", "'string'", "||", "!", "key", ")", "return", "undefined", ";", "// lookup according to the order", "for", "(", "i", "=", "0", ";", "i", "<", "state", ".", "order", ".", "length", ";", "i", "++", ")", "{", "if", "(", "(", "value", "=", "lookup", "[", "state", ".", "order", "[", "i", "]", "]", "(", "key", ")", ")", "!==", "undefined", ")", "{", "return", "value", ";", "}", "}", "// nothing found", "return", "undefined", ";", "}" ]
Looks up requested variable @param {string} key - variable name to look for @returns {mixed} - found variable or `undefined` if nothing found
[ "Looks", "up", "requested", "variable" ]
8599dbb82d6e160704543ff5d6623b6d49c501fb
https://github.com/alexindigo/node-envar/blob/8599dbb82d6e160704543ff5d6623b6d49c501fb/index.js#L41-L59
46,556
ndp/csster
src/ie/rounded_corners.js
roundedCorners
function roundedCorners(side, radius) { if (!radius) { radius = side || 10; side = 'all'; } if (side == 'all') { if (browserInfo().msie) { return { 'border-radius': radius, behavior: 'url(border-radius-ie.htc)', visibility: 'hidden' } } else if (browserInfo().mozilla) { return { '-moz-border-radius': radius } } else { return { 'border-radius': radius, '-webkit-border-radius': radius } } } else { var rules = {}; if (side == 'tl' || side == 'top' || side == 'left') { rules['-moz-border-radius-topleft'] = radius; rules['-webkit-border-top-left-radius'] = radius; rules['border-top-left-radius'] = radius; } if (side == 'tr' || side == 'top' || side == 'right') { rules['-webkit-border-top-right-radius'] = radius; rules['-moz-border-radius-topright'] = radius; rules['border-top-right-radius'] = radius; } if (side == 'bl' || side == 'bottom' || side == 'left') { rules['-webkit-border-bottom-left-radius'] = radius; rules['-moz-border-radius-bottomleft'] = radius; rules['border-bottom-left-radius'] = radius; } if (side == 'br' || side == 'bottom' || side == 'right') { rules['-webkit-border-bottom-right-radius'] = radius; rules['-moz-border-radius-bottomright'] = radius; rules['border-bottom-right-radius'] = radius; } return rules; } }
javascript
function roundedCorners(side, radius) { if (!radius) { radius = side || 10; side = 'all'; } if (side == 'all') { if (browserInfo().msie) { return { 'border-radius': radius, behavior: 'url(border-radius-ie.htc)', visibility: 'hidden' } } else if (browserInfo().mozilla) { return { '-moz-border-radius': radius } } else { return { 'border-radius': radius, '-webkit-border-radius': radius } } } else { var rules = {}; if (side == 'tl' || side == 'top' || side == 'left') { rules['-moz-border-radius-topleft'] = radius; rules['-webkit-border-top-left-radius'] = radius; rules['border-top-left-radius'] = radius; } if (side == 'tr' || side == 'top' || side == 'right') { rules['-webkit-border-top-right-radius'] = radius; rules['-moz-border-radius-topright'] = radius; rules['border-top-right-radius'] = radius; } if (side == 'bl' || side == 'bottom' || side == 'left') { rules['-webkit-border-bottom-left-radius'] = radius; rules['-moz-border-radius-bottomleft'] = radius; rules['border-bottom-left-radius'] = radius; } if (side == 'br' || side == 'bottom' || side == 'right') { rules['-webkit-border-bottom-right-radius'] = radius; rules['-moz-border-radius-bottomright'] = radius; rules['border-bottom-right-radius'] = radius; } return rules; } }
[ "function", "roundedCorners", "(", "side", ",", "radius", ")", "{", "if", "(", "!", "radius", ")", "{", "radius", "=", "side", "||", "10", ";", "side", "=", "'all'", ";", "}", "if", "(", "side", "==", "'all'", ")", "{", "if", "(", "browserInfo", "(", ")", ".", "msie", ")", "{", "return", "{", "'border-radius'", ":", "radius", ",", "behavior", ":", "'url(border-radius-ie.htc)'", ",", "visibility", ":", "'hidden'", "}", "}", "else", "if", "(", "browserInfo", "(", ")", ".", "mozilla", ")", "{", "return", "{", "'-moz-border-radius'", ":", "radius", "}", "}", "else", "{", "return", "{", "'border-radius'", ":", "radius", ",", "'-webkit-border-radius'", ":", "radius", "}", "}", "}", "else", "{", "var", "rules", "=", "{", "}", ";", "if", "(", "side", "==", "'tl'", "||", "side", "==", "'top'", "||", "side", "==", "'left'", ")", "{", "rules", "[", "'-moz-border-radius-topleft'", "]", "=", "radius", ";", "rules", "[", "'-webkit-border-top-left-radius'", "]", "=", "radius", ";", "rules", "[", "'border-top-left-radius'", "]", "=", "radius", ";", "}", "if", "(", "side", "==", "'tr'", "||", "side", "==", "'top'", "||", "side", "==", "'right'", ")", "{", "rules", "[", "'-webkit-border-top-right-radius'", "]", "=", "radius", ";", "rules", "[", "'-moz-border-radius-topright'", "]", "=", "radius", ";", "rules", "[", "'border-top-right-radius'", "]", "=", "radius", ";", "}", "if", "(", "side", "==", "'bl'", "||", "side", "==", "'bottom'", "||", "side", "==", "'left'", ")", "{", "rules", "[", "'-webkit-border-bottom-left-radius'", "]", "=", "radius", ";", "rules", "[", "'-moz-border-radius-bottomleft'", "]", "=", "radius", ";", "rules", "[", "'border-bottom-left-radius'", "]", "=", "radius", ";", "}", "if", "(", "side", "==", "'br'", "||", "side", "==", "'bottom'", "||", "side", "==", "'right'", ")", "{", "rules", "[", "'-webkit-border-bottom-right-radius'", "]", "=", "radius", ";", "rules", "[", "'-moz-border-radius-bottomright'", "]", "=", "radius", ";", "rules", "[", "'border-bottom-right-radius'", "]", "=", "radius", ";", "}", "return", "rules", ";", "}", "}" ]
Override of Csster's built-in method to support rounded corners on IE. See docs there for description.
[ "Override", "of", "Csster", "s", "built", "-", "in", "method", "to", "support", "rounded", "corners", "on", "IE", ".", "See", "docs", "there", "for", "description", "." ]
d836680b58dc8d6d06dc62c9893aca34c69d3de5
https://github.com/ndp/csster/blob/d836680b58dc8d6d06dc62c9893aca34c69d3de5/src/ie/rounded_corners.js#L7-L54
46,557
graemeboy/matrix-rotate
lib/rotateMatrix.js
transpose
function transpose(matrix) { // For NxN matrix var n = matrix[0].length; var temp; // Walk through columns for (var i = 0, j = 0; i < n; i++) { j = i; // Walk through rows while (j < n) { if (i !== j) { temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } j++; } } }
javascript
function transpose(matrix) { // For NxN matrix var n = matrix[0].length; var temp; // Walk through columns for (var i = 0, j = 0; i < n; i++) { j = i; // Walk through rows while (j < n) { if (i !== j) { temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } j++; } } }
[ "function", "transpose", "(", "matrix", ")", "{", "// For NxN matrix", "var", "n", "=", "matrix", "[", "0", "]", ".", "length", ";", "var", "temp", ";", "// Walk through columns", "for", "(", "var", "i", "=", "0", ",", "j", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "j", "=", "i", ";", "// Walk through rows", "while", "(", "j", "<", "n", ")", "{", "if", "(", "i", "!==", "j", ")", "{", "temp", "=", "matrix", "[", "i", "]", "[", "j", "]", ";", "matrix", "[", "i", "]", "[", "j", "]", "=", "matrix", "[", "j", "]", "[", "i", "]", ";", "matrix", "[", "j", "]", "[", "i", "]", "=", "temp", ";", "}", "j", "++", ";", "}", "}", "}" ]
Transpose a 2D matrix
[ "Transpose", "a", "2D", "matrix" ]
126f52de06cb9c165505db7ba626cf308d586d4a
https://github.com/graemeboy/matrix-rotate/blob/126f52de06cb9c165505db7ba626cf308d586d4a/lib/rotateMatrix.js#L21-L39
46,558
thealjey/webcompiler
lib/webpack.js
getConfig
function getConfig(react) { const loaders = [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel', query: _util.babelFEOptions }, { test: /\.json$/, loader: 'json' }, { test: /jsdom/, loader: 'null' }]; if (react) { loaders.unshift({ test: /\.js$/, exclude: /node_modules/, loader: 'react-hot' }); } return { cache, debug: true, node: { fs: 'empty' }, module: { loaders }, // temporary hack while `react-hot-loader` v3 is not out resolve: { alias: { 'react/lib/ReactMount': 'react-dom/lib/ReactMount' } } }; }
javascript
function getConfig(react) { const loaders = [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel', query: _util.babelFEOptions }, { test: /\.json$/, loader: 'json' }, { test: /jsdom/, loader: 'null' }]; if (react) { loaders.unshift({ test: /\.js$/, exclude: /node_modules/, loader: 'react-hot' }); } return { cache, debug: true, node: { fs: 'empty' }, module: { loaders }, // temporary hack while `react-hot-loader` v3 is not out resolve: { alias: { 'react/lib/ReactMount': 'react-dom/lib/ReactMount' } } }; }
[ "function", "getConfig", "(", "react", ")", "{", "const", "loaders", "=", "[", "{", "test", ":", "/", "\\.js$", "/", ",", "exclude", ":", "/", "node_modules", "/", ",", "loader", ":", "'babel'", ",", "query", ":", "_util", ".", "babelFEOptions", "}", ",", "{", "test", ":", "/", "\\.json$", "/", ",", "loader", ":", "'json'", "}", ",", "{", "test", ":", "/", "jsdom", "/", ",", "loader", ":", "'null'", "}", "]", ";", "if", "(", "react", ")", "{", "loaders", ".", "unshift", "(", "{", "test", ":", "/", "\\.js$", "/", ",", "exclude", ":", "/", "node_modules", "/", ",", "loader", ":", "'react-hot'", "}", ")", ";", "}", "return", "{", "cache", ",", "debug", ":", "true", ",", "node", ":", "{", "fs", ":", "'empty'", "}", ",", "module", ":", "{", "loaders", "}", ",", "// temporary hack while `react-hot-loader` v3 is not out", "resolve", ":", "{", "alias", ":", "{", "'react/lib/ReactMount'", ":", "'react-dom/lib/ReactMount'", "}", "}", "}", ";", "}" ]
Webpack helpers. Mostly for internal use. You can use it to tweak the Babel options. @module webpack @private Returns a webpack configuration object. @memberof module:webpack @private @method getConfig @param {boolean} react - true if the react loader is needed @return {Object} webpack configuration object
[ "Webpack", "helpers", ".", "Mostly", "for", "internal", "use", "." ]
eb094f1632e5313ed0c5391a303150f1416b9629
https://github.com/thealjey/webcompiler/blob/eb094f1632e5313ed0c5391a303150f1416b9629/lib/webpack.js#L59-L94
46,559
thealjey/webcompiler
lib/webpack.js
getCompiler
function getCompiler(inPath, outPath, { library, libraryTarget }) { const compiler = (0, _webpack2.default)(_extends({}, getConfig(false), { devtool: _util.isProduction ? 'source-map' : 'eval-source-map', entry: ['babel-polyfill', inPath], output: { path: (0, _path.dirname)(outPath), filename: (0, _path.basename)(outPath), publicPath: '/', library, libraryTarget }, plugins: _util.isProduction ? productionPlugins : [] })); compiler.outputFileSystem = fakeFS; return compiler; }
javascript
function getCompiler(inPath, outPath, { library, libraryTarget }) { const compiler = (0, _webpack2.default)(_extends({}, getConfig(false), { devtool: _util.isProduction ? 'source-map' : 'eval-source-map', entry: ['babel-polyfill', inPath], output: { path: (0, _path.dirname)(outPath), filename: (0, _path.basename)(outPath), publicPath: '/', library, libraryTarget }, plugins: _util.isProduction ? productionPlugins : [] })); compiler.outputFileSystem = fakeFS; return compiler; }
[ "function", "getCompiler", "(", "inPath", ",", "outPath", ",", "{", "library", ",", "libraryTarget", "}", ")", "{", "const", "compiler", "=", "(", "0", ",", "_webpack2", ".", "default", ")", "(", "_extends", "(", "{", "}", ",", "getConfig", "(", "false", ")", ",", "{", "devtool", ":", "_util", ".", "isProduction", "?", "'source-map'", ":", "'eval-source-map'", ",", "entry", ":", "[", "'babel-polyfill'", ",", "inPath", "]", ",", "output", ":", "{", "path", ":", "(", "0", ",", "_path", ".", "dirname", ")", "(", "outPath", ")", ",", "filename", ":", "(", "0", ",", "_path", ".", "basename", ")", "(", "outPath", ")", ",", "publicPath", ":", "'/'", ",", "library", ",", "libraryTarget", "}", ",", "plugins", ":", "_util", ".", "isProduction", "?", "productionPlugins", ":", "[", "]", "}", ")", ")", ";", "compiler", ".", "outputFileSystem", "=", "fakeFS", ";", "return", "compiler", ";", "}" ]
Returns a webpack Compiler instance. @memberof module:webpack @private @method getCompiler @param {string} inPath - the path to an input file @param {string} outPath - the path to an output file @param {JSCompilerConfig} options - configuration object @return {Object} webpack Compiler instance
[ "Returns", "a", "webpack", "Compiler", "instance", "." ]
eb094f1632e5313ed0c5391a303150f1416b9629
https://github.com/thealjey/webcompiler/blob/eb094f1632e5313ed0c5391a303150f1416b9629/lib/webpack.js#L107-L118
46,560
thealjey/webcompiler
lib/webpack.js
getServer
function getServer(inPath, { react, port, contentBase, configureApplication }) { const server = new _webpackDevServer2.default((0, _webpack2.default)(_extends({}, getConfig(react), { devtool: 'eval-source-map', entry: [`webpack-dev-server/client?http://0.0.0.0:${port}`, 'webpack/hot/only-dev-server', 'babel-polyfill', inPath], output: { path: contentBase, filename: 'script.js', publicPath: '/' }, plugins: serverPlugins })), { contentBase: false, publicPath: '/', hot: true }); server.use((0, _serveStatic2.default)(contentBase)); configureApplication(server.app); return server; }
javascript
function getServer(inPath, { react, port, contentBase, configureApplication }) { const server = new _webpackDevServer2.default((0, _webpack2.default)(_extends({}, getConfig(react), { devtool: 'eval-source-map', entry: [`webpack-dev-server/client?http://0.0.0.0:${port}`, 'webpack/hot/only-dev-server', 'babel-polyfill', inPath], output: { path: contentBase, filename: 'script.js', publicPath: '/' }, plugins: serverPlugins })), { contentBase: false, publicPath: '/', hot: true }); server.use((0, _serveStatic2.default)(contentBase)); configureApplication(server.app); return server; }
[ "function", "getServer", "(", "inPath", ",", "{", "react", ",", "port", ",", "contentBase", ",", "configureApplication", "}", ")", "{", "const", "server", "=", "new", "_webpackDevServer2", ".", "default", "(", "(", "0", ",", "_webpack2", ".", "default", ")", "(", "_extends", "(", "{", "}", ",", "getConfig", "(", "react", ")", ",", "{", "devtool", ":", "'eval-source-map'", ",", "entry", ":", "[", "`", "${", "port", "}", "`", ",", "'webpack/hot/only-dev-server'", ",", "'babel-polyfill'", ",", "inPath", "]", ",", "output", ":", "{", "path", ":", "contentBase", ",", "filename", ":", "'script.js'", ",", "publicPath", ":", "'/'", "}", ",", "plugins", ":", "serverPlugins", "}", ")", ")", ",", "{", "contentBase", ":", "false", ",", "publicPath", ":", "'/'", ",", "hot", ":", "true", "}", ")", ";", "server", ".", "use", "(", "(", "0", ",", "_serveStatic2", ".", "default", ")", "(", "contentBase", ")", ")", ";", "configureApplication", "(", "server", ".", "app", ")", ";", "return", "server", ";", "}" ]
Returns a webpack development server instance. @memberof module:webpack @private @method getServer @param {string} inPath - the path to an input file @param {DevServerConfig} options - a config object @return {Object} an instance of the webpack development server
[ "Returns", "a", "webpack", "development", "server", "instance", "." ]
eb094f1632e5313ed0c5391a303150f1416b9629
https://github.com/thealjey/webcompiler/blob/eb094f1632e5313ed0c5391a303150f1416b9629/lib/webpack.js#L130-L142
46,561
svanderburg/nijs
lib/ast/NixInlineJS.js
NixInlineJS
function NixInlineJS(args) { /* Compose the NixInlineJS function's parameters */ var params = {}; if(typeof args.code == "function") { params.codeIsFunction = true; params.code = args.code.toString(); } else { params.codeIsFunction = false; params.code = args.code; } if(args.requires === undefined) params.requires = []; else params.requires = args.requires; if(args.modules === undefined) params.modules = []; else params.modules = args.modules; /* Construct function invocation object to the nijsInlineProxy */ NixFunInvocation.call(this, { funExpr: new nijs.NixExpression("nijsInlineProxy"), paramExpr: params }); }
javascript
function NixInlineJS(args) { /* Compose the NixInlineJS function's parameters */ var params = {}; if(typeof args.code == "function") { params.codeIsFunction = true; params.code = args.code.toString(); } else { params.codeIsFunction = false; params.code = args.code; } if(args.requires === undefined) params.requires = []; else params.requires = args.requires; if(args.modules === undefined) params.modules = []; else params.modules = args.modules; /* Construct function invocation object to the nijsInlineProxy */ NixFunInvocation.call(this, { funExpr: new nijs.NixExpression("nijsInlineProxy"), paramExpr: params }); }
[ "function", "NixInlineJS", "(", "args", ")", "{", "/* Compose the NixInlineJS function's parameters */", "var", "params", "=", "{", "}", ";", "if", "(", "typeof", "args", ".", "code", "==", "\"function\"", ")", "{", "params", ".", "codeIsFunction", "=", "true", ";", "params", ".", "code", "=", "args", ".", "code", ".", "toString", "(", ")", ";", "}", "else", "{", "params", ".", "codeIsFunction", "=", "false", ";", "params", ".", "code", "=", "args", ".", "code", ";", "}", "if", "(", "args", ".", "requires", "===", "undefined", ")", "params", ".", "requires", "=", "[", "]", ";", "else", "params", ".", "requires", "=", "args", ".", "requires", ";", "if", "(", "args", ".", "modules", "===", "undefined", ")", "params", ".", "modules", "=", "[", "]", ";", "else", "params", ".", "modules", "=", "args", ".", "modules", ";", "/* Construct function invocation object to the nijsInlineProxy */", "NixFunInvocation", ".", "call", "(", "this", ",", "{", "funExpr", ":", "new", "nijs", ".", "NixExpression", "(", "\"nijsInlineProxy\"", ")", ",", "paramExpr", ":", "params", "}", ")", ";", "}" ]
Creates a new NixInlineJS instance. @class NixInlineJS @extends NixFunInvocation @classdesc Creates embedded shell code in a string performing a Node.js invocation to execute an inline JavaScript code fragment. @constructor @param {Object} args Arguments to the function @param {Function} args.code A JavaScript function containing code that must be executed @param {Object[]} args.requires An array of objects representing var-module pairs used to include CommonJS modules. var contains the identifier of the variable, the module the path to the CommonJS module @param {Object[]} args.module An array of Nix expressions containing Node.js packages that this function must utilise.
[ "Creates", "a", "new", "NixInlineJS", "instance", "." ]
4e2738cbff3a43aba9297315ca5120cecf8dae3e
https://github.com/svanderburg/nijs/blob/4e2738cbff3a43aba9297315ca5120cecf8dae3e/lib/ast/NixInlineJS.js#L20-L48
46,562
d-oliveros/isomorphine
src/server/controllers.js
getPayload
function getPayload(req, res, next) { req.hasCallback = false; req.payload = req.body.payload || []; // Determines if the request is asynchronous or not req.payload.forEach(function(arg, i) { if (arg === '__clientCallback__') { req.hasCallback = true; req.clientCallbackIndex = i; } }); debug('Got payload' + (req.hasCallback ? ' with callback' : '') + ': ' + JSON.stringify(req.payload, null, 3)); next(); }
javascript
function getPayload(req, res, next) { req.hasCallback = false; req.payload = req.body.payload || []; // Determines if the request is asynchronous or not req.payload.forEach(function(arg, i) { if (arg === '__clientCallback__') { req.hasCallback = true; req.clientCallbackIndex = i; } }); debug('Got payload' + (req.hasCallback ? ' with callback' : '') + ': ' + JSON.stringify(req.payload, null, 3)); next(); }
[ "function", "getPayload", "(", "req", ",", "res", ",", "next", ")", "{", "req", ".", "hasCallback", "=", "false", ";", "req", ".", "payload", "=", "req", ".", "body", ".", "payload", "||", "[", "]", ";", "// Determines if the request is asynchronous or not", "req", ".", "payload", ".", "forEach", "(", "function", "(", "arg", ",", "i", ")", "{", "if", "(", "arg", "===", "'__clientCallback__'", ")", "{", "req", ".", "hasCallback", "=", "true", ";", "req", ".", "clientCallbackIndex", "=", "i", ";", "}", "}", ")", ";", "debug", "(", "'Got payload'", "+", "(", "req", ".", "hasCallback", "?", "' with callback'", ":", "''", ")", "+", "': '", "+", "JSON", ".", "stringify", "(", "req", ".", "payload", ",", "null", ",", "3", ")", ")", ";", "next", "(", ")", ";", "}" ]
Processes the client-side payload, and transforms the client-side callback function signal to an actual callback function
[ "Processes", "the", "client", "-", "side", "payload", "and", "transforms", "the", "client", "-", "side", "callback", "function", "signal", "to", "an", "actual", "callback", "function" ]
cb123d16b4be3bb7ec57758bd0b2e43767e91864
https://github.com/d-oliveros/isomorphine/blob/cb123d16b4be3bb7ec57758bd0b2e43767e91864/src/server/controllers.js#L15-L31
46,563
d-oliveros/isomorphine
src/server/controllers.js
callEntityMethod
function callEntityMethod(req, res, next) { var payload = req.payload; var method = req.serversideMethod; if (req.hasCallback) { debug('Transforming callback function'); payload[req.clientCallbackIndex] = function(err) { if (err) { return next(err); } var values = Array.prototype.slice.call(arguments).slice(1); debug('Callback function called. Values are:', values); res.entityResponse = values; next(); }; } debug('Calling ' + req.path + ' with arguments:', payload); var context = { req: req, xhr: true, setCookie: res.cookie.bind(res), clearCookie: res.clearCookie.bind(res) }; var ret; // Calls the requested serverside method. // Applies the payload, and provides a context for validation purposes. // Caches errors in the method's scope, and sends it to the next error handler. try { ret = method.apply(context, payload); } catch(err) { return next(err); } if (util.isPromise(ret)) { ret.then(function(resolved) { res.entityResponse = [resolved]; next(); }) .catch(function(err) { next(err); }); } // If the request is not expecting the response from the entity, // send a generic 'Ok' response. else if (!req.hasCallback) { res.entityResponse = [ret]; debug('Not asynchronous. Returning value: ', res.entityResponse); next(); } }
javascript
function callEntityMethod(req, res, next) { var payload = req.payload; var method = req.serversideMethod; if (req.hasCallback) { debug('Transforming callback function'); payload[req.clientCallbackIndex] = function(err) { if (err) { return next(err); } var values = Array.prototype.slice.call(arguments).slice(1); debug('Callback function called. Values are:', values); res.entityResponse = values; next(); }; } debug('Calling ' + req.path + ' with arguments:', payload); var context = { req: req, xhr: true, setCookie: res.cookie.bind(res), clearCookie: res.clearCookie.bind(res) }; var ret; // Calls the requested serverside method. // Applies the payload, and provides a context for validation purposes. // Caches errors in the method's scope, and sends it to the next error handler. try { ret = method.apply(context, payload); } catch(err) { return next(err); } if (util.isPromise(ret)) { ret.then(function(resolved) { res.entityResponse = [resolved]; next(); }) .catch(function(err) { next(err); }); } // If the request is not expecting the response from the entity, // send a generic 'Ok' response. else if (!req.hasCallback) { res.entityResponse = [ret]; debug('Not asynchronous. Returning value: ', res.entityResponse); next(); } }
[ "function", "callEntityMethod", "(", "req", ",", "res", ",", "next", ")", "{", "var", "payload", "=", "req", ".", "payload", ";", "var", "method", "=", "req", ".", "serversideMethod", ";", "if", "(", "req", ".", "hasCallback", ")", "{", "debug", "(", "'Transforming callback function'", ")", ";", "payload", "[", "req", ".", "clientCallbackIndex", "]", "=", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", ";", "}", "var", "values", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ".", "slice", "(", "1", ")", ";", "debug", "(", "'Callback function called. Values are:'", ",", "values", ")", ";", "res", ".", "entityResponse", "=", "values", ";", "next", "(", ")", ";", "}", ";", "}", "debug", "(", "'Calling '", "+", "req", ".", "path", "+", "' with arguments:'", ",", "payload", ")", ";", "var", "context", "=", "{", "req", ":", "req", ",", "xhr", ":", "true", ",", "setCookie", ":", "res", ".", "cookie", ".", "bind", "(", "res", ")", ",", "clearCookie", ":", "res", ".", "clearCookie", ".", "bind", "(", "res", ")", "}", ";", "var", "ret", ";", "// Calls the requested serverside method.", "// Applies the payload, and provides a context for validation purposes.", "// Caches errors in the method's scope, and sends it to the next error handler.", "try", "{", "ret", "=", "method", ".", "apply", "(", "context", ",", "payload", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "next", "(", "err", ")", ";", "}", "if", "(", "util", ".", "isPromise", "(", "ret", ")", ")", "{", "ret", ".", "then", "(", "function", "(", "resolved", ")", "{", "res", ".", "entityResponse", "=", "[", "resolved", "]", ";", "next", "(", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "next", "(", "err", ")", ";", "}", ")", ";", "}", "// If the request is not expecting the response from the entity,", "// send a generic 'Ok' response.", "else", "if", "(", "!", "req", ".", "hasCallback", ")", "{", "res", ".", "entityResponse", "=", "[", "ret", "]", ";", "debug", "(", "'Not asynchronous. Returning value: '", ",", "res", ".", "entityResponse", ")", ";", "next", "(", ")", ";", "}", "}" ]
Calls the server-side entity, and returns the results to the client
[ "Calls", "the", "server", "-", "side", "entity", "and", "returns", "the", "results", "to", "the", "client" ]
cb123d16b4be3bb7ec57758bd0b2e43767e91864
https://github.com/d-oliveros/isomorphine/blob/cb123d16b4be3bb7ec57758bd0b2e43767e91864/src/server/controllers.js#L36-L95
46,564
d-oliveros/isomorphine
src/server/controllers.js
serve
function serve(req, res) { var responseIsArray = Array.isArray(res.entityResponse); util.invariant(responseIsArray, 'Response values are required.'); res.json({ values: res.entityResponse }); }
javascript
function serve(req, res) { var responseIsArray = Array.isArray(res.entityResponse); util.invariant(responseIsArray, 'Response values are required.'); res.json({ values: res.entityResponse }); }
[ "function", "serve", "(", "req", ",", "res", ")", "{", "var", "responseIsArray", "=", "Array", ".", "isArray", "(", "res", ".", "entityResponse", ")", ";", "util", ".", "invariant", "(", "responseIsArray", ",", "'Response values are required.'", ")", ";", "res", ".", "json", "(", "{", "values", ":", "res", ".", "entityResponse", "}", ")", ";", "}" ]
Serves the value in req.entityResponse as a JSON object.
[ "Serves", "the", "value", "in", "req", ".", "entityResponse", "as", "a", "JSON", "object", "." ]
cb123d16b4be3bb7ec57758bd0b2e43767e91864
https://github.com/d-oliveros/isomorphine/blob/cb123d16b4be3bb7ec57758bd0b2e43767e91864/src/server/controllers.js#L100-L105
46,565
sebelga/promised-hooks
hooks.js
nextPreHook
function nextPreHook() { /** * read the arguments from previous "hook" response */ const args = Array.prototype.slice.apply(arguments); /** * Check if the arguments contains an "__override" property * that would override the arguments sent originally to the * target method */ if (is.object(args[0]) && {}.hasOwnProperty.call(args[0], '__override')) { passedArgs = arrify(args[0].__override); } /** * Reference to current pre hook */ let currentHook; if (currentPre + 1 < totalPres) { currentPre += 1; currentHook = pres[currentPre]; const hookMethod = currentHook.displayName || currentHook.name; /** * If there is a __scopeHook function on the object * we call it to get the scope wanted for the hook */ scope = getScope(self, name, passedArgs, hookMethod, 'pre'); /** * Execute the hook and recursively call the next one */ return currentHook.apply(scope, passedArgs).then(nextPreHook, handleError); } /** * We are done with "pre" hooks */ return done.apply(scope, passedArgs); }
javascript
function nextPreHook() { /** * read the arguments from previous "hook" response */ const args = Array.prototype.slice.apply(arguments); /** * Check if the arguments contains an "__override" property * that would override the arguments sent originally to the * target method */ if (is.object(args[0]) && {}.hasOwnProperty.call(args[0], '__override')) { passedArgs = arrify(args[0].__override); } /** * Reference to current pre hook */ let currentHook; if (currentPre + 1 < totalPres) { currentPre += 1; currentHook = pres[currentPre]; const hookMethod = currentHook.displayName || currentHook.name; /** * If there is a __scopeHook function on the object * we call it to get the scope wanted for the hook */ scope = getScope(self, name, passedArgs, hookMethod, 'pre'); /** * Execute the hook and recursively call the next one */ return currentHook.apply(scope, passedArgs).then(nextPreHook, handleError); } /** * We are done with "pre" hooks */ return done.apply(scope, passedArgs); }
[ "function", "nextPreHook", "(", ")", "{", "/**\n * read the arguments from previous \"hook\" response\n */", "const", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "apply", "(", "arguments", ")", ";", "/**\n * Check if the arguments contains an \"__override\" property\n * that would override the arguments sent originally to the\n * target method\n */", "if", "(", "is", ".", "object", "(", "args", "[", "0", "]", ")", "&&", "{", "}", ".", "hasOwnProperty", ".", "call", "(", "args", "[", "0", "]", ",", "'__override'", ")", ")", "{", "passedArgs", "=", "arrify", "(", "args", "[", "0", "]", ".", "__override", ")", ";", "}", "/**\n * Reference to current pre hook\n */", "let", "currentHook", ";", "if", "(", "currentPre", "+", "1", "<", "totalPres", ")", "{", "currentPre", "+=", "1", ";", "currentHook", "=", "pres", "[", "currentPre", "]", ";", "const", "hookMethod", "=", "currentHook", ".", "displayName", "||", "currentHook", ".", "name", ";", "/**\n * If there is a __scopeHook function on the object\n * we call it to get the scope wanted for the hook\n */", "scope", "=", "getScope", "(", "self", ",", "name", ",", "passedArgs", ",", "hookMethod", ",", "'pre'", ")", ";", "/**\n * Execute the hook and recursively call the next one\n */", "return", "currentHook", ".", "apply", "(", "scope", ",", "passedArgs", ")", ".", "then", "(", "nextPreHook", ",", "handleError", ")", ";", "}", "/**\n * We are done with \"pre\" hooks\n */", "return", "done", ".", "apply", "(", "scope", ",", "passedArgs", ")", ";", "}" ]
"pre" hook handler
[ "pre", "hook", "handler" ]
6eeebe085f3e11d8597002ad918c78db3bb30ad4
https://github.com/sebelga/promised-hooks/blob/6eeebe085f3e11d8597002ad918c78db3bb30ad4/hooks.js#L88-L128
46,566
sebelga/promised-hooks
hooks.js
nextPostHook
function nextPostHook(res) { response = checkResponse(res, response); if (currentPost + 1 < totalPost && self.__hooksEnabled !== false) { currentPost += 1; // Reference to current post hook const currPost = posts[currentPost]; const hookMethod = currPost.displayName || currPost.name; scope = getScope(self, name, res, hookMethod, 'post'); // Recursively call all the "post" hooks return currPost.call(scope, response).then(nextPostHook, postHookErrorHandler); } /** * All "post" hook process done. * If the response has an "__override" property it will be our response */ if (is.object(response) && {}.hasOwnProperty.call(response, '__override')) { response = response.__override; } return resolveFn(response); }
javascript
function nextPostHook(res) { response = checkResponse(res, response); if (currentPost + 1 < totalPost && self.__hooksEnabled !== false) { currentPost += 1; // Reference to current post hook const currPost = posts[currentPost]; const hookMethod = currPost.displayName || currPost.name; scope = getScope(self, name, res, hookMethod, 'post'); // Recursively call all the "post" hooks return currPost.call(scope, response).then(nextPostHook, postHookErrorHandler); } /** * All "post" hook process done. * If the response has an "__override" property it will be our response */ if (is.object(response) && {}.hasOwnProperty.call(response, '__override')) { response = response.__override; } return resolveFn(response); }
[ "function", "nextPostHook", "(", "res", ")", "{", "response", "=", "checkResponse", "(", "res", ",", "response", ")", ";", "if", "(", "currentPost", "+", "1", "<", "totalPost", "&&", "self", ".", "__hooksEnabled", "!==", "false", ")", "{", "currentPost", "+=", "1", ";", "// Reference to current post hook", "const", "currPost", "=", "posts", "[", "currentPost", "]", ";", "const", "hookMethod", "=", "currPost", ".", "displayName", "||", "currPost", ".", "name", ";", "scope", "=", "getScope", "(", "self", ",", "name", ",", "res", ",", "hookMethod", ",", "'post'", ")", ";", "// Recursively call all the \"post\" hooks", "return", "currPost", ".", "call", "(", "scope", ",", "response", ")", ".", "then", "(", "nextPostHook", ",", "postHookErrorHandler", ")", ";", "}", "/**\n * All \"post\" hook process done.\n * If the response has an \"__override\" property it will be our response\n */", "if", "(", "is", ".", "object", "(", "response", ")", "&&", "{", "}", ".", "hasOwnProperty", ".", "call", "(", "response", ",", "'__override'", ")", ")", "{", "response", "=", "response", ".", "__override", ";", "}", "return", "resolveFn", "(", "response", ")", ";", "}" ]
"post" hook handler @param {*} res the response coming from the target method or the reponse from any "post" hook
[ "post", "hook", "handler" ]
6eeebe085f3e11d8597002ad918c78db3bb30ad4
https://github.com/sebelga/promised-hooks/blob/6eeebe085f3e11d8597002ad918c78db3bb30ad4/hooks.js#L147-L171
46,567
sebelga/promised-hooks
hooks.js
postHookErrorHandler
function postHookErrorHandler(err) { /** * Helper to add an error to an Object "errors" Symbol */ const addError = (obj) => { obj[ERR_KEY] = obj[ERR_KEY] || []; obj[ERR_KEY].push(err); return obj; }; /** * For response type that are *not* objects (string, integers, functions...) * we convert the response to an object with a "result" property and set it as "override" */ if (typeof response !== 'object') { response = { __override: { result: response, }, }; } if ({}.hasOwnProperty.call(response, '__override')) { response.__override = addError(response.__override); } else { response = addError(response); } return nextPostHook(response); }
javascript
function postHookErrorHandler(err) { /** * Helper to add an error to an Object "errors" Symbol */ const addError = (obj) => { obj[ERR_KEY] = obj[ERR_KEY] || []; obj[ERR_KEY].push(err); return obj; }; /** * For response type that are *not* objects (string, integers, functions...) * we convert the response to an object with a "result" property and set it as "override" */ if (typeof response !== 'object') { response = { __override: { result: response, }, }; } if ({}.hasOwnProperty.call(response, '__override')) { response.__override = addError(response.__override); } else { response = addError(response); } return nextPostHook(response); }
[ "function", "postHookErrorHandler", "(", "err", ")", "{", "/**\n * Helper to add an error to an Object \"errors\" Symbol\n */", "const", "addError", "=", "(", "obj", ")", "=>", "{", "obj", "[", "ERR_KEY", "]", "=", "obj", "[", "ERR_KEY", "]", "||", "[", "]", ";", "obj", "[", "ERR_KEY", "]", ".", "push", "(", "err", ")", ";", "return", "obj", ";", "}", ";", "/**\n * For response type that are *not* objects (string, integers, functions...)\n * we convert the response to an object with a \"result\" property and set it as \"override\"\n */", "if", "(", "typeof", "response", "!==", "'object'", ")", "{", "response", "=", "{", "__override", ":", "{", "result", ":", "response", ",", "}", ",", "}", ";", "}", "if", "(", "{", "}", ".", "hasOwnProperty", ".", "call", "(", "response", ",", "'__override'", ")", ")", "{", "response", ".", "__override", "=", "addError", "(", "response", ".", "__override", ")", ";", "}", "else", "{", "response", "=", "addError", "(", "response", ")", ";", "}", "return", "nextPostHook", "(", "response", ")", ";", "}" ]
"post" hook Error handling @param {*} err the error returned by latest "post" hook
[ "post", "hook", "Error", "handling" ]
6eeebe085f3e11d8597002ad918c78db3bb30ad4
https://github.com/sebelga/promised-hooks/blob/6eeebe085f3e11d8597002ad918c78db3bb30ad4/hooks.js#L177-L206
46,568
mayanklahiri/node-genesis-device
src/HCL.js
renderInlines
function renderInlines(val, indent) { const indentStr = Array(indent + 1).join(' '); return '\n' + map(orderBy(val, first), (pair) => [ `${indentStr}${pair[0]} { ${exports.renderDefinition(pair[1], indent + 2)} ${indentStr}}`, ].join('\n') ).join('\n\n'); }
javascript
function renderInlines(val, indent) { const indentStr = Array(indent + 1).join(' '); return '\n' + map(orderBy(val, first), (pair) => [ `${indentStr}${pair[0]} { ${exports.renderDefinition(pair[1], indent + 2)} ${indentStr}}`, ].join('\n') ).join('\n\n'); }
[ "function", "renderInlines", "(", "val", ",", "indent", ")", "{", "const", "indentStr", "=", "Array", "(", "indent", "+", "1", ")", ".", "join", "(", "' '", ")", ";", "return", "'\\n'", "+", "map", "(", "orderBy", "(", "val", ",", "first", ")", ",", "(", "pair", ")", "=>", "[", "`", "${", "indentStr", "}", "${", "pair", "[", "0", "]", "}", "${", "exports", ".", "renderDefinition", "(", "pair", "[", "1", "]", ",", "indent", "+", "2", ")", "}", "${", "indentStr", "}", "`", ",", "]", ".", "join", "(", "'\\n'", ")", ")", ".", "join", "(", "'\\n\\n'", ")", ";", "}" ]
Renders inline values. @private @param {*} val @param {*} indent @return {string} Rendered inlines.
[ "Renders", "inline", "values", "." ]
c31b624b040ab0005afe5e204e96929c67147205
https://github.com/mayanklahiri/node-genesis-device/blob/c31b624b040ab0005afe5e204e96929c67147205/src/HCL.js#L71-L80
46,569
mayanklahiri/node-genesis-device
src/HCL.js
renderDefinitionRhs
function renderDefinitionRhs(val, indent) { indent = indent || 0; const indentStr = Array(indent + 1).join(' '); if (isUndefined(val)) { throw new Error('Undefined value in definition RHS.'); } if (isBoolean(val)) { return val.toString(); } if (isInteger(val)) { return val; } if (isString(val)) { return JSON.stringify(val); } if (isArray(val)) { return ['[', map(val, (elem) => `${indentStr} ${JSON.stringify(elem)}`).join(',\n'), `${indentStr}]`].join('\n'); } if (isObject(val)) { const rhsLines = exports.renderDefinition(val, indent + 2); const rhsStr = rhsLines; return `{ ${rhsStr} ${indentStr}}`; } }
javascript
function renderDefinitionRhs(val, indent) { indent = indent || 0; const indentStr = Array(indent + 1).join(' '); if (isUndefined(val)) { throw new Error('Undefined value in definition RHS.'); } if (isBoolean(val)) { return val.toString(); } if (isInteger(val)) { return val; } if (isString(val)) { return JSON.stringify(val); } if (isArray(val)) { return ['[', map(val, (elem) => `${indentStr} ${JSON.stringify(elem)}`).join(',\n'), `${indentStr}]`].join('\n'); } if (isObject(val)) { const rhsLines = exports.renderDefinition(val, indent + 2); const rhsStr = rhsLines; return `{ ${rhsStr} ${indentStr}}`; } }
[ "function", "renderDefinitionRhs", "(", "val", ",", "indent", ")", "{", "indent", "=", "indent", "||", "0", ";", "const", "indentStr", "=", "Array", "(", "indent", "+", "1", ")", ".", "join", "(", "' '", ")", ";", "if", "(", "isUndefined", "(", "val", ")", ")", "{", "throw", "new", "Error", "(", "'Undefined value in definition RHS.'", ")", ";", "}", "if", "(", "isBoolean", "(", "val", ")", ")", "{", "return", "val", ".", "toString", "(", ")", ";", "}", "if", "(", "isInteger", "(", "val", ")", ")", "{", "return", "val", ";", "}", "if", "(", "isString", "(", "val", ")", ")", "{", "return", "JSON", ".", "stringify", "(", "val", ")", ";", "}", "if", "(", "isArray", "(", "val", ")", ")", "{", "return", "[", "'['", ",", "map", "(", "val", ",", "(", "elem", ")", "=>", "`", "${", "indentStr", "}", "${", "JSON", ".", "stringify", "(", "elem", ")", "}", "`", ")", ".", "join", "(", "',\\n'", ")", ",", "`", "${", "indentStr", "}", "`", "]", ".", "join", "(", "'\\n'", ")", ";", "}", "if", "(", "isObject", "(", "val", ")", ")", "{", "const", "rhsLines", "=", "exports", ".", "renderDefinition", "(", "val", ",", "indent", "+", "2", ")", ";", "const", "rhsStr", "=", "rhsLines", ";", "return", "`", "${", "rhsStr", "}", "${", "indentStr", "}", "`", ";", "}", "}" ]
Render the right-hand side of a definition. @param {*} val Value to render @param {?number} indent Number of spaces to indent. @return {string} Rendered RHS.
[ "Render", "the", "right", "-", "hand", "side", "of", "a", "definition", "." ]
c31b624b040ab0005afe5e204e96929c67147205
https://github.com/mayanklahiri/node-genesis-device/blob/c31b624b040ab0005afe5e204e96929c67147205/src/HCL.js#L88-L114
46,570
reactbits/make-reducer
lib/index.js
makePrefixMapReducer
function makePrefixMapReducer() { for (var _len2 = arguments.length, reducers = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { reducers[_key2] = arguments[_key2]; } if (reducers.some(function (r) { return !_lodash2.default.isFunction(r); })) { throw new Error('all arguments must be a function'); } var initAction = { type: '@@redux/INIT' }; var initialState = reducers.reduce(function (a, r) { return Object.assign(a, r(undefined, initAction)); }, {}); function prefixOf(r, i) { // TODO warning about foreign reducers var p = _lodash2.default.isFunction(r.getPrefix) ? r.getPrefix() : '@@FOREIGN' + i; if (p && p.charAt(p.length - 1) === '/') { return p.substr(0, p.length - 1); } return p; } var reducerMap = reducers.reduce(function (a, r, i) { return _extends({}, a, _defineProperty({}, prefixOf(r, i), r)); }, {}); var reducer = function reducer() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; var action = arguments[1]; var i = action.type.indexOf('/'); var prefix = i >= 0 ? action.type.substring(0, i) : ''; if (prefix) { var fn = reducerMap[prefix]; return fn(state, action); } // TODO try to dispatch foreign reducers return state; }; reducer.getInitialState = function getInitialState() { return _extends({}, initialState); }; return reducer; }
javascript
function makePrefixMapReducer() { for (var _len2 = arguments.length, reducers = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { reducers[_key2] = arguments[_key2]; } if (reducers.some(function (r) { return !_lodash2.default.isFunction(r); })) { throw new Error('all arguments must be a function'); } var initAction = { type: '@@redux/INIT' }; var initialState = reducers.reduce(function (a, r) { return Object.assign(a, r(undefined, initAction)); }, {}); function prefixOf(r, i) { // TODO warning about foreign reducers var p = _lodash2.default.isFunction(r.getPrefix) ? r.getPrefix() : '@@FOREIGN' + i; if (p && p.charAt(p.length - 1) === '/') { return p.substr(0, p.length - 1); } return p; } var reducerMap = reducers.reduce(function (a, r, i) { return _extends({}, a, _defineProperty({}, prefixOf(r, i), r)); }, {}); var reducer = function reducer() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; var action = arguments[1]; var i = action.type.indexOf('/'); var prefix = i >= 0 ? action.type.substring(0, i) : ''; if (prefix) { var fn = reducerMap[prefix]; return fn(state, action); } // TODO try to dispatch foreign reducers return state; }; reducer.getInitialState = function getInitialState() { return _extends({}, initialState); }; return reducer; }
[ "function", "makePrefixMapReducer", "(", ")", "{", "for", "(", "var", "_len2", "=", "arguments", ".", "length", ",", "reducers", "=", "Array", "(", "_len2", ")", ",", "_key2", "=", "0", ";", "_key2", "<", "_len2", ";", "_key2", "++", ")", "{", "reducers", "[", "_key2", "]", "=", "arguments", "[", "_key2", "]", ";", "}", "if", "(", "reducers", ".", "some", "(", "function", "(", "r", ")", "{", "return", "!", "_lodash2", ".", "default", ".", "isFunction", "(", "r", ")", ";", "}", ")", ")", "{", "throw", "new", "Error", "(", "'all arguments must be a function'", ")", ";", "}", "var", "initAction", "=", "{", "type", ":", "'@@redux/INIT'", "}", ";", "var", "initialState", "=", "reducers", ".", "reduce", "(", "function", "(", "a", ",", "r", ")", "{", "return", "Object", ".", "assign", "(", "a", ",", "r", "(", "undefined", ",", "initAction", ")", ")", ";", "}", ",", "{", "}", ")", ";", "function", "prefixOf", "(", "r", ",", "i", ")", "{", "// TODO warning about foreign reducers", "var", "p", "=", "_lodash2", ".", "default", ".", "isFunction", "(", "r", ".", "getPrefix", ")", "?", "r", ".", "getPrefix", "(", ")", ":", "'@@FOREIGN'", "+", "i", ";", "if", "(", "p", "&&", "p", ".", "charAt", "(", "p", ".", "length", "-", "1", ")", "===", "'/'", ")", "{", "return", "p", ".", "substr", "(", "0", ",", "p", ".", "length", "-", "1", ")", ";", "}", "return", "p", ";", "}", "var", "reducerMap", "=", "reducers", ".", "reduce", "(", "function", "(", "a", ",", "r", ",", "i", ")", "{", "return", "_extends", "(", "{", "}", ",", "a", ",", "_defineProperty", "(", "{", "}", ",", "prefixOf", "(", "r", ",", "i", ")", ",", "r", ")", ")", ";", "}", ",", "{", "}", ")", ";", "var", "reducer", "=", "function", "reducer", "(", ")", "{", "var", "state", "=", "arguments", ".", "length", ">", "0", "&&", "arguments", "[", "0", "]", "!==", "undefined", "?", "arguments", "[", "0", "]", ":", "initialState", ";", "var", "action", "=", "arguments", "[", "1", "]", ";", "var", "i", "=", "action", ".", "type", ".", "indexOf", "(", "'/'", ")", ";", "var", "prefix", "=", "i", ">=", "0", "?", "action", ".", "type", ".", "substring", "(", "0", ",", "i", ")", ":", "''", ";", "if", "(", "prefix", ")", "{", "var", "fn", "=", "reducerMap", "[", "prefix", "]", ";", "return", "fn", "(", "state", ",", "action", ")", ";", "}", "// TODO try to dispatch foreign reducers", "return", "state", ";", "}", ";", "reducer", ".", "getInitialState", "=", "function", "getInitialState", "(", ")", "{", "return", "_extends", "(", "{", "}", ",", "initialState", ")", ";", "}", ";", "return", "reducer", ";", "}" ]
Combines reducers into reducer that dispatches action to appropriate reducer depending on action type prefix. @param {functions} ...reducers List of reducer functions to dispatch. @return {function} A reducer function that dispatches action to appropriate reducer depending on action type prefix.
[ "Combines", "reducers", "into", "reducer", "that", "dispatches", "action", "to", "appropriate", "reducer", "depending", "on", "action", "type", "prefix", "." ]
b0c59e32e67b232a22d791d7bf477c67f508ae43
https://github.com/reactbits/make-reducer/blob/b0c59e32e67b232a22d791d7bf477c67f508ae43/lib/index.js#L198-L246
46,571
svanderburg/nijs
lib/ast/NixIf.js
NixIf
function NixIf(args) { this.ifExpr = args.ifExpr; this.thenExpr = args.thenExpr; this.elseExpr = args.elseExpr; }
javascript
function NixIf(args) { this.ifExpr = args.ifExpr; this.thenExpr = args.thenExpr; this.elseExpr = args.elseExpr; }
[ "function", "NixIf", "(", "args", ")", "{", "this", ".", "ifExpr", "=", "args", ".", "ifExpr", ";", "this", ".", "thenExpr", "=", "args", ".", "thenExpr", ";", "this", ".", "elseExpr", "=", "args", ".", "elseExpr", ";", "}" ]
Creates a new NixIf instance. @class NixIf @extends NixBlock @classdesc Captures the abstract syntax of a Nix of if-then-else statement. @constructor @param {Object} args Arguments to this function @param {Mixed} args.ifExpr An object representing an expression evaluating to a boolean @param {Mixed} args.thenExpr Expression that gets evaluated if the condition is true @param {Mixed} args.elseExpr Expression that gets evaluated if the condition is false
[ "Creates", "a", "new", "NixIf", "instance", "." ]
4e2738cbff3a43aba9297315ca5120cecf8dae3e
https://github.com/svanderburg/nijs/blob/4e2738cbff3a43aba9297315ca5120cecf8dae3e/lib/ast/NixIf.js#L18-L22
46,572
adityamukho/node-box-sdk
lib/api/content/files.js
function (id, version, done, headers, config) { if (!_.isNumber(parseInt(id, 10))) { return done(new Error('id must be specified.')); } if (!_.isEmpty(version) && !_.isNumber(parseInt(version, 10))) { return done(new Error('version must be a number.')); } this._request(['files', id, 'versions', version], 'DELETE', done, null, null, null, headers, null, config); }
javascript
function (id, version, done, headers, config) { if (!_.isNumber(parseInt(id, 10))) { return done(new Error('id must be specified.')); } if (!_.isEmpty(version) && !_.isNumber(parseInt(version, 10))) { return done(new Error('version must be a number.')); } this._request(['files', id, 'versions', version], 'DELETE', done, null, null, null, headers, null, config); }
[ "function", "(", "id", ",", "version", ",", "done", ",", "headers", ",", "config", ")", "{", "if", "(", "!", "_", ".", "isNumber", "(", "parseInt", "(", "id", ",", "10", ")", ")", ")", "{", "return", "done", "(", "new", "Error", "(", "'id must be specified.'", ")", ")", ";", "}", "if", "(", "!", "_", ".", "isEmpty", "(", "version", ")", "&&", "!", "_", ".", "isNumber", "(", "parseInt", "(", "version", ",", "10", ")", ")", ")", "{", "return", "done", "(", "new", "Error", "(", "'version must be a number.'", ")", ")", ";", "}", "this", ".", "_request", "(", "[", "'files'", ",", "id", ",", "'versions'", ",", "version", "]", ",", "'DELETE'", ",", "done", ",", "null", ",", "null", ",", "null", ",", "headers", ",", "null", ",", "config", ")", ";", "}" ]
Discards a specific file version to the trash. @summary Delete an Old Version of a File. @see {@link https://developers.box.com/docs/#files-delete-version} @param {number} id - The file's ID. @param {number} version - File version to promote. @param {requestCallback} done - The callback to invoke (with possible errors) when the request returns. @param {?RequestHeaders} [headers] - Additional headers. @param {?RequestConfig} [config] - Configure the request behaviour.
[ "Discards", "a", "specific", "file", "version", "to", "the", "trash", "." ]
b8403df59d53ba4e8bed5de3675467544981a683
https://github.com/adityamukho/node-box-sdk/blob/b8403df59d53ba4e8bed5de3675467544981a683/lib/api/content/files.js#L248-L257
46,573
Hugo-ter-Doest/chart-parsers
lib/DoubleDottedItem.js
DoubleDottedItem
function DoubleDottedItem(parameters) { // An identifier is constructed from rule, dots, from and to this.id = "DoubleDottedItem(" + parameters.rule.lhs + "->" + parameters.rule.rhs + ", " + parameters.left_dot + ", " + parameters.right_dot + ", " + parameters.from + ", " + parameters.to +")"; logger.debug("Enter DoubleDottedItem: " + this.id); this.name = parameters.rule.lhs; this.children = []; this.data = {}; this.data.rule = parameters.rule; this.data.left_dot = parameters.left_dot; this.data.right_dot = parameters.right_dot; this.data.from = parameters.from; this.data.to = parameters.to; this.data.fs = parameters.fs; logger.debug("Exit DoubleDottedItem: created item: " + this.id); }
javascript
function DoubleDottedItem(parameters) { // An identifier is constructed from rule, dots, from and to this.id = "DoubleDottedItem(" + parameters.rule.lhs + "->" + parameters.rule.rhs + ", " + parameters.left_dot + ", " + parameters.right_dot + ", " + parameters.from + ", " + parameters.to +")"; logger.debug("Enter DoubleDottedItem: " + this.id); this.name = parameters.rule.lhs; this.children = []; this.data = {}; this.data.rule = parameters.rule; this.data.left_dot = parameters.left_dot; this.data.right_dot = parameters.right_dot; this.data.from = parameters.from; this.data.to = parameters.to; this.data.fs = parameters.fs; logger.debug("Exit DoubleDottedItem: created item: " + this.id); }
[ "function", "DoubleDottedItem", "(", "parameters", ")", "{", "// An identifier is constructed from rule, dots, from and to", "this", ".", "id", "=", "\"DoubleDottedItem(\"", "+", "parameters", ".", "rule", ".", "lhs", "+", "\"->\"", "+", "parameters", ".", "rule", ".", "rhs", "+", "\", \"", "+", "parameters", ".", "left_dot", "+", "\", \"", "+", "parameters", ".", "right_dot", "+", "\", \"", "+", "parameters", ".", "from", "+", "\", \"", "+", "parameters", ".", "to", "+", "\")\"", ";", "logger", ".", "debug", "(", "\"Enter DoubleDottedItem: \"", "+", "this", ".", "id", ")", ";", "this", ".", "name", "=", "parameters", ".", "rule", ".", "lhs", ";", "this", ".", "children", "=", "[", "]", ";", "this", ".", "data", "=", "{", "}", ";", "this", ".", "data", ".", "rule", "=", "parameters", ".", "rule", ";", "this", ".", "data", ".", "left_dot", "=", "parameters", ".", "left_dot", ";", "this", ".", "data", ".", "right_dot", "=", "parameters", ".", "right_dot", ";", "this", ".", "data", ".", "from", "=", "parameters", ".", "from", ";", "this", ".", "data", ".", "to", "=", "parameters", ".", "to", ";", "this", ".", "data", ".", "fs", "=", "parameters", ".", "fs", ";", "logger", ".", "debug", "(", "\"Exit DoubleDottedItem: created item: \"", "+", "this", ".", "id", ")", ";", "}" ]
Creates a doubledotted item; left_dot is an index in the RHS of the rule as well as right_dot from is the starting point in the sentence Data structure is prepared for use with InfoVis
[ "Creates", "a", "doubledotted", "item", ";", "left_dot", "is", "an", "index", "in", "the", "RHS", "of", "the", "rule", "as", "well", "as", "right_dot", "from", "is", "the", "starting", "point", "in", "the", "sentence", "Data", "structure", "is", "prepared", "for", "use", "with", "InfoVis" ]
81be32f897f6dceeffebd2009ad865964da12c4b
https://github.com/Hugo-ter-Doest/chart-parsers/blob/81be32f897f6dceeffebd2009ad865964da12c4b/lib/DoubleDottedItem.js#L38-L55
46,574
Hugo-ter-Doest/chart-parsers
lib/EarleyItem.js
EarleyItem
function EarleyItem(parameters) { // A unique identifier is constructed from rule, dot and from this.id = "Earley(" + parameters.rule.lhs + "->" + parameters.rule.rhs + ", " + parameters.dot + ", " + parameters.from + ", " + parameters.to +")"; logger.debug("EarleyItem: " + this.id); this.name = parameters.rule.lhs; this.children = []; this.data = {}; this.data.rule = parameters.rule; this.data.dot = parameters.dot; this.data.from = parameters.from; this.data.to = parameters.to; if (global.config.UNIFICATION) { this.data.fs = parameters.fs; } }
javascript
function EarleyItem(parameters) { // A unique identifier is constructed from rule, dot and from this.id = "Earley(" + parameters.rule.lhs + "->" + parameters.rule.rhs + ", " + parameters.dot + ", " + parameters.from + ", " + parameters.to +")"; logger.debug("EarleyItem: " + this.id); this.name = parameters.rule.lhs; this.children = []; this.data = {}; this.data.rule = parameters.rule; this.data.dot = parameters.dot; this.data.from = parameters.from; this.data.to = parameters.to; if (global.config.UNIFICATION) { this.data.fs = parameters.fs; } }
[ "function", "EarleyItem", "(", "parameters", ")", "{", "// A unique identifier is constructed from rule, dot and from", "this", ".", "id", "=", "\"Earley(\"", "+", "parameters", ".", "rule", ".", "lhs", "+", "\"->\"", "+", "parameters", ".", "rule", ".", "rhs", "+", "\", \"", "+", "parameters", ".", "dot", "+", "\", \"", "+", "parameters", ".", "from", "+", "\", \"", "+", "parameters", ".", "to", "+", "\")\"", ";", "logger", ".", "debug", "(", "\"EarleyItem: \"", "+", "this", ".", "id", ")", ";", "this", ".", "name", "=", "parameters", ".", "rule", ".", "lhs", ";", "this", ".", "children", "=", "[", "]", ";", "this", ".", "data", "=", "{", "}", ";", "this", ".", "data", ".", "rule", "=", "parameters", ".", "rule", ";", "this", ".", "data", ".", "dot", "=", "parameters", ".", "dot", ";", "this", ".", "data", ".", "from", "=", "parameters", ".", "from", ";", "this", ".", "data", ".", "to", "=", "parameters", ".", "to", ";", "if", "(", "global", ".", "config", ".", "UNIFICATION", ")", "{", "this", ".", "data", ".", "fs", "=", "parameters", ".", "fs", ";", "}", "}" ]
Creates an item; dot is an index in the RHS of the rule, from is the starting point in the sentence Data structure is prepared for InfoVis
[ "Creates", "an", "item", ";", "dot", "is", "an", "index", "in", "the", "RHS", "of", "the", "rule", "from", "is", "the", "starting", "point", "in", "the", "sentence", "Data", "structure", "is", "prepared", "for", "InfoVis" ]
81be32f897f6dceeffebd2009ad865964da12c4b
https://github.com/Hugo-ter-Doest/chart-parsers/blob/81be32f897f6dceeffebd2009ad865964da12c4b/lib/EarleyItem.js#L32-L48
46,575
brettz9/jamilih
dist/jml-polyglot.js
_applyAnyStylesheet
function _applyAnyStylesheet(node) { if (!doc.createStyleSheet) { return; } if (_getHTMLNodeName(node) === 'style') { // IE var ss = doc.createStyleSheet(); // Create a stylesheet to actually do something useful ss.cssText = node.cssText; // We continue to add the style tag, however } }
javascript
function _applyAnyStylesheet(node) { if (!doc.createStyleSheet) { return; } if (_getHTMLNodeName(node) === 'style') { // IE var ss = doc.createStyleSheet(); // Create a stylesheet to actually do something useful ss.cssText = node.cssText; // We continue to add the style tag, however } }
[ "function", "_applyAnyStylesheet", "(", "node", ")", "{", "if", "(", "!", "doc", ".", "createStyleSheet", ")", "{", "return", ";", "}", "if", "(", "_getHTMLNodeName", "(", "node", ")", "===", "'style'", ")", "{", "// IE", "var", "ss", "=", "doc", ".", "createStyleSheet", "(", ")", ";", "// Create a stylesheet to actually do something useful", "ss", ".", "cssText", "=", "node", ".", "cssText", ";", "// We continue to add the style tag, however", "}", "}" ]
Apply styles if this is a style tag @static @param {Node} node The element to check whether it is a style tag
[ "Apply", "styles", "if", "this", "is", "a", "style", "tag" ]
9cf3bef69169b1ea3db574866fb6abcab613a3ed
https://github.com/brettz9/jamilih/blob/9cf3bef69169b1ea3db574866fb6abcab613a3ed/dist/jml-polyglot.js#L765-L776
46,576
brettz9/jamilih
dist/jml-polyglot.js
_appendNode
function _appendNode(parent, child) { var parentName = _getHTMLNodeName(parent); var childName = _getHTMLNodeName(child); if (doc.createStyleSheet) { if (parentName === 'script') { parent.text = child.nodeValue; return; } if (parentName === 'style') { parent.cssText = child.nodeValue; // This will not apply it--just make it available within the DOM cotents return; } } if (parentName === 'template') { parent.content.appendChild(child); return; } try { parent.appendChild(child); // IE9 is now ok with this } catch (e) { if (parentName === 'select' && childName === 'option') { try { // Since this is now DOM Level 4 standard behavior (and what IE7+ can handle), we try it first parent.add(child); } catch (err) { // DOM Level 2 did require a second argument, so we try it too just in case the user is using an older version of Firefox, etc. parent.add(child, null); // IE7 has a problem with this, but IE8+ is ok } return; } throw e; } }
javascript
function _appendNode(parent, child) { var parentName = _getHTMLNodeName(parent); var childName = _getHTMLNodeName(child); if (doc.createStyleSheet) { if (parentName === 'script') { parent.text = child.nodeValue; return; } if (parentName === 'style') { parent.cssText = child.nodeValue; // This will not apply it--just make it available within the DOM cotents return; } } if (parentName === 'template') { parent.content.appendChild(child); return; } try { parent.appendChild(child); // IE9 is now ok with this } catch (e) { if (parentName === 'select' && childName === 'option') { try { // Since this is now DOM Level 4 standard behavior (and what IE7+ can handle), we try it first parent.add(child); } catch (err) { // DOM Level 2 did require a second argument, so we try it too just in case the user is using an older version of Firefox, etc. parent.add(child, null); // IE7 has a problem with this, but IE8+ is ok } return; } throw e; } }
[ "function", "_appendNode", "(", "parent", ",", "child", ")", "{", "var", "parentName", "=", "_getHTMLNodeName", "(", "parent", ")", ";", "var", "childName", "=", "_getHTMLNodeName", "(", "child", ")", ";", "if", "(", "doc", ".", "createStyleSheet", ")", "{", "if", "(", "parentName", "===", "'script'", ")", "{", "parent", ".", "text", "=", "child", ".", "nodeValue", ";", "return", ";", "}", "if", "(", "parentName", "===", "'style'", ")", "{", "parent", ".", "cssText", "=", "child", ".", "nodeValue", ";", "// This will not apply it--just make it available within the DOM cotents", "return", ";", "}", "}", "if", "(", "parentName", "===", "'template'", ")", "{", "parent", ".", "content", ".", "appendChild", "(", "child", ")", ";", "return", ";", "}", "try", "{", "parent", ".", "appendChild", "(", "child", ")", ";", "// IE9 is now ok with this", "}", "catch", "(", "e", ")", "{", "if", "(", "parentName", "===", "'select'", "&&", "childName", "===", "'option'", ")", "{", "try", "{", "// Since this is now DOM Level 4 standard behavior (and what IE7+ can handle), we try it first", "parent", ".", "add", "(", "child", ")", ";", "}", "catch", "(", "err", ")", "{", "// DOM Level 2 did require a second argument, so we try it too just in case the user is using an older version of Firefox, etc.", "parent", ".", "add", "(", "child", ",", "null", ")", ";", "// IE7 has a problem with this, but IE8+ is ok", "}", "return", ";", "}", "throw", "e", ";", "}", "}" ]
Need this function for IE since options weren't otherwise getting added @private @static @param {DOMElement} parent The parent to which to append the element @param {DOMNode} child The element or other node to append to the parent
[ "Need", "this", "function", "for", "IE", "since", "options", "weren", "t", "otherwise", "getting", "added" ]
9cf3bef69169b1ea3db574866fb6abcab613a3ed
https://github.com/brettz9/jamilih/blob/9cf3bef69169b1ea3db574866fb6abcab613a3ed/dist/jml-polyglot.js#L786-L826
46,577
brettz9/jamilih
dist/jml-polyglot.js
_addEvent
function _addEvent(el, type, handler, capturing) { el.addEventListener(type, handler, !!capturing); }
javascript
function _addEvent(el, type, handler, capturing) { el.addEventListener(type, handler, !!capturing); }
[ "function", "_addEvent", "(", "el", ",", "type", ",", "handler", ",", "capturing", ")", "{", "el", ".", "addEventListener", "(", "type", ",", "handler", ",", "!", "!", "capturing", ")", ";", "}" ]
Attach event in a cross-browser fashion @static @param {DOMElement} el DOM element to which to attach the event @param {String} type The DOM event (without 'on') to attach to the element @param {Function} handler The event handler to attach to the element @param {Boolean} [capturing] Whether or not the event should be capturing (W3C-browsers only); default is false; NOT IN USE
[ "Attach", "event", "in", "a", "cross", "-", "browser", "fashion" ]
9cf3bef69169b1ea3db574866fb6abcab613a3ed
https://github.com/brettz9/jamilih/blob/9cf3bef69169b1ea3db574866fb6abcab613a3ed/dist/jml-polyglot.js#L838-L840
46,578
brettz9/jamilih
dist/jml-polyglot.js
_createSafeReference
function _createSafeReference(type, prefix, arg) { // For security reasons related to innerHTML, we ensure this string only contains potential entity characters if (!arg.match(/^\w+$/)) { throw new TypeError('Bad ' + type); } var elContainer = doc.createElement('div'); // Todo: No workaround for XML? elContainer.innerHTML = '&' + prefix + arg + ';'; return doc.createTextNode(elContainer.innerHTML); }
javascript
function _createSafeReference(type, prefix, arg) { // For security reasons related to innerHTML, we ensure this string only contains potential entity characters if (!arg.match(/^\w+$/)) { throw new TypeError('Bad ' + type); } var elContainer = doc.createElement('div'); // Todo: No workaround for XML? elContainer.innerHTML = '&' + prefix + arg + ';'; return doc.createTextNode(elContainer.innerHTML); }
[ "function", "_createSafeReference", "(", "type", ",", "prefix", ",", "arg", ")", "{", "// For security reasons related to innerHTML, we ensure this string only contains potential entity characters", "if", "(", "!", "arg", ".", "match", "(", "/", "^\\w+$", "/", ")", ")", "{", "throw", "new", "TypeError", "(", "'Bad '", "+", "type", ")", ";", "}", "var", "elContainer", "=", "doc", ".", "createElement", "(", "'div'", ")", ";", "// Todo: No workaround for XML?", "elContainer", ".", "innerHTML", "=", "'&'", "+", "prefix", "+", "arg", "+", "';'", ";", "return", "doc", ".", "createTextNode", "(", "elContainer", ".", "innerHTML", ")", ";", "}" ]
Creates a text node of the result of resolving an entity or character reference @param {'entity'|'decimal'|'hexadecimal'} type Type of reference @param {String} prefix Text to prefix immediately after the "&" @param {String} arg The body of the reference @returns {Text} The text node of the resolved reference
[ "Creates", "a", "text", "node", "of", "the", "result", "of", "resolving", "an", "entity", "or", "character", "reference" ]
9cf3bef69169b1ea3db574866fb6abcab613a3ed
https://github.com/brettz9/jamilih/blob/9cf3bef69169b1ea3db574866fb6abcab613a3ed/dist/jml-polyglot.js#L850-L860
46,579
brettz9/jamilih
dist/jml-polyglot.js
glue
function glue(jmlArray, glu) { return _toConsumableArray(jmlArray).reduce(function (arr, item) { arr.push(item, glu); return arr; }, []).slice(0, -1); }
javascript
function glue(jmlArray, glu) { return _toConsumableArray(jmlArray).reduce(function (arr, item) { arr.push(item, glu); return arr; }, []).slice(0, -1); }
[ "function", "glue", "(", "jmlArray", ",", "glu", ")", "{", "return", "_toConsumableArray", "(", "jmlArray", ")", ".", "reduce", "(", "function", "(", "arr", ",", "item", ")", "{", "arr", ".", "push", "(", "item", ",", "glu", ")", ";", "return", "arr", ";", "}", ",", "[", "]", ")", ".", "slice", "(", "0", ",", "-", "1", ")", ";", "}" ]
Does not run Jamilih so can be further processed. @param {Array} jmlArray @param {string|Array|Element} glu @returns {Element}
[ "Does", "not", "run", "Jamilih", "so", "can", "be", "further", "processed", "." ]
9cf3bef69169b1ea3db574866fb6abcab613a3ed
https://github.com/brettz9/jamilih/blob/9cf3bef69169b1ea3db574866fb6abcab613a3ed/dist/jml-polyglot.js#L2476-L2481
46,580
patrinhani-ciandt/fortune-datastore
lib/helpers.js
inputRecord
function inputRecord (type, record) { const clone = {}; const recordTypes = this.recordTypes; const primaryKey = this.keys.primary; const isArrayKey = this.keys.isArray; const generateId = this.options.generateId; const fields = recordTypes[type]; // ID business. const id = record[primaryKey]; clone[idKey] = id ? id : generateId(type); for (const field in record) { if (field === primaryKey) continue; clone[field] = record[field]; } for (const field of Object.getOwnPropertyNames(fields)) if (!(field in record)) clone[field] = fields[field][isArrayKey] ? [] : null; return clone; }
javascript
function inputRecord (type, record) { const clone = {}; const recordTypes = this.recordTypes; const primaryKey = this.keys.primary; const isArrayKey = this.keys.isArray; const generateId = this.options.generateId; const fields = recordTypes[type]; // ID business. const id = record[primaryKey]; clone[idKey] = id ? id : generateId(type); for (const field in record) { if (field === primaryKey) continue; clone[field] = record[field]; } for (const field of Object.getOwnPropertyNames(fields)) if (!(field in record)) clone[field] = fields[field][isArrayKey] ? [] : null; return clone; }
[ "function", "inputRecord", "(", "type", ",", "record", ")", "{", "const", "clone", "=", "{", "}", ";", "const", "recordTypes", "=", "this", ".", "recordTypes", ";", "const", "primaryKey", "=", "this", ".", "keys", ".", "primary", ";", "const", "isArrayKey", "=", "this", ".", "keys", ".", "isArray", ";", "const", "generateId", "=", "this", ".", "options", ".", "generateId", ";", "const", "fields", "=", "recordTypes", "[", "type", "]", ";", "// ID business.", "const", "id", "=", "record", "[", "primaryKey", "]", ";", "clone", "[", "idKey", "]", "=", "id", "?", "id", ":", "generateId", "(", "type", ")", ";", "for", "(", "const", "field", "in", "record", ")", "{", "if", "(", "field", "===", "primaryKey", ")", "continue", ";", "clone", "[", "field", "]", "=", "record", "[", "field", "]", ";", "}", "for", "(", "const", "field", "of", "Object", ".", "getOwnPropertyNames", "(", "fields", ")", ")", "if", "(", "!", "(", "field", "in", "record", ")", ")", "clone", "[", "field", "]", "=", "fields", "[", "field", "]", "[", "isArrayKey", "]", "?", "[", "]", ":", "null", ";", "return", "clone", ";", "}" ]
Cast and assign values per field definition.
[ "Cast", "and", "assign", "values", "per", "field", "definition", "." ]
63dee9093412d1d68481297f4480e2439ddb9a4a
https://github.com/patrinhani-ciandt/fortune-datastore/blob/63dee9093412d1d68481297f4480e2439ddb9a4a/lib/helpers.js#L8-L30
46,581
thealjey/webcompiler
lib/jsx.js
parseHTML
function parseHTML(html) { const dom = (0, _cheerio.load)(html), { children } = dom.root().toArray()[0]; return { dom, children }; }
javascript
function parseHTML(html) { const dom = (0, _cheerio.load)(html), { children } = dom.root().toArray()[0]; return { dom, children }; }
[ "function", "parseHTML", "(", "html", ")", "{", "const", "dom", "=", "(", "0", ",", "_cheerio", ".", "load", ")", "(", "html", ")", ",", "{", "children", "}", "=", "dom", ".", "root", "(", ")", ".", "toArray", "(", ")", "[", "0", "]", ";", "return", "{", "dom", ",", "children", "}", ";", "}" ]
Useful utilities for working with JSX. @module jsx Parses an HTML string. @memberof module:jsx @private @method parseHTML @param {string} html - an arbitrary HTML string @return {Object} an object containing a CheerioDOM object and a CheerioCollection of the `pre.CodeMirror-line` elements
[ "Useful", "utilities", "for", "working", "with", "JSX", "." ]
eb094f1632e5313ed0c5391a303150f1416b9629
https://github.com/thealjey/webcompiler/blob/eb094f1632e5313ed0c5391a303150f1416b9629/lib/jsx.js#L84-L89
46,582
thealjey/webcompiler
lib/jsx.js
toJSXKey
function toJSXKey(key) { return (0, _replace2.default)(/^-ms-/.test(key) ? key.substr(1) : key, /-(.)/g, (match, chr) => (0, _toUpper2.default)(chr)); }
javascript
function toJSXKey(key) { return (0, _replace2.default)(/^-ms-/.test(key) ? key.substr(1) : key, /-(.)/g, (match, chr) => (0, _toUpper2.default)(chr)); }
[ "function", "toJSXKey", "(", "key", ")", "{", "return", "(", "0", ",", "_replace2", ".", "default", ")", "(", "/", "^-ms-", "/", ".", "test", "(", "key", ")", "?", "key", ".", "substr", "(", "1", ")", ":", "key", ",", "/", "-(.)", "/", "g", ",", "(", "match", ",", "chr", ")", "=>", "(", "0", ",", "_toUpper2", ".", "default", ")", "(", "chr", ")", ")", ";", "}" ]
Convert the CSS style key to a JSX style key. @memberof module:jsx @private @method toJSXKey @param {string} key - CSS style key @return {string} JSX style key
[ "Convert", "the", "CSS", "style", "key", "to", "a", "JSX", "style", "key", "." ]
eb094f1632e5313ed0c5391a303150f1416b9629
https://github.com/thealjey/webcompiler/blob/eb094f1632e5313ed0c5391a303150f1416b9629/lib/jsx.js#L100-L102
46,583
thealjey/webcompiler
lib/jsx.js
transformStyle
function transformStyle(object) { if ((0, _has2.default)(object, 'style')) { object.style = (0, _transform2.default)((0, _split2.default)(object.style, ';'), (result, style) => { const firstColon = style.indexOf(':'), key = (0, _trim2.default)(style.substr(0, firstColon)); if (key) { result[toJSXKey((0, _toLower2.default)(key))] = (0, _trim2.default)(style.substr(firstColon + 1)); } }, {}); } }
javascript
function transformStyle(object) { if ((0, _has2.default)(object, 'style')) { object.style = (0, _transform2.default)((0, _split2.default)(object.style, ';'), (result, style) => { const firstColon = style.indexOf(':'), key = (0, _trim2.default)(style.substr(0, firstColon)); if (key) { result[toJSXKey((0, _toLower2.default)(key))] = (0, _trim2.default)(style.substr(firstColon + 1)); } }, {}); } }
[ "function", "transformStyle", "(", "object", ")", "{", "if", "(", "(", "0", ",", "_has2", ".", "default", ")", "(", "object", ",", "'style'", ")", ")", "{", "object", ".", "style", "=", "(", "0", ",", "_transform2", ".", "default", ")", "(", "(", "0", ",", "_split2", ".", "default", ")", "(", "object", ".", "style", ",", "';'", ")", ",", "(", "result", ",", "style", ")", "=>", "{", "const", "firstColon", "=", "style", ".", "indexOf", "(", "':'", ")", ",", "key", "=", "(", "0", ",", "_trim2", ".", "default", ")", "(", "style", ".", "substr", "(", "0", ",", "firstColon", ")", ")", ";", "if", "(", "key", ")", "{", "result", "[", "toJSXKey", "(", "(", "0", ",", "_toLower2", ".", "default", ")", "(", "key", ")", ")", "]", "=", "(", "0", ",", "_trim2", ".", "default", ")", "(", "style", ".", "substr", "(", "firstColon", "+", "1", ")", ")", ";", "}", "}", ",", "{", "}", ")", ";", "}", "}" ]
Parse the specified inline style attribute value. @memberof module:jsx @private @method transformStyle @param {Object} object - the object to perform replacements on
[ "Parse", "the", "specified", "inline", "style", "attribute", "value", "." ]
eb094f1632e5313ed0c5391a303150f1416b9629
https://github.com/thealjey/webcompiler/blob/eb094f1632e5313ed0c5391a303150f1416b9629/lib/jsx.js#L112-L123
46,584
thealjey/webcompiler
lib/jsx.js
rename
function rename(object, fromKey, toKey) { if ((0, _has2.default)(object, fromKey)) { object[toKey] = object[fromKey]; delete object[fromKey]; } }
javascript
function rename(object, fromKey, toKey) { if ((0, _has2.default)(object, fromKey)) { object[toKey] = object[fromKey]; delete object[fromKey]; } }
[ "function", "rename", "(", "object", ",", "fromKey", ",", "toKey", ")", "{", "if", "(", "(", "0", ",", "_has2", ".", "default", ")", "(", "object", ",", "fromKey", ")", ")", "{", "object", "[", "toKey", "]", "=", "object", "[", "fromKey", "]", ";", "delete", "object", "[", "fromKey", "]", ";", "}", "}" ]
Renames specified attributes if present. @memberof module:jsx @private @method rename @param {Object} object - the object to perform replacements on @param {string} fromKey - a key to look for @param {string} toKey - a key to rename to
[ "Renames", "specified", "attributes", "if", "present", "." ]
eb094f1632e5313ed0c5391a303150f1416b9629
https://github.com/thealjey/webcompiler/blob/eb094f1632e5313ed0c5391a303150f1416b9629/lib/jsx.js#L135-L140
46,585
thealjey/webcompiler
lib/jsx.js
transformElement
function transformElement({ name: type, attribs: props, children: childElements }) { transformStyle(props); rename(props, 'for', 'htmlFor'); rename(props, 'class', 'className'); if ('input' === type) { rename(props, 'checked', 'defaultChecked'); rename(props, 'value', 'defaultValue'); } let children = transformElements(childElements); if ('textarea' === type && children.length) { props.defaultValue = children[0]; children = []; } return { type, props, children }; }
javascript
function transformElement({ name: type, attribs: props, children: childElements }) { transformStyle(props); rename(props, 'for', 'htmlFor'); rename(props, 'class', 'className'); if ('input' === type) { rename(props, 'checked', 'defaultChecked'); rename(props, 'value', 'defaultValue'); } let children = transformElements(childElements); if ('textarea' === type && children.length) { props.defaultValue = children[0]; children = []; } return { type, props, children }; }
[ "function", "transformElement", "(", "{", "name", ":", "type", ",", "attribs", ":", "props", ",", "children", ":", "childElements", "}", ")", "{", "transformStyle", "(", "props", ")", ";", "rename", "(", "props", ",", "'for'", ",", "'htmlFor'", ")", ";", "rename", "(", "props", ",", "'class'", ",", "'className'", ")", ";", "if", "(", "'input'", "===", "type", ")", "{", "rename", "(", "props", ",", "'checked'", ",", "'defaultChecked'", ")", ";", "rename", "(", "props", ",", "'value'", ",", "'defaultValue'", ")", ";", "}", "let", "children", "=", "transformElements", "(", "childElements", ")", ";", "if", "(", "'textarea'", "===", "type", "&&", "children", ".", "length", ")", "{", "props", ".", "defaultValue", "=", "children", "[", "0", "]", ";", "children", "=", "[", "]", ";", "}", "return", "{", "type", ",", "props", ",", "children", "}", ";", "}" ]
Converts a Cheerio Element into an object that can later be used to create a React Element. @memberof module:jsx @private @method transformElement @param {Object} element - a Cheerio Element @return {Object} a plain object describing a React Element
[ "Converts", "a", "Cheerio", "Element", "into", "an", "object", "that", "can", "later", "be", "used", "to", "create", "a", "React", "Element", "." ]
eb094f1632e5313ed0c5391a303150f1416b9629
https://github.com/thealjey/webcompiler/blob/eb094f1632e5313ed0c5391a303150f1416b9629/lib/jsx.js#L151-L167
46,586
thealjey/webcompiler
lib/jsx.js
flatten
function flatten(...args) { return (0, _transform2.default)((0, _flattenDeep2.default)(args), (accumulator, value) => { if (!value) { return; } const lastIndex = accumulator.length - 1; if ((0, _isString2.default)(value) && (0, _isString2.default)(accumulator[lastIndex])) { accumulator[lastIndex] += value; } else { accumulator.push(value); } }, []); }
javascript
function flatten(...args) { return (0, _transform2.default)((0, _flattenDeep2.default)(args), (accumulator, value) => { if (!value) { return; } const lastIndex = accumulator.length - 1; if ((0, _isString2.default)(value) && (0, _isString2.default)(accumulator[lastIndex])) { accumulator[lastIndex] += value; } else { accumulator.push(value); } }, []); }
[ "function", "flatten", "(", "...", "args", ")", "{", "return", "(", "0", ",", "_transform2", ".", "default", ")", "(", "(", "0", ",", "_flattenDeep2", ".", "default", ")", "(", "args", ")", ",", "(", "accumulator", ",", "value", ")", "=>", "{", "if", "(", "!", "value", ")", "{", "return", ";", "}", "const", "lastIndex", "=", "accumulator", ".", "length", "-", "1", ";", "if", "(", "(", "0", ",", "_isString2", ".", "default", ")", "(", "value", ")", "&&", "(", "0", ",", "_isString2", ".", "default", ")", "(", "accumulator", "[", "lastIndex", "]", ")", ")", "{", "accumulator", "[", "lastIndex", "]", "+=", "value", ";", "}", "else", "{", "accumulator", ".", "push", "(", "value", ")", ";", "}", "}", ",", "[", "]", ")", ";", "}" ]
Recursively flattens `args`, removes falsy values and combines string values. Can be used as a simple optimization step on the JSX children-to-be to simplify the resulting DOM structure by joining adjacent text nodes together. @memberof module:jsx @method flatten @param {...*} args - the input values @return {Array<*>} the flattened result @example import {flatten} from 'webcompiler'; // or - import {flatten} from 'webcompiler/lib/jsx'; // or - var flatten = require('webcompiler').flatten; // or - var flatten = require('webcompiler/lib/jsx').flatten; flatten('lorem ', ['ipsum ', null, ['dolor ', ['sit ', ['amet']]]]); // ["lorem ipsum dolor sit amet"]
[ "Recursively", "flattens", "args", "removes", "falsy", "values", "and", "combines", "string", "values", "." ]
eb094f1632e5313ed0c5391a303150f1416b9629
https://github.com/thealjey/webcompiler/blob/eb094f1632e5313ed0c5391a303150f1416b9629/lib/jsx.js#L201-L214
46,587
thealjey/webcompiler
lib/jsx.js
arrayToJSX
function arrayToJSX(arr = []) { return (0, _map2.default)(arr, (el, key) => { if ((0, _isString2.default)(el)) { return el; } const { type, props, children } = el; return (0, _react.createElement)(type, _extends({}, props, { key }), ...arrayToJSX(children)); }); }
javascript
function arrayToJSX(arr = []) { return (0, _map2.default)(arr, (el, key) => { if ((0, _isString2.default)(el)) { return el; } const { type, props, children } = el; return (0, _react.createElement)(type, _extends({}, props, { key }), ...arrayToJSX(children)); }); }
[ "function", "arrayToJSX", "(", "arr", "=", "[", "]", ")", "{", "return", "(", "0", ",", "_map2", ".", "default", ")", "(", "arr", ",", "(", "el", ",", "key", ")", "=>", "{", "if", "(", "(", "0", ",", "_isString2", ".", "default", ")", "(", "el", ")", ")", "{", "return", "el", ";", "}", "const", "{", "type", ",", "props", ",", "children", "}", "=", "el", ";", "return", "(", "0", ",", "_react", ".", "createElement", ")", "(", "type", ",", "_extends", "(", "{", "}", ",", "props", ",", "{", "key", "}", ")", ",", "...", "arrayToJSX", "(", "children", ")", ")", ";", "}", ")", ";", "}" ]
Converts an array of plain objects describing React Elements to an array of React Elements. @memberof module:jsx @method arrayToJSX @param {Array<string|Object>} [arr=[]] - an array of plain objects describing React Elements @return {Array<ReactElement>} an array of React Elements @example import {arrayToJSX} from 'webcompiler'; // or - import {arrayToJSX} from 'webcompiler/lib/jsx'; // or - var arrayToJSX = require('webcompiler').arrayToJSX; // or - var arrayToJSX = require('webcompiler/lib/jsx').arrayToJSX; <div>{arrayToJSX([{type: 'h1', children: ['Hello world!']}])}</div>
[ "Converts", "an", "array", "of", "plain", "objects", "describing", "React", "Elements", "to", "an", "array", "of", "React", "Elements", "." ]
eb094f1632e5313ed0c5391a303150f1416b9629
https://github.com/thealjey/webcompiler/blob/eb094f1632e5313ed0c5391a303150f1416b9629/lib/jsx.js#L231-L240
46,588
CocktailJS/cocktail
lib/processor/annotation/Merge.js
function (mine, their, strategy) { this._doMerge(mine, their, function(key){ if (typeof their[key] === 'object') { if (their[key] instanceof Array) { mine[key] = [].concat(mine[key], their[key]); } else { mine[key] = this[strategy](mine[key], their[key]); } } else if (mine[key] === undefined ) { mine[key] = their[key]; } }); return mine; }
javascript
function (mine, their, strategy) { this._doMerge(mine, their, function(key){ if (typeof their[key] === 'object') { if (their[key] instanceof Array) { mine[key] = [].concat(mine[key], their[key]); } else { mine[key] = this[strategy](mine[key], their[key]); } } else if (mine[key] === undefined ) { mine[key] = their[key]; } }); return mine; }
[ "function", "(", "mine", ",", "their", ",", "strategy", ")", "{", "this", ".", "_doMerge", "(", "mine", ",", "their", ",", "function", "(", "key", ")", "{", "if", "(", "typeof", "their", "[", "key", "]", "===", "'object'", ")", "{", "if", "(", "their", "[", "key", "]", "instanceof", "Array", ")", "{", "mine", "[", "key", "]", "=", "[", "]", ".", "concat", "(", "mine", "[", "key", "]", ",", "their", "[", "key", "]", ")", ";", "}", "else", "{", "mine", "[", "key", "]", "=", "this", "[", "strategy", "]", "(", "mine", "[", "key", "]", ",", "their", "[", "key", "]", ")", ";", "}", "}", "else", "if", "(", "mine", "[", "key", "]", "===", "undefined", ")", "{", "mine", "[", "key", "]", "=", "their", "[", "key", "]", ";", "}", "}", ")", ";", "return", "mine", ";", "}" ]
runs the deep merge using the given strategy
[ "runs", "the", "deep", "merge", "using", "the", "given", "strategy" ]
0c963d8afa18d6387c5fae29f5749cd51efc04aa
https://github.com/CocktailJS/cocktail/blob/0c963d8afa18d6387c5fae29f5749cd51efc04aa/lib/processor/annotation/Merge.js#L116-L130
46,589
freakimkaefig/musicjson2abc
lib/abc_parser/index.js
function(line, curr_pos) { var ret = tokenizer.getBarLine(line, curr_pos); if (ret.len === 0) return [0,""]; if (ret.warn) { warn(ret.warn, line, curr_pos); return [ret.len,""]; } // Now see if this is a repeated ending // A repeated ending is all of the characters 1,2,3,4,5,6,7,8,9,0,-, and comma // It can also optionally start with '[', which is ignored. // Also, it can have white space before the '['. for (var ws = 0; ws < line.length; ws++) if (line.charAt(curr_pos + ret.len + ws) !== ' ') break; var orig_bar_len = ret.len; if (line.charAt(curr_pos+ret.len+ws) === '[') { ret.len += ws + 1; } // It can also be a quoted string. It is unclear whether that construct requires '[', but it seems like it would. otherwise it would be confused with a regular chord. if (line.charAt(curr_pos+ret.len) === '"' && line.charAt(curr_pos+ret.len-1) === '[') { var ending = tokenizer.getBrackettedSubstring(line, curr_pos+ret.len, 5); return [ret.len+ending[0], ret.token, ending[1]]; } var retRep = tokenizer.getTokenOf(line.substring(curr_pos+ret.len), "1234567890-,"); if (retRep.len === 0 || retRep.token[0] === '-') return [orig_bar_len, ret.token]; return [ret.len+retRep.len, ret.token, retRep.token]; }
javascript
function(line, curr_pos) { var ret = tokenizer.getBarLine(line, curr_pos); if (ret.len === 0) return [0,""]; if (ret.warn) { warn(ret.warn, line, curr_pos); return [ret.len,""]; } // Now see if this is a repeated ending // A repeated ending is all of the characters 1,2,3,4,5,6,7,8,9,0,-, and comma // It can also optionally start with '[', which is ignored. // Also, it can have white space before the '['. for (var ws = 0; ws < line.length; ws++) if (line.charAt(curr_pos + ret.len + ws) !== ' ') break; var orig_bar_len = ret.len; if (line.charAt(curr_pos+ret.len+ws) === '[') { ret.len += ws + 1; } // It can also be a quoted string. It is unclear whether that construct requires '[', but it seems like it would. otherwise it would be confused with a regular chord. if (line.charAt(curr_pos+ret.len) === '"' && line.charAt(curr_pos+ret.len-1) === '[') { var ending = tokenizer.getBrackettedSubstring(line, curr_pos+ret.len, 5); return [ret.len+ending[0], ret.token, ending[1]]; } var retRep = tokenizer.getTokenOf(line.substring(curr_pos+ret.len), "1234567890-,"); if (retRep.len === 0 || retRep.token[0] === '-') return [orig_bar_len, ret.token]; return [ret.len+retRep.len, ret.token, retRep.token]; }
[ "function", "(", "line", ",", "curr_pos", ")", "{", "var", "ret", "=", "tokenizer", ".", "getBarLine", "(", "line", ",", "curr_pos", ")", ";", "if", "(", "ret", ".", "len", "===", "0", ")", "return", "[", "0", ",", "\"\"", "]", ";", "if", "(", "ret", ".", "warn", ")", "{", "warn", "(", "ret", ".", "warn", ",", "line", ",", "curr_pos", ")", ";", "return", "[", "ret", ".", "len", ",", "\"\"", "]", ";", "}", "// Now see if this is a repeated ending", "// A repeated ending is all of the characters 1,2,3,4,5,6,7,8,9,0,-, and comma", "// It can also optionally start with '[', which is ignored.", "// Also, it can have white space before the '['.", "for", "(", "var", "ws", "=", "0", ";", "ws", "<", "line", ".", "length", ";", "ws", "++", ")", "if", "(", "line", ".", "charAt", "(", "curr_pos", "+", "ret", ".", "len", "+", "ws", ")", "!==", "' '", ")", "break", ";", "var", "orig_bar_len", "=", "ret", ".", "len", ";", "if", "(", "line", ".", "charAt", "(", "curr_pos", "+", "ret", ".", "len", "+", "ws", ")", "===", "'['", ")", "{", "ret", ".", "len", "+=", "ws", "+", "1", ";", "}", "// It can also be a quoted string. It is unclear whether that construct requires '[', but it seems like it would. otherwise it would be confused with a regular chord.", "if", "(", "line", ".", "charAt", "(", "curr_pos", "+", "ret", ".", "len", ")", "===", "'\"'", "&&", "line", ".", "charAt", "(", "curr_pos", "+", "ret", ".", "len", "-", "1", ")", "===", "'['", ")", "{", "var", "ending", "=", "tokenizer", ".", "getBrackettedSubstring", "(", "line", ",", "curr_pos", "+", "ret", ".", "len", ",", "5", ")", ";", "return", "[", "ret", ".", "len", "+", "ending", "[", "0", "]", ",", "ret", ".", "token", ",", "ending", "[", "1", "]", "]", ";", "}", "var", "retRep", "=", "tokenizer", ".", "getTokenOf", "(", "line", ".", "substring", "(", "curr_pos", "+", "ret", ".", "len", ")", ",", "\"1234567890-,\"", ")", ";", "if", "(", "retRep", ".", "len", "===", "0", "||", "retRep", ".", "token", "[", "0", "]", "===", "'-'", ")", "return", "[", "orig_bar_len", ",", "ret", ".", "token", "]", ";", "return", "[", "ret", ".", "len", "+", "retRep", ".", "len", ",", "ret", ".", "token", ",", "retRep", ".", "token", "]", ";", "}" ]
returns the class of the bar line the number of the repeat and the number of characters used up if 0 is returned, then the next element was not a bar line
[ "returns", "the", "class", "of", "the", "bar", "line", "the", "number", "of", "the", "repeat", "and", "the", "number", "of", "characters", "used", "up", "if", "0", "is", "returned", "then", "the", "next", "element", "was", "not", "a", "bar", "line" ]
c119c7927c3c9b6aa5f3558cc73990478472dfbb
https://github.com/freakimkaefig/musicjson2abc/blob/c119c7927c3c9b6aa5f3558cc73990478472dfbb/lib/abc_parser/index.js#L308-L340
46,590
freakimkaefig/musicjson2abc
lib/abc_parser/index.js
function(all, backslash, comment){ var spaces = " "; var padding = comment ? spaces.substring(0, comment.length) : ""; return backslash + " \x12" + padding; }
javascript
function(all, backslash, comment){ var spaces = " "; var padding = comment ? spaces.substring(0, comment.length) : ""; return backslash + " \x12" + padding; }
[ "function", "(", "all", ",", "backslash", ",", "comment", ")", "{", "var", "spaces", "=", "\" \"", ";", "var", "padding", "=", "comment", "?", "spaces", ".", "substring", "(", "0", ",", "comment", ".", "length", ")", ":", "\"\"", ";", "return", "backslash", "+", "\" \\x12\"", "+", "padding", ";", "}" ]
get rid of latex commands.
[ "get", "rid", "of", "latex", "commands", "." ]
c119c7927c3c9b6aa5f3558cc73990478472dfbb
https://github.com/freakimkaefig/musicjson2abc/blob/c119c7927c3c9b6aa5f3558cc73990478472dfbb/lib/abc_parser/index.js#L1407-L1411
46,591
Zerg00s/spforms
src/Templates/App/directives/commonDirectives.js
function (attachment) { // Define custom metadata properties for the file before saving var customFileMetadata = {}; var parentItemId = model.getParentItemId(); if (parentItemId && parentItemId != '') customFileMetadata[scope.attachmentFilterFieldName + "Id"] = String(parentItemId); // Upload the file using the SharePoint item service return spFormFactory.uploadFileToDocLib(attachment.File.ArrayBuffer, scope.attachmentDocLibName, scope.attachmentDocFolderName, attachment.File.Name, attachment.File.Title, customFileMetadata); }
javascript
function (attachment) { // Define custom metadata properties for the file before saving var customFileMetadata = {}; var parentItemId = model.getParentItemId(); if (parentItemId && parentItemId != '') customFileMetadata[scope.attachmentFilterFieldName + "Id"] = String(parentItemId); // Upload the file using the SharePoint item service return spFormFactory.uploadFileToDocLib(attachment.File.ArrayBuffer, scope.attachmentDocLibName, scope.attachmentDocFolderName, attachment.File.Name, attachment.File.Title, customFileMetadata); }
[ "function", "(", "attachment", ")", "{", "// Define custom metadata properties for the file before saving", "var", "customFileMetadata", "=", "{", "}", ";", "var", "parentItemId", "=", "model", ".", "getParentItemId", "(", ")", ";", "if", "(", "parentItemId", "&&", "parentItemId", "!=", "''", ")", "customFileMetadata", "[", "scope", ".", "attachmentFilterFieldName", "+", "\"Id\"", "]", "=", "String", "(", "parentItemId", ")", ";", "// Upload the file using the SharePoint item service", "return", "spFormFactory", ".", "uploadFileToDocLib", "(", "attachment", ".", "File", ".", "ArrayBuffer", ",", "scope", ".", "attachmentDocLibName", ",", "scope", ".", "attachmentDocFolderName", ",", "attachment", ".", "File", ".", "Name", ",", "attachment", ".", "File", ".", "Title", ",", "customFileMetadata", ")", ";", "}" ]
Upload the file. You can upload files up to 2 GB with the REST API.
[ "Upload", "the", "file", ".", "You", "can", "upload", "files", "up", "to", "2", "GB", "with", "the", "REST", "API", "." ]
f8eaa19eeefa6ca7a3664138b76744f9c1d9ecec
https://github.com/Zerg00s/spforms/blob/f8eaa19eeefa6ca7a3664138b76744f9c1d9ecec/src/Templates/App/directives/commonDirectives.js#L116-L124
46,592
bitinn/decent
lib/decent.js
Queue
function Queue(name, opts) { // allow call as function if (!(this instanceof Queue)) return new Queue(name, opts); if (!name) { throw new Error('queue name is required'); } opts = opts || {}; // basic this.name = name; this.port = opts.port || 6379; this.host = opts.host || '127.0.0.1'; // queue config this.config = { blockTimeout: opts.blockTimeout || 60 , maxRetry: opts.maxRetry || 3 }; // redis options this.opts = opts; // main redis client this.client = Redis.createClient(this.port, this.host, this.opts); // client for blocking command only this.bclient = Redis.createClient(this.port, this.host, this.opts); // queue name this.prefix = 'dq:' + this.name; this.workQueue = this.prefix + ':work'; this.runQueue = this.prefix + ':run'; this.failQueue = this.prefix + ':fail'; // status code this.status_timeout = 1; // queue status this.shutdown = false; this.running = false; }
javascript
function Queue(name, opts) { // allow call as function if (!(this instanceof Queue)) return new Queue(name, opts); if (!name) { throw new Error('queue name is required'); } opts = opts || {}; // basic this.name = name; this.port = opts.port || 6379; this.host = opts.host || '127.0.0.1'; // queue config this.config = { blockTimeout: opts.blockTimeout || 60 , maxRetry: opts.maxRetry || 3 }; // redis options this.opts = opts; // main redis client this.client = Redis.createClient(this.port, this.host, this.opts); // client for blocking command only this.bclient = Redis.createClient(this.port, this.host, this.opts); // queue name this.prefix = 'dq:' + this.name; this.workQueue = this.prefix + ':work'; this.runQueue = this.prefix + ':run'; this.failQueue = this.prefix + ':fail'; // status code this.status_timeout = 1; // queue status this.shutdown = false; this.running = false; }
[ "function", "Queue", "(", "name", ",", "opts", ")", "{", "// allow call as function", "if", "(", "!", "(", "this", "instanceof", "Queue", ")", ")", "return", "new", "Queue", "(", "name", ",", "opts", ")", ";", "if", "(", "!", "name", ")", "{", "throw", "new", "Error", "(", "'queue name is required'", ")", ";", "}", "opts", "=", "opts", "||", "{", "}", ";", "// basic", "this", ".", "name", "=", "name", ";", "this", ".", "port", "=", "opts", ".", "port", "||", "6379", ";", "this", ".", "host", "=", "opts", ".", "host", "||", "'127.0.0.1'", ";", "// queue config", "this", ".", "config", "=", "{", "blockTimeout", ":", "opts", ".", "blockTimeout", "||", "60", ",", "maxRetry", ":", "opts", ".", "maxRetry", "||", "3", "}", ";", "// redis options", "this", ".", "opts", "=", "opts", ";", "// main redis client", "this", ".", "client", "=", "Redis", ".", "createClient", "(", "this", ".", "port", ",", "this", ".", "host", ",", "this", ".", "opts", ")", ";", "// client for blocking command only", "this", ".", "bclient", "=", "Redis", ".", "createClient", "(", "this", ".", "port", ",", "this", ".", "host", ",", "this", ".", "opts", ")", ";", "// queue name", "this", ".", "prefix", "=", "'dq:'", "+", "this", ".", "name", ";", "this", ".", "workQueue", "=", "this", ".", "prefix", "+", "':work'", ";", "this", ".", "runQueue", "=", "this", ".", "prefix", "+", "':run'", ";", "this", ".", "failQueue", "=", "this", ".", "prefix", "+", "':fail'", ";", "// status code", "this", ".", "status_timeout", "=", "1", ";", "// queue status", "this", ".", "shutdown", "=", "false", ";", "this", ".", "running", "=", "false", ";", "}" ]
Create an instance of Queue @param String name Name of this queue @param Object opts Redis options @return Object
[ "Create", "an", "instance", "of", "Queue" ]
410f24a71161ccacb7ff7cc11d3976bd039f434a
https://github.com/bitinn/decent/blob/410f24a71161ccacb7ff7cc11d3976bd039f434a/lib/decent.js#L25-L70
46,593
reklatsmasters/ip2buf
lib/pton4.js
pton4
function pton4(addr, dest, index = 0) { if (typeof addr !== 'string') { throw new TypeError('Argument 1 should be a string.') } if (arguments.length >= 3) { if (typeof index !== 'number') { throw new TypeError('Argument 3 should be a Number.') } } const isbuffer = Buffer.isBuffer(dest) if (isbuffer) { if (index + IPV4_OCTETS > dest.length) { throw new Error('Too small target buffer.') } } const buf = isbuffer ? dest : Buffer.allocUnsafe(IPV4_OCTETS) let octets = 0 let sawDigit = false let number = 0 for (let i = 0; i < addr.length; ++i) { const char = code(addr[i]) if (isDigit(char)) { number = (number * 10) + (char - CHAR0) if (sawDigit && number === 0) { einval() } if (number > 0xFF) { einval() } if (!sawDigit) { if (++octets > IPV4_OCTETS) { einval() } sawDigit = true } } else if (char === CHARPOINT && sawDigit) { if (octets === IPV4_OCTETS) { einval() } buf[index++] = number number = 0 sawDigit = false } else { einval() } } if (octets < IPV4_OCTETS) { einval() } if (sawDigit) { buf[index] = number } return buf }
javascript
function pton4(addr, dest, index = 0) { if (typeof addr !== 'string') { throw new TypeError('Argument 1 should be a string.') } if (arguments.length >= 3) { if (typeof index !== 'number') { throw new TypeError('Argument 3 should be a Number.') } } const isbuffer = Buffer.isBuffer(dest) if (isbuffer) { if (index + IPV4_OCTETS > dest.length) { throw new Error('Too small target buffer.') } } const buf = isbuffer ? dest : Buffer.allocUnsafe(IPV4_OCTETS) let octets = 0 let sawDigit = false let number = 0 for (let i = 0; i < addr.length; ++i) { const char = code(addr[i]) if (isDigit(char)) { number = (number * 10) + (char - CHAR0) if (sawDigit && number === 0) { einval() } if (number > 0xFF) { einval() } if (!sawDigit) { if (++octets > IPV4_OCTETS) { einval() } sawDigit = true } } else if (char === CHARPOINT && sawDigit) { if (octets === IPV4_OCTETS) { einval() } buf[index++] = number number = 0 sawDigit = false } else { einval() } } if (octets < IPV4_OCTETS) { einval() } if (sawDigit) { buf[index] = number } return buf }
[ "function", "pton4", "(", "addr", ",", "dest", ",", "index", "=", "0", ")", "{", "if", "(", "typeof", "addr", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'Argument 1 should be a string.'", ")", "}", "if", "(", "arguments", ".", "length", ">=", "3", ")", "{", "if", "(", "typeof", "index", "!==", "'number'", ")", "{", "throw", "new", "TypeError", "(", "'Argument 3 should be a Number.'", ")", "}", "}", "const", "isbuffer", "=", "Buffer", ".", "isBuffer", "(", "dest", ")", "if", "(", "isbuffer", ")", "{", "if", "(", "index", "+", "IPV4_OCTETS", ">", "dest", ".", "length", ")", "{", "throw", "new", "Error", "(", "'Too small target buffer.'", ")", "}", "}", "const", "buf", "=", "isbuffer", "?", "dest", ":", "Buffer", ".", "allocUnsafe", "(", "IPV4_OCTETS", ")", "let", "octets", "=", "0", "let", "sawDigit", "=", "false", "let", "number", "=", "0", "for", "(", "let", "i", "=", "0", ";", "i", "<", "addr", ".", "length", ";", "++", "i", ")", "{", "const", "char", "=", "code", "(", "addr", "[", "i", "]", ")", "if", "(", "isDigit", "(", "char", ")", ")", "{", "number", "=", "(", "number", "*", "10", ")", "+", "(", "char", "-", "CHAR0", ")", "if", "(", "sawDigit", "&&", "number", "===", "0", ")", "{", "einval", "(", ")", "}", "if", "(", "number", ">", "0xFF", ")", "{", "einval", "(", ")", "}", "if", "(", "!", "sawDigit", ")", "{", "if", "(", "++", "octets", ">", "IPV4_OCTETS", ")", "{", "einval", "(", ")", "}", "sawDigit", "=", "true", "}", "}", "else", "if", "(", "char", "===", "CHARPOINT", "&&", "sawDigit", ")", "{", "if", "(", "octets", "===", "IPV4_OCTETS", ")", "{", "einval", "(", ")", "}", "buf", "[", "index", "++", "]", "=", "number", "number", "=", "0", "sawDigit", "=", "false", "}", "else", "{", "einval", "(", ")", "}", "}", "if", "(", "octets", "<", "IPV4_OCTETS", ")", "{", "einval", "(", ")", "}", "if", "(", "sawDigit", ")", "{", "buf", "[", "index", "]", "=", "number", "}", "return", "buf", "}" ]
Convert IPv4 to the Buffer. @param {string} addr @param {Buffer} [dest] @param {number} [index=0] @returns {Buffer}
[ "Convert", "IPv4", "to", "the", "Buffer", "." ]
439c55cc7605423929808d42a29b9cd284914cd6
https://github.com/reklatsmasters/ip2buf/blob/439c55cc7605423929808d42a29b9cd284914cd6/lib/pton4.js#L17-L84
46,594
looeee/npm-three-app
demo/module-import/js/vendor/three.module.js
BufferGeometry
function BufferGeometry() { Object.defineProperty( this, 'id', { value: bufferGeometryId += 2 } ); this.uuid = _Math.generateUUID(); this.name = ''; this.type = 'BufferGeometry'; this.index = null; this.attributes = {}; this.morphAttributes = {}; this.groups = []; this.boundingBox = null; this.boundingSphere = null; this.drawRange = { start: 0, count: Infinity }; this.userData = {}; }
javascript
function BufferGeometry() { Object.defineProperty( this, 'id', { value: bufferGeometryId += 2 } ); this.uuid = _Math.generateUUID(); this.name = ''; this.type = 'BufferGeometry'; this.index = null; this.attributes = {}; this.morphAttributes = {}; this.groups = []; this.boundingBox = null; this.boundingSphere = null; this.drawRange = { start: 0, count: Infinity }; this.userData = {}; }
[ "function", "BufferGeometry", "(", ")", "{", "Object", ".", "defineProperty", "(", "this", ",", "'id'", ",", "{", "value", ":", "bufferGeometryId", "+=", "2", "}", ")", ";", "this", ".", "uuid", "=", "_Math", ".", "generateUUID", "(", ")", ";", "this", ".", "name", "=", "''", ";", "this", ".", "type", "=", "'BufferGeometry'", ";", "this", ".", "index", "=", "null", ";", "this", ".", "attributes", "=", "{", "}", ";", "this", ".", "morphAttributes", "=", "{", "}", ";", "this", ".", "groups", "=", "[", "]", ";", "this", ".", "boundingBox", "=", "null", ";", "this", ".", "boundingSphere", "=", "null", ";", "this", ".", "drawRange", "=", "{", "start", ":", "0", ",", "count", ":", "Infinity", "}", ";", "this", ".", "userData", "=", "{", "}", ";", "}" ]
BufferGeometry uses odd numbers as Id
[ "BufferGeometry", "uses", "odd", "numbers", "as", "Id" ]
439be8d3119bf0f00a7790f77a57ec76fc126580
https://github.com/looeee/npm-three-app/blob/439be8d3119bf0f00a7790f77a57ec76fc126580/demo/module-import/js/vendor/three.module.js#L11161-L11184
46,595
looeee/npm-three-app
demo/module-import/js/vendor/three.module.js
getSingularSetter
function getSingularSetter( type ) { switch ( type ) { case 0x1406: return setValue1f; // FLOAT case 0x8b50: return setValue2fv; // _VEC2 case 0x8b51: return setValue3fv; // _VEC3 case 0x8b52: return setValue4fv; // _VEC4 case 0x8b5a: return setValue2fm; // _MAT2 case 0x8b5b: return setValue3fm; // _MAT3 case 0x8b5c: return setValue4fm; // _MAT4 case 0x8b5e: case 0x8d66: return setValueT1; // SAMPLER_2D, SAMPLER_EXTERNAL_OES case 0x8B5F: return setValueT3D1; // SAMPLER_3D case 0x8b60: return setValueT6; // SAMPLER_CUBE case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2 case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3 case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4 } }
javascript
function getSingularSetter( type ) { switch ( type ) { case 0x1406: return setValue1f; // FLOAT case 0x8b50: return setValue2fv; // _VEC2 case 0x8b51: return setValue3fv; // _VEC3 case 0x8b52: return setValue4fv; // _VEC4 case 0x8b5a: return setValue2fm; // _MAT2 case 0x8b5b: return setValue3fm; // _MAT3 case 0x8b5c: return setValue4fm; // _MAT4 case 0x8b5e: case 0x8d66: return setValueT1; // SAMPLER_2D, SAMPLER_EXTERNAL_OES case 0x8B5F: return setValueT3D1; // SAMPLER_3D case 0x8b60: return setValueT6; // SAMPLER_CUBE case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2 case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3 case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4 } }
[ "function", "getSingularSetter", "(", "type", ")", "{", "switch", "(", "type", ")", "{", "case", "0x1406", ":", "return", "setValue1f", ";", "// FLOAT", "case", "0x8b50", ":", "return", "setValue2fv", ";", "// _VEC2", "case", "0x8b51", ":", "return", "setValue3fv", ";", "// _VEC3", "case", "0x8b52", ":", "return", "setValue4fv", ";", "// _VEC4", "case", "0x8b5a", ":", "return", "setValue2fm", ";", "// _MAT2", "case", "0x8b5b", ":", "return", "setValue3fm", ";", "// _MAT3", "case", "0x8b5c", ":", "return", "setValue4fm", ";", "// _MAT4", "case", "0x8b5e", ":", "case", "0x8d66", ":", "return", "setValueT1", ";", "// SAMPLER_2D, SAMPLER_EXTERNAL_OES", "case", "0x8B5F", ":", "return", "setValueT3D1", ";", "// SAMPLER_3D", "case", "0x8b60", ":", "return", "setValueT6", ";", "// SAMPLER_CUBE", "case", "0x1404", ":", "case", "0x8b56", ":", "return", "setValue1i", ";", "// INT, BOOL", "case", "0x8b53", ":", "case", "0x8b57", ":", "return", "setValue2iv", ";", "// _VEC2", "case", "0x8b54", ":", "case", "0x8b58", ":", "return", "setValue3iv", ";", "// _VEC3", "case", "0x8b55", ":", "case", "0x8b59", ":", "return", "setValue4iv", ";", "// _VEC4", "}", "}" ]
Helper to pick the right setter for the singular case
[ "Helper", "to", "pick", "the", "right", "setter", "for", "the", "singular", "case" ]
439be8d3119bf0f00a7790f77a57ec76fc126580
https://github.com/looeee/npm-three-app/blob/439be8d3119bf0f00a7790f77a57ec76fc126580/demo/module-import/js/vendor/three.module.js#L16194-L16218
46,596
looeee/npm-three-app
demo/module-import/js/vendor/three.module.js
setValue1fv
function setValue1fv( gl, v ) { var cache = this.cache; if ( arraysEqual( cache, v ) ) return; gl.uniform1fv( this.addr, v ); copyArray( cache, v ); }
javascript
function setValue1fv( gl, v ) { var cache = this.cache; if ( arraysEqual( cache, v ) ) return; gl.uniform1fv( this.addr, v ); copyArray( cache, v ); }
[ "function", "setValue1fv", "(", "gl", ",", "v", ")", "{", "var", "cache", "=", "this", ".", "cache", ";", "if", "(", "arraysEqual", "(", "cache", ",", "v", ")", ")", "return", ";", "gl", ".", "uniform1fv", "(", "this", ".", "addr", ",", "v", ")", ";", "copyArray", "(", "cache", ",", "v", ")", ";", "}" ]
Array of scalars
[ "Array", "of", "scalars" ]
439be8d3119bf0f00a7790f77a57ec76fc126580
https://github.com/looeee/npm-three-app/blob/439be8d3119bf0f00a7790f77a57ec76fc126580/demo/module-import/js/vendor/three.module.js#L16222-L16232
46,597
looeee/npm-three-app
demo/module-import/js/vendor/three.module.js
CubicInterpolant
function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); this._weightPrev = - 0; this._offsetPrev = - 0; this._weightNext = - 0; this._offsetNext = - 0; }
javascript
function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); this._weightPrev = - 0; this._offsetPrev = - 0; this._weightNext = - 0; this._offsetNext = - 0; }
[ "function", "CubicInterpolant", "(", "parameterPositions", ",", "sampleValues", ",", "sampleSize", ",", "resultBuffer", ")", "{", "Interpolant", ".", "call", "(", "this", ",", "parameterPositions", ",", "sampleValues", ",", "sampleSize", ",", "resultBuffer", ")", ";", "this", ".", "_weightPrev", "=", "-", "0", ";", "this", ".", "_offsetPrev", "=", "-", "0", ";", "this", ".", "_weightNext", "=", "-", "0", ";", "this", ".", "_offsetNext", "=", "-", "0", ";", "}" ]
Fast and simple cubic spline interpolant. It was derived from a Hermitian construction setting the first derivative at each sample position to the linear slope between neighboring positions over their parameter interval. @author tschw
[ "Fast", "and", "simple", "cubic", "spline", "interpolant", "." ]
439be8d3119bf0f00a7790f77a57ec76fc126580
https://github.com/looeee/npm-three-app/blob/439be8d3119bf0f00a7790f77a57ec76fc126580/demo/module-import/js/vendor/three.module.js#L32339-L32348
46,598
looeee/npm-three-app
demo/module-import/js/vendor/three.module.js
function () { var valid = true; var valueSize = this.getValueSize(); if ( valueSize - Math.floor( valueSize ) !== 0 ) { console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this ); valid = false; } var times = this.times, values = this.values, nKeys = times.length; if ( nKeys === 0 ) { console.error( 'THREE.KeyframeTrack: Track is empty.', this ); valid = false; } var prevTime = null; for ( var i = 0; i !== nKeys; i ++ ) { var currTime = times[ i ]; if ( typeof currTime === 'number' && isNaN( currTime ) ) { console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime ); valid = false; break; } if ( prevTime !== null && prevTime > currTime ) { console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime ); valid = false; break; } prevTime = currTime; } if ( values !== undefined ) { if ( AnimationUtils.isTypedArray( values ) ) { for ( var i = 0, n = values.length; i !== n; ++ i ) { var value = values[ i ]; if ( isNaN( value ) ) { console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value ); valid = false; break; } } } } return valid; }
javascript
function () { var valid = true; var valueSize = this.getValueSize(); if ( valueSize - Math.floor( valueSize ) !== 0 ) { console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this ); valid = false; } var times = this.times, values = this.values, nKeys = times.length; if ( nKeys === 0 ) { console.error( 'THREE.KeyframeTrack: Track is empty.', this ); valid = false; } var prevTime = null; for ( var i = 0; i !== nKeys; i ++ ) { var currTime = times[ i ]; if ( typeof currTime === 'number' && isNaN( currTime ) ) { console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime ); valid = false; break; } if ( prevTime !== null && prevTime > currTime ) { console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime ); valid = false; break; } prevTime = currTime; } if ( values !== undefined ) { if ( AnimationUtils.isTypedArray( values ) ) { for ( var i = 0, n = values.length; i !== n; ++ i ) { var value = values[ i ]; if ( isNaN( value ) ) { console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value ); valid = false; break; } } } } return valid; }
[ "function", "(", ")", "{", "var", "valid", "=", "true", ";", "var", "valueSize", "=", "this", ".", "getValueSize", "(", ")", ";", "if", "(", "valueSize", "-", "Math", ".", "floor", "(", "valueSize", ")", "!==", "0", ")", "{", "console", ".", "error", "(", "'THREE.KeyframeTrack: Invalid value size in track.'", ",", "this", ")", ";", "valid", "=", "false", ";", "}", "var", "times", "=", "this", ".", "times", ",", "values", "=", "this", ".", "values", ",", "nKeys", "=", "times", ".", "length", ";", "if", "(", "nKeys", "===", "0", ")", "{", "console", ".", "error", "(", "'THREE.KeyframeTrack: Track is empty.'", ",", "this", ")", ";", "valid", "=", "false", ";", "}", "var", "prevTime", "=", "null", ";", "for", "(", "var", "i", "=", "0", ";", "i", "!==", "nKeys", ";", "i", "++", ")", "{", "var", "currTime", "=", "times", "[", "i", "]", ";", "if", "(", "typeof", "currTime", "===", "'number'", "&&", "isNaN", "(", "currTime", ")", ")", "{", "console", ".", "error", "(", "'THREE.KeyframeTrack: Time is not a valid number.'", ",", "this", ",", "i", ",", "currTime", ")", ";", "valid", "=", "false", ";", "break", ";", "}", "if", "(", "prevTime", "!==", "null", "&&", "prevTime", ">", "currTime", ")", "{", "console", ".", "error", "(", "'THREE.KeyframeTrack: Out of order keys.'", ",", "this", ",", "i", ",", "currTime", ",", "prevTime", ")", ";", "valid", "=", "false", ";", "break", ";", "}", "prevTime", "=", "currTime", ";", "}", "if", "(", "values", "!==", "undefined", ")", "{", "if", "(", "AnimationUtils", ".", "isTypedArray", "(", "values", ")", ")", "{", "for", "(", "var", "i", "=", "0", ",", "n", "=", "values", ".", "length", ";", "i", "!==", "n", ";", "++", "i", ")", "{", "var", "value", "=", "values", "[", "i", "]", ";", "if", "(", "isNaN", "(", "value", ")", ")", "{", "console", ".", "error", "(", "'THREE.KeyframeTrack: Value is not a valid number.'", ",", "this", ",", "i", ",", "value", ")", ";", "valid", "=", "false", ";", "break", ";", "}", "}", "}", "}", "return", "valid", ";", "}" ]
ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
[ "ensure", "we", "do", "not", "get", "a", "GarbageInGarbageOut", "situation", "make", "sure", "tracks", "are", "at", "least", "minimally", "viable" ]
439be8d3119bf0f00a7790f77a57ec76fc126580
https://github.com/looeee/npm-three-app/blob/439be8d3119bf0f00a7790f77a57ec76fc126580/demo/module-import/js/vendor/three.module.js#L32804-L32878
46,599
looeee/npm-three-app
demo/module-import/js/vendor/three.module.js
QuaternionLinearInterpolant
function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); }
javascript
function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); }
[ "function", "QuaternionLinearInterpolant", "(", "parameterPositions", ",", "sampleValues", ",", "sampleSize", ",", "resultBuffer", ")", "{", "Interpolant", ".", "call", "(", "this", ",", "parameterPositions", ",", "sampleValues", ",", "sampleSize", ",", "resultBuffer", ")", ";", "}" ]
Spherical linear unit quaternion interpolant. @author tschw
[ "Spherical", "linear", "unit", "quaternion", "interpolant", "." ]
439be8d3119bf0f00a7790f77a57ec76fc126580
https://github.com/looeee/npm-three-app/blob/439be8d3119bf0f00a7790f77a57ec76fc126580/demo/module-import/js/vendor/three.module.js#L33086-L33090