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
15,600
leapmotion/leapjs
examples/lib/leap-plugins-0.1.6.js
function () { if (this.frameData.length == 0) { return 0 } return this.frameData.length / (this.frameData[this.frameData.length - 1].timestamp - this.frameData[0].timestamp) * 1000000; }
javascript
function () { if (this.frameData.length == 0) { return 0 } return this.frameData.length / (this.frameData[this.frameData.length - 1].timestamp - this.frameData[0].timestamp) * 1000000; }
[ "function", "(", ")", "{", "if", "(", "this", ".", "frameData", ".", "length", "==", "0", ")", "{", "return", "0", "}", "return", "this", ".", "frameData", ".", "length", "/", "(", "this", ".", "frameData", "[", "this", ".", "frameData", ".", "length", "-", "1", "]", ".", "timestamp", "-", "this", ".", "frameData", "[", "0", "]", ".", "timestamp", ")", "*", "1000000", ";", "}" ]
Returns the average frames per second of the recording
[ "Returns", "the", "average", "frames", "per", "second", "of", "the", "recording" ]
31b00723f98077304acda3200f9fbcbaaf29294a
https://github.com/leapmotion/leapjs/blob/31b00723f98077304acda3200f9fbcbaaf29294a/examples/lib/leap-plugins-0.1.6.js#L1125-L1130
15,601
leapmotion/leapjs
examples/lib/leap-plugins-0.1.6.js
function(){ var frameData = this.croppedFrameData(), packedFrames = [], frameDatum; packedFrames.push(this.packingStructure); for (var i = 0, len = frameData.length; i < len; i++){ frameDatum = frameData[i]; packedFrames.push( this.packArray( this.packingStructure, frameDatum ) ); } return packedFrames; }
javascript
function(){ var frameData = this.croppedFrameData(), packedFrames = [], frameDatum; packedFrames.push(this.packingStructure); for (var i = 0, len = frameData.length; i < len; i++){ frameDatum = frameData[i]; packedFrames.push( this.packArray( this.packingStructure, frameDatum ) ); } return packedFrames; }
[ "function", "(", ")", "{", "var", "frameData", "=", "this", ".", "croppedFrameData", "(", ")", ",", "packedFrames", "=", "[", "]", ",", "frameDatum", ";", "packedFrames", ".", "push", "(", "this", ".", "packingStructure", ")", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "frameData", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "frameDatum", "=", "frameData", "[", "i", "]", ";", "packedFrames", ".", "push", "(", "this", ".", "packArray", "(", "this", ".", "packingStructure", ",", "frameDatum", ")", ")", ";", "}", "return", "packedFrames", ";", "}" ]
returns an array the first item is the keys of the following items nested arrays are expected to have idententical siblings
[ "returns", "an", "array", "the", "first", "item", "is", "the", "keys", "of", "the", "following", "items", "nested", "arrays", "are", "expected", "to", "have", "idententical", "siblings" ]
31b00723f98077304acda3200f9fbcbaaf29294a
https://github.com/leapmotion/leapjs/blob/31b00723f98077304acda3200f9fbcbaaf29294a/examples/lib/leap-plugins-0.1.6.js#L1160-L1180
15,602
leapmotion/leapjs
examples/lib/leap-plugins-0.1.6.js
function(packedFrames){ var packingStructure = packedFrames[0]; var frameData = [], frameDatum; for (var i = 1, len = packedFrames.length; i < len; i++) { frameDatum = packedFrames[i]; frameData.push( this.unPackArray( packingStructure, frameDatum ) ); } return frameData; }
javascript
function(packedFrames){ var packingStructure = packedFrames[0]; var frameData = [], frameDatum; for (var i = 1, len = packedFrames.length; i < len; i++) { frameDatum = packedFrames[i]; frameData.push( this.unPackArray( packingStructure, frameDatum ) ); } return frameData; }
[ "function", "(", "packedFrames", ")", "{", "var", "packingStructure", "=", "packedFrames", "[", "0", "]", ";", "var", "frameData", "=", "[", "]", ",", "frameDatum", ";", "for", "(", "var", "i", "=", "1", ",", "len", "=", "packedFrames", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "frameDatum", "=", "packedFrames", "[", "i", "]", ";", "frameData", ".", "push", "(", "this", ".", "unPackArray", "(", "packingStructure", ",", "frameDatum", ")", ")", ";", "}", "return", "frameData", ";", "}" ]
expects the first array element to describe the following arrays this algorithm copies frames to a new array could there be merit in something which would do an in-place substitution?
[ "expects", "the", "first", "array", "element", "to", "describe", "the", "following", "arrays", "this", "algorithm", "copies", "frames", "to", "a", "new", "array", "could", "there", "be", "merit", "in", "something", "which", "would", "do", "an", "in", "-", "place", "substitution?" ]
31b00723f98077304acda3200f9fbcbaaf29294a
https://github.com/leapmotion/leapjs/blob/31b00723f98077304acda3200f9fbcbaaf29294a/examples/lib/leap-plugins-0.1.6.js#L1236-L1253
15,603
leapmotion/leapjs
examples/lib/leap-plugins-0.1.6.js
function (callback) { var xhr = new XMLHttpRequest(), url = this.url, recording = this, contentLength = 0; xhr.onreadystatechange = function () { if (xhr.readyState === xhr.DONE) { if (xhr.status === 200 || xhr.status === 0) { if (xhr.responseText) { recording.finishLoad(xhr.responseText, callback); } else { console.error('Leap Playback: "' + url + '" seems to be unreachable or the file is empty.'); } } else { console.error('Leap Playback: Couldn\'t load "' + url + '" (' + xhr.status + ')'); } } }; xhr.addEventListener('progress', function(oEvent){ if ( recording.options.loadProgress ) { if (oEvent.lengthComputable) { var percentComplete = oEvent.loaded / oEvent.total; recording.options.loadProgress( recording, percentComplete, oEvent ); } } }); this.loading = true; xhr.open("GET", url, true); xhr.send(null); }
javascript
function (callback) { var xhr = new XMLHttpRequest(), url = this.url, recording = this, contentLength = 0; xhr.onreadystatechange = function () { if (xhr.readyState === xhr.DONE) { if (xhr.status === 200 || xhr.status === 0) { if (xhr.responseText) { recording.finishLoad(xhr.responseText, callback); } else { console.error('Leap Playback: "' + url + '" seems to be unreachable or the file is empty.'); } } else { console.error('Leap Playback: Couldn\'t load "' + url + '" (' + xhr.status + ')'); } } }; xhr.addEventListener('progress', function(oEvent){ if ( recording.options.loadProgress ) { if (oEvent.lengthComputable) { var percentComplete = oEvent.loaded / oEvent.total; recording.options.loadProgress( recording, percentComplete, oEvent ); } } }); this.loading = true; xhr.open("GET", url, true); xhr.send(null); }
[ "function", "(", "callback", ")", "{", "var", "xhr", "=", "new", "XMLHttpRequest", "(", ")", ",", "url", "=", "this", ".", "url", ",", "recording", "=", "this", ",", "contentLength", "=", "0", ";", "xhr", ".", "onreadystatechange", "=", "function", "(", ")", "{", "if", "(", "xhr", ".", "readyState", "===", "xhr", ".", "DONE", ")", "{", "if", "(", "xhr", ".", "status", "===", "200", "||", "xhr", ".", "status", "===", "0", ")", "{", "if", "(", "xhr", ".", "responseText", ")", "{", "recording", ".", "finishLoad", "(", "xhr", ".", "responseText", ",", "callback", ")", ";", "}", "else", "{", "console", ".", "error", "(", "'Leap Playback: \"'", "+", "url", "+", "'\" seems to be unreachable or the file is empty.'", ")", ";", "}", "}", "else", "{", "console", ".", "error", "(", "'Leap Playback: Couldn\\'t load \"'", "+", "url", "+", "'\" ('", "+", "xhr", ".", "status", "+", "')'", ")", ";", "}", "}", "}", ";", "xhr", ".", "addEventListener", "(", "'progress'", ",", "function", "(", "oEvent", ")", "{", "if", "(", "recording", ".", "options", ".", "loadProgress", ")", "{", "if", "(", "oEvent", ".", "lengthComputable", ")", "{", "var", "percentComplete", "=", "oEvent", ".", "loaded", "/", "oEvent", ".", "total", ";", "recording", ".", "options", ".", "loadProgress", "(", "recording", ",", "percentComplete", ",", "oEvent", ")", ";", "}", "}", "}", ")", ";", "this", ".", "loading", "=", "true", ";", "xhr", ".", "open", "(", "\"GET\"", ",", "url", ",", "true", ")", ";", "xhr", ".", "send", "(", "null", ")", ";", "}" ]
optional callback once frames are loaded, will have a context of player
[ "optional", "callback", "once", "frames", "are", "loaded", "will", "have", "a", "context", "of", "player" ]
31b00723f98077304acda3200f9fbcbaaf29294a
https://github.com/leapmotion/leapjs/blob/31b00723f98077304acda3200f9fbcbaaf29294a/examples/lib/leap-plugins-0.1.6.js#L1381-L1420
15,604
leapmotion/leapjs
examples/lib/leap-plugins-0.1.6.js
function () { this.idle(); delete this.recording; this.recording = new Recording({ timeBetweenLoops: this.options.timeBetweenLoops, loop: this.options.loop, requestProtocolVersion: this.controller.connection.opts.requestProtocolVersion, serviceVersion: this.controller.connection.protocol.serviceVersion }); this.controller.emit('playback.stop', this); }
javascript
function () { this.idle(); delete this.recording; this.recording = new Recording({ timeBetweenLoops: this.options.timeBetweenLoops, loop: this.options.loop, requestProtocolVersion: this.controller.connection.opts.requestProtocolVersion, serviceVersion: this.controller.connection.protocol.serviceVersion }); this.controller.emit('playback.stop', this); }
[ "function", "(", ")", "{", "this", ".", "idle", "(", ")", ";", "delete", "this", ".", "recording", ";", "this", ".", "recording", "=", "new", "Recording", "(", "{", "timeBetweenLoops", ":", "this", ".", "options", ".", "timeBetweenLoops", ",", "loop", ":", "this", ".", "options", ".", "loop", ",", "requestProtocolVersion", ":", "this", ".", "controller", ".", "connection", ".", "opts", ".", "requestProtocolVersion", ",", "serviceVersion", ":", "this", ".", "controller", ".", "connection", ".", "protocol", ".", "serviceVersion", "}", ")", ";", "this", ".", "controller", ".", "emit", "(", "'playback.stop'", ",", "this", ")", ";", "}" ]
used after record
[ "used", "after", "record" ]
31b00723f98077304acda3200f9fbcbaaf29294a
https://github.com/leapmotion/leapjs/blob/31b00723f98077304acda3200f9fbcbaaf29294a/examples/lib/leap-plugins-0.1.6.js#L1646-L1659
15,605
leapmotion/leapjs
examples/lib/leap-plugins-0.1.6.js
function () { if (!this.recording || this.recording.blank()) return; var finalFrame = this.recording.cloneCurrentFrame(); finalFrame.hands = []; finalFrame.fingers = []; finalFrame.pointables = []; finalFrame.tools = []; this.sendImmediateFrame(finalFrame); }
javascript
function () { if (!this.recording || this.recording.blank()) return; var finalFrame = this.recording.cloneCurrentFrame(); finalFrame.hands = []; finalFrame.fingers = []; finalFrame.pointables = []; finalFrame.tools = []; this.sendImmediateFrame(finalFrame); }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "recording", "||", "this", ".", "recording", ".", "blank", "(", ")", ")", "return", ";", "var", "finalFrame", "=", "this", ".", "recording", ".", "cloneCurrentFrame", "(", ")", ";", "finalFrame", ".", "hands", "=", "[", "]", ";", "finalFrame", ".", "fingers", "=", "[", "]", ";", "finalFrame", ".", "pointables", "=", "[", "]", ";", "finalFrame", ".", "tools", "=", "[", "]", ";", "this", ".", "sendImmediateFrame", "(", "finalFrame", ")", ";", "}" ]
if there is existing frame data, sends a frame with nothing in it
[ "if", "there", "is", "existing", "frame", "data", "sends", "a", "frame", "with", "nothing", "in", "it" ]
31b00723f98077304acda3200f9fbcbaaf29294a
https://github.com/leapmotion/leapjs/blob/31b00723f98077304acda3200f9fbcbaaf29294a/examples/lib/leap-plugins-0.1.6.js#L1696-L1704
15,606
leapmotion/leapjs
examples/lib/leap-plugins-0.1.6.js
function (frameData) { // Would be better to check controller.streaming() in showOverlay, but that method doesn't exist, yet. this.setGraphic('wave'); if (frameData.hands.length > 0) { this.recording.addFrame(frameData); this.hideOverlay(); } else if ( !this.recording.blank() ) { this.finishRecording(); } }
javascript
function (frameData) { // Would be better to check controller.streaming() in showOverlay, but that method doesn't exist, yet. this.setGraphic('wave'); if (frameData.hands.length > 0) { this.recording.addFrame(frameData); this.hideOverlay(); } else if ( !this.recording.blank() ) { this.finishRecording(); } }
[ "function", "(", "frameData", ")", "{", "// Would be better to check controller.streaming() in showOverlay, but that method doesn't exist, yet.", "this", ".", "setGraphic", "(", "'wave'", ")", ";", "if", "(", "frameData", ".", "hands", ".", "length", ">", "0", ")", "{", "this", ".", "recording", ".", "addFrame", "(", "frameData", ")", ";", "this", ".", "hideOverlay", "(", ")", ";", "}", "else", "if", "(", "!", "this", ".", "recording", ".", "blank", "(", ")", ")", "{", "this", ".", "finishRecording", "(", ")", ";", "}", "}" ]
this method replaces connection.handleData when in record mode It accepts the raw connection data which is used to make a frame.
[ "this", "method", "replaces", "connection", ".", "handleData", "when", "in", "record", "mode", "It", "accepts", "the", "raw", "connection", "data", "which", "is", "used", "to", "make", "a", "frame", "." ]
31b00723f98077304acda3200f9fbcbaaf29294a
https://github.com/leapmotion/leapjs/blob/31b00723f98077304acda3200f9fbcbaaf29294a/examples/lib/leap-plugins-0.1.6.js#L1767-L1776
15,607
leapmotion/leapjs
examples/lib/leap-plugins-0.1.6.js
function (frames) { this.setFrames(frames); if (player.recording != this){ console.log('recordings changed during load'); return } // it would be better to use streamingCount here, but that won't be in until 0.5.0+ // For now, it just flashes for a moment until the first frame comes through with a hand on it. // if (autoPlay && (controller.streamingCount == 0 || pauseOnHand)) { if (player.autoPlay) { player.play(); if (player.pauseOnHand) { player.setGraphic('connect'); } } player.controller.emit('playback.recordingSet', this); }
javascript
function (frames) { this.setFrames(frames); if (player.recording != this){ console.log('recordings changed during load'); return } // it would be better to use streamingCount here, but that won't be in until 0.5.0+ // For now, it just flashes for a moment until the first frame comes through with a hand on it. // if (autoPlay && (controller.streamingCount == 0 || pauseOnHand)) { if (player.autoPlay) { player.play(); if (player.pauseOnHand) { player.setGraphic('connect'); } } player.controller.emit('playback.recordingSet', this); }
[ "function", "(", "frames", ")", "{", "this", ".", "setFrames", "(", "frames", ")", ";", "if", "(", "player", ".", "recording", "!=", "this", ")", "{", "console", ".", "log", "(", "'recordings changed during load'", ")", ";", "return", "}", "// it would be better to use streamingCount here, but that won't be in until 0.5.0+", "// For now, it just flashes for a moment until the first frame comes through with a hand on it.", "// if (autoPlay && (controller.streamingCount == 0 || pauseOnHand)) {", "if", "(", "player", ".", "autoPlay", ")", "{", "player", ".", "play", "(", ")", ";", "if", "(", "player", ".", "pauseOnHand", ")", "{", "player", ".", "setGraphic", "(", "'connect'", ")", ";", "}", "}", "player", ".", "controller", ".", "emit", "(", "'playback.recordingSet'", ",", "this", ")", ";", "}" ]
this is called on the context of the recording
[ "this", "is", "called", "on", "the", "context", "of", "the", "recording" ]
31b00723f98077304acda3200f9fbcbaaf29294a
https://github.com/leapmotion/leapjs/blob/31b00723f98077304acda3200f9fbcbaaf29294a/examples/lib/leap-plugins-0.1.6.js#L1789-L1809
15,608
leapmotion/leapjs
examples/lib/leap-plugins-0.1.6.js
function (graphicName) { if (!this.overlay) return; if (this.graphicName == graphicName) return; this.graphicName = graphicName; switch (graphicName) { case 'connect': this.overlay.style.display = 'block'; this.overlay.innerHTML = CONNECT_LEAP_ICON; break; case 'wave': this.overlay.style.display = 'block'; this.overlay.innerHTML = MOVE_HAND_OVER_LEAP_ICON; break; case undefined: this.overlay.innerHTML = ''; break; } }
javascript
function (graphicName) { if (!this.overlay) return; if (this.graphicName == graphicName) return; this.graphicName = graphicName; switch (graphicName) { case 'connect': this.overlay.style.display = 'block'; this.overlay.innerHTML = CONNECT_LEAP_ICON; break; case 'wave': this.overlay.style.display = 'block'; this.overlay.innerHTML = MOVE_HAND_OVER_LEAP_ICON; break; case undefined: this.overlay.innerHTML = ''; break; } }
[ "function", "(", "graphicName", ")", "{", "if", "(", "!", "this", ".", "overlay", ")", "return", ";", "if", "(", "this", ".", "graphicName", "==", "graphicName", ")", "return", ";", "this", ".", "graphicName", "=", "graphicName", ";", "switch", "(", "graphicName", ")", "{", "case", "'connect'", ":", "this", ".", "overlay", ".", "style", ".", "display", "=", "'block'", ";", "this", ".", "overlay", ".", "innerHTML", "=", "CONNECT_LEAP_ICON", ";", "break", ";", "case", "'wave'", ":", "this", ".", "overlay", ".", "style", ".", "display", "=", "'block'", ";", "this", ".", "overlay", ".", "innerHTML", "=", "MOVE_HAND_OVER_LEAP_ICON", ";", "break", ";", "case", "undefined", ":", "this", ".", "overlay", ".", "innerHTML", "=", "''", ";", "break", ";", "}", "}" ]
Accepts either "connect", "wave", or undefined.
[ "Accepts", "either", "connect", "wave", "or", "undefined", "." ]
31b00723f98077304acda3200f9fbcbaaf29294a
https://github.com/leapmotion/leapjs/blob/31b00723f98077304acda3200f9fbcbaaf29294a/examples/lib/leap-plugins-0.1.6.js#L1858-L1876
15,609
formly-js/vue-formly
src/util.js
hasNestedProperty
function hasNestedProperty(obj, propertyPath, returnVal = false) { if (!propertyPath) return false; // strip the leading dot propertyPath = propertyPath.replace(/^\./, ''); const properties = propertyPath.split('.'); for (var i = 0; i < properties.length; i++) { var prop = properties[i]; if (!obj || !obj.hasOwnProperty(prop)) { return returnVal ? null : false; } else { obj = obj[prop]; } } return returnVal ? obj : true; }
javascript
function hasNestedProperty(obj, propertyPath, returnVal = false) { if (!propertyPath) return false; // strip the leading dot propertyPath = propertyPath.replace(/^\./, ''); const properties = propertyPath.split('.'); for (var i = 0; i < properties.length; i++) { var prop = properties[i]; if (!obj || !obj.hasOwnProperty(prop)) { return returnVal ? null : false; } else { obj = obj[prop]; } } return returnVal ? obj : true; }
[ "function", "hasNestedProperty", "(", "obj", ",", "propertyPath", ",", "returnVal", "=", "false", ")", "{", "if", "(", "!", "propertyPath", ")", "return", "false", ";", "// strip the leading dot", "propertyPath", "=", "propertyPath", ".", "replace", "(", "/", "^\\.", "/", ",", "''", ")", ";", "const", "properties", "=", "propertyPath", ".", "split", "(", "'.'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "properties", ".", "length", ";", "i", "++", ")", "{", "var", "prop", "=", "properties", "[", "i", "]", ";", "if", "(", "!", "obj", "||", "!", "obj", ".", "hasOwnProperty", "(", "prop", ")", ")", "{", "return", "returnVal", "?", "null", ":", "false", ";", "}", "else", "{", "obj", "=", "obj", "[", "prop", "]", ";", "}", "}", "return", "returnVal", "?", "obj", ":", "true", ";", "}" ]
Checks to see whether an object has a deeply nested path @param {Object} target @param {String} propertyPath @param {Boolean} returnVal @returns {Boolean || Any} will return either true/false for existance or the actual value
[ "Checks", "to", "see", "whether", "an", "object", "has", "a", "deeply", "nested", "path" ]
37975d401f1acd17abf31792bb411b60b2dfedf3
https://github.com/formly-js/vue-formly/blob/37975d401f1acd17abf31792bb411b60b2dfedf3/src/util.js#L58-L76
15,610
aichaos/rivescript-js
eg/web-client/datadumper.js
DumperGetArgs
function DumperGetArgs(a,index) { var args = new Array(); // This is kind of ugly, but I don't want to use js1.2 functions, just in case... for (var i=index; i<a.length; i++) { args[args.length] = a[i]; } return args; }
javascript
function DumperGetArgs(a,index) { var args = new Array(); // This is kind of ugly, but I don't want to use js1.2 functions, just in case... for (var i=index; i<a.length; i++) { args[args.length] = a[i]; } return args; }
[ "function", "DumperGetArgs", "(", "a", ",", "index", ")", "{", "var", "args", "=", "new", "Array", "(", ")", ";", "// This is kind of ugly, but I don't want to use js1.2 functions, just in case...", "for", "(", "var", "i", "=", "index", ";", "i", "<", "a", ".", "length", ";", "i", "++", ")", "{", "args", "[", "args", ".", "length", "]", "=", "a", "[", "i", "]", ";", "}", "return", "args", ";", "}" ]
Holds properties to traverse for certain HTML tags
[ "Holds", "properties", "to", "traverse", "for", "certain", "HTML", "tags" ]
7f9407cda0d663d956666ae338e0f57d9dfe9785
https://github.com/aichaos/rivescript-js/blob/7f9407cda0d663d956666ae338e0f57d9dfe9785/eg/web-client/datadumper.js#L59-L66
15,611
aichaos/rivescript-js
eg/reply-async/weatherman.js
function(onReady) { var self = this; if (APPID === 'change me') { console.log('Error -- edit weatherman.js and provide the APPID for Open Weathermap.'.bold.yellow); } // Load the replies and process them. rs.loadFile("weatherman.rive").then(function() { rs.sortReplies(); onReady(); }).catch(function(err) { console.error(err); }); // This is a function for delivering the message to a user. Its actual // implementation could vary; for example if you were writing an IRC chatbot // this message could deliver a private message to a target username. self.sendMessage = function(username, message) { // This just logs it to the console like "[Bot] @username: message" console.log( ["[Brick Tamland]", message].join(": ").underline.green ); }; // This is a function for a user requesting a reply. It just proxies through // to RiveScript. self.getReply = function(username, message, callback) { return rs.reply(username, message, self); } }
javascript
function(onReady) { var self = this; if (APPID === 'change me') { console.log('Error -- edit weatherman.js and provide the APPID for Open Weathermap.'.bold.yellow); } // Load the replies and process them. rs.loadFile("weatherman.rive").then(function() { rs.sortReplies(); onReady(); }).catch(function(err) { console.error(err); }); // This is a function for delivering the message to a user. Its actual // implementation could vary; for example if you were writing an IRC chatbot // this message could deliver a private message to a target username. self.sendMessage = function(username, message) { // This just logs it to the console like "[Bot] @username: message" console.log( ["[Brick Tamland]", message].join(": ").underline.green ); }; // This is a function for a user requesting a reply. It just proxies through // to RiveScript. self.getReply = function(username, message, callback) { return rs.reply(username, message, self); } }
[ "function", "(", "onReady", ")", "{", "var", "self", "=", "this", ";", "if", "(", "APPID", "===", "'change me'", ")", "{", "console", ".", "log", "(", "'Error -- edit weatherman.js and provide the APPID for Open Weathermap.'", ".", "bold", ".", "yellow", ")", ";", "}", "// Load the replies and process them.", "rs", ".", "loadFile", "(", "\"weatherman.rive\"", ")", ".", "then", "(", "function", "(", ")", "{", "rs", ".", "sortReplies", "(", ")", ";", "onReady", "(", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "console", ".", "error", "(", "err", ")", ";", "}", ")", ";", "// This is a function for delivering the message to a user. Its actual", "// implementation could vary; for example if you were writing an IRC chatbot", "// this message could deliver a private message to a target username.", "self", ".", "sendMessage", "=", "function", "(", "username", ",", "message", ")", "{", "// This just logs it to the console like \"[Bot] @username: message\"", "console", ".", "log", "(", "[", "\"[Brick Tamland]\"", ",", "message", "]", ".", "join", "(", "\": \"", ")", ".", "underline", ".", "green", ")", ";", "}", ";", "// This is a function for a user requesting a reply. It just proxies through", "// to RiveScript.", "self", ".", "getReply", "=", "function", "(", "username", ",", "message", ",", "callback", ")", "{", "return", "rs", ".", "reply", "(", "username", ",", "message", ",", "self", ")", ";", "}", "}" ]
Create a prototypical class for our own chatbot.
[ "Create", "a", "prototypical", "class", "for", "our", "own", "chatbot", "." ]
7f9407cda0d663d956666ae338e0f57d9dfe9785
https://github.com/aichaos/rivescript-js/blob/7f9407cda0d663d956666ae338e0f57d9dfe9785/eg/reply-async/weatherman.js#L65-L95
15,612
aichaos/rivescript-js
eg/router/router.js
function(rs, args) { // This function is invoked by messages such as: // what is 5 subtracted by 2 // add 6 to 7 if (args[0].match(/^\d+$/)) { // They used the first form, with a number. return Controllers.doMath(args[1], args[0], args[2]); } else { // The second form, first word being the operation. return Controllers.doMath(args[0], args[1], args[2]); } }
javascript
function(rs, args) { // This function is invoked by messages such as: // what is 5 subtracted by 2 // add 6 to 7 if (args[0].match(/^\d+$/)) { // They used the first form, with a number. return Controllers.doMath(args[1], args[0], args[2]); } else { // The second form, first word being the operation. return Controllers.doMath(args[0], args[1], args[2]); } }
[ "function", "(", "rs", ",", "args", ")", "{", "// This function is invoked by messages such as:", "// what is 5 subtracted by 2", "// add 6 to 7", "if", "(", "args", "[", "0", "]", ".", "match", "(", "/", "^\\d+$", "/", ")", ")", "{", "// They used the first form, with a number.", "return", "Controllers", ".", "doMath", "(", "args", "[", "1", "]", ",", "args", "[", "0", "]", ",", "args", "[", "2", "]", ")", ";", "}", "else", "{", "// The second form, first word being the operation.", "return", "Controllers", ".", "doMath", "(", "args", "[", "0", "]", ",", "args", "[", "1", "]", ",", "args", "[", "2", "]", ")", ";", "}", "}" ]
The object macro function itself.
[ "The", "object", "macro", "function", "itself", "." ]
7f9407cda0d663d956666ae338e0f57d9dfe9785
https://github.com/aichaos/rivescript-js/blob/7f9407cda0d663d956666ae338e0f57d9dfe9785/eg/router/router.js#L29-L41
15,613
docusign/docusign-node-client
src/auth/errors/docusignapierror.js
DocusignAPIError
function DocusignAPIError(message, type, code, subcode, traceID) { Error.call(this); Error.captureStackTrace(this, arguments.callee); this.name = 'DocusignAPIError'; this.message = message; this.type = type; this.code = code; this.subcode = subcode; this.traceID = traceID; this.status = 500; }
javascript
function DocusignAPIError(message, type, code, subcode, traceID) { Error.call(this); Error.captureStackTrace(this, arguments.callee); this.name = 'DocusignAPIError'; this.message = message; this.type = type; this.code = code; this.subcode = subcode; this.traceID = traceID; this.status = 500; }
[ "function", "DocusignAPIError", "(", "message", ",", "type", ",", "code", ",", "subcode", ",", "traceID", ")", "{", "Error", ".", "call", "(", "this", ")", ";", "Error", ".", "captureStackTrace", "(", "this", ",", "arguments", ".", "callee", ")", ";", "this", ".", "name", "=", "'DocusignAPIError'", ";", "this", ".", "message", "=", "message", ";", "this", ".", "type", "=", "type", ";", "this", ".", "code", "=", "code", ";", "this", ".", "subcode", "=", "subcode", ";", "this", ".", "traceID", "=", "traceID", ";", "this", ".", "status", "=", "500", ";", "}" ]
`DocusignAPIError` error. References: - https://www.docusign.com/p/RESTAPIGuide/RESTAPIGuide.htm#OAuth2/OAuth2 Response Codes.htm @constructor @param {string} [message] @param {string} [type] @param {number} [code] @param {number} [subcode] @param {string} [traceID] @access public
[ "DocusignAPIError", "error", "." ]
3fb90b1afba3b2e0e94f55592120425b4c4f0aab
https://github.com/docusign/docusign-node-client/blob/3fb90b1afba3b2e0e94f55592120425b4c4f0aab/src/auth/errors/docusignapierror.js#L15-L25
15,614
koajs/joi-router
joi-router.js
checkMethods
function checkMethods(spec) { assert(spec.method, 'missing route methods'); if (typeof spec.method === 'string') { spec.method = spec.method.split(' '); } if (!Array.isArray(spec.method)) { throw new TypeError('route methods must be an array or string'); } if (spec.method.length === 0) { throw new Error('missing route method'); } spec.method.forEach((method, i) => { assert(typeof method === 'string', 'route method must be a string'); spec.method[i] = method.toLowerCase(); }); }
javascript
function checkMethods(spec) { assert(spec.method, 'missing route methods'); if (typeof spec.method === 'string') { spec.method = spec.method.split(' '); } if (!Array.isArray(spec.method)) { throw new TypeError('route methods must be an array or string'); } if (spec.method.length === 0) { throw new Error('missing route method'); } spec.method.forEach((method, i) => { assert(typeof method === 'string', 'route method must be a string'); spec.method[i] = method.toLowerCase(); }); }
[ "function", "checkMethods", "(", "spec", ")", "{", "assert", "(", "spec", ".", "method", ",", "'missing route methods'", ")", ";", "if", "(", "typeof", "spec", ".", "method", "===", "'string'", ")", "{", "spec", ".", "method", "=", "spec", ".", "method", ".", "split", "(", "' '", ")", ";", "}", "if", "(", "!", "Array", ".", "isArray", "(", "spec", ".", "method", ")", ")", "{", "throw", "new", "TypeError", "(", "'route methods must be an array or string'", ")", ";", "}", "if", "(", "spec", ".", "method", ".", "length", "===", "0", ")", "{", "throw", "new", "Error", "(", "'missing route method'", ")", ";", "}", "spec", ".", "method", ".", "forEach", "(", "(", "method", ",", "i", ")", "=>", "{", "assert", "(", "typeof", "method", "===", "'string'", ",", "'route method must be a string'", ")", ";", "spec", ".", "method", "[", "i", "]", "=", "method", ".", "toLowerCase", "(", ")", ";", "}", ")", ";", "}" ]
Validate the spec.method @param {Object} spec @api private
[ "Validate", "the", "spec", ".", "method" ]
509a0e6c1699ea7cb5bd9c8f340c8bcbae225247
https://github.com/koajs/joi-router/blob/509a0e6c1699ea7cb5bd9c8f340c8bcbae225247/joi-router.js#L206-L225
15,615
koajs/joi-router
joi-router.js
checkValidators
function checkValidators(spec) { if (!spec.validate) return; let text; if (spec.validate.body) { text = 'validate.type must be declared when using validate.body'; assert(/json|form/.test(spec.validate.type), text); } if (spec.validate.type) { text = 'validate.type must be either json, form, multipart or stream'; assert(/json|form|multipart|stream/i.test(spec.validate.type), text); } if (spec.validate.output) { spec.validate._outputValidator = new OutputValidator(spec.validate.output); } // default HTTP status code for failures if (!spec.validate.failure) { spec.validate.failure = 400; } }
javascript
function checkValidators(spec) { if (!spec.validate) return; let text; if (spec.validate.body) { text = 'validate.type must be declared when using validate.body'; assert(/json|form/.test(spec.validate.type), text); } if (spec.validate.type) { text = 'validate.type must be either json, form, multipart or stream'; assert(/json|form|multipart|stream/i.test(spec.validate.type), text); } if (spec.validate.output) { spec.validate._outputValidator = new OutputValidator(spec.validate.output); } // default HTTP status code for failures if (!spec.validate.failure) { spec.validate.failure = 400; } }
[ "function", "checkValidators", "(", "spec", ")", "{", "if", "(", "!", "spec", ".", "validate", ")", "return", ";", "let", "text", ";", "if", "(", "spec", ".", "validate", ".", "body", ")", "{", "text", "=", "'validate.type must be declared when using validate.body'", ";", "assert", "(", "/", "json|form", "/", ".", "test", "(", "spec", ".", "validate", ".", "type", ")", ",", "text", ")", ";", "}", "if", "(", "spec", ".", "validate", ".", "type", ")", "{", "text", "=", "'validate.type must be either json, form, multipart or stream'", ";", "assert", "(", "/", "json|form|multipart|stream", "/", "i", ".", "test", "(", "spec", ".", "validate", ".", "type", ")", ",", "text", ")", ";", "}", "if", "(", "spec", ".", "validate", ".", "output", ")", "{", "spec", ".", "validate", ".", "_outputValidator", "=", "new", "OutputValidator", "(", "spec", ".", "validate", ".", "output", ")", ";", "}", "// default HTTP status code for failures", "if", "(", "!", "spec", ".", "validate", ".", "failure", ")", "{", "spec", ".", "validate", ".", "failure", "=", "400", ";", "}", "}" ]
Validate the spec.validators @param {Object} spec @api private
[ "Validate", "the", "spec", ".", "validators" ]
509a0e6c1699ea7cb5bd9c8f340c8bcbae225247
https://github.com/koajs/joi-router/blob/509a0e6c1699ea7cb5bd9c8f340c8bcbae225247/joi-router.js#L234-L256
15,616
koajs/joi-router
joi-router.js
wrapError
function wrapError(spec, parsePayload) { return async function errorHandler(ctx, next) { try { await parsePayload(ctx, next); } catch (err) { captureError(ctx, 'type', err); if (spec.validate.continueOnError) { return await next(); } else { return ctx.throw(err); } } }; }
javascript
function wrapError(spec, parsePayload) { return async function errorHandler(ctx, next) { try { await parsePayload(ctx, next); } catch (err) { captureError(ctx, 'type', err); if (spec.validate.continueOnError) { return await next(); } else { return ctx.throw(err); } } }; }
[ "function", "wrapError", "(", "spec", ",", "parsePayload", ")", "{", "return", "async", "function", "errorHandler", "(", "ctx", ",", "next", ")", "{", "try", "{", "await", "parsePayload", "(", "ctx", ",", "next", ")", ";", "}", "catch", "(", "err", ")", "{", "captureError", "(", "ctx", ",", "'type'", ",", "err", ")", ";", "if", "(", "spec", ".", "validate", ".", "continueOnError", ")", "{", "return", "await", "next", "(", ")", ";", "}", "else", "{", "return", "ctx", ".", "throw", "(", "err", ")", ";", "}", "}", "}", ";", "}" ]
Handles parser internal errors @param {Object} spec [description] @param {function} parsePayload [description] @return {async function} [description] @api private
[ "Handles", "parser", "internal", "errors" ]
509a0e6c1699ea7cb5bd9c8f340c8bcbae225247
https://github.com/koajs/joi-router/blob/509a0e6c1699ea7cb5bd9c8f340c8bcbae225247/joi-router.js#L278-L291
15,617
koajs/joi-router
joi-router.js
makeJSONBodyParser
function makeJSONBodyParser(spec) { const opts = spec.validate.jsonOptions || {}; if (typeof opts.limit === 'undefined') { opts.limit = spec.validate.maxBody; } return async function parseJSONPayload(ctx, next) { if (!ctx.request.is('json')) { return ctx.throw(400, 'expected json'); } ctx.request.body = ctx.request.body || await parse.json(ctx, opts); await next(); }; }
javascript
function makeJSONBodyParser(spec) { const opts = spec.validate.jsonOptions || {}; if (typeof opts.limit === 'undefined') { opts.limit = spec.validate.maxBody; } return async function parseJSONPayload(ctx, next) { if (!ctx.request.is('json')) { return ctx.throw(400, 'expected json'); } ctx.request.body = ctx.request.body || await parse.json(ctx, opts); await next(); }; }
[ "function", "makeJSONBodyParser", "(", "spec", ")", "{", "const", "opts", "=", "spec", ".", "validate", ".", "jsonOptions", "||", "{", "}", ";", "if", "(", "typeof", "opts", ".", "limit", "===", "'undefined'", ")", "{", "opts", ".", "limit", "=", "spec", ".", "validate", ".", "maxBody", ";", "}", "return", "async", "function", "parseJSONPayload", "(", "ctx", ",", "next", ")", "{", "if", "(", "!", "ctx", ".", "request", ".", "is", "(", "'json'", ")", ")", "{", "return", "ctx", ".", "throw", "(", "400", ",", "'expected json'", ")", ";", "}", "ctx", ".", "request", ".", "body", "=", "ctx", ".", "request", ".", "body", "||", "await", "parse", ".", "json", "(", "ctx", ",", "opts", ")", ";", "await", "next", "(", ")", ";", "}", ";", "}" ]
Creates JSON body parser middleware. @param {Object} spec @return {async function} @api private
[ "Creates", "JSON", "body", "parser", "middleware", "." ]
509a0e6c1699ea7cb5bd9c8f340c8bcbae225247
https://github.com/koajs/joi-router/blob/509a0e6c1699ea7cb5bd9c8f340c8bcbae225247/joi-router.js#L301-L314
15,618
koajs/joi-router
joi-router.js
makeFormBodyParser
function makeFormBodyParser(spec) { const opts = spec.validate.formOptions || {}; if (typeof opts.limit === 'undefined') { opts.limit = spec.validate.maxBody; } return async function parseFormBody(ctx, next) { if (!ctx.request.is('urlencoded')) { return ctx.throw(400, 'expected x-www-form-urlencoded'); } ctx.request.body = ctx.request.body || await parse.form(ctx, opts); await next(); }; }
javascript
function makeFormBodyParser(spec) { const opts = spec.validate.formOptions || {}; if (typeof opts.limit === 'undefined') { opts.limit = spec.validate.maxBody; } return async function parseFormBody(ctx, next) { if (!ctx.request.is('urlencoded')) { return ctx.throw(400, 'expected x-www-form-urlencoded'); } ctx.request.body = ctx.request.body || await parse.form(ctx, opts); await next(); }; }
[ "function", "makeFormBodyParser", "(", "spec", ")", "{", "const", "opts", "=", "spec", ".", "validate", ".", "formOptions", "||", "{", "}", ";", "if", "(", "typeof", "opts", ".", "limit", "===", "'undefined'", ")", "{", "opts", ".", "limit", "=", "spec", ".", "validate", ".", "maxBody", ";", "}", "return", "async", "function", "parseFormBody", "(", "ctx", ",", "next", ")", "{", "if", "(", "!", "ctx", ".", "request", ".", "is", "(", "'urlencoded'", ")", ")", "{", "return", "ctx", ".", "throw", "(", "400", ",", "'expected x-www-form-urlencoded'", ")", ";", "}", "ctx", ".", "request", ".", "body", "=", "ctx", ".", "request", ".", "body", "||", "await", "parse", ".", "form", "(", "ctx", ",", "opts", ")", ";", "await", "next", "(", ")", ";", "}", ";", "}" ]
Creates form body parser middleware. @param {Object} spec @return {async function} @api private
[ "Creates", "form", "body", "parser", "middleware", "." ]
509a0e6c1699ea7cb5bd9c8f340c8bcbae225247
https://github.com/koajs/joi-router/blob/509a0e6c1699ea7cb5bd9c8f340c8bcbae225247/joi-router.js#L324-L336
15,619
koajs/joi-router
joi-router.js
makeBodyParser
function makeBodyParser(spec) { if (!(spec.validate && spec.validate.type)) return noopMiddleware; switch (spec.validate.type) { case 'json': return wrapError(spec, makeJSONBodyParser(spec)); case 'form': return wrapError(spec, makeFormBodyParser(spec)); case 'stream': case 'multipart': return wrapError(spec, makeMultipartParser(spec)); default: throw new Error(`unsupported body type: ${spec.validate.type}`); } }
javascript
function makeBodyParser(spec) { if (!(spec.validate && spec.validate.type)) return noopMiddleware; switch (spec.validate.type) { case 'json': return wrapError(spec, makeJSONBodyParser(spec)); case 'form': return wrapError(spec, makeFormBodyParser(spec)); case 'stream': case 'multipart': return wrapError(spec, makeMultipartParser(spec)); default: throw new Error(`unsupported body type: ${spec.validate.type}`); } }
[ "function", "makeBodyParser", "(", "spec", ")", "{", "if", "(", "!", "(", "spec", ".", "validate", "&&", "spec", ".", "validate", ".", "type", ")", ")", "return", "noopMiddleware", ";", "switch", "(", "spec", ".", "validate", ".", "type", ")", "{", "case", "'json'", ":", "return", "wrapError", "(", "spec", ",", "makeJSONBodyParser", "(", "spec", ")", ")", ";", "case", "'form'", ":", "return", "wrapError", "(", "spec", ",", "makeFormBodyParser", "(", "spec", ")", ")", ";", "case", "'stream'", ":", "case", "'multipart'", ":", "return", "wrapError", "(", "spec", ",", "makeMultipartParser", "(", "spec", ")", ")", ";", "default", ":", "throw", "new", "Error", "(", "`", "${", "spec", ".", "validate", ".", "type", "}", "`", ")", ";", "}", "}" ]
Creates body parser middleware. @param {Object} spec @return {async function} @api private
[ "Creates", "body", "parser", "middleware", "." ]
509a0e6c1699ea7cb5bd9c8f340c8bcbae225247
https://github.com/koajs/joi-router/blob/509a0e6c1699ea7cb5bd9c8f340c8bcbae225247/joi-router.js#L368-L382
15,620
koajs/joi-router
joi-router.js
makeValidator
function makeValidator(spec) { const props = 'header query params body'.split(' '); return async function validator(ctx, next) { if (!spec.validate) return await next(); let err; for (let i = 0; i < props.length; ++i) { const prop = props[i]; if (spec.validate[prop]) { err = validateInput(prop, ctx, spec.validate); if (err) { captureError(ctx, prop, err); if (!spec.validate.continueOnError) return ctx.throw(err); } } } await next(); if (spec.validate._outputValidator) { debug('validating output'); err = spec.validate._outputValidator.validate(ctx); if (err) { err.status = 500; return ctx.throw(err); } } }; }
javascript
function makeValidator(spec) { const props = 'header query params body'.split(' '); return async function validator(ctx, next) { if (!spec.validate) return await next(); let err; for (let i = 0; i < props.length; ++i) { const prop = props[i]; if (spec.validate[prop]) { err = validateInput(prop, ctx, spec.validate); if (err) { captureError(ctx, prop, err); if (!spec.validate.continueOnError) return ctx.throw(err); } } } await next(); if (spec.validate._outputValidator) { debug('validating output'); err = spec.validate._outputValidator.validate(ctx); if (err) { err.status = 500; return ctx.throw(err); } } }; }
[ "function", "makeValidator", "(", "spec", ")", "{", "const", "props", "=", "'header query params body'", ".", "split", "(", "' '", ")", ";", "return", "async", "function", "validator", "(", "ctx", ",", "next", ")", "{", "if", "(", "!", "spec", ".", "validate", ")", "return", "await", "next", "(", ")", ";", "let", "err", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "props", ".", "length", ";", "++", "i", ")", "{", "const", "prop", "=", "props", "[", "i", "]", ";", "if", "(", "spec", ".", "validate", "[", "prop", "]", ")", "{", "err", "=", "validateInput", "(", "prop", ",", "ctx", ",", "spec", ".", "validate", ")", ";", "if", "(", "err", ")", "{", "captureError", "(", "ctx", ",", "prop", ",", "err", ")", ";", "if", "(", "!", "spec", ".", "validate", ".", "continueOnError", ")", "return", "ctx", ".", "throw", "(", "err", ")", ";", "}", "}", "}", "await", "next", "(", ")", ";", "if", "(", "spec", ".", "validate", ".", "_outputValidator", ")", "{", "debug", "(", "'validating output'", ")", ";", "err", "=", "spec", ".", "validate", ".", "_outputValidator", ".", "validate", "(", "ctx", ")", ";", "if", "(", "err", ")", "{", "err", ".", "status", "=", "500", ";", "return", "ctx", ".", "throw", "(", "err", ")", ";", "}", "}", "}", ";", "}" ]
Creates validator middleware. @param {Object} spec @return {async function} @api private
[ "Creates", "validator", "middleware", "." ]
509a0e6c1699ea7cb5bd9c8f340c8bcbae225247
https://github.com/koajs/joi-router/blob/509a0e6c1699ea7cb5bd9c8f340c8bcbae225247/joi-router.js#L403-L436
15,621
koajs/joi-router
joi-router.js
makeSpecExposer
function makeSpecExposer(spec) { const defn = clone(spec); return async function specExposer(ctx, next) { ctx.state.route = defn; await next(); }; }
javascript
function makeSpecExposer(spec) { const defn = clone(spec); return async function specExposer(ctx, next) { ctx.state.route = defn; await next(); }; }
[ "function", "makeSpecExposer", "(", "spec", ")", "{", "const", "defn", "=", "clone", "(", "spec", ")", ";", "return", "async", "function", "specExposer", "(", "ctx", ",", "next", ")", "{", "ctx", ".", "state", ".", "route", "=", "defn", ";", "await", "next", "(", ")", ";", "}", ";", "}" ]
Exposes route spec @param {Object} spec The route spec @returns {async Function} Middleware @api private
[ "Exposes", "route", "spec" ]
509a0e6c1699ea7cb5bd9c8f340c8bcbae225247
https://github.com/koajs/joi-router/blob/509a0e6c1699ea7cb5bd9c8f340c8bcbae225247/joi-router.js#L444-L450
15,622
koajs/joi-router
joi-router.js
prepareRequest
async function prepareRequest(ctx, next) { ctx.request.params = ctx.params; await next(); }
javascript
async function prepareRequest(ctx, next) { ctx.request.params = ctx.params; await next(); }
[ "async", "function", "prepareRequest", "(", "ctx", ",", "next", ")", "{", "ctx", ".", "request", ".", "params", "=", "ctx", ".", "params", ";", "await", "next", "(", ")", ";", "}" ]
Middleware which creates `request.params`. @api private
[ "Middleware", "which", "creates", "request", ".", "params", "." ]
509a0e6c1699ea7cb5bd9c8f340c8bcbae225247
https://github.com/koajs/joi-router/blob/509a0e6c1699ea7cb5bd9c8f340c8bcbae225247/joi-router.js#L458-L461
15,623
unosquare/tubular
src/js/tubular/services/tubularConfig.js
addConfig
function addConfig(configObj, platformObj) { for (const n in configObj) { if (n != PLATFORM && configObj.hasOwnProperty(n)) { if (angular.isObject(configObj[n])) { if (angular.isUndefined(platformObj[n])) { platformObj[n] = {}; } addConfig(configObj[n], platformObj[n]); } else if (angular.isUndefined(platformObj[n])) { platformObj[n] = null; } } } }
javascript
function addConfig(configObj, platformObj) { for (const n in configObj) { if (n != PLATFORM && configObj.hasOwnProperty(n)) { if (angular.isObject(configObj[n])) { if (angular.isUndefined(platformObj[n])) { platformObj[n] = {}; } addConfig(configObj[n], platformObj[n]); } else if (angular.isUndefined(platformObj[n])) { platformObj[n] = null; } } } }
[ "function", "addConfig", "(", "configObj", ",", "platformObj", ")", "{", "for", "(", "const", "n", "in", "configObj", ")", "{", "if", "(", "n", "!=", "PLATFORM", "&&", "configObj", ".", "hasOwnProperty", "(", "n", ")", ")", "{", "if", "(", "angular", ".", "isObject", "(", "configObj", "[", "n", "]", ")", ")", "{", "if", "(", "angular", ".", "isUndefined", "(", "platformObj", "[", "n", "]", ")", ")", "{", "platformObj", "[", "n", "]", "=", "{", "}", ";", "}", "addConfig", "(", "configObj", "[", "n", "]", ",", "platformObj", "[", "n", "]", ")", ";", "}", "else", "if", "(", "angular", ".", "isUndefined", "(", "platformObj", "[", "n", "]", ")", ")", "{", "platformObj", "[", "n", "]", "=", "null", ";", "}", "}", "}", "}" ]
add new platform configs
[ "add", "new", "platform", "configs" ]
4863f519b838df9f30ae4786704a939bca7a481f
https://github.com/unosquare/tubular/blob/4863f519b838df9f30ae4786704a939bca7a481f/src/js/tubular/services/tubularConfig.js#L66-L80
15,624
flowtype/flow-remove-types
index.js
removeImplementedInterfaces
function removeImplementedInterfaces(context, node, ast) { if (node.implements && node.implements.length > 0) { var first = node.implements[0]; var last = node.implements[node.implements.length - 1]; var idx = findTokenIndex(ast.tokens, first.start); do { idx--; } while (ast.tokens[idx].value !== 'implements'); var lastIdx = findTokenIndex(ast.tokens, last.start); do { if (!isComment(ast.tokens[idx])) { removeNode(context, ast.tokens[idx]); } } while (idx++ !== lastIdx); } }
javascript
function removeImplementedInterfaces(context, node, ast) { if (node.implements && node.implements.length > 0) { var first = node.implements[0]; var last = node.implements[node.implements.length - 1]; var idx = findTokenIndex(ast.tokens, first.start); do { idx--; } while (ast.tokens[idx].value !== 'implements'); var lastIdx = findTokenIndex(ast.tokens, last.start); do { if (!isComment(ast.tokens[idx])) { removeNode(context, ast.tokens[idx]); } } while (idx++ !== lastIdx); } }
[ "function", "removeImplementedInterfaces", "(", "context", ",", "node", ",", "ast", ")", "{", "if", "(", "node", ".", "implements", "&&", "node", ".", "implements", ".", "length", ">", "0", ")", "{", "var", "first", "=", "node", ".", "implements", "[", "0", "]", ";", "var", "last", "=", "node", ".", "implements", "[", "node", ".", "implements", ".", "length", "-", "1", "]", ";", "var", "idx", "=", "findTokenIndex", "(", "ast", ".", "tokens", ",", "first", ".", "start", ")", ";", "do", "{", "idx", "--", ";", "}", "while", "(", "ast", ".", "tokens", "[", "idx", "]", ".", "value", "!==", "'implements'", ")", ";", "var", "lastIdx", "=", "findTokenIndex", "(", "ast", ".", "tokens", ",", "last", ".", "start", ")", ";", "do", "{", "if", "(", "!", "isComment", "(", "ast", ".", "tokens", "[", "idx", "]", ")", ")", "{", "removeNode", "(", "context", ",", "ast", ".", "tokens", "[", "idx", "]", ")", ";", "}", "}", "while", "(", "idx", "++", "!==", "lastIdx", ")", ";", "}", "}" ]
If this class declaration or expression implements interfaces, remove the associated tokens.
[ "If", "this", "class", "declaration", "or", "expression", "implements", "interfaces", "remove", "the", "associated", "tokens", "." ]
d6e560f21c8f7221f6a6fb7f1bed1ec923397b8f
https://github.com/flowtype/flow-remove-types/blob/d6e560f21c8f7221f6a6fb7f1bed1ec923397b8f/index.js#L200-L216
15,625
flowtype/flow-remove-types
register.js
regexpPattern
function regexpPattern(pattern) { if (!pattern) { return pattern; } // A very simplified glob transform which allows passing legible strings like // "myPath/*.js" instead of a harder to read RegExp like /\/myPath\/.*\.js/. if (typeof pattern === 'string') { pattern = pattern.replace(/\./g, '\\.').replace(/\*/g, '.*'); if (pattern[0] !== '/') { pattern = '/' + pattern; } return new RegExp(pattern); } if (typeof pattern.test === 'function') { return pattern; } throw new Error( 'flow-remove-types: includes and excludes must be RegExp or path strings. Got: ' + pattern ); }
javascript
function regexpPattern(pattern) { if (!pattern) { return pattern; } // A very simplified glob transform which allows passing legible strings like // "myPath/*.js" instead of a harder to read RegExp like /\/myPath\/.*\.js/. if (typeof pattern === 'string') { pattern = pattern.replace(/\./g, '\\.').replace(/\*/g, '.*'); if (pattern[0] !== '/') { pattern = '/' + pattern; } return new RegExp(pattern); } if (typeof pattern.test === 'function') { return pattern; } throw new Error( 'flow-remove-types: includes and excludes must be RegExp or path strings. Got: ' + pattern ); }
[ "function", "regexpPattern", "(", "pattern", ")", "{", "if", "(", "!", "pattern", ")", "{", "return", "pattern", ";", "}", "// A very simplified glob transform which allows passing legible strings like", "// \"myPath/*.js\" instead of a harder to read RegExp like /\\/myPath\\/.*\\.js/.", "if", "(", "typeof", "pattern", "===", "'string'", ")", "{", "pattern", "=", "pattern", ".", "replace", "(", "/", "\\.", "/", "g", ",", "'\\\\.'", ")", ".", "replace", "(", "/", "\\*", "/", "g", ",", "'.*'", ")", ";", "if", "(", "pattern", "[", "0", "]", "!==", "'/'", ")", "{", "pattern", "=", "'/'", "+", "pattern", ";", "}", "return", "new", "RegExp", "(", "pattern", ")", ";", "}", "if", "(", "typeof", "pattern", ".", "test", "===", "'function'", ")", "{", "return", "pattern", ";", "}", "throw", "new", "Error", "(", "'flow-remove-types: includes and excludes must be RegExp or path strings. Got: '", "+", "pattern", ")", ";", "}" ]
Given a null | string | RegExp | any, returns null | Regexp or throws a more helpful error.
[ "Given", "a", "null", "|", "string", "|", "RegExp", "|", "any", "returns", "null", "|", "Regexp", "or", "throws", "a", "more", "helpful", "error", "." ]
d6e560f21c8f7221f6a6fb7f1bed1ec923397b8f
https://github.com/flowtype/flow-remove-types/blob/d6e560f21c8f7221f6a6fb7f1bed1ec923397b8f/register.js#L61-L80
15,626
jellekralt/Responsive-Tabs
js/jquery.responsiveTabs.js
function(e) { var current = _this._getCurrentTab(); // Fetch current tab var activatedTab = e.data.tab; e.preventDefault(); // Trigger click event for whenever a tab is clicked/touched even if the tab is disabled activatedTab.tab.trigger('tabs-click', activatedTab); // Make sure this tab isn't disabled if(!activatedTab.disabled) { // Check if hash has to be set in the URL location if(_this.options.setHash) { // Set the hash using the history api if available to tackle Chromes repaint bug on hash change if(history.pushState) { // Fix for missing window.location.origin in IE if (!window.location.origin) { window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: ''); } history.pushState(null, null, window.location.origin + window.location.pathname + window.location.search + activatedTab.selector); } else { // Otherwise fallback to the hash update for sites that don't support the history api window.location.hash = activatedTab.selector; } } e.data.tab._ignoreHashChange = true; // Check if the activated tab isnt the current one or if its collapsible. If not, do nothing if(current !== activatedTab || _this._isCollapisble()) { // The activated tab is either another tab of the current one. If it's the current tab it is collapsible // Either way, the current tab can be closed _this._closeTab(e, current); // Check if the activated tab isnt the current one or if it isnt collapsible if(current !== activatedTab || !_this._isCollapisble()) { _this._openTab(e, activatedTab, false, true); } } } }
javascript
function(e) { var current = _this._getCurrentTab(); // Fetch current tab var activatedTab = e.data.tab; e.preventDefault(); // Trigger click event for whenever a tab is clicked/touched even if the tab is disabled activatedTab.tab.trigger('tabs-click', activatedTab); // Make sure this tab isn't disabled if(!activatedTab.disabled) { // Check if hash has to be set in the URL location if(_this.options.setHash) { // Set the hash using the history api if available to tackle Chromes repaint bug on hash change if(history.pushState) { // Fix for missing window.location.origin in IE if (!window.location.origin) { window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: ''); } history.pushState(null, null, window.location.origin + window.location.pathname + window.location.search + activatedTab.selector); } else { // Otherwise fallback to the hash update for sites that don't support the history api window.location.hash = activatedTab.selector; } } e.data.tab._ignoreHashChange = true; // Check if the activated tab isnt the current one or if its collapsible. If not, do nothing if(current !== activatedTab || _this._isCollapisble()) { // The activated tab is either another tab of the current one. If it's the current tab it is collapsible // Either way, the current tab can be closed _this._closeTab(e, current); // Check if the activated tab isnt the current one or if it isnt collapsible if(current !== activatedTab || !_this._isCollapisble()) { _this._openTab(e, activatedTab, false, true); } } } }
[ "function", "(", "e", ")", "{", "var", "current", "=", "_this", ".", "_getCurrentTab", "(", ")", ";", "// Fetch current tab", "var", "activatedTab", "=", "e", ".", "data", ".", "tab", ";", "e", ".", "preventDefault", "(", ")", ";", "// Trigger click event for whenever a tab is clicked/touched even if the tab is disabled", "activatedTab", ".", "tab", ".", "trigger", "(", "'tabs-click'", ",", "activatedTab", ")", ";", "// Make sure this tab isn't disabled", "if", "(", "!", "activatedTab", ".", "disabled", ")", "{", "// Check if hash has to be set in the URL location", "if", "(", "_this", ".", "options", ".", "setHash", ")", "{", "// Set the hash using the history api if available to tackle Chromes repaint bug on hash change", "if", "(", "history", ".", "pushState", ")", "{", "// Fix for missing window.location.origin in IE", "if", "(", "!", "window", ".", "location", ".", "origin", ")", "{", "window", ".", "location", ".", "origin", "=", "window", ".", "location", ".", "protocol", "+", "\"//\"", "+", "window", ".", "location", ".", "hostname", "+", "(", "window", ".", "location", ".", "port", "?", "':'", "+", "window", ".", "location", ".", "port", ":", "''", ")", ";", "}", "history", ".", "pushState", "(", "null", ",", "null", ",", "window", ".", "location", ".", "origin", "+", "window", ".", "location", ".", "pathname", "+", "window", ".", "location", ".", "search", "+", "activatedTab", ".", "selector", ")", ";", "}", "else", "{", "// Otherwise fallback to the hash update for sites that don't support the history api", "window", ".", "location", ".", "hash", "=", "activatedTab", ".", "selector", ";", "}", "}", "e", ".", "data", ".", "tab", ".", "_ignoreHashChange", "=", "true", ";", "// Check if the activated tab isnt the current one or if its collapsible. If not, do nothing", "if", "(", "current", "!==", "activatedTab", "||", "_this", ".", "_isCollapisble", "(", ")", ")", "{", "// The activated tab is either another tab of the current one. If it's the current tab it is collapsible", "// Either way, the current tab can be closed", "_this", ".", "_closeTab", "(", "e", ",", "current", ")", ";", "// Check if the activated tab isnt the current one or if it isnt collapsible", "if", "(", "current", "!==", "activatedTab", "||", "!", "_this", ".", "_isCollapisble", "(", ")", ")", "{", "_this", ".", "_openTab", "(", "e", ",", "activatedTab", ",", "false", ",", "true", ")", ";", "}", "}", "}", "}" ]
Define activate event on a tab element
[ "Define", "activate", "event", "on", "a", "tab", "element" ]
7deb5aa383599915c598c7cba54893d253f2c196
https://github.com/jellekralt/Responsive-Tabs/blob/7deb5aa383599915c598c7cba54893d253f2c196/js/jquery.responsiveTabs.js#L227-L269
15,627
uber-node/ringpop-node
examples/cluster.js
after
function after(count, callback) { var countdown = count; return function shim(err) { if (typeof callback !== 'function') return; if (err) { callback(err); callback = null; return; } if (--countdown === 0) { callback(); callback = null; } }; }
javascript
function after(count, callback) { var countdown = count; return function shim(err) { if (typeof callback !== 'function') return; if (err) { callback(err); callback = null; return; } if (--countdown === 0) { callback(); callback = null; } }; }
[ "function", "after", "(", "count", ",", "callback", ")", "{", "var", "countdown", "=", "count", ";", "return", "function", "shim", "(", "err", ")", "{", "if", "(", "typeof", "callback", "!==", "'function'", ")", "return", ";", "if", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "callback", "=", "null", ";", "return", ";", "}", "if", "(", "--", "countdown", "===", "0", ")", "{", "callback", "(", ")", ";", "callback", "=", "null", ";", "}", "}", ";", "}" ]
IGNORE THIS! It's a little utility function that invokes a callback after a specified number of invocations of its shim.
[ "IGNORE", "THIS!", "It", "s", "a", "little", "utility", "function", "that", "invokes", "a", "callback", "after", "a", "specified", "number", "of", "invocations", "of", "its", "shim", "." ]
aec09a8ed304f4db3e1d67a4e94c55fffe06206e
https://github.com/uber-node/ringpop-node/blob/aec09a8ed304f4db3e1d67a4e94c55fffe06206e/examples/cluster.js#L85-L102
15,628
uber-node/ringpop-node
discover-providers.js
createJsonFileDiscoverProvider
function createJsonFileDiscoverProvider(hostsFile) { var fs = require('fs'); return function jsonFileProvider(callback) { fs.readFile(hostsFile, function onFileRead(err, data) { if (err) { callback(err); return; } var hosts; try { hosts = JSON.parse(data.toString()); } catch (e) { callback(e); return; } callback(null, hosts); return; }); }; }
javascript
function createJsonFileDiscoverProvider(hostsFile) { var fs = require('fs'); return function jsonFileProvider(callback) { fs.readFile(hostsFile, function onFileRead(err, data) { if (err) { callback(err); return; } var hosts; try { hosts = JSON.parse(data.toString()); } catch (e) { callback(e); return; } callback(null, hosts); return; }); }; }
[ "function", "createJsonFileDiscoverProvider", "(", "hostsFile", ")", "{", "var", "fs", "=", "require", "(", "'fs'", ")", ";", "return", "function", "jsonFileProvider", "(", "callback", ")", "{", "fs", ".", "readFile", "(", "hostsFile", ",", "function", "onFileRead", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "return", ";", "}", "var", "hosts", ";", "try", "{", "hosts", "=", "JSON", ".", "parse", "(", "data", ".", "toString", "(", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "callback", "(", "e", ")", ";", "return", ";", "}", "callback", "(", "null", ",", "hosts", ")", ";", "return", ";", "}", ")", ";", "}", ";", "}" ]
Create a new DiscoverProvider using a host-file. @param {string} hostsFile The path to a json file containing an array of strings. @returns {DiscoverProvider}
[ "Create", "a", "new", "DiscoverProvider", "using", "a", "host", "-", "file", "." ]
aec09a8ed304f4db3e1d67a4e94c55fffe06206e
https://github.com/uber-node/ringpop-node/blob/aec09a8ed304f4db3e1d67a4e94c55fffe06206e/discover-providers.js#L56-L77
15,629
uber-node/ringpop-node
discover-providers.js
retryDiscoverProvider
function retryDiscoverProvider(opts, innerDiscoverProvider) { if (!opts) { return innerDiscoverProvider; } return function retryingDiscoverProvider(callback) { var policy; var defaultPolicy = { minDelay: 500, maxDelay: 15000, timeout: 60000 }; if (opts === true) { policy = defaultPolicy; } else { policy = _.defaults({}, opts, defaultPolicy); } var backoff = opts.backoff || new Backoff(policy); var lastError = null; attempt(null); function attempt(fail) { if (fail) { fail.lastError = lastError; return setImmediate(callback, fail); } innerDiscoverProvider(function onTry(err, hosts) { // We got results! if (!err && hosts !== null && hosts.length > 0) { return setImmediate(callback, null, hosts); } lastError = err; backoff.retry(attempt); }); } }; }
javascript
function retryDiscoverProvider(opts, innerDiscoverProvider) { if (!opts) { return innerDiscoverProvider; } return function retryingDiscoverProvider(callback) { var policy; var defaultPolicy = { minDelay: 500, maxDelay: 15000, timeout: 60000 }; if (opts === true) { policy = defaultPolicy; } else { policy = _.defaults({}, opts, defaultPolicy); } var backoff = opts.backoff || new Backoff(policy); var lastError = null; attempt(null); function attempt(fail) { if (fail) { fail.lastError = lastError; return setImmediate(callback, fail); } innerDiscoverProvider(function onTry(err, hosts) { // We got results! if (!err && hosts !== null && hosts.length > 0) { return setImmediate(callback, null, hosts); } lastError = err; backoff.retry(attempt); }); } }; }
[ "function", "retryDiscoverProvider", "(", "opts", ",", "innerDiscoverProvider", ")", "{", "if", "(", "!", "opts", ")", "{", "return", "innerDiscoverProvider", ";", "}", "return", "function", "retryingDiscoverProvider", "(", "callback", ")", "{", "var", "policy", ";", "var", "defaultPolicy", "=", "{", "minDelay", ":", "500", ",", "maxDelay", ":", "15000", ",", "timeout", ":", "60000", "}", ";", "if", "(", "opts", "===", "true", ")", "{", "policy", "=", "defaultPolicy", ";", "}", "else", "{", "policy", "=", "_", ".", "defaults", "(", "{", "}", ",", "opts", ",", "defaultPolicy", ")", ";", "}", "var", "backoff", "=", "opts", ".", "backoff", "||", "new", "Backoff", "(", "policy", ")", ";", "var", "lastError", "=", "null", ";", "attempt", "(", "null", ")", ";", "function", "attempt", "(", "fail", ")", "{", "if", "(", "fail", ")", "{", "fail", ".", "lastError", "=", "lastError", ";", "return", "setImmediate", "(", "callback", ",", "fail", ")", ";", "}", "innerDiscoverProvider", "(", "function", "onTry", "(", "err", ",", "hosts", ")", "{", "// We got results!", "if", "(", "!", "err", "&&", "hosts", "!==", "null", "&&", "hosts", ".", "length", ">", "0", ")", "{", "return", "setImmediate", "(", "callback", ",", "null", ",", "hosts", ")", ";", "}", "lastError", "=", "err", ";", "backoff", ".", "retry", "(", "attempt", ")", ";", "}", ")", ";", "}", "}", ";", "}" ]
Wrap a innerDiscoverProvider with a retrying mechanism. @param {Object} opts the options used as a Backoff policy {@see Backoff} @param {Object} [opts.backoff] a mocked backoff for testing @param {DiscoverProvider} innerDiscoverProvider The discover provider to wrap @returns {DiscoverProvider} The retrying discover provider.
[ "Wrap", "a", "innerDiscoverProvider", "with", "a", "retrying", "mechanism", "." ]
aec09a8ed304f4db3e1d67a4e94c55fffe06206e
https://github.com/uber-node/ringpop-node/blob/aec09a8ed304f4db3e1d67a4e94c55fffe06206e/discover-providers.js#L88-L128
15,630
uber-node/ringpop-node
discover-providers.js
createFromOpts
function createFromOpts(opts) { opts = opts || {}; if (typeof opts === 'function') { return opts; } if (typeof opts === 'string') { return createJsonFileDiscoverProvider(opts); } if (Array.isArray(opts)) { return createStaticHostsProvider(opts); } var discoverProvider; if (opts.discoverProvider) { discoverProvider = opts.discoverProvider; } else if (opts.hosts) { discoverProvider = createStaticHostsProvider(opts.hosts); } else if (opts.bootstrapFile && typeof opts.bootstrapFile === 'string') { discoverProvider = createJsonFileDiscoverProvider(opts.bootstrapFile); } else if (opts.bootstrapFile && Array.isArray(opts.bootstrapFile)) { /* This weird case is added for backwards compatibility :( */ discoverProvider = createStaticHostsProvider(opts.bootstrapFile); } else { return null; } if (opts.retry) { discoverProvider = retryDiscoverProvider(opts.retry, discoverProvider); } return discoverProvider; }
javascript
function createFromOpts(opts) { opts = opts || {}; if (typeof opts === 'function') { return opts; } if (typeof opts === 'string') { return createJsonFileDiscoverProvider(opts); } if (Array.isArray(opts)) { return createStaticHostsProvider(opts); } var discoverProvider; if (opts.discoverProvider) { discoverProvider = opts.discoverProvider; } else if (opts.hosts) { discoverProvider = createStaticHostsProvider(opts.hosts); } else if (opts.bootstrapFile && typeof opts.bootstrapFile === 'string') { discoverProvider = createJsonFileDiscoverProvider(opts.bootstrapFile); } else if (opts.bootstrapFile && Array.isArray(opts.bootstrapFile)) { /* This weird case is added for backwards compatibility :( */ discoverProvider = createStaticHostsProvider(opts.bootstrapFile); } else { return null; } if (opts.retry) { discoverProvider = retryDiscoverProvider(opts.retry, discoverProvider); } return discoverProvider; }
[ "function", "createFromOpts", "(", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "if", "(", "typeof", "opts", "===", "'function'", ")", "{", "return", "opts", ";", "}", "if", "(", "typeof", "opts", "===", "'string'", ")", "{", "return", "createJsonFileDiscoverProvider", "(", "opts", ")", ";", "}", "if", "(", "Array", ".", "isArray", "(", "opts", ")", ")", "{", "return", "createStaticHostsProvider", "(", "opts", ")", ";", "}", "var", "discoverProvider", ";", "if", "(", "opts", ".", "discoverProvider", ")", "{", "discoverProvider", "=", "opts", ".", "discoverProvider", ";", "}", "else", "if", "(", "opts", ".", "hosts", ")", "{", "discoverProvider", "=", "createStaticHostsProvider", "(", "opts", ".", "hosts", ")", ";", "}", "else", "if", "(", "opts", ".", "bootstrapFile", "&&", "typeof", "opts", ".", "bootstrapFile", "===", "'string'", ")", "{", "discoverProvider", "=", "createJsonFileDiscoverProvider", "(", "opts", ".", "bootstrapFile", ")", ";", "}", "else", "if", "(", "opts", ".", "bootstrapFile", "&&", "Array", ".", "isArray", "(", "opts", ".", "bootstrapFile", ")", ")", "{", "/* This weird case is added for backwards compatibility :( */", "discoverProvider", "=", "createStaticHostsProvider", "(", "opts", ".", "bootstrapFile", ")", ";", "}", "else", "{", "return", "null", ";", "}", "if", "(", "opts", ".", "retry", ")", "{", "discoverProvider", "=", "retryDiscoverProvider", "(", "opts", ".", "retry", ",", "discoverProvider", ")", ";", "}", "return", "discoverProvider", ";", "}" ]
Creates a DiscoverProvider from the provided options. @param opts: an object configuring the DiscoverProvider: - if opts or opts.discoverProvider is a function, it's returned as the {DiscoverProvider}. - if opts or opts.hosts is an array, a static hosts discover provider is returned (see {createStaticHostsProvider}) - if opts or opts.bootstrapFile is a string, a json file discover provider is returned (see {createJsonFileDiscoverProvider}) - if opts.retry is set, the discover provider is wrapped using retryDiscoverProvider (see {retryDiscoverProvider}). @returns {DiscoverProvider} The discover provider.
[ "Creates", "a", "DiscoverProvider", "from", "the", "provided", "options", "." ]
aec09a8ed304f4db3e1d67a4e94c55fffe06206e
https://github.com/uber-node/ringpop-node/blob/aec09a8ed304f4db3e1d67a4e94c55fffe06206e/discover-providers.js#L141-L172
15,631
uber-node/ringpop-node
lib/trace/core.js
resolveEventConfig
function resolveEventConfig(ringpop, traceEvent) { var tracerConfig = tracerConfigMap[traceEvent]; if (!tracerConfig) { return null; } var sourcePath = tracerConfig.sourcePath; // subtle but important -- if we resolve here, then the underlying object // can never change. if we do latent resolution, there may be a resource // leak when we try to remove listener from something that is out of our // reachable scope. var emitter = getIn(ringpop, sourcePath.slice(0, -1)); var event = _.last(sourcePath); return emitter && _.defaults( {}, { sourceEmitter: emitter, sourceEvent: event, traceEvent: traceEvent }, tracerConfig ); }
javascript
function resolveEventConfig(ringpop, traceEvent) { var tracerConfig = tracerConfigMap[traceEvent]; if (!tracerConfig) { return null; } var sourcePath = tracerConfig.sourcePath; // subtle but important -- if we resolve here, then the underlying object // can never change. if we do latent resolution, there may be a resource // leak when we try to remove listener from something that is out of our // reachable scope. var emitter = getIn(ringpop, sourcePath.slice(0, -1)); var event = _.last(sourcePath); return emitter && _.defaults( {}, { sourceEmitter: emitter, sourceEvent: event, traceEvent: traceEvent }, tracerConfig ); }
[ "function", "resolveEventConfig", "(", "ringpop", ",", "traceEvent", ")", "{", "var", "tracerConfig", "=", "tracerConfigMap", "[", "traceEvent", "]", ";", "if", "(", "!", "tracerConfig", ")", "{", "return", "null", ";", "}", "var", "sourcePath", "=", "tracerConfig", ".", "sourcePath", ";", "// subtle but important -- if we resolve here, then the underlying object", "// can never change. if we do latent resolution, there may be a resource", "// leak when we try to remove listener from something that is out of our", "// reachable scope.", "var", "emitter", "=", "getIn", "(", "ringpop", ",", "sourcePath", ".", "slice", "(", "0", ",", "-", "1", ")", ")", ";", "var", "event", "=", "_", ".", "last", "(", "sourcePath", ")", ";", "return", "emitter", "&&", "_", ".", "defaults", "(", "{", "}", ",", "{", "sourceEmitter", ":", "emitter", ",", "sourceEvent", ":", "event", ",", "traceEvent", ":", "traceEvent", "}", ",", "tracerConfig", ")", ";", "}" ]
resolves and returns a tracer config object, with traceEvent, sourceEmitter, and sourceEvent bound
[ "resolves", "and", "returns", "a", "tracer", "config", "object", "with", "traceEvent", "sourceEmitter", "and", "sourceEvent", "bound" ]
aec09a8ed304f4db3e1d67a4e94c55fffe06206e
https://github.com/uber-node/ringpop-node/blob/aec09a8ed304f4db3e1d67a4e94c55fffe06206e/lib/trace/core.js#L34-L57
15,632
uber-node/ringpop-node
config.js
Config
function Config(ringpop, seedConfig) { seedConfig = seedConfig || {}; this.ringpop = ringpop; this.store = {}; this._seed(seedConfig); }
javascript
function Config(ringpop, seedConfig) { seedConfig = seedConfig || {}; this.ringpop = ringpop; this.store = {}; this._seed(seedConfig); }
[ "function", "Config", "(", "ringpop", ",", "seedConfig", ")", "{", "seedConfig", "=", "seedConfig", "||", "{", "}", ";", "this", ".", "ringpop", "=", "ringpop", ";", "this", ".", "store", "=", "{", "}", ";", "this", ".", "_seed", "(", "seedConfig", ")", ";", "}" ]
This Config class is meant to be a central store for configurable parameters in Ringpop. Parameters are meant to be initialized in the constructor.
[ "This", "Config", "class", "is", "meant", "to", "be", "a", "central", "store", "for", "configurable", "parameters", "in", "Ringpop", ".", "Parameters", "are", "meant", "to", "be", "initialized", "in", "the", "constructor", "." ]
aec09a8ed304f4db3e1d67a4e94c55fffe06206e
https://github.com/uber-node/ringpop-node/blob/aec09a8ed304f4db3e1d67a4e94c55fffe06206e/config.js#L31-L36
15,633
uber-node/ringpop-node
lib/membership/update.js
Update
function Update(subject, source) { if (!(this instanceof Update)) { return new Update(subject, source); } this.id = uuid.v4(); this.timestamp = Date.now(); // Populate subject subject = subject || {}; this.address = subject.address; this.incarnationNumber = subject.incarnationNumber; this.status = subject.status; // Populate source source = source || {}; this.source = source.address; this.sourceIncarnationNumber = source.incarnationNumber; }
javascript
function Update(subject, source) { if (!(this instanceof Update)) { return new Update(subject, source); } this.id = uuid.v4(); this.timestamp = Date.now(); // Populate subject subject = subject || {}; this.address = subject.address; this.incarnationNumber = subject.incarnationNumber; this.status = subject.status; // Populate source source = source || {}; this.source = source.address; this.sourceIncarnationNumber = source.incarnationNumber; }
[ "function", "Update", "(", "subject", ",", "source", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Update", ")", ")", "{", "return", "new", "Update", "(", "subject", ",", "source", ")", ";", "}", "this", ".", "id", "=", "uuid", ".", "v4", "(", ")", ";", "this", ".", "timestamp", "=", "Date", ".", "now", "(", ")", ";", "// Populate subject", "subject", "=", "subject", "||", "{", "}", ";", "this", ".", "address", "=", "subject", ".", "address", ";", "this", ".", "incarnationNumber", "=", "subject", ".", "incarnationNumber", ";", "this", ".", "status", "=", "subject", ".", "status", ";", "// Populate source", "source", "=", "source", "||", "{", "}", ";", "this", ".", "source", "=", "source", ".", "address", ";", "this", ".", "sourceIncarnationNumber", "=", "source", ".", "incarnationNumber", ";", "}" ]
Create a new Update @param {IMember} subject the subject of the update. @param {IMember} [source] the source of the update. @constructor
[ "Create", "a", "new", "Update" ]
aec09a8ed304f4db3e1d67a4e94c55fffe06206e
https://github.com/uber-node/ringpop-node/blob/aec09a8ed304f4db3e1d67a4e94c55fffe06206e/lib/membership/update.js#L31-L48
15,634
uber-node/ringpop-node
lib/gossip/joiner.js
takeNode
function takeNode(hosts) { var index = Math.floor(Math.random() * hosts.length); var host = hosts[index]; hosts.splice(index, 1); return host; }
javascript
function takeNode(hosts) { var index = Math.floor(Math.random() * hosts.length); var host = hosts[index]; hosts.splice(index, 1); return host; }
[ "function", "takeNode", "(", "hosts", ")", "{", "var", "index", "=", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "hosts", ".", "length", ")", ";", "var", "host", "=", "hosts", "[", "index", "]", ";", "hosts", ".", "splice", "(", "index", ",", "1", ")", ";", "return", "host", ";", "}" ]
Note that this function mutates the array passed in.
[ "Note", "that", "this", "function", "mutates", "the", "array", "passed", "in", "." ]
aec09a8ed304f4db3e1d67a4e94c55fffe06206e
https://github.com/uber-node/ringpop-node/blob/aec09a8ed304f4db3e1d67a4e94c55fffe06206e/lib/gossip/joiner.js#L55-L60
15,635
uber-node/ringpop-node
lib/membership/events.js
DampingReusableEvent
function DampingReusableEvent(member, oldDampScore) { this.name = this.constructor.name; this.member = member; this.oldDampScore = oldDampScore; }
javascript
function DampingReusableEvent(member, oldDampScore) { this.name = this.constructor.name; this.member = member; this.oldDampScore = oldDampScore; }
[ "function", "DampingReusableEvent", "(", "member", ",", "oldDampScore", ")", "{", "this", ".", "name", "=", "this", ".", "constructor", ".", "name", ";", "this", ".", "member", "=", "member", ";", "this", ".", "oldDampScore", "=", "oldDampScore", ";", "}" ]
A member becomes reusable when the damp score of a previously damped member falls below the reuse limit as specified in config.js by dampScoringReuseLimit.
[ "A", "member", "becomes", "reusable", "when", "the", "damp", "score", "of", "a", "previously", "damped", "member", "falls", "below", "the", "reuse", "limit", "as", "specified", "in", "config", ".", "js", "by", "dampScoringReuseLimit", "." ]
aec09a8ed304f4db3e1d67a4e94c55fffe06206e
https://github.com/uber-node/ringpop-node/blob/aec09a8ed304f4db3e1d67a4e94c55fffe06206e/lib/membership/events.js#L33-L37
15,636
uber-node/ringpop-node
lib/gossip/damper.js
createDampReqHandler
function createDampReqHandler(addr) { var start = self.Date.now(); return function onDampReq(err, res) { var timing = self.Date.now() - start; self.ringpop.stat('timing', 'protocol.damp-req', timing); // Prevents double-callback if (typeof callback !== 'function') { return; } numPendingReqs--; if (err) { errors.push(err); } else { // Enrich the result with the addr of the damp // req member for reporting purposes. res.dampReqAddr = addr; res.timing = timing; results.push(res); } // The first rVal requests will be reported. if (results.length >= rVal) { callback(null, results); callback = null; return; } if (numPendingReqs < rVal - results.length) { callback(UnattainableRValError({ flappers: flapperAddrs, rVal: rVal, errors: errors })); callback = null; return; } }; }
javascript
function createDampReqHandler(addr) { var start = self.Date.now(); return function onDampReq(err, res) { var timing = self.Date.now() - start; self.ringpop.stat('timing', 'protocol.damp-req', timing); // Prevents double-callback if (typeof callback !== 'function') { return; } numPendingReqs--; if (err) { errors.push(err); } else { // Enrich the result with the addr of the damp // req member for reporting purposes. res.dampReqAddr = addr; res.timing = timing; results.push(res); } // The first rVal requests will be reported. if (results.length >= rVal) { callback(null, results); callback = null; return; } if (numPendingReqs < rVal - results.length) { callback(UnattainableRValError({ flappers: flapperAddrs, rVal: rVal, errors: errors })); callback = null; return; } }; }
[ "function", "createDampReqHandler", "(", "addr", ")", "{", "var", "start", "=", "self", ".", "Date", ".", "now", "(", ")", ";", "return", "function", "onDampReq", "(", "err", ",", "res", ")", "{", "var", "timing", "=", "self", ".", "Date", ".", "now", "(", ")", "-", "start", ";", "self", ".", "ringpop", ".", "stat", "(", "'timing'", ",", "'protocol.damp-req'", ",", "timing", ")", ";", "// Prevents double-callback", "if", "(", "typeof", "callback", "!==", "'function'", ")", "{", "return", ";", "}", "numPendingReqs", "--", ";", "if", "(", "err", ")", "{", "errors", ".", "push", "(", "err", ")", ";", "}", "else", "{", "// Enrich the result with the addr of the damp", "// req member for reporting purposes.", "res", ".", "dampReqAddr", "=", "addr", ";", "res", ".", "timing", "=", "timing", ";", "results", ".", "push", "(", "res", ")", ";", "}", "// The first rVal requests will be reported.", "if", "(", "results", ".", "length", ">=", "rVal", ")", "{", "callback", "(", "null", ",", "results", ")", ";", "callback", "=", "null", ";", "return", ";", "}", "if", "(", "numPendingReqs", "<", "rVal", "-", "results", ".", "length", ")", "{", "callback", "(", "UnattainableRValError", "(", "{", "flappers", ":", "flapperAddrs", ",", "rVal", ":", "rVal", ",", "errors", ":", "errors", "}", ")", ")", ";", "callback", "=", "null", ";", "return", ";", "}", "}", ";", "}" ]
Accumulate responses until rVal is satisfied or is impossible to satisfy because too many error responses.
[ "Accumulate", "responses", "until", "rVal", "is", "satisfied", "or", "is", "impossible", "to", "satisfy", "because", "too", "many", "error", "responses", "." ]
aec09a8ed304f4db3e1d67a4e94c55fffe06206e
https://github.com/uber-node/ringpop-node/blob/aec09a8ed304f4db3e1d67a4e94c55fffe06206e/lib/gossip/damper.js#L427-L467
15,637
uber-node/ringpop-node
lib/middleware/stack.js
callRequestMiddleware
function callRequestMiddleware(arg2, arg3) { i += 1; if (i < self.middlewares.length) { var next = self.middlewares[i].request; if (typeof next === 'function') { next(req, arg2, arg3, callRequestMiddleware); } else { // skip this middleware if it doesn't implement request callRequestMiddleware(arg2, arg3); } } else { handler(req, arg2, arg3, callResponseMiddleware); } }
javascript
function callRequestMiddleware(arg2, arg3) { i += 1; if (i < self.middlewares.length) { var next = self.middlewares[i].request; if (typeof next === 'function') { next(req, arg2, arg3, callRequestMiddleware); } else { // skip this middleware if it doesn't implement request callRequestMiddleware(arg2, arg3); } } else { handler(req, arg2, arg3, callResponseMiddleware); } }
[ "function", "callRequestMiddleware", "(", "arg2", ",", "arg3", ")", "{", "i", "+=", "1", ";", "if", "(", "i", "<", "self", ".", "middlewares", ".", "length", ")", "{", "var", "next", "=", "self", ".", "middlewares", "[", "i", "]", ".", "request", ";", "if", "(", "typeof", "next", "===", "'function'", ")", "{", "next", "(", "req", ",", "arg2", ",", "arg3", ",", "callRequestMiddleware", ")", ";", "}", "else", "{", "// skip this middleware if it doesn't implement request", "callRequestMiddleware", "(", "arg2", ",", "arg3", ")", ";", "}", "}", "else", "{", "handler", "(", "req", ",", "arg2", ",", "arg3", ",", "callResponseMiddleware", ")", ";", "}", "}" ]
This function calls the next request middleware in the stack or, if there is none left, calls the first response middleware, in reverse. It also skips any middlewares that don't implement the request method.
[ "This", "function", "calls", "the", "next", "request", "middleware", "in", "the", "stack", "or", "if", "there", "is", "none", "left", "calls", "the", "first", "response", "middleware", "in", "reverse", ".", "It", "also", "skips", "any", "middlewares", "that", "don", "t", "implement", "the", "request", "method", "." ]
aec09a8ed304f4db3e1d67a4e94c55fffe06206e
https://github.com/uber-node/ringpop-node/blob/aec09a8ed304f4db3e1d67a4e94c55fffe06206e/lib/middleware/stack.js#L73-L86
15,638
uber-node/ringpop-node
lib/middleware/stack.js
callResponseMiddleware
function callResponseMiddleware(err, res1, res2) { i -= 1; if (i >= 0) { var next = self.middlewares[i].response; if (typeof next === 'function') { next(req, err, res1, res2, callResponseMiddleware); } else { // skip this middleware if it doesn't implement response callResponseMiddleware(err, res1, res2); } } else { callback(req, err, res1, res2); } }
javascript
function callResponseMiddleware(err, res1, res2) { i -= 1; if (i >= 0) { var next = self.middlewares[i].response; if (typeof next === 'function') { next(req, err, res1, res2, callResponseMiddleware); } else { // skip this middleware if it doesn't implement response callResponseMiddleware(err, res1, res2); } } else { callback(req, err, res1, res2); } }
[ "function", "callResponseMiddleware", "(", "err", ",", "res1", ",", "res2", ")", "{", "i", "-=", "1", ";", "if", "(", "i", ">=", "0", ")", "{", "var", "next", "=", "self", ".", "middlewares", "[", "i", "]", ".", "response", ";", "if", "(", "typeof", "next", "===", "'function'", ")", "{", "next", "(", "req", ",", "err", ",", "res1", ",", "res2", ",", "callResponseMiddleware", ")", ";", "}", "else", "{", "// skip this middleware if it doesn't implement response", "callResponseMiddleware", "(", "err", ",", "res1", ",", "res2", ")", ";", "}", "}", "else", "{", "callback", "(", "req", ",", "err", ",", "res1", ",", "res2", ")", ";", "}", "}" ]
This function call the next response middleware in the stack until there are none left; in that case the callback is called instead, and the middleware run is completed.
[ "This", "function", "call", "the", "next", "response", "middleware", "in", "the", "stack", "until", "there", "are", "none", "left", ";", "in", "that", "case", "the", "callback", "is", "called", "instead", "and", "the", "middleware", "run", "is", "completed", "." ]
aec09a8ed304f4db3e1d67a4e94c55fffe06206e
https://github.com/uber-node/ringpop-node/blob/aec09a8ed304f4db3e1d67a4e94c55fffe06206e/lib/middleware/stack.js#L90-L103
15,639
dependents/node-dependency-tree
index.js
dedupeNonExistent
function dedupeNonExistent(nonExistent) { const deduped = new Set(nonExistent); nonExistent.length = deduped.size; let i = 0; for (const elem of deduped) { nonExistent[i] = elem; i++; } }
javascript
function dedupeNonExistent(nonExistent) { const deduped = new Set(nonExistent); nonExistent.length = deduped.size; let i = 0; for (const elem of deduped) { nonExistent[i] = elem; i++; } }
[ "function", "dedupeNonExistent", "(", "nonExistent", ")", "{", "const", "deduped", "=", "new", "Set", "(", "nonExistent", ")", ";", "nonExistent", ".", "length", "=", "deduped", ".", "size", ";", "let", "i", "=", "0", ";", "for", "(", "const", "elem", "of", "deduped", ")", "{", "nonExistent", "[", "i", "]", "=", "elem", ";", "i", "++", ";", "}", "}" ]
Mutate the list input to do a dereferenced modification of the user-supplied list
[ "Mutate", "the", "list", "input", "to", "do", "a", "dereferenced", "modification", "of", "the", "user", "-", "supplied", "list" ]
bcb7d304c15590be4bf7d4a533aaaa2f109e5bb1
https://github.com/dependents/node-dependency-tree/blob/bcb7d304c15590be4bf7d4a533aaaa2f109e5bb1/index.js#L190-L199
15,640
appium/appium-ios-driver
lib/settings.js
setLocale
async function setLocale (sim, opts, localeConfig = {}, safari = false) { if (!opts.language && !opts.locale && !opts.calendarFormat) { logger.debug('No reason to set locale'); return { _updated: false, }; } // we need the simulator to have its directories in place if (await sim.isFresh()) { await launchAndQuitSimulator(sim, safari); } logger.debug('Setting locale information'); localeConfig = { language: opts.language || localeConfig.language, locale: opts.locale || localeConfig.locale, calendarFormat: opts.calendarFormat || localeConfig.calendarFormat, _updated: false, }; try { let updated = await sim.updateLocale(opts.language, opts.locale, opts.calendarFormat); if (updated) { localeConfig._updated = true; } } catch (e) { logger.errorAndThrow(`Appium was unable to set locale info: ${e}`); } return localeConfig; }
javascript
async function setLocale (sim, opts, localeConfig = {}, safari = false) { if (!opts.language && !opts.locale && !opts.calendarFormat) { logger.debug('No reason to set locale'); return { _updated: false, }; } // we need the simulator to have its directories in place if (await sim.isFresh()) { await launchAndQuitSimulator(sim, safari); } logger.debug('Setting locale information'); localeConfig = { language: opts.language || localeConfig.language, locale: opts.locale || localeConfig.locale, calendarFormat: opts.calendarFormat || localeConfig.calendarFormat, _updated: false, }; try { let updated = await sim.updateLocale(opts.language, opts.locale, opts.calendarFormat); if (updated) { localeConfig._updated = true; } } catch (e) { logger.errorAndThrow(`Appium was unable to set locale info: ${e}`); } return localeConfig; }
[ "async", "function", "setLocale", "(", "sim", ",", "opts", ",", "localeConfig", "=", "{", "}", ",", "safari", "=", "false", ")", "{", "if", "(", "!", "opts", ".", "language", "&&", "!", "opts", ".", "locale", "&&", "!", "opts", ".", "calendarFormat", ")", "{", "logger", ".", "debug", "(", "'No reason to set locale'", ")", ";", "return", "{", "_updated", ":", "false", ",", "}", ";", "}", "// we need the simulator to have its directories in place", "if", "(", "await", "sim", ".", "isFresh", "(", ")", ")", "{", "await", "launchAndQuitSimulator", "(", "sim", ",", "safari", ")", ";", "}", "logger", ".", "debug", "(", "'Setting locale information'", ")", ";", "localeConfig", "=", "{", "language", ":", "opts", ".", "language", "||", "localeConfig", ".", "language", ",", "locale", ":", "opts", ".", "locale", "||", "localeConfig", ".", "locale", ",", "calendarFormat", ":", "opts", ".", "calendarFormat", "||", "localeConfig", ".", "calendarFormat", ",", "_updated", ":", "false", ",", "}", ";", "try", "{", "let", "updated", "=", "await", "sim", ".", "updateLocale", "(", "opts", ".", "language", ",", "opts", ".", "locale", ",", "opts", ".", "calendarFormat", ")", ";", "if", "(", "updated", ")", "{", "localeConfig", ".", "_updated", "=", "true", ";", "}", "}", "catch", "(", "e", ")", "{", "logger", ".", "errorAndThrow", "(", "`", "${", "e", "}", "`", ")", ";", "}", "return", "localeConfig", ";", "}" ]
pass in the simulator so that other systems that use the function can supply whatever they have
[ "pass", "in", "the", "simulator", "so", "that", "other", "systems", "that", "use", "the", "function", "can", "supply", "whatever", "they", "have" ]
539ea68298c7cfd6658c7881599cb9d62c82a579
https://github.com/appium/appium-ios-driver/blob/539ea68298c7cfd6658c7881599cb9d62c82a579/lib/settings.js#L42-L73
15,641
appium/appium-ios-driver
lib/commands/find.js
function (strategy, selector, mult, context) { let ext = mult ? 's' : ''; let command = ''; context = !context ? context : `, '${context}'` ; switch (strategy) { case 'name': command = `au.getElement${ext}ByName('${selector}'${context})`; break; case 'accessibility id': command = `au.getElement${ext}ByAccessibilityId('${selector}'${context})`; break; case 'id': command = `au.getElement${ext}ById('${selector}')`; break; case '-ios uiautomation': command = `au.getElement${ext}ByUIAutomation('${selector}'${context})`; break; default: command = `au.getElement${ext}ByType('${selector}'${context})`; } return command; }
javascript
function (strategy, selector, mult, context) { let ext = mult ? 's' : ''; let command = ''; context = !context ? context : `, '${context}'` ; switch (strategy) { case 'name': command = `au.getElement${ext}ByName('${selector}'${context})`; break; case 'accessibility id': command = `au.getElement${ext}ByAccessibilityId('${selector}'${context})`; break; case 'id': command = `au.getElement${ext}ById('${selector}')`; break; case '-ios uiautomation': command = `au.getElement${ext}ByUIAutomation('${selector}'${context})`; break; default: command = `au.getElement${ext}ByType('${selector}'${context})`; } return command; }
[ "function", "(", "strategy", ",", "selector", ",", "mult", ",", "context", ")", "{", "let", "ext", "=", "mult", "?", "'s'", ":", "''", ";", "let", "command", "=", "''", ";", "context", "=", "!", "context", "?", "context", ":", "`", "${", "context", "}", "`", ";", "switch", "(", "strategy", ")", "{", "case", "'name'", ":", "command", "=", "`", "${", "ext", "}", "${", "selector", "}", "${", "context", "}", "`", ";", "break", ";", "case", "'accessibility id'", ":", "command", "=", "`", "${", "ext", "}", "${", "selector", "}", "${", "context", "}", "`", ";", "break", ";", "case", "'id'", ":", "command", "=", "`", "${", "ext", "}", "${", "selector", "}", "`", ";", "break", ";", "case", "'-ios uiautomation'", ":", "command", "=", "`", "${", "ext", "}", "${", "selector", "}", "${", "context", "}", "`", ";", "break", ";", "default", ":", "command", "=", "`", "${", "ext", "}", "${", "selector", "}", "${", "context", "}", "`", ";", "}", "return", "command", ";", "}" ]
eslint-disable-line curly
[ "eslint", "-", "disable", "-", "line", "curly" ]
539ea68298c7cfd6658c7881599cb9d62c82a579
https://github.com/appium/appium-ios-driver/blob/539ea68298c7cfd6658c7881599cb9d62c82a579/lib/commands/find.js#L60-L82
15,642
appium/appium-ios-driver
uiauto/lib/mechanic-ext/alert-ext.js
function () { var alert = getAlert(); if (alert.isNil()) { throw new ERROR.NoAlertOpenError(); } var texts = this.getElementsByType('text', alert); // If an alert does not have a title, alert.name() is null, use empty string var text = alert.name() || ""; if (texts.length > 1) { // Safari alerts have the URL as a title if (text.indexOf('http') === 0 || text === "") { text = texts.last().name(); } else { // go through all the text elements and concatenate text = null; for (var i = 0; i < texts.length; i++) { var subtext = texts[i].name(); if (subtext) { // if there is text, append it, otherwise use sub text text = text ? text + ' ' + subtext : subtext; } } } } else if (parseFloat($.systemVersion) >= 9.3) { // iOS 9.3 Safari alerts only have one UIATextView texts = this.getElementsByType('UIATextView', alert); text = texts[0].name(); } return text; }
javascript
function () { var alert = getAlert(); if (alert.isNil()) { throw new ERROR.NoAlertOpenError(); } var texts = this.getElementsByType('text', alert); // If an alert does not have a title, alert.name() is null, use empty string var text = alert.name() || ""; if (texts.length > 1) { // Safari alerts have the URL as a title if (text.indexOf('http') === 0 || text === "") { text = texts.last().name(); } else { // go through all the text elements and concatenate text = null; for (var i = 0; i < texts.length; i++) { var subtext = texts[i].name(); if (subtext) { // if there is text, append it, otherwise use sub text text = text ? text + ' ' + subtext : subtext; } } } } else if (parseFloat($.systemVersion) >= 9.3) { // iOS 9.3 Safari alerts only have one UIATextView texts = this.getElementsByType('UIATextView', alert); text = texts[0].name(); } return text; }
[ "function", "(", ")", "{", "var", "alert", "=", "getAlert", "(", ")", ";", "if", "(", "alert", ".", "isNil", "(", ")", ")", "{", "throw", "new", "ERROR", ".", "NoAlertOpenError", "(", ")", ";", "}", "var", "texts", "=", "this", ".", "getElementsByType", "(", "'text'", ",", "alert", ")", ";", "// If an alert does not have a title, alert.name() is null, use empty string", "var", "text", "=", "alert", ".", "name", "(", ")", "||", "\"\"", ";", "if", "(", "texts", ".", "length", ">", "1", ")", "{", "// Safari alerts have the URL as a title", "if", "(", "text", ".", "indexOf", "(", "'http'", ")", "===", "0", "||", "text", "===", "\"\"", ")", "{", "text", "=", "texts", ".", "last", "(", ")", ".", "name", "(", ")", ";", "}", "else", "{", "// go through all the text elements and concatenate", "text", "=", "null", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "texts", ".", "length", ";", "i", "++", ")", "{", "var", "subtext", "=", "texts", "[", "i", "]", ".", "name", "(", ")", ";", "if", "(", "subtext", ")", "{", "// if there is text, append it, otherwise use sub text", "text", "=", "text", "?", "text", "+", "' '", "+", "subtext", ":", "subtext", ";", "}", "}", "}", "}", "else", "if", "(", "parseFloat", "(", "$", ".", "systemVersion", ")", ">=", "9.3", ")", "{", "// iOS 9.3 Safari alerts only have one UIATextView", "texts", "=", "this", ".", "getElementsByType", "(", "'UIATextView'", ",", "alert", ")", ";", "text", "=", "texts", "[", "0", "]", ".", "name", "(", ")", ";", "}", "return", "text", ";", "}" ]
Alert-related functions
[ "Alert", "-", "related", "functions" ]
539ea68298c7cfd6658c7881599cb9d62c82a579
https://github.com/appium/appium-ios-driver/blob/539ea68298c7cfd6658c7881599cb9d62c82a579/uiauto/lib/mechanic-ext/alert-ext.js#L39-L69
15,643
appium/appium-ios-driver
lib/instruments/utils.js
quickLaunch
async function quickLaunch (udid, appPath = path.resolve(__dirname, '..', '..', 'assets', 'TestApp.app')) { let traceTemplatePath = await xcode.getAutomationTraceTemplatePath(); let scriptPath = path.resolve(__dirname, '..', '..', 'assets', 'blank_instruments_test.js'); let traceDocument = path.resolve('/', 'tmp', 'testTrace.trace'); let resultsPath = path.resolve('/', 'tmp'); // the trace document can be in a weird state // but we never do anything with it, so delete await fs.rimraf(traceDocument); let args = [ 'instruments', '-D', traceDocument, '-t', traceTemplatePath, '-w', udid, appPath, '-e', 'UIASCRIPT', scriptPath, '-e', 'UIARESULTSPATH', resultsPath]; log.debug(`Running command: 'xcrun ${args.join(' ')}'`); await exec('xcrun', args); }
javascript
async function quickLaunch (udid, appPath = path.resolve(__dirname, '..', '..', 'assets', 'TestApp.app')) { let traceTemplatePath = await xcode.getAutomationTraceTemplatePath(); let scriptPath = path.resolve(__dirname, '..', '..', 'assets', 'blank_instruments_test.js'); let traceDocument = path.resolve('/', 'tmp', 'testTrace.trace'); let resultsPath = path.resolve('/', 'tmp'); // the trace document can be in a weird state // but we never do anything with it, so delete await fs.rimraf(traceDocument); let args = [ 'instruments', '-D', traceDocument, '-t', traceTemplatePath, '-w', udid, appPath, '-e', 'UIASCRIPT', scriptPath, '-e', 'UIARESULTSPATH', resultsPath]; log.debug(`Running command: 'xcrun ${args.join(' ')}'`); await exec('xcrun', args); }
[ "async", "function", "quickLaunch", "(", "udid", ",", "appPath", "=", "path", ".", "resolve", "(", "__dirname", ",", "'..'", ",", "'..'", ",", "'assets'", ",", "'TestApp.app'", ")", ")", "{", "let", "traceTemplatePath", "=", "await", "xcode", ".", "getAutomationTraceTemplatePath", "(", ")", ";", "let", "scriptPath", "=", "path", ".", "resolve", "(", "__dirname", ",", "'..'", ",", "'..'", ",", "'assets'", ",", "'blank_instruments_test.js'", ")", ";", "let", "traceDocument", "=", "path", ".", "resolve", "(", "'/'", ",", "'tmp'", ",", "'testTrace.trace'", ")", ";", "let", "resultsPath", "=", "path", ".", "resolve", "(", "'/'", ",", "'tmp'", ")", ";", "// the trace document can be in a weird state", "// but we never do anything with it, so delete", "await", "fs", ".", "rimraf", "(", "traceDocument", ")", ";", "let", "args", "=", "[", "'instruments'", ",", "'-D'", ",", "traceDocument", ",", "'-t'", ",", "traceTemplatePath", ",", "'-w'", ",", "udid", ",", "appPath", ",", "'-e'", ",", "'UIASCRIPT'", ",", "scriptPath", ",", "'-e'", ",", "'UIARESULTSPATH'", ",", "resultsPath", "]", ";", "log", ".", "debug", "(", "`", "${", "args", ".", "join", "(", "' '", ")", "}", "`", ")", ";", "await", "exec", "(", "'xcrun'", ",", "args", ")", ";", "}" ]
this function launches an instruments test with a default test that immediately passes. In this way we can start a simulator and be notified when it completely launches
[ "this", "function", "launches", "an", "instruments", "test", "with", "a", "default", "test", "that", "immediately", "passes", ".", "In", "this", "way", "we", "can", "start", "a", "simulator", "and", "be", "notified", "when", "it", "completely", "launches" ]
539ea68298c7cfd6658c7881599cb9d62c82a579
https://github.com/appium/appium-ios-driver/blob/539ea68298c7cfd6658c7881599cb9d62c82a579/lib/instruments/utils.js#L96-L116
15,644
appium/appium-ios-driver
lib/cookies.js
convertCookie
function convertCookie (value, converter) { if (value.indexOf('"') === 0) { // this is a quoted cookied according to RFC2068 // remove enclosing quotes and internal quotes and backslashes value = value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\'); } let parsedValue; try { parsedValue = decodeURIComponent(value.replace(/\+/g, ' ')); } catch (e) { // no need to fail if we can't decode log.warn(e); } return converter ? converter(parsedValue) : parsedValue; }
javascript
function convertCookie (value, converter) { if (value.indexOf('"') === 0) { // this is a quoted cookied according to RFC2068 // remove enclosing quotes and internal quotes and backslashes value = value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\'); } let parsedValue; try { parsedValue = decodeURIComponent(value.replace(/\+/g, ' ')); } catch (e) { // no need to fail if we can't decode log.warn(e); } return converter ? converter(parsedValue) : parsedValue; }
[ "function", "convertCookie", "(", "value", ",", "converter", ")", "{", "if", "(", "value", ".", "indexOf", "(", "'\"'", ")", "===", "0", ")", "{", "// this is a quoted cookied according to RFC2068", "// remove enclosing quotes and internal quotes and backslashes", "value", "=", "value", ".", "slice", "(", "1", ",", "-", "1", ")", ".", "replace", "(", "/", "\\\\\"", "/", "g", ",", "'\"'", ")", ".", "replace", "(", "/", "\\\\\\\\", "/", "g", ",", "'\\\\'", ")", ";", "}", "let", "parsedValue", ";", "try", "{", "parsedValue", "=", "decodeURIComponent", "(", "value", ".", "replace", "(", "/", "\\+", "/", "g", ",", "' '", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "// no need to fail if we can't decode", "log", ".", "warn", "(", "e", ")", ";", "}", "return", "converter", "?", "converter", "(", "parsedValue", ")", ":", "parsedValue", ";", "}" ]
parses the value if needed and converts the value if a converter is provided internal function, not exported
[ "parses", "the", "value", "if", "needed", "and", "converts", "the", "value", "if", "a", "converter", "is", "provided", "internal", "function", "not", "exported" ]
539ea68298c7cfd6658c7881599cb9d62c82a579
https://github.com/appium/appium-ios-driver/blob/539ea68298c7cfd6658c7881599cb9d62c82a579/lib/cookies.js#L16-L32
15,645
appium/appium-ios-driver
lib/cookies.js
createJSCookie
function createJSCookie (key, value, options = {}) { return [ encodeURIComponent(key), '=', value, options.expires ? `; expires=${options.expires}` : '', options.path ? `; path=${options.path}` : '', options.domain ? `; domain=${options.domain}` : '', options.secure ? '; secure' : '' ].join(''); }
javascript
function createJSCookie (key, value, options = {}) { return [ encodeURIComponent(key), '=', value, options.expires ? `; expires=${options.expires}` : '', options.path ? `; path=${options.path}` : '', options.domain ? `; domain=${options.domain}` : '', options.secure ? '; secure' : '' ].join(''); }
[ "function", "createJSCookie", "(", "key", ",", "value", ",", "options", "=", "{", "}", ")", "{", "return", "[", "encodeURIComponent", "(", "key", ")", ",", "'='", ",", "value", ",", "options", ".", "expires", "?", "`", "${", "options", ".", "expires", "}", "`", ":", "''", ",", "options", ".", "path", "?", "`", "${", "options", ".", "path", "}", "`", ":", "''", ",", "options", ".", "domain", "?", "`", "${", "options", ".", "domain", "}", "`", ":", "''", ",", "options", ".", "secure", "?", "'; secure'", ":", "''", "]", ".", "join", "(", "''", ")", ";", "}" ]
takes arguments given and creates a JavaScript Cookie
[ "takes", "arguments", "given", "and", "creates", "a", "JavaScript", "Cookie" ]
539ea68298c7cfd6658c7881599cb9d62c82a579
https://github.com/appium/appium-ios-driver/blob/539ea68298c7cfd6658c7881599cb9d62c82a579/lib/cookies.js#L35-L51
15,646
appium/appium-ios-driver
lib/cookies.js
createJWPCookie
function createJWPCookie (key, cookieString, converter = null) { let result = {}; let cookies = cookieString ? cookieString.split('; ') : []; for (let cookie of cookies) { let parts = cookie.split('='); // get the first and second element as name and value let name = decodeURIComponent(parts.shift()); let val = parts[0]; // if name is key, this is the central element of the cookie, so add as `name` // otherwise it is an optional element if (key && key === name) { result.name = key; result.value = convertCookie(val, converter); } else { result[name] = convertCookie(val, converter); } } return result; }
javascript
function createJWPCookie (key, cookieString, converter = null) { let result = {}; let cookies = cookieString ? cookieString.split('; ') : []; for (let cookie of cookies) { let parts = cookie.split('='); // get the first and second element as name and value let name = decodeURIComponent(parts.shift()); let val = parts[0]; // if name is key, this is the central element of the cookie, so add as `name` // otherwise it is an optional element if (key && key === name) { result.name = key; result.value = convertCookie(val, converter); } else { result[name] = convertCookie(val, converter); } } return result; }
[ "function", "createJWPCookie", "(", "key", ",", "cookieString", ",", "converter", "=", "null", ")", "{", "let", "result", "=", "{", "}", ";", "let", "cookies", "=", "cookieString", "?", "cookieString", ".", "split", "(", "'; '", ")", ":", "[", "]", ";", "for", "(", "let", "cookie", "of", "cookies", ")", "{", "let", "parts", "=", "cookie", ".", "split", "(", "'='", ")", ";", "// get the first and second element as name and value", "let", "name", "=", "decodeURIComponent", "(", "parts", ".", "shift", "(", ")", ")", ";", "let", "val", "=", "parts", "[", "0", "]", ";", "// if name is key, this is the central element of the cookie, so add as `name`", "// otherwise it is an optional element", "if", "(", "key", "&&", "key", "===", "name", ")", "{", "result", ".", "name", "=", "key", ";", "result", ".", "value", "=", "convertCookie", "(", "val", ",", "converter", ")", ";", "}", "else", "{", "result", "[", "name", "]", "=", "convertCookie", "(", "val", ",", "converter", ")", ";", "}", "}", "return", "result", ";", "}" ]
takes the JavaScript cookieString and translates it into a JSONWire formatted cookie
[ "takes", "the", "JavaScript", "cookieString", "and", "translates", "it", "into", "a", "JSONWire", "formatted", "cookie" ]
539ea68298c7cfd6658c7881599cb9d62c82a579
https://github.com/appium/appium-ios-driver/blob/539ea68298c7cfd6658c7881599cb9d62c82a579/lib/cookies.js#L54-L74
15,647
appium/appium-ios-driver
lib/cookies.js
getValue
function getValue (key, cookieString, converter = null) { let result = createJWPCookie(key, cookieString, converter); // if `key` is undefined we want the entire cookie return _.isUndefined(key) ? result : result.value; }
javascript
function getValue (key, cookieString, converter = null) { let result = createJWPCookie(key, cookieString, converter); // if `key` is undefined we want the entire cookie return _.isUndefined(key) ? result : result.value; }
[ "function", "getValue", "(", "key", ",", "cookieString", ",", "converter", "=", "null", ")", "{", "let", "result", "=", "createJWPCookie", "(", "key", ",", "cookieString", ",", "converter", ")", ";", "// if `key` is undefined we want the entire cookie", "return", "_", ".", "isUndefined", "(", "key", ")", "?", "result", ":", "result", ".", "value", ";", "}" ]
takes a JavaScript cookiestring and parses it for the value given the key
[ "takes", "a", "JavaScript", "cookiestring", "and", "parses", "it", "for", "the", "value", "given", "the", "key" ]
539ea68298c7cfd6658c7881599cb9d62c82a579
https://github.com/appium/appium-ios-driver/blob/539ea68298c7cfd6658c7881599cb9d62c82a579/lib/cookies.js#L77-L82
15,648
appium/appium-ios-driver
uiauto/lib/mechanic-ext/lookup-ext.js
function (selector, ctx) { if (typeof selector !== 'string') { return null; } var _ctx = $.mainApp() , elems = []; if (typeof ctx === 'string') { _ctx = this.cache[ctx]; } else if (typeof ctx !== 'undefined') { _ctx = ctx; } $.target().pushTimeout(0); if (selector === 'alert') { var alert = $.mainApp().alert(); if (alert) { elems = $(alert); } } else { elems = $(selector, _ctx); } $.target().popTimeout(); return elems; }
javascript
function (selector, ctx) { if (typeof selector !== 'string') { return null; } var _ctx = $.mainApp() , elems = []; if (typeof ctx === 'string') { _ctx = this.cache[ctx]; } else if (typeof ctx !== 'undefined') { _ctx = ctx; } $.target().pushTimeout(0); if (selector === 'alert') { var alert = $.mainApp().alert(); if (alert) { elems = $(alert); } } else { elems = $(selector, _ctx); } $.target().popTimeout(); return elems; }
[ "function", "(", "selector", ",", "ctx", ")", "{", "if", "(", "typeof", "selector", "!==", "'string'", ")", "{", "return", "null", ";", "}", "var", "_ctx", "=", "$", ".", "mainApp", "(", ")", ",", "elems", "=", "[", "]", ";", "if", "(", "typeof", "ctx", "===", "'string'", ")", "{", "_ctx", "=", "this", ".", "cache", "[", "ctx", "]", ";", "}", "else", "if", "(", "typeof", "ctx", "!==", "'undefined'", ")", "{", "_ctx", "=", "ctx", ";", "}", "$", ".", "target", "(", ")", ".", "pushTimeout", "(", "0", ")", ";", "if", "(", "selector", "===", "'alert'", ")", "{", "var", "alert", "=", "$", ".", "mainApp", "(", ")", ".", "alert", "(", ")", ";", "if", "(", "alert", ")", "{", "elems", "=", "$", "(", "alert", ")", ";", "}", "}", "else", "{", "elems", "=", "$", "(", "selector", ",", "_ctx", ")", ";", "}", "$", ".", "target", "(", ")", ".", "popTimeout", "(", ")", ";", "return", "elems", ";", "}" ]
Element lookup functions
[ "Element", "lookup", "functions" ]
539ea68298c7cfd6658c7881599cb9d62c82a579
https://github.com/appium/appium-ios-driver/blob/539ea68298c7cfd6658c7881599cb9d62c82a579/uiauto/lib/mechanic-ext/lookup-ext.js#L8-L34
15,649
appium/appium-ios-driver
uiauto/lib/mechanic-ext/screen-ext.js
function () { var orientation = $.orientation() , value = null; switch (orientation) { case UIA_DEVICE_ORIENTATION_UNKNOWN: case UIA_DEVICE_ORIENTATION_FACEUP: case UIA_DEVICE_ORIENTATION_FACEDOWN: value = "UNKNOWN"; break; case UIA_DEVICE_ORIENTATION_PORTRAIT: case UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN: value = "PORTRAIT"; break; case UIA_DEVICE_ORIENTATION_LANDSCAPELEFT: case UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT: value = "LANDSCAPE"; break; } if (value !== null) { return value; } else { throw new ERROR.UnknownError('Unsupported Orientation: ' + orientation); } }
javascript
function () { var orientation = $.orientation() , value = null; switch (orientation) { case UIA_DEVICE_ORIENTATION_UNKNOWN: case UIA_DEVICE_ORIENTATION_FACEUP: case UIA_DEVICE_ORIENTATION_FACEDOWN: value = "UNKNOWN"; break; case UIA_DEVICE_ORIENTATION_PORTRAIT: case UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN: value = "PORTRAIT"; break; case UIA_DEVICE_ORIENTATION_LANDSCAPELEFT: case UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT: value = "LANDSCAPE"; break; } if (value !== null) { return value; } else { throw new ERROR.UnknownError('Unsupported Orientation: ' + orientation); } }
[ "function", "(", ")", "{", "var", "orientation", "=", "$", ".", "orientation", "(", ")", ",", "value", "=", "null", ";", "switch", "(", "orientation", ")", "{", "case", "UIA_DEVICE_ORIENTATION_UNKNOWN", ":", "case", "UIA_DEVICE_ORIENTATION_FACEUP", ":", "case", "UIA_DEVICE_ORIENTATION_FACEDOWN", ":", "value", "=", "\"UNKNOWN\"", ";", "break", ";", "case", "UIA_DEVICE_ORIENTATION_PORTRAIT", ":", "case", "UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN", ":", "value", "=", "\"PORTRAIT\"", ";", "break", ";", "case", "UIA_DEVICE_ORIENTATION_LANDSCAPELEFT", ":", "case", "UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT", ":", "value", "=", "\"LANDSCAPE\"", ";", "break", ";", "}", "if", "(", "value", "!==", "null", ")", "{", "return", "value", ";", "}", "else", "{", "throw", "new", "ERROR", ".", "UnknownError", "(", "'Unsupported Orientation: '", "+", "orientation", ")", ";", "}", "}" ]
Screen-related functions
[ "Screen", "-", "related", "functions" ]
539ea68298c7cfd6658c7881599cb9d62c82a579
https://github.com/appium/appium-ios-driver/blob/539ea68298c7cfd6658c7881599cb9d62c82a579/uiauto/lib/mechanic-ext/screen-ext.js#L7-L30
15,650
imsky/pull-review
src/github/graphql.js
Request
function Request(options) { return new Promise(function(resolve, reject) { client(options, function(err, res) { if (err) { reject(err); } else { resolve(res); } }); }); }
javascript
function Request(options) { return new Promise(function(resolve, reject) { client(options, function(err, res) { if (err) { reject(err); } else { resolve(res); } }); }); }
[ "function", "Request", "(", "options", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "client", "(", "options", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "else", "{", "resolve", "(", "res", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Promisified wrapper over github-graphql-client @param {Object} options - GraphQL request options
[ "Promisified", "wrapper", "over", "github", "-", "graphql", "-", "client" ]
9eb6d389ac6b7da1ceff470110cfd382a3cde8c1
https://github.com/imsky/pull-review/blob/9eb6d389ac6b7da1ceff470110cfd382a3cde8c1/src/github/graphql.js#L9-L19
15,651
imsky/pull-review
src/github/index.js
BlameRangeList
function BlameRangeList(blame) { var ranges = blame.ranges; return ranges .filter(function(range) { return ( range && range.commit && range.commit.author && range.commit.author.user && range.commit.author.user.login ); }) .map(function(range) { return BlameRange({ age: range.age, count: range.endingLine - range.startingLine + 1, login: range.commit.author.user.login }); }) .filter(Boolean); }
javascript
function BlameRangeList(blame) { var ranges = blame.ranges; return ranges .filter(function(range) { return ( range && range.commit && range.commit.author && range.commit.author.user && range.commit.author.user.login ); }) .map(function(range) { return BlameRange({ age: range.age, count: range.endingLine - range.startingLine + 1, login: range.commit.author.user.login }); }) .filter(Boolean); }
[ "function", "BlameRangeList", "(", "blame", ")", "{", "var", "ranges", "=", "blame", ".", "ranges", ";", "return", "ranges", ".", "filter", "(", "function", "(", "range", ")", "{", "return", "(", "range", "&&", "range", ".", "commit", "&&", "range", ".", "commit", ".", "author", "&&", "range", ".", "commit", ".", "author", ".", "user", "&&", "range", ".", "commit", ".", "author", ".", "user", ".", "login", ")", ";", "}", ")", ".", "map", "(", "function", "(", "range", ")", "{", "return", "BlameRange", "(", "{", "age", ":", "range", ".", "age", ",", "count", ":", "range", ".", "endingLine", "-", "range", ".", "startingLine", "+", "1", ",", "login", ":", "range", ".", "commit", ".", "author", ".", "user", ".", "login", "}", ")", ";", "}", ")", ".", "filter", "(", "Boolean", ")", ";", "}" ]
Convert raw blame data into BlameRanges @param {Object} blame - GitHub blame data @returns {Array} list of BlameRanges
[ "Convert", "raw", "blame", "data", "into", "BlameRanges" ]
9eb6d389ac6b7da1ceff470110cfd382a3cde8c1
https://github.com/imsky/pull-review/blob/9eb6d389ac6b7da1ceff470110cfd382a3cde8c1/src/github/index.js#L33-L54
15,652
imsky/pull-review
src/github/index.js
parseGithubURL
function parseGithubURL(url) { var githubUrlRe = /github\.com\/([^/]+)\/([^/]+)\/pull\/([0-9]+)/; var match = url.match(githubUrlRe); if (!match) { return null; } return { owner: match[1], repo: match[2], number: match[3] }; }
javascript
function parseGithubURL(url) { var githubUrlRe = /github\.com\/([^/]+)\/([^/]+)\/pull\/([0-9]+)/; var match = url.match(githubUrlRe); if (!match) { return null; } return { owner: match[1], repo: match[2], number: match[3] }; }
[ "function", "parseGithubURL", "(", "url", ")", "{", "var", "githubUrlRe", "=", "/", "github\\.com\\/([^/]+)\\/([^/]+)\\/pull\\/([0-9]+)", "/", ";", "var", "match", "=", "url", ".", "match", "(", "githubUrlRe", ")", ";", "if", "(", "!", "match", ")", "{", "return", "null", ";", "}", "return", "{", "owner", ":", "match", "[", "1", "]", ",", "repo", ":", "match", "[", "2", "]", ",", "number", ":", "match", "[", "3", "]", "}", ";", "}" ]
Helper that converts URLs into GitHub resource objects compatible with node-github @param {String} url - A GitHub resource URL @return {Object} GitHub resource parsed from URL
[ "Helper", "that", "converts", "URLs", "into", "GitHub", "resource", "objects", "compatible", "with", "node", "-", "github" ]
9eb6d389ac6b7da1ceff470110cfd382a3cde8c1
https://github.com/imsky/pull-review/blob/9eb6d389ac6b7da1ceff470110cfd382a3cde8c1/src/github/index.js#L62-L75
15,653
ream/ream
app/client-entry.js
main
async function main() { event.$emit('before-client-render') if (globalState.initialData) { dataStore.replaceState(globalState.initialData) } await routerReady(router) if (router.getMatchedComponents().length === 0) { throw new ReamError(pageNotFound(router.currentRoute.path)) } }
javascript
async function main() { event.$emit('before-client-render') if (globalState.initialData) { dataStore.replaceState(globalState.initialData) } await routerReady(router) if (router.getMatchedComponents().length === 0) { throw new ReamError(pageNotFound(router.currentRoute.path)) } }
[ "async", "function", "main", "(", ")", "{", "event", ".", "$emit", "(", "'before-client-render'", ")", "if", "(", "globalState", ".", "initialData", ")", "{", "dataStore", ".", "replaceState", "(", "globalState", ".", "initialData", ")", "}", "await", "routerReady", "(", "router", ")", "if", "(", "router", ".", "getMatchedComponents", "(", ")", ".", "length", "===", "0", ")", "{", "throw", "new", "ReamError", "(", "pageNotFound", "(", "router", ".", "currentRoute", ".", "path", ")", ")", "}", "}" ]
Wait until router has resolved all async before hooks and async components...
[ "Wait", "until", "router", "has", "resolved", "all", "async", "before", "hooks", "and", "async", "components", "..." ]
5f0926c6fe3864ac27c07a6f12503e7b231b0680
https://github.com/ream/ream/blob/5f0926c6fe3864ac27c07a6f12503e7b231b0680/app/client-entry.js#L107-L119
15,654
pillarjs/send
index.js
SendStream
function SendStream (req, path, options) { Stream.call(this) var opts = options || {} this.options = opts this.path = path this.req = req this._acceptRanges = opts.acceptRanges !== undefined ? Boolean(opts.acceptRanges) : true this._cacheControl = opts.cacheControl !== undefined ? Boolean(opts.cacheControl) : true this._etag = opts.etag !== undefined ? Boolean(opts.etag) : true this._dotfiles = opts.dotfiles !== undefined ? opts.dotfiles : 'ignore' if (this._dotfiles !== 'ignore' && this._dotfiles !== 'allow' && this._dotfiles !== 'deny') { throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"') } this._hidden = Boolean(opts.hidden) if (opts.hidden !== undefined) { deprecate('hidden: use dotfiles: \'' + (this._hidden ? 'allow' : 'ignore') + '\' instead') } // legacy support if (opts.dotfiles === undefined) { this._dotfiles = undefined } this._extensions = opts.extensions !== undefined ? normalizeList(opts.extensions, 'extensions option') : [] this._immutable = opts.immutable !== undefined ? Boolean(opts.immutable) : false this._index = opts.index !== undefined ? normalizeList(opts.index, 'index option') : ['index.html'] this._lastModified = opts.lastModified !== undefined ? Boolean(opts.lastModified) : true this._maxage = opts.maxAge || opts.maxage this._maxage = typeof this._maxage === 'string' ? ms(this._maxage) : Number(this._maxage) this._maxage = !isNaN(this._maxage) ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) : 0 this._root = opts.root ? resolve(opts.root) : null if (!this._root && opts.from) { this.from(opts.from) } }
javascript
function SendStream (req, path, options) { Stream.call(this) var opts = options || {} this.options = opts this.path = path this.req = req this._acceptRanges = opts.acceptRanges !== undefined ? Boolean(opts.acceptRanges) : true this._cacheControl = opts.cacheControl !== undefined ? Boolean(opts.cacheControl) : true this._etag = opts.etag !== undefined ? Boolean(opts.etag) : true this._dotfiles = opts.dotfiles !== undefined ? opts.dotfiles : 'ignore' if (this._dotfiles !== 'ignore' && this._dotfiles !== 'allow' && this._dotfiles !== 'deny') { throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"') } this._hidden = Boolean(opts.hidden) if (opts.hidden !== undefined) { deprecate('hidden: use dotfiles: \'' + (this._hidden ? 'allow' : 'ignore') + '\' instead') } // legacy support if (opts.dotfiles === undefined) { this._dotfiles = undefined } this._extensions = opts.extensions !== undefined ? normalizeList(opts.extensions, 'extensions option') : [] this._immutable = opts.immutable !== undefined ? Boolean(opts.immutable) : false this._index = opts.index !== undefined ? normalizeList(opts.index, 'index option') : ['index.html'] this._lastModified = opts.lastModified !== undefined ? Boolean(opts.lastModified) : true this._maxage = opts.maxAge || opts.maxage this._maxage = typeof this._maxage === 'string' ? ms(this._maxage) : Number(this._maxage) this._maxage = !isNaN(this._maxage) ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) : 0 this._root = opts.root ? resolve(opts.root) : null if (!this._root && opts.from) { this.from(opts.from) } }
[ "function", "SendStream", "(", "req", ",", "path", ",", "options", ")", "{", "Stream", ".", "call", "(", "this", ")", "var", "opts", "=", "options", "||", "{", "}", "this", ".", "options", "=", "opts", "this", ".", "path", "=", "path", "this", ".", "req", "=", "req", "this", ".", "_acceptRanges", "=", "opts", ".", "acceptRanges", "!==", "undefined", "?", "Boolean", "(", "opts", ".", "acceptRanges", ")", ":", "true", "this", ".", "_cacheControl", "=", "opts", ".", "cacheControl", "!==", "undefined", "?", "Boolean", "(", "opts", ".", "cacheControl", ")", ":", "true", "this", ".", "_etag", "=", "opts", ".", "etag", "!==", "undefined", "?", "Boolean", "(", "opts", ".", "etag", ")", ":", "true", "this", ".", "_dotfiles", "=", "opts", ".", "dotfiles", "!==", "undefined", "?", "opts", ".", "dotfiles", ":", "'ignore'", "if", "(", "this", ".", "_dotfiles", "!==", "'ignore'", "&&", "this", ".", "_dotfiles", "!==", "'allow'", "&&", "this", ".", "_dotfiles", "!==", "'deny'", ")", "{", "throw", "new", "TypeError", "(", "'dotfiles option must be \"allow\", \"deny\", or \"ignore\"'", ")", "}", "this", ".", "_hidden", "=", "Boolean", "(", "opts", ".", "hidden", ")", "if", "(", "opts", ".", "hidden", "!==", "undefined", ")", "{", "deprecate", "(", "'hidden: use dotfiles: \\''", "+", "(", "this", ".", "_hidden", "?", "'allow'", ":", "'ignore'", ")", "+", "'\\' instead'", ")", "}", "// legacy support", "if", "(", "opts", ".", "dotfiles", "===", "undefined", ")", "{", "this", ".", "_dotfiles", "=", "undefined", "}", "this", ".", "_extensions", "=", "opts", ".", "extensions", "!==", "undefined", "?", "normalizeList", "(", "opts", ".", "extensions", ",", "'extensions option'", ")", ":", "[", "]", "this", ".", "_immutable", "=", "opts", ".", "immutable", "!==", "undefined", "?", "Boolean", "(", "opts", ".", "immutable", ")", ":", "false", "this", ".", "_index", "=", "opts", ".", "index", "!==", "undefined", "?", "normalizeList", "(", "opts", ".", "index", ",", "'index option'", ")", ":", "[", "'index.html'", "]", "this", ".", "_lastModified", "=", "opts", ".", "lastModified", "!==", "undefined", "?", "Boolean", "(", "opts", ".", "lastModified", ")", ":", "true", "this", ".", "_maxage", "=", "opts", ".", "maxAge", "||", "opts", ".", "maxage", "this", ".", "_maxage", "=", "typeof", "this", ".", "_maxage", "===", "'string'", "?", "ms", "(", "this", ".", "_maxage", ")", ":", "Number", "(", "this", ".", "_maxage", ")", "this", ".", "_maxage", "=", "!", "isNaN", "(", "this", ".", "_maxage", ")", "?", "Math", ".", "min", "(", "Math", ".", "max", "(", "0", ",", "this", ".", "_maxage", ")", ",", "MAX_MAXAGE", ")", ":", "0", "this", ".", "_root", "=", "opts", ".", "root", "?", "resolve", "(", "opts", ".", "root", ")", ":", "null", "if", "(", "!", "this", ".", "_root", "&&", "opts", ".", "from", ")", "{", "this", ".", "from", "(", "opts", ".", "from", ")", "}", "}" ]
Initialize a `SendStream` with the given `path`. @param {Request} req @param {String} path @param {object} [options] @private
[ "Initialize", "a", "SendStream", "with", "the", "given", "path", "." ]
0ef8f0cb8d8f3875f034d04d16db37a85f6150d8
https://github.com/pillarjs/send/blob/0ef8f0cb8d8f3875f034d04d16db37a85f6150d8/index.js#L96-L167
15,655
pillarjs/send
index.js
clearHeaders
function clearHeaders (res) { var headers = getHeaderNames(res) for (var i = 0; i < headers.length; i++) { res.removeHeader(headers[i]) } }
javascript
function clearHeaders (res) { var headers = getHeaderNames(res) for (var i = 0; i < headers.length; i++) { res.removeHeader(headers[i]) } }
[ "function", "clearHeaders", "(", "res", ")", "{", "var", "headers", "=", "getHeaderNames", "(", "res", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "headers", ".", "length", ";", "i", "++", ")", "{", "res", ".", "removeHeader", "(", "headers", "[", "i", "]", ")", "}", "}" ]
Clear all headers from a response. @param {object} res @private
[ "Clear", "all", "headers", "from", "a", "response", "." ]
0ef8f0cb8d8f3875f034d04d16db37a85f6150d8
https://github.com/pillarjs/send/blob/0ef8f0cb8d8f3875f034d04d16db37a85f6150d8/index.js#L901-L907
15,656
pillarjs/send
index.js
containsDotFile
function containsDotFile (parts) { for (var i = 0; i < parts.length; i++) { var part = parts[i] if (part.length > 1 && part[0] === '.') { return true } } return false }
javascript
function containsDotFile (parts) { for (var i = 0; i < parts.length; i++) { var part = parts[i] if (part.length > 1 && part[0] === '.') { return true } } return false }
[ "function", "containsDotFile", "(", "parts", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "var", "part", "=", "parts", "[", "i", "]", "if", "(", "part", ".", "length", ">", "1", "&&", "part", "[", "0", "]", "===", "'.'", ")", "{", "return", "true", "}", "}", "return", "false", "}" ]
Determine if path parts contain a dotfile. @api private
[ "Determine", "if", "path", "parts", "contain", "a", "dotfile", "." ]
0ef8f0cb8d8f3875f034d04d16db37a85f6150d8
https://github.com/pillarjs/send/blob/0ef8f0cb8d8f3875f034d04d16db37a85f6150d8/index.js#L933-L942
15,657
pillarjs/send
index.js
contentRange
function contentRange (type, size, range) { return type + ' ' + (range ? range.start + '-' + range.end : '*') + '/' + size }
javascript
function contentRange (type, size, range) { return type + ' ' + (range ? range.start + '-' + range.end : '*') + '/' + size }
[ "function", "contentRange", "(", "type", ",", "size", ",", "range", ")", "{", "return", "type", "+", "' '", "+", "(", "range", "?", "range", ".", "start", "+", "'-'", "+", "range", ".", "end", ":", "'*'", ")", "+", "'/'", "+", "size", "}" ]
Create a Content-Range header. @param {string} type @param {number} size @param {array} [range]
[ "Create", "a", "Content", "-", "Range", "header", "." ]
0ef8f0cb8d8f3875f034d04d16db37a85f6150d8
https://github.com/pillarjs/send/blob/0ef8f0cb8d8f3875f034d04d16db37a85f6150d8/index.js#L952-L954
15,658
pillarjs/send
index.js
getHeaderNames
function getHeaderNames (res) { return typeof res.getHeaderNames !== 'function' ? Object.keys(res._headers || {}) : res.getHeaderNames() }
javascript
function getHeaderNames (res) { return typeof res.getHeaderNames !== 'function' ? Object.keys(res._headers || {}) : res.getHeaderNames() }
[ "function", "getHeaderNames", "(", "res", ")", "{", "return", "typeof", "res", ".", "getHeaderNames", "!==", "'function'", "?", "Object", ".", "keys", "(", "res", ".", "_headers", "||", "{", "}", ")", ":", "res", ".", "getHeaderNames", "(", ")", "}" ]
Get the header names on a respnse. @param {object} res @returns {array[string]} @private
[ "Get", "the", "header", "names", "on", "a", "respnse", "." ]
0ef8f0cb8d8f3875f034d04d16db37a85f6150d8
https://github.com/pillarjs/send/blob/0ef8f0cb8d8f3875f034d04d16db37a85f6150d8/index.js#L1003-L1007
15,659
pillarjs/send
index.js
hasListeners
function hasListeners (emitter, type) { var count = typeof emitter.listenerCount !== 'function' ? emitter.listeners(type).length : emitter.listenerCount(type) return count > 0 }
javascript
function hasListeners (emitter, type) { var count = typeof emitter.listenerCount !== 'function' ? emitter.listeners(type).length : emitter.listenerCount(type) return count > 0 }
[ "function", "hasListeners", "(", "emitter", ",", "type", ")", "{", "var", "count", "=", "typeof", "emitter", ".", "listenerCount", "!==", "'function'", "?", "emitter", ".", "listeners", "(", "type", ")", ".", "length", ":", "emitter", ".", "listenerCount", "(", "type", ")", "return", "count", ">", "0", "}" ]
Determine if emitter has listeners of a given type. The way to do this check is done three different ways in Node.js >= 0.8 so this consolidates them into a minimal set using instance methods. @param {EventEmitter} emitter @param {string} type @returns {boolean} @private
[ "Determine", "if", "emitter", "has", "listeners", "of", "a", "given", "type", "." ]
0ef8f0cb8d8f3875f034d04d16db37a85f6150d8
https://github.com/pillarjs/send/blob/0ef8f0cb8d8f3875f034d04d16db37a85f6150d8/index.js#L1021-L1027
15,660
pillarjs/send
index.js
normalizeList
function normalizeList (val, name) { var list = [].concat(val || []) for (var i = 0; i < list.length; i++) { if (typeof list[i] !== 'string') { throw new TypeError(name + ' must be array of strings or false') } } return list }
javascript
function normalizeList (val, name) { var list = [].concat(val || []) for (var i = 0; i < list.length; i++) { if (typeof list[i] !== 'string') { throw new TypeError(name + ' must be array of strings or false') } } return list }
[ "function", "normalizeList", "(", "val", ",", "name", ")", "{", "var", "list", "=", "[", "]", ".", "concat", "(", "val", "||", "[", "]", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "list", ".", "length", ";", "i", "++", ")", "{", "if", "(", "typeof", "list", "[", "i", "]", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "name", "+", "' must be array of strings or false'", ")", "}", "}", "return", "list", "}" ]
Normalize the index option into an array. @param {boolean|string|array} val @param {string} name @private
[ "Normalize", "the", "index", "option", "into", "an", "array", "." ]
0ef8f0cb8d8f3875f034d04d16db37a85f6150d8
https://github.com/pillarjs/send/blob/0ef8f0cb8d8f3875f034d04d16db37a85f6150d8/index.js#L1051-L1061
15,661
pillarjs/send
index.js
parseTokenList
function parseTokenList (str) { var end = 0 var list = [] var start = 0 // gather tokens for (var i = 0, len = str.length; i < len; i++) { switch (str.charCodeAt(i)) { case 0x20: /* */ if (start === end) { start = end = i + 1 } break case 0x2c: /* , */ list.push(str.substring(start, end)) start = end = i + 1 break default: end = i + 1 break } } // final token list.push(str.substring(start, end)) return list }
javascript
function parseTokenList (str) { var end = 0 var list = [] var start = 0 // gather tokens for (var i = 0, len = str.length; i < len; i++) { switch (str.charCodeAt(i)) { case 0x20: /* */ if (start === end) { start = end = i + 1 } break case 0x2c: /* , */ list.push(str.substring(start, end)) start = end = i + 1 break default: end = i + 1 break } } // final token list.push(str.substring(start, end)) return list }
[ "function", "parseTokenList", "(", "str", ")", "{", "var", "end", "=", "0", "var", "list", "=", "[", "]", "var", "start", "=", "0", "// gather tokens", "for", "(", "var", "i", "=", "0", ",", "len", "=", "str", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "switch", "(", "str", ".", "charCodeAt", "(", "i", ")", ")", "{", "case", "0x20", ":", "/* */", "if", "(", "start", "===", "end", ")", "{", "start", "=", "end", "=", "i", "+", "1", "}", "break", "case", "0x2c", ":", "/* , */", "list", ".", "push", "(", "str", ".", "substring", "(", "start", ",", "end", ")", ")", "start", "=", "end", "=", "i", "+", "1", "break", "default", ":", "end", "=", "i", "+", "1", "break", "}", "}", "// final token", "list", ".", "push", "(", "str", ".", "substring", "(", "start", ",", "end", ")", ")", "return", "list", "}" ]
Parse a HTTP token list. @param {string} str @private
[ "Parse", "a", "HTTP", "token", "list", "." ]
0ef8f0cb8d8f3875f034d04d16db37a85f6150d8
https://github.com/pillarjs/send/blob/0ef8f0cb8d8f3875f034d04d16db37a85f6150d8/index.js#L1085-L1112
15,662
zkat/pacote
lib/finalize-manifest.js
tarballedProps
function tarballedProps (pkg, spec, opts) { const needsShrinkwrap = (!pkg || ( pkg._hasShrinkwrap !== false && !pkg._shrinkwrap )) const needsBin = !!(!pkg || ( !pkg.bin && pkg.directories && pkg.directories.bin )) const needsIntegrity = !pkg || (!pkg._integrity && pkg._integrity !== false) const needsShasum = !pkg || (!pkg._shasum && pkg._shasum !== false) const needsHash = needsIntegrity || needsShasum const needsManifest = !pkg || !pkg.name const needsExtract = needsShrinkwrap || needsBin || needsManifest if (!needsShrinkwrap && !needsBin && !needsHash && !needsManifest) { return BB.resolve({}) } else { opts = optCheck(opts) const tarStream = fetchFromManifest(pkg, spec, opts) const extracted = needsExtract && new tar.Parse() return BB.join( needsShrinkwrap && jsonFromStream('npm-shrinkwrap.json', extracted), needsManifest && jsonFromStream('package.json', extracted), needsBin && getPaths(extracted), needsHash && ssri.fromStream(tarStream, { algorithms: ['sha1', 'sha512'] }), needsExtract && pipe(tarStream, extracted), (sr, mani, paths, hash) => { if (needsManifest && !mani) { const err = new Error(`Non-registry package missing package.json: ${spec}.`) err.code = 'ENOPACKAGEJSON' throw err } const extraProps = mani || {} delete extraProps._resolved // drain out the rest of the tarball tarStream.resume() // if we have directories.bin, we need to collect any matching files // to add to bin if (paths && paths.length) { const dirBin = mani ? (mani && mani.directories && mani.directories.bin) : (pkg && pkg.directories && pkg.directories.bin) if (dirBin) { extraProps.bin = {} paths.forEach(filePath => { if (minimatch(filePath, dirBin + '/**')) { const relative = path.relative(dirBin, filePath) if (relative && relative[0] !== '.') { extraProps.bin[path.basename(relative)] = path.join(dirBin, relative) } } }) } } return Object.assign(extraProps, { _shrinkwrap: sr, _resolved: (mani && mani._resolved) || (pkg && pkg._resolved) || spec.fetchSpec, _integrity: needsIntegrity && hash && hash.sha512 && hash.sha512[0].toString(), _shasum: needsShasum && hash && hash.sha1 && hash.sha1[0].hexDigest() }) } ) } }
javascript
function tarballedProps (pkg, spec, opts) { const needsShrinkwrap = (!pkg || ( pkg._hasShrinkwrap !== false && !pkg._shrinkwrap )) const needsBin = !!(!pkg || ( !pkg.bin && pkg.directories && pkg.directories.bin )) const needsIntegrity = !pkg || (!pkg._integrity && pkg._integrity !== false) const needsShasum = !pkg || (!pkg._shasum && pkg._shasum !== false) const needsHash = needsIntegrity || needsShasum const needsManifest = !pkg || !pkg.name const needsExtract = needsShrinkwrap || needsBin || needsManifest if (!needsShrinkwrap && !needsBin && !needsHash && !needsManifest) { return BB.resolve({}) } else { opts = optCheck(opts) const tarStream = fetchFromManifest(pkg, spec, opts) const extracted = needsExtract && new tar.Parse() return BB.join( needsShrinkwrap && jsonFromStream('npm-shrinkwrap.json', extracted), needsManifest && jsonFromStream('package.json', extracted), needsBin && getPaths(extracted), needsHash && ssri.fromStream(tarStream, { algorithms: ['sha1', 'sha512'] }), needsExtract && pipe(tarStream, extracted), (sr, mani, paths, hash) => { if (needsManifest && !mani) { const err = new Error(`Non-registry package missing package.json: ${spec}.`) err.code = 'ENOPACKAGEJSON' throw err } const extraProps = mani || {} delete extraProps._resolved // drain out the rest of the tarball tarStream.resume() // if we have directories.bin, we need to collect any matching files // to add to bin if (paths && paths.length) { const dirBin = mani ? (mani && mani.directories && mani.directories.bin) : (pkg && pkg.directories && pkg.directories.bin) if (dirBin) { extraProps.bin = {} paths.forEach(filePath => { if (minimatch(filePath, dirBin + '/**')) { const relative = path.relative(dirBin, filePath) if (relative && relative[0] !== '.') { extraProps.bin[path.basename(relative)] = path.join(dirBin, relative) } } }) } } return Object.assign(extraProps, { _shrinkwrap: sr, _resolved: (mani && mani._resolved) || (pkg && pkg._resolved) || spec.fetchSpec, _integrity: needsIntegrity && hash && hash.sha512 && hash.sha512[0].toString(), _shasum: needsShasum && hash && hash.sha1 && hash.sha1[0].hexDigest() }) } ) } }
[ "function", "tarballedProps", "(", "pkg", ",", "spec", ",", "opts", ")", "{", "const", "needsShrinkwrap", "=", "(", "!", "pkg", "||", "(", "pkg", ".", "_hasShrinkwrap", "!==", "false", "&&", "!", "pkg", ".", "_shrinkwrap", ")", ")", "const", "needsBin", "=", "!", "!", "(", "!", "pkg", "||", "(", "!", "pkg", ".", "bin", "&&", "pkg", ".", "directories", "&&", "pkg", ".", "directories", ".", "bin", ")", ")", "const", "needsIntegrity", "=", "!", "pkg", "||", "(", "!", "pkg", ".", "_integrity", "&&", "pkg", ".", "_integrity", "!==", "false", ")", "const", "needsShasum", "=", "!", "pkg", "||", "(", "!", "pkg", ".", "_shasum", "&&", "pkg", ".", "_shasum", "!==", "false", ")", "const", "needsHash", "=", "needsIntegrity", "||", "needsShasum", "const", "needsManifest", "=", "!", "pkg", "||", "!", "pkg", ".", "name", "const", "needsExtract", "=", "needsShrinkwrap", "||", "needsBin", "||", "needsManifest", "if", "(", "!", "needsShrinkwrap", "&&", "!", "needsBin", "&&", "!", "needsHash", "&&", "!", "needsManifest", ")", "{", "return", "BB", ".", "resolve", "(", "{", "}", ")", "}", "else", "{", "opts", "=", "optCheck", "(", "opts", ")", "const", "tarStream", "=", "fetchFromManifest", "(", "pkg", ",", "spec", ",", "opts", ")", "const", "extracted", "=", "needsExtract", "&&", "new", "tar", ".", "Parse", "(", ")", "return", "BB", ".", "join", "(", "needsShrinkwrap", "&&", "jsonFromStream", "(", "'npm-shrinkwrap.json'", ",", "extracted", ")", ",", "needsManifest", "&&", "jsonFromStream", "(", "'package.json'", ",", "extracted", ")", ",", "needsBin", "&&", "getPaths", "(", "extracted", ")", ",", "needsHash", "&&", "ssri", ".", "fromStream", "(", "tarStream", ",", "{", "algorithms", ":", "[", "'sha1'", ",", "'sha512'", "]", "}", ")", ",", "needsExtract", "&&", "pipe", "(", "tarStream", ",", "extracted", ")", ",", "(", "sr", ",", "mani", ",", "paths", ",", "hash", ")", "=>", "{", "if", "(", "needsManifest", "&&", "!", "mani", ")", "{", "const", "err", "=", "new", "Error", "(", "`", "${", "spec", "}", "`", ")", "err", ".", "code", "=", "'ENOPACKAGEJSON'", "throw", "err", "}", "const", "extraProps", "=", "mani", "||", "{", "}", "delete", "extraProps", ".", "_resolved", "// drain out the rest of the tarball", "tarStream", ".", "resume", "(", ")", "// if we have directories.bin, we need to collect any matching files", "// to add to bin", "if", "(", "paths", "&&", "paths", ".", "length", ")", "{", "const", "dirBin", "=", "mani", "?", "(", "mani", "&&", "mani", ".", "directories", "&&", "mani", ".", "directories", ".", "bin", ")", ":", "(", "pkg", "&&", "pkg", ".", "directories", "&&", "pkg", ".", "directories", ".", "bin", ")", "if", "(", "dirBin", ")", "{", "extraProps", ".", "bin", "=", "{", "}", "paths", ".", "forEach", "(", "filePath", "=>", "{", "if", "(", "minimatch", "(", "filePath", ",", "dirBin", "+", "'/**'", ")", ")", "{", "const", "relative", "=", "path", ".", "relative", "(", "dirBin", ",", "filePath", ")", "if", "(", "relative", "&&", "relative", "[", "0", "]", "!==", "'.'", ")", "{", "extraProps", ".", "bin", "[", "path", ".", "basename", "(", "relative", ")", "]", "=", "path", ".", "join", "(", "dirBin", ",", "relative", ")", "}", "}", "}", ")", "}", "}", "return", "Object", ".", "assign", "(", "extraProps", ",", "{", "_shrinkwrap", ":", "sr", ",", "_resolved", ":", "(", "mani", "&&", "mani", ".", "_resolved", ")", "||", "(", "pkg", "&&", "pkg", ".", "_resolved", ")", "||", "spec", ".", "fetchSpec", ",", "_integrity", ":", "needsIntegrity", "&&", "hash", "&&", "hash", ".", "sha512", "&&", "hash", ".", "sha512", "[", "0", "]", ".", "toString", "(", ")", ",", "_shasum", ":", "needsShasum", "&&", "hash", "&&", "hash", ".", "sha1", "&&", "hash", ".", "sha1", "[", "0", "]", ".", "hexDigest", "(", ")", "}", ")", "}", ")", "}", "}" ]
Some things aren't filled in by standard manifest fetching. If this function needs to do its work, it will grab the package tarball, extract it, and take whatever it needs from the stream.
[ "Some", "things", "aren", "t", "filled", "in", "by", "standard", "manifest", "fetching", ".", "If", "this", "function", "needs", "to", "do", "its", "work", "it", "will", "grab", "the", "package", "tarball", "extract", "it", "and", "take", "whatever", "it", "needs", "from", "the", "stream", "." ]
33c53cf10b080e78182bccc56ec1d5126f8b627e
https://github.com/zkat/pacote/blob/33c53cf10b080e78182bccc56ec1d5126f8b627e/lib/finalize-manifest.js#L135-L201
15,663
zkat/pacote
lib/util/read-json.js
stripBOM
function stripBOM (content) { content = content.toString() // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) // because the buffer-to-string conversion in `fs.readFileSync()` // translates it to FEFF, the UTF-16 BOM. if (content.charCodeAt(0) === 0xFEFF) return content.slice(1) return content }
javascript
function stripBOM (content) { content = content.toString() // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) // because the buffer-to-string conversion in `fs.readFileSync()` // translates it to FEFF, the UTF-16 BOM. if (content.charCodeAt(0) === 0xFEFF) return content.slice(1) return content }
[ "function", "stripBOM", "(", "content", ")", "{", "content", "=", "content", ".", "toString", "(", ")", "// Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)", "// because the buffer-to-string conversion in `fs.readFileSync()`", "// translates it to FEFF, the UTF-16 BOM.", "if", "(", "content", ".", "charCodeAt", "(", "0", ")", "===", "0xFEFF", ")", "return", "content", ".", "slice", "(", "1", ")", "return", "content", "}" ]
Code also yanked from read-package-json.
[ "Code", "also", "yanked", "from", "read", "-", "package", "-", "json", "." ]
33c53cf10b080e78182bccc56ec1d5126f8b627e
https://github.com/zkat/pacote/blob/33c53cf10b080e78182bccc56ec1d5126f8b627e/lib/util/read-json.js#L5-L12
15,664
DeviaVir/vue-bar
dist/vue-bars.esm.js
genPoints
function genPoints (inArr, ref, ref$1) { var minX = ref.minX; var minY = ref.minY; var maxX = ref.maxX; var maxY = ref.maxY; var max = ref$1.max; var min = ref$1.min; var arr = inArr.map(function (item) { return (typeof item === 'number' ? item : item.value); }); var minValue = Math.min.apply(Math, arr.concat( [min] )) - 0.001; var gridX = (maxX - minX) / (arr.length - 1); var gridY = (maxY - minY) / (Math.max.apply(Math, arr.concat( [max] )) + 0.001 - minValue); return arr.map(function (value, index) { var title = typeof inArr[index] === 'number' ? inArr[index] : inArr[index].title; return { x: index * gridX + minX, y: maxY - (value - minValue) * gridY + +(index === arr.length - 1) * 0.00001 - +(index === 0) * 0.00001, v: title } }) }
javascript
function genPoints (inArr, ref, ref$1) { var minX = ref.minX; var minY = ref.minY; var maxX = ref.maxX; var maxY = ref.maxY; var max = ref$1.max; var min = ref$1.min; var arr = inArr.map(function (item) { return (typeof item === 'number' ? item : item.value); }); var minValue = Math.min.apply(Math, arr.concat( [min] )) - 0.001; var gridX = (maxX - minX) / (arr.length - 1); var gridY = (maxY - minY) / (Math.max.apply(Math, arr.concat( [max] )) + 0.001 - minValue); return arr.map(function (value, index) { var title = typeof inArr[index] === 'number' ? inArr[index] : inArr[index].title; return { x: index * gridX + minX, y: maxY - (value - minValue) * gridY + +(index === arr.length - 1) * 0.00001 - +(index === 0) * 0.00001, v: title } }) }
[ "function", "genPoints", "(", "inArr", ",", "ref", ",", "ref$1", ")", "{", "var", "minX", "=", "ref", ".", "minX", ";", "var", "minY", "=", "ref", ".", "minY", ";", "var", "maxX", "=", "ref", ".", "maxX", ";", "var", "maxY", "=", "ref", ".", "maxY", ";", "var", "max", "=", "ref$1", ".", "max", ";", "var", "min", "=", "ref$1", ".", "min", ";", "var", "arr", "=", "inArr", ".", "map", "(", "function", "(", "item", ")", "{", "return", "(", "typeof", "item", "===", "'number'", "?", "item", ":", "item", ".", "value", ")", ";", "}", ")", ";", "var", "minValue", "=", "Math", ".", "min", ".", "apply", "(", "Math", ",", "arr", ".", "concat", "(", "[", "min", "]", ")", ")", "-", "0.001", ";", "var", "gridX", "=", "(", "maxX", "-", "minX", ")", "/", "(", "arr", ".", "length", "-", "1", ")", ";", "var", "gridY", "=", "(", "maxY", "-", "minY", ")", "/", "(", "Math", ".", "max", ".", "apply", "(", "Math", ",", "arr", ".", "concat", "(", "[", "max", "]", ")", ")", "+", "0.001", "-", "minValue", ")", ";", "return", "arr", ".", "map", "(", "function", "(", "value", ",", "index", ")", "{", "var", "title", "=", "typeof", "inArr", "[", "index", "]", "===", "'number'", "?", "inArr", "[", "index", "]", ":", "inArr", "[", "index", "]", ".", "title", ";", "return", "{", "x", ":", "index", "*", "gridX", "+", "minX", ",", "y", ":", "maxY", "-", "(", "value", "-", "minValue", ")", "*", "gridY", "+", "+", "(", "index", "===", "arr", ".", "length", "-", "1", ")", "*", "0.00001", "-", "+", "(", "index", "===", "0", ")", "*", "0.00001", ",", "v", ":", "title", "}", "}", ")", "}" ]
Calculate the coordinate @param {number[]|object[]} arr @param {object} boundary @return {object[]}
[ "Calculate", "the", "coordinate" ]
079695b3ba0780e6927fdbaad59927e290e95e21
https://github.com/DeviaVir/vue-bar/blob/079695b3ba0780e6927fdbaad59927e290e95e21/dist/vue-bars.esm.js#L57-L82
15,665
alleyinteractive/sasslint-webpack-plugin
index.js
ignorePlugins
function ignorePlugins(plugins, currentPlugin) { return plugins.reduce(function (acc, plugin) { if (currentPlugin && currentPlugin.indexOf(plugin) > -1) { return true; } return acc; }, false); }
javascript
function ignorePlugins(plugins, currentPlugin) { return plugins.reduce(function (acc, plugin) { if (currentPlugin && currentPlugin.indexOf(plugin) > -1) { return true; } return acc; }, false); }
[ "function", "ignorePlugins", "(", "plugins", ",", "currentPlugin", ")", "{", "return", "plugins", ".", "reduce", "(", "function", "(", "acc", ",", "plugin", ")", "{", "if", "(", "currentPlugin", "&&", "currentPlugin", ".", "indexOf", "(", "plugin", ")", ">", "-", "1", ")", "{", "return", "true", ";", "}", "return", "acc", ";", "}", ",", "false", ")", ";", "}" ]
Check if plugin is ignored
[ "Check", "if", "plugin", "is", "ignored" ]
0f73c610817b89f0f4b2fb025717695fca52f6d7
https://github.com/alleyinteractive/sasslint-webpack-plugin/blob/0f73c610817b89f0f4b2fb025717695fca52f6d7/index.js#L9-L17
15,666
parse-community/parse-server-push-adapter
src/GCM.js
generateGCMPayload
function generateGCMPayload(requestData, pushId, timeStamp, expirationTime) { let payload = { priority: 'high' }; payload.data = { data: requestData.data, push_id: pushId, time: new Date(timeStamp).toISOString() } const optionalKeys = ['content_available', 'notification']; optionalKeys.forEach((key, index, array) => { if (requestData.hasOwnProperty(key)) { payload[key] = requestData[key]; } }); if (expirationTime) { // The timeStamp and expiration is in milliseconds but gcm requires second let timeToLive = Math.floor((expirationTime - timeStamp) / 1000); if (timeToLive < 0) { timeToLive = 0; } if (timeToLive >= GCMTimeToLiveMax) { timeToLive = GCMTimeToLiveMax; } payload.timeToLive = timeToLive; } return payload; }
javascript
function generateGCMPayload(requestData, pushId, timeStamp, expirationTime) { let payload = { priority: 'high' }; payload.data = { data: requestData.data, push_id: pushId, time: new Date(timeStamp).toISOString() } const optionalKeys = ['content_available', 'notification']; optionalKeys.forEach((key, index, array) => { if (requestData.hasOwnProperty(key)) { payload[key] = requestData[key]; } }); if (expirationTime) { // The timeStamp and expiration is in milliseconds but gcm requires second let timeToLive = Math.floor((expirationTime - timeStamp) / 1000); if (timeToLive < 0) { timeToLive = 0; } if (timeToLive >= GCMTimeToLiveMax) { timeToLive = GCMTimeToLiveMax; } payload.timeToLive = timeToLive; } return payload; }
[ "function", "generateGCMPayload", "(", "requestData", ",", "pushId", ",", "timeStamp", ",", "expirationTime", ")", "{", "let", "payload", "=", "{", "priority", ":", "'high'", "}", ";", "payload", ".", "data", "=", "{", "data", ":", "requestData", ".", "data", ",", "push_id", ":", "pushId", ",", "time", ":", "new", "Date", "(", "timeStamp", ")", ".", "toISOString", "(", ")", "}", "const", "optionalKeys", "=", "[", "'content_available'", ",", "'notification'", "]", ";", "optionalKeys", ".", "forEach", "(", "(", "key", ",", "index", ",", "array", ")", "=>", "{", "if", "(", "requestData", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "payload", "[", "key", "]", "=", "requestData", "[", "key", "]", ";", "}", "}", ")", ";", "if", "(", "expirationTime", ")", "{", "// The timeStamp and expiration is in milliseconds but gcm requires second", "let", "timeToLive", "=", "Math", ".", "floor", "(", "(", "expirationTime", "-", "timeStamp", ")", "/", "1000", ")", ";", "if", "(", "timeToLive", "<", "0", ")", "{", "timeToLive", "=", "0", ";", "}", "if", "(", "timeToLive", ">=", "GCMTimeToLiveMax", ")", "{", "timeToLive", "=", "GCMTimeToLiveMax", ";", "}", "payload", ".", "timeToLive", "=", "timeToLive", ";", "}", "return", "payload", ";", "}" ]
Generate the gcm payload from the data we get from api request. @param {Object} requestData The request body @param {String} pushId A random string @param {Number} timeStamp A number whose format is the Unix Epoch @param {Number|undefined} expirationTime A number whose format is the Unix Epoch or undefined @returns {Object} A promise which is resolved after we get results from gcm
[ "Generate", "the", "gcm", "payload", "from", "the", "data", "we", "get", "from", "api", "request", "." ]
30c3e8992c63cf888b43e1a72a10e1da43403844
https://github.com/parse-community/parse-server-push-adapter/blob/30c3e8992c63cf888b43e1a72a10e1da43403844/src/GCM.js#L125-L153
15,667
parse-community/parse-server-push-adapter
src/GCM.js
sliceDevices
function sliceDevices(devices, chunkSize) { let chunkDevices = []; while (devices.length > 0) { chunkDevices.push(devices.splice(0, chunkSize)); } return chunkDevices; }
javascript
function sliceDevices(devices, chunkSize) { let chunkDevices = []; while (devices.length > 0) { chunkDevices.push(devices.splice(0, chunkSize)); } return chunkDevices; }
[ "function", "sliceDevices", "(", "devices", ",", "chunkSize", ")", "{", "let", "chunkDevices", "=", "[", "]", ";", "while", "(", "devices", ".", "length", ">", "0", ")", "{", "chunkDevices", ".", "push", "(", "devices", ".", "splice", "(", "0", ",", "chunkSize", ")", ")", ";", "}", "return", "chunkDevices", ";", "}" ]
Slice a list of devices to several list of devices with fixed chunk size. @param {Array} devices An array of devices @param {Number} chunkSize The size of the a chunk @returns {Array} An array which contaisn several arries of devices with fixed chunk size
[ "Slice", "a", "list", "of", "devices", "to", "several", "list", "of", "devices", "with", "fixed", "chunk", "size", "." ]
30c3e8992c63cf888b43e1a72a10e1da43403844
https://github.com/parse-community/parse-server-push-adapter/blob/30c3e8992c63cf888b43e1a72a10e1da43403844/src/GCM.js#L161-L167
15,668
cliqz-oss/adblocker
bench/run_benchmark.js
runMicroBenchmarks
function runMicroBenchmarks(lists, resources) { console.log('Run micro bench...'); // Create adb engine to use in benchmark const { engine, serialized } = createEngine(lists, resources, { loadCosmeticFilters: true, loadNetworkFilters: true, }, true /* Also serialize engine */); const filters = getFiltersFromLists(lists); const combinedLists = filters.join('\n'); const { networkFilters, cosmeticFilters } = parseFilters(combinedLists); const results = {}; // Arguments shared among benchmarks const args = { lists, resources, engine, filters, serialized, networkFilters, cosmeticFilters, combinedLists, }; [ benchCosmeticsFiltersParsing, benchEngineCreation, benchEngineDeserialization, benchEngineSerialization, benchGetCosmeticTokens, benchGetNetworkTokens, benchNetworkFiltersParsing, benchStringHashing, benchStringTokenize, benchGetCosmeticsFilters, ].forEach((bench) => { if (bench.name.toLowerCase().includes(GREP)) { const suite = new Benchmark.Suite(); suite.add(bench.name, () => bench(args)).on('cycle', (event) => { results[bench.name] = { opsPerSecond: event.target.hz, relativeMarginOfError: event.target.stats.rme, numberOfSamples: event.target.stats.sample.length, }; }).run({ async: false }); } }); return { engineStats: { numFilters: engine.size, numCosmeticFilters: engine.cosmetics.size, numExceptionFilters: engine.exceptions.size, numImportantFilters: engine.importants.size, numRedirectFilters: engine.redirects.size, }, microBenchmarks: results, }; }
javascript
function runMicroBenchmarks(lists, resources) { console.log('Run micro bench...'); // Create adb engine to use in benchmark const { engine, serialized } = createEngine(lists, resources, { loadCosmeticFilters: true, loadNetworkFilters: true, }, true /* Also serialize engine */); const filters = getFiltersFromLists(lists); const combinedLists = filters.join('\n'); const { networkFilters, cosmeticFilters } = parseFilters(combinedLists); const results = {}; // Arguments shared among benchmarks const args = { lists, resources, engine, filters, serialized, networkFilters, cosmeticFilters, combinedLists, }; [ benchCosmeticsFiltersParsing, benchEngineCreation, benchEngineDeserialization, benchEngineSerialization, benchGetCosmeticTokens, benchGetNetworkTokens, benchNetworkFiltersParsing, benchStringHashing, benchStringTokenize, benchGetCosmeticsFilters, ].forEach((bench) => { if (bench.name.toLowerCase().includes(GREP)) { const suite = new Benchmark.Suite(); suite.add(bench.name, () => bench(args)).on('cycle', (event) => { results[bench.name] = { opsPerSecond: event.target.hz, relativeMarginOfError: event.target.stats.rme, numberOfSamples: event.target.stats.sample.length, }; }).run({ async: false }); } }); return { engineStats: { numFilters: engine.size, numCosmeticFilters: engine.cosmetics.size, numExceptionFilters: engine.exceptions.size, numImportantFilters: engine.importants.size, numRedirectFilters: engine.redirects.size, }, microBenchmarks: results, }; }
[ "function", "runMicroBenchmarks", "(", "lists", ",", "resources", ")", "{", "console", ".", "log", "(", "'Run micro bench...'", ")", ";", "// Create adb engine to use in benchmark", "const", "{", "engine", ",", "serialized", "}", "=", "createEngine", "(", "lists", ",", "resources", ",", "{", "loadCosmeticFilters", ":", "true", ",", "loadNetworkFilters", ":", "true", ",", "}", ",", "true", "/* Also serialize engine */", ")", ";", "const", "filters", "=", "getFiltersFromLists", "(", "lists", ")", ";", "const", "combinedLists", "=", "filters", ".", "join", "(", "'\\n'", ")", ";", "const", "{", "networkFilters", ",", "cosmeticFilters", "}", "=", "parseFilters", "(", "combinedLists", ")", ";", "const", "results", "=", "{", "}", ";", "// Arguments shared among benchmarks", "const", "args", "=", "{", "lists", ",", "resources", ",", "engine", ",", "filters", ",", "serialized", ",", "networkFilters", ",", "cosmeticFilters", ",", "combinedLists", ",", "}", ";", "[", "benchCosmeticsFiltersParsing", ",", "benchEngineCreation", ",", "benchEngineDeserialization", ",", "benchEngineSerialization", ",", "benchGetCosmeticTokens", ",", "benchGetNetworkTokens", ",", "benchNetworkFiltersParsing", ",", "benchStringHashing", ",", "benchStringTokenize", ",", "benchGetCosmeticsFilters", ",", "]", ".", "forEach", "(", "(", "bench", ")", "=>", "{", "if", "(", "bench", ".", "name", ".", "toLowerCase", "(", ")", ".", "includes", "(", "GREP", ")", ")", "{", "const", "suite", "=", "new", "Benchmark", ".", "Suite", "(", ")", ";", "suite", ".", "add", "(", "bench", ".", "name", ",", "(", ")", "=>", "bench", "(", "args", ")", ")", ".", "on", "(", "'cycle'", ",", "(", "event", ")", "=>", "{", "results", "[", "bench", ".", "name", "]", "=", "{", "opsPerSecond", ":", "event", ".", "target", ".", "hz", ",", "relativeMarginOfError", ":", "event", ".", "target", ".", "stats", ".", "rme", ",", "numberOfSamples", ":", "event", ".", "target", ".", "stats", ".", "sample", ".", "length", ",", "}", ";", "}", ")", ".", "run", "(", "{", "async", ":", "false", "}", ")", ";", "}", "}", ")", ";", "return", "{", "engineStats", ":", "{", "numFilters", ":", "engine", ".", "size", ",", "numCosmeticFilters", ":", "engine", ".", "cosmetics", ".", "size", ",", "numExceptionFilters", ":", "engine", ".", "exceptions", ".", "size", ",", "numImportantFilters", ":", "engine", ".", "importants", ".", "size", ",", "numRedirectFilters", ":", "engine", ".", "redirects", ".", "size", ",", "}", ",", "microBenchmarks", ":", "results", ",", "}", ";", "}" ]
Micro benchmarks are a set of benchmarks measuring specific aspects of the library
[ "Micro", "benchmarks", "are", "a", "set", "of", "benchmarks", "measuring", "specific", "aspects", "of", "the", "library" ]
fc2af492eefb0a9b251f7ca621b8de59df26ea91
https://github.com/cliqz-oss/adblocker/blob/fc2af492eefb0a9b251f7ca621b8de59df26ea91/bench/run_benchmark.js#L75-L134
15,669
cliqz-oss/adblocker
bench/comparison/blockers/ublock/filtering-context.js
function() { let docDomain = this.getDocDomain(); if ( docDomain === '' ) { docDomain = this.docHostname; } if ( this.domain !== undefined && this.domain !== '' ) { return this.domain !== docDomain; } const hostname = this.getHostname(); if ( hostname.endsWith(docDomain) === false ) { return true; } const i = hostname.length - docDomain.length; if ( i === 0 ) { return false; } return hostname.charCodeAt(i - 1) !== 0x2E /* '.' */; }
javascript
function() { let docDomain = this.getDocDomain(); if ( docDomain === '' ) { docDomain = this.docHostname; } if ( this.domain !== undefined && this.domain !== '' ) { return this.domain !== docDomain; } const hostname = this.getHostname(); if ( hostname.endsWith(docDomain) === false ) { return true; } const i = hostname.length - docDomain.length; if ( i === 0 ) { return false; } return hostname.charCodeAt(i - 1) !== 0x2E /* '.' */; }
[ "function", "(", ")", "{", "let", "docDomain", "=", "this", ".", "getDocDomain", "(", ")", ";", "if", "(", "docDomain", "===", "''", ")", "{", "docDomain", "=", "this", ".", "docHostname", ";", "}", "if", "(", "this", ".", "domain", "!==", "undefined", "&&", "this", ".", "domain", "!==", "''", ")", "{", "return", "this", ".", "domain", "!==", "docDomain", ";", "}", "const", "hostname", "=", "this", ".", "getHostname", "(", ")", ";", "if", "(", "hostname", ".", "endsWith", "(", "docDomain", ")", "===", "false", ")", "{", "return", "true", ";", "}", "const", "i", "=", "hostname", ".", "length", "-", "docDomain", ".", "length", ";", "if", "(", "i", "===", "0", ")", "{", "return", "false", ";", "}", "return", "hostname", ".", "charCodeAt", "(", "i", "-", "1", ")", "!==", "0x2E", "/* '.' */", ";", "}" ]
The idea is to minimize the amout of work done to figure out whether the resource is 3rd-party to the document.
[ "The", "idea", "is", "to", "minimize", "the", "amout", "of", "work", "done", "to", "figure", "out", "whether", "the", "resource", "is", "3rd", "-", "party", "to", "the", "document", "." ]
fc2af492eefb0a9b251f7ca621b8de59df26ea91
https://github.com/cliqz-oss/adblocker/blob/fc2af492eefb0a9b251f7ca621b8de59df26ea91/bench/comparison/blockers/ublock/filtering-context.js#L202-L213
15,670
cliqz-oss/adblocker
bench/comparison/blockers/ublock/filtering-context.js
function() { let tabDomain = this.getTabDomain(); if ( tabDomain === '' ) { tabDomain = this.tabHostname; } if ( this.domain !== undefined && this.domain !== '' ) { return this.domain !== tabDomain; } const hostname = this.getHostname(); if ( hostname.endsWith(tabDomain) === false ) { return true; } const i = hostname.length - tabDomain.length; if ( i === 0 ) { return false; } return hostname.charCodeAt(i - 1) !== 0x2E /* '.' */; }
javascript
function() { let tabDomain = this.getTabDomain(); if ( tabDomain === '' ) { tabDomain = this.tabHostname; } if ( this.domain !== undefined && this.domain !== '' ) { return this.domain !== tabDomain; } const hostname = this.getHostname(); if ( hostname.endsWith(tabDomain) === false ) { return true; } const i = hostname.length - tabDomain.length; if ( i === 0 ) { return false; } return hostname.charCodeAt(i - 1) !== 0x2E /* '.' */; }
[ "function", "(", ")", "{", "let", "tabDomain", "=", "this", ".", "getTabDomain", "(", ")", ";", "if", "(", "tabDomain", "===", "''", ")", "{", "tabDomain", "=", "this", ".", "tabHostname", ";", "}", "if", "(", "this", ".", "domain", "!==", "undefined", "&&", "this", ".", "domain", "!==", "''", ")", "{", "return", "this", ".", "domain", "!==", "tabDomain", ";", "}", "const", "hostname", "=", "this", ".", "getHostname", "(", ")", ";", "if", "(", "hostname", ".", "endsWith", "(", "tabDomain", ")", "===", "false", ")", "{", "return", "true", ";", "}", "const", "i", "=", "hostname", ".", "length", "-", "tabDomain", ".", "length", ";", "if", "(", "i", "===", "0", ")", "{", "return", "false", ";", "}", "return", "hostname", ".", "charCodeAt", "(", "i", "-", "1", ")", "!==", "0x2E", "/* '.' */", ";", "}" ]
The idea is to minimize the amout of work done to figure out whether the resource is 3rd-party to the top document.
[ "The", "idea", "is", "to", "minimize", "the", "amout", "of", "work", "done", "to", "figure", "out", "whether", "the", "resource", "is", "3rd", "-", "party", "to", "the", "top", "document", "." ]
fc2af492eefb0a9b251f7ca621b8de59df26ea91
https://github.com/cliqz-oss/adblocker/blob/fc2af492eefb0a9b251f7ca621b8de59df26ea91/bench/comparison/blockers/ublock/filtering-context.js#L262-L273
15,671
cliqz-oss/adblocker
bench/comparison/blockers/ublock/publicsuffixlist.js
function() { const buf8 = pslBuffer8; const buf32 = pslBuffer32; const iCharData = buf32[CHARDATA_PTR_SLOT]; let iNode = pslBuffer32[RULES_PTR_SLOT]; let cursorPos = -1; let iLabel = LABEL_INDICES_SLOT; // Label-lookup loop for (;;) { // Extract label indices const labelBeg = buf8[iLabel+1]; const labelLen = buf8[iLabel+0] - labelBeg; // Match-lookup loop: binary search let r = buf32[iNode+0] >>> 16; if ( r === 0 ) { break; } const iCandidates = buf32[iNode+2]; let l = 0; let iFound = 0; while ( l < r ) { const iCandidate = l + r >>> 1; const iCandidateNode = iCandidates + iCandidate + (iCandidate << 1); const candidateLen = buf32[iCandidateNode+0] & 0x000000FF; let d = labelLen - candidateLen; if ( d === 0 ) { const iCandidateChar = candidateLen <= 4 ? iCandidateNode + 1 << 2 : iCharData + buf32[iCandidateNode+1]; for ( let i = 0; i < labelLen; i++ ) { d = buf8[labelBeg+i] - buf8[iCandidateChar+i]; if ( d !== 0 ) { break; } } } if ( d < 0 ) { r = iCandidate; } else if ( d > 0 ) { l = iCandidate + 1; } else /* if ( d === 0 ) */ { iFound = iCandidateNode; break; } } // 2. If no rules match, the prevailing rule is "*". if ( iFound === 0 ) { if ( buf8[iCandidates + 1 << 2] !== 0x2A /* '*' */ ) { break; } iFound = iCandidates; } iNode = iFound; // 5. If the prevailing rule is a exception rule, modify it by // removing the leftmost label. if ( (buf32[iNode+0] & 0x00000200) !== 0 ) { if ( iLabel > LABEL_INDICES_SLOT ) { return iLabel - 2; } break; } if ( (buf32[iNode+0] & 0x00000100) !== 0 ) { cursorPos = iLabel; } if ( labelBeg === 0 ) { break; } iLabel += 2; } return cursorPos; }
javascript
function() { const buf8 = pslBuffer8; const buf32 = pslBuffer32; const iCharData = buf32[CHARDATA_PTR_SLOT]; let iNode = pslBuffer32[RULES_PTR_SLOT]; let cursorPos = -1; let iLabel = LABEL_INDICES_SLOT; // Label-lookup loop for (;;) { // Extract label indices const labelBeg = buf8[iLabel+1]; const labelLen = buf8[iLabel+0] - labelBeg; // Match-lookup loop: binary search let r = buf32[iNode+0] >>> 16; if ( r === 0 ) { break; } const iCandidates = buf32[iNode+2]; let l = 0; let iFound = 0; while ( l < r ) { const iCandidate = l + r >>> 1; const iCandidateNode = iCandidates + iCandidate + (iCandidate << 1); const candidateLen = buf32[iCandidateNode+0] & 0x000000FF; let d = labelLen - candidateLen; if ( d === 0 ) { const iCandidateChar = candidateLen <= 4 ? iCandidateNode + 1 << 2 : iCharData + buf32[iCandidateNode+1]; for ( let i = 0; i < labelLen; i++ ) { d = buf8[labelBeg+i] - buf8[iCandidateChar+i]; if ( d !== 0 ) { break; } } } if ( d < 0 ) { r = iCandidate; } else if ( d > 0 ) { l = iCandidate + 1; } else /* if ( d === 0 ) */ { iFound = iCandidateNode; break; } } // 2. If no rules match, the prevailing rule is "*". if ( iFound === 0 ) { if ( buf8[iCandidates + 1 << 2] !== 0x2A /* '*' */ ) { break; } iFound = iCandidates; } iNode = iFound; // 5. If the prevailing rule is a exception rule, modify it by // removing the leftmost label. if ( (buf32[iNode+0] & 0x00000200) !== 0 ) { if ( iLabel > LABEL_INDICES_SLOT ) { return iLabel - 2; } break; } if ( (buf32[iNode+0] & 0x00000100) !== 0 ) { cursorPos = iLabel; } if ( labelBeg === 0 ) { break; } iLabel += 2; } return cursorPos; }
[ "function", "(", ")", "{", "const", "buf8", "=", "pslBuffer8", ";", "const", "buf32", "=", "pslBuffer32", ";", "const", "iCharData", "=", "buf32", "[", "CHARDATA_PTR_SLOT", "]", ";", "let", "iNode", "=", "pslBuffer32", "[", "RULES_PTR_SLOT", "]", ";", "let", "cursorPos", "=", "-", "1", ";", "let", "iLabel", "=", "LABEL_INDICES_SLOT", ";", "// Label-lookup loop", "for", "(", ";", ";", ")", "{", "// Extract label indices", "const", "labelBeg", "=", "buf8", "[", "iLabel", "+", "1", "]", ";", "const", "labelLen", "=", "buf8", "[", "iLabel", "+", "0", "]", "-", "labelBeg", ";", "// Match-lookup loop: binary search", "let", "r", "=", "buf32", "[", "iNode", "+", "0", "]", ">>>", "16", ";", "if", "(", "r", "===", "0", ")", "{", "break", ";", "}", "const", "iCandidates", "=", "buf32", "[", "iNode", "+", "2", "]", ";", "let", "l", "=", "0", ";", "let", "iFound", "=", "0", ";", "while", "(", "l", "<", "r", ")", "{", "const", "iCandidate", "=", "l", "+", "r", ">>>", "1", ";", "const", "iCandidateNode", "=", "iCandidates", "+", "iCandidate", "+", "(", "iCandidate", "<<", "1", ")", ";", "const", "candidateLen", "=", "buf32", "[", "iCandidateNode", "+", "0", "]", "&", "0x000000FF", ";", "let", "d", "=", "labelLen", "-", "candidateLen", ";", "if", "(", "d", "===", "0", ")", "{", "const", "iCandidateChar", "=", "candidateLen", "<=", "4", "?", "iCandidateNode", "+", "1", "<<", "2", ":", "iCharData", "+", "buf32", "[", "iCandidateNode", "+", "1", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "labelLen", ";", "i", "++", ")", "{", "d", "=", "buf8", "[", "labelBeg", "+", "i", "]", "-", "buf8", "[", "iCandidateChar", "+", "i", "]", ";", "if", "(", "d", "!==", "0", ")", "{", "break", ";", "}", "}", "}", "if", "(", "d", "<", "0", ")", "{", "r", "=", "iCandidate", ";", "}", "else", "if", "(", "d", ">", "0", ")", "{", "l", "=", "iCandidate", "+", "1", ";", "}", "else", "/* if ( d === 0 ) */", "{", "iFound", "=", "iCandidateNode", ";", "break", ";", "}", "}", "// 2. If no rules match, the prevailing rule is \"*\".", "if", "(", "iFound", "===", "0", ")", "{", "if", "(", "buf8", "[", "iCandidates", "+", "1", "<<", "2", "]", "!==", "0x2A", "/* '*' */", ")", "{", "break", ";", "}", "iFound", "=", "iCandidates", ";", "}", "iNode", "=", "iFound", ";", "// 5. If the prevailing rule is a exception rule, modify it by", "// removing the leftmost label.", "if", "(", "(", "buf32", "[", "iNode", "+", "0", "]", "&", "0x00000200", ")", "!==", "0", ")", "{", "if", "(", "iLabel", ">", "LABEL_INDICES_SLOT", ")", "{", "return", "iLabel", "-", "2", ";", "}", "break", ";", "}", "if", "(", "(", "buf32", "[", "iNode", "+", "0", "]", "&", "0x00000100", ")", "!==", "0", ")", "{", "cursorPos", "=", "iLabel", ";", "}", "if", "(", "labelBeg", "===", "0", ")", "{", "break", ";", "}", "iLabel", "+=", "2", ";", "}", "return", "cursorPos", ";", "}" ]
Returns an offset to the start of the public suffix. WASM-able, because no information outside the buffer content is required.
[ "Returns", "an", "offset", "to", "the", "start", "of", "the", "public", "suffix", ".", "WASM", "-", "able", "because", "no", "information", "outside", "the", "buffer", "content", "is", "required", "." ]
fc2af492eefb0a9b251f7ca621b8de59df26ea91
https://github.com/cliqz-oss/adblocker/blob/fc2af492eefb0a9b251f7ca621b8de59df26ea91/bench/comparison/blockers/ublock/publicsuffixlist.js#L359-L424
15,672
cliqz-oss/adblocker
bench/comparison/blockers/ublock/tab.js
function(tabId, url) { var entry = tabContexts.get(tabId); if ( entry === undefined ) { entry = new TabContext(tabId); entry.autodestroy(); } entry.push(url); mostRecentRootDocURL = url; mostRecentRootDocURLTimestamp = Date.now(); return entry; }
javascript
function(tabId, url) { var entry = tabContexts.get(tabId); if ( entry === undefined ) { entry = new TabContext(tabId); entry.autodestroy(); } entry.push(url); mostRecentRootDocURL = url; mostRecentRootDocURLTimestamp = Date.now(); return entry; }
[ "function", "(", "tabId", ",", "url", ")", "{", "var", "entry", "=", "tabContexts", ".", "get", "(", "tabId", ")", ";", "if", "(", "entry", "===", "undefined", ")", "{", "entry", "=", "new", "TabContext", "(", "tabId", ")", ";", "entry", ".", "autodestroy", "(", ")", ";", "}", "entry", ".", "push", "(", "url", ")", ";", "mostRecentRootDocURL", "=", "url", ";", "mostRecentRootDocURLTimestamp", "=", "Date", ".", "now", "(", ")", ";", "return", "entry", ";", "}" ]
These are to be used for the API of the tab context manager.
[ "These", "are", "to", "be", "used", "for", "the", "API", "of", "the", "tab", "context", "manager", "." ]
fc2af492eefb0a9b251f7ca621b8de59df26ea91
https://github.com/cliqz-oss/adblocker/blob/fc2af492eefb0a9b251f7ca621b8de59df26ea91/bench/comparison/blockers/ublock/tab.js#L376-L386
15,673
cliqz-oss/adblocker
bench/comparison/blockers/ublock/tab.js
function(tabId) { var entry = tabContexts.get(tabId); if ( entry !== undefined ) { return entry; } // https://github.com/chrisaljoudi/uBlock/issues/1025 // Google Hangout popup opens without a root frame. So for now we will // just discard that best-guess root frame if it is too far in the // future, at which point it ceases to be a "best guess". if ( mostRecentRootDocURL !== '' && mostRecentRootDocURLTimestamp + 500 < Date.now() ) { mostRecentRootDocURL = ''; } // https://github.com/chrisaljoudi/uBlock/issues/1001 // Not a behind-the-scene request, yet no page store found for the // tab id: we will thus bind the last-seen root document to the // unbound tab. It's a guess, but better than ending up filtering // nothing at all. if ( mostRecentRootDocURL !== '' ) { return push(tabId, mostRecentRootDocURL); } // If all else fail at finding a page store, re-categorize the // request as behind-the-scene. At least this ensures that ultimately // the user can still inspect/filter those net requests which were // about to fall through the cracks. // Example: Chromium + case #12 at // http://raymondhill.net/ublock/popup.html return tabContexts.get(vAPI.noTabId); }
javascript
function(tabId) { var entry = tabContexts.get(tabId); if ( entry !== undefined ) { return entry; } // https://github.com/chrisaljoudi/uBlock/issues/1025 // Google Hangout popup opens without a root frame. So for now we will // just discard that best-guess root frame if it is too far in the // future, at which point it ceases to be a "best guess". if ( mostRecentRootDocURL !== '' && mostRecentRootDocURLTimestamp + 500 < Date.now() ) { mostRecentRootDocURL = ''; } // https://github.com/chrisaljoudi/uBlock/issues/1001 // Not a behind-the-scene request, yet no page store found for the // tab id: we will thus bind the last-seen root document to the // unbound tab. It's a guess, but better than ending up filtering // nothing at all. if ( mostRecentRootDocURL !== '' ) { return push(tabId, mostRecentRootDocURL); } // If all else fail at finding a page store, re-categorize the // request as behind-the-scene. At least this ensures that ultimately // the user can still inspect/filter those net requests which were // about to fall through the cracks. // Example: Chromium + case #12 at // http://raymondhill.net/ublock/popup.html return tabContexts.get(vAPI.noTabId); }
[ "function", "(", "tabId", ")", "{", "var", "entry", "=", "tabContexts", ".", "get", "(", "tabId", ")", ";", "if", "(", "entry", "!==", "undefined", ")", "{", "return", "entry", ";", "}", "// https://github.com/chrisaljoudi/uBlock/issues/1025", "// Google Hangout popup opens without a root frame. So for now we will", "// just discard that best-guess root frame if it is too far in the", "// future, at which point it ceases to be a \"best guess\".", "if", "(", "mostRecentRootDocURL", "!==", "''", "&&", "mostRecentRootDocURLTimestamp", "+", "500", "<", "Date", ".", "now", "(", ")", ")", "{", "mostRecentRootDocURL", "=", "''", ";", "}", "// https://github.com/chrisaljoudi/uBlock/issues/1001", "// Not a behind-the-scene request, yet no page store found for the", "// tab id: we will thus bind the last-seen root document to the", "// unbound tab. It's a guess, but better than ending up filtering", "// nothing at all.", "if", "(", "mostRecentRootDocURL", "!==", "''", ")", "{", "return", "push", "(", "tabId", ",", "mostRecentRootDocURL", ")", ";", "}", "// If all else fail at finding a page store, re-categorize the", "// request as behind-the-scene. At least this ensures that ultimately", "// the user can still inspect/filter those net requests which were", "// about to fall through the cracks.", "// Example: Chromium + case #12 at", "// http://raymondhill.net/ublock/popup.html", "return", "tabContexts", ".", "get", "(", "vAPI", ".", "noTabId", ")", ";", "}" ]
Find a tab context for a specific tab. If none is found, attempt to fix this. When all fail, the behind-the-scene context is returned.
[ "Find", "a", "tab", "context", "for", "a", "specific", "tab", ".", "If", "none", "is", "found", "attempt", "to", "fix", "this", ".", "When", "all", "fail", "the", "behind", "-", "the", "-", "scene", "context", "is", "returned", "." ]
fc2af492eefb0a9b251f7ca621b8de59df26ea91
https://github.com/cliqz-oss/adblocker/blob/fc2af492eefb0a9b251f7ca621b8de59df26ea91/bench/comparison/blockers/ublock/tab.js#L395-L422
15,674
cliqz-oss/adblocker
bench/comparison/blockers/ublock/static-ext-filtering.js
function(s) { const match = reParseRegexLiteral.exec(s); let regexDetails; if ( match !== null ) { regexDetails = match[1]; if ( isBadRegex(regexDetails) ) { return; } if ( match[2] ) { regexDetails = [ regexDetails, match[2] ]; } } else { regexDetails = s.replace(reEatBackslashes, '$1') .replace(reEscapeRegex, '\\$&'); regexToRawValue.set(regexDetails, s); } return regexDetails; }
javascript
function(s) { const match = reParseRegexLiteral.exec(s); let regexDetails; if ( match !== null ) { regexDetails = match[1]; if ( isBadRegex(regexDetails) ) { return; } if ( match[2] ) { regexDetails = [ regexDetails, match[2] ]; } } else { regexDetails = s.replace(reEatBackslashes, '$1') .replace(reEscapeRegex, '\\$&'); regexToRawValue.set(regexDetails, s); } return regexDetails; }
[ "function", "(", "s", ")", "{", "const", "match", "=", "reParseRegexLiteral", ".", "exec", "(", "s", ")", ";", "let", "regexDetails", ";", "if", "(", "match", "!==", "null", ")", "{", "regexDetails", "=", "match", "[", "1", "]", ";", "if", "(", "isBadRegex", "(", "regexDetails", ")", ")", "{", "return", ";", "}", "if", "(", "match", "[", "2", "]", ")", "{", "regexDetails", "=", "[", "regexDetails", ",", "match", "[", "2", "]", "]", ";", "}", "}", "else", "{", "regexDetails", "=", "s", ".", "replace", "(", "reEatBackslashes", ",", "'$1'", ")", ".", "replace", "(", "reEscapeRegex", ",", "'\\\\$&'", ")", ";", "regexToRawValue", ".", "set", "(", "regexDetails", ",", "s", ")", ";", "}", "return", "regexDetails", ";", "}" ]
When dealing with literal text, we must first eat _some_ backslash characters.
[ "When", "dealing", "with", "literal", "text", "we", "must", "first", "eat", "_some_", "backslash", "characters", "." ]
fc2af492eefb0a9b251f7ca621b8de59df26ea91
https://github.com/cliqz-oss/adblocker/blob/fc2af492eefb0a9b251f7ca621b8de59df26ea91/bench/comparison/blockers/ublock/static-ext-filtering.js#L187-L202
15,675
dthree/vantage
lib/index.js
function(server, port, options, cb) { return this.client.connect.call(this.client, server, port, options, cb); }
javascript
function(server, port, options, cb) { return this.client.connect.call(this.client, server, port, options, cb); }
[ "function", "(", "server", ",", "port", ",", "options", ",", "cb", ")", "{", "return", "this", ".", "client", ".", "connect", ".", "call", "(", "this", ".", "client", ",", "server", ",", "port", ",", "options", ",", "cb", ")", ";", "}" ]
Programatically connect to another server instance running Vantage. @param {Server} server @param {Integer} port @param {Object} options @param {Function} cb @return {Promise} @api public
[ "Programatically", "connect", "to", "another", "server", "instance", "running", "Vantage", "." ]
5bbf7e58a94d34d8ce980ae7048dfff3e9569c31
https://github.com/dthree/vantage/blob/5bbf7e58a94d34d8ce980ae7048dfff3e9569c31/lib/index.js#L71-L73
15,676
dthree/vantage
lib/index.js
function(middleware, options) { if (this.server && this.server.auth) { this.server.auth(middleware, options); } else { throw new Error("vantage.auth is only available in Vantage.IO. Please use this (npm install vantage-io --save)"); } return this; }
javascript
function(middleware, options) { if (this.server && this.server.auth) { this.server.auth(middleware, options); } else { throw new Error("vantage.auth is only available in Vantage.IO. Please use this (npm install vantage-io --save)"); } return this; }
[ "function", "(", "middleware", ",", "options", ")", "{", "if", "(", "this", ".", "server", "&&", "this", ".", "server", ".", "auth", ")", "{", "this", ".", "server", ".", "auth", "(", "middleware", ",", "options", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"vantage.auth is only available in Vantage.IO. Please use this (npm install vantage-io --save)\"", ")", ";", "}", "return", "this", ";", "}" ]
Imports an authentication middleware module to replace the server's auth function, which is called when a remote instance of vantage connects. @param {Function} middleware @param {Object} options @return {Vantage} @api public
[ "Imports", "an", "authentication", "middleware", "module", "to", "replace", "the", "server", "s", "auth", "function", "which", "is", "called", "when", "a", "remote", "instance", "of", "vantage", "connects", "." ]
5bbf7e58a94d34d8ce980ae7048dfff3e9569c31
https://github.com/dthree/vantage/blob/5bbf7e58a94d34d8ce980ae7048dfff3e9569c31/lib/index.js#L100-L107
15,677
dthree/vantage
lib/index.js
function(args, cb) { var ssn = this.getSessionById(args.sessionId); if (!this._authFn) { var nodeEnv = process.env.NODE_ENV || "development"; if (nodeEnv !== "development") { var msg = "The Node server you are connecting to appears " + "to be a production server, and yet its Vantage.js " + "instance does not support any means of authentication. \n" + "To connect to this server without authentication, " + "ensure its 'NODE_ENV' environmental variable is set " + "to 'development' (it is currently '" + nodeEnv + "')."; ssn.log(chalk.yellow(msg)); ssn.authenticating = false; ssn.authenticated = false; cb(msg, false); } else { ssn.authenticating = false; ssn.authenticated = true; cb(void 0, true); } } else { this._authFn.call(ssn, args, function(message, authenticated) { ssn.authenticating = false; ssn.authenticated = authenticated; if (authenticated === true) { cb(void 0, true); } else { cb(message); } }); } }
javascript
function(args, cb) { var ssn = this.getSessionById(args.sessionId); if (!this._authFn) { var nodeEnv = process.env.NODE_ENV || "development"; if (nodeEnv !== "development") { var msg = "The Node server you are connecting to appears " + "to be a production server, and yet its Vantage.js " + "instance does not support any means of authentication. \n" + "To connect to this server without authentication, " + "ensure its 'NODE_ENV' environmental variable is set " + "to 'development' (it is currently '" + nodeEnv + "')."; ssn.log(chalk.yellow(msg)); ssn.authenticating = false; ssn.authenticated = false; cb(msg, false); } else { ssn.authenticating = false; ssn.authenticated = true; cb(void 0, true); } } else { this._authFn.call(ssn, args, function(message, authenticated) { ssn.authenticating = false; ssn.authenticated = authenticated; if (authenticated === true) { cb(void 0, true); } else { cb(message); } }); } }
[ "function", "(", "args", ",", "cb", ")", "{", "var", "ssn", "=", "this", ".", "getSessionById", "(", "args", ".", "sessionId", ")", ";", "if", "(", "!", "this", ".", "_authFn", ")", "{", "var", "nodeEnv", "=", "process", ".", "env", ".", "NODE_ENV", "||", "\"development\"", ";", "if", "(", "nodeEnv", "!==", "\"development\"", ")", "{", "var", "msg", "=", "\"The Node server you are connecting to appears \"", "+", "\"to be a production server, and yet its Vantage.js \"", "+", "\"instance does not support any means of authentication. \\n\"", "+", "\"To connect to this server without authentication, \"", "+", "\"ensure its 'NODE_ENV' environmental variable is set \"", "+", "\"to 'development' (it is currently '\"", "+", "nodeEnv", "+", "\"').\"", ";", "ssn", ".", "log", "(", "chalk", ".", "yellow", "(", "msg", ")", ")", ";", "ssn", ".", "authenticating", "=", "false", ";", "ssn", ".", "authenticated", "=", "false", ";", "cb", "(", "msg", ",", "false", ")", ";", "}", "else", "{", "ssn", ".", "authenticating", "=", "false", ";", "ssn", ".", "authenticated", "=", "true", ";", "cb", "(", "void", "0", ",", "true", ")", ";", "}", "}", "else", "{", "this", ".", "_authFn", ".", "call", "(", "ssn", ",", "args", ",", "function", "(", "message", ",", "authenticated", ")", "{", "ssn", ".", "authenticating", "=", "false", ";", "ssn", ".", "authenticated", "=", "authenticated", ";", "if", "(", "authenticated", "===", "true", ")", "{", "cb", "(", "void", "0", ",", "true", ")", ";", "}", "else", "{", "cb", "(", "message", ")", ";", "}", "}", ")", ";", "}", "}" ]
Calls authentication middleware @param {Object} args @param {Function} cb @api private
[ "Calls", "authentication", "middleware" ]
5bbf7e58a94d34d8ce980ae7048dfff3e9569c31
https://github.com/dthree/vantage/blob/5bbf7e58a94d34d8ce980ae7048dfff3e9569c31/lib/index.js#L117-L148
15,678
dthree/vantage
lib/server.js
on
function on(str, opts, cbk) { cbk = (_.isFunction(opts)) ? opts : cbk; cbk = cbk || function() {}; opts = opts || {}; ssn.server.on(str, function() { if (!ssn.server || (!ssn.authenticating && !ssn.authenticated)) { //console.log("Not Authenticated. Closing Session.", ssn.authenticating, ssn.authenticated); self.parent._send("vantage-close-downstream", "downstream", { sessionId: ssn.id }); return; } cbk.apply(self, arguments); }); }
javascript
function on(str, opts, cbk) { cbk = (_.isFunction(opts)) ? opts : cbk; cbk = cbk || function() {}; opts = opts || {}; ssn.server.on(str, function() { if (!ssn.server || (!ssn.authenticating && !ssn.authenticated)) { //console.log("Not Authenticated. Closing Session.", ssn.authenticating, ssn.authenticated); self.parent._send("vantage-close-downstream", "downstream", { sessionId: ssn.id }); return; } cbk.apply(self, arguments); }); }
[ "function", "on", "(", "str", ",", "opts", ",", "cbk", ")", "{", "cbk", "=", "(", "_", ".", "isFunction", "(", "opts", ")", ")", "?", "opts", ":", "cbk", ";", "cbk", "=", "cbk", "||", "function", "(", ")", "{", "}", ";", "opts", "=", "opts", "||", "{", "}", ";", "ssn", ".", "server", ".", "on", "(", "str", ",", "function", "(", ")", "{", "if", "(", "!", "ssn", ".", "server", "||", "(", "!", "ssn", ".", "authenticating", "&&", "!", "ssn", ".", "authenticated", ")", ")", "{", "//console.log(\"Not Authenticated. Closing Session.\", ssn.authenticating, ssn.authenticated);\r", "self", ".", "parent", ".", "_send", "(", "\"vantage-close-downstream\"", ",", "\"downstream\"", ",", "{", "sessionId", ":", "ssn", ".", "id", "}", ")", ";", "return", ";", "}", "cbk", ".", "apply", "(", "self", ",", "arguments", ")", ";", "}", ")", ";", "}" ]
Listens for an event, authenticating the session first.
[ "Listens", "for", "an", "event", "authenticating", "the", "session", "first", "." ]
5bbf7e58a94d34d8ce980ae7048dfff3e9569c31
https://github.com/dthree/vantage/blob/5bbf7e58a94d34d8ce980ae7048dfff3e9569c31/lib/server.js#L213-L225
15,679
infusion/Fraction.js
examples/hesse-convergence.js
matrMult
function matrMult(m, v) { return [ new Fraction(m[0]).mul(v[0]).add(new Fraction(m[1]).mul(v[1])), new Fraction(m[2]).mul(v[0]).add(new Fraction(m[3]).mul(v[1])) ]; }
javascript
function matrMult(m, v) { return [ new Fraction(m[0]).mul(v[0]).add(new Fraction(m[1]).mul(v[1])), new Fraction(m[2]).mul(v[0]).add(new Fraction(m[3]).mul(v[1])) ]; }
[ "function", "matrMult", "(", "m", ",", "v", ")", "{", "return", "[", "new", "Fraction", "(", "m", "[", "0", "]", ")", ".", "mul", "(", "v", "[", "0", "]", ")", ".", "add", "(", "new", "Fraction", "(", "m", "[", "1", "]", ")", ".", "mul", "(", "v", "[", "1", "]", ")", ")", ",", "new", "Fraction", "(", "m", "[", "2", "]", ")", ".", "mul", "(", "v", "[", "0", "]", ")", ".", "add", "(", "new", "Fraction", "(", "m", "[", "3", "]", ")", ".", "mul", "(", "v", "[", "1", "]", ")", ")", "]", ";", "}" ]
A simple matrix multiplication helper
[ "A", "simple", "matrix", "multiplication", "helper" ]
0298e604eb28a7cf8fba3240e6aa639fbc5c4432
https://github.com/infusion/Fraction.js/blob/0298e604eb28a7cf8fba3240e6aa639fbc5c4432/examples/hesse-convergence.js#L54-L60
15,680
infusion/Fraction.js
examples/hesse-convergence.js
vecSub
function vecSub(a, b) { return [ new Fraction(a[0]).sub(b[0]), new Fraction(a[1]).sub(b[1]) ]; }
javascript
function vecSub(a, b) { return [ new Fraction(a[0]).sub(b[0]), new Fraction(a[1]).sub(b[1]) ]; }
[ "function", "vecSub", "(", "a", ",", "b", ")", "{", "return", "[", "new", "Fraction", "(", "a", "[", "0", "]", ")", ".", "sub", "(", "b", "[", "0", "]", ")", ",", "new", "Fraction", "(", "a", "[", "1", "]", ")", ".", "sub", "(", "b", "[", "1", "]", ")", "]", ";", "}" ]
A simple vector subtraction helper
[ "A", "simple", "vector", "subtraction", "helper" ]
0298e604eb28a7cf8fba3240e6aa639fbc5c4432
https://github.com/infusion/Fraction.js/blob/0298e604eb28a7cf8fba3240e6aa639fbc5c4432/examples/hesse-convergence.js#L63-L69
15,681
infusion/Fraction.js
examples/hesse-convergence.js
run
function run(V, j) { var t = H(V); //console.log("H(X)"); for (var i in t) { // console.log(t[i].toFraction()); } var s = grad(V); //console.log("vf(X)"); for (var i in s) { // console.log(s[i].toFraction()); } //console.log("multiplikation"); var r = matrMult(t, s); for (var i in r) { // console.log(r[i].toFraction()); } var R = (vecSub(V, r)); console.log("X"+j); console.log(R[0].toFraction(), "= "+R[0].valueOf()); console.log(R[1].toFraction(), "= "+R[1].valueOf()); console.log("\n"); return R; }
javascript
function run(V, j) { var t = H(V); //console.log("H(X)"); for (var i in t) { // console.log(t[i].toFraction()); } var s = grad(V); //console.log("vf(X)"); for (var i in s) { // console.log(s[i].toFraction()); } //console.log("multiplikation"); var r = matrMult(t, s); for (var i in r) { // console.log(r[i].toFraction()); } var R = (vecSub(V, r)); console.log("X"+j); console.log(R[0].toFraction(), "= "+R[0].valueOf()); console.log(R[1].toFraction(), "= "+R[1].valueOf()); console.log("\n"); return R; }
[ "function", "run", "(", "V", ",", "j", ")", "{", "var", "t", "=", "H", "(", "V", ")", ";", "//console.log(\"H(X)\");", "for", "(", "var", "i", "in", "t", ")", "{", "//\tconsole.log(t[i].toFraction());", "}", "var", "s", "=", "grad", "(", "V", ")", ";", "//console.log(\"vf(X)\");", "for", "(", "var", "i", "in", "s", ")", "{", "//\tconsole.log(s[i].toFraction());", "}", "//console.log(\"multiplikation\");", "var", "r", "=", "matrMult", "(", "t", ",", "s", ")", ";", "for", "(", "var", "i", "in", "r", ")", "{", "//\tconsole.log(r[i].toFraction());", "}", "var", "R", "=", "(", "vecSub", "(", "V", ",", "r", ")", ")", ";", "console", ".", "log", "(", "\"X\"", "+", "j", ")", ";", "console", ".", "log", "(", "R", "[", "0", "]", ".", "toFraction", "(", ")", ",", "\"= \"", "+", "R", "[", "0", "]", ".", "valueOf", "(", ")", ")", ";", "console", ".", "log", "(", "R", "[", "1", "]", ".", "toFraction", "(", ")", ",", "\"= \"", "+", "R", "[", "1", "]", ".", "valueOf", "(", ")", ")", ";", "console", ".", "log", "(", "\"\\n\"", ")", ";", "return", "R", ";", "}" ]
Main function, gets a vector and the actual index
[ "Main", "function", "gets", "a", "vector", "and", "the", "actual", "index" ]
0298e604eb28a7cf8fba3240e6aa639fbc5c4432
https://github.com/infusion/Fraction.js/blob/0298e604eb28a7cf8fba3240e6aa639fbc5c4432/examples/hesse-convergence.js#L72-L103
15,682
infusion/Fraction.js
bigfraction.js
function(a, b) { parse(a, b); return new Fraction( this["s"] * this["n"] * P["d"] + P["s"] * this["d"] * P["n"], this["d"] * P["d"] ); }
javascript
function(a, b) { parse(a, b); return new Fraction( this["s"] * this["n"] * P["d"] + P["s"] * this["d"] * P["n"], this["d"] * P["d"] ); }
[ "function", "(", "a", ",", "b", ")", "{", "parse", "(", "a", ",", "b", ")", ";", "return", "new", "Fraction", "(", "this", "[", "\"s\"", "]", "*", "this", "[", "\"n\"", "]", "*", "P", "[", "\"d\"", "]", "+", "P", "[", "\"s\"", "]", "*", "this", "[", "\"d\"", "]", "*", "P", "[", "\"n\"", "]", ",", "this", "[", "\"d\"", "]", "*", "P", "[", "\"d\"", "]", ")", ";", "}" ]
Adds two rational numbers Ex: new Fraction({n: 2, d: 3}).add("14.9") => 467 / 30
[ "Adds", "two", "rational", "numbers" ]
0298e604eb28a7cf8fba3240e6aa639fbc5c4432
https://github.com/infusion/Fraction.js/blob/0298e604eb28a7cf8fba3240e6aa639fbc5c4432/bigfraction.js#L400-L407
15,683
infusion/Fraction.js
fraction.js
function(a, b) { if (isNaN(this['n']) || isNaN(this['d'])) { return new Fraction(NaN); } if (a === undefined) { return new Fraction(this["s"] * this["n"] % this["d"], 1); } parse(a, b); if (0 === P["n"] && 0 === this["d"]) { Fraction(0, 0); // Throw DivisionByZero } /* * First silly attempt, kinda slow * return that["sub"]({ "n": num["n"] * Math.floor((this.n / this.d) / (num.n / num.d)), "d": num["d"], "s": this["s"] });*/ /* * New attempt: a1 / b1 = a2 / b2 * q + r * => b2 * a1 = a2 * b1 * q + b1 * b2 * r * => (b2 * a1 % a2 * b1) / (b1 * b2) */ return new Fraction( this["s"] * (P["d"] * this["n"]) % (P["n"] * this["d"]), P["d"] * this["d"] ); }
javascript
function(a, b) { if (isNaN(this['n']) || isNaN(this['d'])) { return new Fraction(NaN); } if (a === undefined) { return new Fraction(this["s"] * this["n"] % this["d"], 1); } parse(a, b); if (0 === P["n"] && 0 === this["d"]) { Fraction(0, 0); // Throw DivisionByZero } /* * First silly attempt, kinda slow * return that["sub"]({ "n": num["n"] * Math.floor((this.n / this.d) / (num.n / num.d)), "d": num["d"], "s": this["s"] });*/ /* * New attempt: a1 / b1 = a2 / b2 * q + r * => b2 * a1 = a2 * b1 * q + b1 * b2 * r * => (b2 * a1 % a2 * b1) / (b1 * b2) */ return new Fraction( this["s"] * (P["d"] * this["n"]) % (P["n"] * this["d"]), P["d"] * this["d"] ); }
[ "function", "(", "a", ",", "b", ")", "{", "if", "(", "isNaN", "(", "this", "[", "'n'", "]", ")", "||", "isNaN", "(", "this", "[", "'d'", "]", ")", ")", "{", "return", "new", "Fraction", "(", "NaN", ")", ";", "}", "if", "(", "a", "===", "undefined", ")", "{", "return", "new", "Fraction", "(", "this", "[", "\"s\"", "]", "*", "this", "[", "\"n\"", "]", "%", "this", "[", "\"d\"", "]", ",", "1", ")", ";", "}", "parse", "(", "a", ",", "b", ")", ";", "if", "(", "0", "===", "P", "[", "\"n\"", "]", "&&", "0", "===", "this", "[", "\"d\"", "]", ")", "{", "Fraction", "(", "0", ",", "0", ")", ";", "// Throw DivisionByZero", "}", "/*\n * First silly attempt, kinda slow\n *\n return that[\"sub\"]({\n \"n\": num[\"n\"] * Math.floor((this.n / this.d) / (num.n / num.d)),\n \"d\": num[\"d\"],\n \"s\": this[\"s\"]\n });*/", "/*\n * New attempt: a1 / b1 = a2 / b2 * q + r\n * => b2 * a1 = a2 * b1 * q + b1 * b2 * r\n * => (b2 * a1 % a2 * b1) / (b1 * b2)\n */", "return", "new", "Fraction", "(", "this", "[", "\"s\"", "]", "*", "(", "P", "[", "\"d\"", "]", "*", "this", "[", "\"n\"", "]", ")", "%", "(", "P", "[", "\"n\"", "]", "*", "this", "[", "\"d\"", "]", ")", ",", "P", "[", "\"d\"", "]", "*", "this", "[", "\"d\"", "]", ")", ";", "}" ]
Calculates the modulo of two rational numbers - a more precise fmod Ex: new Fraction('4.(3)').mod([7, 8]) => (13/3) % (7/8) = (5/6)
[ "Calculates", "the", "modulo", "of", "two", "rational", "numbers", "-", "a", "more", "precise", "fmod" ]
0298e604eb28a7cf8fba3240e6aa639fbc5c4432
https://github.com/infusion/Fraction.js/blob/0298e604eb28a7cf8fba3240e6aa639fbc5c4432/fraction.js#L465-L498
15,684
infusion/Fraction.js
fraction.js
function(a, b) { parse(a, b); var t = (this["s"] * this["n"] * P["d"] - P["s"] * P["n"] * this["d"]); return (0 < t) - (t < 0); }
javascript
function(a, b) { parse(a, b); var t = (this["s"] * this["n"] * P["d"] - P["s"] * P["n"] * this["d"]); return (0 < t) - (t < 0); }
[ "function", "(", "a", ",", "b", ")", "{", "parse", "(", "a", ",", "b", ")", ";", "var", "t", "=", "(", "this", "[", "\"s\"", "]", "*", "this", "[", "\"n\"", "]", "*", "P", "[", "\"d\"", "]", "-", "P", "[", "\"s\"", "]", "*", "P", "[", "\"n\"", "]", "*", "this", "[", "\"d\"", "]", ")", ";", "return", "(", "0", "<", "t", ")", "-", "(", "t", "<", "0", ")", ";", "}" ]
Check if two rational numbers are the same Ex: new Fraction(19.6).equals([98, 5]);
[ "Check", "if", "two", "rational", "numbers", "are", "the", "same" ]
0298e604eb28a7cf8fba3240e6aa639fbc5c4432
https://github.com/infusion/Fraction.js/blob/0298e604eb28a7cf8fba3240e6aa639fbc5c4432/fraction.js#L616-L621
15,685
skale-me/skale
ml/sgd-linear-model.js
regularizeNone
function regularizeNone(weights, gradientCount) { const [gradient, count] = gradientCount; for (let i = 0; i < gradient.length; i++) { let grad = (gradient[i] || 0) / count; weights[i] = (weights[i] || 0) - grad; } }
javascript
function regularizeNone(weights, gradientCount) { const [gradient, count] = gradientCount; for (let i = 0; i < gradient.length; i++) { let grad = (gradient[i] || 0) / count; weights[i] = (weights[i] || 0) - grad; } }
[ "function", "regularizeNone", "(", "weights", ",", "gradientCount", ")", "{", "const", "[", "gradient", ",", "count", "]", "=", "gradientCount", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "gradient", ".", "length", ";", "i", "++", ")", "{", "let", "grad", "=", "(", "gradient", "[", "i", "]", "||", "0", ")", "/", "count", ";", "weights", "[", "i", "]", "=", "(", "weights", "[", "i", "]", "||", "0", ")", "-", "grad", ";", "}", "}" ]
None, a.k.a ordinary least squares
[ "None", "a", ".", "k", ".", "a", "ordinary", "least", "squares" ]
fdb4b5d08ca4f6321ceda888385a68208d04a545
https://github.com/skale-me/skale/blob/fdb4b5d08ca4f6321ceda888385a68208d04a545/ml/sgd-linear-model.js#L91-L98
15,686
skale-me/skale
ml/sgd-linear-model.js
regularizeL1
function regularizeL1(weights, gradientCount, stepSize) { const [gradient, count] = gradientCount; for (let i = 0; i < gradient.length; i++) { let grad = (gradient[i] || 0) / count; weights[i] = weights[i] || 0; weights[i] -= stepSize * grad + (weights[i] > 0 ? 1 : -1); } }
javascript
function regularizeL1(weights, gradientCount, stepSize) { const [gradient, count] = gradientCount; for (let i = 0; i < gradient.length; i++) { let grad = (gradient[i] || 0) / count; weights[i] = weights[i] || 0; weights[i] -= stepSize * grad + (weights[i] > 0 ? 1 : -1); } }
[ "function", "regularizeL1", "(", "weights", ",", "gradientCount", ",", "stepSize", ")", "{", "const", "[", "gradient", ",", "count", "]", "=", "gradientCount", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "gradient", ".", "length", ";", "i", "++", ")", "{", "let", "grad", "=", "(", "gradient", "[", "i", "]", "||", "0", ")", "/", "count", ";", "weights", "[", "i", "]", "=", "weights", "[", "i", "]", "||", "0", ";", "weights", "[", "i", "]", "-=", "stepSize", "*", "grad", "+", "(", "weights", "[", "i", "]", ">", "0", "?", "1", ":", "-", "1", ")", ";", "}", "}" ]
L1, a.k.a Lasso
[ "L1", "a", ".", "k", ".", "a", "Lasso" ]
fdb4b5d08ca4f6321ceda888385a68208d04a545
https://github.com/skale-me/skale/blob/fdb4b5d08ca4f6321ceda888385a68208d04a545/ml/sgd-linear-model.js#L101-L109
15,687
skale-me/skale
ml/sgd-linear-model.js
regularizeL2
function regularizeL2(weights, gradientCount, stepSize, regParam) { const [gradient, count] = gradientCount; for (let i = 0; i < gradient.length; i++) { let grad = (gradient[i] || 0) / count; weights[i] = weights[i] || 0; weights[i] -= stepSize * (grad + regParam * weights[i]); } }
javascript
function regularizeL2(weights, gradientCount, stepSize, regParam) { const [gradient, count] = gradientCount; for (let i = 0; i < gradient.length; i++) { let grad = (gradient[i] || 0) / count; weights[i] = weights[i] || 0; weights[i] -= stepSize * (grad + regParam * weights[i]); } }
[ "function", "regularizeL2", "(", "weights", ",", "gradientCount", ",", "stepSize", ",", "regParam", ")", "{", "const", "[", "gradient", ",", "count", "]", "=", "gradientCount", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "gradient", ".", "length", ";", "i", "++", ")", "{", "let", "grad", "=", "(", "gradient", "[", "i", "]", "||", "0", ")", "/", "count", ";", "weights", "[", "i", "]", "=", "weights", "[", "i", "]", "||", "0", ";", "weights", "[", "i", "]", "-=", "stepSize", "*", "(", "grad", "+", "regParam", "*", "weights", "[", "i", "]", ")", ";", "}", "}" ]
L2, a.k.a ridge regression
[ "L2", "a", ".", "k", ".", "a", "ridge", "regression" ]
fdb4b5d08ca4f6321ceda888385a68208d04a545
https://github.com/skale-me/skale/blob/fdb4b5d08ca4f6321ceda888385a68208d04a545/ml/sgd-linear-model.js#L112-L120
15,688
skale-me/skale
lib/dataset.js
randomizeArray
function randomizeArray(array) { let i = array.length; while (i) { let j = Math.floor(Math.random() * i--); [array[i], array[j]] = [array[j], array[i]]; } return array; }
javascript
function randomizeArray(array) { let i = array.length; while (i) { let j = Math.floor(Math.random() * i--); [array[i], array[j]] = [array[j], array[i]]; } return array; }
[ "function", "randomizeArray", "(", "array", ")", "{", "let", "i", "=", "array", ".", "length", ";", "while", "(", "i", ")", "{", "let", "j", "=", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "i", "--", ")", ";", "[", "array", "[", "i", "]", ",", "array", "[", "j", "]", "]", "=", "[", "array", "[", "j", "]", ",", "array", "[", "i", "]", "]", ";", "}", "return", "array", ";", "}" ]
Randomize order of an array using Fisher-Yates shuffe
[ "Randomize", "order", "of", "an", "array", "using", "Fisher", "-", "Yates", "shuffe" ]
fdb4b5d08ca4f6321ceda888385a68208d04a545
https://github.com/skale-me/skale/blob/fdb4b5d08ca4f6321ceda888385a68208d04a545/lib/dataset.js#L584-L591
15,689
skale-me/skale
lib/dataset.js
sampleSizeFraction
function sampleSizeFraction(num, total, withReplacement) { const minSamplingRate = 1e-10; // Limited by RNG's resolution const delta = 1e-4; // To have 0.9999 success rate const fraction = num / total; let upperBound; if (withReplacement) { // Poisson upper bound for Pr(num successful poisson trials) > (1-delta) let numStd = num < 6 ? 12 : num < 16 ? 9 : 6; upperBound = Math.max(num + numStd * Math.sqrt(num), minSamplingRate) / total; } else { // Binomial upper bound for Pr(num successful bernoulli trials) > (1-delta) let gamma = - Math.log(delta) / total; upperBound = Math.min(1, Math.max(minSamplingRate, fraction + gamma + Math.sqrt(gamma * gamma + 2 * gamma * fraction))); } return upperBound; }
javascript
function sampleSizeFraction(num, total, withReplacement) { const minSamplingRate = 1e-10; // Limited by RNG's resolution const delta = 1e-4; // To have 0.9999 success rate const fraction = num / total; let upperBound; if (withReplacement) { // Poisson upper bound for Pr(num successful poisson trials) > (1-delta) let numStd = num < 6 ? 12 : num < 16 ? 9 : 6; upperBound = Math.max(num + numStd * Math.sqrt(num), minSamplingRate) / total; } else { // Binomial upper bound for Pr(num successful bernoulli trials) > (1-delta) let gamma = - Math.log(delta) / total; upperBound = Math.min(1, Math.max(minSamplingRate, fraction + gamma + Math.sqrt(gamma * gamma + 2 * gamma * fraction))); } return upperBound; }
[ "function", "sampleSizeFraction", "(", "num", ",", "total", ",", "withReplacement", ")", "{", "const", "minSamplingRate", "=", "1e-10", ";", "// Limited by RNG's resolution", "const", "delta", "=", "1e-4", ";", "// To have 0.9999 success rate", "const", "fraction", "=", "num", "/", "total", ";", "let", "upperBound", ";", "if", "(", "withReplacement", ")", "{", "// Poisson upper bound for Pr(num successful poisson trials) > (1-delta)", "let", "numStd", "=", "num", "<", "6", "?", "12", ":", "num", "<", "16", "?", "9", ":", "6", ";", "upperBound", "=", "Math", ".", "max", "(", "num", "+", "numStd", "*", "Math", ".", "sqrt", "(", "num", ")", ",", "minSamplingRate", ")", "/", "total", ";", "}", "else", "{", "// Binomial upper bound for Pr(num successful bernoulli trials) > (1-delta)", "let", "gamma", "=", "-", "Math", ".", "log", "(", "delta", ")", "/", "total", ";", "upperBound", "=", "Math", ".", "min", "(", "1", ",", "Math", ".", "max", "(", "minSamplingRate", ",", "fraction", "+", "gamma", "+", "Math", ".", "sqrt", "(", "gamma", "*", "gamma", "+", "2", "*", "gamma", "*", "fraction", ")", ")", ")", ";", "}", "return", "upperBound", ";", "}" ]
Returns a sampling rate that ensures a size >= lowerBound most of the time. Inspired from spark
[ "Returns", "a", "sampling", "rate", "that", "ensures", "a", "size", ">", "=", "lowerBound", "most", "of", "the", "time", ".", "Inspired", "from", "spark" ]
fdb4b5d08ca4f6321ceda888385a68208d04a545
https://github.com/skale-me/skale/blob/fdb4b5d08ca4f6321ceda888385a68208d04a545/lib/dataset.js#L595-L611
15,690
skale-me/skale
lib/task.js
iterateDone
function iterateDone() { dlog(start, 'iterate'); blocksToRegister.map(function(block) {mm.register(block);}); if (action) { if (action.opt._postIterate) { action.opt._postIterate(action.init, action.opt, self, tmpPart.partitionIndex, function () { done({data: {host: self.grid.host.uuid, path: self.exportFile}}); }); } else done({data: action.init}); } else { const start1 = Date.now(); self.nodes[self.datasetId].spillToDisk(self, function() { done({pid: self.pid, files: self.files}); dlog(start1, 'spillToDisk'); }); } }
javascript
function iterateDone() { dlog(start, 'iterate'); blocksToRegister.map(function(block) {mm.register(block);}); if (action) { if (action.opt._postIterate) { action.opt._postIterate(action.init, action.opt, self, tmpPart.partitionIndex, function () { done({data: {host: self.grid.host.uuid, path: self.exportFile}}); }); } else done({data: action.init}); } else { const start1 = Date.now(); self.nodes[self.datasetId].spillToDisk(self, function() { done({pid: self.pid, files: self.files}); dlog(start1, 'spillToDisk'); }); } }
[ "function", "iterateDone", "(", ")", "{", "dlog", "(", "start", ",", "'iterate'", ")", ";", "blocksToRegister", ".", "map", "(", "function", "(", "block", ")", "{", "mm", ".", "register", "(", "block", ")", ";", "}", ")", ";", "if", "(", "action", ")", "{", "if", "(", "action", ".", "opt", ".", "_postIterate", ")", "{", "action", ".", "opt", ".", "_postIterate", "(", "action", ".", "init", ",", "action", ".", "opt", ",", "self", ",", "tmpPart", ".", "partitionIndex", ",", "function", "(", ")", "{", "done", "(", "{", "data", ":", "{", "host", ":", "self", ".", "grid", ".", "host", ".", "uuid", ",", "path", ":", "self", ".", "exportFile", "}", "}", ")", ";", "}", ")", ";", "}", "else", "done", "(", "{", "data", ":", "action", ".", "init", "}", ")", ";", "}", "else", "{", "const", "start1", "=", "Date", ".", "now", "(", ")", ";", "self", ".", "nodes", "[", "self", ".", "datasetId", "]", ".", "spillToDisk", "(", "self", ",", "function", "(", ")", "{", "done", "(", "{", "pid", ":", "self", ".", "pid", ",", "files", ":", "self", ".", "files", "}", ")", ";", "dlog", "(", "start1", ",", "'spillToDisk'", ")", ";", "}", ")", ";", "}", "}" ]
Post-iterate actions
[ "Post", "-", "iterate", "actions" ]
fdb4b5d08ca4f6321ceda888385a68208d04a545
https://github.com/skale-me/skale/blob/fdb4b5d08ca4f6321ceda888385a68208d04a545/lib/task.js#L100-L116
15,691
noopkat/avrgirl-arduino
lib/protocol.js
function(options) { this.debug = options.debug; this.board = options.board; this.connection = options.connection; this.chip = new options.protocol({ quiet: true }); }
javascript
function(options) { this.debug = options.debug; this.board = options.board; this.connection = options.connection; this.chip = new options.protocol({ quiet: true }); }
[ "function", "(", "options", ")", "{", "this", ".", "debug", "=", "options", ".", "debug", ";", "this", ".", "board", "=", "options", ".", "board", ";", "this", ".", "connection", "=", "options", ".", "connection", ";", "this", ".", "chip", "=", "new", "options", ".", "protocol", "(", "{", "quiet", ":", "true", "}", ")", ";", "}" ]
Generic Protocol for other protocols to inherit from
[ "Generic", "Protocol", "for", "other", "protocols", "to", "inherit", "from" ]
dc787b3113a383ce724df324df319c70d9ed59f1
https://github.com/noopkat/avrgirl-arduino/blob/dc787b3113a383ce724df324df319c70d9ed59f1/lib/protocol.js#L5-L12
15,692
noopkat/avrgirl-arduino
boards.js
boardLookupTable
function boardLookupTable() { var byBoard = {}; for (var i = 0; i < boards.length; i++) { var currentBoard = boards[i]; byBoard[currentBoard.name] = currentBoard; var aliases = currentBoard.aliases; if (Array.isArray(aliases)) { for (var j = 0; j < aliases.length; j++) { var currentAlias = aliases[j]; byBoard[currentAlias] = currentBoard; } } } return byBoard; }
javascript
function boardLookupTable() { var byBoard = {}; for (var i = 0; i < boards.length; i++) { var currentBoard = boards[i]; byBoard[currentBoard.name] = currentBoard; var aliases = currentBoard.aliases; if (Array.isArray(aliases)) { for (var j = 0; j < aliases.length; j++) { var currentAlias = aliases[j]; byBoard[currentAlias] = currentBoard; } } } return byBoard; }
[ "function", "boardLookupTable", "(", ")", "{", "var", "byBoard", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "boards", ".", "length", ";", "i", "++", ")", "{", "var", "currentBoard", "=", "boards", "[", "i", "]", ";", "byBoard", "[", "currentBoard", ".", "name", "]", "=", "currentBoard", ";", "var", "aliases", "=", "currentBoard", ".", "aliases", ";", "if", "(", "Array", ".", "isArray", "(", "aliases", ")", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "aliases", ".", "length", ";", "j", "++", ")", "{", "var", "currentAlias", "=", "aliases", "[", "j", "]", ";", "byBoard", "[", "currentAlias", "]", "=", "currentBoard", ";", "}", "}", "}", "return", "byBoard", ";", "}" ]
Generate an object with board name keys for faster lookup @return {object} byBoardName
[ "Generate", "an", "object", "with", "board", "name", "keys", "for", "faster", "lookup" ]
dc787b3113a383ce724df324df319c70d9ed59f1
https://github.com/noopkat/avrgirl-arduino/blob/dc787b3113a383ce724df324df319c70d9ed59f1/boards.js#L266-L281
15,693
unshiftio/querystringify
index.js
querystringify
function querystringify(obj, prefix) { prefix = prefix || ''; var pairs = [] , value , key; // // Optionally prefix with a '?' if needed // if ('string' !== typeof prefix) prefix = '?'; for (key in obj) { if (has.call(obj, key)) { value = obj[key]; // // Edge cases where we actually want to encode the value to an empty // string instead of the stringified value. // if (!value && (value === null || value === undef || isNaN(value))) { value = ''; } key = encodeURIComponent(key); value = encodeURIComponent(value); // // If we failed to encode the strings, we should bail out as we don't // want to add invalid strings to the query. // if (key === null || value === null) continue; pairs.push(key +'='+ value); } } return pairs.length ? prefix + pairs.join('&') : ''; }
javascript
function querystringify(obj, prefix) { prefix = prefix || ''; var pairs = [] , value , key; // // Optionally prefix with a '?' if needed // if ('string' !== typeof prefix) prefix = '?'; for (key in obj) { if (has.call(obj, key)) { value = obj[key]; // // Edge cases where we actually want to encode the value to an empty // string instead of the stringified value. // if (!value && (value === null || value === undef || isNaN(value))) { value = ''; } key = encodeURIComponent(key); value = encodeURIComponent(value); // // If we failed to encode the strings, we should bail out as we don't // want to add invalid strings to the query. // if (key === null || value === null) continue; pairs.push(key +'='+ value); } } return pairs.length ? prefix + pairs.join('&') : ''; }
[ "function", "querystringify", "(", "obj", ",", "prefix", ")", "{", "prefix", "=", "prefix", "||", "''", ";", "var", "pairs", "=", "[", "]", ",", "value", ",", "key", ";", "//", "// Optionally prefix with a '?' if needed", "//", "if", "(", "'string'", "!==", "typeof", "prefix", ")", "prefix", "=", "'?'", ";", "for", "(", "key", "in", "obj", ")", "{", "if", "(", "has", ".", "call", "(", "obj", ",", "key", ")", ")", "{", "value", "=", "obj", "[", "key", "]", ";", "//", "// Edge cases where we actually want to encode the value to an empty", "// string instead of the stringified value.", "//", "if", "(", "!", "value", "&&", "(", "value", "===", "null", "||", "value", "===", "undef", "||", "isNaN", "(", "value", ")", ")", ")", "{", "value", "=", "''", ";", "}", "key", "=", "encodeURIComponent", "(", "key", ")", ";", "value", "=", "encodeURIComponent", "(", "value", ")", ";", "//", "// If we failed to encode the strings, we should bail out as we don't", "// want to add invalid strings to the query.", "//", "if", "(", "key", "===", "null", "||", "value", "===", "null", ")", "continue", ";", "pairs", ".", "push", "(", "key", "+", "'='", "+", "value", ")", ";", "}", "}", "return", "pairs", ".", "length", "?", "prefix", "+", "pairs", ".", "join", "(", "'&'", ")", ":", "''", ";", "}" ]
Transform a query string to an object. @param {Object} obj Object that should be transformed. @param {String} prefix Optional prefix. @returns {String} @api public
[ "Transform", "a", "query", "string", "to", "an", "object", "." ]
cb645f2841adef7fae0fb695deeaa37e35566359
https://github.com/unshiftio/querystringify/blob/cb645f2841adef7fae0fb695deeaa37e35566359/index.js#L75-L112
15,694
ninsuo/symfony-collection
jquery.collection.js
function () { var rand = '' + Math.random() * 1000 * new Date().getTime(); return rand.replace('.', '').split('').sort(function () { return 0.5 - Math.random(); }).join(''); }
javascript
function () { var rand = '' + Math.random() * 1000 * new Date().getTime(); return rand.replace('.', '').split('').sort(function () { return 0.5 - Math.random(); }).join(''); }
[ "function", "(", ")", "{", "var", "rand", "=", "''", "+", "Math", ".", "random", "(", ")", "*", "1000", "*", "new", "Date", "(", ")", ".", "getTime", "(", ")", ";", "return", "rand", ".", "replace", "(", "'.'", ",", "''", ")", ".", "split", "(", "''", ")", ".", "sort", "(", "function", "(", ")", "{", "return", "0.5", "-", "Math", ".", "random", "(", ")", ";", "}", ")", ".", "join", "(", "''", ")", ";", "}" ]
used to generate random id attributes when required and missing
[ "used", "to", "generate", "random", "id", "attributes", "when", "required", "and", "missing" ]
d5e6cbc7c7dc1f0509631c9bb6094fead0f6c8f0
https://github.com/ninsuo/symfony-collection/blob/d5e6cbc7c7dc1f0509631c9bb6094fead0f6c8f0/jquery.collection.js#L100-L105
15,695
ninsuo/symfony-collection
jquery.collection.js
function (prefix, obj) { if (!obj.attr('id')) { var generated_id; do { generated_id = prefix + '_' + randomNumber(); } while ($('#' + generated_id).length > 0); obj.attr('id', generated_id); } return obj.attr('id'); }
javascript
function (prefix, obj) { if (!obj.attr('id')) { var generated_id; do { generated_id = prefix + '_' + randomNumber(); } while ($('#' + generated_id).length > 0); obj.attr('id', generated_id); } return obj.attr('id'); }
[ "function", "(", "prefix", ",", "obj", ")", "{", "if", "(", "!", "obj", ".", "attr", "(", "'id'", ")", ")", "{", "var", "generated_id", ";", "do", "{", "generated_id", "=", "prefix", "+", "'_'", "+", "randomNumber", "(", ")", ";", "}", "while", "(", "$", "(", "'#'", "+", "generated_id", ")", ".", "length", ">", "0", ")", ";", "obj", ".", "attr", "(", "'id'", ",", "generated_id", ")", ";", "}", "return", "obj", ".", "attr", "(", "'id'", ")", ";", "}" ]
return an element's id, after generating one when missing
[ "return", "an", "element", "s", "id", "after", "generating", "one", "when", "missing" ]
d5e6cbc7c7dc1f0509631c9bb6094fead0f6c8f0
https://github.com/ninsuo/symfony-collection/blob/d5e6cbc7c7dc1f0509631c9bb6094fead0f6c8f0/jquery.collection.js#L108-L117
15,696
ninsuo/symfony-collection
jquery.collection.js
function (selector) { try { var jqElem = $(selector); } catch (e) { return null; } if (jqElem.length === 0) { return null; } else if (jqElem.is('input[type="checkbox"]')) { return (jqElem.prop('checked') === true ? true : false); } else if (jqElem.is('input[type="radio"]') && jqElem.attr('name') !== undefined) { return $('input[name="' + jqElem.attr('name') + '"]:checked').val(); } else if (jqElem.prop('value') !== undefined) { return jqElem.val(); } else { return jqElem.html(); } }
javascript
function (selector) { try { var jqElem = $(selector); } catch (e) { return null; } if (jqElem.length === 0) { return null; } else if (jqElem.is('input[type="checkbox"]')) { return (jqElem.prop('checked') === true ? true : false); } else if (jqElem.is('input[type="radio"]') && jqElem.attr('name') !== undefined) { return $('input[name="' + jqElem.attr('name') + '"]:checked').val(); } else if (jqElem.prop('value') !== undefined) { return jqElem.val(); } else { return jqElem.html(); } }
[ "function", "(", "selector", ")", "{", "try", "{", "var", "jqElem", "=", "$", "(", "selector", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "null", ";", "}", "if", "(", "jqElem", ".", "length", "===", "0", ")", "{", "return", "null", ";", "}", "else", "if", "(", "jqElem", ".", "is", "(", "'input[type=\"checkbox\"]'", ")", ")", "{", "return", "(", "jqElem", ".", "prop", "(", "'checked'", ")", "===", "true", "?", "true", ":", "false", ")", ";", "}", "else", "if", "(", "jqElem", ".", "is", "(", "'input[type=\"radio\"]'", ")", "&&", "jqElem", ".", "attr", "(", "'name'", ")", "!==", "undefined", ")", "{", "return", "$", "(", "'input[name=\"'", "+", "jqElem", ".", "attr", "(", "'name'", ")", "+", "'\"]:checked'", ")", ".", "val", "(", ")", ";", "}", "else", "if", "(", "jqElem", ".", "prop", "(", "'value'", ")", "!==", "undefined", ")", "{", "return", "jqElem", ".", "val", "(", ")", ";", "}", "else", "{", "return", "jqElem", ".", "html", "(", ")", ";", "}", "}" ]
return a field value whatever the field type
[ "return", "a", "field", "value", "whatever", "the", "field", "type" ]
d5e6cbc7c7dc1f0509631c9bb6094fead0f6c8f0
https://github.com/ninsuo/symfony-collection/blob/d5e6cbc7c7dc1f0509631c9bb6094fead0f6c8f0/jquery.collection.js#L120-L137
15,697
ninsuo/symfony-collection
jquery.collection.js
function (selector, value, physical) { try { var jqElem = $(selector); } catch (e) { return; } if (jqElem.length === 0) { return; } else if (jqElem.is('input[type="checkbox"]')) { if (value) { jqElem.attr('checked', true); } else { jqElem.removeAttr('checked'); } } else if (jqElem.prop('value') !== undefined) { if (physical) { jqElem.attr('value', value); } else { jqElem.val(value); } } else { jqElem.html(value); } }
javascript
function (selector, value, physical) { try { var jqElem = $(selector); } catch (e) { return; } if (jqElem.length === 0) { return; } else if (jqElem.is('input[type="checkbox"]')) { if (value) { jqElem.attr('checked', true); } else { jqElem.removeAttr('checked'); } } else if (jqElem.prop('value') !== undefined) { if (physical) { jqElem.attr('value', value); } else { jqElem.val(value); } } else { jqElem.html(value); } }
[ "function", "(", "selector", ",", "value", ",", "physical", ")", "{", "try", "{", "var", "jqElem", "=", "$", "(", "selector", ")", ";", "}", "catch", "(", "e", ")", "{", "return", ";", "}", "if", "(", "jqElem", ".", "length", "===", "0", ")", "{", "return", ";", "}", "else", "if", "(", "jqElem", ".", "is", "(", "'input[type=\"checkbox\"]'", ")", ")", "{", "if", "(", "value", ")", "{", "jqElem", ".", "attr", "(", "'checked'", ",", "true", ")", ";", "}", "else", "{", "jqElem", ".", "removeAttr", "(", "'checked'", ")", ";", "}", "}", "else", "if", "(", "jqElem", ".", "prop", "(", "'value'", ")", "!==", "undefined", ")", "{", "if", "(", "physical", ")", "{", "jqElem", ".", "attr", "(", "'value'", ",", "value", ")", ";", "}", "else", "{", "jqElem", ".", "val", "(", "value", ")", ";", "}", "}", "else", "{", "jqElem", ".", "html", "(", "value", ")", ";", "}", "}" ]
set a field value in accordance to the field type
[ "set", "a", "field", "value", "in", "accordance", "to", "the", "field", "type" ]
d5e6cbc7c7dc1f0509631c9bb6094fead0f6c8f0
https://github.com/ninsuo/symfony-collection/blob/d5e6cbc7c7dc1f0509631c9bb6094fead0f6c8f0/jquery.collection.js#L140-L163
15,698
ninsuo/symfony-collection
jquery.collection.js
function (elements, index, toReplace, replaceWith) { var replaceAttrDataNode = function (node) { var jqNode = $(node); if (typeof node === 'object' && 'attributes' in node) { $.each(node.attributes, function (i, attrib) { if ($.type(attrib.value) === 'string') { jqNode.attr(attrib.name.replace(toReplace, replaceWith), attrib.value.replace(toReplace, replaceWith)); } }); } if (jqNode.length > 0) { $.each(jqNode.data(), function (name, value) { if ($.type(value) === 'string') { jqNode.data(name.replace(toReplace, replaceWith), value.replace(toReplace, replaceWith)); } }); } }; var element = elements.eq(index); replaceAttrDataNode(element[0]); element.find('*').each(function () { replaceAttrDataNode(this); }); }
javascript
function (elements, index, toReplace, replaceWith) { var replaceAttrDataNode = function (node) { var jqNode = $(node); if (typeof node === 'object' && 'attributes' in node) { $.each(node.attributes, function (i, attrib) { if ($.type(attrib.value) === 'string') { jqNode.attr(attrib.name.replace(toReplace, replaceWith), attrib.value.replace(toReplace, replaceWith)); } }); } if (jqNode.length > 0) { $.each(jqNode.data(), function (name, value) { if ($.type(value) === 'string') { jqNode.data(name.replace(toReplace, replaceWith), value.replace(toReplace, replaceWith)); } }); } }; var element = elements.eq(index); replaceAttrDataNode(element[0]); element.find('*').each(function () { replaceAttrDataNode(this); }); }
[ "function", "(", "elements", ",", "index", ",", "toReplace", ",", "replaceWith", ")", "{", "var", "replaceAttrDataNode", "=", "function", "(", "node", ")", "{", "var", "jqNode", "=", "$", "(", "node", ")", ";", "if", "(", "typeof", "node", "===", "'object'", "&&", "'attributes'", "in", "node", ")", "{", "$", ".", "each", "(", "node", ".", "attributes", ",", "function", "(", "i", ",", "attrib", ")", "{", "if", "(", "$", ".", "type", "(", "attrib", ".", "value", ")", "===", "'string'", ")", "{", "jqNode", ".", "attr", "(", "attrib", ".", "name", ".", "replace", "(", "toReplace", ",", "replaceWith", ")", ",", "attrib", ".", "value", ".", "replace", "(", "toReplace", ",", "replaceWith", ")", ")", ";", "}", "}", ")", ";", "}", "if", "(", "jqNode", ".", "length", ">", "0", ")", "{", "$", ".", "each", "(", "jqNode", ".", "data", "(", ")", ",", "function", "(", "name", ",", "value", ")", "{", "if", "(", "$", ".", "type", "(", "value", ")", "===", "'string'", ")", "{", "jqNode", ".", "data", "(", "name", ".", "replace", "(", "toReplace", ",", "replaceWith", ")", ",", "value", ".", "replace", "(", "toReplace", ",", "replaceWith", ")", ")", ";", "}", "}", ")", ";", "}", "}", ";", "var", "element", "=", "elements", ".", "eq", "(", "index", ")", ";", "replaceAttrDataNode", "(", "element", "[", "0", "]", ")", ";", "element", ".", "find", "(", "'*'", ")", ".", "each", "(", "function", "(", ")", "{", "replaceAttrDataNode", "(", "this", ")", ";", "}", ")", ";", "}" ]
if we need to change CollectionType_field_42_value to CollectionType_field_84_value, this method will change it in id="CollectionType_field_42_value", but also data-id="CollectionType_field_42_value" or anywhere else just in case it could be used otherwise.
[ "if", "we", "need", "to", "change", "CollectionType_field_42_value", "to", "CollectionType_field_84_value", "this", "method", "will", "change", "it", "in", "id", "=", "CollectionType_field_42_value", "but", "also", "data", "-", "id", "=", "CollectionType_field_42_value", "or", "anywhere", "else", "just", "in", "case", "it", "could", "be", "used", "otherwise", "." ]
d5e6cbc7c7dc1f0509631c9bb6094fead0f6c8f0
https://github.com/ninsuo/symfony-collection/blob/d5e6cbc7c7dc1f0509631c9bb6094fead0f6c8f0/jquery.collection.js#L179-L204
15,699
ninsuo/symfony-collection
jquery.collection.js
function (collection, settings, html, oldIndex, newIndex, oldKey, newKey) { var toReplace = new RegExp(pregQuote(settings.name_prefix + '[' + oldKey + ']'), 'g'); var replaceWith = settings.name_prefix + '[' + newKey + ']'; html = html.replace(toReplace, replaceWith); toReplace = new RegExp(pregQuote(collection.attr('id') + '_' + oldIndex), 'g'); replaceWith = collection.attr('id') + '_' + newIndex; html = html.replace(toReplace, replaceWith); return html; }
javascript
function (collection, settings, html, oldIndex, newIndex, oldKey, newKey) { var toReplace = new RegExp(pregQuote(settings.name_prefix + '[' + oldKey + ']'), 'g'); var replaceWith = settings.name_prefix + '[' + newKey + ']'; html = html.replace(toReplace, replaceWith); toReplace = new RegExp(pregQuote(collection.attr('id') + '_' + oldIndex), 'g'); replaceWith = collection.attr('id') + '_' + newIndex; html = html.replace(toReplace, replaceWith); return html; }
[ "function", "(", "collection", ",", "settings", ",", "html", ",", "oldIndex", ",", "newIndex", ",", "oldKey", ",", "newKey", ")", "{", "var", "toReplace", "=", "new", "RegExp", "(", "pregQuote", "(", "settings", ".", "name_prefix", "+", "'['", "+", "oldKey", "+", "']'", ")", ",", "'g'", ")", ";", "var", "replaceWith", "=", "settings", ".", "name_prefix", "+", "'['", "+", "newKey", "+", "']'", ";", "html", "=", "html", ".", "replace", "(", "toReplace", ",", "replaceWith", ")", ";", "toReplace", "=", "new", "RegExp", "(", "pregQuote", "(", "collection", ".", "attr", "(", "'id'", ")", "+", "'_'", "+", "oldIndex", ")", ",", "'g'", ")", ";", "replaceWith", "=", "collection", ".", "attr", "(", "'id'", ")", "+", "'_'", "+", "newIndex", ";", "html", "=", "html", ".", "replace", "(", "toReplace", ",", "replaceWith", ")", ";", "return", "html", ";", "}" ]
same as above, but will replace element names and indexes in an html string instead of in a dom element.
[ "same", "as", "above", "but", "will", "replace", "element", "names", "and", "indexes", "in", "an", "html", "string", "instead", "of", "in", "a", "dom", "element", "." ]
d5e6cbc7c7dc1f0509631c9bb6094fead0f6c8f0
https://github.com/ninsuo/symfony-collection/blob/d5e6cbc7c7dc1f0509631c9bb6094fead0f6c8f0/jquery.collection.js#L247-L257