id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
53,900
aaronpowell/bespoke-markdown
lib/bespoke-markdown.js
function(path, callbackSuccess, callbackError) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status >= 200 && xhr.status < 300) { callbackSuccess(xhr.responseText); } else { callbackError(); } } }; xhr.open('GET', path, false); try { xhr.send(); } catch (e) { callbackError(); } }
javascript
function(path, callbackSuccess, callbackError) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status >= 200 && xhr.status < 300) { callbackSuccess(xhr.responseText); } else { callbackError(); } } }; xhr.open('GET', path, false); try { xhr.send(); } catch (e) { callbackError(); } }
[ "function", "(", "path", ",", "callbackSuccess", ",", "callbackError", ")", "{", "var", "xhr", "=", "new", "XMLHttpRequest", "(", ")", ";", "xhr", ".", "onreadystatechange", "=", "function", "(", ")", "{", "if", "(", "xhr", ".", "readyState", "===", "4", ")", "{", "if", "(", "xhr", ".", "status", ">=", "200", "&&", "xhr", ".", "status", "<", "300", ")", "{", "callbackSuccess", "(", "xhr", ".", "responseText", ")", ";", "}", "else", "{", "callbackError", "(", ")", ";", "}", "}", "}", ";", "xhr", ".", "open", "(", "'GET'", ",", "path", ",", "false", ")", ";", "try", "{", "xhr", ".", "send", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "callbackError", "(", ")", ";", "}", "}" ]
Fetches the content of a file through AJAX. @param {string} path the path of the file to fetch @param {Function} callbackSuccess @param {Function} callbackError
[ "Fetches", "the", "content", "of", "a", "file", "through", "AJAX", "." ]
fa518c99647c81b97644feb4a7239210ca875e59
https://github.com/aaronpowell/bespoke-markdown/blob/fa518c99647c81b97644feb4a7239210ca875e59/lib/bespoke-markdown.js#L42-L59
53,901
AndiDittrich/Node.mysql-magic
lib/pool-manager.js
initPool
function initPool(name, config){ // new pool const pool = _mysql.createPool(config); // create pool wrapper _pools[name || '_default'] = { _instance: pool, getConnection: function(scope){ return _poolConnection.getConnection(pool, scope); } } }
javascript
function initPool(name, config){ // new pool const pool = _mysql.createPool(config); // create pool wrapper _pools[name || '_default'] = { _instance: pool, getConnection: function(scope){ return _poolConnection.getConnection(pool, scope); } } }
[ "function", "initPool", "(", "name", ",", "config", ")", "{", "// new pool", "const", "pool", "=", "_mysql", ".", "createPool", "(", "config", ")", ";", "// create pool wrapper", "_pools", "[", "name", "||", "'_default'", "]", "=", "{", "_instance", ":", "pool", ",", "getConnection", ":", "function", "(", "scope", ")", "{", "return", "_poolConnection", ".", "getConnection", "(", "pool", ",", "scope", ")", ";", "}", "}", "}" ]
create new pool
[ "create", "new", "pool" ]
f9783ac93f4a5744407781d7875ae68cad58cc48
https://github.com/AndiDittrich/Node.mysql-magic/blob/f9783ac93f4a5744407781d7875ae68cad58cc48/lib/pool-manager.js#L8-L19
53,902
AndCake/zino
zino-ssr.js
merge
function merge(target) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } for (var arg, len = args.length, index = 0; arg = args[index], index < len; index += 1) { for (var all in arg) { if (typeof HTMLElement !== 'undefined' && arg instanceof HTMLElement || typeof propDetails(arg, all).value !== 'undefined' && (!target[all] || propDetails(target, all).writable)) { if (all !== 'attributes') target[all] = arg[all]; } } } return target; }
javascript
function merge(target) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } for (var arg, len = args.length, index = 0; arg = args[index], index < len; index += 1) { for (var all in arg) { if (typeof HTMLElement !== 'undefined' && arg instanceof HTMLElement || typeof propDetails(arg, all).value !== 'undefined' && (!target[all] || propDetails(target, all).writable)) { if (all !== 'attributes') target[all] = arg[all]; } } } return target; }
[ "function", "merge", "(", "target", ")", "{", "for", "(", "var", "_len", "=", "arguments", ".", "length", ",", "args", "=", "Array", "(", "_len", ">", "1", "?", "_len", "-", "1", ":", "0", ")", ",", "_key", "=", "1", ";", "_key", "<", "_len", ";", "_key", "++", ")", "{", "args", "[", "_key", "-", "1", "]", "=", "arguments", "[", "_key", "]", ";", "}", "for", "(", "var", "arg", ",", "len", "=", "args", ".", "length", ",", "index", "=", "0", ";", "arg", "=", "args", "[", "index", "]", ",", "index", "<", "len", ";", "index", "+=", "1", ")", "{", "for", "(", "var", "all", "in", "arg", ")", "{", "if", "(", "typeof", "HTMLElement", "!==", "'undefined'", "&&", "arg", "instanceof", "HTMLElement", "||", "typeof", "propDetails", "(", "arg", ",", "all", ")", ".", "value", "!==", "'undefined'", "&&", "(", "!", "target", "[", "all", "]", "||", "propDetails", "(", "target", ",", "all", ")", ".", "writable", ")", ")", "{", "if", "(", "all", "!==", "'attributes'", ")", "target", "[", "all", "]", "=", "arg", "[", "all", "]", ";", "}", "}", "}", "return", "target", ";", "}" ]
Merges all objects provided as parameters into the first parameter object @param {...Object} args list of arguments @return {Object} the merged object (same as first argument)
[ "Merges", "all", "objects", "provided", "as", "parameters", "into", "the", "first", "parameter", "object" ]
a9d1de87ad80fe2d106fd84a0c20984c0f3ab125
https://github.com/AndCake/zino/blob/a9d1de87ad80fe2d106fd84a0c20984c0f3ab125/zino-ssr.js#L22-L36
53,903
AndCake/zino
zino-ssr.js
getInnerHTML
function getInnerHTML(node) { if (!node.children) return ''; if (!isArray(node.children) && typeof HTMLCollection !== 'undefined' && !(node.children instanceof HTMLCollection)) node.children = [node.children]; return (isArray(node) && node || (typeof HTMLCollection !== 'undefined' && node.children instanceof HTMLCollection ? [].slice.call(node.children) : node.children)).map(function (child) { if ((typeof child === 'undefined' ? 'undefined' : _typeof(child)) !== 'object') { return '' + child; } else if (isArray(child)) { return getInnerHTML(child); } else { var attributes = [''].concat(Object.keys(child.attributes).map(function (attr) { return attr + '="' + child.attributes[attr].value + '"'; })); if (['img', 'link', 'meta', 'input', 'br', 'area', 'base', 'param', 'source', 'hr', 'embed'].indexOf(child.tagName) < 0) { return '<' + child.tagName + attributes.join(' ') + '>' + getInnerHTML(child) + '</' + child.tagName + '>'; } else { return '<' + child.tagName + attributes.join(' ') + '/>'; } } }).join(''); }
javascript
function getInnerHTML(node) { if (!node.children) return ''; if (!isArray(node.children) && typeof HTMLCollection !== 'undefined' && !(node.children instanceof HTMLCollection)) node.children = [node.children]; return (isArray(node) && node || (typeof HTMLCollection !== 'undefined' && node.children instanceof HTMLCollection ? [].slice.call(node.children) : node.children)).map(function (child) { if ((typeof child === 'undefined' ? 'undefined' : _typeof(child)) !== 'object') { return '' + child; } else if (isArray(child)) { return getInnerHTML(child); } else { var attributes = [''].concat(Object.keys(child.attributes).map(function (attr) { return attr + '="' + child.attributes[attr].value + '"'; })); if (['img', 'link', 'meta', 'input', 'br', 'area', 'base', 'param', 'source', 'hr', 'embed'].indexOf(child.tagName) < 0) { return '<' + child.tagName + attributes.join(' ') + '>' + getInnerHTML(child) + '</' + child.tagName + '>'; } else { return '<' + child.tagName + attributes.join(' ') + '/>'; } } }).join(''); }
[ "function", "getInnerHTML", "(", "node", ")", "{", "if", "(", "!", "node", ".", "children", ")", "return", "''", ";", "if", "(", "!", "isArray", "(", "node", ".", "children", ")", "&&", "typeof", "HTMLCollection", "!==", "'undefined'", "&&", "!", "(", "node", ".", "children", "instanceof", "HTMLCollection", ")", ")", "node", ".", "children", "=", "[", "node", ".", "children", "]", ";", "return", "(", "isArray", "(", "node", ")", "&&", "node", "||", "(", "typeof", "HTMLCollection", "!==", "'undefined'", "&&", "node", ".", "children", "instanceof", "HTMLCollection", "?", "[", "]", ".", "slice", ".", "call", "(", "node", ".", "children", ")", ":", "node", ".", "children", ")", ")", ".", "map", "(", "function", "(", "child", ")", "{", "if", "(", "(", "typeof", "child", "===", "'undefined'", "?", "'undefined'", ":", "_typeof", "(", "child", ")", ")", "!==", "'object'", ")", "{", "return", "''", "+", "child", ";", "}", "else", "if", "(", "isArray", "(", "child", ")", ")", "{", "return", "getInnerHTML", "(", "child", ")", ";", "}", "else", "{", "var", "attributes", "=", "[", "''", "]", ".", "concat", "(", "Object", ".", "keys", "(", "child", ".", "attributes", ")", ".", "map", "(", "function", "(", "attr", ")", "{", "return", "attr", "+", "'=\"'", "+", "child", ".", "attributes", "[", "attr", "]", ".", "value", "+", "'\"'", ";", "}", ")", ")", ";", "if", "(", "[", "'img'", ",", "'link'", ",", "'meta'", ",", "'input'", ",", "'br'", ",", "'area'", ",", "'base'", ",", "'param'", ",", "'source'", ",", "'hr'", ",", "'embed'", "]", ".", "indexOf", "(", "child", ".", "tagName", ")", "<", "0", ")", "{", "return", "'<'", "+", "child", ".", "tagName", "+", "attributes", ".", "join", "(", "' '", ")", "+", "'>'", "+", "getInnerHTML", "(", "child", ")", "+", "'</'", "+", "child", ".", "tagName", "+", "'>'", ";", "}", "else", "{", "return", "'<'", "+", "child", ".", "tagName", "+", "attributes", ".", "join", "(", "' '", ")", "+", "'/>'", ";", "}", "}", "}", ")", ".", "join", "(", "''", ")", ";", "}" ]
Calculates the HTML structure as a String represented by the VDOM @param {Object} node - the VDOM node whose inner HTML to generate @return {String} - the HTML structure representing the VDOM
[ "Calculates", "the", "HTML", "structure", "as", "a", "String", "represented", "by", "the", "VDOM" ]
a9d1de87ad80fe2d106fd84a0c20984c0f3ab125
https://github.com/AndCake/zino/blob/a9d1de87ad80fe2d106fd84a0c20984c0f3ab125/zino-ssr.js#L216-L236
53,904
AndCake/zino
zino-ssr.js
createElement
function createElement(node, document) { var tag = void 0; if ((typeof node === 'undefined' ? 'undefined' : _typeof(node)) !== 'object') { // we have a text node, so create one tag = document.createTextNode('' + node); } else { tag = document.createElement(node.tagName); // add all required attributes Object.keys(node.attributes).forEach(function (attr) { tag.setAttribute(attr, node.attributes[attr].value); }); // define it's inner structure tag.innerHTML = getInnerHTML(node); tag.__hash = node.__hash; attachSetAttribute(tag); } return tag; }
javascript
function createElement(node, document) { var tag = void 0; if ((typeof node === 'undefined' ? 'undefined' : _typeof(node)) !== 'object') { // we have a text node, so create one tag = document.createTextNode('' + node); } else { tag = document.createElement(node.tagName); // add all required attributes Object.keys(node.attributes).forEach(function (attr) { tag.setAttribute(attr, node.attributes[attr].value); }); // define it's inner structure tag.innerHTML = getInnerHTML(node); tag.__hash = node.__hash; attachSetAttribute(tag); } return tag; }
[ "function", "createElement", "(", "node", ",", "document", ")", "{", "var", "tag", "=", "void", "0", ";", "if", "(", "(", "typeof", "node", "===", "'undefined'", "?", "'undefined'", ":", "_typeof", "(", "node", ")", ")", "!==", "'object'", ")", "{", "// we have a text node, so create one", "tag", "=", "document", ".", "createTextNode", "(", "''", "+", "node", ")", ";", "}", "else", "{", "tag", "=", "document", ".", "createElement", "(", "node", ".", "tagName", ")", ";", "// add all required attributes", "Object", ".", "keys", "(", "node", ".", "attributes", ")", ".", "forEach", "(", "function", "(", "attr", ")", "{", "tag", ".", "setAttribute", "(", "attr", ",", "node", ".", "attributes", "[", "attr", "]", ".", "value", ")", ";", "}", ")", ";", "// define it's inner structure", "tag", ".", "innerHTML", "=", "getInnerHTML", "(", "node", ")", ";", "tag", ".", "__hash", "=", "node", ".", "__hash", ";", "attachSetAttribute", "(", "tag", ")", ";", "}", "return", "tag", ";", "}" ]
Creates a new DOM node @param {Object|String} node - a VDOM node @param {Document} document - the document in which to create the DOM node @return {Node} - the DOM node created (either a text element or an HTML element)
[ "Creates", "a", "new", "DOM", "node" ]
a9d1de87ad80fe2d106fd84a0c20984c0f3ab125
https://github.com/AndCake/zino/blob/a9d1de87ad80fe2d106fd84a0c20984c0f3ab125/zino-ssr.js#L263-L281
53,905
changchang/stream-pkg
lib/composer.js
function(opts) { EventEmitter.call(this); opts = opts || {}; this.maxLength = opts.maxLength || DEFAULT_MAX_LENGTH; this.offset = 0; this.left = 0; this.length = 0; this.buf = null; this.state = ST_LENGTH; }
javascript
function(opts) { EventEmitter.call(this); opts = opts || {}; this.maxLength = opts.maxLength || DEFAULT_MAX_LENGTH; this.offset = 0; this.left = 0; this.length = 0; this.buf = null; this.state = ST_LENGTH; }
[ "function", "(", "opts", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "opts", "=", "opts", "||", "{", "}", ";", "this", ".", "maxLength", "=", "opts", ".", "maxLength", "||", "DEFAULT_MAX_LENGTH", ";", "this", ".", "offset", "=", "0", ";", "this", ".", "left", "=", "0", ";", "this", ".", "length", "=", "0", ";", "this", ".", "buf", "=", "null", ";", "this", ".", "state", "=", "ST_LENGTH", ";", "}" ]
state that something wrong has happened
[ "state", "that", "something", "wrong", "has", "happened" ]
b8c2ab9fb2ce537a3c786588e798a7b5be3e11eb
https://github.com/changchang/stream-pkg/blob/b8c2ab9fb2ce537a3c786588e798a7b5be3e11eb/lib/composer.js#L11-L23
53,906
viskan/log4js-logstash-appender
index.js
send
function send(socket, host, port, loggingObject) { var buffer = new Buffer(JSON.stringify(loggingObject)); socket.send(buffer, 0, buffer.length, port, host, function(err, bytes) { if (err) { console.error('log4js-logstash-appender (%s:%p) - %s', host, port, util.inspect(err)); } }); }
javascript
function send(socket, host, port, loggingObject) { var buffer = new Buffer(JSON.stringify(loggingObject)); socket.send(buffer, 0, buffer.length, port, host, function(err, bytes) { if (err) { console.error('log4js-logstash-appender (%s:%p) - %s', host, port, util.inspect(err)); } }); }
[ "function", "send", "(", "socket", ",", "host", ",", "port", ",", "loggingObject", ")", "{", "var", "buffer", "=", "new", "Buffer", "(", "JSON", ".", "stringify", "(", "loggingObject", ")", ")", ";", "socket", ".", "send", "(", "buffer", ",", "0", ",", "buffer", ".", "length", ",", "port", ",", "host", ",", "function", "(", "err", ",", "bytes", ")", "{", "if", "(", "err", ")", "{", "console", ".", "error", "(", "'log4js-logstash-appender (%s:%p) - %s'", ",", "host", ",", "port", ",", "util", ".", "inspect", "(", "err", ")", ")", ";", "}", "}", ")", ";", "}" ]
Sends data to logstash.
[ "Sends", "data", "to", "logstash", "." ]
08722aa00714abf86866aa45826ced454b32fd14
https://github.com/viskan/log4js-logstash-appender/blob/08722aa00714abf86866aa45826ced454b32fd14/index.js#L10-L20
53,907
viskan/log4js-logstash-appender
index.js
appender
function appender(configuration) { var socket = dgram.createSocket('udp4'); return function(loggingEvent) { var loggingObject = { name: loggingEvent.categoryName, message: layout(loggingEvent), severity: loggingEvent.level.level, severityText: loggingEvent.level.levelStr, }; if (configuration.application) { loggingObject.application = configuration.application; } if (configuration.environment) { loggingObject.environment = configuration.environment; } if (MDC && MDC.active) { Object.keys(MDC.active).forEach(function(key) { loggingObject[key] = MDC.active[key]; }); } send(socket, configuration.host, configuration.port, loggingObject); }; }
javascript
function appender(configuration) { var socket = dgram.createSocket('udp4'); return function(loggingEvent) { var loggingObject = { name: loggingEvent.categoryName, message: layout(loggingEvent), severity: loggingEvent.level.level, severityText: loggingEvent.level.levelStr, }; if (configuration.application) { loggingObject.application = configuration.application; } if (configuration.environment) { loggingObject.environment = configuration.environment; } if (MDC && MDC.active) { Object.keys(MDC.active).forEach(function(key) { loggingObject[key] = MDC.active[key]; }); } send(socket, configuration.host, configuration.port, loggingObject); }; }
[ "function", "appender", "(", "configuration", ")", "{", "var", "socket", "=", "dgram", ".", "createSocket", "(", "'udp4'", ")", ";", "return", "function", "(", "loggingEvent", ")", "{", "var", "loggingObject", "=", "{", "name", ":", "loggingEvent", ".", "categoryName", ",", "message", ":", "layout", "(", "loggingEvent", ")", ",", "severity", ":", "loggingEvent", ".", "level", ".", "level", ",", "severityText", ":", "loggingEvent", ".", "level", ".", "levelStr", ",", "}", ";", "if", "(", "configuration", ".", "application", ")", "{", "loggingObject", ".", "application", "=", "configuration", ".", "application", ";", "}", "if", "(", "configuration", ".", "environment", ")", "{", "loggingObject", ".", "environment", "=", "configuration", ".", "environment", ";", "}", "if", "(", "MDC", "&&", "MDC", ".", "active", ")", "{", "Object", ".", "keys", "(", "MDC", ".", "active", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "loggingObject", "[", "key", "]", "=", "MDC", ".", "active", "[", "key", "]", ";", "}", ")", ";", "}", "send", "(", "socket", ",", "configuration", ".", "host", ",", "configuration", ".", "port", ",", "loggingObject", ")", ";", "}", ";", "}" ]
Returns the appender.
[ "Returns", "the", "appender", "." ]
08722aa00714abf86866aa45826ced454b32fd14
https://github.com/viskan/log4js-logstash-appender/blob/08722aa00714abf86866aa45826ced454b32fd14/index.js#L23-L57
53,908
wilmoore/inarray.js
index.js
inarray
function inarray (list, item) { list = Object.prototype.toString.call(list) === '[object Array]' ? list : [] var idx = -1 var end = list.length while (++idx < end) { if (list[idx] === item) return true } return false }
javascript
function inarray (list, item) { list = Object.prototype.toString.call(list) === '[object Array]' ? list : [] var idx = -1 var end = list.length while (++idx < end) { if (list[idx] === item) return true } return false }
[ "function", "inarray", "(", "list", ",", "item", ")", "{", "list", "=", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "list", ")", "===", "'[object Array]'", "?", "list", ":", "[", "]", "var", "idx", "=", "-", "1", "var", "end", "=", "list", ".", "length", "while", "(", "++", "idx", "<", "end", ")", "{", "if", "(", "list", "[", "idx", "]", "===", "item", ")", "return", "true", "}", "return", "false", "}" ]
Whether given value exists in array. @param {Array} list The list to search. @param {*} item The item/value to search for. @return {Boolean} Whether given value exists in array.
[ "Whether", "given", "value", "exists", "in", "array", "." ]
8ea7cd7efb10d46e56ebed08427e0297d525c458
https://github.com/wilmoore/inarray.js/blob/8ea7cd7efb10d46e56ebed08427e0297d525c458/index.js#L28-L39
53,909
coen-hyde/gulp-cog
index.js
getIncludes
function getIncludes(file) { var content = String(file.contents); var matches = []; while (regexMatch = DIRECTIVE_REGEX.exec(content)) { matches.push(regexMatch); } // For every require fetch it's matching files var fileLists = _.map(matches, function(match) { return globMatch(match, file).sort(); }); // Merge all matching file lists into one concat list var order = _.reduce(fileLists, function(memo, fileList) { return _.union(memo, fileList); }, []); // And self to include list order.push(file.relative); return order; }
javascript
function getIncludes(file) { var content = String(file.contents); var matches = []; while (regexMatch = DIRECTIVE_REGEX.exec(content)) { matches.push(regexMatch); } // For every require fetch it's matching files var fileLists = _.map(matches, function(match) { return globMatch(match, file).sort(); }); // Merge all matching file lists into one concat list var order = _.reduce(fileLists, function(memo, fileList) { return _.union(memo, fileList); }, []); // And self to include list order.push(file.relative); return order; }
[ "function", "getIncludes", "(", "file", ")", "{", "var", "content", "=", "String", "(", "file", ".", "contents", ")", ";", "var", "matches", "=", "[", "]", ";", "while", "(", "regexMatch", "=", "DIRECTIVE_REGEX", ".", "exec", "(", "content", ")", ")", "{", "matches", ".", "push", "(", "regexMatch", ")", ";", "}", "// For every require fetch it's matching files", "var", "fileLists", "=", "_", ".", "map", "(", "matches", ",", "function", "(", "match", ")", "{", "return", "globMatch", "(", "match", ",", "file", ")", ".", "sort", "(", ")", ";", "}", ")", ";", "// Merge all matching file lists into one concat list", "var", "order", "=", "_", ".", "reduce", "(", "fileLists", ",", "function", "(", "memo", ",", "fileList", ")", "{", "return", "_", ".", "union", "(", "memo", ",", "fileList", ")", ";", "}", ",", "[", "]", ")", ";", "// And self to include list", "order", ".", "push", "(", "file", ".", "relative", ")", ";", "return", "order", ";", "}" ]
Get all includes for a file
[ "Get", "all", "includes", "for", "a", "file" ]
c96c71e4bbb3426a5580ba3029b003563ab13da6
https://github.com/coen-hyde/gulp-cog/blob/c96c71e4bbb3426a5580ba3029b003563ab13da6/index.js#L32-L53
53,910
coen-hyde/gulp-cog
index.js
globMatch
function globMatch(match, file) { var directiveType = match[1]; var globPattern = match[2]; // relative file // require all files under a directory if (directiveType.indexOf('_tree') !== -1) { globPattern = globPattern.concat('/**/*'); directiveType = directiveType.replace('_tree', ''); } // require only first level files in a directory if (directiveType.indexOf('_directory') !== -1) { globPattern = globPattern.concat('/*'); directiveType = directiveType.replace('_directory', ''); } // Only require and include directives are allowed if (directiveType !== 'require' && directiveType !== 'include') { return []; } // Add file extension to glob pattern if not already set var jsExt = '.js'; if (globPattern.substr(globPattern.length-jsExt.length).indexOf(jsExt) !== 0) { globPattern += jsExt; } // Append the current dir to include so we can match the glob against the file list var relativeDir = getRelativeDir(file); globPattern = relativeDir+globPattern; var possibleIncludes = []; _.each(_.keys(allFiles), function(fileName) { // Only process files in the current directory. ../ will not work. if (fileName.indexOf(relativeDir) !== 0) { return; } possibleIncludes.push(fileName); }); return minimatch.match(possibleIncludes, globPattern); }
javascript
function globMatch(match, file) { var directiveType = match[1]; var globPattern = match[2]; // relative file // require all files under a directory if (directiveType.indexOf('_tree') !== -1) { globPattern = globPattern.concat('/**/*'); directiveType = directiveType.replace('_tree', ''); } // require only first level files in a directory if (directiveType.indexOf('_directory') !== -1) { globPattern = globPattern.concat('/*'); directiveType = directiveType.replace('_directory', ''); } // Only require and include directives are allowed if (directiveType !== 'require' && directiveType !== 'include') { return []; } // Add file extension to glob pattern if not already set var jsExt = '.js'; if (globPattern.substr(globPattern.length-jsExt.length).indexOf(jsExt) !== 0) { globPattern += jsExt; } // Append the current dir to include so we can match the glob against the file list var relativeDir = getRelativeDir(file); globPattern = relativeDir+globPattern; var possibleIncludes = []; _.each(_.keys(allFiles), function(fileName) { // Only process files in the current directory. ../ will not work. if (fileName.indexOf(relativeDir) !== 0) { return; } possibleIncludes.push(fileName); }); return minimatch.match(possibleIncludes, globPattern); }
[ "function", "globMatch", "(", "match", ",", "file", ")", "{", "var", "directiveType", "=", "match", "[", "1", "]", ";", "var", "globPattern", "=", "match", "[", "2", "]", ";", "// relative file", "// require all files under a directory", "if", "(", "directiveType", ".", "indexOf", "(", "'_tree'", ")", "!==", "-", "1", ")", "{", "globPattern", "=", "globPattern", ".", "concat", "(", "'/**/*'", ")", ";", "directiveType", "=", "directiveType", ".", "replace", "(", "'_tree'", ",", "''", ")", ";", "}", "// require only first level files in a directory", "if", "(", "directiveType", ".", "indexOf", "(", "'_directory'", ")", "!==", "-", "1", ")", "{", "globPattern", "=", "globPattern", ".", "concat", "(", "'/*'", ")", ";", "directiveType", "=", "directiveType", ".", "replace", "(", "'_directory'", ",", "''", ")", ";", "}", "// Only require and include directives are allowed", "if", "(", "directiveType", "!==", "'require'", "&&", "directiveType", "!==", "'include'", ")", "{", "return", "[", "]", ";", "}", "// Add file extension to glob pattern if not already set", "var", "jsExt", "=", "'.js'", ";", "if", "(", "globPattern", ".", "substr", "(", "globPattern", ".", "length", "-", "jsExt", ".", "length", ")", ".", "indexOf", "(", "jsExt", ")", "!==", "0", ")", "{", "globPattern", "+=", "jsExt", ";", "}", "// Append the current dir to include so we can match the glob against the file list", "var", "relativeDir", "=", "getRelativeDir", "(", "file", ")", ";", "globPattern", "=", "relativeDir", "+", "globPattern", ";", "var", "possibleIncludes", "=", "[", "]", ";", "_", ".", "each", "(", "_", ".", "keys", "(", "allFiles", ")", ",", "function", "(", "fileName", ")", "{", "// Only process files in the current directory. ../ will not work.", "if", "(", "fileName", ".", "indexOf", "(", "relativeDir", ")", "!==", "0", ")", "{", "return", ";", "}", "possibleIncludes", ".", "push", "(", "fileName", ")", ";", "}", ")", ";", "return", "minimatch", ".", "match", "(", "possibleIncludes", ",", "globPattern", ")", ";", "}" ]
Translate an include match to a glob
[ "Translate", "an", "include", "match", "to", "a", "glob" ]
c96c71e4bbb3426a5580ba3029b003563ab13da6
https://github.com/coen-hyde/gulp-cog/blob/c96c71e4bbb3426a5580ba3029b003563ab13da6/index.js#L64-L106
53,911
Psychopoulet/node-logs
lib/inputInterfaces.js
_inputInterfaces
function _inputInterfaces (interfaces, msg, type, options, i = 0) { return i >= interfaces.length ? Promise.resolve() : Promise.resolve().then(() => { let result = null; switch (type) { case "log": result = interfaces[i].log(msg, options); break; case "success": result = interfaces[i].success(msg, options); break; case "information": result = interfaces[i].information(msg, options); break; case "warning": result = interfaces[i].warning(msg, options); break; case "error": result = interfaces[i].error(msg, options); break; default: // nothing to do here break; } return null === result ? Promise.resolve() : Promise.resolve().then(() => { if ("boolean" === typeof result) { return result ? Promise.resolve() : Promise.reject( new Error("Impossible to log \"" + msg + "\" message with \"" + type + "\" type on all the interfaces") ); } else { return "object" === typeof result && result instanceof Promise ? result : Promise.resolve(); } }).then(() => { return _inputInterfaces(interfaces, msg, type, options, i + 1); }); }); }
javascript
function _inputInterfaces (interfaces, msg, type, options, i = 0) { return i >= interfaces.length ? Promise.resolve() : Promise.resolve().then(() => { let result = null; switch (type) { case "log": result = interfaces[i].log(msg, options); break; case "success": result = interfaces[i].success(msg, options); break; case "information": result = interfaces[i].information(msg, options); break; case "warning": result = interfaces[i].warning(msg, options); break; case "error": result = interfaces[i].error(msg, options); break; default: // nothing to do here break; } return null === result ? Promise.resolve() : Promise.resolve().then(() => { if ("boolean" === typeof result) { return result ? Promise.resolve() : Promise.reject( new Error("Impossible to log \"" + msg + "\" message with \"" + type + "\" type on all the interfaces") ); } else { return "object" === typeof result && result instanceof Promise ? result : Promise.resolve(); } }).then(() => { return _inputInterfaces(interfaces, msg, type, options, i + 1); }); }); }
[ "function", "_inputInterfaces", "(", "interfaces", ",", "msg", ",", "type", ",", "options", ",", "i", "=", "0", ")", "{", "return", "i", ">=", "interfaces", ".", "length", "?", "Promise", ".", "resolve", "(", ")", ":", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "let", "result", "=", "null", ";", "switch", "(", "type", ")", "{", "case", "\"log\"", ":", "result", "=", "interfaces", "[", "i", "]", ".", "log", "(", "msg", ",", "options", ")", ";", "break", ";", "case", "\"success\"", ":", "result", "=", "interfaces", "[", "i", "]", ".", "success", "(", "msg", ",", "options", ")", ";", "break", ";", "case", "\"information\"", ":", "result", "=", "interfaces", "[", "i", "]", ".", "information", "(", "msg", ",", "options", ")", ";", "break", ";", "case", "\"warning\"", ":", "result", "=", "interfaces", "[", "i", "]", ".", "warning", "(", "msg", ",", "options", ")", ";", "break", ";", "case", "\"error\"", ":", "result", "=", "interfaces", "[", "i", "]", ".", "error", "(", "msg", ",", "options", ")", ";", "break", ";", "default", ":", "// nothing to do here", "break", ";", "}", "return", "null", "===", "result", "?", "Promise", ".", "resolve", "(", ")", ":", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "if", "(", "\"boolean\"", "===", "typeof", "result", ")", "{", "return", "result", "?", "Promise", ".", "resolve", "(", ")", ":", "Promise", ".", "reject", "(", "new", "Error", "(", "\"Impossible to log \\\"\"", "+", "msg", "+", "\"\\\" message with \\\"\"", "+", "type", "+", "\"\\\" type on all the interfaces\"", ")", ")", ";", "}", "else", "{", "return", "\"object\"", "===", "typeof", "result", "&&", "result", "instanceof", "Promise", "?", "result", ":", "Promise", ".", "resolve", "(", ")", ";", "}", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "return", "_inputInterfaces", "(", "interfaces", ",", "msg", ",", "type", ",", "options", ",", "i", "+", "1", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
methods Execute interfaces @param {Array} interfaces all interfaces @param {string} msg message to log @param {string} type log type @param {null|object} options style options @param {number} i cursor @returns {Promise} Operation result
[ "methods", "Execute", "interfaces" ]
907c341ad87452604bf2dc86e92e6bb7220b88e2
https://github.com/Psychopoulet/node-logs/blob/907c341ad87452604bf2dc86e92e6bb7220b88e2/lib/inputInterfaces.js#L20-L69
53,912
deanlandolt/endo
auth.js
auth
function auth(endo, options) { options || (options = {}); // // add token utility methods, binding first options arg // endo.createToken = auth.createToken.bind(null, options.sign); endo.verifyToken = auth.verifyToken.bind(null, options.verify); // // verify provided credentials are valid and set user auth on request // var _parseRequest = endo.parseRequest; endo.parseRequest = function() { var request = _parseRequest.apply(this, arguments); return Promise.resolve(request).then(this.authenticate.bind(this)); }; endo.authenticate = function (request) { // // no auth if request already contains user auth data // if (request.user !== undefined) { return; } // // parse authorization header for JWT token // request.headers || (request.headers || {}); var header = request.headers && request.headers.authorization || ''; var match = header.match(BEARER_RE); if (!match) { throw new util.UnauthorizedError('Token required'); } return auth.verifyToken(match[1]) .then(endo.handleAuthentication.bind(endo, request)) }; // // implementations may wrap this method perform additional verification // endo.handleAuthentication = function (request, data) { request.user = data || null; }; return endo; }
javascript
function auth(endo, options) { options || (options = {}); // // add token utility methods, binding first options arg // endo.createToken = auth.createToken.bind(null, options.sign); endo.verifyToken = auth.verifyToken.bind(null, options.verify); // // verify provided credentials are valid and set user auth on request // var _parseRequest = endo.parseRequest; endo.parseRequest = function() { var request = _parseRequest.apply(this, arguments); return Promise.resolve(request).then(this.authenticate.bind(this)); }; endo.authenticate = function (request) { // // no auth if request already contains user auth data // if (request.user !== undefined) { return; } // // parse authorization header for JWT token // request.headers || (request.headers || {}); var header = request.headers && request.headers.authorization || ''; var match = header.match(BEARER_RE); if (!match) { throw new util.UnauthorizedError('Token required'); } return auth.verifyToken(match[1]) .then(endo.handleAuthentication.bind(endo, request)) }; // // implementations may wrap this method perform additional verification // endo.handleAuthentication = function (request, data) { request.user = data || null; }; return endo; }
[ "function", "auth", "(", "endo", ",", "options", ")", "{", "options", "||", "(", "options", "=", "{", "}", ")", ";", "//", "// add token utility methods, binding first options arg", "//", "endo", ".", "createToken", "=", "auth", ".", "createToken", ".", "bind", "(", "null", ",", "options", ".", "sign", ")", ";", "endo", ".", "verifyToken", "=", "auth", ".", "verifyToken", ".", "bind", "(", "null", ",", "options", ".", "verify", ")", ";", "//", "// verify provided credentials are valid and set user auth on request", "//", "var", "_parseRequest", "=", "endo", ".", "parseRequest", ";", "endo", ".", "parseRequest", "=", "function", "(", ")", "{", "var", "request", "=", "_parseRequest", ".", "apply", "(", "this", ",", "arguments", ")", ";", "return", "Promise", ".", "resolve", "(", "request", ")", ".", "then", "(", "this", ".", "authenticate", ".", "bind", "(", "this", ")", ")", ";", "}", ";", "endo", ".", "authenticate", "=", "function", "(", "request", ")", "{", "//", "// no auth if request already contains user auth data", "//", "if", "(", "request", ".", "user", "!==", "undefined", ")", "{", "return", ";", "}", "//", "// parse authorization header for JWT token", "//", "request", ".", "headers", "||", "(", "request", ".", "headers", "||", "{", "}", ")", ";", "var", "header", "=", "request", ".", "headers", "&&", "request", ".", "headers", ".", "authorization", "||", "''", ";", "var", "match", "=", "header", ".", "match", "(", "BEARER_RE", ")", ";", "if", "(", "!", "match", ")", "{", "throw", "new", "util", ".", "UnauthorizedError", "(", "'Token required'", ")", ";", "}", "return", "auth", ".", "verifyToken", "(", "match", "[", "1", "]", ")", ".", "then", "(", "endo", ".", "handleAuthentication", ".", "bind", "(", "endo", ",", "request", ")", ")", "}", ";", "//", "// implementations may wrap this method perform additional verification", "//", "endo", ".", "handleAuthentication", "=", "function", "(", "request", ",", "data", ")", "{", "request", ".", "user", "=", "data", "||", "null", ";", "}", ";", "return", "endo", ";", "}" ]
wrapper to add JWT-based bearer auth to an endo instance
[ "wrapper", "to", "add", "JWT", "-", "based", "bearer", "auth", "to", "an", "endo", "instance" ]
e96234226e3a56e5c71b7f68690b5cc98123ed03
https://github.com/deanlandolt/endo/blob/e96234226e3a56e5c71b7f68690b5cc98123ed03/auth.js#L12-L60
53,913
supercrabtree/tie-dye
hslToRgb.js
hslToRgb
function hslToRgb(h, s, l) { h /= 360; s /= 100; l /= 100; var r, g, b; if (s === 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hueToRgb(p, q, h + 1 / 3); g = hueToRgb(p, q, h); b = hueToRgb(p, q, h - 1 / 3); } return ({ r: r * 255, g: g * 255, b: b * 255 }); }
javascript
function hslToRgb(h, s, l) { h /= 360; s /= 100; l /= 100; var r, g, b; if (s === 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hueToRgb(p, q, h + 1 / 3); g = hueToRgb(p, q, h); b = hueToRgb(p, q, h - 1 / 3); } return ({ r: r * 255, g: g * 255, b: b * 255 }); }
[ "function", "hslToRgb", "(", "h", ",", "s", ",", "l", ")", "{", "h", "/=", "360", ";", "s", "/=", "100", ";", "l", "/=", "100", ";", "var", "r", ",", "g", ",", "b", ";", "if", "(", "s", "===", "0", ")", "{", "r", "=", "g", "=", "b", "=", "l", ";", "// achromatic", "}", "else", "{", "var", "q", "=", "l", "<", "0.5", "?", "l", "*", "(", "1", "+", "s", ")", ":", "l", "+", "s", "-", "l", "*", "s", ";", "var", "p", "=", "2", "*", "l", "-", "q", ";", "r", "=", "hueToRgb", "(", "p", ",", "q", ",", "h", "+", "1", "/", "3", ")", ";", "g", "=", "hueToRgb", "(", "p", ",", "q", ",", "h", ")", ";", "b", "=", "hueToRgb", "(", "p", ",", "q", ",", "h", "-", "1", "/", "3", ")", ";", "}", "return", "(", "{", "r", ":", "r", "*", "255", ",", "g", ":", "g", "*", "255", ",", "b", ":", "b", "*", "255", "}", ")", ";", "}" ]
Convert a color from HSL to RGB @param {number} h - A value from 0 - 360 @param {number} s - A value from 0 - 100 @param {number} l - A value from 0 - 100 @returns {object} With the signature {r: 0-255, g: 0-255, b: 0-255}
[ "Convert", "a", "color", "from", "HSL", "to", "RGB" ]
1bf045767ce1a3fcf88450fbf95f72b5646f63df
https://github.com/supercrabtree/tie-dye/blob/1bf045767ce1a3fcf88450fbf95f72b5646f63df/hslToRgb.js#L11-L34
53,914
jfseb/mgnlq_model
js/match/breakdown.js
isCombinableSplit
function isCombinableSplit(tokenized) { if (tokenized.tokens.length <= 1) { return false; } for (var i = 1; i < tokenized.tokens.length; ++i) { if (!tokenized.fusable[i]) { return false; } } return true; }
javascript
function isCombinableSplit(tokenized) { if (tokenized.tokens.length <= 1) { return false; } for (var i = 1; i < tokenized.tokens.length; ++i) { if (!tokenized.fusable[i]) { return false; } } return true; }
[ "function", "isCombinableSplit", "(", "tokenized", ")", "{", "if", "(", "tokenized", ".", "tokens", ".", "length", "<=", "1", ")", "{", "return", "false", ";", "}", "for", "(", "var", "i", "=", "1", ";", "i", "<", "tokenized", ".", "tokens", ".", "length", ";", "++", "i", ")", "{", "if", "(", "!", "tokenized", ".", "fusable", "[", "i", "]", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Returns true iff tokenized represents multiple words, which can potenially be added together;
[ "Returns", "true", "iff", "tokenized", "represents", "multiple", "words", "which", "can", "potenially", "be", "added", "together", ";" ]
be1be4406b05718d666d6d0f712c9cadb5169f2c
https://github.com/jfseb/mgnlq_model/blob/be1be4406b05718d666d6d0f712c9cadb5169f2c/js/match/breakdown.js#L157-L167
53,915
mini-eggs/babel-plugin-css-modules
src/main.js
toCssModule
function toCssModule(styles) { var done = false; var res; new modules().load(styles, prefix + uni()).then(function(next) { done = true; res = next; }); deasync.loopWhile(function() { return !done; }); return res; }
javascript
function toCssModule(styles) { var done = false; var res; new modules().load(styles, prefix + uni()).then(function(next) { done = true; res = next; }); deasync.loopWhile(function() { return !done; }); return res; }
[ "function", "toCssModule", "(", "styles", ")", "{", "var", "done", "=", "false", ";", "var", "res", ";", "new", "modules", "(", ")", ".", "load", "(", "styles", ",", "prefix", "+", "uni", "(", ")", ")", ".", "then", "(", "function", "(", "next", ")", "{", "done", "=", "true", ";", "res", "=", "next", ";", "}", ")", ";", "deasync", ".", "loopWhile", "(", "function", "(", ")", "{", "return", "!", "done", ";", "}", ")", ";", "return", "res", ";", "}" ]
sync create css module
[ "sync", "create", "css", "module" ]
37960a59a0d732ed70fd8ed27805f360246341d9
https://github.com/mini-eggs/babel-plugin-css-modules/blob/37960a59a0d732ed70fd8ed27805f360246341d9/src/main.js#L15-L29
53,916
smikes/molfile
lib/parser.js
SDFSplitter
function SDFSplitter(handler) { parser.SDFTransform.call(this); this.on('data', function (chunk) { handler(String(chunk)); }); }
javascript
function SDFSplitter(handler) { parser.SDFTransform.call(this); this.on('data', function (chunk) { handler(String(chunk)); }); }
[ "function", "SDFSplitter", "(", "handler", ")", "{", "parser", ".", "SDFTransform", ".", "call", "(", "this", ")", ";", "this", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "handler", "(", "String", "(", "chunk", ")", ")", ";", "}", ")", ";", "}" ]
A Writable stream that splits an SDF file into individual MOL file segments suitable for passing to parseMol. Output is via callback. See SDFTransform for output via Streams API @class SDFSplitter @constructor @method SDFSplitter @param {Function} callback function to call with molfile data @return {SDFSplitter} a Writable stream which calls the supplied callback once per molfile in the supplied SDFSplitter stream
[ "A", "Writable", "stream", "that", "splits", "an", "SDF", "file", "into", "individual", "MOL", "file", "segments", "suitable", "for", "passing", "to", "parseMol", "." ]
d851fab7f963b27deca945255be9eb0d26dd57bd
https://github.com/smikes/molfile/blob/d851fab7f963b27deca945255be9eb0d26dd57bd/lib/parser.js#L521-L527
53,917
jwilm/pygments-async
lib/pygmentize_options.js
PygmentizeOptions
function PygmentizeOptions (options) { if(!(this instanceof PygmentizeOptions)) return new PygmentizeOptions(options); if(options.lexer && validate.lexer.test(options.lexer)) this.lexer = options.lexer; if(options.guess && !this.lexer) this.guess = true; if(options.formatter && validate.formatter.test(options.formatter)) this.formatter = options.formatter; else this.formatter = 'html' }
javascript
function PygmentizeOptions (options) { if(!(this instanceof PygmentizeOptions)) return new PygmentizeOptions(options); if(options.lexer && validate.lexer.test(options.lexer)) this.lexer = options.lexer; if(options.guess && !this.lexer) this.guess = true; if(options.formatter && validate.formatter.test(options.formatter)) this.formatter = options.formatter; else this.formatter = 'html' }
[ "function", "PygmentizeOptions", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "PygmentizeOptions", ")", ")", "return", "new", "PygmentizeOptions", "(", "options", ")", ";", "if", "(", "options", ".", "lexer", "&&", "validate", ".", "lexer", ".", "test", "(", "options", ".", "lexer", ")", ")", "this", ".", "lexer", "=", "options", ".", "lexer", ";", "if", "(", "options", ".", "guess", "&&", "!", "this", ".", "lexer", ")", "this", ".", "guess", "=", "true", ";", "if", "(", "options", ".", "formatter", "&&", "validate", ".", "formatter", ".", "test", "(", "options", ".", "formatter", ")", ")", "this", ".", "formatter", "=", "options", ".", "formatter", ";", "else", "this", ".", "formatter", "=", "'html'", "}" ]
Wrap an options object with convenience methods for working with pygmentize @param {Object} options
[ "Wrap", "an", "options", "object", "with", "convenience", "methods", "for", "working", "with", "pygmentize" ]
4167b1b2d53edf79f10fe2c330596e316ade5f79
https://github.com/jwilm/pygments-async/blob/4167b1b2d53edf79f10fe2c330596e316ade5f79/lib/pygmentize_options.js#L13-L28
53,918
linyngfly/omelo
lib/common/service/handlerService.js
function(app, opts) { this.app = app; this.handlerMap = {}; if(!!opts.reloadHandlers) { watchHandlers(app, this.handlerMap); } this.enableForwardLog = opts.enableForwardLog || false; }
javascript
function(app, opts) { this.app = app; this.handlerMap = {}; if(!!opts.reloadHandlers) { watchHandlers(app, this.handlerMap); } this.enableForwardLog = opts.enableForwardLog || false; }
[ "function", "(", "app", ",", "opts", ")", "{", "this", ".", "app", "=", "app", ";", "this", ".", "handlerMap", "=", "{", "}", ";", "if", "(", "!", "!", "opts", ".", "reloadHandlers", ")", "{", "watchHandlers", "(", "app", ",", "this", ".", "handlerMap", ")", ";", "}", "this", ".", "enableForwardLog", "=", "opts", ".", "enableForwardLog", "||", "false", ";", "}" ]
Handler service. Dispatch request to the relactive handler. @param {Object} app current application context
[ "Handler", "service", ".", "Dispatch", "request", "to", "the", "relactive", "handler", "." ]
fb5f79fa31c69de36bd1c370bad5edfa753ca601
https://github.com/linyngfly/omelo/blob/fb5f79fa31c69de36bd1c370bad5edfa753ca601/lib/common/service/handlerService.js#L13-L21
53,919
linyngfly/omelo
lib/common/service/handlerService.js
function(app, serverType, handlerMap) { let p = pathUtil.getHandlerPath(app.getBase(), serverType); if(p) { handlerMap[serverType] = Loader.load(p, app); } }
javascript
function(app, serverType, handlerMap) { let p = pathUtil.getHandlerPath(app.getBase(), serverType); if(p) { handlerMap[serverType] = Loader.load(p, app); } }
[ "function", "(", "app", ",", "serverType", ",", "handlerMap", ")", "{", "let", "p", "=", "pathUtil", ".", "getHandlerPath", "(", "app", ".", "getBase", "(", ")", ",", "serverType", ")", ";", "if", "(", "p", ")", "{", "handlerMap", "[", "serverType", "]", "=", "Loader", ".", "load", "(", "p", ",", "app", ")", ";", "}", "}" ]
Load handlers from current application
[ "Load", "handlers", "from", "current", "application" ]
fb5f79fa31c69de36bd1c370bad5edfa753ca601
https://github.com/linyngfly/omelo/blob/fb5f79fa31c69de36bd1c370bad5edfa753ca601/lib/common/service/handlerService.js#L96-L101
53,920
ludwigschubert/postal-react-mixin
postal-react-mixin.js
function() { if (!this.hasOwnProperty("_postalSubscriptions")) { this._postalSubscriptions = {}; } for (var topic in this.subscriptions) { if (this.subscriptions.hasOwnProperty(topic)) { var callback = this.subscriptions[topic]; this.subscribe(topic, callback); } } }
javascript
function() { if (!this.hasOwnProperty("_postalSubscriptions")) { this._postalSubscriptions = {}; } for (var topic in this.subscriptions) { if (this.subscriptions.hasOwnProperty(topic)) { var callback = this.subscriptions[topic]; this.subscribe(topic, callback); } } }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "hasOwnProperty", "(", "\"_postalSubscriptions\"", ")", ")", "{", "this", ".", "_postalSubscriptions", "=", "{", "}", ";", "}", "for", "(", "var", "topic", "in", "this", ".", "subscriptions", ")", "{", "if", "(", "this", ".", "subscriptions", ".", "hasOwnProperty", "(", "topic", ")", ")", "{", "var", "callback", "=", "this", ".", "subscriptions", "[", "topic", "]", ";", "this", ".", "subscribe", "(", "topic", ",", "callback", ")", ";", "}", "}", "}" ]
React component lifecycle methods
[ "React", "component", "lifecycle", "methods" ]
de732aa939e8a2b857e723e3b5b92b44f4155aef
https://github.com/ludwigschubert/postal-react-mixin/blob/de732aa939e8a2b857e723e3b5b92b44f4155aef/postal-react-mixin.js#L41-L51
53,921
frankban/shapeup
shapeup.js
fromShape
function fromShape(obj, propType, options=null) { const declaration = propType[SHAPE]; if (!(declaration instanceof Declaration)) { throw new Error('fromShape called with a non-shape property type'); } const shape = declaration.shape; const instance = {}; const checker = {}; Object.keys(shape).forEach(key => { const type = shape[key]; if (type[SHAPE] instanceof Reshape) { // Add the reshape function to the resulting instance. addReshape(instance, key); return; } let value = obj[key]; if (value === undefined) { // The object does not have the declared shape. // An error will be returned by PropTypes.shape. return; } if (type[SHAPE] instanceof Declaration) { // This is a nested shape type. instance[key] = fromShape(value, type); return; } if (checker.toString.call(value) === '[object Function]') { // This can be an unbound method: try to bind it. value = value.bind(obj); } instance[key] = value; }); options = options || {}; if (options.mutable) { return instance; } return deepFreeze(instance); }
javascript
function fromShape(obj, propType, options=null) { const declaration = propType[SHAPE]; if (!(declaration instanceof Declaration)) { throw new Error('fromShape called with a non-shape property type'); } const shape = declaration.shape; const instance = {}; const checker = {}; Object.keys(shape).forEach(key => { const type = shape[key]; if (type[SHAPE] instanceof Reshape) { // Add the reshape function to the resulting instance. addReshape(instance, key); return; } let value = obj[key]; if (value === undefined) { // The object does not have the declared shape. // An error will be returned by PropTypes.shape. return; } if (type[SHAPE] instanceof Declaration) { // This is a nested shape type. instance[key] = fromShape(value, type); return; } if (checker.toString.call(value) === '[object Function]') { // This can be an unbound method: try to bind it. value = value.bind(obj); } instance[key] = value; }); options = options || {}; if (options.mutable) { return instance; } return deepFreeze(instance); }
[ "function", "fromShape", "(", "obj", ",", "propType", ",", "options", "=", "null", ")", "{", "const", "declaration", "=", "propType", "[", "SHAPE", "]", ";", "if", "(", "!", "(", "declaration", "instanceof", "Declaration", ")", ")", "{", "throw", "new", "Error", "(", "'fromShape called with a non-shape property type'", ")", ";", "}", "const", "shape", "=", "declaration", ".", "shape", ";", "const", "instance", "=", "{", "}", ";", "const", "checker", "=", "{", "}", ";", "Object", ".", "keys", "(", "shape", ")", ".", "forEach", "(", "key", "=>", "{", "const", "type", "=", "shape", "[", "key", "]", ";", "if", "(", "type", "[", "SHAPE", "]", "instanceof", "Reshape", ")", "{", "// Add the reshape function to the resulting instance.", "addReshape", "(", "instance", ",", "key", ")", ";", "return", ";", "}", "let", "value", "=", "obj", "[", "key", "]", ";", "if", "(", "value", "===", "undefined", ")", "{", "// The object does not have the declared shape.", "// An error will be returned by PropTypes.shape.", "return", ";", "}", "if", "(", "type", "[", "SHAPE", "]", "instanceof", "Declaration", ")", "{", "// This is a nested shape type.", "instance", "[", "key", "]", "=", "fromShape", "(", "value", ",", "type", ")", ";", "return", ";", "}", "if", "(", "checker", ".", "toString", ".", "call", "(", "value", ")", "===", "'[object Function]'", ")", "{", "// This can be an unbound method: try to bind it.", "value", "=", "value", ".", "bind", "(", "obj", ")", ";", "}", "instance", "[", "key", "]", "=", "value", ";", "}", ")", ";", "options", "=", "options", "||", "{", "}", ";", "if", "(", "options", ".", "mutable", ")", "{", "return", "instance", ";", "}", "return", "deepFreeze", "(", "instance", ")", ";", "}" ]
Build a property from the given object and shape property type. The resulting property is a deeply frozen object, with initially unbound methods bound to the provided object. All fields in the provided object that are not declared in the shape are not included in the returned object. If the shape property type includes the special field "shapeup.reshape", then a reshape method is included in that field of the returned object, providing the ability to reshape from the object itself using a new shape property type. @param {Object} obj The object from which to build the shape. This object is assumed to include all properties declared in the shape, except for the optionally declared "shapeup.reshape" property. @param {Function} propType The property type with the declared shape (built using "shapeup.shape"). @param {Object} options Additional optional parameters, including: - mutable: whether to skip deeply freezing of the resulting object. @returns {Object} The resulting property, as a deeply frozen object.
[ "Build", "a", "property", "from", "the", "given", "object", "and", "shape", "property", "type", ".", "The", "resulting", "property", "is", "a", "deeply", "frozen", "object", "with", "initially", "unbound", "methods", "bound", "to", "the", "provided", "object", ".", "All", "fields", "in", "the", "provided", "object", "that", "are", "not", "declared", "in", "the", "shape", "are", "not", "included", "in", "the", "returned", "object", ".", "If", "the", "shape", "property", "type", "includes", "the", "special", "field", "shapeup", ".", "reshape", "then", "a", "reshape", "method", "is", "included", "in", "that", "field", "of", "the", "returned", "object", "providing", "the", "ability", "to", "reshape", "from", "the", "object", "itself", "using", "a", "new", "shape", "property", "type", "." ]
a537f051f2597582197f0d5e54afd971578a6363
https://github.com/frankban/shapeup/blob/a537f051f2597582197f0d5e54afd971578a6363/shapeup.js#L87-L124
53,922
frankban/shapeup
shapeup.js
isRequiredWrapper
function isRequiredWrapper(propType) { const isRequired = (props, propName, componentName, ...rest) => { if (!props[propName]) { return new Error( `the property "${propName}" is marked as required for the component ` + `"${componentName}" but "${props[propName]}" has been provided` ); } return propType(props, propName, componentName, ...rest); }; isRequired[SHAPE] = propType[SHAPE]; return isRequired; }
javascript
function isRequiredWrapper(propType) { const isRequired = (props, propName, componentName, ...rest) => { if (!props[propName]) { return new Error( `the property "${propName}" is marked as required for the component ` + `"${componentName}" but "${props[propName]}" has been provided` ); } return propType(props, propName, componentName, ...rest); }; isRequired[SHAPE] = propType[SHAPE]; return isRequired; }
[ "function", "isRequiredWrapper", "(", "propType", ")", "{", "const", "isRequired", "=", "(", "props", ",", "propName", ",", "componentName", ",", "...", "rest", ")", "=>", "{", "if", "(", "!", "props", "[", "propName", "]", ")", "{", "return", "new", "Error", "(", "`", "${", "propName", "}", "`", "+", "`", "${", "componentName", "}", "${", "props", "[", "propName", "]", "}", "`", ")", ";", "}", "return", "propType", "(", "props", ",", "propName", ",", "componentName", ",", "...", "rest", ")", ";", "}", ";", "isRequired", "[", "SHAPE", "]", "=", "propType", "[", "SHAPE", "]", ";", "return", "isRequired", ";", "}" ]
Return the isRequired wrapper for the given propType validator. @param {Function} propType A shape or frozen validator. @return {Function} The isRequired validator.
[ "Return", "the", "isRequired", "wrapper", "for", "the", "given", "propType", "validator", "." ]
a537f051f2597582197f0d5e54afd971578a6363
https://github.com/frankban/shapeup/blob/a537f051f2597582197f0d5e54afd971578a6363/shapeup.js#L150-L162
53,923
frankban/shapeup
shapeup.js
frozenWrapper
function frozenWrapper(propType) { const checkFrozen = (obj, propName, componentName) => { if (!Object.isFrozen(obj)) { throw new Error( `the property "${propName}" provided to component ` + `"${componentName}" is not frozen` ); } forEachKeyValue(obj, (name, prop) => { const type = typeof obj; if (prop !== null && (type === 'object' || type === 'function')) { checkFrozen(prop, `${propName}.${name}`, componentName); } }); }; const frozen = (props, propName, componentName, ...rest) => { const propValue = props[propName]; if (!propValue) { return null; } try { checkFrozen(propValue, propName, componentName); } catch (err) { return err; } return propType(props, propName, componentName, ...rest); }; frozen[SHAPE] = propType[SHAPE]; return frozen; }
javascript
function frozenWrapper(propType) { const checkFrozen = (obj, propName, componentName) => { if (!Object.isFrozen(obj)) { throw new Error( `the property "${propName}" provided to component ` + `"${componentName}" is not frozen` ); } forEachKeyValue(obj, (name, prop) => { const type = typeof obj; if (prop !== null && (type === 'object' || type === 'function')) { checkFrozen(prop, `${propName}.${name}`, componentName); } }); }; const frozen = (props, propName, componentName, ...rest) => { const propValue = props[propName]; if (!propValue) { return null; } try { checkFrozen(propValue, propName, componentName); } catch (err) { return err; } return propType(props, propName, componentName, ...rest); }; frozen[SHAPE] = propType[SHAPE]; return frozen; }
[ "function", "frozenWrapper", "(", "propType", ")", "{", "const", "checkFrozen", "=", "(", "obj", ",", "propName", ",", "componentName", ")", "=>", "{", "if", "(", "!", "Object", ".", "isFrozen", "(", "obj", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "propName", "}", "`", "+", "`", "${", "componentName", "}", "`", ")", ";", "}", "forEachKeyValue", "(", "obj", ",", "(", "name", ",", "prop", ")", "=>", "{", "const", "type", "=", "typeof", "obj", ";", "if", "(", "prop", "!==", "null", "&&", "(", "type", "===", "'object'", "||", "type", "===", "'function'", ")", ")", "{", "checkFrozen", "(", "prop", ",", "`", "${", "propName", "}", "${", "name", "}", "`", ",", "componentName", ")", ";", "}", "}", ")", ";", "}", ";", "const", "frozen", "=", "(", "props", ",", "propName", ",", "componentName", ",", "...", "rest", ")", "=>", "{", "const", "propValue", "=", "props", "[", "propName", "]", ";", "if", "(", "!", "propValue", ")", "{", "return", "null", ";", "}", "try", "{", "checkFrozen", "(", "propValue", ",", "propName", ",", "componentName", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "err", ";", "}", "return", "propType", "(", "props", ",", "propName", ",", "componentName", ",", "...", "rest", ")", ";", "}", ";", "frozen", "[", "SHAPE", "]", "=", "propType", "[", "SHAPE", "]", ";", "return", "frozen", ";", "}" ]
Return a frozen wrapper for the given propType validator. The resulting validator checks that the provided property is deeply frozen. @param {Function} propType A shape validator. @return {Function} The frozen validator.
[ "Return", "a", "frozen", "wrapper", "for", "the", "given", "propType", "validator", ".", "The", "resulting", "validator", "checks", "that", "the", "provided", "property", "is", "deeply", "frozen", "." ]
a537f051f2597582197f0d5e54afd971578a6363
https://github.com/frankban/shapeup/blob/a537f051f2597582197f0d5e54afd971578a6363/shapeup.js#L171-L201
53,924
frankban/shapeup
shapeup.js
deepFreeze
function deepFreeze(obj) { Object.freeze(obj); forEachKeyValue(obj, (name, prop) => { const type = typeof obj; if ( prop !== null && (type === 'object' || type === 'function') && !Object.isFrozen(prop) ) { deepFreeze(prop); } }); return obj; }
javascript
function deepFreeze(obj) { Object.freeze(obj); forEachKeyValue(obj, (name, prop) => { const type = typeof obj; if ( prop !== null && (type === 'object' || type === 'function') && !Object.isFrozen(prop) ) { deepFreeze(prop); } }); return obj; }
[ "function", "deepFreeze", "(", "obj", ")", "{", "Object", ".", "freeze", "(", "obj", ")", ";", "forEachKeyValue", "(", "obj", ",", "(", "name", ",", "prop", ")", "=>", "{", "const", "type", "=", "typeof", "obj", ";", "if", "(", "prop", "!==", "null", "&&", "(", "type", "===", "'object'", "||", "type", "===", "'function'", ")", "&&", "!", "Object", ".", "isFrozen", "(", "prop", ")", ")", "{", "deepFreeze", "(", "prop", ")", ";", "}", "}", ")", ";", "return", "obj", ";", "}" ]
Deep freeze the given object and all its properties. @param {Object} obj The object to freeze. @returns {Object} The resulting deeply frozen object.
[ "Deep", "freeze", "the", "given", "object", "and", "all", "its", "properties", "." ]
a537f051f2597582197f0d5e54afd971578a6363
https://github.com/frankban/shapeup/blob/a537f051f2597582197f0d5e54afd971578a6363/shapeup.js#L209-L222
53,925
TestArmada/midway-logger
lib/utils/validator.js
function (level) { var lowerCaseLevel = level.toLowerCase(); if (_.contains(LEVELS, lowerCaseLevel)) { return lowerCaseLevel; } else { return LEVEL_OFF; } }
javascript
function (level) { var lowerCaseLevel = level.toLowerCase(); if (_.contains(LEVELS, lowerCaseLevel)) { return lowerCaseLevel; } else { return LEVEL_OFF; } }
[ "function", "(", "level", ")", "{", "var", "lowerCaseLevel", "=", "level", ".", "toLowerCase", "(", ")", ";", "if", "(", "_", ".", "contains", "(", "LEVELS", ",", "lowerCaseLevel", ")", ")", "{", "return", "lowerCaseLevel", ";", "}", "else", "{", "return", "LEVEL_OFF", ";", "}", "}" ]
If level returned by tracer is not in LEVELS object, treat it as 'off'.
[ "If", "level", "returned", "by", "tracer", "is", "not", "in", "LEVELS", "object", "treat", "it", "as", "off", "." ]
b3479e2ab2909ec3420246d1edd27d300da97887
https://github.com/TestArmada/midway-logger/blob/b3479e2ab2909ec3420246d1edd27d300da97887/lib/utils/validator.js#L34-L41
53,926
keithws/x10
lib/x10.js
HouseCode
function HouseCode(houseCode) { this.raw = null; switch (typeof houseCode) { case "string": if (houseCode !== "" && houseCode.length === 1) { var index = houseCode.charCodeAt(0) - 65; if ((index >= 0) && (index <= (deviceCodes.length - 1))) { this.raw = deviceCodes[index]; } else { throw new Error("House code string out of range."); } } else { throw new Error("Invalid house code."); } break; default: if (deviceCodes.indexOf(houseCode) !== -1) { this.raw = houseCode; } else { throw new Error("House code number out of range."); } break; } return this.raw; }
javascript
function HouseCode(houseCode) { this.raw = null; switch (typeof houseCode) { case "string": if (houseCode !== "" && houseCode.length === 1) { var index = houseCode.charCodeAt(0) - 65; if ((index >= 0) && (index <= (deviceCodes.length - 1))) { this.raw = deviceCodes[index]; } else { throw new Error("House code string out of range."); } } else { throw new Error("Invalid house code."); } break; default: if (deviceCodes.indexOf(houseCode) !== -1) { this.raw = houseCode; } else { throw new Error("House code number out of range."); } break; } return this.raw; }
[ "function", "HouseCode", "(", "houseCode", ")", "{", "this", ".", "raw", "=", "null", ";", "switch", "(", "typeof", "houseCode", ")", "{", "case", "\"string\"", ":", "if", "(", "houseCode", "!==", "\"\"", "&&", "houseCode", ".", "length", "===", "1", ")", "{", "var", "index", "=", "houseCode", ".", "charCodeAt", "(", "0", ")", "-", "65", ";", "if", "(", "(", "index", ">=", "0", ")", "&&", "(", "index", "<=", "(", "deviceCodes", ".", "length", "-", "1", ")", ")", ")", "{", "this", ".", "raw", "=", "deviceCodes", "[", "index", "]", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"House code string out of range.\"", ")", ";", "}", "}", "else", "{", "throw", "new", "Error", "(", "\"Invalid house code.\"", ")", ";", "}", "break", ";", "default", ":", "if", "(", "deviceCodes", ".", "indexOf", "(", "houseCode", ")", "!==", "-", "1", ")", "{", "this", ".", "raw", "=", "houseCode", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"House code number out of range.\"", ")", ";", "}", "break", ";", "}", "return", "this", ".", "raw", ";", "}" ]
object to convert X-10 house codes from numbers to strings and back
[ "object", "to", "convert", "X", "-", "10", "house", "codes", "from", "numbers", "to", "strings", "and", "back" ]
c3f050580a14e1d43df31e72639cc66f9427e5b3
https://github.com/keithws/x10/blob/c3f050580a14e1d43df31e72639cc66f9427e5b3/lib/x10.js#L20-L45
53,927
keithws/x10
lib/x10.js
UnitCode
function UnitCode(unitCode) { switch (typeof unitCode) { case "string": unitCode = parseInt(unitCode, 10); if (unitCode || unitCode === 0) { var index = unitCode - 1; if ((index >= 0) && (index <= (deviceCodes.length - 1))) { this.raw = deviceCodes[index]; } else { throw new Error("Unit code string out of range."); } } else { throw new Error("Invalid unit code."); } break; default: if (deviceCodes.indexOf(unitCode) !== -1) { this.raw = unitCode; } else { throw new Error("Unit code number out of range."); } break; } return this.raw; }
javascript
function UnitCode(unitCode) { switch (typeof unitCode) { case "string": unitCode = parseInt(unitCode, 10); if (unitCode || unitCode === 0) { var index = unitCode - 1; if ((index >= 0) && (index <= (deviceCodes.length - 1))) { this.raw = deviceCodes[index]; } else { throw new Error("Unit code string out of range."); } } else { throw new Error("Invalid unit code."); } break; default: if (deviceCodes.indexOf(unitCode) !== -1) { this.raw = unitCode; } else { throw new Error("Unit code number out of range."); } break; } return this.raw; }
[ "function", "UnitCode", "(", "unitCode", ")", "{", "switch", "(", "typeof", "unitCode", ")", "{", "case", "\"string\"", ":", "unitCode", "=", "parseInt", "(", "unitCode", ",", "10", ")", ";", "if", "(", "unitCode", "||", "unitCode", "===", "0", ")", "{", "var", "index", "=", "unitCode", "-", "1", ";", "if", "(", "(", "index", ">=", "0", ")", "&&", "(", "index", "<=", "(", "deviceCodes", ".", "length", "-", "1", ")", ")", ")", "{", "this", ".", "raw", "=", "deviceCodes", "[", "index", "]", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"Unit code string out of range.\"", ")", ";", "}", "}", "else", "{", "throw", "new", "Error", "(", "\"Invalid unit code.\"", ")", ";", "}", "break", ";", "default", ":", "if", "(", "deviceCodes", ".", "indexOf", "(", "unitCode", ")", "!==", "-", "1", ")", "{", "this", ".", "raw", "=", "unitCode", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"Unit code number out of range.\"", ")", ";", "}", "break", ";", "}", "return", "this", ".", "raw", ";", "}" ]
object to convert X-10 unit codes from numbers to strings and back
[ "object", "to", "convert", "X", "-", "10", "unit", "codes", "from", "numbers", "to", "strings", "and", "back" ]
c3f050580a14e1d43df31e72639cc66f9427e5b3
https://github.com/keithws/x10/blob/c3f050580a14e1d43df31e72639cc66f9427e5b3/lib/x10.js#L63-L87
53,928
keithws/x10
lib/x10.js
Address
function Address(address) { this.houseCode = null; this.unitCode = null; try { switch (typeof address) { case "object": if (_.isArray(address) && address.length === 2) { this.houseCode = new HouseCode(address[0]); this.unitCode = new UnitCode(address[1]); } else { if (address.houseCode !== undefined && address.houseCode !== null) { this.houseCode = new HouseCode(address.houseCode); } if (address.unitCode !== undefined && address.unitCode !== null) { this.unitCode = new UnitCode(address.unitCode); } } break; case "string": try { address = JSON.parse(address); if (address.hasOwnProperty("houseCode") && address.houseCode !== null) { this.houseCode = new HouseCode(address.houseCode); } if (address.hasOwnProperty("unitCode") && address.unitCode !== null) { this.unitCode = new UnitCode(address.unitCode); } } catch (e) { this.houseCode = new HouseCode((address.toUpperCase().match(/[A-P]+/)||[null])[0]); this.unitCode = new UnitCode((address.match(/\d+/)||[null])[0]); } break; case "number": this.houseCode = new HouseCode(address>>>4); this.unitCode = new UnitCode(address&0x0F); break; default: throw new Error("Invalid address."); break; } } catch (e) { throw new Error('Address out of range.'); } }
javascript
function Address(address) { this.houseCode = null; this.unitCode = null; try { switch (typeof address) { case "object": if (_.isArray(address) && address.length === 2) { this.houseCode = new HouseCode(address[0]); this.unitCode = new UnitCode(address[1]); } else { if (address.houseCode !== undefined && address.houseCode !== null) { this.houseCode = new HouseCode(address.houseCode); } if (address.unitCode !== undefined && address.unitCode !== null) { this.unitCode = new UnitCode(address.unitCode); } } break; case "string": try { address = JSON.parse(address); if (address.hasOwnProperty("houseCode") && address.houseCode !== null) { this.houseCode = new HouseCode(address.houseCode); } if (address.hasOwnProperty("unitCode") && address.unitCode !== null) { this.unitCode = new UnitCode(address.unitCode); } } catch (e) { this.houseCode = new HouseCode((address.toUpperCase().match(/[A-P]+/)||[null])[0]); this.unitCode = new UnitCode((address.match(/\d+/)||[null])[0]); } break; case "number": this.houseCode = new HouseCode(address>>>4); this.unitCode = new UnitCode(address&0x0F); break; default: throw new Error("Invalid address."); break; } } catch (e) { throw new Error('Address out of range.'); } }
[ "function", "Address", "(", "address", ")", "{", "this", ".", "houseCode", "=", "null", ";", "this", ".", "unitCode", "=", "null", ";", "try", "{", "switch", "(", "typeof", "address", ")", "{", "case", "\"object\"", ":", "if", "(", "_", ".", "isArray", "(", "address", ")", "&&", "address", ".", "length", "===", "2", ")", "{", "this", ".", "houseCode", "=", "new", "HouseCode", "(", "address", "[", "0", "]", ")", ";", "this", ".", "unitCode", "=", "new", "UnitCode", "(", "address", "[", "1", "]", ")", ";", "}", "else", "{", "if", "(", "address", ".", "houseCode", "!==", "undefined", "&&", "address", ".", "houseCode", "!==", "null", ")", "{", "this", ".", "houseCode", "=", "new", "HouseCode", "(", "address", ".", "houseCode", ")", ";", "}", "if", "(", "address", ".", "unitCode", "!==", "undefined", "&&", "address", ".", "unitCode", "!==", "null", ")", "{", "this", ".", "unitCode", "=", "new", "UnitCode", "(", "address", ".", "unitCode", ")", ";", "}", "}", "break", ";", "case", "\"string\"", ":", "try", "{", "address", "=", "JSON", ".", "parse", "(", "address", ")", ";", "if", "(", "address", ".", "hasOwnProperty", "(", "\"houseCode\"", ")", "&&", "address", ".", "houseCode", "!==", "null", ")", "{", "this", ".", "houseCode", "=", "new", "HouseCode", "(", "address", ".", "houseCode", ")", ";", "}", "if", "(", "address", ".", "hasOwnProperty", "(", "\"unitCode\"", ")", "&&", "address", ".", "unitCode", "!==", "null", ")", "{", "this", ".", "unitCode", "=", "new", "UnitCode", "(", "address", ".", "unitCode", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "this", ".", "houseCode", "=", "new", "HouseCode", "(", "(", "address", ".", "toUpperCase", "(", ")", ".", "match", "(", "/", "[A-P]+", "/", ")", "||", "[", "null", "]", ")", "[", "0", "]", ")", ";", "this", ".", "unitCode", "=", "new", "UnitCode", "(", "(", "address", ".", "match", "(", "/", "\\d+", "/", ")", "||", "[", "null", "]", ")", "[", "0", "]", ")", ";", "}", "break", ";", "case", "\"number\"", ":", "this", ".", "houseCode", "=", "new", "HouseCode", "(", "address", ">>>", "4", ")", ";", "this", ".", "unitCode", "=", "new", "UnitCode", "(", "address", "&", "0x0F", ")", ";", "break", ";", "default", ":", "throw", "new", "Error", "(", "\"Invalid address.\"", ")", ";", "break", ";", "}", "}", "catch", "(", "e", ")", "{", "throw", "new", "Error", "(", "'Address out of range.'", ")", ";", "}", "}" ]
object to convert X-10 addresses from numbers to strings and back
[ "object", "to", "convert", "X", "-", "10", "addresses", "from", "numbers", "to", "strings", "and", "back" ]
c3f050580a14e1d43df31e72639cc66f9427e5b3
https://github.com/keithws/x10/blob/c3f050580a14e1d43df31e72639cc66f9427e5b3/lib/x10.js#L106-L150
53,929
boylesoftware/x2node-validators
lib/record-normalizer.js
normalize
function normalize(recordTypes, recordTypeName, record, lang, validationSets) { // check that we have the record if ((record === null) || ((typeof record) !== 'object')) throw new common.X2UsageError('Record object was not provided.'); // get the record type descriptor (or throw error if invalid record type) const recordTypeDesc = recordTypes.getRecordTypeDesc(recordTypeName); // extract validation sets var sets = new Set( (validationSets ? validationSets.trim() + ',*' : '*').split(/\s*,\s*/)); // create validation context const ctx = new ValidationContext( recordTypes, recordTypeDesc, new MessageResolver(lang || '*'), sets); // run recursive validation/normalization of the record properties normalizeChildren(ctx, recordTypeDesc, null, record, sets); // validate/normalize the record as a whole const recordValidators = getValidators(recordTypeDesc, false, sets); if (recordValidators) for (let validator of recordValidators) validator(ctx, record); // return the result return ctx.getResult(); }
javascript
function normalize(recordTypes, recordTypeName, record, lang, validationSets) { // check that we have the record if ((record === null) || ((typeof record) !== 'object')) throw new common.X2UsageError('Record object was not provided.'); // get the record type descriptor (or throw error if invalid record type) const recordTypeDesc = recordTypes.getRecordTypeDesc(recordTypeName); // extract validation sets var sets = new Set( (validationSets ? validationSets.trim() + ',*' : '*').split(/\s*,\s*/)); // create validation context const ctx = new ValidationContext( recordTypes, recordTypeDesc, new MessageResolver(lang || '*'), sets); // run recursive validation/normalization of the record properties normalizeChildren(ctx, recordTypeDesc, null, record, sets); // validate/normalize the record as a whole const recordValidators = getValidators(recordTypeDesc, false, sets); if (recordValidators) for (let validator of recordValidators) validator(ctx, record); // return the result return ctx.getResult(); }
[ "function", "normalize", "(", "recordTypes", ",", "recordTypeName", ",", "record", ",", "lang", ",", "validationSets", ")", "{", "// check that we have the record", "if", "(", "(", "record", "===", "null", ")", "||", "(", "(", "typeof", "record", ")", "!==", "'object'", ")", ")", "throw", "new", "common", ".", "X2UsageError", "(", "'Record object was not provided.'", ")", ";", "// get the record type descriptor (or throw error if invalid record type)", "const", "recordTypeDesc", "=", "recordTypes", ".", "getRecordTypeDesc", "(", "recordTypeName", ")", ";", "// extract validation sets", "var", "sets", "=", "new", "Set", "(", "(", "validationSets", "?", "validationSets", ".", "trim", "(", ")", "+", "',*'", ":", "'*'", ")", ".", "split", "(", "/", "\\s*,\\s*", "/", ")", ")", ";", "// create validation context", "const", "ctx", "=", "new", "ValidationContext", "(", "recordTypes", ",", "recordTypeDesc", ",", "new", "MessageResolver", "(", "lang", "||", "'*'", ")", ",", "sets", ")", ";", "// run recursive validation/normalization of the record properties", "normalizeChildren", "(", "ctx", ",", "recordTypeDesc", ",", "null", ",", "record", ",", "sets", ")", ";", "// validate/normalize the record as a whole", "const", "recordValidators", "=", "getValidators", "(", "recordTypeDesc", ",", "false", ",", "sets", ")", ";", "if", "(", "recordValidators", ")", "for", "(", "let", "validator", "of", "recordValidators", ")", "validator", "(", "ctx", ",", "record", ")", ";", "// return the result", "return", "ctx", ".", "getResult", "(", ")", ";", "}" ]
Validate and normalize the specified record. @function module:x2node-validators.normalizeRecord @param {module:x2node-records~RecordTypesLibrary} recordType Record types library. @param {string} recordTypeName Record type name. @param {Object} record The record to validate. May not be <code>null</code> or <code>undefined</code>. @param {string} [lang] Language for the error messages in the same format as used by the HTTP's "Accept-Language" request header. If not provided, "*" is assumed. @param {string} [validationSets] Comma-separated validation set names. If not provided, the default validation set is used. @returns {module:x2node-validators~ValidationErrors} Errors if the record is invalid, or <code>null</code> if it has been successfully validated and normalized. @throws {module:x2node-common.X2UsageError} If unknown record type, record was not provided or invalid language or validation set specification.
[ "Validate", "and", "normalize", "the", "specified", "record", "." ]
e98a65c13a4092f80e96517c8e8c9523f8e84c63
https://github.com/boylesoftware/x2node-validators/blob/e98a65c13a4092f80e96517c8e8c9523f8e84c63/lib/record-normalizer.js#L29-L57
53,930
boylesoftware/x2node-validators
lib/record-normalizer.js
getValidators
function getValidators(subjDesc, element, validationSets) { const validators = subjDesc.validators; if (!validators) return null; const allValidators = new Array(); for (let set in validators) { if (element && !set.startsWith('element:')) continue; if (validationSets.has(element ? set.substring('element:'.length) : set)) for (let validator of validators[set]) allValidators.push(validator); } return (allValidators.length > 0 ? allValidators : null); }
javascript
function getValidators(subjDesc, element, validationSets) { const validators = subjDesc.validators; if (!validators) return null; const allValidators = new Array(); for (let set in validators) { if (element && !set.startsWith('element:')) continue; if (validationSets.has(element ? set.substring('element:'.length) : set)) for (let validator of validators[set]) allValidators.push(validator); } return (allValidators.length > 0 ? allValidators : null); }
[ "function", "getValidators", "(", "subjDesc", ",", "element", ",", "validationSets", ")", "{", "const", "validators", "=", "subjDesc", ".", "validators", ";", "if", "(", "!", "validators", ")", "return", "null", ";", "const", "allValidators", "=", "new", "Array", "(", ")", ";", "for", "(", "let", "set", "in", "validators", ")", "{", "if", "(", "element", "&&", "!", "set", ".", "startsWith", "(", "'element:'", ")", ")", "continue", ";", "if", "(", "validationSets", ".", "has", "(", "element", "?", "set", ".", "substring", "(", "'element:'", ".", "length", ")", ":", "set", ")", ")", "for", "(", "let", "validator", "of", "validators", "[", "set", "]", ")", "allValidators", ".", "push", "(", "validator", ")", ";", "}", "return", "(", "allValidators", ".", "length", ">", "0", "?", "allValidators", ":", "null", ")", ";", "}" ]
Get validators sequence for the specified subject descriptor. @private @param {(module:x2node-records~RecordTypeDescriptor|module:x2node-records~PropertyDescriptor)} subjDesc Descriptor with validators on it. @param {boolean} element <code>true</code> for collection element validators. @param {Set.<string>} validationSets Validation sets. @returns {Array.<module:x2node-validators.curriedValidator>} List of validators to run or <code>null</code> if none.
[ "Get", "validators", "sequence", "for", "the", "specified", "subject", "descriptor", "." ]
e98a65c13a4092f80e96517c8e8c9523f8e84c63
https://github.com/boylesoftware/x2node-validators/blob/e98a65c13a4092f80e96517c8e8c9523f8e84c63/lib/record-normalizer.js#L223-L240
53,931
aledbf/deis-api
lib/perms.js
list
function list(appName, callback) { commons.get(format('/%s/apps/%s/perms/', deis.version, appName), callback); }
javascript
function list(appName, callback) { commons.get(format('/%s/apps/%s/perms/', deis.version, appName), callback); }
[ "function", "list", "(", "appName", ",", "callback", ")", "{", "commons", ".", "get", "(", "format", "(", "'/%s/apps/%s/perms/'", ",", "deis", ".", "version", ",", "appName", ")", ",", "callback", ")", ";", "}" ]
list permissions granted on an app
[ "list", "permissions", "granted", "on", "an", "app" ]
f0833789998032b11221a3a617bb566ade1fcc13
https://github.com/aledbf/deis-api/blob/f0833789998032b11221a3a617bb566ade1fcc13/lib/perms.js#L10-L12
53,932
teabyii/qa
lib/ui.js
UI
function UI (input, output) { this.rl = readline.createInterface({ input: input || ttys.stdin, output: output || ttys.stdout }) // Delegated events bind. this.onLine = (function onLine () { _events.line.apply(this, arguments) }).bind(this) this.onKeypress = (function onKeypress () { if (this.rl) { _events.keypress.apply(this, arguments) } }).bind(this) this.forceClose = this.forceClose.bind(this) this.rl.addListener('line', this.onLine) this.rl.input.addListener('keypress', this.onKeypress) this.rl.on('SIGINT', this.forceClose) process.on('exit', this.forceClose) }
javascript
function UI (input, output) { this.rl = readline.createInterface({ input: input || ttys.stdin, output: output || ttys.stdout }) // Delegated events bind. this.onLine = (function onLine () { _events.line.apply(this, arguments) }).bind(this) this.onKeypress = (function onKeypress () { if (this.rl) { _events.keypress.apply(this, arguments) } }).bind(this) this.forceClose = this.forceClose.bind(this) this.rl.addListener('line', this.onLine) this.rl.input.addListener('keypress', this.onKeypress) this.rl.on('SIGINT', this.forceClose) process.on('exit', this.forceClose) }
[ "function", "UI", "(", "input", ",", "output", ")", "{", "this", ".", "rl", "=", "readline", ".", "createInterface", "(", "{", "input", ":", "input", "||", "ttys", ".", "stdin", ",", "output", ":", "output", "||", "ttys", ".", "stdout", "}", ")", "// Delegated events bind.", "this", ".", "onLine", "=", "(", "function", "onLine", "(", ")", "{", "_events", ".", "line", ".", "apply", "(", "this", ",", "arguments", ")", "}", ")", ".", "bind", "(", "this", ")", "this", ".", "onKeypress", "=", "(", "function", "onKeypress", "(", ")", "{", "if", "(", "this", ".", "rl", ")", "{", "_events", ".", "keypress", ".", "apply", "(", "this", ",", "arguments", ")", "}", "}", ")", ".", "bind", "(", "this", ")", "this", ".", "forceClose", "=", "this", ".", "forceClose", ".", "bind", "(", "this", ")", "this", ".", "rl", ".", "addListener", "(", "'line'", ",", "this", ".", "onLine", ")", "this", ".", "rl", ".", "input", ".", "addListener", "(", "'keypress'", ",", "this", ".", "onKeypress", ")", "this", ".", "rl", ".", "on", "(", "'SIGINT'", ",", "this", ".", "forceClose", ")", "process", ".", "on", "(", "'exit'", ",", "this", ".", "forceClose", ")", "}" ]
UI constructor, to create ui to control IO. @constructor @param {Stream} [input] @param {Stream} [output]
[ "UI", "constructor", "to", "create", "ui", "to", "control", "IO", "." ]
9224180dcb9e6b57c021f83b259316e84ebc573e
https://github.com/teabyii/qa/blob/9224180dcb9e6b57c021f83b259316e84ebc573e/lib/ui.js#L21-L45
53,933
h1bomb/yo
examples/yo.yohobuy-mobile/client/js/saunter.js
lazyLoad
function lazyLoad(imgs, options) { var setting = { effect: 'fadeIn', effect_speed: 10, placeholder: 'data:image/gif;base64,R0lGODlhAQABAJEAAAAAAP///93d3f///yH5BAEAAAMALAAAAAABAAEAAAICVAEAOw==' }, $imgs; if (typeof imgs === 'undefined') { $imgs = $('img.lazy'); } else { $imgs = imgs; } if (typeof options !== 'undefined') { $.extend(setting, options); } $imgs.lazyload(setting); }
javascript
function lazyLoad(imgs, options) { var setting = { effect: 'fadeIn', effect_speed: 10, placeholder: 'data:image/gif;base64,R0lGODlhAQABAJEAAAAAAP///93d3f///yH5BAEAAAMALAAAAAABAAEAAAICVAEAOw==' }, $imgs; if (typeof imgs === 'undefined') { $imgs = $('img.lazy'); } else { $imgs = imgs; } if (typeof options !== 'undefined') { $.extend(setting, options); } $imgs.lazyload(setting); }
[ "function", "lazyLoad", "(", "imgs", ",", "options", ")", "{", "var", "setting", "=", "{", "effect", ":", "'fadeIn'", ",", "effect_speed", ":", "10", ",", "placeholder", ":", "'data:image/gif;base64,R0lGODlhAQABAJEAAAAAAP///93d3f///yH5BAEAAAMALAAAAAABAAEAAAICVAEAOw=='", "}", ",", "$imgs", ";", "if", "(", "typeof", "imgs", "===", "'undefined'", ")", "{", "$imgs", "=", "$", "(", "'img.lazy'", ")", ";", "}", "else", "{", "$imgs", "=", "imgs", ";", "}", "if", "(", "typeof", "options", "!==", "'undefined'", ")", "{", "$", ".", "extend", "(", "setting", ",", "options", ")", ";", "}", "$imgs", ".", "lazyload", "(", "setting", ")", ";", "}" ]
lazyLoad-Fn
[ "lazyLoad", "-", "Fn" ]
11a05222d4fd1c0b5e8239672058f3d0d93aad44
https://github.com/h1bomb/yo/blob/11a05222d4fd1c0b5e8239672058f3d0d93aad44/examples/yo.yohobuy-mobile/client/js/saunter.js#L14-L30
53,934
aledbf/deis-api
lib/tags.js
list
function list(appName, callback) { var url = format('/%s/apps/%s/config/', deis.version, appName); commons.get(url, function onListResponse(err, result) { callback(err, result ? result.tags : null); }); }
javascript
function list(appName, callback) { var url = format('/%s/apps/%s/config/', deis.version, appName); commons.get(url, function onListResponse(err, result) { callback(err, result ? result.tags : null); }); }
[ "function", "list", "(", "appName", ",", "callback", ")", "{", "var", "url", "=", "format", "(", "'/%s/apps/%s/config/'", ",", "deis", ".", "version", ",", "appName", ")", ";", "commons", ".", "get", "(", "url", ",", "function", "onListResponse", "(", "err", ",", "result", ")", "{", "callback", "(", "err", ",", "result", "?", "result", ".", "tags", ":", "null", ")", ";", "}", ")", ";", "}" ]
list tags for an app
[ "list", "tags", "for", "an", "app" ]
f0833789998032b11221a3a617bb566ade1fcc13
https://github.com/aledbf/deis-api/blob/f0833789998032b11221a3a617bb566ade1fcc13/lib/tags.js#L12-L17
53,935
aledbf/deis-api
lib/tags.js
set
function set(appName, tagValues, callback) { if (!isObject(tagValues)) { return callback(new Error('To set a variable pass an object')); } commons.post(format('/%s/apps/%s/config/', deis.version, appName), { tags: tagValues },function onSetResponse(err, result) { callback(err, result ? result.tags : null); }); }
javascript
function set(appName, tagValues, callback) { if (!isObject(tagValues)) { return callback(new Error('To set a variable pass an object')); } commons.post(format('/%s/apps/%s/config/', deis.version, appName), { tags: tagValues },function onSetResponse(err, result) { callback(err, result ? result.tags : null); }); }
[ "function", "set", "(", "appName", ",", "tagValues", ",", "callback", ")", "{", "if", "(", "!", "isObject", "(", "tagValues", ")", ")", "{", "return", "callback", "(", "new", "Error", "(", "'To set a variable pass an object'", ")", ")", ";", "}", "commons", ".", "post", "(", "format", "(", "'/%s/apps/%s/config/'", ",", "deis", ".", "version", ",", "appName", ")", ",", "{", "tags", ":", "tagValues", "}", ",", "function", "onSetResponse", "(", "err", ",", "result", ")", "{", "callback", "(", "err", ",", "result", "?", "result", ".", "tags", ":", "null", ")", ";", "}", ")", ";", "}" ]
set tags for an app
[ "set", "tags", "for", "an", "app" ]
f0833789998032b11221a3a617bb566ade1fcc13
https://github.com/aledbf/deis-api/blob/f0833789998032b11221a3a617bb566ade1fcc13/lib/tags.js#L22-L32
53,936
aledbf/deis-api
lib/tags.js
unset
function unset(appName, tagNames, callback) { if (!util.isArray(tagNames)) { return callback(new Error('To unset a tag pass an array of names')); } var keyValues = {}; tagNames.forEach(function eachTag(tagName) { keyValues[tagName] = null; }); set(appName, keyValues, callback); }
javascript
function unset(appName, tagNames, callback) { if (!util.isArray(tagNames)) { return callback(new Error('To unset a tag pass an array of names')); } var keyValues = {}; tagNames.forEach(function eachTag(tagName) { keyValues[tagName] = null; }); set(appName, keyValues, callback); }
[ "function", "unset", "(", "appName", ",", "tagNames", ",", "callback", ")", "{", "if", "(", "!", "util", ".", "isArray", "(", "tagNames", ")", ")", "{", "return", "callback", "(", "new", "Error", "(", "'To unset a tag pass an array of names'", ")", ")", ";", "}", "var", "keyValues", "=", "{", "}", ";", "tagNames", ".", "forEach", "(", "function", "eachTag", "(", "tagName", ")", "{", "keyValues", "[", "tagName", "]", "=", "null", ";", "}", ")", ";", "set", "(", "appName", ",", "keyValues", ",", "callback", ")", ";", "}" ]
unset tags for an app
[ "unset", "tags", "for", "an", "app" ]
f0833789998032b11221a3a617bb566ade1fcc13
https://github.com/aledbf/deis-api/blob/f0833789998032b11221a3a617bb566ade1fcc13/lib/tags.js#L37-L48
53,937
lmammino/indexed-string-variation
lib/generate/generateBigInt.js
getLevel
function getLevel(base, index) { var level = (0, _bigInteger2.default)('0'); var current = index; var parent = void 0; while (current.gt(zero)) { parent = current.prev().divide(base); level = level.next(); current = parent; } return level; }
javascript
function getLevel(base, index) { var level = (0, _bigInteger2.default)('0'); var current = index; var parent = void 0; while (current.gt(zero)) { parent = current.prev().divide(base); level = level.next(); current = parent; } return level; }
[ "function", "getLevel", "(", "base", ",", "index", ")", "{", "var", "level", "=", "(", "0", ",", "_bigInteger2", ".", "default", ")", "(", "'0'", ")", ";", "var", "current", "=", "index", ";", "var", "parent", "=", "void", "0", ";", "while", "(", "current", ".", "gt", "(", "zero", ")", ")", "{", "parent", "=", "current", ".", "prev", "(", ")", ".", "divide", "(", "base", ")", ";", "level", "=", "level", ".", "next", "(", ")", ";", "current", "=", "parent", ";", "}", "return", "level", ";", "}" ]
calculates the level of a given index in the current virtual tree
[ "calculates", "the", "level", "of", "a", "given", "index", "in", "the", "current", "virtual", "tree" ]
52fb6b5b05940138fb58f9a1c937531ad90adda5
https://github.com/lmammino/indexed-string-variation/blob/52fb6b5b05940138fb58f9a1c937531ad90adda5/lib/generate/generateBigInt.js#L17-L28
53,938
glennschler/spotspec
lib/spotspec.js
SpotSpec
function SpotSpec (options) { if (this.constructor.name === 'Object') { throw new Error('Object must be instantiated using new') } let self = this let specOptions = Object.assign({}, options) // Have the superclass constuct as an EC2 service Service.call(this, SvcAws.EC2, specOptions) this.logger.info('Loading EC2 for: ' + specOptions.keys.region) this.once(Const.EVENT_INITIALIZED, function onComplete (err, data) { /** * Emitted as the response to constuct SpotSpec * @event SpotSpec#initialized * @param {?error} err - Only on error * @param {object} [initData] - Null on error */ Intern.emitAsync.call(self, Const.EVENT_INITIALIZED, err, data) }) }
javascript
function SpotSpec (options) { if (this.constructor.name === 'Object') { throw new Error('Object must be instantiated using new') } let self = this let specOptions = Object.assign({}, options) // Have the superclass constuct as an EC2 service Service.call(this, SvcAws.EC2, specOptions) this.logger.info('Loading EC2 for: ' + specOptions.keys.region) this.once(Const.EVENT_INITIALIZED, function onComplete (err, data) { /** * Emitted as the response to constuct SpotSpec * @event SpotSpec#initialized * @param {?error} err - Only on error * @param {object} [initData] - Null on error */ Intern.emitAsync.call(self, Const.EVENT_INITIALIZED, err, data) }) }
[ "function", "SpotSpec", "(", "options", ")", "{", "if", "(", "this", ".", "constructor", ".", "name", "===", "'Object'", ")", "{", "throw", "new", "Error", "(", "'Object must be instantiated using new'", ")", "}", "let", "self", "=", "this", "let", "specOptions", "=", "Object", ".", "assign", "(", "{", "}", ",", "options", ")", "// Have the superclass constuct as an EC2 service", "Service", ".", "call", "(", "this", ",", "SvcAws", ".", "EC2", ",", "specOptions", ")", "this", ".", "logger", ".", "info", "(", "'Loading EC2 for: '", "+", "specOptions", ".", "keys", ".", "region", ")", "this", ".", "once", "(", "Const", ".", "EVENT_INITIALIZED", ",", "function", "onComplete", "(", "err", ",", "data", ")", "{", "/**\n * Emitted as the response to constuct SpotSpec\n * @event SpotSpec#initialized\n * @param {?error} err - Only on error\n * @param {object} [initData] - Null on error\n */", "Intern", ".", "emitAsync", ".", "call", "(", "self", ",", "Const", ".", "EVENT_INITIALIZED", ",", "err", ",", "data", ")", "}", ")", "}" ]
Constructs a new SpotSpec Library @constructor @arg {object} options - The AWS service IAM credentials - See [aws docs]{@link http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Credentials.html} @arg {object} options.keys - AWS credentials @arg {string} options.keys.accessKeyId - AWS access key ID @arg {string} options.keys.secretAccessKey - AWS secret access key. @arg {string} options.keys.region - The EC2 region to send service requests @arg {object} options.upgrade - Temporary Session Token credentials - See [aws docs]{@link http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/STS.html#getSessionToken-property} @arg {string} options.upgrade.serialNumber - Identifies the user's hardware or virtual MFA device. @arg {string} options.upgrade.tokenCode - Time-based one-time password (TOTP) that the MFA devices produces @arg {number} [options.upgrade.durationSeconds=900] - How long the temporary key will last @arg {boolean} [options.isLogging=false] - Use internal logging @throws {error} @emits {SpotSpec#initialized}
[ "Constructs", "a", "new", "SpotSpec", "Library" ]
ca6f5b17b84b3536b6b2ce9a472d5ae91c8cd727
https://github.com/glennschler/spotspec/blob/ca6f5b17b84b3536b6b2ce9a472d5ae91c8cd727/lib/spotspec.js#L25-L46
53,939
hashchange/backbone.cycle
demo/amd/main.js
function ( options ) { _.bindAll( this, "selectNext", "selectPrev", "onSelect", "render" ); this.collection = options.collection; this.listenTo( this.collection, "select:one", this.onSelect ); this.listenTo( this.collection, "remove", this.render ); this.render(); }
javascript
function ( options ) { _.bindAll( this, "selectNext", "selectPrev", "onSelect", "render" ); this.collection = options.collection; this.listenTo( this.collection, "select:one", this.onSelect ); this.listenTo( this.collection, "remove", this.render ); this.render(); }
[ "function", "(", "options", ")", "{", "_", ".", "bindAll", "(", "this", ",", "\"selectNext\"", ",", "\"selectPrev\"", ",", "\"onSelect\"", ",", "\"render\"", ")", ";", "this", ".", "collection", "=", "options", ".", "collection", ";", "this", ".", "listenTo", "(", "this", ".", "collection", ",", "\"select:one\"", ",", "this", ".", "onSelect", ")", ";", "this", ".", "listenTo", "(", "this", ".", "collection", ",", "\"remove\"", ",", "this", ".", "render", ")", ";", "this", ".", "render", "(", ")", ";", "}" ]
A base class. Extend, don't instantiate. By default, render is a no-op. Override if necessary.
[ "A", "base", "class", ".", "Extend", "don", "t", "instantiate", ".", "By", "default", "render", "is", "a", "no", "-", "op", ".", "Override", "if", "necessary", "." ]
7e898ae2ebc6540b62a66f32fcb10f1a60d2f4b1
https://github.com/hashchange/backbone.cycle/blob/7e898ae2ebc6540b62a66f32fcb10f1a60d2f4b1/demo/amd/main.js#L32-L38
53,940
harrisiirak/buffer-stream-reader
reader.js
BufferStreamReader
function BufferStreamReader (data, options) { if (!(this instanceof BufferStreamReader)) { return new BufferStreamReader(data); } if (!options) { options = {}; } stream.Readable.call(this, options); this._data = null; this._chunkSize = options.chunkSize || -1; if (typeof data === 'string') { this._data = new Buffer(data, options.encoding || 'utf8'); } else if (Buffer.isBuffer(data)) { this._data = data; } }
javascript
function BufferStreamReader (data, options) { if (!(this instanceof BufferStreamReader)) { return new BufferStreamReader(data); } if (!options) { options = {}; } stream.Readable.call(this, options); this._data = null; this._chunkSize = options.chunkSize || -1; if (typeof data === 'string') { this._data = new Buffer(data, options.encoding || 'utf8'); } else if (Buffer.isBuffer(data)) { this._data = data; } }
[ "function", "BufferStreamReader", "(", "data", ",", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "BufferStreamReader", ")", ")", "{", "return", "new", "BufferStreamReader", "(", "data", ")", ";", "}", "if", "(", "!", "options", ")", "{", "options", "=", "{", "}", ";", "}", "stream", ".", "Readable", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "_data", "=", "null", ";", "this", ".", "_chunkSize", "=", "options", ".", "chunkSize", "||", "-", "1", ";", "if", "(", "typeof", "data", "===", "'string'", ")", "{", "this", ".", "_data", "=", "new", "Buffer", "(", "data", ",", "options", ".", "encoding", "||", "'utf8'", ")", ";", "}", "else", "if", "(", "Buffer", ".", "isBuffer", "(", "data", ")", ")", "{", "this", ".", "_data", "=", "data", ";", "}", "}" ]
Create a new stream reader @param data @param options @returns {StringReader} @constructor
[ "Create", "a", "new", "stream", "reader" ]
79ef10ddd35a95790c5eae1861b315a97156b400
https://github.com/harrisiirak/buffer-stream-reader/blob/79ef10ddd35a95790c5eae1861b315a97156b400/reader.js#L15-L34
53,941
spacemaus/postvox
vox-client/vox.js
RootContext
function RootContext(argv, profileFilenames, view) { var self = { commands: COMMANDS, // Overwritten when interactive profileFilenames: profileFilenames, interactive: false, argv: argv, view: view, config: null, nick: null, privkey: null, hubClient: null, voxClient: null, }; self.initWithConfig = function(config) { if (self.voxClient) { throw new Error('Already initialized!'); } self.config = config; self.nick = config.nick; self.voxClient = new VoxClient({ config: config, agentString: AGENT_STRING, }); return self.voxClient.connect(); } self.reinitWithConfig = function(config) { self.close(); return self.initWithConfig(config); } self.close = function() { if (self.voxClient) { self.voxClient.close(); self.voxClient = null; } } /** * Logs connection status events. */ self.listenForConnectionStatusEvents = function() { self.voxClient.on('connect', function(info) { self.view.log(colors.cyan.dim('Connected: ' + info.interchangeUrl)); }); self.voxClient.on('disconnect', function(info) { self.view.log(colors.red.dim('Disconnected: ' + info.interchangeUrl)); }); self.voxClient.on('error', function(info) { self.view.log(colors.red.dim('Connection error: ' + info.interchangeUrl)); }); self.voxClient.on('reconnect_failed', function(info) { self.view.log(colors.red.dim('Reconnection failed: ' + info.interchangeUrl)); }); } self.printJson = function(obj_or_name, obj) { if (obj !== undefined) { self.view.log('%s %s', obj_or_name, JSON.stringify(obj)); } else { self.view.log(JSON.stringify(obj_or_name)); } } return self; }
javascript
function RootContext(argv, profileFilenames, view) { var self = { commands: COMMANDS, // Overwritten when interactive profileFilenames: profileFilenames, interactive: false, argv: argv, view: view, config: null, nick: null, privkey: null, hubClient: null, voxClient: null, }; self.initWithConfig = function(config) { if (self.voxClient) { throw new Error('Already initialized!'); } self.config = config; self.nick = config.nick; self.voxClient = new VoxClient({ config: config, agentString: AGENT_STRING, }); return self.voxClient.connect(); } self.reinitWithConfig = function(config) { self.close(); return self.initWithConfig(config); } self.close = function() { if (self.voxClient) { self.voxClient.close(); self.voxClient = null; } } /** * Logs connection status events. */ self.listenForConnectionStatusEvents = function() { self.voxClient.on('connect', function(info) { self.view.log(colors.cyan.dim('Connected: ' + info.interchangeUrl)); }); self.voxClient.on('disconnect', function(info) { self.view.log(colors.red.dim('Disconnected: ' + info.interchangeUrl)); }); self.voxClient.on('error', function(info) { self.view.log(colors.red.dim('Connection error: ' + info.interchangeUrl)); }); self.voxClient.on('reconnect_failed', function(info) { self.view.log(colors.red.dim('Reconnection failed: ' + info.interchangeUrl)); }); } self.printJson = function(obj_or_name, obj) { if (obj !== undefined) { self.view.log('%s %s', obj_or_name, JSON.stringify(obj)); } else { self.view.log(JSON.stringify(obj_or_name)); } } return self; }
[ "function", "RootContext", "(", "argv", ",", "profileFilenames", ",", "view", ")", "{", "var", "self", "=", "{", "commands", ":", "COMMANDS", ",", "// Overwritten when interactive", "profileFilenames", ":", "profileFilenames", ",", "interactive", ":", "false", ",", "argv", ":", "argv", ",", "view", ":", "view", ",", "config", ":", "null", ",", "nick", ":", "null", ",", "privkey", ":", "null", ",", "hubClient", ":", "null", ",", "voxClient", ":", "null", ",", "}", ";", "self", ".", "initWithConfig", "=", "function", "(", "config", ")", "{", "if", "(", "self", ".", "voxClient", ")", "{", "throw", "new", "Error", "(", "'Already initialized!'", ")", ";", "}", "self", ".", "config", "=", "config", ";", "self", ".", "nick", "=", "config", ".", "nick", ";", "self", ".", "voxClient", "=", "new", "VoxClient", "(", "{", "config", ":", "config", ",", "agentString", ":", "AGENT_STRING", ",", "}", ")", ";", "return", "self", ".", "voxClient", ".", "connect", "(", ")", ";", "}", "self", ".", "reinitWithConfig", "=", "function", "(", "config", ")", "{", "self", ".", "close", "(", ")", ";", "return", "self", ".", "initWithConfig", "(", "config", ")", ";", "}", "self", ".", "close", "=", "function", "(", ")", "{", "if", "(", "self", ".", "voxClient", ")", "{", "self", ".", "voxClient", ".", "close", "(", ")", ";", "self", ".", "voxClient", "=", "null", ";", "}", "}", "/**\n * Logs connection status events.\n */", "self", ".", "listenForConnectionStatusEvents", "=", "function", "(", ")", "{", "self", ".", "voxClient", ".", "on", "(", "'connect'", ",", "function", "(", "info", ")", "{", "self", ".", "view", ".", "log", "(", "colors", ".", "cyan", ".", "dim", "(", "'Connected: '", "+", "info", ".", "interchangeUrl", ")", ")", ";", "}", ")", ";", "self", ".", "voxClient", ".", "on", "(", "'disconnect'", ",", "function", "(", "info", ")", "{", "self", ".", "view", ".", "log", "(", "colors", ".", "red", ".", "dim", "(", "'Disconnected: '", "+", "info", ".", "interchangeUrl", ")", ")", ";", "}", ")", ";", "self", ".", "voxClient", ".", "on", "(", "'error'", ",", "function", "(", "info", ")", "{", "self", ".", "view", ".", "log", "(", "colors", ".", "red", ".", "dim", "(", "'Connection error: '", "+", "info", ".", "interchangeUrl", ")", ")", ";", "}", ")", ";", "self", ".", "voxClient", ".", "on", "(", "'reconnect_failed'", ",", "function", "(", "info", ")", "{", "self", ".", "view", ".", "log", "(", "colors", ".", "red", ".", "dim", "(", "'Reconnection failed: '", "+", "info", ".", "interchangeUrl", ")", ")", ";", "}", ")", ";", "}", "self", ".", "printJson", "=", "function", "(", "obj_or_name", ",", "obj", ")", "{", "if", "(", "obj", "!==", "undefined", ")", "{", "self", ".", "view", ".", "log", "(", "'%s %s'", ",", "obj_or_name", ",", "JSON", ".", "stringify", "(", "obj", ")", ")", ";", "}", "else", "{", "self", ".", "view", ".", "log", "(", "JSON", ".", "stringify", "(", "obj_or_name", ")", ")", ";", "}", "}", "return", "self", ";", "}" ]
Creates a context object that can be passed to command handlers.
[ "Creates", "a", "context", "object", "that", "can", "be", "passed", "to", "command", "handlers", "." ]
de98e5ed37edaee1b1edadf93e15eb8f8d21f457
https://github.com/spacemaus/postvox/blob/de98e5ed37edaee1b1edadf93e15eb8f8d21f457/vox-client/vox.js#L133-L201
53,942
mathieuhays/LCD_Scrolling
index.js
progress
function progress( _line ){ messages[ _line ].progress++; if( (messages[ _line ].progress + messages[ _line ].diff) > 0 ){ messages[ _line ].progress = 0; } }
javascript
function progress( _line ){ messages[ _line ].progress++; if( (messages[ _line ].progress + messages[ _line ].diff) > 0 ){ messages[ _line ].progress = 0; } }
[ "function", "progress", "(", "_line", ")", "{", "messages", "[", "_line", "]", ".", "progress", "++", ";", "if", "(", "(", "messages", "[", "_line", "]", ".", "progress", "+", "messages", "[", "_line", "]", ".", "diff", ")", ">", "0", ")", "{", "messages", "[", "_line", "]", ".", "progress", "=", "0", ";", "}", "}" ]
Incremente progress or reset if done. @param (int) _line - Line index
[ "Incremente", "progress", "or", "reset", "if", "done", "." ]
b70b5f54268eefc6dca384ec4de090643e53adb1
https://github.com/mathieuhays/LCD_Scrolling/blob/b70b5f54268eefc6dca384ec4de090643e53adb1/index.js#L67-L77
53,943
mathieuhays/LCD_Scrolling
index.js
anim
function anim( _line ){ var msg = messages[ _line ]; lcd.cursor( _line, 0 ); if( msg.progress === 0 ){ lcd.print( msg.msg ); progress( _line ); (function( _line ){ timeout = setTimeout(function(){ anim( _line ) }, anim_settings.firstCharPauseDuration ); })( _line ); }else{ lcd.print( msg.msg.substr( msg.progress ) ); progress( _line ); (function( _line ){ var time = anim_settings.scrollingDuration; if( messages[ _line ].progress === 0 ){ time = anim_settings.lastCharPauseDuration; } timeout = setTimeout( function(){ anim( _line ); }, time ); })( _line ); } }
javascript
function anim( _line ){ var msg = messages[ _line ]; lcd.cursor( _line, 0 ); if( msg.progress === 0 ){ lcd.print( msg.msg ); progress( _line ); (function( _line ){ timeout = setTimeout(function(){ anim( _line ) }, anim_settings.firstCharPauseDuration ); })( _line ); }else{ lcd.print( msg.msg.substr( msg.progress ) ); progress( _line ); (function( _line ){ var time = anim_settings.scrollingDuration; if( messages[ _line ].progress === 0 ){ time = anim_settings.lastCharPauseDuration; } timeout = setTimeout( function(){ anim( _line ); }, time ); })( _line ); } }
[ "function", "anim", "(", "_line", ")", "{", "var", "msg", "=", "messages", "[", "_line", "]", ";", "lcd", ".", "cursor", "(", "_line", ",", "0", ")", ";", "if", "(", "msg", ".", "progress", "===", "0", ")", "{", "lcd", ".", "print", "(", "msg", ".", "msg", ")", ";", "progress", "(", "_line", ")", ";", "(", "function", "(", "_line", ")", "{", "timeout", "=", "setTimeout", "(", "function", "(", ")", "{", "anim", "(", "_line", ")", "}", ",", "anim_settings", ".", "firstCharPauseDuration", ")", ";", "}", ")", "(", "_line", ")", ";", "}", "else", "{", "lcd", ".", "print", "(", "msg", ".", "msg", ".", "substr", "(", "msg", ".", "progress", ")", ")", ";", "progress", "(", "_line", ")", ";", "(", "function", "(", "_line", ")", "{", "var", "time", "=", "anim_settings", ".", "scrollingDuration", ";", "if", "(", "messages", "[", "_line", "]", ".", "progress", "===", "0", ")", "{", "time", "=", "anim_settings", ".", "lastCharPauseDuration", ";", "}", "timeout", "=", "setTimeout", "(", "function", "(", ")", "{", "anim", "(", "_line", ")", ";", "}", ",", "time", ")", ";", "}", ")", "(", "_line", ")", ";", "}", "}" ]
Animate the text on screen @param (int) _line - Line index
[ "Animate", "the", "text", "on", "screen" ]
b70b5f54268eefc6dca384ec4de090643e53adb1
https://github.com/mathieuhays/LCD_Scrolling/blob/b70b5f54268eefc6dca384ec4de090643e53adb1/index.js#L84-L123
53,944
rkaw92/esdf
Commit.js
Commit
function Commit(events, sequenceID, sequenceSlot, aggregateType, metadata){ if(!Array.isArray(events)){ throw new Error('events must be an array while constructing Commit'); } if(typeof(sequenceID) !== 'string'){ throw new Error('sequenceID is not a string while constructing Commit'); } if(!sequenceSlot){ throw new Error('sequenceSlot not a number, or zero, while constructing Commit'); } this.events = events; this.sequenceID = sequenceID; this.sequenceSlot = sequenceSlot; this.aggregateType = aggregateType; this.metadata = metadata ? metadata : {}; }
javascript
function Commit(events, sequenceID, sequenceSlot, aggregateType, metadata){ if(!Array.isArray(events)){ throw new Error('events must be an array while constructing Commit'); } if(typeof(sequenceID) !== 'string'){ throw new Error('sequenceID is not a string while constructing Commit'); } if(!sequenceSlot){ throw new Error('sequenceSlot not a number, or zero, while constructing Commit'); } this.events = events; this.sequenceID = sequenceID; this.sequenceSlot = sequenceSlot; this.aggregateType = aggregateType; this.metadata = metadata ? metadata : {}; }
[ "function", "Commit", "(", "events", ",", "sequenceID", ",", "sequenceSlot", ",", "aggregateType", ",", "metadata", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "events", ")", ")", "{", "throw", "new", "Error", "(", "'events must be an array while constructing Commit'", ")", ";", "}", "if", "(", "typeof", "(", "sequenceID", ")", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'sequenceID is not a string while constructing Commit'", ")", ";", "}", "if", "(", "!", "sequenceSlot", ")", "{", "throw", "new", "Error", "(", "'sequenceSlot not a number, or zero, while constructing Commit'", ")", ";", "}", "this", ".", "events", "=", "events", ";", "this", ".", "sequenceID", "=", "sequenceID", ";", "this", ".", "sequenceSlot", "=", "sequenceSlot", ";", "this", ".", "aggregateType", "=", "aggregateType", ";", "this", ".", "metadata", "=", "metadata", "?", "metadata", ":", "{", "}", ";", "}" ]
Construct a new commit. A commit is an atomic group of events, handled in an all-or-nothing manner by an event sink. It is the basic unit of event storage in this framework. @constructor @param {module:esdf/core/Event.Event[]} events A list of events that the commit is composed of. @param {String} sequenceID Character-based ID (typically a GUID) of the stream to which this commit belongs. @param {Number} sequenceSlot The slot number this commit is meant to occupy within the sequence. Only one commit may take a particular slot. @param {String} aggregateType Name of the aggregate type, as reported by the proper EventSourcedAggregate. @param {Object} metadata The additional information, in a map format, associated with this commit.
[ "Construct", "a", "new", "commit", ".", "A", "commit", "is", "an", "atomic", "group", "of", "events", "handled", "in", "an", "all", "-", "or", "-", "nothing", "manner", "by", "an", "event", "sink", ".", "It", "is", "the", "basic", "unit", "of", "event", "storage", "in", "this", "framework", "." ]
9c6bd2c278428096cb8c1ceeca62a5493d19613e
https://github.com/rkaw92/esdf/blob/9c6bd2c278428096cb8c1ceeca62a5493d19613e/Commit.js#L15-L25
53,945
marcelomf/graojs
modeling/assets/WebGL/webgl-debug.js
init
function init(ctx) { if (glEnums == null) { glEnums = { }; for (var propertyName in ctx) { if (typeof ctx[propertyName] == 'number') { glEnums[ctx[propertyName]] = propertyName; } } } }
javascript
function init(ctx) { if (glEnums == null) { glEnums = { }; for (var propertyName in ctx) { if (typeof ctx[propertyName] == 'number') { glEnums[ctx[propertyName]] = propertyName; } } } }
[ "function", "init", "(", "ctx", ")", "{", "if", "(", "glEnums", "==", "null", ")", "{", "glEnums", "=", "{", "}", ";", "for", "(", "var", "propertyName", "in", "ctx", ")", "{", "if", "(", "typeof", "ctx", "[", "propertyName", "]", "==", "'number'", ")", "{", "glEnums", "[", "ctx", "[", "propertyName", "]", "]", "=", "propertyName", ";", "}", "}", "}", "}" ]
Initializes this module. Safe to call more than once. @param {!WebGLRenderingContext} ctx A WebGL context. If you have more than one context it doesn't matter which one you pass in, it is only used to pull out constants.
[ "Initializes", "this", "module", ".", "Safe", "to", "call", "more", "than", "once", "." ]
f8fd9e5ed9406c6266c30777eb4f77474fe6ac4f
https://github.com/marcelomf/graojs/blob/f8fd9e5ed9406c6266c30777eb4f77474fe6ac4f/modeling/assets/WebGL/webgl-debug.js#L143-L152
53,946
marcelomf/graojs
modeling/assets/WebGL/webgl-debug.js
glEnumToString
function glEnumToString(value) { checkInit(); var name = glEnums[value]; return (name !== undefined) ? name : ("*UNKNOWN WebGL ENUM (0x" + value.toString(16) + ")"); }
javascript
function glEnumToString(value) { checkInit(); var name = glEnums[value]; return (name !== undefined) ? name : ("*UNKNOWN WebGL ENUM (0x" + value.toString(16) + ")"); }
[ "function", "glEnumToString", "(", "value", ")", "{", "checkInit", "(", ")", ";", "var", "name", "=", "glEnums", "[", "value", "]", ";", "return", "(", "name", "!==", "undefined", ")", "?", "name", ":", "(", "\"*UNKNOWN WebGL ENUM (0x\"", "+", "value", ".", "toString", "(", "16", ")", "+", "\")\"", ")", ";", "}" ]
Gets an string version of an WebGL enum. Example: var str = WebGLDebugUtil.glEnumToString(ctx.getError()); @param {number} value Value to return an enum for @return {string} The string version of the enum.
[ "Gets", "an", "string", "version", "of", "an", "WebGL", "enum", "." ]
f8fd9e5ed9406c6266c30777eb4f77474fe6ac4f
https://github.com/marcelomf/graojs/blob/f8fd9e5ed9406c6266c30777eb4f77474fe6ac4f/modeling/assets/WebGL/webgl-debug.js#L182-L187
53,947
marcelomf/graojs
modeling/assets/WebGL/webgl-debug.js
glFunctionArgsToString
function glFunctionArgsToString(functionName, args) { // apparently we can't do args.join(","); var argStr = ""; for (var ii = 0; ii < args.length; ++ii) { argStr += ((ii == 0) ? '' : ', ') + glFunctionArgToString(functionName, ii, args[ii]); } return argStr; }
javascript
function glFunctionArgsToString(functionName, args) { // apparently we can't do args.join(","); var argStr = ""; for (var ii = 0; ii < args.length; ++ii) { argStr += ((ii == 0) ? '' : ', ') + glFunctionArgToString(functionName, ii, args[ii]); } return argStr; }
[ "function", "glFunctionArgsToString", "(", "functionName", ",", "args", ")", "{", "// apparently we can't do args.join(\",\");", "var", "argStr", "=", "\"\"", ";", "for", "(", "var", "ii", "=", "0", ";", "ii", "<", "args", ".", "length", ";", "++", "ii", ")", "{", "argStr", "+=", "(", "(", "ii", "==", "0", ")", "?", "''", ":", "', '", ")", "+", "glFunctionArgToString", "(", "functionName", ",", "ii", ",", "args", "[", "ii", "]", ")", ";", "}", "return", "argStr", ";", "}" ]
Converts the arguments of a WebGL function to a string. Attempts to convert enum arguments to strings. @param {string} functionName the name of the WebGL function. @param {number} args The arguments. @return {string} The arguments as a string.
[ "Converts", "the", "arguments", "of", "a", "WebGL", "function", "to", "a", "string", ".", "Attempts", "to", "convert", "enum", "arguments", "to", "strings", "." ]
f8fd9e5ed9406c6266c30777eb4f77474fe6ac4f
https://github.com/marcelomf/graojs/blob/f8fd9e5ed9406c6266c30777eb4f77474fe6ac4f/modeling/assets/WebGL/webgl-debug.js#L221-L229
53,948
marcelomf/graojs
modeling/assets/WebGL/webgl-debug.js
makeDebugContext
function makeDebugContext(ctx, opt_onErrorFunc, opt_onFunc) { init(ctx); opt_onErrorFunc = opt_onErrorFunc || function(err, functionName, args) { // apparently we can't do args.join(","); var argStr = ""; for (var ii = 0; ii < args.length; ++ii) { argStr += ((ii == 0) ? '' : ', ') + glFunctionArgToString(functionName, ii, args[ii]); } error("WebGL error "+ glEnumToString(err) + " in "+ functionName + "(" + argStr + ")"); }; // Holds booleans for each GL error so after we get the error ourselves // we can still return it to the client app. var glErrorShadow = { }; // Makes a function that calls a WebGL function and then calls getError. function makeErrorWrapper(ctx, functionName) { return function() { if (opt_onFunc) { opt_onFunc(functionName, arguments); } var result = ctx[functionName].apply(ctx, arguments); var err = ctx.getError(); if (err != 0) { glErrorShadow[err] = true; opt_onErrorFunc(err, functionName, arguments); } return result; }; } // Make a an object that has a copy of every property of the WebGL context // but wraps all functions. var wrapper = {}; for (var propertyName in ctx) { if (typeof ctx[propertyName] == 'function') { wrapper[propertyName] = makeErrorWrapper(ctx, propertyName); } else { makePropertyWrapper(wrapper, ctx, propertyName); } } // Override the getError function with one that returns our saved results. wrapper.getError = function() { for (var err in glErrorShadow) { if (glErrorShadow.hasOwnProperty(err)) { if (glErrorShadow[err]) { glErrorShadow[err] = false; return err; } } } return ctx.NO_ERROR; }; return wrapper; }
javascript
function makeDebugContext(ctx, opt_onErrorFunc, opt_onFunc) { init(ctx); opt_onErrorFunc = opt_onErrorFunc || function(err, functionName, args) { // apparently we can't do args.join(","); var argStr = ""; for (var ii = 0; ii < args.length; ++ii) { argStr += ((ii == 0) ? '' : ', ') + glFunctionArgToString(functionName, ii, args[ii]); } error("WebGL error "+ glEnumToString(err) + " in "+ functionName + "(" + argStr + ")"); }; // Holds booleans for each GL error so after we get the error ourselves // we can still return it to the client app. var glErrorShadow = { }; // Makes a function that calls a WebGL function and then calls getError. function makeErrorWrapper(ctx, functionName) { return function() { if (opt_onFunc) { opt_onFunc(functionName, arguments); } var result = ctx[functionName].apply(ctx, arguments); var err = ctx.getError(); if (err != 0) { glErrorShadow[err] = true; opt_onErrorFunc(err, functionName, arguments); } return result; }; } // Make a an object that has a copy of every property of the WebGL context // but wraps all functions. var wrapper = {}; for (var propertyName in ctx) { if (typeof ctx[propertyName] == 'function') { wrapper[propertyName] = makeErrorWrapper(ctx, propertyName); } else { makePropertyWrapper(wrapper, ctx, propertyName); } } // Override the getError function with one that returns our saved results. wrapper.getError = function() { for (var err in glErrorShadow) { if (glErrorShadow.hasOwnProperty(err)) { if (glErrorShadow[err]) { glErrorShadow[err] = false; return err; } } } return ctx.NO_ERROR; }; return wrapper; }
[ "function", "makeDebugContext", "(", "ctx", ",", "opt_onErrorFunc", ",", "opt_onFunc", ")", "{", "init", "(", "ctx", ")", ";", "opt_onErrorFunc", "=", "opt_onErrorFunc", "||", "function", "(", "err", ",", "functionName", ",", "args", ")", "{", "// apparently we can't do args.join(\",\");", "var", "argStr", "=", "\"\"", ";", "for", "(", "var", "ii", "=", "0", ";", "ii", "<", "args", ".", "length", ";", "++", "ii", ")", "{", "argStr", "+=", "(", "(", "ii", "==", "0", ")", "?", "''", ":", "', '", ")", "+", "glFunctionArgToString", "(", "functionName", ",", "ii", ",", "args", "[", "ii", "]", ")", ";", "}", "error", "(", "\"WebGL error \"", "+", "glEnumToString", "(", "err", ")", "+", "\" in \"", "+", "functionName", "+", "\"(\"", "+", "argStr", "+", "\")\"", ")", ";", "}", ";", "// Holds booleans for each GL error so after we get the error ourselves", "// we can still return it to the client app.", "var", "glErrorShadow", "=", "{", "}", ";", "// Makes a function that calls a WebGL function and then calls getError.", "function", "makeErrorWrapper", "(", "ctx", ",", "functionName", ")", "{", "return", "function", "(", ")", "{", "if", "(", "opt_onFunc", ")", "{", "opt_onFunc", "(", "functionName", ",", "arguments", ")", ";", "}", "var", "result", "=", "ctx", "[", "functionName", "]", ".", "apply", "(", "ctx", ",", "arguments", ")", ";", "var", "err", "=", "ctx", ".", "getError", "(", ")", ";", "if", "(", "err", "!=", "0", ")", "{", "glErrorShadow", "[", "err", "]", "=", "true", ";", "opt_onErrorFunc", "(", "err", ",", "functionName", ",", "arguments", ")", ";", "}", "return", "result", ";", "}", ";", "}", "// Make a an object that has a copy of every property of the WebGL context", "// but wraps all functions.", "var", "wrapper", "=", "{", "}", ";", "for", "(", "var", "propertyName", "in", "ctx", ")", "{", "if", "(", "typeof", "ctx", "[", "propertyName", "]", "==", "'function'", ")", "{", "wrapper", "[", "propertyName", "]", "=", "makeErrorWrapper", "(", "ctx", ",", "propertyName", ")", ";", "}", "else", "{", "makePropertyWrapper", "(", "wrapper", ",", "ctx", ",", "propertyName", ")", ";", "}", "}", "// Override the getError function with one that returns our saved results.", "wrapper", ".", "getError", "=", "function", "(", ")", "{", "for", "(", "var", "err", "in", "glErrorShadow", ")", "{", "if", "(", "glErrorShadow", ".", "hasOwnProperty", "(", "err", ")", ")", "{", "if", "(", "glErrorShadow", "[", "err", "]", ")", "{", "glErrorShadow", "[", "err", "]", "=", "false", ";", "return", "err", ";", "}", "}", "}", "return", "ctx", ".", "NO_ERROR", ";", "}", ";", "return", "wrapper", ";", "}" ]
Given a WebGL context returns a wrapped context that calls gl.getError after every command and calls a function if the result is not gl.NO_ERROR. @param {!WebGLRenderingContext} ctx The webgl context to wrap. @param {!function(err, funcName, args): void} opt_onErrorFunc The function to call when gl.getError returns an error. If not specified the default function calls console.log with a message. @param {!function(funcName, args): void} opt_onFunc The function to call when each webgl function is called. You can use this to log all calls for example.
[ "Given", "a", "WebGL", "context", "returns", "a", "wrapped", "context", "that", "calls", "gl", ".", "getError", "after", "every", "command", "and", "calls", "a", "function", "if", "the", "result", "is", "not", "gl", ".", "NO_ERROR", "." ]
f8fd9e5ed9406c6266c30777eb4f77474fe6ac4f
https://github.com/marcelomf/graojs/blob/f8fd9e5ed9406c6266c30777eb4f77474fe6ac4f/modeling/assets/WebGL/webgl-debug.js#L271-L329
53,949
Raynos/seaport-proxy
lib/service.js
createServer
function createServer(serverName) { console.log("creating server", serverName) var server = servers[serverName] = net.createServer(handleConnection) ports.service(serverName, listen) function handleConnection(connection) { console.log("got incoming connection", connection) var stream = proxy.connect(serverName) , buffer = PauseStream().pause() , intermediate = through(stringer) connection.pipe(buffer) process.nextTick(pipe) function pipe() { buffer.pipe(intermediate) .pipe(stream).pipe(connection) buffer.resume() } } function listen(port, ready) { server.listen(port, ready) } }
javascript
function createServer(serverName) { console.log("creating server", serverName) var server = servers[serverName] = net.createServer(handleConnection) ports.service(serverName, listen) function handleConnection(connection) { console.log("got incoming connection", connection) var stream = proxy.connect(serverName) , buffer = PauseStream().pause() , intermediate = through(stringer) connection.pipe(buffer) process.nextTick(pipe) function pipe() { buffer.pipe(intermediate) .pipe(stream).pipe(connection) buffer.resume() } } function listen(port, ready) { server.listen(port, ready) } }
[ "function", "createServer", "(", "serverName", ")", "{", "console", ".", "log", "(", "\"creating server\"", ",", "serverName", ")", "var", "server", "=", "servers", "[", "serverName", "]", "=", "net", ".", "createServer", "(", "handleConnection", ")", "ports", ".", "service", "(", "serverName", ",", "listen", ")", "function", "handleConnection", "(", "connection", ")", "{", "console", ".", "log", "(", "\"got incoming connection\"", ",", "connection", ")", "var", "stream", "=", "proxy", ".", "connect", "(", "serverName", ")", ",", "buffer", "=", "PauseStream", "(", ")", ".", "pause", "(", ")", ",", "intermediate", "=", "through", "(", "stringer", ")", "connection", ".", "pipe", "(", "buffer", ")", "process", ".", "nextTick", "(", "pipe", ")", "function", "pipe", "(", ")", "{", "buffer", ".", "pipe", "(", "intermediate", ")", ".", "pipe", "(", "stream", ")", ".", "pipe", "(", "connection", ")", "buffer", ".", "resume", "(", ")", "}", "}", "function", "listen", "(", "port", ",", "ready", ")", "{", "server", ".", "listen", "(", "port", ",", "ready", ")", "}", "}" ]
create seaport service when server stream comes up
[ "create", "seaport", "service", "when", "server", "stream", "comes", "up" ]
3a05afe6e6f801b09a3810eea27e7366221cadad
https://github.com/Raynos/seaport-proxy/blob/3a05afe6e6f801b09a3810eea27e7366221cadad/lib/service.js#L20-L46
53,950
haasz/laravel-mix-ext
config/index.js
modifyOutRules
function modifyOutRules(rules) { for (let i = 0; i < rules.length; ++i) { if (rules[i].test) { switch ('' + rules[i].test) { // Images case '/\\.(png|jpe?g|gif)$/': modifyOutRule(rules[i], 'images'); break; // Fonts case '/\\.(woff2?|ttf|eot|svg|otf)$/': modifyOutRule(rules[i], 'fonts'); break; default: } } } }
javascript
function modifyOutRules(rules) { for (let i = 0; i < rules.length; ++i) { if (rules[i].test) { switch ('' + rules[i].test) { // Images case '/\\.(png|jpe?g|gif)$/': modifyOutRule(rules[i], 'images'); break; // Fonts case '/\\.(woff2?|ttf|eot|svg|otf)$/': modifyOutRule(rules[i], 'fonts'); break; default: } } } }
[ "function", "modifyOutRules", "(", "rules", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "rules", ".", "length", ";", "++", "i", ")", "{", "if", "(", "rules", "[", "i", "]", ".", "test", ")", "{", "switch", "(", "''", "+", "rules", "[", "i", "]", ".", "test", ")", "{", "// Images", "case", "'/\\\\.(png|jpe?g|gif)$/'", ":", "modifyOutRule", "(", "rules", "[", "i", "]", ",", "'images'", ")", ";", "break", ";", "// Fonts", "case", "'/\\\\.(woff2?|ttf|eot|svg|otf)$/'", ":", "modifyOutRule", "(", "rules", "[", "i", "]", ",", "'fonts'", ")", ";", "break", ";", "default", ":", "}", "}", "}", "}" ]
Modify the rules of output directories. @param {Array} rules The rules.
[ "Modify", "the", "rules", "of", "output", "directories", "." ]
bd1c794bdbf934dae233ab697dc5d5593d4b1124
https://github.com/haasz/laravel-mix-ext/blob/bd1c794bdbf934dae233ab697dc5d5593d4b1124/config/index.js#L41-L58
53,951
haasz/laravel-mix-ext
config/index.js
modifyOutRule
function modifyOutRule(rule, type) { rule.test = new RegExp( '\\.(' + Config.out[type].extensions.join('|') + ')$' ); }
javascript
function modifyOutRule(rule, type) { rule.test = new RegExp( '\\.(' + Config.out[type].extensions.join('|') + ')$' ); }
[ "function", "modifyOutRule", "(", "rule", ",", "type", ")", "{", "rule", ".", "test", "=", "new", "RegExp", "(", "'\\\\.('", "+", "Config", ".", "out", "[", "type", "]", ".", "extensions", ".", "join", "(", "'|'", ")", "+", "')$'", ")", ";", "}" ]
Modify the rule of output directory. @param {Object} rule The rule. @param {string} type The output directory type.
[ "Modify", "the", "rule", "of", "output", "directory", "." ]
bd1c794bdbf934dae233ab697dc5d5593d4b1124
https://github.com/haasz/laravel-mix-ext/blob/bd1c794bdbf934dae233ab697dc5d5593d4b1124/config/index.js#L67-L71
53,952
jfseb/mgnlq_model
js/modelload/schemaload.js
loadModelNames
function loadModelNames(modelPath) { modelPath = modelPath || envModelPath; debuglog(() => `modelpath is ${modelPath} `); var mdls = FUtils.readFileAsJSON('./' + modelPath + '/models.json'); mdls.forEach(name => { if (name !== makeMongoCollectionName(name)) { throw new Error('bad modelname, must terminate with s and be lowercase'); } }); return mdls; }
javascript
function loadModelNames(modelPath) { modelPath = modelPath || envModelPath; debuglog(() => `modelpath is ${modelPath} `); var mdls = FUtils.readFileAsJSON('./' + modelPath + '/models.json'); mdls.forEach(name => { if (name !== makeMongoCollectionName(name)) { throw new Error('bad modelname, must terminate with s and be lowercase'); } }); return mdls; }
[ "function", "loadModelNames", "(", "modelPath", ")", "{", "modelPath", "=", "modelPath", "||", "envModelPath", ";", "debuglog", "(", "(", ")", "=>", "`", "${", "modelPath", "}", "`", ")", ";", "var", "mdls", "=", "FUtils", ".", "readFileAsJSON", "(", "'./'", "+", "modelPath", "+", "'/models.json'", ")", ";", "mdls", ".", "forEach", "(", "name", "=>", "{", "if", "(", "name", "!==", "makeMongoCollectionName", "(", "name", ")", ")", "{", "throw", "new", "Error", "(", "'bad modelname, must terminate with s and be lowercase'", ")", ";", "}", "}", ")", ";", "return", "mdls", ";", "}" ]
load the models
[ "load", "the", "models" ]
be1be4406b05718d666d6d0f712c9cadb5169f2c
https://github.com/jfseb/mgnlq_model/blob/be1be4406b05718d666d6d0f712c9cadb5169f2c/js/modelload/schemaload.js#L58-L68
53,953
jfseb/mgnlq_model
js/modelload/schemaload.js
makeMongooseModelName
function makeMongooseModelName(collectionName) { if (collectionName !== collectionName.toLowerCase()) { throw new Error('expect lowercase, was ' + collectionName); } if (collectionName.charAt(collectionName.length - 1) === 's') { return collectionName.substring(0, collectionName.length - 1); } throw new Error('expected name with trailing s'); }
javascript
function makeMongooseModelName(collectionName) { if (collectionName !== collectionName.toLowerCase()) { throw new Error('expect lowercase, was ' + collectionName); } if (collectionName.charAt(collectionName.length - 1) === 's') { return collectionName.substring(0, collectionName.length - 1); } throw new Error('expected name with trailing s'); }
[ "function", "makeMongooseModelName", "(", "collectionName", ")", "{", "if", "(", "collectionName", "!==", "collectionName", ".", "toLowerCase", "(", ")", ")", "{", "throw", "new", "Error", "(", "'expect lowercase, was '", "+", "collectionName", ")", ";", "}", "if", "(", "collectionName", ".", "charAt", "(", "collectionName", ".", "length", "-", "1", ")", "===", "'s'", ")", "{", "return", "collectionName", ".", "substring", "(", "0", ",", "collectionName", ".", "length", "-", "1", ")", ";", "}", "throw", "new", "Error", "(", "'expected name with trailing s'", ")", ";", "}" ]
return a modelname without a traling s @param collectionName
[ "return", "a", "modelname", "without", "a", "traling", "s" ]
be1be4406b05718d666d6d0f712c9cadb5169f2c
https://github.com/jfseb/mgnlq_model/blob/be1be4406b05718d666d6d0f712c9cadb5169f2c/js/modelload/schemaload.js#L176-L184
53,954
jfseb/mgnlq_model
js/modelload/schemaload.js
makeMongoCollectionName
function makeMongoCollectionName(modelName) { if (modelName !== modelName.toLowerCase()) { throw new Error('expect lowercase, was ' + modelName); } if (modelName.charAt(modelName.length - 1) !== 's') { return modelName + 's'; } return modelName; }
javascript
function makeMongoCollectionName(modelName) { if (modelName !== modelName.toLowerCase()) { throw new Error('expect lowercase, was ' + modelName); } if (modelName.charAt(modelName.length - 1) !== 's') { return modelName + 's'; } return modelName; }
[ "function", "makeMongoCollectionName", "(", "modelName", ")", "{", "if", "(", "modelName", "!==", "modelName", ".", "toLowerCase", "(", ")", ")", "{", "throw", "new", "Error", "(", "'expect lowercase, was '", "+", "modelName", ")", ";", "}", "if", "(", "modelName", ".", "charAt", "(", "modelName", ".", "length", "-", "1", ")", "!==", "'s'", ")", "{", "return", "modelName", "+", "'s'", ";", "}", "return", "modelName", ";", "}" ]
returns a mongoose collection name @param modelName
[ "returns", "a", "mongoose", "collection", "name" ]
be1be4406b05718d666d6d0f712c9cadb5169f2c
https://github.com/jfseb/mgnlq_model/blob/be1be4406b05718d666d6d0f712c9cadb5169f2c/js/modelload/schemaload.js#L190-L198
53,955
SolarNetwork/solarnetwork-d3
src/net/sec.js
token
function token(value) { if ( !arguments.length ) return cred.token; cred.token = (value && value.length > 0 ? value : undefined); return that; }
javascript
function token(value) { if ( !arguments.length ) return cred.token; cred.token = (value && value.length > 0 ? value : undefined); return that; }
[ "function", "token", "(", "value", ")", "{", "if", "(", "!", "arguments", ".", "length", ")", "return", "cred", ".", "token", ";", "cred", ".", "token", "=", "(", "value", "&&", "value", ".", "length", ">", "0", "?", "value", ":", "undefined", ")", ";", "return", "that", ";", "}" ]
Get or set the in-memory security token to use. @param {String} [value] The value to set, or <code>null</code> to clear. @returs When used as a getter, the current token value, otherwise this object. @preserve
[ "Get", "or", "set", "the", "in", "-", "memory", "security", "token", "to", "use", "." ]
26848b1c303b98b7c0ddeefb8c68c5f5bf78927e
https://github.com/SolarNetwork/solarnetwork-d3/blob/26848b1c303b98b7c0ddeefb8c68c5f5bf78927e/src/net/sec.js#L55-L59
53,956
SolarNetwork/solarnetwork-d3
src/net/sec.js
generateAuthorizationHeaderValue
function generateAuthorizationHeaderValue(signedHeaders, signKey, signingMsg) { var signature = CryptoJS.HmacSHA256(signingMsg, signKey); var authHeader = 'SNWS2 Credential=' +cred.token +',SignedHeaders=' +signedHeaders.join(';') +',Signature=' +CryptoJS.enc.Hex.stringify(signature); return authHeader; }
javascript
function generateAuthorizationHeaderValue(signedHeaders, signKey, signingMsg) { var signature = CryptoJS.HmacSHA256(signingMsg, signKey); var authHeader = 'SNWS2 Credential=' +cred.token +',SignedHeaders=' +signedHeaders.join(';') +',Signature=' +CryptoJS.enc.Hex.stringify(signature); return authHeader; }
[ "function", "generateAuthorizationHeaderValue", "(", "signedHeaders", ",", "signKey", ",", "signingMsg", ")", "{", "var", "signature", "=", "CryptoJS", ".", "HmacSHA256", "(", "signingMsg", ",", "signKey", ")", ";", "var", "authHeader", "=", "'SNWS2 Credential='", "+", "cred", ".", "token", "+", "',SignedHeaders='", "+", "signedHeaders", ".", "join", "(", "';'", ")", "+", "',Signature='", "+", "CryptoJS", ".", "enc", ".", "Hex", ".", "stringify", "(", "signature", ")", ";", "return", "authHeader", ";", "}" ]
Generate the V2 HTTP Authorization header. @param {String} token the SN token ID @param {Array} signedHeaders the sorted array of signed header names @param {Object} signKey the key to encrypt the signature with @param {String} signingMsg the message to sign @return {String} the HTTP header value @preserve
[ "Generate", "the", "V2", "HTTP", "Authorization", "header", "." ]
26848b1c303b98b7c0ddeefb8c68c5f5bf78927e
https://github.com/SolarNetwork/solarnetwork-d3/blob/26848b1c303b98b7c0ddeefb8c68c5f5bf78927e/src/net/sec.js#L160-L166
53,957
SolarNetwork/solarnetwork-d3
src/net/sec.js
computeAuthorization
function computeAuthorization(url, method, data, contentType, date) { date = (date || new Date()); var uri = URI.parse(url); var canonQueryParams = canonicalQueryParameters(uri, data, contentType); var canonHeaders = canonicalHeaders(uri, contentType, date, bodyContentDigest); var bodyContentDigest = bodyContentSHA256(data, contentType); var canonRequestMsg = generateCanonicalRequestMessage({ method: method, uri: uri, queryParams : canonQueryParams, headers : canonHeaders, bodyDigest: bodyContentDigest }); var signingMsg = generateSigningMessage(date, canonRequestMsg); var signKey = signingKey(date); var authHeader = generateAuthorizationHeaderValue(canonHeaders.headerNames, signKey, signingMsg); return { header: authHeader, date: date, dateHeader: canonHeaders.headers['x-sn-date'], verb: method, canonicalUri: uri.path, canonicalQueryParameters: canonQueryParams, canonicalHeaders: canonHeaders, bodyContentDigest: bodyContentDigest, canonicalRequestMessage: canonRequestMsg, signingMessage: signingMsg, signingKey: signKey }; }
javascript
function computeAuthorization(url, method, data, contentType, date) { date = (date || new Date()); var uri = URI.parse(url); var canonQueryParams = canonicalQueryParameters(uri, data, contentType); var canonHeaders = canonicalHeaders(uri, contentType, date, bodyContentDigest); var bodyContentDigest = bodyContentSHA256(data, contentType); var canonRequestMsg = generateCanonicalRequestMessage({ method: method, uri: uri, queryParams : canonQueryParams, headers : canonHeaders, bodyDigest: bodyContentDigest }); var signingMsg = generateSigningMessage(date, canonRequestMsg); var signKey = signingKey(date); var authHeader = generateAuthorizationHeaderValue(canonHeaders.headerNames, signKey, signingMsg); return { header: authHeader, date: date, dateHeader: canonHeaders.headers['x-sn-date'], verb: method, canonicalUri: uri.path, canonicalQueryParameters: canonQueryParams, canonicalHeaders: canonHeaders, bodyContentDigest: bodyContentDigest, canonicalRequestMessage: canonRequestMsg, signingMessage: signingMsg, signingKey: signKey }; }
[ "function", "computeAuthorization", "(", "url", ",", "method", ",", "data", ",", "contentType", ",", "date", ")", "{", "date", "=", "(", "date", "||", "new", "Date", "(", ")", ")", ";", "var", "uri", "=", "URI", ".", "parse", "(", "url", ")", ";", "var", "canonQueryParams", "=", "canonicalQueryParameters", "(", "uri", ",", "data", ",", "contentType", ")", ";", "var", "canonHeaders", "=", "canonicalHeaders", "(", "uri", ",", "contentType", ",", "date", ",", "bodyContentDigest", ")", ";", "var", "bodyContentDigest", "=", "bodyContentSHA256", "(", "data", ",", "contentType", ")", ";", "var", "canonRequestMsg", "=", "generateCanonicalRequestMessage", "(", "{", "method", ":", "method", ",", "uri", ":", "uri", ",", "queryParams", ":", "canonQueryParams", ",", "headers", ":", "canonHeaders", ",", "bodyDigest", ":", "bodyContentDigest", "}", ")", ";", "var", "signingMsg", "=", "generateSigningMessage", "(", "date", ",", "canonRequestMsg", ")", ";", "var", "signKey", "=", "signingKey", "(", "date", ")", ";", "var", "authHeader", "=", "generateAuthorizationHeaderValue", "(", "canonHeaders", ".", "headerNames", ",", "signKey", ",", "signingMsg", ")", ";", "return", "{", "header", ":", "authHeader", ",", "date", ":", "date", ",", "dateHeader", ":", "canonHeaders", ".", "headers", "[", "'x-sn-date'", "]", ",", "verb", ":", "method", ",", "canonicalUri", ":", "uri", ".", "path", ",", "canonicalQueryParameters", ":", "canonQueryParams", ",", "canonicalHeaders", ":", "canonHeaders", ",", "bodyContentDigest", ":", "bodyContentDigest", ",", "canonicalRequestMessage", ":", "canonRequestMsg", ",", "signingMessage", ":", "signingMsg", ",", "signingKey", ":", "signKey", "}", ";", "}" ]
Compute SNWS2 authorization info. <p>This method will compute the components necessary to later invoke a SolarNetwork API request using the SNWS2 authorization scheme. The {@code token} and {@code secret} properties must have been set on this object before calling this method. Often just the <code>header</code> value is of interest to calling code, but the other properties returned can be useful when debugging or otherwise showing the steps involved in computing the header value. The returned object will contain the following properties: <dl> <dt>header</dt> <dd>The full <code>Authorization</code> HTTP header value string, which can be added to an actual XHR request using the same connection properties passed to this method.</dd> <dt>date</dt> <dd>The same <code>date</code> object passed to this method.</dd> <dt>dateHeader</dt> <dd>A date string, which can be added to an actual XHR request as the <code>X-SN-Date</code> HTTP header.</dd> <dt>verb</dt> <dd>The HTTP <code>method</code> passed to this method.</dd> <dt>canonicalUri</dt> <dd>The canonical URI used in the canonical request message.</dd> <dt>canonicalQueryParameters</dt> <dd>The canonical query parameters, which come either from the actual <code>urL</code> query parameters or <code>data</code> if the <code>contentType</code> is a form post.</dd> <dt>canonicalHeaders</dt> <dd>An object with a <code>headerNames</code> property containing the canonical header names as an array of strings in lower case, and a <code>headers</code> property containing an object with keys from the <code>headerNames</code> array and their associated header values.</dd> <dt>bodyContentDigest</dt> <dd>A CryptoJS.SHA256 digest of <code>data</code if <code>contentType</code> if form data, otherwise a digest of an empty string value.</dd> <dt>canonicalRequestMessage</dt> <dd>The full canonical request message as a string.</dd> <dt>signingMessage</dt> <dd>The computed message to sign, as a string.</dd> <dt>signingKey</dt> <dd>A CryptoJS.HmacSHA256 digest of the key used to sign the signing message.</dd> </dl> @param {String} url the web service URL to invoke @param {String} method the HTTP method to use; e.g. GET or POST @param {String} data the data to upload, or <code>undefined</code> if none @param {String} contentType the content type of <code>data</code>, or <code>undefined</code> if none @param {Date} date the date to use for the authorization request @return {Object} the computed authorization details @preserve
[ "Compute", "SNWS2", "authorization", "info", "." ]
26848b1c303b98b7c0ddeefb8c68c5f5bf78927e
https://github.com/SolarNetwork/solarnetwork-d3/blob/26848b1c303b98b7c0ddeefb8c68c5f5bf78927e/src/net/sec.js#L358-L395
53,958
SolarNetwork/solarnetwork-d3
src/net/sec.js
json
function json(url, method, data, contentType, callback) { var requestUrl = url; // We might be passed to queue, and then our callback will be the last argument (but possibly not #5 // if the original call to queue didn't pass all arguments) so we check for that at the start and // adjust what we consider the method, data, and contentType parameter values. if ( arguments.length > 0 ) { if ( arguments.length < 5 && typeof arguments[arguments.length - 1] === 'function' ) { callback = arguments[arguments.length - 1]; } if ( typeof method !== 'string' ) { method = undefined; } if ( typeof data !== 'string' ) { data = undefined; } if ( typeof contentType !== 'string' ) { contentType = undefined; } } method = (method === undefined ? 'GET' : method.toUpperCase()); if ( method === 'POST' || method === 'PUT' ) { // extract any URL request parameters and put into POST body if ( !data ) { (function() { var queryIndex = url.indexOf('?'); if ( queryIndex !== -1 ) { if ( queryIndex + 1 < url.length - 1 ) { data = url.substring(queryIndex + 1); } requestUrl = url.substring(0, queryIndex); contentType = 'application/x-www-form-urlencoded; charset=UTF-8'; } }()); } } var xhr = d3.json(requestUrl); if ( contentType !== undefined ) { xhr.header('Content-Type', contentType); } xhr.on('beforesend', function(request) { var authorization = computeAuthorization(url, method, data, contentType, new Date()); // set the headers on our request request.setRequestHeader('Authorization', authorization.header); if ( authorization.bodyContentDigest && shouldIncludeContentDigest(contentType) ) { request.setRequestHeader('Digest', authorization.canonicalHeaders.headers['digest']); } request.setRequestHeader('X-SN-Date', authorization.canonicalHeaders.headers['x-sn-date']); }); // register a load handler always, just so one is present xhr.on('load.internal', function() { //sn.log('URL {0} response received.', url); }); if ( callback !== undefined ) { xhr.send(method, data, callback); } return xhr; }
javascript
function json(url, method, data, contentType, callback) { var requestUrl = url; // We might be passed to queue, and then our callback will be the last argument (but possibly not #5 // if the original call to queue didn't pass all arguments) so we check for that at the start and // adjust what we consider the method, data, and contentType parameter values. if ( arguments.length > 0 ) { if ( arguments.length < 5 && typeof arguments[arguments.length - 1] === 'function' ) { callback = arguments[arguments.length - 1]; } if ( typeof method !== 'string' ) { method = undefined; } if ( typeof data !== 'string' ) { data = undefined; } if ( typeof contentType !== 'string' ) { contentType = undefined; } } method = (method === undefined ? 'GET' : method.toUpperCase()); if ( method === 'POST' || method === 'PUT' ) { // extract any URL request parameters and put into POST body if ( !data ) { (function() { var queryIndex = url.indexOf('?'); if ( queryIndex !== -1 ) { if ( queryIndex + 1 < url.length - 1 ) { data = url.substring(queryIndex + 1); } requestUrl = url.substring(0, queryIndex); contentType = 'application/x-www-form-urlencoded; charset=UTF-8'; } }()); } } var xhr = d3.json(requestUrl); if ( contentType !== undefined ) { xhr.header('Content-Type', contentType); } xhr.on('beforesend', function(request) { var authorization = computeAuthorization(url, method, data, contentType, new Date()); // set the headers on our request request.setRequestHeader('Authorization', authorization.header); if ( authorization.bodyContentDigest && shouldIncludeContentDigest(contentType) ) { request.setRequestHeader('Digest', authorization.canonicalHeaders.headers['digest']); } request.setRequestHeader('X-SN-Date', authorization.canonicalHeaders.headers['x-sn-date']); }); // register a load handler always, just so one is present xhr.on('load.internal', function() { //sn.log('URL {0} response received.', url); }); if ( callback !== undefined ) { xhr.send(method, data, callback); } return xhr; }
[ "function", "json", "(", "url", ",", "method", ",", "data", ",", "contentType", ",", "callback", ")", "{", "var", "requestUrl", "=", "url", ";", "// We might be passed to queue, and then our callback will be the last argument (but possibly not #5", "// if the original call to queue didn't pass all arguments) so we check for that at the start and", "// adjust what we consider the method, data, and contentType parameter values.", "if", "(", "arguments", ".", "length", ">", "0", ")", "{", "if", "(", "arguments", ".", "length", "<", "5", "&&", "typeof", "arguments", "[", "arguments", ".", "length", "-", "1", "]", "===", "'function'", ")", "{", "callback", "=", "arguments", "[", "arguments", ".", "length", "-", "1", "]", ";", "}", "if", "(", "typeof", "method", "!==", "'string'", ")", "{", "method", "=", "undefined", ";", "}", "if", "(", "typeof", "data", "!==", "'string'", ")", "{", "data", "=", "undefined", ";", "}", "if", "(", "typeof", "contentType", "!==", "'string'", ")", "{", "contentType", "=", "undefined", ";", "}", "}", "method", "=", "(", "method", "===", "undefined", "?", "'GET'", ":", "method", ".", "toUpperCase", "(", ")", ")", ";", "if", "(", "method", "===", "'POST'", "||", "method", "===", "'PUT'", ")", "{", "// extract any URL request parameters and put into POST body", "if", "(", "!", "data", ")", "{", "(", "function", "(", ")", "{", "var", "queryIndex", "=", "url", ".", "indexOf", "(", "'?'", ")", ";", "if", "(", "queryIndex", "!==", "-", "1", ")", "{", "if", "(", "queryIndex", "+", "1", "<", "url", ".", "length", "-", "1", ")", "{", "data", "=", "url", ".", "substring", "(", "queryIndex", "+", "1", ")", ";", "}", "requestUrl", "=", "url", ".", "substring", "(", "0", ",", "queryIndex", ")", ";", "contentType", "=", "'application/x-www-form-urlencoded; charset=UTF-8'", ";", "}", "}", "(", ")", ")", ";", "}", "}", "var", "xhr", "=", "d3", ".", "json", "(", "requestUrl", ")", ";", "if", "(", "contentType", "!==", "undefined", ")", "{", "xhr", ".", "header", "(", "'Content-Type'", ",", "contentType", ")", ";", "}", "xhr", ".", "on", "(", "'beforesend'", ",", "function", "(", "request", ")", "{", "var", "authorization", "=", "computeAuthorization", "(", "url", ",", "method", ",", "data", ",", "contentType", ",", "new", "Date", "(", ")", ")", ";", "// set the headers on our request", "request", ".", "setRequestHeader", "(", "'Authorization'", ",", "authorization", ".", "header", ")", ";", "if", "(", "authorization", ".", "bodyContentDigest", "&&", "shouldIncludeContentDigest", "(", "contentType", ")", ")", "{", "request", ".", "setRequestHeader", "(", "'Digest'", ",", "authorization", ".", "canonicalHeaders", ".", "headers", "[", "'digest'", "]", ")", ";", "}", "request", ".", "setRequestHeader", "(", "'X-SN-Date'", ",", "authorization", ".", "canonicalHeaders", ".", "headers", "[", "'x-sn-date'", "]", ")", ";", "}", ")", ";", "// register a load handler always, just so one is present", "xhr", ".", "on", "(", "'load.internal'", ",", "function", "(", ")", "{", "//sn.log('URL {0} response received.', url);", "}", ")", ";", "if", "(", "callback", "!==", "undefined", ")", "{", "xhr", ".", "send", "(", "method", ",", "data", ",", "callback", ")", ";", "}", "return", "xhr", ";", "}" ]
Invoke the web service URL, adding the required SNWS2 authorization headers to the request. <p>This method will construct the <code>X-SN-Date</code> and <code>Authorization</code> header values needed to invoke the web service. It returns a d3 XHR object, so you can call <code>.on()</code> on that to handle the response, unless a callback parameter is specified, then the request is issued immediately, passing the <code>method</code>, <code>data</code>, and <code>callback</code> parameters to <code>xhr.send()</code>.</p> @param {String} url the web service URL to invoke @param {String} method the HTTP method to use; e.g. GET or POST @param {String} [data] the data to upload @param {String} [contentType] the content type of the data @param {Function} [callback] if defined, a d3 callback function to handle the response JSON with @return {Object} d3 XHR object @preserve
[ "Invoke", "the", "web", "service", "URL", "adding", "the", "required", "SNWS2", "authorization", "headers", "to", "the", "request", "." ]
26848b1c303b98b7c0ddeefb8c68c5f5bf78927e
https://github.com/SolarNetwork/solarnetwork-d3/blob/26848b1c303b98b7c0ddeefb8c68c5f5bf78927e/src/net/sec.js#L415-L474
53,959
racker/node-rackspace-shared-middleware
lib/middleware/validator.js
check
function check(log, validity, req, res, type, full, finalValidator, callback) { var validator, v; log.info.call(log, 'deserializing and validating request body', { serializerType: type, full: full, finalValidator: finalValidator ? true : false }); if (!req.body) { callback(new Error('Empty Request Body')); return; } if (!validity.hasOwnProperty(type)) { throw new Error('Unrecognized type: ' + type); } v = new Valve(validity[type]); if (req.ctx) { req.ctx.setValve(v); } if (finalValidator) { v.addFinalValidator(finalValidator); } v.baton = {req: req}; validator = full ? v.check : v.checkPartial; validator.call(v, req.body, function(err, cleaned) { if (err) { log.debug.call(log, 'validation_check (error)', {request: req, body: req.body}); callback(err); return; } log.debug.call(log, 'validation_check (success)', {request: req, cleaned: cleaned}); callback(null, cleaned); }); }
javascript
function check(log, validity, req, res, type, full, finalValidator, callback) { var validator, v; log.info.call(log, 'deserializing and validating request body', { serializerType: type, full: full, finalValidator: finalValidator ? true : false }); if (!req.body) { callback(new Error('Empty Request Body')); return; } if (!validity.hasOwnProperty(type)) { throw new Error('Unrecognized type: ' + type); } v = new Valve(validity[type]); if (req.ctx) { req.ctx.setValve(v); } if (finalValidator) { v.addFinalValidator(finalValidator); } v.baton = {req: req}; validator = full ? v.check : v.checkPartial; validator.call(v, req.body, function(err, cleaned) { if (err) { log.debug.call(log, 'validation_check (error)', {request: req, body: req.body}); callback(err); return; } log.debug.call(log, 'validation_check (success)', {request: req, cleaned: cleaned}); callback(null, cleaned); }); }
[ "function", "check", "(", "log", ",", "validity", ",", "req", ",", "res", ",", "type", ",", "full", ",", "finalValidator", ",", "callback", ")", "{", "var", "validator", ",", "v", ";", "log", ".", "info", ".", "call", "(", "log", ",", "'deserializing and validating request body'", ",", "{", "serializerType", ":", "type", ",", "full", ":", "full", ",", "finalValidator", ":", "finalValidator", "?", "true", ":", "false", "}", ")", ";", "if", "(", "!", "req", ".", "body", ")", "{", "callback", "(", "new", "Error", "(", "'Empty Request Body'", ")", ")", ";", "return", ";", "}", "if", "(", "!", "validity", ".", "hasOwnProperty", "(", "type", ")", ")", "{", "throw", "new", "Error", "(", "'Unrecognized type: '", "+", "type", ")", ";", "}", "v", "=", "new", "Valve", "(", "validity", "[", "type", "]", ")", ";", "if", "(", "req", ".", "ctx", ")", "{", "req", ".", "ctx", ".", "setValve", "(", "v", ")", ";", "}", "if", "(", "finalValidator", ")", "{", "v", ".", "addFinalValidator", "(", "finalValidator", ")", ";", "}", "v", ".", "baton", "=", "{", "req", ":", "req", "}", ";", "validator", "=", "full", "?", "v", ".", "check", ":", "v", ".", "checkPartial", ";", "validator", ".", "call", "(", "v", ",", "req", ".", "body", ",", "function", "(", "err", ",", "cleaned", ")", "{", "if", "(", "err", ")", "{", "log", ".", "debug", ".", "call", "(", "log", ",", "'validation_check (error)'", ",", "{", "request", ":", "req", ",", "body", ":", "req", ".", "body", "}", ")", ";", "callback", "(", "err", ")", ";", "return", ";", "}", "log", ".", "debug", ".", "call", "(", "log", ",", "'validation_check (success)'", ",", "{", "request", ":", "req", ",", "cleaned", ":", "cleaned", "}", ")", ";", "callback", "(", "null", ",", "cleaned", ")", ";", "}", ")", ";", "}" ]
Verifies the object given. I thought about having it detect things but that just seemed to be too leaky. Serializes the object pointed to by data, into XML or JSON, depending on the request headers. Using the object_name we look up a consistent mapping of the Object -> XML/JSON layout. @param {Object} log Log method. @param {Valve} validity Valve validity object. @param {http.ServerRequest} req http request. @param {http.ServerResponse} res http response. @param {String} type The type of the object. @param {boolean} full If true, perform full validation; otherwise, perform partial validation. @param {?Function} finalValidator Optional finalValidator which can perform validator on the whole cleaned object. @param {Function(err, cleaned)} callback A function to be called when the verification is complete. Sets err to a non-null error message string if an error has occurred. Sets cleaned to the cleaned version of the body, if applicable.
[ "Verifies", "the", "object", "given", ".", "I", "thought", "about", "having", "it", "detect", "things", "but", "that", "just", "seemed", "to", "be", "too", "leaky", "." ]
613657b98b646e750882b5ce9b56ee7a1c6ac122
https://github.com/racker/node-rackspace-shared-middleware/blob/613657b98b646e750882b5ce9b56ee7a1c6ac122/lib/middleware/validator.js#L26-L67
53,960
azendal/argon
argon/storage/json_rest.js
_sendRequest
function _sendRequest(requestObj, callback) { var Storage, ajaxConfig; Storage = this; ajaxConfig = { url : requestObj.config.url, type : requestObj.config.type || this.REQUEST_TYPE_GET, contentType : requestObj.config.contentType || 'application/json', global : false, async : true, cache : false, complete : function(xhr, message){ Storage._processResponse(xhr, message, callback); } }; if (ajaxConfig.type != Argon.Storage.JsonRest.REQUEST_TYPE_GET) { ajaxConfig.data = JSON.stringify(requestObj.data); } if (ajaxConfig.type == this.REQUEST_TYPE_PUT || ajaxConfig.type == this.REQUEST_TYPE_DELETE) { ajaxConfig.beforeSend = function(xhr) { xhr.setRequestHeader("X-Http-Method-Override", ajaxConfig.type); }; ajaxConfig.type = this.REQUEST_TYPE_POST; } $.ajax(ajaxConfig); return this; }
javascript
function _sendRequest(requestObj, callback) { var Storage, ajaxConfig; Storage = this; ajaxConfig = { url : requestObj.config.url, type : requestObj.config.type || this.REQUEST_TYPE_GET, contentType : requestObj.config.contentType || 'application/json', global : false, async : true, cache : false, complete : function(xhr, message){ Storage._processResponse(xhr, message, callback); } }; if (ajaxConfig.type != Argon.Storage.JsonRest.REQUEST_TYPE_GET) { ajaxConfig.data = JSON.stringify(requestObj.data); } if (ajaxConfig.type == this.REQUEST_TYPE_PUT || ajaxConfig.type == this.REQUEST_TYPE_DELETE) { ajaxConfig.beforeSend = function(xhr) { xhr.setRequestHeader("X-Http-Method-Override", ajaxConfig.type); }; ajaxConfig.type = this.REQUEST_TYPE_POST; } $.ajax(ajaxConfig); return this; }
[ "function", "_sendRequest", "(", "requestObj", ",", "callback", ")", "{", "var", "Storage", ",", "ajaxConfig", ";", "Storage", "=", "this", ";", "ajaxConfig", "=", "{", "url", ":", "requestObj", ".", "config", ".", "url", ",", "type", ":", "requestObj", ".", "config", ".", "type", "||", "this", ".", "REQUEST_TYPE_GET", ",", "contentType", ":", "requestObj", ".", "config", ".", "contentType", "||", "'application/json'", ",", "global", ":", "false", ",", "async", ":", "true", ",", "cache", ":", "false", ",", "complete", ":", "function", "(", "xhr", ",", "message", ")", "{", "Storage", ".", "_processResponse", "(", "xhr", ",", "message", ",", "callback", ")", ";", "}", "}", ";", "if", "(", "ajaxConfig", ".", "type", "!=", "Argon", ".", "Storage", ".", "JsonRest", ".", "REQUEST_TYPE_GET", ")", "{", "ajaxConfig", ".", "data", "=", "JSON", ".", "stringify", "(", "requestObj", ".", "data", ")", ";", "}", "if", "(", "ajaxConfig", ".", "type", "==", "this", ".", "REQUEST_TYPE_PUT", "||", "ajaxConfig", ".", "type", "==", "this", ".", "REQUEST_TYPE_DELETE", ")", "{", "ajaxConfig", ".", "beforeSend", "=", "function", "(", "xhr", ")", "{", "xhr", ".", "setRequestHeader", "(", "\"X-Http-Method-Override\"", ",", "ajaxConfig", ".", "type", ")", ";", "}", ";", "ajaxConfig", ".", "type", "=", "this", ".", "REQUEST_TYPE_POST", ";", "}", "$", ".", "ajax", "(", "ajaxConfig", ")", ";", "return", "this", ";", "}" ]
Internal implementation of the communication sequence with the service All requests at some point rely on this method to format the data and send the request to the service @method _sendRequest <public, static> [Function] @argument requestObj @argument callback the function to execute when the process finishes @return Argon.Storage.JsonRest
[ "Internal", "implementation", "of", "the", "communication", "sequence", "with", "the", "service", "All", "requests", "at", "some", "point", "rely", "on", "this", "method", "to", "format", "the", "data", "and", "send", "the", "request", "to", "the", "service" ]
0cfd3a3b3731b69abca55c956c757476779ec1bd
https://github.com/azendal/argon/blob/0cfd3a3b3731b69abca55c956c757476779ec1bd/argon/storage/json_rest.js#L139-L170
53,961
azendal/argon
argon/storage/json_rest.js
function (xhr, message, callback) { var response; switch (xhr.status) { case this.RESPONSE_OK: response = JSON.parse(xhr.responseText); break; case this.RESPONSE_UNPROCESSABLE_ENTITY: response = JSON.parse(xhr.responseText); break; case this.RESPONSE_NOT_FOUND: response = { error : xhr.status }; break; case this.RESPONSE_INTERNAL_SERVER_ERROR: response = {}; break; case this.RESPONSE_SERVER_UNAVALIABLE: console.log('Server is unavailable, probably shutdown.'); response = {}; break; default: console.log('Unsuported code returned from the server: ', xhr.status); response = { error : xhr.status }; } callback(response); return this; }
javascript
function (xhr, message, callback) { var response; switch (xhr.status) { case this.RESPONSE_OK: response = JSON.parse(xhr.responseText); break; case this.RESPONSE_UNPROCESSABLE_ENTITY: response = JSON.parse(xhr.responseText); break; case this.RESPONSE_NOT_FOUND: response = { error : xhr.status }; break; case this.RESPONSE_INTERNAL_SERVER_ERROR: response = {}; break; case this.RESPONSE_SERVER_UNAVALIABLE: console.log('Server is unavailable, probably shutdown.'); response = {}; break; default: console.log('Unsuported code returned from the server: ', xhr.status); response = { error : xhr.status }; } callback(response); return this; }
[ "function", "(", "xhr", ",", "message", ",", "callback", ")", "{", "var", "response", ";", "switch", "(", "xhr", ".", "status", ")", "{", "case", "this", ".", "RESPONSE_OK", ":", "response", "=", "JSON", ".", "parse", "(", "xhr", ".", "responseText", ")", ";", "break", ";", "case", "this", ".", "RESPONSE_UNPROCESSABLE_ENTITY", ":", "response", "=", "JSON", ".", "parse", "(", "xhr", ".", "responseText", ")", ";", "break", ";", "case", "this", ".", "RESPONSE_NOT_FOUND", ":", "response", "=", "{", "error", ":", "xhr", ".", "status", "}", ";", "break", ";", "case", "this", ".", "RESPONSE_INTERNAL_SERVER_ERROR", ":", "response", "=", "{", "}", ";", "break", ";", "case", "this", ".", "RESPONSE_SERVER_UNAVALIABLE", ":", "console", ".", "log", "(", "'Server is unavailable, probably shutdown.'", ")", ";", "response", "=", "{", "}", ";", "break", ";", "default", ":", "console", ".", "log", "(", "'Unsuported code returned from the server: '", ",", "xhr", ".", "status", ")", ";", "response", "=", "{", "error", ":", "xhr", ".", "status", "}", ";", "}", "callback", "(", "response", ")", ";", "return", "this", ";", "}" ]
Internal data processing for request responses In order to transform the responses from the server to native models this process does certain operations to transform the data from the server notation to JavaScript notation @method _processResponse <public, static> [Function] @argument xhr @argument message @argument callback
[ "Internal", "data", "processing", "for", "request", "responses", "In", "order", "to", "transform", "the", "responses", "from", "the", "server", "to", "native", "models", "this", "process", "does", "certain", "operations", "to", "transform", "the", "data", "from", "the", "server", "notation", "to", "JavaScript", "notation" ]
0cfd3a3b3731b69abca55c956c757476779ec1bd
https://github.com/azendal/argon/blob/0cfd3a3b3731b69abca55c956c757476779ec1bd/argon/storage/json_rest.js#L181-L213
53,962
azendal/argon
argon/storage/json_rest.js
create
function create(requestObj, callback) { var i, requestConfig, storage; storage = this; callback = callback || function(){}; if ((typeof requestObj) === 'undefined' || requestObj === null) { callback(null); return this; } requestObj.config = {}; requestObj.config.url = requestObj.config.url || this.url.post; requestObj.config.type = requestObj.config.type || this.constructor.REQUEST_TYPE_POST; for (i = 0; i < storage.preprocessors.length; i++) { requestObj.data = storage.preprocessors[i](requestObj.data, requestObj); } this.constructor._sendRequest(requestObj, function(data){ for (i = 0; i < storage.processors.length; i++) { data = storage.processors[i](data, requestObj); } callback(data); }); return this; }
javascript
function create(requestObj, callback) { var i, requestConfig, storage; storage = this; callback = callback || function(){}; if ((typeof requestObj) === 'undefined' || requestObj === null) { callback(null); return this; } requestObj.config = {}; requestObj.config.url = requestObj.config.url || this.url.post; requestObj.config.type = requestObj.config.type || this.constructor.REQUEST_TYPE_POST; for (i = 0; i < storage.preprocessors.length; i++) { requestObj.data = storage.preprocessors[i](requestObj.data, requestObj); } this.constructor._sendRequest(requestObj, function(data){ for (i = 0; i < storage.processors.length; i++) { data = storage.processors[i](data, requestObj); } callback(data); }); return this; }
[ "function", "create", "(", "requestObj", ",", "callback", ")", "{", "var", "i", ",", "requestConfig", ",", "storage", ";", "storage", "=", "this", ";", "callback", "=", "callback", "||", "function", "(", ")", "{", "}", ";", "if", "(", "(", "typeof", "requestObj", ")", "===", "'undefined'", "||", "requestObj", "===", "null", ")", "{", "callback", "(", "null", ")", ";", "return", "this", ";", "}", "requestObj", ".", "config", "=", "{", "}", ";", "requestObj", ".", "config", ".", "url", "=", "requestObj", ".", "config", ".", "url", "||", "this", ".", "url", ".", "post", ";", "requestObj", ".", "config", ".", "type", "=", "requestObj", ".", "config", ".", "type", "||", "this", ".", "constructor", ".", "REQUEST_TYPE_POST", ";", "for", "(", "i", "=", "0", ";", "i", "<", "storage", ".", "preprocessors", ".", "length", ";", "i", "++", ")", "{", "requestObj", ".", "data", "=", "storage", ".", "preprocessors", "[", "i", "]", "(", "requestObj", ".", "data", ",", "requestObj", ")", ";", "}", "this", ".", "constructor", ".", "_sendRequest", "(", "requestObj", ",", "function", "(", "data", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "storage", ".", "processors", ".", "length", ";", "i", "++", ")", "{", "data", "=", "storage", ".", "processors", "[", "i", "]", "(", "data", ",", "requestObj", ")", ";", "}", "callback", "(", "data", ")", ";", "}", ")", ";", "return", "this", ";", "}" ]
Pushes the instance to the storage service @method post <public> @argument requestObj <optional> [Object] the data to post, generally this comes from a model @argument callback <optional> [Function]
[ "Pushes", "the", "instance", "to", "the", "storage", "service" ]
0cfd3a3b3731b69abca55c956c757476779ec1bd
https://github.com/azendal/argon/blob/0cfd3a3b3731b69abca55c956c757476779ec1bd/argon/storage/json_rest.js#L276-L305
53,963
azendal/argon
argon/storage/json_rest.js
update
function update(requestObj, callback) { var i, found, storedData, storage; storage = this; callback = callback || function(){}; if ((typeof requestObj) === 'undefined' || requestObj === null) { callback(null); return this; } requestObj.config = {}; requestObj.config.url = requestObj.config.url || this.url.put; requestObj.config.type = requestObj.config.type || this.constructor.REQUEST_TYPE_POST; if (requestObj.data) { for (i = 0; i < storage.preprocessors.length; i++) { requestObj.data = storage.preprocessors[i](requestObj.data, requestObj); } } this.constructor._sendRequest(requestObj, function(data){ for (i = 0; i < storage.processors.length; i++) { data = storage.processors[i](data, requestObj); } callback(data); }); return this; }
javascript
function update(requestObj, callback) { var i, found, storedData, storage; storage = this; callback = callback || function(){}; if ((typeof requestObj) === 'undefined' || requestObj === null) { callback(null); return this; } requestObj.config = {}; requestObj.config.url = requestObj.config.url || this.url.put; requestObj.config.type = requestObj.config.type || this.constructor.REQUEST_TYPE_POST; if (requestObj.data) { for (i = 0; i < storage.preprocessors.length; i++) { requestObj.data = storage.preprocessors[i](requestObj.data, requestObj); } } this.constructor._sendRequest(requestObj, function(data){ for (i = 0; i < storage.processors.length; i++) { data = storage.processors[i](data, requestObj); } callback(data); }); return this; }
[ "function", "update", "(", "requestObj", ",", "callback", ")", "{", "var", "i", ",", "found", ",", "storedData", ",", "storage", ";", "storage", "=", "this", ";", "callback", "=", "callback", "||", "function", "(", ")", "{", "}", ";", "if", "(", "(", "typeof", "requestObj", ")", "===", "'undefined'", "||", "requestObj", "===", "null", ")", "{", "callback", "(", "null", ")", ";", "return", "this", ";", "}", "requestObj", ".", "config", "=", "{", "}", ";", "requestObj", ".", "config", ".", "url", "=", "requestObj", ".", "config", ".", "url", "||", "this", ".", "url", ".", "put", ";", "requestObj", ".", "config", ".", "type", "=", "requestObj", ".", "config", ".", "type", "||", "this", ".", "constructor", ".", "REQUEST_TYPE_POST", ";", "if", "(", "requestObj", ".", "data", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "storage", ".", "preprocessors", ".", "length", ";", "i", "++", ")", "{", "requestObj", ".", "data", "=", "storage", ".", "preprocessors", "[", "i", "]", "(", "requestObj", ".", "data", ",", "requestObj", ")", ";", "}", "}", "this", ".", "constructor", ".", "_sendRequest", "(", "requestObj", ",", "function", "(", "data", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "storage", ".", "processors", ".", "length", ";", "i", "++", ")", "{", "data", "=", "storage", ".", "processors", "[", "i", "]", "(", "data", ",", "requestObj", ")", ";", "}", "callback", "(", "data", ")", ";", "}", ")", ";", "return", "this", ";", "}" ]
Updates from the resource @method put <public> @argument params <optional> [Object] @argument callback <optional> [Function]
[ "Updates", "from", "the", "resource" ]
0cfd3a3b3731b69abca55c956c757476779ec1bd
https://github.com/azendal/argon/blob/0cfd3a3b3731b69abca55c956c757476779ec1bd/argon/storage/json_rest.js#L385-L416
53,964
azendal/argon
argon/storage/json_rest.js
remove
function remove(requestObj, callback) { var i, storage; storage = this; callback = callback || function(){}; if ((typeof requestObj) === 'undefined' || requestObj === null) { callback(null); return this; } requestObj.config = {}; requestObj.config.url = requestObj.config.url || this.url.remove; requestObj.config.type = requestObj.config.type || this.constructor.REQUEST_TYPE_GET; if (requestObj.data) { for (i = 0; i < storage.preprocessors.length; i++) { requestObj.data = storage.preprocessors[i](requestObj.data, requestObj); } } this.constructor._sendRequest(requestObj, function(data){ callback(null); }); return this; }
javascript
function remove(requestObj, callback) { var i, storage; storage = this; callback = callback || function(){}; if ((typeof requestObj) === 'undefined' || requestObj === null) { callback(null); return this; } requestObj.config = {}; requestObj.config.url = requestObj.config.url || this.url.remove; requestObj.config.type = requestObj.config.type || this.constructor.REQUEST_TYPE_GET; if (requestObj.data) { for (i = 0; i < storage.preprocessors.length; i++) { requestObj.data = storage.preprocessors[i](requestObj.data, requestObj); } } this.constructor._sendRequest(requestObj, function(data){ callback(null); }); return this; }
[ "function", "remove", "(", "requestObj", ",", "callback", ")", "{", "var", "i", ",", "storage", ";", "storage", "=", "this", ";", "callback", "=", "callback", "||", "function", "(", ")", "{", "}", ";", "if", "(", "(", "typeof", "requestObj", ")", "===", "'undefined'", "||", "requestObj", "===", "null", ")", "{", "callback", "(", "null", ")", ";", "return", "this", ";", "}", "requestObj", ".", "config", "=", "{", "}", ";", "requestObj", ".", "config", ".", "url", "=", "requestObj", ".", "config", ".", "url", "||", "this", ".", "url", ".", "remove", ";", "requestObj", ".", "config", ".", "type", "=", "requestObj", ".", "config", ".", "type", "||", "this", ".", "constructor", ".", "REQUEST_TYPE_GET", ";", "if", "(", "requestObj", ".", "data", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "storage", ".", "preprocessors", ".", "length", ";", "i", "++", ")", "{", "requestObj", ".", "data", "=", "storage", ".", "preprocessors", "[", "i", "]", "(", "requestObj", ".", "data", ",", "requestObj", ")", ";", "}", "}", "this", ".", "constructor", ".", "_sendRequest", "(", "requestObj", ",", "function", "(", "data", ")", "{", "callback", "(", "null", ")", ";", "}", ")", ";", "return", "this", ";", "}" ]
Removes this from the resource Delete cannot be used because its a reserved word on JavaScript and for now is safer to use a synonim later this could be aliased by the correct method @method remove <public> @argument params <optional> [Object] @argument callback <optional> [Function]
[ "Removes", "this", "from", "the", "resource" ]
0cfd3a3b3731b69abca55c956c757476779ec1bd
https://github.com/azendal/argon/blob/0cfd3a3b3731b69abca55c956c757476779ec1bd/argon/storage/json_rest.js#L428-L456
53,965
KenanY/alea-random
index.js
aleaRandom
function aleaRandom(min, max, floating) { var gen = new Alea(uuid.v4()); if (floating && typeof floating !== 'boolean' && isIterateeCall(min, max, floating)) { max = floating = undefined; } if (floating === undefined) { if (typeof max === 'boolean') { floating = max; max = undefined; } else if (typeof min === 'boolean') { floating = min; min = undefined; } } if (min === undefined && max === undefined) { min = 0; max = 1; } else { min = toNumber(min) || 0; if (max === undefined) { max = min; min = 0; } else { max = toNumber(max) || 0; } } if (min > max) { var temp = min; min = max; max = temp; } if (floating || min % 1 || max % 1) { var rand = gen(); return Math.min(min + (rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1)))), max); } return min + Math.floor(gen() * (max - min + 1)); }
javascript
function aleaRandom(min, max, floating) { var gen = new Alea(uuid.v4()); if (floating && typeof floating !== 'boolean' && isIterateeCall(min, max, floating)) { max = floating = undefined; } if (floating === undefined) { if (typeof max === 'boolean') { floating = max; max = undefined; } else if (typeof min === 'boolean') { floating = min; min = undefined; } } if (min === undefined && max === undefined) { min = 0; max = 1; } else { min = toNumber(min) || 0; if (max === undefined) { max = min; min = 0; } else { max = toNumber(max) || 0; } } if (min > max) { var temp = min; min = max; max = temp; } if (floating || min % 1 || max % 1) { var rand = gen(); return Math.min(min + (rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1)))), max); } return min + Math.floor(gen() * (max - min + 1)); }
[ "function", "aleaRandom", "(", "min", ",", "max", ",", "floating", ")", "{", "var", "gen", "=", "new", "Alea", "(", "uuid", ".", "v4", "(", ")", ")", ";", "if", "(", "floating", "&&", "typeof", "floating", "!==", "'boolean'", "&&", "isIterateeCall", "(", "min", ",", "max", ",", "floating", ")", ")", "{", "max", "=", "floating", "=", "undefined", ";", "}", "if", "(", "floating", "===", "undefined", ")", "{", "if", "(", "typeof", "max", "===", "'boolean'", ")", "{", "floating", "=", "max", ";", "max", "=", "undefined", ";", "}", "else", "if", "(", "typeof", "min", "===", "'boolean'", ")", "{", "floating", "=", "min", ";", "min", "=", "undefined", ";", "}", "}", "if", "(", "min", "===", "undefined", "&&", "max", "===", "undefined", ")", "{", "min", "=", "0", ";", "max", "=", "1", ";", "}", "else", "{", "min", "=", "toNumber", "(", "min", ")", "||", "0", ";", "if", "(", "max", "===", "undefined", ")", "{", "max", "=", "min", ";", "min", "=", "0", ";", "}", "else", "{", "max", "=", "toNumber", "(", "max", ")", "||", "0", ";", "}", "}", "if", "(", "min", ">", "max", ")", "{", "var", "temp", "=", "min", ";", "min", "=", "max", ";", "max", "=", "temp", ";", "}", "if", "(", "floating", "||", "min", "%", "1", "||", "max", "%", "1", ")", "{", "var", "rand", "=", "gen", "(", ")", ";", "return", "Math", ".", "min", "(", "min", "+", "(", "rand", "*", "(", "max", "-", "min", "+", "parseFloat", "(", "'1e-'", "+", "(", "(", "rand", "+", "''", ")", ".", "length", "-", "1", ")", ")", ")", ")", ",", "max", ")", ";", "}", "return", "min", "+", "Math", ".", "floor", "(", "gen", "(", ")", "*", "(", "max", "-", "min", "+", "1", ")", ")", ";", "}" ]
Produces a random number between the inclusive `min` and `max` bounds. If only one argument is provided a number between `0` and the given number is returned. If `floating` is `true`, or either `min` or `max` are floats, a floating-point number is returned instead of an integer. **Note:** JavaScript follows the IEEE-754 standard for resolving floating-point values which can produce unexpected results. @static @param {number} [min=0] The lower bound. @param {number} [max=1] The upper bound. @param {boolean} [floating] Specify returning a floating-point number. @returns {number} Returns the random number. @example aleaRandom(0, 5); // => an integer between 0 and 5 aleaRandom(5); // => also an integer between 0 and 5 aleaRandom(5, true); // => a floating-point number between 0 and 5 aleaRandom(1.2, 5.2); // => a floating-point number between 1.2 and 5.2
[ "Produces", "a", "random", "number", "between", "the", "inclusive", "min", "and", "max", "bounds", ".", "If", "only", "one", "argument", "is", "provided", "a", "number", "between", "0", "and", "the", "given", "number", "is", "returned", ".", "If", "floating", "is", "true", "or", "either", "min", "or", "max", "are", "floats", "a", "floating", "-", "point", "number", "is", "returned", "instead", "of", "an", "integer", "." ]
f6752504570a6314ea201c5abb0c8b13157403db
https://github.com/KenanY/alea-random/blob/f6752504570a6314ea201c5abb0c8b13157403db/index.js#L34-L79
53,966
wojtkowiak/private-decorator
src/privateMember.js
_functionBelongsToObject
function _functionBelongsToObject(self, caller, target, protectedMode = false) { if (!caller) return false; // We are caching the results for better performance. let cacheOfResultsForSelf = resultCache.get(self); if (cacheOfResultsForSelf && cacheOfResultsForSelf.has(caller)) { return cacheOfResultsForSelf.get(caller); } let proto = Object.getPrototypeOf(self); // proto !== target - means that extend was made. let check; if ((caller.name === 'get' || caller.name === 'set')) { check = !getterOrSetterBelongsToObject(caller, target); } else { check = !(target[caller.name] || target.constructor === caller); } if (target && proto !== target && check) { if (protectedMode) { if (!checkIfTargetIsRelated(proto, target)) { return false; } } else { return false; } } let result = false; while (proto !== Object && result === false && proto.constructor !== Object) { result = functionBelongsToObjectInternal(proto, caller); proto = Object.getPrototypeOf(proto); } if (!cacheOfResultsForSelf) { cacheOfResultsForSelf = new WeakMap(); } cacheOfResultsForSelf.set(caller, result); resultCache.set(self, cacheOfResultsForSelf); return result; }
javascript
function _functionBelongsToObject(self, caller, target, protectedMode = false) { if (!caller) return false; // We are caching the results for better performance. let cacheOfResultsForSelf = resultCache.get(self); if (cacheOfResultsForSelf && cacheOfResultsForSelf.has(caller)) { return cacheOfResultsForSelf.get(caller); } let proto = Object.getPrototypeOf(self); // proto !== target - means that extend was made. let check; if ((caller.name === 'get' || caller.name === 'set')) { check = !getterOrSetterBelongsToObject(caller, target); } else { check = !(target[caller.name] || target.constructor === caller); } if (target && proto !== target && check) { if (protectedMode) { if (!checkIfTargetIsRelated(proto, target)) { return false; } } else { return false; } } let result = false; while (proto !== Object && result === false && proto.constructor !== Object) { result = functionBelongsToObjectInternal(proto, caller); proto = Object.getPrototypeOf(proto); } if (!cacheOfResultsForSelf) { cacheOfResultsForSelf = new WeakMap(); } cacheOfResultsForSelf.set(caller, result); resultCache.set(self, cacheOfResultsForSelf); return result; }
[ "function", "_functionBelongsToObject", "(", "self", ",", "caller", ",", "target", ",", "protectedMode", "=", "false", ")", "{", "if", "(", "!", "caller", ")", "return", "false", ";", "// We are caching the results for better performance.", "let", "cacheOfResultsForSelf", "=", "resultCache", ".", "get", "(", "self", ")", ";", "if", "(", "cacheOfResultsForSelf", "&&", "cacheOfResultsForSelf", ".", "has", "(", "caller", ")", ")", "{", "return", "cacheOfResultsForSelf", ".", "get", "(", "caller", ")", ";", "}", "let", "proto", "=", "Object", ".", "getPrototypeOf", "(", "self", ")", ";", "// proto !== target - means that extend was made.", "let", "check", ";", "if", "(", "(", "caller", ".", "name", "===", "'get'", "||", "caller", ".", "name", "===", "'set'", ")", ")", "{", "check", "=", "!", "getterOrSetterBelongsToObject", "(", "caller", ",", "target", ")", ";", "}", "else", "{", "check", "=", "!", "(", "target", "[", "caller", ".", "name", "]", "||", "target", ".", "constructor", "===", "caller", ")", ";", "}", "if", "(", "target", "&&", "proto", "!==", "target", "&&", "check", ")", "{", "if", "(", "protectedMode", ")", "{", "if", "(", "!", "checkIfTargetIsRelated", "(", "proto", ",", "target", ")", ")", "{", "return", "false", ";", "}", "}", "else", "{", "return", "false", ";", "}", "}", "let", "result", "=", "false", ";", "while", "(", "proto", "!==", "Object", "&&", "result", "===", "false", "&&", "proto", ".", "constructor", "!==", "Object", ")", "{", "result", "=", "functionBelongsToObjectInternal", "(", "proto", ",", "caller", ")", ";", "proto", "=", "Object", ".", "getPrototypeOf", "(", "proto", ")", ";", "}", "if", "(", "!", "cacheOfResultsForSelf", ")", "{", "cacheOfResultsForSelf", "=", "new", "WeakMap", "(", ")", ";", "}", "cacheOfResultsForSelf", ".", "set", "(", "caller", ",", "result", ")", ";", "resultCache", ".", "set", "(", "self", ",", "cacheOfResultsForSelf", ")", ";", "return", "result", ";", "}" ]
Checks if `caller` belongs to `self`. @param {Object} self - The current `this`. @param {Object} caller - The caller function. @param {Object} target - The original define property target. @param {boolean} protectedMode - Whether this should be protected instead of private. @returns {bool} @private
[ "Checks", "if", "caller", "belongs", "to", "self", "." ]
5895bb37a8b9bf5bf6d21f120d7217f23c304f1b
https://github.com/wojtkowiak/private-decorator/blob/5895bb37a8b9bf5bf6d21f120d7217f23c304f1b/src/privateMember.js#L225-L268
53,967
spacemaus/postvox
vox-client/vox-client.js
prepareProfileDir
function prepareProfileDir(profilesDir, nick) { var nick = nick || '.tmp'; // Just in case `nick` has any funny business... nick = nick.replace(/[^\w\d.]/g, '-').replace('..', '-'); var profileDir = path.join(profilesDir, util.format('vox-%s', nick)); debug('Ensuring directory at %s', profileDir); mkdirp.sync(profileDir, 0700); return profileDir; }
javascript
function prepareProfileDir(profilesDir, nick) { var nick = nick || '.tmp'; // Just in case `nick` has any funny business... nick = nick.replace(/[^\w\d.]/g, '-').replace('..', '-'); var profileDir = path.join(profilesDir, util.format('vox-%s', nick)); debug('Ensuring directory at %s', profileDir); mkdirp.sync(profileDir, 0700); return profileDir; }
[ "function", "prepareProfileDir", "(", "profilesDir", ",", "nick", ")", "{", "var", "nick", "=", "nick", "||", "'.tmp'", ";", "// Just in case `nick` has any funny business...", "nick", "=", "nick", ".", "replace", "(", "/", "[^\\w\\d.]", "/", "g", ",", "'-'", ")", ".", "replace", "(", "'..'", ",", "'-'", ")", ";", "var", "profileDir", "=", "path", ".", "join", "(", "profilesDir", ",", "util", ".", "format", "(", "'vox-%s'", ",", "nick", ")", ")", ";", "debug", "(", "'Ensuring directory at %s'", ",", "profileDir", ")", ";", "mkdirp", ".", "sync", "(", "profileDir", ",", "0700", ")", ";", "return", "profileDir", ";", "}" ]
Ensures that profilesDir exists and formats an appropriate name for the profile directory. @return {String} DB file path.
[ "Ensures", "that", "profilesDir", "exists", "and", "formats", "an", "appropriate", "name", "for", "the", "profile", "directory", "." ]
de98e5ed37edaee1b1edadf93e15eb8f8d21f457
https://github.com/spacemaus/postvox/blob/de98e5ed37edaee1b1edadf93e15eb8f8d21f457/vox-client/vox-client.js#L725-L733
53,968
SwirlNetworks/discus
src/list_view.js
function(model) { var _d = this._d; // quicker lookup if (!_d.hasData) { // if we've never rendered data yet, queue up a reset collection // this probably means we just finished our very first fetch // reset needed to clear out loading / no data state.. return this.resetCollection(); } _d.modelChanges[model.cid] = {t: 'add', m: model}; this.updateViews(); }
javascript
function(model) { var _d = this._d; // quicker lookup if (!_d.hasData) { // if we've never rendered data yet, queue up a reset collection // this probably means we just finished our very first fetch // reset needed to clear out loading / no data state.. return this.resetCollection(); } _d.modelChanges[model.cid] = {t: 'add', m: model}; this.updateViews(); }
[ "function", "(", "model", ")", "{", "var", "_d", "=", "this", ".", "_d", ";", "// quicker lookup", "if", "(", "!", "_d", ".", "hasData", ")", "{", "// if we've never rendered data yet, queue up a reset collection", "// this probably means we just finished our very first fetch", "// reset needed to clear out loading / no data state..", "return", "this", ".", "resetCollection", "(", ")", ";", "}", "_d", ".", "modelChanges", "[", "model", ".", "cid", "]", "=", "{", "t", ":", "'add'", ",", "m", ":", "model", "}", ";", "this", ".", "updateViews", "(", ")", ";", "}" ]
these next coupl of methods queue up structures to then be flushed using updateViews updateViews should really be updateInternalCache or something...
[ "these", "next", "coupl", "of", "methods", "queue", "up", "structures", "to", "then", "be", "flushed", "using", "updateViews", "updateViews", "should", "really", "be", "updateInternalCache", "or", "something", "..." ]
79df8de5ec268879e50ec1e12e78b62a13b4a427
https://github.com/SwirlNetworks/discus/blob/79df8de5ec268879e50ec1e12e78b62a13b4a427/src/list_view.js#L273-L283
53,969
SwirlNetworks/discus
src/list_view.js
function(id) { var self = this; this.collection.each(function(model) { if (model.id == id || _(id).contains(model.id)) { return; } // console.log("Unselecting model", model.id, id); self.getStateModel(model).set({ selected: false }); }); }
javascript
function(id) { var self = this; this.collection.each(function(model) { if (model.id == id || _(id).contains(model.id)) { return; } // console.log("Unselecting model", model.id, id); self.getStateModel(model).set({ selected: false }); }); }
[ "function", "(", "id", ")", "{", "var", "self", "=", "this", ";", "this", ".", "collection", ".", "each", "(", "function", "(", "model", ")", "{", "if", "(", "model", ".", "id", "==", "id", "||", "_", "(", "id", ")", ".", "contains", "(", "model", ".", "id", ")", ")", "{", "return", ";", "}", "//\t\t\tconsole.log(\"Unselecting model\", model.id, id);", "self", ".", "getStateModel", "(", "model", ")", ".", "set", "(", "{", "selected", ":", "false", "}", ")", ";", "}", ")", ";", "}" ]
optional, unselect all but id
[ "optional", "unselect", "all", "but", "id" ]
79df8de5ec268879e50ec1e12e78b62a13b4a427
https://github.com/SwirlNetworks/discus/blob/79df8de5ec268879e50ec1e12e78b62a13b4a427/src/list_view.js#L1387-L1397
53,970
ebrelsford/cartodb-export
index.js
exportVis
function exportVis(url, dest, callback) { if (dest === undefined) dest = '.'; (0, _mkdirp2['default'])(dest, function (err) { if (err && callback) return callback(err); if (!isVisUrl(url)) { url = getVisUrl(url); } getVisJson(url, _path2['default'].join(dest, 'viz.json'), function (err, visJson) { downloadVisualizationData(visJson, dest, callback); }); }); }
javascript
function exportVis(url, dest, callback) { if (dest === undefined) dest = '.'; (0, _mkdirp2['default'])(dest, function (err) { if (err && callback) return callback(err); if (!isVisUrl(url)) { url = getVisUrl(url); } getVisJson(url, _path2['default'].join(dest, 'viz.json'), function (err, visJson) { downloadVisualizationData(visJson, dest, callback); }); }); }
[ "function", "exportVis", "(", "url", ",", "dest", ",", "callback", ")", "{", "if", "(", "dest", "===", "undefined", ")", "dest", "=", "'.'", ";", "(", "0", ",", "_mkdirp2", "[", "'default'", "]", ")", "(", "dest", ",", "function", "(", "err", ")", "{", "if", "(", "err", "&&", "callback", ")", "return", "callback", "(", "err", ")", ";", "if", "(", "!", "isVisUrl", "(", "url", ")", ")", "{", "url", "=", "getVisUrl", "(", "url", ")", ";", "}", "getVisJson", "(", "url", ",", "_path2", "[", "'default'", "]", ".", "join", "(", "dest", ",", "'viz.json'", ")", ",", "function", "(", "err", ",", "visJson", ")", "{", "downloadVisualizationData", "(", "visJson", ",", "dest", ",", "callback", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Export a visualization at the given url. @param {String} url the visualization's url @param {String} dest the directory to export the visualization into @example exportVis('https://eric.cartodb.com/api/v2/viz/85c59718-082c-11e3-86d3-5404a6a69006/viz.json', 'my_vis');
[ "Export", "a", "visualization", "at", "the", "given", "url", "." ]
939cc17f16dc6777f1267e4c12425a9ad17b77ab
https://github.com/ebrelsford/cartodb-export/blob/939cc17f16dc6777f1267e4c12425a9ad17b77ab/index.js#L60-L72
53,971
ebrelsford/cartodb-export
index.js
getVisUrl
function getVisUrl(url) { var match = /https?:\/\/(\S+)\.cartodb\.com\/viz\/(\S+)\/(?:public_)?map/.exec(url); if (match) { var user = match[1], mapId = match[2]; return 'https://' + user + '.cartodb.com/api/v2/viz/' + mapId + '/viz.json'; } }
javascript
function getVisUrl(url) { var match = /https?:\/\/(\S+)\.cartodb\.com\/viz\/(\S+)\/(?:public_)?map/.exec(url); if (match) { var user = match[1], mapId = match[2]; return 'https://' + user + '.cartodb.com/api/v2/viz/' + mapId + '/viz.json'; } }
[ "function", "getVisUrl", "(", "url", ")", "{", "var", "match", "=", "/", "https?:\\/\\/(\\S+)\\.cartodb\\.com\\/viz\\/(\\S+)\\/(?:public_)?map", "/", ".", "exec", "(", "url", ")", ";", "if", "(", "match", ")", "{", "var", "user", "=", "match", "[", "1", "]", ",", "mapId", "=", "match", "[", "2", "]", ";", "return", "'https://'", "+", "user", "+", "'.cartodb.com/api/v2/viz/'", "+", "mapId", "+", "'/viz.json'", ";", "}", "}" ]
Convert a map's url into the viz.json url for that map. @param {String} url the map's url @return {String} the viz.json url, if found
[ "Convert", "a", "map", "s", "url", "into", "the", "viz", ".", "json", "url", "for", "that", "map", "." ]
939cc17f16dc6777f1267e4c12425a9ad17b77ab
https://github.com/ebrelsford/cartodb-export/blob/939cc17f16dc6777f1267e4c12425a9ad17b77ab/index.js#L86-L93
53,972
ebrelsford/cartodb-export
index.js
downloadVisualizationData
function downloadVisualizationData(_visJson, destDir, callback) { if (destDir === undefined) destDir = '.'; withVisJson(_visJson, function (err, visJson) { if (err && callback) return callback(err); _async2['default'].forEachOf(visJson.layers, function (layer, layerIndex, callback) { if (layer.type === 'namedmap') { console.error("Layer is not public, cannot download its data. If you own the map and datasets, please change the privacy settings to 'public' and try again."); return callback(); } if (layer.type !== 'layergroup') { if (callback) callback(); return; } _async2['default'].forEachOf(layer.options.layer_definition.layers, function (sublayer, sublayerIndex, callback) { var dest = _path2['default'].join(sublayerDir(destDir, layerIndex, sublayerIndex), 'layer.geojson'); downloadSublayerData(visJson, layerIndex, sublayerIndex, dest, callback); }, callback); }, callback); }); }
javascript
function downloadVisualizationData(_visJson, destDir, callback) { if (destDir === undefined) destDir = '.'; withVisJson(_visJson, function (err, visJson) { if (err && callback) return callback(err); _async2['default'].forEachOf(visJson.layers, function (layer, layerIndex, callback) { if (layer.type === 'namedmap') { console.error("Layer is not public, cannot download its data. If you own the map and datasets, please change the privacy settings to 'public' and try again."); return callback(); } if (layer.type !== 'layergroup') { if (callback) callback(); return; } _async2['default'].forEachOf(layer.options.layer_definition.layers, function (sublayer, sublayerIndex, callback) { var dest = _path2['default'].join(sublayerDir(destDir, layerIndex, sublayerIndex), 'layer.geojson'); downloadSublayerData(visJson, layerIndex, sublayerIndex, dest, callback); }, callback); }, callback); }); }
[ "function", "downloadVisualizationData", "(", "_visJson", ",", "destDir", ",", "callback", ")", "{", "if", "(", "destDir", "===", "undefined", ")", "destDir", "=", "'.'", ";", "withVisJson", "(", "_visJson", ",", "function", "(", "err", ",", "visJson", ")", "{", "if", "(", "err", "&&", "callback", ")", "return", "callback", "(", "err", ")", ";", "_async2", "[", "'default'", "]", ".", "forEachOf", "(", "visJson", ".", "layers", ",", "function", "(", "layer", ",", "layerIndex", ",", "callback", ")", "{", "if", "(", "layer", ".", "type", "===", "'namedmap'", ")", "{", "console", ".", "error", "(", "\"Layer is not public, cannot download its data. If you own the map and datasets, please change the privacy settings to 'public' and try again.\"", ")", ";", "return", "callback", "(", ")", ";", "}", "if", "(", "layer", ".", "type", "!==", "'layergroup'", ")", "{", "if", "(", "callback", ")", "callback", "(", ")", ";", "return", ";", "}", "_async2", "[", "'default'", "]", ".", "forEachOf", "(", "layer", ".", "options", ".", "layer_definition", ".", "layers", ",", "function", "(", "sublayer", ",", "sublayerIndex", ",", "callback", ")", "{", "var", "dest", "=", "_path2", "[", "'default'", "]", ".", "join", "(", "sublayerDir", "(", "destDir", ",", "layerIndex", ",", "sublayerIndex", ")", ",", "'layer.geojson'", ")", ";", "downloadSublayerData", "(", "visJson", ",", "layerIndex", ",", "sublayerIndex", ",", "dest", ",", "callback", ")", ";", "}", ",", "callback", ")", ";", "}", ",", "callback", ")", ";", "}", ")", ";", "}" ]
Download the layer data for a visualization. @param {Object|String} visJson the visualization's JSON or the url where it can be found @param {String} destDir the base directory where the data should be saved
[ "Download", "the", "layer", "data", "for", "a", "visualization", "." ]
939cc17f16dc6777f1267e4c12425a9ad17b77ab
https://github.com/ebrelsford/cartodb-export/blob/939cc17f16dc6777f1267e4c12425a9ad17b77ab/index.js#L147-L167
53,973
ebrelsford/cartodb-export
index.js
downloadSublayerData
function downloadSublayerData(visJson, layerIndex, sublayerIndex, dest, callback) { var layer = visJson.layers[layerIndex], sublayer = layer.options.layer_definition.layers[sublayerIndex]; (0, _mkdirp2['default'])(_path2['default'].dirname(dest), function () { var dataFile = _fs2['default'].createWriteStream(dest).on('close', function () { if (callback) { callback(); } }); var req = (0, _request2['default'])({ url: getLayerSqlUrl(layer), qs: { format: 'GeoJSON', q: getSublayerSql(sublayer) } }); req.pipe(dataFile); // Show progress as file downloads req.on('response', function (res) { var len = parseInt(res.headers['content-length'], 10); var bar = new _progress2['default'](' downloading [:bar] :percent :etas', { complete: '=', incomplete: ' ', width: 20, total: len }); res.on('data', function (chunk) { bar.tick(chunk.length); }); res.on('end', function (chunk) { console.log('\n'); }); }); }); }
javascript
function downloadSublayerData(visJson, layerIndex, sublayerIndex, dest, callback) { var layer = visJson.layers[layerIndex], sublayer = layer.options.layer_definition.layers[sublayerIndex]; (0, _mkdirp2['default'])(_path2['default'].dirname(dest), function () { var dataFile = _fs2['default'].createWriteStream(dest).on('close', function () { if (callback) { callback(); } }); var req = (0, _request2['default'])({ url: getLayerSqlUrl(layer), qs: { format: 'GeoJSON', q: getSublayerSql(sublayer) } }); req.pipe(dataFile); // Show progress as file downloads req.on('response', function (res) { var len = parseInt(res.headers['content-length'], 10); var bar = new _progress2['default'](' downloading [:bar] :percent :etas', { complete: '=', incomplete: ' ', width: 20, total: len }); res.on('data', function (chunk) { bar.tick(chunk.length); }); res.on('end', function (chunk) { console.log('\n'); }); }); }); }
[ "function", "downloadSublayerData", "(", "visJson", ",", "layerIndex", ",", "sublayerIndex", ",", "dest", ",", "callback", ")", "{", "var", "layer", "=", "visJson", ".", "layers", "[", "layerIndex", "]", ",", "sublayer", "=", "layer", ".", "options", ".", "layer_definition", ".", "layers", "[", "sublayerIndex", "]", ";", "(", "0", ",", "_mkdirp2", "[", "'default'", "]", ")", "(", "_path2", "[", "'default'", "]", ".", "dirname", "(", "dest", ")", ",", "function", "(", ")", "{", "var", "dataFile", "=", "_fs2", "[", "'default'", "]", ".", "createWriteStream", "(", "dest", ")", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "if", "(", "callback", ")", "{", "callback", "(", ")", ";", "}", "}", ")", ";", "var", "req", "=", "(", "0", ",", "_request2", "[", "'default'", "]", ")", "(", "{", "url", ":", "getLayerSqlUrl", "(", "layer", ")", ",", "qs", ":", "{", "format", ":", "'GeoJSON'", ",", "q", ":", "getSublayerSql", "(", "sublayer", ")", "}", "}", ")", ";", "req", ".", "pipe", "(", "dataFile", ")", ";", "// Show progress as file downloads", "req", ".", "on", "(", "'response'", ",", "function", "(", "res", ")", "{", "var", "len", "=", "parseInt", "(", "res", ".", "headers", "[", "'content-length'", "]", ",", "10", ")", ";", "var", "bar", "=", "new", "_progress2", "[", "'default'", "]", "(", "' downloading [:bar] :percent :etas'", ",", "{", "complete", ":", "'='", ",", "incomplete", ":", "' '", ",", "width", ":", "20", ",", "total", ":", "len", "}", ")", ";", "res", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "bar", ".", "tick", "(", "chunk", ".", "length", ")", ";", "}", ")", ";", "res", ".", "on", "(", "'end'", ",", "function", "(", "chunk", ")", "{", "console", ".", "log", "(", "'\\n'", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Download the data for a single sublayer. @param {Object} visJson the visualization's JSON @param {Number} layerIndex the index of the layer @param {Number} sublayerIndex the index of the sublayer @param {String} dest the directory to save the sublayer's data in @param {Function} callback called on success
[ "Download", "the", "data", "for", "a", "single", "sublayer", "." ]
939cc17f16dc6777f1267e4c12425a9ad17b77ab
https://github.com/ebrelsford/cartodb-export/blob/939cc17f16dc6777f1267e4c12425a9ad17b77ab/index.js#L211-L251
53,974
ClickInspire/sails-relational-fixtures
index.js
function(folder) { var files, modelName; folder = folder || process.cwd() + '/test/fixtures'; files = fs.readdirSync(folder); for (var i = 0; i < files.length; i++) { if (getFileExtension(files[i]) === '.json') { modelName = fileToModelName(files[i]); this.objects[modelName] = require(path.join(folder, files[i])); } } return this; }
javascript
function(folder) { var files, modelName; folder = folder || process.cwd() + '/test/fixtures'; files = fs.readdirSync(folder); for (var i = 0; i < files.length; i++) { if (getFileExtension(files[i]) === '.json') { modelName = fileToModelName(files[i]); this.objects[modelName] = require(path.join(folder, files[i])); } } return this; }
[ "function", "(", "folder", ")", "{", "var", "files", ",", "modelName", ";", "folder", "=", "folder", "||", "process", ".", "cwd", "(", ")", "+", "'/test/fixtures'", ";", "files", "=", "fs", ".", "readdirSync", "(", "folder", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "files", ".", "length", ";", "i", "++", ")", "{", "if", "(", "getFileExtension", "(", "files", "[", "i", "]", ")", "===", "'.json'", ")", "{", "modelName", "=", "fileToModelName", "(", "files", "[", "i", "]", ")", ";", "this", ".", "objects", "[", "modelName", "]", "=", "require", "(", "path", ".", "join", "(", "folder", ",", "files", "[", "i", "]", ")", ")", ";", "}", "}", "return", "this", ";", "}" ]
Read fixtures from JSON files into `objects` @param {String} [folder='<project_root>/test/fixtures'] path to fixtures @return {Object} this module, where the objects member is holding loaded fixtures
[ "Read", "fixtures", "from", "JSON", "files", "into", "objects" ]
50fc57b328bb0da22049cb6e16b3fb3e1f1cc7b4
https://github.com/ClickInspire/sails-relational-fixtures/blob/50fc57b328bb0da22049cb6e16b3fb3e1f1cc7b4/index.js#L27-L42
53,975
ClickInspire/sails-relational-fixtures
index.js
function () { var that = this, independent, dependencyNotRequired; promiseIndependent = this.saveFixturesFromArray(independentFixtures); promiseDelayedDependency = this.saveFixturesFromArray(delayedDependencyFixtures); promise = Q.all([ promiseIndependent, promiseDelayedDependency ]) .then(function(models) { return that.saveFixturesFromArray(requiredDependencyFixtures); }); return promise; }
javascript
function () { var that = this, independent, dependencyNotRequired; promiseIndependent = this.saveFixturesFromArray(independentFixtures); promiseDelayedDependency = this.saveFixturesFromArray(delayedDependencyFixtures); promise = Q.all([ promiseIndependent, promiseDelayedDependency ]) .then(function(models) { return that.saveFixturesFromArray(requiredDependencyFixtures); }); return promise; }
[ "function", "(", ")", "{", "var", "that", "=", "this", ",", "independent", ",", "dependencyNotRequired", ";", "promiseIndependent", "=", "this", ".", "saveFixturesFromArray", "(", "independentFixtures", ")", ";", "promiseDelayedDependency", "=", "this", ".", "saveFixturesFromArray", "(", "delayedDependencyFixtures", ")", ";", "promise", "=", "Q", ".", "all", "(", "[", "promiseIndependent", ",", "promiseDelayedDependency", "]", ")", ".", "then", "(", "function", "(", "models", ")", "{", "return", "that", ".", "saveFixturesFromArray", "(", "requiredDependencyFixtures", ")", ";", "}", ")", ";", "return", "promise", ";", "}" ]
Create all of the fixtures in order using grouped arrays.
[ "Create", "all", "of", "the", "fixtures", "in", "order", "using", "grouped", "arrays", "." ]
50fc57b328bb0da22049cb6e16b3fb3e1f1cc7b4
https://github.com/ClickInspire/sails-relational-fixtures/blob/50fc57b328bb0da22049cb6e16b3fb3e1f1cc7b4/index.js#L149-L163
53,976
jhermsmeier/node-cyclic-32
lib/crc32.js
crc32
function crc32( buffer, seed, table ) { var crc = seed ^ -1 var length = buffer.length - 15 var TABLE = table || crc32.TABLE.DEFAULT var i = 0 while( i < length ) { crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] } length = length + 15 while( i < length ) crc = ( crc >>> 8 ) ^ TABLE[ ( crc ^ buffer[ i++ ] ) & 0xFF ] return crc ^ -1 }
javascript
function crc32( buffer, seed, table ) { var crc = seed ^ -1 var length = buffer.length - 15 var TABLE = table || crc32.TABLE.DEFAULT var i = 0 while( i < length ) { crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] } length = length + 15 while( i < length ) crc = ( crc >>> 8 ) ^ TABLE[ ( crc ^ buffer[ i++ ] ) & 0xFF ] return crc ^ -1 }
[ "function", "crc32", "(", "buffer", ",", "seed", ",", "table", ")", "{", "var", "crc", "=", "seed", "^", "-", "1", "var", "length", "=", "buffer", ".", "length", "-", "15", "var", "TABLE", "=", "table", "||", "crc32", ".", "TABLE", ".", "DEFAULT", "var", "i", "=", "0", "while", "(", "i", "<", "length", ")", "{", "crc", "=", "(", "crc", ">>>", "8", ")", "^", "TABLE", "[", "0xFF", "&", "(", "crc", "^", "buffer", "[", "i", "++", "]", ")", "]", "crc", "=", "(", "crc", ">>>", "8", ")", "^", "TABLE", "[", "0xFF", "&", "(", "crc", "^", "buffer", "[", "i", "++", "]", ")", "]", "crc", "=", "(", "crc", ">>>", "8", ")", "^", "TABLE", "[", "0xFF", "&", "(", "crc", "^", "buffer", "[", "i", "++", "]", ")", "]", "crc", "=", "(", "crc", ">>>", "8", ")", "^", "TABLE", "[", "0xFF", "&", "(", "crc", "^", "buffer", "[", "i", "++", "]", ")", "]", "crc", "=", "(", "crc", ">>>", "8", ")", "^", "TABLE", "[", "0xFF", "&", "(", "crc", "^", "buffer", "[", "i", "++", "]", ")", "]", "crc", "=", "(", "crc", ">>>", "8", ")", "^", "TABLE", "[", "0xFF", "&", "(", "crc", "^", "buffer", "[", "i", "++", "]", ")", "]", "crc", "=", "(", "crc", ">>>", "8", ")", "^", "TABLE", "[", "0xFF", "&", "(", "crc", "^", "buffer", "[", "i", "++", "]", ")", "]", "crc", "=", "(", "crc", ">>>", "8", ")", "^", "TABLE", "[", "0xFF", "&", "(", "crc", "^", "buffer", "[", "i", "++", "]", ")", "]", "crc", "=", "(", "crc", ">>>", "8", ")", "^", "TABLE", "[", "0xFF", "&", "(", "crc", "^", "buffer", "[", "i", "++", "]", ")", "]", "crc", "=", "(", "crc", ">>>", "8", ")", "^", "TABLE", "[", "0xFF", "&", "(", "crc", "^", "buffer", "[", "i", "++", "]", ")", "]", "crc", "=", "(", "crc", ">>>", "8", ")", "^", "TABLE", "[", "0xFF", "&", "(", "crc", "^", "buffer", "[", "i", "++", "]", ")", "]", "crc", "=", "(", "crc", ">>>", "8", ")", "^", "TABLE", "[", "0xFF", "&", "(", "crc", "^", "buffer", "[", "i", "++", "]", ")", "]", "crc", "=", "(", "crc", ">>>", "8", ")", "^", "TABLE", "[", "0xFF", "&", "(", "crc", "^", "buffer", "[", "i", "++", "]", ")", "]", "crc", "=", "(", "crc", ">>>", "8", ")", "^", "TABLE", "[", "0xFF", "&", "(", "crc", "^", "buffer", "[", "i", "++", "]", ")", "]", "crc", "=", "(", "crc", ">>>", "8", ")", "^", "TABLE", "[", "0xFF", "&", "(", "crc", "^", "buffer", "[", "i", "++", "]", ")", "]", "crc", "=", "(", "crc", ">>>", "8", ")", "^", "TABLE", "[", "0xFF", "&", "(", "crc", "^", "buffer", "[", "i", "++", "]", ")", "]", "}", "length", "=", "length", "+", "15", "while", "(", "i", "<", "length", ")", "crc", "=", "(", "crc", ">>>", "8", ")", "^", "TABLE", "[", "(", "crc", "^", "buffer", "[", "i", "++", "]", ")", "&", "0xFF", "]", "return", "crc", "^", "-", "1", "}" ]
Calculate the CRC32 checksum of a given buffer @param {Buffer} buffer @param {Number} [seed=0] @param {Int32Array} [table=crc32.TABLE.DEFAULT] @returns {Number} checksum
[ "Calculate", "the", "CRC32", "checksum", "of", "a", "given", "buffer" ]
5ba7f4d8c9c3c1e61ae52591461f3225fde064e2
https://github.com/jhermsmeier/node-cyclic-32/blob/5ba7f4d8c9c3c1e61ae52591461f3225fde064e2/lib/crc32.js#L12-L45
53,977
joemccann/photopipe
plugins/twitter/twitter.js
normalizeTwitterData
function normalizeTwitterData(data,req,res){ var normalized = { error: false, error_message: '', media: [] } // console.dir(req.session.twitter) if( isTwitterOverCapacity() ){ normalized.error = true normalized.error_message = "It appears Twitter is over capacity. Try again." } else{ console.log("Twitter Response array length: %s\n", data.length) // If the media response is empty... if(!data.length){ normalized.error = true normalized.error_message = "We were unable to fetch any images from your media timeline." console.dir(data) return processNormalizedResponse(normalized, req, res) } // We use a for loop so we can break out if // the cache is met for(i=0, len = data.length; i<len; i++){ var el = data[i] // console.dir(el) // TODO: Session won't stash this much data so switch this logic to pull from redis. if( req.session.media_cache && isItemFirstCacheItem(el.id, req.session.media_cache.latest_id ) ){ console.log('\n\nCache is same so we are breaking...\n\n') // update latest_id in cache normalized.latest_id = el.id // Now process the the response with new updated normalized data processNormalizedResponse(normalized, req, res) break } // The first time we run this, we need to stash the latest_id if( i === len-1 ){ normalized.latest_id = data[0].id } // In the case of just pic.twitter.com.... if(el.entities && el.entities.media && el.entities.media.length){ var twitMediaObj = el.entities.media[0] var item = { full_url: twitMediaObj.media_url+":large", thumb_url: twitMediaObj.media_url+":thumb", } normalized.media.push(item) } // Otherwise, we have 3rd part attributed providers. else if(el.entities && el.entities.urls && el.entities.urls.length && el.entities.urls[0].display_url){ var url = el.entities.urls[el.entities.urls.length-1].display_url if(url.indexOf('instagr.am') > -1){ var item = { full_url: "https://" + url + "/media/?size=l", thumb_url: "https://" + url + "/media/?size=t", } normalized.media.push(item) } if(url.indexOf('twimg.com') > -1){ // https://p.twimg.com/A128d2CCIAAPt--.jpg:small // https://p.twimg.com/A128d2CCIAAPt--.jpg:large } if(url.indexOf('flickr.com') > -1){ /* <div class="thumbnail-wrapper" data-url="http://flickr.com/groups/dalekcakes"> <img class="scaled-image" src="//farm7.static.flickr.com/6140/5917491915_8e92c65aa8.jpg"></div> */ // WILL NEED TO FIGURE OUT FLICKR RESPONSE // Requires API call via photo ID, or just use twitter: /* https://widgets.platform.twitter.com/services/rest?jsoncallback=jQuery15205886323538143188_1346683837796&format=json&api_key=2a56884b56a00758525eaa2fee16a798&method=flickr.photos.getInfo&photo_id=7275880290&_=1346683837809 */ console.dir(el) } if(url.indexOf('twitpic.com') > -1){ // POP OFF ID OF END OF TWITPIC URL // http://twitpic.com/9k68zj var url_id = url.split('com')[1] // includes slash var item = { full_url: "https://twitpic.com/show/iphone" + url_id, thumb_url: "https://twitpic.com/show/iphone" + url_id, } normalized.media.push(item) } // if(url.indexOf('etsy.am') > -1){} if(url.indexOf('twitgoo.com') > -1){ // http://twitgoo.com/66akxy/img var item = { full_url: url + '/img', thumb_url: url + '/img', } normalized.media.push(item) } // Daily booth closed down.... // if(url.indexOf('dailybooth.com') > -1){ // console.log(url) // request({ // followRedirect: false, // uri: 'http://'+url, // callback: function(e,r,b){ // need to handle errors better... // if(e) console.error(e) // // console.dir(r) // // var id = r.headers.location.split('/').pop() // // request({ // uri: "https://api.dailybooth.com/v1/picture/" + id + ".json", // json: true, // callback: function(e,r,b){ // if(e) return console.error(e) // /* // urls: // { tiny: 'http://d1oi94rh653f1l.cloudfront.net/15/pictures/tiny/78e4b486c80b29435504d94fdf626b7c_29230840.jpg', // small: 'http://d1oi94rh653f1l.cloudfront.net/15/pictures/small/78e4b486c80b29435504d94fdf626b7c_29230840.jpg', // medium: 'http://d1oi94rh653f1l.cloudfront.net/15/pictures/medium/78e4b486c80b29435504d94fdf626b7c_29230840.jpg', // large: 'http://d1oi94rh653f1l.cloudfront.net/15/pictures/large/78e4b486c80b29435504d94fdf626b7c_29230840.jpg' // } // // { error: // { error: 'rate_limit', // error_description: 'Rate limit exceeded.', // error_code: 412 } } // var item = { // full_url: b.urls.large + '/img', // thumb_url: b.urls.small + '/img', // } // */ // // if( (r.statusCode >= 400) || b.error) { // console.log('Fail. '.red +'Status Code for Daily Booth request: %s', r.statusCode) // console.error(b.error) // } // else{ // // var item = { // full_url: b.urls.large, // thumb_url: b.urls.small, // } // // normalized.media.push(item) // } // // delay = false // // processNormalizedResponse(normalized, req, res) // // } // end inner request callback // }) // end request() // } // end outer request callback // }) // end request() // // // Because of the async nature of the above request() calls, // // we set the delay here and mark it false in the last callback // if(!delay) delay = true // // } if(url.indexOf('yfrog.com') > -1){ // console.dir(el) var item = { full_url: "https://" + url + ":tw1", thumb_url: "https://" + url + ":tw1", } normalized.media.push(item) } // if(url.indexOf('lockerz.am') > -1){} // if(url.indexOf('kiva.am') > -1){} // if(url.indexOf('kickstarter.com') > -1){} if(url.indexOf('dipdive.com') > -1){ isVideo = false || true; // could be photo } // if(url.indexOf('photobucket.com') > -1){} // if(url.indexOf('with.me') > -1){} // if(url.indexOf('facebook.com') > -1){} if(url.indexOf('deviantart.com') > -1 || url.indexOf('fav.me') > -1){ // TODO: IMAGES DON'T SHOW UP? } } // end if el.entities.url } // end forloop } // end else capacity return processNormalizedResponse(normalized, req, res) }
javascript
function normalizeTwitterData(data,req,res){ var normalized = { error: false, error_message: '', media: [] } // console.dir(req.session.twitter) if( isTwitterOverCapacity() ){ normalized.error = true normalized.error_message = "It appears Twitter is over capacity. Try again." } else{ console.log("Twitter Response array length: %s\n", data.length) // If the media response is empty... if(!data.length){ normalized.error = true normalized.error_message = "We were unable to fetch any images from your media timeline." console.dir(data) return processNormalizedResponse(normalized, req, res) } // We use a for loop so we can break out if // the cache is met for(i=0, len = data.length; i<len; i++){ var el = data[i] // console.dir(el) // TODO: Session won't stash this much data so switch this logic to pull from redis. if( req.session.media_cache && isItemFirstCacheItem(el.id, req.session.media_cache.latest_id ) ){ console.log('\n\nCache is same so we are breaking...\n\n') // update latest_id in cache normalized.latest_id = el.id // Now process the the response with new updated normalized data processNormalizedResponse(normalized, req, res) break } // The first time we run this, we need to stash the latest_id if( i === len-1 ){ normalized.latest_id = data[0].id } // In the case of just pic.twitter.com.... if(el.entities && el.entities.media && el.entities.media.length){ var twitMediaObj = el.entities.media[0] var item = { full_url: twitMediaObj.media_url+":large", thumb_url: twitMediaObj.media_url+":thumb", } normalized.media.push(item) } // Otherwise, we have 3rd part attributed providers. else if(el.entities && el.entities.urls && el.entities.urls.length && el.entities.urls[0].display_url){ var url = el.entities.urls[el.entities.urls.length-1].display_url if(url.indexOf('instagr.am') > -1){ var item = { full_url: "https://" + url + "/media/?size=l", thumb_url: "https://" + url + "/media/?size=t", } normalized.media.push(item) } if(url.indexOf('twimg.com') > -1){ // https://p.twimg.com/A128d2CCIAAPt--.jpg:small // https://p.twimg.com/A128d2CCIAAPt--.jpg:large } if(url.indexOf('flickr.com') > -1){ /* <div class="thumbnail-wrapper" data-url="http://flickr.com/groups/dalekcakes"> <img class="scaled-image" src="//farm7.static.flickr.com/6140/5917491915_8e92c65aa8.jpg"></div> */ // WILL NEED TO FIGURE OUT FLICKR RESPONSE // Requires API call via photo ID, or just use twitter: /* https://widgets.platform.twitter.com/services/rest?jsoncallback=jQuery15205886323538143188_1346683837796&format=json&api_key=2a56884b56a00758525eaa2fee16a798&method=flickr.photos.getInfo&photo_id=7275880290&_=1346683837809 */ console.dir(el) } if(url.indexOf('twitpic.com') > -1){ // POP OFF ID OF END OF TWITPIC URL // http://twitpic.com/9k68zj var url_id = url.split('com')[1] // includes slash var item = { full_url: "https://twitpic.com/show/iphone" + url_id, thumb_url: "https://twitpic.com/show/iphone" + url_id, } normalized.media.push(item) } // if(url.indexOf('etsy.am') > -1){} if(url.indexOf('twitgoo.com') > -1){ // http://twitgoo.com/66akxy/img var item = { full_url: url + '/img', thumb_url: url + '/img', } normalized.media.push(item) } // Daily booth closed down.... // if(url.indexOf('dailybooth.com') > -1){ // console.log(url) // request({ // followRedirect: false, // uri: 'http://'+url, // callback: function(e,r,b){ // need to handle errors better... // if(e) console.error(e) // // console.dir(r) // // var id = r.headers.location.split('/').pop() // // request({ // uri: "https://api.dailybooth.com/v1/picture/" + id + ".json", // json: true, // callback: function(e,r,b){ // if(e) return console.error(e) // /* // urls: // { tiny: 'http://d1oi94rh653f1l.cloudfront.net/15/pictures/tiny/78e4b486c80b29435504d94fdf626b7c_29230840.jpg', // small: 'http://d1oi94rh653f1l.cloudfront.net/15/pictures/small/78e4b486c80b29435504d94fdf626b7c_29230840.jpg', // medium: 'http://d1oi94rh653f1l.cloudfront.net/15/pictures/medium/78e4b486c80b29435504d94fdf626b7c_29230840.jpg', // large: 'http://d1oi94rh653f1l.cloudfront.net/15/pictures/large/78e4b486c80b29435504d94fdf626b7c_29230840.jpg' // } // // { error: // { error: 'rate_limit', // error_description: 'Rate limit exceeded.', // error_code: 412 } } // var item = { // full_url: b.urls.large + '/img', // thumb_url: b.urls.small + '/img', // } // */ // // if( (r.statusCode >= 400) || b.error) { // console.log('Fail. '.red +'Status Code for Daily Booth request: %s', r.statusCode) // console.error(b.error) // } // else{ // // var item = { // full_url: b.urls.large, // thumb_url: b.urls.small, // } // // normalized.media.push(item) // } // // delay = false // // processNormalizedResponse(normalized, req, res) // // } // end inner request callback // }) // end request() // } // end outer request callback // }) // end request() // // // Because of the async nature of the above request() calls, // // we set the delay here and mark it false in the last callback // if(!delay) delay = true // // } if(url.indexOf('yfrog.com') > -1){ // console.dir(el) var item = { full_url: "https://" + url + ":tw1", thumb_url: "https://" + url + ":tw1", } normalized.media.push(item) } // if(url.indexOf('lockerz.am') > -1){} // if(url.indexOf('kiva.am') > -1){} // if(url.indexOf('kickstarter.com') > -1){} if(url.indexOf('dipdive.com') > -1){ isVideo = false || true; // could be photo } // if(url.indexOf('photobucket.com') > -1){} // if(url.indexOf('with.me') > -1){} // if(url.indexOf('facebook.com') > -1){} if(url.indexOf('deviantart.com') > -1 || url.indexOf('fav.me') > -1){ // TODO: IMAGES DON'T SHOW UP? } } // end if el.entities.url } // end forloop } // end else capacity return processNormalizedResponse(normalized, req, res) }
[ "function", "normalizeTwitterData", "(", "data", ",", "req", ",", "res", ")", "{", "var", "normalized", "=", "{", "error", ":", "false", ",", "error_message", ":", "''", ",", "media", ":", "[", "]", "}", "// console.dir(req.session.twitter)", "if", "(", "isTwitterOverCapacity", "(", ")", ")", "{", "normalized", ".", "error", "=", "true", "normalized", ".", "error_message", "=", "\"It appears Twitter is over capacity. Try again.\"", "}", "else", "{", "console", ".", "log", "(", "\"Twitter Response array length: %s\\n\"", ",", "data", ".", "length", ")", "// If the media response is empty...", "if", "(", "!", "data", ".", "length", ")", "{", "normalized", ".", "error", "=", "true", "normalized", ".", "error_message", "=", "\"We were unable to fetch any images from your media timeline.\"", "console", ".", "dir", "(", "data", ")", "return", "processNormalizedResponse", "(", "normalized", ",", "req", ",", "res", ")", "}", "// We use a for loop so we can break out if", "// the cache is met", "for", "(", "i", "=", "0", ",", "len", "=", "data", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "el", "=", "data", "[", "i", "]", "// console.dir(el)", "// TODO: Session won't stash this much data so switch this logic to pull from redis.", "if", "(", "req", ".", "session", ".", "media_cache", "&&", "isItemFirstCacheItem", "(", "el", ".", "id", ",", "req", ".", "session", ".", "media_cache", ".", "latest_id", ")", ")", "{", "console", ".", "log", "(", "'\\n\\nCache is same so we are breaking...\\n\\n'", ")", "// update latest_id in cache", "normalized", ".", "latest_id", "=", "el", ".", "id", "// Now process the the response with new updated normalized data", "processNormalizedResponse", "(", "normalized", ",", "req", ",", "res", ")", "break", "}", "// The first time we run this, we need to stash the latest_id", "if", "(", "i", "===", "len", "-", "1", ")", "{", "normalized", ".", "latest_id", "=", "data", "[", "0", "]", ".", "id", "}", "// In the case of just pic.twitter.com....", "if", "(", "el", ".", "entities", "&&", "el", ".", "entities", ".", "media", "&&", "el", ".", "entities", ".", "media", ".", "length", ")", "{", "var", "twitMediaObj", "=", "el", ".", "entities", ".", "media", "[", "0", "]", "var", "item", "=", "{", "full_url", ":", "twitMediaObj", ".", "media_url", "+", "\":large\"", ",", "thumb_url", ":", "twitMediaObj", ".", "media_url", "+", "\":thumb\"", ",", "}", "normalized", ".", "media", ".", "push", "(", "item", ")", "}", "// Otherwise, we have 3rd part attributed providers.", "else", "if", "(", "el", ".", "entities", "&&", "el", ".", "entities", ".", "urls", "&&", "el", ".", "entities", ".", "urls", ".", "length", "&&", "el", ".", "entities", ".", "urls", "[", "0", "]", ".", "display_url", ")", "{", "var", "url", "=", "el", ".", "entities", ".", "urls", "[", "el", ".", "entities", ".", "urls", ".", "length", "-", "1", "]", ".", "display_url", "if", "(", "url", ".", "indexOf", "(", "'instagr.am'", ")", ">", "-", "1", ")", "{", "var", "item", "=", "{", "full_url", ":", "\"https://\"", "+", "url", "+", "\"/media/?size=l\"", ",", "thumb_url", ":", "\"https://\"", "+", "url", "+", "\"/media/?size=t\"", ",", "}", "normalized", ".", "media", ".", "push", "(", "item", ")", "}", "if", "(", "url", ".", "indexOf", "(", "'twimg.com'", ")", ">", "-", "1", ")", "{", "// https://p.twimg.com/A128d2CCIAAPt--.jpg:small", "// https://p.twimg.com/A128d2CCIAAPt--.jpg:large", "}", "if", "(", "url", ".", "indexOf", "(", "'flickr.com'", ")", ">", "-", "1", ")", "{", "/*\n \n <div class=\"thumbnail-wrapper\" data-url=\"http://flickr.com/groups/dalekcakes\">\n <img class=\"scaled-image\" src=\"//farm7.static.flickr.com/6140/5917491915_8e92c65aa8.jpg\"></div>\n \n */", "// WILL NEED TO FIGURE OUT FLICKR RESPONSE", "// Requires API call via photo ID, or just use twitter:", "/*\n https://widgets.platform.twitter.com/services/rest?jsoncallback=jQuery15205886323538143188_1346683837796&format=json&api_key=2a56884b56a00758525eaa2fee16a798&method=flickr.photos.getInfo&photo_id=7275880290&_=1346683837809\n */", "console", ".", "dir", "(", "el", ")", "}", "if", "(", "url", ".", "indexOf", "(", "'twitpic.com'", ")", ">", "-", "1", ")", "{", "// POP OFF ID OF END OF TWITPIC URL", "// http://twitpic.com/9k68zj", "var", "url_id", "=", "url", ".", "split", "(", "'com'", ")", "[", "1", "]", "// includes slash", "var", "item", "=", "{", "full_url", ":", "\"https://twitpic.com/show/iphone\"", "+", "url_id", ",", "thumb_url", ":", "\"https://twitpic.com/show/iphone\"", "+", "url_id", ",", "}", "normalized", ".", "media", ".", "push", "(", "item", ")", "}", "// if(url.indexOf('etsy.am') > -1){}", "if", "(", "url", ".", "indexOf", "(", "'twitgoo.com'", ")", ">", "-", "1", ")", "{", "// http://twitgoo.com/66akxy/img", "var", "item", "=", "{", "full_url", ":", "url", "+", "'/img'", ",", "thumb_url", ":", "url", "+", "'/img'", ",", "}", "normalized", ".", "media", ".", "push", "(", "item", ")", "}", "// Daily booth closed down....", "// if(url.indexOf('dailybooth.com') > -1){", "// console.log(url)", "// request({", "// followRedirect: false,", "// uri: 'http://'+url,", "// callback: function(e,r,b){", "// need to handle errors better...", "// if(e) console.error(e)", "// ", "// console.dir(r)", "// ", "// var id = r.headers.location.split('/').pop()", "// ", "// request({", "// uri: \"https://api.dailybooth.com/v1/picture/\" + id + \".json\",", "// json: true,", "// callback: function(e,r,b){", "// if(e) return console.error(e)", "// /*", "// urls: ", "// { tiny: 'http://d1oi94rh653f1l.cloudfront.net/15/pictures/tiny/78e4b486c80b29435504d94fdf626b7c_29230840.jpg',", "// small: 'http://d1oi94rh653f1l.cloudfront.net/15/pictures/small/78e4b486c80b29435504d94fdf626b7c_29230840.jpg',", "// medium: 'http://d1oi94rh653f1l.cloudfront.net/15/pictures/medium/78e4b486c80b29435504d94fdf626b7c_29230840.jpg',", "// large: 'http://d1oi94rh653f1l.cloudfront.net/15/pictures/large/78e4b486c80b29435504d94fdf626b7c_29230840.jpg' ", "// }", "// ", "// { error: ", "// { error: 'rate_limit',", "// error_description: 'Rate limit exceeded.',", "// error_code: 412 } }", "// var item = {", "// full_url: b.urls.large + '/img',", "// thumb_url: b.urls.small + '/img',", "// }", "// */", "// ", "// if( (r.statusCode >= 400) || b.error) {", "// console.log('Fail. '.red +'Status Code for Daily Booth request: %s', r.statusCode)", "// console.error(b.error)", "// }", "// else{", "// ", "// var item = {", "// full_url: b.urls.large,", "// thumb_url: b.urls.small,", "// }", "// ", "// normalized.media.push(item) ", "// }", "// ", "// delay = false", "// ", "// processNormalizedResponse(normalized, req, res)", "// ", "// } // end inner request callback", "// }) // end request()", "// } // end outer request callback", "// }) // end request()", "// ", "// // Because of the async nature of the above request() calls,", "// // we set the delay here and mark it false in the last callback", "// if(!delay) delay = true", "// ", "// }", "if", "(", "url", ".", "indexOf", "(", "'yfrog.com'", ")", ">", "-", "1", ")", "{", "// console.dir(el)", "var", "item", "=", "{", "full_url", ":", "\"https://\"", "+", "url", "+", "\":tw1\"", ",", "thumb_url", ":", "\"https://\"", "+", "url", "+", "\":tw1\"", ",", "}", "normalized", ".", "media", ".", "push", "(", "item", ")", "}", "// if(url.indexOf('lockerz.am') > -1){}", "// if(url.indexOf('kiva.am') > -1){}", "// if(url.indexOf('kickstarter.com') > -1){}", "if", "(", "url", ".", "indexOf", "(", "'dipdive.com'", ")", ">", "-", "1", ")", "{", "isVideo", "=", "false", "||", "true", ";", "// could be photo", "}", "// if(url.indexOf('photobucket.com') > -1){}", "// if(url.indexOf('with.me') > -1){}", "// if(url.indexOf('facebook.com') > -1){}", "if", "(", "url", ".", "indexOf", "(", "'deviantart.com'", ")", ">", "-", "1", "||", "url", ".", "indexOf", "(", "'fav.me'", ")", ">", "-", "1", ")", "{", "// TODO: IMAGES DON'T SHOW UP?", "}", "}", "// end if el.entities.url", "}", "// end forloop", "}", "// end else capacity", "return", "processNormalizedResponse", "(", "normalized", ",", "req", ",", "res", ")", "}" ]
Let's normalize the response of media data to only include the photos we want.
[ "Let", "s", "normalize", "the", "response", "of", "media", "data", "to", "only", "include", "the", "photos", "we", "want", "." ]
20318fde11163a8b732b077a141a8d8530372333
https://github.com/joemccann/photopipe/blob/20318fde11163a8b732b077a141a8d8530372333/plugins/twitter/twitter.js#L33-L261
53,978
craigbilner/eslint-plugin-react-props
lib/utilities.js
isPropTypesDeclaration
function isPropTypesDeclaration(context, node) { // Special case for class properties // (babel-eslint does not expose property name so we have to rely on tokens) if (node.type === 'ClassProperty') { const tokens = context.getFirstTokens(node, 2); if (isTypesDecl(tokens[0].value) || isTypesDecl(tokens[1].value)) { return true; } return false; } return Boolean(node && isTypesDecl(node.name)); }
javascript
function isPropTypesDeclaration(context, node) { // Special case for class properties // (babel-eslint does not expose property name so we have to rely on tokens) if (node.type === 'ClassProperty') { const tokens = context.getFirstTokens(node, 2); if (isTypesDecl(tokens[0].value) || isTypesDecl(tokens[1].value)) { return true; } return false; } return Boolean(node && isTypesDecl(node.name)); }
[ "function", "isPropTypesDeclaration", "(", "context", ",", "node", ")", "{", "// Special case for class properties", "// (babel-eslint does not expose property name so we have to rely on tokens)", "if", "(", "node", ".", "type", "===", "'ClassProperty'", ")", "{", "const", "tokens", "=", "context", ".", "getFirstTokens", "(", "node", ",", "2", ")", ";", "if", "(", "isTypesDecl", "(", "tokens", "[", "0", "]", ".", "value", ")", "||", "isTypesDecl", "(", "tokens", "[", "1", "]", ".", "value", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", "return", "Boolean", "(", "node", "&&", "isTypesDecl", "(", "node", ".", "name", ")", ")", ";", "}" ]
Checks if node is `propTypes` declaration @param {ASTNode} node The AST node being checked. @returns {Boolean} True if node is `propTypes` declaration, false if not.
[ "Checks", "if", "node", "is", "propTypes", "declaration" ]
d4138351d36cadb7ce319440b75d5437772e6882
https://github.com/craigbilner/eslint-plugin-react-props/blob/d4138351d36cadb7ce319440b75d5437772e6882/lib/utilities.js#L14-L26
53,979
sdawood/functional-pipelines
src/functional-pipelines.js
reduce
function reduce(reducingFn, initFn, enumerable, resultFn) { if (isFunction(resultFn)) { resultFn = pipe(unreduced, resultFn); } else { resultFn = unreduced; } let result; const iter = iterator(enumerable); if (!initFn) { const [initValue] = iter; initFn = lazy(initValue); } result = initFn(); for (const value of iter) { if (isReduced(result)) { break; } result = reducingFn(result, value); } return resultFn(result); }
javascript
function reduce(reducingFn, initFn, enumerable, resultFn) { if (isFunction(resultFn)) { resultFn = pipe(unreduced, resultFn); } else { resultFn = unreduced; } let result; const iter = iterator(enumerable); if (!initFn) { const [initValue] = iter; initFn = lazy(initValue); } result = initFn(); for (const value of iter) { if (isReduced(result)) { break; } result = reducingFn(result, value); } return resultFn(result); }
[ "function", "reduce", "(", "reducingFn", ",", "initFn", ",", "enumerable", ",", "resultFn", ")", "{", "if", "(", "isFunction", "(", "resultFn", ")", ")", "{", "resultFn", "=", "pipe", "(", "unreduced", ",", "resultFn", ")", ";", "}", "else", "{", "resultFn", "=", "unreduced", ";", "}", "let", "result", ";", "const", "iter", "=", "iterator", "(", "enumerable", ")", ";", "if", "(", "!", "initFn", ")", "{", "const", "[", "initValue", "]", "=", "iter", ";", "initFn", "=", "lazy", "(", "initValue", ")", ";", "}", "result", "=", "initFn", "(", ")", ";", "for", "(", "const", "value", "of", "iter", ")", "{", "if", "(", "isReduced", "(", "result", ")", ")", "{", "break", ";", "}", "result", "=", "reducingFn", "(", "result", ",", "value", ")", ";", "}", "return", "resultFn", "(", "result", ")", ";", "}" ]
Implements reduce for iterables Uses the for-of to reduce an iterable, accepting a reducing function @param iterable @param reducingFn: function of arity 2, (acc, input) -> new acc @param initFn: produces the initial value for the accumulator @returns {Accumulator-Collection}
[ "Implements", "reduce", "for", "iterables" ]
c613b19546d013a851843660c830df30f8d9e800
https://github.com/sdawood/functional-pipelines/blob/c613b19546d013a851843660c830df30f8d9e800/src/functional-pipelines.js#L409-L431
53,980
Joris-van-der-Wel/node-throwable
lib/Throwable.js
Throwable
function Throwable(wrapped) { if (!(this instanceof Throwable)) { return new Throwable(wrapped); } /* istanbul ignore if */ if (typeof wrapped !== 'object') { throw Error('Throwable should wrap an Error'); } // Wrap the Error so that the stack, lineNumber, fileName, etc is correct this.wrapped = wrapped; this.wrapped.name = 'Throwable'; }
javascript
function Throwable(wrapped) { if (!(this instanceof Throwable)) { return new Throwable(wrapped); } /* istanbul ignore if */ if (typeof wrapped !== 'object') { throw Error('Throwable should wrap an Error'); } // Wrap the Error so that the stack, lineNumber, fileName, etc is correct this.wrapped = wrapped; this.wrapped.name = 'Throwable'; }
[ "function", "Throwable", "(", "wrapped", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Throwable", ")", ")", "{", "return", "new", "Throwable", "(", "wrapped", ")", ";", "}", "/* istanbul ignore if */", "if", "(", "typeof", "wrapped", "!==", "'object'", ")", "{", "throw", "Error", "(", "'Throwable should wrap an Error'", ")", ";", "}", "// Wrap the Error so that the stack, lineNumber, fileName, etc is correct", "this", ".", "wrapped", "=", "wrapped", ";", "this", ".", "wrapped", ".", "name", "=", "'Throwable'", ";", "}" ]
Inherit from Error without performance penalties, `instanceof` behaves as expected and the error stack is correct. This module can be used cross-browser using Browserify. @module Throwable @author Joris van der Wel <[email protected]> Constructs a new Throwable by wrapping around an Error() (a decorator). All of Error's properties and methods are proxied to this wrapped Error. This ensures the "stack" is correct without having to inspect this stack during the construction of Throwable (which would have been slow). Throwable has its prototype chained to Error, which means that (new Throwable() instanceof Error) is true. You can inherit from this class by using normal prototype chaining (for example using util.inherits). Make sure you also call the Throwable constructor function in your own constructor. @constructor @augments Error @alias module:Throwable @param {!Error} wrapped @example throw new Throwable(Error('Hrm'));
[ "Inherit", "from", "Error", "without", "performance", "penalties", "instanceof", "behaves", "as", "expected", "and", "the", "error", "stack", "is", "correct", ".", "This", "module", "can", "be", "used", "cross", "-", "browser", "using", "Browserify", "." ]
5b7dab5fd8807b5ed8b2eb010d5ae65d2b35fe31
https://github.com/Joris-van-der-Wel/node-throwable/blob/5b7dab5fd8807b5ed8b2eb010d5ae65d2b35fe31/lib/Throwable.js#L25-L41
53,981
akashacms/akashacms-epub
index.js
_bundleEPUB
function _bundleEPUB(config, done) { var epubconfig = config.akashacmsEPUB; var archive = archiver('zip'); var output = fs.createWriteStream(config.akashacmsEPUB.bookmetadata.epub); output.on('close', function() { logger.info(archive.pointer() + ' total bytes'); logger.info('archiver has been finalized and the output file descriptor has closed.'); done(); }); archive.on('error', function(err) { logger.info('*********** BundleEPUB ERROR '+ err); done(err); }); archive.pipe(output); // The mimetype file must be the first entry, and must not be compressed archive.append( fs.createReadStream(path.join(config.root_out, "mimetype")), { name: "mimetype", store: true }); archive.append( fs.createReadStream(path.join(config.root_out, "META-INF", "container.xml")), { name: path.join("META-INF", "container.xml") }); archive.append( fs.createReadStream(path.join(config.root_out, config.akashacmsEPUB.bookmetadata.opf)), { name: config.akashacmsEPUB.bookmetadata.opf }); // archive.append( // fs.createReadStream(path.join(config.root_out, config.akashacmsEPUB.files.ncx)), // { name: config.akashacmsEPUB.files.ncx }); // logger.info(util.inspect(config.akashacmsEPUB.manifest)); async.eachSeries(config.akashacmsEPUB.manifest, function(item, next) { // logger.info(util.inspect(item)); // if (item.spinetoc !== true) { // this had been used to skip the NCX file archive.append( fs.createReadStream(path.join(config.root_out, item.href)), { name: item.href } ); // } next(); }, function(err) { if (err) logger.error(err); logger.info('before finalize'); archive.finalize(); }); }
javascript
function _bundleEPUB(config, done) { var epubconfig = config.akashacmsEPUB; var archive = archiver('zip'); var output = fs.createWriteStream(config.akashacmsEPUB.bookmetadata.epub); output.on('close', function() { logger.info(archive.pointer() + ' total bytes'); logger.info('archiver has been finalized and the output file descriptor has closed.'); done(); }); archive.on('error', function(err) { logger.info('*********** BundleEPUB ERROR '+ err); done(err); }); archive.pipe(output); // The mimetype file must be the first entry, and must not be compressed archive.append( fs.createReadStream(path.join(config.root_out, "mimetype")), { name: "mimetype", store: true }); archive.append( fs.createReadStream(path.join(config.root_out, "META-INF", "container.xml")), { name: path.join("META-INF", "container.xml") }); archive.append( fs.createReadStream(path.join(config.root_out, config.akashacmsEPUB.bookmetadata.opf)), { name: config.akashacmsEPUB.bookmetadata.opf }); // archive.append( // fs.createReadStream(path.join(config.root_out, config.akashacmsEPUB.files.ncx)), // { name: config.akashacmsEPUB.files.ncx }); // logger.info(util.inspect(config.akashacmsEPUB.manifest)); async.eachSeries(config.akashacmsEPUB.manifest, function(item, next) { // logger.info(util.inspect(item)); // if (item.spinetoc !== true) { // this had been used to skip the NCX file archive.append( fs.createReadStream(path.join(config.root_out, item.href)), { name: item.href } ); // } next(); }, function(err) { if (err) logger.error(err); logger.info('before finalize'); archive.finalize(); }); }
[ "function", "_bundleEPUB", "(", "config", ",", "done", ")", "{", "var", "epubconfig", "=", "config", ".", "akashacmsEPUB", ";", "var", "archive", "=", "archiver", "(", "'zip'", ")", ";", "var", "output", "=", "fs", ".", "createWriteStream", "(", "config", ".", "akashacmsEPUB", ".", "bookmetadata", ".", "epub", ")", ";", "output", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "logger", ".", "info", "(", "archive", ".", "pointer", "(", ")", "+", "' total bytes'", ")", ";", "logger", ".", "info", "(", "'archiver has been finalized and the output file descriptor has closed.'", ")", ";", "done", "(", ")", ";", "}", ")", ";", "archive", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "logger", ".", "info", "(", "'*********** BundleEPUB ERROR '", "+", "err", ")", ";", "done", "(", "err", ")", ";", "}", ")", ";", "archive", ".", "pipe", "(", "output", ")", ";", "// The mimetype file must be the first entry, and must not be compressed", "archive", ".", "append", "(", "fs", ".", "createReadStream", "(", "path", ".", "join", "(", "config", ".", "root_out", ",", "\"mimetype\"", ")", ")", ",", "{", "name", ":", "\"mimetype\"", ",", "store", ":", "true", "}", ")", ";", "archive", ".", "append", "(", "fs", ".", "createReadStream", "(", "path", ".", "join", "(", "config", ".", "root_out", ",", "\"META-INF\"", ",", "\"container.xml\"", ")", ")", ",", "{", "name", ":", "path", ".", "join", "(", "\"META-INF\"", ",", "\"container.xml\"", ")", "}", ")", ";", "archive", ".", "append", "(", "fs", ".", "createReadStream", "(", "path", ".", "join", "(", "config", ".", "root_out", ",", "config", ".", "akashacmsEPUB", ".", "bookmetadata", ".", "opf", ")", ")", ",", "{", "name", ":", "config", ".", "akashacmsEPUB", ".", "bookmetadata", ".", "opf", "}", ")", ";", "// archive.append(", "// fs.createReadStream(path.join(config.root_out, config.akashacmsEPUB.files.ncx)),", "// { name: config.akashacmsEPUB.files.ncx });", "// logger.info(util.inspect(config.akashacmsEPUB.manifest));", "async", ".", "eachSeries", "(", "config", ".", "akashacmsEPUB", ".", "manifest", ",", "function", "(", "item", ",", "next", ")", "{", "// logger.info(util.inspect(item));", "// if (item.spinetoc !== true) { // this had been used to skip the NCX file", "archive", ".", "append", "(", "fs", ".", "createReadStream", "(", "path", ".", "join", "(", "config", ".", "root_out", ",", "item", ".", "href", ")", ")", ",", "{", "name", ":", "item", ".", "href", "}", ")", ";", "// }", "next", "(", ")", ";", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "logger", ".", "error", "(", "err", ")", ";", "logger", ".", "info", "(", "'before finalize'", ")", ";", "archive", ".", "finalize", "(", ")", ";", "}", ")", ";", "}" ]
Construct the .epub file
[ "Construct", "the", ".", "epub", "file" ]
d292c9e3b8c82cc1378239485ed130022ff31bd3
https://github.com/akashacms/akashacms-epub/blob/d292c9e3b8c82cc1378239485ed130022ff31bd3/index.js#L524-L576
53,982
akashacms/akashacms-epub
index.js
function(next) { // Stylesheet and JavaScript files are listed in the config config.headerScripts.stylesheets.forEach(function(cssentry) { config.akashacmsEPUB.manifest.push({ id: cssentry.id, type: "text/css", href: rewriteURL(akasha, config, { rendered_url: config.akashacmsEPUB.bookmetadata.opf }, cssentry.href, false) // MAP this URL }); }); config.headerScripts.javaScriptTop.concat(config.headerScripts.javaScriptBottom).forEach(function(jsentry) { config.akashacmsEPUB.manifest.push({ id: jsentry.id, type: "application/javascript", href: rewriteURL(akasha, config, { rendered_url: config.akashacmsEPUB.bookmetadata.opf }, jsentry.href, false) // MAP this URL }); }); // There had formerly been a list of allowed file extensions in globfs.operate // // Turns out to have been too restrictive because those who wanted to // include other kinds of files weren't free to do so. // // The purpose here is to add manifest entries for files that aren't documents // and aren't already in the manifest for any other reason. var assetNum = 0; globfs.operate(config.root_assets.concat(config.root_docs), [ "**/*" ], function(basedir, fpath, fini) { // logger.trace('asset file '+ path.join(basedir, fpath)); fs.stat(path.join(basedir, fpath), function(err, stats) { if (err || !stats) { // Shouldn't get this, because globfs will only give us // files which exist logger.error('ERROR '+ basedir +' '+ fpath +' '+ err); fini(); } else if (stats.isDirectory()) { // Skip directories // logger.trace('isDirectory '+ basedir +' '+ fpath); fini(); } else { // logger.trace('regular file '+ basedir +' '+ fpath); akasha.readDocumentEntry(fpath, function(err, docEntry) { if (docEntry) { // If there's a docEntry, we need to override the fpath // with the filename it renders to. This is to properly // detect files that are already in the manifest. // logger.trace('docEntry '+ basedir +' '+ fpath); fpath = docEntry.renderedFileName; } // Detect any files that are already in manifest // Only add to manifest stuff which isn't already there var inManifest = false; config.akashacmsEPUB.manifest.forEach(function(item) { if (item.href === fpath) { inManifest = true; } }); if (!inManifest) { // We're not using the mime library for some // file extensions because it gives // incorrect values for the .otf and .ttf files // logger.trace('assetManifestEntries '+ basedir +' '+ fpath); var mimetype; if (fpath.match(/\.ttf$/i)) mimetype = "application/vnd.ms-opentype"; else if (fpath.match(/\.otf$/i)) mimetype = "application/vnd.ms-opentype"; else mimetype = mime.lookup(fpath); config.akashacmsEPUB.manifest.push({ id: "asset" + assetNum++, type: mimetype, href: rewriteURL(akasha, config, { rendered_url: config.akashacmsEPUB.bookmetadata.opf }, fpath, false) }); } fini(); }); } }); }, next); }
javascript
function(next) { // Stylesheet and JavaScript files are listed in the config config.headerScripts.stylesheets.forEach(function(cssentry) { config.akashacmsEPUB.manifest.push({ id: cssentry.id, type: "text/css", href: rewriteURL(akasha, config, { rendered_url: config.akashacmsEPUB.bookmetadata.opf }, cssentry.href, false) // MAP this URL }); }); config.headerScripts.javaScriptTop.concat(config.headerScripts.javaScriptBottom).forEach(function(jsentry) { config.akashacmsEPUB.manifest.push({ id: jsentry.id, type: "application/javascript", href: rewriteURL(akasha, config, { rendered_url: config.akashacmsEPUB.bookmetadata.opf }, jsentry.href, false) // MAP this URL }); }); // There had formerly been a list of allowed file extensions in globfs.operate // // Turns out to have been too restrictive because those who wanted to // include other kinds of files weren't free to do so. // // The purpose here is to add manifest entries for files that aren't documents // and aren't already in the manifest for any other reason. var assetNum = 0; globfs.operate(config.root_assets.concat(config.root_docs), [ "**/*" ], function(basedir, fpath, fini) { // logger.trace('asset file '+ path.join(basedir, fpath)); fs.stat(path.join(basedir, fpath), function(err, stats) { if (err || !stats) { // Shouldn't get this, because globfs will only give us // files which exist logger.error('ERROR '+ basedir +' '+ fpath +' '+ err); fini(); } else if (stats.isDirectory()) { // Skip directories // logger.trace('isDirectory '+ basedir +' '+ fpath); fini(); } else { // logger.trace('regular file '+ basedir +' '+ fpath); akasha.readDocumentEntry(fpath, function(err, docEntry) { if (docEntry) { // If there's a docEntry, we need to override the fpath // with the filename it renders to. This is to properly // detect files that are already in the manifest. // logger.trace('docEntry '+ basedir +' '+ fpath); fpath = docEntry.renderedFileName; } // Detect any files that are already in manifest // Only add to manifest stuff which isn't already there var inManifest = false; config.akashacmsEPUB.manifest.forEach(function(item) { if (item.href === fpath) { inManifest = true; } }); if (!inManifest) { // We're not using the mime library for some // file extensions because it gives // incorrect values for the .otf and .ttf files // logger.trace('assetManifestEntries '+ basedir +' '+ fpath); var mimetype; if (fpath.match(/\.ttf$/i)) mimetype = "application/vnd.ms-opentype"; else if (fpath.match(/\.otf$/i)) mimetype = "application/vnd.ms-opentype"; else mimetype = mime.lookup(fpath); config.akashacmsEPUB.manifest.push({ id: "asset" + assetNum++, type: mimetype, href: rewriteURL(akasha, config, { rendered_url: config.akashacmsEPUB.bookmetadata.opf }, fpath, false) }); } fini(); }); } }); }, next); }
[ "function", "(", "next", ")", "{", "// Stylesheet and JavaScript files are listed in the config", "config", ".", "headerScripts", ".", "stylesheets", ".", "forEach", "(", "function", "(", "cssentry", ")", "{", "config", ".", "akashacmsEPUB", ".", "manifest", ".", "push", "(", "{", "id", ":", "cssentry", ".", "id", ",", "type", ":", "\"text/css\"", ",", "href", ":", "rewriteURL", "(", "akasha", ",", "config", ",", "{", "rendered_url", ":", "config", ".", "akashacmsEPUB", ".", "bookmetadata", ".", "opf", "}", ",", "cssentry", ".", "href", ",", "false", ")", "// MAP this URL", "}", ")", ";", "}", ")", ";", "config", ".", "headerScripts", ".", "javaScriptTop", ".", "concat", "(", "config", ".", "headerScripts", ".", "javaScriptBottom", ")", ".", "forEach", "(", "function", "(", "jsentry", ")", "{", "config", ".", "akashacmsEPUB", ".", "manifest", ".", "push", "(", "{", "id", ":", "jsentry", ".", "id", ",", "type", ":", "\"application/javascript\"", ",", "href", ":", "rewriteURL", "(", "akasha", ",", "config", ",", "{", "rendered_url", ":", "config", ".", "akashacmsEPUB", ".", "bookmetadata", ".", "opf", "}", ",", "jsentry", ".", "href", ",", "false", ")", "// MAP this URL", "}", ")", ";", "}", ")", ";", "// There had formerly been a list of allowed file extensions in globfs.operate", "//", "// Turns out to have been too restrictive because those who wanted to", "// include other kinds of files weren't free to do so.", "//", "// The purpose here is to add manifest entries for files that aren't documents", "// and aren't already in the manifest for any other reason.", "var", "assetNum", "=", "0", ";", "globfs", ".", "operate", "(", "config", ".", "root_assets", ".", "concat", "(", "config", ".", "root_docs", ")", ",", "[", "\"**/*\"", "]", ",", "function", "(", "basedir", ",", "fpath", ",", "fini", ")", "{", "// logger.trace('asset file '+ path.join(basedir, fpath));", "fs", ".", "stat", "(", "path", ".", "join", "(", "basedir", ",", "fpath", ")", ",", "function", "(", "err", ",", "stats", ")", "{", "if", "(", "err", "||", "!", "stats", ")", "{", "// Shouldn't get this, because globfs will only give us", "// files which exist", "logger", ".", "error", "(", "'ERROR '", "+", "basedir", "+", "' '", "+", "fpath", "+", "' '", "+", "err", ")", ";", "fini", "(", ")", ";", "}", "else", "if", "(", "stats", ".", "isDirectory", "(", ")", ")", "{", "// Skip directories", "// logger.trace('isDirectory '+ basedir +' '+ fpath);", "fini", "(", ")", ";", "}", "else", "{", "// logger.trace('regular file '+ basedir +' '+ fpath);", "akasha", ".", "readDocumentEntry", "(", "fpath", ",", "function", "(", "err", ",", "docEntry", ")", "{", "if", "(", "docEntry", ")", "{", "// If there's a docEntry, we need to override the fpath", "// with the filename it renders to. This is to properly", "// detect files that are already in the manifest.", "// logger.trace('docEntry '+ basedir +' '+ fpath);", "fpath", "=", "docEntry", ".", "renderedFileName", ";", "}", "// Detect any files that are already in manifest", "// Only add to manifest stuff which isn't already there", "var", "inManifest", "=", "false", ";", "config", ".", "akashacmsEPUB", ".", "manifest", ".", "forEach", "(", "function", "(", "item", ")", "{", "if", "(", "item", ".", "href", "===", "fpath", ")", "{", "inManifest", "=", "true", ";", "}", "}", ")", ";", "if", "(", "!", "inManifest", ")", "{", "// We're not using the mime library for some", "// file extensions because it gives", "// incorrect values for the .otf and .ttf files", "// logger.trace('assetManifestEntries '+ basedir +' '+ fpath);", "var", "mimetype", ";", "if", "(", "fpath", ".", "match", "(", "/", "\\.ttf$", "/", "i", ")", ")", "mimetype", "=", "\"application/vnd.ms-opentype\"", ";", "else", "if", "(", "fpath", ".", "match", "(", "/", "\\.otf$", "/", "i", ")", ")", "mimetype", "=", "\"application/vnd.ms-opentype\"", ";", "else", "mimetype", "=", "mime", ".", "lookup", "(", "fpath", ")", ";", "config", ".", "akashacmsEPUB", ".", "manifest", ".", "push", "(", "{", "id", ":", "\"asset\"", "+", "assetNum", "++", ",", "type", ":", "mimetype", ",", "href", ":", "rewriteURL", "(", "akasha", ",", "config", ",", "{", "rendered_url", ":", "config", ".", "akashacmsEPUB", ".", "bookmetadata", ".", "opf", "}", ",", "fpath", ",", "false", ")", "}", ")", ";", "}", "fini", "(", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}", ",", "next", ")", ";", "}" ]
fill in manifest entries for asset files
[ "fill", "in", "manifest", "entries", "for", "asset", "files" ]
d292c9e3b8c82cc1378239485ed130022ff31bd3
https://github.com/akashacms/akashacms-epub/blob/d292c9e3b8c82cc1378239485ed130022ff31bd3/index.js#L823-L912
53,983
unkhz/almost-static-site
main/directives/fixContainerHeight.js
waitAndSet
function waitAndSet() { var i; var times = [0,200,400,700,1000,1500,2000]; var len = times.length; for ( i = 0; i < len; i++ ) { $timeout(setParentHeight,times[i]); } }
javascript
function waitAndSet() { var i; var times = [0,200,400,700,1000,1500,2000]; var len = times.length; for ( i = 0; i < len; i++ ) { $timeout(setParentHeight,times[i]); } }
[ "function", "waitAndSet", "(", ")", "{", "var", "i", ";", "var", "times", "=", "[", "0", ",", "200", ",", "400", ",", "700", ",", "1000", ",", "1500", ",", "2000", "]", ";", "var", "len", "=", "times", ".", "length", ";", "for", "(", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "$timeout", "(", "setParentHeight", ",", "times", "[", "i", "]", ")", ";", "}", "}" ]
Wait for the content to be appended and set parent height
[ "Wait", "for", "the", "content", "to", "be", "appended", "and", "set", "parent", "height" ]
cd09f02ffec06ee2c7494a76ef9a545dbdb58653
https://github.com/unkhz/almost-static-site/blob/cd09f02ffec06ee2c7494a76ef9a545dbdb58653/main/directives/fixContainerHeight.js#L20-L27
53,984
aerobatic/grunt-aerobatic
tasks/lib/simulator.js
uploadIndexPages
function uploadIndexPages(pagePaths, config, options, callback) { var requestOptions = { method: 'POST', url: options.airport + '/dev/' + config.appId + '/simulator', form: {} }; // Attach the files as multi-part var request = api(config, requestOptions, callback); var form = request.form(); pagePaths.forEach(function(pagePath) { grunt.log.debug("Uploading " + pagePath); form.append(path.basename(pagePath, '.html'), fs.createReadStream(pagePath)); }); }
javascript
function uploadIndexPages(pagePaths, config, options, callback) { var requestOptions = { method: 'POST', url: options.airport + '/dev/' + config.appId + '/simulator', form: {} }; // Attach the files as multi-part var request = api(config, requestOptions, callback); var form = request.form(); pagePaths.forEach(function(pagePath) { grunt.log.debug("Uploading " + pagePath); form.append(path.basename(pagePath, '.html'), fs.createReadStream(pagePath)); }); }
[ "function", "uploadIndexPages", "(", "pagePaths", ",", "config", ",", "options", ",", "callback", ")", "{", "var", "requestOptions", "=", "{", "method", ":", "'POST'", ",", "url", ":", "options", ".", "airport", "+", "'/dev/'", "+", "config", ".", "appId", "+", "'/simulator'", ",", "form", ":", "{", "}", "}", ";", "// Attach the files as multi-part", "var", "request", "=", "api", "(", "config", ",", "requestOptions", ",", "callback", ")", ";", "var", "form", "=", "request", ".", "form", "(", ")", ";", "pagePaths", ".", "forEach", "(", "function", "(", "pagePath", ")", "{", "grunt", ".", "log", ".", "debug", "(", "\"Uploading \"", "+", "pagePath", ")", ";", "form", ".", "append", "(", "path", ".", "basename", "(", "pagePath", ",", "'.html'", ")", ",", "fs", ".", "createReadStream", "(", "pagePath", ")", ")", ";", "}", ")", ";", "}" ]
Upload the indexx.html file to the server.
[ "Upload", "the", "indexx", ".", "html", "file", "to", "the", "server", "." ]
a1788d1889186b78b7f7d09e53c811fb664b621c
https://github.com/aerobatic/grunt-aerobatic/blob/a1788d1889186b78b7f7d09e53c811fb664b621c/tasks/lib/simulator.js#L18-L33
53,985
anandthakker/css-rule-stream
lib/match.js
write
function write(token, enc, next) { var type = token[0], buf = token[1]; if(('rule_start' === type || 'atrule_start' === type)) depth++; if(depth > 0 && !current) current = {location: [line, column], buffers:[]}; if('rule_end' === type || 'atrule_end' === type) depth--; if(current) { current.buffers.push(buf); if(depth === 0) pushRule.call(this); } updatePosition(buf); next(); }
javascript
function write(token, enc, next) { var type = token[0], buf = token[1]; if(('rule_start' === type || 'atrule_start' === type)) depth++; if(depth > 0 && !current) current = {location: [line, column], buffers:[]}; if('rule_end' === type || 'atrule_end' === type) depth--; if(current) { current.buffers.push(buf); if(depth === 0) pushRule.call(this); } updatePosition(buf); next(); }
[ "function", "write", "(", "token", ",", "enc", ",", "next", ")", "{", "var", "type", "=", "token", "[", "0", "]", ",", "buf", "=", "token", "[", "1", "]", ";", "if", "(", "(", "'rule_start'", "===", "type", "||", "'atrule_start'", "===", "type", ")", ")", "depth", "++", ";", "if", "(", "depth", ">", "0", "&&", "!", "current", ")", "current", "=", "{", "location", ":", "[", "line", ",", "column", "]", ",", "buffers", ":", "[", "]", "}", ";", "if", "(", "'rule_end'", "===", "type", "||", "'atrule_end'", "===", "type", ")", "depth", "--", ";", "if", "(", "current", ")", "{", "current", ".", "buffers", ".", "push", "(", "buf", ")", ";", "if", "(", "depth", "===", "0", ")", "pushRule", ".", "call", "(", "this", ")", ";", "}", "updatePosition", "(", "buf", ")", ";", "next", "(", ")", ";", "}" ]
track this and pass it downstream for source mapping.
[ "track", "this", "and", "pass", "it", "downstream", "for", "source", "mapping", "." ]
3797400bfbe4df660690858254b953607a5fe7f3
https://github.com/anandthakker/css-rule-stream/blob/3797400bfbe4df660690858254b953607a5fe7f3/lib/match.js#L13-L30
53,986
Augmentedjs/next-core-model
dist/core-next-model.js
createPartial
function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & BIND_FLAG, Ctor = createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = this && this !== root && this instanceof wrapper ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return apply(fn, isBind ? thisArg : this, args); } return wrapper; }
javascript
function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & BIND_FLAG, Ctor = createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = this && this !== root && this instanceof wrapper ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return apply(fn, isBind ? thisArg : this, args); } return wrapper; }
[ "function", "createPartial", "(", "func", ",", "bitmask", ",", "thisArg", ",", "partials", ")", "{", "var", "isBind", "=", "bitmask", "&", "BIND_FLAG", ",", "Ctor", "=", "createCtor", "(", "func", ")", ";", "function", "wrapper", "(", ")", "{", "var", "argsIndex", "=", "-", "1", ",", "argsLength", "=", "arguments", ".", "length", ",", "leftIndex", "=", "-", "1", ",", "leftLength", "=", "partials", ".", "length", ",", "args", "=", "Array", "(", "leftLength", "+", "argsLength", ")", ",", "fn", "=", "this", "&&", "this", "!==", "root", "&&", "this", "instanceof", "wrapper", "?", "Ctor", ":", "func", ";", "while", "(", "++", "leftIndex", "<", "leftLength", ")", "{", "args", "[", "leftIndex", "]", "=", "partials", "[", "leftIndex", "]", ";", "}", "while", "(", "argsLength", "--", ")", "{", "args", "[", "leftIndex", "++", "]", "=", "arguments", "[", "++", "argsIndex", "]", ";", "}", "return", "apply", "(", "fn", ",", "isBind", "?", "thisArg", ":", "this", ",", "args", ")", ";", "}", "return", "wrapper", ";", "}" ]
Creates a function that wraps `func` to invoke it with the `this` binding of `thisArg` and `partials` prepended to the arguments it receives. @private @param {Function} func The function to wrap. @param {number} bitmask The bitmask flags. See `createWrap` for more details. @param {*} thisArg The `this` binding of `func`. @param {Array} partials The arguments to prepend to those provided to the new function. @returns {Function} Returns the new wrapped function.
[ "Creates", "a", "function", "that", "wraps", "func", "to", "invoke", "it", "with", "the", "this", "binding", "of", "thisArg", "and", "partials", "prepended", "to", "the", "arguments", "it", "receives", "." ]
9a702a1c64021a79a8988f903df85baa72d389b8
https://github.com/Augmentedjs/next-core-model/blob/9a702a1c64021a79a8988f903df85baa72d389b8/dist/core-next-model.js#L753-L774
53,987
femto113/node-ec2-instance-data
index.js
deep_set
function deep_set(root, path, value) { var twig = root; path.split('/').forEach(function (branch, index, branches) { if (branch) { if (self.camelize) { branch = branch.replace(/(\-([a-z]))/g, function (m) { return m[1].toUpperCase(); }) } if (index < branches.length - 1) { twig = twig[branch] || (twig[branch] = {}); } else { // optimistically try treating the value as JSON try { twig[branch] = JSON.parse(value); } catch (e) { twig[branch] = value; } } } }); }
javascript
function deep_set(root, path, value) { var twig = root; path.split('/').forEach(function (branch, index, branches) { if (branch) { if (self.camelize) { branch = branch.replace(/(\-([a-z]))/g, function (m) { return m[1].toUpperCase(); }) } if (index < branches.length - 1) { twig = twig[branch] || (twig[branch] = {}); } else { // optimistically try treating the value as JSON try { twig[branch] = JSON.parse(value); } catch (e) { twig[branch] = value; } } } }); }
[ "function", "deep_set", "(", "root", ",", "path", ",", "value", ")", "{", "var", "twig", "=", "root", ";", "path", ".", "split", "(", "'/'", ")", ".", "forEach", "(", "function", "(", "branch", ",", "index", ",", "branches", ")", "{", "if", "(", "branch", ")", "{", "if", "(", "self", ".", "camelize", ")", "{", "branch", "=", "branch", ".", "replace", "(", "/", "(\\-([a-z]))", "/", "g", ",", "function", "(", "m", ")", "{", "return", "m", "[", "1", "]", ".", "toUpperCase", "(", ")", ";", "}", ")", "}", "if", "(", "index", "<", "branches", ".", "length", "-", "1", ")", "{", "twig", "=", "twig", "[", "branch", "]", "||", "(", "twig", "[", "branch", "]", "=", "{", "}", ")", ";", "}", "else", "{", "// optimistically try treating the value as JSON", "try", "{", "twig", "[", "branch", "]", "=", "JSON", ".", "parse", "(", "value", ")", ";", "}", "catch", "(", "e", ")", "{", "twig", "[", "branch", "]", "=", "value", ";", "}", "}", "}", "}", ")", ";", "}" ]
helper to turn a set of paths into nested objects
[ "helper", "to", "turn", "a", "set", "of", "paths", "into", "nested", "objects" ]
0b7f297c2ec13b095706f151a5ab46a4bf17ffb5
https://github.com/femto113/node-ec2-instance-data/blob/0b7f297c2ec13b095706f151a5ab46a4bf17ffb5/index.js#L81-L100
53,988
femto113/node-ec2-instance-data
index.js
deep_get
function deep_get(root, path) { var twig = root, result = undefined; path.split('/').forEach(function (branch, index, branches) { if (branch) { if (self.camelize) { branch = branch.replace(/(\-([a-z]))/g, function (m) { return m[1].toUpperCase(); }) } if (index < branches.length - 1) { twig = twig[branch]; } else { result = twig && twig[branch]; } } }); return result; }
javascript
function deep_get(root, path) { var twig = root, result = undefined; path.split('/').forEach(function (branch, index, branches) { if (branch) { if (self.camelize) { branch = branch.replace(/(\-([a-z]))/g, function (m) { return m[1].toUpperCase(); }) } if (index < branches.length - 1) { twig = twig[branch]; } else { result = twig && twig[branch]; } } }); return result; }
[ "function", "deep_get", "(", "root", ",", "path", ")", "{", "var", "twig", "=", "root", ",", "result", "=", "undefined", ";", "path", ".", "split", "(", "'/'", ")", ".", "forEach", "(", "function", "(", "branch", ",", "index", ",", "branches", ")", "{", "if", "(", "branch", ")", "{", "if", "(", "self", ".", "camelize", ")", "{", "branch", "=", "branch", ".", "replace", "(", "/", "(\\-([a-z]))", "/", "g", ",", "function", "(", "m", ")", "{", "return", "m", "[", "1", "]", ".", "toUpperCase", "(", ")", ";", "}", ")", "}", "if", "(", "index", "<", "branches", ".", "length", "-", "1", ")", "{", "twig", "=", "twig", "[", "branch", "]", ";", "}", "else", "{", "result", "=", "twig", "&&", "twig", "[", "branch", "]", ";", "}", "}", "}", ")", ";", "return", "result", ";", "}" ]
sort of inverse of above, get a nested object value from a path
[ "sort", "of", "inverse", "of", "above", "get", "a", "nested", "object", "value", "from", "a", "path" ]
0b7f297c2ec13b095706f151a5ab46a4bf17ffb5
https://github.com/femto113/node-ec2-instance-data/blob/0b7f297c2ec13b095706f151a5ab46a4bf17ffb5/index.js#L103-L118
53,989
femto113/node-ec2-instance-data
index.js
parse_date_strings
function parse_date_strings(root) { for (key in root) { if (!root.hasOwnProperty(key)) continue; var value = root[key]; if (typeof(value) === 'object') { parse_date_strings(value); } else if (typeof(value) === 'string' && /\d{4}-?\d{2}-?\d{2}(T?\d{2}:?\d{2}:?\d{2}(Z)?)?/.test(value)) { var timestamp = Date.parse(value); if (!isNaN(timestamp)) { root[key] = new Date(timestamp); } } } }
javascript
function parse_date_strings(root) { for (key in root) { if (!root.hasOwnProperty(key)) continue; var value = root[key]; if (typeof(value) === 'object') { parse_date_strings(value); } else if (typeof(value) === 'string' && /\d{4}-?\d{2}-?\d{2}(T?\d{2}:?\d{2}:?\d{2}(Z)?)?/.test(value)) { var timestamp = Date.parse(value); if (!isNaN(timestamp)) { root[key] = new Date(timestamp); } } } }
[ "function", "parse_date_strings", "(", "root", ")", "{", "for", "(", "key", "in", "root", ")", "{", "if", "(", "!", "root", ".", "hasOwnProperty", "(", "key", ")", ")", "continue", ";", "var", "value", "=", "root", "[", "key", "]", ";", "if", "(", "typeof", "(", "value", ")", "===", "'object'", ")", "{", "parse_date_strings", "(", "value", ")", ";", "}", "else", "if", "(", "typeof", "(", "value", ")", "===", "'string'", "&&", "/", "\\d{4}-?\\d{2}-?\\d{2}(T?\\d{2}:?\\d{2}:?\\d{2}(Z)?)?", "/", ".", "test", "(", "value", ")", ")", "{", "var", "timestamp", "=", "Date", ".", "parse", "(", "value", ")", ";", "if", "(", "!", "isNaN", "(", "timestamp", ")", ")", "{", "root", "[", "key", "]", "=", "new", "Date", "(", "timestamp", ")", ";", "}", "}", "}", "}" ]
helper to recursively parse all date strings into Date objects
[ "helper", "to", "recursively", "parse", "all", "date", "strings", "into", "Date", "objects" ]
0b7f297c2ec13b095706f151a5ab46a4bf17ffb5
https://github.com/femto113/node-ec2-instance-data/blob/0b7f297c2ec13b095706f151a5ab46a4bf17ffb5/index.js#L121-L134
53,990
MechanicalHuman/hnp-utilities
packages/commitizen-adapter/lib/commitizen-adapter.js
getChoices
function getChoices() { const name = choice => fp.padStart(MAX_DESC)(choice.value) const desc = choice => wrap(choice.description, MAX) return types.map(choice => { if (choice.value === 'separator') return SEPARATOR return { name: `${name(choice)} ${choice.emoji} ${desc(choice)}`, value: choice.value, short: name(choice) } }) }
javascript
function getChoices() { const name = choice => fp.padStart(MAX_DESC)(choice.value) const desc = choice => wrap(choice.description, MAX) return types.map(choice => { if (choice.value === 'separator') return SEPARATOR return { name: `${name(choice)} ${choice.emoji} ${desc(choice)}`, value: choice.value, short: name(choice) } }) }
[ "function", "getChoices", "(", ")", "{", "const", "name", "=", "choice", "=>", "fp", ".", "padStart", "(", "MAX_DESC", ")", "(", "choice", ".", "value", ")", "const", "desc", "=", "choice", "=>", "wrap", "(", "choice", ".", "description", ",", "MAX", ")", "return", "types", ".", "map", "(", "choice", "=>", "{", "if", "(", "choice", ".", "value", "===", "'separator'", ")", "return", "SEPARATOR", "return", "{", "name", ":", "`", "${", "name", "(", "choice", ")", "}", "${", "choice", ".", "emoji", "}", "${", "desc", "(", "choice", ")", "}", "`", ",", "value", ":", "choice", ".", "value", ",", "short", ":", "name", "(", "choice", ")", "}", "}", ")", "}" ]
Parses the types to create a pretty choice
[ "Parses", "the", "types", "to", "create", "a", "pretty", "choice" ]
7c2893be5b5ca4d8c6afb1d5838811de9a720424
https://github.com/MechanicalHuman/hnp-utilities/blob/7c2893be5b5ca4d8c6afb1d5838811de9a720424/packages/commitizen-adapter/lib/commitizen-adapter.js#L69-L80
53,991
anoopchaurasia/jsfm
jsfm.js
createObj
function createObj( str ) { if (!str || str.length == 0) { return window; } var d = str.split("."), j, o = window; for (j = 0; j < d.length; j = j + 1) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } return o; }
javascript
function createObj( str ) { if (!str || str.length == 0) { return window; } var d = str.split("."), j, o = window; for (j = 0; j < d.length; j = j + 1) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } return o; }
[ "function", "createObj", "(", "str", ")", "{", "if", "(", "!", "str", "||", "str", ".", "length", "==", "0", ")", "{", "return", "window", ";", "}", "var", "d", "=", "str", ".", "split", "(", "\".\"", ")", ",", "j", ",", "o", "=", "window", ";", "for", "(", "j", "=", "0", ";", "j", "<", "d", ".", "length", ";", "j", "=", "j", "+", "1", ")", "{", "o", "[", "d", "[", "j", "]", "]", "=", "o", "[", "d", "[", "j", "]", "]", "||", "{", "}", ";", "o", "=", "o", "[", "d", "[", "j", "]", "]", ";", "}", "return", "o", ";", "}" ]
Map string to corresponding object.
[ "Map", "string", "to", "corresponding", "object", "." ]
20ca3bd7417008c331285237e64b106c30887e36
https://github.com/anoopchaurasia/jsfm/blob/20ca3bd7417008c331285237e64b106c30887e36/jsfm.js#L25-L35
53,992
anoopchaurasia/jsfm
jsfm.js
addPrototypeBeforeCall
function addPrototypeBeforeCall( Class, isAbstract ) { var constStatic = {}, currentState = { Static: window.Static, Abstract: window.Abstract, Const: window.Const, Private: window.Private }; saveState.push(currentState); window.Static = Class.prototype.Static = {Const:constStatic}; window.Abstract = Class.prototype.Abstract = isAbstract ? {} : undefined; window.Const = Class.prototype.Const = {Static:constStatic}; window.Private = Class.prototype.Private = {}; }
javascript
function addPrototypeBeforeCall( Class, isAbstract ) { var constStatic = {}, currentState = { Static: window.Static, Abstract: window.Abstract, Const: window.Const, Private: window.Private }; saveState.push(currentState); window.Static = Class.prototype.Static = {Const:constStatic}; window.Abstract = Class.prototype.Abstract = isAbstract ? {} : undefined; window.Const = Class.prototype.Const = {Static:constStatic}; window.Private = Class.prototype.Private = {}; }
[ "function", "addPrototypeBeforeCall", "(", "Class", ",", "isAbstract", ")", "{", "var", "constStatic", "=", "{", "}", ",", "currentState", "=", "{", "Static", ":", "window", ".", "Static", ",", "Abstract", ":", "window", ".", "Abstract", ",", "Const", ":", "window", ".", "Const", ",", "Private", ":", "window", ".", "Private", "}", ";", "saveState", ".", "push", "(", "currentState", ")", ";", "window", ".", "Static", "=", "Class", ".", "prototype", ".", "Static", "=", "{", "Const", ":", "constStatic", "}", ";", "window", ".", "Abstract", "=", "Class", ".", "prototype", ".", "Abstract", "=", "isAbstract", "?", "{", "}", ":", "undefined", ";", "window", ".", "Const", "=", "Class", ".", "prototype", ".", "Const", "=", "{", "Static", ":", "constStatic", "}", ";", "window", ".", "Private", "=", "Class", ".", "prototype", ".", "Private", "=", "{", "}", ";", "}" ]
Add information before calling the class.
[ "Add", "information", "before", "calling", "the", "class", "." ]
20ca3bd7417008c331285237e64b106c30887e36
https://github.com/anoopchaurasia/jsfm/blob/20ca3bd7417008c331285237e64b106c30887e36/jsfm.js#L68-L81
53,993
anoopchaurasia/jsfm
jsfm.js
deleteAddedProtoTypes
function deleteAddedProtoTypes( Class ) { delete Class.prototype.Static; delete Class.prototype.Const; delete Class.prototype.Private; delete Class.prototype.Abstract; var currentState = saveState.pop(); window.Private = currentState.Private; window.Const = currentState.Const; window.Abstract = currentState.Abstract; window.Static = currentState.Static; }
javascript
function deleteAddedProtoTypes( Class ) { delete Class.prototype.Static; delete Class.prototype.Const; delete Class.prototype.Private; delete Class.prototype.Abstract; var currentState = saveState.pop(); window.Private = currentState.Private; window.Const = currentState.Const; window.Abstract = currentState.Abstract; window.Static = currentState.Static; }
[ "function", "deleteAddedProtoTypes", "(", "Class", ")", "{", "delete", "Class", ".", "prototype", ".", "Static", ";", "delete", "Class", ".", "prototype", ".", "Const", ";", "delete", "Class", ".", "prototype", ".", "Private", ";", "delete", "Class", ".", "prototype", ".", "Abstract", ";", "var", "currentState", "=", "saveState", ".", "pop", "(", ")", ";", "window", ".", "Private", "=", "currentState", ".", "Private", ";", "window", ".", "Const", "=", "currentState", ".", "Const", ";", "window", ".", "Abstract", "=", "currentState", ".", "Abstract", ";", "window", ".", "Static", "=", "currentState", ".", "Static", ";", "}" ]
Delete all added information after call.
[ "Delete", "all", "added", "information", "after", "call", "." ]
20ca3bd7417008c331285237e64b106c30887e36
https://github.com/anoopchaurasia/jsfm/blob/20ca3bd7417008c331285237e64b106c30887e36/jsfm.js#L84-L96
53,994
anoopchaurasia/jsfm
jsfm.js
simpleExtend
function simpleExtend( from, to ) { for ( var k in from) { if (to[k] == undefined) { to[k] = from[k]; } } return to; }
javascript
function simpleExtend( from, to ) { for ( var k in from) { if (to[k] == undefined) { to[k] = from[k]; } } return to; }
[ "function", "simpleExtend", "(", "from", ",", "to", ")", "{", "for", "(", "var", "k", "in", "from", ")", "{", "if", "(", "to", "[", "k", "]", "==", "undefined", ")", "{", "to", "[", "k", "]", "=", "from", "[", "k", "]", ";", "}", "}", "return", "to", ";", "}" ]
Extend to one level.
[ "Extend", "to", "one", "level", "." ]
20ca3bd7417008c331285237e64b106c30887e36
https://github.com/anoopchaurasia/jsfm/blob/20ca3bd7417008c331285237e64b106c30887e36/jsfm.js#L99-L106
53,995
anoopchaurasia/jsfm
jsfm.js
addAddedFileInnScript
function addAddedFileInnScript(key, path, dot_path){ dot_path = dot_path || path; // checking if same file imported twice for same Class. if(!dot_path) return; var script = scriptArr[scriptArr.length - 1]; if( !script ){ return; } var arr = script[key] || (script[key] = []); if( arr.indexOf(dot_path) === -1 ) { arr.push(dot_path); } return true; }
javascript
function addAddedFileInnScript(key, path, dot_path){ dot_path = dot_path || path; // checking if same file imported twice for same Class. if(!dot_path) return; var script = scriptArr[scriptArr.length - 1]; if( !script ){ return; } var arr = script[key] || (script[key] = []); if( arr.indexOf(dot_path) === -1 ) { arr.push(dot_path); } return true; }
[ "function", "addAddedFileInnScript", "(", "key", ",", "path", ",", "dot_path", ")", "{", "dot_path", "=", "dot_path", "||", "path", ";", "// checking if same file imported twice for same Class.", "if", "(", "!", "dot_path", ")", "return", ";", "var", "script", "=", "scriptArr", "[", "scriptArr", ".", "length", "-", "1", "]", ";", "if", "(", "!", "script", ")", "{", "return", ";", "}", "var", "arr", "=", "script", "[", "key", "]", "||", "(", "script", "[", "key", "]", "=", "[", "]", ")", ";", "if", "(", "arr", ".", "indexOf", "(", "dot_path", ")", "===", "-", "1", ")", "{", "arr", ".", "push", "(", "dot_path", ")", ";", "}", "return", "true", ";", "}" ]
Add imports for current loaded javascript file. Add imported javascript file for current class into scriptArr.
[ "Add", "imports", "for", "current", "loaded", "javascript", "file", ".", "Add", "imported", "javascript", "file", "for", "current", "class", "into", "scriptArr", "." ]
20ca3bd7417008c331285237e64b106c30887e36
https://github.com/anoopchaurasia/jsfm/blob/20ca3bd7417008c331285237e64b106c30887e36/jsfm.js#L244-L257
53,996
anoopchaurasia/jsfm
jsfm.js
include
function include( path, isFromInclude, dot_path ) { if(!path){ return; } all_paths.push(path) if(isNode){ require(path); listenFileChange(path); if(isFromInclude){ fileLoadeManager.iamready(dot_path); } return; } if (fm.isConcatinated) { fileLoadeManager.iamready(dot_path); return; } if (!docHead) { docHead = document.getElementsByTagName("head")[0]; } // isNonfm && fm.holdReady(true); var e = document.createElement("script"); // onerror is not supported by IE so this will throw exception only for // non IE browsers. if(me.version){ path += "?v=" + me.version; } e.onerror = onFileLoadError; if(isFromInclude){ e.onload = function(){ fileLoadeManager.iamready(dot_path); $(document).trigger('jsfm-iamready-'+ path.split("/").pop().replace(".js", ""), [path]); }; } e.src = path; e.type = "text/javascript"; docHead.appendChild(e); }
javascript
function include( path, isFromInclude, dot_path ) { if(!path){ return; } all_paths.push(path) if(isNode){ require(path); listenFileChange(path); if(isFromInclude){ fileLoadeManager.iamready(dot_path); } return; } if (fm.isConcatinated) { fileLoadeManager.iamready(dot_path); return; } if (!docHead) { docHead = document.getElementsByTagName("head")[0]; } // isNonfm && fm.holdReady(true); var e = document.createElement("script"); // onerror is not supported by IE so this will throw exception only for // non IE browsers. if(me.version){ path += "?v=" + me.version; } e.onerror = onFileLoadError; if(isFromInclude){ e.onload = function(){ fileLoadeManager.iamready(dot_path); $(document).trigger('jsfm-iamready-'+ path.split("/").pop().replace(".js", ""), [path]); }; } e.src = path; e.type = "text/javascript"; docHead.appendChild(e); }
[ "function", "include", "(", "path", ",", "isFromInclude", ",", "dot_path", ")", "{", "if", "(", "!", "path", ")", "{", "return", ";", "}", "all_paths", ".", "push", "(", "path", ")", "if", "(", "isNode", ")", "{", "require", "(", "path", ")", ";", "listenFileChange", "(", "path", ")", ";", "if", "(", "isFromInclude", ")", "{", "fileLoadeManager", ".", "iamready", "(", "dot_path", ")", ";", "}", "return", ";", "}", "if", "(", "fm", ".", "isConcatinated", ")", "{", "fileLoadeManager", ".", "iamready", "(", "dot_path", ")", ";", "return", ";", "}", "if", "(", "!", "docHead", ")", "{", "docHead", "=", "document", ".", "getElementsByTagName", "(", "\"head\"", ")", "[", "0", "]", ";", "}", "// isNonfm && fm.holdReady(true);", "var", "e", "=", "document", ".", "createElement", "(", "\"script\"", ")", ";", "// onerror is not supported by IE so this will throw exception only for", "// non IE browsers.", "if", "(", "me", ".", "version", ")", "{", "path", "+=", "\"?v=\"", "+", "me", ".", "version", ";", "}", "e", ".", "onerror", "=", "onFileLoadError", ";", "if", "(", "isFromInclude", ")", "{", "e", ".", "onload", "=", "function", "(", ")", "{", "fileLoadeManager", ".", "iamready", "(", "dot_path", ")", ";", "$", "(", "document", ")", ".", "trigger", "(", "'jsfm-iamready-'", "+", "path", ".", "split", "(", "\"/\"", ")", ".", "pop", "(", ")", ".", "replace", "(", "\".js\"", ",", "\"\"", ")", ",", "[", "path", "]", ")", ";", "}", ";", "}", "e", ".", "src", "=", "path", ";", "e", ".", "type", "=", "\"text/javascript\"", ";", "docHead", ".", "appendChild", "(", "e", ")", ";", "}" ]
Create script tag inside head.
[ "Create", "script", "tag", "inside", "head", "." ]
20ca3bd7417008c331285237e64b106c30887e36
https://github.com/anoopchaurasia/jsfm/blob/20ca3bd7417008c331285237e64b106c30887e36/jsfm.js#L276-L317
53,997
anoopchaurasia/jsfm
jsfm.js
getReleventClassInfo
function getReleventClassInfo( Class, fn, pofn ) { /// this is script addPrototypeBeforeCall(Class, this.isAbstract); var tempObj, k, len; tempObj = invoke(Class, this.args, pofn.base, this.ics, this.Package, pofn); tempObj.setMe && tempObj.setMe(pofn); tempObj.base = pofn.base; delete tempObj.setMe; this.shortHand = tempObj.shortHand || this.shortHand; var info = separeteMethodsAndFields(tempObj); this.methods = info.methods = pofn.base ? info.methods.concat(pofn.base.prototype.$get('methods')) : info.methods; if (this.isInterface) { pofn.base && simpleExtend(pofn.base.prototype.$get('fields'), info.fields); this.fields = info.fields; checkMandSetF(pofn); deleteAddedProtoTypes(Class); return this; } if (tempObj.init){ tempObj.init(); } this.isAbstract && checkForAbstractFields(tempObj.Abstract, this.Class); this.Static = simpleExtend(tempObj.Static, {}); this.isAbstract && (this.Abstract = simpleExtend(tempObj.Abstract, {})); this.staticConst = this.Static.Const; delete this.Static.Const; this.Const = simpleExtend(tempObj.Const, {}); delete this.Const.Static; checkAvailability(tempObj, this.Static, this.staticConst, this.Abstract, this.Const); addTransient(this, tempObj); this.privateConstructor = !!tempObj["Private"] && tempObj["Private"][fn]; deleteAddedProtoTypes(Class); var plugins = this.plugins, pp; //add plugin as extensin for(var p in plugins) { if(plugins.hasOwnProperty(p)) { pp = fm.isExist(plugins[p]); simpleExtend(pp.prototype.$get("Static"), this.Static); simpleExtend(pp.prototype.$get("staticConst"), this.staticConst); } } var temp = this.interfaces; if (temp) { for (k = 0, len = temp.length; k < len; k++) { createObj(temp[k]).prototype.$checkMAndGetF(pofn, info.methods, this.isAbstract, tempObj, this); } } temp = k = tempObj = info = Class = fn = undefined; }
javascript
function getReleventClassInfo( Class, fn, pofn ) { /// this is script addPrototypeBeforeCall(Class, this.isAbstract); var tempObj, k, len; tempObj = invoke(Class, this.args, pofn.base, this.ics, this.Package, pofn); tempObj.setMe && tempObj.setMe(pofn); tempObj.base = pofn.base; delete tempObj.setMe; this.shortHand = tempObj.shortHand || this.shortHand; var info = separeteMethodsAndFields(tempObj); this.methods = info.methods = pofn.base ? info.methods.concat(pofn.base.prototype.$get('methods')) : info.methods; if (this.isInterface) { pofn.base && simpleExtend(pofn.base.prototype.$get('fields'), info.fields); this.fields = info.fields; checkMandSetF(pofn); deleteAddedProtoTypes(Class); return this; } if (tempObj.init){ tempObj.init(); } this.isAbstract && checkForAbstractFields(tempObj.Abstract, this.Class); this.Static = simpleExtend(tempObj.Static, {}); this.isAbstract && (this.Abstract = simpleExtend(tempObj.Abstract, {})); this.staticConst = this.Static.Const; delete this.Static.Const; this.Const = simpleExtend(tempObj.Const, {}); delete this.Const.Static; checkAvailability(tempObj, this.Static, this.staticConst, this.Abstract, this.Const); addTransient(this, tempObj); this.privateConstructor = !!tempObj["Private"] && tempObj["Private"][fn]; deleteAddedProtoTypes(Class); var plugins = this.plugins, pp; //add plugin as extensin for(var p in plugins) { if(plugins.hasOwnProperty(p)) { pp = fm.isExist(plugins[p]); simpleExtend(pp.prototype.$get("Static"), this.Static); simpleExtend(pp.prototype.$get("staticConst"), this.staticConst); } } var temp = this.interfaces; if (temp) { for (k = 0, len = temp.length; k < len; k++) { createObj(temp[k]).prototype.$checkMAndGetF(pofn, info.methods, this.isAbstract, tempObj, this); } } temp = k = tempObj = info = Class = fn = undefined; }
[ "function", "getReleventClassInfo", "(", "Class", ",", "fn", ",", "pofn", ")", "{", "/// this is script", "addPrototypeBeforeCall", "(", "Class", ",", "this", ".", "isAbstract", ")", ";", "var", "tempObj", ",", "k", ",", "len", ";", "tempObj", "=", "invoke", "(", "Class", ",", "this", ".", "args", ",", "pofn", ".", "base", ",", "this", ".", "ics", ",", "this", ".", "Package", ",", "pofn", ")", ";", "tempObj", ".", "setMe", "&&", "tempObj", ".", "setMe", "(", "pofn", ")", ";", "tempObj", ".", "base", "=", "pofn", ".", "base", ";", "delete", "tempObj", ".", "setMe", ";", "this", ".", "shortHand", "=", "tempObj", ".", "shortHand", "||", "this", ".", "shortHand", ";", "var", "info", "=", "separeteMethodsAndFields", "(", "tempObj", ")", ";", "this", ".", "methods", "=", "info", ".", "methods", "=", "pofn", ".", "base", "?", "info", ".", "methods", ".", "concat", "(", "pofn", ".", "base", ".", "prototype", ".", "$get", "(", "'methods'", ")", ")", ":", "info", ".", "methods", ";", "if", "(", "this", ".", "isInterface", ")", "{", "pofn", ".", "base", "&&", "simpleExtend", "(", "pofn", ".", "base", ".", "prototype", ".", "$get", "(", "'fields'", ")", ",", "info", ".", "fields", ")", ";", "this", ".", "fields", "=", "info", ".", "fields", ";", "checkMandSetF", "(", "pofn", ")", ";", "deleteAddedProtoTypes", "(", "Class", ")", ";", "return", "this", ";", "}", "if", "(", "tempObj", ".", "init", ")", "{", "tempObj", ".", "init", "(", ")", ";", "}", "this", ".", "isAbstract", "&&", "checkForAbstractFields", "(", "tempObj", ".", "Abstract", ",", "this", ".", "Class", ")", ";", "this", ".", "Static", "=", "simpleExtend", "(", "tempObj", ".", "Static", ",", "{", "}", ")", ";", "this", ".", "isAbstract", "&&", "(", "this", ".", "Abstract", "=", "simpleExtend", "(", "tempObj", ".", "Abstract", ",", "{", "}", ")", ")", ";", "this", ".", "staticConst", "=", "this", ".", "Static", ".", "Const", ";", "delete", "this", ".", "Static", ".", "Const", ";", "this", ".", "Const", "=", "simpleExtend", "(", "tempObj", ".", "Const", ",", "{", "}", ")", ";", "delete", "this", ".", "Const", ".", "Static", ";", "checkAvailability", "(", "tempObj", ",", "this", ".", "Static", ",", "this", ".", "staticConst", ",", "this", ".", "Abstract", ",", "this", ".", "Const", ")", ";", "addTransient", "(", "this", ",", "tempObj", ")", ";", "this", ".", "privateConstructor", "=", "!", "!", "tempObj", "[", "\"Private\"", "]", "&&", "tempObj", "[", "\"Private\"", "]", "[", "fn", "]", ";", "deleteAddedProtoTypes", "(", "Class", ")", ";", "var", "plugins", "=", "this", ".", "plugins", ",", "pp", ";", "//add plugin as extensin", "for", "(", "var", "p", "in", "plugins", ")", "{", "if", "(", "plugins", ".", "hasOwnProperty", "(", "p", ")", ")", "{", "pp", "=", "fm", ".", "isExist", "(", "plugins", "[", "p", "]", ")", ";", "simpleExtend", "(", "pp", ".", "prototype", ".", "$get", "(", "\"Static\"", ")", ",", "this", ".", "Static", ")", ";", "simpleExtend", "(", "pp", ".", "prototype", ".", "$get", "(", "\"staticConst\"", ")", ",", "this", ".", "staticConst", ")", ";", "}", "}", "var", "temp", "=", "this", ".", "interfaces", ";", "if", "(", "temp", ")", "{", "for", "(", "k", "=", "0", ",", "len", "=", "temp", ".", "length", ";", "k", "<", "len", ";", "k", "++", ")", "{", "createObj", "(", "temp", "[", "k", "]", ")", ".", "prototype", ".", "$checkMAndGetF", "(", "pofn", ",", "info", ".", "methods", ",", "this", ".", "isAbstract", ",", "tempObj", ",", "this", ")", ";", "}", "}", "temp", "=", "k", "=", "tempObj", "=", "info", "=", "Class", "=", "fn", "=", "undefined", ";", "}" ]
Set relevent class information.
[ "Set", "relevent", "class", "information", "." ]
20ca3bd7417008c331285237e64b106c30887e36
https://github.com/anoopchaurasia/jsfm/blob/20ca3bd7417008c331285237e64b106c30887e36/jsfm.js#L927-L978
53,998
anoopchaurasia/jsfm
jsfm.js
checkAvailability
function checkAvailability( obj ) { for ( var k = 1, len = arguments.length; k < len; k++) { for ( var m in arguments[k]) { if (obj.hasOwnProperty(m)) { throw obj.getClass() + ": has " + m + " at more than one places"; } } } }
javascript
function checkAvailability( obj ) { for ( var k = 1, len = arguments.length; k < len; k++) { for ( var m in arguments[k]) { if (obj.hasOwnProperty(m)) { throw obj.getClass() + ": has " + m + " at more than one places"; } } } }
[ "function", "checkAvailability", "(", "obj", ")", "{", "for", "(", "var", "k", "=", "1", ",", "len", "=", "arguments", ".", "length", ";", "k", "<", "len", ";", "k", "++", ")", "{", "for", "(", "var", "m", "in", "arguments", "[", "k", "]", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "m", ")", ")", "{", "throw", "obj", ".", "getClass", "(", ")", "+", "\": has \"", "+", "m", "+", "\" at more than one places\"", ";", "}", "}", "}", "}" ]
Check if same property already available in object for static and Const;
[ "Check", "if", "same", "property", "already", "available", "in", "object", "for", "static", "and", "Const", ";" ]
20ca3bd7417008c331285237e64b106c30887e36
https://github.com/anoopchaurasia/jsfm/blob/20ca3bd7417008c331285237e64b106c30887e36/jsfm.js#L981-L989
53,999
anoopchaurasia/jsfm
jsfm.js
addTransient
function addTransient( internalObj, tempObj ) { var temp = {}, k, tr = tempObj["transient"] || []; tr.push("shortHand"); for (k = 0; k < tr.length; k++) { (temp[tr[k]] = true); } eachPropertyOf(internalObj.Static, function( v, key ) { temp[key] = true; }); eachPropertyOf(internalObj.staticConst, function( v, key ) { temp[key] = true; }); internalObj["transient"] = temp; internalObj = tempObj = k = temp = undefined; }
javascript
function addTransient( internalObj, tempObj ) { var temp = {}, k, tr = tempObj["transient"] || []; tr.push("shortHand"); for (k = 0; k < tr.length; k++) { (temp[tr[k]] = true); } eachPropertyOf(internalObj.Static, function( v, key ) { temp[key] = true; }); eachPropertyOf(internalObj.staticConst, function( v, key ) { temp[key] = true; }); internalObj["transient"] = temp; internalObj = tempObj = k = temp = undefined; }
[ "function", "addTransient", "(", "internalObj", ",", "tempObj", ")", "{", "var", "temp", "=", "{", "}", ",", "k", ",", "tr", "=", "tempObj", "[", "\"transient\"", "]", "||", "[", "]", ";", "tr", ".", "push", "(", "\"shortHand\"", ")", ";", "for", "(", "k", "=", "0", ";", "k", "<", "tr", ".", "length", ";", "k", "++", ")", "{", "(", "temp", "[", "tr", "[", "k", "]", "]", "=", "true", ")", ";", "}", "eachPropertyOf", "(", "internalObj", ".", "Static", ",", "function", "(", "v", ",", "key", ")", "{", "temp", "[", "key", "]", "=", "true", ";", "}", ")", ";", "eachPropertyOf", "(", "internalObj", ".", "staticConst", ",", "function", "(", "v", ",", "key", ")", "{", "temp", "[", "key", "]", "=", "true", ";", "}", ")", ";", "internalObj", "[", "\"transient\"", "]", "=", "temp", ";", "internalObj", "=", "tempObj", "=", "k", "=", "temp", "=", "undefined", ";", "}" ]
add all transient fields to list.
[ "add", "all", "transient", "fields", "to", "list", "." ]
20ca3bd7417008c331285237e64b106c30887e36
https://github.com/anoopchaurasia/jsfm/blob/20ca3bd7417008c331285237e64b106c30887e36/jsfm.js#L992-L1006