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
50,300
tolokoban/ToloFrameWork
ker/mod/wdg.js
function() { var e = this._element; if (e) { var p = e.parentNode; if (p) { p.removeChild(e); } } return this; }
javascript
function() { var e = this._element; if (e) { var p = e.parentNode; if (p) { p.removeChild(e); } } return this; }
[ "function", "(", ")", "{", "var", "e", "=", "this", ".", "_element", ";", "if", "(", "e", ")", "{", "var", "p", "=", "e", ".", "parentNode", ";", "if", "(", "p", ")", "{", "p", ".", "removeChild", "(", "e", ")", ";", "}", "}", "return", "this", ";", "}" ]
Remove this element from its parent. @memberof wdg
[ "Remove", "this", "element", "from", "its", "parent", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/wdg.js#L62-L71
50,301
tolokoban/ToloFrameWork
ker/mod/wdg.js
function() { var i, arg; for (i = 0 ; i < arguments.length ; i++) { arg = arguments[i]; if (typeof arg === 'number') arg = "" + arg; if (typeof arg === 'undefined' || typeof arg === 'null' || (typeof arg !== 'object' && typeof arg !== 'string')) { console.error("[Widget.append] Argument #" + i + " is invalid!", arguments); console.error("[Widget.append] Is type is: " + (typeof arg)); continue; }; if (typeof arg === 'string') { if (arg.length < 1) arg = " "; arg = window.document.createTextNode(arg); if (!arg) { console.error( "[Widget.append] Unable to create a text node with this text: ", arg ); console.error("[wdg] arguments=...", arguments); throw Error( "[Widget.append] Unable to create a text node with this text: " + JSON.stringify(arg) ); } } if (Array.isArray(arg)) { arg.forEach( function(item) { this.append(item); }, this ); } else { var e = arg; if( !(e instanceof Node) ) { if( e.$ instanceof Node ) e = e.$; else if( typeof e.element === 'function' ) e = e.element(); else if( e.element ) e = e.element; } this._element.appendChild(e); } } return this; }
javascript
function() { var i, arg; for (i = 0 ; i < arguments.length ; i++) { arg = arguments[i]; if (typeof arg === 'number') arg = "" + arg; if (typeof arg === 'undefined' || typeof arg === 'null' || (typeof arg !== 'object' && typeof arg !== 'string')) { console.error("[Widget.append] Argument #" + i + " is invalid!", arguments); console.error("[Widget.append] Is type is: " + (typeof arg)); continue; }; if (typeof arg === 'string') { if (arg.length < 1) arg = " "; arg = window.document.createTextNode(arg); if (!arg) { console.error( "[Widget.append] Unable to create a text node with this text: ", arg ); console.error("[wdg] arguments=...", arguments); throw Error( "[Widget.append] Unable to create a text node with this text: " + JSON.stringify(arg) ); } } if (Array.isArray(arg)) { arg.forEach( function(item) { this.append(item); }, this ); } else { var e = arg; if( !(e instanceof Node) ) { if( e.$ instanceof Node ) e = e.$; else if( typeof e.element === 'function' ) e = e.element(); else if( e.element ) e = e.element; } this._element.appendChild(e); } } return this; }
[ "function", "(", ")", "{", "var", "i", ",", "arg", ";", "for", "(", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "arg", "=", "arguments", "[", "i", "]", ";", "if", "(", "typeof", "arg", "===", "'number'", ")", "arg", "=", "\"\"", "+", "arg", ";", "if", "(", "typeof", "arg", "===", "'undefined'", "||", "typeof", "arg", "===", "'null'", "||", "(", "typeof", "arg", "!==", "'object'", "&&", "typeof", "arg", "!==", "'string'", ")", ")", "{", "console", ".", "error", "(", "\"[Widget.append] Argument #\"", "+", "i", "+", "\" is invalid!\"", ",", "arguments", ")", ";", "console", ".", "error", "(", "\"[Widget.append] Is type is: \"", "+", "(", "typeof", "arg", ")", ")", ";", "continue", ";", "}", ";", "if", "(", "typeof", "arg", "===", "'string'", ")", "{", "if", "(", "arg", ".", "length", "<", "1", ")", "arg", "=", "\" \"", ";", "arg", "=", "window", ".", "document", ".", "createTextNode", "(", "arg", ")", ";", "if", "(", "!", "arg", ")", "{", "console", ".", "error", "(", "\"[Widget.append] Unable to create a text node with this text: \"", ",", "arg", ")", ";", "console", ".", "error", "(", "\"[wdg] arguments=...\"", ",", "arguments", ")", ";", "throw", "Error", "(", "\"[Widget.append] Unable to create a text node with this text: \"", "+", "JSON", ".", "stringify", "(", "arg", ")", ")", ";", "}", "}", "if", "(", "Array", ".", "isArray", "(", "arg", ")", ")", "{", "arg", ".", "forEach", "(", "function", "(", "item", ")", "{", "this", ".", "append", "(", "item", ")", ";", "}", ",", "this", ")", ";", "}", "else", "{", "var", "e", "=", "arg", ";", "if", "(", "!", "(", "e", "instanceof", "Node", ")", ")", "{", "if", "(", "e", ".", "$", "instanceof", "Node", ")", "e", "=", "e", ".", "$", ";", "else", "if", "(", "typeof", "e", ".", "element", "===", "'function'", ")", "e", "=", "e", ".", "element", "(", ")", ";", "else", "if", "(", "e", ".", "element", ")", "e", "=", "e", ".", "element", ";", "}", "this", ".", "_element", ".", "appendChild", "(", "e", ")", ";", "}", "}", "return", "this", ";", "}" ]
Append children to this widget.
[ "Append", "children", "to", "this", "widget", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/wdg.js#L251-L294
50,302
tolokoban/ToloFrameWork
ker/mod/wdg.js
function(parent) { if (!parent) return this; if (typeof parent.append === 'function') { parent.append(this); } else if (typeof parent.appendChild === 'function') { parent.appendChild(this._element); this.onAppend(); } return this; }
javascript
function(parent) { if (!parent) return this; if (typeof parent.append === 'function') { parent.append(this); } else if (typeof parent.appendChild === 'function') { parent.appendChild(this._element); this.onAppend(); } return this; }
[ "function", "(", "parent", ")", "{", "if", "(", "!", "parent", ")", "return", "this", ";", "if", "(", "typeof", "parent", ".", "append", "===", "'function'", ")", "{", "parent", ".", "append", "(", "this", ")", ";", "}", "else", "if", "(", "typeof", "parent", ".", "appendChild", "===", "'function'", ")", "{", "parent", ".", "appendChild", "(", "this", ".", "_element", ")", ";", "this", ".", "onAppend", "(", ")", ";", "}", "return", "this", ";", "}" ]
Append this widget to a parent. @param parent @memberof wdg
[ "Append", "this", "widget", "to", "a", "parent", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/wdg.js#L301-L310
50,303
tolokoban/ToloFrameWork
ker/mod/wdg.js
function() { // (!) On préfère retirer les éléments un par un du DOM plutôt que d'utiliser simplement // this.html(""). // En effet, le code simplifié a des conséquences inattendues dans IE9 et IE10 au moins. // Le bug des markers qui disparaissaients sur les cartes de Trail-Passion 4 a été corrigé // avec cette modification. var e = this.element(); while(e.firstChild){ e.removeChild(e.firstChild); } var i, arg; for (i = 0 ; i < arguments.length ; i++) { arg = arguments[i]; this.append(arg); } return this; }
javascript
function() { // (!) On préfère retirer les éléments un par un du DOM plutôt que d'utiliser simplement // this.html(""). // En effet, le code simplifié a des conséquences inattendues dans IE9 et IE10 au moins. // Le bug des markers qui disparaissaients sur les cartes de Trail-Passion 4 a été corrigé // avec cette modification. var e = this.element(); while(e.firstChild){ e.removeChild(e.firstChild); } var i, arg; for (i = 0 ; i < arguments.length ; i++) { arg = arguments[i]; this.append(arg); } return this; }
[ "function", "(", ")", "{", "// (!) On préfère retirer les éléments un par un du DOM plutôt que d'utiliser simplement", "// this.html(\"\").", "// En effet, le code simplifié a des conséquences inattendues dans IE9 et IE10 au moins.", "// Le bug des markers qui disparaissaients sur les cartes de Trail-Passion 4 a été corrigé", "// avec cette modification.", "var", "e", "=", "this", ".", "element", "(", ")", ";", "while", "(", "e", ".", "firstChild", ")", "{", "e", ".", "removeChild", "(", "e", ".", "firstChild", ")", ";", "}", "var", "i", ",", "arg", ";", "for", "(", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "arg", "=", "arguments", "[", "i", "]", ";", "this", ".", "append", "(", "arg", ")", ";", "}", "return", "this", ";", "}" ]
Remove all children of this widget. Any argument passed will be appended to this widget. @memberof wdg
[ "Remove", "all", "children", "of", "this", "widget", ".", "Any", "argument", "passed", "will", "be", "appended", "to", "this", "widget", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/wdg.js#L384-L401
50,304
tolokoban/ToloFrameWork
ker/mod/wdg.js
function() { var e = this._element; if (!e) return null; if (typeof e.getBoundingClientRect !== 'function') { console.error("[wdg.rect] This element has non `getBoundingClientRect` function:", e); } var r = e.getBoundingClientRect(); if( typeof r.width === 'undefined' ) r.width = r.right - r.left; if( typeof r.height === 'undefined' ) r.height = r.bottom - r.top; return r; }
javascript
function() { var e = this._element; if (!e) return null; if (typeof e.getBoundingClientRect !== 'function') { console.error("[wdg.rect] This element has non `getBoundingClientRect` function:", e); } var r = e.getBoundingClientRect(); if( typeof r.width === 'undefined' ) r.width = r.right - r.left; if( typeof r.height === 'undefined' ) r.height = r.bottom - r.top; return r; }
[ "function", "(", ")", "{", "var", "e", "=", "this", ".", "_element", ";", "if", "(", "!", "e", ")", "return", "null", ";", "if", "(", "typeof", "e", ".", "getBoundingClientRect", "!==", "'function'", ")", "{", "console", ".", "error", "(", "\"[wdg.rect] This element has non `getBoundingClientRect` function:\"", ",", "e", ")", ";", "}", "var", "r", "=", "e", ".", "getBoundingClientRect", "(", ")", ";", "if", "(", "typeof", "r", ".", "width", "===", "'undefined'", ")", "r", ".", "width", "=", "r", ".", "right", "-", "r", ".", "left", ";", "if", "(", "typeof", "r", ".", "height", "===", "'undefined'", ")", "r", ".", "height", "=", "r", ".", "bottom", "-", "r", ".", "top", ";", "return", "r", ";", "}" ]
Returns the bounds of the underlying element. @memberof wdg
[ "Returns", "the", "bounds", "of", "the", "underlying", "element", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/wdg.js#L474-L484
50,305
vmarkdown/vremark-parse
packages/mdast-util-to-hast/lib/revert.js
revert
function revert(h, node) { var subtype = node.referenceType var suffix = ']' var contents var head var tail if (subtype === 'collapsed') { suffix += '[]' } else if (subtype === 'full') { suffix += '[' + node.identifier + ']' } if (node.type === 'imageReference') { return u('text', '![' + node.alt + suffix) } contents = all(h, node) head = contents[0] if (head && head.type === 'text') { head.value = '[' + head.value } else { contents.unshift(u('text', '[')) } tail = contents[contents.length - 1] if (tail && tail.type === 'text') { tail.value += suffix } else { contents.push(u('text', suffix)) } return contents }
javascript
function revert(h, node) { var subtype = node.referenceType var suffix = ']' var contents var head var tail if (subtype === 'collapsed') { suffix += '[]' } else if (subtype === 'full') { suffix += '[' + node.identifier + ']' } if (node.type === 'imageReference') { return u('text', '![' + node.alt + suffix) } contents = all(h, node) head = contents[0] if (head && head.type === 'text') { head.value = '[' + head.value } else { contents.unshift(u('text', '[')) } tail = contents[contents.length - 1] if (tail && tail.type === 'text') { tail.value += suffix } else { contents.push(u('text', suffix)) } return contents }
[ "function", "revert", "(", "h", ",", "node", ")", "{", "var", "subtype", "=", "node", ".", "referenceType", "var", "suffix", "=", "']'", "var", "contents", "var", "head", "var", "tail", "if", "(", "subtype", "===", "'collapsed'", ")", "{", "suffix", "+=", "'[]'", "}", "else", "if", "(", "subtype", "===", "'full'", ")", "{", "suffix", "+=", "'['", "+", "node", ".", "identifier", "+", "']'", "}", "if", "(", "node", ".", "type", "===", "'imageReference'", ")", "{", "return", "u", "(", "'text'", ",", "'!['", "+", "node", ".", "alt", "+", "suffix", ")", "}", "contents", "=", "all", "(", "h", ",", "node", ")", "head", "=", "contents", "[", "0", "]", "if", "(", "head", "&&", "head", ".", "type", "===", "'text'", ")", "{", "head", ".", "value", "=", "'['", "+", "head", ".", "value", "}", "else", "{", "contents", ".", "unshift", "(", "u", "(", "'text'", ",", "'['", ")", ")", "}", "tail", "=", "contents", "[", "contents", ".", "length", "-", "1", "]", "if", "(", "tail", "&&", "tail", ".", "type", "===", "'text'", ")", "{", "tail", ".", "value", "+=", "suffix", "}", "else", "{", "contents", ".", "push", "(", "u", "(", "'text'", ",", "suffix", ")", ")", "}", "return", "contents", "}" ]
Return the content of a reference without definition as markdown.
[ "Return", "the", "content", "of", "a", "reference", "without", "definition", "as", "markdown", "." ]
d7b353dcb5d021eeceb40f3c505ece893202db7a
https://github.com/vmarkdown/vremark-parse/blob/d7b353dcb5d021eeceb40f3c505ece893202db7a/packages/mdast-util-to-hast/lib/revert.js#L9-L44
50,306
straticjs/gulp-attach-to-template
index.js
function(callback) { // TODO: don't wait until the end. Instead, emit immediately upon finding the template if (!templateFile) throw new Error('template not found in stream'); templateFile.data = templateFile.data || {}; files.forEach(function(file) { var newFile = templateFile.clone(); newFile.data.file = file; newFile.path = file.path; this.push(newFile); }, this); callback(); }
javascript
function(callback) { // TODO: don't wait until the end. Instead, emit immediately upon finding the template if (!templateFile) throw new Error('template not found in stream'); templateFile.data = templateFile.data || {}; files.forEach(function(file) { var newFile = templateFile.clone(); newFile.data.file = file; newFile.path = file.path; this.push(newFile); }, this); callback(); }
[ "function", "(", "callback", ")", "{", "// TODO: don't wait until the end. Instead, emit immediately upon finding the template", "if", "(", "!", "templateFile", ")", "throw", "new", "Error", "(", "'template not found in stream'", ")", ";", "templateFile", ".", "data", "=", "templateFile", ".", "data", "||", "{", "}", ";", "files", ".", "forEach", "(", "function", "(", "file", ")", "{", "var", "newFile", "=", "templateFile", ".", "clone", "(", ")", ";", "newFile", ".", "data", ".", "file", "=", "file", ";", "newFile", ".", "path", "=", "file", ".", "path", ";", "this", ".", "push", "(", "newFile", ")", ";", "}", ",", "this", ")", ";", "callback", "(", ")", ";", "}" ]
Wait until all files have come through, then attach the non-template files
[ "Wait", "until", "all", "files", "have", "come", "through", "then", "attach", "the", "non", "-", "template", "files" ]
417309e94db8491a96fd4a52b483f4db7dcc1290
https://github.com/straticjs/gulp-attach-to-template/blob/417309e94db8491a96fd4a52b483f4db7dcc1290/index.js#L39-L56
50,307
finvernizzi/mplane_http_transport
mplane_http_transport.js
registerSpecification
function registerSpecification(specification, remoteDN , options , callback){ // Serialize the capability Object var post_data = {}; post_data[remoteDN] = JSON.parse(specification.to_dict()); post_data = JSON.stringify(post_data); var proto = https; var post_options = { path: SUPERVISOR_PATH_REGISTER_SPECIFICATION, method: 'POST', host: options.host, port: options.port, followRedirect:false, headers: { 'Content-Type': MIME_TYPE, 'Content-Length': Buffer.byteLength(post_data) } , key: ssl_files.readFileContent(options.keyFile) ,cert: ssl_files.readFileContent(options.certFile) ,ca: ssl_files.readCaChain(options.caFile) }; // Set up the request var post_req = proto.request(post_options, function(res) { var body = ""; res.setEncoding('utf8'); res.on('data', function (chunk) { if (chunk) body +=chunk; }); res.on('end', function (chunk) { if (chunk) body +=chunk; if (res.statusCode == 200){ // Send back the receipt callback(null, body); }else{ callback(new Error(res.statusCode), null); } }); }); // post the data post_req.write(post_data); post_req.end(); }
javascript
function registerSpecification(specification, remoteDN , options , callback){ // Serialize the capability Object var post_data = {}; post_data[remoteDN] = JSON.parse(specification.to_dict()); post_data = JSON.stringify(post_data); var proto = https; var post_options = { path: SUPERVISOR_PATH_REGISTER_SPECIFICATION, method: 'POST', host: options.host, port: options.port, followRedirect:false, headers: { 'Content-Type': MIME_TYPE, 'Content-Length': Buffer.byteLength(post_data) } , key: ssl_files.readFileContent(options.keyFile) ,cert: ssl_files.readFileContent(options.certFile) ,ca: ssl_files.readCaChain(options.caFile) }; // Set up the request var post_req = proto.request(post_options, function(res) { var body = ""; res.setEncoding('utf8'); res.on('data', function (chunk) { if (chunk) body +=chunk; }); res.on('end', function (chunk) { if (chunk) body +=chunk; if (res.statusCode == 200){ // Send back the receipt callback(null, body); }else{ callback(new Error(res.statusCode), null); } }); }); // post the data post_req.write(post_data); post_req.end(); }
[ "function", "registerSpecification", "(", "specification", ",", "remoteDN", ",", "options", ",", "callback", ")", "{", "// Serialize the capability Object", "var", "post_data", "=", "{", "}", ";", "post_data", "[", "remoteDN", "]", "=", "JSON", ".", "parse", "(", "specification", ".", "to_dict", "(", ")", ")", ";", "post_data", "=", "JSON", ".", "stringify", "(", "post_data", ")", ";", "var", "proto", "=", "https", ";", "var", "post_options", "=", "{", "path", ":", "SUPERVISOR_PATH_REGISTER_SPECIFICATION", ",", "method", ":", "'POST'", ",", "host", ":", "options", ".", "host", ",", "port", ":", "options", ".", "port", ",", "followRedirect", ":", "false", ",", "headers", ":", "{", "'Content-Type'", ":", "MIME_TYPE", ",", "'Content-Length'", ":", "Buffer", ".", "byteLength", "(", "post_data", ")", "}", ",", "key", ":", "ssl_files", ".", "readFileContent", "(", "options", ".", "keyFile", ")", ",", "cert", ":", "ssl_files", ".", "readFileContent", "(", "options", ".", "certFile", ")", ",", "ca", ":", "ssl_files", ".", "readCaChain", "(", "options", ".", "caFile", ")", "}", ";", "// Set up the request", "var", "post_req", "=", "proto", ".", "request", "(", "post_options", ",", "function", "(", "res", ")", "{", "var", "body", "=", "\"\"", ";", "res", ".", "setEncoding", "(", "'utf8'", ")", ";", "res", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "if", "(", "chunk", ")", "body", "+=", "chunk", ";", "}", ")", ";", "res", ".", "on", "(", "'end'", ",", "function", "(", "chunk", ")", "{", "if", "(", "chunk", ")", "body", "+=", "chunk", ";", "if", "(", "res", ".", "statusCode", "==", "200", ")", "{", "// Send back the receipt", "callback", "(", "null", ",", "body", ")", ";", "}", "else", "{", "callback", "(", "new", "Error", "(", "res", ".", "statusCode", ")", ",", "null", ")", ";", "}", "}", ")", ";", "}", ")", ";", "// post the data", "post_req", ".", "write", "(", "post_data", ")", ";", "post_req", ".", "end", "(", ")", ";", "}" ]
Register with a POST a specification to the supervisor @param specification an mPlane Spcification options MUST include (or an INVALID parameters error is thrown): - options.host - options.port - options.caFile - options.keyFile - options.certFile
[ "Register", "with", "a", "POST", "a", "specification", "to", "the", "supervisor" ]
1102d8e1458c3010f3b126b536434114c790b180
https://github.com/finvernizzi/mplane_http_transport/blob/1102d8e1458c3010f3b126b536434114c790b180/mplane_http_transport.js#L191-L234
50,308
finvernizzi/mplane_http_transport
mplane_http_transport.js
showResults
function showResults(redeem , options , callback){ if (typeof redeem !== 'object') redeem = new mplane.Redemption(redeem); var post_data = redeem.to_dict(); var post_options = { path: SUPERVISOR_PATH_SHOW_RESULT, method: 'POST', host: options.host, port: options.port, followRedirect:false, headers: { 'Content-Type': MIME_TYPE, 'Content-Length': Buffer.byteLength(post_data) } }; post_options.ca = ssl_files.readCaChain(options.ca); post_options.key = ssl_files.readFileContent(options.key); post_options.cert = ssl_files.readFileContent(options.cert); // Try to redeem the specification var post_req = https.request(post_options, function(res) { var bodyChunks=[]; res.on('data', function (chunk) { bodyChunks.push(chunk); }).on('end', function () { body = Buffer.concat(bodyChunks); if (res.statusCode != 200){ if (res.statusCode == 403){ callback(new Error(403),null); return; }else{ callback(new Error("Error from server"),null);//Wrong answer return; } } var result = mplane.from_dict(body); callback(null,result); }); }); post_req.on("error", function(err){ callback(err,null) }); post_req.write(post_data); post_req.end(); }
javascript
function showResults(redeem , options , callback){ if (typeof redeem !== 'object') redeem = new mplane.Redemption(redeem); var post_data = redeem.to_dict(); var post_options = { path: SUPERVISOR_PATH_SHOW_RESULT, method: 'POST', host: options.host, port: options.port, followRedirect:false, headers: { 'Content-Type': MIME_TYPE, 'Content-Length': Buffer.byteLength(post_data) } }; post_options.ca = ssl_files.readCaChain(options.ca); post_options.key = ssl_files.readFileContent(options.key); post_options.cert = ssl_files.readFileContent(options.cert); // Try to redeem the specification var post_req = https.request(post_options, function(res) { var bodyChunks=[]; res.on('data', function (chunk) { bodyChunks.push(chunk); }).on('end', function () { body = Buffer.concat(bodyChunks); if (res.statusCode != 200){ if (res.statusCode == 403){ callback(new Error(403),null); return; }else{ callback(new Error("Error from server"),null);//Wrong answer return; } } var result = mplane.from_dict(body); callback(null,result); }); }); post_req.on("error", function(err){ callback(err,null) }); post_req.write(post_data); post_req.end(); }
[ "function", "showResults", "(", "redeem", ",", "options", ",", "callback", ")", "{", "if", "(", "typeof", "redeem", "!==", "'object'", ")", "redeem", "=", "new", "mplane", ".", "Redemption", "(", "redeem", ")", ";", "var", "post_data", "=", "redeem", ".", "to_dict", "(", ")", ";", "var", "post_options", "=", "{", "path", ":", "SUPERVISOR_PATH_SHOW_RESULT", ",", "method", ":", "'POST'", ",", "host", ":", "options", ".", "host", ",", "port", ":", "options", ".", "port", ",", "followRedirect", ":", "false", ",", "headers", ":", "{", "'Content-Type'", ":", "MIME_TYPE", ",", "'Content-Length'", ":", "Buffer", ".", "byteLength", "(", "post_data", ")", "}", "}", ";", "post_options", ".", "ca", "=", "ssl_files", ".", "readCaChain", "(", "options", ".", "ca", ")", ";", "post_options", ".", "key", "=", "ssl_files", ".", "readFileContent", "(", "options", ".", "key", ")", ";", "post_options", ".", "cert", "=", "ssl_files", ".", "readFileContent", "(", "options", ".", "cert", ")", ";", "// Try to redeem the specification", "var", "post_req", "=", "https", ".", "request", "(", "post_options", ",", "function", "(", "res", ")", "{", "var", "bodyChunks", "=", "[", "]", ";", "res", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "bodyChunks", ".", "push", "(", "chunk", ")", ";", "}", ")", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "body", "=", "Buffer", ".", "concat", "(", "bodyChunks", ")", ";", "if", "(", "res", ".", "statusCode", "!=", "200", ")", "{", "if", "(", "res", ".", "statusCode", "==", "403", ")", "{", "callback", "(", "new", "Error", "(", "403", ")", ",", "null", ")", ";", "return", ";", "}", "else", "{", "callback", "(", "new", "Error", "(", "\"Error from server\"", ")", ",", "null", ")", ";", "//Wrong answer", "return", ";", "}", "}", "var", "result", "=", "mplane", ".", "from_dict", "(", "body", ")", ";", "callback", "(", "null", ",", "result", ")", ";", "}", ")", ";", "}", ")", ";", "post_req", ".", "on", "(", "\"error\"", ",", "function", "(", "err", ")", "{", "callback", "(", "err", ",", "null", ")", "}", ")", ";", "post_req", ".", "write", "(", "post_data", ")", ";", "post_req", ".", "end", "(", ")", ";", "}" ]
Given a redeem, ask if results are ready @param redeem @param options @param callback
[ "Given", "a", "redeem", "ask", "if", "results", "are", "ready" ]
1102d8e1458c3010f3b126b536434114c790b180
https://github.com/finvernizzi/mplane_http_transport/blob/1102d8e1458c3010f3b126b536434114c790b180/mplane_http_transport.js#L294-L337
50,309
finvernizzi/mplane_http_transport
mplane_http_transport.js
showCapabilities
function showCapabilities( options, callback){ options.url = 'https://'+options.host+':'+options.port+SUPERVISOR_PATH_SHOW_CAPABILITY; options.ca = ssl_files.readCaChain(options.caFile); options.key = ssl_files.readFileContent(options.keyFile); options.cert = ssl_files.readFileContent(options.certFile); request(options, function (error, response, body) { if (!error && (response.statusCode = 200)) { var caps = (JSON.parse(body)); callback(null, caps); }else{ console.log(error); callback(new Error("Error connecting to the supervisor"), null); } }); }
javascript
function showCapabilities( options, callback){ options.url = 'https://'+options.host+':'+options.port+SUPERVISOR_PATH_SHOW_CAPABILITY; options.ca = ssl_files.readCaChain(options.caFile); options.key = ssl_files.readFileContent(options.keyFile); options.cert = ssl_files.readFileContent(options.certFile); request(options, function (error, response, body) { if (!error && (response.statusCode = 200)) { var caps = (JSON.parse(body)); callback(null, caps); }else{ console.log(error); callback(new Error("Error connecting to the supervisor"), null); } }); }
[ "function", "showCapabilities", "(", "options", ",", "callback", ")", "{", "options", ".", "url", "=", "'https://'", "+", "options", ".", "host", "+", "':'", "+", "options", ".", "port", "+", "SUPERVISOR_PATH_SHOW_CAPABILITY", ";", "options", ".", "ca", "=", "ssl_files", ".", "readCaChain", "(", "options", ".", "caFile", ")", ";", "options", ".", "key", "=", "ssl_files", ".", "readFileContent", "(", "options", ".", "keyFile", ")", ";", "options", ".", "cert", "=", "ssl_files", ".", "readFileContent", "(", "options", ".", "certFile", ")", ";", "request", "(", "options", ",", "function", "(", "error", ",", "response", ",", "body", ")", "{", "if", "(", "!", "error", "&&", "(", "response", ".", "statusCode", "=", "200", ")", ")", "{", "var", "caps", "=", "(", "JSON", ".", "parse", "(", "body", ")", ")", ";", "callback", "(", "null", ",", "caps", ")", ";", "}", "else", "{", "console", ".", "log", "(", "error", ")", ";", "callback", "(", "new", "Error", "(", "\"Error connecting to the supervisor\"", ")", ",", "null", ")", ";", "}", "}", ")", ";", "}" ]
Contact the supervisor for requesting all the registered capabilities @param options @param callback
[ "Contact", "the", "supervisor", "for", "requesting", "all", "the", "registered", "capabilities" ]
1102d8e1458c3010f3b126b536434114c790b180
https://github.com/finvernizzi/mplane_http_transport/blob/1102d8e1458c3010f3b126b536434114c790b180/mplane_http_transport.js#L344-L359
50,310
finvernizzi/mplane_http_transport
mplane_http_transport.js
info
function info(options , callback){ options.url = 'https://'+options.host+':'+options.port+SUPERVISOR_PATH_INFO; options.key = ssl_files.readFileContent(options.keyFile); options.cert = ssl_files.readFileContent(options.certFile); options.ca = ssl_files.readCaChain(options.ca); request(options, function (error, response, body) { if (!error && response.statusCode == 200) { callback(null, JSON.parse(body)); }else{ callback(new Error("Error connecting to the supervisor:"+error.toString()) , null); } }); }
javascript
function info(options , callback){ options.url = 'https://'+options.host+':'+options.port+SUPERVISOR_PATH_INFO; options.key = ssl_files.readFileContent(options.keyFile); options.cert = ssl_files.readFileContent(options.certFile); options.ca = ssl_files.readCaChain(options.ca); request(options, function (error, response, body) { if (!error && response.statusCode == 200) { callback(null, JSON.parse(body)); }else{ callback(new Error("Error connecting to the supervisor:"+error.toString()) , null); } }); }
[ "function", "info", "(", "options", ",", "callback", ")", "{", "options", ".", "url", "=", "'https://'", "+", "options", ".", "host", "+", "':'", "+", "options", ".", "port", "+", "SUPERVISOR_PATH_INFO", ";", "options", ".", "key", "=", "ssl_files", ".", "readFileContent", "(", "options", ".", "keyFile", ")", ";", "options", ".", "cert", "=", "ssl_files", ".", "readFileContent", "(", "options", ".", "certFile", ")", ";", "options", ".", "ca", "=", "ssl_files", ".", "readCaChain", "(", "options", ".", "ca", ")", ";", "request", "(", "options", ",", "function", "(", "error", ",", "response", ",", "body", ")", "{", "if", "(", "!", "error", "&&", "response", ".", "statusCode", "==", "200", ")", "{", "callback", "(", "null", ",", "JSON", ".", "parse", "(", "body", ")", ")", ";", "}", "else", "{", "callback", "(", "new", "Error", "(", "\"Error connecting to the supervisor:\"", "+", "error", ".", "toString", "(", ")", ")", ",", "null", ")", ";", "}", "}", ")", ";", "}" ]
Reads supervisor informations
[ "Reads", "supervisor", "informations" ]
1102d8e1458c3010f3b126b536434114c790b180
https://github.com/finvernizzi/mplane_http_transport/blob/1102d8e1458c3010f3b126b536434114c790b180/mplane_http_transport.js#L362-L376
50,311
jedrichards/twitreq
lib/twitreq.js
genReq
function genReq (options,cb) { log(options.verbose,"Starting twitreq ..."); if ( typeof options.protocol === "undefined" ) { options.protocol = PROTOCOL; } if ( typeof options.host === "undefined" ) { options.host = HOST; } if ( typeof options.oAuthSignatureMethod === "undefined" ) { options.oAuthSignatureMethod = OAUTH_SIGNATURE_METHOD; } if ( options.oAuthSignatureMethod !== OAUTH_SIGNATURE_METHOD ) { cb(new Error("HMAC-SHA1 is the only supported signature signing method at present.")); return; } if ( typeof options.oAuthVersion === "undefined" ) { options.oAuthVersion = OAUTH_VERSION; } log(options.verbose,"Using options:"); log(options.verbose,options); options.baseURL = options.protocol+"://"+options.host+options.path; options.oAuthTimestamp = getTimestamp(); log(options.verbose,"Generated timestamp: "+options.oAuthTimestamp); options.oAuthNonce = getNonce(); log(options.verbose,"Generated nonce: "+options.oAuthNonce); options.oAuthSignature = genOAuthSig(options); options.authHeaderValue = genAuthorizationHeaderValue(options); options.queryString = genQueryString(options); var headers = {}; headers["Authorization"] = options.authHeaderValue; headers["Accept"] = "*/*"; headers["Connection"] = "close"; headers["User-Agent"] = "Node.js/twitreq v"+TWITREQ_VERSION; headers["Content-Type"] = "application/x-www-form-urlencoded"; headers["Host"] = options.host; var reqOptions = { method: options.method, path: options.path+options.queryString, hostname: options.host, headers: headers, }; log(options.verbose,"Complete! Generated request object is:"); log(options.verbose,reqOptions); cb(null,reqOptions); }
javascript
function genReq (options,cb) { log(options.verbose,"Starting twitreq ..."); if ( typeof options.protocol === "undefined" ) { options.protocol = PROTOCOL; } if ( typeof options.host === "undefined" ) { options.host = HOST; } if ( typeof options.oAuthSignatureMethod === "undefined" ) { options.oAuthSignatureMethod = OAUTH_SIGNATURE_METHOD; } if ( options.oAuthSignatureMethod !== OAUTH_SIGNATURE_METHOD ) { cb(new Error("HMAC-SHA1 is the only supported signature signing method at present.")); return; } if ( typeof options.oAuthVersion === "undefined" ) { options.oAuthVersion = OAUTH_VERSION; } log(options.verbose,"Using options:"); log(options.verbose,options); options.baseURL = options.protocol+"://"+options.host+options.path; options.oAuthTimestamp = getTimestamp(); log(options.verbose,"Generated timestamp: "+options.oAuthTimestamp); options.oAuthNonce = getNonce(); log(options.verbose,"Generated nonce: "+options.oAuthNonce); options.oAuthSignature = genOAuthSig(options); options.authHeaderValue = genAuthorizationHeaderValue(options); options.queryString = genQueryString(options); var headers = {}; headers["Authorization"] = options.authHeaderValue; headers["Accept"] = "*/*"; headers["Connection"] = "close"; headers["User-Agent"] = "Node.js/twitreq v"+TWITREQ_VERSION; headers["Content-Type"] = "application/x-www-form-urlencoded"; headers["Host"] = options.host; var reqOptions = { method: options.method, path: options.path+options.queryString, hostname: options.host, headers: headers, }; log(options.verbose,"Complete! Generated request object is:"); log(options.verbose,reqOptions); cb(null,reqOptions); }
[ "function", "genReq", "(", "options", ",", "cb", ")", "{", "log", "(", "options", ".", "verbose", ",", "\"Starting twitreq ...\"", ")", ";", "if", "(", "typeof", "options", ".", "protocol", "===", "\"undefined\"", ")", "{", "options", ".", "protocol", "=", "PROTOCOL", ";", "}", "if", "(", "typeof", "options", ".", "host", "===", "\"undefined\"", ")", "{", "options", ".", "host", "=", "HOST", ";", "}", "if", "(", "typeof", "options", ".", "oAuthSignatureMethod", "===", "\"undefined\"", ")", "{", "options", ".", "oAuthSignatureMethod", "=", "OAUTH_SIGNATURE_METHOD", ";", "}", "if", "(", "options", ".", "oAuthSignatureMethod", "!==", "OAUTH_SIGNATURE_METHOD", ")", "{", "cb", "(", "new", "Error", "(", "\"HMAC-SHA1 is the only supported signature signing method at present.\"", ")", ")", ";", "return", ";", "}", "if", "(", "typeof", "options", ".", "oAuthVersion", "===", "\"undefined\"", ")", "{", "options", ".", "oAuthVersion", "=", "OAUTH_VERSION", ";", "}", "log", "(", "options", ".", "verbose", ",", "\"Using options:\"", ")", ";", "log", "(", "options", ".", "verbose", ",", "options", ")", ";", "options", ".", "baseURL", "=", "options", ".", "protocol", "+", "\"://\"", "+", "options", ".", "host", "+", "options", ".", "path", ";", "options", ".", "oAuthTimestamp", "=", "getTimestamp", "(", ")", ";", "log", "(", "options", ".", "verbose", ",", "\"Generated timestamp: \"", "+", "options", ".", "oAuthTimestamp", ")", ";", "options", ".", "oAuthNonce", "=", "getNonce", "(", ")", ";", "log", "(", "options", ".", "verbose", ",", "\"Generated nonce: \"", "+", "options", ".", "oAuthNonce", ")", ";", "options", ".", "oAuthSignature", "=", "genOAuthSig", "(", "options", ")", ";", "options", ".", "authHeaderValue", "=", "genAuthorizationHeaderValue", "(", "options", ")", ";", "options", ".", "queryString", "=", "genQueryString", "(", "options", ")", ";", "var", "headers", "=", "{", "}", ";", "headers", "[", "\"Authorization\"", "]", "=", "options", ".", "authHeaderValue", ";", "headers", "[", "\"Accept\"", "]", "=", "\"*/*\"", ";", "headers", "[", "\"Connection\"", "]", "=", "\"close\"", ";", "headers", "[", "\"User-Agent\"", "]", "=", "\"Node.js/twitreq v\"", "+", "TWITREQ_VERSION", ";", "headers", "[", "\"Content-Type\"", "]", "=", "\"application/x-www-form-urlencoded\"", ";", "headers", "[", "\"Host\"", "]", "=", "options", ".", "host", ";", "var", "reqOptions", "=", "{", "method", ":", "options", ".", "method", ",", "path", ":", "options", ".", "path", "+", "options", ".", "queryString", ",", "hostname", ":", "options", ".", "host", ",", "headers", ":", "headers", ",", "}", ";", "log", "(", "options", ".", "verbose", ",", "\"Complete! Generated request object is:\"", ")", ";", "log", "(", "options", ".", "verbose", ",", "reqOptions", ")", ";", "cb", "(", "null", ",", "reqOptions", ")", ";", "}" ]
Generate a Node HTTP request options object based on a valid set of options.
[ "Generate", "a", "Node", "HTTP", "request", "options", "object", "based", "on", "a", "valid", "set", "of", "options", "." ]
6d6a1702acc812b333401db7aba0aa003904b76b
https://github.com/jedrichards/twitreq/blob/6d6a1702acc812b333401db7aba0aa003904b76b/lib/twitreq.js#L47-L107
50,312
jedrichards/twitreq
lib/twitreq.js
genQueryString
function genQueryString (options) { if ( !options.queryParams ) { return ""; } log(options.verbose,"Now generating query string value ..."); var queryStringParams = []; Object.keys(options.queryParams).forEach(function (key) { queryStringParams.push(createEncodedParam(key,options.queryParams[key])); }); var queryString = "?"; log(options.verbose,"Query string key/value pairs are:"); for ( var i=0; i<queryStringParams.length; i++ ) { log(options.verbose," "+queryStringParams[i].key+"="+queryStringParams[i].value); queryString += queryStringParams[i].key+"="+queryStringParams[i].value; if ( queryStringParams[i+1] ) { queryString += "&"; } } log(options.verbose,"Query string value is: "+queryString); return queryString; }
javascript
function genQueryString (options) { if ( !options.queryParams ) { return ""; } log(options.verbose,"Now generating query string value ..."); var queryStringParams = []; Object.keys(options.queryParams).forEach(function (key) { queryStringParams.push(createEncodedParam(key,options.queryParams[key])); }); var queryString = "?"; log(options.verbose,"Query string key/value pairs are:"); for ( var i=0; i<queryStringParams.length; i++ ) { log(options.verbose," "+queryStringParams[i].key+"="+queryStringParams[i].value); queryString += queryStringParams[i].key+"="+queryStringParams[i].value; if ( queryStringParams[i+1] ) { queryString += "&"; } } log(options.verbose,"Query string value is: "+queryString); return queryString; }
[ "function", "genQueryString", "(", "options", ")", "{", "if", "(", "!", "options", ".", "queryParams", ")", "{", "return", "\"\"", ";", "}", "log", "(", "options", ".", "verbose", ",", "\"Now generating query string value ...\"", ")", ";", "var", "queryStringParams", "=", "[", "]", ";", "Object", ".", "keys", "(", "options", ".", "queryParams", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "queryStringParams", ".", "push", "(", "createEncodedParam", "(", "key", ",", "options", ".", "queryParams", "[", "key", "]", ")", ")", ";", "}", ")", ";", "var", "queryString", "=", "\"?\"", ";", "log", "(", "options", ".", "verbose", ",", "\"Query string key/value pairs are:\"", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "queryStringParams", ".", "length", ";", "i", "++", ")", "{", "log", "(", "options", ".", "verbose", ",", "\" \"", "+", "queryStringParams", "[", "i", "]", ".", "key", "+", "\"=\"", "+", "queryStringParams", "[", "i", "]", ".", "value", ")", ";", "queryString", "+=", "queryStringParams", "[", "i", "]", ".", "key", "+", "\"=\"", "+", "queryStringParams", "[", "i", "]", ".", "value", ";", "if", "(", "queryStringParams", "[", "i", "+", "1", "]", ")", "{", "queryString", "+=", "\"&\"", ";", "}", "}", "log", "(", "options", ".", "verbose", ",", "\"Query string value is: \"", "+", "queryString", ")", ";", "return", "queryString", ";", "}" ]
Generate a percent encoded query string from the supplied options.
[ "Generate", "a", "percent", "encoded", "query", "string", "from", "the", "supplied", "options", "." ]
6d6a1702acc812b333401db7aba0aa003904b76b
https://github.com/jedrichards/twitreq/blob/6d6a1702acc812b333401db7aba0aa003904b76b/lib/twitreq.js#L112-L141
50,313
jedrichards/twitreq
lib/twitreq.js
percentEncode
function percentEncode (value) { var result = encodeURIComponent(value); return result.replace(/\!/g, "%21") .replace(/\'/g, "%27") .replace(/\(/g, "%28") .replace(/\)/g, "%29") .replace(/\*/g, "%2A"); }
javascript
function percentEncode (value) { var result = encodeURIComponent(value); return result.replace(/\!/g, "%21") .replace(/\'/g, "%27") .replace(/\(/g, "%28") .replace(/\)/g, "%29") .replace(/\*/g, "%2A"); }
[ "function", "percentEncode", "(", "value", ")", "{", "var", "result", "=", "encodeURIComponent", "(", "value", ")", ";", "return", "result", ".", "replace", "(", "/", "\\!", "/", "g", ",", "\"%21\"", ")", ".", "replace", "(", "/", "\\'", "/", "g", ",", "\"%27\"", ")", ".", "replace", "(", "/", "\\(", "/", "g", ",", "\"%28\"", ")", ".", "replace", "(", "/", "\\)", "/", "g", ",", "\"%29\"", ")", ".", "replace", "(", "/", "\\*", "/", "g", ",", "\"%2A\"", ")", ";", "}" ]
Return a RFC3986 compliant percent encoded string.
[ "Return", "a", "RFC3986", "compliant", "percent", "encoded", "string", "." ]
6d6a1702acc812b333401db7aba0aa003904b76b
https://github.com/jedrichards/twitreq/blob/6d6a1702acc812b333401db7aba0aa003904b76b/lib/twitreq.js#L267-L274
50,314
scrapjs/hmu-plugin
lib/index.js
error
function error(err) { this.log(`${chalk.red(`${err.name.toLowerCase()}:`)} ${err.message}`); }
javascript
function error(err) { this.log(`${chalk.red(`${err.name.toLowerCase()}:`)} ${err.message}`); }
[ "function", "error", "(", "err", ")", "{", "this", ".", "log", "(", "`", "${", "chalk", ".", "red", "(", "`", "${", "err", ".", "name", ".", "toLowerCase", "(", ")", "}", "`", ")", "}", "${", "err", ".", "message", "}", "`", ")", ";", "}" ]
Log plugin error
[ "Log", "plugin", "error" ]
d96f71274646304ad158c9834ee210c7141a8099
https://github.com/scrapjs/hmu-plugin/blob/d96f71274646304ad158c9834ee210c7141a8099/lib/index.js#L22-L24
50,315
scrapjs/hmu-plugin
lib/index.js
status
function status(url, code, mod) { return this.get(url, mod).then(req => req.statusCode === code); }
javascript
function status(url, code, mod) { return this.get(url, mod).then(req => req.statusCode === code); }
[ "function", "status", "(", "url", ",", "code", ",", "mod", ")", "{", "return", "this", ".", "get", "(", "url", ",", "mod", ")", ".", "then", "(", "req", "=>", "req", ".", "statusCode", "===", "code", ")", ";", "}" ]
Fast status checking
[ "Fast", "status", "checking" ]
d96f71274646304ad158c9834ee210c7141a8099
https://github.com/scrapjs/hmu-plugin/blob/d96f71274646304ad158c9834ee210c7141a8099/lib/index.js#L35-L37
50,316
squid-app/config
index.js
Config
function Config( defaults, extend, envName ) { // Constants // ------------- // test instance uniqueness this._UID = _.uniqueId('config_') this._DEFAULTENV = 'default' // CORE's settings // ------------------------ // default app configuration var confDefault = this.getConfigParam( defaults ) , confExtend = ( !_.isUndefined( extend ) ) ? this.getConfigParam( extend ) : {} this._ENV = envName || this._DEFAULTENV this._CONFIG = _.merge( {} , confDefault , confExtend ) return this }
javascript
function Config( defaults, extend, envName ) { // Constants // ------------- // test instance uniqueness this._UID = _.uniqueId('config_') this._DEFAULTENV = 'default' // CORE's settings // ------------------------ // default app configuration var confDefault = this.getConfigParam( defaults ) , confExtend = ( !_.isUndefined( extend ) ) ? this.getConfigParam( extend ) : {} this._ENV = envName || this._DEFAULTENV this._CONFIG = _.merge( {} , confDefault , confExtend ) return this }
[ "function", "Config", "(", "defaults", ",", "extend", ",", "envName", ")", "{", "// Constants", "// -------------", "// test instance uniqueness", "this", ".", "_UID", "=", "_", ".", "uniqueId", "(", "'config_'", ")", "this", ".", "_DEFAULTENV", "=", "'default'", "// CORE's settings", "// ------------------------", "// default app configuration", "var", "confDefault", "=", "this", ".", "getConfigParam", "(", "defaults", ")", ",", "confExtend", "=", "(", "!", "_", ".", "isUndefined", "(", "extend", ")", ")", "?", "this", ".", "getConfigParam", "(", "extend", ")", ":", "{", "}", "this", ".", "_ENV", "=", "envName", "||", "this", ".", "_DEFAULTENV", "this", ".", "_CONFIG", "=", "_", ".", "merge", "(", "{", "}", ",", "confDefault", ",", "confExtend", ")", "return", "this", "}" ]
Initialize Config Class @params {mixed} object or file path @params {mixed} object or file path @return {object} Config instance
[ "Initialize", "Config", "Class" ]
476b589fb5d74b4093e6c3ebf0edcd8bfad16884
https://github.com/squid-app/config/blob/476b589fb5d74b4093e6c3ebf0edcd8bfad16884/index.js#L24-L52
50,317
vesln/obsessed
lib/async-runner.js
AsyncRunner
function AsyncRunner(times, fn) { Runner.apply(this, arguments); this.pause = 0; this.end = noop; this.times = times; }
javascript
function AsyncRunner(times, fn) { Runner.apply(this, arguments); this.pause = 0; this.end = noop; this.times = times; }
[ "function", "AsyncRunner", "(", "times", ",", "fn", ")", "{", "Runner", ".", "apply", "(", "this", ",", "arguments", ")", ";", "this", ".", "pause", "=", "0", ";", "this", ".", "end", "=", "noop", ";", "this", ".", "times", "=", "times", ";", "}" ]
Async task runner. @param {String|Number} times @param {Function} [optional] task to execute @constructor
[ "Async", "task", "runner", "." ]
4878dfafdea241bff9ad5c57acc2395a4f3487a6
https://github.com/vesln/obsessed/blob/4878dfafdea241bff9ad5c57acc2395a4f3487a6/lib/async-runner.js#L22-L28
50,318
tab58/minimatrix
src/utils.js
printMatrix2
function printMatrix2 (m) { const tStr = m.elements.map(formatPrintNumber); const matrixString = ` +- -+ | ${tStr[0]} ${tStr[2]} | | ${tStr[1]} ${tStr[3]} | +- -+`; return matrixString; }
javascript
function printMatrix2 (m) { const tStr = m.elements.map(formatPrintNumber); const matrixString = ` +- -+ | ${tStr[0]} ${tStr[2]} | | ${tStr[1]} ${tStr[3]} | +- -+`; return matrixString; }
[ "function", "printMatrix2", "(", "m", ")", "{", "const", "tStr", "=", "m", ".", "elements", ".", "map", "(", "formatPrintNumber", ")", ";", "const", "matrixString", "=", "`", "${", "tStr", "[", "0", "]", "}", "${", "tStr", "[", "2", "]", "}", "${", "tStr", "[", "1", "]", "}", "${", "tStr", "[", "3", "]", "}", "`", ";", "return", "matrixString", ";", "}" ]
Pretty prints a Matrix2. @memberof Utils @param {Matrix2} m The 2x2 matrix. @returns {string} The formatted string.
[ "Pretty", "prints", "a", "Matrix2", "." ]
542f1d964b7ae92f96b1069ff5f3495561fe75cd
https://github.com/tab58/minimatrix/blob/542f1d964b7ae92f96b1069ff5f3495561fe75cd/src/utils.js#L47-L55
50,319
tab58/minimatrix
src/utils.js
printMatrix3
function printMatrix3 (m) { const tStr = m.elements.map(formatPrintNumber); const matrixString = ` +- -+ | ${tStr[0]} ${tStr[3]} ${tStr[6]} | | ${tStr[1]} ${tStr[4]} ${tStr[7]} | | ${tStr[2]} ${tStr[5]} ${tStr[8]} | +- -+`; return matrixString; }
javascript
function printMatrix3 (m) { const tStr = m.elements.map(formatPrintNumber); const matrixString = ` +- -+ | ${tStr[0]} ${tStr[3]} ${tStr[6]} | | ${tStr[1]} ${tStr[4]} ${tStr[7]} | | ${tStr[2]} ${tStr[5]} ${tStr[8]} | +- -+`; return matrixString; }
[ "function", "printMatrix3", "(", "m", ")", "{", "const", "tStr", "=", "m", ".", "elements", ".", "map", "(", "formatPrintNumber", ")", ";", "const", "matrixString", "=", "`", "${", "tStr", "[", "0", "]", "}", "${", "tStr", "[", "3", "]", "}", "${", "tStr", "[", "6", "]", "}", "${", "tStr", "[", "1", "]", "}", "${", "tStr", "[", "4", "]", "}", "${", "tStr", "[", "7", "]", "}", "${", "tStr", "[", "2", "]", "}", "${", "tStr", "[", "5", "]", "}", "${", "tStr", "[", "8", "]", "}", "`", ";", "return", "matrixString", ";", "}" ]
Pretty prints a Matrix3. @memberof Utils @param {Matrix2} m The 3x3 matrix. @returns {string} The formatted string.
[ "Pretty", "prints", "a", "Matrix3", "." ]
542f1d964b7ae92f96b1069ff5f3495561fe75cd
https://github.com/tab58/minimatrix/blob/542f1d964b7ae92f96b1069ff5f3495561fe75cd/src/utils.js#L63-L72
50,320
benoror/node-pate
lib/pate.js
xpathFn
function xpathFn(token, rootEl, ns) { var split = token.trim().split('@'); var retVal = rootEl; var path = split[0].replace(/\/$/, "") || null; var attr = split[1] || null; if(path) retVal = retVal.get(path, ns); if(attr) { retVal = retVal ? retVal.attr(attr) : ""; retVal = retVal ? retVal.value() : ""; } else { retVal = retVal ? retVal.text() : ""; } return retVal; }
javascript
function xpathFn(token, rootEl, ns) { var split = token.trim().split('@'); var retVal = rootEl; var path = split[0].replace(/\/$/, "") || null; var attr = split[1] || null; if(path) retVal = retVal.get(path, ns); if(attr) { retVal = retVal ? retVal.attr(attr) : ""; retVal = retVal ? retVal.value() : ""; } else { retVal = retVal ? retVal.text() : ""; } return retVal; }
[ "function", "xpathFn", "(", "token", ",", "rootEl", ",", "ns", ")", "{", "var", "split", "=", "token", ".", "trim", "(", ")", ".", "split", "(", "'@'", ")", ";", "var", "retVal", "=", "rootEl", ";", "var", "path", "=", "split", "[", "0", "]", ".", "replace", "(", "/", "\\/$", "/", ",", "\"\"", ")", "||", "null", ";", "var", "attr", "=", "split", "[", "1", "]", "||", "null", ";", "if", "(", "path", ")", "retVal", "=", "retVal", ".", "get", "(", "path", ",", "ns", ")", ";", "if", "(", "attr", ")", "{", "retVal", "=", "retVal", "?", "retVal", ".", "attr", "(", "attr", ")", ":", "\"\"", ";", "retVal", "=", "retVal", "?", "retVal", ".", "value", "(", ")", ":", "\"\"", ";", "}", "else", "{", "retVal", "=", "retVal", "?", "retVal", ".", "text", "(", ")", ":", "\"\"", ";", "}", "return", "retVal", ";", "}" ]
XPatch matcher function
[ "XPatch", "matcher", "function" ]
869a6e82f588563d5dea6c892cb011505bba7ed3
https://github.com/benoror/node-pate/blob/869a6e82f588563d5dea6c892cb011505bba7ed3/lib/pate.js#L46-L64
50,321
benoror/node-pate
lib/pate.js
evalFn
function evalFn(token, format_lib) { var splited = token.trim().split(/[\(\)]/g); if (splited.length < 3) return token; if (!format_lib) return token var fnstring = splited[0]; var fnparams = splited.slice(1, splited.length - 1); var fn = format_lib[fnstring]; if (typeof fn !== "function") return ""; return fn.apply(null, fnparams); }
javascript
function evalFn(token, format_lib) { var splited = token.trim().split(/[\(\)]/g); if (splited.length < 3) return token; if (!format_lib) return token var fnstring = splited[0]; var fnparams = splited.slice(1, splited.length - 1); var fn = format_lib[fnstring]; if (typeof fn !== "function") return ""; return fn.apply(null, fnparams); }
[ "function", "evalFn", "(", "token", ",", "format_lib", ")", "{", "var", "splited", "=", "token", ".", "trim", "(", ")", ".", "split", "(", "/", "[\\(\\)]", "/", "g", ")", ";", "if", "(", "splited", ".", "length", "<", "3", ")", "return", "token", ";", "if", "(", "!", "format_lib", ")", "return", "token", "var", "fnstring", "=", "splited", "[", "0", "]", ";", "var", "fnparams", "=", "splited", ".", "slice", "(", "1", ",", "splited", ".", "length", "-", "1", ")", ";", "var", "fn", "=", "format_lib", "[", "fnstring", "]", ";", "if", "(", "typeof", "fn", "!==", "\"function\"", ")", "return", "\"\"", ";", "return", "fn", ".", "apply", "(", "null", ",", "fnparams", ")", ";", "}" ]
Eval matcher function
[ "Eval", "matcher", "function" ]
869a6e82f588563d5dea6c892cb011505bba7ed3
https://github.com/benoror/node-pate/blob/869a6e82f588563d5dea6c892cb011505bba7ed3/lib/pate.js#L69-L86
50,322
RikardLegge/modulin-fetch
src/modulin/css/modulizeCss.js
generateClassNameSubstitutions
function generateClassNameSubstitutions(tokens, substitutionPattern, substitutions) { tokens.forEach((tokenList)=> { var token = tokenList[0]; generateSubstitution(token, substitutionPattern, substitutions); }); }
javascript
function generateClassNameSubstitutions(tokens, substitutionPattern, substitutions) { tokens.forEach((tokenList)=> { var token = tokenList[0]; generateSubstitution(token, substitutionPattern, substitutions); }); }
[ "function", "generateClassNameSubstitutions", "(", "tokens", ",", "substitutionPattern", ",", "substitutions", ")", "{", "tokens", ".", "forEach", "(", "(", "tokenList", ")", "=>", "{", "var", "token", "=", "tokenList", "[", "0", "]", ";", "generateSubstitution", "(", "token", ",", "substitutionPattern", ",", "substitutions", ")", ";", "}", ")", ";", "}" ]
Generate an array of substitutions keyed by class name @param tokens Token[] @param substitutionPattern string @param substitutions {{string: string[]}} @returns {{string: string}}
[ "Generate", "an", "array", "of", "substitutions", "keyed", "by", "class", "name" ]
1a31b6b6957cfc7f608e233f10ac5050cd15bb5f
https://github.com/RikardLegge/modulin-fetch/blob/1a31b6b6957cfc7f608e233f10ac5050cd15bb5f/src/modulin/css/modulizeCss.js#L111-L116
50,323
RikardLegge/modulin-fetch
src/modulin/css/modulizeCss.js
generateSubstitution
function generateSubstitution(token, substitutionPattern, substitutions) { var substitution = substitutionPattern.replace(/{([^}]+)}/ig, (all, group)=> { switch (group) { case 'namespace': return token.namespace; case 'name': return token.className; case 'random': return 'r' + Math.random().toString(36).substring(7); case 'hash': return 'h' + (token.hash + 0.0).toString(36); case 'unique': return 'u' + (++uniqueCounter); } }); substitutions[token.className] = []; substitutions[token.className].push(substitution); return substitution; }
javascript
function generateSubstitution(token, substitutionPattern, substitutions) { var substitution = substitutionPattern.replace(/{([^}]+)}/ig, (all, group)=> { switch (group) { case 'namespace': return token.namespace; case 'name': return token.className; case 'random': return 'r' + Math.random().toString(36).substring(7); case 'hash': return 'h' + (token.hash + 0.0).toString(36); case 'unique': return 'u' + (++uniqueCounter); } }); substitutions[token.className] = []; substitutions[token.className].push(substitution); return substitution; }
[ "function", "generateSubstitution", "(", "token", ",", "substitutionPattern", ",", "substitutions", ")", "{", "var", "substitution", "=", "substitutionPattern", ".", "replace", "(", "/", "{([^}]+)}", "/", "ig", ",", "(", "all", ",", "group", ")", "=>", "{", "switch", "(", "group", ")", "{", "case", "'namespace'", ":", "return", "token", ".", "namespace", ";", "case", "'name'", ":", "return", "token", ".", "className", ";", "case", "'random'", ":", "return", "'r'", "+", "Math", ".", "random", "(", ")", ".", "toString", "(", "36", ")", ".", "substring", "(", "7", ")", ";", "case", "'hash'", ":", "return", "'h'", "+", "(", "token", ".", "hash", "+", "0.0", ")", ".", "toString", "(", "36", ")", ";", "case", "'unique'", ":", "return", "'u'", "+", "(", "++", "uniqueCounter", ")", ";", "}", "}", ")", ";", "substitutions", "[", "token", ".", "className", "]", "=", "[", "]", ";", "substitutions", "[", "token", ".", "className", "]", ".", "push", "(", "substitution", ")", ";", "return", "substitution", ";", "}" ]
Generate a substitution for the class or id selector @param token Token @param substitutionPattern string @param substitutions {{string: string[]}} @returns {string}
[ "Generate", "a", "substitution", "for", "the", "class", "or", "id", "selector" ]
1a31b6b6957cfc7f608e233f10ac5050cd15bb5f
https://github.com/RikardLegge/modulin-fetch/blob/1a31b6b6957cfc7f608e233f10ac5050cd15bb5f/src/modulin/css/modulizeCss.js#L126-L145
50,324
dpjanes/iotdb-errors
errors.js
Timestamp
function Timestamp(message, code_id) { Error.call(this); this.message = message || "timestamp out of date"; this.code_id = code_id || null; this.statusCode = 409; }
javascript
function Timestamp(message, code_id) { Error.call(this); this.message = message || "timestamp out of date"; this.code_id = code_id || null; this.statusCode = 409; }
[ "function", "Timestamp", "(", "message", ",", "code_id", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "this", ".", "message", "=", "message", "||", "\"timestamp out of date\"", ";", "this", ".", "code_id", "=", "code_id", "||", "null", ";", "this", ".", "statusCode", "=", "409", ";", "}" ]
Timestanp was out of date
[ "Timestanp", "was", "out", "of", "date" ]
15abf13b7666c4afc505b365bcf562cb85c44f84
https://github.com/dpjanes/iotdb-errors/blob/15abf13b7666c4afc505b365bcf562cb85c44f84/errors.js#L73-L78
50,325
dpjanes/iotdb-errors
errors.js
NotReady
function NotReady(message, code_id) { Error.call(this); this.message = message || "resource is not ready yet"; this.code_id = code_id || null; this.statusCode = 423; }
javascript
function NotReady(message, code_id) { Error.call(this); this.message = message || "resource is not ready yet"; this.code_id = code_id || null; this.statusCode = 423; }
[ "function", "NotReady", "(", "message", ",", "code_id", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "this", ".", "message", "=", "message", "||", "\"resource is not ready yet\"", ";", "this", ".", "code_id", "=", "code_id", "||", "null", ";", "this", ".", "statusCode", "=", "423", ";", "}" ]
waiting for some processing to happen
[ "waiting", "for", "some", "processing", "to", "happen" ]
15abf13b7666c4afc505b365bcf562cb85c44f84
https://github.com/dpjanes/iotdb-errors/blob/15abf13b7666c4afc505b365bcf562cb85c44f84/errors.js#L121-L126
50,326
dpjanes/iotdb-errors
errors.js
Locked
function Locked(message, code_id) { Error.call(this); this.message = message || "resource is locked" this.code_id = code_id || null; this.statusCode = 423; }
javascript
function Locked(message, code_id) { Error.call(this); this.message = message || "resource is locked" this.code_id = code_id || null; this.statusCode = 423; }
[ "function", "Locked", "(", "message", ",", "code_id", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "this", ".", "message", "=", "message", "||", "\"resource is locked\"", "this", ".", "code_id", "=", "code_id", "||", "null", ";", "this", ".", "statusCode", "=", "423", ";", "}" ]
Resource is Locked
[ "Resource", "is", "Locked" ]
15abf13b7666c4afc505b365bcf562cb85c44f84
https://github.com/dpjanes/iotdb-errors/blob/15abf13b7666c4afc505b365bcf562cb85c44f84/errors.js#L133-L138
50,327
dpjanes/iotdb-errors
errors.js
NeverImplemented
function NeverImplemented(message, code_id) { Error.call(this); this.message = message || "never will be implemented"; this.code_id = code_id || null; this.statusCode = 501; }
javascript
function NeverImplemented(message, code_id) { Error.call(this); this.message = message || "never will be implemented"; this.code_id = code_id || null; this.statusCode = 501; }
[ "function", "NeverImplemented", "(", "message", ",", "code_id", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "this", ".", "message", "=", "message", "||", "\"never will be implemented\"", ";", "this", ".", "code_id", "=", "code_id", "||", "null", ";", "this", ".", "statusCode", "=", "501", ";", "}" ]
This is not implemented and never will be implemented
[ "This", "is", "not", "implemented", "and", "never", "will", "be", "implemented" ]
15abf13b7666c4afc505b365bcf562cb85c44f84
https://github.com/dpjanes/iotdb-errors/blob/15abf13b7666c4afc505b365bcf562cb85c44f84/errors.js#L181-L186
50,328
dpjanes/iotdb-errors
errors.js
SetupRequired
function SetupRequired(message, code_id) { Error.call(this); this.message = message || "setup required"; this.code_id = code_id || null; this.statusCode = 500; }
javascript
function SetupRequired(message, code_id) { Error.call(this); this.message = message || "setup required"; this.code_id = code_id || null; this.statusCode = 500; }
[ "function", "SetupRequired", "(", "message", ",", "code_id", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "this", ".", "message", "=", "message", "||", "\"setup required\"", ";", "this", ".", "code_id", "=", "code_id", "||", "null", ";", "this", ".", "statusCode", "=", "500", ";", "}" ]
Additional setup is required
[ "Additional", "setup", "is", "required" ]
15abf13b7666c4afc505b365bcf562cb85c44f84
https://github.com/dpjanes/iotdb-errors/blob/15abf13b7666c4afc505b365bcf562cb85c44f84/errors.js#L193-L198
50,329
dpjanes/iotdb-errors
errors.js
Internal
function Internal(message, code_id) { Error.call(this); this.message = message || "internal error"; this.code_id = code_id || null; this.statusCode = 500; }
javascript
function Internal(message, code_id) { Error.call(this); this.message = message || "internal error"; this.code_id = code_id || null; this.statusCode = 500; }
[ "function", "Internal", "(", "message", ",", "code_id", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "this", ".", "message", "=", "message", "||", "\"internal error\"", ";", "this", ".", "code_id", "=", "code_id", "||", "null", ";", "this", ".", "statusCode", "=", "500", ";", "}" ]
Some sort of internal error
[ "Some", "sort", "of", "internal", "error" ]
15abf13b7666c4afc505b365bcf562cb85c44f84
https://github.com/dpjanes/iotdb-errors/blob/15abf13b7666c4afc505b365bcf562cb85c44f84/errors.js#L205-L210
50,330
dpjanes/iotdb-errors
errors.js
Unavailable
function Unavailable(message, code_id) { Error.call(this); this.message = message || "temporarily unavailable"; this.code_id = code_id || null; this.statusCode = 503; }
javascript
function Unavailable(message, code_id) { Error.call(this); this.message = message || "temporarily unavailable"; this.code_id = code_id || null; this.statusCode = 503; }
[ "function", "Unavailable", "(", "message", ",", "code_id", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "this", ".", "message", "=", "message", "||", "\"temporarily unavailable\"", ";", "this", ".", "code_id", "=", "code_id", "||", "null", ";", "this", ".", "statusCode", "=", "503", ";", "}" ]
Can't do this right now
[ "Can", "t", "do", "this", "right", "now" ]
15abf13b7666c4afc505b365bcf562cb85c44f84
https://github.com/dpjanes/iotdb-errors/blob/15abf13b7666c4afc505b365bcf562cb85c44f84/errors.js#L217-L222
50,331
angelini/lozigo
lib/lozigo.js
function() { var that = this; var boundEmitComplete = emitComplete.bind(this); EventEmitter.call(this); this.middleware = []; this.server = net.createServer(function(conn) { var buffer = ''; var info = null; conn.on('data', function(data) { buffer += data; if(!info) { if(buffer.indexOf('\f') !== -1) { var split = buffer.split('\f'); try { info = JSON.parse(split[0]); buffer = split[1]; } catch(e) { that.emit('error', e); } } } if(buffer && info) { handleEntries(buffer, info, that.middleware, boundEmitComplete); buffer = ''; } }); conn.on('end', function() { that.emit('end'); }); conn.on('error', function(err) { that.emit('error', err); }); }); }
javascript
function() { var that = this; var boundEmitComplete = emitComplete.bind(this); EventEmitter.call(this); this.middleware = []; this.server = net.createServer(function(conn) { var buffer = ''; var info = null; conn.on('data', function(data) { buffer += data; if(!info) { if(buffer.indexOf('\f') !== -1) { var split = buffer.split('\f'); try { info = JSON.parse(split[0]); buffer = split[1]; } catch(e) { that.emit('error', e); } } } if(buffer && info) { handleEntries(buffer, info, that.middleware, boundEmitComplete); buffer = ''; } }); conn.on('end', function() { that.emit('end'); }); conn.on('error', function(err) { that.emit('error', err); }); }); }
[ "function", "(", ")", "{", "var", "that", "=", "this", ";", "var", "boundEmitComplete", "=", "emitComplete", ".", "bind", "(", "this", ")", ";", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "middleware", "=", "[", "]", ";", "this", ".", "server", "=", "net", ".", "createServer", "(", "function", "(", "conn", ")", "{", "var", "buffer", "=", "''", ";", "var", "info", "=", "null", ";", "conn", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "buffer", "+=", "data", ";", "if", "(", "!", "info", ")", "{", "if", "(", "buffer", ".", "indexOf", "(", "'\\f'", ")", "!==", "-", "1", ")", "{", "var", "split", "=", "buffer", ".", "split", "(", "'\\f'", ")", ";", "try", "{", "info", "=", "JSON", ".", "parse", "(", "split", "[", "0", "]", ")", ";", "buffer", "=", "split", "[", "1", "]", ";", "}", "catch", "(", "e", ")", "{", "that", ".", "emit", "(", "'error'", ",", "e", ")", ";", "}", "}", "}", "if", "(", "buffer", "&&", "info", ")", "{", "handleEntries", "(", "buffer", ",", "info", ",", "that", ".", "middleware", ",", "boundEmitComplete", ")", ";", "buffer", "=", "''", ";", "}", "}", ")", ";", "conn", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "that", ".", "emit", "(", "'end'", ")", ";", "}", ")", ";", "conn", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "that", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Main Lozigo Object
[ "Main", "Lozigo", "Object" ]
bcca0cda8a7786493def08fd7189b1edb07091f9
https://github.com/angelini/lozigo/blob/bcca0cda8a7786493def08fd7189b1edb07091f9/lib/lozigo.js#L55-L96
50,332
nbrownus/ppunit
lib/reporters/XUnit.js
function (ppunit, writer) { writer.useColors = false BaseReporter.call(this, ppunit, writer) var self = this ppunit.on('finish', function () { writer.write( self.tag( 'testsuite' , { name: 'PPUnit Tests' , tests: ppunit.stats.tests , failures: ppunit.stats.failures , errors: ppunit.stats.failures , timestamp: (new Date).toUTCString() , time: (ppunit.stats.duration > 0) ? (ppunit.stats.duration / 1000) : 0 } , false ) ) ppunit.allTests.forEach(function (test) { if (test.type === Test.TYPE.ROOT) { return } self.printTest(test) }) writer.write('</testsuite>') }) }
javascript
function (ppunit, writer) { writer.useColors = false BaseReporter.call(this, ppunit, writer) var self = this ppunit.on('finish', function () { writer.write( self.tag( 'testsuite' , { name: 'PPUnit Tests' , tests: ppunit.stats.tests , failures: ppunit.stats.failures , errors: ppunit.stats.failures , timestamp: (new Date).toUTCString() , time: (ppunit.stats.duration > 0) ? (ppunit.stats.duration / 1000) : 0 } , false ) ) ppunit.allTests.forEach(function (test) { if (test.type === Test.TYPE.ROOT) { return } self.printTest(test) }) writer.write('</testsuite>') }) }
[ "function", "(", "ppunit", ",", "writer", ")", "{", "writer", ".", "useColors", "=", "false", "BaseReporter", ".", "call", "(", "this", ",", "ppunit", ",", "writer", ")", "var", "self", "=", "this", "ppunit", ".", "on", "(", "'finish'", ",", "function", "(", ")", "{", "writer", ".", "write", "(", "self", ".", "tag", "(", "'testsuite'", ",", "{", "name", ":", "'PPUnit Tests'", ",", "tests", ":", "ppunit", ".", "stats", ".", "tests", ",", "failures", ":", "ppunit", ".", "stats", ".", "failures", ",", "errors", ":", "ppunit", ".", "stats", ".", "failures", ",", "timestamp", ":", "(", "new", "Date", ")", ".", "toUTCString", "(", ")", ",", "time", ":", "(", "ppunit", ".", "stats", ".", "duration", ">", "0", ")", "?", "(", "ppunit", ".", "stats", ".", "duration", "/", "1000", ")", ":", "0", "}", ",", "false", ")", ")", "ppunit", ".", "allTests", ".", "forEach", "(", "function", "(", "test", ")", "{", "if", "(", "test", ".", "type", "===", "Test", ".", "TYPE", ".", "ROOT", ")", "{", "return", "}", "self", ".", "printTest", "(", "test", ")", "}", ")", "writer", ".", "write", "(", "'</testsuite>'", ")", "}", ")", "}" ]
Outputs xunit compatible xml for reporting test stats @extends BaseReporter
[ "Outputs", "xunit", "compatible", "xml", "for", "reporting", "test", "stats" ]
dcce602497d9548ce9085a8db115e65561dcc3de
https://github.com/nbrownus/ppunit/blob/dcce602497d9548ce9085a8db115e65561dcc3de/lib/reporters/XUnit.js#L11-L44
50,333
Crafity/crafity-storage
lib/providers/CouchDB.Provider.js
CouchDB
function CouchDB(config, nano) { if (!config) { throw new Error("Expected a CouchDB configuration"); } if (!config.url) { throw new Error("Expected a url in the CouchDB configuration"); } if (!config.database) { throw new Error("Expected a database name in the CouchDB configuration"); } if (!config.design) { throw new Error("Expected a design document name in the CouchDB configuration"); } if (!config.view) { throw new Error("Expected a view name in the CouchDB configuration"); } if (!/\/$/.test(config.url)) { config.url += "/"; } this.url = config.url; this.database = config.database; this.design = config.design; this.view = config.view; this.name = config.name; this.type = "CouchDB Provider"; this.config = config; this.__nano = nano || _nano; this.__provider = config.provider || this.__nano(this.url).db.use(this.database); }
javascript
function CouchDB(config, nano) { if (!config) { throw new Error("Expected a CouchDB configuration"); } if (!config.url) { throw new Error("Expected a url in the CouchDB configuration"); } if (!config.database) { throw new Error("Expected a database name in the CouchDB configuration"); } if (!config.design) { throw new Error("Expected a design document name in the CouchDB configuration"); } if (!config.view) { throw new Error("Expected a view name in the CouchDB configuration"); } if (!/\/$/.test(config.url)) { config.url += "/"; } this.url = config.url; this.database = config.database; this.design = config.design; this.view = config.view; this.name = config.name; this.type = "CouchDB Provider"; this.config = config; this.__nano = nano || _nano; this.__provider = config.provider || this.__nano(this.url).db.use(this.database); }
[ "function", "CouchDB", "(", "config", ",", "nano", ")", "{", "if", "(", "!", "config", ")", "{", "throw", "new", "Error", "(", "\"Expected a CouchDB configuration\"", ")", ";", "}", "if", "(", "!", "config", ".", "url", ")", "{", "throw", "new", "Error", "(", "\"Expected a url in the CouchDB configuration\"", ")", ";", "}", "if", "(", "!", "config", ".", "database", ")", "{", "throw", "new", "Error", "(", "\"Expected a database name in the CouchDB configuration\"", ")", ";", "}", "if", "(", "!", "config", ".", "design", ")", "{", "throw", "new", "Error", "(", "\"Expected a design document name in the CouchDB configuration\"", ")", ";", "}", "if", "(", "!", "config", ".", "view", ")", "{", "throw", "new", "Error", "(", "\"Expected a view name in the CouchDB configuration\"", ")", ";", "}", "if", "(", "!", "/", "\\/$", "/", ".", "test", "(", "config", ".", "url", ")", ")", "{", "config", ".", "url", "+=", "\"/\"", ";", "}", "this", ".", "url", "=", "config", ".", "url", ";", "this", ".", "database", "=", "config", ".", "database", ";", "this", ".", "design", "=", "config", ".", "design", ";", "this", ".", "view", "=", "config", ".", "view", ";", "this", ".", "name", "=", "config", ".", "name", ";", "this", ".", "type", "=", "\"CouchDB Provider\"", ";", "this", ".", "config", "=", "config", ";", "this", ".", "__nano", "=", "nano", "||", "_nano", ";", "this", ".", "__provider", "=", "config", ".", "provider", "||", "this", ".", "__nano", "(", "this", ".", "url", ")", ".", "db", ".", "use", "(", "this", ".", "database", ")", ";", "}" ]
CouchDB Provider Constructor @constructor
[ "CouchDB", "Provider", "Constructor" ]
1bea8268bc3deb85f9b07c63ce9ab3c5b989efe0
https://github.com/Crafity/crafity-storage/blob/1bea8268bc3deb85f9b07c63ce9ab3c5b989efe0/lib/providers/CouchDB.Provider.js#L23-L54
50,334
panezhang/ejs-extension-plus
lib/loader/ScriptLoader.class.js
function (path) { var foundPath = self.PathTool.findLibScript(path); if (foundPath) { self.scriptList.push(foundPath); } else { self.logger.warn('script:%s not found!', path); } }
javascript
function (path) { var foundPath = self.PathTool.findLibScript(path); if (foundPath) { self.scriptList.push(foundPath); } else { self.logger.warn('script:%s not found!', path); } }
[ "function", "(", "path", ")", "{", "var", "foundPath", "=", "self", ".", "PathTool", ".", "findLibScript", "(", "path", ")", ";", "if", "(", "foundPath", ")", "{", "self", ".", "scriptList", ".", "push", "(", "foundPath", ")", ";", "}", "else", "{", "self", ".", "logger", ".", "warn", "(", "'script:%s not found!'", ",", "path", ")", ";", "}", "}" ]
path to the static dir or id
[ "path", "to", "the", "static", "dir", "or", "id" ]
802cfc643eb1a42d6341ef2fa7c3a91efc64a16e
https://github.com/panezhang/ejs-extension-plus/blob/802cfc643eb1a42d6341ef2fa7c3a91efc64a16e/lib/loader/ScriptLoader.class.js#L40-L47
50,335
tauren/arrayize
index.js
arrayize
function arrayize(values) { // return empty array if values is empty if (typeof values === 'undefined' || values === null ) { return []; } // return array of values, converting to array if necessary return util.isArray(values) ? values : [values]; }
javascript
function arrayize(values) { // return empty array if values is empty if (typeof values === 'undefined' || values === null ) { return []; } // return array of values, converting to array if necessary return util.isArray(values) ? values : [values]; }
[ "function", "arrayize", "(", "values", ")", "{", "// return empty array if values is empty", "if", "(", "typeof", "values", "===", "'undefined'", "||", "values", "===", "null", ")", "{", "return", "[", "]", ";", "}", "// return array of values, converting to array if necessary", "return", "util", ".", "isArray", "(", "values", ")", "?", "values", ":", "[", "values", "]", ";", "}" ]
Make sure to always return an array. If passed undefined or null, return an empty array. If an array is passed, then return the array. If passed anything else, return an array containing that value. @param {*} values Array of values or a single value @return {Array} Array of values
[ "Make", "sure", "to", "always", "return", "an", "array", ".", "If", "passed", "undefined", "or", "null", "return", "an", "empty", "array", ".", "If", "an", "array", "is", "passed", "then", "return", "the", "array", ".", "If", "passed", "anything", "else", "return", "an", "array", "containing", "that", "value", "." ]
f5c08bee330ffa011b18e13adbecc80d2112af33
https://github.com/tauren/arrayize/blob/f5c08bee330ffa011b18e13adbecc80d2112af33/index.js#L14-L21
50,336
terminalvelocity/sails-generate-seeds-backend
lib/before.js
function() { // Combine random and case-specific factors into a base string var factors = { creationDate: (new Date()).getTime(), random: Math.random() * (Math.random() * 1000), nodeVersion: process.version }; var basestring = ''; _.each(factors, function (val) { basestring += val; }); // Build hash var hash = crypto. createHash('md5'). update(basestring). digest('hex'); return hash; }
javascript
function() { // Combine random and case-specific factors into a base string var factors = { creationDate: (new Date()).getTime(), random: Math.random() * (Math.random() * 1000), nodeVersion: process.version }; var basestring = ''; _.each(factors, function (val) { basestring += val; }); // Build hash var hash = crypto. createHash('md5'). update(basestring). digest('hex'); return hash; }
[ "function", "(", ")", "{", "// Combine random and case-specific factors into a base string", "var", "factors", "=", "{", "creationDate", ":", "(", "new", "Date", "(", ")", ")", ".", "getTime", "(", ")", ",", "random", ":", "Math", ".", "random", "(", ")", "*", "(", "Math", ".", "random", "(", ")", "*", "1000", ")", ",", "nodeVersion", ":", "process", ".", "version", "}", ";", "var", "basestring", "=", "''", ";", "_", ".", "each", "(", "factors", ",", "function", "(", "val", ")", "{", "basestring", "+=", "val", ";", "}", ")", ";", "// Build hash", "var", "hash", "=", "crypto", ".", "createHash", "(", "'md5'", ")", ".", "update", "(", "basestring", ")", ".", "digest", "(", "'hex'", ")", ";", "return", "hash", ";", "}" ]
Generate session secret @return {[type]} [description]
[ "Generate", "session", "secret" ]
9197acae0328163e0caba5ab2b61e38102c03193
https://github.com/terminalvelocity/sails-generate-seeds-backend/blob/9197acae0328163e0caba5ab2b61e38102c03193/lib/before.js#L16-L35
50,337
sinfo/ampersand-io-collection
ampersand-io-collection.js
function (id, options, cb) { if (arguments.length !== 3) { cb = options; options = {}; } var self = this; var model = this.get(id); if (model){ return cb(null, model); } function done() { var model = self.get(id); if (model) { if (cb){ cb(null, model); } } else { cb(new Error('not found')); } } if (options.all) { this.fetch({ callback: done }); } else { this.fetchById(id, cb); } }
javascript
function (id, options, cb) { if (arguments.length !== 3) { cb = options; options = {}; } var self = this; var model = this.get(id); if (model){ return cb(null, model); } function done() { var model = self.get(id); if (model) { if (cb){ cb(null, model); } } else { cb(new Error('not found')); } } if (options.all) { this.fetch({ callback: done }); } else { this.fetchById(id, cb); } }
[ "function", "(", "id", ",", "options", ",", "cb", ")", "{", "if", "(", "arguments", ".", "length", "!==", "3", ")", "{", "cb", "=", "options", ";", "options", "=", "{", "}", ";", "}", "var", "self", "=", "this", ";", "var", "model", "=", "this", ".", "get", "(", "id", ")", ";", "if", "(", "model", ")", "{", "return", "cb", "(", "null", ",", "model", ")", ";", "}", "function", "done", "(", ")", "{", "var", "model", "=", "self", ".", "get", "(", "id", ")", ";", "if", "(", "model", ")", "{", "if", "(", "cb", ")", "{", "cb", "(", "null", ",", "model", ")", ";", "}", "}", "else", "{", "cb", "(", "new", "Error", "(", "'not found'", ")", ")", ";", "}", "}", "if", "(", "options", ".", "all", ")", "{", "this", ".", "fetch", "(", "{", "callback", ":", "done", "}", ")", ";", "}", "else", "{", "this", ".", "fetchById", "(", "id", ",", "cb", ")", ";", "}", "}" ]
Get or fetch a model by Id.
[ "Get", "or", "fetch", "a", "model", "by", "Id", "." ]
81cd1ce246e5a84fe7ba881e8fa441e2f5cbbd67
https://github.com/sinfo/ampersand-io-collection/blob/81cd1ce246e5a84fe7ba881e8fa441e2f5cbbd67/ampersand-io-collection.js#L106-L133
50,338
sinfo/ampersand-io-collection
ampersand-io-collection.js
function(err, model, response, options){ if (options.cb){ options.cb(err, model, response); } if (err){ model.trigger('error', err, model, options); } }
javascript
function(err, model, response, options){ if (options.cb){ options.cb(err, model, response); } if (err){ model.trigger('error', err, model, options); } }
[ "function", "(", "err", ",", "model", ",", "response", ",", "options", ")", "{", "if", "(", "options", ".", "cb", ")", "{", "options", ".", "cb", "(", "err", ",", "model", ",", "response", ")", ";", "}", "if", "(", "err", ")", "{", "model", ".", "trigger", "(", "'error'", ",", "err", ",", "model", ",", "options", ")", ";", "}", "}" ]
Aux func used to trigger errors if they exist and use the optional callback function if given
[ "Aux", "func", "used", "to", "trigger", "errors", "if", "they", "exist", "and", "use", "the", "optional", "callback", "function", "if", "given" ]
81cd1ce246e5a84fe7ba881e8fa441e2f5cbbd67
https://github.com/sinfo/ampersand-io-collection/blob/81cd1ce246e5a84fe7ba881e8fa441e2f5cbbd67/ampersand-io-collection.js#L163-L170
50,339
el2iot2/grunt-hogan
example/Gruntfile.js
function(fileName) { //Grab the path package here locally for clarity var _path = require('path'); //'yada/yada/multi1.html' -> 'multi1' var name = _path .basename( fileName, _path.extname(fileName)); //'multi1' -> 'name_1' return 'name_'+name[5]; }
javascript
function(fileName) { //Grab the path package here locally for clarity var _path = require('path'); //'yada/yada/multi1.html' -> 'multi1' var name = _path .basename( fileName, _path.extname(fileName)); //'multi1' -> 'name_1' return 'name_'+name[5]; }
[ "function", "(", "fileName", ")", "{", "//Grab the path package here locally for clarity", "var", "_path", "=", "require", "(", "'path'", ")", ";", "//'yada/yada/multi1.html' -> 'multi1'", "var", "name", "=", "_path", ".", "basename", "(", "fileName", ",", "_path", ".", "extname", "(", "fileName", ")", ")", ";", "//'multi1' -> 'name_1'", "return", "'name_'", "+", "name", "[", "5", "]", ";", "}" ]
Specify a custom name function
[ "Specify", "a", "custom", "name", "function" ]
47962b7f63593c61fa0e2b0158f10bc6f8d51ca8
https://github.com/el2iot2/grunt-hogan/blob/47962b7f63593c61fa0e2b0158f10bc6f8d51ca8/example/Gruntfile.js#L64-L76
50,340
joneit/synonomous
index.js
function(name, transformations) { var synonyms = []; if (typeof name === 'string' && name) { transformations = transformations || this.transformations; if (!Array.isArray(transformations)) { transformations = Object.keys(transformations); } transformations.forEach(function(key) { if (typeof transformers[key] !== 'function') { throw new ReferenceError('Unknown transformer "' + key + '"'); } var synonym = transformers[key](name); if (synonym !== '' && !(synonym in synonyms)) { synonyms.push(synonym); } }); } return synonyms; }
javascript
function(name, transformations) { var synonyms = []; if (typeof name === 'string' && name) { transformations = transformations || this.transformations; if (!Array.isArray(transformations)) { transformations = Object.keys(transformations); } transformations.forEach(function(key) { if (typeof transformers[key] !== 'function') { throw new ReferenceError('Unknown transformer "' + key + '"'); } var synonym = transformers[key](name); if (synonym !== '' && !(synonym in synonyms)) { synonyms.push(synonym); } }); } return synonyms; }
[ "function", "(", "name", ",", "transformations", ")", "{", "var", "synonyms", "=", "[", "]", ";", "if", "(", "typeof", "name", "===", "'string'", "&&", "name", ")", "{", "transformations", "=", "transformations", "||", "this", ".", "transformations", ";", "if", "(", "!", "Array", ".", "isArray", "(", "transformations", ")", ")", "{", "transformations", "=", "Object", ".", "keys", "(", "transformations", ")", ";", "}", "transformations", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "typeof", "transformers", "[", "key", "]", "!==", "'function'", ")", "{", "throw", "new", "ReferenceError", "(", "'Unknown transformer \"'", "+", "key", "+", "'\"'", ")", ";", "}", "var", "synonym", "=", "transformers", "[", "key", "]", "(", "name", ")", ";", "if", "(", "synonym", "!==", "''", "&&", "!", "(", "synonym", "in", "synonyms", ")", ")", "{", "synonyms", ".", "push", "(", "synonym", ")", ";", "}", "}", ")", ";", "}", "return", "synonyms", ";", "}" ]
default for all instances, settable by Synonomous.prototype.dictPath setter If `name` is a string and non-blank, returns an array containing unique non-blank synonyms of `name` generated by the transformer functions named in `this.transformations`. @param {string} name - String to make synonyms of. @parma {string[]|object} transformations - When provided, temporarily overrides `this.transformations`. @memberOf Synonomous#
[ "default", "for", "all", "instances", "settable", "by", "Synonomous", ".", "prototype", ".", "dictPath", "setter", "If", "name", "is", "a", "string", "and", "non", "-", "blank", "returns", "an", "array", "containing", "unique", "non", "-", "blank", "synonyms", "of", "name", "generated", "by", "the", "transformer", "functions", "named", "in", "this", ".", "transformations", "." ]
38e1a540ef796050fa32ad4c229820d729648d1c
https://github.com/joneit/synonomous/blob/38e1a540ef796050fa32ad4c229820d729648d1c/index.js#L113-L131
50,341
sintaxi/yonder
lib/yonder.js
function(req, rsp, cb){ fs.readFile(path.resolve(routerPath), function(err, buff){ if (buff) { var arrs = buff2arrs(buff) return cb(arrs) } else { return cb(null) } }) }
javascript
function(req, rsp, cb){ fs.readFile(path.resolve(routerPath), function(err, buff){ if (buff) { var arrs = buff2arrs(buff) return cb(arrs) } else { return cb(null) } }) }
[ "function", "(", "req", ",", "rsp", ",", "cb", ")", "{", "fs", ".", "readFile", "(", "path", ".", "resolve", "(", "routerPath", ")", ",", "function", "(", "err", ",", "buff", ")", "{", "if", "(", "buff", ")", "{", "var", "arrs", "=", "buff2arrs", "(", "buff", ")", "return", "cb", "(", "arrs", ")", "}", "else", "{", "return", "cb", "(", "null", ")", "}", "}", ")", "}" ]
returns array of routes.
[ "returns", "array", "of", "routes", "." ]
6f50b36bf17cc348672089ecc71ad0f8d3f33698
https://github.com/sintaxi/yonder/blob/6f50b36bf17cc348672089ecc71ad0f8d3f33698/lib/yonder.js#L119-L128
50,342
byron-dupreez/aws-stream-consumer-core
batch.js
discardIfOverAttempted
function discardIfOverAttempted(tasksByName, count) { if (tasksByName) { taskUtils.getTasks(tasksByName).forEach(task => { const n = task.discardIfOverAttempted(maxNumberOfAttempts, true); if (count) overAttempted += n; }); } }
javascript
function discardIfOverAttempted(tasksByName, count) { if (tasksByName) { taskUtils.getTasks(tasksByName).forEach(task => { const n = task.discardIfOverAttempted(maxNumberOfAttempts, true); if (count) overAttempted += n; }); } }
[ "function", "discardIfOverAttempted", "(", "tasksByName", ",", "count", ")", "{", "if", "(", "tasksByName", ")", "{", "taskUtils", ".", "getTasks", "(", "tasksByName", ")", ".", "forEach", "(", "task", "=>", "{", "const", "n", "=", "task", ".", "discardIfOverAttempted", "(", "maxNumberOfAttempts", ",", "true", ")", ";", "if", "(", "count", ")", "overAttempted", "+=", "n", ";", "}", ")", ";", "}", "}" ]
Mark any over-attempted tasks as discarded
[ "Mark", "any", "over", "-", "attempted", "tasks", "as", "discarded" ]
9b256084297f80d373bcf483aaf68a9da176b3d7
https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/batch.js#L683-L690
50,343
nateGeorge/google-ims
index.js
Client
function Client (id, apiKey) { if (!(this instanceof Client)) { return new Client(id, apiKey); } this.endpoint = 'https://www.googleapis.com'; this.apiKey = apiKey; this.id = id; }
javascript
function Client (id, apiKey) { if (!(this instanceof Client)) { return new Client(id, apiKey); } this.endpoint = 'https://www.googleapis.com'; this.apiKey = apiKey; this.id = id; }
[ "function", "Client", "(", "id", ",", "apiKey", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Client", ")", ")", "{", "return", "new", "Client", "(", "id", ",", "apiKey", ")", ";", "}", "this", ".", "endpoint", "=", "'https://www.googleapis.com'", ";", "this", ".", "apiKey", "=", "apiKey", ";", "this", ".", "id", "=", "id", ";", "}" ]
Google Images Client
[ "Google", "Images", "Client" ]
60df00899a45c2b06fcd1e7767025aa1d252f420
https://github.com/nateGeorge/google-ims/blob/60df00899a45c2b06fcd1e7767025aa1d252f420/index.js#L14-L22
50,344
sendanor/nor-ref
src/ref.js
is_https
function is_https(req) { if(req.headers && req.headers['x-forwarded-proto'] && req.headers['x-forwarded-proto'] === 'https') { return true; } return (req && req.connection && req.connection.encrypted) ? true : false; }
javascript
function is_https(req) { if(req.headers && req.headers['x-forwarded-proto'] && req.headers['x-forwarded-proto'] === 'https') { return true; } return (req && req.connection && req.connection.encrypted) ? true : false; }
[ "function", "is_https", "(", "req", ")", "{", "if", "(", "req", ".", "headers", "&&", "req", ".", "headers", "[", "'x-forwarded-proto'", "]", "&&", "req", ".", "headers", "[", "'x-forwarded-proto'", "]", "===", "'https'", ")", "{", "return", "true", ";", "}", "return", "(", "req", "&&", "req", ".", "connection", "&&", "req", ".", "connection", ".", "encrypted", ")", "?", "true", ":", "false", ";", "}" ]
Check if connection is HTTPS
[ "Check", "if", "connection", "is", "HTTPS" ]
879667125e12317f63f99fea0344eb9dc298fdeb
https://github.com/sendanor/nor-ref/blob/879667125e12317f63f99fea0344eb9dc298fdeb/src/ref.js#L10-L13
50,345
jcare44/node-logmatic
src/logmatic.js
function(message) { if (!_.isObject(message)) { message = { message: message }; } try { message = JSON.stringify(_.defaultsDeep({}, message, this.config.defaultProps)); } catch (e) { return this.logger.error('Logmatic - error while parsing log message. Not sending', e); } if (this.isConnected) { this.sendMessage(message); } else { this.messageBuffer.push(message); } }
javascript
function(message) { if (!_.isObject(message)) { message = { message: message }; } try { message = JSON.stringify(_.defaultsDeep({}, message, this.config.defaultProps)); } catch (e) { return this.logger.error('Logmatic - error while parsing log message. Not sending', e); } if (this.isConnected) { this.sendMessage(message); } else { this.messageBuffer.push(message); } }
[ "function", "(", "message", ")", "{", "if", "(", "!", "_", ".", "isObject", "(", "message", ")", ")", "{", "message", "=", "{", "message", ":", "message", "}", ";", "}", "try", "{", "message", "=", "JSON", ".", "stringify", "(", "_", ".", "defaultsDeep", "(", "{", "}", ",", "message", ",", "this", ".", "config", ".", "defaultProps", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "this", ".", "logger", ".", "error", "(", "'Logmatic - error while parsing log message. Not sending'", ",", "e", ")", ";", "}", "if", "(", "this", ".", "isConnected", ")", "{", "this", ".", "sendMessage", "(", "message", ")", ";", "}", "else", "{", "this", ".", "messageBuffer", ".", "push", "(", "message", ")", ";", "}", "}" ]
Send log message @param {object|any} message
[ "Send", "log", "message" ]
5cbe6c5d0ae67929b3d159facb4f81c3cc8e6db5
https://github.com/jcare44/node-logmatic/blob/5cbe6c5d0ae67929b3d159facb4f81c3cc8e6db5/src/logmatic.js#L84-L102
50,346
dalekjs/dalek-driver-sauce
lib/commands/execute.js
function (script, args, hash) { this.actionQueue.push(this.webdriverClient.execute.bind(this.webdriverClient, {script: script.toString(), arguments: args})); this.actionQueue.push(this._setExecuteCb.bind(this, script.toString(), args, hash)); return this; }
javascript
function (script, args, hash) { this.actionQueue.push(this.webdriverClient.execute.bind(this.webdriverClient, {script: script.toString(), arguments: args})); this.actionQueue.push(this._setExecuteCb.bind(this, script.toString(), args, hash)); return this; }
[ "function", "(", "script", ",", "args", ",", "hash", ")", "{", "this", ".", "actionQueue", ".", "push", "(", "this", ".", "webdriverClient", ".", "execute", ".", "bind", "(", "this", ".", "webdriverClient", ",", "{", "script", ":", "script", ".", "toString", "(", ")", ",", "arguments", ":", "args", "}", ")", ")", ";", "this", ".", "actionQueue", ".", "push", "(", "this", ".", "_setExecuteCb", ".", "bind", "(", "this", ",", "script", ".", "toString", "(", ")", ",", "args", ",", "hash", ")", ")", ";", "return", "this", ";", "}" ]
Executes a JavaScript function @method execute @param {function} script Script to execute @param {array} args Arguments to pass to the function @param {string} hash Unique hash of that fn call @chainable
[ "Executes", "a", "JavaScript", "function" ]
4b3ef87a0c35a91db8456d074b0d47a3e0df58f7
https://github.com/dalekjs/dalek-driver-sauce/blob/4b3ef87a0c35a91db8456d074b0d47a3e0df58f7/lib/commands/execute.js#L50-L54
50,347
dalekjs/dalek-driver-sauce
lib/commands/execute.js
function (script, args, hash, data) { var deferred = Q.defer(); this.events.emit('driver:message', {key: 'execute', value: JSON.parse(data).value, uuid: hash, hash: hash}); deferred.resolve(); return deferred.promise; }
javascript
function (script, args, hash, data) { var deferred = Q.defer(); this.events.emit('driver:message', {key: 'execute', value: JSON.parse(data).value, uuid: hash, hash: hash}); deferred.resolve(); return deferred.promise; }
[ "function", "(", "script", ",", "args", ",", "hash", ",", "data", ")", "{", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "this", ".", "events", ".", "emit", "(", "'driver:message'", ",", "{", "key", ":", "'execute'", ",", "value", ":", "JSON", ".", "parse", "(", "data", ")", ".", "value", ",", "uuid", ":", "hash", ",", "hash", ":", "hash", "}", ")", ";", "deferred", ".", "resolve", "(", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Sends out an event with the results of the `execute` call @method _setExecuteCb @param {function} script Script to execute @param {array} args Arguments to pass to the function @param {string} hash Unique hash of that fn call @param {string} result Serialized JSON with the results of the call @return {object} promise Exists promise @private
[ "Sends", "out", "an", "event", "with", "the", "results", "of", "the", "execute", "call" ]
4b3ef87a0c35a91db8456d074b0d47a3e0df58f7
https://github.com/dalekjs/dalek-driver-sauce/blob/4b3ef87a0c35a91db8456d074b0d47a3e0df58f7/lib/commands/execute.js#L68-L73
50,348
dalekjs/dalek-driver-sauce
lib/commands/execute.js
function (script, args, timeout, hash) { this.actionQueue.push(this.webdriverClient.execute.bind(this.webdriverClient, {script: script.toString(), arguments: args})); this.actionQueue.push(this._waitForCb.bind(this, script.toString(), args, timeout, hash)); return this; }
javascript
function (script, args, timeout, hash) { this.actionQueue.push(this.webdriverClient.execute.bind(this.webdriverClient, {script: script.toString(), arguments: args})); this.actionQueue.push(this._waitForCb.bind(this, script.toString(), args, timeout, hash)); return this; }
[ "function", "(", "script", ",", "args", ",", "timeout", ",", "hash", ")", "{", "this", ".", "actionQueue", ".", "push", "(", "this", ".", "webdriverClient", ".", "execute", ".", "bind", "(", "this", ".", "webdriverClient", ",", "{", "script", ":", "script", ".", "toString", "(", ")", ",", "arguments", ":", "args", "}", ")", ")", ";", "this", ".", "actionQueue", ".", "push", "(", "this", ".", "_waitForCb", ".", "bind", "(", "this", ",", "script", ".", "toString", "(", ")", ",", "args", ",", "timeout", ",", "hash", ")", ")", ";", "return", "this", ";", "}" ]
Executes a JavaScript function until the timeout rans out or the function returns true @method execute @param {function} script Script to execute @param {array} args Arguments to pass to the function @param {integer} timeout Timeout of the function @param {string} hash Unique hash of that fn call @chainable
[ "Executes", "a", "JavaScript", "function", "until", "the", "timeout", "rans", "out", "or", "the", "function", "returns", "true" ]
4b3ef87a0c35a91db8456d074b0d47a3e0df58f7
https://github.com/dalekjs/dalek-driver-sauce/blob/4b3ef87a0c35a91db8456d074b0d47a3e0df58f7/lib/commands/execute.js#L87-L91
50,349
dalekjs/dalek-driver-sauce
lib/commands/execute.js
function (script, args, timeout, hash, data) { var deferred = Q.defer(); var ret = JSON.parse(data); var checker = function (yData) { if (JSON.parse(yData).value.userRet === true) { this.events.emit('driver:message', {key: 'waitFor', value: '', uuid: hash, hash: hash}); deferred.resolve(); } else { Q.when(this.webdriverClient.execute.bind(this.webdriverClient, {script: script, arguments: args})()) .then(checker); } }.bind(this); setTimeout(function () { this.events.emit('driver:message', {key: 'waitFor', value: 'Interrupted by timeout', uuid: hash, hash: hash}); deferred.resolve(); }.bind(this), timeout); if (ret.value.userRet === true) { this.events.emit('driver:message', {key: 'waitFor', value: '', uuid: hash, hash: hash}); deferred.resolve(); } else { Q.when(this.webdriverClient.execute.bind(this.webdriverClient, {script: script, arguments: args})()) .then(checker); } return deferred.promise; }
javascript
function (script, args, timeout, hash, data) { var deferred = Q.defer(); var ret = JSON.parse(data); var checker = function (yData) { if (JSON.parse(yData).value.userRet === true) { this.events.emit('driver:message', {key: 'waitFor', value: '', uuid: hash, hash: hash}); deferred.resolve(); } else { Q.when(this.webdriverClient.execute.bind(this.webdriverClient, {script: script, arguments: args})()) .then(checker); } }.bind(this); setTimeout(function () { this.events.emit('driver:message', {key: 'waitFor', value: 'Interrupted by timeout', uuid: hash, hash: hash}); deferred.resolve(); }.bind(this), timeout); if (ret.value.userRet === true) { this.events.emit('driver:message', {key: 'waitFor', value: '', uuid: hash, hash: hash}); deferred.resolve(); } else { Q.when(this.webdriverClient.execute.bind(this.webdriverClient, {script: script, arguments: args})()) .then(checker); } return deferred.promise; }
[ "function", "(", "script", ",", "args", ",", "timeout", ",", "hash", ",", "data", ")", "{", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "var", "ret", "=", "JSON", ".", "parse", "(", "data", ")", ";", "var", "checker", "=", "function", "(", "yData", ")", "{", "if", "(", "JSON", ".", "parse", "(", "yData", ")", ".", "value", ".", "userRet", "===", "true", ")", "{", "this", ".", "events", ".", "emit", "(", "'driver:message'", ",", "{", "key", ":", "'waitFor'", ",", "value", ":", "''", ",", "uuid", ":", "hash", ",", "hash", ":", "hash", "}", ")", ";", "deferred", ".", "resolve", "(", ")", ";", "}", "else", "{", "Q", ".", "when", "(", "this", ".", "webdriverClient", ".", "execute", ".", "bind", "(", "this", ".", "webdriverClient", ",", "{", "script", ":", "script", ",", "arguments", ":", "args", "}", ")", "(", ")", ")", ".", "then", "(", "checker", ")", ";", "}", "}", ".", "bind", "(", "this", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "this", ".", "events", ".", "emit", "(", "'driver:message'", ",", "{", "key", ":", "'waitFor'", ",", "value", ":", "'Interrupted by timeout'", ",", "uuid", ":", "hash", ",", "hash", ":", "hash", "}", ")", ";", "deferred", ".", "resolve", "(", ")", ";", "}", ".", "bind", "(", "this", ")", ",", "timeout", ")", ";", "if", "(", "ret", ".", "value", ".", "userRet", "===", "true", ")", "{", "this", ".", "events", ".", "emit", "(", "'driver:message'", ",", "{", "key", ":", "'waitFor'", ",", "value", ":", "''", ",", "uuid", ":", "hash", ",", "hash", ":", "hash", "}", ")", ";", "deferred", ".", "resolve", "(", ")", ";", "}", "else", "{", "Q", ".", "when", "(", "this", ".", "webdriverClient", ".", "execute", ".", "bind", "(", "this", ".", "webdriverClient", ",", "{", "script", ":", "script", ",", "arguments", ":", "args", "}", ")", "(", ")", ")", ".", "then", "(", "checker", ")", ";", "}", "return", "deferred", ".", "promise", ";", "}" ]
Sends out an event with the results of the `waitFor` call @method _setExecuteCb @param {function} script Script to execute @param {array} args Arguments to pass to the function @param {integer} timeout Timeout of the function @param {string} hash Unique hash of that fn call @param {string} data Serialized JSON with the reuslts of the toFrame call @return {object} Promise @private
[ "Sends", "out", "an", "event", "with", "the", "results", "of", "the", "waitFor", "call" ]
4b3ef87a0c35a91db8456d074b0d47a3e0df58f7
https://github.com/dalekjs/dalek-driver-sauce/blob/4b3ef87a0c35a91db8456d074b0d47a3e0df58f7/lib/commands/execute.js#L106-L133
50,350
dgalvez/Tere
node-http-proxy/lib/node-http-proxy/http-proxy.js
onUpgrade
function onUpgrade (reverseProxy, proxySocket) { if (!reverseProxy) { proxySocket.end(); socket.end(); return; } // // Any incoming data on this WebSocket to the proxy target // will be written to the `reverseProxy` socket. // proxySocket.on('data', listeners.onIncoming = function (data) { if (reverseProxy.incoming.socket.writable) { try { self.emit('websocket:outgoing', req, socket, head, data); var flushed = reverseProxy.incoming.socket.write(data); if (!flushed) { proxySocket.pause(); reverseProxy.incoming.socket.once('drain', function () { try { proxySocket.resume() } catch (er) { console.error("proxySocket.resume error: %s", er.message) } }); // // Force the `drain` event in 100ms if it hasn't // happened on its own. // setTimeout(function () { reverseProxy.incoming.socket.emit('drain'); }, 100); } } catch (ex) { detach(); } } }); // // Any outgoing data on this Websocket from the proxy target // will be written to the `proxySocket` socket. // reverseProxy.incoming.socket.on('data', listeners.onOutgoing = function (data) { try { self.emit('websocket:incoming', reverseProxy, reverseProxy.incoming, head, data); var flushed = proxySocket.write(data); if (!flushed) { reverseProxy.incoming.socket.pause(); proxySocket.once('drain', function () { try { reverseProxy.incoming.socket.resume() } catch (er) { console.error("reverseProxy.incoming.socket.resume error: %s", er.message) } }); // // Force the `drain` event in 100ms if it hasn't // happened on its own. // setTimeout(function () { proxySocket.emit('drain'); }, 100); } } catch (ex) { detach(); } }); // // Helper function to detach all event listeners // from `reverseProxy` and `proxySocket`. // function detach() { proxySocket.destroySoon(); proxySocket.removeListener('end', listeners.onIncomingClose); proxySocket.removeListener('data', listeners.onIncoming); reverseProxy.incoming.socket.destroySoon(); reverseProxy.incoming.socket.removeListener('end', listeners.onOutgoingClose); reverseProxy.incoming.socket.removeListener('data', listeners.onOutgoing); } // // If the incoming `proxySocket` socket closes, then // detach all event listeners. // proxySocket.on('end', listeners.onIncomingClose = function() { detach(); // Emit the `end` event now that we have completed proxying self.emit('websocket:end', req, socket, head); }); // // If the `reverseProxy` socket closes, then detach all // event listeners. // reverseProxy.incoming.socket.on('end', listeners.onOutgoingClose = function() { detach(); }); }
javascript
function onUpgrade (reverseProxy, proxySocket) { if (!reverseProxy) { proxySocket.end(); socket.end(); return; } // // Any incoming data on this WebSocket to the proxy target // will be written to the `reverseProxy` socket. // proxySocket.on('data', listeners.onIncoming = function (data) { if (reverseProxy.incoming.socket.writable) { try { self.emit('websocket:outgoing', req, socket, head, data); var flushed = reverseProxy.incoming.socket.write(data); if (!flushed) { proxySocket.pause(); reverseProxy.incoming.socket.once('drain', function () { try { proxySocket.resume() } catch (er) { console.error("proxySocket.resume error: %s", er.message) } }); // // Force the `drain` event in 100ms if it hasn't // happened on its own. // setTimeout(function () { reverseProxy.incoming.socket.emit('drain'); }, 100); } } catch (ex) { detach(); } } }); // // Any outgoing data on this Websocket from the proxy target // will be written to the `proxySocket` socket. // reverseProxy.incoming.socket.on('data', listeners.onOutgoing = function (data) { try { self.emit('websocket:incoming', reverseProxy, reverseProxy.incoming, head, data); var flushed = proxySocket.write(data); if (!flushed) { reverseProxy.incoming.socket.pause(); proxySocket.once('drain', function () { try { reverseProxy.incoming.socket.resume() } catch (er) { console.error("reverseProxy.incoming.socket.resume error: %s", er.message) } }); // // Force the `drain` event in 100ms if it hasn't // happened on its own. // setTimeout(function () { proxySocket.emit('drain'); }, 100); } } catch (ex) { detach(); } }); // // Helper function to detach all event listeners // from `reverseProxy` and `proxySocket`. // function detach() { proxySocket.destroySoon(); proxySocket.removeListener('end', listeners.onIncomingClose); proxySocket.removeListener('data', listeners.onIncoming); reverseProxy.incoming.socket.destroySoon(); reverseProxy.incoming.socket.removeListener('end', listeners.onOutgoingClose); reverseProxy.incoming.socket.removeListener('data', listeners.onOutgoing); } // // If the incoming `proxySocket` socket closes, then // detach all event listeners. // proxySocket.on('end', listeners.onIncomingClose = function() { detach(); // Emit the `end` event now that we have completed proxying self.emit('websocket:end', req, socket, head); }); // // If the `reverseProxy` socket closes, then detach all // event listeners. // reverseProxy.incoming.socket.on('end', listeners.onOutgoingClose = function() { detach(); }); }
[ "function", "onUpgrade", "(", "reverseProxy", ",", "proxySocket", ")", "{", "if", "(", "!", "reverseProxy", ")", "{", "proxySocket", ".", "end", "(", ")", ";", "socket", ".", "end", "(", ")", ";", "return", ";", "}", "//", "// Any incoming data on this WebSocket to the proxy target", "// will be written to the `reverseProxy` socket.", "//", "proxySocket", ".", "on", "(", "'data'", ",", "listeners", ".", "onIncoming", "=", "function", "(", "data", ")", "{", "if", "(", "reverseProxy", ".", "incoming", ".", "socket", ".", "writable", ")", "{", "try", "{", "self", ".", "emit", "(", "'websocket:outgoing'", ",", "req", ",", "socket", ",", "head", ",", "data", ")", ";", "var", "flushed", "=", "reverseProxy", ".", "incoming", ".", "socket", ".", "write", "(", "data", ")", ";", "if", "(", "!", "flushed", ")", "{", "proxySocket", ".", "pause", "(", ")", ";", "reverseProxy", ".", "incoming", ".", "socket", ".", "once", "(", "'drain'", ",", "function", "(", ")", "{", "try", "{", "proxySocket", ".", "resume", "(", ")", "}", "catch", "(", "er", ")", "{", "console", ".", "error", "(", "\"proxySocket.resume error: %s\"", ",", "er", ".", "message", ")", "}", "}", ")", ";", "//", "// Force the `drain` event in 100ms if it hasn't", "// happened on its own.", "//", "setTimeout", "(", "function", "(", ")", "{", "reverseProxy", ".", "incoming", ".", "socket", ".", "emit", "(", "'drain'", ")", ";", "}", ",", "100", ")", ";", "}", "}", "catch", "(", "ex", ")", "{", "detach", "(", ")", ";", "}", "}", "}", ")", ";", "//", "// Any outgoing data on this Websocket from the proxy target", "// will be written to the `proxySocket` socket.", "//", "reverseProxy", ".", "incoming", ".", "socket", ".", "on", "(", "'data'", ",", "listeners", ".", "onOutgoing", "=", "function", "(", "data", ")", "{", "try", "{", "self", ".", "emit", "(", "'websocket:incoming'", ",", "reverseProxy", ",", "reverseProxy", ".", "incoming", ",", "head", ",", "data", ")", ";", "var", "flushed", "=", "proxySocket", ".", "write", "(", "data", ")", ";", "if", "(", "!", "flushed", ")", "{", "reverseProxy", ".", "incoming", ".", "socket", ".", "pause", "(", ")", ";", "proxySocket", ".", "once", "(", "'drain'", ",", "function", "(", ")", "{", "try", "{", "reverseProxy", ".", "incoming", ".", "socket", ".", "resume", "(", ")", "}", "catch", "(", "er", ")", "{", "console", ".", "error", "(", "\"reverseProxy.incoming.socket.resume error: %s\"", ",", "er", ".", "message", ")", "}", "}", ")", ";", "//", "// Force the `drain` event in 100ms if it hasn't", "// happened on its own.", "//", "setTimeout", "(", "function", "(", ")", "{", "proxySocket", ".", "emit", "(", "'drain'", ")", ";", "}", ",", "100", ")", ";", "}", "}", "catch", "(", "ex", ")", "{", "detach", "(", ")", ";", "}", "}", ")", ";", "//", "// Helper function to detach all event listeners", "// from `reverseProxy` and `proxySocket`.", "//", "function", "detach", "(", ")", "{", "proxySocket", ".", "destroySoon", "(", ")", ";", "proxySocket", ".", "removeListener", "(", "'end'", ",", "listeners", ".", "onIncomingClose", ")", ";", "proxySocket", ".", "removeListener", "(", "'data'", ",", "listeners", ".", "onIncoming", ")", ";", "reverseProxy", ".", "incoming", ".", "socket", ".", "destroySoon", "(", ")", ";", "reverseProxy", ".", "incoming", ".", "socket", ".", "removeListener", "(", "'end'", ",", "listeners", ".", "onOutgoingClose", ")", ";", "reverseProxy", ".", "incoming", ".", "socket", ".", "removeListener", "(", "'data'", ",", "listeners", ".", "onOutgoing", ")", ";", "}", "//", "// If the incoming `proxySocket` socket closes, then", "// detach all event listeners.", "//", "proxySocket", ".", "on", "(", "'end'", ",", "listeners", ".", "onIncomingClose", "=", "function", "(", ")", "{", "detach", "(", ")", ";", "// Emit the `end` event now that we have completed proxying", "self", ".", "emit", "(", "'websocket:end'", ",", "req", ",", "socket", ",", "head", ")", ";", "}", ")", ";", "//", "// If the `reverseProxy` socket closes, then detach all", "// event listeners.", "//", "reverseProxy", ".", "incoming", ".", "socket", ".", "on", "(", "'end'", ",", "listeners", ".", "onOutgoingClose", "=", "function", "(", ")", "{", "detach", "(", ")", ";", "}", ")", ";", "}" ]
On `upgrade` from the Agent socket, listen to the appropriate events.
[ "On", "upgrade", "from", "the", "Agent", "socket", "listen", "to", "the", "appropriate", "events", "." ]
0b0dcfb1871fea668ad987807e3ed3d8365ab885
https://github.com/dgalvez/Tere/blob/0b0dcfb1871fea668ad987807e3ed3d8365ab885/node-http-proxy/lib/node-http-proxy/http-proxy.js#L475-L573
50,351
dgalvez/Tere
node-http-proxy/lib/node-http-proxy/http-proxy.js
detach
function detach() { proxySocket.destroySoon(); proxySocket.removeListener('end', listeners.onIncomingClose); proxySocket.removeListener('data', listeners.onIncoming); reverseProxy.incoming.socket.destroySoon(); reverseProxy.incoming.socket.removeListener('end', listeners.onOutgoingClose); reverseProxy.incoming.socket.removeListener('data', listeners.onOutgoing); }
javascript
function detach() { proxySocket.destroySoon(); proxySocket.removeListener('end', listeners.onIncomingClose); proxySocket.removeListener('data', listeners.onIncoming); reverseProxy.incoming.socket.destroySoon(); reverseProxy.incoming.socket.removeListener('end', listeners.onOutgoingClose); reverseProxy.incoming.socket.removeListener('data', listeners.onOutgoing); }
[ "function", "detach", "(", ")", "{", "proxySocket", ".", "destroySoon", "(", ")", ";", "proxySocket", ".", "removeListener", "(", "'end'", ",", "listeners", ".", "onIncomingClose", ")", ";", "proxySocket", ".", "removeListener", "(", "'data'", ",", "listeners", ".", "onIncoming", ")", ";", "reverseProxy", ".", "incoming", ".", "socket", ".", "destroySoon", "(", ")", ";", "reverseProxy", ".", "incoming", ".", "socket", ".", "removeListener", "(", "'end'", ",", "listeners", ".", "onOutgoingClose", ")", ";", "reverseProxy", ".", "incoming", ".", "socket", ".", "removeListener", "(", "'data'", ",", "listeners", ".", "onOutgoing", ")", ";", "}" ]
Helper function to detach all event listeners from `reverseProxy` and `proxySocket`.
[ "Helper", "function", "to", "detach", "all", "event", "listeners", "from", "reverseProxy", "and", "proxySocket", "." ]
0b0dcfb1871fea668ad987807e3ed3d8365ab885
https://github.com/dgalvez/Tere/blob/0b0dcfb1871fea668ad987807e3ed3d8365ab885/node-http-proxy/lib/node-http-proxy/http-proxy.js#L546-L553
50,352
dgalvez/Tere
node-http-proxy/lib/node-http-proxy/http-proxy.js
proxyError
function proxyError (err) { reverseProxy.destroy(); process.nextTick(function () { // // Destroy the incoming socket in the next tick, in case the error handler // wants to write to it. // socket.destroy(); }); self.emit('webSocketProxyError', req, socket, head); }
javascript
function proxyError (err) { reverseProxy.destroy(); process.nextTick(function () { // // Destroy the incoming socket in the next tick, in case the error handler // wants to write to it. // socket.destroy(); }); self.emit('webSocketProxyError', req, socket, head); }
[ "function", "proxyError", "(", "err", ")", "{", "reverseProxy", ".", "destroy", "(", ")", ";", "process", ".", "nextTick", "(", "function", "(", ")", "{", "//", "// Destroy the incoming socket in the next tick, in case the error handler", "// wants to write to it.", "//", "socket", ".", "destroy", "(", ")", ";", "}", ")", ";", "self", ".", "emit", "(", "'webSocketProxyError'", ",", "req", ",", "socket", ",", "head", ")", ";", "}" ]
On any errors from the `reverseProxy` emit the `webSocketProxyError` and close the appropriate connections.
[ "On", "any", "errors", "from", "the", "reverseProxy", "emit", "the", "webSocketProxyError", "and", "close", "the", "appropriate", "connections", "." ]
0b0dcfb1871fea668ad987807e3ed3d8365ab885
https://github.com/dgalvez/Tere/blob/0b0dcfb1871fea668ad987807e3ed3d8365ab885/node-http-proxy/lib/node-http-proxy/http-proxy.js#L615-L627
50,353
jaredhanson/crane-amqp
lib/broker.js
Broker
function Broker(options) { EventEmitter.call(this); this._exchange = null; this._queues = {}; this._ctags = {}; this._options = options; }
javascript
function Broker(options) { EventEmitter.call(this); this._exchange = null; this._queues = {}; this._ctags = {}; this._options = options; }
[ "function", "Broker", "(", "options", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "_exchange", "=", "null", ";", "this", ".", "_queues", "=", "{", "}", ";", "this", ".", "_ctags", "=", "{", "}", ";", "this", ".", "_options", "=", "options", ";", "}" ]
`Broker` constructor. @api public
[ "Broker", "constructor", "." ]
2f2a653a5567550d035daf8a2587fac0ebc9d8ce
https://github.com/jaredhanson/crane-amqp/blob/2f2a653a5567550d035daf8a2587fac0ebc9d8ce/lib/broker.js#L26-L33
50,354
ottojs/otto-errors
lib/save.error.js
ErrorSave
function ErrorSave (message) { Error.call(this); // Add Information this.name = 'ErrorSave'; this.type = 'server'; this.status = 500; if (message) { this.message = message; } }
javascript
function ErrorSave (message) { Error.call(this); // Add Information this.name = 'ErrorSave'; this.type = 'server'; this.status = 500; if (message) { this.message = message; } }
[ "function", "ErrorSave", "(", "message", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "// Add Information", "this", ".", "name", "=", "'ErrorSave'", ";", "this", ".", "type", "=", "'server'", ";", "this", ".", "status", "=", "500", ";", "if", "(", "message", ")", "{", "this", ".", "message", "=", "message", ";", "}", "}" ]
Error - ErrorSave
[ "Error", "-", "ErrorSave" ]
a3c6d98fd5d35ce3c136ed7e1edd2f800af268d9
https://github.com/ottojs/otto-errors/blob/a3c6d98fd5d35ce3c136ed7e1edd2f800af268d9/lib/save.error.js#L8-L20
50,355
AtlasIQ/makedeb
lib/validate.js
isRealDirectory
function isRealDirectory(p) { var stats; try { stats = fs.statSync(p); } catch (error) { // Not a valid path if stat fails. return false; } return (stats.isDirectory()); }
javascript
function isRealDirectory(p) { var stats; try { stats = fs.statSync(p); } catch (error) { // Not a valid path if stat fails. return false; } return (stats.isDirectory()); }
[ "function", "isRealDirectory", "(", "p", ")", "{", "var", "stats", ";", "try", "{", "stats", "=", "fs", ".", "statSync", "(", "p", ")", ";", "}", "catch", "(", "error", ")", "{", "// Not a valid path if stat fails.", "return", "false", ";", "}", "return", "(", "stats", ".", "isDirectory", "(", ")", ")", ";", "}" ]
Expects that a path points to a real directory.
[ "Expects", "that", "a", "path", "points", "to", "a", "real", "directory", "." ]
017719bc0e0d3594a05d7b30af2430c635e49363
https://github.com/AtlasIQ/makedeb/blob/017719bc0e0d3594a05d7b30af2430c635e49363/lib/validate.js#L15-L25
50,356
dwilhelm89/RandomGeoJSON
index.js
generatePolygon
function generatePolygon() { var coordNumber = getRandomNumber(3, options.maxCoordCount); var feature = rawFeature(); feature.geometry.type = 'Polygon'; feature.geometry.coordinates = [ [] ]; var firstCoordinate = generateLonLat(); feature.geometry.coordinates[0].push(firstCoordinate); addCoordinates(feature.geometry.coordinates[0], coordNumber - 2); feature.geometry.coordinates[0].push(firstCoordinate); return feature; }
javascript
function generatePolygon() { var coordNumber = getRandomNumber(3, options.maxCoordCount); var feature = rawFeature(); feature.geometry.type = 'Polygon'; feature.geometry.coordinates = [ [] ]; var firstCoordinate = generateLonLat(); feature.geometry.coordinates[0].push(firstCoordinate); addCoordinates(feature.geometry.coordinates[0], coordNumber - 2); feature.geometry.coordinates[0].push(firstCoordinate); return feature; }
[ "function", "generatePolygon", "(", ")", "{", "var", "coordNumber", "=", "getRandomNumber", "(", "3", ",", "options", ".", "maxCoordCount", ")", ";", "var", "feature", "=", "rawFeature", "(", ")", ";", "feature", ".", "geometry", ".", "type", "=", "'Polygon'", ";", "feature", ".", "geometry", ".", "coordinates", "=", "[", "[", "]", "]", ";", "var", "firstCoordinate", "=", "generateLonLat", "(", ")", ";", "feature", ".", "geometry", ".", "coordinates", "[", "0", "]", ".", "push", "(", "firstCoordinate", ")", ";", "addCoordinates", "(", "feature", ".", "geometry", ".", "coordinates", "[", "0", "]", ",", "coordNumber", "-", "2", ")", ";", "feature", ".", "geometry", ".", "coordinates", "[", "0", "]", ".", "push", "(", "firstCoordinate", ")", ";", "return", "feature", ";", "}" ]
Generates a Polygon @return {Object} GeoJSON Polygon
[ "Generates", "a", "Polygon" ]
539070dcbf6e67fcb6c4047c24dfb9588a702de9
https://github.com/dwilhelm89/RandomGeoJSON/blob/539070dcbf6e67fcb6c4047c24dfb9588a702de9/index.js#L42-L58
50,357
dwilhelm89/RandomGeoJSON
index.js
generateLineString
function generateLineString() { var coordNumber = getRandomNumber(3, options.maxCoordCount); var feature = rawFeature(); feature.geometry.type = 'LineString'; addCoordinates(feature.geometry.coordinates, coordNumber); return feature; }
javascript
function generateLineString() { var coordNumber = getRandomNumber(3, options.maxCoordCount); var feature = rawFeature(); feature.geometry.type = 'LineString'; addCoordinates(feature.geometry.coordinates, coordNumber); return feature; }
[ "function", "generateLineString", "(", ")", "{", "var", "coordNumber", "=", "getRandomNumber", "(", "3", ",", "options", ".", "maxCoordCount", ")", ";", "var", "feature", "=", "rawFeature", "(", ")", ";", "feature", ".", "geometry", ".", "type", "=", "'LineString'", ";", "addCoordinates", "(", "feature", ".", "geometry", ".", "coordinates", ",", "coordNumber", ")", ";", "return", "feature", ";", "}" ]
Generates a LineString @return {Object} GeoJSON LineString
[ "Generates", "a", "LineString" ]
539070dcbf6e67fcb6c4047c24dfb9588a702de9
https://github.com/dwilhelm89/RandomGeoJSON/blob/539070dcbf6e67fcb6c4047c24dfb9588a702de9/index.js#L65-L74
50,358
dwilhelm89/RandomGeoJSON
index.js
generateFeatures
function generateFeatures() { var collection = { type: 'FeatureCollection', features: [] }; for (var i = 0; i < options.number; i++) { collection.features.push(generateFeature(randomType())); } return collection; }
javascript
function generateFeatures() { var collection = { type: 'FeatureCollection', features: [] }; for (var i = 0; i < options.number; i++) { collection.features.push(generateFeature(randomType())); } return collection; }
[ "function", "generateFeatures", "(", ")", "{", "var", "collection", "=", "{", "type", ":", "'FeatureCollection'", ",", "features", ":", "[", "]", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "options", ".", "number", ";", "i", "++", ")", "{", "collection", ".", "features", ".", "push", "(", "generateFeature", "(", "randomType", "(", ")", ")", ")", ";", "}", "return", "collection", ";", "}" ]
Creates a FeatureCollection and adds features @return {Object} GeoJSON FeatureCollection
[ "Creates", "a", "FeatureCollection", "and", "adds", "features" ]
539070dcbf6e67fcb6c4047c24dfb9588a702de9
https://github.com/dwilhelm89/RandomGeoJSON/blob/539070dcbf6e67fcb6c4047c24dfb9588a702de9/index.js#L115-L125
50,359
dwilhelm89/RandomGeoJSON
index.js
addCoordinates
function addCoordinates(coordArray, number) { for (var i = 0; i < number; i++) { coordArray.push(generateLonLat()); } }
javascript
function addCoordinates(coordArray, number) { for (var i = 0; i < number; i++) { coordArray.push(generateLonLat()); } }
[ "function", "addCoordinates", "(", "coordArray", ",", "number", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "number", ";", "i", "++", ")", "{", "coordArray", ".", "push", "(", "generateLonLat", "(", ")", ")", ";", "}", "}" ]
Adds a random coordinate to an array @param {Array} coordArray the coordinate array @param {Number} number amount of coordinates which should be added
[ "Adds", "a", "random", "coordinate", "to", "an", "array" ]
539070dcbf6e67fcb6c4047c24dfb9588a702de9
https://github.com/dwilhelm89/RandomGeoJSON/blob/539070dcbf6e67fcb6c4047c24dfb9588a702de9/index.js#L163-L167
50,360
Becklyn/becklyn-gulp
tasks/js_simple.js
compileSingleFile
function compileSingleFile (filePath, isDebug, options) { var outputPath = "./" + path.dirname(filePath).replace(/(^|\/)assets\/js/, "$1public/js"); var uglifyOptions = {}; gulpUtil.log(gulpUtil.colors.blue("Uglify"), pathHelper.makeRelative(filePath), " -> ", pathHelper.makeRelative(outputPath) + "/" + path.basename(filePath)); if (options.lint) { jsHintHelper.lintFile(filePath); } if (isDebug) { uglifyOptions.compress = false; uglifyOptions.preserveComments = "all"; } return gulp.src(filePath) .pipe(plumber()) .pipe(uglify(uglifyOptions)) .pipe(gulp.dest(outputPath)); }
javascript
function compileSingleFile (filePath, isDebug, options) { var outputPath = "./" + path.dirname(filePath).replace(/(^|\/)assets\/js/, "$1public/js"); var uglifyOptions = {}; gulpUtil.log(gulpUtil.colors.blue("Uglify"), pathHelper.makeRelative(filePath), " -> ", pathHelper.makeRelative(outputPath) + "/" + path.basename(filePath)); if (options.lint) { jsHintHelper.lintFile(filePath); } if (isDebug) { uglifyOptions.compress = false; uglifyOptions.preserveComments = "all"; } return gulp.src(filePath) .pipe(plumber()) .pipe(uglify(uglifyOptions)) .pipe(gulp.dest(outputPath)); }
[ "function", "compileSingleFile", "(", "filePath", ",", "isDebug", ",", "options", ")", "{", "var", "outputPath", "=", "\"./\"", "+", "path", ".", "dirname", "(", "filePath", ")", ".", "replace", "(", "/", "(^|\\/)assets\\/js", "/", ",", "\"$1public/js\"", ")", ";", "var", "uglifyOptions", "=", "{", "}", ";", "gulpUtil", ".", "log", "(", "gulpUtil", ".", "colors", ".", "blue", "(", "\"Uglify\"", ")", ",", "pathHelper", ".", "makeRelative", "(", "filePath", ")", ",", "\" -> \"", ",", "pathHelper", ".", "makeRelative", "(", "outputPath", ")", "+", "\"/\"", "+", "path", ".", "basename", "(", "filePath", ")", ")", ";", "if", "(", "options", ".", "lint", ")", "{", "jsHintHelper", ".", "lintFile", "(", "filePath", ")", ";", "}", "if", "(", "isDebug", ")", "{", "uglifyOptions", ".", "compress", "=", "false", ";", "uglifyOptions", ".", "preserveComments", "=", "\"all\"", ";", "}", "return", "gulp", ".", "src", "(", "filePath", ")", ".", "pipe", "(", "plumber", "(", ")", ")", ".", "pipe", "(", "uglify", "(", "uglifyOptions", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "outputPath", ")", ")", ";", "}" ]
Compiles a single file @param {string} filePath @param {boolean} isDebug @param {UglifyTaskOptions} options @returns {*}
[ "Compiles", "a", "single", "file" ]
1c633378d561f07101f9db19ccd153617b8e0252
https://github.com/Becklyn/becklyn-gulp/blob/1c633378d561f07101f9db19ccd153617b8e0252/tasks/js_simple.js#L31-L53
50,361
tylerbeck/grunt-bower-map
classes/BowerMap.js
validateParameters
function validateParameters() { grunt.verbose.writeln( 'BowerMap::validateParameters' ); //flag used to determine if validation passes var check = true; //lib path must be set //TODO: get default bowerpath from .bowerrc bowerPath = bowerPath || "bower_components"; if ( typeof bowerPath !== 'string' ) { grunt.log.error( 'Bower path must be a string.' ); check = false; } //lib path must be set if ( !destPath || typeof destPath !== 'string' ) { grunt.log.error( 'Default destination path must be configured.' ); check = false; } //shim isn't required, but must be a key value object shim = shim || {}; if ( typeof shim !== "object" ) { grunt.log.error( 'shim must be an object.' ); check = false; } //map isn't required, but must be a key value object map = map || {}; if ( typeof map !== "object" ) { grunt.log.error( 'map must be an object.' ); check = false; } //ignore isn't required, but must be an array ignore = ignore || []; if ( !Array.isArray( ignore ) ) { grunt.log.error( 'ignore must be an array of strings.' ); check = false; } //maintainCommonPaths isn't required, but must be boolean maintainCommonPaths = maintainCommonPaths || false; if ( typeof maintainCommonPaths !== "boolean" ) { grunt.log.error( 'maintainCommonPaths must be a boolean value.' ); check = false; } //useNamespace isn't required, but must be undefined or boolean if ( useNamespace !== undefined && typeof useNamespace !== "boolean" ) { grunt.log.error( 'useNamespace must be boolean or undefined.' ); check = false; } //extensions isn't required, but must be an array extensions = extensions || undefined; if ( extensions !== undefined && !Array.isArray( extensions ) ) { grunt.log.error( 'extensions must be an array or undefined.' ); check = false; } return check; }
javascript
function validateParameters() { grunt.verbose.writeln( 'BowerMap::validateParameters' ); //flag used to determine if validation passes var check = true; //lib path must be set //TODO: get default bowerpath from .bowerrc bowerPath = bowerPath || "bower_components"; if ( typeof bowerPath !== 'string' ) { grunt.log.error( 'Bower path must be a string.' ); check = false; } //lib path must be set if ( !destPath || typeof destPath !== 'string' ) { grunt.log.error( 'Default destination path must be configured.' ); check = false; } //shim isn't required, but must be a key value object shim = shim || {}; if ( typeof shim !== "object" ) { grunt.log.error( 'shim must be an object.' ); check = false; } //map isn't required, but must be a key value object map = map || {}; if ( typeof map !== "object" ) { grunt.log.error( 'map must be an object.' ); check = false; } //ignore isn't required, but must be an array ignore = ignore || []; if ( !Array.isArray( ignore ) ) { grunt.log.error( 'ignore must be an array of strings.' ); check = false; } //maintainCommonPaths isn't required, but must be boolean maintainCommonPaths = maintainCommonPaths || false; if ( typeof maintainCommonPaths !== "boolean" ) { grunt.log.error( 'maintainCommonPaths must be a boolean value.' ); check = false; } //useNamespace isn't required, but must be undefined or boolean if ( useNamespace !== undefined && typeof useNamespace !== "boolean" ) { grunt.log.error( 'useNamespace must be boolean or undefined.' ); check = false; } //extensions isn't required, but must be an array extensions = extensions || undefined; if ( extensions !== undefined && !Array.isArray( extensions ) ) { grunt.log.error( 'extensions must be an array or undefined.' ); check = false; } return check; }
[ "function", "validateParameters", "(", ")", "{", "grunt", ".", "verbose", ".", "writeln", "(", "'BowerMap::validateParameters'", ")", ";", "//flag used to determine if validation passes", "var", "check", "=", "true", ";", "//lib path must be set", "//TODO: get default bowerpath from .bowerrc", "bowerPath", "=", "bowerPath", "||", "\"bower_components\"", ";", "if", "(", "typeof", "bowerPath", "!==", "'string'", ")", "{", "grunt", ".", "log", ".", "error", "(", "'Bower path must be a string.'", ")", ";", "check", "=", "false", ";", "}", "//lib path must be set", "if", "(", "!", "destPath", "||", "typeof", "destPath", "!==", "'string'", ")", "{", "grunt", ".", "log", ".", "error", "(", "'Default destination path must be configured.'", ")", ";", "check", "=", "false", ";", "}", "//shim isn't required, but must be a key value object", "shim", "=", "shim", "||", "{", "}", ";", "if", "(", "typeof", "shim", "!==", "\"object\"", ")", "{", "grunt", ".", "log", ".", "error", "(", "'shim must be an object.'", ")", ";", "check", "=", "false", ";", "}", "//map isn't required, but must be a key value object", "map", "=", "map", "||", "{", "}", ";", "if", "(", "typeof", "map", "!==", "\"object\"", ")", "{", "grunt", ".", "log", ".", "error", "(", "'map must be an object.'", ")", ";", "check", "=", "false", ";", "}", "//ignore isn't required, but must be an array", "ignore", "=", "ignore", "||", "[", "]", ";", "if", "(", "!", "Array", ".", "isArray", "(", "ignore", ")", ")", "{", "grunt", ".", "log", ".", "error", "(", "'ignore must be an array of strings.'", ")", ";", "check", "=", "false", ";", "}", "//maintainCommonPaths isn't required, but must be boolean", "maintainCommonPaths", "=", "maintainCommonPaths", "||", "false", ";", "if", "(", "typeof", "maintainCommonPaths", "!==", "\"boolean\"", ")", "{", "grunt", ".", "log", ".", "error", "(", "'maintainCommonPaths must be a boolean value.'", ")", ";", "check", "=", "false", ";", "}", "//useNamespace isn't required, but must be undefined or boolean", "if", "(", "useNamespace", "!==", "undefined", "&&", "typeof", "useNamespace", "!==", "\"boolean\"", ")", "{", "grunt", ".", "log", ".", "error", "(", "'useNamespace must be boolean or undefined.'", ")", ";", "check", "=", "false", ";", "}", "//extensions isn't required, but must be an array", "extensions", "=", "extensions", "||", "undefined", ";", "if", "(", "extensions", "!==", "undefined", "&&", "!", "Array", ".", "isArray", "(", "extensions", ")", ")", "{", "grunt", ".", "log", ".", "error", "(", "'extensions must be an array or undefined.'", ")", ";", "check", "=", "false", ";", "}", "return", "check", ";", "}" ]
validates bower copy task parameters @returns {boolean}
[ "validates", "bower", "copy", "task", "parameters" ]
b72e43719123a8a1c09eff5bea48fe494693cb1d
https://github.com/tylerbeck/grunt-bower-map/blob/b72e43719123a8a1c09eff5bea48fe494693cb1d/classes/BowerMap.js#L103-L164
50,362
tylerbeck/grunt-bower-map
classes/BowerMap.js
handleListResults
function handleListResults( results ) { grunt.verbose.writeln( 'BowerMap::handleListResults' ); for ( var k in results ) { if ( results.hasOwnProperty( k ) ) { grunt.verbose.writeln( '------------------------------------' ); grunt.verbose.writeln( ' ' + k + ' - ' + results[k] ); if ( ignore.indexOf( k ) >= 0 ){ grunt.verbose.writeln( ' ' + k + ' - IGNORED' ); } else{ copyComponentFiles( k, results[k] ); } } } done(); }
javascript
function handleListResults( results ) { grunt.verbose.writeln( 'BowerMap::handleListResults' ); for ( var k in results ) { if ( results.hasOwnProperty( k ) ) { grunt.verbose.writeln( '------------------------------------' ); grunt.verbose.writeln( ' ' + k + ' - ' + results[k] ); if ( ignore.indexOf( k ) >= 0 ){ grunt.verbose.writeln( ' ' + k + ' - IGNORED' ); } else{ copyComponentFiles( k, results[k] ); } } } done(); }
[ "function", "handleListResults", "(", "results", ")", "{", "grunt", ".", "verbose", ".", "writeln", "(", "'BowerMap::handleListResults'", ")", ";", "for", "(", "var", "k", "in", "results", ")", "{", "if", "(", "results", ".", "hasOwnProperty", "(", "k", ")", ")", "{", "grunt", ".", "verbose", ".", "writeln", "(", "'------------------------------------'", ")", ";", "grunt", ".", "verbose", ".", "writeln", "(", "' '", "+", "k", "+", "' - '", "+", "results", "[", "k", "]", ")", ";", "if", "(", "ignore", ".", "indexOf", "(", "k", ")", ">=", "0", ")", "{", "grunt", ".", "verbose", ".", "writeln", "(", "' '", "+", "k", "+", "' - IGNORED'", ")", ";", "}", "else", "{", "copyComponentFiles", "(", "k", ",", "results", "[", "k", "]", ")", ";", "}", "}", "}", "done", "(", ")", ";", "}" ]
bower list results handler @param results
[ "bower", "list", "results", "handler" ]
b72e43719123a8a1c09eff5bea48fe494693cb1d
https://github.com/tylerbeck/grunt-bower-map/blob/b72e43719123a8a1c09eff5bea48fe494693cb1d/classes/BowerMap.js#L283-L299
50,363
tylerbeck/grunt-bower-map
classes/BowerMap.js
copyComponentFiles
function copyComponentFiles( name, files ) { grunt.verbose.writeln( 'BowerMap::copyComponentFiles - ' + name ); //get map of files to copy var componentMap = getComponentMapping( name, files ); //copy files for ( var k in componentMap ) { if ( componentMap.hasOwnProperty( k ) ) { //console.log( path.fix( k ) ); //console.log( path.fix( componentMap[ k ] ) ); //grunt.file.copy( path.fix( k ), path.fix( componentMap[ k ] ) ); var replacements = replace ? replace[ name ] || false : false; if ( componentMap[ k ] !== false){ copyReplace( path.fix( k ), path.fix( componentMap[ k ] ), replacements ); } } } }
javascript
function copyComponentFiles( name, files ) { grunt.verbose.writeln( 'BowerMap::copyComponentFiles - ' + name ); //get map of files to copy var componentMap = getComponentMapping( name, files ); //copy files for ( var k in componentMap ) { if ( componentMap.hasOwnProperty( k ) ) { //console.log( path.fix( k ) ); //console.log( path.fix( componentMap[ k ] ) ); //grunt.file.copy( path.fix( k ), path.fix( componentMap[ k ] ) ); var replacements = replace ? replace[ name ] || false : false; if ( componentMap[ k ] !== false){ copyReplace( path.fix( k ), path.fix( componentMap[ k ] ), replacements ); } } } }
[ "function", "copyComponentFiles", "(", "name", ",", "files", ")", "{", "grunt", ".", "verbose", ".", "writeln", "(", "'BowerMap::copyComponentFiles - '", "+", "name", ")", ";", "//get map of files to copy", "var", "componentMap", "=", "getComponentMapping", "(", "name", ",", "files", ")", ";", "//copy files", "for", "(", "var", "k", "in", "componentMap", ")", "{", "if", "(", "componentMap", ".", "hasOwnProperty", "(", "k", ")", ")", "{", "//console.log( path.fix( k ) );", "//console.log( path.fix( componentMap[ k ] ) );", "//grunt.file.copy( path.fix( k ), path.fix( componentMap[ k ] ) );", "var", "replacements", "=", "replace", "?", "replace", "[", "name", "]", "||", "false", ":", "false", ";", "if", "(", "componentMap", "[", "k", "]", "!==", "false", ")", "{", "copyReplace", "(", "path", ".", "fix", "(", "k", ")", ",", "path", ".", "fix", "(", "componentMap", "[", "k", "]", ")", ",", "replacements", ")", ";", "}", "}", "}", "}" ]
copies specified component files based on mapping @param name @param files @returns {boolean}
[ "copies", "specified", "component", "files", "based", "on", "mapping" ]
b72e43719123a8a1c09eff5bea48fe494693cb1d
https://github.com/tylerbeck/grunt-bower-map/blob/b72e43719123a8a1c09eff5bea48fe494693cb1d/classes/BowerMap.js#L308-L327
50,364
tylerbeck/grunt-bower-map
classes/BowerMap.js
getComponentMapping
function getComponentMapping( name, files ) { grunt.verbose.writeln( 'BowerMap::getComponentMapping - ' + name ); //first get list of all files var fileList = []; if ( shim[ name ] !== undefined ) { grunt.verbose.writeln( ' using shim value' ); //use shim value fileList = fileList.concat( shim[ name ] ); } else { grunt.verbose.writeln( ' using result value - ' + files ); //make sure files is an array if (typeof files === 'string'){ files = [files]; } //we just need the path relative to the module directory files.forEach( function( file ){ file = path.fix( file ); fileList.push( file.replace( path.fix( path.join( bowerPath, name ) ) , "" ) ); }); } //expand list var expandedList = []; fileList.forEach( function( file ){ grunt.verbose.writeln( ' globbing - ' + path.join( name, file ) ); glob.sync( path.join( name, file ), { cwd: bowerPath, dot: true } ).forEach( function( filename ) { var src = path.fix( path.join( bowerPath, filename ) ); grunt.verbose.writeln( 'src ' + src ); expandedList.push( src ); }); }); //filter filetypes expandedList = expandedList.filter( function( file ){ var ext = path.extname( file ).substr(1); if ( extensions ){ return extensions.indexOf( ext ) >= 0; } else{ return true; } }); //get common path for building destination var commonPath = maintainCommonPaths ? "" : getCommonPathBase( expandedList ); grunt.verbose.writeln( ' common path: ' + commonPath ); //build default mapping var componentMap = {}; grunt.verbose.writeln( ' mapping files:' ); expandedList.forEach( function( file ){ if ( expandedMap[ file ] !== undefined ) { //use user configured mapping if set componentMap[ file ] = expandedMap[ file ]; grunt.log.writeln( ' * '+file+' -> '+ expandedMap[ file ] ); } else { var newFilename = commonPath === "" ? file : file.replace( commonPath, "" ); //console.log(' newfileName:',newFilename); var dest = path.join( destPath, newFilename ); //console.log(' dest:',dest); if ( useNamespace === true || ( useNamespace === undefined && expandedList.length > 1 ) ){ dest = dest.replace( destPath, path.join( destPath, name ) ); } componentMap[ file ] = dest; grunt.log.writeln( ' '+file+' -> '+ dest ); } }); return componentMap; }
javascript
function getComponentMapping( name, files ) { grunt.verbose.writeln( 'BowerMap::getComponentMapping - ' + name ); //first get list of all files var fileList = []; if ( shim[ name ] !== undefined ) { grunt.verbose.writeln( ' using shim value' ); //use shim value fileList = fileList.concat( shim[ name ] ); } else { grunt.verbose.writeln( ' using result value - ' + files ); //make sure files is an array if (typeof files === 'string'){ files = [files]; } //we just need the path relative to the module directory files.forEach( function( file ){ file = path.fix( file ); fileList.push( file.replace( path.fix( path.join( bowerPath, name ) ) , "" ) ); }); } //expand list var expandedList = []; fileList.forEach( function( file ){ grunt.verbose.writeln( ' globbing - ' + path.join( name, file ) ); glob.sync( path.join( name, file ), { cwd: bowerPath, dot: true } ).forEach( function( filename ) { var src = path.fix( path.join( bowerPath, filename ) ); grunt.verbose.writeln( 'src ' + src ); expandedList.push( src ); }); }); //filter filetypes expandedList = expandedList.filter( function( file ){ var ext = path.extname( file ).substr(1); if ( extensions ){ return extensions.indexOf( ext ) >= 0; } else{ return true; } }); //get common path for building destination var commonPath = maintainCommonPaths ? "" : getCommonPathBase( expandedList ); grunt.verbose.writeln( ' common path: ' + commonPath ); //build default mapping var componentMap = {}; grunt.verbose.writeln( ' mapping files:' ); expandedList.forEach( function( file ){ if ( expandedMap[ file ] !== undefined ) { //use user configured mapping if set componentMap[ file ] = expandedMap[ file ]; grunt.log.writeln( ' * '+file+' -> '+ expandedMap[ file ] ); } else { var newFilename = commonPath === "" ? file : file.replace( commonPath, "" ); //console.log(' newfileName:',newFilename); var dest = path.join( destPath, newFilename ); //console.log(' dest:',dest); if ( useNamespace === true || ( useNamespace === undefined && expandedList.length > 1 ) ){ dest = dest.replace( destPath, path.join( destPath, name ) ); } componentMap[ file ] = dest; grunt.log.writeln( ' '+file+' -> '+ dest ); } }); return componentMap; }
[ "function", "getComponentMapping", "(", "name", ",", "files", ")", "{", "grunt", ".", "verbose", ".", "writeln", "(", "'BowerMap::getComponentMapping - '", "+", "name", ")", ";", "//first get list of all files", "var", "fileList", "=", "[", "]", ";", "if", "(", "shim", "[", "name", "]", "!==", "undefined", ")", "{", "grunt", ".", "verbose", ".", "writeln", "(", "' using shim value'", ")", ";", "//use shim value", "fileList", "=", "fileList", ".", "concat", "(", "shim", "[", "name", "]", ")", ";", "}", "else", "{", "grunt", ".", "verbose", ".", "writeln", "(", "' using result value - '", "+", "files", ")", ";", "//make sure files is an array", "if", "(", "typeof", "files", "===", "'string'", ")", "{", "files", "=", "[", "files", "]", ";", "}", "//we just need the path relative to the module directory", "files", ".", "forEach", "(", "function", "(", "file", ")", "{", "file", "=", "path", ".", "fix", "(", "file", ")", ";", "fileList", ".", "push", "(", "file", ".", "replace", "(", "path", ".", "fix", "(", "path", ".", "join", "(", "bowerPath", ",", "name", ")", ")", ",", "\"\"", ")", ")", ";", "}", ")", ";", "}", "//expand list", "var", "expandedList", "=", "[", "]", ";", "fileList", ".", "forEach", "(", "function", "(", "file", ")", "{", "grunt", ".", "verbose", ".", "writeln", "(", "' globbing - '", "+", "path", ".", "join", "(", "name", ",", "file", ")", ")", ";", "glob", ".", "sync", "(", "path", ".", "join", "(", "name", ",", "file", ")", ",", "{", "cwd", ":", "bowerPath", ",", "dot", ":", "true", "}", ")", ".", "forEach", "(", "function", "(", "filename", ")", "{", "var", "src", "=", "path", ".", "fix", "(", "path", ".", "join", "(", "bowerPath", ",", "filename", ")", ")", ";", "grunt", ".", "verbose", ".", "writeln", "(", "'src '", "+", "src", ")", ";", "expandedList", ".", "push", "(", "src", ")", ";", "}", ")", ";", "}", ")", ";", "//filter filetypes", "expandedList", "=", "expandedList", ".", "filter", "(", "function", "(", "file", ")", "{", "var", "ext", "=", "path", ".", "extname", "(", "file", ")", ".", "substr", "(", "1", ")", ";", "if", "(", "extensions", ")", "{", "return", "extensions", ".", "indexOf", "(", "ext", ")", ">=", "0", ";", "}", "else", "{", "return", "true", ";", "}", "}", ")", ";", "//get common path for building destination", "var", "commonPath", "=", "maintainCommonPaths", "?", "\"\"", ":", "getCommonPathBase", "(", "expandedList", ")", ";", "grunt", ".", "verbose", ".", "writeln", "(", "' common path: '", "+", "commonPath", ")", ";", "//build default mapping", "var", "componentMap", "=", "{", "}", ";", "grunt", ".", "verbose", ".", "writeln", "(", "' mapping files:'", ")", ";", "expandedList", ".", "forEach", "(", "function", "(", "file", ")", "{", "if", "(", "expandedMap", "[", "file", "]", "!==", "undefined", ")", "{", "//use user configured mapping if set", "componentMap", "[", "file", "]", "=", "expandedMap", "[", "file", "]", ";", "grunt", ".", "log", ".", "writeln", "(", "' * '", "+", "file", "+", "' -> '", "+", "expandedMap", "[", "file", "]", ")", ";", "}", "else", "{", "var", "newFilename", "=", "commonPath", "===", "\"\"", "?", "file", ":", "file", ".", "replace", "(", "commonPath", ",", "\"\"", ")", ";", "//console.log(' newfileName:',newFilename);", "var", "dest", "=", "path", ".", "join", "(", "destPath", ",", "newFilename", ")", ";", "//console.log(' dest:',dest);", "if", "(", "useNamespace", "===", "true", "||", "(", "useNamespace", "===", "undefined", "&&", "expandedList", ".", "length", ">", "1", ")", ")", "{", "dest", "=", "dest", ".", "replace", "(", "destPath", ",", "path", ".", "join", "(", "destPath", ",", "name", ")", ")", ";", "}", "componentMap", "[", "file", "]", "=", "dest", ";", "grunt", ".", "log", ".", "writeln", "(", "' '", "+", "file", "+", "' -> '", "+", "dest", ")", ";", "}", "}", ")", ";", "return", "componentMap", ";", "}" ]
gets file mapping for specified component @param name @param files @returns {{}}
[ "gets", "file", "mapping", "for", "specified", "component" ]
b72e43719123a8a1c09eff5bea48fe494693cb1d
https://github.com/tylerbeck/grunt-bower-map/blob/b72e43719123a8a1c09eff5bea48fe494693cb1d/classes/BowerMap.js#L335-L415
50,365
tylerbeck/grunt-bower-map
classes/BowerMap.js
getCommonPathBase
function getCommonPathBase( paths ) { var list = []; var minLength = 999999999; var commonPath = ""; //break up paths into parts paths.forEach( function( file ) { //normalize path seperators file = file.replace( pathSepRegExp, path.sep ); //get resolved path parts for file directory if ( file.charAt(0) === path.sep ){ file = file.substr(1); } //console.log(" "+file); //console.log(" "+path.dirname( file )); var dirname = path.dirname( file ); var parts = dirname === "." ? [] : dirname.split( path.sep ); list.push( parts ); //save minimum path length for next step minLength = Math.min( minLength, parts.length ); } ); var listLength = list.length; grunt.verbose.writeln( JSON.stringify( list, undefined, " ") ); //check for common parts if ( listLength > 1 ) { var common = true; var index = -1; //iterate parts up to minLength for ( var i = 0; i < minLength; i++ ) { for ( var j = 1; j < listLength; j++ ) { if ( list[ j ][ i ] !== list[ j - 1 ][ i ] ) { common = false; break; } } if ( !common ) { index = i; break; } } //catch case where all paths are common if ( index < 0 ){ index = minLength; } //build new paths array //for ( var n=0; n<listLength; n++ ) { // newPaths.push( path.join( list[n].slice( index ) ) ); //} commonPath = list[0].slice( 0, index ).join( path.sep ); } else if ( listLength === 1 ) { commonPath = list[0].join( path.sep ); } return commonPath; }
javascript
function getCommonPathBase( paths ) { var list = []; var minLength = 999999999; var commonPath = ""; //break up paths into parts paths.forEach( function( file ) { //normalize path seperators file = file.replace( pathSepRegExp, path.sep ); //get resolved path parts for file directory if ( file.charAt(0) === path.sep ){ file = file.substr(1); } //console.log(" "+file); //console.log(" "+path.dirname( file )); var dirname = path.dirname( file ); var parts = dirname === "." ? [] : dirname.split( path.sep ); list.push( parts ); //save minimum path length for next step minLength = Math.min( minLength, parts.length ); } ); var listLength = list.length; grunt.verbose.writeln( JSON.stringify( list, undefined, " ") ); //check for common parts if ( listLength > 1 ) { var common = true; var index = -1; //iterate parts up to minLength for ( var i = 0; i < minLength; i++ ) { for ( var j = 1; j < listLength; j++ ) { if ( list[ j ][ i ] !== list[ j - 1 ][ i ] ) { common = false; break; } } if ( !common ) { index = i; break; } } //catch case where all paths are common if ( index < 0 ){ index = minLength; } //build new paths array //for ( var n=0; n<listLength; n++ ) { // newPaths.push( path.join( list[n].slice( index ) ) ); //} commonPath = list[0].slice( 0, index ).join( path.sep ); } else if ( listLength === 1 ) { commonPath = list[0].join( path.sep ); } return commonPath; }
[ "function", "getCommonPathBase", "(", "paths", ")", "{", "var", "list", "=", "[", "]", ";", "var", "minLength", "=", "999999999", ";", "var", "commonPath", "=", "\"\"", ";", "//break up paths into parts", "paths", ".", "forEach", "(", "function", "(", "file", ")", "{", "//normalize path seperators", "file", "=", "file", ".", "replace", "(", "pathSepRegExp", ",", "path", ".", "sep", ")", ";", "//get resolved path parts for file directory", "if", "(", "file", ".", "charAt", "(", "0", ")", "===", "path", ".", "sep", ")", "{", "file", "=", "file", ".", "substr", "(", "1", ")", ";", "}", "//console.log(\" \"+file);", "//console.log(\" \"+path.dirname( file ));", "var", "dirname", "=", "path", ".", "dirname", "(", "file", ")", ";", "var", "parts", "=", "dirname", "===", "\".\"", "?", "[", "]", ":", "dirname", ".", "split", "(", "path", ".", "sep", ")", ";", "list", ".", "push", "(", "parts", ")", ";", "//save minimum path length for next step", "minLength", "=", "Math", ".", "min", "(", "minLength", ",", "parts", ".", "length", ")", ";", "}", ")", ";", "var", "listLength", "=", "list", ".", "length", ";", "grunt", ".", "verbose", ".", "writeln", "(", "JSON", ".", "stringify", "(", "list", ",", "undefined", ",", "\" \"", ")", ")", ";", "//check for common parts", "if", "(", "listLength", ">", "1", ")", "{", "var", "common", "=", "true", ";", "var", "index", "=", "-", "1", ";", "//iterate parts up to minLength", "for", "(", "var", "i", "=", "0", ";", "i", "<", "minLength", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "1", ";", "j", "<", "listLength", ";", "j", "++", ")", "{", "if", "(", "list", "[", "j", "]", "[", "i", "]", "!==", "list", "[", "j", "-", "1", "]", "[", "i", "]", ")", "{", "common", "=", "false", ";", "break", ";", "}", "}", "if", "(", "!", "common", ")", "{", "index", "=", "i", ";", "break", ";", "}", "}", "//catch case where all paths are common", "if", "(", "index", "<", "0", ")", "{", "index", "=", "minLength", ";", "}", "//build new paths array", "//for ( var n=0; n<listLength; n++ ) {", "//\tnewPaths.push( path.join( list[n].slice( index ) ) );", "//}", "commonPath", "=", "list", "[", "0", "]", ".", "slice", "(", "0", ",", "index", ")", ".", "join", "(", "path", ".", "sep", ")", ";", "}", "else", "if", "(", "listLength", "===", "1", ")", "{", "commonPath", "=", "list", "[", "0", "]", ".", "join", "(", "path", ".", "sep", ")", ";", "}", "return", "commonPath", ";", "}" ]
determines a shared base path among paths @param paths {Array} of strings @returns {String}
[ "determines", "a", "shared", "base", "path", "among", "paths" ]
b72e43719123a8a1c09eff5bea48fe494693cb1d
https://github.com/tylerbeck/grunt-bower-map/blob/b72e43719123a8a1c09eff5bea48fe494693cb1d/classes/BowerMap.js#L423-L493
50,366
shuvava/dev-http-server
lib/httpserver.js
urlWeight
function urlWeight(config) { if (isUndefined(config) || config.url == undefined) { // eslint-disable-line eqeqeq return 0; } if (config.url instanceof RegExp) { return 1 + config.url.toString().length; } if (isFunction(config.url)) { return 1; } return 100 + config.url.length; }
javascript
function urlWeight(config) { if (isUndefined(config) || config.url == undefined) { // eslint-disable-line eqeqeq return 0; } if (config.url instanceof RegExp) { return 1 + config.url.toString().length; } if (isFunction(config.url)) { return 1; } return 100 + config.url.length; }
[ "function", "urlWeight", "(", "config", ")", "{", "if", "(", "isUndefined", "(", "config", ")", "||", "config", ".", "url", "==", "undefined", ")", "{", "// eslint-disable-line eqeqeq", "return", "0", ";", "}", "if", "(", "config", ".", "url", "instanceof", "RegExp", ")", "{", "return", "1", "+", "config", ".", "url", ".", "toString", "(", ")", ".", "length", ";", "}", "if", "(", "isFunction", "(", "config", ".", "url", ")", ")", "{", "return", "1", ";", "}", "return", "100", "+", "config", ".", "url", ".", "length", ";", "}" ]
Calculate relative weight of URL comparing object @param {Object} config Internal object of URL comparing @param {string|RegExp} [config.url] URL pattern to compare @return {number} relative weight
[ "Calculate", "relative", "weight", "of", "URL", "comparing", "object" ]
db0f3b28f5805125959679828d81c1919cf519b6
https://github.com/shuvava/dev-http-server/blob/db0f3b28f5805125959679828d81c1919cf519b6/lib/httpserver.js#L44-L55
50,367
andrewscwei/requiem
src/helpers/defineProperty.js
defineProperty
function defineProperty(element, propertyName, descriptor, scope) { assert(element, 'Parameter \'element\' must be defined'); assertType(descriptor, 'object', false, 'Parameter \'descriptor\' must be an object literal'); assertType(descriptor.configurable, 'boolean', true, 'Optional configurable key in descriptor must be a boolean'); assertType(descriptor.enumerable, 'boolean', true, 'Optional enumerable key in descriptor must be a boolean'); assertType(descriptor.writable, 'boolean', true, 'Optional writable key in descriptor must be a boolean'); assertType(descriptor.unique, 'boolean', true, 'Optional unique key in descriptor must be a boolean'); assertType(descriptor.dirtyType, 'number', true, 'Optional dirty type must be of DirtyType enum (number)'); assertType(descriptor.eventType, 'string', true, 'Optional event type must be a string'); assertType(descriptor.attributed, 'boolean', true, 'Optional attributed must be a boolean'); assertType(descriptor.onChange, 'function', true, 'Optional change handler must be a function'); assertType(scope, 'string', true, 'Optional parameter \'scope\' must be a string'); let dirtyType = descriptor.dirtyType; let defaultValue = descriptor.defaultValue; let attributed = descriptor.attributed; let attributeName = Directive.DATA+propertyName.replace(/([A-Z])/g, ($1) => ('-'+$1.toLowerCase())); let eventType = descriptor.eventType; let unique = descriptor.unique; assert(!attributeName || !hasOwnValue(Directive, attributeName), 'Attribute \'' + attributeName + '\' is reserved'); if (unique === undefined) unique = true; if (scope === undefined) { scope = element; } else { assert(element.hasOwnProperty(scope), 'The specified Element instance does not have a property called \'' + scope + '\''); scope = element[scope]; } if (defaultValue !== undefined) { scope.__private__ = scope.__private__ || {}; Object.defineProperty(scope.__private__, propertyName, { value: defaultValue, writable: true }); } let newDescriptor = {}; if (descriptor.configurable !== undefined) newDescriptor.configurable = descriptor.configurable; if (descriptor.enumerable !== undefined) newDescriptor.enumerable = descriptor.enumerable; if (descriptor.value !== undefined) newDescriptor.value = descriptor.value; if (descriptor.writable !== undefined) newDescriptor.writable = descriptor.writable; if (descriptor.get) { newDescriptor.get = () => ((typeof descriptor.get === 'function') ? descriptor.get(scope.__private__[propertyName]) : scope.__private__[propertyName]); } if (descriptor.set) { newDescriptor.set = (val) => { let oldVal = scope.__private__[propertyName]; if (typeof descriptor.set === 'function') val = descriptor.set(val); if (unique && (oldVal === val)) return; if (oldVal === undefined) { scope.__private__ = scope.__private__ || {}; Object.defineProperty(scope.__private__, propertyName, { value: val, writable: true }); } else { scope.__private__[propertyName] = val; } if (descriptor.onChange !== undefined) descriptor.onChange(oldVal, val); if (attributed === true) dom.setAttribute(element, attributeName, val); if ((dirtyType !== undefined) && (element.setDirty)) element.setDirty(dirtyType); if (eventType !== undefined) { let event = new CustomEvent(eventType, { detail: { property: propertyName, oldValue: oldVal, newValue: val } }); if (element.dispatchEvent) element.dispatchEvent(event); } }; } Object.defineProperty(scope, propertyName, newDescriptor); if (defaultValue !== undefined && attributed === true) { dom.setAttribute(element, attributeName, defaultValue); } if (defaultValue !== undefined && dirtyType !== undefined && element.nodeState >= NodeState.UPDATED && element.setDirty) { element.setDirty(dirtyType); } }
javascript
function defineProperty(element, propertyName, descriptor, scope) { assert(element, 'Parameter \'element\' must be defined'); assertType(descriptor, 'object', false, 'Parameter \'descriptor\' must be an object literal'); assertType(descriptor.configurable, 'boolean', true, 'Optional configurable key in descriptor must be a boolean'); assertType(descriptor.enumerable, 'boolean', true, 'Optional enumerable key in descriptor must be a boolean'); assertType(descriptor.writable, 'boolean', true, 'Optional writable key in descriptor must be a boolean'); assertType(descriptor.unique, 'boolean', true, 'Optional unique key in descriptor must be a boolean'); assertType(descriptor.dirtyType, 'number', true, 'Optional dirty type must be of DirtyType enum (number)'); assertType(descriptor.eventType, 'string', true, 'Optional event type must be a string'); assertType(descriptor.attributed, 'boolean', true, 'Optional attributed must be a boolean'); assertType(descriptor.onChange, 'function', true, 'Optional change handler must be a function'); assertType(scope, 'string', true, 'Optional parameter \'scope\' must be a string'); let dirtyType = descriptor.dirtyType; let defaultValue = descriptor.defaultValue; let attributed = descriptor.attributed; let attributeName = Directive.DATA+propertyName.replace(/([A-Z])/g, ($1) => ('-'+$1.toLowerCase())); let eventType = descriptor.eventType; let unique = descriptor.unique; assert(!attributeName || !hasOwnValue(Directive, attributeName), 'Attribute \'' + attributeName + '\' is reserved'); if (unique === undefined) unique = true; if (scope === undefined) { scope = element; } else { assert(element.hasOwnProperty(scope), 'The specified Element instance does not have a property called \'' + scope + '\''); scope = element[scope]; } if (defaultValue !== undefined) { scope.__private__ = scope.__private__ || {}; Object.defineProperty(scope.__private__, propertyName, { value: defaultValue, writable: true }); } let newDescriptor = {}; if (descriptor.configurable !== undefined) newDescriptor.configurable = descriptor.configurable; if (descriptor.enumerable !== undefined) newDescriptor.enumerable = descriptor.enumerable; if (descriptor.value !== undefined) newDescriptor.value = descriptor.value; if (descriptor.writable !== undefined) newDescriptor.writable = descriptor.writable; if (descriptor.get) { newDescriptor.get = () => ((typeof descriptor.get === 'function') ? descriptor.get(scope.__private__[propertyName]) : scope.__private__[propertyName]); } if (descriptor.set) { newDescriptor.set = (val) => { let oldVal = scope.__private__[propertyName]; if (typeof descriptor.set === 'function') val = descriptor.set(val); if (unique && (oldVal === val)) return; if (oldVal === undefined) { scope.__private__ = scope.__private__ || {}; Object.defineProperty(scope.__private__, propertyName, { value: val, writable: true }); } else { scope.__private__[propertyName] = val; } if (descriptor.onChange !== undefined) descriptor.onChange(oldVal, val); if (attributed === true) dom.setAttribute(element, attributeName, val); if ((dirtyType !== undefined) && (element.setDirty)) element.setDirty(dirtyType); if (eventType !== undefined) { let event = new CustomEvent(eventType, { detail: { property: propertyName, oldValue: oldVal, newValue: val } }); if (element.dispatchEvent) element.dispatchEvent(event); } }; } Object.defineProperty(scope, propertyName, newDescriptor); if (defaultValue !== undefined && attributed === true) { dom.setAttribute(element, attributeName, defaultValue); } if (defaultValue !== undefined && dirtyType !== undefined && element.nodeState >= NodeState.UPDATED && element.setDirty) { element.setDirty(dirtyType); } }
[ "function", "defineProperty", "(", "element", ",", "propertyName", ",", "descriptor", ",", "scope", ")", "{", "assert", "(", "element", ",", "'Parameter \\'element\\' must be defined'", ")", ";", "assertType", "(", "descriptor", ",", "'object'", ",", "false", ",", "'Parameter \\'descriptor\\' must be an object literal'", ")", ";", "assertType", "(", "descriptor", ".", "configurable", ",", "'boolean'", ",", "true", ",", "'Optional configurable key in descriptor must be a boolean'", ")", ";", "assertType", "(", "descriptor", ".", "enumerable", ",", "'boolean'", ",", "true", ",", "'Optional enumerable key in descriptor must be a boolean'", ")", ";", "assertType", "(", "descriptor", ".", "writable", ",", "'boolean'", ",", "true", ",", "'Optional writable key in descriptor must be a boolean'", ")", ";", "assertType", "(", "descriptor", ".", "unique", ",", "'boolean'", ",", "true", ",", "'Optional unique key in descriptor must be a boolean'", ")", ";", "assertType", "(", "descriptor", ".", "dirtyType", ",", "'number'", ",", "true", ",", "'Optional dirty type must be of DirtyType enum (number)'", ")", ";", "assertType", "(", "descriptor", ".", "eventType", ",", "'string'", ",", "true", ",", "'Optional event type must be a string'", ")", ";", "assertType", "(", "descriptor", ".", "attributed", ",", "'boolean'", ",", "true", ",", "'Optional attributed must be a boolean'", ")", ";", "assertType", "(", "descriptor", ".", "onChange", ",", "'function'", ",", "true", ",", "'Optional change handler must be a function'", ")", ";", "assertType", "(", "scope", ",", "'string'", ",", "true", ",", "'Optional parameter \\'scope\\' must be a string'", ")", ";", "let", "dirtyType", "=", "descriptor", ".", "dirtyType", ";", "let", "defaultValue", "=", "descriptor", ".", "defaultValue", ";", "let", "attributed", "=", "descriptor", ".", "attributed", ";", "let", "attributeName", "=", "Directive", ".", "DATA", "+", "propertyName", ".", "replace", "(", "/", "([A-Z])", "/", "g", ",", "(", "$1", ")", "=>", "(", "'-'", "+", "$1", ".", "toLowerCase", "(", ")", ")", ")", ";", "let", "eventType", "=", "descriptor", ".", "eventType", ";", "let", "unique", "=", "descriptor", ".", "unique", ";", "assert", "(", "!", "attributeName", "||", "!", "hasOwnValue", "(", "Directive", ",", "attributeName", ")", ",", "'Attribute \\''", "+", "attributeName", "+", "'\\' is reserved'", ")", ";", "if", "(", "unique", "===", "undefined", ")", "unique", "=", "true", ";", "if", "(", "scope", "===", "undefined", ")", "{", "scope", "=", "element", ";", "}", "else", "{", "assert", "(", "element", ".", "hasOwnProperty", "(", "scope", ")", ",", "'The specified Element instance does not have a property called \\''", "+", "scope", "+", "'\\''", ")", ";", "scope", "=", "element", "[", "scope", "]", ";", "}", "if", "(", "defaultValue", "!==", "undefined", ")", "{", "scope", ".", "__private__", "=", "scope", ".", "__private__", "||", "{", "}", ";", "Object", ".", "defineProperty", "(", "scope", ".", "__private__", ",", "propertyName", ",", "{", "value", ":", "defaultValue", ",", "writable", ":", "true", "}", ")", ";", "}", "let", "newDescriptor", "=", "{", "}", ";", "if", "(", "descriptor", ".", "configurable", "!==", "undefined", ")", "newDescriptor", ".", "configurable", "=", "descriptor", ".", "configurable", ";", "if", "(", "descriptor", ".", "enumerable", "!==", "undefined", ")", "newDescriptor", ".", "enumerable", "=", "descriptor", ".", "enumerable", ";", "if", "(", "descriptor", ".", "value", "!==", "undefined", ")", "newDescriptor", ".", "value", "=", "descriptor", ".", "value", ";", "if", "(", "descriptor", ".", "writable", "!==", "undefined", ")", "newDescriptor", ".", "writable", "=", "descriptor", ".", "writable", ";", "if", "(", "descriptor", ".", "get", ")", "{", "newDescriptor", ".", "get", "=", "(", ")", "=>", "(", "(", "typeof", "descriptor", ".", "get", "===", "'function'", ")", "?", "descriptor", ".", "get", "(", "scope", ".", "__private__", "[", "propertyName", "]", ")", ":", "scope", ".", "__private__", "[", "propertyName", "]", ")", ";", "}", "if", "(", "descriptor", ".", "set", ")", "{", "newDescriptor", ".", "set", "=", "(", "val", ")", "=>", "{", "let", "oldVal", "=", "scope", ".", "__private__", "[", "propertyName", "]", ";", "if", "(", "typeof", "descriptor", ".", "set", "===", "'function'", ")", "val", "=", "descriptor", ".", "set", "(", "val", ")", ";", "if", "(", "unique", "&&", "(", "oldVal", "===", "val", ")", ")", "return", ";", "if", "(", "oldVal", "===", "undefined", ")", "{", "scope", ".", "__private__", "=", "scope", ".", "__private__", "||", "{", "}", ";", "Object", ".", "defineProperty", "(", "scope", ".", "__private__", ",", "propertyName", ",", "{", "value", ":", "val", ",", "writable", ":", "true", "}", ")", ";", "}", "else", "{", "scope", ".", "__private__", "[", "propertyName", "]", "=", "val", ";", "}", "if", "(", "descriptor", ".", "onChange", "!==", "undefined", ")", "descriptor", ".", "onChange", "(", "oldVal", ",", "val", ")", ";", "if", "(", "attributed", "===", "true", ")", "dom", ".", "setAttribute", "(", "element", ",", "attributeName", ",", "val", ")", ";", "if", "(", "(", "dirtyType", "!==", "undefined", ")", "&&", "(", "element", ".", "setDirty", ")", ")", "element", ".", "setDirty", "(", "dirtyType", ")", ";", "if", "(", "eventType", "!==", "undefined", ")", "{", "let", "event", "=", "new", "CustomEvent", "(", "eventType", ",", "{", "detail", ":", "{", "property", ":", "propertyName", ",", "oldValue", ":", "oldVal", ",", "newValue", ":", "val", "}", "}", ")", ";", "if", "(", "element", ".", "dispatchEvent", ")", "element", ".", "dispatchEvent", "(", "event", ")", ";", "}", "}", ";", "}", "Object", ".", "defineProperty", "(", "scope", ",", "propertyName", ",", "newDescriptor", ")", ";", "if", "(", "defaultValue", "!==", "undefined", "&&", "attributed", "===", "true", ")", "{", "dom", ".", "setAttribute", "(", "element", ",", "attributeName", ",", "defaultValue", ")", ";", "}", "if", "(", "defaultValue", "!==", "undefined", "&&", "dirtyType", "!==", "undefined", "&&", "element", ".", "nodeState", ">=", "NodeState", ".", "UPDATED", "&&", "element", ".", "setDirty", ")", "{", "element", ".", "setDirty", "(", "dirtyType", ")", ";", "}", "}" ]
Defines a property in an element instance. @param {Node} element - Element instance to define the new property in. @param {string} propertyName - Name of the property to be defined. @param {Object} descriptor - An object literal that defines the behavior of this new property. This object literal inherits that of the descriptor param in Object#defineProperty. @param {boolean} [descriptor.unique=true] - Specifies that the modifier method will only invoke if the new value is different from the old value. @param {DirtyType} [descriptor.dirtyType] - Specifies the DirtyType to flag whenever a new value is set. @param {EventType} [descriptor.eventType] - Specifies the EventType to dispatch whenever a new value is set. @param {boolean} [descriptor.attributed] - Specifies whether the a corresponding DOM attribute will update whenever a new value is set. @param {Function} [descriptor.onChange] - Method invoked when the property changes. @param {Function|boolean} [descriptor.get] - Method invoked when the accessor method is called. This is a good place to manipulate the value before it is returned. If simply set to true, a generic accessor method will be used. @param {Function|boolean} [descriptor.set] - Method invoked when the modifier method is called. This is a good place to manipulate the value before it is set. If simply set to true, a generic modifier method will be used. @param {string} [scope] - Name of the instance property of the Element to create the new property in. This property must be enumerable. @alias module:requiem~helpers.defineProperty
[ "Defines", "a", "property", "in", "an", "element", "instance", "." ]
c4182bfffc9841c6de5718f689ad3c2060511777
https://github.com/andrewscwei/requiem/blob/c4182bfffc9841c6de5718f689ad3c2060511777/src/helpers/defineProperty.js#L54-L146
50,368
jmjuanes/readl-async
index.js
function(file, opt) { //Check the file if(typeof file !== 'string'){ throw new Error('Missing file argument'); return null; } //Check the options if(typeof opt === 'undefined'){ var opt = {}; } //Save the file name this._file = file; //Check the encoding option this._encoding = (typeof opt.encoding === 'undefined') ? 'utf8' : opt.encoding.toString(); //Check the chunk option this._chunk = (typeof opt.chunk === 'undefined') ? 10240 : opt.chunk; //Check the line break option this._endl = (typeof opt.endl === 'undefined') ? 0x0a : opt.endl; //Check the emptylines option this._emptyLines = (typeof opt.emptyLines === 'undefined') ? true : opt.emptyLines; //File object this._fd = null; //Actual position this._position = (typeof opt.start === 'undefined') ? 0 : opt.start; //Line count this._count = 0; //Events this._events = {}; //Return this return this; }
javascript
function(file, opt) { //Check the file if(typeof file !== 'string'){ throw new Error('Missing file argument'); return null; } //Check the options if(typeof opt === 'undefined'){ var opt = {}; } //Save the file name this._file = file; //Check the encoding option this._encoding = (typeof opt.encoding === 'undefined') ? 'utf8' : opt.encoding.toString(); //Check the chunk option this._chunk = (typeof opt.chunk === 'undefined') ? 10240 : opt.chunk; //Check the line break option this._endl = (typeof opt.endl === 'undefined') ? 0x0a : opt.endl; //Check the emptylines option this._emptyLines = (typeof opt.emptyLines === 'undefined') ? true : opt.emptyLines; //File object this._fd = null; //Actual position this._position = (typeof opt.start === 'undefined') ? 0 : opt.start; //Line count this._count = 0; //Events this._events = {}; //Return this return this; }
[ "function", "(", "file", ",", "opt", ")", "{", "//Check the file", "if", "(", "typeof", "file", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'Missing file argument'", ")", ";", "return", "null", ";", "}", "//Check the options", "if", "(", "typeof", "opt", "===", "'undefined'", ")", "{", "var", "opt", "=", "{", "}", ";", "}", "//Save the file name", "this", ".", "_file", "=", "file", ";", "//Check the encoding option", "this", ".", "_encoding", "=", "(", "typeof", "opt", ".", "encoding", "===", "'undefined'", ")", "?", "'utf8'", ":", "opt", ".", "encoding", ".", "toString", "(", ")", ";", "//Check the chunk option", "this", ".", "_chunk", "=", "(", "typeof", "opt", ".", "chunk", "===", "'undefined'", ")", "?", "10240", ":", "opt", ".", "chunk", ";", "//Check the line break option", "this", ".", "_endl", "=", "(", "typeof", "opt", ".", "endl", "===", "'undefined'", ")", "?", "0x0a", ":", "opt", ".", "endl", ";", "//Check the emptylines option", "this", ".", "_emptyLines", "=", "(", "typeof", "opt", ".", "emptyLines", "===", "'undefined'", ")", "?", "true", ":", "opt", ".", "emptyLines", ";", "//File object", "this", ".", "_fd", "=", "null", ";", "//Actual position", "this", ".", "_position", "=", "(", "typeof", "opt", ".", "start", "===", "'undefined'", ")", "?", "0", ":", "opt", ".", "start", ";", "//Line count", "this", ".", "_count", "=", "0", ";", "//Events", "this", ".", "_events", "=", "{", "}", ";", "//Return this", "return", "this", ";", "}" ]
Read line by line object
[ "Read", "line", "by", "line", "object" ]
e263adbae41972cf7301360b412f293285305d75
https://github.com/jmjuanes/readl-async/blob/e263adbae41972cf7301360b412f293285305d75/index.js#L6-L43
50,369
joerx/grunt-crontab
lib/grunt-crontab.js
setup
function setup(done) { crontab.load(function(err, ct) { if (err) return done(err); clean(ct); load(ct); ct.save(done); }); }
javascript
function setup(done) { crontab.load(function(err, ct) { if (err) return done(err); clean(ct); load(ct); ct.save(done); }); }
[ "function", "setup", "(", "done", ")", "{", "crontab", ".", "load", "(", "function", "(", "err", ",", "ct", ")", "{", "if", "(", "err", ")", "return", "done", "(", "err", ")", ";", "clean", "(", "ct", ")", ";", "load", "(", "ct", ")", ";", "ct", ".", "save", "(", "done", ")", ";", "}", ")", ";", "}" ]
Remove cronjobs from given crontab
[ "Remove", "cronjobs", "from", "given", "crontab" ]
47e26c3d7897f79524ac1d37cd48acaf963fc1f3
https://github.com/joerx/grunt-crontab/blob/47e26c3d7897f79524ac1d37cd48acaf963fc1f3/lib/grunt-crontab.js#L21-L28
50,370
joerx/grunt-crontab
lib/grunt-crontab.js
readCronFile
function readCronFile(cronfile) { var substitutes = { project: { baseDir: process.cwd() }, pkg: pkg } var content = _.template(grunt.file.read(cronfile), substitutes); return JSON.parse(content).jobs; }
javascript
function readCronFile(cronfile) { var substitutes = { project: { baseDir: process.cwd() }, pkg: pkg } var content = _.template(grunt.file.read(cronfile), substitutes); return JSON.parse(content).jobs; }
[ "function", "readCronFile", "(", "cronfile", ")", "{", "var", "substitutes", "=", "{", "project", ":", "{", "baseDir", ":", "process", ".", "cwd", "(", ")", "}", ",", "pkg", ":", "pkg", "}", "var", "content", "=", "_", ".", "template", "(", "grunt", ".", "file", ".", "read", "(", "cronfile", ")", ",", "substitutes", ")", ";", "return", "JSON", ".", "parse", "(", "content", ")", ".", "jobs", ";", "}" ]
Read cronjob definition file from disk.
[ "Read", "cronjob", "definition", "file", "from", "disk", "." ]
47e26c3d7897f79524ac1d37cd48acaf963fc1f3
https://github.com/joerx/grunt-crontab/blob/47e26c3d7897f79524ac1d37cd48acaf963fc1f3/lib/grunt-crontab.js#L59-L68
50,371
underdogio/resolve-link
lib/resolve-link.js
resolveLink
function resolveLink(srcUrl, targetUrl) { // Parse the src URL var srcUrlObj = url.parse(srcUrl); // If there isn't a protocol // DEV: `[email protected]` has this as `undefined`, `[email protected]` has this as `null` if (!srcUrlObj.protocol) { // With no protocol, we have everything in pathname. Add on `//` and force treatment of `host` var tmpSrcUrl = '//' + srcUrl; var tmpSrcUrlObj = url.parse(tmpSrcUrl, null, true); // If this new hostname has a TLD, then keep it as the srcUrlObj // DEV: We are trading accuracy for size (technically not all dots mean a tld // If we want to be accurate, use https://github.com/ramitos/tld.js/blob/305a285fd8f5d618417178521d8729855baadb37/src/tld.js if (tmpSrcUrlObj.hostname && tldRegexp.test(tmpSrcUrlObj.hostname)) { srcUrl = tmpSrcUrl; srcUrlObj = tmpSrcUrlObj; } } // Fallback pathname srcUrlObj.pathname = srcUrlObj.pathname || '/'; // If we still have no protocol // DEV: `[email protected]` has this as `undefined`, `[email protected]` has this as `null` if (!srcUrlObj.protocol) { // Parse our targetUrl var targetUrlObj = url.parse(targetUrl); // If there is a hostname // DEV: `[email protected]` has this as `undefined`, `[email protected]` has this as `null` if (srcUrlObj.hostname) { // If the hostname is the same as our original, add on a protocol if (srcUrlObj.hostname === targetUrlObj.hostname) { srcUrlObj.protocol = targetUrlObj.protocol; // Otherwise, default to HTTP } else { srcUrlObj.protocol = 'http:'; } // Otherwise, pickup the target protocol and hostname } else { srcUrlObj.protocol = targetUrlObj.protocol; srcUrlObj.hostname = targetUrlObj.hostname; } } // Return our completed src url return url.format(srcUrlObj); }
javascript
function resolveLink(srcUrl, targetUrl) { // Parse the src URL var srcUrlObj = url.parse(srcUrl); // If there isn't a protocol // DEV: `[email protected]` has this as `undefined`, `[email protected]` has this as `null` if (!srcUrlObj.protocol) { // With no protocol, we have everything in pathname. Add on `//` and force treatment of `host` var tmpSrcUrl = '//' + srcUrl; var tmpSrcUrlObj = url.parse(tmpSrcUrl, null, true); // If this new hostname has a TLD, then keep it as the srcUrlObj // DEV: We are trading accuracy for size (technically not all dots mean a tld // If we want to be accurate, use https://github.com/ramitos/tld.js/blob/305a285fd8f5d618417178521d8729855baadb37/src/tld.js if (tmpSrcUrlObj.hostname && tldRegexp.test(tmpSrcUrlObj.hostname)) { srcUrl = tmpSrcUrl; srcUrlObj = tmpSrcUrlObj; } } // Fallback pathname srcUrlObj.pathname = srcUrlObj.pathname || '/'; // If we still have no protocol // DEV: `[email protected]` has this as `undefined`, `[email protected]` has this as `null` if (!srcUrlObj.protocol) { // Parse our targetUrl var targetUrlObj = url.parse(targetUrl); // If there is a hostname // DEV: `[email protected]` has this as `undefined`, `[email protected]` has this as `null` if (srcUrlObj.hostname) { // If the hostname is the same as our original, add on a protocol if (srcUrlObj.hostname === targetUrlObj.hostname) { srcUrlObj.protocol = targetUrlObj.protocol; // Otherwise, default to HTTP } else { srcUrlObj.protocol = 'http:'; } // Otherwise, pickup the target protocol and hostname } else { srcUrlObj.protocol = targetUrlObj.protocol; srcUrlObj.hostname = targetUrlObj.hostname; } } // Return our completed src url return url.format(srcUrlObj); }
[ "function", "resolveLink", "(", "srcUrl", ",", "targetUrl", ")", "{", "// Parse the src URL", "var", "srcUrlObj", "=", "url", ".", "parse", "(", "srcUrl", ")", ";", "// If there isn't a protocol", "// DEV: `[email protected]` has this as `undefined`, `[email protected]` has this as `null`", "if", "(", "!", "srcUrlObj", ".", "protocol", ")", "{", "// With no protocol, we have everything in pathname. Add on `//` and force treatment of `host`", "var", "tmpSrcUrl", "=", "'//'", "+", "srcUrl", ";", "var", "tmpSrcUrlObj", "=", "url", ".", "parse", "(", "tmpSrcUrl", ",", "null", ",", "true", ")", ";", "// If this new hostname has a TLD, then keep it as the srcUrlObj", "// DEV: We are trading accuracy for size (technically not all dots mean a tld", "// If we want to be accurate, use https://github.com/ramitos/tld.js/blob/305a285fd8f5d618417178521d8729855baadb37/src/tld.js", "if", "(", "tmpSrcUrlObj", ".", "hostname", "&&", "tldRegexp", ".", "test", "(", "tmpSrcUrlObj", ".", "hostname", ")", ")", "{", "srcUrl", "=", "tmpSrcUrl", ";", "srcUrlObj", "=", "tmpSrcUrlObj", ";", "}", "}", "// Fallback pathname", "srcUrlObj", ".", "pathname", "=", "srcUrlObj", ".", "pathname", "||", "'/'", ";", "// If we still have no protocol", "// DEV: `[email protected]` has this as `undefined`, `[email protected]` has this as `null`", "if", "(", "!", "srcUrlObj", ".", "protocol", ")", "{", "// Parse our targetUrl", "var", "targetUrlObj", "=", "url", ".", "parse", "(", "targetUrl", ")", ";", "// If there is a hostname", "// DEV: `[email protected]` has this as `undefined`, `[email protected]` has this as `null`", "if", "(", "srcUrlObj", ".", "hostname", ")", "{", "// If the hostname is the same as our original, add on a protocol", "if", "(", "srcUrlObj", ".", "hostname", "===", "targetUrlObj", ".", "hostname", ")", "{", "srcUrlObj", ".", "protocol", "=", "targetUrlObj", ".", "protocol", ";", "// Otherwise, default to HTTP", "}", "else", "{", "srcUrlObj", ".", "protocol", "=", "'http:'", ";", "}", "// Otherwise, pickup the target protocol and hostname", "}", "else", "{", "srcUrlObj", ".", "protocol", "=", "targetUrlObj", ".", "protocol", ";", "srcUrlObj", ".", "hostname", "=", "targetUrlObj", ".", "hostname", ";", "}", "}", "// Return our completed src url", "return", "url", ".", "format", "(", "srcUrlObj", ")", ";", "}" ]
Define our helper
[ "Define", "our", "helper" ]
075ee9be703806ac0cb4cf36a8550c5357f4a686
https://github.com/underdogio/resolve-link/blob/075ee9be703806ac0cb4cf36a8550c5357f4a686/lib/resolve-link.js#L6-L54
50,372
Nazariglez/perenquen
lib/pixi/src/core/textures/RenderTexture.js
RenderTexture
function RenderTexture(renderer, width, height, scaleMode, resolution) { if (!renderer) { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } width = width || 100; height = height || 100; resolution = resolution || CONST.RESOLUTION; /** * The base texture object that this texture uses * * @member {BaseTexture} */ var baseTexture = new BaseTexture(); baseTexture.width = width; baseTexture.height = height; baseTexture.resolution = resolution; baseTexture.scaleMode = scaleMode || CONST.SCALE_MODES.DEFAULT; baseTexture.hasLoaded = true; Texture.call(this, baseTexture, new math.Rectangle(0, 0, width, height) ); /** * The with of the render texture * * @member {number} */ this.width = width; /** * The height of the render texture * * @member {number} */ this.height = height; /** * The Resolution of the texture. * * @member {number} */ this.resolution = resolution; /** * The framing rectangle of the render texture * * @member {Rectangle} */ //this._frame = new math.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution); /** * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) * * @member {Rectangle} */ //this.crop = new math.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution); /** * Draw/render the given DisplayObject onto the texture. * * The displayObject and descendents are transformed during this operation. * If `updateTransform` is true then the transformations will be restored before the * method returns. Otherwise it is up to the calling code to correctly use or reset * the transformed display objects. * * The display object is always rendered with a worldAlpha value of 1. * * @method * @param displayObject {DisplayObject} The display object to render this texture on * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. * @param [clear=false] {boolean} If true the texture will be cleared before the displayObject is drawn * @param [updateTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ this.render = null; /** * The renderer this RenderTexture uses. A RenderTexture can only belong to one renderer at the moment if its webGL. * * @member {CanvasRenderer|WebGLRenderer} */ this.renderer = renderer; if (this.renderer.type === CONST.RENDERER_TYPE.WEBGL) { var gl = this.renderer.gl; this.textureBuffer = new RenderTarget(gl, this.width, this.height, baseTexture.scaleMode, this.resolution);//, this.baseTexture.scaleMode); this.baseTexture._glTextures[gl.id] = this.textureBuffer.texture; //TODO refactor filter manager.. as really its no longer a manager if we use it here.. this.filterManager = new FilterManager(this.renderer); this.filterManager.onContextChange(); this.filterManager.resize(width, height); this.render = this.renderWebGL; // the creation of a filter manager unbinds the buffers.. this.renderer.currentRenderer.start(); this.renderer.currentRenderTarget.activate(); } else { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; } /** * @member {boolean} */ this.valid = true; this._updateUvs(); }
javascript
function RenderTexture(renderer, width, height, scaleMode, resolution) { if (!renderer) { throw new Error('Unable to create RenderTexture, you must pass a renderer into the constructor.'); } width = width || 100; height = height || 100; resolution = resolution || CONST.RESOLUTION; /** * The base texture object that this texture uses * * @member {BaseTexture} */ var baseTexture = new BaseTexture(); baseTexture.width = width; baseTexture.height = height; baseTexture.resolution = resolution; baseTexture.scaleMode = scaleMode || CONST.SCALE_MODES.DEFAULT; baseTexture.hasLoaded = true; Texture.call(this, baseTexture, new math.Rectangle(0, 0, width, height) ); /** * The with of the render texture * * @member {number} */ this.width = width; /** * The height of the render texture * * @member {number} */ this.height = height; /** * The Resolution of the texture. * * @member {number} */ this.resolution = resolution; /** * The framing rectangle of the render texture * * @member {Rectangle} */ //this._frame = new math.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution); /** * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) * * @member {Rectangle} */ //this.crop = new math.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution); /** * Draw/render the given DisplayObject onto the texture. * * The displayObject and descendents are transformed during this operation. * If `updateTransform` is true then the transformations will be restored before the * method returns. Otherwise it is up to the calling code to correctly use or reset * the transformed display objects. * * The display object is always rendered with a worldAlpha value of 1. * * @method * @param displayObject {DisplayObject} The display object to render this texture on * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering. * @param [clear=false] {boolean} If true the texture will be cleared before the displayObject is drawn * @param [updateTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children * transformations will be restored. Not restoring this information will be a little faster. */ this.render = null; /** * The renderer this RenderTexture uses. A RenderTexture can only belong to one renderer at the moment if its webGL. * * @member {CanvasRenderer|WebGLRenderer} */ this.renderer = renderer; if (this.renderer.type === CONST.RENDERER_TYPE.WEBGL) { var gl = this.renderer.gl; this.textureBuffer = new RenderTarget(gl, this.width, this.height, baseTexture.scaleMode, this.resolution);//, this.baseTexture.scaleMode); this.baseTexture._glTextures[gl.id] = this.textureBuffer.texture; //TODO refactor filter manager.. as really its no longer a manager if we use it here.. this.filterManager = new FilterManager(this.renderer); this.filterManager.onContextChange(); this.filterManager.resize(width, height); this.render = this.renderWebGL; // the creation of a filter manager unbinds the buffers.. this.renderer.currentRenderer.start(); this.renderer.currentRenderTarget.activate(); } else { this.render = this.renderCanvas; this.textureBuffer = new CanvasBuffer(this.width* this.resolution, this.height* this.resolution); this.baseTexture.source = this.textureBuffer.canvas; } /** * @member {boolean} */ this.valid = true; this._updateUvs(); }
[ "function", "RenderTexture", "(", "renderer", ",", "width", ",", "height", ",", "scaleMode", ",", "resolution", ")", "{", "if", "(", "!", "renderer", ")", "{", "throw", "new", "Error", "(", "'Unable to create RenderTexture, you must pass a renderer into the constructor.'", ")", ";", "}", "width", "=", "width", "||", "100", ";", "height", "=", "height", "||", "100", ";", "resolution", "=", "resolution", "||", "CONST", ".", "RESOLUTION", ";", "/**\n * The base texture object that this texture uses\n *\n * @member {BaseTexture}\n */", "var", "baseTexture", "=", "new", "BaseTexture", "(", ")", ";", "baseTexture", ".", "width", "=", "width", ";", "baseTexture", ".", "height", "=", "height", ";", "baseTexture", ".", "resolution", "=", "resolution", ";", "baseTexture", ".", "scaleMode", "=", "scaleMode", "||", "CONST", ".", "SCALE_MODES", ".", "DEFAULT", ";", "baseTexture", ".", "hasLoaded", "=", "true", ";", "Texture", ".", "call", "(", "this", ",", "baseTexture", ",", "new", "math", ".", "Rectangle", "(", "0", ",", "0", ",", "width", ",", "height", ")", ")", ";", "/**\n * The with of the render texture\n *\n * @member {number}\n */", "this", ".", "width", "=", "width", ";", "/**\n * The height of the render texture\n *\n * @member {number}\n */", "this", ".", "height", "=", "height", ";", "/**\n * The Resolution of the texture.\n *\n * @member {number}\n */", "this", ".", "resolution", "=", "resolution", ";", "/**\n * The framing rectangle of the render texture\n *\n * @member {Rectangle}\n */", "//this._frame = new math.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution);", "/**\n * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering,\n * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases)\n *\n * @member {Rectangle}\n */", "//this.crop = new math.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution);", "/**\n * Draw/render the given DisplayObject onto the texture.\n *\n * The displayObject and descendents are transformed during this operation.\n * If `updateTransform` is true then the transformations will be restored before the\n * method returns. Otherwise it is up to the calling code to correctly use or reset\n * the transformed display objects.\n *\n * The display object is always rendered with a worldAlpha value of 1.\n *\n * @method\n * @param displayObject {DisplayObject} The display object to render this texture on\n * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering.\n * @param [clear=false] {boolean} If true the texture will be cleared before the displayObject is drawn\n * @param [updateTransform=true] {boolean} If true the displayObject's worldTransform/worldAlpha and all children\n * transformations will be restored. Not restoring this information will be a little faster.\n */", "this", ".", "render", "=", "null", ";", "/**\n * The renderer this RenderTexture uses. A RenderTexture can only belong to one renderer at the moment if its webGL.\n *\n * @member {CanvasRenderer|WebGLRenderer}\n */", "this", ".", "renderer", "=", "renderer", ";", "if", "(", "this", ".", "renderer", ".", "type", "===", "CONST", ".", "RENDERER_TYPE", ".", "WEBGL", ")", "{", "var", "gl", "=", "this", ".", "renderer", ".", "gl", ";", "this", ".", "textureBuffer", "=", "new", "RenderTarget", "(", "gl", ",", "this", ".", "width", ",", "this", ".", "height", ",", "baseTexture", ".", "scaleMode", ",", "this", ".", "resolution", ")", ";", "//, this.baseTexture.scaleMode);", "this", ".", "baseTexture", ".", "_glTextures", "[", "gl", ".", "id", "]", "=", "this", ".", "textureBuffer", ".", "texture", ";", "//TODO refactor filter manager.. as really its no longer a manager if we use it here..", "this", ".", "filterManager", "=", "new", "FilterManager", "(", "this", ".", "renderer", ")", ";", "this", ".", "filterManager", ".", "onContextChange", "(", ")", ";", "this", ".", "filterManager", ".", "resize", "(", "width", ",", "height", ")", ";", "this", ".", "render", "=", "this", ".", "renderWebGL", ";", "// the creation of a filter manager unbinds the buffers..", "this", ".", "renderer", ".", "currentRenderer", ".", "start", "(", ")", ";", "this", ".", "renderer", ".", "currentRenderTarget", ".", "activate", "(", ")", ";", "}", "else", "{", "this", ".", "render", "=", "this", ".", "renderCanvas", ";", "this", ".", "textureBuffer", "=", "new", "CanvasBuffer", "(", "this", ".", "width", "*", "this", ".", "resolution", ",", "this", ".", "height", "*", "this", ".", "resolution", ")", ";", "this", ".", "baseTexture", ".", "source", "=", "this", ".", "textureBuffer", ".", "canvas", ";", "}", "/**\n * @member {boolean}\n */", "this", ".", "valid", "=", "true", ";", "this", ".", "_updateUvs", "(", ")", ";", "}" ]
A RenderTexture is a special texture that allows any Pixi display object to be rendered to it. __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded otherwise black rectangles will be drawn instead. A RenderTexture takes a snapshot of any Display Object given to its render method. The position and rotation of the given Display Objects is ignored. For example: ```js var renderTexture = new PIXI.RenderTexture(800, 600); var sprite = PIXI.Sprite.fromImage("spinObj_01.png"); sprite.position.x = 800/2; sprite.position.y = 600/2; sprite.anchor.x = 0.5; sprite.anchor.y = 0.5; renderTexture.render(sprite); ``` The Sprite in this case will be rendered to a position of 0,0. To render this sprite at its actual position a Container should be used: ```js var doc = new Container(); doc.addChild(sprite); renderTexture.render(doc); // Renders to center of renderTexture ``` @class @extends Texture @memberof PIXI @param renderer {CanvasRenderer|WebGLRenderer} The renderer used for this RenderTexture @param [width=100] {number} The width of the render texture @param [height=100] {number} The height of the render texture @param [scaleMode] {number} See {@link SCALE_MODES} for possible values @param [resolution=1] {number} The resolution of the texture being generated
[ "A", "RenderTexture", "is", "a", "special", "texture", "that", "allows", "any", "Pixi", "display", "object", "to", "be", "rendered", "to", "it", "." ]
e023964d05afeefebdcac4e2044819fdfa3899ae
https://github.com/Nazariglez/perenquen/blob/e023964d05afeefebdcac4e2044819fdfa3899ae/lib/pixi/src/core/textures/RenderTexture.js#L51-L174
50,373
senecajs-labs/seneca-sqlite-store
lib/sqlite-store.js
function (args, done) { var q = _.clone(args.q) var qent = args.qent q.limit$ = 1 var qs = schemastm(qent) self.connection.all(qs.text, function (err, results) { if (err) { return done(err) } var schema = {} results.forEach(function (row) { schema[row.name] = row.type.toLowerCase() }) var query = selectstm(qent, q) self.connection.get(query.text, query.values, function (err, row) { if (err) { return done(err) } if (row) { var fent = makeent(qent, row, schema) seneca.log.debug('load', q, fent, desc) return done(null, fent) } return done(null, null) }) }) }
javascript
function (args, done) { var q = _.clone(args.q) var qent = args.qent q.limit$ = 1 var qs = schemastm(qent) self.connection.all(qs.text, function (err, results) { if (err) { return done(err) } var schema = {} results.forEach(function (row) { schema[row.name] = row.type.toLowerCase() }) var query = selectstm(qent, q) self.connection.get(query.text, query.values, function (err, row) { if (err) { return done(err) } if (row) { var fent = makeent(qent, row, schema) seneca.log.debug('load', q, fent, desc) return done(null, fent) } return done(null, null) }) }) }
[ "function", "(", "args", ",", "done", ")", "{", "var", "q", "=", "_", ".", "clone", "(", "args", ".", "q", ")", "var", "qent", "=", "args", ".", "qent", "q", ".", "limit$", "=", "1", "var", "qs", "=", "schemastm", "(", "qent", ")", "self", ".", "connection", ".", "all", "(", "qs", ".", "text", ",", "function", "(", "err", ",", "results", ")", "{", "if", "(", "err", ")", "{", "return", "done", "(", "err", ")", "}", "var", "schema", "=", "{", "}", "results", ".", "forEach", "(", "function", "(", "row", ")", "{", "schema", "[", "row", ".", "name", "]", "=", "row", ".", "type", ".", "toLowerCase", "(", ")", "}", ")", "var", "query", "=", "selectstm", "(", "qent", ",", "q", ")", "self", ".", "connection", ".", "get", "(", "query", ".", "text", ",", "query", ".", "values", ",", "function", "(", "err", ",", "row", ")", "{", "if", "(", "err", ")", "{", "return", "done", "(", "err", ")", "}", "if", "(", "row", ")", "{", "var", "fent", "=", "makeent", "(", "qent", ",", "row", ",", "schema", ")", "seneca", ".", "log", ".", "debug", "(", "'load'", ",", "q", ",", "fent", ",", "desc", ")", "return", "done", "(", "null", ",", "fent", ")", "}", "return", "done", "(", "null", ",", "null", ")", "}", ")", "}", ")", "}" ]
load the first matching entity
[ "load", "the", "first", "matching", "entity" ]
9d3f45f1ae093de30d709dbb990c4921263bf45e
https://github.com/senecajs-labs/seneca-sqlite-store/blob/9d3f45f1ae093de30d709dbb990c4921263bf45e/lib/sqlite-store.js#L52-L81
50,374
forumone/yeoman-generator-bluebird
index.js
promptAsync
function promptAsync(prompts) { return new Promise(function(resolve, reject) { parent.prompt.call(parent, prompts, function(answers) { resolve(answers) }); }); }
javascript
function promptAsync(prompts) { return new Promise(function(resolve, reject) { parent.prompt.call(parent, prompts, function(answers) { resolve(answers) }); }); }
[ "function", "promptAsync", "(", "prompts", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "parent", ".", "prompt", ".", "call", "(", "parent", ",", "prompts", ",", "function", "(", "answers", ")", "{", "resolve", "(", "answers", ")", "}", ")", ";", "}", ")", ";", "}" ]
Asynchronous prompt function that returns a Promise @param prompts @returns {Promise}
[ "Asynchronous", "prompt", "function", "that", "returns", "a", "Promise" ]
01d917fe4bc9081e512a206d390b9661947d1f2f
https://github.com/forumone/yeoman-generator-bluebird/blob/01d917fe4bc9081e512a206d390b9661947d1f2f/index.js#L17-L23
50,375
forumone/yeoman-generator-bluebird
index.js
remoteAsync
function remoteAsync() { var generator = this.generator; var username; var repo; var branch; var refresh; var url; // With URL and refresh if (arguments.length <= 2) { url = arguments[0]; refresh = arguments[1]; } else { username = arguments[0]; repo = arguments[1]; branch = arguments[2]; refresh = arguments[3]; url = 'https://github.com/' + [username, repo, 'archive', branch].join('/') + '.tar.gz'; } return new Promise(function(resolve, reject) { parent.remote.call(parent, url, function(err, remote) { if (err) { reject(err); } else { resolve(remote); } }, refresh); }); }
javascript
function remoteAsync() { var generator = this.generator; var username; var repo; var branch; var refresh; var url; // With URL and refresh if (arguments.length <= 2) { url = arguments[0]; refresh = arguments[1]; } else { username = arguments[0]; repo = arguments[1]; branch = arguments[2]; refresh = arguments[3]; url = 'https://github.com/' + [username, repo, 'archive', branch].join('/') + '.tar.gz'; } return new Promise(function(resolve, reject) { parent.remote.call(parent, url, function(err, remote) { if (err) { reject(err); } else { resolve(remote); } }, refresh); }); }
[ "function", "remoteAsync", "(", ")", "{", "var", "generator", "=", "this", ".", "generator", ";", "var", "username", ";", "var", "repo", ";", "var", "branch", ";", "var", "refresh", ";", "var", "url", ";", "// With URL and refresh", "if", "(", "arguments", ".", "length", "<=", "2", ")", "{", "url", "=", "arguments", "[", "0", "]", ";", "refresh", "=", "arguments", "[", "1", "]", ";", "}", "else", "{", "username", "=", "arguments", "[", "0", "]", ";", "repo", "=", "arguments", "[", "1", "]", ";", "branch", "=", "arguments", "[", "2", "]", ";", "refresh", "=", "arguments", "[", "3", "]", ";", "url", "=", "'https://github.com/'", "+", "[", "username", ",", "repo", ",", "'archive'", ",", "branch", "]", ".", "join", "(", "'/'", ")", "+", "'.tar.gz'", ";", "}", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "parent", ".", "remote", ".", "call", "(", "parent", ",", "url", ",", "function", "(", "err", ",", "remote", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "else", "{", "resolve", "(", "remote", ")", ";", "}", "}", ",", "refresh", ")", ";", "}", ")", ";", "}" ]
Asynchronous remote function that returns a Promise @returns {Promise}
[ "Asynchronous", "remote", "function", "that", "returns", "a", "Promise" ]
01d917fe4bc9081e512a206d390b9661947d1f2f
https://github.com/forumone/yeoman-generator-bluebird/blob/01d917fe4bc9081e512a206d390b9661947d1f2f/index.js#L30-L61
50,376
Wizcorp/panopticon
lib/TimedSample.js
TimedSample
function TimedSample(dt, timeStamp, persistObj, scaleFactor) { var time = (dt[0] + dt[1] / 1e9) * 1000 / scaleFactor; this.scaleFactor = scaleFactor; this.min = time; this.max = time; this.sigma = new StandardDeviation(time); this.average = new Average(time); this.timeStamp = timeStamp; if (persistObj) { var that = this; persistObj.on('reset', function (timeStamp) { that.reset(timeStamp); }); } }
javascript
function TimedSample(dt, timeStamp, persistObj, scaleFactor) { var time = (dt[0] + dt[1] / 1e9) * 1000 / scaleFactor; this.scaleFactor = scaleFactor; this.min = time; this.max = time; this.sigma = new StandardDeviation(time); this.average = new Average(time); this.timeStamp = timeStamp; if (persistObj) { var that = this; persistObj.on('reset', function (timeStamp) { that.reset(timeStamp); }); } }
[ "function", "TimedSample", "(", "dt", ",", "timeStamp", ",", "persistObj", ",", "scaleFactor", ")", "{", "var", "time", "=", "(", "dt", "[", "0", "]", "+", "dt", "[", "1", "]", "/", "1e9", ")", "*", "1000", "/", "scaleFactor", ";", "this", ".", "scaleFactor", "=", "scaleFactor", ";", "this", ".", "min", "=", "time", ";", "this", ".", "max", "=", "time", ";", "this", ".", "sigma", "=", "new", "StandardDeviation", "(", "time", ")", ";", "this", ".", "average", "=", "new", "Average", "(", "time", ")", ";", "this", ".", "timeStamp", "=", "timeStamp", ";", "if", "(", "persistObj", ")", "{", "var", "that", "=", "this", ";", "persistObj", ".", "on", "(", "'reset'", ",", "function", "(", "timeStamp", ")", "{", "that", ".", "reset", "(", "timeStamp", ")", ";", "}", ")", ";", "}", "}" ]
Timed sample object constructor. @param {Number[]} dt Takes the output of a diff produced by feeding the result of one hrtime as the parameter to another. @param {Number} timeStamp A unix time stamp (in ms). @param {Object} persistObj Emits reset events. An instance of timed sample belongs to this object. @param {Number} scaleFactor The scale factor for time calculations. 1 -> 1kHz, 1000 -> 1Hz. @constructor @alias module:TimedSample
[ "Timed", "sample", "object", "constructor", "." ]
e0d660cd5287b45aafdb5a91e54affa7364b14e0
https://github.com/Wizcorp/panopticon/blob/e0d660cd5287b45aafdb5a91e54affa7364b14e0/lib/TimedSample.js#L18-L35
50,377
MaximTovstashev/brest
lib/middleware/bodyparser.js
addMode
function addMode(middle, mode, settings) { if (!modes.includes(mode)) throw `Incorrect bodyparser mode ${mode}`; middle.push(bodyParser[mode](settings[mode])); }
javascript
function addMode(middle, mode, settings) { if (!modes.includes(mode)) throw `Incorrect bodyparser mode ${mode}`; middle.push(bodyParser[mode](settings[mode])); }
[ "function", "addMode", "(", "middle", ",", "mode", ",", "settings", ")", "{", "if", "(", "!", "modes", ".", "includes", "(", "mode", ")", ")", "throw", "`", "${", "mode", "}", "`", ";", "middle", ".", "push", "(", "bodyParser", "[", "mode", "]", "(", "settings", "[", "mode", "]", ")", ")", ";", "}" ]
Add a single parse mode to the route middleware @param middle @param mode @param settings
[ "Add", "a", "single", "parse", "mode", "to", "the", "route", "middleware" ]
9b0bd6ee452e55b86cd01d1647f0dff460ad191f
https://github.com/MaximTovstashev/brest/blob/9b0bd6ee452e55b86cd01d1647f0dff460ad191f/lib/middleware/bodyparser.js#L29-L32
50,378
MaximTovstashev/brest
lib/middleware/bodyparser.js
initEndpoint
function initEndpoint(brest, description) { const settings = _.defaultsDeep(description.bodyParser, settingsDefault); if (description.bodyParserModes) { description.bodyParserModes.forEach((mode) => addMode(description.middle, mode, settings)); } else { const mode = description.bodyParserMode || BODY_PARSER_JSON; addMode(description.middle, mode, settings); } // return bodyParser[mode](settings[mode]); }
javascript
function initEndpoint(brest, description) { const settings = _.defaultsDeep(description.bodyParser, settingsDefault); if (description.bodyParserModes) { description.bodyParserModes.forEach((mode) => addMode(description.middle, mode, settings)); } else { const mode = description.bodyParserMode || BODY_PARSER_JSON; addMode(description.middle, mode, settings); } // return bodyParser[mode](settings[mode]); }
[ "function", "initEndpoint", "(", "brest", ",", "description", ")", "{", "const", "settings", "=", "_", ".", "defaultsDeep", "(", "description", ".", "bodyParser", ",", "settingsDefault", ")", ";", "if", "(", "description", ".", "bodyParserModes", ")", "{", "description", ".", "bodyParserModes", ".", "forEach", "(", "(", "mode", ")", "=>", "addMode", "(", "description", ".", "middle", ",", "mode", ",", "settings", ")", ")", ";", "}", "else", "{", "const", "mode", "=", "description", ".", "bodyParserMode", "||", "BODY_PARSER_JSON", ";", "addMode", "(", "description", ".", "middle", ",", "mode", ",", "settings", ")", ";", "}", "// return bodyParser[mode](settings[mode]);", "}" ]
Setup bodyParser middleware according to settings @param brest @param description
[ "Setup", "bodyParser", "middleware", "according", "to", "settings" ]
9b0bd6ee452e55b86cd01d1647f0dff460ad191f
https://github.com/MaximTovstashev/brest/blob/9b0bd6ee452e55b86cd01d1647f0dff460ad191f/lib/middleware/bodyparser.js#L39-L51
50,379
ritenv/ng-wistia-components
ng-wistia-components.js
function (e, data) { ctrl.coreWistia.setError(); //clear any previous errors data .submit() .then(function (result, textStatus, jqXHR) { ctrl.coreWistia.playVideo(result.hashed_id); }) .catch(function (jqXHR, textStatus, errorThrown) { $timeout(function() { ctrl.coreWistia.setError('WistiaError: ' + jqXHR.responseJSON ? jqXHR.responseJSON.error : errorThrown); }); }) ; }
javascript
function (e, data) { ctrl.coreWistia.setError(); //clear any previous errors data .submit() .then(function (result, textStatus, jqXHR) { ctrl.coreWistia.playVideo(result.hashed_id); }) .catch(function (jqXHR, textStatus, errorThrown) { $timeout(function() { ctrl.coreWistia.setError('WistiaError: ' + jqXHR.responseJSON ? jqXHR.responseJSON.error : errorThrown); }); }) ; }
[ "function", "(", "e", ",", "data", ")", "{", "ctrl", ".", "coreWistia", ".", "setError", "(", ")", ";", "//clear any previous errors", "data", ".", "submit", "(", ")", ".", "then", "(", "function", "(", "result", ",", "textStatus", ",", "jqXHR", ")", "{", "ctrl", ".", "coreWistia", ".", "playVideo", "(", "result", ".", "hashed_id", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "jqXHR", ",", "textStatus", ",", "errorThrown", ")", "{", "$timeout", "(", "function", "(", ")", "{", "ctrl", ".", "coreWistia", ".", "setError", "(", "'WistiaError: '", "+", "jqXHR", ".", "responseJSON", "?", "jqXHR", ".", "responseJSON", ".", "error", ":", "errorThrown", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Called when a file is added for uploading
[ "Called", "when", "a", "file", "is", "added", "for", "uploading" ]
d3aa58c2c52550e8784168073d91f1d62d90ed76
https://github.com/ritenv/ng-wistia-components/blob/d3aa58c2c52550e8784168073d91f1d62d90ed76/ng-wistia-components.js#L194-L208
50,380
ritenv/ng-wistia-components
ng-wistia-components.js
function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $timeout(function() { ctrl.coreWistia.setProgress(progress); }); }
javascript
function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $timeout(function() { ctrl.coreWistia.setProgress(progress); }); }
[ "function", "(", "e", ",", "data", ")", "{", "var", "progress", "=", "parseInt", "(", "data", ".", "loaded", "/", "data", ".", "total", "*", "100", ",", "10", ")", ";", "$timeout", "(", "function", "(", ")", "{", "ctrl", ".", "coreWistia", ".", "setProgress", "(", "progress", ")", ";", "}", ")", ";", "}" ]
Called whenever upload progress is updated
[ "Called", "whenever", "upload", "progress", "is", "updated" ]
d3aa58c2c52550e8784168073d91f1d62d90ed76
https://github.com/ritenv/ng-wistia-components/blob/d3aa58c2c52550e8784168073d91f1d62d90ed76/ng-wistia-components.js#L213-L219
50,381
andreaswillems/mongo-crud-layer
lib/mongo-crud-layer.js
MongoCrud
function MongoCrud(uri, options, gridFS) { this.uri = uri || 'mongodb://localhost:27017/mongo-crud-test'; this.options = options || {}; this.gridFS = gridFS; }
javascript
function MongoCrud(uri, options, gridFS) { this.uri = uri || 'mongodb://localhost:27017/mongo-crud-test'; this.options = options || {}; this.gridFS = gridFS; }
[ "function", "MongoCrud", "(", "uri", ",", "options", ",", "gridFS", ")", "{", "this", ".", "uri", "=", "uri", "||", "'mongodb://localhost:27017/mongo-crud-test'", ";", "this", ".", "options", "=", "options", "||", "{", "}", ";", "this", ".", "gridFS", "=", "gridFS", ";", "}" ]
Creates a MongoCrudLayer instance with given properties. @param uri - the MongoDB URI, defaults to 'mongodb://localhost:27017/mongo-crud-test @param options - Options used when connecting to MongoDB, defaults to an empty object @param gridFS - set to true, if objects exceed MongoDB document limit of 16mb, to store objects with GridFS mechanism @constructor
[ "Creates", "a", "MongoCrudLayer", "instance", "with", "given", "properties", "." ]
571c523c6b4f37226626c7eff339f745d94cbe68
https://github.com/andreaswillems/mongo-crud-layer/blob/571c523c6b4f37226626c7eff339f745d94cbe68/lib/mongo-crud-layer.js#L24-L28
50,382
origin1tech/mustr
dist/cli.js
help
function help() { var padBtm = [0, 0, 1, 0]; var msg = ' See additional required/optional arguments for each command below. \n'; pargv .logo('Mustr', 'cyan') .ui(95) .join(chalk.magenta('Usage:'), 'mu', chalk.cyan('<cmd>'), '\n') .div({ text: chalk.bgBlue.white(msg) }) .div({ text: chalk.cyan('help, h'), width: 35, padding: padBtm }, { text: chalk.gray('displays help and usage information.'), width: 40, padding: padBtm }) .div({ text: chalk.cyan('init, i'), width: 35, padding: padBtm }, { text: chalk.gray('initialize the application for use with Mustr.'), width: 40, padding: padBtm }) .div({ text: chalk.cyan('generate, g') + " " + chalk.white('<template>') + " " + chalk.magenta('[output]'), width: 35, padding: padBtm }, { text: chalk.gray('generates and renders a template.'), width: 40, padding: padBtm }) .div({ text: chalk.white('<template>'), width: 35, padding: [0, 2, 0, 2] }, { text: chalk.gray('template to generate and compile.'), width: 40 }, { text: chalk.red('[required]'), align: 'right' }) .div({ text: chalk.white('[output]'), width: 35, padding: [0, 2, 0, 2] }, { text: chalk.gray('output name/path for template'), width: 40, padding: padBtm }) .div({ text: chalk.cyan('rollback, r') + " " + chalk.white('<name/id>') + " " + chalk.magenta('[output]'), width: 35, padding: padBtm }, { text: chalk.gray('Rolls back a template or component.'), width: 40, padding: padBtm }) .div({ text: chalk.white('<name/id>'), width: 35, padding: [0, 2, 0, 2] }, { text: chalk.gray('the rollback id, index or template name.'), width: 40 }) .div({ text: chalk.white('[output]'), width: 35, padding: [0, 2, 0, 2] }, { text: chalk.gray('output name/path for template'), width: 40, padding: padBtm }) .div({ text: chalk.cyan('show, s') + " " + chalk.white('<type>'), width: 35, padding: padBtm }, { text: chalk.gray('shows details/stats for the given type.'), width: 40, padding: padBtm }) .div({ text: chalk.white('<type>'), width: 35, padding: [0, 2, 0, 2] }, { text: chalk.gray('currently there is only one type "rollbacks"'), width: 40 }) .show(); }
javascript
function help() { var padBtm = [0, 0, 1, 0]; var msg = ' See additional required/optional arguments for each command below. \n'; pargv .logo('Mustr', 'cyan') .ui(95) .join(chalk.magenta('Usage:'), 'mu', chalk.cyan('<cmd>'), '\n') .div({ text: chalk.bgBlue.white(msg) }) .div({ text: chalk.cyan('help, h'), width: 35, padding: padBtm }, { text: chalk.gray('displays help and usage information.'), width: 40, padding: padBtm }) .div({ text: chalk.cyan('init, i'), width: 35, padding: padBtm }, { text: chalk.gray('initialize the application for use with Mustr.'), width: 40, padding: padBtm }) .div({ text: chalk.cyan('generate, g') + " " + chalk.white('<template>') + " " + chalk.magenta('[output]'), width: 35, padding: padBtm }, { text: chalk.gray('generates and renders a template.'), width: 40, padding: padBtm }) .div({ text: chalk.white('<template>'), width: 35, padding: [0, 2, 0, 2] }, { text: chalk.gray('template to generate and compile.'), width: 40 }, { text: chalk.red('[required]'), align: 'right' }) .div({ text: chalk.white('[output]'), width: 35, padding: [0, 2, 0, 2] }, { text: chalk.gray('output name/path for template'), width: 40, padding: padBtm }) .div({ text: chalk.cyan('rollback, r') + " " + chalk.white('<name/id>') + " " + chalk.magenta('[output]'), width: 35, padding: padBtm }, { text: chalk.gray('Rolls back a template or component.'), width: 40, padding: padBtm }) .div({ text: chalk.white('<name/id>'), width: 35, padding: [0, 2, 0, 2] }, { text: chalk.gray('the rollback id, index or template name.'), width: 40 }) .div({ text: chalk.white('[output]'), width: 35, padding: [0, 2, 0, 2] }, { text: chalk.gray('output name/path for template'), width: 40, padding: padBtm }) .div({ text: chalk.cyan('show, s') + " " + chalk.white('<type>'), width: 35, padding: padBtm }, { text: chalk.gray('shows details/stats for the given type.'), width: 40, padding: padBtm }) .div({ text: chalk.white('<type>'), width: 35, padding: [0, 2, 0, 2] }, { text: chalk.gray('currently there is only one type "rollbacks"'), width: 40 }) .show(); }
[ "function", "help", "(", ")", "{", "var", "padBtm", "=", "[", "0", ",", "0", ",", "1", ",", "0", "]", ";", "var", "msg", "=", "' See additional required/optional arguments for each command below. \\n'", ";", "pargv", ".", "logo", "(", "'Mustr'", ",", "'cyan'", ")", ".", "ui", "(", "95", ")", ".", "join", "(", "chalk", ".", "magenta", "(", "'Usage:'", ")", ",", "'mu'", ",", "chalk", ".", "cyan", "(", "'<cmd>'", ")", ",", "'\\n'", ")", ".", "div", "(", "{", "text", ":", "chalk", ".", "bgBlue", ".", "white", "(", "msg", ")", "}", ")", ".", "div", "(", "{", "text", ":", "chalk", ".", "cyan", "(", "'help, h'", ")", ",", "width", ":", "35", ",", "padding", ":", "padBtm", "}", ",", "{", "text", ":", "chalk", ".", "gray", "(", "'displays help and usage information.'", ")", ",", "width", ":", "40", ",", "padding", ":", "padBtm", "}", ")", ".", "div", "(", "{", "text", ":", "chalk", ".", "cyan", "(", "'init, i'", ")", ",", "width", ":", "35", ",", "padding", ":", "padBtm", "}", ",", "{", "text", ":", "chalk", ".", "gray", "(", "'initialize the application for use with Mustr.'", ")", ",", "width", ":", "40", ",", "padding", ":", "padBtm", "}", ")", ".", "div", "(", "{", "text", ":", "chalk", ".", "cyan", "(", "'generate, g'", ")", "+", "\" \"", "+", "chalk", ".", "white", "(", "'<template>'", ")", "+", "\" \"", "+", "chalk", ".", "magenta", "(", "'[output]'", ")", ",", "width", ":", "35", ",", "padding", ":", "padBtm", "}", ",", "{", "text", ":", "chalk", ".", "gray", "(", "'generates and renders a template.'", ")", ",", "width", ":", "40", ",", "padding", ":", "padBtm", "}", ")", ".", "div", "(", "{", "text", ":", "chalk", ".", "white", "(", "'<template>'", ")", ",", "width", ":", "35", ",", "padding", ":", "[", "0", ",", "2", ",", "0", ",", "2", "]", "}", ",", "{", "text", ":", "chalk", ".", "gray", "(", "'template to generate and compile.'", ")", ",", "width", ":", "40", "}", ",", "{", "text", ":", "chalk", ".", "red", "(", "'[required]'", ")", ",", "align", ":", "'right'", "}", ")", ".", "div", "(", "{", "text", ":", "chalk", ".", "white", "(", "'[output]'", ")", ",", "width", ":", "35", ",", "padding", ":", "[", "0", ",", "2", ",", "0", ",", "2", "]", "}", ",", "{", "text", ":", "chalk", ".", "gray", "(", "'output name/path for template'", ")", ",", "width", ":", "40", ",", "padding", ":", "padBtm", "}", ")", ".", "div", "(", "{", "text", ":", "chalk", ".", "cyan", "(", "'rollback, r'", ")", "+", "\" \"", "+", "chalk", ".", "white", "(", "'<name/id>'", ")", "+", "\" \"", "+", "chalk", ".", "magenta", "(", "'[output]'", ")", ",", "width", ":", "35", ",", "padding", ":", "padBtm", "}", ",", "{", "text", ":", "chalk", ".", "gray", "(", "'Rolls back a template or component.'", ")", ",", "width", ":", "40", ",", "padding", ":", "padBtm", "}", ")", ".", "div", "(", "{", "text", ":", "chalk", ".", "white", "(", "'<name/id>'", ")", ",", "width", ":", "35", ",", "padding", ":", "[", "0", ",", "2", ",", "0", ",", "2", "]", "}", ",", "{", "text", ":", "chalk", ".", "gray", "(", "'the rollback id, index or template name.'", ")", ",", "width", ":", "40", "}", ")", ".", "div", "(", "{", "text", ":", "chalk", ".", "white", "(", "'[output]'", ")", ",", "width", ":", "35", ",", "padding", ":", "[", "0", ",", "2", ",", "0", ",", "2", "]", "}", ",", "{", "text", ":", "chalk", ".", "gray", "(", "'output name/path for template'", ")", ",", "width", ":", "40", ",", "padding", ":", "padBtm", "}", ")", ".", "div", "(", "{", "text", ":", "chalk", ".", "cyan", "(", "'show, s'", ")", "+", "\" \"", "+", "chalk", ".", "white", "(", "'<type>'", ")", ",", "width", ":", "35", ",", "padding", ":", "padBtm", "}", ",", "{", "text", ":", "chalk", ".", "gray", "(", "'shows details/stats for the given type.'", ")", ",", "width", ":", "40", ",", "padding", ":", "padBtm", "}", ")", ".", "div", "(", "{", "text", ":", "chalk", ".", "white", "(", "'<type>'", ")", ",", "width", ":", "35", ",", "padding", ":", "[", "0", ",", "2", ",", "0", ",", "2", "]", "}", ",", "{", "text", ":", "chalk", ".", "gray", "(", "'currently there is only one type \"rollbacks\"'", ")", ",", "width", ":", "40", "}", ")", ".", "show", "(", ")", ";", "}" ]
Handler for help.
[ "Handler", "for", "help", "." ]
66e6a9fbbf8c7d3a3939bf3d2c69f56e047909d8
https://github.com/origin1tech/mustr/blob/66e6a9fbbf8c7d3a3939bf3d2c69f56e047909d8/dist/cli.js#L37-L56
50,383
origin1tech/mustr
dist/cli.js
generate
function generate() { var parsed = ensureConfig(); if (!parsed.name) mu.log.error('cannot generate template using name of undefined.\n').write().exit(); // Generate the template. mu.render(parsed.name, parsed.output, parsed.options); }
javascript
function generate() { var parsed = ensureConfig(); if (!parsed.name) mu.log.error('cannot generate template using name of undefined.\n').write().exit(); // Generate the template. mu.render(parsed.name, parsed.output, parsed.options); }
[ "function", "generate", "(", ")", "{", "var", "parsed", "=", "ensureConfig", "(", ")", ";", "if", "(", "!", "parsed", ".", "name", ")", "mu", ".", "log", ".", "error", "(", "'cannot generate template using name of undefined.\\n'", ")", ".", "write", "(", ")", ".", "exit", "(", ")", ";", "// Generate the template.", "mu", ".", "render", "(", "parsed", ".", "name", ",", "parsed", ".", "output", ",", "parsed", ".", "options", ")", ";", "}" ]
Handler for generating templates.
[ "Handler", "for", "generating", "templates", "." ]
66e6a9fbbf8c7d3a3939bf3d2c69f56e047909d8
https://github.com/origin1tech/mustr/blob/66e6a9fbbf8c7d3a3939bf3d2c69f56e047909d8/dist/cli.js#L62-L68
50,384
origin1tech/mustr
dist/cli.js
rollback
function rollback() { var parsed = ensureConfig(); var name = parsed.name; // check if is an index number. // if yes try to lookup the id // by its index. try { var idx = void 0; if (/^[0-9]+$/.test(name)) { idx = parseInt(parsed.name) - 1; if (idx >= 0) { var keys = Object.keys(mu.rollbacks); var key = keys[idx]; if (key) name = key; } } } catch (ex) { } mu.rollback(parsed.name, parsed.output); }
javascript
function rollback() { var parsed = ensureConfig(); var name = parsed.name; // check if is an index number. // if yes try to lookup the id // by its index. try { var idx = void 0; if (/^[0-9]+$/.test(name)) { idx = parseInt(parsed.name) - 1; if (idx >= 0) { var keys = Object.keys(mu.rollbacks); var key = keys[idx]; if (key) name = key; } } } catch (ex) { } mu.rollback(parsed.name, parsed.output); }
[ "function", "rollback", "(", ")", "{", "var", "parsed", "=", "ensureConfig", "(", ")", ";", "var", "name", "=", "parsed", ".", "name", ";", "// check if is an index number.", "// if yes try to lookup the id", "// by its index.", "try", "{", "var", "idx", "=", "void", "0", ";", "if", "(", "/", "^[0-9]+$", "/", ".", "test", "(", "name", ")", ")", "{", "idx", "=", "parseInt", "(", "parsed", ".", "name", ")", "-", "1", ";", "if", "(", "idx", ">=", "0", ")", "{", "var", "keys", "=", "Object", ".", "keys", "(", "mu", ".", "rollbacks", ")", ";", "var", "key", "=", "keys", "[", "idx", "]", ";", "if", "(", "key", ")", "name", "=", "key", ";", "}", "}", "}", "catch", "(", "ex", ")", "{", "}", "mu", ".", "rollback", "(", "parsed", ".", "name", ",", "parsed", ".", "output", ")", ";", "}" ]
Handler for rollbacks
[ "Handler", "for", "rollbacks" ]
66e6a9fbbf8c7d3a3939bf3d2c69f56e047909d8
https://github.com/origin1tech/mustr/blob/66e6a9fbbf8c7d3a3939bf3d2c69f56e047909d8/dist/cli.js#L70-L90
50,385
origin1tech/mustr
dist/cli.js
show
function show() { var parsed = ensureConfig(); function showRollbacks() { var rollbacks = mu.getRollbacks(); var keys = Object.keys(rollbacks); var padBtm = [0, 0, 1, 0]; var ui = pargv.ui(105); var i = keys.length; var hdrNo = { text: " ", width: 5 }; var hdrId = { text: "" + chalk.underline.gray('ID'), width: 20 }; var hdrTs = { text: "" + chalk.underline.gray('Timestamp'), width: 30 }; var hdrCt = { text: "" + chalk.underline.gray('Count'), width: 10 }; var hdrTpl = { text: "" + chalk.underline.gray('Templates'), width: 35, padding: padBtm }; ui.div(hdrNo, hdrId, hdrTs, hdrCt, hdrTpl); while (i--) { var key = keys[i]; var rb = rollbacks[key]; var no = { text: i + 1 + ")", width: 5 }; var id = { text: "" + chalk.cyan(rb.id), width: 20 }; var ts = { text: "" + chalk.yellow(rb.timestamp), width: 30 }; var ct = { text: "" + chalk.green(rb.count + ''), width: 10 }; var tpl = { text: "" + chalk.magenta(rb.templates.join(', ')), width: 35 }; ui.div(no, id, ts, ct, tpl); } ui.show(); } switch (parsed.name) { case 'r': showRollbacks(); break; case 'rollbacks': showRollbacks(); break; default: break; } }
javascript
function show() { var parsed = ensureConfig(); function showRollbacks() { var rollbacks = mu.getRollbacks(); var keys = Object.keys(rollbacks); var padBtm = [0, 0, 1, 0]; var ui = pargv.ui(105); var i = keys.length; var hdrNo = { text: " ", width: 5 }; var hdrId = { text: "" + chalk.underline.gray('ID'), width: 20 }; var hdrTs = { text: "" + chalk.underline.gray('Timestamp'), width: 30 }; var hdrCt = { text: "" + chalk.underline.gray('Count'), width: 10 }; var hdrTpl = { text: "" + chalk.underline.gray('Templates'), width: 35, padding: padBtm }; ui.div(hdrNo, hdrId, hdrTs, hdrCt, hdrTpl); while (i--) { var key = keys[i]; var rb = rollbacks[key]; var no = { text: i + 1 + ")", width: 5 }; var id = { text: "" + chalk.cyan(rb.id), width: 20 }; var ts = { text: "" + chalk.yellow(rb.timestamp), width: 30 }; var ct = { text: "" + chalk.green(rb.count + ''), width: 10 }; var tpl = { text: "" + chalk.magenta(rb.templates.join(', ')), width: 35 }; ui.div(no, id, ts, ct, tpl); } ui.show(); } switch (parsed.name) { case 'r': showRollbacks(); break; case 'rollbacks': showRollbacks(); break; default: break; } }
[ "function", "show", "(", ")", "{", "var", "parsed", "=", "ensureConfig", "(", ")", ";", "function", "showRollbacks", "(", ")", "{", "var", "rollbacks", "=", "mu", ".", "getRollbacks", "(", ")", ";", "var", "keys", "=", "Object", ".", "keys", "(", "rollbacks", ")", ";", "var", "padBtm", "=", "[", "0", ",", "0", ",", "1", ",", "0", "]", ";", "var", "ui", "=", "pargv", ".", "ui", "(", "105", ")", ";", "var", "i", "=", "keys", ".", "length", ";", "var", "hdrNo", "=", "{", "text", ":", "\" \"", ",", "width", ":", "5", "}", ";", "var", "hdrId", "=", "{", "text", ":", "\"\"", "+", "chalk", ".", "underline", ".", "gray", "(", "'ID'", ")", ",", "width", ":", "20", "}", ";", "var", "hdrTs", "=", "{", "text", ":", "\"\"", "+", "chalk", ".", "underline", ".", "gray", "(", "'Timestamp'", ")", ",", "width", ":", "30", "}", ";", "var", "hdrCt", "=", "{", "text", ":", "\"\"", "+", "chalk", ".", "underline", ".", "gray", "(", "'Count'", ")", ",", "width", ":", "10", "}", ";", "var", "hdrTpl", "=", "{", "text", ":", "\"\"", "+", "chalk", ".", "underline", ".", "gray", "(", "'Templates'", ")", ",", "width", ":", "35", ",", "padding", ":", "padBtm", "}", ";", "ui", ".", "div", "(", "hdrNo", ",", "hdrId", ",", "hdrTs", ",", "hdrCt", ",", "hdrTpl", ")", ";", "while", "(", "i", "--", ")", "{", "var", "key", "=", "keys", "[", "i", "]", ";", "var", "rb", "=", "rollbacks", "[", "key", "]", ";", "var", "no", "=", "{", "text", ":", "i", "+", "1", "+", "\")\"", ",", "width", ":", "5", "}", ";", "var", "id", "=", "{", "text", ":", "\"\"", "+", "chalk", ".", "cyan", "(", "rb", ".", "id", ")", ",", "width", ":", "20", "}", ";", "var", "ts", "=", "{", "text", ":", "\"\"", "+", "chalk", ".", "yellow", "(", "rb", ".", "timestamp", ")", ",", "width", ":", "30", "}", ";", "var", "ct", "=", "{", "text", ":", "\"\"", "+", "chalk", ".", "green", "(", "rb", ".", "count", "+", "''", ")", ",", "width", ":", "10", "}", ";", "var", "tpl", "=", "{", "text", ":", "\"\"", "+", "chalk", ".", "magenta", "(", "rb", ".", "templates", ".", "join", "(", "', '", ")", ")", ",", "width", ":", "35", "}", ";", "ui", ".", "div", "(", "no", ",", "id", ",", "ts", ",", "ct", ",", "tpl", ")", ";", "}", "ui", ".", "show", "(", ")", ";", "}", "switch", "(", "parsed", ".", "name", ")", "{", "case", "'r'", ":", "showRollbacks", "(", ")", ";", "break", ";", "case", "'rollbacks'", ":", "showRollbacks", "(", ")", ";", "break", ";", "default", ":", "break", ";", "}", "}" ]
Handler for show
[ "Handler", "for", "show" ]
66e6a9fbbf8c7d3a3939bf3d2c69f56e047909d8
https://github.com/origin1tech/mustr/blob/66e6a9fbbf8c7d3a3939bf3d2c69f56e047909d8/dist/cli.js#L92-L128
50,386
syntheticore/declaire
src/clientAuth.js
function(username, pw) { return _.ajax({ verb: 'POST', url: '/login', data: { username: username, password: pw } }).then(function(id) { document.cookie = 'user=' + id; return id; }); }
javascript
function(username, pw) { return _.ajax({ verb: 'POST', url: '/login', data: { username: username, password: pw } }).then(function(id) { document.cookie = 'user=' + id; return id; }); }
[ "function", "(", "username", ",", "pw", ")", "{", "return", "_", ".", "ajax", "(", "{", "verb", ":", "'POST'", ",", "url", ":", "'/login'", ",", "data", ":", "{", "username", ":", "username", ",", "password", ":", "pw", "}", "}", ")", ".", "then", "(", "function", "(", "id", ")", "{", "document", ".", "cookie", "=", "'user='", "+", "id", ";", "return", "id", ";", "}", ")", ";", "}" ]
Return a promise that resolves to a user ID if authorization was successful
[ "Return", "a", "promise", "that", "resolves", "to", "a", "user", "ID", "if", "authorization", "was", "successful" ]
cb5ea205eeb3aa26fd0c6348e86d840c04e9ba9f
https://github.com/syntheticore/declaire/blob/cb5ea205eeb3aa26fd0c6348e86d840c04e9ba9f/src/clientAuth.js#L6-L18
50,387
tableflip/uri-to-multiaddr
index.js
multiaddrFromUri
function multiaddrFromUri (uriStr, opts) { opts = opts || {} const defaultDnsType = opts.defaultDnsType || 'dns4' const { scheme, hostname, port } = parseUri(uriStr) const parts = [ tupleForHostname(hostname, defaultDnsType), tupleForPort(port, scheme), tupleForScheme(scheme) ] const multiaddrStr = '/' + parts .filter(x => !!x) .reduce((a, b) => a.concat(b)) .join('/') return Multiaddr(multiaddrStr) }
javascript
function multiaddrFromUri (uriStr, opts) { opts = opts || {} const defaultDnsType = opts.defaultDnsType || 'dns4' const { scheme, hostname, port } = parseUri(uriStr) const parts = [ tupleForHostname(hostname, defaultDnsType), tupleForPort(port, scheme), tupleForScheme(scheme) ] const multiaddrStr = '/' + parts .filter(x => !!x) .reduce((a, b) => a.concat(b)) .join('/') return Multiaddr(multiaddrStr) }
[ "function", "multiaddrFromUri", "(", "uriStr", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", "const", "defaultDnsType", "=", "opts", ".", "defaultDnsType", "||", "'dns4'", "const", "{", "scheme", ",", "hostname", ",", "port", "}", "=", "parseUri", "(", "uriStr", ")", "const", "parts", "=", "[", "tupleForHostname", "(", "hostname", ",", "defaultDnsType", ")", ",", "tupleForPort", "(", "port", ",", "scheme", ")", ",", "tupleForScheme", "(", "scheme", ")", "]", "const", "multiaddrStr", "=", "'/'", "+", "parts", ".", "filter", "(", "x", "=>", "!", "!", "x", ")", ".", "reduce", "(", "(", "a", ",", "b", ")", "=>", "a", ".", "concat", "(", "b", ")", ")", ".", "join", "(", "'/'", ")", "return", "Multiaddr", "(", "multiaddrStr", ")", "}" ]
Convert a URI to a multiaddr http://foobar.com => /dns4/foobar.com/tcp/80/http https://foobar.com => /dns4/foobar.com/tcp/443/https https://foobar.com:5001 => /dns4/foobar.com/tcp/5001/https https://127.0.0.1:8080 => /ip4/127.0.0.1/tcp/8080/https http://[::1]:8080 => /ip6/::1/tcp/8080/http tcp://foobar.com:8080 => /dns4/foobar.com/tcp/8080 udp://foobar.com:8080 => /dns4/foobar.com/udp/8080
[ "Convert", "a", "URI", "to", "a", "multiaddr" ]
f92410ebc04f0d46eede7905c06e235f5c698758
https://github.com/tableflip/uri-to-multiaddr/blob/f92410ebc04f0d46eede7905c06e235f5c698758/index.js#L16-L31
50,388
makanaleu/wmt-marketplace-auth
lib/headers.js
sign
function sign(custom, request) { /** * An Epoch timestamp is required for the digital signature. */ let epoch = Util.epochInMilliseconds(); /** * Override the generated Epoch timestamp if a timestamp was included in the * custom headers. */ if (custom.WMSecurity && custom.WMSecurity.Timestamp) { epoch = custom.WMSecurity.Timestamp; } /** * The generated digital signature. */ let signature = digitalSignature(custom, request, epoch); /** * Override the generated digital signature if a signature was included in the * custom headers. */ if (custom.WMSecurity && custom.WMSecurity.AuthSignature) { signature = custom.WMSecurity.AuthSignature; } /** * The signed request headers according to Walmart API spec. */ let signedHeaders = { 'WM_SVC.NAME': custom.WMService.Name, 'WM_QOS.CORRELATION_ID': custom.WMQOS.CorrelationId, 'WM_SEC.TIMESTAMP': epoch, 'WM_SEC.AUTH_SIGNATURE': signature, 'WM_CONSUMER.CHANNEL.TYPE': custom.WMConsumer.Channel.Type, 'WM_CONSUMER.ID': custom.WMConsumer.ConsumerId, 'Accept': custom.Accept, 'Content-Type': custom.Accept }; return signedHeaders; }
javascript
function sign(custom, request) { /** * An Epoch timestamp is required for the digital signature. */ let epoch = Util.epochInMilliseconds(); /** * Override the generated Epoch timestamp if a timestamp was included in the * custom headers. */ if (custom.WMSecurity && custom.WMSecurity.Timestamp) { epoch = custom.WMSecurity.Timestamp; } /** * The generated digital signature. */ let signature = digitalSignature(custom, request, epoch); /** * Override the generated digital signature if a signature was included in the * custom headers. */ if (custom.WMSecurity && custom.WMSecurity.AuthSignature) { signature = custom.WMSecurity.AuthSignature; } /** * The signed request headers according to Walmart API spec. */ let signedHeaders = { 'WM_SVC.NAME': custom.WMService.Name, 'WM_QOS.CORRELATION_ID': custom.WMQOS.CorrelationId, 'WM_SEC.TIMESTAMP': epoch, 'WM_SEC.AUTH_SIGNATURE': signature, 'WM_CONSUMER.CHANNEL.TYPE': custom.WMConsumer.Channel.Type, 'WM_CONSUMER.ID': custom.WMConsumer.ConsumerId, 'Accept': custom.Accept, 'Content-Type': custom.Accept }; return signedHeaders; }
[ "function", "sign", "(", "custom", ",", "request", ")", "{", "/**\n * An Epoch timestamp is required for the digital signature.\n */", "let", "epoch", "=", "Util", ".", "epochInMilliseconds", "(", ")", ";", "/**\n * Override the generated Epoch timestamp if a timestamp was included in the\n * custom headers.\n */", "if", "(", "custom", ".", "WMSecurity", "&&", "custom", ".", "WMSecurity", ".", "Timestamp", ")", "{", "epoch", "=", "custom", ".", "WMSecurity", ".", "Timestamp", ";", "}", "/**\n * The generated digital signature.\n */", "let", "signature", "=", "digitalSignature", "(", "custom", ",", "request", ",", "epoch", ")", ";", "/**\n * Override the generated digital signature if a signature was included in the\n * custom headers.\n */", "if", "(", "custom", ".", "WMSecurity", "&&", "custom", ".", "WMSecurity", ".", "AuthSignature", ")", "{", "signature", "=", "custom", ".", "WMSecurity", ".", "AuthSignature", ";", "}", "/**\n * The signed request headers according to Walmart API spec.\n */", "let", "signedHeaders", "=", "{", "'WM_SVC.NAME'", ":", "custom", ".", "WMService", ".", "Name", ",", "'WM_QOS.CORRELATION_ID'", ":", "custom", ".", "WMQOS", ".", "CorrelationId", ",", "'WM_SEC.TIMESTAMP'", ":", "epoch", ",", "'WM_SEC.AUTH_SIGNATURE'", ":", "signature", ",", "'WM_CONSUMER.CHANNEL.TYPE'", ":", "custom", ".", "WMConsumer", ".", "Channel", ".", "Type", ",", "'WM_CONSUMER.ID'", ":", "custom", ".", "WMConsumer", ".", "ConsumerId", ",", "'Accept'", ":", "custom", ".", "Accept", ",", "'Content-Type'", ":", "custom", ".", "Accept", "}", ";", "return", "signedHeaders", ";", "}" ]
Returns the signed headers required for the API request. @param custom Walmart authentication headers. Use the custom class to set custom values to the headers before adding to the request. @param request The request properties required to generate the digital signature.
[ "Returns", "the", "signed", "headers", "required", "for", "the", "API", "request", "." ]
1c48336293d52709bdda774ec1158193edf90773
https://github.com/makanaleu/wmt-marketplace-auth/blob/1c48336293d52709bdda774ec1158193edf90773/lib/headers.js#L58-L95
50,389
makanaleu/wmt-marketplace-auth
lib/headers.js
digitalSignature
function digitalSignature(custom, request, epoch) { /** * Node Crypto Sign object that uses the given algorithm. * * @see {@link https://nodejs.org/api/crypto.html#crypto_class_sign} */ const signer = crypto_1.createSign('RSA-SHA256'); /** * Walmart API request string to be signed. */ let stringToSign = custom.WMConsumer.ConsumerId + "\n" + request.RequestUrl + "\n" + request.RequestMethod.toUpperCase() + "\n" + epoch + "\n"; /** * Updates the Sign content with the given data. * @see {@link https://nodejs.org/api/crypto.html#crypto_sign_update_data_inputencoding} */ signer.update(stringToSign); /** * Private key wrapped in key header and footer. */ let privateKey = "-----BEGIN PRIVATE KEY-----\n" + request.PrivateKey + "\n-----END PRIVATE KEY-----"; return signer.sign(privateKey, 'base64'); }
javascript
function digitalSignature(custom, request, epoch) { /** * Node Crypto Sign object that uses the given algorithm. * * @see {@link https://nodejs.org/api/crypto.html#crypto_class_sign} */ const signer = crypto_1.createSign('RSA-SHA256'); /** * Walmart API request string to be signed. */ let stringToSign = custom.WMConsumer.ConsumerId + "\n" + request.RequestUrl + "\n" + request.RequestMethod.toUpperCase() + "\n" + epoch + "\n"; /** * Updates the Sign content with the given data. * @see {@link https://nodejs.org/api/crypto.html#crypto_sign_update_data_inputencoding} */ signer.update(stringToSign); /** * Private key wrapped in key header and footer. */ let privateKey = "-----BEGIN PRIVATE KEY-----\n" + request.PrivateKey + "\n-----END PRIVATE KEY-----"; return signer.sign(privateKey, 'base64'); }
[ "function", "digitalSignature", "(", "custom", ",", "request", ",", "epoch", ")", "{", "/**\n * Node Crypto Sign object that uses the given algorithm.\n *\n * @see {@link https://nodejs.org/api/crypto.html#crypto_class_sign}\n */", "const", "signer", "=", "crypto_1", ".", "createSign", "(", "'RSA-SHA256'", ")", ";", "/**\n * Walmart API request string to be signed.\n */", "let", "stringToSign", "=", "custom", ".", "WMConsumer", ".", "ConsumerId", "+", "\"\\n\"", "+", "request", ".", "RequestUrl", "+", "\"\\n\"", "+", "request", ".", "RequestMethod", ".", "toUpperCase", "(", ")", "+", "\"\\n\"", "+", "epoch", "+", "\"\\n\"", ";", "/**\n * Updates the Sign content with the given data.\n * @see {@link https://nodejs.org/api/crypto.html#crypto_sign_update_data_inputencoding}\n */", "signer", ".", "update", "(", "stringToSign", ")", ";", "/**\n * Private key wrapped in key header and footer.\n */", "let", "privateKey", "=", "\"-----BEGIN PRIVATE KEY-----\\n\"", "+", "request", ".", "PrivateKey", "+", "\"\\n-----END PRIVATE KEY-----\"", ";", "return", "signer", ".", "sign", "(", "privateKey", ",", "'base64'", ")", ";", "}" ]
Generates the digital signature required for the API request. @param custom Walmart authentication headers. Use the custom class to set custom values to the headers before adding to the request. @param request The request properties required to generate the digital signature. @param epoch An Epoch timestamp is required for the digital signature.
[ "Generates", "the", "digital", "signature", "required", "for", "the", "API", "request", "." ]
1c48336293d52709bdda774ec1158193edf90773
https://github.com/makanaleu/wmt-marketplace-auth/blob/1c48336293d52709bdda774ec1158193edf90773/lib/headers.js#L105-L127
50,390
andrewscwei/requiem
src/dom/namespace.js
namespace
function namespace(path, scope) { assertType(path, 'string', true, 'Invalid parameter: path'); assertType(scope, 'object', true, 'Invalid optional parameter: scope'); if (!scope) scope = (window) ? window : {}; if (path === undefined || path === '') return scope; let groups = path.split('.'); let currentScope = scope; for (let i = 0; i < groups.length; i++) { currentScope = currentScope[groups[i]] || (currentScope[groups[i]] = {}); } return currentScope; }
javascript
function namespace(path, scope) { assertType(path, 'string', true, 'Invalid parameter: path'); assertType(scope, 'object', true, 'Invalid optional parameter: scope'); if (!scope) scope = (window) ? window : {}; if (path === undefined || path === '') return scope; let groups = path.split('.'); let currentScope = scope; for (let i = 0; i < groups.length; i++) { currentScope = currentScope[groups[i]] || (currentScope[groups[i]] = {}); } return currentScope; }
[ "function", "namespace", "(", "path", ",", "scope", ")", "{", "assertType", "(", "path", ",", "'string'", ",", "true", ",", "'Invalid parameter: path'", ")", ";", "assertType", "(", "scope", ",", "'object'", ",", "true", ",", "'Invalid optional parameter: scope'", ")", ";", "if", "(", "!", "scope", ")", "scope", "=", "(", "window", ")", "?", "window", ":", "{", "}", ";", "if", "(", "path", "===", "undefined", "||", "path", "===", "''", ")", "return", "scope", ";", "let", "groups", "=", "path", ".", "split", "(", "'.'", ")", ";", "let", "currentScope", "=", "scope", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "groups", ".", "length", ";", "i", "++", ")", "{", "currentScope", "=", "currentScope", "[", "groups", "[", "i", "]", "]", "||", "(", "currentScope", "[", "groups", "[", "i", "]", "]", "=", "{", "}", ")", ";", "}", "return", "currentScope", ";", "}" ]
Generates a nested namespace in the specified scope, as described by the dot- notated namespace path. @param {string} [path] - Namespace path with keywords separated by dots. @param {Object|window} [scope=window|{}] - Scope/object to create the nested namespace in. If browser environment is detected, this param will default to window. Otherwise it will be an empty object literal. @return {Object} The generated namespace. @alias module:requiem~dom.namespace
[ "Generates", "a", "nested", "namespace", "in", "the", "specified", "scope", "as", "described", "by", "the", "dot", "-", "notated", "namespace", "path", "." ]
c4182bfffc9841c6de5718f689ad3c2060511777
https://github.com/andrewscwei/requiem/blob/c4182bfffc9841c6de5718f689ad3c2060511777/src/dom/namespace.js#L23-L38
50,391
tolokoban/ToloFrameWork
lib/boilerplate.view.template.js
isSpecial
function isSpecial( obj, name ) { if ( !obj ) return false; if ( typeof obj[ 0 ] !== 'string' ) return false; if ( typeof name === 'string' ) { return obj[ 0 ].toLowerCase() === name; } return true; }
javascript
function isSpecial( obj, name ) { if ( !obj ) return false; if ( typeof obj[ 0 ] !== 'string' ) return false; if ( typeof name === 'string' ) { return obj[ 0 ].toLowerCase() === name; } return true; }
[ "function", "isSpecial", "(", "obj", ",", "name", ")", "{", "if", "(", "!", "obj", ")", "return", "false", ";", "if", "(", "typeof", "obj", "[", "0", "]", "!==", "'string'", ")", "return", "false", ";", "if", "(", "typeof", "name", "===", "'string'", ")", "{", "return", "obj", "[", "0", "]", ".", "toLowerCase", "(", ")", "===", "name", ";", "}", "return", "true", ";", "}" ]
An object is special of and only if it's attribute of key "0" is a string.
[ "An", "object", "is", "special", "of", "and", "only", "if", "it", "s", "attribute", "of", "key", "0", "is", "a", "string", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/lib/boilerplate.view.template.js#L557-L564
50,392
tolokoban/ToloFrameWork
lib/boilerplate.view.template.js
createSectionStructure
function createSectionStructure() { return { init: null, comments: [], attribs: { define: [], init: [] }, elements: { define: [], init: [] }, events: [], links: [], ons: [], statics: [] }; }
javascript
function createSectionStructure() { return { init: null, comments: [], attribs: { define: [], init: [] }, elements: { define: [], init: [] }, events: [], links: [], ons: [], statics: [] }; }
[ "function", "createSectionStructure", "(", ")", "{", "return", "{", "init", ":", "null", ",", "comments", ":", "[", "]", ",", "attribs", ":", "{", "define", ":", "[", "]", ",", "init", ":", "[", "]", "}", ",", "elements", ":", "{", "define", ":", "[", "]", ",", "init", ":", "[", "]", "}", ",", "events", ":", "[", "]", ",", "links", ":", "[", "]", ",", "ons", ":", "[", "]", ",", "statics", ":", "[", "]", "}", ";", "}" ]
Returns the initial content of Template.section. @returns {object} Initial content of Template.section.
[ "Returns", "the", "initial", "content", "of", "Template", ".", "section", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/lib/boilerplate.view.template.js#L595-L612
50,393
goblindegook/findup-node-modules
index.js
findPath
function findPath(path, directories) { var cwd = directories[0]; if (!cwd) { return null; } return findup(path, {cwd: cwd}) || findPath(path, slice.call(directories, 1)); }
javascript
function findPath(path, directories) { var cwd = directories[0]; if (!cwd) { return null; } return findup(path, {cwd: cwd}) || findPath(path, slice.call(directories, 1)); }
[ "function", "findPath", "(", "path", ",", "directories", ")", "{", "var", "cwd", "=", "directories", "[", "0", "]", ";", "if", "(", "!", "cwd", ")", "{", "return", "null", ";", "}", "return", "findup", "(", "path", ",", "{", "cwd", ":", "cwd", "}", ")", "||", "findPath", "(", "path", ",", "slice", ".", "call", "(", "directories", ",", "1", ")", ")", ";", "}" ]
Find the requested path inside a list of candidate directories. @param {String} path Path to locate. @param {Array} directories Array of directories. @return {String} Located path, or null if not found.
[ "Find", "the", "requested", "path", "inside", "a", "list", "of", "candidate", "directories", "." ]
9baecb55c615bd36d804226dc1568218ba059b11
https://github.com/goblindegook/findup-node-modules/blob/9baecb55c615bd36d804226dc1568218ba059b11/index.js#L14-L22
50,394
tgi-io/tgi-store-local
spec/html-runner.js
log
function log(txt) { var p = document.createElement("p"); p.style.margin = '2px'; p.style.padding = '1px'; p.style.backgroundColor = "#FFFFF0"; p.style.border = "solid"; p.style.borderWidth = "1px"; p.style.borderColor = "#7F7F8F"; p.style.lineHeight = "1.0"; p.appendChild(document.createTextNode(txt)); document.body.appendChild(p); }
javascript
function log(txt) { var p = document.createElement("p"); p.style.margin = '2px'; p.style.padding = '1px'; p.style.backgroundColor = "#FFFFF0"; p.style.border = "solid"; p.style.borderWidth = "1px"; p.style.borderColor = "#7F7F8F"; p.style.lineHeight = "1.0"; p.appendChild(document.createTextNode(txt)); document.body.appendChild(p); }
[ "function", "log", "(", "txt", ")", "{", "var", "p", "=", "document", ".", "createElement", "(", "\"p\"", ")", ";", "p", ".", "style", ".", "margin", "=", "'2px'", ";", "p", ".", "style", ".", "padding", "=", "'1px'", ";", "p", ".", "style", ".", "backgroundColor", "=", "\"#FFFFF0\"", ";", "p", ".", "style", ".", "border", "=", "\"solid\"", ";", "p", ".", "style", ".", "borderWidth", "=", "\"1px\"", ";", "p", ".", "style", ".", "borderColor", "=", "\"#7F7F8F\"", ";", "p", ".", "style", ".", "lineHeight", "=", "\"1.0\"", ";", "p", ".", "appendChild", "(", "document", ".", "createTextNode", "(", "txt", ")", ")", ";", "document", ".", "body", ".", "appendChild", "(", "p", ")", ";", "}" ]
DOM rendering functions
[ "DOM", "rendering", "functions" ]
e046eb06c1b2f9594988ecbad184d94176d267ae
https://github.com/tgi-io/tgi-store-local/blob/e046eb06c1b2f9594988ecbad184d94176d267ae/spec/html-runner.js#L33-L44
50,395
nbrownus/ppunit
lib/reporters/Dependencies.js
function (ppunit, writer) { Dependencies.super_.call(this, ppunit, writer) var self = this self.subGraphs = [] ppunit.on('start', function () { writer.write('digraph PPUnit {') self.printNodes() self.printSubGraphs() self.printDependencies() writer.write('}') }) }
javascript
function (ppunit, writer) { Dependencies.super_.call(this, ppunit, writer) var self = this self.subGraphs = [] ppunit.on('start', function () { writer.write('digraph PPUnit {') self.printNodes() self.printSubGraphs() self.printDependencies() writer.write('}') }) }
[ "function", "(", "ppunit", ",", "writer", ")", "{", "Dependencies", ".", "super_", ".", "call", "(", "this", ",", "ppunit", ",", "writer", ")", "var", "self", "=", "this", "self", ".", "subGraphs", "=", "[", "]", "ppunit", ".", "on", "(", "'start'", ",", "function", "(", ")", "{", "writer", ".", "write", "(", "'digraph PPUnit {'", ")", "self", ".", "printNodes", "(", ")", "self", ".", "printSubGraphs", "(", ")", "self", ".", "printDependencies", "(", ")", "writer", ".", "write", "(", "'}'", ")", "}", ")", "}" ]
Outputs graphviz dot notation of the test dependency graph @param {PPUnit} ppunit PPUnit instance @param {Object} writer An object that has a write method @param {function} writer.write A method that writes the output @constructor
[ "Outputs", "graphviz", "dot", "notation", "of", "the", "test", "dependency", "graph" ]
dcce602497d9548ce9085a8db115e65561dcc3de
https://github.com/nbrownus/ppunit/blob/dcce602497d9548ce9085a8db115e65561dcc3de/lib/reporters/Dependencies.js#L14-L27
50,396
icelab/attache-upload.js
lib/index.js
abortXHRRequest
function abortXHRRequest(uid, fn) { if (reqs.hasOwnProperty(uid)) { if (!reqs[uid]) return; if (fn) { fn(); } else { reqs[uid].abort(); } delete reqs[uid]; return reqs; } }
javascript
function abortXHRRequest(uid, fn) { if (reqs.hasOwnProperty(uid)) { if (!reqs[uid]) return; if (fn) { fn(); } else { reqs[uid].abort(); } delete reqs[uid]; return reqs; } }
[ "function", "abortXHRRequest", "(", "uid", ",", "fn", ")", "{", "if", "(", "reqs", ".", "hasOwnProperty", "(", "uid", ")", ")", "{", "if", "(", "!", "reqs", "[", "uid", "]", ")", "return", ";", "if", "(", "fn", ")", "{", "fn", "(", ")", ";", "}", "else", "{", "reqs", "[", "uid", "]", ".", "abort", "(", ")", ";", "}", "delete", "reqs", "[", "uid", "]", ";", "return", "reqs", ";", "}", "}" ]
abortXHRRequest Abort a XHR request by 'uid' @param {String} uid @param {Function} optional function @return {Object}
[ "abortXHRRequest", "Abort", "a", "XHR", "request", "by", "uid" ]
ff40a9d8caa45c53e147c810dc7449de685fcaf4
https://github.com/icelab/attache-upload.js/blob/ff40a9d8caa45c53e147c810dc7449de685fcaf4/lib/index.js#L62-L74
50,397
icelab/attache-upload.js
lib/index.js
customError
function customError(name, error) { return { error: error, message: error.message, name: name }; }
javascript
function customError(name, error) { return { error: error, message: error.message, name: name }; }
[ "function", "customError", "(", "name", ",", "error", ")", "{", "return", "{", "error", ":", "error", ",", "message", ":", "error", ".", "message", ",", "name", ":", "name", "}", ";", "}" ]
customError return an object forming a custom error message @param {String} name @param {Object} error @return {Object}
[ "customError", "return", "an", "object", "forming", "a", "custom", "error", "message" ]
ff40a9d8caa45c53e147c810dc7449de685fcaf4
https://github.com/icelab/attache-upload.js/blob/ff40a9d8caa45c53e147c810dc7449de685fcaf4/lib/index.js#L84-L90
50,398
icelab/attache-upload.js
lib/index.js
responseStatus
function responseStatus(res) { if (res.status >= 200 && res.status < 300) { return res; } else { var error = new Error(res.statusText); error.response = res; throw customError('responseStatus', error); } }
javascript
function responseStatus(res) { if (res.status >= 200 && res.status < 300) { return res; } else { var error = new Error(res.statusText); error.response = res; throw customError('responseStatus', error); } }
[ "function", "responseStatus", "(", "res", ")", "{", "if", "(", "res", ".", "status", ">=", "200", "&&", "res", ".", "status", "<", "300", ")", "{", "return", "res", ";", "}", "else", "{", "var", "error", "=", "new", "Error", "(", "res", ".", "statusText", ")", ";", "error", ".", "response", "=", "res", ";", "throw", "customError", "(", "'responseStatus'", ",", "error", ")", ";", "}", "}" ]
responseStatus take a response and check the response `status` property if between 200-300 return the response object else throw a custom error @param {Object} res @return {Object}
[ "responseStatus", "take", "a", "response", "and", "check", "the", "response", "status", "property", "if", "between", "200", "-", "300", "return", "the", "response", "object", "else", "throw", "a", "custom", "error" ]
ff40a9d8caa45c53e147c810dc7449de685fcaf4
https://github.com/icelab/attache-upload.js/blob/ff40a9d8caa45c53e147c810dc7449de685fcaf4/lib/index.js#L101-L109
50,399
icelab/attache-upload.js
lib/index.js
buildUploadURL
function buildUploadURL(url, uuid, expiration, hmac, filename) { return url + '?uuid=' + uuid + '&expiration=' + expiration + '&hmac=' + hmac + '&file=' + filename; }
javascript
function buildUploadURL(url, uuid, expiration, hmac, filename) { return url + '?uuid=' + uuid + '&expiration=' + expiration + '&hmac=' + hmac + '&file=' + filename; }
[ "function", "buildUploadURL", "(", "url", ",", "uuid", ",", "expiration", ",", "hmac", ",", "filename", ")", "{", "return", "url", "+", "'?uuid='", "+", "uuid", "+", "'&expiration='", "+", "expiration", "+", "'&hmac='", "+", "hmac", "+", "'&file='", "+", "filename", ";", "}" ]
buildUploadURL Construct a string using params @param {String} url @param {String} uuid @param {String} expiration @param {String} hmac @param {String} filename @return {String}
[ "buildUploadURL", "Construct", "a", "string", "using", "params" ]
ff40a9d8caa45c53e147c810dc7449de685fcaf4
https://github.com/icelab/attache-upload.js/blob/ff40a9d8caa45c53e147c810dc7449de685fcaf4/lib/index.js#L133-L135