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
37,000
myrmex-org/myrmex
packages/api-gateway/src/cli/inspect-endpoint.js
executeCommand
function executeCommand(parameters) { if (parameters.colors === undefined) { parameters.colors = plugin.myrmex.getConfig('colors'); } return plugin.findEndpoint(parameters.resourcePath, parameters.httpMethod) .then(endpoint => { const jsonSpec = endpoint.generateSpec(parameters.specVersion); let spec = JSON.stringify(jsonSpec, null, 2); if (parameters.colors) { spec = icli.highlight(spec, { json: true }); } icli.print(spec); return Promise.resolve(jsonSpec); }); }
javascript
function executeCommand(parameters) { if (parameters.colors === undefined) { parameters.colors = plugin.myrmex.getConfig('colors'); } return plugin.findEndpoint(parameters.resourcePath, parameters.httpMethod) .then(endpoint => { const jsonSpec = endpoint.generateSpec(parameters.specVersion); let spec = JSON.stringify(jsonSpec, null, 2); if (parameters.colors) { spec = icli.highlight(spec, { json: true }); } icli.print(spec); return Promise.resolve(jsonSpec); }); }
[ "function", "executeCommand", "(", "parameters", ")", "{", "if", "(", "parameters", ".", "colors", "===", "undefined", ")", "{", "parameters", ".", "colors", "=", "plugin", ".", "myrmex", ".", "getConfig", "(", "'colors'", ")", ";", "}", "return", "plugin", ".", "findEndpoint", "(", "parameters", ".", "resourcePath", ",", "parameters", ".", "httpMethod", ")", ".", "then", "(", "endpoint", "=>", "{", "const", "jsonSpec", "=", "endpoint", ".", "generateSpec", "(", "parameters", ".", "specVersion", ")", ";", "let", "spec", "=", "JSON", ".", "stringify", "(", "jsonSpec", ",", "null", ",", "2", ")", ";", "if", "(", "parameters", ".", "colors", ")", "{", "spec", "=", "icli", ".", "highlight", "(", "spec", ",", "{", "json", ":", "true", "}", ")", ";", "}", "icli", ".", "print", "(", "spec", ")", ";", "return", "Promise", ".", "resolve", "(", "jsonSpec", ")", ";", "}", ")", ";", "}" ]
Output endpoint specification @param {Object} parameters - the parameters provided in the command and in the prompt @returns {Promise<null>} - The execution stops here
[ "Output", "endpoint", "specification" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/api-gateway/src/cli/inspect-endpoint.js#L133-L146
37,001
myrmex-org/myrmex
packages/cli/src/cli/disable-default.js
executeCommand
function executeCommand(parameters) { let msg = '\n ' + icli.format.ko('Unknown command \n\n'); msg += ' Enter ' + icli.format.cmd('myrmex -h') + ' to see available commands\n'; msg += ' You have to be in the root folder of your Myrmex project to see commands implemented by Myrmex plugins\n'; console.log(msg); process.exit(1); }
javascript
function executeCommand(parameters) { let msg = '\n ' + icli.format.ko('Unknown command \n\n'); msg += ' Enter ' + icli.format.cmd('myrmex -h') + ' to see available commands\n'; msg += ' You have to be in the root folder of your Myrmex project to see commands implemented by Myrmex plugins\n'; console.log(msg); process.exit(1); }
[ "function", "executeCommand", "(", "parameters", ")", "{", "let", "msg", "=", "'\\n '", "+", "icli", ".", "format", ".", "ko", "(", "'Unknown command \\n\\n'", ")", ";", "msg", "+=", "' Enter '", "+", "icli", ".", "format", ".", "cmd", "(", "'myrmex -h'", ")", "+", "' to see available commands\\n'", ";", "msg", "+=", "' You have to be in the root folder of your Myrmex project to see commands implemented by Myrmex plugins\\n'", ";", "console", ".", "log", "(", "msg", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}" ]
Show an error if a unknown command was called @param {Object} parameters - the parameters provided in the command and in the prompt @returns {void} - the execution stops here
[ "Show", "an", "error", "if", "a", "unknown", "command", "was", "called" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/cli/src/cli/disable-default.js#L26-L32
37,002
webmodules/get-document
index.js
getDocument
function getDocument(node) { if (isDocument(node)) { return node; } else if (isDocument(node.ownerDocument)) { return node.ownerDocument; } else if (isDocument(node.document)) { return node.document; } else if (node.parentNode) { return getDocument(node.parentNode); // Range support } else if (node.commonAncestorContainer) { return getDocument(node.commonAncestorContainer); } else if (node.startContainer) { return getDocument(node.startContainer); // Selection support } else if (node.anchorNode) { return getDocument(node.anchorNode); } }
javascript
function getDocument(node) { if (isDocument(node)) { return node; } else if (isDocument(node.ownerDocument)) { return node.ownerDocument; } else if (isDocument(node.document)) { return node.document; } else if (node.parentNode) { return getDocument(node.parentNode); // Range support } else if (node.commonAncestorContainer) { return getDocument(node.commonAncestorContainer); } else if (node.startContainer) { return getDocument(node.startContainer); // Selection support } else if (node.anchorNode) { return getDocument(node.anchorNode); } }
[ "function", "getDocument", "(", "node", ")", "{", "if", "(", "isDocument", "(", "node", ")", ")", "{", "return", "node", ";", "}", "else", "if", "(", "isDocument", "(", "node", ".", "ownerDocument", ")", ")", "{", "return", "node", ".", "ownerDocument", ";", "}", "else", "if", "(", "isDocument", "(", "node", ".", "document", ")", ")", "{", "return", "node", ".", "document", ";", "}", "else", "if", "(", "node", ".", "parentNode", ")", "{", "return", "getDocument", "(", "node", ".", "parentNode", ")", ";", "// Range support", "}", "else", "if", "(", "node", ".", "commonAncestorContainer", ")", "{", "return", "getDocument", "(", "node", ".", "commonAncestorContainer", ")", ";", "}", "else", "if", "(", "node", ".", "startContainer", ")", "{", "return", "getDocument", "(", "node", ".", "startContainer", ")", ";", "// Selection support", "}", "else", "if", "(", "node", ".", "anchorNode", ")", "{", "return", "getDocument", "(", "node", ".", "anchorNode", ")", ";", "}", "}" ]
Returns the `document` object associated with the given `node`, which may be a DOM element, the Window object, a Selection, a Range. Basically any DOM object that references the Document in some way, this function will find it. @param {Mixed} node - DOM node, selection, or range in which to find the `document` object @return {Document} the `document` object associated with `node` @public
[ "Returns", "the", "document", "object", "associated", "with", "the", "given", "node", "which", "may", "be", "a", "DOM", "element", "the", "Window", "object", "a", "Selection", "a", "Range", ".", "Basically", "any", "DOM", "object", "that", "references", "the", "Document", "in", "some", "way", "this", "function", "will", "find", "it", "." ]
a04ccb499d6e0433a368c3bb150b4899b698461f
https://github.com/webmodules/get-document/blob/a04ccb499d6e0433a368c3bb150b4899b698461f/index.js#L33-L57
37,003
nodetiles/nodetiles-core
lib/cartoRenderer.js
d2h
function d2h(d, digits) { d = d.toString(16); while (d.length < digits) { d = '0' + d; } return d; }
javascript
function d2h(d, digits) { d = d.toString(16); while (d.length < digits) { d = '0' + d; } return d; }
[ "function", "d2h", "(", "d", ",", "digits", ")", "{", "d", "=", "d", ".", "toString", "(", "16", ")", ";", "while", "(", "d", ".", "length", "<", "digits", ")", "{", "d", "=", "'0'", "+", "d", ";", "}", "return", "d", ";", "}" ]
hex helper functions
[ "hex", "helper", "functions" ]
117853de6935081f7ebefb19c766ab6c1bded244
https://github.com/nodetiles/nodetiles-core/blob/117853de6935081f7ebefb19c766ab6c1bded244/lib/cartoRenderer.js#L1020-L1027
37,004
wotcity/wotcity-wot-framework
lib/framework.js
function() { _.each(this._models, function(model) { var cid = model.get('cid'); model.fetch({ success: function(model, response, options) { if (_.isFunction(model.parseJSON)) model.parseJSON(response); }.bind(model) }); }.bind(this)); }
javascript
function() { _.each(this._models, function(model) { var cid = model.get('cid'); model.fetch({ success: function(model, response, options) { if (_.isFunction(model.parseJSON)) model.parseJSON(response); }.bind(model) }); }.bind(this)); }
[ "function", "(", ")", "{", "_", ".", "each", "(", "this", ".", "_models", ",", "function", "(", "model", ")", "{", "var", "cid", "=", "model", ".", "get", "(", "'cid'", ")", ";", "model", ".", "fetch", "(", "{", "success", ":", "function", "(", "model", ",", "response", ",", "options", ")", "{", "if", "(", "_", ".", "isFunction", "(", "model", ".", "parseJSON", ")", ")", "model", ".", "parseJSON", "(", "response", ")", ";", "}", ".", "bind", "(", "model", ")", "}", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Fetch data of every element
[ "Fetch", "data", "of", "every", "element" ]
050ee10ed34a324fae76429e0014575abde9df35
https://github.com/wotcity/wotcity-wot-framework/blob/050ee10ed34a324fae76429e0014575abde9df35/lib/framework.js#L159-L170
37,005
wotcity/wotcity-wot-framework
lib/framework.js
function(method, args){ _.each(this._elements, function(elem){ if (_.isFunction(elem[method])){ elem[method].apply(elem, args || []); } }); }
javascript
function(method, args){ _.each(this._elements, function(elem){ if (_.isFunction(elem[method])){ elem[method].apply(elem, args || []); } }); }
[ "function", "(", "method", ",", "args", ")", "{", "_", ".", "each", "(", "this", ".", "_elements", ",", "function", "(", "elem", ")", "{", "if", "(", "_", ".", "isFunction", "(", "elem", "[", "method", "]", ")", ")", "{", "elem", "[", "method", "]", ".", "apply", "(", "elem", ",", "args", "||", "[", "]", ")", ";", "}", "}", ")", ";", "}" ]
Apply a method on every element in the container, passing parameters to the call method one at a time, like `function.apply`.
[ "Apply", "a", "method", "on", "every", "element", "in", "the", "container", "passing", "parameters", "to", "the", "call", "method", "one", "at", "a", "time", "like", "function", ".", "apply", "." ]
050ee10ed34a324fae76429e0014575abde9df35
https://github.com/wotcity/wotcity-wot-framework/blob/050ee10ed34a324fae76429e0014575abde9df35/lib/framework.js#L182-L188
37,006
myrmex-org/myrmex
packages/iam/src/cli/create-role.js
executeCommand
function executeCommand(parameters) { const configFilePath = path.join(process.cwd(), plugin.config.rolesPath); return mkdirpAsync(configFilePath) .then(() => { if (parameters.model !== 'none') { // Case a preset config has been choosen const src = path.join(__dirname, 'templates', 'roles', parameters.model + '.json'); const dest = path.join(configFilePath, parameters.identifier + '.json'); return ncpAsync(src, dest); } else { // Case no preset config has been choosen const config = { 'managed-policies': parameters.policies, 'inline-policies': [], 'trust-relationship': { Version: '2012-10-17', Statement: [{ Effect: 'Allow', Principal: { AWS: '*'}, Action: 'sts:AssumeRole' }] } }; // We save the specification in a json file return fs.writeFileAsync(configFilePath + path.sep + parameters.identifier + '.json', JSON.stringify(config, null, 2)); } }) .then(() => { const msg = '\n The IAM role ' + icli.format.info(parameters.identifier) + ' has been created in ' + icli.format.info(configFilePath + path.sep + parameters.identifier + '.json') + '\n'; icli.print(msg); }); }
javascript
function executeCommand(parameters) { const configFilePath = path.join(process.cwd(), plugin.config.rolesPath); return mkdirpAsync(configFilePath) .then(() => { if (parameters.model !== 'none') { // Case a preset config has been choosen const src = path.join(__dirname, 'templates', 'roles', parameters.model + '.json'); const dest = path.join(configFilePath, parameters.identifier + '.json'); return ncpAsync(src, dest); } else { // Case no preset config has been choosen const config = { 'managed-policies': parameters.policies, 'inline-policies': [], 'trust-relationship': { Version: '2012-10-17', Statement: [{ Effect: 'Allow', Principal: { AWS: '*'}, Action: 'sts:AssumeRole' }] } }; // We save the specification in a json file return fs.writeFileAsync(configFilePath + path.sep + parameters.identifier + '.json', JSON.stringify(config, null, 2)); } }) .then(() => { const msg = '\n The IAM role ' + icli.format.info(parameters.identifier) + ' has been created in ' + icli.format.info(configFilePath + path.sep + parameters.identifier + '.json') + '\n'; icli.print(msg); }); }
[ "function", "executeCommand", "(", "parameters", ")", "{", "const", "configFilePath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "plugin", ".", "config", ".", "rolesPath", ")", ";", "return", "mkdirpAsync", "(", "configFilePath", ")", ".", "then", "(", "(", ")", "=>", "{", "if", "(", "parameters", ".", "model", "!==", "'none'", ")", "{", "// Case a preset config has been choosen", "const", "src", "=", "path", ".", "join", "(", "__dirname", ",", "'templates'", ",", "'roles'", ",", "parameters", ".", "model", "+", "'.json'", ")", ";", "const", "dest", "=", "path", ".", "join", "(", "configFilePath", ",", "parameters", ".", "identifier", "+", "'.json'", ")", ";", "return", "ncpAsync", "(", "src", ",", "dest", ")", ";", "}", "else", "{", "// Case no preset config has been choosen", "const", "config", "=", "{", "'managed-policies'", ":", "parameters", ".", "policies", ",", "'inline-policies'", ":", "[", "]", ",", "'trust-relationship'", ":", "{", "Version", ":", "'2012-10-17'", ",", "Statement", ":", "[", "{", "Effect", ":", "'Allow'", ",", "Principal", ":", "{", "AWS", ":", "'*'", "}", ",", "Action", ":", "'sts:AssumeRole'", "}", "]", "}", "}", ";", "// We save the specification in a json file", "return", "fs", ".", "writeFileAsync", "(", "configFilePath", "+", "path", ".", "sep", "+", "parameters", ".", "identifier", "+", "'.json'", ",", "JSON", ".", "stringify", "(", "config", ",", "null", ",", "2", ")", ")", ";", "}", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "const", "msg", "=", "'\\n The IAM role '", "+", "icli", ".", "format", ".", "info", "(", "parameters", ".", "identifier", ")", "+", "' has been created in '", "+", "icli", ".", "format", ".", "info", "(", "configFilePath", "+", "path", ".", "sep", "+", "parameters", ".", "identifier", "+", "'.json'", ")", "+", "'\\n'", ";", "icli", ".", "print", "(", "msg", ")", ";", "}", ")", ";", "}" ]
Create the new role @param {Object} parameters - the parameters provided in the command and in the prompt @returns {Promise<null>} - The execution stops here
[ "Create", "the", "new", "role" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/iam/src/cli/create-role.js#L105-L137
37,007
helion3/lodash-addons
src/getFunction.js
getFunction
function getFunction(value, replacement) { return baseGetType(_.isFunction, _.noop, value, replacement); }
javascript
function getFunction(value, replacement) { return baseGetType(_.isFunction, _.noop, value, replacement); }
[ "function", "getFunction", "(", "value", ",", "replacement", ")", "{", "return", "baseGetType", "(", "_", ".", "isFunction", ",", "_", ".", "noop", ",", "value", ",", "replacement", ")", ";", "}" ]
Returns value if a function, otherwise a default function. @static @memberOf _ @category Lang @param {mixed} value Source value @param {number} replacement Custom default if value is invalid type. @return {number} Final function. @example _.getFunction(null); // => function () {}
[ "Returns", "value", "if", "a", "function", "otherwise", "a", "default", "function", "." ]
83b5bf14258241e7ae35eef346151a332fdb6f50
https://github.com/helion3/lodash-addons/blob/83b5bf14258241e7ae35eef346151a332fdb6f50/src/getFunction.js#L18-L20
37,008
scrapjs/browser-window
index.js
browser
function browser (winOptions) { winOptions = assign({ graceful: true }, winOptions) // Handle `browser-window` being passed as `parent`. if (winOptions.parent && winOptions.parent._native) { winOptions.parent = winOptions.parent._native } if (winOptions.graceful) winOptions.show = false // Create `BrowserWindow` backend. const window = new BrowserWindow(winOptions) if (winOptions.graceful) window.on('ready-to-show', function () { window.show() }) // Method for loading urls or data. function load (source, options, callback = noop) { if (typeof options === 'function') callback = options, options = {} options = assign({type: null, encoding: 'base64'}, options) // Callback handler var contents = window.webContents eventcb(contents, 'did-finish-load', 'did-fail-load', callback) // Load source as data: if (options.type) { const data = Buffer.from(source).toString(options.encoding) return window.loadURL(`data:${options.type};${options.encoding},${data}`, options) } // Load source as URL: const protocol = url.parse(source).protocol if (!protocol) source = 'file://' + source return window.loadURL(source, options) } // Send IPC messages function send (...args) { return window.webContents.send(...args) } // Create a child window function subwindow (options) { return browser(assign({ parent: window }, options)) } // Return methods return {load, send, subwindow, native: window} }
javascript
function browser (winOptions) { winOptions = assign({ graceful: true }, winOptions) // Handle `browser-window` being passed as `parent`. if (winOptions.parent && winOptions.parent._native) { winOptions.parent = winOptions.parent._native } if (winOptions.graceful) winOptions.show = false // Create `BrowserWindow` backend. const window = new BrowserWindow(winOptions) if (winOptions.graceful) window.on('ready-to-show', function () { window.show() }) // Method for loading urls or data. function load (source, options, callback = noop) { if (typeof options === 'function') callback = options, options = {} options = assign({type: null, encoding: 'base64'}, options) // Callback handler var contents = window.webContents eventcb(contents, 'did-finish-load', 'did-fail-load', callback) // Load source as data: if (options.type) { const data = Buffer.from(source).toString(options.encoding) return window.loadURL(`data:${options.type};${options.encoding},${data}`, options) } // Load source as URL: const protocol = url.parse(source).protocol if (!protocol) source = 'file://' + source return window.loadURL(source, options) } // Send IPC messages function send (...args) { return window.webContents.send(...args) } // Create a child window function subwindow (options) { return browser(assign({ parent: window }, options)) } // Return methods return {load, send, subwindow, native: window} }
[ "function", "browser", "(", "winOptions", ")", "{", "winOptions", "=", "assign", "(", "{", "graceful", ":", "true", "}", ",", "winOptions", ")", "// Handle `browser-window` being passed as `parent`.", "if", "(", "winOptions", ".", "parent", "&&", "winOptions", ".", "parent", ".", "_native", ")", "{", "winOptions", ".", "parent", "=", "winOptions", ".", "parent", ".", "_native", "}", "if", "(", "winOptions", ".", "graceful", ")", "winOptions", ".", "show", "=", "false", "// Create `BrowserWindow` backend.", "const", "window", "=", "new", "BrowserWindow", "(", "winOptions", ")", "if", "(", "winOptions", ".", "graceful", ")", "window", ".", "on", "(", "'ready-to-show'", ",", "function", "(", ")", "{", "window", ".", "show", "(", ")", "}", ")", "// Method for loading urls or data.", "function", "load", "(", "source", ",", "options", ",", "callback", "=", "noop", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "callback", "=", "options", ",", "options", "=", "{", "}", "options", "=", "assign", "(", "{", "type", ":", "null", ",", "encoding", ":", "'base64'", "}", ",", "options", ")", "// Callback handler", "var", "contents", "=", "window", ".", "webContents", "eventcb", "(", "contents", ",", "'did-finish-load'", ",", "'did-fail-load'", ",", "callback", ")", "// Load source as data:", "if", "(", "options", ".", "type", ")", "{", "const", "data", "=", "Buffer", ".", "from", "(", "source", ")", ".", "toString", "(", "options", ".", "encoding", ")", "return", "window", ".", "loadURL", "(", "`", "${", "options", ".", "type", "}", "${", "options", ".", "encoding", "}", "${", "data", "}", "`", ",", "options", ")", "}", "// Load source as URL:", "const", "protocol", "=", "url", ".", "parse", "(", "source", ")", ".", "protocol", "if", "(", "!", "protocol", ")", "source", "=", "'file://'", "+", "source", "return", "window", ".", "loadURL", "(", "source", ",", "options", ")", "}", "// Send IPC messages", "function", "send", "(", "...", "args", ")", "{", "return", "window", ".", "webContents", ".", "send", "(", "...", "args", ")", "}", "// Create a child window", "function", "subwindow", "(", "options", ")", "{", "return", "browser", "(", "assign", "(", "{", "parent", ":", "window", "}", ",", "options", ")", ")", "}", "// Return methods", "return", "{", "load", ",", "send", ",", "subwindow", ",", "native", ":", "window", "}", "}" ]
Custom browser window object
[ "Custom", "browser", "window", "object" ]
4dce6f56c33368b25371b8ecabde0e5f6027d72a
https://github.com/scrapjs/browser-window/blob/4dce6f56c33368b25371b8ecabde0e5f6027d72a/index.js#L20-L68
37,009
scrapjs/browser-window
index.js
load
function load (source, options, callback = noop) { if (typeof options === 'function') callback = options, options = {} options = assign({type: null, encoding: 'base64'}, options) // Callback handler var contents = window.webContents eventcb(contents, 'did-finish-load', 'did-fail-load', callback) // Load source as data: if (options.type) { const data = Buffer.from(source).toString(options.encoding) return window.loadURL(`data:${options.type};${options.encoding},${data}`, options) } // Load source as URL: const protocol = url.parse(source).protocol if (!protocol) source = 'file://' + source return window.loadURL(source, options) }
javascript
function load (source, options, callback = noop) { if (typeof options === 'function') callback = options, options = {} options = assign({type: null, encoding: 'base64'}, options) // Callback handler var contents = window.webContents eventcb(contents, 'did-finish-load', 'did-fail-load', callback) // Load source as data: if (options.type) { const data = Buffer.from(source).toString(options.encoding) return window.loadURL(`data:${options.type};${options.encoding},${data}`, options) } // Load source as URL: const protocol = url.parse(source).protocol if (!protocol) source = 'file://' + source return window.loadURL(source, options) }
[ "function", "load", "(", "source", ",", "options", ",", "callback", "=", "noop", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "callback", "=", "options", ",", "options", "=", "{", "}", "options", "=", "assign", "(", "{", "type", ":", "null", ",", "encoding", ":", "'base64'", "}", ",", "options", ")", "// Callback handler", "var", "contents", "=", "window", ".", "webContents", "eventcb", "(", "contents", ",", "'did-finish-load'", ",", "'did-fail-load'", ",", "callback", ")", "// Load source as data:", "if", "(", "options", ".", "type", ")", "{", "const", "data", "=", "Buffer", ".", "from", "(", "source", ")", ".", "toString", "(", "options", ".", "encoding", ")", "return", "window", ".", "loadURL", "(", "`", "${", "options", ".", "type", "}", "${", "options", ".", "encoding", "}", "${", "data", "}", "`", ",", "options", ")", "}", "// Load source as URL:", "const", "protocol", "=", "url", ".", "parse", "(", "source", ")", ".", "protocol", "if", "(", "!", "protocol", ")", "source", "=", "'file://'", "+", "source", "return", "window", ".", "loadURL", "(", "source", ",", "options", ")", "}" ]
Method for loading urls or data.
[ "Method", "for", "loading", "urls", "or", "data", "." ]
4dce6f56c33368b25371b8ecabde0e5f6027d72a
https://github.com/scrapjs/browser-window/blob/4dce6f56c33368b25371b8ecabde0e5f6027d72a/index.js#L36-L54
37,010
myrmex-org/myrmex
packages/lambda/src/index.js
loadLambdas
function loadLambdas() { const lambdasPath = path.join(process.cwd(), plugin.config.lambdasPath); // This event allows to inject code before loading all APIs return plugin.myrmex.fire('beforeLambdasLoad') .then(() => { // Retrieve configuration path of all Lambdas return Promise.promisify(fs.readdir)(lambdasPath); }) .then((subdirs) => { // Load all Lambdas configurations const lambdaPromises = []; _.forEach(subdirs, (subdir) => { const lambdaPath = path.join(lambdasPath, subdir); // subdir is the identifier of the Lambda, so we pass it as the second argument lambdaPromises.push(loadLambda(lambdaPath, subdir)); }); return Promise.all(lambdaPromises); }) .then((lambdas) => { // This event allows to inject code to add or delete or alter lambda configurations return plugin.myrmex.fire('afterLambdasLoad', lambdas); }) .spread((lambdas) => { return Promise.resolve(lambdas); }) .catch(e => { // In case the project does not have any Lambda yet, an exception will be thrown // We silently ignore it if (e.code === 'ENOENT' && path.basename(e.path) === 'lambdas') { return Promise.resolve([]); } return Promise.reject(e); }); }
javascript
function loadLambdas() { const lambdasPath = path.join(process.cwd(), plugin.config.lambdasPath); // This event allows to inject code before loading all APIs return plugin.myrmex.fire('beforeLambdasLoad') .then(() => { // Retrieve configuration path of all Lambdas return Promise.promisify(fs.readdir)(lambdasPath); }) .then((subdirs) => { // Load all Lambdas configurations const lambdaPromises = []; _.forEach(subdirs, (subdir) => { const lambdaPath = path.join(lambdasPath, subdir); // subdir is the identifier of the Lambda, so we pass it as the second argument lambdaPromises.push(loadLambda(lambdaPath, subdir)); }); return Promise.all(lambdaPromises); }) .then((lambdas) => { // This event allows to inject code to add or delete or alter lambda configurations return plugin.myrmex.fire('afterLambdasLoad', lambdas); }) .spread((lambdas) => { return Promise.resolve(lambdas); }) .catch(e => { // In case the project does not have any Lambda yet, an exception will be thrown // We silently ignore it if (e.code === 'ENOENT' && path.basename(e.path) === 'lambdas') { return Promise.resolve([]); } return Promise.reject(e); }); }
[ "function", "loadLambdas", "(", ")", "{", "const", "lambdasPath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "plugin", ".", "config", ".", "lambdasPath", ")", ";", "// This event allows to inject code before loading all APIs", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'beforeLambdasLoad'", ")", ".", "then", "(", "(", ")", "=>", "{", "// Retrieve configuration path of all Lambdas", "return", "Promise", ".", "promisify", "(", "fs", ".", "readdir", ")", "(", "lambdasPath", ")", ";", "}", ")", ".", "then", "(", "(", "subdirs", ")", "=>", "{", "// Load all Lambdas configurations", "const", "lambdaPromises", "=", "[", "]", ";", "_", ".", "forEach", "(", "subdirs", ",", "(", "subdir", ")", "=>", "{", "const", "lambdaPath", "=", "path", ".", "join", "(", "lambdasPath", ",", "subdir", ")", ";", "// subdir is the identifier of the Lambda, so we pass it as the second argument", "lambdaPromises", ".", "push", "(", "loadLambda", "(", "lambdaPath", ",", "subdir", ")", ")", ";", "}", ")", ";", "return", "Promise", ".", "all", "(", "lambdaPromises", ")", ";", "}", ")", ".", "then", "(", "(", "lambdas", ")", "=>", "{", "// This event allows to inject code to add or delete or alter lambda configurations", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'afterLambdasLoad'", ",", "lambdas", ")", ";", "}", ")", ".", "spread", "(", "(", "lambdas", ")", "=>", "{", "return", "Promise", ".", "resolve", "(", "lambdas", ")", ";", "}", ")", ".", "catch", "(", "e", "=>", "{", "// In case the project does not have any Lambda yet, an exception will be thrown", "// We silently ignore it", "if", "(", "e", ".", "code", "===", "'ENOENT'", "&&", "path", ".", "basename", "(", "e", ".", "path", ")", "===", "'lambdas'", ")", "{", "return", "Promise", ".", "resolve", "(", "[", "]", ")", ";", "}", "return", "Promise", ".", "reject", "(", "e", ")", ";", "}", ")", ";", "}" ]
Load all lambda configurations @return {Promise<[Lambda]>} - promise of an array of lambdas
[ "Load", "all", "lambda", "configurations" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/lambda/src/index.js#L13-L47
37,011
myrmex-org/myrmex
packages/lambda/src/index.js
loadLambda
function loadLambda(lambdaPath, identifier) { return plugin.myrmex.fire('beforeLambdaLoad', lambdaPath, identifier) .spread((lambdaPath, identifier) => { // Because we use require() to get the config, it could either be a JSON file // or the content exported by a node module // But because require() caches the content it loads, we clone the result to avoid bugs // if the function is called twice. const lambdaConfig = _.cloneDeep(require(path.join(lambdaPath, 'config'))); // If the identifier is not specified, it will be the name of the directory that contains the config lambdaConfig.identifier = lambdaConfig.identifier || identifier; // Lasy loading because the plugin has to be registered in a Myrmex instance before requiring ./lambda const Lambda = require('./lambda'); const lambda = new Lambda(lambdaConfig, lambdaPath); // This event allows to inject code to alter the Lambda configuration return plugin.myrmex.fire('afterLambdaLoad', lambda); }) .spread((lambda) => { return Promise.resolve(lambda); }); }
javascript
function loadLambda(lambdaPath, identifier) { return plugin.myrmex.fire('beforeLambdaLoad', lambdaPath, identifier) .spread((lambdaPath, identifier) => { // Because we use require() to get the config, it could either be a JSON file // or the content exported by a node module // But because require() caches the content it loads, we clone the result to avoid bugs // if the function is called twice. const lambdaConfig = _.cloneDeep(require(path.join(lambdaPath, 'config'))); // If the identifier is not specified, it will be the name of the directory that contains the config lambdaConfig.identifier = lambdaConfig.identifier || identifier; // Lasy loading because the plugin has to be registered in a Myrmex instance before requiring ./lambda const Lambda = require('./lambda'); const lambda = new Lambda(lambdaConfig, lambdaPath); // This event allows to inject code to alter the Lambda configuration return plugin.myrmex.fire('afterLambdaLoad', lambda); }) .spread((lambda) => { return Promise.resolve(lambda); }); }
[ "function", "loadLambda", "(", "lambdaPath", ",", "identifier", ")", "{", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'beforeLambdaLoad'", ",", "lambdaPath", ",", "identifier", ")", ".", "spread", "(", "(", "lambdaPath", ",", "identifier", ")", "=>", "{", "// Because we use require() to get the config, it could either be a JSON file", "// or the content exported by a node module", "// But because require() caches the content it loads, we clone the result to avoid bugs", "// if the function is called twice.", "const", "lambdaConfig", "=", "_", ".", "cloneDeep", "(", "require", "(", "path", ".", "join", "(", "lambdaPath", ",", "'config'", ")", ")", ")", ";", "// If the identifier is not specified, it will be the name of the directory that contains the config", "lambdaConfig", ".", "identifier", "=", "lambdaConfig", ".", "identifier", "||", "identifier", ";", "// Lasy loading because the plugin has to be registered in a Myrmex instance before requiring ./lambda", "const", "Lambda", "=", "require", "(", "'./lambda'", ")", ";", "const", "lambda", "=", "new", "Lambda", "(", "lambdaConfig", ",", "lambdaPath", ")", ";", "// This event allows to inject code to alter the Lambda configuration", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'afterLambdaLoad'", ",", "lambda", ")", ";", "}", ")", ".", "spread", "(", "(", "lambda", ")", "=>", "{", "return", "Promise", ".", "resolve", "(", "lambda", ")", ";", "}", ")", ";", "}" ]
Load a lambda @param {string} lambdaPath - path to the Lambda module @param {string} identifier - the lambda identifier @returns {Promise<Lambda>} - the promise of a lambda
[ "Load", "a", "lambda" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/lambda/src/index.js#L55-L77
37,012
myrmex-org/myrmex
packages/lambda/src/index.js
loadNodeModule
function loadNodeModule(nodeModulePath, name) { return plugin.myrmex.fire('beforeNodeModuleLoad', nodeModulePath, name) .spread((nodeModulePath, name) => { let packageJson = {}; try { packageJson = _.cloneDeep(require(path.join(nodeModulePath, 'package.json'))); } catch (e) { if (e.code !== 'MODULE_NOT_FOUND') { throw e; } } // Lasy loading because the plugin has to be registered in a Myrmex instance before requiring ./node-module const NodeModule = require('./node-module'); const nodePackage = new NodeModule(packageJson, name, nodeModulePath); // This event allows to inject code to alter the Lambda configuration return plugin.myrmex.fire('afterNodeModuleLoad', nodePackage); }) .spread(nodePackage => { return Promise.resolve(nodePackage); }); }
javascript
function loadNodeModule(nodeModulePath, name) { return plugin.myrmex.fire('beforeNodeModuleLoad', nodeModulePath, name) .spread((nodeModulePath, name) => { let packageJson = {}; try { packageJson = _.cloneDeep(require(path.join(nodeModulePath, 'package.json'))); } catch (e) { if (e.code !== 'MODULE_NOT_FOUND') { throw e; } } // Lasy loading because the plugin has to be registered in a Myrmex instance before requiring ./node-module const NodeModule = require('./node-module'); const nodePackage = new NodeModule(packageJson, name, nodeModulePath); // This event allows to inject code to alter the Lambda configuration return plugin.myrmex.fire('afterNodeModuleLoad', nodePackage); }) .spread(nodePackage => { return Promise.resolve(nodePackage); }); }
[ "function", "loadNodeModule", "(", "nodeModulePath", ",", "name", ")", "{", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'beforeNodeModuleLoad'", ",", "nodeModulePath", ",", "name", ")", ".", "spread", "(", "(", "nodeModulePath", ",", "name", ")", "=>", "{", "let", "packageJson", "=", "{", "}", ";", "try", "{", "packageJson", "=", "_", ".", "cloneDeep", "(", "require", "(", "path", ".", "join", "(", "nodeModulePath", ",", "'package.json'", ")", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "e", ".", "code", "!==", "'MODULE_NOT_FOUND'", ")", "{", "throw", "e", ";", "}", "}", "// Lasy loading because the plugin has to be registered in a Myrmex instance before requiring ./node-module", "const", "NodeModule", "=", "require", "(", "'./node-module'", ")", ";", "const", "nodePackage", "=", "new", "NodeModule", "(", "packageJson", ",", "name", ",", "nodeModulePath", ")", ";", "// This event allows to inject code to alter the Lambda configuration", "return", "plugin", ".", "myrmex", ".", "fire", "(", "'afterNodeModuleLoad'", ",", "nodePackage", ")", ";", "}", ")", ".", "spread", "(", "nodePackage", "=>", "{", "return", "Promise", ".", "resolve", "(", "nodePackage", ")", ";", "}", ")", ";", "}" ]
Load a NodeModule object @param {string} packageJsonPath - path to the package.json file of the package @param {string} name - name of the package @return {Promise<NodeModule>} - promise of a node packages
[ "Load", "a", "NodeModule", "object" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/lambda/src/index.js#L124-L146
37,013
myrmex-org/myrmex
packages/lambda/src/index.js
findLambda
function findLambda(identifier) { return loadLambdas() .then(lambdas => { const lambda = _.find(lambdas, (lambda) => { return lambda.getIdentifier() === identifier; }); if (!lambda) { throw new Error('The Lambda "' + identifier + '" does not exists in this Myrmex project'); } return lambda; }); }
javascript
function findLambda(identifier) { return loadLambdas() .then(lambdas => { const lambda = _.find(lambdas, (lambda) => { return lambda.getIdentifier() === identifier; }); if (!lambda) { throw new Error('The Lambda "' + identifier + '" does not exists in this Myrmex project'); } return lambda; }); }
[ "function", "findLambda", "(", "identifier", ")", "{", "return", "loadLambdas", "(", ")", ".", "then", "(", "lambdas", "=>", "{", "const", "lambda", "=", "_", ".", "find", "(", "lambdas", ",", "(", "lambda", ")", "=>", "{", "return", "lambda", ".", "getIdentifier", "(", ")", "===", "identifier", ";", "}", ")", ";", "if", "(", "!", "lambda", ")", "{", "throw", "new", "Error", "(", "'The Lambda \"'", "+", "identifier", "+", "'\" does not exists in this Myrmex project'", ")", ";", "}", "return", "lambda", ";", "}", ")", ";", "}" ]
Find an Lambda by its identifier @param {string} name - the name of the Lambda @returns {Array}
[ "Find", "an", "Lambda", "by", "its", "identifier" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/lambda/src/index.js#L153-L162
37,014
myrmex-org/myrmex
packages/lambda/src/index.js
findNodeModule
function findNodeModule(name) { return loadModules() .then(nodeModules => { const nodeModule = _.find(nodeModules, (nodeModule) => { return nodeModule.getName() === name; }); if (!nodeModule) { throw new Error('The node module "' + name + '" does not exists in this Myrmex project'); } return nodeModule; }); }
javascript
function findNodeModule(name) { return loadModules() .then(nodeModules => { const nodeModule = _.find(nodeModules, (nodeModule) => { return nodeModule.getName() === name; }); if (!nodeModule) { throw new Error('The node module "' + name + '" does not exists in this Myrmex project'); } return nodeModule; }); }
[ "function", "findNodeModule", "(", "name", ")", "{", "return", "loadModules", "(", ")", ".", "then", "(", "nodeModules", "=>", "{", "const", "nodeModule", "=", "_", ".", "find", "(", "nodeModules", ",", "(", "nodeModule", ")", "=>", "{", "return", "nodeModule", ".", "getName", "(", ")", "===", "name", ";", "}", ")", ";", "if", "(", "!", "nodeModule", ")", "{", "throw", "new", "Error", "(", "'The node module \"'", "+", "name", "+", "'\" does not exists in this Myrmex project'", ")", ";", "}", "return", "nodeModule", ";", "}", ")", ";", "}" ]
Find an node package by its identifier @param {string} name - the name of the node package @returns {Array}
[ "Find", "an", "node", "package", "by", "its", "identifier" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/lambda/src/index.js#L169-L178
37,015
myrmex-org/myrmex
packages/lambda/src/index.js
registerCommandsHook
function registerCommandsHook(icli) { return Promise.all([ require('./cli/create-lambda')(icli), require('./cli/create-node-module')(icli), require('./cli/deploy-lambdas')(icli), require('./cli/install-lambdas-locally')(icli), require('./cli/test-lambda-locally')(icli), require('./cli/test-lambda')(icli) ]); }
javascript
function registerCommandsHook(icli) { return Promise.all([ require('./cli/create-lambda')(icli), require('./cli/create-node-module')(icli), require('./cli/deploy-lambdas')(icli), require('./cli/install-lambdas-locally')(icli), require('./cli/test-lambda-locally')(icli), require('./cli/test-lambda')(icli) ]); }
[ "function", "registerCommandsHook", "(", "icli", ")", "{", "return", "Promise", ".", "all", "(", "[", "require", "(", "'./cli/create-lambda'", ")", "(", "icli", ")", ",", "require", "(", "'./cli/create-node-module'", ")", "(", "icli", ")", ",", "require", "(", "'./cli/deploy-lambdas'", ")", "(", "icli", ")", ",", "require", "(", "'./cli/install-lambdas-locally'", ")", "(", "icli", ")", ",", "require", "(", "'./cli/test-lambda-locally'", ")", "(", "icli", ")", ",", "require", "(", "'./cli/test-lambda'", ")", "(", "icli", ")", "]", ")", ";", "}" ]
Register plugin commands @returns {Promise} - a promise that resolves when all commands are registered
[ "Register", "plugin", "commands" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/lambda/src/index.js#L203-L212
37,016
myrmex-org/myrmex
packages/lambda/src/index.js
loadIntegrationsHook
function loadIntegrationsHook(region, context, endpoints, integrationResults) { return require('./hooks/load-integration').hook(region, context, endpoints, integrationResults); }
javascript
function loadIntegrationsHook(region, context, endpoints, integrationResults) { return require('./hooks/load-integration').hook(region, context, endpoints, integrationResults); }
[ "function", "loadIntegrationsHook", "(", "region", ",", "context", ",", "endpoints", ",", "integrationResults", ")", "{", "return", "require", "(", "'./hooks/load-integration'", ")", ".", "hook", "(", "region", ",", "context", ",", "endpoints", ",", "integrationResults", ")", ";", "}" ]
This hook perform the deployment of lambdas in AWS and return integration data that will be used to configure the related endpoints @param {string} region - the AWS region where we doing the deployment @param {Object} endpoints - the list of endpoints that will be deployed @param {Array} context - a object containing the stage and the environment @param {Array} integrationResults - the collection of integration results we will add our own integrations results to this array @returns {Promise<Array>}
[ "This", "hook", "perform", "the", "deployment", "of", "lambdas", "in", "AWS", "and", "return", "integration", "data", "that", "will", "be", "used", "to", "configure", "the", "related", "endpoints" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/lambda/src/index.js#L234-L236
37,017
glayzzle/grafine
src/graph.js
function (hash, capacity) { if (!hash) hash = 255; if (!capacity) capacity = hash * 4; this._hash = hash; this._capacity = capacity; this._nextId = 0; this._shards = []; this._indexes = []; }
javascript
function (hash, capacity) { if (!hash) hash = 255; if (!capacity) capacity = hash * 4; this._hash = hash; this._capacity = capacity; this._nextId = 0; this._shards = []; this._indexes = []; }
[ "function", "(", "hash", ",", "capacity", ")", "{", "if", "(", "!", "hash", ")", "hash", "=", "255", ";", "if", "(", "!", "capacity", ")", "capacity", "=", "hash", "*", "4", ";", "this", ".", "_hash", "=", "hash", ";", "this", ".", "_capacity", "=", "capacity", ";", "this", ".", "_nextId", "=", "0", ";", "this", ".", "_shards", "=", "[", "]", ";", "this", ".", "_indexes", "=", "[", "]", ";", "}" ]
Initialize a storage @constructor Graph
[ "Initialize", "a", "storage" ]
616ff0a57806d6b809b69e81f3e5ff77919fc3cd
https://github.com/glayzzle/grafine/blob/616ff0a57806d6b809b69e81f3e5ff77919fc3cd/src/graph.js#L14-L22
37,018
jefersondaniel/dom-form-serializer
lib/InputWriters.js
setSelectValue
function setSelectValue (elem, value) { var optionSet, option var options = elem.options var values = makeArray(value) var i = options.length while (i--) { option = options[ i ] /* eslint-disable no-cond-assign */ if (values.indexOf(option.value) > -1) { option.setAttribute('selected', true) optionSet = true } /* eslint-enable no-cond-assign */ } // Force browsers to behave consistently when non-matching value is set if (!optionSet) { elem.selectedIndex = -1 } }
javascript
function setSelectValue (elem, value) { var optionSet, option var options = elem.options var values = makeArray(value) var i = options.length while (i--) { option = options[ i ] /* eslint-disable no-cond-assign */ if (values.indexOf(option.value) > -1) { option.setAttribute('selected', true) optionSet = true } /* eslint-enable no-cond-assign */ } // Force browsers to behave consistently when non-matching value is set if (!optionSet) { elem.selectedIndex = -1 } }
[ "function", "setSelectValue", "(", "elem", ",", "value", ")", "{", "var", "optionSet", ",", "option", "var", "options", "=", "elem", ".", "options", "var", "values", "=", "makeArray", "(", "value", ")", "var", "i", "=", "options", ".", "length", "while", "(", "i", "--", ")", "{", "option", "=", "options", "[", "i", "]", "/* eslint-disable no-cond-assign */", "if", "(", "values", ".", "indexOf", "(", "option", ".", "value", ")", ">", "-", "1", ")", "{", "option", ".", "setAttribute", "(", "'selected'", ",", "true", ")", "optionSet", "=", "true", "}", "/* eslint-enable no-cond-assign */", "}", "// Force browsers to behave consistently when non-matching value is set", "if", "(", "!", "optionSet", ")", "{", "elem", ".", "selectedIndex", "=", "-", "1", "}", "}" ]
Write select values @see {@link https://github.com/jquery/jquery/blob/master/src/attributes/val.js|Github} @param {object} Select element @param {string|array} Select value
[ "Write", "select", "values" ]
97e0ebf0431b87e4a9b98d87b1d2d037d27c8af2
https://github.com/jefersondaniel/dom-form-serializer/blob/97e0ebf0431b87e4a9b98d87b1d2d037d27c8af2/lib/InputWriters.js#L42-L62
37,019
tcr/rem
lib/rem.js
disambiguateInvocation
function disambiguateInvocation() { if (req.body && !req._explicitMime) { req.setHeader('Content-Type', req.body); req.removeHeader('Content-Length'); req.body = null; } }
javascript
function disambiguateInvocation() { if (req.body && !req._explicitMime) { req.setHeader('Content-Type', req.body); req.removeHeader('Content-Length'); req.body = null; } }
[ "function", "disambiguateInvocation", "(", ")", "{", "if", "(", "req", ".", "body", "&&", "!", "req", ".", "_explicitMime", ")", "{", "req", ".", "setHeader", "(", "'Content-Type'", ",", "req", ".", "body", ")", ";", "req", ".", "removeHeader", "(", "'Content-Length'", ")", ";", "req", ".", "body", "=", "null", ";", "}", "}" ]
Disambiguate between MIME type and string body in route invocation.
[ "Disambiguate", "between", "MIME", "type", "and", "string", "body", "in", "route", "invocation", "." ]
992775542608f2de148f6560c248a65a217d6422
https://github.com/tcr/rem/blob/992775542608f2de148f6560c248a65a217d6422/lib/rem.js#L1695-L1701
37,020
greedbell/gulp-require-modules
path.js
realRequirPath
function realRequirPath(filePath) { // console.log('realRequirPath:filePath: ' + filePath); var jsFilePath = filePath + '.js'; if (fs.existsSync(filePath)) { if (fs.statSync(filePath).isDirectory()) { jsFilePath = filePath + '.js'; if (fs.existsSync(jsFilePath)) { return jsFilePath; } else { jsFilePath = path.join(filePath, 'index.js'); } // console.log('realRequirPath:jsFilePath: ' + jsFilePath); } else if (fs.statSync(filePath).isFile()) { return filePath; } else { return null; } } else { jsFilePath = filePath + '.js'; // console.log('realRequirPath:filePath: ' + filePath); } if (fs.existsSync(jsFilePath)) { // console.log('realRequirPath:filePath: ' + filePath); return jsFilePath; } else { return null; } }
javascript
function realRequirPath(filePath) { // console.log('realRequirPath:filePath: ' + filePath); var jsFilePath = filePath + '.js'; if (fs.existsSync(filePath)) { if (fs.statSync(filePath).isDirectory()) { jsFilePath = filePath + '.js'; if (fs.existsSync(jsFilePath)) { return jsFilePath; } else { jsFilePath = path.join(filePath, 'index.js'); } // console.log('realRequirPath:jsFilePath: ' + jsFilePath); } else if (fs.statSync(filePath).isFile()) { return filePath; } else { return null; } } else { jsFilePath = filePath + '.js'; // console.log('realRequirPath:filePath: ' + filePath); } if (fs.existsSync(jsFilePath)) { // console.log('realRequirPath:filePath: ' + filePath); return jsFilePath; } else { return null; } }
[ "function", "realRequirPath", "(", "filePath", ")", "{", "// console.log('realRequirPath:filePath: ' + filePath);", "var", "jsFilePath", "=", "filePath", "+", "'.js'", ";", "if", "(", "fs", ".", "existsSync", "(", "filePath", ")", ")", "{", "if", "(", "fs", ".", "statSync", "(", "filePath", ")", ".", "isDirectory", "(", ")", ")", "{", "jsFilePath", "=", "filePath", "+", "'.js'", ";", "if", "(", "fs", ".", "existsSync", "(", "jsFilePath", ")", ")", "{", "return", "jsFilePath", ";", "}", "else", "{", "jsFilePath", "=", "path", ".", "join", "(", "filePath", ",", "'index.js'", ")", ";", "}", "// console.log('realRequirPath:jsFilePath: ' + jsFilePath);", "}", "else", "if", "(", "fs", ".", "statSync", "(", "filePath", ")", ".", "isFile", "(", ")", ")", "{", "return", "filePath", ";", "}", "else", "{", "return", "null", ";", "}", "}", "else", "{", "jsFilePath", "=", "filePath", "+", "'.js'", ";", "// console.log('realRequirPath:filePath: ' + filePath);", "}", "if", "(", "fs", ".", "existsSync", "(", "jsFilePath", ")", ")", "{", "// console.log('realRequirPath:filePath: ' + filePath);", "return", "jsFilePath", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
get real required file path module to module.js or module/index.js @param filePath @returns {*}
[ "get", "real", "required", "file", "path" ]
a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc
https://github.com/greedbell/gulp-require-modules/blob/a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc/path.js#L12-L40
37,021
greedbell/gulp-require-modules
path.js
subModulePath
function subModulePath(subModule, node_modules) { var index = subModule.indexOf("/"); var length = subModule.length; if (index <= 0 || index + 1 == length) { return null; } var module = subModule.substring(0, index); var relative = subModule.substring(index + 1, length); var moduleDirectory = path.join(node_modules, module); var filePath = path.join(moduleDirectory, relative); return realRequirPath(filePath); }
javascript
function subModulePath(subModule, node_modules) { var index = subModule.indexOf("/"); var length = subModule.length; if (index <= 0 || index + 1 == length) { return null; } var module = subModule.substring(0, index); var relative = subModule.substring(index + 1, length); var moduleDirectory = path.join(node_modules, module); var filePath = path.join(moduleDirectory, relative); return realRequirPath(filePath); }
[ "function", "subModulePath", "(", "subModule", ",", "node_modules", ")", "{", "var", "index", "=", "subModule", ".", "indexOf", "(", "\"/\"", ")", ";", "var", "length", "=", "subModule", ".", "length", ";", "if", "(", "index", "<=", "0", "||", "index", "+", "1", "==", "length", ")", "{", "return", "null", ";", "}", "var", "module", "=", "subModule", ".", "substring", "(", "0", ",", "index", ")", ";", "var", "relative", "=", "subModule", ".", "substring", "(", "index", "+", "1", ",", "length", ")", ";", "var", "moduleDirectory", "=", "path", ".", "join", "(", "node_modules", ",", "module", ")", ";", "var", "filePath", "=", "path", ".", "join", "(", "moduleDirectory", ",", "relative", ")", ";", "return", "realRequirPath", "(", "filePath", ")", ";", "}" ]
get the full path of subModule @param subModule subModule @returns {*} /User/XXXX/node_modules/module/relative.js
[ "get", "the", "full", "path", "of", "subModule" ]
a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc
https://github.com/greedbell/gulp-require-modules/blob/a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc/path.js#L48-L60
37,022
greedbell/gulp-require-modules
path.js
modulePath
function modulePath(module, node_modules) { var pkgFile = path.join(node_modules, module, 'package.json'); if (!fs.existsSync(pkgFile)) { return null; } var data = fs.readFileSync(pkgFile, 'utf8'); var pkg = JSON.parse(data); var fileName = pkg.main || 'index.js'; var filePath = path.join(node_modules, module, fileName); return realRequirPath(filePath); }
javascript
function modulePath(module, node_modules) { var pkgFile = path.join(node_modules, module, 'package.json'); if (!fs.existsSync(pkgFile)) { return null; } var data = fs.readFileSync(pkgFile, 'utf8'); var pkg = JSON.parse(data); var fileName = pkg.main || 'index.js'; var filePath = path.join(node_modules, module, fileName); return realRequirPath(filePath); }
[ "function", "modulePath", "(", "module", ",", "node_modules", ")", "{", "var", "pkgFile", "=", "path", ".", "join", "(", "node_modules", ",", "module", ",", "'package.json'", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "pkgFile", ")", ")", "{", "return", "null", ";", "}", "var", "data", "=", "fs", ".", "readFileSync", "(", "pkgFile", ",", "'utf8'", ")", ";", "var", "pkg", "=", "JSON", ".", "parse", "(", "data", ")", ";", "var", "fileName", "=", "pkg", ".", "main", "||", "'index.js'", ";", "var", "filePath", "=", "path", ".", "join", "(", "node_modules", ",", "module", ",", "fileName", ")", ";", "return", "realRequirPath", "(", "filePath", ")", ";", "}" ]
get required module full path @param module module @returns {*} /User/XXXX/node_modules/module/index.js
[ "get", "required", "module", "full", "path" ]
a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc
https://github.com/greedbell/gulp-require-modules/blob/a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc/path.js#L68-L78
37,023
greedbell/gulp-require-modules
path.js
requirePath
function requirePath(fromPath, require) { // console.log('requirePath:fromPath: ' + fromPath); // console.log('requirePath:require: ' + require); if (fromPath === null || fromPath === undefined || require === null || require === undefined) { return null; } var filePath = path.resolve(path.dirname(fromPath), require); return realRequirPath(filePath); }
javascript
function requirePath(fromPath, require) { // console.log('requirePath:fromPath: ' + fromPath); // console.log('requirePath:require: ' + require); if (fromPath === null || fromPath === undefined || require === null || require === undefined) { return null; } var filePath = path.resolve(path.dirname(fromPath), require); return realRequirPath(filePath); }
[ "function", "requirePath", "(", "fromPath", ",", "require", ")", "{", "// console.log('requirePath:fromPath: ' + fromPath);", "// console.log('requirePath:require: ' + require);", "if", "(", "fromPath", "===", "null", "||", "fromPath", "===", "undefined", "||", "require", "===", "null", "||", "require", "===", "undefined", ")", "{", "return", "null", ";", "}", "var", "filePath", "=", "path", ".", "resolve", "(", "path", ".", "dirname", "(", "fromPath", ")", ",", "require", ")", ";", "return", "realRequirPath", "(", "filePath", ")", ";", "}" ]
get required file full path @param fromPath /User/XXXX/node_modules/module/index.js @param require ./require @returns {*} /User/XXXX/node_modules/module/require/index.js
[ "get", "required", "file", "full", "path" ]
a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc
https://github.com/greedbell/gulp-require-modules/blob/a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc/path.js#L87-L96
37,024
greedbell/gulp-require-modules
path.js
targetPath
function targetPath(fromPath, basePath, targetDirectory) { // console.log('targetPath:fromPath: ' + fromPath); // console.log('targetPath:basePath: ' + basePath); // console.log('targetPath:targetDirectory: ' + targetDirectory); var relativePath = path.relative(basePath, fromPath); // console.log('targetPath:relativePath: ' + relativePath); // console.log('targetPath: ' + path.resolve(targetDirectory, relativePath)); return path.resolve(targetDirectory, relativePath); }
javascript
function targetPath(fromPath, basePath, targetDirectory) { // console.log('targetPath:fromPath: ' + fromPath); // console.log('targetPath:basePath: ' + basePath); // console.log('targetPath:targetDirectory: ' + targetDirectory); var relativePath = path.relative(basePath, fromPath); // console.log('targetPath:relativePath: ' + relativePath); // console.log('targetPath: ' + path.resolve(targetDirectory, relativePath)); return path.resolve(targetDirectory, relativePath); }
[ "function", "targetPath", "(", "fromPath", ",", "basePath", ",", "targetDirectory", ")", "{", "// console.log('targetPath:fromPath: ' + fromPath);", "// console.log('targetPath:basePath: ' + basePath);", "// console.log('targetPath:targetDirectory: ' + targetDirectory);", "var", "relativePath", "=", "path", ".", "relative", "(", "basePath", ",", "fromPath", ")", ";", "// console.log('targetPath:relativePath: ' + relativePath);", "// console.log('targetPath: ' + path.resolve(targetDirectory, relativePath));", "return", "path", ".", "resolve", "(", "targetDirectory", ",", "relativePath", ")", ";", "}" ]
full path in targetDirectory @param fromPath /User/XXXX/node_modules/module/index.js @param basePath /User/XXXX/node_modules/ @param targetDirectory /User/XXXX/dist/npm/ @returns {*} /User/XXXX/dist/npm/module/index.js
[ "full", "path", "in", "targetDirectory" ]
a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc
https://github.com/greedbell/gulp-require-modules/blob/a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc/path.js#L105-L113
37,025
greedbell/gulp-require-modules
path.js
relativePath
function relativePath(from, to) { // console.log('relativePath:from: ' + from); // console.log('relativePath:to: ' + to); var relative = path.relative(from, to); if (!relative || relative.length < 1) { return relative; } var first = relative.substr(0, 1); if (first !== '.' && first !== '/') { relative = './' + relative; } // especially used for windows relative = relative.split(path.sep).join('/'); return relative; }
javascript
function relativePath(from, to) { // console.log('relativePath:from: ' + from); // console.log('relativePath:to: ' + to); var relative = path.relative(from, to); if (!relative || relative.length < 1) { return relative; } var first = relative.substr(0, 1); if (first !== '.' && first !== '/') { relative = './' + relative; } // especially used for windows relative = relative.split(path.sep).join('/'); return relative; }
[ "function", "relativePath", "(", "from", ",", "to", ")", "{", "// console.log('relativePath:from: ' + from);", "// console.log('relativePath:to: ' + to);", "var", "relative", "=", "path", ".", "relative", "(", "from", ",", "to", ")", ";", "if", "(", "!", "relative", "||", "relative", ".", "length", "<", "1", ")", "{", "return", "relative", ";", "}", "var", "first", "=", "relative", ".", "substr", "(", "0", ",", "1", ")", ";", "if", "(", "first", "!==", "'.'", "&&", "first", "!==", "'/'", ")", "{", "relative", "=", "'./'", "+", "relative", ";", "}", "// especially used for windows", "relative", "=", "relative", ".", "split", "(", "path", ".", "sep", ")", ".", "join", "(", "'/'", ")", ";", "return", "relative", ";", "}" ]
get relative path @param from @param to @returns {*}
[ "get", "relative", "path" ]
a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc
https://github.com/greedbell/gulp-require-modules/blob/a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc/path.js#L122-L138
37,026
andrey-p/remarkable-classy
index.js
replaceRenderer
function replaceRenderer(md, renderer) { var openMethodName = renderer.fullName + "_open"; replacedMethods[openMethodName] = md.renderer.rules[openMethodName]; md.renderer.rules[openMethodName] = function (tokens, idx) { var classy, result; // first get the result as per the original method we replaced result = replacedMethods[openMethodName].apply(null, arguments).trim(); if (renderer.inline) { classy = getClassyFromInlineElement(tokens, idx, renderer.fullName); } else { classy = getClassyFromBlockElement(tokens, idx, renderer.fullName); } if (classy) { result = result.replace(new RegExp("<" + renderer.pattern), "$& class=\"" + classy.content + "\""); } return result; }; }
javascript
function replaceRenderer(md, renderer) { var openMethodName = renderer.fullName + "_open"; replacedMethods[openMethodName] = md.renderer.rules[openMethodName]; md.renderer.rules[openMethodName] = function (tokens, idx) { var classy, result; // first get the result as per the original method we replaced result = replacedMethods[openMethodName].apply(null, arguments).trim(); if (renderer.inline) { classy = getClassyFromInlineElement(tokens, idx, renderer.fullName); } else { classy = getClassyFromBlockElement(tokens, idx, renderer.fullName); } if (classy) { result = result.replace(new RegExp("<" + renderer.pattern), "$& class=\"" + classy.content + "\""); } return result; }; }
[ "function", "replaceRenderer", "(", "md", ",", "renderer", ")", "{", "var", "openMethodName", "=", "renderer", ".", "fullName", "+", "\"_open\"", ";", "replacedMethods", "[", "openMethodName", "]", "=", "md", ".", "renderer", ".", "rules", "[", "openMethodName", "]", ";", "md", ".", "renderer", ".", "rules", "[", "openMethodName", "]", "=", "function", "(", "tokens", ",", "idx", ")", "{", "var", "classy", ",", "result", ";", "// first get the result as per the original method we replaced", "result", "=", "replacedMethods", "[", "openMethodName", "]", ".", "apply", "(", "null", ",", "arguments", ")", ".", "trim", "(", ")", ";", "if", "(", "renderer", ".", "inline", ")", "{", "classy", "=", "getClassyFromInlineElement", "(", "tokens", ",", "idx", ",", "renderer", ".", "fullName", ")", ";", "}", "else", "{", "classy", "=", "getClassyFromBlockElement", "(", "tokens", ",", "idx", ",", "renderer", ".", "fullName", ")", ";", "}", "if", "(", "classy", ")", "{", "result", "=", "result", ".", "replace", "(", "new", "RegExp", "(", "\"<\"", "+", "renderer", ".", "pattern", ")", ",", "\"$& class=\\\"\"", "+", "classy", ".", "content", "+", "\"\\\"\"", ")", ";", "}", "return", "result", ";", "}", ";", "}" ]
replace all rules that we want to enable classy on
[ "replace", "all", "rules", "that", "we", "want", "to", "enable", "classy", "on" ]
f4517df3d9d8a270c7e1d1d0ca1c13cd4a88bb4a
https://github.com/andrey-p/remarkable-classy/blob/f4517df3d9d8a270c7e1d1d0ca1c13cd4a88bb4a/index.js#L138-L160
37,027
segmentio/ecs-logs-js
lib/index.js
Logger
function Logger(options) { if (!options) { options = { }; } if (typeof options.level === 'undefined') { options.level = 'debug'; } if (!options.transports) { options.transports = [new Transport(options)]; delete options.name; delete options.hostname; delete options.timestamp; delete options.formatter; } Logger.super_.call(this, options); this.setLevels(options.levels || Levels); }
javascript
function Logger(options) { if (!options) { options = { }; } if (typeof options.level === 'undefined') { options.level = 'debug'; } if (!options.transports) { options.transports = [new Transport(options)]; delete options.name; delete options.hostname; delete options.timestamp; delete options.formatter; } Logger.super_.call(this, options); this.setLevels(options.levels || Levels); }
[ "function", "Logger", "(", "options", ")", "{", "if", "(", "!", "options", ")", "{", "options", "=", "{", "}", ";", "}", "if", "(", "typeof", "options", ".", "level", "===", "'undefined'", ")", "{", "options", ".", "level", "=", "'debug'", ";", "}", "if", "(", "!", "options", ".", "transports", ")", "{", "options", ".", "transports", "=", "[", "new", "Transport", "(", "options", ")", "]", ";", "delete", "options", ".", "name", ";", "delete", "options", ".", "hostname", ";", "delete", "options", ".", "timestamp", ";", "delete", "options", ".", "formatter", ";", "}", "Logger", ".", "super_", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "setLevels", "(", "options", ".", "levels", "||", "Levels", ")", ";", "}" ]
The Logger type is a winston logger with preconfigured defaults to output log messages compatible with ecs-logs. @example var ecslogs = require('ecs-logs-js'); var log = new ecslogs.Logger({ level: 'info' }); log.info('Hi there!'); @param {Object} [options] The configuration object for the new logger, besides the properties documented here the options object can also carry all properties that the Transport and Formatter constructors accept, they will be passed to the default transport and formatter instantiated if none was given. @param {string} [level] The minimum level for log messages this logger will pass to its transports, defaults to 'debug' @param {transports} [Object[]] An array of winston transports that the logger will be passing log messages to, defaults to a single instance of Transport.
[ "The", "Logger", "type", "is", "a", "winston", "logger", "with", "preconfigured", "defaults", "to", "output", "log", "messages", "compatible", "with", "ecs", "-", "logs", "." ]
0e089554ac6ff77b9cbebbaae45a40a3a14d7336
https://github.com/segmentio/ecs-logs-js/blob/0e089554ac6ff77b9cbebbaae45a40a3a14d7336/lib/index.js#L55-L74
37,028
segmentio/ecs-logs-js
lib/index.js
Transport
function Transport(options) { if (!options) { options = { }; } this.name = options.name || 'ecs-logs'; this.level = options.level || 'debug'; this.output = options.output || function(s) { process.stdout.write(s + '\n'); }; this.timestamp = options.timestamp || Date.now; this.formatter = options.formatter || new Formatter({ hostname: options.hostname }); }
javascript
function Transport(options) { if (!options) { options = { }; } this.name = options.name || 'ecs-logs'; this.level = options.level || 'debug'; this.output = options.output || function(s) { process.stdout.write(s + '\n'); }; this.timestamp = options.timestamp || Date.now; this.formatter = options.formatter || new Formatter({ hostname: options.hostname }); }
[ "function", "Transport", "(", "options", ")", "{", "if", "(", "!", "options", ")", "{", "options", "=", "{", "}", ";", "}", "this", ".", "name", "=", "options", ".", "name", "||", "'ecs-logs'", ";", "this", ".", "level", "=", "options", ".", "level", "||", "'debug'", ";", "this", ".", "output", "=", "options", ".", "output", "||", "function", "(", "s", ")", "{", "process", ".", "stdout", ".", "write", "(", "s", "+", "'\\n'", ")", ";", "}", ";", "this", ".", "timestamp", "=", "options", ".", "timestamp", "||", "Date", ".", "now", ";", "this", ".", "formatter", "=", "options", ".", "formatter", "||", "new", "Formatter", "(", "{", "hostname", ":", "options", ".", "hostname", "}", ")", ";", "}" ]
The Transport type implements a winston log transport preconfigured to output log messages compatible with ecs-logs. @example var ecslogs = require('ecs-logs-js'); var winston = require('winston'); // Instantiate an ecs-logs compatible winston logger with ecslogs.Transport var logger = new winston.Logger({ transports: [ new ecslogs.Transport() ] }); @param {Object} [options] The configuration object for the new transport, besides the properties documented here the options object can also carry all properties that the Formatter constructor accepts, they will be passed to the default formatter instantiated if none was given. @param {string} [options.name] The transport name, defaults to 'ecs-logs' @param {string} [options.level] The transport level, defaults to 'debug' messages, this is passed to the default formatter if none was provided @param {function} [options.output] A function called when the transport has a log message to send, defaults to writing to stdout. @param {function} [options.timestamp] A function returning timestamps, defaults to Date.now @param {Object} [options.formatter] A winston formatter, defaults to an instance of Formatter
[ "The", "Transport", "type", "implements", "a", "winston", "log", "transport", "preconfigured", "to", "output", "log", "messages", "compatible", "with", "ecs", "-", "logs", "." ]
0e089554ac6ff77b9cbebbaae45a40a3a14d7336
https://github.com/segmentio/ecs-logs-js/blob/0e089554ac6ff77b9cbebbaae45a40a3a14d7336/lib/index.js#L112-L126
37,029
segmentio/ecs-logs-js
lib/index.js
Formatter
function Formatter(options) { function format(entry) { // eslint-disable-line return stringify(makeEvent(entry, format.hostname)); } if (!options) { options = { }; } Object.setPrototypeOf(format, Formatter.prototype); format.hostname = options.hostname || os.hostname(); return format; }
javascript
function Formatter(options) { function format(entry) { // eslint-disable-line return stringify(makeEvent(entry, format.hostname)); } if (!options) { options = { }; } Object.setPrototypeOf(format, Formatter.prototype); format.hostname = options.hostname || os.hostname(); return format; }
[ "function", "Formatter", "(", "options", ")", "{", "function", "format", "(", "entry", ")", "{", "// eslint-disable-line", "return", "stringify", "(", "makeEvent", "(", "entry", ",", "format", ".", "hostname", ")", ")", ";", "}", "if", "(", "!", "options", ")", "{", "options", "=", "{", "}", ";", "}", "Object", ".", "setPrototypeOf", "(", "format", ",", "Formatter", ".", "prototype", ")", ";", "format", ".", "hostname", "=", "options", ".", "hostname", "||", "os", ".", "hostname", "(", ")", ";", "return", "format", ";", "}" ]
The Formatter type implements a winston log formatter that produces messages compatible with ecs-logs. The object returned when instantiating the Formatter type is callable. When called, it expects a log entry object. @example var ecslogs = require('ecs-logs-js'); var winston = require('winston'); // Instantiate an ecs-logs compatible winston logger with ecslogs.Formatter var logger = new winston.Logger({ transports: [ new winston.transports.Console({ timestamp: Date.now, formatter: new ecslogs.Formatter() }) ] }); @example var ecslogs = require('ecs-logs-js'); var formatter = new ecslogs.Formatter(); // Returns a serialized log message compatible with ecs-logs. var s = formatter({ message: 'the log message', level: 'info', meta: { 'User-Agent': 'node' } }); @param {Object} [options] The configuration object for the new formatter @param {string} [options.hostname] The hostname to report in the log messages, defaults to the value returned by os.hostname() @return {string} When a formatter instance is called it accepts a log entry as argument and returns a JSON representation of the entry in a format compatible with ecs-logs
[ "The", "Formatter", "type", "implements", "a", "winston", "log", "formatter", "that", "produces", "messages", "compatible", "with", "ecs", "-", "logs", "." ]
0e089554ac6ff77b9cbebbaae45a40a3a14d7336
https://github.com/segmentio/ecs-logs-js/blob/0e089554ac6ff77b9cbebbaae45a40a3a14d7336/lib/index.js#L184-L196
37,030
segmentio/ecs-logs-js
lib/index.js
makeEvent
function makeEvent(entry, hostname) { var errors = extractErrors(entry.meta); var event = { level: entry.level ? entry.level.toUpperCase() : 'NONE', time: new Date( entry.timestamp ? entry.timestamp() : Date.now() ).toISOString(), info: { }, data: entry.meta || { }, message: entry.message || '' }; if (hostname) { event.info.host = hostname; } if (errors.length) { errors.forEach(function(e, i) { errors[i] = makeEventError(e); }); event.info.errors = errors; } return event; }
javascript
function makeEvent(entry, hostname) { var errors = extractErrors(entry.meta); var event = { level: entry.level ? entry.level.toUpperCase() : 'NONE', time: new Date( entry.timestamp ? entry.timestamp() : Date.now() ).toISOString(), info: { }, data: entry.meta || { }, message: entry.message || '' }; if (hostname) { event.info.host = hostname; } if (errors.length) { errors.forEach(function(e, i) { errors[i] = makeEventError(e); }); event.info.errors = errors; } return event; }
[ "function", "makeEvent", "(", "entry", ",", "hostname", ")", "{", "var", "errors", "=", "extractErrors", "(", "entry", ".", "meta", ")", ";", "var", "event", "=", "{", "level", ":", "entry", ".", "level", "?", "entry", ".", "level", ".", "toUpperCase", "(", ")", ":", "'NONE'", ",", "time", ":", "new", "Date", "(", "entry", ".", "timestamp", "?", "entry", ".", "timestamp", "(", ")", ":", "Date", ".", "now", "(", ")", ")", ".", "toISOString", "(", ")", ",", "info", ":", "{", "}", ",", "data", ":", "entry", ".", "meta", "||", "{", "}", ",", "message", ":", "entry", ".", "message", "||", "''", "}", ";", "if", "(", "hostname", ")", "{", "event", ".", "info", ".", "host", "=", "hostname", ";", "}", "if", "(", "errors", ".", "length", ")", "{", "errors", ".", "forEach", "(", "function", "(", "e", ",", "i", ")", "{", "errors", "[", "i", "]", "=", "makeEventError", "(", "e", ")", ";", "}", ")", ";", "event", ".", "info", ".", "errors", "=", "errors", ";", "}", "return", "event", ";", "}" ]
Given a log entry and an optional hostname the function generates and returns an ecs-logs event. @param {Object} entry A log entry, this is the type of objects received by formatters. @param {string} [hostname] An optional hostname to set on the event. @return {Object} An ecs-logs event generated from the arguments.
[ "Given", "a", "log", "entry", "and", "an", "optional", "hostname", "the", "function", "generates", "and", "returns", "an", "ecs", "-", "logs", "event", "." ]
0e089554ac6ff77b9cbebbaae45a40a3a14d7336
https://github.com/segmentio/ecs-logs-js/blob/0e089554ac6ff77b9cbebbaae45a40a3a14d7336/lib/index.js#L211-L235
37,031
segmentio/ecs-logs-js
lib/index.js
makeEventError
function makeEventError(error) { var stack = error.stack.split('\n'); stack.splice(0, 1); stack.forEach(function(s, i) { stack[i] = s.trim(); }); return { type: typeName(error), error: error.message, stack: stack.filter(function(s) { return s; }) }; }
javascript
function makeEventError(error) { var stack = error.stack.split('\n'); stack.splice(0, 1); stack.forEach(function(s, i) { stack[i] = s.trim(); }); return { type: typeName(error), error: error.message, stack: stack.filter(function(s) { return s; }) }; }
[ "function", "makeEventError", "(", "error", ")", "{", "var", "stack", "=", "error", ".", "stack", ".", "split", "(", "'\\n'", ")", ";", "stack", ".", "splice", "(", "0", ",", "1", ")", ";", "stack", ".", "forEach", "(", "function", "(", "s", ",", "i", ")", "{", "stack", "[", "i", "]", "=", "s", ".", "trim", "(", ")", ";", "}", ")", ";", "return", "{", "type", ":", "typeName", "(", "error", ")", ",", "error", ":", "error", ".", "message", ",", "stack", ":", "stack", ".", "filter", "(", "function", "(", "s", ")", "{", "return", "s", ";", "}", ")", "}", ";", "}" ]
Given an error object, returns an event error as expected in the `info` field of ecs-logs messages. @param {Object} error The error object to convert. @return {Object} An event error object generated from the argument.
[ "Given", "an", "error", "object", "returns", "an", "event", "error", "as", "expected", "in", "the", "info", "field", "of", "ecs", "-", "logs", "messages", "." ]
0e089554ac6ff77b9cbebbaae45a40a3a14d7336
https://github.com/segmentio/ecs-logs-js/blob/0e089554ac6ff77b9cbebbaae45a40a3a14d7336/lib/index.js#L245-L260
37,032
segmentio/ecs-logs-js
lib/index.js
extractErrors
function extractErrors(obj) { if (obj instanceof Error) { return [obj]; } var errors = []; if (obj) { Object.keys(obj).forEach(function(key) { var val = obj[key]; if (val instanceof Error) { errors.push(val); delete obj[key]; } }); } return errors; }
javascript
function extractErrors(obj) { if (obj instanceof Error) { return [obj]; } var errors = []; if (obj) { Object.keys(obj).forEach(function(key) { var val = obj[key]; if (val instanceof Error) { errors.push(val); delete obj[key]; } }); } return errors; }
[ "function", "extractErrors", "(", "obj", ")", "{", "if", "(", "obj", "instanceof", "Error", ")", "{", "return", "[", "obj", "]", ";", "}", "var", "errors", "=", "[", "]", ";", "if", "(", "obj", ")", "{", "Object", ".", "keys", "(", "obj", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "var", "val", "=", "obj", "[", "key", "]", ";", "if", "(", "val", "instanceof", "Error", ")", "{", "errors", ".", "push", "(", "val", ")", ";", "delete", "obj", "[", "key", "]", ";", "}", "}", ")", ";", "}", "return", "errors", ";", "}" ]
Scans the object passed as argument looking for Error values. The values that matched are removed from the object and placed in the array returned by the function. Only the top-level properties of the object are checked, the function doesn't search the object recursively. @param {Object} obj The object to extract errors from. @return {Array} The list of errors extracted from the object.
[ "Scans", "the", "object", "passed", "as", "argument", "looking", "for", "Error", "values", ".", "The", "values", "that", "matched", "are", "removed", "from", "the", "object", "and", "placed", "in", "the", "array", "returned", "by", "the", "function", "." ]
0e089554ac6ff77b9cbebbaae45a40a3a14d7336
https://github.com/segmentio/ecs-logs-js/blob/0e089554ac6ff77b9cbebbaae45a40a3a14d7336/lib/index.js#L274-L292
37,033
jamonserrano/jamon
jamon.js
addRemoveToggleClass
function addRemoveToggleClass (context, className, method) { // Split by spaces, then remove empty elements caused by extra whitespace const classNames = trimAndSplit(className); if (classNames.length) { context.forEach(element => { if (method !== "toggle") { // 'add' and 'remove' accept multiple parameters… element.classList[method](...classNames); } else { // while 'toggle' accepts only one classNames.forEach(className => element.classList.toggle(className)) } }); } return context; }
javascript
function addRemoveToggleClass (context, className, method) { // Split by spaces, then remove empty elements caused by extra whitespace const classNames = trimAndSplit(className); if (classNames.length) { context.forEach(element => { if (method !== "toggle") { // 'add' and 'remove' accept multiple parameters… element.classList[method](...classNames); } else { // while 'toggle' accepts only one classNames.forEach(className => element.classList.toggle(className)) } }); } return context; }
[ "function", "addRemoveToggleClass", "(", "context", ",", "className", ",", "method", ")", "{", "// Split by spaces, then remove empty elements caused by extra whitespace", "const", "classNames", "=", "trimAndSplit", "(", "className", ")", ";", "if", "(", "classNames", ".", "length", ")", "{", "context", ".", "forEach", "(", "element", "=>", "{", "if", "(", "method", "!==", "\"toggle\"", ")", "{", "// 'add' and 'remove' accept multiple parameters…", "element", ".", "classList", "[", "method", "]", "(", "...", "classNames", ")", ";", "}", "else", "{", "// while 'toggle' accepts only one", "classNames", ".", "forEach", "(", "className", "=>", "element", ".", "classList", ".", "toggle", "(", "className", ")", ")", "}", "}", ")", ";", "}", "return", "context", ";", "}" ]
Add, remove, or toggle class names @private @param {Jamon} context - The Jamón instance @param {string} className - Space-separated class names @param {string} method - Method to use on the class name(s) @return {Jamon}
[ "Add", "remove", "or", "toggle", "class", "names" ]
3640aba49009938a35763d0ed2170d3b63f9f6c2
https://github.com/jamonserrano/jamon/blob/3640aba49009938a35763d0ed2170d3b63f9f6c2/jamon.js#L111-L128
37,034
jamonserrano/jamon
jamon.js
getSetRemoveProperty
function getSetRemoveProperty (collection, property, value) { if (isUndefined(value)) { // get property of first element if there is one return collection[0] ? collection[0][property] : undefined; } else if (value !== null) { collection.forEach(element => element[property] = value) } else { collection.forEach(element => delete element[property]) } return collection; }
javascript
function getSetRemoveProperty (collection, property, value) { if (isUndefined(value)) { // get property of first element if there is one return collection[0] ? collection[0][property] : undefined; } else if (value !== null) { collection.forEach(element => element[property] = value) } else { collection.forEach(element => delete element[property]) } return collection; }
[ "function", "getSetRemoveProperty", "(", "collection", ",", "property", ",", "value", ")", "{", "if", "(", "isUndefined", "(", "value", ")", ")", "{", "// get property of first element if there is one", "return", "collection", "[", "0", "]", "?", "collection", "[", "0", "]", "[", "property", "]", ":", "undefined", ";", "}", "else", "if", "(", "value", "!==", "null", ")", "{", "collection", ".", "forEach", "(", "element", "=>", "element", "[", "property", "]", "=", "value", ")", "}", "else", "{", "collection", ".", "forEach", "(", "element", "=>", "delete", "element", "[", "property", "]", ")", "}", "return", "collection", ";", "}" ]
Get, set or remove element properties @private @param {Jamon} collection - The Jamón instance @param {string} property - Property name @param {string|null|undefined} value - Property value (null to remove property) @return {Jamon}
[ "Get", "set", "or", "remove", "element", "properties" ]
3640aba49009938a35763d0ed2170d3b63f9f6c2
https://github.com/jamonserrano/jamon/blob/3640aba49009938a35763d0ed2170d3b63f9f6c2/jamon.js#L138-L149
37,035
jamonserrano/jamon
jamon.js
getDimension
function getDimension (collection, dimension) { const first = collection[0]; if (first && typeof first.getBoundingClientRect === "function") { return first.getBoundingClientRect()[dimension]; } }
javascript
function getDimension (collection, dimension) { const first = collection[0]; if (first && typeof first.getBoundingClientRect === "function") { return first.getBoundingClientRect()[dimension]; } }
[ "function", "getDimension", "(", "collection", ",", "dimension", ")", "{", "const", "first", "=", "collection", "[", "0", "]", ";", "if", "(", "first", "&&", "typeof", "first", ".", "getBoundingClientRect", "===", "\"function\"", ")", "{", "return", "first", ".", "getBoundingClientRect", "(", ")", "[", "dimension", "]", ";", "}", "}" ]
Get the width or height of the first element in the collection @private @param {Jamon} collection - The Jamón instance @param {string} dimension - The dimension to get @return {(number|undefined)} - The result
[ "Get", "the", "width", "or", "height", "of", "the", "first", "element", "in", "the", "collection" ]
3640aba49009938a35763d0ed2170d3b63f9f6c2
https://github.com/jamonserrano/jamon/blob/3640aba49009938a35763d0ed2170d3b63f9f6c2/jamon.js#L158-L163
37,036
jamonserrano/jamon
jamon.js
callNodeMethod
function callNodeMethod(targets, subjects, method, returnTargets) { targets.forEach(target => { const subject = targets.indexOf(target) ? clone(subjects, true) : subjects; if (isIterable(subjects)) { target[method](...subject); } else { target[method](subject); } normalize(target); }); return returnTargets ? targets : subjects; }
javascript
function callNodeMethod(targets, subjects, method, returnTargets) { targets.forEach(target => { const subject = targets.indexOf(target) ? clone(subjects, true) : subjects; if (isIterable(subjects)) { target[method](...subject); } else { target[method](subject); } normalize(target); }); return returnTargets ? targets : subjects; }
[ "function", "callNodeMethod", "(", "targets", ",", "subjects", ",", "method", ",", "returnTargets", ")", "{", "targets", ".", "forEach", "(", "target", "=>", "{", "const", "subject", "=", "targets", ".", "indexOf", "(", "target", ")", "?", "clone", "(", "subjects", ",", "true", ")", ":", "subjects", ";", "if", "(", "isIterable", "(", "subjects", ")", ")", "{", "target", "[", "method", "]", "(", "...", "subject", ")", ";", "}", "else", "{", "target", "[", "method", "]", "(", "subject", ")", ";", "}", "normalize", "(", "target", ")", ";", "}", ")", ";", "return", "returnTargets", "?", "targets", ":", "subjects", ";", "}" ]
Call node methods on multiple targets and with multiple subjects @private @param {Jamon} targets @param {Jamon} subjects @param {string} method - node method to call @param {boolean} returnTargets - return the targets? @return {Jamon} @todo jamonize both targets and subjects if needed
[ "Call", "node", "methods", "on", "multiple", "targets", "and", "with", "multiple", "subjects" ]
3640aba49009938a35763d0ed2170d3b63f9f6c2
https://github.com/jamonserrano/jamon/blob/3640aba49009938a35763d0ed2170d3b63f9f6c2/jamon.js#L175-L189
37,037
jamonserrano/jamon
jamon.js
normalize
function normalize(node, method) { if (method === "prepend" || method === "append") { node.normalize(); } else if (node.parentNode) { node.parentNode.normalize(); } }
javascript
function normalize(node, method) { if (method === "prepend" || method === "append") { node.normalize(); } else if (node.parentNode) { node.parentNode.normalize(); } }
[ "function", "normalize", "(", "node", ",", "method", ")", "{", "if", "(", "method", "===", "\"prepend\"", "||", "method", "===", "\"append\"", ")", "{", "node", ".", "normalize", "(", ")", ";", "}", "else", "if", "(", "node", ".", "parentNode", ")", "{", "node", ".", "parentNode", ".", "normalize", "(", ")", ";", "}", "}" ]
Normalize text nodes @private @param {Node} node @param {string} method - node method that needs normalization
[ "Normalize", "text", "nodes" ]
3640aba49009938a35763d0ed2170d3b63f9f6c2
https://github.com/jamonserrano/jamon/blob/3640aba49009938a35763d0ed2170d3b63f9f6c2/jamon.js#L197-L203
37,038
jamonserrano/jamon
jamon.js
clone
function clone(collection, deep = true) { const clones = new Jamon(); collection.forEach(element => clones.push(element.cloneNode(deep))); return clones; }
javascript
function clone(collection, deep = true) { const clones = new Jamon(); collection.forEach(element => clones.push(element.cloneNode(deep))); return clones; }
[ "function", "clone", "(", "collection", ",", "deep", "=", "true", ")", "{", "const", "clones", "=", "new", "Jamon", "(", ")", ";", "collection", ".", "forEach", "(", "element", "=>", "clones", ".", "push", "(", "element", ".", "cloneNode", "(", "deep", ")", ")", ")", ";", "return", "clones", ";", "}" ]
Clone each element in a collection @private @param {Jamon} collection @param {boolean} [deep=true] - deep clone? @return {Jamon} the cloned collection
[ "Clone", "each", "element", "in", "a", "collection" ]
3640aba49009938a35763d0ed2170d3b63f9f6c2
https://github.com/jamonserrano/jamon/blob/3640aba49009938a35763d0ed2170d3b63f9f6c2/jamon.js#L212-L218
37,039
jamonserrano/jamon
jamon.js
getProxiedListener
function getProxiedListener (listener, selector) { // get existing proxy storage of the listener let proxies = listener[proxyKey]; // the proxy to return let proxy; // or create the storage if (isUndefined(proxies)) { proxies = new Map(); listener[proxyKey] = proxies; } if (proxies.has(selector)) { // a proxy for this selector already exists - get it proxy = proxies.get(selector); } else { // create a new proxy for this selector proxy = function (e) { const target = e.target; // only call the listener if the target matches the selector if (target.matches(selector)) { listener.call(target, e); } } // store proxy proxies.set(selector, proxy); } return proxy; }
javascript
function getProxiedListener (listener, selector) { // get existing proxy storage of the listener let proxies = listener[proxyKey]; // the proxy to return let proxy; // or create the storage if (isUndefined(proxies)) { proxies = new Map(); listener[proxyKey] = proxies; } if (proxies.has(selector)) { // a proxy for this selector already exists - get it proxy = proxies.get(selector); } else { // create a new proxy for this selector proxy = function (e) { const target = e.target; // only call the listener if the target matches the selector if (target.matches(selector)) { listener.call(target, e); } } // store proxy proxies.set(selector, proxy); } return proxy; }
[ "function", "getProxiedListener", "(", "listener", ",", "selector", ")", "{", "// get existing proxy storage of the listener", "let", "proxies", "=", "listener", "[", "proxyKey", "]", ";", "// the proxy to return", "let", "proxy", ";", "// or create the storage", "if", "(", "isUndefined", "(", "proxies", ")", ")", "{", "proxies", "=", "new", "Map", "(", ")", ";", "listener", "[", "proxyKey", "]", "=", "proxies", ";", "}", "if", "(", "proxies", ".", "has", "(", "selector", ")", ")", "{", "// a proxy for this selector already exists - get it", "proxy", "=", "proxies", ".", "get", "(", "selector", ")", ";", "}", "else", "{", "// create a new proxy for this selector", "proxy", "=", "function", "(", "e", ")", "{", "const", "target", "=", "e", ".", "target", ";", "// only call the listener if the target matches the selector", "if", "(", "target", ".", "matches", "(", "selector", ")", ")", "{", "listener", ".", "call", "(", "target", ",", "e", ")", ";", "}", "}", "// store proxy", "proxies", ".", "set", "(", "selector", ",", "proxy", ")", ";", "}", "return", "proxy", ";", "}" ]
Generate a proxy for the given listener-selector combination @private @param {Function} listener - the listener function @param {string} selector - the selector @return {Function} - the listener or the proxy
[ "Generate", "a", "proxy", "for", "the", "given", "listener", "-", "selector", "combination" ]
3640aba49009938a35763d0ed2170d3b63f9f6c2
https://github.com/jamonserrano/jamon/blob/3640aba49009938a35763d0ed2170d3b63f9f6c2/jamon.js#L227-L256
37,040
vorpaljs/vorpal-grep
dist/grep.js
walkDirRecursive
function walkDirRecursive(arr, currentDirPath) { fs.readdirSync(currentDirPath).forEach(function (name) { var filePath = path.join(currentDirPath, name); var stat = fs.statSync(filePath); if (stat.isDirectory()) { arr = walkDirRecursive(arr, filePath); } else { arr.push(filePath); } }); return arr; }
javascript
function walkDirRecursive(arr, currentDirPath) { fs.readdirSync(currentDirPath).forEach(function (name) { var filePath = path.join(currentDirPath, name); var stat = fs.statSync(filePath); if (stat.isDirectory()) { arr = walkDirRecursive(arr, filePath); } else { arr.push(filePath); } }); return arr; }
[ "function", "walkDirRecursive", "(", "arr", ",", "currentDirPath", ")", "{", "fs", ".", "readdirSync", "(", "currentDirPath", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "var", "filePath", "=", "path", ".", "join", "(", "currentDirPath", ",", "name", ")", ";", "var", "stat", "=", "fs", ".", "statSync", "(", "filePath", ")", ";", "if", "(", "stat", ".", "isDirectory", "(", ")", ")", "{", "arr", "=", "walkDirRecursive", "(", "arr", ",", "filePath", ")", ";", "}", "else", "{", "arr", ".", "push", "(", "filePath", ")", ";", "}", "}", ")", ";", "return", "arr", ";", "}" ]
Recursively walks through and executes a callback function for each directory found. @param {String} currentDirPath @param {Function} callback @api private
[ "Recursively", "walks", "through", "and", "executes", "a", "callback", "function", "for", "each", "directory", "found", "." ]
a9f19ceca6099702134f59618e6809d9d6fb4e59
https://github.com/vorpaljs/vorpal-grep/blob/a9f19ceca6099702134f59618e6809d9d6fb4e59/dist/grep.js#L226-L237
37,041
shakyShane/svg-sprite-data
lib/svg-sprite.js
SVGSprite
function SVGSprite(options) { options = _.extend({}, options); // Validate & prepare the options this._options = _.extend(defaultOptions, options); this._options.prefix = (new String(this._options.prefix || '').trim()) || null; this._options.common = (new String(this._options.common || '').trim()) || null; this._options.maxwidth = Math.abs(parseInt(this._options.maxwidth || 1000, 10)); this._options.maxheight = Math.abs(parseInt(this._options.maxheight || 1000, 10)); this._options.padding = Math.abs(parseInt(this._options.padding, 10)); this._options.pseudo = (new String(this._options.pseudo).trim()) || '~'; this._options.dims = !!this._options.dims; this._options.verbose = Math.min(Math.max(0, parseInt(this._options.verbose, 10)), 3); this._options.render = _.extend({css: true}, this._options.render); this._options.cleanwith = (new String(this._options.cleanwith || '').trim()) || null; this._options.cleanconfig = _.extend({}, this._options.cleanconfig || {}); this.namespacePow = []; // Reset all internal stacks this._reset(); var SVGO = require('svgo'); this._options.cleanconfig.plugins = svgoDefaults.concat(this._options.cleanconfig.plugins || []); this._cleaner = new SVGO(this._options.cleanconfig); this._clean = this._cleanSVGO; }
javascript
function SVGSprite(options) { options = _.extend({}, options); // Validate & prepare the options this._options = _.extend(defaultOptions, options); this._options.prefix = (new String(this._options.prefix || '').trim()) || null; this._options.common = (new String(this._options.common || '').trim()) || null; this._options.maxwidth = Math.abs(parseInt(this._options.maxwidth || 1000, 10)); this._options.maxheight = Math.abs(parseInt(this._options.maxheight || 1000, 10)); this._options.padding = Math.abs(parseInt(this._options.padding, 10)); this._options.pseudo = (new String(this._options.pseudo).trim()) || '~'; this._options.dims = !!this._options.dims; this._options.verbose = Math.min(Math.max(0, parseInt(this._options.verbose, 10)), 3); this._options.render = _.extend({css: true}, this._options.render); this._options.cleanwith = (new String(this._options.cleanwith || '').trim()) || null; this._options.cleanconfig = _.extend({}, this._options.cleanconfig || {}); this.namespacePow = []; // Reset all internal stacks this._reset(); var SVGO = require('svgo'); this._options.cleanconfig.plugins = svgoDefaults.concat(this._options.cleanconfig.plugins || []); this._cleaner = new SVGO(this._options.cleanconfig); this._clean = this._cleanSVGO; }
[ "function", "SVGSprite", "(", "options", ")", "{", "options", "=", "_", ".", "extend", "(", "{", "}", ",", "options", ")", ";", "// Validate & prepare the options", "this", ".", "_options", "=", "_", ".", "extend", "(", "defaultOptions", ",", "options", ")", ";", "this", ".", "_options", ".", "prefix", "=", "(", "new", "String", "(", "this", ".", "_options", ".", "prefix", "||", "''", ")", ".", "trim", "(", ")", ")", "||", "null", ";", "this", ".", "_options", ".", "common", "=", "(", "new", "String", "(", "this", ".", "_options", ".", "common", "||", "''", ")", ".", "trim", "(", ")", ")", "||", "null", ";", "this", ".", "_options", ".", "maxwidth", "=", "Math", ".", "abs", "(", "parseInt", "(", "this", ".", "_options", ".", "maxwidth", "||", "1000", ",", "10", ")", ")", ";", "this", ".", "_options", ".", "maxheight", "=", "Math", ".", "abs", "(", "parseInt", "(", "this", ".", "_options", ".", "maxheight", "||", "1000", ",", "10", ")", ")", ";", "this", ".", "_options", ".", "padding", "=", "Math", ".", "abs", "(", "parseInt", "(", "this", ".", "_options", ".", "padding", ",", "10", ")", ")", ";", "this", ".", "_options", ".", "pseudo", "=", "(", "new", "String", "(", "this", ".", "_options", ".", "pseudo", ")", ".", "trim", "(", ")", ")", "||", "'~'", ";", "this", ".", "_options", ".", "dims", "=", "!", "!", "this", ".", "_options", ".", "dims", ";", "this", ".", "_options", ".", "verbose", "=", "Math", ".", "min", "(", "Math", ".", "max", "(", "0", ",", "parseInt", "(", "this", ".", "_options", ".", "verbose", ",", "10", ")", ")", ",", "3", ")", ";", "this", ".", "_options", ".", "render", "=", "_", ".", "extend", "(", "{", "css", ":", "true", "}", ",", "this", ".", "_options", ".", "render", ")", ";", "this", ".", "_options", ".", "cleanwith", "=", "(", "new", "String", "(", "this", ".", "_options", ".", "cleanwith", "||", "''", ")", ".", "trim", "(", ")", ")", "||", "null", ";", "this", ".", "_options", ".", "cleanconfig", "=", "_", ".", "extend", "(", "{", "}", ",", "this", ".", "_options", ".", "cleanconfig", "||", "{", "}", ")", ";", "this", ".", "namespacePow", "=", "[", "]", ";", "// Reset all internal stacks", "this", ".", "_reset", "(", ")", ";", "var", "SVGO", "=", "require", "(", "'svgo'", ")", ";", "this", ".", "_options", ".", "cleanconfig", ".", "plugins", "=", "svgoDefaults", ".", "concat", "(", "this", ".", "_options", ".", "cleanconfig", ".", "plugins", "||", "[", "]", ")", ";", "this", ".", "_cleaner", "=", "new", "SVGO", "(", "this", ".", "_options", ".", "cleanconfig", ")", ";", "this", ".", "_clean", "=", "this", ".", "_cleanSVGO", ";", "}" ]
SVG Sprite generator @param {Object} options Options @return {SVGSprite} SVG sprite generator instance @throws {Error}
[ "SVG", "Sprite", "generator" ]
fa2bd9e68df3dd5906153333245aa06a5ac4b2b3
https://github.com/shakyShane/svg-sprite-data/blob/fa2bd9e68df3dd5906153333245aa06a5ac4b2b3/lib/svg-sprite.js#L76-L102
37,042
myrmex-org/myrmex
packages/api-gateway/src/cli/inspect-api.js
executeCommand
function executeCommand(parameters) { if (parameters.colors === undefined) { parameters.colors = plugin.myrmex.getConfig('colors'); } return plugin.findApi(parameters.apiIdentifier) .then(api => { return api.generateSpec(parameters.specVersion); }) .then(jsonSpec => { let spec = JSON.stringify(jsonSpec, null, 2); if (parameters.colors) { spec = icli.highlight(spec, { json: true }); } icli.print(spec); return Promise.resolve(jsonSpec); }); }
javascript
function executeCommand(parameters) { if (parameters.colors === undefined) { parameters.colors = plugin.myrmex.getConfig('colors'); } return plugin.findApi(parameters.apiIdentifier) .then(api => { return api.generateSpec(parameters.specVersion); }) .then(jsonSpec => { let spec = JSON.stringify(jsonSpec, null, 2); if (parameters.colors) { spec = icli.highlight(spec, { json: true }); } icli.print(spec); return Promise.resolve(jsonSpec); }); }
[ "function", "executeCommand", "(", "parameters", ")", "{", "if", "(", "parameters", ".", "colors", "===", "undefined", ")", "{", "parameters", ".", "colors", "=", "plugin", ".", "myrmex", ".", "getConfig", "(", "'colors'", ")", ";", "}", "return", "plugin", ".", "findApi", "(", "parameters", ".", "apiIdentifier", ")", ".", "then", "(", "api", "=>", "{", "return", "api", ".", "generateSpec", "(", "parameters", ".", "specVersion", ")", ";", "}", ")", ".", "then", "(", "jsonSpec", "=>", "{", "let", "spec", "=", "JSON", ".", "stringify", "(", "jsonSpec", ",", "null", ",", "2", ")", ";", "if", "(", "parameters", ".", "colors", ")", "{", "spec", "=", "icli", ".", "highlight", "(", "spec", ",", "{", "json", ":", "true", "}", ")", ";", "}", "icli", ".", "print", "(", "spec", ")", ";", "return", "Promise", ".", "resolve", "(", "jsonSpec", ")", ";", "}", ")", ";", "}" ]
Output API specification @param {Object} parameters - the parameters provided in the command and in the prompt @returns {Promise<null>} - The execution stops here
[ "Output", "API", "specification" ]
9dba3b8686d87bd603779b00c0545cd12ccad43c
https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/api-gateway/src/cli/inspect-api.js#L91-L107
37,043
helion3/lodash-addons
src/check.js
check
function check(value, ...validators) { let valid = false; _.each(validators, (validator) => { return !(valid = validator(value)); }); if (!valid) { throw new TypeError('Argument is not any of the accepted types.'); } }
javascript
function check(value, ...validators) { let valid = false; _.each(validators, (validator) => { return !(valid = validator(value)); }); if (!valid) { throw new TypeError('Argument is not any of the accepted types.'); } }
[ "function", "check", "(", "value", ",", "...", "validators", ")", "{", "let", "valid", "=", "false", ";", "_", ".", "each", "(", "validators", ",", "(", "validator", ")", "=>", "{", "return", "!", "(", "valid", "=", "validator", "(", "value", ")", ")", ";", "}", ")", ";", "if", "(", "!", "valid", ")", "{", "throw", "new", "TypeError", "(", "'Argument is not any of the accepted types.'", ")", ";", "}", "}" ]
Throw a TypeError if value doesn't match one of any provided validation methods. @static @memberOf _ @category Preconditions @param {mixed} value Value @return {void}
[ "Throw", "a", "TypeError", "if", "value", "doesn", "t", "match", "one", "of", "any", "provided", "validation", "methods", "." ]
83b5bf14258241e7ae35eef346151a332fdb6f50
https://github.com/helion3/lodash-addons/blob/83b5bf14258241e7ae35eef346151a332fdb6f50/src/check.js#L12-L21
37,044
jonschlinkert/engine-lodash
index.js
delimsObject
function delimsObject(delims) { var a = delims[0], b = delims[1]; var res = {}; res.interpolate = lazy.delimiters(a + '=', b); res.evaluate = lazy.delimiters(a, b); res.escape = lazy.delimiters(a + '-', b); return res; }
javascript
function delimsObject(delims) { var a = delims[0], b = delims[1]; var res = {}; res.interpolate = lazy.delimiters(a + '=', b); res.evaluate = lazy.delimiters(a, b); res.escape = lazy.delimiters(a + '-', b); return res; }
[ "function", "delimsObject", "(", "delims", ")", "{", "var", "a", "=", "delims", "[", "0", "]", ",", "b", "=", "delims", "[", "1", "]", ";", "var", "res", "=", "{", "}", ";", "res", ".", "interpolate", "=", "lazy", ".", "delimiters", "(", "a", "+", "'='", ",", "b", ")", ";", "res", ".", "evaluate", "=", "lazy", ".", "delimiters", "(", "a", ",", "b", ")", ";", "res", ".", "escape", "=", "lazy", ".", "delimiters", "(", "a", "+", "'-'", ",", "b", ")", ";", "return", "res", ";", "}" ]
Handle custom delimiters
[ "Handle", "custom", "delimiters" ]
2fce0ea5e773345d98cd71867580af348ed50bc0
https://github.com/jonschlinkert/engine-lodash/blob/2fce0ea5e773345d98cd71867580af348ed50bc0/index.js#L187-L194
37,045
jonschlinkert/engine-lodash
index.js
inspectHelpers
function inspectHelpers(settings, opts) { var helpers = Object.keys(settings.imports); for (var key in opts) { if (helpers.indexOf(key) !== -1) { conflictMessage(settings, opts, key); } } }
javascript
function inspectHelpers(settings, opts) { var helpers = Object.keys(settings.imports); for (var key in opts) { if (helpers.indexOf(key) !== -1) { conflictMessage(settings, opts, key); } } }
[ "function", "inspectHelpers", "(", "settings", ",", "opts", ")", "{", "var", "helpers", "=", "Object", ".", "keys", "(", "settings", ".", "imports", ")", ";", "for", "(", "var", "key", "in", "opts", ")", "{", "if", "(", "helpers", ".", "indexOf", "(", "key", ")", "!==", "-", "1", ")", "{", "conflictMessage", "(", "settings", ",", "opts", ",", "key", ")", ";", "}", "}", "}" ]
Inspect helpers if `debugEngine` is enabled
[ "Inspect", "helpers", "if", "debugEngine", "is", "enabled" ]
2fce0ea5e773345d98cd71867580af348ed50bc0
https://github.com/jonschlinkert/engine-lodash/blob/2fce0ea5e773345d98cd71867580af348ed50bc0/index.js#L200-L207
37,046
helion3/lodash-addons
src/hasOfType.js
hasOfType
function hasOfType(value, path, validator) { return _.has(value, path) ? validator(_.get(value, path)) : false; }
javascript
function hasOfType(value, path, validator) { return _.has(value, path) ? validator(_.get(value, path)) : false; }
[ "function", "hasOfType", "(", "value", ",", "path", ",", "validator", ")", "{", "return", "_", ".", "has", "(", "value", ",", "path", ")", "?", "validator", "(", "_", ".", "get", "(", "value", ",", "path", ")", ")", ":", "false", ";", "}" ]
If _.has returns true, run a validator on value. @static @memberOf _ @category Object @param {mixed} value Collection for _.has @param {string} path Path @param {function} validator Function to validate value. @return {boolean} Whether collection has prop, and it passes validation @example _.hasOfType({ test: '' }, 'test', _.isString); // => true
[ "If", "_", ".", "has", "returns", "true", "run", "a", "validator", "on", "value", "." ]
83b5bf14258241e7ae35eef346151a332fdb6f50
https://github.com/helion3/lodash-addons/blob/83b5bf14258241e7ae35eef346151a332fdb6f50/src/hasOfType.js#L18-L20
37,047
anseki/htmlclean-cli
htmlclean-cli.js
mkdirParents
function mkdirParents(dirPath) { dirPath.split(/\/|\\/).reduce(function(parents, dir) { var path = pathUtil.resolve((parents += dir + pathUtil.sep)); // normalize if (!fs.existsSync(path)) { fs.mkdirSync(path); } else if (!fs.statSync(path).isDirectory()) { throw new Error('Non directory already exists: ' + path); } return parents; }, ''); }
javascript
function mkdirParents(dirPath) { dirPath.split(/\/|\\/).reduce(function(parents, dir) { var path = pathUtil.resolve((parents += dir + pathUtil.sep)); // normalize if (!fs.existsSync(path)) { fs.mkdirSync(path); } else if (!fs.statSync(path).isDirectory()) { throw new Error('Non directory already exists: ' + path); } return parents; }, ''); }
[ "function", "mkdirParents", "(", "dirPath", ")", "{", "dirPath", ".", "split", "(", "/", "\\/|\\\\", "/", ")", ".", "reduce", "(", "function", "(", "parents", ",", "dir", ")", "{", "var", "path", "=", "pathUtil", ".", "resolve", "(", "(", "parents", "+=", "dir", "+", "pathUtil", ".", "sep", ")", ")", ";", "// normalize", "if", "(", "!", "fs", ".", "existsSync", "(", "path", ")", ")", "{", "fs", ".", "mkdirSync", "(", "path", ")", ";", "}", "else", "if", "(", "!", "fs", ".", "statSync", "(", "path", ")", ".", "isDirectory", "(", ")", ")", "{", "throw", "new", "Error", "(", "'Non directory already exists: '", "+", "path", ")", ";", "}", "return", "parents", ";", "}", ",", "''", ")", ";", "}" ]
mkdir -p
[ "mkdir", "-", "p" ]
f468a97a70bc870a5cfcbd644b3735053f4d83c6
https://github.com/anseki/htmlclean-cli/blob/f468a97a70bc870a5cfcbd644b3735053f4d83c6/htmlclean-cli.js#L29-L39
37,048
anseki/htmlclean-cli
htmlclean-cli.js
readStdin
function readStdin() { var stdin = process.stdin, fd = stdin.isTTY && process.platform !== 'win32' ? fs.openSync('/dev/tty', 'rs') : stdin.fd, bufSize = stdin.isTTY ? DEFAULT_BUF_SIZE : (fs.fstatSync(fd).size || DEFAULT_BUF_SIZE), buffer = Buffer.allocUnsafe && Buffer.alloc ? Buffer.alloc(bufSize) : new Buffer(bufSize), rsize, input = ''; while (true) { rsize = 0; try { rsize = fs.readSync(fd, buffer, 0, bufSize); } catch (e) { if (e.code === 'EOF') { break; } throw e; } if (rsize === 0) { break; } input += buffer.toString(program.encoding, 0, rsize); } return input; }
javascript
function readStdin() { var stdin = process.stdin, fd = stdin.isTTY && process.platform !== 'win32' ? fs.openSync('/dev/tty', 'rs') : stdin.fd, bufSize = stdin.isTTY ? DEFAULT_BUF_SIZE : (fs.fstatSync(fd).size || DEFAULT_BUF_SIZE), buffer = Buffer.allocUnsafe && Buffer.alloc ? Buffer.alloc(bufSize) : new Buffer(bufSize), rsize, input = ''; while (true) { rsize = 0; try { rsize = fs.readSync(fd, buffer, 0, bufSize); } catch (e) { if (e.code === 'EOF') { break; } throw e; } if (rsize === 0) { break; } input += buffer.toString(program.encoding, 0, rsize); } return input; }
[ "function", "readStdin", "(", ")", "{", "var", "stdin", "=", "process", ".", "stdin", ",", "fd", "=", "stdin", ".", "isTTY", "&&", "process", ".", "platform", "!==", "'win32'", "?", "fs", ".", "openSync", "(", "'/dev/tty'", ",", "'rs'", ")", ":", "stdin", ".", "fd", ",", "bufSize", "=", "stdin", ".", "isTTY", "?", "DEFAULT_BUF_SIZE", ":", "(", "fs", ".", "fstatSync", "(", "fd", ")", ".", "size", "||", "DEFAULT_BUF_SIZE", ")", ",", "buffer", "=", "Buffer", ".", "allocUnsafe", "&&", "Buffer", ".", "alloc", "?", "Buffer", ".", "alloc", "(", "bufSize", ")", ":", "new", "Buffer", "(", "bufSize", ")", ",", "rsize", ",", "input", "=", "''", ";", "while", "(", "true", ")", "{", "rsize", "=", "0", ";", "try", "{", "rsize", "=", "fs", ".", "readSync", "(", "fd", ",", "buffer", ",", "0", ",", "bufSize", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "e", ".", "code", "===", "'EOF'", ")", "{", "break", ";", "}", "throw", "e", ";", "}", "if", "(", "rsize", "===", "0", ")", "{", "break", ";", "}", "input", "+=", "buffer", ".", "toString", "(", "program", ".", "encoding", ",", "0", ",", "rsize", ")", ";", "}", "return", "input", ";", "}" ]
path was normalized
[ "path", "was", "normalized" ]
f468a97a70bc870a5cfcbd644b3735053f4d83c6
https://github.com/anseki/htmlclean-cli/blob/f468a97a70bc870a5cfcbd644b3735053f4d83c6/htmlclean-cli.js#L54-L74
37,049
dbartholomae/create-readme
docs/javascript/application.js
dispatch
function dispatch(event, scope){ var key, handler, k, i, modifiersMatch; key = event.keyCode; // if a modifier key, set the key.<modifierkeyname> property to true and return if(key == 93 || key == 224) key = 91; // right command on webkit, command on Gecko if(key in _mods) { _mods[key] = true; // 'assignKey' from inside this closure is exported to window.key for(k in _MODIFIERS) if(_MODIFIERS[k] == key) assignKey[k] = true; return; } // see if we need to ignore the keypress (ftiler() can can be overridden) // by default ignore key presses if a select, textarea, or input is focused if(!assignKey.filter.call(this, event)) return; // abort if no potentially matching shortcuts found if (!(key in _handlers)) return; // for each potential shortcut for (i = 0; i < _handlers[key].length; i++) { handler = _handlers[key][i]; // see if it's in the current scope if(handler.scope == scope || handler.scope == 'all'){ // check if modifiers match if any modifiersMatch = handler.mods.length > 0; for(k in _mods) if((!_mods[k] && index(handler.mods, +k) > -1) || (_mods[k] && index(handler.mods, +k) == -1)) modifiersMatch = false; // call the handler and stop the event if neccessary if((handler.mods.length == 0 && !_mods[16] && !_mods[18] && !_mods[17] && !_mods[91]) || modifiersMatch){ if(handler.method(event, handler)===false){ if(event.preventDefault) event.preventDefault(); else event.returnValue = false; if(event.stopPropagation) event.stopPropagation(); if(event.cancelBubble) event.cancelBubble = true; } } } } }
javascript
function dispatch(event, scope){ var key, handler, k, i, modifiersMatch; key = event.keyCode; // if a modifier key, set the key.<modifierkeyname> property to true and return if(key == 93 || key == 224) key = 91; // right command on webkit, command on Gecko if(key in _mods) { _mods[key] = true; // 'assignKey' from inside this closure is exported to window.key for(k in _MODIFIERS) if(_MODIFIERS[k] == key) assignKey[k] = true; return; } // see if we need to ignore the keypress (ftiler() can can be overridden) // by default ignore key presses if a select, textarea, or input is focused if(!assignKey.filter.call(this, event)) return; // abort if no potentially matching shortcuts found if (!(key in _handlers)) return; // for each potential shortcut for (i = 0; i < _handlers[key].length; i++) { handler = _handlers[key][i]; // see if it's in the current scope if(handler.scope == scope || handler.scope == 'all'){ // check if modifiers match if any modifiersMatch = handler.mods.length > 0; for(k in _mods) if((!_mods[k] && index(handler.mods, +k) > -1) || (_mods[k] && index(handler.mods, +k) == -1)) modifiersMatch = false; // call the handler and stop the event if neccessary if((handler.mods.length == 0 && !_mods[16] && !_mods[18] && !_mods[17] && !_mods[91]) || modifiersMatch){ if(handler.method(event, handler)===false){ if(event.preventDefault) event.preventDefault(); else event.returnValue = false; if(event.stopPropagation) event.stopPropagation(); if(event.cancelBubble) event.cancelBubble = true; } } } } }
[ "function", "dispatch", "(", "event", ",", "scope", ")", "{", "var", "key", ",", "handler", ",", "k", ",", "i", ",", "modifiersMatch", ";", "key", "=", "event", ".", "keyCode", ";", "// if a modifier key, set the key.<modifierkeyname> property to true and return", "if", "(", "key", "==", "93", "||", "key", "==", "224", ")", "key", "=", "91", ";", "// right command on webkit, command on Gecko", "if", "(", "key", "in", "_mods", ")", "{", "_mods", "[", "key", "]", "=", "true", ";", "// 'assignKey' from inside this closure is exported to window.key", "for", "(", "k", "in", "_MODIFIERS", ")", "if", "(", "_MODIFIERS", "[", "k", "]", "==", "key", ")", "assignKey", "[", "k", "]", "=", "true", ";", "return", ";", "}", "// see if we need to ignore the keypress (ftiler() can can be overridden)", "// by default ignore key presses if a select, textarea, or input is focused", "if", "(", "!", "assignKey", ".", "filter", ".", "call", "(", "this", ",", "event", ")", ")", "return", ";", "// abort if no potentially matching shortcuts found", "if", "(", "!", "(", "key", "in", "_handlers", ")", ")", "return", ";", "// for each potential shortcut", "for", "(", "i", "=", "0", ";", "i", "<", "_handlers", "[", "key", "]", ".", "length", ";", "i", "++", ")", "{", "handler", "=", "_handlers", "[", "key", "]", "[", "i", "]", ";", "// see if it's in the current scope", "if", "(", "handler", ".", "scope", "==", "scope", "||", "handler", ".", "scope", "==", "'all'", ")", "{", "// check if modifiers match if any", "modifiersMatch", "=", "handler", ".", "mods", ".", "length", ">", "0", ";", "for", "(", "k", "in", "_mods", ")", "if", "(", "(", "!", "_mods", "[", "k", "]", "&&", "index", "(", "handler", ".", "mods", ",", "+", "k", ")", ">", "-", "1", ")", "||", "(", "_mods", "[", "k", "]", "&&", "index", "(", "handler", ".", "mods", ",", "+", "k", ")", "==", "-", "1", ")", ")", "modifiersMatch", "=", "false", ";", "// call the handler and stop the event if neccessary", "if", "(", "(", "handler", ".", "mods", ".", "length", "==", "0", "&&", "!", "_mods", "[", "16", "]", "&&", "!", "_mods", "[", "18", "]", "&&", "!", "_mods", "[", "17", "]", "&&", "!", "_mods", "[", "91", "]", ")", "||", "modifiersMatch", ")", "{", "if", "(", "handler", ".", "method", "(", "event", ",", "handler", ")", "===", "false", ")", "{", "if", "(", "event", ".", "preventDefault", ")", "event", ".", "preventDefault", "(", ")", ";", "else", "event", ".", "returnValue", "=", "false", ";", "if", "(", "event", ".", "stopPropagation", ")", "event", ".", "stopPropagation", "(", ")", ";", "if", "(", "event", ".", "cancelBubble", ")", "event", ".", "cancelBubble", "=", "true", ";", "}", "}", "}", "}", "}" ]
handle keydown event
[ "handle", "keydown", "event" ]
7c1a49aaa38897fa686a1f358e9229db37f2604b
https://github.com/dbartholomae/create-readme/blob/7c1a49aaa38897fa686a1f358e9229db37f2604b/docs/javascript/application.js#L10245-L10287
37,050
greedbell/gulp-require-modules
index.js
getMatches
function getMatches(str, re) { if (str == null) { return null; } if (re == null) { return null; } var results = []; var match; while ((match = re.exec(str)) !== null) { results.push(match[1]); } return results; }
javascript
function getMatches(str, re) { if (str == null) { return null; } if (re == null) { return null; } var results = []; var match; while ((match = re.exec(str)) !== null) { results.push(match[1]); } return results; }
[ "function", "getMatches", "(", "str", ",", "re", ")", "{", "if", "(", "str", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "re", "==", "null", ")", "{", "return", "null", ";", "}", "var", "results", "=", "[", "]", ";", "var", "match", ";", "while", "(", "(", "match", "=", "re", ".", "exec", "(", "str", ")", ")", "!==", "null", ")", "{", "results", ".", "push", "(", "match", "[", "1", "]", ")", ";", "}", "return", "results", ";", "}" ]
get mateched string @param str @param re @returns {*}
[ "get", "mateched", "string" ]
a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc
https://github.com/greedbell/gulp-require-modules/blob/a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc/index.js#L60-L73
37,051
greedbell/gulp-require-modules
index.js
transformFile
function transformFile(from, to, modulesDirectory) { var contents = fs.readFileSync(from, 'utf8'); // modules var modules = getModules(contents); for (var index in modules) { var module = modules[index]; if (modulesManifest.hasOwnProperty(module)) { continue; } var modulePath = path_util.modulePath(module, node_modules); if (modulePath === null) { continue; } var targetPath = path_util.targetPath(modulePath, node_modules, modulesDirectory); modulesManifest[module] = path.relative(process.cwd(), targetPath); if (!fs.existsSync(targetPath)) { transformFile(modulePath, targetPath, modulesDirectory); } var relativePath = path_util.relativePath(to, targetPath); var re = eval('\/require\\\(\[\'\"\]' + module + '\[\'\"\]\\\)\/ig'); contents = contents.replace(re, 'require(\'' + relativePath + '\')'); } // requires var requires = getRequires(contents); for (var index in requires) { var require = requires[index]; var requirePath = path_util.requirePath(from, require); if (requirePath === null) { continue; } if (requiresManifest.hasOwnProperty(requirePath)) { continue; } else { requiresManifest[requirePath] = true; } var targetPath = path_util.targetPath(requirePath, node_modules, modulesDirectory); if (!fs.existsSync(targetPath)) { transformFile(requirePath, targetPath, modulesDirectory); } } var dirname = path.dirname(to); fs.mkdirsSync(dirname); fs.writeFileSync(to, contents, 'utf8'); }
javascript
function transformFile(from, to, modulesDirectory) { var contents = fs.readFileSync(from, 'utf8'); // modules var modules = getModules(contents); for (var index in modules) { var module = modules[index]; if (modulesManifest.hasOwnProperty(module)) { continue; } var modulePath = path_util.modulePath(module, node_modules); if (modulePath === null) { continue; } var targetPath = path_util.targetPath(modulePath, node_modules, modulesDirectory); modulesManifest[module] = path.relative(process.cwd(), targetPath); if (!fs.existsSync(targetPath)) { transformFile(modulePath, targetPath, modulesDirectory); } var relativePath = path_util.relativePath(to, targetPath); var re = eval('\/require\\\(\[\'\"\]' + module + '\[\'\"\]\\\)\/ig'); contents = contents.replace(re, 'require(\'' + relativePath + '\')'); } // requires var requires = getRequires(contents); for (var index in requires) { var require = requires[index]; var requirePath = path_util.requirePath(from, require); if (requirePath === null) { continue; } if (requiresManifest.hasOwnProperty(requirePath)) { continue; } else { requiresManifest[requirePath] = true; } var targetPath = path_util.targetPath(requirePath, node_modules, modulesDirectory); if (!fs.existsSync(targetPath)) { transformFile(requirePath, targetPath, modulesDirectory); } } var dirname = path.dirname(to); fs.mkdirsSync(dirname); fs.writeFileSync(to, contents, 'utf8'); }
[ "function", "transformFile", "(", "from", ",", "to", ",", "modulesDirectory", ")", "{", "var", "contents", "=", "fs", ".", "readFileSync", "(", "from", ",", "'utf8'", ")", ";", "// modules", "var", "modules", "=", "getModules", "(", "contents", ")", ";", "for", "(", "var", "index", "in", "modules", ")", "{", "var", "module", "=", "modules", "[", "index", "]", ";", "if", "(", "modulesManifest", ".", "hasOwnProperty", "(", "module", ")", ")", "{", "continue", ";", "}", "var", "modulePath", "=", "path_util", ".", "modulePath", "(", "module", ",", "node_modules", ")", ";", "if", "(", "modulePath", "===", "null", ")", "{", "continue", ";", "}", "var", "targetPath", "=", "path_util", ".", "targetPath", "(", "modulePath", ",", "node_modules", ",", "modulesDirectory", ")", ";", "modulesManifest", "[", "module", "]", "=", "path", ".", "relative", "(", "process", ".", "cwd", "(", ")", ",", "targetPath", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "targetPath", ")", ")", "{", "transformFile", "(", "modulePath", ",", "targetPath", ",", "modulesDirectory", ")", ";", "}", "var", "relativePath", "=", "path_util", ".", "relativePath", "(", "to", ",", "targetPath", ")", ";", "var", "re", "=", "eval", "(", "'\\/require\\\\\\(\\[\\'\\\"\\]'", "+", "module", "+", "'\\[\\'\\\"\\]\\\\\\)\\/ig'", ")", ";", "contents", "=", "contents", ".", "replace", "(", "re", ",", "'require(\\''", "+", "relativePath", "+", "'\\')'", ")", ";", "}", "// requires", "var", "requires", "=", "getRequires", "(", "contents", ")", ";", "for", "(", "var", "index", "in", "requires", ")", "{", "var", "require", "=", "requires", "[", "index", "]", ";", "var", "requirePath", "=", "path_util", ".", "requirePath", "(", "from", ",", "require", ")", ";", "if", "(", "requirePath", "===", "null", ")", "{", "continue", ";", "}", "if", "(", "requiresManifest", ".", "hasOwnProperty", "(", "requirePath", ")", ")", "{", "continue", ";", "}", "else", "{", "requiresManifest", "[", "requirePath", "]", "=", "true", ";", "}", "var", "targetPath", "=", "path_util", ".", "targetPath", "(", "requirePath", ",", "node_modules", ",", "modulesDirectory", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "targetPath", ")", ")", "{", "transformFile", "(", "requirePath", ",", "targetPath", ",", "modulesDirectory", ")", ";", "}", "}", "var", "dirname", "=", "path", ".", "dirname", "(", "to", ")", ";", "fs", ".", "mkdirsSync", "(", "dirname", ")", ";", "fs", ".", "writeFileSync", "(", "to", ",", "contents", ",", "'utf8'", ")", ";", "}" ]
copy file from node_module to modulesDirectory @param from file full path @param to file full path @param modulesDirectory
[ "copy", "file", "from", "node_module", "to", "modulesDirectory" ]
a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc
https://github.com/greedbell/gulp-require-modules/blob/a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc/index.js#L82-L128
37,052
borela-tech/js-toolbox
entries/react/spa/ErrorBoundary.js
parseMappedStack
function parseMappedStack(stack) { let result = [] for (let line of stack) { // at ... (file:///namespace/path:line:column) const MATCHED = line.match(/\(.*?:\/{3}(.*?)\/(.*):(.*?):(.*?)\)$/) // The line couldn’t be parsed. if (!MATCHED){ result.push({stackLine: line}) continue } result.push({ column: MATCHED[4], line: MATCHED[3], namespace: MATCHED[1], path: MATCHED[2], stackLine: line, }) } return result }
javascript
function parseMappedStack(stack) { let result = [] for (let line of stack) { // at ... (file:///namespace/path:line:column) const MATCHED = line.match(/\(.*?:\/{3}(.*?)\/(.*):(.*?):(.*?)\)$/) // The line couldn’t be parsed. if (!MATCHED){ result.push({stackLine: line}) continue } result.push({ column: MATCHED[4], line: MATCHED[3], namespace: MATCHED[1], path: MATCHED[2], stackLine: line, }) } return result }
[ "function", "parseMappedStack", "(", "stack", ")", "{", "let", "result", "=", "[", "]", "for", "(", "let", "line", "of", "stack", ")", "{", "// at ... (file:///namespace/path:line:column)", "const", "MATCHED", "=", "line", ".", "match", "(", "/", "\\(.*?:\\/{3}(.*?)\\/(.*):(.*?):(.*?)\\)$", "/", ")", "// The line couldn’t be parsed.", "if", "(", "!", "MATCHED", ")", "{", "result", ".", "push", "(", "{", "stackLine", ":", "line", "}", ")", "continue", "}", "result", ".", "push", "(", "{", "column", ":", "MATCHED", "[", "4", "]", ",", "line", ":", "MATCHED", "[", "3", "]", ",", "namespace", ":", "MATCHED", "[", "1", "]", ",", "path", ":", "MATCHED", "[", "2", "]", ",", "stackLine", ":", "line", ",", "}", ")", "}", "return", "result", "}" ]
Return the a new mapped stack where each item is an object with properties for line, column, namespace and file path.
[ "Return", "the", "a", "new", "mapped", "stack", "where", "each", "item", "is", "an", "object", "with", "properties", "for", "line", "column", "namespace", "and", "file", "path", "." ]
0ed75d373fa1573d64a3d715ee8e6e24852824e4
https://github.com/borela-tech/js-toolbox/blob/0ed75d373fa1573d64a3d715ee8e6e24852824e4/entries/react/spa/ErrorBoundary.js#L21-L42
37,053
helion3/lodash-addons
src/sign.js
sign
function sign(value) { let sign = NaN; if (_.isNumber(value)) { if (value === 0) { sign = value; } else if (value >= 1) { sign = 1; } else if (value <= -1) { sign = -1; } } return sign; }
javascript
function sign(value) { let sign = NaN; if (_.isNumber(value)) { if (value === 0) { sign = value; } else if (value >= 1) { sign = 1; } else if (value <= -1) { sign = -1; } } return sign; }
[ "function", "sign", "(", "value", ")", "{", "let", "sign", "=", "NaN", ";", "if", "(", "_", ".", "isNumber", "(", "value", ")", ")", "{", "if", "(", "value", "===", "0", ")", "{", "sign", "=", "value", ";", "}", "else", "if", "(", "value", ">=", "1", ")", "{", "sign", "=", "1", ";", "}", "else", "if", "(", "value", "<=", "-", "1", ")", "{", "sign", "=", "-", "1", ";", "}", "}", "return", "sign", ";", "}" ]
Returns a number representing the sign of `value`. If `value` is a positive number, negative number, positive zero or negative zero, the function will return 1, -1, 0 or -0 respectively. Otherwise, NaN is returned. @static @memberOf _ @category Math @param {number} value A number @returns {number} A number representing the sign @example _.sign(10); // => 1 _.sign(-10); // => -1
[ "Returns", "a", "number", "representing", "the", "sign", "of", "value", "." ]
83b5bf14258241e7ae35eef346151a332fdb6f50
https://github.com/helion3/lodash-addons/blob/83b5bf14258241e7ae35eef346151a332fdb6f50/src/sign.js#L22-L38
37,054
helion3/lodash-addons
src/internal/baseGetType.js
baseGetType
function baseGetType(validator, baseDefault, value, replacement) { let result; if (validator(value)) { result = value; } else if (validator(replacement)) { result = replacement; } else { result = baseDefault; } return result; }
javascript
function baseGetType(validator, baseDefault, value, replacement) { let result; if (validator(value)) { result = value; } else if (validator(replacement)) { result = replacement; } else { result = baseDefault; } return result; }
[ "function", "baseGetType", "(", "validator", ",", "baseDefault", ",", "value", ",", "replacement", ")", "{", "let", "result", ";", "if", "(", "validator", "(", "value", ")", ")", "{", "result", "=", "value", ";", "}", "else", "if", "(", "validator", "(", "replacement", ")", ")", "{", "result", "=", "replacement", ";", "}", "else", "{", "result", "=", "baseDefault", ";", "}", "return", "result", ";", "}" ]
Base function for returning a default when the given value fails validation. @private @param {function} validator Validation function. @param {*} baseDefault Base default value. @param {*} value Given value. @param {*} replacement Custom replacement. @return {*} Final value.
[ "Base", "function", "for", "returning", "a", "default", "when", "the", "given", "value", "fails", "validation", "." ]
83b5bf14258241e7ae35eef346151a332fdb6f50
https://github.com/helion3/lodash-addons/blob/83b5bf14258241e7ae35eef346151a332fdb6f50/src/internal/baseGetType.js#L11-L25
37,055
Frijol/PulseSensor
index.js
use
function use (hardware, callback) { if (!hardware) { // Set default configuration hardware = require('tessel').port['GPIO'].pin['A1']; } return new PulseSensor(hardware, callback); }
javascript
function use (hardware, callback) { if (!hardware) { // Set default configuration hardware = require('tessel').port['GPIO'].pin['A1']; } return new PulseSensor(hardware, callback); }
[ "function", "use", "(", "hardware", ",", "callback", ")", "{", "if", "(", "!", "hardware", ")", "{", "// Set default configuration", "hardware", "=", "require", "(", "'tessel'", ")", ".", "port", "[", "'GPIO'", "]", ".", "pin", "[", "'A1'", "]", ";", "}", "return", "new", "PulseSensor", "(", "hardware", ",", "callback", ")", ";", "}" ]
Standard Tessel use function
[ "Standard", "Tessel", "use", "function" ]
a28b0687ca2f287ba6ed58fc38149b25a7e0c949
https://github.com/Frijol/PulseSensor/blob/a28b0687ca2f287ba6ed58fc38149b25a7e0c949/index.js#L80-L86
37,056
karlkfi/ngindox
lib/nginx.js
parse
function parse(fileString, callback) { return NginxConf.parse(fileString, function(err, _config) { if (err) { return callback(err); } return parseNginxConf(_config, callback); }); }
javascript
function parse(fileString, callback) { return NginxConf.parse(fileString, function(err, _config) { if (err) { return callback(err); } return parseNginxConf(_config, callback); }); }
[ "function", "parse", "(", "fileString", ",", "callback", ")", "{", "return", "NginxConf", ".", "parse", "(", "fileString", ",", "function", "(", "err", ",", "_config", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "return", "parseNginxConf", "(", "_config", ",", "callback", ")", ";", "}", ")", ";", "}" ]
Parses a file string into an Nginx Config object. Does not expand file includes.
[ "Parses", "a", "file", "string", "into", "an", "Nginx", "Config", "object", ".", "Does", "not", "expand", "file", "includes", "." ]
2c0e8a682d7bde9e5d73a853f45bf1460f4664e9
https://github.com/karlkfi/ngindox/blob/2c0e8a682d7bde9e5d73a853f45bf1460f4664e9/lib/nginx.js#L10-L18
37,057
karlkfi/ngindox
lib/nginx.js
parseFile
function parseFile(filePath, encoding, callback) { return fs.readFile(filePath, encoding, function(err, fileString) { if (err) { return callback(err); } fileString = expandIncludes(fileString, path.dirname(filePath)); return parse(fileString, callback); }); }
javascript
function parseFile(filePath, encoding, callback) { return fs.readFile(filePath, encoding, function(err, fileString) { if (err) { return callback(err); } fileString = expandIncludes(fileString, path.dirname(filePath)); return parse(fileString, callback); }); }
[ "function", "parseFile", "(", "filePath", ",", "encoding", ",", "callback", ")", "{", "return", "fs", ".", "readFile", "(", "filePath", ",", "encoding", ",", "function", "(", "err", ",", "fileString", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "fileString", "=", "expandIncludes", "(", "fileString", ",", "path", ".", "dirname", "(", "filePath", ")", ")", ";", "return", "parse", "(", "fileString", ",", "callback", ")", ";", "}", ")", ";", "}" ]
Reads and parses a file into an Nginx Config object Expands file includes.
[ "Reads", "and", "parses", "a", "file", "into", "an", "Nginx", "Config", "object", "Expands", "file", "includes", "." ]
2c0e8a682d7bde9e5d73a853f45bf1460f4664e9
https://github.com/karlkfi/ngindox/blob/2c0e8a682d7bde9e5d73a853f45bf1460f4664e9/lib/nginx.js#L22-L32
37,058
Bitclimb/coinjs-lib
src/script.js
isOPInt
function isOPInt (value) { return types.Number(value) && ((value === OPS.OP_0) || (value >= OPS.OP_1 && value <= OPS.OP_16) || (value === OPS.OP_1NEGATE)); }
javascript
function isOPInt (value) { return types.Number(value) && ((value === OPS.OP_0) || (value >= OPS.OP_1 && value <= OPS.OP_16) || (value === OPS.OP_1NEGATE)); }
[ "function", "isOPInt", "(", "value", ")", "{", "return", "types", ".", "Number", "(", "value", ")", "&&", "(", "(", "value", "===", "OPS", ".", "OP_0", ")", "||", "(", "value", ">=", "OPS", ".", "OP_1", "&&", "value", "<=", "OPS", ".", "OP_16", ")", "||", "(", "value", "===", "OPS", ".", "OP_1NEGATE", ")", ")", ";", "}" ]
OP_1 - 1
[ "OP_1", "-", "1" ]
df40d37a63b3f77eda590c7aa46555c6faee3c6d
https://github.com/Bitclimb/coinjs-lib/blob/df40d37a63b3f77eda590c7aa46555c6faee3c6d/src/script.js#L11-L16
37,059
toymachiner62/mongo-factory
index.js
getConnection
function getConnection(connectionString) { return new Promise(function(resolve, reject) { // If connectionString is null or undefined, return an error. if (_.isEmpty(connectionString)) { return reject('getConnection must be called with a mongo connection string'); } // Check if a connection already exists for the provided connectionString. var pool = _.findWhere(connections, { connectionString: connectionString }); // If a connection pool was found, resolve the promise with it. if (pool) { return resolve(pool.db); } // If the connection pool has not been instantiated, // instantiate it and return the connection. MongoClient.connect(connectionString, function(err, database) { if (err) { return reject(err); } // Store the connection in the connections array. connections.push({ connectionString: connectionString, db: database }); return resolve(database); }); }); }
javascript
function getConnection(connectionString) { return new Promise(function(resolve, reject) { // If connectionString is null or undefined, return an error. if (_.isEmpty(connectionString)) { return reject('getConnection must be called with a mongo connection string'); } // Check if a connection already exists for the provided connectionString. var pool = _.findWhere(connections, { connectionString: connectionString }); // If a connection pool was found, resolve the promise with it. if (pool) { return resolve(pool.db); } // If the connection pool has not been instantiated, // instantiate it and return the connection. MongoClient.connect(connectionString, function(err, database) { if (err) { return reject(err); } // Store the connection in the connections array. connections.push({ connectionString: connectionString, db: database }); return resolve(database); }); }); }
[ "function", "getConnection", "(", "connectionString", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "// If connectionString is null or undefined, return an error.", "if", "(", "_", ".", "isEmpty", "(", "connectionString", ")", ")", "{", "return", "reject", "(", "'getConnection must be called with a mongo connection string'", ")", ";", "}", "// Check if a connection already exists for the provided connectionString.", "var", "pool", "=", "_", ".", "findWhere", "(", "connections", ",", "{", "connectionString", ":", "connectionString", "}", ")", ";", "// If a connection pool was found, resolve the promise with it.", "if", "(", "pool", ")", "{", "return", "resolve", "(", "pool", ".", "db", ")", ";", "}", "// If the connection pool has not been instantiated,", "// instantiate it and return the connection.", "MongoClient", ".", "connect", "(", "connectionString", ",", "function", "(", "err", ",", "database", ")", "{", "if", "(", "err", ")", "{", "return", "reject", "(", "err", ")", ";", "}", "// Store the connection in the connections array.", "connections", ".", "push", "(", "{", "connectionString", ":", "connectionString", ",", "db", ":", "database", "}", ")", ";", "return", "resolve", "(", "database", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Gets a Mongo connection from the pool. If the connection pool has not been instantiated yet, it is first instantiated and a connection is returned. @returns {Promise|Db} - A promise object that resolves to a Mongo db object.
[ "Gets", "a", "Mongo", "connection", "from", "the", "pool", "." ]
a080b957cdda8e6969ea600e89afe74a09248419
https://github.com/toymachiner62/mongo-factory/blob/a080b957cdda8e6969ea600e89afe74a09248419/index.js#L26-L57
37,060
pmorjan/couchdb-promises
examples/attachment-stream2.js
initDB
function initDB () { return db.listDatabases() .then(response => { if (response.data.indexOf(dbName) !== -1) { // database already exists return Promise.resolve('ok') } else { // create new database return db.createDatabase(dbName).then(() => 'ok') } }) }
javascript
function initDB () { return db.listDatabases() .then(response => { if (response.data.indexOf(dbName) !== -1) { // database already exists return Promise.resolve('ok') } else { // create new database return db.createDatabase(dbName).then(() => 'ok') } }) }
[ "function", "initDB", "(", ")", "{", "return", "db", ".", "listDatabases", "(", ")", ".", "then", "(", "response", "=>", "{", "if", "(", "response", ".", "data", ".", "indexOf", "(", "dbName", ")", "!==", "-", "1", ")", "{", "// database already exists", "return", "Promise", ".", "resolve", "(", "'ok'", ")", "}", "else", "{", "// create new database", "return", "db", ".", "createDatabase", "(", "dbName", ")", ".", "then", "(", "(", ")", "=>", "'ok'", ")", "}", "}", ")", "}" ]
create db if it does not already exist @return {Promise}
[ "create", "db", "if", "it", "does", "not", "already", "exist" ]
7472ea272e417970ab2b036739909e227aefd296
https://github.com/pmorjan/couchdb-promises/blob/7472ea272e417970ab2b036739909e227aefd296/examples/attachment-stream2.js#L13-L24
37,061
pmorjan/couchdb-promises
examples/attachment-stream2.js
initDocument
function initDocument (docName) { return db.getDocument(dbName, docName) .then(response => response.data._rev) // document already exists .catch(response => { if (response.status === 404) { // create new document return db.createDocument(dbName, {foo: 'bar'}, docName) .then(response => response.data.rev) } else { // real error return Promise.reject(response) } }) }
javascript
function initDocument (docName) { return db.getDocument(dbName, docName) .then(response => response.data._rev) // document already exists .catch(response => { if (response.status === 404) { // create new document return db.createDocument(dbName, {foo: 'bar'}, docName) .then(response => response.data.rev) } else { // real error return Promise.reject(response) } }) }
[ "function", "initDocument", "(", "docName", ")", "{", "return", "db", ".", "getDocument", "(", "dbName", ",", "docName", ")", ".", "then", "(", "response", "=>", "response", ".", "data", ".", "_rev", ")", "// document already exists", ".", "catch", "(", "response", "=>", "{", "if", "(", "response", ".", "status", "===", "404", ")", "{", "// create new document", "return", "db", ".", "createDocument", "(", "dbName", ",", "{", "foo", ":", "'bar'", "}", ",", "docName", ")", ".", "then", "(", "response", "=>", "response", ".", "data", ".", "rev", ")", "}", "else", "{", "// real error", "return", "Promise", ".", "reject", "(", "response", ")", "}", "}", ")", "}" ]
get existing document or create new @param {String} docName @return {Promise} - fulfilled with document revision
[ "get", "existing", "document", "or", "create", "new" ]
7472ea272e417970ab2b036739909e227aefd296
https://github.com/pmorjan/couchdb-promises/blob/7472ea272e417970ab2b036739909e227aefd296/examples/attachment-stream2.js#L31-L44
37,062
pmorjan/couchdb-promises
examples/attachment-stream2.js
addAttachment
function addAttachment (docName, docRev) { const args = os.type() === 'Darwin' ? ['-l', '1'] : ['-b', '-n', '1'] const stream = spawn('top', args).stdout const attName = `top-${Date.now()}.txt` const attContentType = 'text/plain' return db.addAttachment(dbName, docName, attName, docRev, attContentType, stream) .then(response => response.data.rev) }
javascript
function addAttachment (docName, docRev) { const args = os.type() === 'Darwin' ? ['-l', '1'] : ['-b', '-n', '1'] const stream = spawn('top', args).stdout const attName = `top-${Date.now()}.txt` const attContentType = 'text/plain' return db.addAttachment(dbName, docName, attName, docRev, attContentType, stream) .then(response => response.data.rev) }
[ "function", "addAttachment", "(", "docName", ",", "docRev", ")", "{", "const", "args", "=", "os", ".", "type", "(", ")", "===", "'Darwin'", "?", "[", "'-l'", ",", "'1'", "]", ":", "[", "'-b'", ",", "'-n'", ",", "'1'", "]", "const", "stream", "=", "spawn", "(", "'top'", ",", "args", ")", ".", "stdout", "const", "attName", "=", "`", "${", "Date", ".", "now", "(", ")", "}", "`", "const", "attContentType", "=", "'text/plain'", "return", "db", ".", "addAttachment", "(", "dbName", ",", "docName", ",", "attName", ",", "docRev", ",", "attContentType", ",", "stream", ")", ".", "then", "(", "response", "=>", "response", ".", "data", ".", "rev", ")", "}" ]
attach the output of 'top' to the document @param {String} docName @param {String} docRev @return {Promise} - fulfilled with new document revision
[ "attach", "the", "output", "of", "top", "to", "the", "document" ]
7472ea272e417970ab2b036739909e227aefd296
https://github.com/pmorjan/couchdb-promises/blob/7472ea272e417970ab2b036739909e227aefd296/examples/attachment-stream2.js#L52-L59
37,063
DesTincT/bemlint
lib/formatters/tap.js
outputDiagnostics
function outputDiagnostics(diagnostic) { var prefix = " "; var output = prefix + "---\n"; output += prefix + yaml.safeDump(diagnostic).split("\n").join("\n" + prefix); output += "...\n"; return output; }
javascript
function outputDiagnostics(diagnostic) { var prefix = " "; var output = prefix + "---\n"; output += prefix + yaml.safeDump(diagnostic).split("\n").join("\n" + prefix); output += "...\n"; return output; }
[ "function", "outputDiagnostics", "(", "diagnostic", ")", "{", "var", "prefix", "=", "\" \"", ";", "var", "output", "=", "prefix", "+", "\"---\\n\"", ";", "output", "+=", "prefix", "+", "yaml", ".", "safeDump", "(", "diagnostic", ")", ".", "split", "(", "\"\\n\"", ")", ".", "join", "(", "\"\\n\"", "+", "prefix", ")", ";", "output", "+=", "\"...\\n\"", ";", "return", "output", ";", "}" ]
Takes in a JavaScript object and outputs a TAP diagnostics string @param {object} diagnostic JavaScript object to be embedded as YAML into output. @returns {string} diagnostics string with YAML embedded - TAP version 13 compliant
[ "Takes", "in", "a", "JavaScript", "object", "and", "outputs", "a", "TAP", "diagnostics", "string" ]
e30963deae2c93f1d5e925389339ad740250dd68
https://github.com/DesTincT/bemlint/blob/e30963deae2c93f1d5e925389339ad740250dd68/lib/formatters/tap.js#L31-L37
37,064
thumbsup/theme-classic
theme/public/lightgallery/js/lightgallery-all.js
function(element) { this.core = $(element).data('lightGallery'); this.$el = $(element); // Execute only if items are above 1 if (this.core.$items.length < 2) { return false; } this.core.s = $.extend({}, defaults, this.core.s); this.interval = false; // Identify if slide happened from autoplay this.fromAuto = true; // Identify if autoplay canceled from touch/drag this.canceledOnTouch = false; // save fourceautoplay value this.fourceAutoplayTemp = this.core.s.fourceAutoplay; // do not allow progress bar if browser does not support css3 transitions if (!this.core.doCss()) { this.core.s.progressBar = false; } this.init(); return this; }
javascript
function(element) { this.core = $(element).data('lightGallery'); this.$el = $(element); // Execute only if items are above 1 if (this.core.$items.length < 2) { return false; } this.core.s = $.extend({}, defaults, this.core.s); this.interval = false; // Identify if slide happened from autoplay this.fromAuto = true; // Identify if autoplay canceled from touch/drag this.canceledOnTouch = false; // save fourceautoplay value this.fourceAutoplayTemp = this.core.s.fourceAutoplay; // do not allow progress bar if browser does not support css3 transitions if (!this.core.doCss()) { this.core.s.progressBar = false; } this.init(); return this; }
[ "function", "(", "element", ")", "{", "this", ".", "core", "=", "$", "(", "element", ")", ".", "data", "(", "'lightGallery'", ")", ";", "this", ".", "$el", "=", "$", "(", "element", ")", ";", "// Execute only if items are above 1\r", "if", "(", "this", ".", "core", ".", "$items", ".", "length", "<", "2", ")", "{", "return", "false", ";", "}", "this", ".", "core", ".", "s", "=", "$", ".", "extend", "(", "{", "}", ",", "defaults", ",", "this", ".", "core", ".", "s", ")", ";", "this", ".", "interval", "=", "false", ";", "// Identify if slide happened from autoplay\r", "this", ".", "fromAuto", "=", "true", ";", "// Identify if autoplay canceled from touch/drag\r", "this", ".", "canceledOnTouch", "=", "false", ";", "// save fourceautoplay value\r", "this", ".", "fourceAutoplayTemp", "=", "this", ".", "core", ".", "s", ".", "fourceAutoplay", ";", "// do not allow progress bar if browser does not support css3 transitions\r", "if", "(", "!", "this", ".", "core", ".", "doCss", "(", ")", ")", "{", "this", ".", "core", ".", "s", ".", "progressBar", "=", "false", ";", "}", "this", ".", "init", "(", ")", ";", "return", "this", ";", "}" ]
Creates the autoplay plugin. @param {object} element - lightGallery element
[ "Creates", "the", "autoplay", "plugin", "." ]
9fe4545a0e8552969ff7daf34f95fc5c05e7c22c
https://github.com/thumbsup/theme-classic/blob/9fe4545a0e8552969ff7daf34f95fc5c05e7c22c/theme/public/lightgallery/js/lightgallery-all.js#L1327-L1358
37,065
Mike96Angelo/Generate-JS
generate.js
getFunctionName
function getFunctionName(func) { if (func.name !== void(0)) { return func.name; } // Else use IE Shim var funcNameMatch = func.toString() .match(/function\s*([^\s]*)\s*\(/); func.name = (funcNameMatch && funcNameMatch[1]) || ''; return func.name; }
javascript
function getFunctionName(func) { if (func.name !== void(0)) { return func.name; } // Else use IE Shim var funcNameMatch = func.toString() .match(/function\s*([^\s]*)\s*\(/); func.name = (funcNameMatch && funcNameMatch[1]) || ''; return func.name; }
[ "function", "getFunctionName", "(", "func", ")", "{", "if", "(", "func", ".", "name", "!==", "void", "(", "0", ")", ")", "{", "return", "func", ".", "name", ";", "}", "// Else use IE Shim", "var", "funcNameMatch", "=", "func", ".", "toString", "(", ")", ".", "match", "(", "/", "function\\s*([^\\s]*)\\s*\\(", "/", ")", ";", "func", ".", "name", "=", "(", "funcNameMatch", "&&", "funcNameMatch", "[", "1", "]", ")", "||", "''", ";", "return", "func", ".", "name", ";", "}" ]
Returns the name of function 'func'. @param {Function} func Any function. @return {String} Name of 'func'.
[ "Returns", "the", "name", "of", "function", "func", "." ]
f207fa08dad991f6cd54e47d4a775f2c70a7aee5
https://github.com/Mike96Angelo/Generate-JS/blob/f207fa08dad991f6cd54e47d4a775f2c70a7aee5/generate.js#L36-L45
37,066
Mike96Angelo/Generate-JS
generate.js
isGetSet
function isGetSet(obj) { var keys, length; if (obj && typeof obj === 'object') { keys = Object.getOwnPropertyNames(obj) .sort(); length = keys.length; if ((length === 1 && (keys[0] === 'get' && typeof obj.get === 'function' || keys[0] === 'set' && typeof obj.set === 'function' )) || (length === 2 && (keys[0] === 'get' && typeof obj.get === 'function' && keys[1] === 'set' && typeof obj.set === 'function' ))) { return true; } } return false; }
javascript
function isGetSet(obj) { var keys, length; if (obj && typeof obj === 'object') { keys = Object.getOwnPropertyNames(obj) .sort(); length = keys.length; if ((length === 1 && (keys[0] === 'get' && typeof obj.get === 'function' || keys[0] === 'set' && typeof obj.set === 'function' )) || (length === 2 && (keys[0] === 'get' && typeof obj.get === 'function' && keys[1] === 'set' && typeof obj.set === 'function' ))) { return true; } } return false; }
[ "function", "isGetSet", "(", "obj", ")", "{", "var", "keys", ",", "length", ";", "if", "(", "obj", "&&", "typeof", "obj", "===", "'object'", ")", "{", "keys", "=", "Object", ".", "getOwnPropertyNames", "(", "obj", ")", ".", "sort", "(", ")", ";", "length", "=", "keys", ".", "length", ";", "if", "(", "(", "length", "===", "1", "&&", "(", "keys", "[", "0", "]", "===", "'get'", "&&", "typeof", "obj", ".", "get", "===", "'function'", "||", "keys", "[", "0", "]", "===", "'set'", "&&", "typeof", "obj", ".", "set", "===", "'function'", ")", ")", "||", "(", "length", "===", "2", "&&", "(", "keys", "[", "0", "]", "===", "'get'", "&&", "typeof", "obj", ".", "get", "===", "'function'", "&&", "keys", "[", "1", "]", "===", "'set'", "&&", "typeof", "obj", ".", "set", "===", "'function'", ")", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Returns true if 'obj' is an object containing only get and set functions, false otherwise. @param {Any} obj Value to be tested. @return {Boolean} true or false.
[ "Returns", "true", "if", "obj", "is", "an", "object", "containing", "only", "get", "and", "set", "functions", "false", "otherwise", "." ]
f207fa08dad991f6cd54e47d4a775f2c70a7aee5
https://github.com/Mike96Angelo/Generate-JS/blob/f207fa08dad991f6cd54e47d4a775f2c70a7aee5/generate.js#L52-L71
37,067
Mike96Angelo/Generate-JS
generate.js
defineObjectProperties
function defineObjectProperties(obj, descriptor, properties) { var setProperties = {}, i, keys, length, p = properties || descriptor, d = properties && descriptor; properties = (p && typeof p === 'object') ? p : {}; descriptor = (d && typeof d === 'object') ? d : {}; keys = Object.getOwnPropertyNames(properties); length = keys.length; for (i = 0; i < length; i++) { if (isGetSet(properties[keys[i]])) { setProperties[keys[i]] = { configurable: !!descriptor.configurable, enumerable: !!descriptor.enumerable, get: properties[keys[i]].get, set: properties[keys[i]].set }; } else { setProperties[keys[i]] = { configurable: !!descriptor.configurable, enumerable: !!descriptor.enumerable, writable: !!descriptor.writable, value: properties[keys[i]] }; } } Object.defineProperties(obj, setProperties); return obj; }
javascript
function defineObjectProperties(obj, descriptor, properties) { var setProperties = {}, i, keys, length, p = properties || descriptor, d = properties && descriptor; properties = (p && typeof p === 'object') ? p : {}; descriptor = (d && typeof d === 'object') ? d : {}; keys = Object.getOwnPropertyNames(properties); length = keys.length; for (i = 0; i < length; i++) { if (isGetSet(properties[keys[i]])) { setProperties[keys[i]] = { configurable: !!descriptor.configurable, enumerable: !!descriptor.enumerable, get: properties[keys[i]].get, set: properties[keys[i]].set }; } else { setProperties[keys[i]] = { configurable: !!descriptor.configurable, enumerable: !!descriptor.enumerable, writable: !!descriptor.writable, value: properties[keys[i]] }; } } Object.defineProperties(obj, setProperties); return obj; }
[ "function", "defineObjectProperties", "(", "obj", ",", "descriptor", ",", "properties", ")", "{", "var", "setProperties", "=", "{", "}", ",", "i", ",", "keys", ",", "length", ",", "p", "=", "properties", "||", "descriptor", ",", "d", "=", "properties", "&&", "descriptor", ";", "properties", "=", "(", "p", "&&", "typeof", "p", "===", "'object'", ")", "?", "p", ":", "{", "}", ";", "descriptor", "=", "(", "d", "&&", "typeof", "d", "===", "'object'", ")", "?", "d", ":", "{", "}", ";", "keys", "=", "Object", ".", "getOwnPropertyNames", "(", "properties", ")", ";", "length", "=", "keys", ".", "length", ";", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "if", "(", "isGetSet", "(", "properties", "[", "keys", "[", "i", "]", "]", ")", ")", "{", "setProperties", "[", "keys", "[", "i", "]", "]", "=", "{", "configurable", ":", "!", "!", "descriptor", ".", "configurable", ",", "enumerable", ":", "!", "!", "descriptor", ".", "enumerable", ",", "get", ":", "properties", "[", "keys", "[", "i", "]", "]", ".", "get", ",", "set", ":", "properties", "[", "keys", "[", "i", "]", "]", ".", "set", "}", ";", "}", "else", "{", "setProperties", "[", "keys", "[", "i", "]", "]", "=", "{", "configurable", ":", "!", "!", "descriptor", ".", "configurable", ",", "enumerable", ":", "!", "!", "descriptor", ".", "enumerable", ",", "writable", ":", "!", "!", "descriptor", ".", "writable", ",", "value", ":", "properties", "[", "keys", "[", "i", "]", "]", "}", ";", "}", "}", "Object", ".", "defineProperties", "(", "obj", ",", "setProperties", ")", ";", "return", "obj", ";", "}" ]
Defines properties on 'obj'. @param {Object} obj An object that 'properties' will be attached to. @param {Object} descriptor Optional object descriptor that will be applied to all attaching properties on 'properties'. @param {Object} properties An object who's properties will be attached to 'obj'. @return {Generator} 'obj'.
[ "Defines", "properties", "on", "obj", "." ]
f207fa08dad991f6cd54e47d4a775f2c70a7aee5
https://github.com/Mike96Angelo/Generate-JS/blob/f207fa08dad991f6cd54e47d4a775f2c70a7aee5/generate.js#L80-L114
37,068
Mike96Angelo/Generate-JS
generate.js
isGeneration
function isGeneration(generator) { assertTypeError(generator, 'function'); var _ = this; return _.prototype.isPrototypeOf(generator.prototype); }
javascript
function isGeneration(generator) { assertTypeError(generator, 'function'); var _ = this; return _.prototype.isPrototypeOf(generator.prototype); }
[ "function", "isGeneration", "(", "generator", ")", "{", "assertTypeError", "(", "generator", ",", "'function'", ")", ";", "var", "_", "=", "this", ";", "return", "_", ".", "prototype", ".", "isPrototypeOf", "(", "generator", ".", "prototype", ")", ";", "}" ]
Returns true if 'generator' was generated by this Generator. @param {Generator} generator A Generator. @return {Boolean} true or false.
[ "Returns", "true", "if", "generator", "was", "generated", "by", "this", "Generator", "." ]
f207fa08dad991f6cd54e47d4a775f2c70a7aee5
https://github.com/Mike96Angelo/Generate-JS/blob/f207fa08dad991f6cd54e47d4a775f2c70a7aee5/generate.js#L155-L161
37,069
vesln/b
lib/child-bench/index.js
ChildBench
function ChildBench(name, file, opts){ opts || (opts = {}) var args = [file] var options = {} // extra process arguments if (opts.args) args.push.apply(args, opts.args) // bench subject if (opts.subject) options.env = { subject: opts.subject } var reqs = this.requests = {} this.child = fork(runner, args, options) .on('message', function(msg){ var result = reqs[msg.id] msg.value.name = name switch (msg.type) { case 'result': result.write(msg.value); break case 'error': var err = new Error(msg.value.message) err.stack = msg.value.stack result.error(err) break default: throw new Error('unknown message ' + JSON.stringify(msg)) } }) // clean up .on('exit', function(code){ if (code > 0) process.exit(code) }) }
javascript
function ChildBench(name, file, opts){ opts || (opts = {}) var args = [file] var options = {} // extra process arguments if (opts.args) args.push.apply(args, opts.args) // bench subject if (opts.subject) options.env = { subject: opts.subject } var reqs = this.requests = {} this.child = fork(runner, args, options) .on('message', function(msg){ var result = reqs[msg.id] msg.value.name = name switch (msg.type) { case 'result': result.write(msg.value); break case 'error': var err = new Error(msg.value.message) err.stack = msg.value.stack result.error(err) break default: throw new Error('unknown message ' + JSON.stringify(msg)) } }) // clean up .on('exit', function(code){ if (code > 0) process.exit(code) }) }
[ "function", "ChildBench", "(", "name", ",", "file", ",", "opts", ")", "{", "opts", "||", "(", "opts", "=", "{", "}", ")", "var", "args", "=", "[", "file", "]", "var", "options", "=", "{", "}", "// extra process arguments", "if", "(", "opts", ".", "args", ")", "args", ".", "push", ".", "apply", "(", "args", ",", "opts", ".", "args", ")", "// bench subject", "if", "(", "opts", ".", "subject", ")", "options", ".", "env", "=", "{", "subject", ":", "opts", ".", "subject", "}", "var", "reqs", "=", "this", ".", "requests", "=", "{", "}", "this", ".", "child", "=", "fork", "(", "runner", ",", "args", ",", "options", ")", ".", "on", "(", "'message'", ",", "function", "(", "msg", ")", "{", "var", "result", "=", "reqs", "[", "msg", ".", "id", "]", "msg", ".", "value", ".", "name", "=", "name", "switch", "(", "msg", ".", "type", ")", "{", "case", "'result'", ":", "result", ".", "write", "(", "msg", ".", "value", ")", ";", "break", "case", "'error'", ":", "var", "err", "=", "new", "Error", "(", "msg", ".", "value", ".", "message", ")", "err", ".", "stack", "=", "msg", ".", "value", ".", "stack", "result", ".", "error", "(", "err", ")", "break", "default", ":", "throw", "new", "Error", "(", "'unknown message '", "+", "JSON", ".", "stringify", "(", "msg", ")", ")", "}", "}", ")", "// clean up", ".", "on", "(", "'exit'", ",", "function", "(", "code", ")", "{", "if", "(", "code", ">", "0", ")", "process", ".", "exit", "(", "code", ")", "}", ")", "}" ]
create benchmark that runs in a separate process implements a similar API to benchmark.js @param {String} name @param {String} file absolute path @param {Object} [opts]
[ "create", "benchmark", "that", "runs", "in", "a", "separate", "process", "implements", "a", "similar", "API", "to", "benchmark", ".", "js" ]
9bddf3032885ae51095946a2f153e5b03cbec332
https://github.com/vesln/b/blob/9bddf3032885ae51095946a2f153e5b03cbec332/lib/child-bench/index.js#L17-L46
37,070
perezpaya/irelia
lib/main.js
function(settings) { this.key = settings.key; this.endpoint = settings.endpoint; if (this.endpoint) { console.log( 'Irelia has been updated to version 0.2 where we are using a new url system. You will have to update your config for using it. Check documentation at: ' .cyan + 'https://github.com/alexperezpaya/irelia'.underline.blue); } if (settings.debug === true) { this.debug = true; } this.secure = (settings.secure) ? settings.secure : false; this.host = settings.host; this.path = settings.path; return this; }
javascript
function(settings) { this.key = settings.key; this.endpoint = settings.endpoint; if (this.endpoint) { console.log( 'Irelia has been updated to version 0.2 where we are using a new url system. You will have to update your config for using it. Check documentation at: ' .cyan + 'https://github.com/alexperezpaya/irelia'.underline.blue); } if (settings.debug === true) { this.debug = true; } this.secure = (settings.secure) ? settings.secure : false; this.host = settings.host; this.path = settings.path; return this; }
[ "function", "(", "settings", ")", "{", "this", ".", "key", "=", "settings", ".", "key", ";", "this", ".", "endpoint", "=", "settings", ".", "endpoint", ";", "if", "(", "this", ".", "endpoint", ")", "{", "console", ".", "log", "(", "'Irelia has been updated to version 0.2 where we are using a new url system. You will have to update your config for using it. Check documentation at: '", ".", "cyan", "+", "'https://github.com/alexperezpaya/irelia'", ".", "underline", ".", "blue", ")", ";", "}", "if", "(", "settings", ".", "debug", "===", "true", ")", "{", "this", ".", "debug", "=", "true", ";", "}", "this", ".", "secure", "=", "(", "settings", ".", "secure", ")", "?", "settings", ".", "secure", ":", "false", ";", "this", ".", "host", "=", "settings", ".", "host", ";", "this", ".", "path", "=", "settings", ".", "path", ";", "return", "this", ";", "}" ]
Inits class and saves settings in it
[ "Inits", "class", "and", "saves", "settings", "in", "it" ]
6c1237fe7f7ed0483fdfeda414dcb69222d4b567
https://github.com/perezpaya/irelia/blob/6c1237fe7f7ed0483fdfeda414dcb69222d4b567/lib/main.js#L12-L34
37,071
rewgt/shadow-widget
src/react_widget.js
getLineInfo
function getLineInfo(bRet,bNum,code) { var numCount = 0, hintCount = 0; var bLn = code.split(ln_re_), len = bLn.length; var iLastLn = -1, sLastNum = '0'; for (var i=0; i < len; i++) { var item = bLn[i], hasHint = false; var sNew = item.replace(hint_re_, function(sMatch) { hasHint = true; hintCount += 1; var iTmp = sMatch.length; if (iLastLn + 1 == i) { iLastLn = i; sLastNum = (parseInt(sLastNum) + 1) + ''; iTmp -= 1; sLastNum = sLastNum.slice(-iTmp); // trim to same width: ~~ if (sLastNum.length < iTmp) sLastNum = (new Array(iTmp-sLastNum.length+1)).join('0') + sLastNum; bRet[i] = sLastNum + '!'; } else bRet[i] = (new Array(iTmp)).join(' ') + '!'; return ''; }); if (hasHint) bLn[i] = sNew; else { var hasNum = false; var sNew2 = item.replace(num_re_, function(sMatch) { hasNum = true; numCount += 1; sLastNum = bRet[i] = sMatch.slice(0,-1); iLastLn = i; return ''; }); if (hasNum) bLn[i] = sNew2; } } if (!bRet.length) // no changing return code; else { if (!hintCount && numCount <= 1) { // avoid accident preceed-number bRet.splice(0); return code; // no changing } else { if (numCount) bNum.push(numCount); return bLn.join('\n'); } } }
javascript
function getLineInfo(bRet,bNum,code) { var numCount = 0, hintCount = 0; var bLn = code.split(ln_re_), len = bLn.length; var iLastLn = -1, sLastNum = '0'; for (var i=0; i < len; i++) { var item = bLn[i], hasHint = false; var sNew = item.replace(hint_re_, function(sMatch) { hasHint = true; hintCount += 1; var iTmp = sMatch.length; if (iLastLn + 1 == i) { iLastLn = i; sLastNum = (parseInt(sLastNum) + 1) + ''; iTmp -= 1; sLastNum = sLastNum.slice(-iTmp); // trim to same width: ~~ if (sLastNum.length < iTmp) sLastNum = (new Array(iTmp-sLastNum.length+1)).join('0') + sLastNum; bRet[i] = sLastNum + '!'; } else bRet[i] = (new Array(iTmp)).join(' ') + '!'; return ''; }); if (hasHint) bLn[i] = sNew; else { var hasNum = false; var sNew2 = item.replace(num_re_, function(sMatch) { hasNum = true; numCount += 1; sLastNum = bRet[i] = sMatch.slice(0,-1); iLastLn = i; return ''; }); if (hasNum) bLn[i] = sNew2; } } if (!bRet.length) // no changing return code; else { if (!hintCount && numCount <= 1) { // avoid accident preceed-number bRet.splice(0); return code; // no changing } else { if (numCount) bNum.push(numCount); return bLn.join('\n'); } } }
[ "function", "getLineInfo", "(", "bRet", ",", "bNum", ",", "code", ")", "{", "var", "numCount", "=", "0", ",", "hintCount", "=", "0", ";", "var", "bLn", "=", "code", ".", "split", "(", "ln_re_", ")", ",", "len", "=", "bLn", ".", "length", ";", "var", "iLastLn", "=", "-", "1", ",", "sLastNum", "=", "'0'", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "item", "=", "bLn", "[", "i", "]", ",", "hasHint", "=", "false", ";", "var", "sNew", "=", "item", ".", "replace", "(", "hint_re_", ",", "function", "(", "sMatch", ")", "{", "hasHint", "=", "true", ";", "hintCount", "+=", "1", ";", "var", "iTmp", "=", "sMatch", ".", "length", ";", "if", "(", "iLastLn", "+", "1", "==", "i", ")", "{", "iLastLn", "=", "i", ";", "sLastNum", "=", "(", "parseInt", "(", "sLastNum", ")", "+", "1", ")", "+", "''", ";", "iTmp", "-=", "1", ";", "sLastNum", "=", "sLastNum", ".", "slice", "(", "-", "iTmp", ")", ";", "// trim to same width: ~~", "if", "(", "sLastNum", ".", "length", "<", "iTmp", ")", "sLastNum", "=", "(", "new", "Array", "(", "iTmp", "-", "sLastNum", ".", "length", "+", "1", ")", ")", ".", "join", "(", "'0'", ")", "+", "sLastNum", ";", "bRet", "[", "i", "]", "=", "sLastNum", "+", "'!'", ";", "}", "else", "bRet", "[", "i", "]", "=", "(", "new", "Array", "(", "iTmp", ")", ")", ".", "join", "(", "' '", ")", "+", "'!'", ";", "return", "''", ";", "}", ")", ";", "if", "(", "hasHint", ")", "bLn", "[", "i", "]", "=", "sNew", ";", "else", "{", "var", "hasNum", "=", "false", ";", "var", "sNew2", "=", "item", ".", "replace", "(", "num_re_", ",", "function", "(", "sMatch", ")", "{", "hasNum", "=", "true", ";", "numCount", "+=", "1", ";", "sLastNum", "=", "bRet", "[", "i", "]", "=", "sMatch", ".", "slice", "(", "0", ",", "-", "1", ")", ";", "iLastLn", "=", "i", ";", "return", "''", ";", "}", ")", ";", "if", "(", "hasNum", ")", "bLn", "[", "i", "]", "=", "sNew2", ";", "}", "}", "if", "(", "!", "bRet", ".", "length", ")", "// no changing", "return", "code", ";", "else", "{", "if", "(", "!", "hintCount", "&&", "numCount", "<=", "1", ")", "{", "// avoid accident preceed-number", "bRet", ".", "splice", "(", "0", ")", ";", "return", "code", ";", "// no changing", "}", "else", "{", "if", "(", "numCount", ")", "bNum", ".", "push", "(", "numCount", ")", ";", "return", "bLn", ".", "join", "(", "'\\n'", ")", ";", "}", "}", "}" ]
start with '~~' means highlight this line
[ "start", "with", "~~", "means", "highlight", "this", "line" ]
5baa1f563d647b6d1ecb6c108bc5bcef150ea683
https://github.com/rewgt/shadow-widget/blob/5baa1f563d647b6d1ecb6c108bc5bcef150ea683/src/react_widget.js#L1922-L1968
37,072
pfmooney/node-ldap-filter
lib/helpers.js
getAttrValue
function getAttrValue(obj, attr, strictCase) { assert.object(obj); assert.string(attr); // Check for exact case match first if (obj.hasOwnProperty(attr)) { return obj[attr]; } else if (strictCase) { return undefined; } // Perform case-insensitive enumeration after that var lower = attr.toLowerCase(); var result; Object.getOwnPropertyNames(obj).some(function (name) { if (name.toLowerCase() === lower) { result = obj[name]; return true; } return false; }); return result; }
javascript
function getAttrValue(obj, attr, strictCase) { assert.object(obj); assert.string(attr); // Check for exact case match first if (obj.hasOwnProperty(attr)) { return obj[attr]; } else if (strictCase) { return undefined; } // Perform case-insensitive enumeration after that var lower = attr.toLowerCase(); var result; Object.getOwnPropertyNames(obj).some(function (name) { if (name.toLowerCase() === lower) { result = obj[name]; return true; } return false; }); return result; }
[ "function", "getAttrValue", "(", "obj", ",", "attr", ",", "strictCase", ")", "{", "assert", ".", "object", "(", "obj", ")", ";", "assert", ".", "string", "(", "attr", ")", ";", "// Check for exact case match first", "if", "(", "obj", ".", "hasOwnProperty", "(", "attr", ")", ")", "{", "return", "obj", "[", "attr", "]", ";", "}", "else", "if", "(", "strictCase", ")", "{", "return", "undefined", ";", "}", "// Perform case-insensitive enumeration after that", "var", "lower", "=", "attr", ".", "toLowerCase", "(", ")", ";", "var", "result", ";", "Object", ".", "getOwnPropertyNames", "(", "obj", ")", ".", "some", "(", "function", "(", "name", ")", "{", "if", "(", "name", ".", "toLowerCase", "(", ")", "===", "lower", ")", "{", "result", "=", "obj", "[", "name", "]", ";", "return", "true", ";", "}", "return", "false", ";", "}", ")", ";", "return", "result", ";", "}" ]
Fetch value for named object attribute. @param {Object} obj object to fetch value from @param {String} attr name of attribute to fetch @param {Boolean} strictCase attribute name is case-sensitive. default: false
[ "Fetch", "value", "for", "named", "object", "attribute", "." ]
daa5a5d5d11c73582275cc75aa9f3ff839b1ab06
https://github.com/pfmooney/node-ldap-filter/blob/daa5a5d5d11c73582275cc75aa9f3ff839b1ab06/lib/helpers.js#L103-L124
37,073
exsilium/xmodem.js
lib/index.js
function(callback, delay, repetitions) { var x = 0; var intervalID = setInterval(function () { if (++x === repetitions) { clearInterval(intervalID); receive_interval_timer = false; } callback(); }, delay); return intervalID; }
javascript
function(callback, delay, repetitions) { var x = 0; var intervalID = setInterval(function () { if (++x === repetitions) { clearInterval(intervalID); receive_interval_timer = false; } callback(); }, delay); return intervalID; }
[ "function", "(", "callback", ",", "delay", ",", "repetitions", ")", "{", "var", "x", "=", "0", ";", "var", "intervalID", "=", "setInterval", "(", "function", "(", ")", "{", "if", "(", "++", "x", "===", "repetitions", ")", "{", "clearInterval", "(", "intervalID", ")", ";", "receive_interval_timer", "=", "false", ";", "}", "callback", "(", ")", ";", "}", ",", "delay", ")", ";", "return", "intervalID", ";", "}" ]
Internal helper function for scoped intervals @private
[ "Internal", "helper", "function", "for", "scoped", "intervals" ]
045ea33cbe62f0820891000daf89a46e186fd1a0
https://github.com/exsilium/xmodem.js/blob/045ea33cbe62f0820891000daf89a46e186fd1a0/lib/index.js#L352-L362
37,074
DesTincT/bemlint
lib/ignored-paths.js
removePrefixFromFilepath
function removePrefixFromFilepath(filepath, prefix) { prefix += "/"; if (filepath.indexOf(prefix) === 0) { filepath = filepath.substr(prefix.length); } return filepath; }
javascript
function removePrefixFromFilepath(filepath, prefix) { prefix += "/"; if (filepath.indexOf(prefix) === 0) { filepath = filepath.substr(prefix.length); } return filepath; }
[ "function", "removePrefixFromFilepath", "(", "filepath", ",", "prefix", ")", "{", "prefix", "+=", "\"/\"", ";", "if", "(", "filepath", ".", "indexOf", "(", "prefix", ")", "===", "0", ")", "{", "filepath", "=", "filepath", ".", "substr", "(", "prefix", ".", "length", ")", ";", "}", "return", "filepath", ";", "}" ]
Remove a prefix from a filepath @param {string} filepath Path to remove the prefix from @param {string} prefix Prefix to remove from filepath @returns {string} Normalized filepath
[ "Remove", "a", "prefix", "from", "a", "filepath" ]
e30963deae2c93f1d5e925389339ad740250dd68
https://github.com/DesTincT/bemlint/blob/e30963deae2c93f1d5e925389339ad740250dd68/lib/ignored-paths.js#L69-L75
37,075
DesTincT/bemlint
lib/ignored-paths.js
resolveFilepath
function resolveFilepath(filepath, baseDir) { if (baseDir) { var base = normalizeFilepath(path.resolve(baseDir)); filepath = removePrefixFromFilepath(filepath, base); filepath = removePrefixFromFilepath(filepath, fs.realpathSync(base)); } filepath.replace(/^\//, ""); return filepath; }
javascript
function resolveFilepath(filepath, baseDir) { if (baseDir) { var base = normalizeFilepath(path.resolve(baseDir)); filepath = removePrefixFromFilepath(filepath, base); filepath = removePrefixFromFilepath(filepath, fs.realpathSync(base)); } filepath.replace(/^\//, ""); return filepath; }
[ "function", "resolveFilepath", "(", "filepath", ",", "baseDir", ")", "{", "if", "(", "baseDir", ")", "{", "var", "base", "=", "normalizeFilepath", "(", "path", ".", "resolve", "(", "baseDir", ")", ")", ";", "filepath", "=", "removePrefixFromFilepath", "(", "filepath", ",", "base", ")", ";", "filepath", "=", "removePrefixFromFilepath", "(", "filepath", ",", "fs", ".", "realpathSync", "(", "base", ")", ")", ";", "}", "filepath", ".", "replace", "(", "/", "^\\/", "/", ",", "\"\"", ")", ";", "return", "filepath", ";", "}" ]
Resolves a filepath @param {string} filepath Path resolve @param {string} baseDir Base directory to resolve the filepath from @returns {string} Resolved filepath
[ "Resolves", "a", "filepath" ]
e30963deae2c93f1d5e925389339ad740250dd68
https://github.com/DesTincT/bemlint/blob/e30963deae2c93f1d5e925389339ad740250dd68/lib/ignored-paths.js#L83-L91
37,076
DesTincT/bemlint
lib/ignored-paths.js
addIgnoreFile
function addIgnoreFile(ig, filepath) { if (fs.existsSync(filepath)) { ig.add(fs.readFileSync(filepath).toString()); } return ig; }
javascript
function addIgnoreFile(ig, filepath) { if (fs.existsSync(filepath)) { ig.add(fs.readFileSync(filepath).toString()); } return ig; }
[ "function", "addIgnoreFile", "(", "ig", ",", "filepath", ")", "{", "if", "(", "fs", ".", "existsSync", "(", "filepath", ")", ")", "{", "ig", ".", "add", "(", "fs", ".", "readFileSync", "(", "filepath", ")", ".", "toString", "(", ")", ")", ";", "}", "return", "ig", ";", "}" ]
add ignore file to node-ignore instance @param {object} ig, instance of node-ignore @param {string} filepath, file to add to ig @returns {array} raw ignore rules
[ "add", "ignore", "file", "to", "node", "-", "ignore", "instance" ]
e30963deae2c93f1d5e925389339ad740250dd68
https://github.com/DesTincT/bemlint/blob/e30963deae2c93f1d5e925389339ad740250dd68/lib/ignored-paths.js#L144-L149
37,077
eGavr/toc-md
lib/toc.js
function (header, prevToken) { var options = this.options; if (header.depth > options.maxDepth) return; var headerText = utils.getHeader(header.text, prevToken); if (!headerText) return; var anchor = this._getAnchor(header.text, prevToken), indent = utils.getIndent(this._usedHeaders, header.depth); this._usedHeaders.unshift({ depth: header.depth, indent: indent }); this.data += indent + options.bullet + ' [' + headerText.replace(/\\/g, '\\\\') + '](#' + anchor + ')' + EOL; }
javascript
function (header, prevToken) { var options = this.options; if (header.depth > options.maxDepth) return; var headerText = utils.getHeader(header.text, prevToken); if (!headerText) return; var anchor = this._getAnchor(header.text, prevToken), indent = utils.getIndent(this._usedHeaders, header.depth); this._usedHeaders.unshift({ depth: header.depth, indent: indent }); this.data += indent + options.bullet + ' [' + headerText.replace(/\\/g, '\\\\') + '](#' + anchor + ')' + EOL; }
[ "function", "(", "header", ",", "prevToken", ")", "{", "var", "options", "=", "this", ".", "options", ";", "if", "(", "header", ".", "depth", ">", "options", ".", "maxDepth", ")", "return", ";", "var", "headerText", "=", "utils", ".", "getHeader", "(", "header", ".", "text", ",", "prevToken", ")", ";", "if", "(", "!", "headerText", ")", "return", ";", "var", "anchor", "=", "this", ".", "_getAnchor", "(", "header", ".", "text", ",", "prevToken", ")", ",", "indent", "=", "utils", ".", "getIndent", "(", "this", ".", "_usedHeaders", ",", "header", ".", "depth", ")", ";", "this", ".", "_usedHeaders", ".", "unshift", "(", "{", "depth", ":", "header", ".", "depth", ",", "indent", ":", "indent", "}", ")", ";", "this", ".", "data", "+=", "indent", "+", "options", ".", "bullet", "+", "' ['", "+", "headerText", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "'\\\\\\\\'", ")", "+", "'](#'", "+", "anchor", "+", "')'", "+", "EOL", ";", "}" ]
Adds a TOC elemet @param {Object} [header] @param {Number} [header.depth] @param {String} [header.text] @returns {undefined} @public
[ "Adds", "a", "TOC", "elemet" ]
debdf98d7c1035eeec2a25350c5ab2263c2cd89e
https://github.com/eGavr/toc-md/blob/debdf98d7c1035eeec2a25350c5ab2263c2cd89e/lib/toc.js#L34-L52
37,078
eGavr/toc-md
lib/toc.js
function (headerText, prevToken) { if (prevToken && prevToken.type === 'paragraph' && utils.isHtml(prevToken.text)) { var anchorFromHtml = utils.getAnchorFromHtml(prevToken.text); if (anchorFromHtml) { return anchorFromHtml; } } var anchor = utils.getAnchorFromHeader(headerText, prevToken); if (this._cache.hasOwnProperty(anchor)) { anchor += '-' + this._cache[anchor]++; } else { this._cache[anchor] = 1; } return anchor; }
javascript
function (headerText, prevToken) { if (prevToken && prevToken.type === 'paragraph' && utils.isHtml(prevToken.text)) { var anchorFromHtml = utils.getAnchorFromHtml(prevToken.text); if (anchorFromHtml) { return anchorFromHtml; } } var anchor = utils.getAnchorFromHeader(headerText, prevToken); if (this._cache.hasOwnProperty(anchor)) { anchor += '-' + this._cache[anchor]++; } else { this._cache[anchor] = 1; } return anchor; }
[ "function", "(", "headerText", ",", "prevToken", ")", "{", "if", "(", "prevToken", "&&", "prevToken", ".", "type", "===", "'paragraph'", "&&", "utils", ".", "isHtml", "(", "prevToken", ".", "text", ")", ")", "{", "var", "anchorFromHtml", "=", "utils", ".", "getAnchorFromHtml", "(", "prevToken", ".", "text", ")", ";", "if", "(", "anchorFromHtml", ")", "{", "return", "anchorFromHtml", ";", "}", "}", "var", "anchor", "=", "utils", ".", "getAnchorFromHeader", "(", "headerText", ",", "prevToken", ")", ";", "if", "(", "this", ".", "_cache", ".", "hasOwnProperty", "(", "anchor", ")", ")", "{", "anchor", "+=", "'-'", "+", "this", ".", "_cache", "[", "anchor", "]", "++", ";", "}", "else", "{", "this", ".", "_cache", "[", "anchor", "]", "=", "1", ";", "}", "return", "anchor", ";", "}" ]
Returns an anchor for a given header @param {String} headerText @returns {String}
[ "Returns", "an", "anchor", "for", "a", "given", "header" ]
debdf98d7c1035eeec2a25350c5ab2263c2cd89e
https://github.com/eGavr/toc-md/blob/debdf98d7c1035eeec2a25350c5ab2263c2cd89e/lib/toc.js#L89-L106
37,079
AdamMoses-GitHub/NPMJS-googlenews-rss-scraper
index.js
parseGoogleNewsRSSData
function parseGoogleNewsRSSData(fileData) { // sanity check that this is valid google news RSS if (fileData.indexOf('[email protected]') != -1) { // set an empty array of news story objects var allGoogleNewsData = [ ]; var params = {normalizeWhitespace: true, xmlMode: true}; // load the html into the cheerio doc var cheerio = require("cheerio"); var fullDoc = cheerio.load(fileData, params); // iterate through movies and strip useful parts, add each to return object fullDoc('item').each(function(i, elem) { // load current item var itemDoc = cheerio.load(fullDoc(this).html(), params); // break out parts of interest // some sections need cleaning so do that as well var fullTitleLine = itemDoc('title').text().trim(); var fullTitleSplitIndex = fullTitleLine.lastIndexOf(' - '); var titlePart = fullTitleLine.substring(0, fullTitleSplitIndex); var sourcePart = fullTitleLine.substring(fullTitleSplitIndex + 3, fullTitleSplitIndex.length); var fullURLPart = itemDoc('link').html().trim(); var cleanURLPart = fullURLPart.split(';url=')[1]; var categoryPart = itemDoc('category').html(); if (categoryPart != null) categoryPart = categoryPart.trim(); var pubDatePart = itemDoc('pubDate').html().trim(); var fullDescriptionPart = itemDoc('description').text().trim(); var descriptionStart = fullDescriptionPart.indexOf('</font><br><font size="-1">'); var descriptionEnd = fullDescriptionPart.indexOf('</font>', descriptionStart + 1); var cleanDescriptionPart = fullDescriptionPart.substring(descriptionStart, descriptionEnd); var cleanDescriptionPart = cleanDescriptionPart.replace('</font><br><font size="-1">', ''); var cleanDescriptionPart = cleanDescriptionPart.replace('<b>...</b>', '...'); // build final object for the current news story var fullObject = { title: titlePart , source: sourcePart , category: categoryPart , pubDate: pubDatePart , fullURL: fullURLPart , cleanURL: cleanURLPart , fullDescription: fullDescriptionPart , cleanDescription: cleanDescriptionPart }; // add thew news story obejct to the array allGoogleNewsData.push(fullObject); }); // return no error state and the collected news story objects return {error: false, data: allGoogleNewsData}; } // if sanity check failed, return true error state and an error message return {error: errorFlag, errorMessage: 'Fetched RSS data does not contain expected content.', data: null}; }
javascript
function parseGoogleNewsRSSData(fileData) { // sanity check that this is valid google news RSS if (fileData.indexOf('[email protected]') != -1) { // set an empty array of news story objects var allGoogleNewsData = [ ]; var params = {normalizeWhitespace: true, xmlMode: true}; // load the html into the cheerio doc var cheerio = require("cheerio"); var fullDoc = cheerio.load(fileData, params); // iterate through movies and strip useful parts, add each to return object fullDoc('item').each(function(i, elem) { // load current item var itemDoc = cheerio.load(fullDoc(this).html(), params); // break out parts of interest // some sections need cleaning so do that as well var fullTitleLine = itemDoc('title').text().trim(); var fullTitleSplitIndex = fullTitleLine.lastIndexOf(' - '); var titlePart = fullTitleLine.substring(0, fullTitleSplitIndex); var sourcePart = fullTitleLine.substring(fullTitleSplitIndex + 3, fullTitleSplitIndex.length); var fullURLPart = itemDoc('link').html().trim(); var cleanURLPart = fullURLPart.split(';url=')[1]; var categoryPart = itemDoc('category').html(); if (categoryPart != null) categoryPart = categoryPart.trim(); var pubDatePart = itemDoc('pubDate').html().trim(); var fullDescriptionPart = itemDoc('description').text().trim(); var descriptionStart = fullDescriptionPart.indexOf('</font><br><font size="-1">'); var descriptionEnd = fullDescriptionPart.indexOf('</font>', descriptionStart + 1); var cleanDescriptionPart = fullDescriptionPart.substring(descriptionStart, descriptionEnd); var cleanDescriptionPart = cleanDescriptionPart.replace('</font><br><font size="-1">', ''); var cleanDescriptionPart = cleanDescriptionPart.replace('<b>...</b>', '...'); // build final object for the current news story var fullObject = { title: titlePart , source: sourcePart , category: categoryPart , pubDate: pubDatePart , fullURL: fullURLPart , cleanURL: cleanURLPart , fullDescription: fullDescriptionPart , cleanDescription: cleanDescriptionPart }; // add thew news story obejct to the array allGoogleNewsData.push(fullObject); }); // return no error state and the collected news story objects return {error: false, data: allGoogleNewsData}; } // if sanity check failed, return true error state and an error message return {error: errorFlag, errorMessage: 'Fetched RSS data does not contain expected content.', data: null}; }
[ "function", "parseGoogleNewsRSSData", "(", "fileData", ")", "{", "// sanity check that this is valid google news RSS\r", "if", "(", "fileData", ".", "indexOf", "(", "'[email protected]'", ")", "!=", "-", "1", ")", "{", "// set an empty array of news story objects\r", "var", "allGoogleNewsData", "=", "[", "]", ";", "var", "params", "=", "{", "normalizeWhitespace", ":", "true", ",", "xmlMode", ":", "true", "}", ";", "// load the html into the cheerio doc\r", "var", "cheerio", "=", "require", "(", "\"cheerio\"", ")", ";", "var", "fullDoc", "=", "cheerio", ".", "load", "(", "fileData", ",", "params", ")", ";", "// iterate through movies and strip useful parts, add each to return object\r", "fullDoc", "(", "'item'", ")", ".", "each", "(", "function", "(", "i", ",", "elem", ")", "{", "// load current item\r", "var", "itemDoc", "=", "cheerio", ".", "load", "(", "fullDoc", "(", "this", ")", ".", "html", "(", ")", ",", "params", ")", ";", "// break out parts of interest\r", "// some sections need cleaning so do that as well\r", "var", "fullTitleLine", "=", "itemDoc", "(", "'title'", ")", ".", "text", "(", ")", ".", "trim", "(", ")", ";", "var", "fullTitleSplitIndex", "=", "fullTitleLine", ".", "lastIndexOf", "(", "' - '", ")", ";", "var", "titlePart", "=", "fullTitleLine", ".", "substring", "(", "0", ",", "fullTitleSplitIndex", ")", ";", "var", "sourcePart", "=", "fullTitleLine", ".", "substring", "(", "fullTitleSplitIndex", "+", "3", ",", "fullTitleSplitIndex", ".", "length", ")", ";", "var", "fullURLPart", "=", "itemDoc", "(", "'link'", ")", ".", "html", "(", ")", ".", "trim", "(", ")", ";", "var", "cleanURLPart", "=", "fullURLPart", ".", "split", "(", "';url='", ")", "[", "1", "]", ";", "var", "categoryPart", "=", "itemDoc", "(", "'category'", ")", ".", "html", "(", ")", ";", "if", "(", "categoryPart", "!=", "null", ")", "categoryPart", "=", "categoryPart", ".", "trim", "(", ")", ";", "var", "pubDatePart", "=", "itemDoc", "(", "'pubDate'", ")", ".", "html", "(", ")", ".", "trim", "(", ")", ";", "var", "fullDescriptionPart", "=", "itemDoc", "(", "'description'", ")", ".", "text", "(", ")", ".", "trim", "(", ")", ";", "var", "descriptionStart", "=", "fullDescriptionPart", ".", "indexOf", "(", "'</font><br><font size=\"-1\">'", ")", ";", "var", "descriptionEnd", "=", "fullDescriptionPart", ".", "indexOf", "(", "'</font>'", ",", "descriptionStart", "+", "1", ")", ";", "var", "cleanDescriptionPart", "=", "fullDescriptionPart", ".", "substring", "(", "descriptionStart", ",", "descriptionEnd", ")", ";", "var", "cleanDescriptionPart", "=", "cleanDescriptionPart", ".", "replace", "(", "'</font><br><font size=\"-1\">'", ",", "''", ")", ";", "var", "cleanDescriptionPart", "=", "cleanDescriptionPart", ".", "replace", "(", "'<b>...</b>'", ",", "'...'", ")", ";", "// build final object for the current news story\r", "var", "fullObject", "=", "{", "title", ":", "titlePart", ",", "source", ":", "sourcePart", ",", "category", ":", "categoryPart", ",", "pubDate", ":", "pubDatePart", ",", "fullURL", ":", "fullURLPart", ",", "cleanURL", ":", "cleanURLPart", ",", "fullDescription", ":", "fullDescriptionPart", ",", "cleanDescription", ":", "cleanDescriptionPart", "}", ";", "// add thew news story obejct to the array\r", "allGoogleNewsData", ".", "push", "(", "fullObject", ")", ";", "}", ")", ";", "// return no error state and the collected news story objects\r", "return", "{", "error", ":", "false", ",", "data", ":", "allGoogleNewsData", "}", ";", "}", "// if sanity check failed, return true error state and an error message\r", "return", "{", "error", ":", "errorFlag", ",", "errorMessage", ":", "'Fetched RSS data does not contain expected content.'", ",", "data", ":", "null", "}", ";", "}" ]
parses the data returned from the RSS request returns the data object sent back via the callback
[ "parses", "the", "data", "returned", "from", "the", "RSS", "request", "returns", "the", "data", "object", "sent", "back", "via", "the", "callback" ]
df62b2d1af2d6154e3a075f30ed152282dd9e2f3
https://github.com/AdamMoses-GitHub/NPMJS-googlenews-rss-scraper/blob/df62b2d1af2d6154e3a075f30ed152282dd9e2f3/index.js#L27-L76
37,080
AdamMoses-GitHub/NPMJS-googlenews-rss-scraper
index.js
parseGoogleNewsRSSParamsErrorHelper
function parseGoogleNewsRSSParamsErrorHelper(errorMessage) { return {error: true , errorMessage: errorMessage , type: null , terms: null , url: null }; }
javascript
function parseGoogleNewsRSSParamsErrorHelper(errorMessage) { return {error: true , errorMessage: errorMessage , type: null , terms: null , url: null }; }
[ "function", "parseGoogleNewsRSSParamsErrorHelper", "(", "errorMessage", ")", "{", "return", "{", "error", ":", "true", ",", "errorMessage", ":", "errorMessage", ",", "type", ":", "null", ",", "terms", ":", "null", ",", "url", ":", "null", "}", ";", "}" ]
returns a proper return object with error and message set as specfied
[ "returns", "a", "proper", "return", "object", "with", "error", "and", "message", "set", "as", "specfied" ]
df62b2d1af2d6154e3a075f30ed152282dd9e2f3
https://github.com/AdamMoses-GitHub/NPMJS-googlenews-rss-scraper/blob/df62b2d1af2d6154e3a075f30ed152282dd9e2f3/index.js#L79-L86
37,081
AdamMoses-GitHub/NPMJS-googlenews-rss-scraper
index.js
parseGoogleNewsRSSParams
function parseGoogleNewsRSSParams(params) { // get params of interest var newsType = params.newsType; var newsTypeTerms = params.newsTypeTerms; // if missing just one parameter flag error as such if ((newsType == undefined) && (newsTypeTerms != undefined)) return parseGoogleNewsRSSParamsErrorHelper('Parameter newsTypeTerms set with no newsType set.'); if ((newsType != undefined) && (newsTypeTerms == undefined)) return parseGoogleNewsRSSParamsErrorHelper('Parameter newsType set with no newsTypeTerms set.'); // if missing both parameters, set to default if ((newsType == undefined) && (newsTypeTerms == undefined)) { newsType = 'TOPIC'; newsTypeTerms = 'HEADLINES'; } // fix case parameters newsType = newsType.toUpperCase(); newsTypeTerms = newsTypeTerms.toUpperCase(); // expand newsType name if needed if (newsType == 'T') newsType = 'TOPIC'; if (newsType == 'Q') newsType = 'QUERY'; // if an invalid newsType set flag error as such if ((newsType != 'TOPIC') && (newsType != 'QUERY')) return parseGoogleNewsRSSParamsErrorHelper('Invalid newsType parameter specified.'); // if type is topic if (newsType == 'TOPIC') { // init the short and long term names of the topic type var newsTypeTermTopicShort = null; var newsTypeTermTopicLong = null; // check the term for either short or long name and then set names accordingly if ((newsTypeTerms == 'H') || (newsTypeTerms == 'HEADLINES')) { newsTypeTermTopicShort = 'H'; newsTypeTermTopicLong = 'HEADLINES'; } if ((newsTypeTerms == 'N') || (newsTypeTerms == 'NATIONAL')) { newsTypeTermTopicShort = 'N'; newsTypeTermTopicLong = 'NATIONAL'; } if ((newsTypeTerms == 'W') || (newsTypeTerms == 'WORLD')) { newsTypeTermTopicShort = 'W'; newsTypeTermTopicLong = 'WORLD'; } if ((newsTypeTerms == 'E') || (newsTypeTerms == 'ENTERTAINMENT')) { newsTypeTermTopicShort = 'E'; newsTypeTermTopicLong = 'ENTERTAINMENT'; } if ((newsTypeTerms == 'B') || (newsTypeTerms == 'BUSINESS')) { newsTypeTermTopicShort = 'B'; newsTypeTermTopicLong = 'BUSINESS'; } if ((newsTypeTerms == 'S') || (newsTypeTerms == 'SPORTS')) { newsTypeTermTopicShort = 'S'; newsTypeTermTopicLong = 'SPORTS'; } if ((newsTypeTerms == 'T') || (newsTypeTerms == 'SCI/TECH')) { newsTypeTermTopicShort = 'T'; newsTypeTermTopicLong = 'SCI/TECH'; } if ((newsTypeTerms == 'TC') || (newsTypeTerms == 'TECHNOLOGY')) { newsTypeTermTopicShort = 'TC'; newsTypeTermTopicLong = 'TECHNOLOGY'; } // if nothing was set it was a bad topic type flag error as such if (newsTypeTermTopicShort == null) return parseGoogleNewsRSSParamsErrorHelper('Parameter newsTypeTerms is unknown for newsType TOPIC.'); // build the request URL var newsURL = 'https://news.google.com/news?cf=all&hl=en&pz=1&ned=us&topic=' + newsTypeTermTopicShort.toLowerCase() + '&output=rss'; // build the return object return {error: false, errorMessage: null, type: 'TOPIC', terms: newsTypeTermTopicLong, url: newsURL}; } // if type is query if (newsType == 'QUERY') { var newsTypeTermsQuery = newsTypeTerms.toLowerCase().replace(',', '+OR+').replace(' ', '+'); var newsURL = 'https://news.google.com/news?cf=all&hl=en&pz=1&ned=us&q=' + newsTypeTermsQuery + '&output=rss'; // build the return object return {error: false, errorMessage: null, type: 'QUERY', terms: newsTypeTerms, url: newsURL}; } // otherwise return generic error state return parseGoogleNewsRSSParamsErrorHelper('Unknown parameter error occured.'); }
javascript
function parseGoogleNewsRSSParams(params) { // get params of interest var newsType = params.newsType; var newsTypeTerms = params.newsTypeTerms; // if missing just one parameter flag error as such if ((newsType == undefined) && (newsTypeTerms != undefined)) return parseGoogleNewsRSSParamsErrorHelper('Parameter newsTypeTerms set with no newsType set.'); if ((newsType != undefined) && (newsTypeTerms == undefined)) return parseGoogleNewsRSSParamsErrorHelper('Parameter newsType set with no newsTypeTerms set.'); // if missing both parameters, set to default if ((newsType == undefined) && (newsTypeTerms == undefined)) { newsType = 'TOPIC'; newsTypeTerms = 'HEADLINES'; } // fix case parameters newsType = newsType.toUpperCase(); newsTypeTerms = newsTypeTerms.toUpperCase(); // expand newsType name if needed if (newsType == 'T') newsType = 'TOPIC'; if (newsType == 'Q') newsType = 'QUERY'; // if an invalid newsType set flag error as such if ((newsType != 'TOPIC') && (newsType != 'QUERY')) return parseGoogleNewsRSSParamsErrorHelper('Invalid newsType parameter specified.'); // if type is topic if (newsType == 'TOPIC') { // init the short and long term names of the topic type var newsTypeTermTopicShort = null; var newsTypeTermTopicLong = null; // check the term for either short or long name and then set names accordingly if ((newsTypeTerms == 'H') || (newsTypeTerms == 'HEADLINES')) { newsTypeTermTopicShort = 'H'; newsTypeTermTopicLong = 'HEADLINES'; } if ((newsTypeTerms == 'N') || (newsTypeTerms == 'NATIONAL')) { newsTypeTermTopicShort = 'N'; newsTypeTermTopicLong = 'NATIONAL'; } if ((newsTypeTerms == 'W') || (newsTypeTerms == 'WORLD')) { newsTypeTermTopicShort = 'W'; newsTypeTermTopicLong = 'WORLD'; } if ((newsTypeTerms == 'E') || (newsTypeTerms == 'ENTERTAINMENT')) { newsTypeTermTopicShort = 'E'; newsTypeTermTopicLong = 'ENTERTAINMENT'; } if ((newsTypeTerms == 'B') || (newsTypeTerms == 'BUSINESS')) { newsTypeTermTopicShort = 'B'; newsTypeTermTopicLong = 'BUSINESS'; } if ((newsTypeTerms == 'S') || (newsTypeTerms == 'SPORTS')) { newsTypeTermTopicShort = 'S'; newsTypeTermTopicLong = 'SPORTS'; } if ((newsTypeTerms == 'T') || (newsTypeTerms == 'SCI/TECH')) { newsTypeTermTopicShort = 'T'; newsTypeTermTopicLong = 'SCI/TECH'; } if ((newsTypeTerms == 'TC') || (newsTypeTerms == 'TECHNOLOGY')) { newsTypeTermTopicShort = 'TC'; newsTypeTermTopicLong = 'TECHNOLOGY'; } // if nothing was set it was a bad topic type flag error as such if (newsTypeTermTopicShort == null) return parseGoogleNewsRSSParamsErrorHelper('Parameter newsTypeTerms is unknown for newsType TOPIC.'); // build the request URL var newsURL = 'https://news.google.com/news?cf=all&hl=en&pz=1&ned=us&topic=' + newsTypeTermTopicShort.toLowerCase() + '&output=rss'; // build the return object return {error: false, errorMessage: null, type: 'TOPIC', terms: newsTypeTermTopicLong, url: newsURL}; } // if type is query if (newsType == 'QUERY') { var newsTypeTermsQuery = newsTypeTerms.toLowerCase().replace(',', '+OR+').replace(' ', '+'); var newsURL = 'https://news.google.com/news?cf=all&hl=en&pz=1&ned=us&q=' + newsTypeTermsQuery + '&output=rss'; // build the return object return {error: false, errorMessage: null, type: 'QUERY', terms: newsTypeTerms, url: newsURL}; } // otherwise return generic error state return parseGoogleNewsRSSParamsErrorHelper('Unknown parameter error occured.'); }
[ "function", "parseGoogleNewsRSSParams", "(", "params", ")", "{", "// get params of interest\r", "var", "newsType", "=", "params", ".", "newsType", ";", "var", "newsTypeTerms", "=", "params", ".", "newsTypeTerms", ";", "// if missing just one parameter flag error as such\r", "if", "(", "(", "newsType", "==", "undefined", ")", "&&", "(", "newsTypeTerms", "!=", "undefined", ")", ")", "return", "parseGoogleNewsRSSParamsErrorHelper", "(", "'Parameter newsTypeTerms set with no newsType set.'", ")", ";", "if", "(", "(", "newsType", "!=", "undefined", ")", "&&", "(", "newsTypeTerms", "==", "undefined", ")", ")", "return", "parseGoogleNewsRSSParamsErrorHelper", "(", "'Parameter newsType set with no newsTypeTerms set.'", ")", ";", "// if missing both parameters, set to default\r", "if", "(", "(", "newsType", "==", "undefined", ")", "&&", "(", "newsTypeTerms", "==", "undefined", ")", ")", "{", "newsType", "=", "'TOPIC'", ";", "newsTypeTerms", "=", "'HEADLINES'", ";", "}", "// fix case parameters\r", "newsType", "=", "newsType", ".", "toUpperCase", "(", ")", ";", "newsTypeTerms", "=", "newsTypeTerms", ".", "toUpperCase", "(", ")", ";", "// expand newsType name if needed\r", "if", "(", "newsType", "==", "'T'", ")", "newsType", "=", "'TOPIC'", ";", "if", "(", "newsType", "==", "'Q'", ")", "newsType", "=", "'QUERY'", ";", "// if an invalid newsType set flag error as such\r", "if", "(", "(", "newsType", "!=", "'TOPIC'", ")", "&&", "(", "newsType", "!=", "'QUERY'", ")", ")", "return", "parseGoogleNewsRSSParamsErrorHelper", "(", "'Invalid newsType parameter specified.'", ")", ";", "// if type is topic\r", "if", "(", "newsType", "==", "'TOPIC'", ")", "{", "// init the short and long term names of the topic type\r", "var", "newsTypeTermTopicShort", "=", "null", ";", "var", "newsTypeTermTopicLong", "=", "null", ";", "// check the term for either short or long name and then set names accordingly\r", "if", "(", "(", "newsTypeTerms", "==", "'H'", ")", "||", "(", "newsTypeTerms", "==", "'HEADLINES'", ")", ")", "{", "newsTypeTermTopicShort", "=", "'H'", ";", "newsTypeTermTopicLong", "=", "'HEADLINES'", ";", "}", "if", "(", "(", "newsTypeTerms", "==", "'N'", ")", "||", "(", "newsTypeTerms", "==", "'NATIONAL'", ")", ")", "{", "newsTypeTermTopicShort", "=", "'N'", ";", "newsTypeTermTopicLong", "=", "'NATIONAL'", ";", "}", "if", "(", "(", "newsTypeTerms", "==", "'W'", ")", "||", "(", "newsTypeTerms", "==", "'WORLD'", ")", ")", "{", "newsTypeTermTopicShort", "=", "'W'", ";", "newsTypeTermTopicLong", "=", "'WORLD'", ";", "}", "if", "(", "(", "newsTypeTerms", "==", "'E'", ")", "||", "(", "newsTypeTerms", "==", "'ENTERTAINMENT'", ")", ")", "{", "newsTypeTermTopicShort", "=", "'E'", ";", "newsTypeTermTopicLong", "=", "'ENTERTAINMENT'", ";", "}", "if", "(", "(", "newsTypeTerms", "==", "'B'", ")", "||", "(", "newsTypeTerms", "==", "'BUSINESS'", ")", ")", "{", "newsTypeTermTopicShort", "=", "'B'", ";", "newsTypeTermTopicLong", "=", "'BUSINESS'", ";", "}", "if", "(", "(", "newsTypeTerms", "==", "'S'", ")", "||", "(", "newsTypeTerms", "==", "'SPORTS'", ")", ")", "{", "newsTypeTermTopicShort", "=", "'S'", ";", "newsTypeTermTopicLong", "=", "'SPORTS'", ";", "}", "if", "(", "(", "newsTypeTerms", "==", "'T'", ")", "||", "(", "newsTypeTerms", "==", "'SCI/TECH'", ")", ")", "{", "newsTypeTermTopicShort", "=", "'T'", ";", "newsTypeTermTopicLong", "=", "'SCI/TECH'", ";", "}", "if", "(", "(", "newsTypeTerms", "==", "'TC'", ")", "||", "(", "newsTypeTerms", "==", "'TECHNOLOGY'", ")", ")", "{", "newsTypeTermTopicShort", "=", "'TC'", ";", "newsTypeTermTopicLong", "=", "'TECHNOLOGY'", ";", "}", "// if nothing was set it was a bad topic type flag error as such\r", "if", "(", "newsTypeTermTopicShort", "==", "null", ")", "return", "parseGoogleNewsRSSParamsErrorHelper", "(", "'Parameter newsTypeTerms is unknown for newsType TOPIC.'", ")", ";", "// build the request URL\r", "var", "newsURL", "=", "'https://news.google.com/news?cf=all&hl=en&pz=1&ned=us&topic='", "+", "newsTypeTermTopicShort", ".", "toLowerCase", "(", ")", "+", "'&output=rss'", ";", "// build the return object \r", "return", "{", "error", ":", "false", ",", "errorMessage", ":", "null", ",", "type", ":", "'TOPIC'", ",", "terms", ":", "newsTypeTermTopicLong", ",", "url", ":", "newsURL", "}", ";", "}", "// if type is query\r", "if", "(", "newsType", "==", "'QUERY'", ")", "{", "var", "newsTypeTermsQuery", "=", "newsTypeTerms", ".", "toLowerCase", "(", ")", ".", "replace", "(", "','", ",", "'+OR+'", ")", ".", "replace", "(", "' '", ",", "'+'", ")", ";", "var", "newsURL", "=", "'https://news.google.com/news?cf=all&hl=en&pz=1&ned=us&q='", "+", "newsTypeTermsQuery", "+", "'&output=rss'", ";", "// build the return object \r", "return", "{", "error", ":", "false", ",", "errorMessage", ":", "null", ",", "type", ":", "'QUERY'", ",", "terms", ":", "newsTypeTerms", ",", "url", ":", "newsURL", "}", ";", "}", "// otherwise return generic error state\r", "return", "parseGoogleNewsRSSParamsErrorHelper", "(", "'Unknown parameter error occured.'", ")", ";", "}" ]
parse the initial paremeters specfied by the original calling params returns well defined types for type, terms, and the calling RSS URL
[ "parse", "the", "initial", "paremeters", "specfied", "by", "the", "original", "calling", "params", "returns", "well", "defined", "types", "for", "type", "terms", "and", "the", "calling", "RSS", "URL" ]
df62b2d1af2d6154e3a075f30ed152282dd9e2f3
https://github.com/AdamMoses-GitHub/NPMJS-googlenews-rss-scraper/blob/df62b2d1af2d6154e3a075f30ed152282dd9e2f3/index.js#L90-L178
37,082
AdamMoses-GitHub/NPMJS-googlenews-rss-scraper
index.js
requestGoogleNewsRSS
function requestGoogleNewsRSS(params, callback) { // parse the params var returnObject = parseGoogleNewsRSSParams(params); returnObject.newsArray = null; // if no error from the parsing object if (!returnObject.error) { // make a request to the RSS using the URL var request = require("request"); request({uri: returnObject.url}, function(error, response, body) { // if no error in the call if (!error) { // parse the RSS data var parsedData = parseGoogleNewsRSSData(body); // if parsing runs okay, add data to the return object and return it if (parsedData.error == false) { returnObject.error = false; returnObject.errorMessage = null; returnObject.newsArray = parsedData.data; callback(returnObject); } // otherwise parsing failed, indicate such else { returnObject.error = true; returnObject.errorMessage = 'Error with parsing data return from Google News.'; callback(returnObject); } } // otherwise indicate bad request else { returnObject.error = true; returnObject.errorMessage = 'Error with request for data from Google News.'; callback(returnObject); } }); } // otherwise send back error true object from original params parsing else { callback(returnObject); } }
javascript
function requestGoogleNewsRSS(params, callback) { // parse the params var returnObject = parseGoogleNewsRSSParams(params); returnObject.newsArray = null; // if no error from the parsing object if (!returnObject.error) { // make a request to the RSS using the URL var request = require("request"); request({uri: returnObject.url}, function(error, response, body) { // if no error in the call if (!error) { // parse the RSS data var parsedData = parseGoogleNewsRSSData(body); // if parsing runs okay, add data to the return object and return it if (parsedData.error == false) { returnObject.error = false; returnObject.errorMessage = null; returnObject.newsArray = parsedData.data; callback(returnObject); } // otherwise parsing failed, indicate such else { returnObject.error = true; returnObject.errorMessage = 'Error with parsing data return from Google News.'; callback(returnObject); } } // otherwise indicate bad request else { returnObject.error = true; returnObject.errorMessage = 'Error with request for data from Google News.'; callback(returnObject); } }); } // otherwise send back error true object from original params parsing else { callback(returnObject); } }
[ "function", "requestGoogleNewsRSS", "(", "params", ",", "callback", ")", "{", "// parse the params\r", "var", "returnObject", "=", "parseGoogleNewsRSSParams", "(", "params", ")", ";", "returnObject", ".", "newsArray", "=", "null", ";", "// if no error from the parsing object\r", "if", "(", "!", "returnObject", ".", "error", ")", "{", "// make a request to the RSS using the URL\r", "var", "request", "=", "require", "(", "\"request\"", ")", ";", "request", "(", "{", "uri", ":", "returnObject", ".", "url", "}", ",", "function", "(", "error", ",", "response", ",", "body", ")", "{", "// if no error in the call\r", "if", "(", "!", "error", ")", "{", "// parse the RSS data\r", "var", "parsedData", "=", "parseGoogleNewsRSSData", "(", "body", ")", ";", "// if parsing runs okay, add data to the return object and return it\r", "if", "(", "parsedData", ".", "error", "==", "false", ")", "{", "returnObject", ".", "error", "=", "false", ";", "returnObject", ".", "errorMessage", "=", "null", ";", "returnObject", ".", "newsArray", "=", "parsedData", ".", "data", ";", "callback", "(", "returnObject", ")", ";", "}", "// otherwise parsing failed, indicate such\r", "else", "{", "returnObject", ".", "error", "=", "true", ";", "returnObject", ".", "errorMessage", "=", "'Error with parsing data return from Google News.'", ";", "callback", "(", "returnObject", ")", ";", "}", "}", "// otherwise indicate bad request\r", "else", "{", "returnObject", ".", "error", "=", "true", ";", "returnObject", ".", "errorMessage", "=", "'Error with request for data from Google News.'", ";", "callback", "(", "returnObject", ")", ";", "}", "}", ")", ";", "}", "// otherwise send back error true object from original params parsing\r", "else", "{", "callback", "(", "returnObject", ")", ";", "}", "}" ]
makes a call to get the HTML from the rotten tomatoes front page uses the request package to achieve this
[ "makes", "a", "call", "to", "get", "the", "HTML", "from", "the", "rotten", "tomatoes", "front", "page", "uses", "the", "request", "package", "to", "achieve", "this" ]
df62b2d1af2d6154e3a075f30ed152282dd9e2f3
https://github.com/AdamMoses-GitHub/NPMJS-googlenews-rss-scraper/blob/df62b2d1af2d6154e3a075f30ed152282dd9e2f3/index.js#L182-L222
37,083
koopjs/geohub
lib/gist.js
gist
function gist (options, callback) { if (!options.id) return callback(new Error('missing option: id')) request({ url: '/gists/' + options.id, qs: { access_token: options.token } }, function (err, json) { if (err) return callback(err) var results = [] async.forEachOf(json.files, function (item, key, callback) { processGithubFile({ item: item, key: key, json: json }, function (err, geojson) { if (err) return callback(err) if (geojson) results.push(geojson) callback(null) }) }, function (err) { if (err) return callback(err) if (!results.length) return callback(new Error('no geojson found in gist ' + options.id)) callback(null, results) }) }) }
javascript
function gist (options, callback) { if (!options.id) return callback(new Error('missing option: id')) request({ url: '/gists/' + options.id, qs: { access_token: options.token } }, function (err, json) { if (err) return callback(err) var results = [] async.forEachOf(json.files, function (item, key, callback) { processGithubFile({ item: item, key: key, json: json }, function (err, geojson) { if (err) return callback(err) if (geojson) results.push(geojson) callback(null) }) }, function (err) { if (err) return callback(err) if (!results.length) return callback(new Error('no geojson found in gist ' + options.id)) callback(null, results) }) }) }
[ "function", "gist", "(", "options", ",", "callback", ")", "{", "if", "(", "!", "options", ".", "id", ")", "return", "callback", "(", "new", "Error", "(", "'missing option: id'", ")", ")", "request", "(", "{", "url", ":", "'/gists/'", "+", "options", ".", "id", ",", "qs", ":", "{", "access_token", ":", "options", ".", "token", "}", "}", ",", "function", "(", "err", ",", "json", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", "var", "results", "=", "[", "]", "async", ".", "forEachOf", "(", "json", ".", "files", ",", "function", "(", "item", ",", "key", ",", "callback", ")", "{", "processGithubFile", "(", "{", "item", ":", "item", ",", "key", ":", "key", ",", "json", ":", "json", "}", ",", "function", "(", "err", ",", "geojson", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", "if", "(", "geojson", ")", "results", ".", "push", "(", "geojson", ")", "callback", "(", "null", ")", "}", ")", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", "if", "(", "!", "results", ".", "length", ")", "return", "callback", "(", "new", "Error", "(", "'no geojson found in gist '", "+", "options", ".", "id", ")", ")", "callback", "(", "null", ",", "results", ")", "}", ")", "}", ")", "}" ]
get geojson from a gist @param {object} options - id, token (optional) @param {Function} callback - err, data
[ "get", "geojson", "from", "a", "gist" ]
d58c12daba4b33edc0b70333d440572f9c39e6db
https://github.com/koopjs/geohub/blob/d58c12daba4b33edc0b70333d440572f9c39e6db/lib/gist.js#L10-L39
37,084
koopjs/geohub
lib/gist.js
processGithubFile
function processGithubFile (options, callback) { var item = options.item var key = options.key var json = options.json function respond (content) { if (isFeatureCollection(content)) { content.name = key content.updated_at = json.updated_at return content } return false } if (item.truncated) { return request({ url: item.raw_url }, function (err, content) { if (err) return callback(err) callback(null, respond(content)) }) } try { var content = JSON.parse(item.content) } catch (e) { var msg = 'could not parse file contents of ' + key + ': ' + e.message return callback(new Error(msg)) } callback(null, respond(content)) }
javascript
function processGithubFile (options, callback) { var item = options.item var key = options.key var json = options.json function respond (content) { if (isFeatureCollection(content)) { content.name = key content.updated_at = json.updated_at return content } return false } if (item.truncated) { return request({ url: item.raw_url }, function (err, content) { if (err) return callback(err) callback(null, respond(content)) }) } try { var content = JSON.parse(item.content) } catch (e) { var msg = 'could not parse file contents of ' + key + ': ' + e.message return callback(new Error(msg)) } callback(null, respond(content)) }
[ "function", "processGithubFile", "(", "options", ",", "callback", ")", "{", "var", "item", "=", "options", ".", "item", "var", "key", "=", "options", ".", "key", "var", "json", "=", "options", ".", "json", "function", "respond", "(", "content", ")", "{", "if", "(", "isFeatureCollection", "(", "content", ")", ")", "{", "content", ".", "name", "=", "key", "content", ".", "updated_at", "=", "json", ".", "updated_at", "return", "content", "}", "return", "false", "}", "if", "(", "item", ".", "truncated", ")", "{", "return", "request", "(", "{", "url", ":", "item", ".", "raw_url", "}", ",", "function", "(", "err", ",", "content", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", "callback", "(", "null", ",", "respond", "(", "content", ")", ")", "}", ")", "}", "try", "{", "var", "content", "=", "JSON", ".", "parse", "(", "item", ".", "content", ")", "}", "catch", "(", "e", ")", "{", "var", "msg", "=", "'could not parse file contents of '", "+", "key", "+", "': '", "+", "e", ".", "message", "return", "callback", "(", "new", "Error", "(", "msg", ")", ")", "}", "callback", "(", "null", ",", "respond", "(", "content", ")", ")", "}" ]
find and parse geojson objects in a given github gist api "files" object @private @param {object} options - item, key, json @param {Function} callback - err, geojson
[ "find", "and", "parse", "geojson", "objects", "in", "a", "given", "github", "gist", "api", "files", "object" ]
d58c12daba4b33edc0b70333d440572f9c39e6db
https://github.com/koopjs/geohub/blob/d58c12daba4b33edc0b70333d440572f9c39e6db/lib/gist.js#L48-L80
37,085
karlkfi/ngindox
lib/ngindox.js
parse
function parse(fileString, callback) { try { return callback(null, Yaml.safeLoad(fileString)); } catch (err) { return callback(err); } }
javascript
function parse(fileString, callback) { try { return callback(null, Yaml.safeLoad(fileString)); } catch (err) { return callback(err); } }
[ "function", "parse", "(", "fileString", ",", "callback", ")", "{", "try", "{", "return", "callback", "(", "null", ",", "Yaml", ".", "safeLoad", "(", "fileString", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "}" ]
Parses a Yaml file string into an Ngindox object
[ "Parses", "a", "Yaml", "file", "string", "into", "an", "Ngindox", "object" ]
2c0e8a682d7bde9e5d73a853f45bf1460f4664e9
https://github.com/karlkfi/ngindox/blob/2c0e8a682d7bde9e5d73a853f45bf1460f4664e9/lib/ngindox.js#L5-L11
37,086
karlkfi/ngindox
lib/ngindox.js
parseFile
function parseFile(filePath, encoding, callback) { fs.readFile(filePath, encoding, function(err, fileString) { if (err) { return callback(err); } return parse(fileString, callback); }); }
javascript
function parseFile(filePath, encoding, callback) { fs.readFile(filePath, encoding, function(err, fileString) { if (err) { return callback(err); } return parse(fileString, callback); }); }
[ "function", "parseFile", "(", "filePath", ",", "encoding", ",", "callback", ")", "{", "fs", ".", "readFile", "(", "filePath", ",", "encoding", ",", "function", "(", "err", ",", "fileString", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "return", "parse", "(", "fileString", ",", "callback", ")", ";", "}", ")", ";", "}" ]
Parses a Yaml file into an Ngindox object
[ "Parses", "a", "Yaml", "file", "into", "an", "Ngindox", "object" ]
2c0e8a682d7bde9e5d73a853f45bf1460f4664e9
https://github.com/karlkfi/ngindox/blob/2c0e8a682d7bde9e5d73a853f45bf1460f4664e9/lib/ngindox.js#L14-L21
37,087
karlkfi/ngindox
lib/ngindox.js
write
function write(ngindoxMap, callback) { try { return callback(null, Yaml.safeDump(ngindoxMap)); } catch (err) { return callback(err); } }
javascript
function write(ngindoxMap, callback) { try { return callback(null, Yaml.safeDump(ngindoxMap)); } catch (err) { return callback(err); } }
[ "function", "write", "(", "ngindoxMap", ",", "callback", ")", "{", "try", "{", "return", "callback", "(", "null", ",", "Yaml", ".", "safeDump", "(", "ngindoxMap", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "}" ]
Writes a Ngindox object to a Yaml file string
[ "Writes", "a", "Ngindox", "object", "to", "a", "Yaml", "file", "string" ]
2c0e8a682d7bde9e5d73a853f45bf1460f4664e9
https://github.com/karlkfi/ngindox/blob/2c0e8a682d7bde9e5d73a853f45bf1460f4664e9/lib/ngindox.js#L24-L30
37,088
karlkfi/ngindox
lib/ngindox.js
writeFile
function writeFile(ngindoxObj, encoding, callback) { fs.writeFile(filePath, fileString, encoding, function(err) { if (err) { return callback(err); } return write(ngindoxObj, callback); }); }
javascript
function writeFile(ngindoxObj, encoding, callback) { fs.writeFile(filePath, fileString, encoding, function(err) { if (err) { return callback(err); } return write(ngindoxObj, callback); }); }
[ "function", "writeFile", "(", "ngindoxObj", ",", "encoding", ",", "callback", ")", "{", "fs", ".", "writeFile", "(", "filePath", ",", "fileString", ",", "encoding", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "return", "write", "(", "ngindoxObj", ",", "callback", ")", ";", "}", ")", ";", "}" ]
Writes a Ngindox object to a Yaml file
[ "Writes", "a", "Ngindox", "object", "to", "a", "Yaml", "file" ]
2c0e8a682d7bde9e5d73a853f45bf1460f4664e9
https://github.com/karlkfi/ngindox/blob/2c0e8a682d7bde9e5d73a853f45bf1460f4664e9/lib/ngindox.js#L33-L40
37,089
nodejitsu/defaultable
defaultable.js
merge_obj
function merge_obj(high, low) { if(!is_obj(high)) throw new Error('Bad merge high-priority'); if(!is_obj(low)) throw new Error('Bad merge low-priority'); var keys = []; function add_key(k) { if(!~ keys.indexOf(k)) keys.push(k); } _each(_keys(high), add_key); _each(_keys(low), add_key); var result = {}; _each(keys, function (key) { var high_val = high[key]; var low_val = low[key]; if(is_obj(high_val) && is_obj(low_val)) result[key] = merge_obj(high_val, low_val); else if (key in high) result[key] = high[key]; else if (key in low) result[key] = low[key]; else throw new Error('Unknown key type: ' + key); }) return result; }
javascript
function merge_obj(high, low) { if(!is_obj(high)) throw new Error('Bad merge high-priority'); if(!is_obj(low)) throw new Error('Bad merge low-priority'); var keys = []; function add_key(k) { if(!~ keys.indexOf(k)) keys.push(k); } _each(_keys(high), add_key); _each(_keys(low), add_key); var result = {}; _each(keys, function (key) { var high_val = high[key]; var low_val = low[key]; if(is_obj(high_val) && is_obj(low_val)) result[key] = merge_obj(high_val, low_val); else if (key in high) result[key] = high[key]; else if (key in low) result[key] = low[key]; else throw new Error('Unknown key type: ' + key); }) return result; }
[ "function", "merge_obj", "(", "high", ",", "low", ")", "{", "if", "(", "!", "is_obj", "(", "high", ")", ")", "throw", "new", "Error", "(", "'Bad merge high-priority'", ")", ";", "if", "(", "!", "is_obj", "(", "low", ")", ")", "throw", "new", "Error", "(", "'Bad merge low-priority'", ")", ";", "var", "keys", "=", "[", "]", ";", "function", "add_key", "(", "k", ")", "{", "if", "(", "!", "~", "keys", ".", "indexOf", "(", "k", ")", ")", "keys", ".", "push", "(", "k", ")", ";", "}", "_each", "(", "_keys", "(", "high", ")", ",", "add_key", ")", ";", "_each", "(", "_keys", "(", "low", ")", ",", "add_key", ")", ";", "var", "result", "=", "{", "}", ";", "_each", "(", "keys", ",", "function", "(", "key", ")", "{", "var", "high_val", "=", "high", "[", "key", "]", ";", "var", "low_val", "=", "low", "[", "key", "]", ";", "if", "(", "is_obj", "(", "high_val", ")", "&&", "is_obj", "(", "low_val", ")", ")", "result", "[", "key", "]", "=", "merge_obj", "(", "high_val", ",", "low_val", ")", ";", "else", "if", "(", "key", "in", "high", ")", "result", "[", "key", "]", "=", "high", "[", "key", "]", ";", "else", "if", "(", "key", "in", "low", ")", "result", "[", "key", "]", "=", "low", "[", "key", "]", ";", "else", "throw", "new", "Error", "(", "'Unknown key type: '", "+", "key", ")", ";", "}", ")", "return", "result", ";", "}" ]
Recursively merge higher-priority values into previously-set lower-priority ones.
[ "Recursively", "merge", "higher", "-", "priority", "values", "into", "previously", "-", "set", "lower", "-", "priority", "ones", "." ]
aabf6cd1b4382c004689a051ee32461ed923ed54
https://github.com/nodejitsu/defaultable/blob/aabf6cd1b4382c004689a051ee32461ed923ed54/defaultable.js#L98-L129
37,090
joebandenburg/libaxolotl-javascript
src/Ratchet.js
Ratchet
function Ratchet(crypto) { const self = this; const hkdf = new HKDF(crypto); /** * Derive the main and sub ratchet states from the shared secrets derived from the handshake. * * @method * @param {number} sessionVersion * @param {Array.<ArrayBuffer>} agreements - an array of ArrayBuffers containing the shared secrets * @return {Promise.<Object, Error>} the root and chain keys */ this.deriveInitialRootKeyAndChain = co.wrap(function*(sessionVersion, agreements) { var secrets = []; if (sessionVersion >= 3) { secrets.push(discontinuityBytes); } secrets = secrets.concat(agreements); var masterSecret = ArrayBufferUtils.concat(secrets); var derivedSecret = yield hkdf.deriveSecrets(masterSecret, whisperText, ProtocolConstants.rootKeyByteCount + ProtocolConstants.chainKeyByteCount); return { rootKey: derivedSecret.slice(0, ProtocolConstants.rootKeyByteCount), chain: new Chain(derivedSecret.slice(ProtocolConstants.rootKeyByteCount)) }; }); /** * Derive the next main and sub ratchet states from the previous state. * <p> * This method "clicks" the Diffie-Hellman ratchet forwards. * * @method * @param {ArrayBuffer} rootKey - the current root key * @param {ArrayBuffer} theirEphemeralPublicKey - the receiving ephemeral/ratchet key * @param {ArrayBuffer} ourEphemeralPrivateKey - our current ephemeral/ratchet key * @return {Promise.<Object, Error>} the next root and chain keys */ this.deriveNextRootKeyAndChain = co.wrap(function*(rootKey, theirEphemeralPublicKey, ourEphemeralPrivateKey) { var sharedSecret = yield crypto.calculateAgreement(theirEphemeralPublicKey, ourEphemeralPrivateKey); var derivedSecretBytes = yield hkdf.deriveSecretsWithSalt(sharedSecret, rootKey, whisperRatchet, ProtocolConstants.rootKeyByteCount + ProtocolConstants.chainKeyByteCount); return { rootKey: derivedSecretBytes.slice(0, ProtocolConstants.rootKeyByteCount), chain: new Chain(derivedSecretBytes.slice(ProtocolConstants.rootKeyByteCount)) }; }); // /** * Derive the next sub ratchet state from the previous state. * <p> * This method "clicks" the hash iteration ratchet forwards. * * @method * @param {Chain} chain * @return {Promise.<void, Error>} */ this.clickSubRatchet = co.wrap(function*(chain) { chain.index++; chain.key = yield deriveNextChainKey(chain.key); }); /** * Derive the message keys from the chain key. * * @method * @param {ArrayBuffer} chainKey * @return {Promise.<object, Error>} an object containing the message keys. */ this.deriveMessageKeys = co.wrap(function*(chainKey) { var messageKey = yield deriveMessageKey(chainKey); var keyMaterialBytes = yield hkdf.deriveSecrets(messageKey, whisperMessageKeys, ProtocolConstants.cipherKeyByteCount + ProtocolConstants.macKeyByteCount + ProtocolConstants.ivByteCount); var cipherKeyBytes = keyMaterialBytes.slice(0, ProtocolConstants.cipherKeyByteCount); var macKeyBytes = keyMaterialBytes.slice(ProtocolConstants.cipherKeyByteCount, ProtocolConstants.cipherKeyByteCount + ProtocolConstants.macKeyByteCount); var ivBytes = keyMaterialBytes.slice(ProtocolConstants.cipherKeyByteCount + ProtocolConstants.macKeyByteCount); return { cipherKey: cipherKeyBytes, macKey: macKeyBytes, iv: ivBytes }; }); var hmacByte = co.wrap(function*(key, byte) { return yield crypto.hmac(key, ArrayBufferUtils.fromByte(byte)); }); var deriveMessageKey = co.wrap(function*(chainKey) { return yield hmacByte(chainKey, messageKeySeed); }); var deriveNextChainKey = co.wrap(function*(chainKey) { return yield hmacByte(chainKey, chainKeySeed); }); }
javascript
function Ratchet(crypto) { const self = this; const hkdf = new HKDF(crypto); /** * Derive the main and sub ratchet states from the shared secrets derived from the handshake. * * @method * @param {number} sessionVersion * @param {Array.<ArrayBuffer>} agreements - an array of ArrayBuffers containing the shared secrets * @return {Promise.<Object, Error>} the root and chain keys */ this.deriveInitialRootKeyAndChain = co.wrap(function*(sessionVersion, agreements) { var secrets = []; if (sessionVersion >= 3) { secrets.push(discontinuityBytes); } secrets = secrets.concat(agreements); var masterSecret = ArrayBufferUtils.concat(secrets); var derivedSecret = yield hkdf.deriveSecrets(masterSecret, whisperText, ProtocolConstants.rootKeyByteCount + ProtocolConstants.chainKeyByteCount); return { rootKey: derivedSecret.slice(0, ProtocolConstants.rootKeyByteCount), chain: new Chain(derivedSecret.slice(ProtocolConstants.rootKeyByteCount)) }; }); /** * Derive the next main and sub ratchet states from the previous state. * <p> * This method "clicks" the Diffie-Hellman ratchet forwards. * * @method * @param {ArrayBuffer} rootKey - the current root key * @param {ArrayBuffer} theirEphemeralPublicKey - the receiving ephemeral/ratchet key * @param {ArrayBuffer} ourEphemeralPrivateKey - our current ephemeral/ratchet key * @return {Promise.<Object, Error>} the next root and chain keys */ this.deriveNextRootKeyAndChain = co.wrap(function*(rootKey, theirEphemeralPublicKey, ourEphemeralPrivateKey) { var sharedSecret = yield crypto.calculateAgreement(theirEphemeralPublicKey, ourEphemeralPrivateKey); var derivedSecretBytes = yield hkdf.deriveSecretsWithSalt(sharedSecret, rootKey, whisperRatchet, ProtocolConstants.rootKeyByteCount + ProtocolConstants.chainKeyByteCount); return { rootKey: derivedSecretBytes.slice(0, ProtocolConstants.rootKeyByteCount), chain: new Chain(derivedSecretBytes.slice(ProtocolConstants.rootKeyByteCount)) }; }); // /** * Derive the next sub ratchet state from the previous state. * <p> * This method "clicks" the hash iteration ratchet forwards. * * @method * @param {Chain} chain * @return {Promise.<void, Error>} */ this.clickSubRatchet = co.wrap(function*(chain) { chain.index++; chain.key = yield deriveNextChainKey(chain.key); }); /** * Derive the message keys from the chain key. * * @method * @param {ArrayBuffer} chainKey * @return {Promise.<object, Error>} an object containing the message keys. */ this.deriveMessageKeys = co.wrap(function*(chainKey) { var messageKey = yield deriveMessageKey(chainKey); var keyMaterialBytes = yield hkdf.deriveSecrets(messageKey, whisperMessageKeys, ProtocolConstants.cipherKeyByteCount + ProtocolConstants.macKeyByteCount + ProtocolConstants.ivByteCount); var cipherKeyBytes = keyMaterialBytes.slice(0, ProtocolConstants.cipherKeyByteCount); var macKeyBytes = keyMaterialBytes.slice(ProtocolConstants.cipherKeyByteCount, ProtocolConstants.cipherKeyByteCount + ProtocolConstants.macKeyByteCount); var ivBytes = keyMaterialBytes.slice(ProtocolConstants.cipherKeyByteCount + ProtocolConstants.macKeyByteCount); return { cipherKey: cipherKeyBytes, macKey: macKeyBytes, iv: ivBytes }; }); var hmacByte = co.wrap(function*(key, byte) { return yield crypto.hmac(key, ArrayBufferUtils.fromByte(byte)); }); var deriveMessageKey = co.wrap(function*(chainKey) { return yield hmacByte(chainKey, messageKeySeed); }); var deriveNextChainKey = co.wrap(function*(chainKey) { return yield hmacByte(chainKey, chainKeySeed); }); }
[ "function", "Ratchet", "(", "crypto", ")", "{", "const", "self", "=", "this", ";", "const", "hkdf", "=", "new", "HKDF", "(", "crypto", ")", ";", "/**\n * Derive the main and sub ratchet states from the shared secrets derived from the handshake.\n *\n * @method\n * @param {number} sessionVersion\n * @param {Array.<ArrayBuffer>} agreements - an array of ArrayBuffers containing the shared secrets\n * @return {Promise.<Object, Error>} the root and chain keys\n */", "this", ".", "deriveInitialRootKeyAndChain", "=", "co", ".", "wrap", "(", "function", "*", "(", "sessionVersion", ",", "agreements", ")", "{", "var", "secrets", "=", "[", "]", ";", "if", "(", "sessionVersion", ">=", "3", ")", "{", "secrets", ".", "push", "(", "discontinuityBytes", ")", ";", "}", "secrets", "=", "secrets", ".", "concat", "(", "agreements", ")", ";", "var", "masterSecret", "=", "ArrayBufferUtils", ".", "concat", "(", "secrets", ")", ";", "var", "derivedSecret", "=", "yield", "hkdf", ".", "deriveSecrets", "(", "masterSecret", ",", "whisperText", ",", "ProtocolConstants", ".", "rootKeyByteCount", "+", "ProtocolConstants", ".", "chainKeyByteCount", ")", ";", "return", "{", "rootKey", ":", "derivedSecret", ".", "slice", "(", "0", ",", "ProtocolConstants", ".", "rootKeyByteCount", ")", ",", "chain", ":", "new", "Chain", "(", "derivedSecret", ".", "slice", "(", "ProtocolConstants", ".", "rootKeyByteCount", ")", ")", "}", ";", "}", ")", ";", "/**\n * Derive the next main and sub ratchet states from the previous state.\n * <p>\n * This method \"clicks\" the Diffie-Hellman ratchet forwards.\n *\n * @method\n * @param {ArrayBuffer} rootKey - the current root key\n * @param {ArrayBuffer} theirEphemeralPublicKey - the receiving ephemeral/ratchet key\n * @param {ArrayBuffer} ourEphemeralPrivateKey - our current ephemeral/ratchet key\n * @return {Promise.<Object, Error>} the next root and chain keys\n */", "this", ".", "deriveNextRootKeyAndChain", "=", "co", ".", "wrap", "(", "function", "*", "(", "rootKey", ",", "theirEphemeralPublicKey", ",", "ourEphemeralPrivateKey", ")", "{", "var", "sharedSecret", "=", "yield", "crypto", ".", "calculateAgreement", "(", "theirEphemeralPublicKey", ",", "ourEphemeralPrivateKey", ")", ";", "var", "derivedSecretBytes", "=", "yield", "hkdf", ".", "deriveSecretsWithSalt", "(", "sharedSecret", ",", "rootKey", ",", "whisperRatchet", ",", "ProtocolConstants", ".", "rootKeyByteCount", "+", "ProtocolConstants", ".", "chainKeyByteCount", ")", ";", "return", "{", "rootKey", ":", "derivedSecretBytes", ".", "slice", "(", "0", ",", "ProtocolConstants", ".", "rootKeyByteCount", ")", ",", "chain", ":", "new", "Chain", "(", "derivedSecretBytes", ".", "slice", "(", "ProtocolConstants", ".", "rootKeyByteCount", ")", ")", "}", ";", "}", ")", ";", "//", "/**\n * Derive the next sub ratchet state from the previous state.\n * <p>\n * This method \"clicks\" the hash iteration ratchet forwards.\n *\n * @method\n * @param {Chain} chain\n * @return {Promise.<void, Error>}\n */", "this", ".", "clickSubRatchet", "=", "co", ".", "wrap", "(", "function", "*", "(", "chain", ")", "{", "chain", ".", "index", "++", ";", "chain", ".", "key", "=", "yield", "deriveNextChainKey", "(", "chain", ".", "key", ")", ";", "}", ")", ";", "/**\n * Derive the message keys from the chain key.\n *\n * @method\n * @param {ArrayBuffer} chainKey\n * @return {Promise.<object, Error>} an object containing the message keys.\n */", "this", ".", "deriveMessageKeys", "=", "co", ".", "wrap", "(", "function", "*", "(", "chainKey", ")", "{", "var", "messageKey", "=", "yield", "deriveMessageKey", "(", "chainKey", ")", ";", "var", "keyMaterialBytes", "=", "yield", "hkdf", ".", "deriveSecrets", "(", "messageKey", ",", "whisperMessageKeys", ",", "ProtocolConstants", ".", "cipherKeyByteCount", "+", "ProtocolConstants", ".", "macKeyByteCount", "+", "ProtocolConstants", ".", "ivByteCount", ")", ";", "var", "cipherKeyBytes", "=", "keyMaterialBytes", ".", "slice", "(", "0", ",", "ProtocolConstants", ".", "cipherKeyByteCount", ")", ";", "var", "macKeyBytes", "=", "keyMaterialBytes", ".", "slice", "(", "ProtocolConstants", ".", "cipherKeyByteCount", ",", "ProtocolConstants", ".", "cipherKeyByteCount", "+", "ProtocolConstants", ".", "macKeyByteCount", ")", ";", "var", "ivBytes", "=", "keyMaterialBytes", ".", "slice", "(", "ProtocolConstants", ".", "cipherKeyByteCount", "+", "ProtocolConstants", ".", "macKeyByteCount", ")", ";", "return", "{", "cipherKey", ":", "cipherKeyBytes", ",", "macKey", ":", "macKeyBytes", ",", "iv", ":", "ivBytes", "}", ";", "}", ")", ";", "var", "hmacByte", "=", "co", ".", "wrap", "(", "function", "*", "(", "key", ",", "byte", ")", "{", "return", "yield", "crypto", ".", "hmac", "(", "key", ",", "ArrayBufferUtils", ".", "fromByte", "(", "byte", ")", ")", ";", "}", ")", ";", "var", "deriveMessageKey", "=", "co", ".", "wrap", "(", "function", "*", "(", "chainKey", ")", "{", "return", "yield", "hmacByte", "(", "chainKey", ",", "messageKeySeed", ")", ";", "}", ")", ";", "var", "deriveNextChainKey", "=", "co", ".", "wrap", "(", "function", "*", "(", "chainKey", ")", "{", "return", "yield", "hmacByte", "(", "chainKey", ",", "chainKeySeed", ")", ";", "}", ")", ";", "}" ]
A utility class for performing the Axolotl ratcheting. @param {Crypto} crypto @constructor
[ "A", "utility", "class", "for", "performing", "the", "Axolotl", "ratcheting", "." ]
046466831f4b2a5c1a225d4db6b8a8bfab9a2adf
https://github.com/joebandenburg/libaxolotl-javascript/blob/046466831f4b2a5c1a225d4db6b8a8bfab9a2adf/src/Ratchet.js#L40-L138
37,091
jonschlinkert/normalize-pkg
index.js
NormalizePkg
function NormalizePkg(options) { if (!(this instanceof NormalizePkg)) { return new NormalizePkg(options); } this.options = options || {}; this.schema = schema(this.options); this.data = this.schema.data; this.schema.on('warning', this.emit.bind(this, 'warning')); this.schema.on('error', this.emit.bind(this, 'error')); this.schema.union = function(key, config, arr) { config[key] = utils.arrayify(config[key]); config[key] = utils.union([], config[key], utils.arrayify(arr)); }; }
javascript
function NormalizePkg(options) { if (!(this instanceof NormalizePkg)) { return new NormalizePkg(options); } this.options = options || {}; this.schema = schema(this.options); this.data = this.schema.data; this.schema.on('warning', this.emit.bind(this, 'warning')); this.schema.on('error', this.emit.bind(this, 'error')); this.schema.union = function(key, config, arr) { config[key] = utils.arrayify(config[key]); config[key] = utils.union([], config[key], utils.arrayify(arr)); }; }
[ "function", "NormalizePkg", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "NormalizePkg", ")", ")", "{", "return", "new", "NormalizePkg", "(", "options", ")", ";", "}", "this", ".", "options", "=", "options", "||", "{", "}", ";", "this", ".", "schema", "=", "schema", "(", "this", ".", "options", ")", ";", "this", ".", "data", "=", "this", ".", "schema", ".", "data", ";", "this", ".", "schema", ".", "on", "(", "'warning'", ",", "this", ".", "emit", ".", "bind", "(", "this", ",", "'warning'", ")", ")", ";", "this", ".", "schema", ".", "on", "(", "'error'", ",", "this", ".", "emit", ".", "bind", "(", "this", ",", "'error'", ")", ")", ";", "this", ".", "schema", ".", "union", "=", "function", "(", "key", ",", "config", ",", "arr", ")", "{", "config", "[", "key", "]", "=", "utils", ".", "arrayify", "(", "config", "[", "key", "]", ")", ";", "config", "[", "key", "]", "=", "utils", ".", "union", "(", "[", "]", ",", "config", "[", "key", "]", ",", "utils", ".", "arrayify", "(", "arr", ")", ")", ";", "}", ";", "}" ]
Create an instance of `NormalizePkg` with the given `options`. ```js var config = new NormalizePkg(); var pkg = config.normalize({ author: { name: 'Jon Schlinkert', url: 'https://github.com/jonschlinkert' } }); console.log(pkg); //=> {author: 'Jon Schlinkert (https://github.com/jonschlinkert)'} ``` @param {Object} `options` @api public
[ "Create", "an", "instance", "of", "NormalizePkg", "with", "the", "given", "options", "." ]
523c73c5f89b40f0bf5faeab69b2a59bbe9ad7f8
https://github.com/jonschlinkert/normalize-pkg/blob/523c73c5f89b40f0bf5faeab69b2a59bbe9ad7f8/index.js#L26-L41
37,092
wikimedia/web-stream-util
lib/index.js
readerToStream
function readerToStream(reader) { return new ReadableStream({ pull(controller) { return reader.read() .then(res => { if (res.done) { controller.close(); } else { controller.enqueue(res.value); } }); }, cancel(reason) { return reader.cancel(reason); } }); }
javascript
function readerToStream(reader) { return new ReadableStream({ pull(controller) { return reader.read() .then(res => { if (res.done) { controller.close(); } else { controller.enqueue(res.value); } }); }, cancel(reason) { return reader.cancel(reason); } }); }
[ "function", "readerToStream", "(", "reader", ")", "{", "return", "new", "ReadableStream", "(", "{", "pull", "(", "controller", ")", "{", "return", "reader", ".", "read", "(", ")", ".", "then", "(", "res", "=>", "{", "if", "(", "res", ".", "done", ")", "{", "controller", ".", "close", "(", ")", ";", "}", "else", "{", "controller", ".", "enqueue", "(", "res", ".", "value", ")", ";", "}", "}", ")", ";", "}", ",", "cancel", "(", "reason", ")", "{", "return", "reader", ".", "cancel", "(", "reason", ")", ";", "}", "}", ")", ";", "}" ]
Adapt a Reader to an UnderlyingSource, for wrapping into a ReadableStream. @param {Reader} reader @return {ReadableStream}
[ "Adapt", "a", "Reader", "to", "an", "UnderlyingSource", "for", "wrapping", "into", "a", "ReadableStream", "." ]
fc76740cd6a73dcb044251a233bc3c868d3c9a77
https://github.com/wikimedia/web-stream-util/blob/fc76740cd6a73dcb044251a233bc3c868d3c9a77/lib/index.js#L131-L145
37,093
DesTincT/bemlint
lib/bemlint.js
validate
function validate (input, source, line, column, bemlintId) { for (var rule_id in currentRules) { var messageOptions = lodash.assign({}, { input: input, source: source, bemlintId: bemlintId, elem: options.elem, mod: options.mod, wordPattern: options.wordPattern }), message = new Message(cheerio.load(modifiedText), rule_id, messageOptions); if ( message.text ) { messages.push({ message: message.text, line: line, column: column, ruleId: rule_id }); } } }
javascript
function validate (input, source, line, column, bemlintId) { for (var rule_id in currentRules) { var messageOptions = lodash.assign({}, { input: input, source: source, bemlintId: bemlintId, elem: options.elem, mod: options.mod, wordPattern: options.wordPattern }), message = new Message(cheerio.load(modifiedText), rule_id, messageOptions); if ( message.text ) { messages.push({ message: message.text, line: line, column: column, ruleId: rule_id }); } } }
[ "function", "validate", "(", "input", ",", "source", ",", "line", ",", "column", ",", "bemlintId", ")", "{", "for", "(", "var", "rule_id", "in", "currentRules", ")", "{", "var", "messageOptions", "=", "lodash", ".", "assign", "(", "{", "}", ",", "{", "input", ":", "input", ",", "source", ":", "source", ",", "bemlintId", ":", "bemlintId", ",", "elem", ":", "options", ".", "elem", ",", "mod", ":", "options", ".", "mod", ",", "wordPattern", ":", "options", ".", "wordPattern", "}", ")", ",", "message", "=", "new", "Message", "(", "cheerio", ".", "load", "(", "modifiedText", ")", ",", "rule_id", ",", "messageOptions", ")", ";", "if", "(", "message", ".", "text", ")", "{", "messages", ".", "push", "(", "{", "message", ":", "message", ".", "text", ",", "line", ":", "line", ",", "column", ":", "column", ",", "ruleId", ":", "rule_id", "}", ")", ";", "}", "}", "}" ]
Generates messages for given classname in source @method validate @param {String} input classname @param {Array} source Array of classnames from html attribute @param {Integer} line line number @param {Integer} column column @param {String} bemlintId Id for each node matched
[ "Generates", "messages", "for", "given", "classname", "in", "source" ]
e30963deae2c93f1d5e925389339ad740250dd68
https://github.com/DesTincT/bemlint/blob/e30963deae2c93f1d5e925389339ad740250dd68/lib/bemlint.js#L91-L114
37,094
san650/ceibo
index.js
buildDescriptor
function buildDescriptor(node, blueprintKey, descriptor /*, descriptorBuilder*/) { if (typeof descriptor.setup === 'function') { descriptor.setup(node, blueprintKey); } if (descriptor.value) { defineProperty(node, blueprintKey, descriptor.value); } else { defineProperty(node, blueprintKey, undefined, function() { return descriptor.get.call(this, blueprintKey); }); } }
javascript
function buildDescriptor(node, blueprintKey, descriptor /*, descriptorBuilder*/) { if (typeof descriptor.setup === 'function') { descriptor.setup(node, blueprintKey); } if (descriptor.value) { defineProperty(node, blueprintKey, descriptor.value); } else { defineProperty(node, blueprintKey, undefined, function() { return descriptor.get.call(this, blueprintKey); }); } }
[ "function", "buildDescriptor", "(", "node", ",", "blueprintKey", ",", "descriptor", "/*, descriptorBuilder*/", ")", "{", "if", "(", "typeof", "descriptor", ".", "setup", "===", "'function'", ")", "{", "descriptor", ".", "setup", "(", "node", ",", "blueprintKey", ")", ";", "}", "if", "(", "descriptor", ".", "value", ")", "{", "defineProperty", "(", "node", ",", "blueprintKey", ",", "descriptor", ".", "value", ")", ";", "}", "else", "{", "defineProperty", "(", "node", ",", "blueprintKey", ",", "undefined", ",", "function", "(", ")", "{", "return", "descriptor", ".", "get", ".", "call", "(", "this", ",", "blueprintKey", ")", ";", "}", ")", ";", "}", "}" ]
Default `Descriptor` builder @param {TreeNode} node - parent node @param {String} blueprintKey - key to build @param {Descriptor} descriptor - descriptor to build @param {Function} defaultBuilder - default function to build this type of node @return undefined
[ "Default", "Descriptor", "builder" ]
a4a9ad944249d0b14d40248f04bc162e5ac024e8
https://github.com/san650/ceibo/blob/a4a9ad944249d0b14d40248f04bc162e5ac024e8/index.js#L66-L78
37,095
san650/ceibo
index.js
buildObject
function buildObject(node, blueprintKey, blueprint /*, defaultBuilder*/) { var value = {}; // Create child component defineProperty(node, blueprintKey, value); // Set meta to object setMeta(value, blueprintKey); return [value, blueprint]; }
javascript
function buildObject(node, blueprintKey, blueprint /*, defaultBuilder*/) { var value = {}; // Create child component defineProperty(node, blueprintKey, value); // Set meta to object setMeta(value, blueprintKey); return [value, blueprint]; }
[ "function", "buildObject", "(", "node", ",", "blueprintKey", ",", "blueprint", "/*, defaultBuilder*/", ")", "{", "var", "value", "=", "{", "}", ";", "// Create child component", "defineProperty", "(", "node", ",", "blueprintKey", ",", "value", ")", ";", "// Set meta to object", "setMeta", "(", "value", ",", "blueprintKey", ")", ";", "return", "[", "value", ",", "blueprint", "]", ";", "}" ]
Default `Object` builder @param {TreeNode} node - parent node @param {String} blueprintKey - key to build @param {Object} blueprint - blueprint to build @param {Function} defaultBuilder - default function to build this type of node @return {Array} [node, blueprint] to build
[ "Default", "Object", "builder" ]
a4a9ad944249d0b14d40248f04bc162e5ac024e8
https://github.com/san650/ceibo/blob/a4a9ad944249d0b14d40248f04bc162e5ac024e8/index.js#L90-L100
37,096
nodef/extra-youtubeuploader
index.js
flags
function flags(o, pre='', z='') { for(var k in o) { if(o[k]==null || k==='stdio') continue; if(Array.isArray(o[k])) z += ` --${pre}${k} "${o[k].join()}"`; else if(typeof o[k]==='object') z = flags(o[k], `${pre}${k}_`, z); else if(typeof o[k]==='boolean') z += o[k]? ` --${pre}${k}`:''; else z += ` --${pre}${k} ${JSON.stringify(o[k])}`; } return z; }
javascript
function flags(o, pre='', z='') { for(var k in o) { if(o[k]==null || k==='stdio') continue; if(Array.isArray(o[k])) z += ` --${pre}${k} "${o[k].join()}"`; else if(typeof o[k]==='object') z = flags(o[k], `${pre}${k}_`, z); else if(typeof o[k]==='boolean') z += o[k]? ` --${pre}${k}`:''; else z += ` --${pre}${k} ${JSON.stringify(o[k])}`; } return z; }
[ "function", "flags", "(", "o", ",", "pre", "=", "''", ",", "z", "=", "''", ")", "{", "for", "(", "var", "k", "in", "o", ")", "{", "if", "(", "o", "[", "k", "]", "==", "null", "||", "k", "===", "'stdio'", ")", "continue", ";", "if", "(", "Array", ".", "isArray", "(", "o", "[", "k", "]", ")", ")", "z", "+=", "`", "${", "pre", "}", "${", "k", "}", "${", "o", "[", "k", "]", ".", "join", "(", ")", "}", "`", ";", "else", "if", "(", "typeof", "o", "[", "k", "]", "===", "'object'", ")", "z", "=", "flags", "(", "o", "[", "k", "]", ",", "`", "${", "pre", "}", "${", "k", "}", "`", ",", "z", ")", ";", "else", "if", "(", "typeof", "o", "[", "k", "]", "===", "'boolean'", ")", "z", "+=", "o", "[", "k", "]", "?", "`", "${", "pre", "}", "${", "k", "}", "`", ":", "''", ";", "else", "z", "+=", "`", "${", "pre", "}", "${", "k", "}", "${", "JSON", ".", "stringify", "(", "o", "[", "k", "]", ")", "}", "`", ";", "}", "return", "z", ";", "}" ]
Generate flags for console.
[ "Generate", "flags", "for", "console", "." ]
c3e3967b99844e472ba850d785b3f572d15b6230
https://github.com/nodef/extra-youtubeuploader/blob/c3e3967b99844e472ba850d785b3f572d15b6230/index.js#L9-L18
37,097
nodef/extra-youtubeuploader
index.js
youtubeuploader
function youtubeuploader(o) { var o = o||{}, cmd = 'youtubeuploader'+flags(o); var stdio = o.log || o.stdio==null? STDIO:o.stdio; if(stdio===STDIO) return Promise.resolve({stdout: cp.execSync(cmd, {stdio})}); return new Promise((fres, frej) => cp.exec(cmd, {stdio}, (err, stdout, stderr) => { return err? frej(err):fres({stdout, stderr}); })); }
javascript
function youtubeuploader(o) { var o = o||{}, cmd = 'youtubeuploader'+flags(o); var stdio = o.log || o.stdio==null? STDIO:o.stdio; if(stdio===STDIO) return Promise.resolve({stdout: cp.execSync(cmd, {stdio})}); return new Promise((fres, frej) => cp.exec(cmd, {stdio}, (err, stdout, stderr) => { return err? frej(err):fres({stdout, stderr}); })); }
[ "function", "youtubeuploader", "(", "o", ")", "{", "var", "o", "=", "o", "||", "{", "}", ",", "cmd", "=", "'youtubeuploader'", "+", "flags", "(", "o", ")", ";", "var", "stdio", "=", "o", ".", "log", "||", "o", ".", "stdio", "==", "null", "?", "STDIO", ":", "o", ".", "stdio", ";", "if", "(", "stdio", "===", "STDIO", ")", "return", "Promise", ".", "resolve", "(", "{", "stdout", ":", "cp", ".", "execSync", "(", "cmd", ",", "{", "stdio", "}", ")", "}", ")", ";", "return", "new", "Promise", "(", "(", "fres", ",", "frej", ")", "=>", "cp", ".", "exec", "(", "cmd", ",", "{", "stdio", "}", ",", "(", "err", ",", "stdout", ",", "stderr", ")", "=>", "{", "return", "err", "?", "frej", "(", "err", ")", ":", "fres", "(", "{", "stdout", ",", "stderr", "}", ")", ";", "}", ")", ")", ";", "}" ]
Invoke "youtubeuploader". @param {object} o upload options.
[ "Invoke", "youtubeuploader", "." ]
c3e3967b99844e472ba850d785b3f572d15b6230
https://github.com/nodef/extra-youtubeuploader/blob/c3e3967b99844e472ba850d785b3f572d15b6230/index.js#L24-L31
37,098
nodef/extra-youtubeuploader
index.js
lines
async function lines(o) { var {stdout} = await youtubeuploader(Object.assign({}, o, {stdio: []})); var out = stdout.toString().trim(); return out? out.split('\n'):[]; }
javascript
async function lines(o) { var {stdout} = await youtubeuploader(Object.assign({}, o, {stdio: []})); var out = stdout.toString().trim(); return out? out.split('\n'):[]; }
[ "async", "function", "lines", "(", "o", ")", "{", "var", "{", "stdout", "}", "=", "await", "youtubeuploader", "(", "Object", ".", "assign", "(", "{", "}", ",", "o", ",", "{", "stdio", ":", "[", "]", "}", ")", ")", ";", "var", "out", "=", "stdout", ".", "toString", "(", ")", ".", "trim", "(", ")", ";", "return", "out", "?", "out", ".", "split", "(", "'\\n'", ")", ":", "[", "]", ";", "}" ]
Invoke "youtubeuploader", and get stdout lines. @param {object} o upload options.
[ "Invoke", "youtubeuploader", "and", "get", "stdout", "lines", "." ]
c3e3967b99844e472ba850d785b3f572d15b6230
https://github.com/nodef/extra-youtubeuploader/blob/c3e3967b99844e472ba850d785b3f572d15b6230/index.js#L37-L41
37,099
DesTincT/bemlint
lib/util/glob-util.js
listFilesToProcess
function listFilesToProcess(globPatterns, options) { var ignoredPaths, ignoredPathsList, files = [], added = {}, globOptions, rulesKey = "_rules"; /** * Executes the linter on a file defined by the `filename`. Skips * unsupported file extensions and any files that are already linted. * @param {string} filename The file to be processed * @returns {void} */ function addFile(filename) { if (ignoredPaths.contains(filename)) { return; } filename = fs.realpathSync(filename); if (added[filename]) { return; } files.push(filename); added[filename] = true; } options = options || { ignore: true, dotfiles: true }; ignoredPaths = new IgnoredPaths(options); ignoredPathsList = ignoredPaths.ig.custom[rulesKey].map(function(rule) { return rule.pattern; }); globOptions = { nodir: true, ignore: ignoredPathsList }; debug("Creating list of files to process."); globPatterns.forEach(function(pattern) { if (shell.test("-f", pattern)) { addFile(pattern); } else { glob.sync(pattern, globOptions).forEach(addFile); } }); return files; }
javascript
function listFilesToProcess(globPatterns, options) { var ignoredPaths, ignoredPathsList, files = [], added = {}, globOptions, rulesKey = "_rules"; /** * Executes the linter on a file defined by the `filename`. Skips * unsupported file extensions and any files that are already linted. * @param {string} filename The file to be processed * @returns {void} */ function addFile(filename) { if (ignoredPaths.contains(filename)) { return; } filename = fs.realpathSync(filename); if (added[filename]) { return; } files.push(filename); added[filename] = true; } options = options || { ignore: true, dotfiles: true }; ignoredPaths = new IgnoredPaths(options); ignoredPathsList = ignoredPaths.ig.custom[rulesKey].map(function(rule) { return rule.pattern; }); globOptions = { nodir: true, ignore: ignoredPathsList }; debug("Creating list of files to process."); globPatterns.forEach(function(pattern) { if (shell.test("-f", pattern)) { addFile(pattern); } else { glob.sync(pattern, globOptions).forEach(addFile); } }); return files; }
[ "function", "listFilesToProcess", "(", "globPatterns", ",", "options", ")", "{", "var", "ignoredPaths", ",", "ignoredPathsList", ",", "files", "=", "[", "]", ",", "added", "=", "{", "}", ",", "globOptions", ",", "rulesKey", "=", "\"_rules\"", ";", "/**\n * Executes the linter on a file defined by the `filename`. Skips\n * unsupported file extensions and any files that are already linted.\n * @param {string} filename The file to be processed\n * @returns {void}\n */", "function", "addFile", "(", "filename", ")", "{", "if", "(", "ignoredPaths", ".", "contains", "(", "filename", ")", ")", "{", "return", ";", "}", "filename", "=", "fs", ".", "realpathSync", "(", "filename", ")", ";", "if", "(", "added", "[", "filename", "]", ")", "{", "return", ";", "}", "files", ".", "push", "(", "filename", ")", ";", "added", "[", "filename", "]", "=", "true", ";", "}", "options", "=", "options", "||", "{", "ignore", ":", "true", ",", "dotfiles", ":", "true", "}", ";", "ignoredPaths", "=", "new", "IgnoredPaths", "(", "options", ")", ";", "ignoredPathsList", "=", "ignoredPaths", ".", "ig", ".", "custom", "[", "rulesKey", "]", ".", "map", "(", "function", "(", "rule", ")", "{", "return", "rule", ".", "pattern", ";", "}", ")", ";", "globOptions", "=", "{", "nodir", ":", "true", ",", "ignore", ":", "ignoredPathsList", "}", ";", "debug", "(", "\"Creating list of files to process.\"", ")", ";", "globPatterns", ".", "forEach", "(", "function", "(", "pattern", ")", "{", "if", "(", "shell", ".", "test", "(", "\"-f\"", ",", "pattern", ")", ")", "{", "addFile", "(", "pattern", ")", ";", "}", "else", "{", "glob", ".", "sync", "(", "pattern", ",", "globOptions", ")", ".", "forEach", "(", "addFile", ")", ";", "}", "}", ")", ";", "return", "files", ";", "}" ]
Build a list of absolute filesnames on which bemlint will act. Ignored files are excluded from the results, as are duplicates. @param {string[]} globPatterns Glob patterns. @param {Object} [options] An options object. @param {boolean} [options.ignore] False disables use of .bemlintignore. @param {string} [options.ignorePath] The ignore file to use instead of .bemlintignore. @param {string} [options.ignorePattern] A pattern of files to ignore. @returns {string[]} Resolved absolute filenames.
[ "Build", "a", "list", "of", "absolute", "filesnames", "on", "which", "bemlint", "will", "act", ".", "Ignored", "files", "are", "excluded", "from", "the", "results", "as", "are", "duplicates", "." ]
e30963deae2c93f1d5e925389339ad740250dd68
https://github.com/DesTincT/bemlint/blob/e30963deae2c93f1d5e925389339ad740250dd68/lib/util/glob-util.js#L100-L146