id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
12,100
expressjs/csurf
index.js
setCookie
function setCookie (res, name, val, options) { var data = Cookie.serialize(name, val, options) var prev = res.getHeader('set-cookie') || [] var header = Array.isArray(prev) ? prev.concat(data) : [prev, data] res.setHeader('set-cookie', header) }
javascript
function setCookie (res, name, val, options) { var data = Cookie.serialize(name, val, options) var prev = res.getHeader('set-cookie') || [] var header = Array.isArray(prev) ? prev.concat(data) : [prev, data] res.setHeader('set-cookie', header) }
[ "function", "setCookie", "(", "res", ",", "name", ",", "val", ",", "options", ")", "{", "var", "data", "=", "Cookie", ".", "serialize", "(", "name", ",", "val", ",", "options", ")", "var", "prev", "=", "res", ".", "getHeader", "(", "'set-cookie'", ")", "||", "[", "]", "var", "header", "=", "Array", ".", "isArray", "(", "prev", ")", "?", "prev", ".", "concat", "(", "data", ")", ":", "[", "prev", ",", "data", "]", "res", ".", "setHeader", "(", "'set-cookie'", ",", "header", ")", "}" ]
Set a cookie on the HTTP response. @param {OutgoingMessage} res @param {string} name @param {string} val @param {Object} [options] @api private
[ "Set", "a", "cookie", "on", "the", "HTTP", "response", "." ]
248112a42f36fc9a84a71b0f5d383a1e03813f54
https://github.com/expressjs/csurf/blob/248112a42f36fc9a84a71b0f5d383a1e03813f54/index.js#L245-L253
12,101
expressjs/csurf
index.js
setSecret
function setSecret (req, res, sessionKey, val, cookie) { if (cookie) { // set secret on cookie var value = val if (cookie.signed) { value = 's:' + sign(val, req.secret) } setCookie(res, cookie.key, value, cookie) } else { // set secret on session req[sessionKey].csrfSecret = val } }
javascript
function setSecret (req, res, sessionKey, val, cookie) { if (cookie) { // set secret on cookie var value = val if (cookie.signed) { value = 's:' + sign(val, req.secret) } setCookie(res, cookie.key, value, cookie) } else { // set secret on session req[sessionKey].csrfSecret = val } }
[ "function", "setSecret", "(", "req", ",", "res", ",", "sessionKey", ",", "val", ",", "cookie", ")", "{", "if", "(", "cookie", ")", "{", "// set secret on cookie", "var", "value", "=", "val", "if", "(", "cookie", ".", "signed", ")", "{", "value", "=", "'s:'", "+", "sign", "(", "val", ",", "req", ".", "secret", ")", "}", "setCookie", "(", "res", ",", "cookie", ".", "key", ",", "value", ",", "cookie", ")", "}", "else", "{", "// set secret on session", "req", "[", "sessionKey", "]", ".", "csrfSecret", "=", "val", "}", "}" ]
Set the token secret on the request. @param {IncomingMessage} req @param {OutgoingMessage} res @param {string} sessionKey @param {string} val @param {Object} [cookie] @api private
[ "Set", "the", "token", "secret", "on", "the", "request", "." ]
248112a42f36fc9a84a71b0f5d383a1e03813f54
https://github.com/expressjs/csurf/blob/248112a42f36fc9a84a71b0f5d383a1e03813f54/index.js#L266-L280
12,102
expressjs/csurf
index.js
verifyConfiguration
function verifyConfiguration (req, sessionKey, cookie) { if (!getSecretBag(req, sessionKey, cookie)) { return false } if (cookie && cookie.signed && !req.secret) { return false } return true }
javascript
function verifyConfiguration (req, sessionKey, cookie) { if (!getSecretBag(req, sessionKey, cookie)) { return false } if (cookie && cookie.signed && !req.secret) { return false } return true }
[ "function", "verifyConfiguration", "(", "req", ",", "sessionKey", ",", "cookie", ")", "{", "if", "(", "!", "getSecretBag", "(", "req", ",", "sessionKey", ",", "cookie", ")", ")", "{", "return", "false", "}", "if", "(", "cookie", "&&", "cookie", ".", "signed", "&&", "!", "req", ".", "secret", ")", "{", "return", "false", "}", "return", "true", "}" ]
Verify the configuration against the request. @private
[ "Verify", "the", "configuration", "against", "the", "request", "." ]
248112a42f36fc9a84a71b0f5d383a1e03813f54
https://github.com/expressjs/csurf/blob/248112a42f36fc9a84a71b0f5d383a1e03813f54/index.js#L287-L297
12,103
alinz/react-native-webview-bridge
scripts/webviewbridge.js
function (message) { receiveQueue.push(message); //reason I need this setTmeout is to return this function as fast as //possible to release the native side thread. setTimeout(function () { var message = receiveQueue.pop(); callFunc(WebViewBridge.onMessage, message); }, 15); //this magic number is just a random small value. I don't like 0. }
javascript
function (message) { receiveQueue.push(message); //reason I need this setTmeout is to return this function as fast as //possible to release the native side thread. setTimeout(function () { var message = receiveQueue.pop(); callFunc(WebViewBridge.onMessage, message); }, 15); //this magic number is just a random small value. I don't like 0. }
[ "function", "(", "message", ")", "{", "receiveQueue", ".", "push", "(", "message", ")", ";", "//reason I need this setTmeout is to return this function as fast as", "//possible to release the native side thread.", "setTimeout", "(", "function", "(", ")", "{", "var", "message", "=", "receiveQueue", ".", "pop", "(", ")", ";", "callFunc", "(", "WebViewBridge", ".", "onMessage", ",", "message", ")", ";", "}", ",", "15", ")", ";", "//this magic number is just a random small value. I don't like 0.", "}" ]
this function will be called by native side to push a new message to webview.
[ "this", "function", "will", "be", "called", "by", "native", "side", "to", "push", "a", "new", "message", "to", "webview", "." ]
bf0d44714385eaf9688c3e5e14bd6769c44bb00f
https://github.com/alinz/react-native-webview-bridge/blob/bf0d44714385eaf9688c3e5e14bd6769c44bb00f/scripts/webviewbridge.js#L30-L38
12,104
alinz/react-native-webview-bridge
scripts/webviewbridge.js
function (message) { if ('string' !== typeof message) { callFunc(WebViewBridge.onError, "message is type '" + typeof message + "', and it needs to be string"); return; } //we queue the messages to make sure that native can collects all of them in one shot. sendQueue.push(message); //signal the objective-c that there is a message in the queue signalNative(); }
javascript
function (message) { if ('string' !== typeof message) { callFunc(WebViewBridge.onError, "message is type '" + typeof message + "', and it needs to be string"); return; } //we queue the messages to make sure that native can collects all of them in one shot. sendQueue.push(message); //signal the objective-c that there is a message in the queue signalNative(); }
[ "function", "(", "message", ")", "{", "if", "(", "'string'", "!==", "typeof", "message", ")", "{", "callFunc", "(", "WebViewBridge", ".", "onError", ",", "\"message is type '\"", "+", "typeof", "message", "+", "\"', and it needs to be string\"", ")", ";", "return", ";", "}", "//we queue the messages to make sure that native can collects all of them in one shot.", "sendQueue", ".", "push", "(", "message", ")", ";", "//signal the objective-c that there is a message in the queue", "signalNative", "(", ")", ";", "}" ]
make sure message is string. because only string can be sent to native, if you don't pass it as string, onError function will be called.
[ "make", "sure", "message", "is", "string", ".", "because", "only", "string", "can", "be", "sent", "to", "native", "if", "you", "don", "t", "pass", "it", "as", "string", "onError", "function", "will", "be", "called", "." ]
bf0d44714385eaf9688c3e5e14bd6769c44bb00f
https://github.com/alinz/react-native-webview-bridge/blob/bf0d44714385eaf9688c3e5e14bd6769c44bb00f/scripts/webviewbridge.js#L52-L62
12,105
zeppelinos/zos
packages/docs/scripts/gen-docs.js
main
function main(argv) { try { shell.mkdir('-p', 'docs') shell.pushd('-q', 'docs') handleErrorCode(shell.exec('npm init -y')) handleErrorCode(shell.exec('npm install docusaurus-init')) handleErrorCode(shell.exec('docusaurus-init')) shell.mv('docs-examples-from-docusaurus/', 'docs') shell.mv('website/blog-examples-from-docusaurus/', 'website/blog') shell.pushd('-q', 'website') handleErrorCode(shell.exec('npm run examples versions')) shell.popd('-q') shell.popd('-q') } catch (err) { shell.rm('-rf', 'docs') throw err } }
javascript
function main(argv) { try { shell.mkdir('-p', 'docs') shell.pushd('-q', 'docs') handleErrorCode(shell.exec('npm init -y')) handleErrorCode(shell.exec('npm install docusaurus-init')) handleErrorCode(shell.exec('docusaurus-init')) shell.mv('docs-examples-from-docusaurus/', 'docs') shell.mv('website/blog-examples-from-docusaurus/', 'website/blog') shell.pushd('-q', 'website') handleErrorCode(shell.exec('npm run examples versions')) shell.popd('-q') shell.popd('-q') } catch (err) { shell.rm('-rf', 'docs') throw err } }
[ "function", "main", "(", "argv", ")", "{", "try", "{", "shell", ".", "mkdir", "(", "'-p'", ",", "'docs'", ")", "shell", ".", "pushd", "(", "'-q'", ",", "'docs'", ")", "handleErrorCode", "(", "shell", ".", "exec", "(", "'npm init -y'", ")", ")", "handleErrorCode", "(", "shell", ".", "exec", "(", "'npm install docusaurus-init'", ")", ")", "handleErrorCode", "(", "shell", ".", "exec", "(", "'docusaurus-init'", ")", ")", "shell", ".", "mv", "(", "'docs-examples-from-docusaurus/'", ",", "'docs'", ")", "shell", ".", "mv", "(", "'website/blog-examples-from-docusaurus/'", ",", "'website/blog'", ")", "shell", ".", "pushd", "(", "'-q'", ",", "'website'", ")", "handleErrorCode", "(", "shell", ".", "exec", "(", "'npm run examples versions'", ")", ")", "shell", ".", "popd", "(", "'-q'", ")", "shell", ".", "popd", "(", "'-q'", ")", "}", "catch", "(", "err", ")", "{", "shell", ".", "rm", "(", "'-rf'", ",", "'docs'", ")", "throw", "err", "}", "}" ]
Entry point.
[ "Entry", "point", "." ]
751ef8d43f65438e25e0d9ba93836f118e4dce0c
https://github.com/zeppelinos/zos/blob/751ef8d43f65438e25e0d9ba93836f118e4dce0c/packages/docs/scripts/gen-docs.js#L9-L27
12,106
silvestreh/onScreen
lib/methods/attach.js
attach
function attach() { const container = this.options.container; if (container instanceof HTMLElement) { const style = window.getComputedStyle(container); if (style.position === 'static') { container.style.position = 'relative'; } } container.addEventListener('scroll', this._scroll); window.addEventListener('resize', this._scroll); this._scroll(); this.attached = true; }
javascript
function attach() { const container = this.options.container; if (container instanceof HTMLElement) { const style = window.getComputedStyle(container); if (style.position === 'static') { container.style.position = 'relative'; } } container.addEventListener('scroll', this._scroll); window.addEventListener('resize', this._scroll); this._scroll(); this.attached = true; }
[ "function", "attach", "(", ")", "{", "const", "container", "=", "this", ".", "options", ".", "container", ";", "if", "(", "container", "instanceof", "HTMLElement", ")", "{", "const", "style", "=", "window", ".", "getComputedStyle", "(", "container", ")", ";", "if", "(", "style", ".", "position", "===", "'static'", ")", "{", "container", ".", "style", ".", "position", "=", "'relative'", ";", "}", "}", "container", ".", "addEventListener", "(", "'scroll'", ",", "this", ".", "_scroll", ")", ";", "window", ".", "addEventListener", "(", "'resize'", ",", "this", ".", "_scroll", ")", ";", "this", ".", "_scroll", "(", ")", ";", "this", ".", "attached", "=", "true", ";", "}" ]
Attaches the scroll event handler @return {void}
[ "Attaches", "the", "scroll", "event", "handler" ]
01f8549587738fe1c50c5c95a2d17d62a3b5c9d7
https://github.com/silvestreh/onScreen/blob/01f8549587738fe1c50c5c95a2d17d62a3b5c9d7/lib/methods/attach.js#L6-L21
12,107
silvestreh/onScreen
lib/methods/off.js
off
function off(event, selector, handler) { const enterCallbacks = Object.keys(this.trackedElements[selector].enter || {}); const leaveCallbacks = Object.keys(this.trackedElements[selector].leave || {}); if ({}.hasOwnProperty.call(this.trackedElements, selector)) { if (handler) { if (this.trackedElements[selector][event]) { const callbackName = (typeof handler === 'function') ? handler.name : handler; delete this.trackedElements[selector][event][callbackName]; } } else { delete this.trackedElements[selector][event]; } } if (!enterCallbacks.length && !leaveCallbacks.length) { delete this.trackedElements[selector]; } }
javascript
function off(event, selector, handler) { const enterCallbacks = Object.keys(this.trackedElements[selector].enter || {}); const leaveCallbacks = Object.keys(this.trackedElements[selector].leave || {}); if ({}.hasOwnProperty.call(this.trackedElements, selector)) { if (handler) { if (this.trackedElements[selector][event]) { const callbackName = (typeof handler === 'function') ? handler.name : handler; delete this.trackedElements[selector][event][callbackName]; } } else { delete this.trackedElements[selector][event]; } } if (!enterCallbacks.length && !leaveCallbacks.length) { delete this.trackedElements[selector]; } }
[ "function", "off", "(", "event", ",", "selector", ",", "handler", ")", "{", "const", "enterCallbacks", "=", "Object", ".", "keys", "(", "this", ".", "trackedElements", "[", "selector", "]", ".", "enter", "||", "{", "}", ")", ";", "const", "leaveCallbacks", "=", "Object", ".", "keys", "(", "this", ".", "trackedElements", "[", "selector", "]", ".", "leave", "||", "{", "}", ")", ";", "if", "(", "{", "}", ".", "hasOwnProperty", ".", "call", "(", "this", ".", "trackedElements", ",", "selector", ")", ")", "{", "if", "(", "handler", ")", "{", "if", "(", "this", ".", "trackedElements", "[", "selector", "]", "[", "event", "]", ")", "{", "const", "callbackName", "=", "(", "typeof", "handler", "===", "'function'", ")", "?", "handler", ".", "name", ":", "handler", ";", "delete", "this", ".", "trackedElements", "[", "selector", "]", "[", "event", "]", "[", "callbackName", "]", ";", "}", "}", "else", "{", "delete", "this", ".", "trackedElements", "[", "selector", "]", "[", "event", "]", ";", "}", "}", "if", "(", "!", "enterCallbacks", ".", "length", "&&", "!", "leaveCallbacks", ".", "length", ")", "{", "delete", "this", ".", "trackedElements", "[", "selector", "]", ";", "}", "}" ]
Stops tracking elements matching a CSS selector. If a selector has no callbacks it gets removed. @param {string} event The event you want to stop tracking (enter or leave) @param {string} selector The CSS selector you want to stop tracking @return {void}
[ "Stops", "tracking", "elements", "matching", "a", "CSS", "selector", ".", "If", "a", "selector", "has", "no", "callbacks", "it", "gets", "removed", "." ]
01f8549587738fe1c50c5c95a2d17d62a3b5c9d7
https://github.com/silvestreh/onScreen/blob/01f8549587738fe1c50c5c95a2d17d62a3b5c9d7/lib/methods/off.js#L9-L27
12,108
silvestreh/onScreen
lib/methods/destroy.js
destroy
function destroy() { this.options.container.removeEventListener('scroll', this._scroll); window.removeEventListener('resize', this._scroll); this.attached = false; }
javascript
function destroy() { this.options.container.removeEventListener('scroll', this._scroll); window.removeEventListener('resize', this._scroll); this.attached = false; }
[ "function", "destroy", "(", ")", "{", "this", ".", "options", ".", "container", ".", "removeEventListener", "(", "'scroll'", ",", "this", ".", "_scroll", ")", ";", "window", ".", "removeEventListener", "(", "'resize'", ",", "this", ".", "_scroll", ")", ";", "this", ".", "attached", "=", "false", ";", "}" ]
Removes the scroll event handler @return {void}
[ "Removes", "the", "scroll", "event", "handler" ]
01f8549587738fe1c50c5c95a2d17d62a3b5c9d7
https://github.com/silvestreh/onScreen/blob/01f8549587738fe1c50c5c95a2d17d62a3b5c9d7/lib/methods/destroy.js#L6-L10
12,109
silvestreh/onScreen
lib/methods/on.js
on
function on(event, selector, callback) { const allowed = ['enter', 'leave']; if (!event) throw new Error('No event given. Choose either enter or leave'); if (!selector) throw new Error('No selector to track'); if (allowed.indexOf(event) < 0) throw new Error(`${event} event is not supported`); if (!{}.hasOwnProperty.call(this.trackedElements, selector)) { this.trackedElements[selector] = {}; } this.trackedElements[selector].nodes = []; for (let i = 0, elems = document.querySelectorAll(selector); i < elems.length; i++) { const item = { isVisible: false, wasVisible: false, node: elems[i] }; this.trackedElements[selector].nodes.push(item); } if (typeof callback === 'function') { if (!this.trackedElements[selector][event]) { this.trackedElements[selector][event] = {}; } this.trackedElements[selector][event][(callback.name || 'anonymous')] = callback; } }
javascript
function on(event, selector, callback) { const allowed = ['enter', 'leave']; if (!event) throw new Error('No event given. Choose either enter or leave'); if (!selector) throw new Error('No selector to track'); if (allowed.indexOf(event) < 0) throw new Error(`${event} event is not supported`); if (!{}.hasOwnProperty.call(this.trackedElements, selector)) { this.trackedElements[selector] = {}; } this.trackedElements[selector].nodes = []; for (let i = 0, elems = document.querySelectorAll(selector); i < elems.length; i++) { const item = { isVisible: false, wasVisible: false, node: elems[i] }; this.trackedElements[selector].nodes.push(item); } if (typeof callback === 'function') { if (!this.trackedElements[selector][event]) { this.trackedElements[selector][event] = {}; } this.trackedElements[selector][event][(callback.name || 'anonymous')] = callback; } }
[ "function", "on", "(", "event", ",", "selector", ",", "callback", ")", "{", "const", "allowed", "=", "[", "'enter'", ",", "'leave'", "]", ";", "if", "(", "!", "event", ")", "throw", "new", "Error", "(", "'No event given. Choose either enter or leave'", ")", ";", "if", "(", "!", "selector", ")", "throw", "new", "Error", "(", "'No selector to track'", ")", ";", "if", "(", "allowed", ".", "indexOf", "(", "event", ")", "<", "0", ")", "throw", "new", "Error", "(", "`", "${", "event", "}", "`", ")", ";", "if", "(", "!", "{", "}", ".", "hasOwnProperty", ".", "call", "(", "this", ".", "trackedElements", ",", "selector", ")", ")", "{", "this", ".", "trackedElements", "[", "selector", "]", "=", "{", "}", ";", "}", "this", ".", "trackedElements", "[", "selector", "]", ".", "nodes", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ",", "elems", "=", "document", ".", "querySelectorAll", "(", "selector", ")", ";", "i", "<", "elems", ".", "length", ";", "i", "++", ")", "{", "const", "item", "=", "{", "isVisible", ":", "false", ",", "wasVisible", ":", "false", ",", "node", ":", "elems", "[", "i", "]", "}", ";", "this", ".", "trackedElements", "[", "selector", "]", ".", "nodes", ".", "push", "(", "item", ")", ";", "}", "if", "(", "typeof", "callback", "===", "'function'", ")", "{", "if", "(", "!", "this", ".", "trackedElements", "[", "selector", "]", "[", "event", "]", ")", "{", "this", ".", "trackedElements", "[", "selector", "]", "[", "event", "]", "=", "{", "}", ";", "}", "this", ".", "trackedElements", "[", "selector", "]", "[", "event", "]", "[", "(", "callback", ".", "name", "||", "'anonymous'", ")", "]", "=", "callback", ";", "}", "}" ]
Starts tracking elements matching a CSS selector @param {string} event The event you want to track (enter or leave) @param {string} selector The element you want to track @param {function} callback The callback function to handle the event @return {void}
[ "Starts", "tracking", "elements", "matching", "a", "CSS", "selector" ]
01f8549587738fe1c50c5c95a2d17d62a3b5c9d7
https://github.com/silvestreh/onScreen/blob/01f8549587738fe1c50c5c95a2d17d62a3b5c9d7/lib/methods/on.js#L9-L39
12,110
silvestreh/onScreen
lib/methods/debounced-scroll.js
debouncedScroll
function debouncedScroll() { let timeout; return () => { clearTimeout(timeout); timeout = setTimeout(() => { scrollHandler(this.trackedElements, this.options); }, this.options.debounce); }; }
javascript
function debouncedScroll() { let timeout; return () => { clearTimeout(timeout); timeout = setTimeout(() => { scrollHandler(this.trackedElements, this.options); }, this.options.debounce); }; }
[ "function", "debouncedScroll", "(", ")", "{", "let", "timeout", ";", "return", "(", ")", "=>", "{", "clearTimeout", "(", "timeout", ")", ";", "timeout", "=", "setTimeout", "(", "(", ")", "=>", "{", "scrollHandler", "(", "this", ".", "trackedElements", ",", "this", ".", "options", ")", ";", "}", ",", "this", ".", "options", ".", "debounce", ")", ";", "}", ";", "}" ]
Debounces the scroll event to avoid performance issues @return {void}
[ "Debounces", "the", "scroll", "event", "to", "avoid", "performance", "issues" ]
01f8549587738fe1c50c5c95a2d17d62a3b5c9d7
https://github.com/silvestreh/onScreen/blob/01f8549587738fe1c50c5c95a2d17d62a3b5c9d7/lib/methods/debounced-scroll.js#L8-L18
12,111
silvestreh/onScreen
lib/helpers/in-container.js
inContainer
function inContainer(el, options = { tolerance: 0, container: '' }) { if (!el) { throw new Error('You should specify the element you want to test'); } if (typeof el === 'string') { el = document.querySelector(el); } if (typeof options === 'string') { options = { tolerance: 0, container: document.querySelector(options) }; } if (typeof options.container === 'string') { options.container = document.querySelector(options.container); } if (options instanceof HTMLElement) { options = { tolerance: 0, container: options }; } if (!options.container) { throw new Error('You should specify a container element'); } const containerRect = options.container.getBoundingClientRect(); return ( // // Check bottom boundary (el.offsetTop + el.clientHeight) - options.tolerance > options.container.scrollTop && // Check right boundary (el.offsetLeft + el.clientWidth) - options.tolerance > options.container.scrollLeft && // Check left boundary el.offsetLeft + options.tolerance < containerRect.width + options.container.scrollLeft && // // Check top boundary el.offsetTop + options.tolerance < containerRect.height + options.container.scrollTop ); }
javascript
function inContainer(el, options = { tolerance: 0, container: '' }) { if (!el) { throw new Error('You should specify the element you want to test'); } if (typeof el === 'string') { el = document.querySelector(el); } if (typeof options === 'string') { options = { tolerance: 0, container: document.querySelector(options) }; } if (typeof options.container === 'string') { options.container = document.querySelector(options.container); } if (options instanceof HTMLElement) { options = { tolerance: 0, container: options }; } if (!options.container) { throw new Error('You should specify a container element'); } const containerRect = options.container.getBoundingClientRect(); return ( // // Check bottom boundary (el.offsetTop + el.clientHeight) - options.tolerance > options.container.scrollTop && // Check right boundary (el.offsetLeft + el.clientWidth) - options.tolerance > options.container.scrollLeft && // Check left boundary el.offsetLeft + options.tolerance < containerRect.width + options.container.scrollLeft && // // Check top boundary el.offsetTop + options.tolerance < containerRect.height + options.container.scrollTop ); }
[ "function", "inContainer", "(", "el", ",", "options", "=", "{", "tolerance", ":", "0", ",", "container", ":", "''", "}", ")", "{", "if", "(", "!", "el", ")", "{", "throw", "new", "Error", "(", "'You should specify the element you want to test'", ")", ";", "}", "if", "(", "typeof", "el", "===", "'string'", ")", "{", "el", "=", "document", ".", "querySelector", "(", "el", ")", ";", "}", "if", "(", "typeof", "options", "===", "'string'", ")", "{", "options", "=", "{", "tolerance", ":", "0", ",", "container", ":", "document", ".", "querySelector", "(", "options", ")", "}", ";", "}", "if", "(", "typeof", "options", ".", "container", "===", "'string'", ")", "{", "options", ".", "container", "=", "document", ".", "querySelector", "(", "options", ".", "container", ")", ";", "}", "if", "(", "options", "instanceof", "HTMLElement", ")", "{", "options", "=", "{", "tolerance", ":", "0", ",", "container", ":", "options", "}", ";", "}", "if", "(", "!", "options", ".", "container", ")", "{", "throw", "new", "Error", "(", "'You should specify a container element'", ")", ";", "}", "const", "containerRect", "=", "options", ".", "container", ".", "getBoundingClientRect", "(", ")", ";", "return", "(", "// // Check bottom boundary", "(", "el", ".", "offsetTop", "+", "el", ".", "clientHeight", ")", "-", "options", ".", "tolerance", ">", "options", ".", "container", ".", "scrollTop", "&&", "// Check right boundary", "(", "el", ".", "offsetLeft", "+", "el", ".", "clientWidth", ")", "-", "options", ".", "tolerance", ">", "options", ".", "container", ".", "scrollLeft", "&&", "// Check left boundary", "el", ".", "offsetLeft", "+", "options", ".", "tolerance", "<", "containerRect", ".", "width", "+", "options", ".", "container", ".", "scrollLeft", "&&", "// // Check top boundary", "el", ".", "offsetTop", "+", "options", ".", "tolerance", "<", "containerRect", ".", "height", "+", "options", ".", "container", ".", "scrollTop", ")", ";", "}" ]
Checks an element's position in respect to a HTMLElement and determines wether it's within its boundaries. @param {node} element The DOM node you want to check @return {boolean} A boolean value that indicates wether is on or off the container.
[ "Checks", "an", "element", "s", "position", "in", "respect", "to", "a", "HTMLElement", "and", "determines", "wether", "it", "s", "within", "its", "boundaries", "." ]
01f8549587738fe1c50c5c95a2d17d62a3b5c9d7
https://github.com/silvestreh/onScreen/blob/01f8549587738fe1c50c5c95a2d17d62a3b5c9d7/lib/helpers/in-container.js#L8-L54
12,112
silvestreh/onScreen
lib/helpers/observe-dom.js
observeDOM
function observeDOM(obj, callback) { const MutationObserver = window.MutationObserver || window.WebKitMutationObserver; /* istanbul ignore else */ if (MutationObserver) { const obs = new MutationObserver(callback); obs.observe(obj, { childList: true, subtree: true }); } else { obj.addEventListener('DOMNodeInserted', callback, false); obj.addEventListener('DOMNodeRemoved', callback, false); } }
javascript
function observeDOM(obj, callback) { const MutationObserver = window.MutationObserver || window.WebKitMutationObserver; /* istanbul ignore else */ if (MutationObserver) { const obs = new MutationObserver(callback); obs.observe(obj, { childList: true, subtree: true }); } else { obj.addEventListener('DOMNodeInserted', callback, false); obj.addEventListener('DOMNodeRemoved', callback, false); } }
[ "function", "observeDOM", "(", "obj", ",", "callback", ")", "{", "const", "MutationObserver", "=", "window", ".", "MutationObserver", "||", "window", ".", "WebKitMutationObserver", ";", "/* istanbul ignore else */", "if", "(", "MutationObserver", ")", "{", "const", "obs", "=", "new", "MutationObserver", "(", "callback", ")", ";", "obs", ".", "observe", "(", "obj", ",", "{", "childList", ":", "true", ",", "subtree", ":", "true", "}", ")", ";", "}", "else", "{", "obj", ".", "addEventListener", "(", "'DOMNodeInserted'", ",", "callback", ",", "false", ")", ";", "obj", ".", "addEventListener", "(", "'DOMNodeRemoved'", ",", "callback", ",", "false", ")", ";", "}", "}" ]
Observes DOM mutations and runs a callback function when detecting one. @param {node} obj The DOM node you want to observe @param {function} callback The callback function you want to call @return {void}
[ "Observes", "DOM", "mutations", "and", "runs", "a", "callback", "function", "when", "detecting", "one", "." ]
01f8549587738fe1c50c5c95a2d17d62a3b5c9d7
https://github.com/silvestreh/onScreen/blob/01f8549587738fe1c50c5c95a2d17d62a3b5c9d7/lib/helpers/observe-dom.js#L9-L24
12,113
silvestreh/onScreen
lib/index.js
OnScreen
function OnScreen(options = { tolerance: 0, debounce: 100, container: window }) { this.options = {}; this.trackedElements = {}; Object.defineProperties(this.options, { container: { configurable: false, enumerable: false, get() { let container; if (typeof options.container === 'string') { container = document.querySelector(options.container); } else if (options.container instanceof HTMLElement) { container = options.container; } return container || window; }, set(value) { options.container = value; } }, debounce: { get() { return parseInt(options.debounce, 10) || 100; }, set(value) { options.debounce = value; } }, tolerance: { get() { return parseInt(options.tolerance, 10) || 0; }, set(value) { options.tolerance = value; } } }); Object.defineProperty(this, '_scroll', { enumerable: false, configurable: false, writable: false, value: this._debouncedScroll.call(this) }); observeDOM(document.querySelector('body'), () => { Object.keys(this.trackedElements).forEach((element) => { this.on('enter', element); this.on('leave', element); }); }); this.attach(); }
javascript
function OnScreen(options = { tolerance: 0, debounce: 100, container: window }) { this.options = {}; this.trackedElements = {}; Object.defineProperties(this.options, { container: { configurable: false, enumerable: false, get() { let container; if (typeof options.container === 'string') { container = document.querySelector(options.container); } else if (options.container instanceof HTMLElement) { container = options.container; } return container || window; }, set(value) { options.container = value; } }, debounce: { get() { return parseInt(options.debounce, 10) || 100; }, set(value) { options.debounce = value; } }, tolerance: { get() { return parseInt(options.tolerance, 10) || 0; }, set(value) { options.tolerance = value; } } }); Object.defineProperty(this, '_scroll', { enumerable: false, configurable: false, writable: false, value: this._debouncedScroll.call(this) }); observeDOM(document.querySelector('body'), () => { Object.keys(this.trackedElements).forEach((element) => { this.on('enter', element); this.on('leave', element); }); }); this.attach(); }
[ "function", "OnScreen", "(", "options", "=", "{", "tolerance", ":", "0", ",", "debounce", ":", "100", ",", "container", ":", "window", "}", ")", "{", "this", ".", "options", "=", "{", "}", ";", "this", ".", "trackedElements", "=", "{", "}", ";", "Object", ".", "defineProperties", "(", "this", ".", "options", ",", "{", "container", ":", "{", "configurable", ":", "false", ",", "enumerable", ":", "false", ",", "get", "(", ")", "{", "let", "container", ";", "if", "(", "typeof", "options", ".", "container", "===", "'string'", ")", "{", "container", "=", "document", ".", "querySelector", "(", "options", ".", "container", ")", ";", "}", "else", "if", "(", "options", ".", "container", "instanceof", "HTMLElement", ")", "{", "container", "=", "options", ".", "container", ";", "}", "return", "container", "||", "window", ";", "}", ",", "set", "(", "value", ")", "{", "options", ".", "container", "=", "value", ";", "}", "}", ",", "debounce", ":", "{", "get", "(", ")", "{", "return", "parseInt", "(", "options", ".", "debounce", ",", "10", ")", "||", "100", ";", "}", ",", "set", "(", "value", ")", "{", "options", ".", "debounce", "=", "value", ";", "}", "}", ",", "tolerance", ":", "{", "get", "(", ")", "{", "return", "parseInt", "(", "options", ".", "tolerance", ",", "10", ")", "||", "0", ";", "}", ",", "set", "(", "value", ")", "{", "options", ".", "tolerance", "=", "value", ";", "}", "}", "}", ")", ";", "Object", ".", "defineProperty", "(", "this", ",", "'_scroll'", ",", "{", "enumerable", ":", "false", ",", "configurable", ":", "false", ",", "writable", ":", "false", ",", "value", ":", "this", ".", "_debouncedScroll", ".", "call", "(", "this", ")", "}", ")", ";", "observeDOM", "(", "document", ".", "querySelector", "(", "'body'", ")", ",", "(", ")", "=>", "{", "Object", ".", "keys", "(", "this", ".", "trackedElements", ")", ".", "forEach", "(", "(", "element", ")", "=>", "{", "this", ".", "on", "(", "'enter'", ",", "element", ")", ";", "this", ".", "on", "(", "'leave'", ",", "element", ")", ";", "}", ")", ";", "}", ")", ";", "this", ".", "attach", "(", ")", ";", "}" ]
Detects wether DOM nodes enter or leave the viewport @constructor @param {object} options The configuration object
[ "Detects", "wether", "DOM", "nodes", "enter", "or", "leave", "the", "viewport" ]
01f8549587738fe1c50c5c95a2d17d62a3b5c9d7
https://github.com/silvestreh/onScreen/blob/01f8549587738fe1c50c5c95a2d17d62a3b5c9d7/lib/index.js#L18-L74
12,114
silvestreh/onScreen
lib/helpers/in-viewport.js
inViewport
function inViewport(el, options = { tolerance: 0 }) { if (!el) { throw new Error('You should specify the element you want to test'); } if (typeof el === 'string') { el = document.querySelector(el); } const elRect = el.getBoundingClientRect(); return ( // Check bottom boundary elRect.bottom - options.tolerance > 0 && // Check right boundary elRect.right - options.tolerance > 0 && // Check left boundary elRect.left + options.tolerance < (window.innerWidth || document.documentElement.clientWidth) && // Check top boundary elRect.top + options.tolerance < (window.innerHeight || document.documentElement.clientHeight) ); }
javascript
function inViewport(el, options = { tolerance: 0 }) { if (!el) { throw new Error('You should specify the element you want to test'); } if (typeof el === 'string') { el = document.querySelector(el); } const elRect = el.getBoundingClientRect(); return ( // Check bottom boundary elRect.bottom - options.tolerance > 0 && // Check right boundary elRect.right - options.tolerance > 0 && // Check left boundary elRect.left + options.tolerance < (window.innerWidth || document.documentElement.clientWidth) && // Check top boundary elRect.top + options.tolerance < (window.innerHeight || document.documentElement.clientHeight) ); }
[ "function", "inViewport", "(", "el", ",", "options", "=", "{", "tolerance", ":", "0", "}", ")", "{", "if", "(", "!", "el", ")", "{", "throw", "new", "Error", "(", "'You should specify the element you want to test'", ")", ";", "}", "if", "(", "typeof", "el", "===", "'string'", ")", "{", "el", "=", "document", ".", "querySelector", "(", "el", ")", ";", "}", "const", "elRect", "=", "el", ".", "getBoundingClientRect", "(", ")", ";", "return", "(", "// Check bottom boundary", "elRect", ".", "bottom", "-", "options", ".", "tolerance", ">", "0", "&&", "// Check right boundary", "elRect", ".", "right", "-", "options", ".", "tolerance", ">", "0", "&&", "// Check left boundary", "elRect", ".", "left", "+", "options", ".", "tolerance", "<", "(", "window", ".", "innerWidth", "||", "document", ".", "documentElement", ".", "clientWidth", ")", "&&", "// Check top boundary", "elRect", ".", "top", "+", "options", ".", "tolerance", "<", "(", "window", ".", "innerHeight", "||", "document", ".", "documentElement", ".", "clientHeight", ")", ")", ";", "}" ]
Checks an element's position in respect to the viewport and determines wether it's inside the viewport. @param {node} element The DOM node you want to check @return {boolean} A boolean value that indicates wether is on or off the viewport.
[ "Checks", "an", "element", "s", "position", "in", "respect", "to", "the", "viewport", "and", "determines", "wether", "it", "s", "inside", "the", "viewport", "." ]
01f8549587738fe1c50c5c95a2d17d62a3b5c9d7
https://github.com/silvestreh/onScreen/blob/01f8549587738fe1c50c5c95a2d17d62a3b5c9d7/lib/helpers/in-viewport.js#L8-L34
12,115
ensdomains/ens
migrations/2_deploy_contracts.js
deployFIFSRegistrar
function deployFIFSRegistrar(deployer, tld) { var rootNode = getRootNodeFromTLD(tld); // Deploy the ENS first deployer.deploy(ENS) .then(() => { // Deploy the FIFSRegistrar and bind it with ENS return deployer.deploy(FIFSRegistrar, ENS.address, rootNode.namehash); }) .then(function() { // Transfer the owner of the `rootNode` to the FIFSRegistrar return ENS.at(ENS.address).then((c) => c.setSubnodeOwner('0x0', rootNode.sha3, FIFSRegistrar.address)); }); }
javascript
function deployFIFSRegistrar(deployer, tld) { var rootNode = getRootNodeFromTLD(tld); // Deploy the ENS first deployer.deploy(ENS) .then(() => { // Deploy the FIFSRegistrar and bind it with ENS return deployer.deploy(FIFSRegistrar, ENS.address, rootNode.namehash); }) .then(function() { // Transfer the owner of the `rootNode` to the FIFSRegistrar return ENS.at(ENS.address).then((c) => c.setSubnodeOwner('0x0', rootNode.sha3, FIFSRegistrar.address)); }); }
[ "function", "deployFIFSRegistrar", "(", "deployer", ",", "tld", ")", "{", "var", "rootNode", "=", "getRootNodeFromTLD", "(", "tld", ")", ";", "// Deploy the ENS first", "deployer", ".", "deploy", "(", "ENS", ")", ".", "then", "(", "(", ")", "=>", "{", "// Deploy the FIFSRegistrar and bind it with ENS", "return", "deployer", ".", "deploy", "(", "FIFSRegistrar", ",", "ENS", ".", "address", ",", "rootNode", ".", "namehash", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "// Transfer the owner of the `rootNode` to the FIFSRegistrar", "return", "ENS", ".", "at", "(", "ENS", ".", "address", ")", ".", "then", "(", "(", "c", ")", "=>", "c", ".", "setSubnodeOwner", "(", "'0x0'", ",", "rootNode", ".", "sha3", ",", "FIFSRegistrar", ".", "address", ")", ")", ";", "}", ")", ";", "}" ]
Deploy the ENS and FIFSRegistrar @param {Object} deployer truffle deployer helper @param {string} tld tld which the FIFS registrar takes charge of
[ "Deploy", "the", "ENS", "and", "FIFSRegistrar" ]
5fc3138ebade51f2d9527adb9ef7b63b78481e1a
https://github.com/ensdomains/ens/blob/5fc3138ebade51f2d9527adb9ef7b63b78481e1a/migrations/2_deploy_contracts.js#L30-L43
12,116
googleapis/nodejs-vision
samples/textDetection.js
lookup
async function lookup(words) { const index = new Index(); const hits = await index.lookup(words); index.quit(); words.forEach((word, i) => { console.log(`hits for "${word}":`, hits[i].join(', ')); }); return hits; }
javascript
async function lookup(words) { const index = new Index(); const hits = await index.lookup(words); index.quit(); words.forEach((word, i) => { console.log(`hits for "${word}":`, hits[i].join(', ')); }); return hits; }
[ "async", "function", "lookup", "(", "words", ")", "{", "const", "index", "=", "new", "Index", "(", ")", ";", "const", "hits", "=", "await", "index", ".", "lookup", "(", "words", ")", ";", "index", ".", "quit", "(", ")", ";", "words", ".", "forEach", "(", "(", "word", ",", "i", ")", "=>", "{", "console", ".", "log", "(", "`", "${", "word", "}", "`", ",", "hits", "[", "i", "]", ".", "join", "(", "', '", ")", ")", ";", "}", ")", ";", "return", "hits", ";", "}" ]
Given a list of words, lookup any matches in the database. @param {string[]} words @returns {Promise<string[][]>}
[ "Given", "a", "list", "of", "words", "lookup", "any", "matches", "in", "the", "database", "." ]
a64bf32d32997d3d4fcd9a99db1bec43c60efc49
https://github.com/googleapis/nodejs-vision/blob/a64bf32d32997d3d4fcd9a99db1bec43c60efc49/samples/textDetection.js#L152-L160
12,117
googleapis/nodejs-vision
samples/textDetection.js
extractDescription
function extractDescription(texts) { let document = ''; texts.forEach(text => { document += text.description || ''; }); return document.toLowerCase(); }
javascript
function extractDescription(texts) { let document = ''; texts.forEach(text => { document += text.description || ''; }); return document.toLowerCase(); }
[ "function", "extractDescription", "(", "texts", ")", "{", "let", "document", "=", "''", ";", "texts", ".", "forEach", "(", "text", "=>", "{", "document", "+=", "text", ".", "description", "||", "''", ";", "}", ")", ";", "return", "document", ".", "toLowerCase", "(", ")", ";", "}" ]
Provide a joined string with all descriptions from the response data @param {TextAnnotation[]} texts Response data from the Vision API @returns {string} A joined string containing al descriptions
[ "Provide", "a", "joined", "string", "with", "all", "descriptions", "from", "the", "response", "data" ]
a64bf32d32997d3d4fcd9a99db1bec43c60efc49
https://github.com/googleapis/nodejs-vision/blob/a64bf32d32997d3d4fcd9a99db1bec43c60efc49/samples/textDetection.js#L167-L173
12,118
googleapis/nodejs-vision
samples/textDetection.js
extractDescriptions
async function extractDescriptions(filename, index, response) { if (response.textAnnotations.length) { const words = extractDescription(response.textAnnotations); await index.add(filename, words); } else { console.log(`${filename} had no discernable text.`); await index.setContainsNoText(filename); } }
javascript
async function extractDescriptions(filename, index, response) { if (response.textAnnotations.length) { const words = extractDescription(response.textAnnotations); await index.add(filename, words); } else { console.log(`${filename} had no discernable text.`); await index.setContainsNoText(filename); } }
[ "async", "function", "extractDescriptions", "(", "filename", ",", "index", ",", "response", ")", "{", "if", "(", "response", ".", "textAnnotations", ".", "length", ")", "{", "const", "words", "=", "extractDescription", "(", "response", ".", "textAnnotations", ")", ";", "await", "index", ".", "add", "(", "filename", ",", "words", ")", ";", "}", "else", "{", "console", ".", "log", "(", "`", "${", "filename", "}", "`", ")", ";", "await", "index", ".", "setContainsNoText", "(", "filename", ")", ";", "}", "}" ]
Grab the description, and push it into redis. @param {string} filename Name of the file being processed @param {Index} index The Index object that wraps Redis @param {*} response Individual response from the Cloud Vision API @returns {Promise<void>}
[ "Grab", "the", "description", "and", "push", "it", "into", "redis", "." ]
a64bf32d32997d3d4fcd9a99db1bec43c60efc49
https://github.com/googleapis/nodejs-vision/blob/a64bf32d32997d3d4fcd9a99db1bec43c60efc49/samples/textDetection.js#L182-L190
12,119
googleapis/nodejs-vision
samples/textDetection.js
main
async function main(inputDir) { const index = new Index(); try { const files = await readdir(inputDir); // Get a list of all files in the directory (filter out other directories) const allImageFiles = (await Promise.all( files.map(async file => { const filename = path.join(inputDir, file); const stats = await stat(filename); if (!stats.isDirectory()) { return filename; } }) )).filter(f => !!f); // Figure out which files have already been processed let imageFilesToProcess = (await Promise.all( allImageFiles.map(async filename => { const processed = await index.documentIsProcessed(filename); if (!processed) { // Forward this filename on for further processing return filename; } }) )).filter(file => !!file); // The batch endpoint won't handle if (imageFilesToProcess.length > 15) { console.log( 'Maximum of 15 images allowed. Analyzing the first 15 found.' ); imageFilesToProcess = imageFilesToProcess.slice(0, 15); } // Analyze any remaining unprocessed files if (imageFilesToProcess.length > 0) { console.log('Files to process: '); await getTextFromFiles(index, imageFilesToProcess); } console.log('All files processed!'); } catch (e) { console.error(e); } index.quit(); }
javascript
async function main(inputDir) { const index = new Index(); try { const files = await readdir(inputDir); // Get a list of all files in the directory (filter out other directories) const allImageFiles = (await Promise.all( files.map(async file => { const filename = path.join(inputDir, file); const stats = await stat(filename); if (!stats.isDirectory()) { return filename; } }) )).filter(f => !!f); // Figure out which files have already been processed let imageFilesToProcess = (await Promise.all( allImageFiles.map(async filename => { const processed = await index.documentIsProcessed(filename); if (!processed) { // Forward this filename on for further processing return filename; } }) )).filter(file => !!file); // The batch endpoint won't handle if (imageFilesToProcess.length > 15) { console.log( 'Maximum of 15 images allowed. Analyzing the first 15 found.' ); imageFilesToProcess = imageFilesToProcess.slice(0, 15); } // Analyze any remaining unprocessed files if (imageFilesToProcess.length > 0) { console.log('Files to process: '); await getTextFromFiles(index, imageFilesToProcess); } console.log('All files processed!'); } catch (e) { console.error(e); } index.quit(); }
[ "async", "function", "main", "(", "inputDir", ")", "{", "const", "index", "=", "new", "Index", "(", ")", ";", "try", "{", "const", "files", "=", "await", "readdir", "(", "inputDir", ")", ";", "// Get a list of all files in the directory (filter out other directories)", "const", "allImageFiles", "=", "(", "await", "Promise", ".", "all", "(", "files", ".", "map", "(", "async", "file", "=>", "{", "const", "filename", "=", "path", ".", "join", "(", "inputDir", ",", "file", ")", ";", "const", "stats", "=", "await", "stat", "(", "filename", ")", ";", "if", "(", "!", "stats", ".", "isDirectory", "(", ")", ")", "{", "return", "filename", ";", "}", "}", ")", ")", ")", ".", "filter", "(", "f", "=>", "!", "!", "f", ")", ";", "// Figure out which files have already been processed", "let", "imageFilesToProcess", "=", "(", "await", "Promise", ".", "all", "(", "allImageFiles", ".", "map", "(", "async", "filename", "=>", "{", "const", "processed", "=", "await", "index", ".", "documentIsProcessed", "(", "filename", ")", ";", "if", "(", "!", "processed", ")", "{", "// Forward this filename on for further processing", "return", "filename", ";", "}", "}", ")", ")", ")", ".", "filter", "(", "file", "=>", "!", "!", "file", ")", ";", "// The batch endpoint won't handle", "if", "(", "imageFilesToProcess", ".", "length", ">", "15", ")", "{", "console", ".", "log", "(", "'Maximum of 15 images allowed. Analyzing the first 15 found.'", ")", ";", "imageFilesToProcess", "=", "imageFilesToProcess", ".", "slice", "(", "0", ",", "15", ")", ";", "}", "// Analyze any remaining unprocessed files", "if", "(", "imageFilesToProcess", ".", "length", ">", "0", ")", "{", "console", ".", "log", "(", "'Files to process: '", ")", ";", "await", "getTextFromFiles", "(", "index", ",", "imageFilesToProcess", ")", ";", "}", "console", ".", "log", "(", "'All files processed!'", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "e", ")", ";", "}", "index", ".", "quit", "(", ")", ";", "}" ]
Main entry point for the program. @param {string} inputDir The directory in which to run the sample. @returns {Promise<void>}
[ "Main", "entry", "point", "for", "the", "program", "." ]
a64bf32d32997d3d4fcd9a99db1bec43c60efc49
https://github.com/googleapis/nodejs-vision/blob/a64bf32d32997d3d4fcd9a99db1bec43c60efc49/samples/textDetection.js#L235-L280
12,120
gmetais/YellowLabTools
lib/server/datastores/resultsDatastore.js
saveScreenshotIfExists
function saveScreenshotIfExists(testResults) { var deferred = Q.defer(); if (testResults.screenshotBuffer) { var screenshotFilePath = path.join(resultsDir, testResults.runId, resultScreenshotName); fs.writeFile(screenshotFilePath, testResults.screenshotBuffer); delete testResults.screenshotBuffer; } else { deferred.resolve(); } return deferred; }
javascript
function saveScreenshotIfExists(testResults) { var deferred = Q.defer(); if (testResults.screenshotBuffer) { var screenshotFilePath = path.join(resultsDir, testResults.runId, resultScreenshotName); fs.writeFile(screenshotFilePath, testResults.screenshotBuffer); delete testResults.screenshotBuffer; } else { deferred.resolve(); } return deferred; }
[ "function", "saveScreenshotIfExists", "(", "testResults", ")", "{", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "if", "(", "testResults", ".", "screenshotBuffer", ")", "{", "var", "screenshotFilePath", "=", "path", ".", "join", "(", "resultsDir", ",", "testResults", ".", "runId", ",", "resultScreenshotName", ")", ";", "fs", ".", "writeFile", "(", "screenshotFilePath", ",", "testResults", ".", "screenshotBuffer", ")", ";", "delete", "testResults", ".", "screenshotBuffer", ";", "}", "else", "{", "deferred", ".", "resolve", "(", ")", ";", "}", "return", "deferred", ";", "}" ]
If there is a screenshot, save it as screenshot.jpg in the same folder as the results
[ "If", "there", "is", "a", "screenshot", "save", "it", "as", "screenshot", ".", "jpg", "in", "the", "same", "folder", "as", "the", "results" ]
c59e9fc3f5d3db4e8f8952f154891ab3194d8f76
https://github.com/gmetais/YellowLabTools/blob/c59e9fc3f5d3db4e8f8952f154891ab3194d8f76/lib/server/datastores/resultsDatastore.js#L93-L108
12,121
gmetais/YellowLabTools
lib/tools/phantomas/custom_modules/core/scopeYLT/scopeYLT.js
spyEnabled
function spyEnabled(state, reason) { enabled = (state === true); phantomas.log('Spying ' + (enabled ? 'enabled' : 'disabled') + (reason ? ' - ' + reason : '')); }
javascript
function spyEnabled(state, reason) { enabled = (state === true); phantomas.log('Spying ' + (enabled ? 'enabled' : 'disabled') + (reason ? ' - ' + reason : '')); }
[ "function", "spyEnabled", "(", "state", ",", "reason", ")", "{", "enabled", "=", "(", "state", "===", "true", ")", ";", "phantomas", ".", "log", "(", "'Spying '", "+", "(", "enabled", "?", "'enabled'", ":", "'disabled'", ")", "+", "(", "reason", "?", "' - '", "+", "reason", ":", "''", ")", ")", ";", "}" ]
turn off spying to not include internal phantomas actions
[ "turn", "off", "spying", "to", "not", "include", "internal", "phantomas", "actions" ]
c59e9fc3f5d3db4e8f8952f154891ab3194d8f76
https://github.com/gmetais/YellowLabTools/blob/c59e9fc3f5d3db4e8f8952f154891ab3194d8f76/lib/tools/phantomas/custom_modules/core/scopeYLT/scopeYLT.js#L30-L34
12,122
gmetais/YellowLabTools
lib/tools/phantomas/custom_modules/core/scopeYLT/scopeYLT.js
pushContext
function pushContext(data) { // Some data is not needed on subchildren if (depth === 0) { data.timestamp = Date.now() - responseEndTime; data.loadingStep = phantomas.currentStep || ''; } // Some data is not needed on subchildren if (depth > 0) { if (data.backtrace) { delete data.backtrace; } if (data.resultsNumber) { delete data.resultsNumber; } } currentContext.addChild(data); }
javascript
function pushContext(data) { // Some data is not needed on subchildren if (depth === 0) { data.timestamp = Date.now() - responseEndTime; data.loadingStep = phantomas.currentStep || ''; } // Some data is not needed on subchildren if (depth > 0) { if (data.backtrace) { delete data.backtrace; } if (data.resultsNumber) { delete data.resultsNumber; } } currentContext.addChild(data); }
[ "function", "pushContext", "(", "data", ")", "{", "// Some data is not needed on subchildren", "if", "(", "depth", "===", "0", ")", "{", "data", ".", "timestamp", "=", "Date", ".", "now", "(", ")", "-", "responseEndTime", ";", "data", ".", "loadingStep", "=", "phantomas", ".", "currentStep", "||", "''", ";", "}", "// Some data is not needed on subchildren", "if", "(", "depth", ">", "0", ")", "{", "if", "(", "data", ".", "backtrace", ")", "{", "delete", "data", ".", "backtrace", ";", "}", "if", "(", "data", ".", "resultsNumber", ")", "{", "delete", "data", ".", "resultsNumber", ";", "}", "}", "currentContext", ".", "addChild", "(", "data", ")", ";", "}" ]
Add a child but don't enter its context
[ "Add", "a", "child", "but", "don", "t", "enter", "its", "context" ]
c59e9fc3f5d3db4e8f8952f154891ab3194d8f76
https://github.com/gmetais/YellowLabTools/blob/c59e9fc3f5d3db4e8f8952f154891ab3194d8f76/lib/tools/phantomas/custom_modules/core/scopeYLT/scopeYLT.js#L112-L131
12,123
gmetais/YellowLabTools
lib/tools/phantomas/custom_modules/core/scopeYLT/scopeYLT.js
leaveContext
function leaveContext(moreData) { // Some data is not needed on subchildren if (depth === 1) { currentContext.data.time = Date.now() - currentContext.data.timestamp - responseEndTime; } // Some data is not needed on subchildren if (depth > 1) { if (moreData && moreData.backtrace) { delete moreData.backtrace; } if (moreData && moreData.resultsNumber) { delete moreData.resultsNumber; } } // Merge previous data with moreData (ovewrites if exists) if (moreData) { for (var key in moreData) { currentContext.data[key] = moreData[key]; } } var parent = currentContext.parent; if (parent === null) { console.error('Error: trying to close root context in ContextTree'); } else { currentContext = parent; } depth --; }
javascript
function leaveContext(moreData) { // Some data is not needed on subchildren if (depth === 1) { currentContext.data.time = Date.now() - currentContext.data.timestamp - responseEndTime; } // Some data is not needed on subchildren if (depth > 1) { if (moreData && moreData.backtrace) { delete moreData.backtrace; } if (moreData && moreData.resultsNumber) { delete moreData.resultsNumber; } } // Merge previous data with moreData (ovewrites if exists) if (moreData) { for (var key in moreData) { currentContext.data[key] = moreData[key]; } } var parent = currentContext.parent; if (parent === null) { console.error('Error: trying to close root context in ContextTree'); } else { currentContext = parent; } depth --; }
[ "function", "leaveContext", "(", "moreData", ")", "{", "// Some data is not needed on subchildren", "if", "(", "depth", "===", "1", ")", "{", "currentContext", ".", "data", ".", "time", "=", "Date", ".", "now", "(", ")", "-", "currentContext", ".", "data", ".", "timestamp", "-", "responseEndTime", ";", "}", "// Some data is not needed on subchildren", "if", "(", "depth", ">", "1", ")", "{", "if", "(", "moreData", "&&", "moreData", ".", "backtrace", ")", "{", "delete", "moreData", ".", "backtrace", ";", "}", "if", "(", "moreData", "&&", "moreData", ".", "resultsNumber", ")", "{", "delete", "moreData", ".", "resultsNumber", ";", "}", "}", "// Merge previous data with moreData (ovewrites if exists)", "if", "(", "moreData", ")", "{", "for", "(", "var", "key", "in", "moreData", ")", "{", "currentContext", ".", "data", "[", "key", "]", "=", "moreData", "[", "key", "]", ";", "}", "}", "var", "parent", "=", "currentContext", ".", "parent", ";", "if", "(", "parent", "===", "null", ")", "{", "console", ".", "error", "(", "'Error: trying to close root context in ContextTree'", ")", ";", "}", "else", "{", "currentContext", "=", "parent", ";", "}", "depth", "--", ";", "}" ]
Save given data in the current context and jump change current context to its parent
[ "Save", "given", "data", "in", "the", "current", "context", "and", "jump", "change", "current", "context", "to", "its", "parent" ]
c59e9fc3f5d3db4e8f8952f154891ab3194d8f76
https://github.com/gmetais/YellowLabTools/blob/c59e9fc3f5d3db4e8f8952f154891ab3194d8f76/lib/tools/phantomas/custom_modules/core/scopeYLT/scopeYLT.js#L158-L190
12,124
gmetais/YellowLabTools
lib/tools/phantomas/custom_modules/core/scopeYLT/scopeYLT.js
readFullTree
function readFullTree() { // Return null if the contextTree is not correctly closed if (root !== currentContext) { return null; } function recusiveRead(node) { if (node.children.length === 0) { delete node.children; } else { for (var i=0, max=node.children.length ; i<max ; i++) { recusiveRead(node.children[i]); } } delete node.parent; } recusiveRead(root); return root; }
javascript
function readFullTree() { // Return null if the contextTree is not correctly closed if (root !== currentContext) { return null; } function recusiveRead(node) { if (node.children.length === 0) { delete node.children; } else { for (var i=0, max=node.children.length ; i<max ; i++) { recusiveRead(node.children[i]); } } delete node.parent; } recusiveRead(root); return root; }
[ "function", "readFullTree", "(", ")", "{", "// Return null if the contextTree is not correctly closed", "if", "(", "root", "!==", "currentContext", ")", "{", "return", "null", ";", "}", "function", "recusiveRead", "(", "node", ")", "{", "if", "(", "node", ".", "children", ".", "length", "===", "0", ")", "{", "delete", "node", ".", "children", ";", "}", "else", "{", "for", "(", "var", "i", "=", "0", ",", "max", "=", "node", ".", "children", ".", "length", ";", "i", "<", "max", ";", "i", "++", ")", "{", "recusiveRead", "(", "node", ".", "children", "[", "i", "]", ")", ";", "}", "}", "delete", "node", ".", "parent", ";", "}", "recusiveRead", "(", "root", ")", ";", "return", "root", ";", "}" ]
Returns a clean object, without the parent which causes recursive loops
[ "Returns", "a", "clean", "object", "without", "the", "parent", "which", "causes", "recursive", "loops" ]
c59e9fc3f5d3db4e8f8952f154891ab3194d8f76
https://github.com/gmetais/YellowLabTools/blob/c59e9fc3f5d3db4e8f8952f154891ab3194d8f76/lib/tools/phantomas/custom_modules/core/scopeYLT/scopeYLT.js#L197-L216
12,125
pocketjoso/penthouse
src/index.js
generateCriticalCssWrapped
async function generateCriticalCssWrapped ( options, { forceTryRestartBrowser } = {} ) { const width = parseInt(options.width || DEFAULT_VIEWPORT_WIDTH, 10) const height = parseInt(options.height || DEFAULT_VIEWPORT_HEIGHT, 10) const timeoutWait = options.timeout || DEFAULT_TIMEOUT // Merge properties with default ones const propertiesToRemove = options.propertiesToRemove || DEFAULT_PROPERTIES_TO_REMOVE // always forceInclude '*', 'html', and 'body' selectors; // yields slight performance improvement const forceInclude = prepareForceIncludeForSerialization( ['*', '*:before', '*:after', 'html', 'body'].concat( options.forceInclude || [] ) ) // promise so we can handle errors and reject, // instead of throwing what would otherwise be uncaught errors in node process return new Promise(async (resolve, reject) => { debuglog('call generateCriticalCssWrapped') let formattedCss let pagePromise try { pagePromise = getOpenBrowserPage() formattedCss = await generateCriticalCss({ pagePromise, url: options.url, cssString: options.cssString, width, height, forceInclude, strict: options.strict, userAgent: options.userAgent || DEFAULT_USER_AGENT, renderWaitTime: options.renderWaitTime || DEFAULT_RENDER_WAIT_TIMEOUT, timeout: timeoutWait, pageLoadSkipTimeout: options.pageLoadSkipTimeout, blockJSRequests: typeof options.blockJSRequests !== 'undefined' ? options.blockJSRequests : DEFAULT_BLOCK_JS_REQUESTS, customPageHeaders: options.customPageHeaders, cookies: options.cookies, screenshots: options.screenshots, keepLargerMediaQueries: options.keepLargerMediaQueries, maxElementsToCheckPerSelector: options.maxElementsToCheckPerSelector, // postformatting propertiesToRemove, maxEmbeddedBase64Length: typeof options.maxEmbeddedBase64Length === 'number' ? options.maxEmbeddedBase64Length : DEFAULT_MAX_EMBEDDED_BASE64_LENGTH, debuglog, unstableKeepBrowserAlive: options.unstableKeepBrowserAlive, allowedResponseCode: options.allowedResponseCode, unstableKeepOpenPages: options.unstableKeepOpenPages || _UNSTABLE_KEEP_ALIVE_MAX_KEPT_OPEN_PAGES }) } catch (e) { const page = await pagePromise.then(({ page }) => page) await closeBrowserPage({ page, error: e, unstableKeepBrowserAlive: options.unstableKeepBrowserAlive, unstableKeepOpenPages: options.unstableKeepOpenPages }) const runningBrowswer = await browserIsRunning() if (!forceTryRestartBrowser && !runningBrowswer) { debuglog( 'Browser unexpecedly not opened - crashed? ' + '\nurl: ' + options.url + '\ncss length: ' + options.cssString.length ) try { await restartBrowser({ width, height, getBrowser: options.puppeteer && options.puppeteer.getBrowser }) // retry resolve( generateCriticalCssWrapped(options, { forceTryRestartBrowser: true }) ) } catch (e) { reject(e) } return } reject(e) return } const page = await pagePromise.then(({ page }) => page) await closeBrowserPage({ page, unstableKeepBrowserAlive: options.unstableKeepBrowserAlive, unstableKeepOpenPages: options.unstableKeepOpenPages }) debuglog('generateCriticalCss done') if (formattedCss.trim().length === 0) { // TODO: would be good to surface this to user, always debuglog('Note: Generated critical css was empty for URL: ' + options.url) resolve('') return } resolve(formattedCss) }) }
javascript
async function generateCriticalCssWrapped ( options, { forceTryRestartBrowser } = {} ) { const width = parseInt(options.width || DEFAULT_VIEWPORT_WIDTH, 10) const height = parseInt(options.height || DEFAULT_VIEWPORT_HEIGHT, 10) const timeoutWait = options.timeout || DEFAULT_TIMEOUT // Merge properties with default ones const propertiesToRemove = options.propertiesToRemove || DEFAULT_PROPERTIES_TO_REMOVE // always forceInclude '*', 'html', and 'body' selectors; // yields slight performance improvement const forceInclude = prepareForceIncludeForSerialization( ['*', '*:before', '*:after', 'html', 'body'].concat( options.forceInclude || [] ) ) // promise so we can handle errors and reject, // instead of throwing what would otherwise be uncaught errors in node process return new Promise(async (resolve, reject) => { debuglog('call generateCriticalCssWrapped') let formattedCss let pagePromise try { pagePromise = getOpenBrowserPage() formattedCss = await generateCriticalCss({ pagePromise, url: options.url, cssString: options.cssString, width, height, forceInclude, strict: options.strict, userAgent: options.userAgent || DEFAULT_USER_AGENT, renderWaitTime: options.renderWaitTime || DEFAULT_RENDER_WAIT_TIMEOUT, timeout: timeoutWait, pageLoadSkipTimeout: options.pageLoadSkipTimeout, blockJSRequests: typeof options.blockJSRequests !== 'undefined' ? options.blockJSRequests : DEFAULT_BLOCK_JS_REQUESTS, customPageHeaders: options.customPageHeaders, cookies: options.cookies, screenshots: options.screenshots, keepLargerMediaQueries: options.keepLargerMediaQueries, maxElementsToCheckPerSelector: options.maxElementsToCheckPerSelector, // postformatting propertiesToRemove, maxEmbeddedBase64Length: typeof options.maxEmbeddedBase64Length === 'number' ? options.maxEmbeddedBase64Length : DEFAULT_MAX_EMBEDDED_BASE64_LENGTH, debuglog, unstableKeepBrowserAlive: options.unstableKeepBrowserAlive, allowedResponseCode: options.allowedResponseCode, unstableKeepOpenPages: options.unstableKeepOpenPages || _UNSTABLE_KEEP_ALIVE_MAX_KEPT_OPEN_PAGES }) } catch (e) { const page = await pagePromise.then(({ page }) => page) await closeBrowserPage({ page, error: e, unstableKeepBrowserAlive: options.unstableKeepBrowserAlive, unstableKeepOpenPages: options.unstableKeepOpenPages }) const runningBrowswer = await browserIsRunning() if (!forceTryRestartBrowser && !runningBrowswer) { debuglog( 'Browser unexpecedly not opened - crashed? ' + '\nurl: ' + options.url + '\ncss length: ' + options.cssString.length ) try { await restartBrowser({ width, height, getBrowser: options.puppeteer && options.puppeteer.getBrowser }) // retry resolve( generateCriticalCssWrapped(options, { forceTryRestartBrowser: true }) ) } catch (e) { reject(e) } return } reject(e) return } const page = await pagePromise.then(({ page }) => page) await closeBrowserPage({ page, unstableKeepBrowserAlive: options.unstableKeepBrowserAlive, unstableKeepOpenPages: options.unstableKeepOpenPages }) debuglog('generateCriticalCss done') if (formattedCss.trim().length === 0) { // TODO: would be good to surface this to user, always debuglog('Note: Generated critical css was empty for URL: ' + options.url) resolve('') return } resolve(formattedCss) }) }
[ "async", "function", "generateCriticalCssWrapped", "(", "options", ",", "{", "forceTryRestartBrowser", "}", "=", "{", "}", ")", "{", "const", "width", "=", "parseInt", "(", "options", ".", "width", "||", "DEFAULT_VIEWPORT_WIDTH", ",", "10", ")", "const", "height", "=", "parseInt", "(", "options", ".", "height", "||", "DEFAULT_VIEWPORT_HEIGHT", ",", "10", ")", "const", "timeoutWait", "=", "options", ".", "timeout", "||", "DEFAULT_TIMEOUT", "// Merge properties with default ones", "const", "propertiesToRemove", "=", "options", ".", "propertiesToRemove", "||", "DEFAULT_PROPERTIES_TO_REMOVE", "// always forceInclude '*', 'html', and 'body' selectors;", "// yields slight performance improvement", "const", "forceInclude", "=", "prepareForceIncludeForSerialization", "(", "[", "'*'", ",", "'*:before'", ",", "'*:after'", ",", "'html'", ",", "'body'", "]", ".", "concat", "(", "options", ".", "forceInclude", "||", "[", "]", ")", ")", "// promise so we can handle errors and reject,", "// instead of throwing what would otherwise be uncaught errors in node process", "return", "new", "Promise", "(", "async", "(", "resolve", ",", "reject", ")", "=>", "{", "debuglog", "(", "'call generateCriticalCssWrapped'", ")", "let", "formattedCss", "let", "pagePromise", "try", "{", "pagePromise", "=", "getOpenBrowserPage", "(", ")", "formattedCss", "=", "await", "generateCriticalCss", "(", "{", "pagePromise", ",", "url", ":", "options", ".", "url", ",", "cssString", ":", "options", ".", "cssString", ",", "width", ",", "height", ",", "forceInclude", ",", "strict", ":", "options", ".", "strict", ",", "userAgent", ":", "options", ".", "userAgent", "||", "DEFAULT_USER_AGENT", ",", "renderWaitTime", ":", "options", ".", "renderWaitTime", "||", "DEFAULT_RENDER_WAIT_TIMEOUT", ",", "timeout", ":", "timeoutWait", ",", "pageLoadSkipTimeout", ":", "options", ".", "pageLoadSkipTimeout", ",", "blockJSRequests", ":", "typeof", "options", ".", "blockJSRequests", "!==", "'undefined'", "?", "options", ".", "blockJSRequests", ":", "DEFAULT_BLOCK_JS_REQUESTS", ",", "customPageHeaders", ":", "options", ".", "customPageHeaders", ",", "cookies", ":", "options", ".", "cookies", ",", "screenshots", ":", "options", ".", "screenshots", ",", "keepLargerMediaQueries", ":", "options", ".", "keepLargerMediaQueries", ",", "maxElementsToCheckPerSelector", ":", "options", ".", "maxElementsToCheckPerSelector", ",", "// postformatting", "propertiesToRemove", ",", "maxEmbeddedBase64Length", ":", "typeof", "options", ".", "maxEmbeddedBase64Length", "===", "'number'", "?", "options", ".", "maxEmbeddedBase64Length", ":", "DEFAULT_MAX_EMBEDDED_BASE64_LENGTH", ",", "debuglog", ",", "unstableKeepBrowserAlive", ":", "options", ".", "unstableKeepBrowserAlive", ",", "allowedResponseCode", ":", "options", ".", "allowedResponseCode", ",", "unstableKeepOpenPages", ":", "options", ".", "unstableKeepOpenPages", "||", "_UNSTABLE_KEEP_ALIVE_MAX_KEPT_OPEN_PAGES", "}", ")", "}", "catch", "(", "e", ")", "{", "const", "page", "=", "await", "pagePromise", ".", "then", "(", "(", "{", "page", "}", ")", "=>", "page", ")", "await", "closeBrowserPage", "(", "{", "page", ",", "error", ":", "e", ",", "unstableKeepBrowserAlive", ":", "options", ".", "unstableKeepBrowserAlive", ",", "unstableKeepOpenPages", ":", "options", ".", "unstableKeepOpenPages", "}", ")", "const", "runningBrowswer", "=", "await", "browserIsRunning", "(", ")", "if", "(", "!", "forceTryRestartBrowser", "&&", "!", "runningBrowswer", ")", "{", "debuglog", "(", "'Browser unexpecedly not opened - crashed? '", "+", "'\\nurl: '", "+", "options", ".", "url", "+", "'\\ncss length: '", "+", "options", ".", "cssString", ".", "length", ")", "try", "{", "await", "restartBrowser", "(", "{", "width", ",", "height", ",", "getBrowser", ":", "options", ".", "puppeteer", "&&", "options", ".", "puppeteer", ".", "getBrowser", "}", ")", "// retry", "resolve", "(", "generateCriticalCssWrapped", "(", "options", ",", "{", "forceTryRestartBrowser", ":", "true", "}", ")", ")", "}", "catch", "(", "e", ")", "{", "reject", "(", "e", ")", "}", "return", "}", "reject", "(", "e", ")", "return", "}", "const", "page", "=", "await", "pagePromise", ".", "then", "(", "(", "{", "page", "}", ")", "=>", "page", ")", "await", "closeBrowserPage", "(", "{", "page", ",", "unstableKeepBrowserAlive", ":", "options", ".", "unstableKeepBrowserAlive", ",", "unstableKeepOpenPages", ":", "options", ".", "unstableKeepOpenPages", "}", ")", "debuglog", "(", "'generateCriticalCss done'", ")", "if", "(", "formattedCss", ".", "trim", "(", ")", ".", "length", "===", "0", ")", "{", "// TODO: would be good to surface this to user, always", "debuglog", "(", "'Note: Generated critical css was empty for URL: '", "+", "options", ".", "url", ")", "resolve", "(", "''", ")", "return", "}", "resolve", "(", "formattedCss", ")", "}", ")", "}" ]
const so not hoisted, so can get regeneratorRuntime inlined above, needed for Node 4
[ "const", "so", "not", "hoisted", "so", "can", "get", "regeneratorRuntime", "inlined", "above", "needed", "for", "Node", "4" ]
a3b4701a31b60eb8080ab48eade94932b2fc2bf3
https://github.com/pocketjoso/penthouse/blob/a3b4701a31b60eb8080ab48eade94932b2fc2bf3/src/index.js#L68-L186
12,126
pocketjoso/penthouse
examples/many-urls.js
startNewJob
function startNewJob () { const url = urls.pop() // NOTE: mutates urls array if (!url) { // no more new jobs to process (might still be jobs currently in process) return Promise.resolve() } return penthouse({ url, ...penthouseOptions }) .then(criticalCss => { // do something with your criticalCSS here! // Then call to see if there are more jobs to process return startNewJob() }) }
javascript
function startNewJob () { const url = urls.pop() // NOTE: mutates urls array if (!url) { // no more new jobs to process (might still be jobs currently in process) return Promise.resolve() } return penthouse({ url, ...penthouseOptions }) .then(criticalCss => { // do something with your criticalCSS here! // Then call to see if there are more jobs to process return startNewJob() }) }
[ "function", "startNewJob", "(", ")", "{", "const", "url", "=", "urls", ".", "pop", "(", ")", "// NOTE: mutates urls array", "if", "(", "!", "url", ")", "{", "// no more new jobs to process (might still be jobs currently in process)", "return", "Promise", ".", "resolve", "(", ")", "}", "return", "penthouse", "(", "{", "url", ",", "...", "penthouseOptions", "}", ")", ".", "then", "(", "criticalCss", "=>", "{", "// do something with your criticalCSS here!", "// Then call to see if there are more jobs to process", "return", "startNewJob", "(", ")", "}", ")", "}" ]
recursively generates critical css for one url at the time, until all urls have been handled
[ "recursively", "generates", "critical", "css", "for", "one", "url", "at", "the", "time", "until", "all", "urls", "have", "been", "handled" ]
a3b4701a31b60eb8080ab48eade94932b2fc2bf3
https://github.com/pocketjoso/penthouse/blob/a3b4701a31b60eb8080ab48eade94932b2fc2bf3/examples/many-urls.js#L25-L40
12,127
dequelabs/axe-cli
index.js
function(url) { if (silentMode) { return; } console.log( colors.bold('\nTesting ' + link(url)) + ' ... please wait, this may take a minute.' ); if (program.timer) { console.time('Total test time'); } }
javascript
function(url) { if (silentMode) { return; } console.log( colors.bold('\nTesting ' + link(url)) + ' ... please wait, this may take a minute.' ); if (program.timer) { console.time('Total test time'); } }
[ "function", "(", "url", ")", "{", "if", "(", "silentMode", ")", "{", "return", ";", "}", "console", ".", "log", "(", "colors", ".", "bold", "(", "'\\nTesting '", "+", "link", "(", "url", ")", ")", "+", "' ... please wait, this may take a minute.'", ")", ";", "if", "(", "program", ".", "timer", ")", "{", "console", ".", "time", "(", "'Total test time'", ")", ";", "}", "}" ]
Inform the user what page is tested
[ "Inform", "the", "user", "what", "page", "is", "tested" ]
7ee59e99f6d351a098ac2cf25bc80ab4cdce8980
https://github.com/dequelabs/axe-cli/blob/7ee59e99f6d351a098ac2cf25bc80ab4cdce8980/index.js#L136-L148
12,128
dequelabs/axe-cli
index.js
logResults
function logResults(results) { const { violations, testEngine, testEnvironment, testRunner } = results; if (violations.length === 0) { cliReporter(colors.green(' 0 violations found!')); return; } const issueCount = violations.reduce((count, violation) => { cliReporter( '\n' + error(' Violation of %j with %d occurrences!\n') + ' %s. Correct invalid elements at:\n' + violation.nodes .map(node => ' - ' + utils.selectorToString(node.target) + '\n') .join('') + ' For details, see: %s', violation.id, violation.nodes.length, violation.description, link(violation.helpUrl.split('?')[0]) ); return count + violation.nodes.length; }, 0); cliReporter(error('\n%d Accessibility issues detected.'), issueCount); if (program.verbose) { const metadata = { 'Test Runner': testRunner, 'Test Engine': testEngine, 'Test Environment': testEnvironment }; cliReporter(`\n${JSON.stringify(metadata, null, 2)}`); } if (program.exit) { process.exitCode = 1; } }
javascript
function logResults(results) { const { violations, testEngine, testEnvironment, testRunner } = results; if (violations.length === 0) { cliReporter(colors.green(' 0 violations found!')); return; } const issueCount = violations.reduce((count, violation) => { cliReporter( '\n' + error(' Violation of %j with %d occurrences!\n') + ' %s. Correct invalid elements at:\n' + violation.nodes .map(node => ' - ' + utils.selectorToString(node.target) + '\n') .join('') + ' For details, see: %s', violation.id, violation.nodes.length, violation.description, link(violation.helpUrl.split('?')[0]) ); return count + violation.nodes.length; }, 0); cliReporter(error('\n%d Accessibility issues detected.'), issueCount); if (program.verbose) { const metadata = { 'Test Runner': testRunner, 'Test Engine': testEngine, 'Test Environment': testEnvironment }; cliReporter(`\n${JSON.stringify(metadata, null, 2)}`); } if (program.exit) { process.exitCode = 1; } }
[ "function", "logResults", "(", "results", ")", "{", "const", "{", "violations", ",", "testEngine", ",", "testEnvironment", ",", "testRunner", "}", "=", "results", ";", "if", "(", "violations", ".", "length", "===", "0", ")", "{", "cliReporter", "(", "colors", ".", "green", "(", "' 0 violations found!'", ")", ")", ";", "return", ";", "}", "const", "issueCount", "=", "violations", ".", "reduce", "(", "(", "count", ",", "violation", ")", "=>", "{", "cliReporter", "(", "'\\n'", "+", "error", "(", "' Violation of %j with %d occurrences!\\n'", ")", "+", "' %s. Correct invalid elements at:\\n'", "+", "violation", ".", "nodes", ".", "map", "(", "node", "=>", "' - '", "+", "utils", ".", "selectorToString", "(", "node", ".", "target", ")", "+", "'\\n'", ")", ".", "join", "(", "''", ")", "+", "' For details, see: %s'", ",", "violation", ".", "id", ",", "violation", ".", "nodes", ".", "length", ",", "violation", ".", "description", ",", "link", "(", "violation", ".", "helpUrl", ".", "split", "(", "'?'", ")", "[", "0", "]", ")", ")", ";", "return", "count", "+", "violation", ".", "nodes", ".", "length", ";", "}", ",", "0", ")", ";", "cliReporter", "(", "error", "(", "'\\n%d Accessibility issues detected.'", ")", ",", "issueCount", ")", ";", "if", "(", "program", ".", "verbose", ")", "{", "const", "metadata", "=", "{", "'Test Runner'", ":", "testRunner", ",", "'Test Engine'", ":", "testEngine", ",", "'Test Environment'", ":", "testEnvironment", "}", ";", "cliReporter", "(", "`", "\\n", "${", "JSON", ".", "stringify", "(", "metadata", ",", "null", ",", "2", ")", "}", "`", ")", ";", "}", "if", "(", "program", ".", "exit", ")", "{", "process", ".", "exitCode", "=", "1", ";", "}", "}" ]
Put the result in the console
[ "Put", "the", "result", "in", "the", "console" ]
7ee59e99f6d351a098ac2cf25bc80ab4cdce8980
https://github.com/dequelabs/axe-cli/blob/7ee59e99f6d351a098ac2cf25bc80ab4cdce8980/index.js#L153-L192
12,129
janeasystems/nodejs-mobile-react-native
scripts/patch-package.js
patchPackageJSON_preNodeGyp_modulePath
function patchPackageJSON_preNodeGyp_modulePath(filePath) { let packageReadData = fs.readFileSync(filePath); let packageJSON = JSON.parse(packageReadData); if ( packageJSON && packageJSON.binary && packageJSON.binary.module_path ) { let binaryPathConfiguration = packageJSON.binary.module_path; binaryPathConfiguration = binaryPathConfiguration.replace(/\{node_abi\}/g, "node_abi"); binaryPathConfiguration = binaryPathConfiguration.replace(/\{platform\}/g, "platform"); binaryPathConfiguration = binaryPathConfiguration.replace(/\{arch\}/g, "arch"); binaryPathConfiguration = binaryPathConfiguration.replace(/\{target_arch\}/g, "target_arch"); binaryPathConfiguration = binaryPathConfiguration.replace(/\{libc\}/g, "libc"); packageJSON.binary.module_path = binaryPathConfiguration; let packageWriteData = JSON.stringify(packageJSON, null, 2); fs.writeFileSync(filePath, packageWriteData); } }
javascript
function patchPackageJSON_preNodeGyp_modulePath(filePath) { let packageReadData = fs.readFileSync(filePath); let packageJSON = JSON.parse(packageReadData); if ( packageJSON && packageJSON.binary && packageJSON.binary.module_path ) { let binaryPathConfiguration = packageJSON.binary.module_path; binaryPathConfiguration = binaryPathConfiguration.replace(/\{node_abi\}/g, "node_abi"); binaryPathConfiguration = binaryPathConfiguration.replace(/\{platform\}/g, "platform"); binaryPathConfiguration = binaryPathConfiguration.replace(/\{arch\}/g, "arch"); binaryPathConfiguration = binaryPathConfiguration.replace(/\{target_arch\}/g, "target_arch"); binaryPathConfiguration = binaryPathConfiguration.replace(/\{libc\}/g, "libc"); packageJSON.binary.module_path = binaryPathConfiguration; let packageWriteData = JSON.stringify(packageJSON, null, 2); fs.writeFileSync(filePath, packageWriteData); } }
[ "function", "patchPackageJSON_preNodeGyp_modulePath", "(", "filePath", ")", "{", "let", "packageReadData", "=", "fs", ".", "readFileSync", "(", "filePath", ")", ";", "let", "packageJSON", "=", "JSON", ".", "parse", "(", "packageReadData", ")", ";", "if", "(", "packageJSON", "&&", "packageJSON", ".", "binary", "&&", "packageJSON", ".", "binary", ".", "module_path", ")", "{", "let", "binaryPathConfiguration", "=", "packageJSON", ".", "binary", ".", "module_path", ";", "binaryPathConfiguration", "=", "binaryPathConfiguration", ".", "replace", "(", "/", "\\{node_abi\\}", "/", "g", ",", "\"node_abi\"", ")", ";", "binaryPathConfiguration", "=", "binaryPathConfiguration", ".", "replace", "(", "/", "\\{platform\\}", "/", "g", ",", "\"platform\"", ")", ";", "binaryPathConfiguration", "=", "binaryPathConfiguration", ".", "replace", "(", "/", "\\{arch\\}", "/", "g", ",", "\"arch\"", ")", ";", "binaryPathConfiguration", "=", "binaryPathConfiguration", ".", "replace", "(", "/", "\\{target_arch\\}", "/", "g", ",", "\"target_arch\"", ")", ";", "binaryPathConfiguration", "=", "binaryPathConfiguration", ".", "replace", "(", "/", "\\{libc\\}", "/", "g", ",", "\"libc\"", ")", ";", "packageJSON", ".", "binary", ".", "module_path", "=", "binaryPathConfiguration", ";", "let", "packageWriteData", "=", "JSON", ".", "stringify", "(", "packageJSON", ",", "null", ",", "2", ")", ";", "fs", ".", "writeFileSync", "(", "filePath", ",", "packageWriteData", ")", ";", "}", "}" ]
Patches a package.json in case it has variable substitution for the module's binary at runtime. Since we are cross-compiling for mobile, this substitution will have different values at build time and runtime, so we pre-substitute them with fixed values.
[ "Patches", "a", "package", ".", "json", "in", "case", "it", "has", "variable", "substitution", "for", "the", "module", "s", "binary", "at", "runtime", ".", "Since", "we", "are", "cross", "-", "compiling", "for", "mobile", "this", "substitution", "will", "have", "different", "values", "at", "build", "time", "and", "runtime", "so", "we", "pre", "-", "substitute", "them", "with", "fixed", "values", "." ]
1feb35d70cec536ae0980147a6b597bcbe5ba5eb
https://github.com/janeasystems/nodejs-mobile-react-native/blob/1feb35d70cec536ae0980147a6b597bcbe5ba5eb/scripts/patch-package.js#L9-L24
12,130
janeasystems/nodejs-mobile-react-native
scripts/patch-package.js
visitPackageJSON
function visitPackageJSON(folderPath) { let files = fs.readdirSync(folderPath); for (var i in files) { let name = files[i]; let filePath = path.join(folderPath, files[i]); if(fs.statSync(filePath).isDirectory()) { visitPackageJSON(filePath); } else { if (name === 'package.json') { try { patchPackageJSON_preNodeGyp_modulePath(filePath); } catch (e) { console.warn( 'Failed to patch the file : "' + filePath + '". The following error was thrown: ' + JSON.stringify(e) ); } } } } }
javascript
function visitPackageJSON(folderPath) { let files = fs.readdirSync(folderPath); for (var i in files) { let name = files[i]; let filePath = path.join(folderPath, files[i]); if(fs.statSync(filePath).isDirectory()) { visitPackageJSON(filePath); } else { if (name === 'package.json') { try { patchPackageJSON_preNodeGyp_modulePath(filePath); } catch (e) { console.warn( 'Failed to patch the file : "' + filePath + '". The following error was thrown: ' + JSON.stringify(e) ); } } } } }
[ "function", "visitPackageJSON", "(", "folderPath", ")", "{", "let", "files", "=", "fs", ".", "readdirSync", "(", "folderPath", ")", ";", "for", "(", "var", "i", "in", "files", ")", "{", "let", "name", "=", "files", "[", "i", "]", ";", "let", "filePath", "=", "path", ".", "join", "(", "folderPath", ",", "files", "[", "i", "]", ")", ";", "if", "(", "fs", ".", "statSync", "(", "filePath", ")", ".", "isDirectory", "(", ")", ")", "{", "visitPackageJSON", "(", "filePath", ")", ";", "}", "else", "{", "if", "(", "name", "===", "'package.json'", ")", "{", "try", "{", "patchPackageJSON_preNodeGyp_modulePath", "(", "filePath", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "warn", "(", "'Failed to patch the file : \"'", "+", "filePath", "+", "'\". The following error was thrown: '", "+", "JSON", ".", "stringify", "(", "e", ")", ")", ";", "}", "}", "}", "}", "}" ]
Visits every package.json to apply patches.
[ "Visits", "every", "package", ".", "json", "to", "apply", "patches", "." ]
1feb35d70cec536ae0980147a6b597bcbe5ba5eb
https://github.com/janeasystems/nodejs-mobile-react-native/blob/1feb35d70cec536ae0980147a6b597bcbe5ba5eb/scripts/patch-package.js#L27-L50
12,131
janeasystems/nodejs-mobile-react-native
scripts/module-postlink.js
function(fileName) { var configurations = xcodeProject.pbxXCBuildConfigurationSection(), INHERITED = '"$(inherited)"', config, buildSettings, searchPaths; var fileDir = path.dirname(fileName); var filePos = '"\\"' + fileDir + '\\""'; for (config in configurations) { buildSettings = configurations[config].buildSettings; if(!buildSettings || !buildSettings['PRODUCT_NAME']) continue; if (!buildSettings['FRAMEWORK_SEARCH_PATHS'] || buildSettings['FRAMEWORK_SEARCH_PATHS'] === INHERITED) { buildSettings['FRAMEWORK_SEARCH_PATHS'] = [INHERITED]; } buildSettings['FRAMEWORK_SEARCH_PATHS'].push(filePos); } }
javascript
function(fileName) { var configurations = xcodeProject.pbxXCBuildConfigurationSection(), INHERITED = '"$(inherited)"', config, buildSettings, searchPaths; var fileDir = path.dirname(fileName); var filePos = '"\\"' + fileDir + '\\""'; for (config in configurations) { buildSettings = configurations[config].buildSettings; if(!buildSettings || !buildSettings['PRODUCT_NAME']) continue; if (!buildSettings['FRAMEWORK_SEARCH_PATHS'] || buildSettings['FRAMEWORK_SEARCH_PATHS'] === INHERITED) { buildSettings['FRAMEWORK_SEARCH_PATHS'] = [INHERITED]; } buildSettings['FRAMEWORK_SEARCH_PATHS'].push(filePos); } }
[ "function", "(", "fileName", ")", "{", "var", "configurations", "=", "xcodeProject", ".", "pbxXCBuildConfigurationSection", "(", ")", ",", "INHERITED", "=", "'\"$(inherited)\"'", ",", "config", ",", "buildSettings", ",", "searchPaths", ";", "var", "fileDir", "=", "path", ".", "dirname", "(", "fileName", ")", ";", "var", "filePos", "=", "'\"\\\\\"'", "+", "fileDir", "+", "'\\\\\"\"'", ";", "for", "(", "config", "in", "configurations", ")", "{", "buildSettings", "=", "configurations", "[", "config", "]", ".", "buildSettings", ";", "if", "(", "!", "buildSettings", "||", "!", "buildSettings", "[", "'PRODUCT_NAME'", "]", ")", "continue", ";", "if", "(", "!", "buildSettings", "[", "'FRAMEWORK_SEARCH_PATHS'", "]", "||", "buildSettings", "[", "'FRAMEWORK_SEARCH_PATHS'", "]", "===", "INHERITED", ")", "{", "buildSettings", "[", "'FRAMEWORK_SEARCH_PATHS'", "]", "=", "[", "INHERITED", "]", ";", "}", "buildSettings", "[", "'FRAMEWORK_SEARCH_PATHS'", "]", ".", "push", "(", "filePos", ")", ";", "}", "}" ]
Override addToFrameworkSearchPaths to add the framework path to all targets. The one provided in the xcode module adds the wrong path and not to the right target.
[ "Override", "addToFrameworkSearchPaths", "to", "add", "the", "framework", "path", "to", "all", "targets", ".", "The", "one", "provided", "in", "the", "xcode", "module", "adds", "the", "wrong", "path", "and", "not", "to", "the", "right", "target", "." ]
1feb35d70cec536ae0980147a6b597bcbe5ba5eb
https://github.com/janeasystems/nodejs-mobile-react-native/blob/1feb35d70cec536ae0980147a6b597bcbe5ba5eb/scripts/module-postlink.js#L120-L142
12,132
hiddentao/squel
src/core.js
_extend
function _extend (dst, ...sources) { if (dst && sources) { for (let src of sources) { if (typeof src === 'object') { Object.getOwnPropertyNames(src).forEach(function (key) { dst[key] = src[key]; }); } } } return dst; }
javascript
function _extend (dst, ...sources) { if (dst && sources) { for (let src of sources) { if (typeof src === 'object') { Object.getOwnPropertyNames(src).forEach(function (key) { dst[key] = src[key]; }); } } } return dst; }
[ "function", "_extend", "(", "dst", ",", "...", "sources", ")", "{", "if", "(", "dst", "&&", "sources", ")", "{", "for", "(", "let", "src", "of", "sources", ")", "{", "if", "(", "typeof", "src", "===", "'object'", ")", "{", "Object", ".", "getOwnPropertyNames", "(", "src", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "dst", "[", "key", "]", "=", "src", "[", "key", "]", ";", "}", ")", ";", "}", "}", "}", "return", "dst", ";", "}" ]
Extend given object's with other objects' properties, overriding existing ones if necessary
[ "Extend", "given", "object", "s", "with", "other", "objects", "properties", "overriding", "existing", "ones", "if", "necessary" ]
8334ea2c83312961f12e9f45cf8b3cc8445482dc
https://github.com/hiddentao/squel/blob/8334ea2c83312961f12e9f45cf8b3cc8445482dc/src/core.js#L9-L21
12,133
hiddentao/squel
src/core.js
_clone
function _clone(src) { if (!src) { return src; } if (typeof src.clone === 'function') { return src.clone(); } else if (_isPlainObject(src) || _isArray(src)) { let ret = new (src.constructor); Object.getOwnPropertyNames(src).forEach(function(key) { if (typeof src[key] !== 'function') { ret[key] = _clone(src[key]); } }); return ret; } else { return JSON.parse(JSON.stringify(src)); } }
javascript
function _clone(src) { if (!src) { return src; } if (typeof src.clone === 'function') { return src.clone(); } else if (_isPlainObject(src) || _isArray(src)) { let ret = new (src.constructor); Object.getOwnPropertyNames(src).forEach(function(key) { if (typeof src[key] !== 'function') { ret[key] = _clone(src[key]); } }); return ret; } else { return JSON.parse(JSON.stringify(src)); } }
[ "function", "_clone", "(", "src", ")", "{", "if", "(", "!", "src", ")", "{", "return", "src", ";", "}", "if", "(", "typeof", "src", ".", "clone", "===", "'function'", ")", "{", "return", "src", ".", "clone", "(", ")", ";", "}", "else", "if", "(", "_isPlainObject", "(", "src", ")", "||", "_isArray", "(", "src", ")", ")", "{", "let", "ret", "=", "new", "(", "src", ".", "constructor", ")", ";", "Object", ".", "getOwnPropertyNames", "(", "src", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "typeof", "src", "[", "key", "]", "!==", "'function'", ")", "{", "ret", "[", "key", "]", "=", "_clone", "(", "src", "[", "key", "]", ")", ";", "}", "}", ")", ";", "return", "ret", ";", "}", "else", "{", "return", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "src", ")", ")", ";", "}", "}" ]
clone given item
[ "clone", "given", "item" ]
8334ea2c83312961f12e9f45cf8b3cc8445482dc
https://github.com/hiddentao/squel/blob/8334ea2c83312961f12e9f45cf8b3cc8445482dc/src/core.js#L39-L59
12,134
hiddentao/squel
src/core.js
registerValueHandler
function registerValueHandler (handlers, type, handler) { let typeofType = typeof type; if (typeofType !== 'function' && typeofType !== 'string') { throw new Error("type must be a class constructor or string"); } if (typeof handler !== 'function') { throw new Error("handler must be a function"); } for (let typeHandler of handlers) { if (typeHandler.type === type) { typeHandler.handler = handler; return; } } handlers.push({ type: type, handler: handler, }); }
javascript
function registerValueHandler (handlers, type, handler) { let typeofType = typeof type; if (typeofType !== 'function' && typeofType !== 'string') { throw new Error("type must be a class constructor or string"); } if (typeof handler !== 'function') { throw new Error("handler must be a function"); } for (let typeHandler of handlers) { if (typeHandler.type === type) { typeHandler.handler = handler; return; } } handlers.push({ type: type, handler: handler, }); }
[ "function", "registerValueHandler", "(", "handlers", ",", "type", ",", "handler", ")", "{", "let", "typeofType", "=", "typeof", "type", ";", "if", "(", "typeofType", "!==", "'function'", "&&", "typeofType", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "\"type must be a class constructor or string\"", ")", ";", "}", "if", "(", "typeof", "handler", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "\"handler must be a function\"", ")", ";", "}", "for", "(", "let", "typeHandler", "of", "handlers", ")", "{", "if", "(", "typeHandler", ".", "type", "===", "type", ")", "{", "typeHandler", ".", "handler", "=", "handler", ";", "return", ";", "}", "}", "handlers", ".", "push", "(", "{", "type", ":", "type", ",", "handler", ":", "handler", ",", "}", ")", ";", "}" ]
Register a value type handler Note: this will override any existing handler registered for this value type.
[ "Register", "a", "value", "type", "handler" ]
8334ea2c83312961f12e9f45cf8b3cc8445482dc
https://github.com/hiddentao/squel/blob/8334ea2c83312961f12e9f45cf8b3cc8445482dc/src/core.js#L67-L90
12,135
hiddentao/squel
src/core.js
getValueHandler
function getValueHandler (value, localHandlers, globalHandlers) { return _getValueHandler(value, localHandlers) || _getValueHandler(value, globalHandlers); }
javascript
function getValueHandler (value, localHandlers, globalHandlers) { return _getValueHandler(value, localHandlers) || _getValueHandler(value, globalHandlers); }
[ "function", "getValueHandler", "(", "value", ",", "localHandlers", ",", "globalHandlers", ")", "{", "return", "_getValueHandler", "(", "value", ",", "localHandlers", ")", "||", "_getValueHandler", "(", "value", ",", "globalHandlers", ")", ";", "}" ]
Get value type handler for given type
[ "Get", "value", "type", "handler", "for", "given", "type" ]
8334ea2c83312961f12e9f45cf8b3cc8445482dc
https://github.com/hiddentao/squel/blob/8334ea2c83312961f12e9f45cf8b3cc8445482dc/src/core.js#L98-L100
12,136
nicgirault/circosJS
src/layout/render.js
blockTicks
function blockTicks (d) { const k = (d.end - d.start) / d.len return range(0, d.len, conf.ticks.spacing).map((v, i) => { return { angle: v * k + d.start, label: displayLabel(v, i) } }) }
javascript
function blockTicks (d) { const k = (d.end - d.start) / d.len return range(0, d.len, conf.ticks.spacing).map((v, i) => { return { angle: v * k + d.start, label: displayLabel(v, i) } }) }
[ "function", "blockTicks", "(", "d", ")", "{", "const", "k", "=", "(", "d", ".", "end", "-", "d", ".", "start", ")", "/", "d", ".", "len", "return", "range", "(", "0", ",", "d", ".", "len", ",", "conf", ".", "ticks", ".", "spacing", ")", ".", "map", "(", "(", "v", ",", "i", ")", "=>", "{", "return", "{", "angle", ":", "v", "*", "k", "+", "d", ".", "start", ",", "label", ":", "displayLabel", "(", "v", ",", "i", ")", "}", "}", ")", "}" ]
Returns an array of tick angles and labels, given a block.
[ "Returns", "an", "array", "of", "tick", "angles", "and", "labels", "given", "a", "block", "." ]
ff9106b39876c98126e894da07c03a7eb90d2356
https://github.com/nicgirault/circosJS/blob/ff9106b39876c98126e894da07c03a7eb90d2356/src/layout/render.js#L34-L42
12,137
anvaka/ngraph.path
a-star/nba/index.js
forwardSearch
function forwardSearch() { cameFrom = open1Set.pop(); if (cameFrom.closed) { return; } cameFrom.closed = true; if (cameFrom.f1 < lMin && (cameFrom.g1 + f2 - heuristic(from, cameFrom.node)) < lMin) { graph.forEachLinkedNode(cameFrom.node.id, forwardVisitor); } if (open1Set.length > 0) { // this will be used in reverse search f1 = open1Set.peek().f1; } }
javascript
function forwardSearch() { cameFrom = open1Set.pop(); if (cameFrom.closed) { return; } cameFrom.closed = true; if (cameFrom.f1 < lMin && (cameFrom.g1 + f2 - heuristic(from, cameFrom.node)) < lMin) { graph.forEachLinkedNode(cameFrom.node.id, forwardVisitor); } if (open1Set.length > 0) { // this will be used in reverse search f1 = open1Set.peek().f1; } }
[ "function", "forwardSearch", "(", ")", "{", "cameFrom", "=", "open1Set", ".", "pop", "(", ")", ";", "if", "(", "cameFrom", ".", "closed", ")", "{", "return", ";", "}", "cameFrom", ".", "closed", "=", "true", ";", "if", "(", "cameFrom", ".", "f1", "<", "lMin", "&&", "(", "cameFrom", ".", "g1", "+", "f2", "-", "heuristic", "(", "from", ",", "cameFrom", ".", "node", ")", ")", "<", "lMin", ")", "{", "graph", ".", "forEachLinkedNode", "(", "cameFrom", ".", "node", ".", "id", ",", "forwardVisitor", ")", ";", "}", "if", "(", "open1Set", ".", "length", ">", "0", ")", "{", "// this will be used in reverse search", "f1", "=", "open1Set", ".", "peek", "(", ")", ".", "f1", ";", "}", "}" ]
the public API is over
[ "the", "public", "API", "is", "over" ]
6798fc9818d17bc04fdffaa3cedcf55dac2090ca
https://github.com/anvaka/ngraph.path/blob/6798fc9818d17bc04fdffaa3cedcf55dac2090ca/a-star/nba/index.js#L137-L153
12,138
primus/primus
middleware/xss.js
xss
function xss(req, res) { var agent = (req.headers['user-agent'] || '').toLowerCase(); if (agent && (~agent.indexOf(';msie') || ~agent.indexOf('trident/'))) { setHeader(res, 'X-XSS-Protection', '0'); } }
javascript
function xss(req, res) { var agent = (req.headers['user-agent'] || '').toLowerCase(); if (agent && (~agent.indexOf(';msie') || ~agent.indexOf('trident/'))) { setHeader(res, 'X-XSS-Protection', '0'); } }
[ "function", "xss", "(", "req", ",", "res", ")", "{", "var", "agent", "=", "(", "req", ".", "headers", "[", "'user-agent'", "]", "||", "''", ")", ".", "toLowerCase", "(", ")", ";", "if", "(", "agent", "&&", "(", "~", "agent", ".", "indexOf", "(", "';msie'", ")", "||", "~", "agent", ".", "indexOf", "(", "'trident/'", ")", ")", ")", "{", "setHeader", "(", "res", ",", "'X-XSS-Protection'", ",", "'0'", ")", ";", "}", "}" ]
Forcefully add x-xss-protection headers. @param {Request} req The incoming HTTP request. @param {Response} res The outgoing HTTP response. @api public
[ "Forcefully", "add", "x", "-", "xss", "-", "protection", "headers", "." ]
7d58d8ebeeed89d7f759ff6c5dfe026deba9666e
https://github.com/primus/primus/blob/7d58d8ebeeed89d7f759ff6c5dfe026deba9666e/middleware/xss.js#L12-L18
12,139
primus/primus
primus.js
context
function context(self, method) { if (self instanceof Primus) return; var failure = new Error('Primus#'+ method + '\'s context should called with a Primus instance'); if ('function' !== typeof self.listeners || !self.listeners('error').length) { throw failure; } self.emit('error', failure); }
javascript
function context(self, method) { if (self instanceof Primus) return; var failure = new Error('Primus#'+ method + '\'s context should called with a Primus instance'); if ('function' !== typeof self.listeners || !self.listeners('error').length) { throw failure; } self.emit('error', failure); }
[ "function", "context", "(", "self", ",", "method", ")", "{", "if", "(", "self", "instanceof", "Primus", ")", "return", ";", "var", "failure", "=", "new", "Error", "(", "'Primus#'", "+", "method", "+", "'\\'s context should called with a Primus instance'", ")", ";", "if", "(", "'function'", "!==", "typeof", "self", ".", "listeners", "||", "!", "self", ".", "listeners", "(", "'error'", ")", ".", "length", ")", "{", "throw", "failure", ";", "}", "self", ".", "emit", "(", "'error'", ",", "failure", ")", ";", "}" ]
Context assertion, ensure that some of our public Primus methods are called with the correct context to ensure that @param {Primus} self The context of the function. @param {String} method The method name. @api private
[ "Context", "assertion", "ensure", "that", "some", "of", "our", "public", "Primus", "methods", "are", "called", "with", "the", "correct", "context", "to", "ensure", "that" ]
7d58d8ebeeed89d7f759ff6c5dfe026deba9666e
https://github.com/primus/primus/blob/7d58d8ebeeed89d7f759ff6c5dfe026deba9666e/primus.js#L22-L32
12,140
primus/primus
primus.js
remove
function remove() { primus.removeListener('error', remove) .removeListener('open', remove) .removeListener('end', remove) .timers.clear('connect'); }
javascript
function remove() { primus.removeListener('error', remove) .removeListener('open', remove) .removeListener('end', remove) .timers.clear('connect'); }
[ "function", "remove", "(", ")", "{", "primus", ".", "removeListener", "(", "'error'", ",", "remove", ")", ".", "removeListener", "(", "'open'", ",", "remove", ")", ".", "removeListener", "(", "'end'", ",", "remove", ")", ".", "timers", ".", "clear", "(", "'connect'", ")", ";", "}" ]
Remove all references to the timeout listener as we've received an event that can be used to determine state. @api private
[ "Remove", "all", "references", "to", "the", "timeout", "listener", "as", "we", "ve", "received", "an", "event", "that", "can", "be", "used", "to", "determine", "state", "." ]
7d58d8ebeeed89d7f759ff6c5dfe026deba9666e
https://github.com/primus/primus/blob/7d58d8ebeeed89d7f759ff6c5dfe026deba9666e/primus.js#L860-L865
12,141
primus/primus
examples/middleware/session.js
session
function session(req, res, next) { // // The session id is stored in the cookies. // `req.signedCookies` is assigned by the `cookie-parser` middleware. // var sid = req.signedCookies[key]; // // Default to an empty session. // req.session = {}; // // If we don't have a session id we are done. // if (!sid) return next(); // // Grab the session from the store. // store.get(sid, function (err, session) { // // We don't want to kill the connection when we get an error from the // session store so we just log the error. // if (err) { primus.emit('log', 'error', err); return next(); } if (session) req.session = session; next(); }); }
javascript
function session(req, res, next) { // // The session id is stored in the cookies. // `req.signedCookies` is assigned by the `cookie-parser` middleware. // var sid = req.signedCookies[key]; // // Default to an empty session. // req.session = {}; // // If we don't have a session id we are done. // if (!sid) return next(); // // Grab the session from the store. // store.get(sid, function (err, session) { // // We don't want to kill the connection when we get an error from the // session store so we just log the error. // if (err) { primus.emit('log', 'error', err); return next(); } if (session) req.session = session; next(); }); }
[ "function", "session", "(", "req", ",", "res", ",", "next", ")", "{", "//", "// The session id is stored in the cookies.", "// `req.signedCookies` is assigned by the `cookie-parser` middleware.", "//", "var", "sid", "=", "req", ".", "signedCookies", "[", "key", "]", ";", "//", "// Default to an empty session.", "//", "req", ".", "session", "=", "{", "}", ";", "//", "// If we don't have a session id we are done.", "//", "if", "(", "!", "sid", ")", "return", "next", "(", ")", ";", "//", "// Grab the session from the store.", "//", "store", ".", "get", "(", "sid", ",", "function", "(", "err", ",", "session", ")", "{", "//", "// We don't want to kill the connection when we get an error from the", "// session store so we just log the error.", "//", "if", "(", "err", ")", "{", "primus", ".", "emit", "(", "'log'", ",", "'error'", ",", "err", ")", ";", "return", "next", "(", ")", ";", "}", "if", "(", "session", ")", "req", ".", "session", "=", "session", ";", "next", "(", ")", ";", "}", ")", ";", "}" ]
The actual session middleware. This middleware is async so we need 3 arguments.
[ "The", "actual", "session", "middleware", ".", "This", "middleware", "is", "async", "so", "we", "need", "3", "arguments", "." ]
7d58d8ebeeed89d7f759ff6c5dfe026deba9666e
https://github.com/primus/primus/blob/7d58d8ebeeed89d7f759ff6c5dfe026deba9666e/examples/middleware/session.js#L26-L60
12,142
primus/primus
spark.js
Spark
function Spark(primus, headers, address, query, id, request, socket) { this.fuse(); var writable = this.writable , spark = this , idgen = primus.options.idGenerator; query = query || {}; id = idgen ? idgen() : (id || nanoid()); headers = headers || {}; address = address || {}; request = request || headers['primus::req::backup']; writable('id', id); // Unique id for socket. writable('primus', primus); // References to Primus. writable('remote', address); // The remote address location. writable('headers', headers); // The request headers. writable('request', request); // Reference to an HTTP request. writable('socket', socket); // Reference to the transformer's socket writable('writable', true); // Silly stream compatibility. writable('readable', true); // Silly stream compatibility. writable('queue', []); // Data queue for data events. writable('query', query); // The query string. writable('ultron', new Ultron(this)); // Our event listening cleanup. writable('alive', true); // Flag used to detect zombie sparks. // // Parse our query string. // if ('string' === typeof this.query) { this.query = parse(this.query); } this.__initialise.forEach(function execute(initialise) { initialise.call(spark); }); }
javascript
function Spark(primus, headers, address, query, id, request, socket) { this.fuse(); var writable = this.writable , spark = this , idgen = primus.options.idGenerator; query = query || {}; id = idgen ? idgen() : (id || nanoid()); headers = headers || {}; address = address || {}; request = request || headers['primus::req::backup']; writable('id', id); // Unique id for socket. writable('primus', primus); // References to Primus. writable('remote', address); // The remote address location. writable('headers', headers); // The request headers. writable('request', request); // Reference to an HTTP request. writable('socket', socket); // Reference to the transformer's socket writable('writable', true); // Silly stream compatibility. writable('readable', true); // Silly stream compatibility. writable('queue', []); // Data queue for data events. writable('query', query); // The query string. writable('ultron', new Ultron(this)); // Our event listening cleanup. writable('alive', true); // Flag used to detect zombie sparks. // // Parse our query string. // if ('string' === typeof this.query) { this.query = parse(this.query); } this.__initialise.forEach(function execute(initialise) { initialise.call(spark); }); }
[ "function", "Spark", "(", "primus", ",", "headers", ",", "address", ",", "query", ",", "id", ",", "request", ",", "socket", ")", "{", "this", ".", "fuse", "(", ")", ";", "var", "writable", "=", "this", ".", "writable", ",", "spark", "=", "this", ",", "idgen", "=", "primus", ".", "options", ".", "idGenerator", ";", "query", "=", "query", "||", "{", "}", ";", "id", "=", "idgen", "?", "idgen", "(", ")", ":", "(", "id", "||", "nanoid", "(", ")", ")", ";", "headers", "=", "headers", "||", "{", "}", ";", "address", "=", "address", "||", "{", "}", ";", "request", "=", "request", "||", "headers", "[", "'primus::req::backup'", "]", ";", "writable", "(", "'id'", ",", "id", ")", ";", "// Unique id for socket.", "writable", "(", "'primus'", ",", "primus", ")", ";", "// References to Primus.", "writable", "(", "'remote'", ",", "address", ")", ";", "// The remote address location.", "writable", "(", "'headers'", ",", "headers", ")", ";", "// The request headers.", "writable", "(", "'request'", ",", "request", ")", ";", "// Reference to an HTTP request.", "writable", "(", "'socket'", ",", "socket", ")", ";", "// Reference to the transformer's socket", "writable", "(", "'writable'", ",", "true", ")", ";", "// Silly stream compatibility.", "writable", "(", "'readable'", ",", "true", ")", ";", "// Silly stream compatibility.", "writable", "(", "'queue'", ",", "[", "]", ")", ";", "// Data queue for data events.", "writable", "(", "'query'", ",", "query", ")", ";", "// The query string.", "writable", "(", "'ultron'", ",", "new", "Ultron", "(", "this", ")", ")", ";", "// Our event listening cleanup.", "writable", "(", "'alive'", ",", "true", ")", ";", "// Flag used to detect zombie sparks.", "//", "// Parse our query string.", "//", "if", "(", "'string'", "===", "typeof", "this", ".", "query", ")", "{", "this", ".", "query", "=", "parse", "(", "this", ".", "query", ")", ";", "}", "this", ".", "__initialise", ".", "forEach", "(", "function", "execute", "(", "initialise", ")", "{", "initialise", ".", "call", "(", "spark", ")", ";", "}", ")", ";", "}" ]
The Spark is an indefinable, indescribable energy or soul of a transformer which can be used to create new transformers. In our case, it's a simple wrapping interface. @constructor @param {Primus} primus Reference to the Primus server. (Set using .bind) @param {Object} headers The request headers for this connection. @param {Object} address The object that holds the remoteAddress and port. @param {Object} query The query string of request. @param {String} id An optional id of the socket, or we will generate one. @param {Request} request The HTTP Request instance that initialised the spark. @param {Mixed} socket Reference to the transformer socket. @api public
[ "The", "Spark", "is", "an", "indefinable", "indescribable", "energy", "or", "soul", "of", "a", "transformer", "which", "can", "be", "used", "to", "create", "new", "transformers", ".", "In", "our", "case", "it", "s", "a", "simple", "wrapping", "interface", "." ]
7d58d8ebeeed89d7f759ff6c5dfe026deba9666e
https://github.com/primus/primus/blob/7d58d8ebeeed89d7f759ff6c5dfe026deba9666e/spark.js#L28-L64
12,143
primus/primus
transformers/sockjs/library.js
resolve
function resolve(relative, base) { var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/')) , i = path.length , last = path[i - 1] , unshift = false , up = 0; while (i--) { if (path[i] === '.') { path.splice(i, 1); } else if (path[i] === '..') { path.splice(i, 1); up++; } else if (up) { if (i === 0) unshift = true; path.splice(i, 1); up--; } } if (unshift) path.unshift(''); if (last === '.' || last === '..') path.push(''); return path.join('/'); }
javascript
function resolve(relative, base) { var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/')) , i = path.length , last = path[i - 1] , unshift = false , up = 0; while (i--) { if (path[i] === '.') { path.splice(i, 1); } else if (path[i] === '..') { path.splice(i, 1); up++; } else if (up) { if (i === 0) unshift = true; path.splice(i, 1); up--; } } if (unshift) path.unshift(''); if (last === '.' || last === '..') path.push(''); return path.join('/'); }
[ "function", "resolve", "(", "relative", ",", "base", ")", "{", "var", "path", "=", "(", "base", "||", "'/'", ")", ".", "split", "(", "'/'", ")", ".", "slice", "(", "0", ",", "-", "1", ")", ".", "concat", "(", "relative", ".", "split", "(", "'/'", ")", ")", ",", "i", "=", "path", ".", "length", ",", "last", "=", "path", "[", "i", "-", "1", "]", ",", "unshift", "=", "false", ",", "up", "=", "0", ";", "while", "(", "i", "--", ")", "{", "if", "(", "path", "[", "i", "]", "===", "'.'", ")", "{", "path", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "else", "if", "(", "path", "[", "i", "]", "===", "'..'", ")", "{", "path", ".", "splice", "(", "i", ",", "1", ")", ";", "up", "++", ";", "}", "else", "if", "(", "up", ")", "{", "if", "(", "i", "===", "0", ")", "unshift", "=", "true", ";", "path", ".", "splice", "(", "i", ",", "1", ")", ";", "up", "--", ";", "}", "}", "if", "(", "unshift", ")", "path", ".", "unshift", "(", "''", ")", ";", "if", "(", "last", "===", "'.'", "||", "last", "===", "'..'", ")", "path", ".", "push", "(", "''", ")", ";", "return", "path", ".", "join", "(", "'/'", ")", ";", "}" ]
Resolve a relative URL pathname against a base URL pathname. @param {String} relative Pathname of the relative URL. @param {String} base Pathname of the base URL. @return {String} Resolved pathname. @private
[ "Resolve", "a", "relative", "URL", "pathname", "against", "a", "base", "URL", "pathname", "." ]
7d58d8ebeeed89d7f759ff6c5dfe026deba9666e
https://github.com/primus/primus/blob/7d58d8ebeeed89d7f759ff6c5dfe026deba9666e/transformers/sockjs/library.js#L4571-L4595
12,144
primus/primus
transformers/sockjs/library.js
set
function set(part, value, fn) { var url = this; switch (part) { case 'query': if ('string' === typeof value && value.length) { value = (fn || qs.parse)(value); } url[part] = value; break; case 'port': url[part] = value; if (!required(value, url.protocol)) { url.host = url.hostname; url[part] = ''; } else if (value) { url.host = url.hostname +':'+ value; } break; case 'hostname': url[part] = value; if (url.port) value += ':'+ url.port; url.host = value; break; case 'host': url[part] = value; if (/:\d+$/.test(value)) { value = value.split(':'); url.port = value.pop(); url.hostname = value.join(':'); } else { url.hostname = value; url.port = ''; } break; case 'protocol': url.protocol = value.toLowerCase(); url.slashes = !fn; break; case 'pathname': case 'hash': if (value) { var char = part === 'pathname' ? '/' : '#'; url[part] = value.charAt(0) !== char ? char + value : value; } else { url[part] = value; } break; default: url[part] = value; } for (var i = 0; i < rules.length; i++) { var ins = rules[i]; if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase(); } url.origin = url.protocol && url.host && url.protocol !== 'file:' ? url.protocol +'//'+ url.host : 'null'; url.href = url.toString(); return url; }
javascript
function set(part, value, fn) { var url = this; switch (part) { case 'query': if ('string' === typeof value && value.length) { value = (fn || qs.parse)(value); } url[part] = value; break; case 'port': url[part] = value; if (!required(value, url.protocol)) { url.host = url.hostname; url[part] = ''; } else if (value) { url.host = url.hostname +':'+ value; } break; case 'hostname': url[part] = value; if (url.port) value += ':'+ url.port; url.host = value; break; case 'host': url[part] = value; if (/:\d+$/.test(value)) { value = value.split(':'); url.port = value.pop(); url.hostname = value.join(':'); } else { url.hostname = value; url.port = ''; } break; case 'protocol': url.protocol = value.toLowerCase(); url.slashes = !fn; break; case 'pathname': case 'hash': if (value) { var char = part === 'pathname' ? '/' : '#'; url[part] = value.charAt(0) !== char ? char + value : value; } else { url[part] = value; } break; default: url[part] = value; } for (var i = 0; i < rules.length; i++) { var ins = rules[i]; if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase(); } url.origin = url.protocol && url.host && url.protocol !== 'file:' ? url.protocol +'//'+ url.host : 'null'; url.href = url.toString(); return url; }
[ "function", "set", "(", "part", ",", "value", ",", "fn", ")", "{", "var", "url", "=", "this", ";", "switch", "(", "part", ")", "{", "case", "'query'", ":", "if", "(", "'string'", "===", "typeof", "value", "&&", "value", ".", "length", ")", "{", "value", "=", "(", "fn", "||", "qs", ".", "parse", ")", "(", "value", ")", ";", "}", "url", "[", "part", "]", "=", "value", ";", "break", ";", "case", "'port'", ":", "url", "[", "part", "]", "=", "value", ";", "if", "(", "!", "required", "(", "value", ",", "url", ".", "protocol", ")", ")", "{", "url", ".", "host", "=", "url", ".", "hostname", ";", "url", "[", "part", "]", "=", "''", ";", "}", "else", "if", "(", "value", ")", "{", "url", ".", "host", "=", "url", ".", "hostname", "+", "':'", "+", "value", ";", "}", "break", ";", "case", "'hostname'", ":", "url", "[", "part", "]", "=", "value", ";", "if", "(", "url", ".", "port", ")", "value", "+=", "':'", "+", "url", ".", "port", ";", "url", ".", "host", "=", "value", ";", "break", ";", "case", "'host'", ":", "url", "[", "part", "]", "=", "value", ";", "if", "(", "/", ":\\d+$", "/", ".", "test", "(", "value", ")", ")", "{", "value", "=", "value", ".", "split", "(", "':'", ")", ";", "url", ".", "port", "=", "value", ".", "pop", "(", ")", ";", "url", ".", "hostname", "=", "value", ".", "join", "(", "':'", ")", ";", "}", "else", "{", "url", ".", "hostname", "=", "value", ";", "url", ".", "port", "=", "''", ";", "}", "break", ";", "case", "'protocol'", ":", "url", ".", "protocol", "=", "value", ".", "toLowerCase", "(", ")", ";", "url", ".", "slashes", "=", "!", "fn", ";", "break", ";", "case", "'pathname'", ":", "case", "'hash'", ":", "if", "(", "value", ")", "{", "var", "char", "=", "part", "===", "'pathname'", "?", "'/'", ":", "'#'", ";", "url", "[", "part", "]", "=", "value", ".", "charAt", "(", "0", ")", "!==", "char", "?", "char", "+", "value", ":", "value", ";", "}", "else", "{", "url", "[", "part", "]", "=", "value", ";", "}", "break", ";", "default", ":", "url", "[", "part", "]", "=", "value", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "rules", ".", "length", ";", "i", "++", ")", "{", "var", "ins", "=", "rules", "[", "i", "]", ";", "if", "(", "ins", "[", "4", "]", ")", "url", "[", "ins", "[", "1", "]", "]", "=", "url", "[", "ins", "[", "1", "]", "]", ".", "toLowerCase", "(", ")", ";", "}", "url", ".", "origin", "=", "url", ".", "protocol", "&&", "url", ".", "host", "&&", "url", ".", "protocol", "!==", "'file:'", "?", "url", ".", "protocol", "+", "'//'", "+", "url", ".", "host", ":", "'null'", ";", "url", ".", "href", "=", "url", ".", "toString", "(", ")", ";", "return", "url", ";", "}" ]
This is convenience method for changing properties in the URL instance to insure that they all propagate correctly. @param {String} part Property we need to adjust. @param {Mixed} value The newly assigned value. @param {Boolean|Function} fn When setting the query, it will be the function used to parse the query. When setting the protocol, double slash will be removed from the final url if it is true. @returns {URL} URL instance for chaining. @public
[ "This", "is", "convenience", "method", "for", "changing", "properties", "in", "the", "URL", "instance", "to", "insure", "that", "they", "all", "propagate", "correctly", "." ]
7d58d8ebeeed89d7f759ff6c5dfe026deba9666e
https://github.com/primus/primus/blob/7d58d8ebeeed89d7f759ff6c5dfe026deba9666e/transformers/sockjs/library.js#L4758-L4835
12,145
primus/primus
errors.js
PrimusError
function PrimusError(message, logger) { Error.captureStackTrace(this, this.constructor); this.message = message; this.name = this.constructor.name; if (logger) { logger.emit('log', 'error', this); } }
javascript
function PrimusError(message, logger) { Error.captureStackTrace(this, this.constructor); this.message = message; this.name = this.constructor.name; if (logger) { logger.emit('log', 'error', this); } }
[ "function", "PrimusError", "(", "message", ",", "logger", ")", "{", "Error", ".", "captureStackTrace", "(", "this", ",", "this", ".", "constructor", ")", ";", "this", ".", "message", "=", "message", ";", "this", ".", "name", "=", "this", ".", "constructor", ".", "name", ";", "if", "(", "logger", ")", "{", "logger", ".", "emit", "(", "'log'", ",", "'error'", ",", "this", ")", ";", "}", "}" ]
Generic Primus error. @constructor @param {String} message The reason for the error @param {EventEmitter} logger Optional EventEmitter to emit a `log` event on. @api public
[ "Generic", "Primus", "error", "." ]
7d58d8ebeeed89d7f759ff6c5dfe026deba9666e
https://github.com/primus/primus/blob/7d58d8ebeeed89d7f759ff6c5dfe026deba9666e/errors.js#L13-L22
12,146
primus/primus
errors.js
ParserError
function ParserError(message, spark) { Error.captureStackTrace(this, this.constructor); this.message = message; this.name = this.constructor.name; if (spark) { if (spark.listeners('error').length) spark.emit('error', this); spark.primus.emit('log', 'error', this); } }
javascript
function ParserError(message, spark) { Error.captureStackTrace(this, this.constructor); this.message = message; this.name = this.constructor.name; if (spark) { if (spark.listeners('error').length) spark.emit('error', this); spark.primus.emit('log', 'error', this); } }
[ "function", "ParserError", "(", "message", ",", "spark", ")", "{", "Error", ".", "captureStackTrace", "(", "this", ",", "this", ".", "constructor", ")", ";", "this", ".", "message", "=", "message", ";", "this", ".", "name", "=", "this", ".", "constructor", ".", "name", ";", "if", "(", "spark", ")", "{", "if", "(", "spark", ".", "listeners", "(", "'error'", ")", ".", "length", ")", "spark", ".", "emit", "(", "'error'", ",", "this", ")", ";", "spark", ".", "primus", ".", "emit", "(", "'log'", ",", "'error'", ",", "this", ")", ";", "}", "}" ]
There was an error while parsing incoming or outgoing data. @param {String} message The reason for the error. @param {Spark} spark The spark that caused the error. @api public
[ "There", "was", "an", "error", "while", "parsing", "incoming", "or", "outgoing", "data", "." ]
7d58d8ebeeed89d7f759ff6c5dfe026deba9666e
https://github.com/primus/primus/blob/7d58d8ebeeed89d7f759ff6c5dfe026deba9666e/errors.js#L33-L43
12,147
primus/primus
transformers/engine.io/library.js
encodeArrayBuffer
function encodeArrayBuffer(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } var data = packet.data; var contentArray = new Uint8Array(data); var resultBuffer = new Uint8Array(1 + data.byteLength); resultBuffer[0] = packets[packet.type]; for (var i = 0; i < contentArray.length; i++) { resultBuffer[i+1] = contentArray[i]; } return callback(resultBuffer.buffer); }
javascript
function encodeArrayBuffer(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } var data = packet.data; var contentArray = new Uint8Array(data); var resultBuffer = new Uint8Array(1 + data.byteLength); resultBuffer[0] = packets[packet.type]; for (var i = 0; i < contentArray.length; i++) { resultBuffer[i+1] = contentArray[i]; } return callback(resultBuffer.buffer); }
[ "function", "encodeArrayBuffer", "(", "packet", ",", "supportsBinary", ",", "callback", ")", "{", "if", "(", "!", "supportsBinary", ")", "{", "return", "exports", ".", "encodeBase64Packet", "(", "packet", ",", "callback", ")", ";", "}", "var", "data", "=", "packet", ".", "data", ";", "var", "contentArray", "=", "new", "Uint8Array", "(", "data", ")", ";", "var", "resultBuffer", "=", "new", "Uint8Array", "(", "1", "+", "data", ".", "byteLength", ")", ";", "resultBuffer", "[", "0", "]", "=", "packets", "[", "packet", ".", "type", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "contentArray", ".", "length", ";", "i", "++", ")", "{", "resultBuffer", "[", "i", "+", "1", "]", "=", "contentArray", "[", "i", "]", ";", "}", "return", "callback", "(", "resultBuffer", ".", "buffer", ")", ";", "}" ]
Encode packet helpers for binary types
[ "Encode", "packet", "helpers", "for", "binary", "types" ]
7d58d8ebeeed89d7f759ff6c5dfe026deba9666e
https://github.com/primus/primus/blob/7d58d8ebeeed89d7f759ff6c5dfe026deba9666e/transformers/engine.io/library.js#L2616-L2631
12,148
primus/primus
transformers/engine.io/library.js
encode
function encode(num) { var encoded = ''; do { encoded = alphabet[num % length] + encoded; num = Math.floor(num / length); } while (num > 0); return encoded; }
javascript
function encode(num) { var encoded = ''; do { encoded = alphabet[num % length] + encoded; num = Math.floor(num / length); } while (num > 0); return encoded; }
[ "function", "encode", "(", "num", ")", "{", "var", "encoded", "=", "''", ";", "do", "{", "encoded", "=", "alphabet", "[", "num", "%", "length", "]", "+", "encoded", ";", "num", "=", "Math", ".", "floor", "(", "num", "/", "length", ")", ";", "}", "while", "(", "num", ">", "0", ")", ";", "return", "encoded", ";", "}" ]
Return a string representing the specified number. @param {Number} num The number to convert. @returns {String} The string representation of the number. @api public
[ "Return", "a", "string", "representing", "the", "specified", "number", "." ]
7d58d8ebeeed89d7f759ff6c5dfe026deba9666e
https://github.com/primus/primus/blob/7d58d8ebeeed89d7f759ff6c5dfe026deba9666e/transformers/engine.io/library.js#L3623-L3632
12,149
primus/primus
transformers/engine.io/library.js
decode
function decode(str) { var decoded = 0; for (i = 0; i < str.length; i++) { decoded = decoded * length + map[str.charAt(i)]; } return decoded; }
javascript
function decode(str) { var decoded = 0; for (i = 0; i < str.length; i++) { decoded = decoded * length + map[str.charAt(i)]; } return decoded; }
[ "function", "decode", "(", "str", ")", "{", "var", "decoded", "=", "0", ";", "for", "(", "i", "=", "0", ";", "i", "<", "str", ".", "length", ";", "i", "++", ")", "{", "decoded", "=", "decoded", "*", "length", "+", "map", "[", "str", ".", "charAt", "(", "i", ")", "]", ";", "}", "return", "decoded", ";", "}" ]
Return the integer value specified by the given string. @param {String} str The string to convert. @returns {Number} The integer value represented by the string. @api public
[ "Return", "the", "integer", "value", "specified", "by", "the", "given", "string", "." ]
7d58d8ebeeed89d7f759ff6c5dfe026deba9666e
https://github.com/primus/primus/blob/7d58d8ebeeed89d7f759ff6c5dfe026deba9666e/transformers/engine.io/library.js#L3641-L3649
12,150
primus/primus
transformers/sockjs/update_tools/stripify.js
stripify
function stripify(file) { if (/\.json$/.test(file)) return through(); var code = ''; function transform(chunk, encoding, next) { code += chunk; next(); } function flush(done) { /* jshint validthis: true */ var ast = rocambole.parse(code); code = rocambole.moonwalk(ast, function strip(node) { if (( // var debug = function() {}; 'VariableDeclaration' === node.type && 'debug' === node.declarations[0].id.name ) || ( // if (process.env.NODE_ENV !== 'production') { debug = ... } 'IfStatement' === node.type && 'BinaryExpression' === node.test.type && 'production' === node.test.right.value ) || ( // debug( ... ); 'ExpressionStatement' === node.type && 'CallExpression' === node.expression.type && 'debug' === node.expression.callee.name )) { return remove(node); } }); this.push(code.toString()); done(); } return through(transform, flush); }
javascript
function stripify(file) { if (/\.json$/.test(file)) return through(); var code = ''; function transform(chunk, encoding, next) { code += chunk; next(); } function flush(done) { /* jshint validthis: true */ var ast = rocambole.parse(code); code = rocambole.moonwalk(ast, function strip(node) { if (( // var debug = function() {}; 'VariableDeclaration' === node.type && 'debug' === node.declarations[0].id.name ) || ( // if (process.env.NODE_ENV !== 'production') { debug = ... } 'IfStatement' === node.type && 'BinaryExpression' === node.test.type && 'production' === node.test.right.value ) || ( // debug( ... ); 'ExpressionStatement' === node.type && 'CallExpression' === node.expression.type && 'debug' === node.expression.callee.name )) { return remove(node); } }); this.push(code.toString()); done(); } return through(transform, flush); }
[ "function", "stripify", "(", "file", ")", "{", "if", "(", "/", "\\.json$", "/", ".", "test", "(", "file", ")", ")", "return", "through", "(", ")", ";", "var", "code", "=", "''", ";", "function", "transform", "(", "chunk", ",", "encoding", ",", "next", ")", "{", "code", "+=", "chunk", ";", "next", "(", ")", ";", "}", "function", "flush", "(", "done", ")", "{", "/* jshint validthis: true */", "var", "ast", "=", "rocambole", ".", "parse", "(", "code", ")", ";", "code", "=", "rocambole", ".", "moonwalk", "(", "ast", ",", "function", "strip", "(", "node", ")", "{", "if", "(", "(", "// var debug = function() {};", "'VariableDeclaration'", "===", "node", ".", "type", "&&", "'debug'", "===", "node", ".", "declarations", "[", "0", "]", ".", "id", ".", "name", ")", "||", "(", "// if (process.env.NODE_ENV !== 'production') { debug = ... }", "'IfStatement'", "===", "node", ".", "type", "&&", "'BinaryExpression'", "===", "node", ".", "test", ".", "type", "&&", "'production'", "===", "node", ".", "test", ".", "right", ".", "value", ")", "||", "(", "// debug( ... );", "'ExpressionStatement'", "===", "node", ".", "type", "&&", "'CallExpression'", "===", "node", ".", "expression", ".", "type", "&&", "'debug'", "===", "node", ".", "expression", ".", "callee", ".", "name", ")", ")", "{", "return", "remove", "(", "node", ")", ";", "}", "}", ")", ";", "this", ".", "push", "(", "code", ".", "toString", "(", ")", ")", ";", "done", "(", ")", ";", "}", "return", "through", "(", "transform", ",", "flush", ")", ";", "}" ]
Browserify transform to remove all debug statements. @param {String} file File name @returns {Stream} Transform stream @api public
[ "Browserify", "transform", "to", "remove", "all", "debug", "statements", "." ]
7d58d8ebeeed89d7f759ff6c5dfe026deba9666e
https://github.com/primus/primus/blob/7d58d8ebeeed89d7f759ff6c5dfe026deba9666e/transformers/sockjs/update_tools/stripify.js#L19-L55
12,151
primus/primus
middleware/spec.js
spec
function spec(req, res) { if (req.uri.pathname !== specification) return; res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(primus.spec)); return true; }
javascript
function spec(req, res) { if (req.uri.pathname !== specification) return; res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(primus.spec)); return true; }
[ "function", "spec", "(", "req", ",", "res", ")", "{", "if", "(", "req", ".", "uri", ".", "pathname", "!==", "specification", ")", "return", ";", "res", ".", "statusCode", "=", "200", ";", "res", ".", "setHeader", "(", "'Content-Type'", ",", "'application/json'", ")", ";", "res", ".", "end", "(", "JSON", ".", "stringify", "(", "primus", ".", "spec", ")", ")", ";", "return", "true", ";", "}" ]
The actual HTTP middleware. @param {Request} req HTTP request. @param {Response} res HTTP response. @api private
[ "The", "actual", "HTTP", "middleware", "." ]
7d58d8ebeeed89d7f759ff6c5dfe026deba9666e
https://github.com/primus/primus/blob/7d58d8ebeeed89d7f759ff6c5dfe026deba9666e/middleware/spec.js#L20-L28
12,152
yeojz/otplib
packages/otplib-utils/padSecret.js
padSecret
function padSecret(secretBuffer, size, encoding) { const secret = secretBuffer.toString(encoding); const len = secret.length; if (size && len < size) { const newSecret = new Array(size - len + 1).join( secretBuffer.toString('hex') ); return Buffer.from(newSecret, 'hex').slice(0, size); } return secretBuffer; }
javascript
function padSecret(secretBuffer, size, encoding) { const secret = secretBuffer.toString(encoding); const len = secret.length; if (size && len < size) { const newSecret = new Array(size - len + 1).join( secretBuffer.toString('hex') ); return Buffer.from(newSecret, 'hex').slice(0, size); } return secretBuffer; }
[ "function", "padSecret", "(", "secretBuffer", ",", "size", ",", "encoding", ")", "{", "const", "secret", "=", "secretBuffer", ".", "toString", "(", "encoding", ")", ";", "const", "len", "=", "secret", ".", "length", ";", "if", "(", "size", "&&", "len", "<", "size", ")", "{", "const", "newSecret", "=", "new", "Array", "(", "size", "-", "len", "+", "1", ")", ".", "join", "(", "secretBuffer", ".", "toString", "(", "'hex'", ")", ")", ";", "return", "Buffer", ".", "from", "(", "newSecret", ",", "'hex'", ")", ".", "slice", "(", "0", ",", "size", ")", ";", "}", "return", "secretBuffer", ";", "}" ]
Padding of secret to a certain buffer size. @module otplib-utils/padSecret @param {Buffer} secretBuffer - a buffer representation of your secret. @param {number} size - number of bytes your secret should be. @param {string} encoding - the encoding of secret @return {Buffer}
[ "Padding", "of", "secret", "to", "a", "certain", "buffer", "size", "." ]
f81a4f11d63b3f00545c60bcef6543cdec2ddc0e
https://github.com/yeojz/otplib/blob/f81a4f11d63b3f00545c60bcef6543cdec2ddc0e/packages/otplib-utils/padSecret.js#L10-L22
12,153
yeojz/otplib
examples/cli.js
getCommandLineOptions
function getCommandLineOptions() { return process.argv .slice(2) .map(arg => arg.split('=')) .reduce((accum, arg) => { const key = arg[0].replace('--', ''); // if secret, do not put in config if (key === 'secret') { secret = arg[1]; return accum; } // If provided key is not encoded, encode it first // do not put in config if (key === 'privatekey') { secret = otplib.authenticator.encode(arg[1]); return accum; } if (key === 'step' || key === 'epoch') { accum[key] = parseInt(arg[1], 10); return accum; } return accum; }, {}); }
javascript
function getCommandLineOptions() { return process.argv .slice(2) .map(arg => arg.split('=')) .reduce((accum, arg) => { const key = arg[0].replace('--', ''); // if secret, do not put in config if (key === 'secret') { secret = arg[1]; return accum; } // If provided key is not encoded, encode it first // do not put in config if (key === 'privatekey') { secret = otplib.authenticator.encode(arg[1]); return accum; } if (key === 'step' || key === 'epoch') { accum[key] = parseInt(arg[1], 10); return accum; } return accum; }, {}); }
[ "function", "getCommandLineOptions", "(", ")", "{", "return", "process", ".", "argv", ".", "slice", "(", "2", ")", ".", "map", "(", "arg", "=>", "arg", ".", "split", "(", "'='", ")", ")", ".", "reduce", "(", "(", "accum", ",", "arg", ")", "=>", "{", "const", "key", "=", "arg", "[", "0", "]", ".", "replace", "(", "'--'", ",", "''", ")", ";", "// if secret, do not put in config", "if", "(", "key", "===", "'secret'", ")", "{", "secret", "=", "arg", "[", "1", "]", ";", "return", "accum", ";", "}", "// If provided key is not encoded, encode it first", "// do not put in config", "if", "(", "key", "===", "'privatekey'", ")", "{", "secret", "=", "otplib", ".", "authenticator", ".", "encode", "(", "arg", "[", "1", "]", ")", ";", "return", "accum", ";", "}", "if", "(", "key", "===", "'step'", "||", "key", "===", "'epoch'", ")", "{", "accum", "[", "key", "]", "=", "parseInt", "(", "arg", "[", "1", "]", ",", "10", ")", ";", "return", "accum", ";", "}", "return", "accum", ";", "}", ",", "{", "}", ")", ";", "}" ]
Parse and prepare CLI values
[ "Parse", "and", "prepare", "CLI", "values" ]
f81a4f11d63b3f00545c60bcef6543cdec2ddc0e
https://github.com/yeojz/otplib/blob/f81a4f11d63b3f00545c60bcef6543cdec2ddc0e/examples/cli.js#L20-L47
12,154
yeojz/otplib
packages/otplib-core/totpCheckWithWindow.js
totpCheckWithWindow
function totpCheckWithWindow(token, secret, options) { let opt = Object.assign({}, options); const bounds = getWindowBounds(opt); const checker = createChecker(token, secret, opt); const backward = checker(-1, 0, bounds[0]); return backward !== null ? backward : checker(1, 1, bounds[1]); }
javascript
function totpCheckWithWindow(token, secret, options) { let opt = Object.assign({}, options); const bounds = getWindowBounds(opt); const checker = createChecker(token, secret, opt); const backward = checker(-1, 0, bounds[0]); return backward !== null ? backward : checker(1, 1, bounds[1]); }
[ "function", "totpCheckWithWindow", "(", "token", ",", "secret", ",", "options", ")", "{", "let", "opt", "=", "Object", ".", "assign", "(", "{", "}", ",", "options", ")", ";", "const", "bounds", "=", "getWindowBounds", "(", "opt", ")", ";", "const", "checker", "=", "createChecker", "(", "token", ",", "secret", ",", "opt", ")", ";", "const", "backward", "=", "checker", "(", "-", "1", ",", "0", ",", "bounds", "[", "0", "]", ")", ";", "return", "backward", "!==", "null", "?", "backward", ":", "checker", "(", "1", ",", "1", ",", "bounds", "[", "1", "]", ")", ";", "}" ]
Checks the provided OTP token against system generated token with support for checking previous or future x time-step windows @module otplib-core/totpCheckWithWindow @param {string} token - the OTP token to check @param {string} secret - your secret that is used to generate the token @param {object} options - options which was used to generate it originally @return {integer | null} - the number of windows back (eg: -1) or forward if it was successful. null otherwise
[ "Checks", "the", "provided", "OTP", "token", "against", "system", "generated", "token", "with", "support", "for", "checking", "previous", "or", "future", "x", "time", "-", "step", "windows" ]
f81a4f11d63b3f00545c60bcef6543cdec2ddc0e
https://github.com/yeojz/otplib/blob/f81a4f11d63b3f00545c60bcef6543cdec2ddc0e/packages/otplib-core/totpCheckWithWindow.js#L43-L50
12,155
yeojz/otplib
packages/otplib-utils/secretKey.js
secretKey
function secretKey(length, options = {}) { if (!length || length < 1) { return ''; } if (!options.crypto || typeof options.crypto.randomBytes !== 'function') { throw new Error('Expecting options.crypto to have a randomBytes function'); } return options.crypto .randomBytes(length) .toString('base64') // convert format .slice(0, length); // return required number of characters }
javascript
function secretKey(length, options = {}) { if (!length || length < 1) { return ''; } if (!options.crypto || typeof options.crypto.randomBytes !== 'function') { throw new Error('Expecting options.crypto to have a randomBytes function'); } return options.crypto .randomBytes(length) .toString('base64') // convert format .slice(0, length); // return required number of characters }
[ "function", "secretKey", "(", "length", ",", "options", "=", "{", "}", ")", "{", "if", "(", "!", "length", "||", "length", "<", "1", ")", "{", "return", "''", ";", "}", "if", "(", "!", "options", ".", "crypto", "||", "typeof", "options", ".", "crypto", ".", "randomBytes", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "'Expecting options.crypto to have a randomBytes function'", ")", ";", "}", "return", "options", ".", "crypto", ".", "randomBytes", "(", "length", ")", ".", "toString", "(", "'base64'", ")", "// convert format", ".", "slice", "(", "0", ",", "length", ")", ";", "// return required number of characters", "}" ]
Naive secret key generation tool @module otplib-utils/secretKey @param {integer} length - the key length @param {string} format - any format supported by node's `crypto` @return {string}
[ "Naive", "secret", "key", "generation", "tool" ]
f81a4f11d63b3f00545c60bcef6543cdec2ddc0e
https://github.com/yeojz/otplib/blob/f81a4f11d63b3f00545c60bcef6543cdec2ddc0e/packages/otplib-utils/secretKey.js#L10-L23
12,156
yeojz/otplib
packages/otplib-core/hotpSecret.js
hotpSecret
function hotpSecret(secret, options) { if (typeof options.encoding !== 'string') { throw new Error('Expecting options.encoding to be a string'); } return Buffer.from(secret, options.encoding); }
javascript
function hotpSecret(secret, options) { if (typeof options.encoding !== 'string') { throw new Error('Expecting options.encoding to be a string'); } return Buffer.from(secret, options.encoding); }
[ "function", "hotpSecret", "(", "secret", ",", "options", ")", "{", "if", "(", "typeof", "options", ".", "encoding", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'Expecting options.encoding to be a string'", ")", ";", "}", "return", "Buffer", ".", "from", "(", "secret", ",", "options", ".", "encoding", ")", ";", "}" ]
Conversion of secret to buffer for HOTP @module otplib-core/hotpSecret @param {string} secret - your secret that is used to generate the token @param {string} options.encoding - the encoding of secret @return {object}
[ "Conversion", "of", "secret", "to", "buffer", "for", "HOTP" ]
f81a4f11d63b3f00545c60bcef6543cdec2ddc0e
https://github.com/yeojz/otplib/blob/f81a4f11d63b3f00545c60bcef6543cdec2ddc0e/packages/otplib-core/hotpSecret.js#L9-L15
12,157
yeojz/otplib
packages/otplib-utils/isSameToken.js
isSameToken
function isSameToken(token1, token2) { if (isValidToken(token1) && isValidToken(token2)) { return String(token1) === String(token2); } return false; }
javascript
function isSameToken(token1, token2) { if (isValidToken(token1) && isValidToken(token2)) { return String(token1) === String(token2); } return false; }
[ "function", "isSameToken", "(", "token1", ",", "token2", ")", "{", "if", "(", "isValidToken", "(", "token1", ")", "&&", "isValidToken", "(", "token2", ")", ")", "{", "return", "String", "(", "token1", ")", "===", "String", "(", "token2", ")", ";", "}", "return", "false", ";", "}" ]
Simple comparison of 2 tokens @module otplib-utils/isSameToken @param {string | number} token1 - base value @param {string | number} token2 - value to compare @return {boolean}
[ "Simple", "comparison", "of", "2", "tokens" ]
f81a4f11d63b3f00545c60bcef6543cdec2ddc0e
https://github.com/yeojz/otplib/blob/f81a4f11d63b3f00545c60bcef6543cdec2ddc0e/packages/otplib-utils/isSameToken.js#L13-L19
12,158
yeojz/otplib
packages/otplib-core/hotpOptions.js
hotpOptions
function hotpOptions(options = {}) { return Object.assign( { algorithm: 'sha1', createHmacSecret: hotpSecret, crypto: null, digits: 6, encoding: 'ascii' }, options ); }
javascript
function hotpOptions(options = {}) { return Object.assign( { algorithm: 'sha1', createHmacSecret: hotpSecret, crypto: null, digits: 6, encoding: 'ascii' }, options ); }
[ "function", "hotpOptions", "(", "options", "=", "{", "}", ")", "{", "return", "Object", ".", "assign", "(", "{", "algorithm", ":", "'sha1'", ",", "createHmacSecret", ":", "hotpSecret", ",", "crypto", ":", "null", ",", "digits", ":", "6", ",", "encoding", ":", "'ascii'", "}", ",", "options", ")", ";", "}" ]
Generates options for HOTP @module otplib-core/hotpOptions @param {number} options.digits - the output token length @param {string} options.encoding - the encoding of secret @return {object}
[ "Generates", "options", "for", "HOTP" ]
f81a4f11d63b3f00545c60bcef6543cdec2ddc0e
https://github.com/yeojz/otplib/blob/f81a4f11d63b3f00545c60bcef6543cdec2ddc0e/packages/otplib-core/hotpOptions.js#L11-L22
12,159
yeojz/otplib
packages/otplib-core/totpOptions.js
totpOptions
function totpOptions(options = {}) { let opt = Object.assign(hotpOptions(), defaultOptions, options); opt.epoch = typeof opt.epoch === 'number' ? opt.epoch * 1000 : Date.now(); return opt; }
javascript
function totpOptions(options = {}) { let opt = Object.assign(hotpOptions(), defaultOptions, options); opt.epoch = typeof opt.epoch === 'number' ? opt.epoch * 1000 : Date.now(); return opt; }
[ "function", "totpOptions", "(", "options", "=", "{", "}", ")", "{", "let", "opt", "=", "Object", ".", "assign", "(", "hotpOptions", "(", ")", ",", "defaultOptions", ",", "options", ")", ";", "opt", ".", "epoch", "=", "typeof", "opt", ".", "epoch", "===", "'number'", "?", "opt", ".", "epoch", "*", "1000", ":", "Date", ".", "now", "(", ")", ";", "return", "opt", ";", "}" ]
Generates options for TOTP @module otplib-core/totpOptions @param {number} options.digits - the output token length @param {string} options.epoch - starting time since the UNIX epoch (seconds) @param {number} options.step - time step (seconds) @param {number|array} options.window - acceptable window where codes a valid. @return {object}
[ "Generates", "options", "for", "TOTP" ]
f81a4f11d63b3f00545c60bcef6543cdec2ddc0e
https://github.com/yeojz/otplib/blob/f81a4f11d63b3f00545c60bcef6543cdec2ddc0e/packages/otplib-core/totpOptions.js#L21-L26
12,160
yeojz/otplib
packages/otplib-core/hotpDigest.js
hotpDigest
function hotpDigest(secret, counter, options) { if (!options.crypto || typeof options.crypto.createHmac !== 'function') { throw new Error('Expecting options.crypto to have a createHmac function'); } if (typeof options.createHmacSecret !== 'function') { throw new Error('Expecting options.createHmacSecret to be a function'); } if (typeof options.algorithm !== 'string') { throw new Error('Expecting options.algorithm to be a string'); } // Convert secret to encoding for hmacSecret const hmacSecret = options.createHmacSecret(secret, { algorithm: options.algorithm, encoding: options.encoding }); // Ensure counter is a buffer or string (for HMAC creation) const hexCounter = hotpCounter(counter); // HMAC creation const cryptoHmac = options.crypto.createHmac(options.algorithm, hmacSecret); // Update HMAC with the counter return cryptoHmac.update(Buffer.from(hexCounter, 'hex')).digest(); }
javascript
function hotpDigest(secret, counter, options) { if (!options.crypto || typeof options.crypto.createHmac !== 'function') { throw new Error('Expecting options.crypto to have a createHmac function'); } if (typeof options.createHmacSecret !== 'function') { throw new Error('Expecting options.createHmacSecret to be a function'); } if (typeof options.algorithm !== 'string') { throw new Error('Expecting options.algorithm to be a string'); } // Convert secret to encoding for hmacSecret const hmacSecret = options.createHmacSecret(secret, { algorithm: options.algorithm, encoding: options.encoding }); // Ensure counter is a buffer or string (for HMAC creation) const hexCounter = hotpCounter(counter); // HMAC creation const cryptoHmac = options.crypto.createHmac(options.algorithm, hmacSecret); // Update HMAC with the counter return cryptoHmac.update(Buffer.from(hexCounter, 'hex')).digest(); }
[ "function", "hotpDigest", "(", "secret", ",", "counter", ",", "options", ")", "{", "if", "(", "!", "options", ".", "crypto", "||", "typeof", "options", ".", "crypto", ".", "createHmac", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "'Expecting options.crypto to have a createHmac function'", ")", ";", "}", "if", "(", "typeof", "options", ".", "createHmacSecret", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "'Expecting options.createHmacSecret to be a function'", ")", ";", "}", "if", "(", "typeof", "options", ".", "algorithm", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'Expecting options.algorithm to be a string'", ")", ";", "}", "// Convert secret to encoding for hmacSecret", "const", "hmacSecret", "=", "options", ".", "createHmacSecret", "(", "secret", ",", "{", "algorithm", ":", "options", ".", "algorithm", ",", "encoding", ":", "options", ".", "encoding", "}", ")", ";", "// Ensure counter is a buffer or string (for HMAC creation)", "const", "hexCounter", "=", "hotpCounter", "(", "counter", ")", ";", "// HMAC creation", "const", "cryptoHmac", "=", "options", ".", "crypto", ".", "createHmac", "(", "options", ".", "algorithm", ",", "hmacSecret", ")", ";", "// Update HMAC with the counter", "return", "cryptoHmac", ".", "update", "(", "Buffer", ".", "from", "(", "hexCounter", ",", "'hex'", ")", ")", ".", "digest", "(", ")", ";", "}" ]
Intermediate HOTP Digests @module otplib-core/hotpDigest @param {string} secret - your secret that is used to generate the token @param {number} counter - the OTP counter (usually it's an incremental count) @param {string} options.algorithm - hmac algorithm @param {function} options.createHmacSecret - the encoding function for secret @param {string} options.encoding - the encoding of secret @return {string} - hex string
[ "Intermediate", "HOTP", "Digests" ]
f81a4f11d63b3f00545c60bcef6543cdec2ddc0e
https://github.com/yeojz/otplib/blob/f81a4f11d63b3f00545c60bcef6543cdec2ddc0e/packages/otplib-core/hotpDigest.js#L14-L41
12,161
yeojz/otplib
packages/otplib-utils/stringToHex.js
stringToHex
function stringToHex(value) { const val = value == null ? '' : value; let hex = ''; let tmp = ''; for (let i = 0; i < val.length; i++) { // Convert to Hex and Ensure it's in 2 digit sets tmp = ('0000' + val.charCodeAt(i).toString(16)).slice(-2); hex += '' + tmp; } return hex; }
javascript
function stringToHex(value) { const val = value == null ? '' : value; let hex = ''; let tmp = ''; for (let i = 0; i < val.length; i++) { // Convert to Hex and Ensure it's in 2 digit sets tmp = ('0000' + val.charCodeAt(i).toString(16)).slice(-2); hex += '' + tmp; } return hex; }
[ "function", "stringToHex", "(", "value", ")", "{", "const", "val", "=", "value", "==", "null", "?", "''", ":", "value", ";", "let", "hex", "=", "''", ";", "let", "tmp", "=", "''", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "val", ".", "length", ";", "i", "++", ")", "{", "// Convert to Hex and Ensure it's in 2 digit sets", "tmp", "=", "(", "'0000'", "+", "val", ".", "charCodeAt", "(", "i", ")", ".", "toString", "(", "16", ")", ")", ".", "slice", "(", "-", "2", ")", ";", "hex", "+=", "''", "+", "tmp", ";", "}", "return", "hex", ";", "}" ]
Converts a string to Hex value @module otplib-utils/stringToHex @param {string} value - the string value to convert @return {string}
[ "Converts", "a", "string", "to", "Hex", "value" ]
f81a4f11d63b3f00545c60bcef6543cdec2ddc0e
https://github.com/yeojz/otplib/blob/f81a4f11d63b3f00545c60bcef6543cdec2ddc0e/packages/otplib-utils/stringToHex.js#L8-L21
12,162
yeojz/otplib
packages/otplib-core/totpSecret.js
totpSecret
function totpSecret(secret, options) { if (typeof options.algorithm !== 'string') { throw new Error('Expecting options.algorithm to be a string'); } if (typeof options.encoding !== 'string') { throw new Error('Expecting options.encoding to be a string'); } const encoded = Buffer.from(secret, options.encoding); const algorithm = options.algorithm.toLowerCase(); switch (algorithm) { case 'sha1': return padSecret(encoded, 20, options.encoding); case 'sha256': return padSecret(encoded, 32, options.encoding); case 'sha512': return padSecret(encoded, 64, options.encoding); default: throw new Error( `Unsupported algorithm ${algorithm}. Accepts: sha1, sha256, sha512` ); } }
javascript
function totpSecret(secret, options) { if (typeof options.algorithm !== 'string') { throw new Error('Expecting options.algorithm to be a string'); } if (typeof options.encoding !== 'string') { throw new Error('Expecting options.encoding to be a string'); } const encoded = Buffer.from(secret, options.encoding); const algorithm = options.algorithm.toLowerCase(); switch (algorithm) { case 'sha1': return padSecret(encoded, 20, options.encoding); case 'sha256': return padSecret(encoded, 32, options.encoding); case 'sha512': return padSecret(encoded, 64, options.encoding); default: throw new Error( `Unsupported algorithm ${algorithm}. Accepts: sha1, sha256, sha512` ); } }
[ "function", "totpSecret", "(", "secret", ",", "options", ")", "{", "if", "(", "typeof", "options", ".", "algorithm", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'Expecting options.algorithm to be a string'", ")", ";", "}", "if", "(", "typeof", "options", ".", "encoding", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'Expecting options.encoding to be a string'", ")", ";", "}", "const", "encoded", "=", "Buffer", ".", "from", "(", "secret", ",", "options", ".", "encoding", ")", ";", "const", "algorithm", "=", "options", ".", "algorithm", ".", "toLowerCase", "(", ")", ";", "switch", "(", "algorithm", ")", "{", "case", "'sha1'", ":", "return", "padSecret", "(", "encoded", ",", "20", ",", "options", ".", "encoding", ")", ";", "case", "'sha256'", ":", "return", "padSecret", "(", "encoded", ",", "32", ",", "options", ".", "encoding", ")", ";", "case", "'sha512'", ":", "return", "padSecret", "(", "encoded", ",", "64", ",", "options", ".", "encoding", ")", ";", "default", ":", "throw", "new", "Error", "(", "`", "${", "algorithm", "}", "`", ")", ";", "}", "}" ]
Conversion of secret to buffer for TOTP Seed for HMAC-SHA1 - 20 bytes Seed for HMAC-SHA256 - 32 bytes Seed for HMAC-SHA512 - 64 bytes @module otplib-core/totpSecret @param {string} secret - your secret that is used to generate the token @param {string} options.algorithm - hmac algorithm @param {string} options.encoding - the encoding of secret @return {object}
[ "Conversion", "of", "secret", "to", "buffer", "for", "TOTP" ]
f81a4f11d63b3f00545c60bcef6543cdec2ddc0e
https://github.com/yeojz/otplib/blob/f81a4f11d63b3f00545c60bcef6543cdec2ddc0e/packages/otplib-core/totpSecret.js#L16-L40
12,163
yeojz/otplib
packages/otplib-browser/randomBytes.js
randomBytes
function randomBytes(size) { const crypto = window.crypto || window.msCrypto; if (!crypto || typeof crypto.getRandomValues !== 'function') { throw new Error( 'Unable to load crypto module. You may be on an older browser' ); } if (size > 65536) { throw new Error('Requested size of random bytes is too large'); } if (size < 1) { throw new Error('Requested size must be more than 0'); } const rawBytes = new Uint8Array(size); crypto.getRandomValues(rawBytes); return Buffer.from(rawBytes.buffer); }
javascript
function randomBytes(size) { const crypto = window.crypto || window.msCrypto; if (!crypto || typeof crypto.getRandomValues !== 'function') { throw new Error( 'Unable to load crypto module. You may be on an older browser' ); } if (size > 65536) { throw new Error('Requested size of random bytes is too large'); } if (size < 1) { throw new Error('Requested size must be more than 0'); } const rawBytes = new Uint8Array(size); crypto.getRandomValues(rawBytes); return Buffer.from(rawBytes.buffer); }
[ "function", "randomBytes", "(", "size", ")", "{", "const", "crypto", "=", "window", ".", "crypto", "||", "window", ".", "msCrypto", ";", "if", "(", "!", "crypto", "||", "typeof", "crypto", ".", "getRandomValues", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "'Unable to load crypto module. You may be on an older browser'", ")", ";", "}", "if", "(", "size", ">", "65536", ")", "{", "throw", "new", "Error", "(", "'Requested size of random bytes is too large'", ")", ";", "}", "if", "(", "size", "<", "1", ")", "{", "throw", "new", "Error", "(", "'Requested size must be more than 0'", ")", ";", "}", "const", "rawBytes", "=", "new", "Uint8Array", "(", "size", ")", ";", "crypto", ".", "getRandomValues", "(", "rawBytes", ")", ";", "return", "Buffer", ".", "from", "(", "rawBytes", ".", "buffer", ")", ";", "}" ]
randomBytes browser implementation. Reference: - https://github.com/crypto-browserify/randombytes - https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues @module otplib-browser/randomBytes @param {string} size - the size @return {string}
[ "randomBytes", "browser", "implementation", "." ]
f81a4f11d63b3f00545c60bcef6543cdec2ddc0e
https://github.com/yeojz/otplib/blob/f81a4f11d63b3f00545c60bcef6543cdec2ddc0e/packages/otplib-browser/randomBytes.js#L12-L33
12,164
yeojz/otplib
packages/otplib-authenticator/keyuri.js
keyuri
function keyuri(user = 'user', service = 'service', secret = '') { const protocol = 'otpauth://totp/'; const value = data .replace('{user}', encodeURIComponent(user)) .replace('{secret}', secret) .replace(/{service}/g, encodeURIComponent(service)); return protocol + value; }
javascript
function keyuri(user = 'user', service = 'service', secret = '') { const protocol = 'otpauth://totp/'; const value = data .replace('{user}', encodeURIComponent(user)) .replace('{secret}', secret) .replace(/{service}/g, encodeURIComponent(service)); return protocol + value; }
[ "function", "keyuri", "(", "user", "=", "'user'", ",", "service", "=", "'service'", ",", "secret", "=", "''", ")", "{", "const", "protocol", "=", "'otpauth://totp/'", ";", "const", "value", "=", "data", ".", "replace", "(", "'{user}'", ",", "encodeURIComponent", "(", "user", ")", ")", ".", "replace", "(", "'{secret}'", ",", "secret", ")", ".", "replace", "(", "/", "{service}", "/", "g", ",", "encodeURIComponent", "(", "service", ")", ")", ";", "return", "protocol", "+", "value", ";", "}" ]
Generates an otpauth uri The "user" and "service" parameters will be passed to encodeURIComponent for encoding @namespace otplib/impl/authenticator @module otplib-authenticator/keyuri @param {string} user - the name/id of your user @param {string} service - the name of your service @param {string} secret - your secret that is used to generate the token @return {string} otpauth uri. Example: otpauth://totp/user:localhost?secret=NKEIBAOUFA
[ "Generates", "an", "otpauth", "uri" ]
f81a4f11d63b3f00545c60bcef6543cdec2ddc0e
https://github.com/yeojz/otplib/blob/f81a4f11d63b3f00545c60bcef6543cdec2ddc0e/packages/otplib-authenticator/keyuri.js#L16-L24
12,165
yeojz/otplib
packages/otplib-utils/leftPad.js
leftPad
function leftPad(value, length) { const total = !length ? 0 : length; let padded = value + ''; while (padded.length < total) { padded = '0' + padded; } return padded; }
javascript
function leftPad(value, length) { const total = !length ? 0 : length; let padded = value + ''; while (padded.length < total) { padded = '0' + padded; } return padded; }
[ "function", "leftPad", "(", "value", ",", "length", ")", "{", "const", "total", "=", "!", "length", "?", "0", ":", "length", ";", "let", "padded", "=", "value", "+", "''", ";", "while", "(", "padded", ".", "length", "<", "total", ")", "{", "padded", "=", "'0'", "+", "padded", ";", "}", "return", "padded", ";", "}" ]
Do a left padding if value's length less than total @module otplib-utils/leftPad @param {integer} value - the original value @param {integer} length - the total length of the string @return {string}
[ "Do", "a", "left", "padding", "if", "value", "s", "length", "less", "than", "total" ]
f81a4f11d63b3f00545c60bcef6543cdec2ddc0e
https://github.com/yeojz/otplib/blob/f81a4f11d63b3f00545c60bcef6543cdec2ddc0e/packages/otplib-utils/leftPad.js#L9-L19
12,166
jstat/jstat
src/linearalgebra.js
norm
function norm(arr, p) { var nnorm = 0, i = 0; // check the p-value of the norm, and set for most common case if (isNaN(p)) p = 2; // check if multi-dimensional array, and make vector correction if (isUsable(arr[0])) arr = arr[0]; // vector norm for (; i < arr.length; i++) { nnorm += Math.pow(Math.abs(arr[i]), p); } return Math.pow(nnorm, 1 / p); }
javascript
function norm(arr, p) { var nnorm = 0, i = 0; // check the p-value of the norm, and set for most common case if (isNaN(p)) p = 2; // check if multi-dimensional array, and make vector correction if (isUsable(arr[0])) arr = arr[0]; // vector norm for (; i < arr.length; i++) { nnorm += Math.pow(Math.abs(arr[i]), p); } return Math.pow(nnorm, 1 / p); }
[ "function", "norm", "(", "arr", ",", "p", ")", "{", "var", "nnorm", "=", "0", ",", "i", "=", "0", ";", "// check the p-value of the norm, and set for most common case", "if", "(", "isNaN", "(", "p", ")", ")", "p", "=", "2", ";", "// check if multi-dimensional array, and make vector correction", "if", "(", "isUsable", "(", "arr", "[", "0", "]", ")", ")", "arr", "=", "arr", "[", "0", "]", ";", "// vector norm", "for", "(", ";", "i", "<", "arr", ".", "length", ";", "i", "++", ")", "{", "nnorm", "+=", "Math", ".", "pow", "(", "Math", ".", "abs", "(", "arr", "[", "i", "]", ")", ",", "p", ")", ";", "}", "return", "Math", ".", "pow", "(", "nnorm", ",", "1", "/", "p", ")", ";", "}" ]
computes the p-norm of the vector In the case that a matrix is passed, uses the first row as the vector
[ "computes", "the", "p", "-", "norm", "of", "the", "vector", "In", "the", "case", "that", "a", "matrix", "is", "passed", "uses", "the", "first", "row", "as", "the", "vector" ]
5d99205d806e72997d863be800ffaf7af1851b97
https://github.com/jstat/jstat/blob/5d99205d806e72997d863be800ffaf7af1851b97/src/linearalgebra.js#L127-L139
12,167
jstat/jstat
src/regression.js
regress
function regress(jMatX,jMatY){ //print("regressin!"); //print(jMatX.toArray()); var innerinv = jStat.xtranspxinv(jMatX); //print(innerinv); var xtransp = jMatX.transpose(); var next = jStat.matrixmult(jStat(innerinv),xtransp); return jStat.matrixmult(next,jMatY); }
javascript
function regress(jMatX,jMatY){ //print("regressin!"); //print(jMatX.toArray()); var innerinv = jStat.xtranspxinv(jMatX); //print(innerinv); var xtransp = jMatX.transpose(); var next = jStat.matrixmult(jStat(innerinv),xtransp); return jStat.matrixmult(next,jMatY); }
[ "function", "regress", "(", "jMatX", ",", "jMatY", ")", "{", "//print(\"regressin!\");", "//print(jMatX.toArray());", "var", "innerinv", "=", "jStat", ".", "xtranspxinv", "(", "jMatX", ")", ";", "//print(innerinv);", "var", "xtransp", "=", "jMatX", ".", "transpose", "(", ")", ";", "var", "next", "=", "jStat", ".", "matrixmult", "(", "jStat", "(", "innerinv", ")", ",", "xtransp", ")", ";", "return", "jStat", ".", "matrixmult", "(", "next", ",", "jMatY", ")", ";", "}" ]
regress and regresst to be fixed
[ "regress", "and", "regresst", "to", "be", "fixed" ]
5d99205d806e72997d863be800ffaf7af1851b97
https://github.com/jstat/jstat/blob/5d99205d806e72997d863be800ffaf7af1851b97/src/regression.js#L90-L99
12,168
jstat/jstat
build/doctool.js
loadIncludes
function loadIncludes(data, current_file) { return data.replace(includeExpr, function(src, name, ext) { try { var include_path = path.join(current_file, "../", name+"."+(ext || "markdown")) return loadIncludes(fs.readFileSync(include_path, "utf8"), current_file); } catch(e) { return ""; } }); }
javascript
function loadIncludes(data, current_file) { return data.replace(includeExpr, function(src, name, ext) { try { var include_path = path.join(current_file, "../", name+"."+(ext || "markdown")) return loadIncludes(fs.readFileSync(include_path, "utf8"), current_file); } catch(e) { return ""; } }); }
[ "function", "loadIncludes", "(", "data", ",", "current_file", ")", "{", "return", "data", ".", "replace", "(", "includeExpr", ",", "function", "(", "src", ",", "name", ",", "ext", ")", "{", "try", "{", "var", "include_path", "=", "path", ".", "join", "(", "current_file", ",", "\"../\"", ",", "name", "+", "\".\"", "+", "(", "ext", "||", "\"markdown\"", ")", ")", "return", "loadIncludes", "(", "fs", ".", "readFileSync", "(", "include_path", ",", "\"utf8\"", ")", ",", "current_file", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "\"\"", ";", "}", "}", ")", ";", "}" ]
Allow including other pages in the data.
[ "Allow", "including", "other", "pages", "in", "the", "data", "." ]
5d99205d806e72997d863be800ffaf7af1851b97
https://github.com/jstat/jstat/blob/5d99205d806e72997d863be800ffaf7af1851b97/build/doctool.js#L66-L76
12,169
jstat/jstat
doc/assets/sh_main.js
sh_extractTagsFromNodeList
function sh_extractTagsFromNodeList(nodeList, result) { var length = nodeList.length; for (var i = 0; i < length; i++) { var node = nodeList.item(i); switch (node.nodeType) { case 1: if (node.nodeName.toLowerCase() === 'br') { var terminator; if (/MSIE/.test(navigator.userAgent)) { terminator = '\r'; } else { terminator = '\n'; } result.text.push(terminator); result.pos++; } else { result.tags.push({node: node.cloneNode(false), pos: result.pos}); sh_extractTagsFromNodeList(node.childNodes, result); result.tags.push({pos: result.pos}); } break; case 3: case 4: result.text.push(node.data); result.pos += node.length; break; } } }
javascript
function sh_extractTagsFromNodeList(nodeList, result) { var length = nodeList.length; for (var i = 0; i < length; i++) { var node = nodeList.item(i); switch (node.nodeType) { case 1: if (node.nodeName.toLowerCase() === 'br') { var terminator; if (/MSIE/.test(navigator.userAgent)) { terminator = '\r'; } else { terminator = '\n'; } result.text.push(terminator); result.pos++; } else { result.tags.push({node: node.cloneNode(false), pos: result.pos}); sh_extractTagsFromNodeList(node.childNodes, result); result.tags.push({pos: result.pos}); } break; case 3: case 4: result.text.push(node.data); result.pos += node.length; break; } } }
[ "function", "sh_extractTagsFromNodeList", "(", "nodeList", ",", "result", ")", "{", "var", "length", "=", "nodeList", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "var", "node", "=", "nodeList", ".", "item", "(", "i", ")", ";", "switch", "(", "node", ".", "nodeType", ")", "{", "case", "1", ":", "if", "(", "node", ".", "nodeName", ".", "toLowerCase", "(", ")", "===", "'br'", ")", "{", "var", "terminator", ";", "if", "(", "/", "MSIE", "/", ".", "test", "(", "navigator", ".", "userAgent", ")", ")", "{", "terminator", "=", "'\\r'", ";", "}", "else", "{", "terminator", "=", "'\\n'", ";", "}", "result", ".", "text", ".", "push", "(", "terminator", ")", ";", "result", ".", "pos", "++", ";", "}", "else", "{", "result", ".", "tags", ".", "push", "(", "{", "node", ":", "node", ".", "cloneNode", "(", "false", ")", ",", "pos", ":", "result", ".", "pos", "}", ")", ";", "sh_extractTagsFromNodeList", "(", "node", ".", "childNodes", ",", "result", ")", ";", "result", ".", "tags", ".", "push", "(", "{", "pos", ":", "result", ".", "pos", "}", ")", ";", "}", "break", ";", "case", "3", ":", "case", "4", ":", "result", ".", "text", ".", "push", "(", "node", ".", "data", ")", ";", "result", ".", "pos", "+=", "node", ".", "length", ";", "break", ";", "}", "}", "}" ]
Extracts the tags from an HTML DOM NodeList. @param nodeList a DOM NodeList @param result an object with text, tags and pos properties
[ "Extracts", "the", "tags", "from", "an", "HTML", "DOM", "NodeList", "." ]
5d99205d806e72997d863be800ffaf7af1851b97
https://github.com/jstat/jstat/blob/5d99205d806e72997d863be800ffaf7af1851b97/doc/assets/sh_main.js#L286-L316
12,170
jstat/jstat
doc/assets/sh_main.js
sh_extractTags
function sh_extractTags(element, tags) { var result = {}; result.text = []; result.tags = tags; result.pos = 0; sh_extractTagsFromNodeList(element.childNodes, result); return result.text.join(''); }
javascript
function sh_extractTags(element, tags) { var result = {}; result.text = []; result.tags = tags; result.pos = 0; sh_extractTagsFromNodeList(element.childNodes, result); return result.text.join(''); }
[ "function", "sh_extractTags", "(", "element", ",", "tags", ")", "{", "var", "result", "=", "{", "}", ";", "result", ".", "text", "=", "[", "]", ";", "result", ".", "tags", "=", "tags", ";", "result", ".", "pos", "=", "0", ";", "sh_extractTagsFromNodeList", "(", "element", ".", "childNodes", ",", "result", ")", ";", "return", "result", ".", "text", ".", "join", "(", "''", ")", ";", "}" ]
Extracts the tags from the text of an HTML element. The extracted tags will be returned as an array of tag objects. See sh_highlightString for the format of the tag objects. @param element a DOM element @param tags an empty array; the extracted tag objects will be returned in it @return the text of the element @see sh_highlightString
[ "Extracts", "the", "tags", "from", "the", "text", "of", "an", "HTML", "element", ".", "The", "extracted", "tags", "will", "be", "returned", "as", "an", "array", "of", "tag", "objects", ".", "See", "sh_highlightString", "for", "the", "format", "of", "the", "tag", "objects", "." ]
5d99205d806e72997d863be800ffaf7af1851b97
https://github.com/jstat/jstat/blob/5d99205d806e72997d863be800ffaf7af1851b97/doc/assets/sh_main.js#L327-L334
12,171
jstat/jstat
doc/assets/sh_main.js
sh_highlightElement
function sh_highlightElement(element, language) { sh_addClass(element, 'sh_sourceCode'); var originalTags = []; var inputString = sh_extractTags(element, originalTags); var highlightTags = sh_highlightString(inputString, language); var tags = sh_mergeTags(originalTags, highlightTags); var documentFragment = sh_insertTags(tags, inputString); while (element.hasChildNodes()) { element.removeChild(element.firstChild); } element.appendChild(documentFragment); }
javascript
function sh_highlightElement(element, language) { sh_addClass(element, 'sh_sourceCode'); var originalTags = []; var inputString = sh_extractTags(element, originalTags); var highlightTags = sh_highlightString(inputString, language); var tags = sh_mergeTags(originalTags, highlightTags); var documentFragment = sh_insertTags(tags, inputString); while (element.hasChildNodes()) { element.removeChild(element.firstChild); } element.appendChild(documentFragment); }
[ "function", "sh_highlightElement", "(", "element", ",", "language", ")", "{", "sh_addClass", "(", "element", ",", "'sh_sourceCode'", ")", ";", "var", "originalTags", "=", "[", "]", ";", "var", "inputString", "=", "sh_extractTags", "(", "element", ",", "originalTags", ")", ";", "var", "highlightTags", "=", "sh_highlightString", "(", "inputString", ",", "language", ")", ";", "var", "tags", "=", "sh_mergeTags", "(", "originalTags", ",", "highlightTags", ")", ";", "var", "documentFragment", "=", "sh_insertTags", "(", "tags", ",", "inputString", ")", ";", "while", "(", "element", ".", "hasChildNodes", "(", ")", ")", "{", "element", ".", "removeChild", "(", "element", ".", "firstChild", ")", ";", "}", "element", ".", "appendChild", "(", "documentFragment", ")", ";", "}" ]
Highlights an element containing source code. Upon completion of this function, the element will have been placed in the "sh_sourceCode" class. @param element a DOM <pre> element containing the source code to be highlighted @param language a language definition object
[ "Highlights", "an", "element", "containing", "source", "code", ".", "Upon", "completion", "of", "this", "function", "the", "element", "will", "have", "been", "placed", "in", "the", "sh_sourceCode", "class", "." ]
5d99205d806e72997d863be800ffaf7af1851b97
https://github.com/jstat/jstat/blob/5d99205d806e72997d863be800ffaf7af1851b97/doc/assets/sh_main.js#L453-L464
12,172
jstat/jstat
build/lib/markdown.js
add
function add(li, loose, inline, nl) { if (loose) { li.push( [ "para" ].concat(inline) ); return; } // Hmmm, should this be any block level element or just paras? var add_to = li[li.length -1] instanceof Array && li[li.length - 1][0] == "para" ? li[li.length -1] : li; // If there is already some content in this list, add the new line in if (nl && li.length > 1) inline.unshift(nl); for (var i=0; i < inline.length; i++) { var what = inline[i], is_str = typeof what == "string"; if (is_str && add_to.length > 1 && typeof add_to[add_to.length-1] == "string" ) { add_to[ add_to.length-1 ] += what; } else { add_to.push( what ); } } }
javascript
function add(li, loose, inline, nl) { if (loose) { li.push( [ "para" ].concat(inline) ); return; } // Hmmm, should this be any block level element or just paras? var add_to = li[li.length -1] instanceof Array && li[li.length - 1][0] == "para" ? li[li.length -1] : li; // If there is already some content in this list, add the new line in if (nl && li.length > 1) inline.unshift(nl); for (var i=0; i < inline.length; i++) { var what = inline[i], is_str = typeof what == "string"; if (is_str && add_to.length > 1 && typeof add_to[add_to.length-1] == "string" ) { add_to[ add_to.length-1 ] += what; } else { add_to.push( what ); } } }
[ "function", "add", "(", "li", ",", "loose", ",", "inline", ",", "nl", ")", "{", "if", "(", "loose", ")", "{", "li", ".", "push", "(", "[", "\"para\"", "]", ".", "concat", "(", "inline", ")", ")", ";", "return", ";", "}", "// Hmmm, should this be any block level element or just paras?", "var", "add_to", "=", "li", "[", "li", ".", "length", "-", "1", "]", "instanceof", "Array", "&&", "li", "[", "li", ".", "length", "-", "1", "]", "[", "0", "]", "==", "\"para\"", "?", "li", "[", "li", ".", "length", "-", "1", "]", ":", "li", ";", "// If there is already some content in this list, add the new line in", "if", "(", "nl", "&&", "li", ".", "length", ">", "1", ")", "inline", ".", "unshift", "(", "nl", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "inline", ".", "length", ";", "i", "++", ")", "{", "var", "what", "=", "inline", "[", "i", "]", ",", "is_str", "=", "typeof", "what", "==", "\"string\"", ";", "if", "(", "is_str", "&&", "add_to", ".", "length", ">", "1", "&&", "typeof", "add_to", "[", "add_to", ".", "length", "-", "1", "]", "==", "\"string\"", ")", "{", "add_to", "[", "add_to", ".", "length", "-", "1", "]", "+=", "what", ";", "}", "else", "{", "add_to", ".", "push", "(", "what", ")", ";", "}", "}", "}" ]
Add inline content `inline` to `li`. inline comes from processInline so is an array of content
[ "Add", "inline", "content", "inline", "to", "li", ".", "inline", "comes", "from", "processInline", "so", "is", "an", "array", "of", "content" ]
5d99205d806e72997d863be800ffaf7af1851b97
https://github.com/jstat/jstat/blob/5d99205d806e72997d863be800ffaf7af1851b97/build/lib/markdown.js#L429-L453
12,173
jstat/jstat
build/lib/markdown.js
merge_text_nodes
function merge_text_nodes( jsonml ) { // skip the tag name and attribute hash var i = extract_attr( jsonml ) ? 2 : 1; while ( i < jsonml.length ) { // if it's a string check the next item too if ( typeof jsonml[ i ] === "string" ) { if ( i + 1 < jsonml.length && typeof jsonml[ i + 1 ] === "string" ) { // merge the second string into the first and remove it jsonml[ i ] += jsonml.splice( i + 1, 1 )[ 0 ]; } else { ++i; } } // if it's not a string recurse else { arguments.callee( jsonml[ i ] ); ++i; } } }
javascript
function merge_text_nodes( jsonml ) { // skip the tag name and attribute hash var i = extract_attr( jsonml ) ? 2 : 1; while ( i < jsonml.length ) { // if it's a string check the next item too if ( typeof jsonml[ i ] === "string" ) { if ( i + 1 < jsonml.length && typeof jsonml[ i + 1 ] === "string" ) { // merge the second string into the first and remove it jsonml[ i ] += jsonml.splice( i + 1, 1 )[ 0 ]; } else { ++i; } } // if it's not a string recurse else { arguments.callee( jsonml[ i ] ); ++i; } } }
[ "function", "merge_text_nodes", "(", "jsonml", ")", "{", "// skip the tag name and attribute hash", "var", "i", "=", "extract_attr", "(", "jsonml", ")", "?", "2", ":", "1", ";", "while", "(", "i", "<", "jsonml", ".", "length", ")", "{", "// if it's a string check the next item too", "if", "(", "typeof", "jsonml", "[", "i", "]", "===", "\"string\"", ")", "{", "if", "(", "i", "+", "1", "<", "jsonml", ".", "length", "&&", "typeof", "jsonml", "[", "i", "+", "1", "]", "===", "\"string\"", ")", "{", "// merge the second string into the first and remove it", "jsonml", "[", "i", "]", "+=", "jsonml", ".", "splice", "(", "i", "+", "1", ",", "1", ")", "[", "0", "]", ";", "}", "else", "{", "++", "i", ";", "}", "}", "// if it's not a string recurse", "else", "{", "arguments", ".", "callee", "(", "jsonml", "[", "i", "]", ")", ";", "++", "i", ";", "}", "}", "}" ]
merges adjacent text nodes into a single node
[ "merges", "adjacent", "text", "nodes", "into", "a", "single", "node" ]
5d99205d806e72997d863be800ffaf7af1851b97
https://github.com/jstat/jstat/blob/5d99205d806e72997d863be800ffaf7af1851b97/build/lib/markdown.js#L1435-L1456
12,174
agraboso/redux-api-middleware
src/util.js
getJSON
async function getJSON(res) { const contentType = res.headers.get('Content-Type'); const emptyCodes = [204, 205]; if ( !~emptyCodes.indexOf(res.status) && contentType && ~contentType.indexOf('json') ) { return await res.json(); } else { return await Promise.resolve(); } }
javascript
async function getJSON(res) { const contentType = res.headers.get('Content-Type'); const emptyCodes = [204, 205]; if ( !~emptyCodes.indexOf(res.status) && contentType && ~contentType.indexOf('json') ) { return await res.json(); } else { return await Promise.resolve(); } }
[ "async", "function", "getJSON", "(", "res", ")", "{", "const", "contentType", "=", "res", ".", "headers", ".", "get", "(", "'Content-Type'", ")", ";", "const", "emptyCodes", "=", "[", "204", ",", "205", "]", ";", "if", "(", "!", "~", "emptyCodes", ".", "indexOf", "(", "res", ".", "status", ")", "&&", "contentType", "&&", "~", "contentType", ".", "indexOf", "(", "'json'", ")", ")", "{", "return", "await", "res", ".", "json", "(", ")", ";", "}", "else", "{", "return", "await", "Promise", ".", "resolve", "(", ")", ";", "}", "}" ]
Extract JSON body from a server response @function getJSON @access public @param {object} res - A raw response object @returns {promise|undefined}
[ "Extract", "JSON", "body", "from", "a", "server", "response" ]
6e782cdea6d5451e6e96406de631db7c11df1a2d
https://github.com/agraboso/redux-api-middleware/blob/6e782cdea6d5451e6e96406de631db7c11df1a2d/src/util.js#L11-L24
12,175
agraboso/redux-api-middleware
src/util.js
normalizeTypeDescriptors
function normalizeTypeDescriptors(types) { let [requestType, successType, failureType] = types; if (typeof requestType === 'string' || typeof requestType === 'symbol') { requestType = { type: requestType }; } if (typeof successType === 'string' || typeof successType === 'symbol') { successType = { type: successType }; } successType = { payload: (action, state, res) => getJSON(res), ...successType }; if (typeof failureType === 'string' || typeof failureType === 'symbol') { failureType = { type: failureType }; } failureType = { payload: (action, state, res) => getJSON(res).then(json => new ApiError(res.status, res.statusText, json)), ...failureType }; return [requestType, successType, failureType]; }
javascript
function normalizeTypeDescriptors(types) { let [requestType, successType, failureType] = types; if (typeof requestType === 'string' || typeof requestType === 'symbol') { requestType = { type: requestType }; } if (typeof successType === 'string' || typeof successType === 'symbol') { successType = { type: successType }; } successType = { payload: (action, state, res) => getJSON(res), ...successType }; if (typeof failureType === 'string' || typeof failureType === 'symbol') { failureType = { type: failureType }; } failureType = { payload: (action, state, res) => getJSON(res).then(json => new ApiError(res.status, res.statusText, json)), ...failureType }; return [requestType, successType, failureType]; }
[ "function", "normalizeTypeDescriptors", "(", "types", ")", "{", "let", "[", "requestType", ",", "successType", ",", "failureType", "]", "=", "types", ";", "if", "(", "typeof", "requestType", "===", "'string'", "||", "typeof", "requestType", "===", "'symbol'", ")", "{", "requestType", "=", "{", "type", ":", "requestType", "}", ";", "}", "if", "(", "typeof", "successType", "===", "'string'", "||", "typeof", "successType", "===", "'symbol'", ")", "{", "successType", "=", "{", "type", ":", "successType", "}", ";", "}", "successType", "=", "{", "payload", ":", "(", "action", ",", "state", ",", "res", ")", "=>", "getJSON", "(", "res", ")", ",", "...", "successType", "}", ";", "if", "(", "typeof", "failureType", "===", "'string'", "||", "typeof", "failureType", "===", "'symbol'", ")", "{", "failureType", "=", "{", "type", ":", "failureType", "}", ";", "}", "failureType", "=", "{", "payload", ":", "(", "action", ",", "state", ",", "res", ")", "=>", "getJSON", "(", "res", ")", ".", "then", "(", "json", "=>", "new", "ApiError", "(", "res", ".", "status", ",", "res", ".", "statusText", ",", "json", ")", ")", ",", "...", "failureType", "}", ";", "return", "[", "requestType", ",", "successType", ",", "failureType", "]", ";", "}" ]
Blow up string or symbol types into full-fledged type descriptors, and add defaults @function normalizeTypeDescriptors @access private @param {array} types - The [RSAA].types from a validated RSAA @returns {array}
[ "Blow", "up", "string", "or", "symbol", "types", "into", "full", "-", "fledged", "type", "descriptors", "and", "add", "defaults" ]
6e782cdea6d5451e6e96406de631db7c11df1a2d
https://github.com/agraboso/redux-api-middleware/blob/6e782cdea6d5451e6e96406de631db7c11df1a2d/src/util.js#L35-L60
12,176
agraboso/redux-api-middleware
src/util.js
actionWith
async function actionWith(descriptor, args = []) { try { descriptor.payload = typeof descriptor.payload === 'function' ? await descriptor.payload(...args) : descriptor.payload; } catch (e) { descriptor.payload = new InternalError(e.message); descriptor.error = true; } try { descriptor.meta = typeof descriptor.meta === 'function' ? await descriptor.meta(...args) : descriptor.meta; } catch (e) { delete descriptor.meta; descriptor.payload = new InternalError(e.message); descriptor.error = true; } return descriptor; }
javascript
async function actionWith(descriptor, args = []) { try { descriptor.payload = typeof descriptor.payload === 'function' ? await descriptor.payload(...args) : descriptor.payload; } catch (e) { descriptor.payload = new InternalError(e.message); descriptor.error = true; } try { descriptor.meta = typeof descriptor.meta === 'function' ? await descriptor.meta(...args) : descriptor.meta; } catch (e) { delete descriptor.meta; descriptor.payload = new InternalError(e.message); descriptor.error = true; } return descriptor; }
[ "async", "function", "actionWith", "(", "descriptor", ",", "args", "=", "[", "]", ")", "{", "try", "{", "descriptor", ".", "payload", "=", "typeof", "descriptor", ".", "payload", "===", "'function'", "?", "await", "descriptor", ".", "payload", "(", "...", "args", ")", ":", "descriptor", ".", "payload", ";", "}", "catch", "(", "e", ")", "{", "descriptor", ".", "payload", "=", "new", "InternalError", "(", "e", ".", "message", ")", ";", "descriptor", ".", "error", "=", "true", ";", "}", "try", "{", "descriptor", ".", "meta", "=", "typeof", "descriptor", ".", "meta", "===", "'function'", "?", "await", "descriptor", ".", "meta", "(", "...", "args", ")", ":", "descriptor", ".", "meta", ";", "}", "catch", "(", "e", ")", "{", "delete", "descriptor", ".", "meta", ";", "descriptor", ".", "payload", "=", "new", "InternalError", "(", "e", ".", "message", ")", ";", "descriptor", ".", "error", "=", "true", ";", "}", "return", "descriptor", ";", "}" ]
Evaluate a type descriptor to an FSA @function actionWith @access private @param {object} descriptor - A type descriptor @param {array} args - The array of arguments for `payload` and `meta` function properties @returns {object}
[ "Evaluate", "a", "type", "descriptor", "to", "an", "FSA" ]
6e782cdea6d5451e6e96406de631db7c11df1a2d
https://github.com/agraboso/redux-api-middleware/blob/6e782cdea6d5451e6e96406de631db7c11df1a2d/src/util.js#L71-L94
12,177
agraboso/redux-api-middleware
src/validation.js
isValidTypeDescriptor
function isValidTypeDescriptor(obj) { const validKeys = ['type', 'payload', 'meta']; if (!isPlainObject(obj)) { return false; } for (let key in obj) { if (!~validKeys.indexOf(key)) { return false; } } if (!('type' in obj)) { return false; } else if (typeof obj.type !== 'string' && typeof obj.type !== 'symbol') { return false; } return true; }
javascript
function isValidTypeDescriptor(obj) { const validKeys = ['type', 'payload', 'meta']; if (!isPlainObject(obj)) { return false; } for (let key in obj) { if (!~validKeys.indexOf(key)) { return false; } } if (!('type' in obj)) { return false; } else if (typeof obj.type !== 'string' && typeof obj.type !== 'symbol') { return false; } return true; }
[ "function", "isValidTypeDescriptor", "(", "obj", ")", "{", "const", "validKeys", "=", "[", "'type'", ",", "'payload'", ",", "'meta'", "]", ";", "if", "(", "!", "isPlainObject", "(", "obj", ")", ")", "{", "return", "false", ";", "}", "for", "(", "let", "key", "in", "obj", ")", "{", "if", "(", "!", "~", "validKeys", ".", "indexOf", "(", "key", ")", ")", "{", "return", "false", ";", "}", "}", "if", "(", "!", "(", "'type'", "in", "obj", ")", ")", "{", "return", "false", ";", "}", "else", "if", "(", "typeof", "obj", ".", "type", "!==", "'string'", "&&", "typeof", "obj", ".", "type", "!==", "'symbol'", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Is the given object a valid type descriptor? @function isValidTypeDescriptor @access private @param {object} obj - The object to check agains the type descriptor definition @returns {boolean}
[ "Is", "the", "given", "object", "a", "valid", "type", "descriptor?" ]
6e782cdea6d5451e6e96406de631db7c11df1a2d
https://github.com/agraboso/redux-api-middleware/blob/6e782cdea6d5451e6e96406de631db7c11df1a2d/src/validation.js#L39-L57
12,178
NEYouFan/nei-toolkit
lib/util/io.js
function (cache, listener) { if (Object.keys(cache).length <= 0) { listener.forEach(function (callback) { try { callback(); } catch (ex) { console.error(ex.stack); } }); } }
javascript
function (cache, listener) { if (Object.keys(cache).length <= 0) { listener.forEach(function (callback) { try { callback(); } catch (ex) { console.error(ex.stack); } }); } }
[ "function", "(", "cache", ",", "listener", ")", "{", "if", "(", "Object", ".", "keys", "(", "cache", ")", ".", "length", "<=", "0", ")", "{", "listener", ".", "forEach", "(", "function", "(", "callback", ")", "{", "try", "{", "callback", "(", ")", ";", "}", "catch", "(", "ex", ")", "{", "console", ".", "error", "(", "ex", ".", "stack", ")", ";", "}", "}", ")", ";", "}", "}" ]
check event trigger
[ "check", "event", "trigger" ]
a2a8bfcfb3d6a4d685afcbcb275277c9e344e295
https://github.com/NEYouFan/nei-toolkit/blob/a2a8bfcfb3d6a4d685afcbcb275277c9e344e295/lib/util/io.js#L38-L48
12,179
NEYouFan/nei-toolkit
lib/util/file.js
function (file, content, charset, callback) { try { if (!file) { return; } charset = (charset || 'utf-8').toLowerCase(); if (charset !== 'utf-8') { content = require('iconv-lite').encode(content + '\r\n', charset); } callback.call(this, file, content); } catch (ex) { throw util.format('cant write file [%s]%s for %s', charset, file, ex); } }
javascript
function (file, content, charset, callback) { try { if (!file) { return; } charset = (charset || 'utf-8').toLowerCase(); if (charset !== 'utf-8') { content = require('iconv-lite').encode(content + '\r\n', charset); } callback.call(this, file, content); } catch (ex) { throw util.format('cant write file [%s]%s for %s', charset, file, ex); } }
[ "function", "(", "file", ",", "content", ",", "charset", ",", "callback", ")", "{", "try", "{", "if", "(", "!", "file", ")", "{", "return", ";", "}", "charset", "=", "(", "charset", "||", "'utf-8'", ")", ".", "toLowerCase", "(", ")", ";", "if", "(", "charset", "!==", "'utf-8'", ")", "{", "content", "=", "require", "(", "'iconv-lite'", ")", ".", "encode", "(", "content", "+", "'\\r\\n'", ",", "charset", ")", ";", "}", "callback", ".", "call", "(", "this", ",", "file", ",", "content", ")", ";", "}", "catch", "(", "ex", ")", "{", "throw", "util", ".", "format", "(", "'cant write file [%s]%s for %s'", ",", "charset", ",", "file", ",", "ex", ")", ";", "}", "}" ]
write content to file @param {string} file - absolute file path @param {string} content - file content @param {string} charset - content charset, default is utf-8 @return {undefined}
[ "write", "content", "to", "file" ]
a2a8bfcfb3d6a4d685afcbcb275277c9e344e295
https://github.com/NEYouFan/nei-toolkit/blob/a2a8bfcfb3d6a4d685afcbcb275277c9e344e295/lib/util/file.js#L91-L104
12,180
ccampbell/rainbow
src/rainbow.js
_messageWorker
function _messageWorker(message, callback) { const worker = _getWorker(); function _listen(e) { if (e.data.id === message.id) { callback(e.data); worker.removeEventListener('message', _listen); } } worker.addEventListener('message', _listen); worker.postMessage(message); }
javascript
function _messageWorker(message, callback) { const worker = _getWorker(); function _listen(e) { if (e.data.id === message.id) { callback(e.data); worker.removeEventListener('message', _listen); } } worker.addEventListener('message', _listen); worker.postMessage(message); }
[ "function", "_messageWorker", "(", "message", ",", "callback", ")", "{", "const", "worker", "=", "_getWorker", "(", ")", ";", "function", "_listen", "(", "e", ")", "{", "if", "(", "e", ".", "data", ".", "id", "===", "message", ".", "id", ")", "{", "callback", "(", "e", ".", "data", ")", ";", "worker", ".", "removeEventListener", "(", "'message'", ",", "_listen", ")", ";", "}", "}", "worker", ".", "addEventListener", "(", "'message'", ",", "_listen", ")", ";", "worker", ".", "postMessage", "(", "message", ")", ";", "}" ]
Helper for matching up callbacks directly with the post message requests to a web worker. @param {object} message data to send to web worker @param {Function} callback callback function for worker to reply to @return {void}
[ "Helper", "for", "matching", "up", "callbacks", "directly", "with", "the", "post", "message", "requests", "to", "a", "web", "worker", "." ]
83308dfd7ce8ecfa05d5dde48dfad4a239382dfb
https://github.com/ccampbell/rainbow/blob/83308dfd7ce8ecfa05d5dde48dfad4a239382dfb/src/rainbow.js#L85-L97
12,181
ccampbell/rainbow
src/rainbow.js
_generateHandler
function _generateHandler(element, waitingOn, callback) { return function _handleResponseFromWorker(data) { element.innerHTML = data.result; element.classList.remove('loading'); element.classList.add('rainbow-show'); if (element.parentNode.tagName === 'PRE') { element.parentNode.classList.remove('loading'); element.parentNode.classList.add('rainbow-show'); } // element.addEventListener('animationend', (e) => { // if (e.animationName === 'fade-in') { // setTimeout(() => { // element.classList.remove('decrease-delay'); // }, 1000); // } // }); if (onHighlightCallback) { onHighlightCallback(element, data.lang); } if (--waitingOn.c === 0) { callback(); } }; }
javascript
function _generateHandler(element, waitingOn, callback) { return function _handleResponseFromWorker(data) { element.innerHTML = data.result; element.classList.remove('loading'); element.classList.add('rainbow-show'); if (element.parentNode.tagName === 'PRE') { element.parentNode.classList.remove('loading'); element.parentNode.classList.add('rainbow-show'); } // element.addEventListener('animationend', (e) => { // if (e.animationName === 'fade-in') { // setTimeout(() => { // element.classList.remove('decrease-delay'); // }, 1000); // } // }); if (onHighlightCallback) { onHighlightCallback(element, data.lang); } if (--waitingOn.c === 0) { callback(); } }; }
[ "function", "_generateHandler", "(", "element", ",", "waitingOn", ",", "callback", ")", "{", "return", "function", "_handleResponseFromWorker", "(", "data", ")", "{", "element", ".", "innerHTML", "=", "data", ".", "result", ";", "element", ".", "classList", ".", "remove", "(", "'loading'", ")", ";", "element", ".", "classList", ".", "add", "(", "'rainbow-show'", ")", ";", "if", "(", "element", ".", "parentNode", ".", "tagName", "===", "'PRE'", ")", "{", "element", ".", "parentNode", ".", "classList", ".", "remove", "(", "'loading'", ")", ";", "element", ".", "parentNode", ".", "classList", ".", "add", "(", "'rainbow-show'", ")", ";", "}", "// element.addEventListener('animationend', (e) => {", "// if (e.animationName === 'fade-in') {", "// setTimeout(() => {", "// element.classList.remove('decrease-delay');", "// }, 1000);", "// }", "// });", "if", "(", "onHighlightCallback", ")", "{", "onHighlightCallback", "(", "element", ",", "data", ".", "lang", ")", ";", "}", "if", "(", "--", "waitingOn", ".", "c", "===", "0", ")", "{", "callback", "(", ")", ";", "}", "}", ";", "}" ]
Browser Only - Handles response from web worker, updates DOM with resulting code, and fires callback @param {Element} element @param {object} waitingOn @param {Function} callback @return {void}
[ "Browser", "Only", "-", "Handles", "response", "from", "web", "worker", "updates", "DOM", "with", "resulting", "code", "and", "fires", "callback" ]
83308dfd7ce8ecfa05d5dde48dfad4a239382dfb
https://github.com/ccampbell/rainbow/blob/83308dfd7ce8ecfa05d5dde48dfad4a239382dfb/src/rainbow.js#L108-L135
12,182
ccampbell/rainbow
src/rainbow.js
_getPrismOptions
function _getPrismOptions(options) { return { patterns, inheritenceMap, aliases, globalClass: options.globalClass, delay: !isNaN(options.delay) ? options.delay : 0 }; }
javascript
function _getPrismOptions(options) { return { patterns, inheritenceMap, aliases, globalClass: options.globalClass, delay: !isNaN(options.delay) ? options.delay : 0 }; }
[ "function", "_getPrismOptions", "(", "options", ")", "{", "return", "{", "patterns", ",", "inheritenceMap", ",", "aliases", ",", "globalClass", ":", "options", ".", "globalClass", ",", "delay", ":", "!", "isNaN", "(", "options", ".", "delay", ")", "?", "options", ".", "delay", ":", "0", "}", ";", "}" ]
Gets options needed to pass into Prism @param {object} options @return {object}
[ "Gets", "options", "needed", "to", "pass", "into", "Prism" ]
83308dfd7ce8ecfa05d5dde48dfad4a239382dfb
https://github.com/ccampbell/rainbow/blob/83308dfd7ce8ecfa05d5dde48dfad4a239382dfb/src/rainbow.js#L143-L151
12,183
ccampbell/rainbow
src/rainbow.js
_getWorkerData
function _getWorkerData(code, lang) { let options = {}; if (typeof lang === 'object') { options = lang; lang = options.language; } lang = aliases[lang] || lang; const workerData = { id: id++, code, lang, options: _getPrismOptions(options), isNode }; return workerData; }
javascript
function _getWorkerData(code, lang) { let options = {}; if (typeof lang === 'object') { options = lang; lang = options.language; } lang = aliases[lang] || lang; const workerData = { id: id++, code, lang, options: _getPrismOptions(options), isNode }; return workerData; }
[ "function", "_getWorkerData", "(", "code", ",", "lang", ")", "{", "let", "options", "=", "{", "}", ";", "if", "(", "typeof", "lang", "===", "'object'", ")", "{", "options", "=", "lang", ";", "lang", "=", "options", ".", "language", ";", "}", "lang", "=", "aliases", "[", "lang", "]", "||", "lang", ";", "const", "workerData", "=", "{", "id", ":", "id", "++", ",", "code", ",", "lang", ",", "options", ":", "_getPrismOptions", "(", "options", ")", ",", "isNode", "}", ";", "return", "workerData", ";", "}" ]
Gets data to send to webworker @param {string} code @param {string} lang @return {object}
[ "Gets", "data", "to", "send", "to", "webworker" ]
83308dfd7ce8ecfa05d5dde48dfad4a239382dfb
https://github.com/ccampbell/rainbow/blob/83308dfd7ce8ecfa05d5dde48dfad4a239382dfb/src/rainbow.js#L160-L178
12,184
ccampbell/rainbow
src/rainbow.js
_highlightCodeBlocks
function _highlightCodeBlocks(codeBlocks, callback) { const waitingOn = { c: 0 }; for (const block of codeBlocks) { const language = getLanguageForBlock(block); if (block.classList.contains('rainbow') || !language) { continue; } // This cancels the pending animation to fade the code in on load // since we want to delay doing this until it is actually // highlighted block.classList.add('loading'); block.classList.add('rainbow'); // We need to make sure to also add the loading class to the pre tag // because that is how we will know to show a preloader if (block.parentNode.tagName === 'PRE') { block.parentNode.classList.add('loading'); } const globalClass = block.getAttribute('data-global-class'); const delay = parseInt(block.getAttribute('data-delay'), 10); ++waitingOn.c; _messageWorker(_getWorkerData(block.innerHTML, { language, globalClass, delay }), _generateHandler(block, waitingOn, callback)); } if (waitingOn.c === 0) { callback(); } }
javascript
function _highlightCodeBlocks(codeBlocks, callback) { const waitingOn = { c: 0 }; for (const block of codeBlocks) { const language = getLanguageForBlock(block); if (block.classList.contains('rainbow') || !language) { continue; } // This cancels the pending animation to fade the code in on load // since we want to delay doing this until it is actually // highlighted block.classList.add('loading'); block.classList.add('rainbow'); // We need to make sure to also add the loading class to the pre tag // because that is how we will know to show a preloader if (block.parentNode.tagName === 'PRE') { block.parentNode.classList.add('loading'); } const globalClass = block.getAttribute('data-global-class'); const delay = parseInt(block.getAttribute('data-delay'), 10); ++waitingOn.c; _messageWorker(_getWorkerData(block.innerHTML, { language, globalClass, delay }), _generateHandler(block, waitingOn, callback)); } if (waitingOn.c === 0) { callback(); } }
[ "function", "_highlightCodeBlocks", "(", "codeBlocks", ",", "callback", ")", "{", "const", "waitingOn", "=", "{", "c", ":", "0", "}", ";", "for", "(", "const", "block", "of", "codeBlocks", ")", "{", "const", "language", "=", "getLanguageForBlock", "(", "block", ")", ";", "if", "(", "block", ".", "classList", ".", "contains", "(", "'rainbow'", ")", "||", "!", "language", ")", "{", "continue", ";", "}", "// This cancels the pending animation to fade the code in on load", "// since we want to delay doing this until it is actually", "// highlighted", "block", ".", "classList", ".", "add", "(", "'loading'", ")", ";", "block", ".", "classList", ".", "add", "(", "'rainbow'", ")", ";", "// We need to make sure to also add the loading class to the pre tag", "// because that is how we will know to show a preloader", "if", "(", "block", ".", "parentNode", ".", "tagName", "===", "'PRE'", ")", "{", "block", ".", "parentNode", ".", "classList", ".", "add", "(", "'loading'", ")", ";", "}", "const", "globalClass", "=", "block", ".", "getAttribute", "(", "'data-global-class'", ")", ";", "const", "delay", "=", "parseInt", "(", "block", ".", "getAttribute", "(", "'data-delay'", ")", ",", "10", ")", ";", "++", "waitingOn", ".", "c", ";", "_messageWorker", "(", "_getWorkerData", "(", "block", ".", "innerHTML", ",", "{", "language", ",", "globalClass", ",", "delay", "}", ")", ",", "_generateHandler", "(", "block", ",", "waitingOn", ",", "callback", ")", ")", ";", "}", "if", "(", "waitingOn", ".", "c", "===", "0", ")", "{", "callback", "(", ")", ";", "}", "}" ]
Browser Only - Sends messages to web worker to highlight elements passed in @param {Array} codeBlocks @param {Function} callback @return {void}
[ "Browser", "Only", "-", "Sends", "messages", "to", "web", "worker", "to", "highlight", "elements", "passed", "in" ]
83308dfd7ce8ecfa05d5dde48dfad4a239382dfb
https://github.com/ccampbell/rainbow/blob/83308dfd7ce8ecfa05d5dde48dfad4a239382dfb/src/rainbow.js#L188-L218
12,185
ccampbell/rainbow
src/rainbow.js
_highlight
function _highlight(node, callback) { callback = callback || function() {}; // The first argument can be an Event or a DOM Element. // // I was originally checking instanceof Event but that made it break // when using mootools. // // @see https://github.com/ccampbell/rainbow/issues/32 node = node && typeof node.getElementsByTagName === 'function' ? node : document; const preBlocks = node.getElementsByTagName('pre'); const codeBlocks = node.getElementsByTagName('code'); const finalPreBlocks = []; const finalCodeBlocks = []; // First loop through all pre blocks to find which ones to highlight for (const preBlock of preBlocks) { _addPreloader(preBlock); // Strip whitespace around code tags when they are inside of a pre // tag. This makes the themes look better because you can't // accidentally add extra linebreaks at the start and end. // // When the pre tag contains a code tag then strip any extra // whitespace. // // For example: // // <pre> // <code>var foo = true;</code> // </pre> // // will become: // // <pre><code>var foo = true;</code></pre> // // If you want to preserve whitespace you can use a pre tag on // its own without a code tag inside of it. if (preBlock.getElementsByTagName('code').length) { // This fixes a race condition when Rainbow.color is called before // the previous color call has finished. if (!preBlock.getAttribute('data-trimmed')) { preBlock.setAttribute('data-trimmed', true); preBlock.innerHTML = preBlock.innerHTML.trim(); } continue; } // If the pre block has no code blocks then we are going to want to // process it directly. finalPreBlocks.push(preBlock); } // @see http://stackoverflow.com/questions/2735067/how-to-convert-a-dom-node-list-to-an-array-in-javascript // We are going to process all <code> blocks for (const codeBlock of codeBlocks) { finalCodeBlocks.push(codeBlock); } _highlightCodeBlocks(finalCodeBlocks.concat(finalPreBlocks), callback); }
javascript
function _highlight(node, callback) { callback = callback || function() {}; // The first argument can be an Event or a DOM Element. // // I was originally checking instanceof Event but that made it break // when using mootools. // // @see https://github.com/ccampbell/rainbow/issues/32 node = node && typeof node.getElementsByTagName === 'function' ? node : document; const preBlocks = node.getElementsByTagName('pre'); const codeBlocks = node.getElementsByTagName('code'); const finalPreBlocks = []; const finalCodeBlocks = []; // First loop through all pre blocks to find which ones to highlight for (const preBlock of preBlocks) { _addPreloader(preBlock); // Strip whitespace around code tags when they are inside of a pre // tag. This makes the themes look better because you can't // accidentally add extra linebreaks at the start and end. // // When the pre tag contains a code tag then strip any extra // whitespace. // // For example: // // <pre> // <code>var foo = true;</code> // </pre> // // will become: // // <pre><code>var foo = true;</code></pre> // // If you want to preserve whitespace you can use a pre tag on // its own without a code tag inside of it. if (preBlock.getElementsByTagName('code').length) { // This fixes a race condition when Rainbow.color is called before // the previous color call has finished. if (!preBlock.getAttribute('data-trimmed')) { preBlock.setAttribute('data-trimmed', true); preBlock.innerHTML = preBlock.innerHTML.trim(); } continue; } // If the pre block has no code blocks then we are going to want to // process it directly. finalPreBlocks.push(preBlock); } // @see http://stackoverflow.com/questions/2735067/how-to-convert-a-dom-node-list-to-an-array-in-javascript // We are going to process all <code> blocks for (const codeBlock of codeBlocks) { finalCodeBlocks.push(codeBlock); } _highlightCodeBlocks(finalCodeBlocks.concat(finalPreBlocks), callback); }
[ "function", "_highlight", "(", "node", ",", "callback", ")", "{", "callback", "=", "callback", "||", "function", "(", ")", "{", "}", ";", "// The first argument can be an Event or a DOM Element.", "//", "// I was originally checking instanceof Event but that made it break", "// when using mootools.", "//", "// @see https://github.com/ccampbell/rainbow/issues/32", "node", "=", "node", "&&", "typeof", "node", ".", "getElementsByTagName", "===", "'function'", "?", "node", ":", "document", ";", "const", "preBlocks", "=", "node", ".", "getElementsByTagName", "(", "'pre'", ")", ";", "const", "codeBlocks", "=", "node", ".", "getElementsByTagName", "(", "'code'", ")", ";", "const", "finalPreBlocks", "=", "[", "]", ";", "const", "finalCodeBlocks", "=", "[", "]", ";", "// First loop through all pre blocks to find which ones to highlight", "for", "(", "const", "preBlock", "of", "preBlocks", ")", "{", "_addPreloader", "(", "preBlock", ")", ";", "// Strip whitespace around code tags when they are inside of a pre", "// tag. This makes the themes look better because you can't", "// accidentally add extra linebreaks at the start and end.", "//", "// When the pre tag contains a code tag then strip any extra", "// whitespace.", "//", "// For example:", "//", "// <pre>", "// <code>var foo = true;</code>", "// </pre>", "//", "// will become:", "//", "// <pre><code>var foo = true;</code></pre>", "//", "// If you want to preserve whitespace you can use a pre tag on", "// its own without a code tag inside of it.", "if", "(", "preBlock", ".", "getElementsByTagName", "(", "'code'", ")", ".", "length", ")", "{", "// This fixes a race condition when Rainbow.color is called before", "// the previous color call has finished.", "if", "(", "!", "preBlock", ".", "getAttribute", "(", "'data-trimmed'", ")", ")", "{", "preBlock", ".", "setAttribute", "(", "'data-trimmed'", ",", "true", ")", ";", "preBlock", ".", "innerHTML", "=", "preBlock", ".", "innerHTML", ".", "trim", "(", ")", ";", "}", "continue", ";", "}", "// If the pre block has no code blocks then we are going to want to", "// process it directly.", "finalPreBlocks", ".", "push", "(", "preBlock", ")", ";", "}", "// @see http://stackoverflow.com/questions/2735067/how-to-convert-a-dom-node-list-to-an-array-in-javascript", "// We are going to process all <code> blocks", "for", "(", "const", "codeBlock", "of", "codeBlocks", ")", "{", "finalCodeBlocks", ".", "push", "(", "codeBlock", ")", ";", "}", "_highlightCodeBlocks", "(", "finalCodeBlocks", ".", "concat", "(", "finalPreBlocks", ")", ",", "callback", ")", ";", "}" ]
Browser Only - Start highlighting all the code blocks @param {Element} node HTMLElement to search within @param {Function} callback @return {void}
[ "Browser", "Only", "-", "Start", "highlighting", "all", "the", "code", "blocks" ]
83308dfd7ce8ecfa05d5dde48dfad4a239382dfb
https://github.com/ccampbell/rainbow/blob/83308dfd7ce8ecfa05d5dde48dfad4a239382dfb/src/rainbow.js#L236-L298
12,186
ccampbell/rainbow
src/rainbow.js
extend
function extend(language, languagePatterns, inherits) { // If we extend a language again we shouldn't need to specify the // inheritence for it. For example, if you are adding special highlighting // for a javascript function that is not in the base javascript rules, you // should be able to do // // Rainbow.extend('javascript', [ … ]); // // Without specifying a language it should inherit (generic in this case) if (!inheritenceMap[language]) { inheritenceMap[language] = inherits; } patterns[language] = languagePatterns.concat(patterns[language] || []); }
javascript
function extend(language, languagePatterns, inherits) { // If we extend a language again we shouldn't need to specify the // inheritence for it. For example, if you are adding special highlighting // for a javascript function that is not in the base javascript rules, you // should be able to do // // Rainbow.extend('javascript', [ … ]); // // Without specifying a language it should inherit (generic in this case) if (!inheritenceMap[language]) { inheritenceMap[language] = inherits; } patterns[language] = languagePatterns.concat(patterns[language] || []); }
[ "function", "extend", "(", "language", ",", "languagePatterns", ",", "inherits", ")", "{", "// If we extend a language again we shouldn't need to specify the", "// inheritence for it. For example, if you are adding special highlighting", "// for a javascript function that is not in the base javascript rules, you", "// should be able to do", "//", "// Rainbow.extend('javascript', [ … ]);", "//", "// Without specifying a language it should inherit (generic in this case)", "if", "(", "!", "inheritenceMap", "[", "language", "]", ")", "{", "inheritenceMap", "[", "language", "]", "=", "inherits", ";", "}", "patterns", "[", "language", "]", "=", "languagePatterns", ".", "concat", "(", "patterns", "[", "language", "]", "||", "[", "]", ")", ";", "}" ]
Extends the language pattern matches @param {string} language name of language @param {object} languagePatterns object of patterns to add on @param {string|undefined} inherits optional language that this language should inherit rules from
[ "Extends", "the", "language", "pattern", "matches" ]
83308dfd7ce8ecfa05d5dde48dfad4a239382dfb
https://github.com/ccampbell/rainbow/blob/83308dfd7ce8ecfa05d5dde48dfad4a239382dfb/src/rainbow.js#L319-L334
12,187
ccampbell/rainbow
src/rainbow.js
color
function color(...args) { // If you want to straight up highlight a string you can pass the // string of code, the language, and a callback function. // // Example: // // Rainbow.color(code, language, function(highlightedCode, language) { // // this code block is now highlighted // }); if (typeof args[0] === 'string') { const workerData = _getWorkerData(args[0], args[1]); _messageWorker(workerData, (function(cb) { return function(data) { if (cb) { cb(data.result, data.lang); } }; }(args[2]))); return; } // If you pass a callback function then we rerun the color function // on all the code and call the callback function on complete. // // Example: // // Rainbow.color(function() { // console.log('All matching tags on the page are now highlighted'); // }); if (typeof args[0] === 'function') { _highlight(0, args[0]); return; } // Otherwise we use whatever node you passed in with an optional // callback function as the second parameter. // // Example: // // var preElement = document.createElement('pre'); // var codeElement = document.createElement('code'); // codeElement.setAttribute('data-language', 'javascript'); // codeElement.innerHTML = '// Here is some JavaScript'; // preElement.appendChild(codeElement); // Rainbow.color(preElement, function() { // // New element is now highlighted // }); // // If you don't pass an element it will default to `document` _highlight(args[0], args[1]); }
javascript
function color(...args) { // If you want to straight up highlight a string you can pass the // string of code, the language, and a callback function. // // Example: // // Rainbow.color(code, language, function(highlightedCode, language) { // // this code block is now highlighted // }); if (typeof args[0] === 'string') { const workerData = _getWorkerData(args[0], args[1]); _messageWorker(workerData, (function(cb) { return function(data) { if (cb) { cb(data.result, data.lang); } }; }(args[2]))); return; } // If you pass a callback function then we rerun the color function // on all the code and call the callback function on complete. // // Example: // // Rainbow.color(function() { // console.log('All matching tags on the page are now highlighted'); // }); if (typeof args[0] === 'function') { _highlight(0, args[0]); return; } // Otherwise we use whatever node you passed in with an optional // callback function as the second parameter. // // Example: // // var preElement = document.createElement('pre'); // var codeElement = document.createElement('code'); // codeElement.setAttribute('data-language', 'javascript'); // codeElement.innerHTML = '// Here is some JavaScript'; // preElement.appendChild(codeElement); // Rainbow.color(preElement, function() { // // New element is now highlighted // }); // // If you don't pass an element it will default to `document` _highlight(args[0], args[1]); }
[ "function", "color", "(", "...", "args", ")", "{", "// If you want to straight up highlight a string you can pass the", "// string of code, the language, and a callback function.", "//", "// Example:", "//", "// Rainbow.color(code, language, function(highlightedCode, language) {", "// // this code block is now highlighted", "// });", "if", "(", "typeof", "args", "[", "0", "]", "===", "'string'", ")", "{", "const", "workerData", "=", "_getWorkerData", "(", "args", "[", "0", "]", ",", "args", "[", "1", "]", ")", ";", "_messageWorker", "(", "workerData", ",", "(", "function", "(", "cb", ")", "{", "return", "function", "(", "data", ")", "{", "if", "(", "cb", ")", "{", "cb", "(", "data", ".", "result", ",", "data", ".", "lang", ")", ";", "}", "}", ";", "}", "(", "args", "[", "2", "]", ")", ")", ")", ";", "return", ";", "}", "// If you pass a callback function then we rerun the color function", "// on all the code and call the callback function on complete.", "//", "// Example:", "//", "// Rainbow.color(function() {", "// console.log('All matching tags on the page are now highlighted');", "// });", "if", "(", "typeof", "args", "[", "0", "]", "===", "'function'", ")", "{", "_highlight", "(", "0", ",", "args", "[", "0", "]", ")", ";", "return", ";", "}", "// Otherwise we use whatever node you passed in with an optional", "// callback function as the second parameter.", "//", "// Example:", "//", "// var preElement = document.createElement('pre');", "// var codeElement = document.createElement('code');", "// codeElement.setAttribute('data-language', 'javascript');", "// codeElement.innerHTML = '// Here is some JavaScript';", "// preElement.appendChild(codeElement);", "// Rainbow.color(preElement, function() {", "// // New element is now highlighted", "// });", "//", "// If you don't pass an element it will default to `document`", "_highlight", "(", "args", "[", "0", "]", ",", "args", "[", "1", "]", ")", ";", "}" ]
Starts the magic rainbow @return {void}
[ "Starts", "the", "magic", "rainbow" ]
83308dfd7ce8ecfa05d5dde48dfad4a239382dfb
https://github.com/ccampbell/rainbow/blob/83308dfd7ce8ecfa05d5dde48dfad4a239382dfb/src/rainbow.js#L346-L397
12,188
nfriedly/node-unblocker
lib/charsets.js
MetaCharsetReplacerStream
function MetaCharsetReplacerStream(options) { options = options || {}; this.encoding = options.encoding = 'utf8'; // this is the *output* encoding options.decodeStrings = false; // don't turn my strings back into a buffer! Transform.call(this, options); }
javascript
function MetaCharsetReplacerStream(options) { options = options || {}; this.encoding = options.encoding = 'utf8'; // this is the *output* encoding options.decodeStrings = false; // don't turn my strings back into a buffer! Transform.call(this, options); }
[ "function", "MetaCharsetReplacerStream", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "encoding", "=", "options", ".", "encoding", "=", "'utf8'", ";", "// this is the *output* encoding", "options", ".", "decodeStrings", "=", "false", ";", "// don't turn my strings back into a buffer!", "Transform", ".", "call", "(", "this", ",", "options", ")", ";", "}" ]
similar to the charset_finder, except global
[ "similar", "to", "the", "charset_finder", "except", "global" ]
30874bcbab993ab8ed525c0751ae2572ae20fdac
https://github.com/nfriedly/node-unblocker/blob/30874bcbab993ab8ed525c0751ae2572ae20fdac/lib/charsets.js#L160-L165
12,189
nfriedly/node-unblocker
lib/proxy.js
proxyRequest
function proxyRequest(data, next) { debug('proxying %s %s', data.clientRequest.method, data.url); var middlewareHandledRequest = _.some(config.requestMiddleware, function(middleware) { middleware(data); return data.clientResponse.headersSent; // if true, then _.some will stop processing middleware here because we can no longer }); if (!middlewareHandledRequest) { var uri = URL.parse(data.url); var options = { host: uri.hostname, port: uri.port, path: uri.path, method: data.clientRequest.method, headers: data.headers }; //set the agent for the request. if(uri.protocol == 'http:' && config.httpAgent) { options.agent = config.httpAgent; } if(uri.protocol == 'https:' && config.httpsAgent) { options.agent = config.httpsAgent; } // what protocol to use for outgoing connections. var proto = (uri.protocol == 'https:') ? https : http; debug('sending remote request: ', options); data.remoteRequest = proto.request(options, function(remoteResponse) { data.remoteResponse = remoteResponse; data.remoteResponse.on('error', next); proxyResponse(data); }); data.remoteRequest.on('error', next); // pass along POST data & let the remote server know when we're done sending data data.stream.pipe(data.remoteRequest); } }
javascript
function proxyRequest(data, next) { debug('proxying %s %s', data.clientRequest.method, data.url); var middlewareHandledRequest = _.some(config.requestMiddleware, function(middleware) { middleware(data); return data.clientResponse.headersSent; // if true, then _.some will stop processing middleware here because we can no longer }); if (!middlewareHandledRequest) { var uri = URL.parse(data.url); var options = { host: uri.hostname, port: uri.port, path: uri.path, method: data.clientRequest.method, headers: data.headers }; //set the agent for the request. if(uri.protocol == 'http:' && config.httpAgent) { options.agent = config.httpAgent; } if(uri.protocol == 'https:' && config.httpsAgent) { options.agent = config.httpsAgent; } // what protocol to use for outgoing connections. var proto = (uri.protocol == 'https:') ? https : http; debug('sending remote request: ', options); data.remoteRequest = proto.request(options, function(remoteResponse) { data.remoteResponse = remoteResponse; data.remoteResponse.on('error', next); proxyResponse(data); }); data.remoteRequest.on('error', next); // pass along POST data & let the remote server know when we're done sending data data.stream.pipe(data.remoteRequest); } }
[ "function", "proxyRequest", "(", "data", ",", "next", ")", "{", "debug", "(", "'proxying %s %s'", ",", "data", ".", "clientRequest", ".", "method", ",", "data", ".", "url", ")", ";", "var", "middlewareHandledRequest", "=", "_", ".", "some", "(", "config", ".", "requestMiddleware", ",", "function", "(", "middleware", ")", "{", "middleware", "(", "data", ")", ";", "return", "data", ".", "clientResponse", ".", "headersSent", ";", "// if true, then _.some will stop processing middleware here because we can no longer", "}", ")", ";", "if", "(", "!", "middlewareHandledRequest", ")", "{", "var", "uri", "=", "URL", ".", "parse", "(", "data", ".", "url", ")", ";", "var", "options", "=", "{", "host", ":", "uri", ".", "hostname", ",", "port", ":", "uri", ".", "port", ",", "path", ":", "uri", ".", "path", ",", "method", ":", "data", ".", "clientRequest", ".", "method", ",", "headers", ":", "data", ".", "headers", "}", ";", "//set the agent for the request.", "if", "(", "uri", ".", "protocol", "==", "'http:'", "&&", "config", ".", "httpAgent", ")", "{", "options", ".", "agent", "=", "config", ".", "httpAgent", ";", "}", "if", "(", "uri", ".", "protocol", "==", "'https:'", "&&", "config", ".", "httpsAgent", ")", "{", "options", ".", "agent", "=", "config", ".", "httpsAgent", ";", "}", "// what protocol to use for outgoing connections.", "var", "proto", "=", "(", "uri", ".", "protocol", "==", "'https:'", ")", "?", "https", ":", "http", ";", "debug", "(", "'sending remote request: '", ",", "options", ")", ";", "data", ".", "remoteRequest", "=", "proto", ".", "request", "(", "options", ",", "function", "(", "remoteResponse", ")", "{", "data", ".", "remoteResponse", "=", "remoteResponse", ";", "data", ".", "remoteResponse", ".", "on", "(", "'error'", ",", "next", ")", ";", "proxyResponse", "(", "data", ")", ";", "}", ")", ";", "data", ".", "remoteRequest", ".", "on", "(", "'error'", ",", "next", ")", ";", "// pass along POST data & let the remote server know when we're done sending data", "data", ".", "stream", ".", "pipe", "(", "data", ".", "remoteRequest", ")", ";", "}", "}" ]
Makes the outgoing request and relays it to the client, modifying it along the way if necessary
[ "Makes", "the", "outgoing", "request", "and", "relays", "it", "to", "the", "client", "modifying", "it", "along", "the", "way", "if", "necessary" ]
30874bcbab993ab8ed525c0751ae2572ae20fdac
https://github.com/nfriedly/node-unblocker/blob/30874bcbab993ab8ed525c0751ae2572ae20fdac/lib/proxy.js#L14-L59
12,190
ljagis/leaflet-measure
src/leaflet-measure.js
function() { this._locked = true; this._measureVertexes = L.featureGroup().addTo(this._layer); this._captureMarker = L.marker(this._map.getCenter(), { clickable: true, zIndexOffset: this.options.captureZIndex, opacity: 0 }).addTo(this._layer); this._setCaptureMarkerIcon(); this._captureMarker .on('mouseout', this._handleMapMouseOut, this) .on('dblclick', this._handleMeasureDoubleClick, this) .on('click', this._handleMeasureClick, this); this._map .on('mousemove', this._handleMeasureMove, this) .on('mouseout', this._handleMapMouseOut, this) .on('move', this._centerCaptureMarker, this) .on('resize', this._setCaptureMarkerIcon, this); L.DomEvent.on(this._container, 'mouseenter', this._handleMapMouseOut, this); this._updateMeasureStartedNoPoints(); this._map.fire('measurestart', null, false); }
javascript
function() { this._locked = true; this._measureVertexes = L.featureGroup().addTo(this._layer); this._captureMarker = L.marker(this._map.getCenter(), { clickable: true, zIndexOffset: this.options.captureZIndex, opacity: 0 }).addTo(this._layer); this._setCaptureMarkerIcon(); this._captureMarker .on('mouseout', this._handleMapMouseOut, this) .on('dblclick', this._handleMeasureDoubleClick, this) .on('click', this._handleMeasureClick, this); this._map .on('mousemove', this._handleMeasureMove, this) .on('mouseout', this._handleMapMouseOut, this) .on('move', this._centerCaptureMarker, this) .on('resize', this._setCaptureMarkerIcon, this); L.DomEvent.on(this._container, 'mouseenter', this._handleMapMouseOut, this); this._updateMeasureStartedNoPoints(); this._map.fire('measurestart', null, false); }
[ "function", "(", ")", "{", "this", ".", "_locked", "=", "true", ";", "this", ".", "_measureVertexes", "=", "L", ".", "featureGroup", "(", ")", ".", "addTo", "(", "this", ".", "_layer", ")", ";", "this", ".", "_captureMarker", "=", "L", ".", "marker", "(", "this", ".", "_map", ".", "getCenter", "(", ")", ",", "{", "clickable", ":", "true", ",", "zIndexOffset", ":", "this", ".", "options", ".", "captureZIndex", ",", "opacity", ":", "0", "}", ")", ".", "addTo", "(", "this", ".", "_layer", ")", ";", "this", ".", "_setCaptureMarkerIcon", "(", ")", ";", "this", ".", "_captureMarker", ".", "on", "(", "'mouseout'", ",", "this", ".", "_handleMapMouseOut", ",", "this", ")", ".", "on", "(", "'dblclick'", ",", "this", ".", "_handleMeasureDoubleClick", ",", "this", ")", ".", "on", "(", "'click'", ",", "this", ".", "_handleMeasureClick", ",", "this", ")", ";", "this", ".", "_map", ".", "on", "(", "'mousemove'", ",", "this", ".", "_handleMeasureMove", ",", "this", ")", ".", "on", "(", "'mouseout'", ",", "this", ".", "_handleMapMouseOut", ",", "this", ")", ".", "on", "(", "'move'", ",", "this", ".", "_centerCaptureMarker", ",", "this", ")", ".", "on", "(", "'resize'", ",", "this", ".", "_setCaptureMarkerIcon", ",", "this", ")", ";", "L", ".", "DomEvent", ".", "on", "(", "this", ".", "_container", ",", "'mouseenter'", ",", "this", ".", "_handleMapMouseOut", ",", "this", ")", ";", "this", ".", "_updateMeasureStartedNoPoints", "(", ")", ";", "this", ".", "_map", ".", "fire", "(", "'measurestart'", ",", "null", ",", "false", ")", ";", "}" ]
get state vars and interface ready for measure
[ "get", "state", "vars", "and", "interface", "ready", "for", "measure" ]
756dff840e42a884e7a41bc512e5fd5be130f1ce
https://github.com/ljagis/leaflet-measure/blob/756dff840e42a884e7a41bc512e5fd5be130f1ce/src/leaflet-measure.js#L145-L171
12,191
ljagis/leaflet-measure
src/leaflet-measure.js
function() { const model = L.extend({}, this._resultsModel, { points: this._latlngs }); this._locked = false; L.DomEvent.off(this._container, 'mouseover', this._handleMapMouseOut, this); this._clearMeasure(); this._captureMarker .off('mouseout', this._handleMapMouseOut, this) .off('dblclick', this._handleMeasureDoubleClick, this) .off('click', this._handleMeasureClick, this); this._map .off('mousemove', this._handleMeasureMove, this) .off('mouseout', this._handleMapMouseOut, this) .off('move', this._centerCaptureMarker, this) .off('resize', this._setCaptureMarkerIcon, this); this._layer.removeLayer(this._measureVertexes).removeLayer(this._captureMarker); this._measureVertexes = null; this._updateMeasureNotStarted(); this._collapse(); this._map.fire('measurefinish', model, false); }
javascript
function() { const model = L.extend({}, this._resultsModel, { points: this._latlngs }); this._locked = false; L.DomEvent.off(this._container, 'mouseover', this._handleMapMouseOut, this); this._clearMeasure(); this._captureMarker .off('mouseout', this._handleMapMouseOut, this) .off('dblclick', this._handleMeasureDoubleClick, this) .off('click', this._handleMeasureClick, this); this._map .off('mousemove', this._handleMeasureMove, this) .off('mouseout', this._handleMapMouseOut, this) .off('move', this._centerCaptureMarker, this) .off('resize', this._setCaptureMarkerIcon, this); this._layer.removeLayer(this._measureVertexes).removeLayer(this._captureMarker); this._measureVertexes = null; this._updateMeasureNotStarted(); this._collapse(); this._map.fire('measurefinish', model, false); }
[ "function", "(", ")", "{", "const", "model", "=", "L", ".", "extend", "(", "{", "}", ",", "this", ".", "_resultsModel", ",", "{", "points", ":", "this", ".", "_latlngs", "}", ")", ";", "this", ".", "_locked", "=", "false", ";", "L", ".", "DomEvent", ".", "off", "(", "this", ".", "_container", ",", "'mouseover'", ",", "this", ".", "_handleMapMouseOut", ",", "this", ")", ";", "this", ".", "_clearMeasure", "(", ")", ";", "this", ".", "_captureMarker", ".", "off", "(", "'mouseout'", ",", "this", ".", "_handleMapMouseOut", ",", "this", ")", ".", "off", "(", "'dblclick'", ",", "this", ".", "_handleMeasureDoubleClick", ",", "this", ")", ".", "off", "(", "'click'", ",", "this", ".", "_handleMeasureClick", ",", "this", ")", ";", "this", ".", "_map", ".", "off", "(", "'mousemove'", ",", "this", ".", "_handleMeasureMove", ",", "this", ")", ".", "off", "(", "'mouseout'", ",", "this", ".", "_handleMapMouseOut", ",", "this", ")", ".", "off", "(", "'move'", ",", "this", ".", "_centerCaptureMarker", ",", "this", ")", ".", "off", "(", "'resize'", ",", "this", ".", "_setCaptureMarkerIcon", ",", "this", ")", ";", "this", ".", "_layer", ".", "removeLayer", "(", "this", ".", "_measureVertexes", ")", ".", "removeLayer", "(", "this", ".", "_captureMarker", ")", ";", "this", ".", "_measureVertexes", "=", "null", ";", "this", ".", "_updateMeasureNotStarted", "(", ")", ";", "this", ".", "_collapse", "(", ")", ";", "this", ".", "_map", ".", "fire", "(", "'measurefinish'", ",", "model", ",", "false", ")", ";", "}" ]
return to state with no measure in progress, undo `this._startMeasure`
[ "return", "to", "state", "with", "no", "measure", "in", "progress", "undo", "this", ".", "_startMeasure" ]
756dff840e42a884e7a41bc512e5fd5be130f1ce
https://github.com/ljagis/leaflet-measure/blob/756dff840e42a884e7a41bc512e5fd5be130f1ce/src/leaflet-measure.js#L173-L200
12,192
ljagis/leaflet-measure
src/leaflet-measure.js
function() { this._latlngs = []; this._resultsModel = null; this._measureVertexes.clearLayers(); if (this._measureDrag) { this._layer.removeLayer(this._measureDrag); } if (this._measureArea) { this._layer.removeLayer(this._measureArea); } if (this._measureBoundary) { this._layer.removeLayer(this._measureBoundary); } this._measureDrag = null; this._measureArea = null; this._measureBoundary = null; }
javascript
function() { this._latlngs = []; this._resultsModel = null; this._measureVertexes.clearLayers(); if (this._measureDrag) { this._layer.removeLayer(this._measureDrag); } if (this._measureArea) { this._layer.removeLayer(this._measureArea); } if (this._measureBoundary) { this._layer.removeLayer(this._measureBoundary); } this._measureDrag = null; this._measureArea = null; this._measureBoundary = null; }
[ "function", "(", ")", "{", "this", ".", "_latlngs", "=", "[", "]", ";", "this", ".", "_resultsModel", "=", "null", ";", "this", ".", "_measureVertexes", ".", "clearLayers", "(", ")", ";", "if", "(", "this", ".", "_measureDrag", ")", "{", "this", ".", "_layer", ".", "removeLayer", "(", "this", ".", "_measureDrag", ")", ";", "}", "if", "(", "this", ".", "_measureArea", ")", "{", "this", ".", "_layer", ".", "removeLayer", "(", "this", ".", "_measureArea", ")", ";", "}", "if", "(", "this", ".", "_measureBoundary", ")", "{", "this", ".", "_layer", ".", "removeLayer", "(", "this", ".", "_measureBoundary", ")", ";", "}", "this", ".", "_measureDrag", "=", "null", ";", "this", ".", "_measureArea", "=", "null", ";", "this", ".", "_measureBoundary", "=", "null", ";", "}" ]
clear all running measure data
[ "clear", "all", "running", "measure", "data" ]
756dff840e42a884e7a41bc512e5fd5be130f1ce
https://github.com/ljagis/leaflet-measure/blob/756dff840e42a884e7a41bc512e5fd5be130f1ce/src/leaflet-measure.js#L202-L218
12,193
ljagis/leaflet-measure
src/leaflet-measure.js
function() { const calced = calc(this._latlngs); const model = (this._resultsModel = L.extend( {}, calced, this._getMeasurementDisplayStrings(calced), { pointCount: this._latlngs.length } )); this.$results.innerHTML = resultsTemplateCompiled({ model }); }
javascript
function() { const calced = calc(this._latlngs); const model = (this._resultsModel = L.extend( {}, calced, this._getMeasurementDisplayStrings(calced), { pointCount: this._latlngs.length } )); this.$results.innerHTML = resultsTemplateCompiled({ model }); }
[ "function", "(", ")", "{", "const", "calced", "=", "calc", "(", "this", ".", "_latlngs", ")", ";", "const", "model", "=", "(", "this", ".", "_resultsModel", "=", "L", ".", "extend", "(", "{", "}", ",", "calced", ",", "this", ".", "_getMeasurementDisplayStrings", "(", "calced", ")", ",", "{", "pointCount", ":", "this", ".", "_latlngs", ".", "length", "}", ")", ")", ";", "this", ".", "$results", ".", "innerHTML", "=", "resultsTemplateCompiled", "(", "{", "model", "}", ")", ";", "}" ]
update results area of dom with calced measure from `this._latlngs`
[ "update", "results", "area", "of", "dom", "with", "calced", "measure", "from", "this", ".", "_latlngs" ]
756dff840e42a884e7a41bc512e5fd5be130f1ce
https://github.com/ljagis/leaflet-measure/blob/756dff840e42a884e7a41bc512e5fd5be130f1ce/src/leaflet-measure.js#L295-L306
12,194
ljagis/leaflet-measure
src/leaflet-measure.js
function(evt) { if (!this._measureDrag) { this._measureDrag = L.circleMarker(evt.latlng, this._symbols.getSymbol('measureDrag')).addTo( this._layer ); } else { this._measureDrag.setLatLng(evt.latlng); } this._measureDrag.bringToFront(); }
javascript
function(evt) { if (!this._measureDrag) { this._measureDrag = L.circleMarker(evt.latlng, this._symbols.getSymbol('measureDrag')).addTo( this._layer ); } else { this._measureDrag.setLatLng(evt.latlng); } this._measureDrag.bringToFront(); }
[ "function", "(", "evt", ")", "{", "if", "(", "!", "this", ".", "_measureDrag", ")", "{", "this", ".", "_measureDrag", "=", "L", ".", "circleMarker", "(", "evt", ".", "latlng", ",", "this", ".", "_symbols", ".", "getSymbol", "(", "'measureDrag'", ")", ")", ".", "addTo", "(", "this", ".", "_layer", ")", ";", "}", "else", "{", "this", ".", "_measureDrag", ".", "setLatLng", "(", "evt", ".", "latlng", ")", ";", "}", "this", ".", "_measureDrag", ".", "bringToFront", "(", ")", ";", "}" ]
mouse move handler while measure in progress adds floating measure marker under cursor
[ "mouse", "move", "handler", "while", "measure", "in", "progress", "adds", "floating", "measure", "marker", "under", "cursor" ]
756dff840e42a884e7a41bc512e5fd5be130f1ce
https://github.com/ljagis/leaflet-measure/blob/756dff840e42a884e7a41bc512e5fd5be130f1ce/src/leaflet-measure.js#L309-L318
12,195
ljagis/leaflet-measure
src/leaflet-measure.js
function() { const latlngs = this._latlngs; let resultFeature, popupContent; this._finishMeasure(); if (!latlngs.length) { return; } if (latlngs.length > 2) { latlngs.push(latlngs[0]); // close path to get full perimeter measurement for areas } const calced = calc(latlngs); if (latlngs.length === 1) { resultFeature = L.circleMarker(latlngs[0], this._symbols.getSymbol('resultPoint')); popupContent = pointPopupTemplateCompiled({ model: calced }); } else if (latlngs.length === 2) { resultFeature = L.polyline(latlngs, this._symbols.getSymbol('resultLine')); popupContent = linePopupTemplateCompiled({ model: L.extend({}, calced, this._getMeasurementDisplayStrings(calced)) }); } else { resultFeature = L.polygon(latlngs, this._symbols.getSymbol('resultArea')); popupContent = areaPopupTemplateCompiled({ model: L.extend({}, calced, this._getMeasurementDisplayStrings(calced)) }); } const popupContainer = L.DomUtil.create('div', ''); popupContainer.innerHTML = popupContent; const zoomLink = $('.js-zoomto', popupContainer); if (zoomLink) { L.DomEvent.on(zoomLink, 'click', L.DomEvent.stop); L.DomEvent.on( zoomLink, 'click', function() { if (resultFeature.getBounds) { this._map.fitBounds(resultFeature.getBounds(), { padding: [20, 20], maxZoom: 17 }); } else if (resultFeature.getLatLng) { this._map.panTo(resultFeature.getLatLng()); } }, this ); } const deleteLink = $('.js-deletemarkup', popupContainer); if (deleteLink) { L.DomEvent.on(deleteLink, 'click', L.DomEvent.stop); L.DomEvent.on( deleteLink, 'click', function() { // TODO. maybe remove any event handlers on zoom and delete buttons? this._layer.removeLayer(resultFeature); }, this ); } resultFeature.addTo(this._layer); resultFeature.bindPopup(popupContainer, this.options.popupOptions); if (resultFeature.getBounds) { resultFeature.openPopup(resultFeature.getBounds().getCenter()); } else if (resultFeature.getLatLng) { resultFeature.openPopup(resultFeature.getLatLng()); } }
javascript
function() { const latlngs = this._latlngs; let resultFeature, popupContent; this._finishMeasure(); if (!latlngs.length) { return; } if (latlngs.length > 2) { latlngs.push(latlngs[0]); // close path to get full perimeter measurement for areas } const calced = calc(latlngs); if (latlngs.length === 1) { resultFeature = L.circleMarker(latlngs[0], this._symbols.getSymbol('resultPoint')); popupContent = pointPopupTemplateCompiled({ model: calced }); } else if (latlngs.length === 2) { resultFeature = L.polyline(latlngs, this._symbols.getSymbol('resultLine')); popupContent = linePopupTemplateCompiled({ model: L.extend({}, calced, this._getMeasurementDisplayStrings(calced)) }); } else { resultFeature = L.polygon(latlngs, this._symbols.getSymbol('resultArea')); popupContent = areaPopupTemplateCompiled({ model: L.extend({}, calced, this._getMeasurementDisplayStrings(calced)) }); } const popupContainer = L.DomUtil.create('div', ''); popupContainer.innerHTML = popupContent; const zoomLink = $('.js-zoomto', popupContainer); if (zoomLink) { L.DomEvent.on(zoomLink, 'click', L.DomEvent.stop); L.DomEvent.on( zoomLink, 'click', function() { if (resultFeature.getBounds) { this._map.fitBounds(resultFeature.getBounds(), { padding: [20, 20], maxZoom: 17 }); } else if (resultFeature.getLatLng) { this._map.panTo(resultFeature.getLatLng()); } }, this ); } const deleteLink = $('.js-deletemarkup', popupContainer); if (deleteLink) { L.DomEvent.on(deleteLink, 'click', L.DomEvent.stop); L.DomEvent.on( deleteLink, 'click', function() { // TODO. maybe remove any event handlers on zoom and delete buttons? this._layer.removeLayer(resultFeature); }, this ); } resultFeature.addTo(this._layer); resultFeature.bindPopup(popupContainer, this.options.popupOptions); if (resultFeature.getBounds) { resultFeature.openPopup(resultFeature.getBounds().getCenter()); } else if (resultFeature.getLatLng) { resultFeature.openPopup(resultFeature.getLatLng()); } }
[ "function", "(", ")", "{", "const", "latlngs", "=", "this", ".", "_latlngs", ";", "let", "resultFeature", ",", "popupContent", ";", "this", ".", "_finishMeasure", "(", ")", ";", "if", "(", "!", "latlngs", ".", "length", ")", "{", "return", ";", "}", "if", "(", "latlngs", ".", "length", ">", "2", ")", "{", "latlngs", ".", "push", "(", "latlngs", "[", "0", "]", ")", ";", "// close path to get full perimeter measurement for areas", "}", "const", "calced", "=", "calc", "(", "latlngs", ")", ";", "if", "(", "latlngs", ".", "length", "===", "1", ")", "{", "resultFeature", "=", "L", ".", "circleMarker", "(", "latlngs", "[", "0", "]", ",", "this", ".", "_symbols", ".", "getSymbol", "(", "'resultPoint'", ")", ")", ";", "popupContent", "=", "pointPopupTemplateCompiled", "(", "{", "model", ":", "calced", "}", ")", ";", "}", "else", "if", "(", "latlngs", ".", "length", "===", "2", ")", "{", "resultFeature", "=", "L", ".", "polyline", "(", "latlngs", ",", "this", ".", "_symbols", ".", "getSymbol", "(", "'resultLine'", ")", ")", ";", "popupContent", "=", "linePopupTemplateCompiled", "(", "{", "model", ":", "L", ".", "extend", "(", "{", "}", ",", "calced", ",", "this", ".", "_getMeasurementDisplayStrings", "(", "calced", ")", ")", "}", ")", ";", "}", "else", "{", "resultFeature", "=", "L", ".", "polygon", "(", "latlngs", ",", "this", ".", "_symbols", ".", "getSymbol", "(", "'resultArea'", ")", ")", ";", "popupContent", "=", "areaPopupTemplateCompiled", "(", "{", "model", ":", "L", ".", "extend", "(", "{", "}", ",", "calced", ",", "this", ".", "_getMeasurementDisplayStrings", "(", "calced", ")", ")", "}", ")", ";", "}", "const", "popupContainer", "=", "L", ".", "DomUtil", ".", "create", "(", "'div'", ",", "''", ")", ";", "popupContainer", ".", "innerHTML", "=", "popupContent", ";", "const", "zoomLink", "=", "$", "(", "'.js-zoomto'", ",", "popupContainer", ")", ";", "if", "(", "zoomLink", ")", "{", "L", ".", "DomEvent", ".", "on", "(", "zoomLink", ",", "'click'", ",", "L", ".", "DomEvent", ".", "stop", ")", ";", "L", ".", "DomEvent", ".", "on", "(", "zoomLink", ",", "'click'", ",", "function", "(", ")", "{", "if", "(", "resultFeature", ".", "getBounds", ")", "{", "this", ".", "_map", ".", "fitBounds", "(", "resultFeature", ".", "getBounds", "(", ")", ",", "{", "padding", ":", "[", "20", ",", "20", "]", ",", "maxZoom", ":", "17", "}", ")", ";", "}", "else", "if", "(", "resultFeature", ".", "getLatLng", ")", "{", "this", ".", "_map", ".", "panTo", "(", "resultFeature", ".", "getLatLng", "(", ")", ")", ";", "}", "}", ",", "this", ")", ";", "}", "const", "deleteLink", "=", "$", "(", "'.js-deletemarkup'", ",", "popupContainer", ")", ";", "if", "(", "deleteLink", ")", "{", "L", ".", "DomEvent", ".", "on", "(", "deleteLink", ",", "'click'", ",", "L", ".", "DomEvent", ".", "stop", ")", ";", "L", ".", "DomEvent", ".", "on", "(", "deleteLink", ",", "'click'", ",", "function", "(", ")", "{", "// TODO. maybe remove any event handlers on zoom and delete buttons?", "this", ".", "_layer", ".", "removeLayer", "(", "resultFeature", ")", ";", "}", ",", "this", ")", ";", "}", "resultFeature", ".", "addTo", "(", "this", ".", "_layer", ")", ";", "resultFeature", ".", "bindPopup", "(", "popupContainer", ",", "this", ".", "options", ".", "popupOptions", ")", ";", "if", "(", "resultFeature", ".", "getBounds", ")", "{", "resultFeature", ".", "openPopup", "(", "resultFeature", ".", "getBounds", "(", ")", ".", "getCenter", "(", ")", ")", ";", "}", "else", "if", "(", "resultFeature", ".", "getLatLng", ")", "{", "resultFeature", ".", "openPopup", "(", "resultFeature", ".", "getLatLng", "(", ")", ")", ";", "}", "}" ]
handler for both double click and clicking finish button do final calc and finish out current measure, clear dom and internal state, add permanent map features
[ "handler", "for", "both", "double", "click", "and", "clicking", "finish", "button", "do", "final", "calc", "and", "finish", "out", "current", "measure", "clear", "dom", "and", "internal", "state", "add", "permanent", "map", "features" ]
756dff840e42a884e7a41bc512e5fd5be130f1ce
https://github.com/ljagis/leaflet-measure/blob/756dff840e42a884e7a41bc512e5fd5be130f1ce/src/leaflet-measure.js#L321-L398
12,196
ljagis/leaflet-measure
src/leaflet-measure.js
function(evt) { const latlng = this._map.mouseEventToLatLng(evt.originalEvent), // get actual latlng instead of the marker's latlng from originalEvent lastClick = this._latlngs[this._latlngs.length - 1], vertexSymbol = this._symbols.getSymbol('measureVertex'); if (!lastClick || !latlng.equals(lastClick)) { // skip if same point as last click, happens on `dblclick` this._latlngs.push(latlng); this._addMeasureArea(this._latlngs); this._addMeasureBoundary(this._latlngs); this._measureVertexes.eachLayer(function(layer) { layer.setStyle(vertexSymbol); // reset all vertexes to non-active class - only last vertex is active // `layer.setStyle({ className: 'layer-measurevertex'})` doesn't work. https://github.com/leaflet/leaflet/issues/2662 // set attribute on path directly if (layer._path) { layer._path.setAttribute('class', vertexSymbol.className); } }); this._addNewVertex(latlng); if (this._measureBoundary) { this._measureBoundary.bringToFront(); } this._measureVertexes.bringToFront(); } this._updateResults(); this._updateMeasureStartedWithPoints(); }
javascript
function(evt) { const latlng = this._map.mouseEventToLatLng(evt.originalEvent), // get actual latlng instead of the marker's latlng from originalEvent lastClick = this._latlngs[this._latlngs.length - 1], vertexSymbol = this._symbols.getSymbol('measureVertex'); if (!lastClick || !latlng.equals(lastClick)) { // skip if same point as last click, happens on `dblclick` this._latlngs.push(latlng); this._addMeasureArea(this._latlngs); this._addMeasureBoundary(this._latlngs); this._measureVertexes.eachLayer(function(layer) { layer.setStyle(vertexSymbol); // reset all vertexes to non-active class - only last vertex is active // `layer.setStyle({ className: 'layer-measurevertex'})` doesn't work. https://github.com/leaflet/leaflet/issues/2662 // set attribute on path directly if (layer._path) { layer._path.setAttribute('class', vertexSymbol.className); } }); this._addNewVertex(latlng); if (this._measureBoundary) { this._measureBoundary.bringToFront(); } this._measureVertexes.bringToFront(); } this._updateResults(); this._updateMeasureStartedWithPoints(); }
[ "function", "(", "evt", ")", "{", "const", "latlng", "=", "this", ".", "_map", ".", "mouseEventToLatLng", "(", "evt", ".", "originalEvent", ")", ",", "// get actual latlng instead of the marker's latlng from originalEvent", "lastClick", "=", "this", ".", "_latlngs", "[", "this", ".", "_latlngs", ".", "length", "-", "1", "]", ",", "vertexSymbol", "=", "this", ".", "_symbols", ".", "getSymbol", "(", "'measureVertex'", ")", ";", "if", "(", "!", "lastClick", "||", "!", "latlng", ".", "equals", "(", "lastClick", ")", ")", "{", "// skip if same point as last click, happens on `dblclick`", "this", ".", "_latlngs", ".", "push", "(", "latlng", ")", ";", "this", ".", "_addMeasureArea", "(", "this", ".", "_latlngs", ")", ";", "this", ".", "_addMeasureBoundary", "(", "this", ".", "_latlngs", ")", ";", "this", ".", "_measureVertexes", ".", "eachLayer", "(", "function", "(", "layer", ")", "{", "layer", ".", "setStyle", "(", "vertexSymbol", ")", ";", "// reset all vertexes to non-active class - only last vertex is active", "// `layer.setStyle({ className: 'layer-measurevertex'})` doesn't work. https://github.com/leaflet/leaflet/issues/2662", "// set attribute on path directly", "if", "(", "layer", ".", "_path", ")", "{", "layer", ".", "_path", ".", "setAttribute", "(", "'class'", ",", "vertexSymbol", ".", "className", ")", ";", "}", "}", ")", ";", "this", ".", "_addNewVertex", "(", "latlng", ")", ";", "if", "(", "this", ".", "_measureBoundary", ")", "{", "this", ".", "_measureBoundary", ".", "bringToFront", "(", ")", ";", "}", "this", ".", "_measureVertexes", ".", "bringToFront", "(", ")", ";", "}", "this", ".", "_updateResults", "(", ")", ";", "this", ".", "_updateMeasureStartedWithPoints", "(", ")", ";", "}" ]
handle map click during ongoing measurement add new clicked point, update measure layers and results ui
[ "handle", "map", "click", "during", "ongoing", "measurement", "add", "new", "clicked", "point", "update", "measure", "layers", "and", "results", "ui" ]
756dff840e42a884e7a41bc512e5fd5be130f1ce
https://github.com/ljagis/leaflet-measure/blob/756dff840e42a884e7a41bc512e5fd5be130f1ce/src/leaflet-measure.js#L401-L432
12,197
que-etc/resize-observer-polyfill
src/utils/geometry.js
getBordersSize
function getBordersSize(styles, ...positions) { return positions.reduce((size, position) => { const value = styles['border-' + position + '-width']; return size + toFloat(value); }, 0); }
javascript
function getBordersSize(styles, ...positions) { return positions.reduce((size, position) => { const value = styles['border-' + position + '-width']; return size + toFloat(value); }, 0); }
[ "function", "getBordersSize", "(", "styles", ",", "...", "positions", ")", "{", "return", "positions", ".", "reduce", "(", "(", "size", ",", "position", ")", "=>", "{", "const", "value", "=", "styles", "[", "'border-'", "+", "position", "+", "'-width'", "]", ";", "return", "size", "+", "toFloat", "(", "value", ")", ";", "}", ",", "0", ")", ";", "}" ]
Extracts borders size from provided styles. @param {CSSStyleDeclaration} styles @param {...string} positions - Borders positions (top, right, ...) @returns {number}
[ "Extracts", "borders", "size", "from", "provided", "styles", "." ]
4a148452494a155656e4d04b9732b5914896b2e0
https://github.com/que-etc/resize-observer-polyfill/blob/4a148452494a155656e4d04b9732b5914896b2e0/src/utils/geometry.js#L25-L31
12,198
que-etc/resize-observer-polyfill
src/utils/geometry.js
getPaddings
function getPaddings(styles) { const positions = ['top', 'right', 'bottom', 'left']; const paddings = {}; for (const position of positions) { const value = styles['padding-' + position]; paddings[position] = toFloat(value); } return paddings; }
javascript
function getPaddings(styles) { const positions = ['top', 'right', 'bottom', 'left']; const paddings = {}; for (const position of positions) { const value = styles['padding-' + position]; paddings[position] = toFloat(value); } return paddings; }
[ "function", "getPaddings", "(", "styles", ")", "{", "const", "positions", "=", "[", "'top'", ",", "'right'", ",", "'bottom'", ",", "'left'", "]", ";", "const", "paddings", "=", "{", "}", ";", "for", "(", "const", "position", "of", "positions", ")", "{", "const", "value", "=", "styles", "[", "'padding-'", "+", "position", "]", ";", "paddings", "[", "position", "]", "=", "toFloat", "(", "value", ")", ";", "}", "return", "paddings", ";", "}" ]
Extracts paddings sizes from provided styles. @param {CSSStyleDeclaration} styles @returns {Object} Paddings box.
[ "Extracts", "paddings", "sizes", "from", "provided", "styles", "." ]
4a148452494a155656e4d04b9732b5914896b2e0
https://github.com/que-etc/resize-observer-polyfill/blob/4a148452494a155656e4d04b9732b5914896b2e0/src/utils/geometry.js#L39-L50
12,199
que-etc/resize-observer-polyfill
src/utils/geometry.js
getSVGContentRect
function getSVGContentRect(target) { const bbox = target.getBBox(); return createRectInit(0, 0, bbox.width, bbox.height); }
javascript
function getSVGContentRect(target) { const bbox = target.getBBox(); return createRectInit(0, 0, bbox.width, bbox.height); }
[ "function", "getSVGContentRect", "(", "target", ")", "{", "const", "bbox", "=", "target", ".", "getBBox", "(", ")", ";", "return", "createRectInit", "(", "0", ",", "0", ",", "bbox", ".", "width", ",", "bbox", ".", "height", ")", ";", "}" ]
Calculates content rectangle of provided SVG element. @param {SVGGraphicsElement} target - Element content rectangle of which needs to be calculated. @returns {DOMRectInit}
[ "Calculates", "content", "rectangle", "of", "provided", "SVG", "element", "." ]
4a148452494a155656e4d04b9732b5914896b2e0
https://github.com/que-etc/resize-observer-polyfill/blob/4a148452494a155656e4d04b9732b5914896b2e0/src/utils/geometry.js#L59-L63