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
9,500
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
stopDetect
function stopDetect() { // clone current data to the store as the previous gesture // used for the double tap gesture, since this is an other gesture detect session this.previous = ionic.Gestures.utils.extend({}, this.current); // reset the current this.current = null; // stopped! this.stopped = true; }
javascript
function stopDetect() { // clone current data to the store as the previous gesture // used for the double tap gesture, since this is an other gesture detect session this.previous = ionic.Gestures.utils.extend({}, this.current); // reset the current this.current = null; // stopped! this.stopped = true; }
[ "function", "stopDetect", "(", ")", "{", "// clone current data to the store as the previous gesture", "// used for the double tap gesture, since this is an other gesture detect session", "this", ".", "previous", "=", "ionic", ".", "Gestures", ".", "utils", ".", "extend", "(", "{", "}", ",", "this", ".", "current", ")", ";", "// reset the current", "this", ".", "current", "=", "null", ";", "// stopped!", "this", ".", "stopped", "=", "true", ";", "}" ]
clear the ionic.Gestures.gesture vars this is called on endDetect, but can also be used when a final ionic.Gestures.gesture has been detected to stop other ionic.Gestures.gestures from being fired
[ "clear", "the", "ionic", ".", "Gestures", ".", "gesture", "vars", "this", "is", "called", "on", "endDetect", "but", "can", "also", "be", "used", "when", "a", "final", "ionic", ".", "Gestures", ".", "gesture", "has", "been", "detected", "to", "stop", "other", "ionic", ".", "Gestures", ".", "gestures", "from", "being", "fired" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L1402-L1412
9,501
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
extendEventData
function extendEventData(ev) { var startEv = this.current.startEvent; // if the touches change, set the new touches over the startEvent touches // this because touchevents don't have all the touches on touchstart, or the // user must place his fingers at the EXACT same time on the screen, which is not realistic // but, sometimes it happens that both fingers are touching at the EXACT same time if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) { // extend 1 level deep to get the touchlist with the touch objects startEv.touches = []; for(var i=0,len=ev.touches.length; i<len; i++) { startEv.touches.push(ionic.Gestures.utils.extend({}, ev.touches[i])); } } var delta_time = ev.timeStamp - startEv.timeStamp, delta_x = ev.center.pageX - startEv.center.pageX, delta_y = ev.center.pageY - startEv.center.pageY, velocity = ionic.Gestures.utils.getVelocity(delta_time, delta_x, delta_y); ionic.Gestures.utils.extend(ev, { deltaTime : delta_time, deltaX : delta_x, deltaY : delta_y, velocityX : velocity.x, velocityY : velocity.y, distance : ionic.Gestures.utils.getDistance(startEv.center, ev.center), angle : ionic.Gestures.utils.getAngle(startEv.center, ev.center), direction : ionic.Gestures.utils.getDirection(startEv.center, ev.center), scale : ionic.Gestures.utils.getScale(startEv.touches, ev.touches), rotation : ionic.Gestures.utils.getRotation(startEv.touches, ev.touches), startEvent : startEv }); return ev; }
javascript
function extendEventData(ev) { var startEv = this.current.startEvent; // if the touches change, set the new touches over the startEvent touches // this because touchevents don't have all the touches on touchstart, or the // user must place his fingers at the EXACT same time on the screen, which is not realistic // but, sometimes it happens that both fingers are touching at the EXACT same time if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) { // extend 1 level deep to get the touchlist with the touch objects startEv.touches = []; for(var i=0,len=ev.touches.length; i<len; i++) { startEv.touches.push(ionic.Gestures.utils.extend({}, ev.touches[i])); } } var delta_time = ev.timeStamp - startEv.timeStamp, delta_x = ev.center.pageX - startEv.center.pageX, delta_y = ev.center.pageY - startEv.center.pageY, velocity = ionic.Gestures.utils.getVelocity(delta_time, delta_x, delta_y); ionic.Gestures.utils.extend(ev, { deltaTime : delta_time, deltaX : delta_x, deltaY : delta_y, velocityX : velocity.x, velocityY : velocity.y, distance : ionic.Gestures.utils.getDistance(startEv.center, ev.center), angle : ionic.Gestures.utils.getAngle(startEv.center, ev.center), direction : ionic.Gestures.utils.getDirection(startEv.center, ev.center), scale : ionic.Gestures.utils.getScale(startEv.touches, ev.touches), rotation : ionic.Gestures.utils.getRotation(startEv.touches, ev.touches), startEvent : startEv }); return ev; }
[ "function", "extendEventData", "(", "ev", ")", "{", "var", "startEv", "=", "this", ".", "current", ".", "startEvent", ";", "// if the touches change, set the new touches over the startEvent touches", "// this because touchevents don't have all the touches on touchstart, or the", "// user must place his fingers at the EXACT same time on the screen, which is not realistic", "// but, sometimes it happens that both fingers are touching at the EXACT same time", "if", "(", "startEv", "&&", "(", "ev", ".", "touches", ".", "length", "!=", "startEv", ".", "touches", ".", "length", "||", "ev", ".", "touches", "===", "startEv", ".", "touches", ")", ")", "{", "// extend 1 level deep to get the touchlist with the touch objects", "startEv", ".", "touches", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "ev", ".", "touches", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "startEv", ".", "touches", ".", "push", "(", "ionic", ".", "Gestures", ".", "utils", ".", "extend", "(", "{", "}", ",", "ev", ".", "touches", "[", "i", "]", ")", ")", ";", "}", "}", "var", "delta_time", "=", "ev", ".", "timeStamp", "-", "startEv", ".", "timeStamp", ",", "delta_x", "=", "ev", ".", "center", ".", "pageX", "-", "startEv", ".", "center", ".", "pageX", ",", "delta_y", "=", "ev", ".", "center", ".", "pageY", "-", "startEv", ".", "center", ".", "pageY", ",", "velocity", "=", "ionic", ".", "Gestures", ".", "utils", ".", "getVelocity", "(", "delta_time", ",", "delta_x", ",", "delta_y", ")", ";", "ionic", ".", "Gestures", ".", "utils", ".", "extend", "(", "ev", ",", "{", "deltaTime", ":", "delta_time", ",", "deltaX", ":", "delta_x", ",", "deltaY", ":", "delta_y", ",", "velocityX", ":", "velocity", ".", "x", ",", "velocityY", ":", "velocity", ".", "y", ",", "distance", ":", "ionic", ".", "Gestures", ".", "utils", ".", "getDistance", "(", "startEv", ".", "center", ",", "ev", ".", "center", ")", ",", "angle", ":", "ionic", ".", "Gestures", ".", "utils", ".", "getAngle", "(", "startEv", ".", "center", ",", "ev", ".", "center", ")", ",", "direction", ":", "ionic", ".", "Gestures", ".", "utils", ".", "getDirection", "(", "startEv", ".", "center", ",", "ev", ".", "center", ")", ",", "scale", ":", "ionic", ".", "Gestures", ".", "utils", ".", "getScale", "(", "startEv", ".", "touches", ",", "ev", ".", "touches", ")", ",", "rotation", ":", "ionic", ".", "Gestures", ".", "utils", ".", "getRotation", "(", "startEv", ".", "touches", ",", "ev", ".", "touches", ")", ",", "startEvent", ":", "startEv", "}", ")", ";", "return", "ev", ";", "}" ]
extend eventData for ionic.Gestures.gestures @param {Object} ev @returns {Object} ev
[ "extend", "eventData", "for", "ionic", ".", "Gestures", ".", "gestures" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L1420-L1460
9,502
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
function(obj) { var args = Array.prototype.slice.call(arguments, 1); for (var i = 0; i < args.length; i++) { var source = args[i]; if (source) { for (var prop in source) { obj[prop] = source[prop]; } } } return obj; }
javascript
function(obj) { var args = Array.prototype.slice.call(arguments, 1); for (var i = 0; i < args.length; i++) { var source = args[i]; if (source) { for (var prop in source) { obj[prop] = source[prop]; } } } return obj; }
[ "function", "(", "obj", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "args", ".", "length", ";", "i", "++", ")", "{", "var", "source", "=", "args", "[", "i", "]", ";", "if", "(", "source", ")", "{", "for", "(", "var", "prop", "in", "source", ")", "{", "obj", "[", "prop", "]", "=", "source", "[", "prop", "]", ";", "}", "}", "}", "return", "obj", ";", "}" ]
Extend adapted from Underscore.js
[ "Extend", "adapted", "from", "Underscore", ".", "js" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L3314-L3325
9,503
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
function() { var index = uid.length; var digit; while (index) { index--; digit = uid[index].charCodeAt(0); if (digit == 57 /*'9'*/) { uid[index] = 'A'; return uid.join(''); } if (digit == 90 /*'Z'*/) { uid[index] = '0'; } else { uid[index] = String.fromCharCode(digit + 1); return uid.join(''); } } uid.unshift('0'); return uid.join(''); }
javascript
function() { var index = uid.length; var digit; while (index) { index--; digit = uid[index].charCodeAt(0); if (digit == 57 /*'9'*/) { uid[index] = 'A'; return uid.join(''); } if (digit == 90 /*'Z'*/) { uid[index] = '0'; } else { uid[index] = String.fromCharCode(digit + 1); return uid.join(''); } } uid.unshift('0'); return uid.join(''); }
[ "function", "(", ")", "{", "var", "index", "=", "uid", ".", "length", ";", "var", "digit", ";", "while", "(", "index", ")", "{", "index", "--", ";", "digit", "=", "uid", "[", "index", "]", ".", "charCodeAt", "(", "0", ")", ";", "if", "(", "digit", "==", "57", "/*'9'*/", ")", "{", "uid", "[", "index", "]", "=", "'A'", ";", "return", "uid", ".", "join", "(", "''", ")", ";", "}", "if", "(", "digit", "==", "90", "/*'Z'*/", ")", "{", "uid", "[", "index", "]", "=", "'0'", ";", "}", "else", "{", "uid", "[", "index", "]", "=", "String", ".", "fromCharCode", "(", "digit", "+", "1", ")", ";", "return", "uid", ".", "join", "(", "''", ")", ";", "}", "}", "uid", ".", "unshift", "(", "'0'", ")", ";", "return", "uid", ".", "join", "(", "''", ")", ";", "}" ]
A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric characters such as '012ABC'. The reason why we are not using simply a number counter is that the number string gets longer over time, and it can also overflow, where as the nextId will grow much slower, it is a string, and it will never overflow. @returns an unique alpha-numeric string
[ "A", "consistent", "way", "of", "creating", "unique", "IDs", "in", "angular", ".", "The", "ID", "is", "a", "sequence", "of", "alpha", "numeric", "characters", "such", "as", "012ABC", ".", "The", "reason", "why", "we", "are", "not", "using", "simply", "a", "number", "counter", "is", "that", "the", "number", "string", "gets", "longer", "over", "time", "and", "it", "can", "also", "overflow", "where", "as", "the", "nextId", "will", "grow", "much", "slower", "it", "is", "a", "string", "and", "it", "will", "never", "overflow", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L3335-L3355
9,504
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
function(stepCallback, verifyCallback, completedCallback, duration, easingMethod, root) { var start = time(); var lastFrame = start; var percent = 0; var dropCounter = 0; var id = counter++; if (!root) { root = document.body; } // Compacting running db automatically every few new animations if (id % 20 === 0) { var newRunning = {}; for (var usedId in running) { newRunning[usedId] = true; } running = newRunning; } // This is the internal step method which is called every few milliseconds var step = function(virtual) { // Normalize virtual value var render = virtual !== true; // Get current time var now = time(); // Verification is executed before next animation step if (!running[id] || (verifyCallback && !verifyCallback(id))) { running[id] = null; completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, false); return; } // For the current rendering to apply let's update omitted steps in memory. // This is important to bring internal state variables up-to-date with progress in time. if (render) { var droppedFrames = Math.round((now - lastFrame) / (millisecondsPerSecond / desiredFrames)) - 1; for (var j = 0; j < Math.min(droppedFrames, 4); j++) { step(true); dropCounter++; } } // Compute percent value if (duration) { percent = (now - start) / duration; if (percent > 1) { percent = 1; } } // Execute step callback, then... var value = easingMethod ? easingMethod(percent) : percent; if ((stepCallback(value, now, render) === false || percent === 1) && render) { running[id] = null; completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, percent === 1 || duration == null); } else if (render) { lastFrame = now; zyngaCore.effect.Animate.requestAnimationFrame(step, root); } }; // Mark as running running[id] = true; // Init first step zyngaCore.effect.Animate.requestAnimationFrame(step, root); // Return unique animation ID return id; }
javascript
function(stepCallback, verifyCallback, completedCallback, duration, easingMethod, root) { var start = time(); var lastFrame = start; var percent = 0; var dropCounter = 0; var id = counter++; if (!root) { root = document.body; } // Compacting running db automatically every few new animations if (id % 20 === 0) { var newRunning = {}; for (var usedId in running) { newRunning[usedId] = true; } running = newRunning; } // This is the internal step method which is called every few milliseconds var step = function(virtual) { // Normalize virtual value var render = virtual !== true; // Get current time var now = time(); // Verification is executed before next animation step if (!running[id] || (verifyCallback && !verifyCallback(id))) { running[id] = null; completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, false); return; } // For the current rendering to apply let's update omitted steps in memory. // This is important to bring internal state variables up-to-date with progress in time. if (render) { var droppedFrames = Math.round((now - lastFrame) / (millisecondsPerSecond / desiredFrames)) - 1; for (var j = 0; j < Math.min(droppedFrames, 4); j++) { step(true); dropCounter++; } } // Compute percent value if (duration) { percent = (now - start) / duration; if (percent > 1) { percent = 1; } } // Execute step callback, then... var value = easingMethod ? easingMethod(percent) : percent; if ((stepCallback(value, now, render) === false || percent === 1) && render) { running[id] = null; completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, percent === 1 || duration == null); } else if (render) { lastFrame = now; zyngaCore.effect.Animate.requestAnimationFrame(step, root); } }; // Mark as running running[id] = true; // Init first step zyngaCore.effect.Animate.requestAnimationFrame(step, root); // Return unique animation ID return id; }
[ "function", "(", "stepCallback", ",", "verifyCallback", ",", "completedCallback", ",", "duration", ",", "easingMethod", ",", "root", ")", "{", "var", "start", "=", "time", "(", ")", ";", "var", "lastFrame", "=", "start", ";", "var", "percent", "=", "0", ";", "var", "dropCounter", "=", "0", ";", "var", "id", "=", "counter", "++", ";", "if", "(", "!", "root", ")", "{", "root", "=", "document", ".", "body", ";", "}", "// Compacting running db automatically every few new animations", "if", "(", "id", "%", "20", "===", "0", ")", "{", "var", "newRunning", "=", "{", "}", ";", "for", "(", "var", "usedId", "in", "running", ")", "{", "newRunning", "[", "usedId", "]", "=", "true", ";", "}", "running", "=", "newRunning", ";", "}", "// This is the internal step method which is called every few milliseconds", "var", "step", "=", "function", "(", "virtual", ")", "{", "// Normalize virtual value", "var", "render", "=", "virtual", "!==", "true", ";", "// Get current time", "var", "now", "=", "time", "(", ")", ";", "// Verification is executed before next animation step", "if", "(", "!", "running", "[", "id", "]", "||", "(", "verifyCallback", "&&", "!", "verifyCallback", "(", "id", ")", ")", ")", "{", "running", "[", "id", "]", "=", "null", ";", "completedCallback", "&&", "completedCallback", "(", "desiredFrames", "-", "(", "dropCounter", "/", "(", "(", "now", "-", "start", ")", "/", "millisecondsPerSecond", ")", ")", ",", "id", ",", "false", ")", ";", "return", ";", "}", "// For the current rendering to apply let's update omitted steps in memory.", "// This is important to bring internal state variables up-to-date with progress in time.", "if", "(", "render", ")", "{", "var", "droppedFrames", "=", "Math", ".", "round", "(", "(", "now", "-", "lastFrame", ")", "/", "(", "millisecondsPerSecond", "/", "desiredFrames", ")", ")", "-", "1", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "Math", ".", "min", "(", "droppedFrames", ",", "4", ")", ";", "j", "++", ")", "{", "step", "(", "true", ")", ";", "dropCounter", "++", ";", "}", "}", "// Compute percent value", "if", "(", "duration", ")", "{", "percent", "=", "(", "now", "-", "start", ")", "/", "duration", ";", "if", "(", "percent", ">", "1", ")", "{", "percent", "=", "1", ";", "}", "}", "// Execute step callback, then...", "var", "value", "=", "easingMethod", "?", "easingMethod", "(", "percent", ")", ":", "percent", ";", "if", "(", "(", "stepCallback", "(", "value", ",", "now", ",", "render", ")", "===", "false", "||", "percent", "===", "1", ")", "&&", "render", ")", "{", "running", "[", "id", "]", "=", "null", ";", "completedCallback", "&&", "completedCallback", "(", "desiredFrames", "-", "(", "dropCounter", "/", "(", "(", "now", "-", "start", ")", "/", "millisecondsPerSecond", ")", ")", ",", "id", ",", "percent", "===", "1", "||", "duration", "==", "null", ")", ";", "}", "else", "if", "(", "render", ")", "{", "lastFrame", "=", "now", ";", "zyngaCore", ".", "effect", ".", "Animate", ".", "requestAnimationFrame", "(", "step", ",", "root", ")", ";", "}", "}", ";", "// Mark as running", "running", "[", "id", "]", "=", "true", ";", "// Init first step", "zyngaCore", ".", "effect", ".", "Animate", ".", "requestAnimationFrame", "(", "step", ",", "root", ")", ";", "// Return unique animation ID", "return", "id", ";", "}" ]
Start the animation. @param stepCallback {Function} Pointer to function which is executed on every step. Signature of the method should be `function(percent, now, virtual) { return continueWithAnimation; }` @param verifyCallback {Function} Executed before every animation step. Signature of the method should be `function() { return continueWithAnimation; }` @param completedCallback {Function} Signature of the method should be `function(droppedFrames, finishedAnimation) {}` @param duration {Integer} Milliseconds to run the animation @param easingMethod {Function} Pointer to easing function Signature of the method should be `function(percent) { return modifiedValue; }` @param root {Element} Render root, when available. Used for internal usage of requestAnimationFrame. @return {Integer} Identifier of animation. Can be used to stop it any time.
[ "Start", "the", "animation", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L4082-L4160
9,505
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
function() { // Use publish instead of scrollTo to allow scrolling to out of boundary position // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled this.__publish(this.__scrollLeft, -this.__refreshHeight, this.__zoomLevel, true); var d = new Date(); this.refreshStartTime = d.getTime(); if (this.__refreshStart) { this.__refreshStart(); } }
javascript
function() { // Use publish instead of scrollTo to allow scrolling to out of boundary position // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled this.__publish(this.__scrollLeft, -this.__refreshHeight, this.__zoomLevel, true); var d = new Date(); this.refreshStartTime = d.getTime(); if (this.__refreshStart) { this.__refreshStart(); } }
[ "function", "(", ")", "{", "// Use publish instead of scrollTo to allow scrolling to out of boundary position", "// We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled", "this", ".", "__publish", "(", "this", ".", "__scrollLeft", ",", "-", "this", ".", "__refreshHeight", ",", "this", ".", "__zoomLevel", ",", "true", ")", ";", "var", "d", "=", "new", "Date", "(", ")", ";", "this", ".", "refreshStartTime", "=", "d", ".", "getTime", "(", ")", ";", "if", "(", "this", ".", "__refreshStart", ")", "{", "this", ".", "__refreshStart", "(", ")", ";", "}", "}" ]
Starts pull-to-refresh manually.
[ "Starts", "pull", "-", "to", "-", "refresh", "manually", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L5287-L5298
9,506
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
function(level, animate, originLeft, originTop) { var self = this; if (!self.options.zooming) { throw new Error("Zooming is not enabled!"); } // Stop deceleration if (self.__isDecelerating) { zyngaCore.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; } var oldLevel = self.__zoomLevel; // Normalize input origin to center of viewport if not defined if (originLeft == null) { originLeft = self.__clientWidth / 2; } if (originTop == null) { originTop = self.__clientHeight / 2; } // Limit level according to configuration level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom); // Recompute maximum values while temporary tweaking maximum scroll ranges self.__computeScrollMax(level); // Recompute left and top coordinates based on new zoom level var left = ((originLeft + self.__scrollLeft) * level / oldLevel) - originLeft; var top = ((originTop + self.__scrollTop) * level / oldLevel) - originTop; // Limit x-axis if (left > self.__maxScrollLeft) { left = self.__maxScrollLeft; } else if (left < 0) { left = 0; } // Limit y-axis if (top > self.__maxScrollTop) { top = self.__maxScrollTop; } else if (top < 0) { top = 0; } // Push values out self.__publish(left, top, level, animate); }
javascript
function(level, animate, originLeft, originTop) { var self = this; if (!self.options.zooming) { throw new Error("Zooming is not enabled!"); } // Stop deceleration if (self.__isDecelerating) { zyngaCore.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; } var oldLevel = self.__zoomLevel; // Normalize input origin to center of viewport if not defined if (originLeft == null) { originLeft = self.__clientWidth / 2; } if (originTop == null) { originTop = self.__clientHeight / 2; } // Limit level according to configuration level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom); // Recompute maximum values while temporary tweaking maximum scroll ranges self.__computeScrollMax(level); // Recompute left and top coordinates based on new zoom level var left = ((originLeft + self.__scrollLeft) * level / oldLevel) - originLeft; var top = ((originTop + self.__scrollTop) * level / oldLevel) - originTop; // Limit x-axis if (left > self.__maxScrollLeft) { left = self.__maxScrollLeft; } else if (left < 0) { left = 0; } // Limit y-axis if (top > self.__maxScrollTop) { top = self.__maxScrollTop; } else if (top < 0) { top = 0; } // Push values out self.__publish(left, top, level, animate); }
[ "function", "(", "level", ",", "animate", ",", "originLeft", ",", "originTop", ")", "{", "var", "self", "=", "this", ";", "if", "(", "!", "self", ".", "options", ".", "zooming", ")", "{", "throw", "new", "Error", "(", "\"Zooming is not enabled!\"", ")", ";", "}", "// Stop deceleration", "if", "(", "self", ".", "__isDecelerating", ")", "{", "zyngaCore", ".", "effect", ".", "Animate", ".", "stop", "(", "self", ".", "__isDecelerating", ")", ";", "self", ".", "__isDecelerating", "=", "false", ";", "}", "var", "oldLevel", "=", "self", ".", "__zoomLevel", ";", "// Normalize input origin to center of viewport if not defined", "if", "(", "originLeft", "==", "null", ")", "{", "originLeft", "=", "self", ".", "__clientWidth", "/", "2", ";", "}", "if", "(", "originTop", "==", "null", ")", "{", "originTop", "=", "self", ".", "__clientHeight", "/", "2", ";", "}", "// Limit level according to configuration", "level", "=", "Math", ".", "max", "(", "Math", ".", "min", "(", "level", ",", "self", ".", "options", ".", "maxZoom", ")", ",", "self", ".", "options", ".", "minZoom", ")", ";", "// Recompute maximum values while temporary tweaking maximum scroll ranges", "self", ".", "__computeScrollMax", "(", "level", ")", ";", "// Recompute left and top coordinates based on new zoom level", "var", "left", "=", "(", "(", "originLeft", "+", "self", ".", "__scrollLeft", ")", "*", "level", "/", "oldLevel", ")", "-", "originLeft", ";", "var", "top", "=", "(", "(", "originTop", "+", "self", ".", "__scrollTop", ")", "*", "level", "/", "oldLevel", ")", "-", "originTop", ";", "// Limit x-axis", "if", "(", "left", ">", "self", ".", "__maxScrollLeft", ")", "{", "left", "=", "self", ".", "__maxScrollLeft", ";", "}", "else", "if", "(", "left", "<", "0", ")", "{", "left", "=", "0", ";", "}", "// Limit y-axis", "if", "(", "top", ">", "self", ".", "__maxScrollTop", ")", "{", "top", "=", "self", ".", "__maxScrollTop", ";", "}", "else", "if", "(", "top", "<", "0", ")", "{", "top", "=", "0", ";", "}", "// Push values out", "self", ".", "__publish", "(", "left", ",", "top", ",", "level", ",", "animate", ")", ";", "}" ]
Zooms to the given level. Supports optional animation. Zooms the center when no coordinates are given. @param level {Number} Level to zoom to @param animate {Boolean} Whether to use animation @param originLeft {Number} Zoom in at given left coordinate @param originTop {Number} Zoom in at given top coordinate
[ "Zooms", "to", "the", "given", "level", ".", "Supports", "optional", "animation", ".", "Zooms", "the", "center", "when", "no", "coordinates", "are", "given", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L5367-L5418
9,507
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
function(left, top, animate, zoom, wasResize) { var self = this; // Stop deceleration if (self.__isDecelerating) { zyngaCore.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; } // Correct coordinates based on new zoom level if (zoom != null && zoom !== self.__zoomLevel) { if (!self.options.zooming) { throw new Error("Zooming is not enabled!"); } left *= zoom; top *= zoom; // Recompute maximum values while temporary tweaking maximum scroll ranges self.__computeScrollMax(zoom); } else { // Keep zoom when not defined zoom = self.__zoomLevel; } if (!self.options.scrollingX) { left = self.__scrollLeft; } else { if (self.options.paging) { left = Math.round(left / self.__clientWidth) * self.__clientWidth; } else if (self.options.snapping) { left = Math.round(left / self.__snapWidth) * self.__snapWidth; } } if (!self.options.scrollingY) { top = self.__scrollTop; } else { if (self.options.paging) { top = Math.round(top / self.__clientHeight) * self.__clientHeight; } else if (self.options.snapping) { top = Math.round(top / self.__snapHeight) * self.__snapHeight; } } // Limit for allowed ranges left = Math.max(Math.min(self.__maxScrollLeft, left), 0); top = Math.max(Math.min(self.__maxScrollTop, top), 0); // Don't animate when no change detected, still call publish to make sure // that rendered position is really in-sync with internal data if (left === self.__scrollLeft && top === self.__scrollTop) { animate = false; } // Publish new values self.__publish(left, top, zoom, animate, wasResize); }
javascript
function(left, top, animate, zoom, wasResize) { var self = this; // Stop deceleration if (self.__isDecelerating) { zyngaCore.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; } // Correct coordinates based on new zoom level if (zoom != null && zoom !== self.__zoomLevel) { if (!self.options.zooming) { throw new Error("Zooming is not enabled!"); } left *= zoom; top *= zoom; // Recompute maximum values while temporary tweaking maximum scroll ranges self.__computeScrollMax(zoom); } else { // Keep zoom when not defined zoom = self.__zoomLevel; } if (!self.options.scrollingX) { left = self.__scrollLeft; } else { if (self.options.paging) { left = Math.round(left / self.__clientWidth) * self.__clientWidth; } else if (self.options.snapping) { left = Math.round(left / self.__snapWidth) * self.__snapWidth; } } if (!self.options.scrollingY) { top = self.__scrollTop; } else { if (self.options.paging) { top = Math.round(top / self.__clientHeight) * self.__clientHeight; } else if (self.options.snapping) { top = Math.round(top / self.__snapHeight) * self.__snapHeight; } } // Limit for allowed ranges left = Math.max(Math.min(self.__maxScrollLeft, left), 0); top = Math.max(Math.min(self.__maxScrollTop, top), 0); // Don't animate when no change detected, still call publish to make sure // that rendered position is really in-sync with internal data if (left === self.__scrollLeft && top === self.__scrollTop) { animate = false; } // Publish new values self.__publish(left, top, zoom, animate, wasResize); }
[ "function", "(", "left", ",", "top", ",", "animate", ",", "zoom", ",", "wasResize", ")", "{", "var", "self", "=", "this", ";", "// Stop deceleration", "if", "(", "self", ".", "__isDecelerating", ")", "{", "zyngaCore", ".", "effect", ".", "Animate", ".", "stop", "(", "self", ".", "__isDecelerating", ")", ";", "self", ".", "__isDecelerating", "=", "false", ";", "}", "// Correct coordinates based on new zoom level", "if", "(", "zoom", "!=", "null", "&&", "zoom", "!==", "self", ".", "__zoomLevel", ")", "{", "if", "(", "!", "self", ".", "options", ".", "zooming", ")", "{", "throw", "new", "Error", "(", "\"Zooming is not enabled!\"", ")", ";", "}", "left", "*=", "zoom", ";", "top", "*=", "zoom", ";", "// Recompute maximum values while temporary tweaking maximum scroll ranges", "self", ".", "__computeScrollMax", "(", "zoom", ")", ";", "}", "else", "{", "// Keep zoom when not defined", "zoom", "=", "self", ".", "__zoomLevel", ";", "}", "if", "(", "!", "self", ".", "options", ".", "scrollingX", ")", "{", "left", "=", "self", ".", "__scrollLeft", ";", "}", "else", "{", "if", "(", "self", ".", "options", ".", "paging", ")", "{", "left", "=", "Math", ".", "round", "(", "left", "/", "self", ".", "__clientWidth", ")", "*", "self", ".", "__clientWidth", ";", "}", "else", "if", "(", "self", ".", "options", ".", "snapping", ")", "{", "left", "=", "Math", ".", "round", "(", "left", "/", "self", ".", "__snapWidth", ")", "*", "self", ".", "__snapWidth", ";", "}", "}", "if", "(", "!", "self", ".", "options", ".", "scrollingY", ")", "{", "top", "=", "self", ".", "__scrollTop", ";", "}", "else", "{", "if", "(", "self", ".", "options", ".", "paging", ")", "{", "top", "=", "Math", ".", "round", "(", "top", "/", "self", ".", "__clientHeight", ")", "*", "self", ".", "__clientHeight", ";", "}", "else", "if", "(", "self", ".", "options", ".", "snapping", ")", "{", "top", "=", "Math", ".", "round", "(", "top", "/", "self", ".", "__snapHeight", ")", "*", "self", ".", "__snapHeight", ";", "}", "}", "// Limit for allowed ranges", "left", "=", "Math", ".", "max", "(", "Math", ".", "min", "(", "self", ".", "__maxScrollLeft", ",", "left", ")", ",", "0", ")", ";", "top", "=", "Math", ".", "max", "(", "Math", ".", "min", "(", "self", ".", "__maxScrollTop", ",", "top", ")", ",", "0", ")", ";", "// Don't animate when no change detected, still call publish to make sure", "// that rendered position is really in-sync with internal data", "if", "(", "left", "===", "self", ".", "__scrollLeft", "&&", "top", "===", "self", ".", "__scrollTop", ")", "{", "animate", "=", "false", ";", "}", "// Publish new values", "self", ".", "__publish", "(", "left", ",", "top", ",", "zoom", ",", "animate", ",", "wasResize", ")", ";", "}" ]
Scrolls to the given position. Respect limitations and snapping automatically. @param left {Number} Horizontal scroll position, keeps current if value is <code>null</code> @param top {Number} Vertical scroll position, keeps current if value is <code>null</code> @param animate {Boolean} Whether the scrolling should happen using an animation @param zoom {Number} Zoom level to go to
[ "Scrolls", "to", "the", "given", "position", ".", "Respect", "limitations", "and", "snapping", "automatically", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L5442-L5512
9,508
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
function() { var self = this; clearTimeout(self.__sizerTimeout); var sizer = function() { self.resize(); // if ((self.options.scrollingX && !self.__maxScrollLeft) || (self.options.scrollingY && !self.__maxScrollTop)) { // //self.__sizerTimeout = setTimeout(sizer, 1000); // } }; sizer(); self.__sizerTimeout = setTimeout(sizer, 1000); }
javascript
function() { var self = this; clearTimeout(self.__sizerTimeout); var sizer = function() { self.resize(); // if ((self.options.scrollingX && !self.__maxScrollLeft) || (self.options.scrollingY && !self.__maxScrollTop)) { // //self.__sizerTimeout = setTimeout(sizer, 1000); // } }; sizer(); self.__sizerTimeout = setTimeout(sizer, 1000); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "clearTimeout", "(", "self", ".", "__sizerTimeout", ")", ";", "var", "sizer", "=", "function", "(", ")", "{", "self", ".", "resize", "(", ")", ";", "// if ((self.options.scrollingX && !self.__maxScrollLeft) || (self.options.scrollingY && !self.__maxScrollTop)) {", "// //self.__sizerTimeout = setTimeout(sizer, 1000);", "// }", "}", ";", "sizer", "(", ")", ";", "self", ".", "__sizerTimeout", "=", "setTimeout", "(", "sizer", ",", "1000", ")", ";", "}" ]
If the scroll view isn't sized correctly on start, wait until we have at least some size
[ "If", "the", "scroll", "view", "isn", "t", "sized", "correctly", "on", "start", "wait", "until", "we", "have", "at", "least", "some", "size" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L6071-L6086
9,509
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
function(target) { while (target) { if (target.classList && target.classList.contains(ITEM_CLASS)) { return target; } target = target.parentNode; } return null; }
javascript
function(target) { while (target) { if (target.classList && target.classList.contains(ITEM_CLASS)) { return target; } target = target.parentNode; } return null; }
[ "function", "(", "target", ")", "{", "while", "(", "target", ")", "{", "if", "(", "target", ".", "classList", "&&", "target", ".", "classList", ".", "contains", "(", "ITEM_CLASS", ")", ")", "{", "return", "target", ";", "}", "target", "=", "target", ".", "parentNode", ";", "}", "return", "null", ";", "}" ]
Return the list item from the given target
[ "Return", "the", "list", "item", "from", "the", "given", "target" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L6832-L6840
9,510
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
function(e) { var _this = this, content, buttons; if (Math.abs(e.gesture.deltaY) > 5) { this._didDragUpOrDown = true; } // If we get a drag event, make sure we aren't in another drag, then check if we should // start one if (!this.isDragging && !this._dragOp) { this._startDrag(e); } // No drag still, pass it up if (!this._dragOp) { //ionic.views.ListView.__super__._handleDrag.call(this, e); return; } e.gesture.srcEvent.preventDefault(); this._dragOp.drag(e); }
javascript
function(e) { var _this = this, content, buttons; if (Math.abs(e.gesture.deltaY) > 5) { this._didDragUpOrDown = true; } // If we get a drag event, make sure we aren't in another drag, then check if we should // start one if (!this.isDragging && !this._dragOp) { this._startDrag(e); } // No drag still, pass it up if (!this._dragOp) { //ionic.views.ListView.__super__._handleDrag.call(this, e); return; } e.gesture.srcEvent.preventDefault(); this._dragOp.drag(e); }
[ "function", "(", "e", ")", "{", "var", "_this", "=", "this", ",", "content", ",", "buttons", ";", "if", "(", "Math", ".", "abs", "(", "e", ".", "gesture", ".", "deltaY", ")", ">", "5", ")", "{", "this", ".", "_didDragUpOrDown", "=", "true", ";", "}", "// If we get a drag event, make sure we aren't in another drag, then check if we should", "// start one", "if", "(", "!", "this", ".", "isDragging", "&&", "!", "this", ".", "_dragOp", ")", "{", "this", ".", "_startDrag", "(", "e", ")", ";", "}", "// No drag still, pass it up", "if", "(", "!", "this", ".", "_dragOp", ")", "{", "//ionic.views.ListView.__super__._handleDrag.call(this, e);", "return", ";", "}", "e", ".", "gesture", ".", "srcEvent", ".", "preventDefault", "(", ")", ";", "this", ".", "_dragOp", ".", "drag", "(", "e", ")", ";", "}" ]
Process the drag event to move the item to the left or right.
[ "Process", "the", "drag", "event", "to", "move", "the", "item", "to", "the", "left", "or", "right", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L6914-L6935
9,511
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
shallowCopy
function shallowCopy(src, dst) { if (isArray(src)) { dst = dst || []; for (var i = 0, ii = src.length; i < ii; i++) { dst[i] = src[i]; } } else if (isObject(src)) { dst = dst || {}; for (var key in src) { if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) { dst[key] = src[key]; } } } return dst || src; }
javascript
function shallowCopy(src, dst) { if (isArray(src)) { dst = dst || []; for (var i = 0, ii = src.length; i < ii; i++) { dst[i] = src[i]; } } else if (isObject(src)) { dst = dst || {}; for (var key in src) { if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) { dst[key] = src[key]; } } } return dst || src; }
[ "function", "shallowCopy", "(", "src", ",", "dst", ")", "{", "if", "(", "isArray", "(", "src", ")", ")", "{", "dst", "=", "dst", "||", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "ii", "=", "src", ".", "length", ";", "i", "<", "ii", ";", "i", "++", ")", "{", "dst", "[", "i", "]", "=", "src", "[", "i", "]", ";", "}", "}", "else", "if", "(", "isObject", "(", "src", ")", ")", "{", "dst", "=", "dst", "||", "{", "}", ";", "for", "(", "var", "key", "in", "src", ")", "{", "if", "(", "!", "(", "key", ".", "charAt", "(", "0", ")", "===", "'$'", "&&", "key", ".", "charAt", "(", "1", ")", "===", "'$'", ")", ")", "{", "dst", "[", "key", "]", "=", "src", "[", "key", "]", ";", "}", "}", "}", "return", "dst", "||", "src", ";", "}" ]
Creates a shallow copy of an object, an array or a primitive. Assumes that there are no proto properties for objects.
[ "Creates", "a", "shallow", "copy", "of", "an", "object", "an", "array", "or", "a", "primitive", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L8667-L8685
9,512
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
getter
function getter(obj, path, bindFnToScope) { if (!path) return obj; var keys = path.split('.'); var key; var lastInstance = obj; var len = keys.length; for (var i = 0; i < len; i++) { key = keys[i]; if (obj) { obj = (lastInstance = obj)[key]; } } if (!bindFnToScope && isFunction(obj)) { return bind(lastInstance, obj); } return obj; }
javascript
function getter(obj, path, bindFnToScope) { if (!path) return obj; var keys = path.split('.'); var key; var lastInstance = obj; var len = keys.length; for (var i = 0; i < len; i++) { key = keys[i]; if (obj) { obj = (lastInstance = obj)[key]; } } if (!bindFnToScope && isFunction(obj)) { return bind(lastInstance, obj); } return obj; }
[ "function", "getter", "(", "obj", ",", "path", ",", "bindFnToScope", ")", "{", "if", "(", "!", "path", ")", "return", "obj", ";", "var", "keys", "=", "path", ".", "split", "(", "'.'", ")", ";", "var", "key", ";", "var", "lastInstance", "=", "obj", ";", "var", "len", "=", "keys", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "key", "=", "keys", "[", "i", "]", ";", "if", "(", "obj", ")", "{", "obj", "=", "(", "lastInstance", "=", "obj", ")", "[", "key", "]", ";", "}", "}", "if", "(", "!", "bindFnToScope", "&&", "isFunction", "(", "obj", ")", ")", "{", "return", "bind", "(", "lastInstance", ",", "obj", ")", ";", "}", "return", "obj", ";", "}" ]
Return the value accessible from the object by path. Any undefined traversals are ignored @param {Object} obj starting object @param {String} path path to traverse @param {boolean} [bindFnToScope=true] @returns {Object} value as accessible by path TODO(misko): this function needs to be removed
[ "Return", "the", "value", "accessible", "from", "the", "object", "by", "path", ".", "Any", "undefined", "traversals", "are", "ignored" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L9423-L9440
9,513
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
HashMap
function HashMap(array, isolatedUid) { if (isolatedUid) { var uid = 0; this.nextUid = function() { return ++uid; }; } forEach(array, this.put, this); }
javascript
function HashMap(array, isolatedUid) { if (isolatedUid) { var uid = 0; this.nextUid = function() { return ++uid; }; } forEach(array, this.put, this); }
[ "function", "HashMap", "(", "array", ",", "isolatedUid", ")", "{", "if", "(", "isolatedUid", ")", "{", "var", "uid", "=", "0", ";", "this", ".", "nextUid", "=", "function", "(", ")", "{", "return", "++", "uid", ";", "}", ";", "}", "forEach", "(", "array", ",", "this", ".", "put", ",", "this", ")", ";", "}" ]
HashMap which can use objects as keys
[ "HashMap", "which", "can", "use", "objects", "as", "keys" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L11134-L11142
9,514
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
directiveIsMultiElement
function directiveIsMultiElement(name) { if (hasDirectives.hasOwnProperty(name)) { for (var directive, directives = $injector.get(name + Suffix), i = 0, ii = directives.length; i < ii; i++) { directive = directives[i]; if (directive.multiElement) { return true; } } } return false; }
javascript
function directiveIsMultiElement(name) { if (hasDirectives.hasOwnProperty(name)) { for (var directive, directives = $injector.get(name + Suffix), i = 0, ii = directives.length; i < ii; i++) { directive = directives[i]; if (directive.multiElement) { return true; } } } return false; }
[ "function", "directiveIsMultiElement", "(", "name", ")", "{", "if", "(", "hasDirectives", ".", "hasOwnProperty", "(", "name", ")", ")", "{", "for", "(", "var", "directive", ",", "directives", "=", "$injector", ".", "get", "(", "name", "+", "Suffix", ")", ",", "i", "=", "0", ",", "ii", "=", "directives", ".", "length", ";", "i", "<", "ii", ";", "i", "++", ")", "{", "directive", "=", "directives", "[", "i", "]", ";", "if", "(", "directive", ".", "multiElement", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
looks up the directive and returns true if it is a multi-element directive, and therefore requires DOM nodes between -start and -end markers to be grouped together. @param {string} name name of the directive to look up. @returns true if directive was registered as multi-element.
[ "looks", "up", "the", "directive", "and", "returns", "true", "if", "it", "is", "a", "multi", "-", "element", "directive", "and", "therefore", "requires", "DOM", "nodes", "between", "-", "start", "and", "-", "end", "markers", "to", "be", "grouped", "together", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L15616-L15627
9,515
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
mergeTemplateAttributes
function mergeTemplateAttributes(dst, src) { var srcAttr = src.$attr, dstAttr = dst.$attr, $element = dst.$$element; // reapply the old attributes to the new element forEach(dst, function(value, key) { if (key.charAt(0) != '$') { if (src[key] && src[key] !== value) { value += (key === 'style' ? ';' : ' ') + src[key]; } dst.$set(key, value, true, srcAttr[key]); } }); // copy the new attributes on the old attrs object forEach(src, function(value, key) { if (key == 'class') { safeAddClass($element, value); dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value; } else if (key == 'style') { $element.attr('style', $element.attr('style') + ';' + value); dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value; // `dst` will never contain hasOwnProperty as DOM parser won't let it. // You will get an "InvalidCharacterError: DOM Exception 5" error if you // have an attribute like "has-own-property" or "data-has-own-property", etc. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) { dst[key] = value; dstAttr[key] = srcAttr[key]; } }); }
javascript
function mergeTemplateAttributes(dst, src) { var srcAttr = src.$attr, dstAttr = dst.$attr, $element = dst.$$element; // reapply the old attributes to the new element forEach(dst, function(value, key) { if (key.charAt(0) != '$') { if (src[key] && src[key] !== value) { value += (key === 'style' ? ';' : ' ') + src[key]; } dst.$set(key, value, true, srcAttr[key]); } }); // copy the new attributes on the old attrs object forEach(src, function(value, key) { if (key == 'class') { safeAddClass($element, value); dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value; } else if (key == 'style') { $element.attr('style', $element.attr('style') + ';' + value); dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value; // `dst` will never contain hasOwnProperty as DOM parser won't let it. // You will get an "InvalidCharacterError: DOM Exception 5" error if you // have an attribute like "has-own-property" or "data-has-own-property", etc. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) { dst[key] = value; dstAttr[key] = srcAttr[key]; } }); }
[ "function", "mergeTemplateAttributes", "(", "dst", ",", "src", ")", "{", "var", "srcAttr", "=", "src", ".", "$attr", ",", "dstAttr", "=", "dst", ".", "$attr", ",", "$element", "=", "dst", ".", "$$element", ";", "// reapply the old attributes to the new element", "forEach", "(", "dst", ",", "function", "(", "value", ",", "key", ")", "{", "if", "(", "key", ".", "charAt", "(", "0", ")", "!=", "'$'", ")", "{", "if", "(", "src", "[", "key", "]", "&&", "src", "[", "key", "]", "!==", "value", ")", "{", "value", "+=", "(", "key", "===", "'style'", "?", "';'", ":", "' '", ")", "+", "src", "[", "key", "]", ";", "}", "dst", ".", "$set", "(", "key", ",", "value", ",", "true", ",", "srcAttr", "[", "key", "]", ")", ";", "}", "}", ")", ";", "// copy the new attributes on the old attrs object", "forEach", "(", "src", ",", "function", "(", "value", ",", "key", ")", "{", "if", "(", "key", "==", "'class'", ")", "{", "safeAddClass", "(", "$element", ",", "value", ")", ";", "dst", "[", "'class'", "]", "=", "(", "dst", "[", "'class'", "]", "?", "dst", "[", "'class'", "]", "+", "' '", ":", "''", ")", "+", "value", ";", "}", "else", "if", "(", "key", "==", "'style'", ")", "{", "$element", ".", "attr", "(", "'style'", ",", "$element", ".", "attr", "(", "'style'", ")", "+", "';'", "+", "value", ")", ";", "dst", "[", "'style'", "]", "=", "(", "dst", "[", "'style'", "]", "?", "dst", "[", "'style'", "]", "+", "';'", ":", "''", ")", "+", "value", ";", "// `dst` will never contain hasOwnProperty as DOM parser won't let it.", "// You will get an \"InvalidCharacterError: DOM Exception 5\" error if you", "// have an attribute like \"has-own-property\" or \"data-has-own-property\", etc.", "}", "else", "if", "(", "key", ".", "charAt", "(", "0", ")", "!=", "'$'", "&&", "!", "dst", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "dst", "[", "key", "]", "=", "value", ";", "dstAttr", "[", "key", "]", "=", "srcAttr", "[", "key", "]", ";", "}", "}", ")", ";", "}" ]
When the element is replaced with HTML template then the new attributes on the template need to be merged with the existing attributes in the DOM. The desired effect is to have both of the attributes present. @param {object} dst destination attributes (original DOM) @param {object} src source attributes (from the directive template)
[ "When", "the", "element", "is", "replaced", "with", "HTML", "template", "then", "the", "new", "attributes", "on", "the", "template", "need", "to", "be", "merged", "with", "the", "existing", "attributes", "in", "the", "DOM", ".", "The", "desired", "effect", "is", "to", "have", "both", "of", "the", "attributes", "present", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L15637-L15668
9,516
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
byPriority
function byPriority(a, b) { var diff = b.priority - a.priority; if (diff !== 0) return diff; if (a.name !== b.name) return (a.name < b.name) ? -1 : 1; return a.index - b.index; }
javascript
function byPriority(a, b) { var diff = b.priority - a.priority; if (diff !== 0) return diff; if (a.name !== b.name) return (a.name < b.name) ? -1 : 1; return a.index - b.index; }
[ "function", "byPriority", "(", "a", ",", "b", ")", "{", "var", "diff", "=", "b", ".", "priority", "-", "a", ".", "priority", ";", "if", "(", "diff", "!==", "0", ")", "return", "diff", ";", "if", "(", "a", ".", "name", "!==", "b", ".", "name", ")", "return", "(", "a", ".", "name", "<", "b", ".", "name", ")", "?", "-", "1", ":", "1", ";", "return", "a", ".", "index", "-", "b", ".", "index", ";", "}" ]
Sorting function for bound directives.
[ "Sorting", "function", "for", "bound", "directives", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L15789-L15794
9,517
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
function(event) { // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have // it. In particular the event is not fired when backspace or delete key are pressed or // when cut operation is performed. // IE10+ implements 'input' event but it erroneously fires under various situations, // e.g. when placeholder changes, or a form is focused. if (event === 'input' && msie <= 11) return false; if (isUndefined(eventSupport[event])) { var divElm = document.createElement('div'); eventSupport[event] = 'on' + event in divElm; } return eventSupport[event]; }
javascript
function(event) { // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have // it. In particular the event is not fired when backspace or delete key are pressed or // when cut operation is performed. // IE10+ implements 'input' event but it erroneously fires under various situations, // e.g. when placeholder changes, or a form is focused. if (event === 'input' && msie <= 11) return false; if (isUndefined(eventSupport[event])) { var divElm = document.createElement('div'); eventSupport[event] = 'on' + event in divElm; } return eventSupport[event]; }
[ "function", "(", "event", ")", "{", "// IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have", "// it. In particular the event is not fired when backspace or delete key are pressed or", "// when cut operation is performed.", "// IE10+ implements 'input' event but it erroneously fires under various situations,", "// e.g. when placeholder changes, or a form is focused.", "if", "(", "event", "===", "'input'", "&&", "msie", "<=", "11", ")", "return", "false", ";", "if", "(", "isUndefined", "(", "eventSupport", "[", "event", "]", ")", ")", "{", "var", "divElm", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "eventSupport", "[", "event", "]", "=", "'on'", "+", "event", "in", "divElm", ";", "}", "return", "eventSupport", "[", "event", "]", ";", "}" ]
jshint +W018
[ "jshint", "+", "W018" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L23760-L23774
9,518
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
urlIsSameOrigin
function urlIsSameOrigin(requestUrl) { var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl; return (parsed.protocol === originUrl.protocol && parsed.host === originUrl.host); }
javascript
function urlIsSameOrigin(requestUrl) { var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl; return (parsed.protocol === originUrl.protocol && parsed.host === originUrl.host); }
[ "function", "urlIsSameOrigin", "(", "requestUrl", ")", "{", "var", "parsed", "=", "(", "isString", "(", "requestUrl", ")", ")", "?", "urlResolve", "(", "requestUrl", ")", ":", "requestUrl", ";", "return", "(", "parsed", ".", "protocol", "===", "originUrl", ".", "protocol", "&&", "parsed", ".", "host", "===", "originUrl", ".", "host", ")", ";", "}" ]
Parse a request URL and determine whether this is a same-origin request as the application document. @param {string|object} requestUrl The url of the request as a string that will be resolved or a parsed URL object. @returns {boolean} Whether the request is for the same origin as the application document.
[ "Parse", "a", "request", "URL", "and", "determine", "whether", "this", "is", "a", "same", "-", "origin", "request", "as", "the", "application", "document", "." ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L24140-L24144
9,519
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
createPredicateFn
function createPredicateFn(expression, comparator, matchAgainstAnyProp) { var predicateFn; if (comparator === true) { comparator = equals; } else if (!isFunction(comparator)) { comparator = function(actual, expected) { if (isObject(actual) || isObject(expected)) { // Prevent an object to be considered equal to a string like `'[object'` return false; } actual = lowercase('' + actual); expected = lowercase('' + expected); return actual.indexOf(expected) !== -1; }; } predicateFn = function(item) { return deepCompare(item, expression, comparator, matchAgainstAnyProp); }; return predicateFn; }
javascript
function createPredicateFn(expression, comparator, matchAgainstAnyProp) { var predicateFn; if (comparator === true) { comparator = equals; } else if (!isFunction(comparator)) { comparator = function(actual, expected) { if (isObject(actual) || isObject(expected)) { // Prevent an object to be considered equal to a string like `'[object'` return false; } actual = lowercase('' + actual); expected = lowercase('' + expected); return actual.indexOf(expected) !== -1; }; } predicateFn = function(item) { return deepCompare(item, expression, comparator, matchAgainstAnyProp); }; return predicateFn; }
[ "function", "createPredicateFn", "(", "expression", ",", "comparator", ",", "matchAgainstAnyProp", ")", "{", "var", "predicateFn", ";", "if", "(", "comparator", "===", "true", ")", "{", "comparator", "=", "equals", ";", "}", "else", "if", "(", "!", "isFunction", "(", "comparator", ")", ")", "{", "comparator", "=", "function", "(", "actual", ",", "expected", ")", "{", "if", "(", "isObject", "(", "actual", ")", "||", "isObject", "(", "expected", ")", ")", "{", "// Prevent an object to be considered equal to a string like `'[object'`", "return", "false", ";", "}", "actual", "=", "lowercase", "(", "''", "+", "actual", ")", ";", "expected", "=", "lowercase", "(", "''", "+", "expected", ")", ";", "return", "actual", ".", "indexOf", "(", "expected", ")", "!==", "-", "1", ";", "}", ";", "}", "predicateFn", "=", "function", "(", "item", ")", "{", "return", "deepCompare", "(", "item", ",", "expression", ",", "comparator", ",", "matchAgainstAnyProp", ")", ";", "}", ";", "return", "predicateFn", ";", "}" ]
Helper functions for `filterFilter`
[ "Helper", "functions", "for", "filterFilter" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L24483-L24506
9,520
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
regExpPrefix
function regExpPrefix(re) { var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source); return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : ''; }
javascript
function regExpPrefix(re) { var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source); return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : ''; }
[ "function", "regExpPrefix", "(", "re", ")", "{", "var", "prefix", "=", "/", "^\\^((?:\\\\[^a-zA-Z0-9]|[^\\\\\\[\\]\\^$*+?.()|{}]+)*)", "/", ".", "exec", "(", "re", ".", "source", ")", ";", "return", "(", "prefix", "!=", "null", ")", "?", "prefix", "[", "1", "]", ".", "replace", "(", "/", "\\\\(.)", "/", "g", ",", "\"$1\"", ")", ":", "''", ";", "}" ]
Returns a string that is a prefix of all strings matching the RegExp
[ "Returns", "a", "string", "that", "is", "a", "prefix", "of", "all", "strings", "matching", "the", "RegExp" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L38394-L38397
9,521
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
function(scope, element, attr) { attr.$observe(ngAttrName, function(value) { if (!value) { element[0].removeAttribute(attrName); } }); }
javascript
function(scope, element, attr) { attr.$observe(ngAttrName, function(value) { if (!value) { element[0].removeAttribute(attrName); } }); }
[ "function", "(", "scope", ",", "element", ",", "attr", ")", "{", "attr", ".", "$observe", "(", "ngAttrName", ",", "function", "(", "value", ")", "{", "if", "(", "!", "value", ")", "{", "element", "[", "0", "]", ".", "removeAttribute", "(", "attrName", ")", ";", "}", "}", ")", ";", "}" ]
it needs to run after the attributes are interpolated
[ "it", "needs", "to", "run", "after", "the", "attributes", "are", "interpolated" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L48701-L48707
9,522
ionic-team/ng-cordova
demo/www/lib/ionic/js/ionic.bundle.js
onContentTap
function onContentTap(gestureEvt) { if (sideMenuCtrl.getOpenAmount() !== 0) { sideMenuCtrl.close(); gestureEvt.gesture.srcEvent.preventDefault(); startCoord = null; primaryScrollAxis = null; } else if (!startCoord) { startCoord = ionic.tap.pointerCoord(gestureEvt.gesture.srcEvent); } }
javascript
function onContentTap(gestureEvt) { if (sideMenuCtrl.getOpenAmount() !== 0) { sideMenuCtrl.close(); gestureEvt.gesture.srcEvent.preventDefault(); startCoord = null; primaryScrollAxis = null; } else if (!startCoord) { startCoord = ionic.tap.pointerCoord(gestureEvt.gesture.srcEvent); } }
[ "function", "onContentTap", "(", "gestureEvt", ")", "{", "if", "(", "sideMenuCtrl", ".", "getOpenAmount", "(", ")", "!==", "0", ")", "{", "sideMenuCtrl", ".", "close", "(", ")", ";", "gestureEvt", ".", "gesture", ".", "srcEvent", ".", "preventDefault", "(", ")", ";", "startCoord", "=", "null", ";", "primaryScrollAxis", "=", "null", ";", "}", "else", "if", "(", "!", "startCoord", ")", "{", "startCoord", "=", "ionic", ".", "tap", ".", "pointerCoord", "(", "gestureEvt", ".", "gesture", ".", "srcEvent", ")", ";", "}", "}" ]
Listen for taps on the content to close the menu
[ "Listen", "for", "taps", "on", "the", "content", "to", "close", "the", "menu" ]
2a401e063eda2889cd54abf17365c22286e32285
https://github.com/ionic-team/ng-cordova/blob/2a401e063eda2889cd54abf17365c22286e32285/demo/www/lib/ionic/js/ionic.bundle.js#L51354-L51363
9,523
twbs/bootlint
src/bootlint.js
sortedColumnClasses
function sortedColumnClasses(classes) { // extract column classes var colClasses = []; while (true) { var match = COL_REGEX.exec(classes); if (!match) { break; } var colClass = match[0]; colClasses.push(colClass); classes = withoutClass(classes, colClass); } colClasses.sort(compareColumnClasses); return classes + ' ' + colClasses.join(' '); }
javascript
function sortedColumnClasses(classes) { // extract column classes var colClasses = []; while (true) { var match = COL_REGEX.exec(classes); if (!match) { break; } var colClass = match[0]; colClasses.push(colClass); classes = withoutClass(classes, colClass); } colClasses.sort(compareColumnClasses); return classes + ' ' + colClasses.join(' '); }
[ "function", "sortedColumnClasses", "(", "classes", ")", "{", "// extract column classes", "var", "colClasses", "=", "[", "]", ";", "while", "(", "true", ")", "{", "var", "match", "=", "COL_REGEX", ".", "exec", "(", "classes", ")", ";", "if", "(", "!", "match", ")", "{", "break", ";", "}", "var", "colClass", "=", "match", "[", "0", "]", ";", "colClasses", ".", "push", "(", "colClass", ")", ";", "classes", "=", "withoutClass", "(", "classes", ",", "colClass", ")", ";", "}", "colClasses", ".", "sort", "(", "compareColumnClasses", ")", ";", "return", "classes", "+", "' '", "+", "colClasses", ".", "join", "(", "' '", ")", ";", "}" ]
Moves any grid column classes to the end of the class string and sorts the grid classes by ascending screen size. @param {string} classes The "class" attribute of a DOM node @returns {string} The processed "class" attribute value
[ "Moves", "any", "grid", "column", "classes", "to", "the", "end", "of", "the", "class", "string", "and", "sorts", "the", "grid", "classes", "by", "ascending", "screen", "size", "." ]
c3f24dcfd3f5f341cc34682c2e487ac3dab6ab78
https://github.com/twbs/bootlint/blob/c3f24dcfd3f5f341cc34682c2e487ac3dab6ab78/src/bootlint.js#L107-L122
9,524
twbs/bootlint
src/location.js
LocationIndex
function LocationIndex(string) { // ensure newline termination if (string[string.length - 1] !== '\n') { string += '\n'; } this._stringLength = string.length; /* * Each triple in _lineStartEndTriples consists of: * [0], the 0-based line index of the line the triple represents * [1], the 0-based code unit index (into the string) of the start of the line (inclusive) * [2], the 0-based code unit index (into the string) of the start of the next line (or the length of the string, if it is the last line) * A line starts with a non-newline character, * and always ends in a newline character, unless it is the very last line in the string. */ this._lineStartEndTriples = [[0, 0]]; var nextLineIndex = 1; var charIndex = 0; while (charIndex < string.length) { charIndex = string.indexOf('\n', charIndex); if (charIndex === -1) { /* istanbul ignore next */ break; } charIndex++;// go past the newline this._lineStartEndTriples[this._lineStartEndTriples.length - 1].push(charIndex); this._lineStartEndTriples.push([nextLineIndex, charIndex]); nextLineIndex++; } this._lineStartEndTriples.pop(); }
javascript
function LocationIndex(string) { // ensure newline termination if (string[string.length - 1] !== '\n') { string += '\n'; } this._stringLength = string.length; /* * Each triple in _lineStartEndTriples consists of: * [0], the 0-based line index of the line the triple represents * [1], the 0-based code unit index (into the string) of the start of the line (inclusive) * [2], the 0-based code unit index (into the string) of the start of the next line (or the length of the string, if it is the last line) * A line starts with a non-newline character, * and always ends in a newline character, unless it is the very last line in the string. */ this._lineStartEndTriples = [[0, 0]]; var nextLineIndex = 1; var charIndex = 0; while (charIndex < string.length) { charIndex = string.indexOf('\n', charIndex); if (charIndex === -1) { /* istanbul ignore next */ break; } charIndex++;// go past the newline this._lineStartEndTriples[this._lineStartEndTriples.length - 1].push(charIndex); this._lineStartEndTriples.push([nextLineIndex, charIndex]); nextLineIndex++; } this._lineStartEndTriples.pop(); }
[ "function", "LocationIndex", "(", "string", ")", "{", "// ensure newline termination", "if", "(", "string", "[", "string", ".", "length", "-", "1", "]", "!==", "'\\n'", ")", "{", "string", "+=", "'\\n'", ";", "}", "this", ".", "_stringLength", "=", "string", ".", "length", ";", "/*\n * Each triple in _lineStartEndTriples consists of:\n * [0], the 0-based line index of the line the triple represents\n * [1], the 0-based code unit index (into the string) of the start of the line (inclusive)\n * [2], the 0-based code unit index (into the string) of the start of the next line (or the length of the string, if it is the last line)\n * A line starts with a non-newline character,\n * and always ends in a newline character, unless it is the very last line in the string.\n */", "this", ".", "_lineStartEndTriples", "=", "[", "[", "0", ",", "0", "]", "]", ";", "var", "nextLineIndex", "=", "1", ";", "var", "charIndex", "=", "0", ";", "while", "(", "charIndex", "<", "string", ".", "length", ")", "{", "charIndex", "=", "string", ".", "indexOf", "(", "'\\n'", ",", "charIndex", ")", ";", "if", "(", "charIndex", "===", "-", "1", ")", "{", "/* istanbul ignore next */", "break", ";", "}", "charIndex", "++", ";", "// go past the newline", "this", ".", "_lineStartEndTriples", "[", "this", ".", "_lineStartEndTriples", ".", "length", "-", "1", "]", ".", "push", "(", "charIndex", ")", ";", "this", ".", "_lineStartEndTriples", ".", "push", "(", "[", "nextLineIndex", ",", "charIndex", "]", ")", ";", "nextLineIndex", "++", ";", "}", "this", ".", "_lineStartEndTriples", ".", "pop", "(", ")", ";", "}" ]
Maps code unit indices into the string to line numbers and column numbers. @param {string} string String to construct the index for @class
[ "Maps", "code", "unit", "indices", "into", "the", "string", "to", "line", "numbers", "and", "column", "numbers", "." ]
c3f24dcfd3f5f341cc34682c2e487ac3dab6ab78
https://github.com/twbs/bootlint/blob/c3f24dcfd3f5f341cc34682c2e487ac3dab6ab78/src/location.js#L23-L53
9,525
wa0x6e/cal-heatmap
src/cal-heatmap.js
w
function w(d, outer) { var width = self.options.cellSize*self._domainType[self.options.subDomain].column(d) + self.options.cellPadding*self._domainType[self.options.subDomain].column(d); if (arguments.length === 2 && outer === true) { return width += self.domainHorizontalLabelWidth + self.options.domainGutter + self.options.domainMargin[1] + self.options.domainMargin[3]; } return width; }
javascript
function w(d, outer) { var width = self.options.cellSize*self._domainType[self.options.subDomain].column(d) + self.options.cellPadding*self._domainType[self.options.subDomain].column(d); if (arguments.length === 2 && outer === true) { return width += self.domainHorizontalLabelWidth + self.options.domainGutter + self.options.domainMargin[1] + self.options.domainMargin[3]; } return width; }
[ "function", "w", "(", "d", ",", "outer", ")", "{", "var", "width", "=", "self", ".", "options", ".", "cellSize", "*", "self", ".", "_domainType", "[", "self", ".", "options", ".", "subDomain", "]", ".", "column", "(", "d", ")", "+", "self", ".", "options", ".", "cellPadding", "*", "self", ".", "_domainType", "[", "self", ".", "options", ".", "subDomain", "]", ".", "column", "(", "d", ")", ";", "if", "(", "arguments", ".", "length", "===", "2", "&&", "outer", "===", "true", ")", "{", "return", "width", "+=", "self", ".", "domainHorizontalLabelWidth", "+", "self", ".", "options", ".", "domainGutter", "+", "self", ".", "options", ".", "domainMargin", "[", "1", "]", "+", "self", ".", "options", ".", "domainMargin", "[", "3", "]", ";", "}", "return", "width", ";", "}" ]
Return the width of the domain block, without the domain gutter @param int d Domain start timestamp
[ "Return", "the", "width", "of", "the", "domain", "block", "without", "the", "domain", "gutter" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L685-L691
9,526
wa0x6e/cal-heatmap
src/cal-heatmap.js
h
function h(d, outer) { var height = self.options.cellSize*self._domainType[self.options.subDomain].row(d) + self.options.cellPadding*self._domainType[self.options.subDomain].row(d); if (arguments.length === 2 && outer === true) { height += self.options.domainGutter + self.domainVerticalLabelHeight + self.options.domainMargin[0] + self.options.domainMargin[2]; } return height; }
javascript
function h(d, outer) { var height = self.options.cellSize*self._domainType[self.options.subDomain].row(d) + self.options.cellPadding*self._domainType[self.options.subDomain].row(d); if (arguments.length === 2 && outer === true) { height += self.options.domainGutter + self.domainVerticalLabelHeight + self.options.domainMargin[0] + self.options.domainMargin[2]; } return height; }
[ "function", "h", "(", "d", ",", "outer", ")", "{", "var", "height", "=", "self", ".", "options", ".", "cellSize", "*", "self", ".", "_domainType", "[", "self", ".", "options", ".", "subDomain", "]", ".", "row", "(", "d", ")", "+", "self", ".", "options", ".", "cellPadding", "*", "self", ".", "_domainType", "[", "self", ".", "options", ".", "subDomain", "]", ".", "row", "(", "d", ")", ";", "if", "(", "arguments", ".", "length", "===", "2", "&&", "outer", "===", "true", ")", "{", "height", "+=", "self", ".", "options", ".", "domainGutter", "+", "self", ".", "domainVerticalLabelHeight", "+", "self", ".", "options", ".", "domainMargin", "[", "0", "]", "+", "self", ".", "options", ".", "domainMargin", "[", "2", "]", ";", "}", "return", "height", ";", "}" ]
Return the height of the domain block, without the domain gutter
[ "Return", "the", "height", "of", "the", "domain", "block", "without", "the", "domain", "gutter" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L694-L700
9,527
wa0x6e/cal-heatmap
src/cal-heatmap.js
validateSelector
function validateSelector(selector, canBeFalse, name) { if (((canBeFalse && selector === false) || selector instanceof Element || typeof selector === "string") && selector !== "") { return true; } throw new Error("The " + name + " is not valid"); }
javascript
function validateSelector(selector, canBeFalse, name) { if (((canBeFalse && selector === false) || selector instanceof Element || typeof selector === "string") && selector !== "") { return true; } throw new Error("The " + name + " is not valid"); }
[ "function", "validateSelector", "(", "selector", ",", "canBeFalse", ",", "name", ")", "{", "if", "(", "(", "(", "canBeFalse", "&&", "selector", "===", "false", ")", "||", "selector", "instanceof", "Element", "||", "typeof", "selector", "===", "\"string\"", ")", "&&", "selector", "!==", "\"\"", ")", "{", "return", "true", ";", "}", "throw", "new", "Error", "(", "\"The \"", "+", "name", "+", "\" is not valid\"", ")", ";", "}" ]
Validate that a queryString is valid @param {Element|string|bool} selector The queryString to test @param {bool} canBeFalse Whether false is an accepted and valid value @param {string} name Name of the tested selector @throws {Error} If the selector is not valid @return {bool} True if the selector is a valid queryString
[ "Validate", "that", "a", "queryString", "is", "valid" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L1171-L1176
9,528
wa0x6e/cal-heatmap
src/cal-heatmap.js
validateDomainType
function validateDomainType() { if (!parent._domainType.hasOwnProperty(options.domain) || options.domain === "min" || options.domain.substring(0, 2) === "x_") { throw new Error("The domain '" + options.domain + "' is not valid"); } if (!parent._domainType.hasOwnProperty(options.subDomain) || options.subDomain === "year") { throw new Error("The subDomain '" + options.subDomain + "' is not valid"); } if (parent._domainType[options.domain].level <= parent._domainType[options.subDomain].level) { throw new Error("'" + options.subDomain + "' is not a valid subDomain to '" + options.domain + "'"); } return true; }
javascript
function validateDomainType() { if (!parent._domainType.hasOwnProperty(options.domain) || options.domain === "min" || options.domain.substring(0, 2) === "x_") { throw new Error("The domain '" + options.domain + "' is not valid"); } if (!parent._domainType.hasOwnProperty(options.subDomain) || options.subDomain === "year") { throw new Error("The subDomain '" + options.subDomain + "' is not valid"); } if (parent._domainType[options.domain].level <= parent._domainType[options.subDomain].level) { throw new Error("'" + options.subDomain + "' is not a valid subDomain to '" + options.domain + "'"); } return true; }
[ "function", "validateDomainType", "(", ")", "{", "if", "(", "!", "parent", ".", "_domainType", ".", "hasOwnProperty", "(", "options", ".", "domain", ")", "||", "options", ".", "domain", "===", "\"min\"", "||", "options", ".", "domain", ".", "substring", "(", "0", ",", "2", ")", "===", "\"x_\"", ")", "{", "throw", "new", "Error", "(", "\"The domain '\"", "+", "options", ".", "domain", "+", "\"' is not valid\"", ")", ";", "}", "if", "(", "!", "parent", ".", "_domainType", ".", "hasOwnProperty", "(", "options", ".", "subDomain", ")", "||", "options", ".", "subDomain", "===", "\"year\"", ")", "{", "throw", "new", "Error", "(", "\"The subDomain '\"", "+", "options", ".", "subDomain", "+", "\"' is not valid\"", ")", ";", "}", "if", "(", "parent", ".", "_domainType", "[", "options", ".", "domain", "]", ".", "level", "<=", "parent", ".", "_domainType", "[", "options", ".", "subDomain", "]", ".", "level", ")", "{", "throw", "new", "Error", "(", "\"'\"", "+", "options", ".", "subDomain", "+", "\"' is not a valid subDomain to '\"", "+", "options", ".", "domain", "+", "\"'\"", ")", ";", "}", "return", "true", ";", "}" ]
Ensure that the domain and subdomain are valid @throw {Error} when domain or subdomain are not valid @return {bool} True if domain and subdomain are valid and compatible
[ "Ensure", "that", "the", "domain", "and", "subdomain", "are", "valid" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L1205-L1219
9,529
wa0x6e/cal-heatmap
src/cal-heatmap.js
autoAlignLabel
function autoAlignLabel() { // Auto-align label, depending on it's position if (!settings.hasOwnProperty("label") || (settings.hasOwnProperty("label") && !settings.label.hasOwnProperty("align"))) { switch(options.label.position) { case "left": options.label.align = "right"; break; case "right": options.label.align = "left"; break; default: options.label.align = "center"; } if (options.label.rotate === "left") { options.label.align = "right"; } else if (options.label.rotate === "right") { options.label.align = "left"; } } if (!settings.hasOwnProperty("label") || (settings.hasOwnProperty("label") && !settings.label.hasOwnProperty("offset"))) { if (options.label.position === "left" || options.label.position === "right") { options.label.offset = { x: 10, y: 15 }; } } }
javascript
function autoAlignLabel() { // Auto-align label, depending on it's position if (!settings.hasOwnProperty("label") || (settings.hasOwnProperty("label") && !settings.label.hasOwnProperty("align"))) { switch(options.label.position) { case "left": options.label.align = "right"; break; case "right": options.label.align = "left"; break; default: options.label.align = "center"; } if (options.label.rotate === "left") { options.label.align = "right"; } else if (options.label.rotate === "right") { options.label.align = "left"; } } if (!settings.hasOwnProperty("label") || (settings.hasOwnProperty("label") && !settings.label.hasOwnProperty("offset"))) { if (options.label.position === "left" || options.label.position === "right") { options.label.offset = { x: 10, y: 15 }; } } }
[ "function", "autoAlignLabel", "(", ")", "{", "// Auto-align label, depending on it's position", "if", "(", "!", "settings", ".", "hasOwnProperty", "(", "\"label\"", ")", "||", "(", "settings", ".", "hasOwnProperty", "(", "\"label\"", ")", "&&", "!", "settings", ".", "label", ".", "hasOwnProperty", "(", "\"align\"", ")", ")", ")", "{", "switch", "(", "options", ".", "label", ".", "position", ")", "{", "case", "\"left\"", ":", "options", ".", "label", ".", "align", "=", "\"right\"", ";", "break", ";", "case", "\"right\"", ":", "options", ".", "label", ".", "align", "=", "\"left\"", ";", "break", ";", "default", ":", "options", ".", "label", ".", "align", "=", "\"center\"", ";", "}", "if", "(", "options", ".", "label", ".", "rotate", "===", "\"left\"", ")", "{", "options", ".", "label", ".", "align", "=", "\"right\"", ";", "}", "else", "if", "(", "options", ".", "label", ".", "rotate", "===", "\"right\"", ")", "{", "options", ".", "label", ".", "align", "=", "\"left\"", ";", "}", "}", "if", "(", "!", "settings", ".", "hasOwnProperty", "(", "\"label\"", ")", "||", "(", "settings", ".", "hasOwnProperty", "(", "\"label\"", ")", "&&", "!", "settings", ".", "label", ".", "hasOwnProperty", "(", "\"offset\"", ")", ")", ")", "{", "if", "(", "options", ".", "label", ".", "position", "===", "\"left\"", "||", "options", ".", "label", ".", "position", "===", "\"right\"", ")", "{", "options", ".", "label", ".", "offset", "=", "{", "x", ":", "10", ",", "y", ":", "15", "}", ";", "}", "}", "}" ]
Fine-tune the label alignement depending on its position @return void
[ "Fine", "-", "tune", "the", "label", "alignement", "depending", "on", "its", "position" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L1226-L1255
9,530
wa0x6e/cal-heatmap
src/cal-heatmap.js
autoAddLegendMargin
function autoAddLegendMargin() { switch(options.legendVerticalPosition) { case "top": options.legendMargin[2] = parent.DEFAULT_LEGEND_MARGIN; break; case "bottom": options.legendMargin[0] = parent.DEFAULT_LEGEND_MARGIN; break; case "middle": case "center": options.legendMargin[options.legendHorizontalPosition === "right" ? 3 : 1] = parent.DEFAULT_LEGEND_MARGIN; } }
javascript
function autoAddLegendMargin() { switch(options.legendVerticalPosition) { case "top": options.legendMargin[2] = parent.DEFAULT_LEGEND_MARGIN; break; case "bottom": options.legendMargin[0] = parent.DEFAULT_LEGEND_MARGIN; break; case "middle": case "center": options.legendMargin[options.legendHorizontalPosition === "right" ? 3 : 1] = parent.DEFAULT_LEGEND_MARGIN; } }
[ "function", "autoAddLegendMargin", "(", ")", "{", "switch", "(", "options", ".", "legendVerticalPosition", ")", "{", "case", "\"top\"", ":", "options", ".", "legendMargin", "[", "2", "]", "=", "parent", ".", "DEFAULT_LEGEND_MARGIN", ";", "break", ";", "case", "\"bottom\"", ":", "options", ".", "legendMargin", "[", "0", "]", "=", "parent", ".", "DEFAULT_LEGEND_MARGIN", ";", "break", ";", "case", "\"middle\"", ":", "case", "\"center\"", ":", "options", ".", "legendMargin", "[", "options", ".", "legendHorizontalPosition", "===", "\"right\"", "?", "3", ":", "1", "]", "=", "parent", ".", "DEFAULT_LEGEND_MARGIN", ";", "}", "}" ]
If not specified, add some margin around the legend depending on its position @return void
[ "If", "not", "specified", "add", "some", "margin", "around", "the", "legend", "depending", "on", "its", "position" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L1262-L1274
9,531
wa0x6e/cal-heatmap
src/cal-heatmap.js
expandMarginSetting
function expandMarginSetting(value) { if (typeof value === "number") { value = [value]; } if (!Array.isArray(value)) { console.log("Margin only takes an integer or an array of integers"); value = [0]; } switch(value.length) { case 1: return [value[0], value[0], value[0], value[0]]; case 2: return [value[0], value[1], value[0], value[1]]; case 3: return [value[0], value[1], value[2], value[1]]; case 4: return value; default: return value.slice(0, 4); } }
javascript
function expandMarginSetting(value) { if (typeof value === "number") { value = [value]; } if (!Array.isArray(value)) { console.log("Margin only takes an integer or an array of integers"); value = [0]; } switch(value.length) { case 1: return [value[0], value[0], value[0], value[0]]; case 2: return [value[0], value[1], value[0], value[1]]; case 3: return [value[0], value[1], value[2], value[1]]; case 4: return value; default: return value.slice(0, 4); } }
[ "function", "expandMarginSetting", "(", "value", ")", "{", "if", "(", "typeof", "value", "===", "\"number\"", ")", "{", "value", "=", "[", "value", "]", ";", "}", "if", "(", "!", "Array", ".", "isArray", "(", "value", ")", ")", "{", "console", ".", "log", "(", "\"Margin only takes an integer or an array of integers\"", ")", ";", "value", "=", "[", "0", "]", ";", "}", "switch", "(", "value", ".", "length", ")", "{", "case", "1", ":", "return", "[", "value", "[", "0", "]", ",", "value", "[", "0", "]", ",", "value", "[", "0", "]", ",", "value", "[", "0", "]", "]", ";", "case", "2", ":", "return", "[", "value", "[", "0", "]", ",", "value", "[", "1", "]", ",", "value", "[", "0", "]", ",", "value", "[", "1", "]", "]", ";", "case", "3", ":", "return", "[", "value", "[", "0", "]", ",", "value", "[", "1", "]", ",", "value", "[", "2", "]", ",", "value", "[", "1", "]", "]", ";", "case", "4", ":", "return", "value", ";", "default", ":", "return", "value", ".", "slice", "(", "0", ",", "4", ")", ";", "}", "}" ]
Expand a number of an array of numbers to an usable 4 values array @param {integer|array} value @return {array} array
[ "Expand", "a", "number", "of", "an", "array", "of", "numbers", "to", "an", "usable", "4", "values", "array" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L1282-L1304
9,532
wa0x6e/cal-heatmap
src/cal-heatmap.js
addStyle
function addStyle(element) { if (parent.legendScale === null) { return false; } element.attr("fill", function(d) { if (d.v === null && (options.hasOwnProperty("considerMissingDataAsZero") && !options.considerMissingDataAsZero)) { if (options.legendColors.hasOwnProperty("base")) { return options.legendColors.base; } } if (options.legendColors !== null && options.legendColors.hasOwnProperty("empty") && (d.v === 0 || (d.v === null && options.hasOwnProperty("considerMissingDataAsZero") && options.considerMissingDataAsZero)) ) { return options.legendColors.empty; } if (d.v < 0 && options.legend[0] > 0 && options.legendColors !== null && options.legendColors.hasOwnProperty("overflow")) { return options.legendColors.overflow; } return parent.legendScale(Math.min(d.v, options.legend[options.legend.length-1])); }); }
javascript
function addStyle(element) { if (parent.legendScale === null) { return false; } element.attr("fill", function(d) { if (d.v === null && (options.hasOwnProperty("considerMissingDataAsZero") && !options.considerMissingDataAsZero)) { if (options.legendColors.hasOwnProperty("base")) { return options.legendColors.base; } } if (options.legendColors !== null && options.legendColors.hasOwnProperty("empty") && (d.v === 0 || (d.v === null && options.hasOwnProperty("considerMissingDataAsZero") && options.considerMissingDataAsZero)) ) { return options.legendColors.empty; } if (d.v < 0 && options.legend[0] > 0 && options.legendColors !== null && options.legendColors.hasOwnProperty("overflow")) { return options.legendColors.overflow; } return parent.legendScale(Math.min(d.v, options.legend[options.legend.length-1])); }); }
[ "function", "addStyle", "(", "element", ")", "{", "if", "(", "parent", ".", "legendScale", "===", "null", ")", "{", "return", "false", ";", "}", "element", ".", "attr", "(", "\"fill\"", ",", "function", "(", "d", ")", "{", "if", "(", "d", ".", "v", "===", "null", "&&", "(", "options", ".", "hasOwnProperty", "(", "\"considerMissingDataAsZero\"", ")", "&&", "!", "options", ".", "considerMissingDataAsZero", ")", ")", "{", "if", "(", "options", ".", "legendColors", ".", "hasOwnProperty", "(", "\"base\"", ")", ")", "{", "return", "options", ".", "legendColors", ".", "base", ";", "}", "}", "if", "(", "options", ".", "legendColors", "!==", "null", "&&", "options", ".", "legendColors", ".", "hasOwnProperty", "(", "\"empty\"", ")", "&&", "(", "d", ".", "v", "===", "0", "||", "(", "d", ".", "v", "===", "null", "&&", "options", ".", "hasOwnProperty", "(", "\"considerMissingDataAsZero\"", ")", "&&", "options", ".", "considerMissingDataAsZero", ")", ")", ")", "{", "return", "options", ".", "legendColors", ".", "empty", ";", "}", "if", "(", "d", ".", "v", "<", "0", "&&", "options", ".", "legend", "[", "0", "]", ">", "0", "&&", "options", ".", "legendColors", "!==", "null", "&&", "options", ".", "legendColors", ".", "hasOwnProperty", "(", "\"overflow\"", ")", ")", "{", "return", "options", ".", "legendColors", ".", "overflow", ";", "}", "return", "parent", ".", "legendScale", "(", "Math", ".", "min", "(", "d", ".", "v", ",", "options", ".", "legend", "[", "options", ".", "legend", ".", "length", "-", "1", "]", ")", ")", ";", "}", ")", ";", "}" ]
Colorize the cell via a style attribute if enabled
[ "Colorize", "the", "cell", "via", "a", "style", "attribute", "if", "enabled" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L1395-L1419
9,533
wa0x6e/cal-heatmap
src/cal-heatmap.js
function(start) { "use strict"; var parent = this; return this.triggerEvent("afterLoadPreviousDomain", function() { var subDomain = parent.getSubDomain(start); return [subDomain.shift(), subDomain.pop()]; }); }
javascript
function(start) { "use strict"; var parent = this; return this.triggerEvent("afterLoadPreviousDomain", function() { var subDomain = parent.getSubDomain(start); return [subDomain.shift(), subDomain.pop()]; }); }
[ "function", "(", "start", ")", "{", "\"use strict\"", ";", "var", "parent", "=", "this", ";", "return", "this", ".", "triggerEvent", "(", "\"afterLoadPreviousDomain\"", ",", "function", "(", ")", "{", "var", "subDomain", "=", "parent", ".", "getSubDomain", "(", "start", ")", ";", "return", "[", "subDomain", ".", "shift", "(", ")", ",", "subDomain", ".", "pop", "(", ")", "]", ";", "}", ")", ";", "}" ]
Event triggered after shifting the calendar one domain back @param Date start Domain start date @param Date end Domain end date
[ "Event", "triggered", "after", "shifting", "the", "calendar", "one", "domain", "back" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L1564-L1572
9,534
wa0x6e/cal-heatmap
src/cal-heatmap.js
function(n) { "use strict"; if (this._minDomainReached || n === 0) { return false; } var bound = this.loadNewDomains(this.NAVIGATE_LEFT, this.getDomain(this.getDomainKeys()[0], -n).reverse()); this.afterLoadPreviousDomain(bound.start); this.checkIfMinDomainIsReached(bound.start, bound.end); return true; }
javascript
function(n) { "use strict"; if (this._minDomainReached || n === 0) { return false; } var bound = this.loadNewDomains(this.NAVIGATE_LEFT, this.getDomain(this.getDomainKeys()[0], -n).reverse()); this.afterLoadPreviousDomain(bound.start); this.checkIfMinDomainIsReached(bound.start, bound.end); return true; }
[ "function", "(", "n", ")", "{", "\"use strict\"", ";", "if", "(", "this", ".", "_minDomainReached", "||", "n", "===", "0", ")", "{", "return", "false", ";", "}", "var", "bound", "=", "this", ".", "loadNewDomains", "(", "this", ".", "NAVIGATE_LEFT", ",", "this", ".", "getDomain", "(", "this", ".", "getDomainKeys", "(", ")", "[", "0", "]", ",", "-", "n", ")", ".", "reverse", "(", ")", ")", ";", "this", ".", "afterLoadPreviousDomain", "(", "bound", ".", "start", ")", ";", "this", ".", "checkIfMinDomainIsReached", "(", "bound", ".", "start", ",", "bound", ".", "end", ")", ";", "return", "true", ";", "}" ]
Shift the calendar one domain backward The previous domain is loaded only if it's not beyond the minDate @param int n Number of domains to load @return bool True if the previous domain was loaded, else false
[ "Shift", "the", "calendar", "one", "domain", "backward" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L1727-L1740
9,535
wa0x6e/cal-heatmap
src/cal-heatmap.js
function() { "use strict"; return this._domains.keys() .map(function(d) { return parseInt(d, 10); }) .sort(function(a,b) { return a-b; }); }
javascript
function() { "use strict"; return this._domains.keys() .map(function(d) { return parseInt(d, 10); }) .sort(function(a,b) { return a-b; }); }
[ "function", "(", ")", "{", "\"use strict\"", ";", "return", "this", ".", "_domains", ".", "keys", "(", ")", ".", "map", "(", "function", "(", "d", ")", "{", "return", "parseInt", "(", "d", ",", "10", ")", ";", "}", ")", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "a", "-", "b", ";", "}", ")", ";", "}" ]
Return the list of the calendar's domain timestamp @return Array a sorted array of timestamp
[ "Return", "the", "list", "of", "the", "calendar", "s", "domain", "timestamp" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L1830-L1836
9,536
wa0x6e/cal-heatmap
src/cal-heatmap.js
function(d) { "use strict"; d = new Date(d); if (this.options.highlight.length > 0) { for (var i in this.options.highlight) { if (this.dateIsEqual(this.options.highlight[i], d)) { return this.isNow(this.options.highlight[i]) ? " highlight-now": " highlight"; } } } return ""; }
javascript
function(d) { "use strict"; d = new Date(d); if (this.options.highlight.length > 0) { for (var i in this.options.highlight) { if (this.dateIsEqual(this.options.highlight[i], d)) { return this.isNow(this.options.highlight[i]) ? " highlight-now": " highlight"; } } } return ""; }
[ "function", "(", "d", ")", "{", "\"use strict\"", ";", "d", "=", "new", "Date", "(", "d", ")", ";", "if", "(", "this", ".", "options", ".", "highlight", ".", "length", ">", "0", ")", "{", "for", "(", "var", "i", "in", "this", ".", "options", ".", "highlight", ")", "{", "if", "(", "this", ".", "dateIsEqual", "(", "this", ".", "options", ".", "highlight", "[", "i", "]", ",", "d", ")", ")", "{", "return", "this", ".", "isNow", "(", "this", ".", "options", ".", "highlight", "[", "i", "]", ")", "?", "\" highlight-now\"", ":", "\" highlight\"", ";", "}", "}", "}", "return", "\"\"", ";", "}" ]
Return a classname if the specified date should be highlighted @param timestamp date Date of the current subDomain @return String the highlight class
[ "Return", "a", "classname", "if", "the", "specified", "date", "should", "be", "highlighted" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L1900-L1913
9,537
wa0x6e/cal-heatmap
src/cal-heatmap.js
function(dateA, dateB) { "use strict"; if(!(dateA instanceof Date)) { dateA = new Date(dateA); } if (!(dateB instanceof Date)) { dateB = new Date(dateB); } switch(this.options.subDomain) { case "x_min": case "min": return dateA.getFullYear() === dateB.getFullYear() && dateA.getMonth() === dateB.getMonth() && dateA.getDate() === dateB.getDate() && dateA.getHours() === dateB.getHours() && dateA.getMinutes() === dateB.getMinutes(); case "x_hour": case "hour": return dateA.getFullYear() === dateB.getFullYear() && dateA.getMonth() === dateB.getMonth() && dateA.getDate() === dateB.getDate() && dateA.getHours() === dateB.getHours(); case "x_day": case "day": return dateA.getFullYear() === dateB.getFullYear() && dateA.getMonth() === dateB.getMonth() && dateA.getDate() === dateB.getDate(); case "x_week": case "week": return dateA.getFullYear() === dateB.getFullYear() && this.getWeekNumber(dateA) === this.getWeekNumber(dateB); case "x_month": case "month": return dateA.getFullYear() === dateB.getFullYear() && dateA.getMonth() === dateB.getMonth(); default: return false; } }
javascript
function(dateA, dateB) { "use strict"; if(!(dateA instanceof Date)) { dateA = new Date(dateA); } if (!(dateB instanceof Date)) { dateB = new Date(dateB); } switch(this.options.subDomain) { case "x_min": case "min": return dateA.getFullYear() === dateB.getFullYear() && dateA.getMonth() === dateB.getMonth() && dateA.getDate() === dateB.getDate() && dateA.getHours() === dateB.getHours() && dateA.getMinutes() === dateB.getMinutes(); case "x_hour": case "hour": return dateA.getFullYear() === dateB.getFullYear() && dateA.getMonth() === dateB.getMonth() && dateA.getDate() === dateB.getDate() && dateA.getHours() === dateB.getHours(); case "x_day": case "day": return dateA.getFullYear() === dateB.getFullYear() && dateA.getMonth() === dateB.getMonth() && dateA.getDate() === dateB.getDate(); case "x_week": case "week": return dateA.getFullYear() === dateB.getFullYear() && this.getWeekNumber(dateA) === this.getWeekNumber(dateB); case "x_month": case "month": return dateA.getFullYear() === dateB.getFullYear() && dateA.getMonth() === dateB.getMonth(); default: return false; } }
[ "function", "(", "dateA", ",", "dateB", ")", "{", "\"use strict\"", ";", "if", "(", "!", "(", "dateA", "instanceof", "Date", ")", ")", "{", "dateA", "=", "new", "Date", "(", "dateA", ")", ";", "}", "if", "(", "!", "(", "dateB", "instanceof", "Date", ")", ")", "{", "dateB", "=", "new", "Date", "(", "dateB", ")", ";", "}", "switch", "(", "this", ".", "options", ".", "subDomain", ")", "{", "case", "\"x_min\"", ":", "case", "\"min\"", ":", "return", "dateA", ".", "getFullYear", "(", ")", "===", "dateB", ".", "getFullYear", "(", ")", "&&", "dateA", ".", "getMonth", "(", ")", "===", "dateB", ".", "getMonth", "(", ")", "&&", "dateA", ".", "getDate", "(", ")", "===", "dateB", ".", "getDate", "(", ")", "&&", "dateA", ".", "getHours", "(", ")", "===", "dateB", ".", "getHours", "(", ")", "&&", "dateA", ".", "getMinutes", "(", ")", "===", "dateB", ".", "getMinutes", "(", ")", ";", "case", "\"x_hour\"", ":", "case", "\"hour\"", ":", "return", "dateA", ".", "getFullYear", "(", ")", "===", "dateB", ".", "getFullYear", "(", ")", "&&", "dateA", ".", "getMonth", "(", ")", "===", "dateB", ".", "getMonth", "(", ")", "&&", "dateA", ".", "getDate", "(", ")", "===", "dateB", ".", "getDate", "(", ")", "&&", "dateA", ".", "getHours", "(", ")", "===", "dateB", ".", "getHours", "(", ")", ";", "case", "\"x_day\"", ":", "case", "\"day\"", ":", "return", "dateA", ".", "getFullYear", "(", ")", "===", "dateB", ".", "getFullYear", "(", ")", "&&", "dateA", ".", "getMonth", "(", ")", "===", "dateB", ".", "getMonth", "(", ")", "&&", "dateA", ".", "getDate", "(", ")", "===", "dateB", ".", "getDate", "(", ")", ";", "case", "\"x_week\"", ":", "case", "\"week\"", ":", "return", "dateA", ".", "getFullYear", "(", ")", "===", "dateB", ".", "getFullYear", "(", ")", "&&", "this", ".", "getWeekNumber", "(", "dateA", ")", "===", "this", ".", "getWeekNumber", "(", "dateB", ")", ";", "case", "\"x_month\"", ":", "case", "\"month\"", ":", "return", "dateA", ".", "getFullYear", "(", ")", "===", "dateB", ".", "getFullYear", "(", ")", "&&", "dateA", ".", "getMonth", "(", ")", "===", "dateB", ".", "getMonth", "(", ")", ";", "default", ":", "return", "false", ";", "}", "}" ]
Return whether 2 dates are equals This function is subdomain-aware, and dates comparison are dependent of the subdomain @param Date dateA First date to compare @param Date dateB Secon date to compare @return bool true if the 2 dates are equals /* jshint maxcomplexity: false
[ "Return", "whether", "2", "dates", "are", "equals", "This", "function", "is", "subdomain", "-", "aware", "and", "dates", "comparison", "are", "dependent", "of", "the", "subdomain" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L1938-L1979
9,538
wa0x6e/cal-heatmap
src/cal-heatmap.js
function(dateA, dateB) { "use strict"; if(!(dateA instanceof Date)) { dateA = new Date(dateA); } if (!(dateB instanceof Date)) { dateB = new Date(dateB); } function normalizedMillis(date, subdomain) { switch(subdomain) { case "x_min": case "min": return new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes()).getTime(); case "x_hour": case "hour": return new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours()).getTime(); case "x_day": case "day": return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime(); case "x_week": case "week": case "x_month": case "month": return new Date(date.getFullYear(), date.getMonth()).getTime(); default: return date.getTime(); } } return normalizedMillis(dateA, this.options.subDomain) < normalizedMillis(dateB, this.options.subDomain); }
javascript
function(dateA, dateB) { "use strict"; if(!(dateA instanceof Date)) { dateA = new Date(dateA); } if (!(dateB instanceof Date)) { dateB = new Date(dateB); } function normalizedMillis(date, subdomain) { switch(subdomain) { case "x_min": case "min": return new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes()).getTime(); case "x_hour": case "hour": return new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours()).getTime(); case "x_day": case "day": return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime(); case "x_week": case "week": case "x_month": case "month": return new Date(date.getFullYear(), date.getMonth()).getTime(); default: return date.getTime(); } } return normalizedMillis(dateA, this.options.subDomain) < normalizedMillis(dateB, this.options.subDomain); }
[ "function", "(", "dateA", ",", "dateB", ")", "{", "\"use strict\"", ";", "if", "(", "!", "(", "dateA", "instanceof", "Date", ")", ")", "{", "dateA", "=", "new", "Date", "(", "dateA", ")", ";", "}", "if", "(", "!", "(", "dateB", "instanceof", "Date", ")", ")", "{", "dateB", "=", "new", "Date", "(", "dateB", ")", ";", "}", "function", "normalizedMillis", "(", "date", ",", "subdomain", ")", "{", "switch", "(", "subdomain", ")", "{", "case", "\"x_min\"", ":", "case", "\"min\"", ":", "return", "new", "Date", "(", "date", ".", "getFullYear", "(", ")", ",", "date", ".", "getMonth", "(", ")", ",", "date", ".", "getDate", "(", ")", ",", "date", ".", "getHours", "(", ")", ",", "date", ".", "getMinutes", "(", ")", ")", ".", "getTime", "(", ")", ";", "case", "\"x_hour\"", ":", "case", "\"hour\"", ":", "return", "new", "Date", "(", "date", ".", "getFullYear", "(", ")", ",", "date", ".", "getMonth", "(", ")", ",", "date", ".", "getDate", "(", ")", ",", "date", ".", "getHours", "(", ")", ")", ".", "getTime", "(", ")", ";", "case", "\"x_day\"", ":", "case", "\"day\"", ":", "return", "new", "Date", "(", "date", ".", "getFullYear", "(", ")", ",", "date", ".", "getMonth", "(", ")", ",", "date", ".", "getDate", "(", ")", ")", ".", "getTime", "(", ")", ";", "case", "\"x_week\"", ":", "case", "\"week\"", ":", "case", "\"x_month\"", ":", "case", "\"month\"", ":", "return", "new", "Date", "(", "date", ".", "getFullYear", "(", ")", ",", "date", ".", "getMonth", "(", ")", ")", ".", "getTime", "(", ")", ";", "default", ":", "return", "date", ".", "getTime", "(", ")", ";", "}", "}", "return", "normalizedMillis", "(", "dateA", ",", "this", ".", "options", ".", "subDomain", ")", "<", "normalizedMillis", "(", "dateB", ",", "this", ".", "options", ".", "subDomain", ")", ";", "}" ]
Returns wether or not dateA is less than or equal to dateB. This function is subdomain aware. Performs automatic conversion of values. @param dateA may be a number or a Date @param dateB may be a number or a Date @returns {boolean}
[ "Returns", "wether", "or", "not", "dateA", "is", "less", "than", "or", "equal", "to", "dateB", ".", "This", "function", "is", "subdomain", "aware", ".", "Performs", "automatic", "conversion", "of", "values", "." ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L1989-L2023
9,539
wa0x6e/cal-heatmap
src/cal-heatmap.js
function(d) { "use strict"; var f = this.options.weekStartOnMonday === true ? d3.time.format("%W"): d3.time.format("%U"); return f(d); }
javascript
function(d) { "use strict"; var f = this.options.weekStartOnMonday === true ? d3.time.format("%W"): d3.time.format("%U"); return f(d); }
[ "function", "(", "d", ")", "{", "\"use strict\"", ";", "var", "f", "=", "this", ".", "options", ".", "weekStartOnMonday", "===", "true", "?", "d3", ".", "time", ".", "format", "(", "\"%W\"", ")", ":", "d3", ".", "time", ".", "format", "(", "\"%U\"", ")", ";", "return", "f", "(", "d", ")", ";", "}" ]
Return the week number of the year Monday as the first day of the week @return int Week number [0-53]
[ "Return", "the", "week", "number", "of", "the", "year", "Monday", "as", "the", "first", "day", "of", "the", "week" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L2042-L2047
9,540
wa0x6e/cal-heatmap
src/cal-heatmap.js
function (d) { "use strict"; if (typeof d === "number") { d = new Date(d); } var monthFirstWeekNumber = this.getWeekNumber(new Date(d.getFullYear(), d.getMonth())); return this.getWeekNumber(d) - monthFirstWeekNumber - 1; }
javascript
function (d) { "use strict"; if (typeof d === "number") { d = new Date(d); } var monthFirstWeekNumber = this.getWeekNumber(new Date(d.getFullYear(), d.getMonth())); return this.getWeekNumber(d) - monthFirstWeekNumber - 1; }
[ "function", "(", "d", ")", "{", "\"use strict\"", ";", "if", "(", "typeof", "d", "===", "\"number\"", ")", "{", "d", "=", "new", "Date", "(", "d", ")", ";", "}", "var", "monthFirstWeekNumber", "=", "this", ".", "getWeekNumber", "(", "new", "Date", "(", "d", ".", "getFullYear", "(", ")", ",", "d", ".", "getMonth", "(", ")", ")", ")", ";", "return", "this", ".", "getWeekNumber", "(", "d", ")", "-", "monthFirstWeekNumber", "-", "1", ";", "}" ]
Return the week number, relative to its month @param int|Date d Date or timestamp in milliseconds @return int Week number, relative to the month [0-5]
[ "Return", "the", "week", "number", "relative", "to", "its", "month" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L2055-L2064
9,541
wa0x6e/cal-heatmap
src/cal-heatmap.js
function(d) { "use strict"; if (this.options.weekStartOnMonday === false) { return d.getDay(); } return d.getDay() === 0 ? 6 : (d.getDay()-1); }
javascript
function(d) { "use strict"; if (this.options.weekStartOnMonday === false) { return d.getDay(); } return d.getDay() === 0 ? 6 : (d.getDay()-1); }
[ "function", "(", "d", ")", "{", "\"use strict\"", ";", "if", "(", "this", ".", "options", ".", "weekStartOnMonday", "===", "false", ")", "{", "return", "d", ".", "getDay", "(", ")", ";", "}", "return", "d", ".", "getDay", "(", ")", "===", "0", "?", "6", ":", "(", "d", ".", "getDay", "(", ")", "-", "1", ")", ";", "}" ]
Get the weekday from a date Return the week day number (0-6) of a date, depending on whether the week start on monday or sunday @param Date d @return int The week day number (0-6)
[ "Get", "the", "weekday", "from", "a", "date" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L2116-L2123
9,542
wa0x6e/cal-heatmap
src/cal-heatmap.js
function(d) { "use strict"; if (typeof d === "number") { d = new Date(d); } return new Date(d.getFullYear(), d.getMonth()+1, 0); }
javascript
function(d) { "use strict"; if (typeof d === "number") { d = new Date(d); } return new Date(d.getFullYear(), d.getMonth()+1, 0); }
[ "function", "(", "d", ")", "{", "\"use strict\"", ";", "if", "(", "typeof", "d", "===", "\"number\"", ")", "{", "d", "=", "new", "Date", "(", "d", ")", ";", "}", "return", "new", "Date", "(", "d", ".", "getFullYear", "(", ")", ",", "d", ".", "getMonth", "(", ")", "+", "1", ",", "0", ")", ";", "}" ]
Get the last day of the month @param Date|int d Date or timestamp in milliseconds @return Date Last day of the month
[ "Get", "the", "last", "day", "of", "the", "month" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L2130-L2137
9,543
wa0x6e/cal-heatmap
src/cal-heatmap.js
function (d, range) { "use strict"; var start = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours()); var stop = null; if (range instanceof Date) { stop = new Date(range.getFullYear(), range.getMonth(), range.getDate(), range.getHours()); } else { stop = new Date(start); stop.setHours(stop.getHours() + range); } var domains = d3.time.hours(Math.min(start, stop), Math.max(start, stop)); // Passing from DST to standard time // If there are 25 hours, let's compress the duplicate hours var i = 0; var total = domains.length; for(i = 0; i < total; i++) { if (i > 0 && (domains[i].getHours() === domains[i-1].getHours())) { this.DSTDomain.push(domains[i].getTime()); domains.splice(i, 1); break; } } // d3.time.hours is returning more hours than needed when changing // from DST to standard time, because there is really 2 hours between // 1am and 2am! if (typeof range === "number" && domains.length > Math.abs(range)) { domains.splice(domains.length-1, 1); } return domains; }
javascript
function (d, range) { "use strict"; var start = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours()); var stop = null; if (range instanceof Date) { stop = new Date(range.getFullYear(), range.getMonth(), range.getDate(), range.getHours()); } else { stop = new Date(start); stop.setHours(stop.getHours() + range); } var domains = d3.time.hours(Math.min(start, stop), Math.max(start, stop)); // Passing from DST to standard time // If there are 25 hours, let's compress the duplicate hours var i = 0; var total = domains.length; for(i = 0; i < total; i++) { if (i > 0 && (domains[i].getHours() === domains[i-1].getHours())) { this.DSTDomain.push(domains[i].getTime()); domains.splice(i, 1); break; } } // d3.time.hours is returning more hours than needed when changing // from DST to standard time, because there is really 2 hours between // 1am and 2am! if (typeof range === "number" && domains.length > Math.abs(range)) { domains.splice(domains.length-1, 1); } return domains; }
[ "function", "(", "d", ",", "range", ")", "{", "\"use strict\"", ";", "var", "start", "=", "new", "Date", "(", "d", ".", "getFullYear", "(", ")", ",", "d", ".", "getMonth", "(", ")", ",", "d", ".", "getDate", "(", ")", ",", "d", ".", "getHours", "(", ")", ")", ";", "var", "stop", "=", "null", ";", "if", "(", "range", "instanceof", "Date", ")", "{", "stop", "=", "new", "Date", "(", "range", ".", "getFullYear", "(", ")", ",", "range", ".", "getMonth", "(", ")", ",", "range", ".", "getDate", "(", ")", ",", "range", ".", "getHours", "(", ")", ")", ";", "}", "else", "{", "stop", "=", "new", "Date", "(", "start", ")", ";", "stop", ".", "setHours", "(", "stop", ".", "getHours", "(", ")", "+", "range", ")", ";", "}", "var", "domains", "=", "d3", ".", "time", ".", "hours", "(", "Math", ".", "min", "(", "start", ",", "stop", ")", ",", "Math", ".", "max", "(", "start", ",", "stop", ")", ")", ";", "// Passing from DST to standard time", "// If there are 25 hours, let's compress the duplicate hours", "var", "i", "=", "0", ";", "var", "total", "=", "domains", ".", "length", ";", "for", "(", "i", "=", "0", ";", "i", "<", "total", ";", "i", "++", ")", "{", "if", "(", "i", ">", "0", "&&", "(", "domains", "[", "i", "]", ".", "getHours", "(", ")", "===", "domains", "[", "i", "-", "1", "]", ".", "getHours", "(", ")", ")", ")", "{", "this", ".", "DSTDomain", ".", "push", "(", "domains", "[", "i", "]", ".", "getTime", "(", ")", ")", ";", "domains", ".", "splice", "(", "i", ",", "1", ")", ";", "break", ";", "}", "}", "// d3.time.hours is returning more hours than needed when changing", "// from DST to standard time, because there is really 2 hours between", "// 1am and 2am!", "if", "(", "typeof", "range", "===", "\"number\"", "&&", "domains", ".", "length", ">", "Math", ".", "abs", "(", "range", ")", ")", "{", "domains", ".", "splice", "(", "domains", ".", "length", "-", "1", ",", "1", ")", ";", "}", "return", "domains", ";", "}" ]
Return all the hours between 2 dates @param Date d A date @param int|date range Number of hours in the range, or a stop date @return array An array of hours
[ "Return", "all", "the", "hours", "between", "2", "dates" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L2201-L2235
9,544
wa0x6e/cal-heatmap
src/cal-heatmap.js
function (d, range) { "use strict"; var start = new Date(d.getFullYear(), d.getMonth(), d.getDate()); var stop = null; if (range instanceof Date) { stop = new Date(range.getFullYear(), range.getMonth(), range.getDate()); } else { stop = new Date(start); stop = new Date(stop.setDate(stop.getDate() + parseInt(range, 10))); } return d3.time.days(Math.min(start, stop), Math.max(start, stop)); }
javascript
function (d, range) { "use strict"; var start = new Date(d.getFullYear(), d.getMonth(), d.getDate()); var stop = null; if (range instanceof Date) { stop = new Date(range.getFullYear(), range.getMonth(), range.getDate()); } else { stop = new Date(start); stop = new Date(stop.setDate(stop.getDate() + parseInt(range, 10))); } return d3.time.days(Math.min(start, stop), Math.max(start, stop)); }
[ "function", "(", "d", ",", "range", ")", "{", "\"use strict\"", ";", "var", "start", "=", "new", "Date", "(", "d", ".", "getFullYear", "(", ")", ",", "d", ".", "getMonth", "(", ")", ",", "d", ".", "getDate", "(", ")", ")", ";", "var", "stop", "=", "null", ";", "if", "(", "range", "instanceof", "Date", ")", "{", "stop", "=", "new", "Date", "(", "range", ".", "getFullYear", "(", ")", ",", "range", ".", "getMonth", "(", ")", ",", "range", ".", "getDate", "(", ")", ")", ";", "}", "else", "{", "stop", "=", "new", "Date", "(", "start", ")", ";", "stop", "=", "new", "Date", "(", "stop", ".", "setDate", "(", "stop", ".", "getDate", "(", ")", "+", "parseInt", "(", "range", ",", "10", ")", ")", ")", ";", "}", "return", "d3", ".", "time", ".", "days", "(", "Math", ".", "min", "(", "start", ",", "stop", ")", ",", "Math", ".", "max", "(", "start", ",", "stop", ")", ")", ";", "}" ]
Return all the days between 2 dates @param Date d A date @param int|date range Number of days in the range, or a stop date @return array An array of weeks
[ "Return", "all", "the", "days", "between", "2", "dates" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L2244-L2257
9,545
wa0x6e/cal-heatmap
src/cal-heatmap.js
function (d, range) { "use strict"; var weekStart; if (this.options.weekStartOnMonday === false) { weekStart = new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay()); } else { if (d.getDay() === 1) { weekStart = new Date(d.getFullYear(), d.getMonth(), d.getDate()); } else if (d.getDay() === 0) { weekStart = new Date(d.getFullYear(), d.getMonth(), d.getDate()); weekStart.setDate(weekStart.getDate() - 6); } else { weekStart = new Date(d.getFullYear(), d.getMonth(), d.getDate()-d.getDay()+1); } } var endDate = new Date(weekStart); var stop = range; if (typeof range !== "object") { stop = new Date(endDate.setDate(endDate.getDate() + range * 7)); } return (this.options.weekStartOnMonday === true) ? d3.time.mondays(Math.min(weekStart, stop), Math.max(weekStart, stop)): d3.time.sundays(Math.min(weekStart, stop), Math.max(weekStart, stop)) ; }
javascript
function (d, range) { "use strict"; var weekStart; if (this.options.weekStartOnMonday === false) { weekStart = new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay()); } else { if (d.getDay() === 1) { weekStart = new Date(d.getFullYear(), d.getMonth(), d.getDate()); } else if (d.getDay() === 0) { weekStart = new Date(d.getFullYear(), d.getMonth(), d.getDate()); weekStart.setDate(weekStart.getDate() - 6); } else { weekStart = new Date(d.getFullYear(), d.getMonth(), d.getDate()-d.getDay()+1); } } var endDate = new Date(weekStart); var stop = range; if (typeof range !== "object") { stop = new Date(endDate.setDate(endDate.getDate() + range * 7)); } return (this.options.weekStartOnMonday === true) ? d3.time.mondays(Math.min(weekStart, stop), Math.max(weekStart, stop)): d3.time.sundays(Math.min(weekStart, stop), Math.max(weekStart, stop)) ; }
[ "function", "(", "d", ",", "range", ")", "{", "\"use strict\"", ";", "var", "weekStart", ";", "if", "(", "this", ".", "options", ".", "weekStartOnMonday", "===", "false", ")", "{", "weekStart", "=", "new", "Date", "(", "d", ".", "getFullYear", "(", ")", ",", "d", ".", "getMonth", "(", ")", ",", "d", ".", "getDate", "(", ")", "-", "d", ".", "getDay", "(", ")", ")", ";", "}", "else", "{", "if", "(", "d", ".", "getDay", "(", ")", "===", "1", ")", "{", "weekStart", "=", "new", "Date", "(", "d", ".", "getFullYear", "(", ")", ",", "d", ".", "getMonth", "(", ")", ",", "d", ".", "getDate", "(", ")", ")", ";", "}", "else", "if", "(", "d", ".", "getDay", "(", ")", "===", "0", ")", "{", "weekStart", "=", "new", "Date", "(", "d", ".", "getFullYear", "(", ")", ",", "d", ".", "getMonth", "(", ")", ",", "d", ".", "getDate", "(", ")", ")", ";", "weekStart", ".", "setDate", "(", "weekStart", ".", "getDate", "(", ")", "-", "6", ")", ";", "}", "else", "{", "weekStart", "=", "new", "Date", "(", "d", ".", "getFullYear", "(", ")", ",", "d", ".", "getMonth", "(", ")", ",", "d", ".", "getDate", "(", ")", "-", "d", ".", "getDay", "(", ")", "+", "1", ")", ";", "}", "}", "var", "endDate", "=", "new", "Date", "(", "weekStart", ")", ";", "var", "stop", "=", "range", ";", "if", "(", "typeof", "range", "!==", "\"object\"", ")", "{", "stop", "=", "new", "Date", "(", "endDate", ".", "setDate", "(", "endDate", ".", "getDate", "(", ")", "+", "range", "*", "7", ")", ")", ";", "}", "return", "(", "this", ".", "options", ".", "weekStartOnMonday", "===", "true", ")", "?", "d3", ".", "time", ".", "mondays", "(", "Math", ".", "min", "(", "weekStart", ",", "stop", ")", ",", "Math", ".", "max", "(", "weekStart", ",", "stop", ")", ")", ":", "d3", ".", "time", ".", "sundays", "(", "Math", ".", "min", "(", "weekStart", ",", "stop", ")", ",", "Math", ".", "max", "(", "weekStart", ",", "stop", ")", ")", ";", "}" ]
Return all the weeks between 2 dates @param Date d A date @param int|date range Number of minutes in the range, or a stop date @return array An array of weeks
[ "Return", "all", "the", "weeks", "between", "2", "dates" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L2266-L2295
9,546
wa0x6e/cal-heatmap
src/cal-heatmap.js
function (d, range) { "use strict"; var start = new Date(d.getFullYear(), d.getMonth()); var stop = null; if (range instanceof Date) { stop = new Date(range.getFullYear(), range.getMonth()); } else { stop = new Date(start); stop = stop.setMonth(stop.getMonth()+range); } return d3.time.months(Math.min(start, stop), Math.max(start, stop)); }
javascript
function (d, range) { "use strict"; var start = new Date(d.getFullYear(), d.getMonth()); var stop = null; if (range instanceof Date) { stop = new Date(range.getFullYear(), range.getMonth()); } else { stop = new Date(start); stop = stop.setMonth(stop.getMonth()+range); } return d3.time.months(Math.min(start, stop), Math.max(start, stop)); }
[ "function", "(", "d", ",", "range", ")", "{", "\"use strict\"", ";", "var", "start", "=", "new", "Date", "(", "d", ".", "getFullYear", "(", ")", ",", "d", ".", "getMonth", "(", ")", ")", ";", "var", "stop", "=", "null", ";", "if", "(", "range", "instanceof", "Date", ")", "{", "stop", "=", "new", "Date", "(", "range", ".", "getFullYear", "(", ")", ",", "range", ".", "getMonth", "(", ")", ")", ";", "}", "else", "{", "stop", "=", "new", "Date", "(", "start", ")", ";", "stop", "=", "stop", ".", "setMonth", "(", "stop", ".", "getMonth", "(", ")", "+", "range", ")", ";", "}", "return", "d3", ".", "time", ".", "months", "(", "Math", ".", "min", "(", "start", ",", "stop", ")", ",", "Math", ".", "max", "(", "start", ",", "stop", ")", ")", ";", "}" ]
Return all the months between 2 dates @param Date d A date @param int|date range Number of months in the range, or a stop date @return array An array of months
[ "Return", "all", "the", "months", "between", "2", "dates" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L2304-L2317
9,547
wa0x6e/cal-heatmap
src/cal-heatmap.js
function(d, range){ "use strict"; var start = new Date(d.getFullYear(), 0); var stop = null; if (range instanceof Date) { stop = new Date(range.getFullYear(), 0); } else { stop = new Date(d.getFullYear()+range, 0); } return d3.time.years(Math.min(start, stop), Math.max(start, stop)); }
javascript
function(d, range){ "use strict"; var start = new Date(d.getFullYear(), 0); var stop = null; if (range instanceof Date) { stop = new Date(range.getFullYear(), 0); } else { stop = new Date(d.getFullYear()+range, 0); } return d3.time.years(Math.min(start, stop), Math.max(start, stop)); }
[ "function", "(", "d", ",", "range", ")", "{", "\"use strict\"", ";", "var", "start", "=", "new", "Date", "(", "d", ".", "getFullYear", "(", ")", ",", "0", ")", ";", "var", "stop", "=", "null", ";", "if", "(", "range", "instanceof", "Date", ")", "{", "stop", "=", "new", "Date", "(", "range", ".", "getFullYear", "(", ")", ",", "0", ")", ";", "}", "else", "{", "stop", "=", "new", "Date", "(", "d", ".", "getFullYear", "(", ")", "+", "range", ",", "0", ")", ";", "}", "return", "d3", ".", "time", ".", "years", "(", "Math", ".", "min", "(", "start", ",", "stop", ")", ",", "Math", ".", "max", "(", "start", ",", "stop", ")", ")", ";", "}" ]
Return all the years between 2 dates @param Date d date A date @param int|date range Number of minutes in the range, or a stop date @return array An array of hours
[ "Return", "all", "the", "years", "between", "2", "dates" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L2326-L2338
9,548
wa0x6e/cal-heatmap
src/cal-heatmap.js
function(date, range) { "use strict"; if (typeof date === "number") { date = new Date(date); } if (arguments.length < 2) { range = this.options.range; } switch(this.options.domain) { case "hour" : var domains = this.getHourDomain(date, range); // Case where an hour is missing, when passing from standard time to DST // Missing hour is perfectly acceptabl in subDomain, but not in domains if (typeof range === "number" && domains.length < range) { if (range > 0) { domains.push(this.getHourDomain(domains[domains.length-1], 2)[1]); } else { domains.shift(this.getHourDomain(domains[0], -2)[0]); } } return domains; case "day" : return this.getDayDomain(date, range); case "week" : return this.getWeekDomain(date, range); case "month": return this.getMonthDomain(date, range); case "year" : return this.getYearDomain(date, range); } }
javascript
function(date, range) { "use strict"; if (typeof date === "number") { date = new Date(date); } if (arguments.length < 2) { range = this.options.range; } switch(this.options.domain) { case "hour" : var domains = this.getHourDomain(date, range); // Case where an hour is missing, when passing from standard time to DST // Missing hour is perfectly acceptabl in subDomain, but not in domains if (typeof range === "number" && domains.length < range) { if (range > 0) { domains.push(this.getHourDomain(domains[domains.length-1], 2)[1]); } else { domains.shift(this.getHourDomain(domains[0], -2)[0]); } } return domains; case "day" : return this.getDayDomain(date, range); case "week" : return this.getWeekDomain(date, range); case "month": return this.getMonthDomain(date, range); case "year" : return this.getYearDomain(date, range); } }
[ "function", "(", "date", ",", "range", ")", "{", "\"use strict\"", ";", "if", "(", "typeof", "date", "===", "\"number\"", ")", "{", "date", "=", "new", "Date", "(", "date", ")", ";", "}", "if", "(", "arguments", ".", "length", "<", "2", ")", "{", "range", "=", "this", ".", "options", ".", "range", ";", "}", "switch", "(", "this", ".", "options", ".", "domain", ")", "{", "case", "\"hour\"", ":", "var", "domains", "=", "this", ".", "getHourDomain", "(", "date", ",", "range", ")", ";", "// Case where an hour is missing, when passing from standard time to DST", "// Missing hour is perfectly acceptabl in subDomain, but not in domains", "if", "(", "typeof", "range", "===", "\"number\"", "&&", "domains", ".", "length", "<", "range", ")", "{", "if", "(", "range", ">", "0", ")", "{", "domains", ".", "push", "(", "this", ".", "getHourDomain", "(", "domains", "[", "domains", ".", "length", "-", "1", "]", ",", "2", ")", "[", "1", "]", ")", ";", "}", "else", "{", "domains", ".", "shift", "(", "this", ".", "getHourDomain", "(", "domains", "[", "0", "]", ",", "-", "2", ")", "[", "0", "]", ")", ";", "}", "}", "return", "domains", ";", "case", "\"day\"", ":", "return", "this", ".", "getDayDomain", "(", "date", ",", "range", ")", ";", "case", "\"week\"", ":", "return", "this", ".", "getWeekDomain", "(", "date", ",", "range", ")", ";", "case", "\"month\"", ":", "return", "this", ".", "getMonthDomain", "(", "date", ",", "range", ")", ";", "case", "\"year\"", ":", "return", "this", ".", "getYearDomain", "(", "date", ",", "range", ")", ";", "}", "}" ]
Get an array of domain start dates @param int|Date date A random date included in the wanted domain @param int|Date range Number of dates to get, or a stop date @return Array of dates
[ "Get", "an", "array", "of", "domain", "start", "dates" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L2347-L2381
9,549
wa0x6e/cal-heatmap
src/cal-heatmap.js
function(data, updateMode, startDate, endDate) { "use strict"; if (updateMode === this.RESET_ALL_ON_UPDATE) { this._domains.forEach(function(key, value) { value.forEach(function(element, index, array) { array[index].v = null; }); }); } var temp = {}; var extractTime = function(d) { return d.t; }; /*jshint forin:false */ for (var d in data) { var date = new Date(d*1000); var domainUnit = this.getDomain(date)[0].getTime(); // The current data belongs to a domain that was compressed // Compress the data for the two duplicate hours into the same hour if (this.DSTDomain.indexOf(domainUnit) >= 0) { // Re-assign all data to the first or the second duplicate hours // depending on which is visible if (this._domains.has(domainUnit - 3600 * 1000)) { domainUnit -= 3600 * 1000; } } // Skip if data is not relevant to current domain if (isNaN(d) || !data.hasOwnProperty(d) || !this._domains.has(domainUnit) || !(domainUnit >= +startDate && domainUnit < +endDate)) { continue; } var subDomainsData = this._domains.get(domainUnit); if (!temp.hasOwnProperty(domainUnit)) { temp[domainUnit] = subDomainsData.map(extractTime); } var index = temp[domainUnit].indexOf(this._domainType[this.options.subDomain].extractUnit(date)); if (updateMode === this.RESET_SINGLE_ON_UPDATE) { subDomainsData[index].v = data[d]; } else { if (!isNaN(subDomainsData[index].v)) { subDomainsData[index].v += data[d]; } else { subDomainsData[index].v = data[d]; } } } }
javascript
function(data, updateMode, startDate, endDate) { "use strict"; if (updateMode === this.RESET_ALL_ON_UPDATE) { this._domains.forEach(function(key, value) { value.forEach(function(element, index, array) { array[index].v = null; }); }); } var temp = {}; var extractTime = function(d) { return d.t; }; /*jshint forin:false */ for (var d in data) { var date = new Date(d*1000); var domainUnit = this.getDomain(date)[0].getTime(); // The current data belongs to a domain that was compressed // Compress the data for the two duplicate hours into the same hour if (this.DSTDomain.indexOf(domainUnit) >= 0) { // Re-assign all data to the first or the second duplicate hours // depending on which is visible if (this._domains.has(domainUnit - 3600 * 1000)) { domainUnit -= 3600 * 1000; } } // Skip if data is not relevant to current domain if (isNaN(d) || !data.hasOwnProperty(d) || !this._domains.has(domainUnit) || !(domainUnit >= +startDate && domainUnit < +endDate)) { continue; } var subDomainsData = this._domains.get(domainUnit); if (!temp.hasOwnProperty(domainUnit)) { temp[domainUnit] = subDomainsData.map(extractTime); } var index = temp[domainUnit].indexOf(this._domainType[this.options.subDomain].extractUnit(date)); if (updateMode === this.RESET_SINGLE_ON_UPDATE) { subDomainsData[index].v = data[d]; } else { if (!isNaN(subDomainsData[index].v)) { subDomainsData[index].v += data[d]; } else { subDomainsData[index].v = data[d]; } } } }
[ "function", "(", "data", ",", "updateMode", ",", "startDate", ",", "endDate", ")", "{", "\"use strict\"", ";", "if", "(", "updateMode", "===", "this", ".", "RESET_ALL_ON_UPDATE", ")", "{", "this", ".", "_domains", ".", "forEach", "(", "function", "(", "key", ",", "value", ")", "{", "value", ".", "forEach", "(", "function", "(", "element", ",", "index", ",", "array", ")", "{", "array", "[", "index", "]", ".", "v", "=", "null", ";", "}", ")", ";", "}", ")", ";", "}", "var", "temp", "=", "{", "}", ";", "var", "extractTime", "=", "function", "(", "d", ")", "{", "return", "d", ".", "t", ";", "}", ";", "/*jshint forin:false */", "for", "(", "var", "d", "in", "data", ")", "{", "var", "date", "=", "new", "Date", "(", "d", "*", "1000", ")", ";", "var", "domainUnit", "=", "this", ".", "getDomain", "(", "date", ")", "[", "0", "]", ".", "getTime", "(", ")", ";", "// The current data belongs to a domain that was compressed", "// Compress the data for the two duplicate hours into the same hour", "if", "(", "this", ".", "DSTDomain", ".", "indexOf", "(", "domainUnit", ")", ">=", "0", ")", "{", "// Re-assign all data to the first or the second duplicate hours", "// depending on which is visible", "if", "(", "this", ".", "_domains", ".", "has", "(", "domainUnit", "-", "3600", "*", "1000", ")", ")", "{", "domainUnit", "-=", "3600", "*", "1000", ";", "}", "}", "// Skip if data is not relevant to current domain", "if", "(", "isNaN", "(", "d", ")", "||", "!", "data", ".", "hasOwnProperty", "(", "d", ")", "||", "!", "this", ".", "_domains", ".", "has", "(", "domainUnit", ")", "||", "!", "(", "domainUnit", ">=", "+", "startDate", "&&", "domainUnit", "<", "+", "endDate", ")", ")", "{", "continue", ";", "}", "var", "subDomainsData", "=", "this", ".", "_domains", ".", "get", "(", "domainUnit", ")", ";", "if", "(", "!", "temp", ".", "hasOwnProperty", "(", "domainUnit", ")", ")", "{", "temp", "[", "domainUnit", "]", "=", "subDomainsData", ".", "map", "(", "extractTime", ")", ";", "}", "var", "index", "=", "temp", "[", "domainUnit", "]", ".", "indexOf", "(", "this", ".", "_domainType", "[", "this", ".", "options", ".", "subDomain", "]", ".", "extractUnit", "(", "date", ")", ")", ";", "if", "(", "updateMode", "===", "this", ".", "RESET_SINGLE_ON_UPDATE", ")", "{", "subDomainsData", "[", "index", "]", ".", "v", "=", "data", "[", "d", "]", ";", "}", "else", "{", "if", "(", "!", "isNaN", "(", "subDomainsData", "[", "index", "]", ".", "v", ")", ")", "{", "subDomainsData", "[", "index", "]", ".", "v", "+=", "data", "[", "d", "]", ";", "}", "else", "{", "subDomainsData", "[", "index", "]", ".", "v", "=", "data", "[", "d", "]", ";", "}", "}", "}", "}" ]
Populate the calendar internal data @param object data @param constant updateMode @param Date startDate @param Date endDate @return void
[ "Populate", "the", "calendar", "internal", "data" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L2615-L2669
9,550
wa0x6e/cal-heatmap
src/cal-heatmap.js
function() { "use strict"; var parent = this; var options = parent.options; var legendWidth = options.displayLegend ? (parent.Legend.getDim("width") + options.legendMargin[1] + options.legendMargin[3]) : 0; var legendHeight = options.displayLegend ? (parent.Legend.getDim("height") + options.legendMargin[0] + options.legendMargin[2]) : 0; var graphWidth = parent.graphDim.width - options.domainGutter - options.cellPadding; var graphHeight = parent.graphDim.height - options.domainGutter - options.cellPadding; this.root.transition().duration(options.animationDuration) .attr("width", function() { if (options.legendVerticalPosition === "middle" || options.legendVerticalPosition === "center") { return graphWidth + legendWidth; } return Math.max(graphWidth, legendWidth); }) .attr("height", function() { if (options.legendVerticalPosition === "middle" || options.legendVerticalPosition === "center") { return Math.max(graphHeight, legendHeight); } return graphHeight + legendHeight; }) ; this.root.select(".graph").transition().duration(options.animationDuration) .attr("y", function() { if (options.legendVerticalPosition === "top") { return legendHeight; } return 0; }) .attr("x", function() { if ( (options.legendVerticalPosition === "middle" || options.legendVerticalPosition === "center") && options.legendHorizontalPosition === "left") { return legendWidth; } return 0; }) ; }
javascript
function() { "use strict"; var parent = this; var options = parent.options; var legendWidth = options.displayLegend ? (parent.Legend.getDim("width") + options.legendMargin[1] + options.legendMargin[3]) : 0; var legendHeight = options.displayLegend ? (parent.Legend.getDim("height") + options.legendMargin[0] + options.legendMargin[2]) : 0; var graphWidth = parent.graphDim.width - options.domainGutter - options.cellPadding; var graphHeight = parent.graphDim.height - options.domainGutter - options.cellPadding; this.root.transition().duration(options.animationDuration) .attr("width", function() { if (options.legendVerticalPosition === "middle" || options.legendVerticalPosition === "center") { return graphWidth + legendWidth; } return Math.max(graphWidth, legendWidth); }) .attr("height", function() { if (options.legendVerticalPosition === "middle" || options.legendVerticalPosition === "center") { return Math.max(graphHeight, legendHeight); } return graphHeight + legendHeight; }) ; this.root.select(".graph").transition().duration(options.animationDuration) .attr("y", function() { if (options.legendVerticalPosition === "top") { return legendHeight; } return 0; }) .attr("x", function() { if ( (options.legendVerticalPosition === "middle" || options.legendVerticalPosition === "center") && options.legendHorizontalPosition === "left") { return legendWidth; } return 0; }) ; }
[ "function", "(", ")", "{", "\"use strict\"", ";", "var", "parent", "=", "this", ";", "var", "options", "=", "parent", ".", "options", ";", "var", "legendWidth", "=", "options", ".", "displayLegend", "?", "(", "parent", ".", "Legend", ".", "getDim", "(", "\"width\"", ")", "+", "options", ".", "legendMargin", "[", "1", "]", "+", "options", ".", "legendMargin", "[", "3", "]", ")", ":", "0", ";", "var", "legendHeight", "=", "options", ".", "displayLegend", "?", "(", "parent", ".", "Legend", ".", "getDim", "(", "\"height\"", ")", "+", "options", ".", "legendMargin", "[", "0", "]", "+", "options", ".", "legendMargin", "[", "2", "]", ")", ":", "0", ";", "var", "graphWidth", "=", "parent", ".", "graphDim", ".", "width", "-", "options", ".", "domainGutter", "-", "options", ".", "cellPadding", ";", "var", "graphHeight", "=", "parent", ".", "graphDim", ".", "height", "-", "options", ".", "domainGutter", "-", "options", ".", "cellPadding", ";", "this", ".", "root", ".", "transition", "(", ")", ".", "duration", "(", "options", ".", "animationDuration", ")", ".", "attr", "(", "\"width\"", ",", "function", "(", ")", "{", "if", "(", "options", ".", "legendVerticalPosition", "===", "\"middle\"", "||", "options", ".", "legendVerticalPosition", "===", "\"center\"", ")", "{", "return", "graphWidth", "+", "legendWidth", ";", "}", "return", "Math", ".", "max", "(", "graphWidth", ",", "legendWidth", ")", ";", "}", ")", ".", "attr", "(", "\"height\"", ",", "function", "(", ")", "{", "if", "(", "options", ".", "legendVerticalPosition", "===", "\"middle\"", "||", "options", ".", "legendVerticalPosition", "===", "\"center\"", ")", "{", "return", "Math", ".", "max", "(", "graphHeight", ",", "legendHeight", ")", ";", "}", "return", "graphHeight", "+", "legendHeight", ";", "}", ")", ";", "this", ".", "root", ".", "select", "(", "\".graph\"", ")", ".", "transition", "(", ")", ".", "duration", "(", "options", ".", "animationDuration", ")", ".", "attr", "(", "\"y\"", ",", "function", "(", ")", "{", "if", "(", "options", ".", "legendVerticalPosition", "===", "\"top\"", ")", "{", "return", "legendHeight", ";", "}", "return", "0", ";", "}", ")", ".", "attr", "(", "\"x\"", ",", "function", "(", ")", "{", "if", "(", "(", "options", ".", "legendVerticalPosition", "===", "\"middle\"", "||", "options", ".", "legendVerticalPosition", "===", "\"center\"", ")", "&&", "options", ".", "legendHorizontalPosition", "===", "\"left\"", ")", "{", "return", "legendWidth", ";", "}", "return", "0", ";", "}", ")", ";", "}" ]
Handle the calendar layout and dimension Expand and shrink the container depending on its children dimension Also rearrange the children position depending on their dimension, and the legend position @return void
[ "Handle", "the", "calendar", "layout", "and", "dimension" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L2706-L2749
9,551
wa0x6e/cal-heatmap
src/cal-heatmap.js
function(date, reset) { "use strict"; if (arguments.length < 2) { reset = false; } var domains = this.getDomainKeys(); var firstDomain = domains[0]; var lastDomain = domains[domains.length-1]; if (date < firstDomain) { return this.loadPreviousDomain(this.getDomain(firstDomain, date).length); } else { if (reset) { return this.loadNextDomain(this.getDomain(firstDomain, date).length); } if (date > lastDomain) { return this.loadNextDomain(this.getDomain(lastDomain, date).length); } } return false; }
javascript
function(date, reset) { "use strict"; if (arguments.length < 2) { reset = false; } var domains = this.getDomainKeys(); var firstDomain = domains[0]; var lastDomain = domains[domains.length-1]; if (date < firstDomain) { return this.loadPreviousDomain(this.getDomain(firstDomain, date).length); } else { if (reset) { return this.loadNextDomain(this.getDomain(firstDomain, date).length); } if (date > lastDomain) { return this.loadNextDomain(this.getDomain(lastDomain, date).length); } } return false; }
[ "function", "(", "date", ",", "reset", ")", "{", "\"use strict\"", ";", "if", "(", "arguments", ".", "length", "<", "2", ")", "{", "reset", "=", "false", ";", "}", "var", "domains", "=", "this", ".", "getDomainKeys", "(", ")", ";", "var", "firstDomain", "=", "domains", "[", "0", "]", ";", "var", "lastDomain", "=", "domains", "[", "domains", ".", "length", "-", "1", "]", ";", "if", "(", "date", "<", "firstDomain", ")", "{", "return", "this", ".", "loadPreviousDomain", "(", "this", ".", "getDomain", "(", "firstDomain", ",", "date", ")", ".", "length", ")", ";", "}", "else", "{", "if", "(", "reset", ")", "{", "return", "this", ".", "loadNextDomain", "(", "this", ".", "getDomain", "(", "firstDomain", ",", "date", ")", ".", "length", ")", ";", "}", "if", "(", "date", ">", "lastDomain", ")", "{", "return", "this", ".", "loadNextDomain", "(", "this", ".", "getDomain", "(", "lastDomain", ",", "date", ")", ".", "length", ")", ";", "}", "}", "return", "false", ";", "}" ]
Jump directly to a specific date JumpTo will scroll the calendar until the wanted domain with the specified date is visible. Unless you set reset to true, the wanted domain will not necessarily be the first (leftmost) domain of the calendar. @param Date date Jump to the domain containing that date @param bool reset Whether the wanted domain should be the first domain of the calendar @param bool True of the calendar was scrolled
[ "Jump", "directly", "to", "a", "specific", "date" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L2790-L2813
9,552
wa0x6e/cal-heatmap
src/cal-heatmap.js
function(dataSource, afterLoad, updateMode) { "use strict"; if (arguments.length === 0) { dataSource = this.options.data; } if (arguments.length < 2) { afterLoad = true; } if (arguments.length < 3) { updateMode = this.RESET_ALL_ON_UPDATE; } var domains = this.getDomainKeys(); var self = this; this.getDatas( dataSource, new Date(domains[0]), this.getSubDomain(domains[domains.length-1]).pop(), function() { self.fill(); self.afterUpdate(); }, afterLoad, updateMode ); }
javascript
function(dataSource, afterLoad, updateMode) { "use strict"; if (arguments.length === 0) { dataSource = this.options.data; } if (arguments.length < 2) { afterLoad = true; } if (arguments.length < 3) { updateMode = this.RESET_ALL_ON_UPDATE; } var domains = this.getDomainKeys(); var self = this; this.getDatas( dataSource, new Date(domains[0]), this.getSubDomain(domains[domains.length-1]).pop(), function() { self.fill(); self.afterUpdate(); }, afterLoad, updateMode ); }
[ "function", "(", "dataSource", ",", "afterLoad", ",", "updateMode", ")", "{", "\"use strict\"", ";", "if", "(", "arguments", ".", "length", "===", "0", ")", "{", "dataSource", "=", "this", ".", "options", ".", "data", ";", "}", "if", "(", "arguments", ".", "length", "<", "2", ")", "{", "afterLoad", "=", "true", ";", "}", "if", "(", "arguments", ".", "length", "<", "3", ")", "{", "updateMode", "=", "this", ".", "RESET_ALL_ON_UPDATE", ";", "}", "var", "domains", "=", "this", ".", "getDomainKeys", "(", ")", ";", "var", "self", "=", "this", ";", "this", ".", "getDatas", "(", "dataSource", ",", "new", "Date", "(", "domains", "[", "0", "]", ")", ",", "this", ".", "getSubDomain", "(", "domains", "[", "domains", ".", "length", "-", "1", "]", ")", ".", "pop", "(", ")", ",", "function", "(", ")", "{", "self", ".", "fill", "(", ")", ";", "self", ".", "afterUpdate", "(", ")", ";", "}", ",", "afterLoad", ",", "updateMode", ")", ";", "}" ]
Update the calendar with new data @param object|string dataSource The calendar's datasource, same type as this.options.data @param boolean|function afterLoad Whether to execute afterLoad() on the data. Pass directly a function if you don't want to use the afterLoad() callback
[ "Update", "the", "calendar", "with", "new", "data" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L2834-L2860
9,553
wa0x6e/cal-heatmap
src/cal-heatmap.js
function(callback) { "use strict"; this.root.transition().duration(this.options.animationDuration) .attr("width", 0) .attr("height", 0) .remove() .each("end", function() { if (typeof callback === "function") { callback(); } else if (typeof callback !== "undefined") { console.log("Provided callback for destroy() is not a function."); } }) ; return null; }
javascript
function(callback) { "use strict"; this.root.transition().duration(this.options.animationDuration) .attr("width", 0) .attr("height", 0) .remove() .each("end", function() { if (typeof callback === "function") { callback(); } else if (typeof callback !== "undefined") { console.log("Provided callback for destroy() is not a function."); } }) ; return null; }
[ "function", "(", "callback", ")", "{", "\"use strict\"", ";", "this", ".", "root", ".", "transition", "(", ")", ".", "duration", "(", "this", ".", "options", ".", "animationDuration", ")", ".", "attr", "(", "\"width\"", ",", "0", ")", ".", "attr", "(", "\"height\"", ",", "0", ")", ".", "remove", "(", ")", ".", "each", "(", "\"end\"", ",", "function", "(", ")", "{", "if", "(", "typeof", "callback", "===", "\"function\"", ")", "{", "callback", "(", ")", ";", "}", "else", "if", "(", "typeof", "callback", "!==", "\"undefined\"", ")", "{", "console", ".", "log", "(", "\"Provided callback for destroy() is not a function.\"", ")", ";", "}", "}", ")", ";", "return", "null", ";", "}" ]
Destroy the calendar Usage: cal = cal.destroy(); @since 3.3.6 @param function A callback function to trigger after destroying the calendar @return null
[ "Destroy", "the", "calendar" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L2951-L2968
9,554
wa0x6e/cal-heatmap
src/cal-heatmap.js
arrayEquals
function arrayEquals(arrayA, arrayB) { "use strict"; // if the other array is a falsy value, return if (!arrayB || !arrayA) { return false; } // compare lengths - can save a lot of time if (arrayA.length !== arrayB.length) { return false; } for (var i = 0; i < arrayA.length; i++) { // Check if we have nested arrays if (arrayA[i] instanceof Array && arrayB[i] instanceof Array) { // recurse into the nested arrays if (!arrayEquals(arrayA[i], arrayB[i])) { return false; } } else if (arrayA[i] !== arrayB[i]) { // Warning - two different object instances will never be equal: {x:20} != {x:20} return false; } } return true; }
javascript
function arrayEquals(arrayA, arrayB) { "use strict"; // if the other array is a falsy value, return if (!arrayB || !arrayA) { return false; } // compare lengths - can save a lot of time if (arrayA.length !== arrayB.length) { return false; } for (var i = 0; i < arrayA.length; i++) { // Check if we have nested arrays if (arrayA[i] instanceof Array && arrayB[i] instanceof Array) { // recurse into the nested arrays if (!arrayEquals(arrayA[i], arrayB[i])) { return false; } } else if (arrayA[i] !== arrayB[i]) { // Warning - two different object instances will never be equal: {x:20} != {x:20} return false; } } return true; }
[ "function", "arrayEquals", "(", "arrayA", ",", "arrayB", ")", "{", "\"use strict\"", ";", "// if the other array is a falsy value, return", "if", "(", "!", "arrayB", "||", "!", "arrayA", ")", "{", "return", "false", ";", "}", "// compare lengths - can save a lot of time", "if", "(", "arrayA", ".", "length", "!==", "arrayB", ".", "length", ")", "{", "return", "false", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arrayA", ".", "length", ";", "i", "++", ")", "{", "// Check if we have nested arrays", "if", "(", "arrayA", "[", "i", "]", "instanceof", "Array", "&&", "arrayB", "[", "i", "]", "instanceof", "Array", ")", "{", "// recurse into the nested arrays", "if", "(", "!", "arrayEquals", "(", "arrayA", "[", "i", "]", ",", "arrayB", "[", "i", "]", ")", ")", "{", "return", "false", ";", "}", "}", "else", "if", "(", "arrayA", "[", "i", "]", "!==", "arrayB", "[", "i", "]", ")", "{", "// Warning - two different object instances will never be equal: {x:20} != {x:20}", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Check if 2 arrays are equals @link http://stackoverflow.com/a/14853974/805649 @param array array the array to compare to @return bool true of the 2 arrays are equals
[ "Check", "if", "2", "arrays", "are", "equals" ]
0b594620104e0b11a94cc45feb0a76b58a038e0e
https://github.com/wa0x6e/cal-heatmap/blob/0b594620104e0b11a94cc45feb0a76b58a038e0e/src/cal-heatmap.js#L3466-L3493
9,555
stjohnjohnson/smartthings-mqtt-bridge
server.js
loadSavedState
function loadSavedState () { var output; try { output = jsonfile.readFileSync(STATE_FILE); } catch (ex) { winston.info('No previous state found, continuing'); output = { subscriptions: [], callback: '', history: {}, version: '0.0.0' }; } return output; }
javascript
function loadSavedState () { var output; try { output = jsonfile.readFileSync(STATE_FILE); } catch (ex) { winston.info('No previous state found, continuing'); output = { subscriptions: [], callback: '', history: {}, version: '0.0.0' }; } return output; }
[ "function", "loadSavedState", "(", ")", "{", "var", "output", ";", "try", "{", "output", "=", "jsonfile", ".", "readFileSync", "(", "STATE_FILE", ")", ";", "}", "catch", "(", "ex", ")", "{", "winston", ".", "info", "(", "'No previous state found, continuing'", ")", ";", "output", "=", "{", "subscriptions", ":", "[", "]", ",", "callback", ":", "''", ",", "history", ":", "{", "}", ",", "version", ":", "'0.0.0'", "}", ";", "}", "return", "output", ";", "}" ]
Load the saved previous state from disk @method loadSavedState @return {Object} Configuration
[ "Load", "the", "saved", "previous", "state", "from", "disk" ]
066d3f492e2f9d9016964bef191230b99cb4e0c8
https://github.com/stjohnjohnson/smartthings-mqtt-bridge/blob/066d3f492e2f9d9016964bef191230b99cb4e0c8/server.js#L71-L85
9,556
stjohnjohnson/smartthings-mqtt-bridge
server.js
saveState
function saveState () { winston.info('Saving current state'); jsonfile.writeFileSync(STATE_FILE, { subscriptions: subscriptions, callback: callback, history: history, version: CURRENT_VERSION }, { spaces: 4 }); }
javascript
function saveState () { winston.info('Saving current state'); jsonfile.writeFileSync(STATE_FILE, { subscriptions: subscriptions, callback: callback, history: history, version: CURRENT_VERSION }, { spaces: 4 }); }
[ "function", "saveState", "(", ")", "{", "winston", ".", "info", "(", "'Saving current state'", ")", ";", "jsonfile", ".", "writeFileSync", "(", "STATE_FILE", ",", "{", "subscriptions", ":", "subscriptions", ",", "callback", ":", "callback", ",", "history", ":", "history", ",", "version", ":", "CURRENT_VERSION", "}", ",", "{", "spaces", ":", "4", "}", ")", ";", "}" ]
Resubscribe on a periodic basis @method saveState
[ "Resubscribe", "on", "a", "periodic", "basis" ]
066d3f492e2f9d9016964bef191230b99cb4e0c8
https://github.com/stjohnjohnson/smartthings-mqtt-bridge/blob/066d3f492e2f9d9016964bef191230b99cb4e0c8/server.js#L91-L101
9,557
stjohnjohnson/smartthings-mqtt-bridge
server.js
migrateState
function migrateState (version) { // Make sure the object exists if (!config.mqtt) { config.mqtt = {}; } // This is the previous default, but it's totally wrong if (!config.mqtt.preface) { config.mqtt.preface = '/smartthings'; } // Default Suffixes if (!config.mqtt[SUFFIX_READ_STATE]) { config.mqtt[SUFFIX_READ_STATE] = ''; } if (!config.mqtt[SUFFIX_COMMAND]) { config.mqtt[SUFFIX_COMMAND] = ''; } if (!config.mqtt[SUFFIX_WRITE_STATE]) { config.mqtt[SUFFIX_WRITE_STATE] = ''; } // Default retain if (config.mqtt[RETAIN] !== false) { config.mqtt[RETAIN] = true; } // Default port if (!config.port) { config.port = 8080; } // Default protocol if (!url.parse(config.mqtt.host).protocol) { config.mqtt.host = 'mqtt://' + config.mqtt.host; } // Stuff was previously in subscription.json, load that and migrate it var SUBSCRIPTION_FILE = path.join(CONFIG_DIR, 'subscription.json'); if (semver.lt(version, '1.1.0') && fs.existsSync(SUBSCRIPTION_FILE)) { var oldState = jsonfile.readFileSync(SUBSCRIPTION_FILE); callback = oldState.callback; subscriptions = oldState.topics; } saveState(); }
javascript
function migrateState (version) { // Make sure the object exists if (!config.mqtt) { config.mqtt = {}; } // This is the previous default, but it's totally wrong if (!config.mqtt.preface) { config.mqtt.preface = '/smartthings'; } // Default Suffixes if (!config.mqtt[SUFFIX_READ_STATE]) { config.mqtt[SUFFIX_READ_STATE] = ''; } if (!config.mqtt[SUFFIX_COMMAND]) { config.mqtt[SUFFIX_COMMAND] = ''; } if (!config.mqtt[SUFFIX_WRITE_STATE]) { config.mqtt[SUFFIX_WRITE_STATE] = ''; } // Default retain if (config.mqtt[RETAIN] !== false) { config.mqtt[RETAIN] = true; } // Default port if (!config.port) { config.port = 8080; } // Default protocol if (!url.parse(config.mqtt.host).protocol) { config.mqtt.host = 'mqtt://' + config.mqtt.host; } // Stuff was previously in subscription.json, load that and migrate it var SUBSCRIPTION_FILE = path.join(CONFIG_DIR, 'subscription.json'); if (semver.lt(version, '1.1.0') && fs.existsSync(SUBSCRIPTION_FILE)) { var oldState = jsonfile.readFileSync(SUBSCRIPTION_FILE); callback = oldState.callback; subscriptions = oldState.topics; } saveState(); }
[ "function", "migrateState", "(", "version", ")", "{", "// Make sure the object exists", "if", "(", "!", "config", ".", "mqtt", ")", "{", "config", ".", "mqtt", "=", "{", "}", ";", "}", "// This is the previous default, but it's totally wrong", "if", "(", "!", "config", ".", "mqtt", ".", "preface", ")", "{", "config", ".", "mqtt", ".", "preface", "=", "'/smartthings'", ";", "}", "// Default Suffixes", "if", "(", "!", "config", ".", "mqtt", "[", "SUFFIX_READ_STATE", "]", ")", "{", "config", ".", "mqtt", "[", "SUFFIX_READ_STATE", "]", "=", "''", ";", "}", "if", "(", "!", "config", ".", "mqtt", "[", "SUFFIX_COMMAND", "]", ")", "{", "config", ".", "mqtt", "[", "SUFFIX_COMMAND", "]", "=", "''", ";", "}", "if", "(", "!", "config", ".", "mqtt", "[", "SUFFIX_WRITE_STATE", "]", ")", "{", "config", ".", "mqtt", "[", "SUFFIX_WRITE_STATE", "]", "=", "''", ";", "}", "// Default retain", "if", "(", "config", ".", "mqtt", "[", "RETAIN", "]", "!==", "false", ")", "{", "config", ".", "mqtt", "[", "RETAIN", "]", "=", "true", ";", "}", "// Default port", "if", "(", "!", "config", ".", "port", ")", "{", "config", ".", "port", "=", "8080", ";", "}", "// Default protocol", "if", "(", "!", "url", ".", "parse", "(", "config", ".", "mqtt", ".", "host", ")", ".", "protocol", ")", "{", "config", ".", "mqtt", ".", "host", "=", "'mqtt://'", "+", "config", ".", "mqtt", ".", "host", ";", "}", "// Stuff was previously in subscription.json, load that and migrate it", "var", "SUBSCRIPTION_FILE", "=", "path", ".", "join", "(", "CONFIG_DIR", ",", "'subscription.json'", ")", ";", "if", "(", "semver", ".", "lt", "(", "version", ",", "'1.1.0'", ")", "&&", "fs", ".", "existsSync", "(", "SUBSCRIPTION_FILE", ")", ")", "{", "var", "oldState", "=", "jsonfile", ".", "readFileSync", "(", "SUBSCRIPTION_FILE", ")", ";", "callback", "=", "oldState", ".", "callback", ";", "subscriptions", "=", "oldState", ".", "topics", ";", "}", "saveState", "(", ")", ";", "}" ]
Migrate the configuration from the current version to the latest version @method migrateState @param {String} version Version the state was written in before
[ "Migrate", "the", "configuration", "from", "the", "current", "version", "to", "the", "latest", "version" ]
066d3f492e2f9d9016964bef191230b99cb4e0c8
https://github.com/stjohnjohnson/smartthings-mqtt-bridge/blob/066d3f492e2f9d9016964bef191230b99cb4e0c8/server.js#L108-L154
9,558
stjohnjohnson/smartthings-mqtt-bridge
server.js
handleSubscribeEvent
function handleSubscribeEvent (req, res) { // Subscribe to all events subscriptions = []; Object.keys(req.body.devices).forEach(function (property) { req.body.devices[property].forEach(function (device) { subscriptions.push(getTopicFor(device, property, TOPIC_COMMAND)); subscriptions.push(getTopicFor(device, property, TOPIC_WRITE_STATE)); }); }); // Store callback callback = req.body.callback; // Store current state on disk saveState(); // Subscribe to events winston.info('Subscribing to ' + subscriptions.join(', ')); client.subscribe(subscriptions, function () { res.send({ status: 'OK' }); }); }
javascript
function handleSubscribeEvent (req, res) { // Subscribe to all events subscriptions = []; Object.keys(req.body.devices).forEach(function (property) { req.body.devices[property].forEach(function (device) { subscriptions.push(getTopicFor(device, property, TOPIC_COMMAND)); subscriptions.push(getTopicFor(device, property, TOPIC_WRITE_STATE)); }); }); // Store callback callback = req.body.callback; // Store current state on disk saveState(); // Subscribe to events winston.info('Subscribing to ' + subscriptions.join(', ')); client.subscribe(subscriptions, function () { res.send({ status: 'OK' }); }); }
[ "function", "handleSubscribeEvent", "(", "req", ",", "res", ")", "{", "// Subscribe to all events", "subscriptions", "=", "[", "]", ";", "Object", ".", "keys", "(", "req", ".", "body", ".", "devices", ")", ".", "forEach", "(", "function", "(", "property", ")", "{", "req", ".", "body", ".", "devices", "[", "property", "]", ".", "forEach", "(", "function", "(", "device", ")", "{", "subscriptions", ".", "push", "(", "getTopicFor", "(", "device", ",", "property", ",", "TOPIC_COMMAND", ")", ")", ";", "subscriptions", ".", "push", "(", "getTopicFor", "(", "device", ",", "property", ",", "TOPIC_WRITE_STATE", ")", ")", ";", "}", ")", ";", "}", ")", ";", "// Store callback", "callback", "=", "req", ".", "body", ".", "callback", ";", "// Store current state on disk", "saveState", "(", ")", ";", "// Subscribe to events", "winston", ".", "info", "(", "'Subscribing to '", "+", "subscriptions", ".", "join", "(", "', '", ")", ")", ";", "client", ".", "subscribe", "(", "subscriptions", ",", "function", "(", ")", "{", "res", ".", "send", "(", "{", "status", ":", "'OK'", "}", ")", ";", "}", ")", ";", "}" ]
Handle Subscribe event from SmartThings @method handleSubscribeEvent @param {Request} req @param {Object} req.body @param {Object} req.body.devices List of properties => device names @param {String} req.body.callback Host and port for SmartThings Hub @param {Result} res Result Object
[ "Handle", "Subscribe", "event", "from", "SmartThings" ]
066d3f492e2f9d9016964bef191230b99cb4e0c8
https://github.com/stjohnjohnson/smartthings-mqtt-bridge/blob/066d3f492e2f9d9016964bef191230b99cb4e0c8/server.js#L193-L216
9,559
stjohnjohnson/smartthings-mqtt-bridge
server.js
getTopicFor
function getTopicFor (device, property, type) { var tree = [config.mqtt.preface, device, property], suffix; if (type === TOPIC_COMMAND) { suffix = config.mqtt[SUFFIX_COMMAND]; } else if (type === TOPIC_READ_STATE) { suffix = config.mqtt[SUFFIX_READ_STATE]; } else if (type === TOPIC_WRITE_STATE) { suffix = config.mqtt[SUFFIX_WRITE_STATE]; } if (suffix) { tree.push(suffix); } return tree.join('/'); }
javascript
function getTopicFor (device, property, type) { var tree = [config.mqtt.preface, device, property], suffix; if (type === TOPIC_COMMAND) { suffix = config.mqtt[SUFFIX_COMMAND]; } else if (type === TOPIC_READ_STATE) { suffix = config.mqtt[SUFFIX_READ_STATE]; } else if (type === TOPIC_WRITE_STATE) { suffix = config.mqtt[SUFFIX_WRITE_STATE]; } if (suffix) { tree.push(suffix); } return tree.join('/'); }
[ "function", "getTopicFor", "(", "device", ",", "property", ",", "type", ")", "{", "var", "tree", "=", "[", "config", ".", "mqtt", ".", "preface", ",", "device", ",", "property", "]", ",", "suffix", ";", "if", "(", "type", "===", "TOPIC_COMMAND", ")", "{", "suffix", "=", "config", ".", "mqtt", "[", "SUFFIX_COMMAND", "]", ";", "}", "else", "if", "(", "type", "===", "TOPIC_READ_STATE", ")", "{", "suffix", "=", "config", ".", "mqtt", "[", "SUFFIX_READ_STATE", "]", ";", "}", "else", "if", "(", "type", "===", "TOPIC_WRITE_STATE", ")", "{", "suffix", "=", "config", ".", "mqtt", "[", "SUFFIX_WRITE_STATE", "]", ";", "}", "if", "(", "suffix", ")", "{", "tree", ".", "push", "(", "suffix", ")", ";", "}", "return", "tree", ".", "join", "(", "'/'", ")", ";", "}" ]
Get the topic name for a given item @method getTopicFor @param {String} device Device Name @param {String} property Property @param {String} type Type of topic (command or state) @return {String} MQTT Topic name
[ "Get", "the", "topic", "name", "for", "a", "given", "item" ]
066d3f492e2f9d9016964bef191230b99cb4e0c8
https://github.com/stjohnjohnson/smartthings-mqtt-bridge/blob/066d3f492e2f9d9016964bef191230b99cb4e0c8/server.js#L227-L244
9,560
stjohnjohnson/smartthings-mqtt-bridge
server.js
parseMQTTMessage
function parseMQTTMessage (topic, message) { var contents = message.toString(); winston.info('Incoming message from MQTT: %s = %s', topic, contents); // Remove the preface from the topic before splitting it var pieces = topic.substr(config.mqtt.preface.length + 1).split('/'), device = pieces[0], property = pieces[1], topicReadState = getTopicFor(device, property, TOPIC_READ_STATE), topicWriteState = getTopicFor(device, property, TOPIC_WRITE_STATE), topicSwitchState = getTopicFor(device, 'switch', TOPIC_READ_STATE), topicLevelCommand = getTopicFor(device, 'level', TOPIC_COMMAND); // Deduplicate only if the incoming message topic is the same as the read state topic if (topic === topicReadState) { if (history[topic] === contents) { winston.info('Skipping duplicate message from: %s = %s', topic, contents); return; } } history[topic] = contents; // If sending level data and the switch is off, don't send anything // SmartThings will turn the device on (which is confusing) if (property === 'level' && history[topicSwitchState] === 'off') { winston.info('Skipping level set due to device being off'); return; } // If sending switch data and there is already a nonzero level value, send level instead // SmartThings will turn the device on if (property === 'switch' && contents === 'on' && history[topicLevelCommand] > 0) { winston.info('Passing level instead of switch on'); property = 'level'; contents = history[topicLevelCommand]; } request.post({ url: 'http://' + callback, json: { name: device, type: property, value: contents, command: (!pieces[2] || pieces[2] && pieces[2] === config.mqtt[SUFFIX_COMMAND]) } }, function (error, resp) { if (error) { // @TODO handle the response from SmartThings winston.error('Error from SmartThings Hub: %s', error.toString()); winston.error(JSON.stringify(error, null, 4)); winston.error(JSON.stringify(resp, null, 4)); } }); }
javascript
function parseMQTTMessage (topic, message) { var contents = message.toString(); winston.info('Incoming message from MQTT: %s = %s', topic, contents); // Remove the preface from the topic before splitting it var pieces = topic.substr(config.mqtt.preface.length + 1).split('/'), device = pieces[0], property = pieces[1], topicReadState = getTopicFor(device, property, TOPIC_READ_STATE), topicWriteState = getTopicFor(device, property, TOPIC_WRITE_STATE), topicSwitchState = getTopicFor(device, 'switch', TOPIC_READ_STATE), topicLevelCommand = getTopicFor(device, 'level', TOPIC_COMMAND); // Deduplicate only if the incoming message topic is the same as the read state topic if (topic === topicReadState) { if (history[topic] === contents) { winston.info('Skipping duplicate message from: %s = %s', topic, contents); return; } } history[topic] = contents; // If sending level data and the switch is off, don't send anything // SmartThings will turn the device on (which is confusing) if (property === 'level' && history[topicSwitchState] === 'off') { winston.info('Skipping level set due to device being off'); return; } // If sending switch data and there is already a nonzero level value, send level instead // SmartThings will turn the device on if (property === 'switch' && contents === 'on' && history[topicLevelCommand] > 0) { winston.info('Passing level instead of switch on'); property = 'level'; contents = history[topicLevelCommand]; } request.post({ url: 'http://' + callback, json: { name: device, type: property, value: contents, command: (!pieces[2] || pieces[2] && pieces[2] === config.mqtt[SUFFIX_COMMAND]) } }, function (error, resp) { if (error) { // @TODO handle the response from SmartThings winston.error('Error from SmartThings Hub: %s', error.toString()); winston.error(JSON.stringify(error, null, 4)); winston.error(JSON.stringify(resp, null, 4)); } }); }
[ "function", "parseMQTTMessage", "(", "topic", ",", "message", ")", "{", "var", "contents", "=", "message", ".", "toString", "(", ")", ";", "winston", ".", "info", "(", "'Incoming message from MQTT: %s = %s'", ",", "topic", ",", "contents", ")", ";", "// Remove the preface from the topic before splitting it", "var", "pieces", "=", "topic", ".", "substr", "(", "config", ".", "mqtt", ".", "preface", ".", "length", "+", "1", ")", ".", "split", "(", "'/'", ")", ",", "device", "=", "pieces", "[", "0", "]", ",", "property", "=", "pieces", "[", "1", "]", ",", "topicReadState", "=", "getTopicFor", "(", "device", ",", "property", ",", "TOPIC_READ_STATE", ")", ",", "topicWriteState", "=", "getTopicFor", "(", "device", ",", "property", ",", "TOPIC_WRITE_STATE", ")", ",", "topicSwitchState", "=", "getTopicFor", "(", "device", ",", "'switch'", ",", "TOPIC_READ_STATE", ")", ",", "topicLevelCommand", "=", "getTopicFor", "(", "device", ",", "'level'", ",", "TOPIC_COMMAND", ")", ";", "// Deduplicate only if the incoming message topic is the same as the read state topic", "if", "(", "topic", "===", "topicReadState", ")", "{", "if", "(", "history", "[", "topic", "]", "===", "contents", ")", "{", "winston", ".", "info", "(", "'Skipping duplicate message from: %s = %s'", ",", "topic", ",", "contents", ")", ";", "return", ";", "}", "}", "history", "[", "topic", "]", "=", "contents", ";", "// If sending level data and the switch is off, don't send anything", "// SmartThings will turn the device on (which is confusing)", "if", "(", "property", "===", "'level'", "&&", "history", "[", "topicSwitchState", "]", "===", "'off'", ")", "{", "winston", ".", "info", "(", "'Skipping level set due to device being off'", ")", ";", "return", ";", "}", "// If sending switch data and there is already a nonzero level value, send level instead", "// SmartThings will turn the device on", "if", "(", "property", "===", "'switch'", "&&", "contents", "===", "'on'", "&&", "history", "[", "topicLevelCommand", "]", ">", "0", ")", "{", "winston", ".", "info", "(", "'Passing level instead of switch on'", ")", ";", "property", "=", "'level'", ";", "contents", "=", "history", "[", "topicLevelCommand", "]", ";", "}", "request", ".", "post", "(", "{", "url", ":", "'http://'", "+", "callback", ",", "json", ":", "{", "name", ":", "device", ",", "type", ":", "property", ",", "value", ":", "contents", ",", "command", ":", "(", "!", "pieces", "[", "2", "]", "||", "pieces", "[", "2", "]", "&&", "pieces", "[", "2", "]", "===", "config", ".", "mqtt", "[", "SUFFIX_COMMAND", "]", ")", "}", "}", ",", "function", "(", "error", ",", "resp", ")", "{", "if", "(", "error", ")", "{", "// @TODO handle the response from SmartThings", "winston", ".", "error", "(", "'Error from SmartThings Hub: %s'", ",", "error", ".", "toString", "(", ")", ")", ";", "winston", ".", "error", "(", "JSON", ".", "stringify", "(", "error", ",", "null", ",", "4", ")", ")", ";", "winston", ".", "error", "(", "JSON", ".", "stringify", "(", "resp", ",", "null", ",", "4", ")", ")", ";", "}", "}", ")", ";", "}" ]
Parse incoming message from MQTT @method parseMQTTMessage @param {String} topic Topic channel the event came from @param {String} message Contents of the event
[ "Parse", "incoming", "message", "from", "MQTT" ]
066d3f492e2f9d9016964bef191230b99cb4e0c8
https://github.com/stjohnjohnson/smartthings-mqtt-bridge/blob/066d3f492e2f9d9016964bef191230b99cb4e0c8/server.js#L252-L306
9,561
publiclab/PublicLab.Editor
src/modules/PublicLab.TitleModule.Related.js
build
function build() { module.el.find('.ple-module-content').append('<div style="display:none;" class="ple-title-related"></div>'); relatedEl = module.el.find('.ple-title-related'); relatedEl.append('<p class="ple-help">Does your work relate to one of these? Click to alert those contributors.</p><hr style="margin: 4px 0;" />'); }
javascript
function build() { module.el.find('.ple-module-content').append('<div style="display:none;" class="ple-title-related"></div>'); relatedEl = module.el.find('.ple-title-related'); relatedEl.append('<p class="ple-help">Does your work relate to one of these? Click to alert those contributors.</p><hr style="margin: 4px 0;" />'); }
[ "function", "build", "(", ")", "{", "module", ".", "el", ".", "find", "(", "'.ple-module-content'", ")", ".", "append", "(", "'<div style=\"display:none;\" class=\"ple-title-related\"></div>'", ")", ";", "relatedEl", "=", "module", ".", "el", ".", "find", "(", "'.ple-title-related'", ")", ";", "relatedEl", ".", "append", "(", "'<p class=\"ple-help\">Does your work relate to one of these? Click to alert those contributors.</p><hr style=\"margin: 4px 0;\" />'", ")", ";", "}" ]
make an area for "related posts" to connect to
[ "make", "an", "area", "for", "related", "posts", "to", "connect", "to" ]
03b7b24682aa860f6f589e93098dd12c496687b3
https://github.com/publiclab/PublicLab.Editor/blob/03b7b24682aa860f6f589e93098dd12c496687b3/src/modules/PublicLab.TitleModule.Related.js#L34-L40
9,562
publiclab/PublicLab.Editor
src/adapters/PublicLab.Formatter.js
function() { var _formatter = this; // functions that accept standard <data> and output form data for known services _formatter.schemas = { "publiclab": function(data) { var output = {}; output.title = data.title || null; output.body = data.body || null; // we can remove this from server req, since we're authenticated output.authenticity_token = data.token || null; // Whether note will be draft or not output.draft = data.draft || false; // Optional: output.tags = data.tags || null; // comma delimited output.has_main_image = data.has_main_image || null; output.main_image = data.main_image || null; // id to associate with pre-uploaded image output.node_images = data.node_images || null; // comma-separated image.ids, I think // photo is probably actually a multipart, but we pre-upload anyways, so probably not necessary: output.image = { }; output.image.photo = data.image || null; return output; }//, // "drupal": { // "title": null, // "body": null // } } _formatter.convert = function(data, destination) { // return formatted version of data return _formatter.schemas[destination](data); } }
javascript
function() { var _formatter = this; // functions that accept standard <data> and output form data for known services _formatter.schemas = { "publiclab": function(data) { var output = {}; output.title = data.title || null; output.body = data.body || null; // we can remove this from server req, since we're authenticated output.authenticity_token = data.token || null; // Whether note will be draft or not output.draft = data.draft || false; // Optional: output.tags = data.tags || null; // comma delimited output.has_main_image = data.has_main_image || null; output.main_image = data.main_image || null; // id to associate with pre-uploaded image output.node_images = data.node_images || null; // comma-separated image.ids, I think // photo is probably actually a multipart, but we pre-upload anyways, so probably not necessary: output.image = { }; output.image.photo = data.image || null; return output; }//, // "drupal": { // "title": null, // "body": null // } } _formatter.convert = function(data, destination) { // return formatted version of data return _formatter.schemas[destination](data); } }
[ "function", "(", ")", "{", "var", "_formatter", "=", "this", ";", "// functions that accept standard <data> and output form data for known services", "_formatter", ".", "schemas", "=", "{", "\"publiclab\"", ":", "function", "(", "data", ")", "{", "var", "output", "=", "{", "}", ";", "output", ".", "title", "=", "data", ".", "title", "||", "null", ";", "output", ".", "body", "=", "data", ".", "body", "||", "null", ";", "// we can remove this from server req, since we're authenticated", "output", ".", "authenticity_token", "=", "data", ".", "token", "||", "null", ";", "// Whether note will be draft or not", "output", ".", "draft", "=", "data", ".", "draft", "||", "false", ";", "// Optional:", "output", ".", "tags", "=", "data", ".", "tags", "||", "null", ";", "// comma delimited", "output", ".", "has_main_image", "=", "data", ".", "has_main_image", "||", "null", ";", "output", ".", "main_image", "=", "data", ".", "main_image", "||", "null", ";", "// id to associate with pre-uploaded image", "output", ".", "node_images", "=", "data", ".", "node_images", "||", "null", ";", "// comma-separated image.ids, I think", "// photo is probably actually a multipart, but we pre-upload anyways, so probably not necessary:", "output", ".", "image", "=", "{", "}", ";", "output", ".", "image", ".", "photo", "=", "data", ".", "image", "||", "null", ";", "return", "output", ";", "}", "//,", "// \"drupal\": {", "// \"title\": null,", "// \"body\": null", "// }", "}", "_formatter", ".", "convert", "=", "function", "(", "data", ",", "destination", ")", "{", "// return formatted version of data", "return", "_formatter", ".", "schemas", "[", "destination", "]", "(", "data", ")", ";", "}", "}" ]
eventually we could accept both a format and a URL
[ "eventually", "we", "could", "accept", "both", "a", "format", "and", "a", "URL" ]
03b7b24682aa860f6f589e93098dd12c496687b3
https://github.com/publiclab/PublicLab.Editor/blob/03b7b24682aa860f6f589e93098dd12c496687b3/src/adapters/PublicLab.Formatter.js#L12-L61
9,563
PhilWaldmann/openrecord
lib/base/save.js
function(options) { var self = this options = options || {} if (typeof options === 'function') throw new Error('then!') return self .validate() .then(function() { return self._create_or_update(options) }) .then(function() { // eliminate changes -> we just saved it to the database! self.changes = {} }) .then(function() { return self }) }
javascript
function(options) { var self = this options = options || {} if (typeof options === 'function') throw new Error('then!') return self .validate() .then(function() { return self._create_or_update(options) }) .then(function() { // eliminate changes -> we just saved it to the database! self.changes = {} }) .then(function() { return self }) }
[ "function", "(", "options", ")", "{", "var", "self", "=", "this", "options", "=", "options", "||", "{", "}", "if", "(", "typeof", "options", "===", "'function'", ")", "throw", "new", "Error", "(", "'then!'", ")", "return", "self", ".", "validate", "(", ")", ".", "then", "(", "function", "(", ")", "{", "return", "self", ".", "_create_or_update", "(", "options", ")", "}", ")", ".", "then", "(", "function", "(", ")", "{", "// eliminate changes -> we just saved it to the database!", "self", ".", "changes", "=", "{", "}", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "self", "}", ")", "}" ]
Save the current record @class Record @method save
[ "Save", "the", "current", "record" ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/base/save.js#L10-L27
9,564
PhilWaldmann/openrecord
lib/base/json.js
function(allowedAttributes, exportObject) { var definition = this.definition var tmp = exportObject || definition.store.utils.clone(this.attributes) for (var i in definition.relations) { var relation = definition.relations[i] if (this['_' + relation.name]) { tmp[relation.name] = this['_' + relation.name] if (typeof tmp[relation.name].toJson === 'function') tmp[relation.name] = tmp[relation.name].toJson() } } if (!allowedAttributes && this.allowedAttributes) allowedAttributes = this.allowedAttributes for (var name in tmp) { if (allowedAttributes && allowedAttributes.indexOf(name) === -1) { delete tmp[name] } else { if ( definition.attributes && definition.attributes[name] && definition.attributes[name].hidden !== true ) { tmp[name] = definition.cast(name, tmp[name], 'output', this) if (tmp[name] && typeof tmp[name].toJson === 'function'){ tmp[name] = tmp[name].toJson() } // convert to external names var value = tmp[name] delete tmp[name] tmp[definition.attributes[name].name] = value } } } return tmp }
javascript
function(allowedAttributes, exportObject) { var definition = this.definition var tmp = exportObject || definition.store.utils.clone(this.attributes) for (var i in definition.relations) { var relation = definition.relations[i] if (this['_' + relation.name]) { tmp[relation.name] = this['_' + relation.name] if (typeof tmp[relation.name].toJson === 'function') tmp[relation.name] = tmp[relation.name].toJson() } } if (!allowedAttributes && this.allowedAttributes) allowedAttributes = this.allowedAttributes for (var name in tmp) { if (allowedAttributes && allowedAttributes.indexOf(name) === -1) { delete tmp[name] } else { if ( definition.attributes && definition.attributes[name] && definition.attributes[name].hidden !== true ) { tmp[name] = definition.cast(name, tmp[name], 'output', this) if (tmp[name] && typeof tmp[name].toJson === 'function'){ tmp[name] = tmp[name].toJson() } // convert to external names var value = tmp[name] delete tmp[name] tmp[definition.attributes[name].name] = value } } } return tmp }
[ "function", "(", "allowedAttributes", ",", "exportObject", ")", "{", "var", "definition", "=", "this", ".", "definition", "var", "tmp", "=", "exportObject", "||", "definition", ".", "store", ".", "utils", ".", "clone", "(", "this", ".", "attributes", ")", "for", "(", "var", "i", "in", "definition", ".", "relations", ")", "{", "var", "relation", "=", "definition", ".", "relations", "[", "i", "]", "if", "(", "this", "[", "'_'", "+", "relation", ".", "name", "]", ")", "{", "tmp", "[", "relation", ".", "name", "]", "=", "this", "[", "'_'", "+", "relation", ".", "name", "]", "if", "(", "typeof", "tmp", "[", "relation", ".", "name", "]", ".", "toJson", "===", "'function'", ")", "tmp", "[", "relation", ".", "name", "]", "=", "tmp", "[", "relation", ".", "name", "]", ".", "toJson", "(", ")", "}", "}", "if", "(", "!", "allowedAttributes", "&&", "this", ".", "allowedAttributes", ")", "allowedAttributes", "=", "this", ".", "allowedAttributes", "for", "(", "var", "name", "in", "tmp", ")", "{", "if", "(", "allowedAttributes", "&&", "allowedAttributes", ".", "indexOf", "(", "name", ")", "===", "-", "1", ")", "{", "delete", "tmp", "[", "name", "]", "}", "else", "{", "if", "(", "definition", ".", "attributes", "&&", "definition", ".", "attributes", "[", "name", "]", "&&", "definition", ".", "attributes", "[", "name", "]", ".", "hidden", "!==", "true", ")", "{", "tmp", "[", "name", "]", "=", "definition", ".", "cast", "(", "name", ",", "tmp", "[", "name", "]", ",", "'output'", ",", "this", ")", "if", "(", "tmp", "[", "name", "]", "&&", "typeof", "tmp", "[", "name", "]", ".", "toJson", "===", "'function'", ")", "{", "tmp", "[", "name", "]", "=", "tmp", "[", "name", "]", ".", "toJson", "(", ")", "}", "// convert to external names", "var", "value", "=", "tmp", "[", "name", "]", "delete", "tmp", "[", "name", "]", "tmp", "[", "definition", ".", "attributes", "[", "name", "]", ".", "name", "]", "=", "value", "}", "}", "}", "return", "tmp", "}" ]
Returns an object which represent the record in plain json @class Record @method toJson @param {array} allowedAttributes - Optional: Only export the given attributes and/or relations @param {object} exportObject - Optional: By default, OpenRecord clones the `attributes` object. If you specify the `exportObject` it will use this instead. @return {object}
[ "Returns", "an", "object", "which", "represent", "the", "record", "in", "plain", "json" ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/base/json.js#L12-L52
9,565
PhilWaldmann/openrecord
lib/base/json.js
function(allowedAttributes) { var tmp = [] this.forEach(function(record) { tmp.push(record.toJson(allowedAttributes)) }) return tmp }
javascript
function(allowedAttributes) { var tmp = [] this.forEach(function(record) { tmp.push(record.toJson(allowedAttributes)) }) return tmp }
[ "function", "(", "allowedAttributes", ")", "{", "var", "tmp", "=", "[", "]", "this", ".", "forEach", "(", "function", "(", "record", ")", "{", "tmp", ".", "push", "(", "record", ".", "toJson", "(", "allowedAttributes", ")", ")", "}", ")", "return", "tmp", "}" ]
Returns an array of objects which represent the records in plain json @class Collection @method toJson @param {array} allowedAttributes - Optional: Only export the given attributes and/or relations @return {array}
[ "Returns", "an", "array", "of", "objects", "which", "represent", "the", "records", "in", "plain", "json" ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/base/json.js#L70-L76
9,566
PhilWaldmann/openrecord
lib/base/scope.js
function(name, fn, lazy) { const Utils = this.store.utils if (!fn && this.model) fn = this.model[name] if (!fn) throw new Error('You need to provide a function in order to use a scope') var tmp = function() { var args = Utils.args(arguments) const self = this.chain()._unresolve() // if the collection is already resolved, return a unresolved and empty copy! if (lazy) { self.addInternal('active_scopes', function() { return fn.apply(this, args) }) } else { fn.apply(self, args) } return self } this.staticMethods[name] = tmp return this }
javascript
function(name, fn, lazy) { const Utils = this.store.utils if (!fn && this.model) fn = this.model[name] if (!fn) throw new Error('You need to provide a function in order to use a scope') var tmp = function() { var args = Utils.args(arguments) const self = this.chain()._unresolve() // if the collection is already resolved, return a unresolved and empty copy! if (lazy) { self.addInternal('active_scopes', function() { return fn.apply(this, args) }) } else { fn.apply(self, args) } return self } this.staticMethods[name] = tmp return this }
[ "function", "(", "name", ",", "fn", ",", "lazy", ")", "{", "const", "Utils", "=", "this", ".", "store", ".", "utils", "if", "(", "!", "fn", "&&", "this", ".", "model", ")", "fn", "=", "this", ".", "model", "[", "name", "]", "if", "(", "!", "fn", ")", "throw", "new", "Error", "(", "'You need to provide a function in order to use a scope'", ")", "var", "tmp", "=", "function", "(", ")", "{", "var", "args", "=", "Utils", ".", "args", "(", "arguments", ")", "const", "self", "=", "this", ".", "chain", "(", ")", ".", "_unresolve", "(", ")", "// if the collection is already resolved, return a unresolved and empty copy!", "if", "(", "lazy", ")", "{", "self", ".", "addInternal", "(", "'active_scopes'", ",", "function", "(", ")", "{", "return", "fn", ".", "apply", "(", "this", ",", "args", ")", "}", ")", "}", "else", "{", "fn", ".", "apply", "(", "self", ",", "args", ")", "}", "return", "self", "}", "this", ".", "staticMethods", "[", "name", "]", "=", "tmp", "return", "this", "}" ]
scope callback function @public @callback scopeFN @param {*} args - All caller arguments @return * @this Model Creates a custom chained Model method @public @memberof Definition @method scope @param {string} name - The name of the scope @param {scopeFN} callback - The scope function @return {Definition}
[ "scope", "callback", "function" ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/base/scope.js#L35-L60
9,567
PhilWaldmann/openrecord
lib/base/chainable.js
function(options) { options = options || {} if (this.chained && options.clone !== true) return this var ChainModel = new this.definition.ChainGenerator(options) if (this.chained && options.clone === true) { ChainModel._internal_attributes = this.definition.store.utils.clone( this._internal_attributes, options.exclude ) ChainModel._internal_attributes.cloned_relation_to = ChainModel._internal_attributes.relation_to ChainModel.clearInternal('relation_to') } return ChainModel.callDefaultScopes() }
javascript
function(options) { options = options || {} if (this.chained && options.clone !== true) return this var ChainModel = new this.definition.ChainGenerator(options) if (this.chained && options.clone === true) { ChainModel._internal_attributes = this.definition.store.utils.clone( this._internal_attributes, options.exclude ) ChainModel._internal_attributes.cloned_relation_to = ChainModel._internal_attributes.relation_to ChainModel.clearInternal('relation_to') } return ChainModel.callDefaultScopes() }
[ "function", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", "if", "(", "this", ".", "chained", "&&", "options", ".", "clone", "!==", "true", ")", "return", "this", "var", "ChainModel", "=", "new", "this", ".", "definition", ".", "ChainGenerator", "(", "options", ")", "if", "(", "this", ".", "chained", "&&", "options", ".", "clone", "===", "true", ")", "{", "ChainModel", ".", "_internal_attributes", "=", "this", ".", "definition", ".", "store", ".", "utils", ".", "clone", "(", "this", ".", "_internal_attributes", ",", "options", ".", "exclude", ")", "ChainModel", ".", "_internal_attributes", ".", "cloned_relation_to", "=", "ChainModel", ".", "_internal_attributes", ".", "relation_to", "ChainModel", ".", "clearInternal", "(", "'relation_to'", ")", "}", "return", "ChainModel", ".", "callDefaultScopes", "(", ")", "}" ]
Returns a Collection, which is in fact a cloned Model - or a chained Model A Collectioin is an Array with all of Models' methods. All `where`, `limit`, `setContext`, ... information will be stored in this chained Model to allow asynchronous usage. @class Model @method chain @param {object} options - The options hash @param {boolean} options.clone - Clone a existing chained object. Default: false @return {Collection}
[ "Returns", "a", "Collection", "which", "is", "in", "fact", "a", "cloned", "Model", "-", "or", "a", "chained", "Model", "A", "Collectioin", "is", "an", "Array", "with", "all", "of", "Models", "methods", ".", "All", "where", "limit", "setContext", "...", "information", "will", "be", "stored", "in", "this", "chained", "Model", "to", "allow", "asynchronous", "usage", "." ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/base/chainable.js#L82-L98
9,568
PhilWaldmann/openrecord
lib/base/relations.js
function() { var self = this Object.keys(this.definition.relations).forEach(function(key) { delete self.relations[key] }) return this }
javascript
function() { var self = this Object.keys(this.definition.relations).forEach(function(key) { delete self.relations[key] }) return this }
[ "function", "(", ")", "{", "var", "self", "=", "this", "Object", ".", "keys", "(", "this", ".", "definition", ".", "relations", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "delete", "self", ".", "relations", "[", "key", "]", "}", ")", "return", "this", "}" ]
clear all loadede relations
[ "clear", "all", "loadede", "relations" ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/base/relations.js#L276-L284
9,569
PhilWaldmann/openrecord
lib/base/attributes.js
function(name, type, options) { const Store = require('../store') options = options || {} type = type || String if (typeof type === 'string') { type = type.toLowerCase() } var fieldType = this.store.getType(type) if (!fieldType) { throw new Store.UnknownAttributeTypeError(type) } Object.assign(options, fieldType.defaults) options.name = this.store.toExternalAttributeName(name) options.type = fieldType options.writable = options.writable === undefined ? true : !!options.writable options.readable = options.readable === undefined ? true : !!options.readable options.track_object_changes = options.track_object_changes === undefined ? false : !!options.track_object_changes options.notifications = [] this.attributes[name] = options this.setter( name, options.setter || function(value) { this.set(options.name, value) } ) if (options.readable || options.getter) { this.getter( name, options.getter || function() { return this.get(name) }, true ) } return this }
javascript
function(name, type, options) { const Store = require('../store') options = options || {} type = type || String if (typeof type === 'string') { type = type.toLowerCase() } var fieldType = this.store.getType(type) if (!fieldType) { throw new Store.UnknownAttributeTypeError(type) } Object.assign(options, fieldType.defaults) options.name = this.store.toExternalAttributeName(name) options.type = fieldType options.writable = options.writable === undefined ? true : !!options.writable options.readable = options.readable === undefined ? true : !!options.readable options.track_object_changes = options.track_object_changes === undefined ? false : !!options.track_object_changes options.notifications = [] this.attributes[name] = options this.setter( name, options.setter || function(value) { this.set(options.name, value) } ) if (options.readable || options.getter) { this.getter( name, options.getter || function() { return this.get(name) }, true ) } return this }
[ "function", "(", "name", ",", "type", ",", "options", ")", "{", "const", "Store", "=", "require", "(", "'../store'", ")", "options", "=", "options", "||", "{", "}", "type", "=", "type", "||", "String", "if", "(", "typeof", "type", "===", "'string'", ")", "{", "type", "=", "type", ".", "toLowerCase", "(", ")", "}", "var", "fieldType", "=", "this", ".", "store", ".", "getType", "(", "type", ")", "if", "(", "!", "fieldType", ")", "{", "throw", "new", "Store", ".", "UnknownAttributeTypeError", "(", "type", ")", "}", "Object", ".", "assign", "(", "options", ",", "fieldType", ".", "defaults", ")", "options", ".", "name", "=", "this", ".", "store", ".", "toExternalAttributeName", "(", "name", ")", "options", ".", "type", "=", "fieldType", "options", ".", "writable", "=", "options", ".", "writable", "===", "undefined", "?", "true", ":", "!", "!", "options", ".", "writable", "options", ".", "readable", "=", "options", ".", "readable", "===", "undefined", "?", "true", ":", "!", "!", "options", ".", "readable", "options", ".", "track_object_changes", "=", "options", ".", "track_object_changes", "===", "undefined", "?", "false", ":", "!", "!", "options", ".", "track_object_changes", "options", ".", "notifications", "=", "[", "]", "this", ".", "attributes", "[", "name", "]", "=", "options", "this", ".", "setter", "(", "name", ",", "options", ".", "setter", "||", "function", "(", "value", ")", "{", "this", ".", "set", "(", "options", ".", "name", ",", "value", ")", "}", ")", "if", "(", "options", ".", "readable", "||", "options", ".", "getter", ")", "{", "this", ".", "getter", "(", "name", ",", "options", ".", "getter", "||", "function", "(", ")", "{", "return", "this", ".", "get", "(", "name", ")", "}", ",", "true", ")", "}", "return", "this", "}" ]
Add a new attribute to your Model @public @memberof Definition @method attribute @param {string} name - The attribute name @param {string} type - The attribute type (e.g. `text`, `integer`, or sql language specific. e.g. `blob`) @param {object} [options] - Optional options @param {boolean} [options.writable=true] - make it writeable @param {boolean} [options.readable=true] - make it readable @param {any} [options.default=null] - Default value @param {boolean} [options.emit_events=false] - emit change events `name_changed` @return {Definition}
[ "Add", "a", "new", "attribute", "to", "your", "Model" ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/base/attributes.js#L56-L106
9,570
PhilWaldmann/openrecord
lib/base/attributes.js
function(name, fn) { const externalName = this.store.toExternalAttributeName(name) this.instanceMethods.__defineSetter__(name, fn) if(externalName !== name) this.instanceMethods.__defineSetter__(externalName, fn) return this }
javascript
function(name, fn) { const externalName = this.store.toExternalAttributeName(name) this.instanceMethods.__defineSetter__(name, fn) if(externalName !== name) this.instanceMethods.__defineSetter__(externalName, fn) return this }
[ "function", "(", "name", ",", "fn", ")", "{", "const", "externalName", "=", "this", ".", "store", ".", "toExternalAttributeName", "(", "name", ")", "this", ".", "instanceMethods", ".", "__defineSetter__", "(", "name", ",", "fn", ")", "if", "(", "externalName", "!==", "name", ")", "this", ".", "instanceMethods", ".", "__defineSetter__", "(", "externalName", ",", "fn", ")", "return", "this", "}" ]
Add a custom setter to your record @class Definition @method setter @param {string} name - The setter name @param {function} fn - The method to call @return {Definition}
[ "Add", "a", "custom", "setter", "to", "your", "record" ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/base/attributes.js#L169-L174
9,571
PhilWaldmann/openrecord
lib/base/attributes.js
function(name, fn) { const _name = this.store.toInternalAttributeName(name) const Store = require('../store') if (!this.attributes[_name]) throw new Store.UnknownAttributeError(name) this.attributes[_name].variant = fn this[name + '$'] = function(args) { return fn.call(this, this[_name], args) } return this }
javascript
function(name, fn) { const _name = this.store.toInternalAttributeName(name) const Store = require('../store') if (!this.attributes[_name]) throw new Store.UnknownAttributeError(name) this.attributes[_name].variant = fn this[name + '$'] = function(args) { return fn.call(this, this[_name], args) } return this }
[ "function", "(", "name", ",", "fn", ")", "{", "const", "_name", "=", "this", ".", "store", ".", "toInternalAttributeName", "(", "name", ")", "const", "Store", "=", "require", "(", "'../store'", ")", "if", "(", "!", "this", ".", "attributes", "[", "_name", "]", ")", "throw", "new", "Store", ".", "UnknownAttributeError", "(", "name", ")", "this", ".", "attributes", "[", "_name", "]", ".", "variant", "=", "fn", "this", "[", "name", "+", "'$'", "]", "=", "function", "(", "args", ")", "{", "return", "fn", ".", "call", "(", "this", ",", "this", "[", "_name", "]", ",", "args", ")", "}", "return", "this", "}" ]
Add a variant method to the specified attribute @class Definition @method variant @param {string} name - The attribute name @param {function} fn - The method to call @return {Definition}
[ "Add", "a", "variant", "method", "to", "the", "specified", "attribute" ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/base/attributes.js#L186-L198
9,572
PhilWaldmann/openrecord
lib/base/attributes.js
function(name, value) { if (!name && !value) return var values = name var castType = value var singleAssign = false if (typeof name === 'string') { values = {} values[name] = value castType = 'input' singleAssign = true } for (var field in this.definition.attributes) { if (this.definition.attributes.hasOwnProperty(field)) { var definition = this.definition.attributes[field] var fieldName = castType === 'input' ? definition.name : field if (singleAssign && values[fieldName] === undefined) { continue } value = values[fieldName] if (!singleAssign && value && typeof definition.setter === 'function') { definition.setter.call(this, value) continue } if ( value === undefined && this.attributes[field] === undefined && definition.default !== undefined ) { if (typeof definition.default === 'function') value = definition.default() else value = this.definition.store.utils.clone(definition.default) } if (value === undefined && this.attributes[field] !== undefined) { value = this.attributes[field] } if (value === undefined) { value = null } // typecasted value castType = castType || 'input' if (!definition.type.cast[castType]) { castType = 'input' } value = value !== null ? this.definition.cast(field, value, castType, this) : null if (this.attributes[field] !== value) { if (value && typeof value === 'object') { // automatically set object tracking to true if the value is still an object after the casting definition.track_object_changes = true } if ( definition.writable && !(value === null && this.attributes[field] === undefined) ) { var beforeValue = this[field] var afterValue = value if (this.changes[field]) { this.changes[field][1] = afterValue } else { this.changes[field] = [beforeValue, afterValue] } } if ( definition.track_object_changes && (this.object_changes[field] === undefined || castType !== 'input') ) { // initial object hash this.object_changes[field] = [ this.definition.store.utils.getHash(value), JSON.stringify(value) ] } if (definition.notifications) { definition.notifications.forEach(function(fn) { fn.call(this, value, castType) }, this) } this.attributes[field] = value // TODO: remove in 2.1! if (definition.emit_events && beforeValue !== value) { // emit old_value, new_value this.definition.emit(field + '_changed', this, beforeValue, value) } } } } return this }
javascript
function(name, value) { if (!name && !value) return var values = name var castType = value var singleAssign = false if (typeof name === 'string') { values = {} values[name] = value castType = 'input' singleAssign = true } for (var field in this.definition.attributes) { if (this.definition.attributes.hasOwnProperty(field)) { var definition = this.definition.attributes[field] var fieldName = castType === 'input' ? definition.name : field if (singleAssign && values[fieldName] === undefined) { continue } value = values[fieldName] if (!singleAssign && value && typeof definition.setter === 'function') { definition.setter.call(this, value) continue } if ( value === undefined && this.attributes[field] === undefined && definition.default !== undefined ) { if (typeof definition.default === 'function') value = definition.default() else value = this.definition.store.utils.clone(definition.default) } if (value === undefined && this.attributes[field] !== undefined) { value = this.attributes[field] } if (value === undefined) { value = null } // typecasted value castType = castType || 'input' if (!definition.type.cast[castType]) { castType = 'input' } value = value !== null ? this.definition.cast(field, value, castType, this) : null if (this.attributes[field] !== value) { if (value && typeof value === 'object') { // automatically set object tracking to true if the value is still an object after the casting definition.track_object_changes = true } if ( definition.writable && !(value === null && this.attributes[field] === undefined) ) { var beforeValue = this[field] var afterValue = value if (this.changes[field]) { this.changes[field][1] = afterValue } else { this.changes[field] = [beforeValue, afterValue] } } if ( definition.track_object_changes && (this.object_changes[field] === undefined || castType !== 'input') ) { // initial object hash this.object_changes[field] = [ this.definition.store.utils.getHash(value), JSON.stringify(value) ] } if (definition.notifications) { definition.notifications.forEach(function(fn) { fn.call(this, value, castType) }, this) } this.attributes[field] = value // TODO: remove in 2.1! if (definition.emit_events && beforeValue !== value) { // emit old_value, new_value this.definition.emit(field + '_changed', this, beforeValue, value) } } } } return this }
[ "function", "(", "name", ",", "value", ")", "{", "if", "(", "!", "name", "&&", "!", "value", ")", "return", "var", "values", "=", "name", "var", "castType", "=", "value", "var", "singleAssign", "=", "false", "if", "(", "typeof", "name", "===", "'string'", ")", "{", "values", "=", "{", "}", "values", "[", "name", "]", "=", "value", "castType", "=", "'input'", "singleAssign", "=", "true", "}", "for", "(", "var", "field", "in", "this", ".", "definition", ".", "attributes", ")", "{", "if", "(", "this", ".", "definition", ".", "attributes", ".", "hasOwnProperty", "(", "field", ")", ")", "{", "var", "definition", "=", "this", ".", "definition", ".", "attributes", "[", "field", "]", "var", "fieldName", "=", "castType", "===", "'input'", "?", "definition", ".", "name", ":", "field", "if", "(", "singleAssign", "&&", "values", "[", "fieldName", "]", "===", "undefined", ")", "{", "continue", "}", "value", "=", "values", "[", "fieldName", "]", "if", "(", "!", "singleAssign", "&&", "value", "&&", "typeof", "definition", ".", "setter", "===", "'function'", ")", "{", "definition", ".", "setter", ".", "call", "(", "this", ",", "value", ")", "continue", "}", "if", "(", "value", "===", "undefined", "&&", "this", ".", "attributes", "[", "field", "]", "===", "undefined", "&&", "definition", ".", "default", "!==", "undefined", ")", "{", "if", "(", "typeof", "definition", ".", "default", "===", "'function'", ")", "value", "=", "definition", ".", "default", "(", ")", "else", "value", "=", "this", ".", "definition", ".", "store", ".", "utils", ".", "clone", "(", "definition", ".", "default", ")", "}", "if", "(", "value", "===", "undefined", "&&", "this", ".", "attributes", "[", "field", "]", "!==", "undefined", ")", "{", "value", "=", "this", ".", "attributes", "[", "field", "]", "}", "if", "(", "value", "===", "undefined", ")", "{", "value", "=", "null", "}", "// typecasted value", "castType", "=", "castType", "||", "'input'", "if", "(", "!", "definition", ".", "type", ".", "cast", "[", "castType", "]", ")", "{", "castType", "=", "'input'", "}", "value", "=", "value", "!==", "null", "?", "this", ".", "definition", ".", "cast", "(", "field", ",", "value", ",", "castType", ",", "this", ")", ":", "null", "if", "(", "this", ".", "attributes", "[", "field", "]", "!==", "value", ")", "{", "if", "(", "value", "&&", "typeof", "value", "===", "'object'", ")", "{", "// automatically set object tracking to true if the value is still an object after the casting", "definition", ".", "track_object_changes", "=", "true", "}", "if", "(", "definition", ".", "writable", "&&", "!", "(", "value", "===", "null", "&&", "this", ".", "attributes", "[", "field", "]", "===", "undefined", ")", ")", "{", "var", "beforeValue", "=", "this", "[", "field", "]", "var", "afterValue", "=", "value", "if", "(", "this", ".", "changes", "[", "field", "]", ")", "{", "this", ".", "changes", "[", "field", "]", "[", "1", "]", "=", "afterValue", "}", "else", "{", "this", ".", "changes", "[", "field", "]", "=", "[", "beforeValue", ",", "afterValue", "]", "}", "}", "if", "(", "definition", ".", "track_object_changes", "&&", "(", "this", ".", "object_changes", "[", "field", "]", "===", "undefined", "||", "castType", "!==", "'input'", ")", ")", "{", "// initial object hash", "this", ".", "object_changes", "[", "field", "]", "=", "[", "this", ".", "definition", ".", "store", ".", "utils", ".", "getHash", "(", "value", ")", ",", "JSON", ".", "stringify", "(", "value", ")", "]", "}", "if", "(", "definition", ".", "notifications", ")", "{", "definition", ".", "notifications", ".", "forEach", "(", "function", "(", "fn", ")", "{", "fn", ".", "call", "(", "this", ",", "value", ",", "castType", ")", "}", ",", "this", ")", "}", "this", ".", "attributes", "[", "field", "]", "=", "value", "// TODO: remove in 2.1!", "if", "(", "definition", ".", "emit_events", "&&", "beforeValue", "!==", "value", ")", "{", "// emit old_value, new_value", "this", ".", "definition", ".", "emit", "(", "field", "+", "'_changed'", ",", "this", ",", "beforeValue", ",", "value", ")", "}", "}", "}", "}", "return", "this", "}" ]
Set one or multiple attributes of a Record. @class Record @method set @param {string} name - The attributes name @param {VALUE} value - The attributes value @or @param {object} attributes - Multiple attribute as an object @param {string} cast_type - Optional cast_type name (Default: `input`) @return {Record}
[ "Set", "one", "or", "multiple", "attributes", "of", "a", "Record", "." ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/base/attributes.js#L229-L337
9,573
PhilWaldmann/openrecord
lib/base/attributes.js
function(name) { var attr = this.definition.attributes[name] if (attr) { // set undefined values to null if (this.attributes[name] === undefined) { this.attributes[name] = null } return this.definition.cast(name, this.attributes[name], 'output', this) } return null }
javascript
function(name) { var attr = this.definition.attributes[name] if (attr) { // set undefined values to null if (this.attributes[name] === undefined) { this.attributes[name] = null } return this.definition.cast(name, this.attributes[name], 'output', this) } return null }
[ "function", "(", "name", ")", "{", "var", "attr", "=", "this", ".", "definition", ".", "attributes", "[", "name", "]", "if", "(", "attr", ")", "{", "// set undefined values to null", "if", "(", "this", ".", "attributes", "[", "name", "]", "===", "undefined", ")", "{", "this", ".", "attributes", "[", "name", "]", "=", "null", "}", "return", "this", ".", "definition", ".", "cast", "(", "name", ",", "this", ".", "attributes", "[", "name", "]", ",", "'output'", ",", "this", ")", "}", "return", "null", "}" ]
Get an attributes. @class Record @method get @param {string} name - The attributes name @return {VALUE}
[ "Get", "an", "attributes", "." ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/base/attributes.js#L348-L361
9,574
PhilWaldmann/openrecord
lib/base/attributes.js
function() { this.checkObjectChanges() var tmp = {} for (var name in this.changes) { if (this.changes.hasOwnProperty(name)) { if ( !this.allowed_attributes || (this.allowed_attributes && this.allowed_attributes.indexOf(name) !== -1) ) { tmp[name] = this.changes[name] } } } return tmp }
javascript
function() { this.checkObjectChanges() var tmp = {} for (var name in this.changes) { if (this.changes.hasOwnProperty(name)) { if ( !this.allowed_attributes || (this.allowed_attributes && this.allowed_attributes.indexOf(name) !== -1) ) { tmp[name] = this.changes[name] } } } return tmp }
[ "function", "(", ")", "{", "this", ".", "checkObjectChanges", "(", ")", "var", "tmp", "=", "{", "}", "for", "(", "var", "name", "in", "this", ".", "changes", ")", "{", "if", "(", "this", ".", "changes", ".", "hasOwnProperty", "(", "name", ")", ")", "{", "if", "(", "!", "this", ".", "allowed_attributes", "||", "(", "this", ".", "allowed_attributes", "&&", "this", ".", "allowed_attributes", ".", "indexOf", "(", "name", ")", "!==", "-", "1", ")", ")", "{", "tmp", "[", "name", "]", "=", "this", ".", "changes", "[", "name", "]", "}", "}", "}", "return", "tmp", "}" ]
Returns an object with all the changes. One attribute will always include the original and current value @class Record @method getChanges @return {object}
[ "Returns", "an", "object", "with", "all", "the", "changes", ".", "One", "attribute", "will", "always", "include", "the", "original", "and", "current", "value" ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/base/attributes.js#L397-L412
9,575
PhilWaldmann/openrecord
lib/base/attributes.js
function() { for (var name in this.changes) { if (this.changes.hasOwnProperty(name)) { this.attributes[name] = this.changes[name][0] } } this.changes = {} return this }
javascript
function() { for (var name in this.changes) { if (this.changes.hasOwnProperty(name)) { this.attributes[name] = this.changes[name][0] } } this.changes = {} return this }
[ "function", "(", ")", "{", "for", "(", "var", "name", "in", "this", ".", "changes", ")", "{", "if", "(", "this", ".", "changes", ".", "hasOwnProperty", "(", "name", ")", ")", "{", "this", ".", "attributes", "[", "name", "]", "=", "this", ".", "changes", "[", "name", "]", "[", "0", "]", "}", "}", "this", ".", "changes", "=", "{", "}", "return", "this", "}" ]
Resets all changes to the original values @class Record @method resetChanges @return {Record}
[ "Resets", "all", "changes", "to", "the", "original", "values" ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/base/attributes.js#L447-L456
9,576
PhilWaldmann/openrecord
lib/base/conditions.js
function() { const Utils = this.definition.store.utils const self = this.chain()._unresolve() // if the collection is already resolved, return a unresolved and empty copy! const existingConditions = self.getInternal('conditions') || [] const existingMap = {} existingConditions.forEach(function(cond) { const key = cond.type + '|' + cond.attribute + '|' + cond.operator + '|' + JSON.stringify(cond.value) existingMap[key] = true }) var attributeNames = Object.keys(self.definition.attributes) attributeNames = attributeNames.concat(attributeNames.map(function(name){ return self.definition.attributes[name].name })) const parentRelations = self.getInternal('parent_relations') const conditions = Utils.toConditionList( Utils.args(arguments), attributeNames ) conditions.forEach(function(cond) { if ( cond.type === 'relation' && !self.definition.relations[cond.relation] && !self.options.polymorph ) { throw new Error( 'Can\'t find attribute or relation "' + cond.relation + '" for ' + self.definition.modelName ) } // used for joins only if (parentRelations) { cond.parents = parentRelations if (cond.value && cond.value.$attribute && !cond.value.$parents) { cond.value.$parents = parentRelations } } if(cond.attribute) cond.attribute = self.store.toInternalAttributeName(cond.attribute) const key = cond.type + '|' + cond.attribute + '|' + cond.operator + '|' + JSON.stringify(cond.value) if (existingMap[key] && cond.type !== 'raw') return self.addInternal('conditions', cond) }) return self }
javascript
function() { const Utils = this.definition.store.utils const self = this.chain()._unresolve() // if the collection is already resolved, return a unresolved and empty copy! const existingConditions = self.getInternal('conditions') || [] const existingMap = {} existingConditions.forEach(function(cond) { const key = cond.type + '|' + cond.attribute + '|' + cond.operator + '|' + JSON.stringify(cond.value) existingMap[key] = true }) var attributeNames = Object.keys(self.definition.attributes) attributeNames = attributeNames.concat(attributeNames.map(function(name){ return self.definition.attributes[name].name })) const parentRelations = self.getInternal('parent_relations') const conditions = Utils.toConditionList( Utils.args(arguments), attributeNames ) conditions.forEach(function(cond) { if ( cond.type === 'relation' && !self.definition.relations[cond.relation] && !self.options.polymorph ) { throw new Error( 'Can\'t find attribute or relation "' + cond.relation + '" for ' + self.definition.modelName ) } // used for joins only if (parentRelations) { cond.parents = parentRelations if (cond.value && cond.value.$attribute && !cond.value.$parents) { cond.value.$parents = parentRelations } } if(cond.attribute) cond.attribute = self.store.toInternalAttributeName(cond.attribute) const key = cond.type + '|' + cond.attribute + '|' + cond.operator + '|' + JSON.stringify(cond.value) if (existingMap[key] && cond.type !== 'raw') return self.addInternal('conditions', cond) }) return self }
[ "function", "(", ")", "{", "const", "Utils", "=", "this", ".", "definition", ".", "store", ".", "utils", "const", "self", "=", "this", ".", "chain", "(", ")", ".", "_unresolve", "(", ")", "// if the collection is already resolved, return a unresolved and empty copy!", "const", "existingConditions", "=", "self", ".", "getInternal", "(", "'conditions'", ")", "||", "[", "]", "const", "existingMap", "=", "{", "}", "existingConditions", ".", "forEach", "(", "function", "(", "cond", ")", "{", "const", "key", "=", "cond", ".", "type", "+", "'|'", "+", "cond", ".", "attribute", "+", "'|'", "+", "cond", ".", "operator", "+", "'|'", "+", "JSON", ".", "stringify", "(", "cond", ".", "value", ")", "existingMap", "[", "key", "]", "=", "true", "}", ")", "var", "attributeNames", "=", "Object", ".", "keys", "(", "self", ".", "definition", ".", "attributes", ")", "attributeNames", "=", "attributeNames", ".", "concat", "(", "attributeNames", ".", "map", "(", "function", "(", "name", ")", "{", "return", "self", ".", "definition", ".", "attributes", "[", "name", "]", ".", "name", "}", ")", ")", "const", "parentRelations", "=", "self", ".", "getInternal", "(", "'parent_relations'", ")", "const", "conditions", "=", "Utils", ".", "toConditionList", "(", "Utils", ".", "args", "(", "arguments", ")", ",", "attributeNames", ")", "conditions", ".", "forEach", "(", "function", "(", "cond", ")", "{", "if", "(", "cond", ".", "type", "===", "'relation'", "&&", "!", "self", ".", "definition", ".", "relations", "[", "cond", ".", "relation", "]", "&&", "!", "self", ".", "options", ".", "polymorph", ")", "{", "throw", "new", "Error", "(", "'Can\\'t find attribute or relation \"'", "+", "cond", ".", "relation", "+", "'\" for '", "+", "self", ".", "definition", ".", "modelName", ")", "}", "// used for joins only", "if", "(", "parentRelations", ")", "{", "cond", ".", "parents", "=", "parentRelations", "if", "(", "cond", ".", "value", "&&", "cond", ".", "value", ".", "$attribute", "&&", "!", "cond", ".", "value", ".", "$parents", ")", "{", "cond", ".", "value", ".", "$parents", "=", "parentRelations", "}", "}", "if", "(", "cond", ".", "attribute", ")", "cond", ".", "attribute", "=", "self", ".", "store", ".", "toInternalAttributeName", "(", "cond", ".", "attribute", ")", "const", "key", "=", "cond", ".", "type", "+", "'|'", "+", "cond", ".", "attribute", "+", "'|'", "+", "cond", ".", "operator", "+", "'|'", "+", "JSON", ".", "stringify", "(", "cond", ".", "value", ")", "if", "(", "existingMap", "[", "key", "]", "&&", "cond", ".", "type", "!==", "'raw'", ")", "return", "self", ".", "addInternal", "(", "'conditions'", ",", "cond", ")", "}", ")", "return", "self", "}" ]
Set some conditions @public @memberof Model @method where @param {(object|array)} conditions - every key-value pair will be translated into a condition @return {Model}
[ "Set", "some", "conditions" ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/base/conditions.js#L97-L165
9,577
PhilWaldmann/openrecord
lib/base/exec.js
function(resolve) { var self = this.chain() // if .find(null) was called if (self.getInternal('exec_null')) { return Promise.resolve(null) } var relation = self.getInternal('relation') if (relation && typeof relation.loadWithCollection === 'function') { const promise = relation.loadWithCollection(self) if (promise && promise.then) return promise.then(resolve) } var dataLoaded = self.getInternal('data_loaded') var options = self.getExecOptions() var data = {} if (dataLoaded) data.result = dataLoaded return self .callInterceptors('beforeFind', [options]) .then(function() { return self.callInterceptors('onFind', [options, data], { executeInParallel: true }) }) .then(function() { return self.callInterceptors('afterFind', [data]) }) .then(function() { if (typeof resolve === 'function') return resolve(data.result) return data.result }) }
javascript
function(resolve) { var self = this.chain() // if .find(null) was called if (self.getInternal('exec_null')) { return Promise.resolve(null) } var relation = self.getInternal('relation') if (relation && typeof relation.loadWithCollection === 'function') { const promise = relation.loadWithCollection(self) if (promise && promise.then) return promise.then(resolve) } var dataLoaded = self.getInternal('data_loaded') var options = self.getExecOptions() var data = {} if (dataLoaded) data.result = dataLoaded return self .callInterceptors('beforeFind', [options]) .then(function() { return self.callInterceptors('onFind', [options, data], { executeInParallel: true }) }) .then(function() { return self.callInterceptors('afterFind', [data]) }) .then(function() { if (typeof resolve === 'function') return resolve(data.result) return data.result }) }
[ "function", "(", "resolve", ")", "{", "var", "self", "=", "this", ".", "chain", "(", ")", "// if .find(null) was called", "if", "(", "self", ".", "getInternal", "(", "'exec_null'", ")", ")", "{", "return", "Promise", ".", "resolve", "(", "null", ")", "}", "var", "relation", "=", "self", ".", "getInternal", "(", "'relation'", ")", "if", "(", "relation", "&&", "typeof", "relation", ".", "loadWithCollection", "===", "'function'", ")", "{", "const", "promise", "=", "relation", ".", "loadWithCollection", "(", "self", ")", "if", "(", "promise", "&&", "promise", ".", "then", ")", "return", "promise", ".", "then", "(", "resolve", ")", "}", "var", "dataLoaded", "=", "self", ".", "getInternal", "(", "'data_loaded'", ")", "var", "options", "=", "self", ".", "getExecOptions", "(", ")", "var", "data", "=", "{", "}", "if", "(", "dataLoaded", ")", "data", ".", "result", "=", "dataLoaded", "return", "self", ".", "callInterceptors", "(", "'beforeFind'", ",", "[", "options", "]", ")", ".", "then", "(", "function", "(", ")", "{", "return", "self", ".", "callInterceptors", "(", "'onFind'", ",", "[", "options", ",", "data", "]", ",", "{", "executeInParallel", ":", "true", "}", ")", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "self", ".", "callInterceptors", "(", "'afterFind'", ",", "[", "data", "]", ")", "}", ")", ".", "then", "(", "function", "(", ")", "{", "if", "(", "typeof", "resolve", "===", "'function'", ")", "return", "resolve", "(", "data", ".", "result", ")", "return", "data", ".", "result", "}", ")", "}" ]
Executes the find @class Model @method exec @callback @param {array|object} result - Either a Collection of records or a single Record @this Collection
[ "Executes", "the", "find" ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/base/exec.js#L12-L47
9,578
PhilWaldmann/openrecord
lib/base/validations.js
function() { var self = this var validations = [] return self .callInterceptors('beforeValidation', [self]) .then(function() { for (var field in self.definition.validations) { var fieldValidations = self.definition.validations[field] // set the scope of all validator function to the current record for (var i in fieldValidations) { validations.push(fieldValidations[i].bind(self)) } } return self.store.utils.parallel(validations) }) .then(function(result) { if (self.errors.has) throw self.errors }) .then(function() { return self.callInterceptors('afterValidation', [self]) }) .then(function() { return self }) }
javascript
function() { var self = this var validations = [] return self .callInterceptors('beforeValidation', [self]) .then(function() { for (var field in self.definition.validations) { var fieldValidations = self.definition.validations[field] // set the scope of all validator function to the current record for (var i in fieldValidations) { validations.push(fieldValidations[i].bind(self)) } } return self.store.utils.parallel(validations) }) .then(function(result) { if (self.errors.has) throw self.errors }) .then(function() { return self.callInterceptors('afterValidation', [self]) }) .then(function() { return self }) }
[ "function", "(", ")", "{", "var", "self", "=", "this", "var", "validations", "=", "[", "]", "return", "self", ".", "callInterceptors", "(", "'beforeValidation'", ",", "[", "self", "]", ")", ".", "then", "(", "function", "(", ")", "{", "for", "(", "var", "field", "in", "self", ".", "definition", ".", "validations", ")", "{", "var", "fieldValidations", "=", "self", ".", "definition", ".", "validations", "[", "field", "]", "// set the scope of all validator function to the current record", "for", "(", "var", "i", "in", "fieldValidations", ")", "{", "validations", ".", "push", "(", "fieldValidations", "[", "i", "]", ".", "bind", "(", "self", ")", ")", "}", "}", "return", "self", ".", "store", ".", "utils", ".", "parallel", "(", "validations", ")", "}", ")", ".", "then", "(", "function", "(", "result", ")", "{", "if", "(", "self", ".", "errors", ".", "has", ")", "throw", "self", ".", "errors", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "self", ".", "callInterceptors", "(", "'afterValidation'", ",", "[", "self", "]", ")", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "self", "}", ")", "}" ]
validates the record @class Record @method validate @this Promise
[ "validates", "the", "record" ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/base/validations.js#L296-L322
9,579
PhilWaldmann/openrecord
lib/base/validations.js
function(resolve) { var self = this return this.validate() .then(function() { return true }) .catch(function(error) { if (error instanceof self.store.ValidationError) return false throw error }) .then(resolve) }
javascript
function(resolve) { var self = this return this.validate() .then(function() { return true }) .catch(function(error) { if (error instanceof self.store.ValidationError) return false throw error }) .then(resolve) }
[ "function", "(", "resolve", ")", "{", "var", "self", "=", "this", "return", "this", ".", "validate", "(", ")", ".", "then", "(", "function", "(", ")", "{", "return", "true", "}", ")", ".", "catch", "(", "function", "(", "error", ")", "{", "if", "(", "error", "instanceof", "self", ".", "store", ".", "ValidationError", ")", "return", "false", "throw", "error", "}", ")", ".", "then", "(", "resolve", ")", "}" ]
validates the record and returns true or false @class Record @method validate @this Promise
[ "validates", "the", "record", "and", "returns", "true", "or", "false" ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/base/validations.js#L332-L343
9,580
PhilWaldmann/openrecord
lib/stores/sql/destroy.js
function(options) { const Store = require('../../store') var self = this var primaryKeys = this.definition.primaryKeys var condition = {} options = options || {} for (var i = 0; i < primaryKeys.length; i++) { condition[primaryKeys[i]] = this[primaryKeys[i]] } return self.store.startTransaction(options, function() { return self .callInterceptors('beforeDestroy', [self, options]) .then(function() { var query = self.definition.query(options) return query .where(condition) .delete() .catch(function(error) { debug(query.toString()) throw new Store.SQLError(error) }) .then(function() { debug(query.toString()) }) .then(function() { return self.callInterceptors('afterDestroy', [self, options]) }) .then(function() { self.__exists = false return self }) }) }) }
javascript
function(options) { const Store = require('../../store') var self = this var primaryKeys = this.definition.primaryKeys var condition = {} options = options || {} for (var i = 0; i < primaryKeys.length; i++) { condition[primaryKeys[i]] = this[primaryKeys[i]] } return self.store.startTransaction(options, function() { return self .callInterceptors('beforeDestroy', [self, options]) .then(function() { var query = self.definition.query(options) return query .where(condition) .delete() .catch(function(error) { debug(query.toString()) throw new Store.SQLError(error) }) .then(function() { debug(query.toString()) }) .then(function() { return self.callInterceptors('afterDestroy', [self, options]) }) .then(function() { self.__exists = false return self }) }) }) }
[ "function", "(", "options", ")", "{", "const", "Store", "=", "require", "(", "'../../store'", ")", "var", "self", "=", "this", "var", "primaryKeys", "=", "this", ".", "definition", ".", "primaryKeys", "var", "condition", "=", "{", "}", "options", "=", "options", "||", "{", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "primaryKeys", ".", "length", ";", "i", "++", ")", "{", "condition", "[", "primaryKeys", "[", "i", "]", "]", "=", "this", "[", "primaryKeys", "[", "i", "]", "]", "}", "return", "self", ".", "store", ".", "startTransaction", "(", "options", ",", "function", "(", ")", "{", "return", "self", ".", "callInterceptors", "(", "'beforeDestroy'", ",", "[", "self", ",", "options", "]", ")", ".", "then", "(", "function", "(", ")", "{", "var", "query", "=", "self", ".", "definition", ".", "query", "(", "options", ")", "return", "query", ".", "where", "(", "condition", ")", ".", "delete", "(", ")", ".", "catch", "(", "function", "(", "error", ")", "{", "debug", "(", "query", ".", "toString", "(", ")", ")", "throw", "new", "Store", ".", "SQLError", "(", "error", ")", "}", ")", ".", "then", "(", "function", "(", ")", "{", "debug", "(", "query", ".", "toString", "(", ")", ")", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "self", ".", "callInterceptors", "(", "'afterDestroy'", ",", "[", "self", ",", "options", "]", ")", "}", ")", ".", "then", "(", "function", "(", ")", "{", "self", ".", "__exists", "=", "false", "return", "self", "}", ")", "}", ")", "}", ")", "}" ]
Destroy a record @class Record @method destroy @return {Record}
[ "Destroy", "a", "record" ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/stores/sql/destroy.js#L16-L54
9,581
PhilWaldmann/openrecord
lib/base/collection.js
function(data, options) { var self = this if (Array.isArray(data)) { return this.chain() .add(data) .save() } return this.runScopes().then(function() { return self.new(data).save(options) }) }
javascript
function(data, options) { var self = this if (Array.isArray(data)) { return this.chain() .add(data) .save() } return this.runScopes().then(function() { return self.new(data).save(options) }) }
[ "function", "(", "data", ",", "options", ")", "{", "var", "self", "=", "this", "if", "(", "Array", ".", "isArray", "(", "data", ")", ")", "{", "return", "this", ".", "chain", "(", ")", ".", "add", "(", "data", ")", ".", "save", "(", ")", "}", "return", "this", ".", "runScopes", "(", ")", ".", "then", "(", "function", "(", ")", "{", "return", "self", ".", "new", "(", "data", ")", ".", "save", "(", "options", ")", "}", ")", "}" ]
Creates a new record and saves it @class Model @method create @param {object} data - The data of the new record
[ "Creates", "a", "new", "record", "and", "saves", "it" ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/base/collection.js#L54-L65
9,582
PhilWaldmann/openrecord
lib/base/collection.js
function(index) { var self = this.chain() if (typeof index !== 'number') { index = self.indexOf(index) } const record = self[index] var relation = self.getInternal('relation') var parentRecord = self.getInternal('relation_to') if ( record && relation && parentRecord && typeof relation.remove === 'function' ) { relation.remove.call(self, parentRecord, record) } self.splice(index, 1) return self }
javascript
function(index) { var self = this.chain() if (typeof index !== 'number') { index = self.indexOf(index) } const record = self[index] var relation = self.getInternal('relation') var parentRecord = self.getInternal('relation_to') if ( record && relation && parentRecord && typeof relation.remove === 'function' ) { relation.remove.call(self, parentRecord, record) } self.splice(index, 1) return self }
[ "function", "(", "index", ")", "{", "var", "self", "=", "this", ".", "chain", "(", ")", "if", "(", "typeof", "index", "!==", "'number'", ")", "{", "index", "=", "self", ".", "indexOf", "(", "index", ")", "}", "const", "record", "=", "self", "[", "index", "]", "var", "relation", "=", "self", ".", "getInternal", "(", "'relation'", ")", "var", "parentRecord", "=", "self", ".", "getInternal", "(", "'relation_to'", ")", "if", "(", "record", "&&", "relation", "&&", "parentRecord", "&&", "typeof", "relation", ".", "remove", "===", "'function'", ")", "{", "relation", ".", "remove", ".", "call", "(", "self", ",", "parentRecord", ",", "record", ")", "}", "self", ".", "splice", "(", "index", ",", "1", ")", "return", "self", "}" ]
Removes a Record from the Collection @class Collection @method remove @param {integer} index - Removes the Record on the given index @or @param {Record} record - Removes given Record from the Collection @return {Collection}
[ "Removes", "a", "Record", "from", "the", "Collection" ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/base/collection.js#L282-L305
9,583
PhilWaldmann/openrecord
lib/stores/sql/save.js
save
function save(options) { const self = this options = options || {} if (self.options.polymorph) return this.callParent(options) return Promise.all( this.map(function(record) { // validate all records at once. return record.validate() }) ) .then(function() { // if validation succeeded, start the transaction return self.store.startTransaction(options, function() { return self ._runLazyOperation(options) .then(function() { // inside the transaction create all new records and afterwards save all the others return self._create(options) }) .then(function() { // will save all existing records with changes... return self.callParent(options, save) }) }) }) .then(function() { return self }) }
javascript
function save(options) { const self = this options = options || {} if (self.options.polymorph) return this.callParent(options) return Promise.all( this.map(function(record) { // validate all records at once. return record.validate() }) ) .then(function() { // if validation succeeded, start the transaction return self.store.startTransaction(options, function() { return self ._runLazyOperation(options) .then(function() { // inside the transaction create all new records and afterwards save all the others return self._create(options) }) .then(function() { // will save all existing records with changes... return self.callParent(options, save) }) }) }) .then(function() { return self }) }
[ "function", "save", "(", "options", ")", "{", "const", "self", "=", "this", "options", "=", "options", "||", "{", "}", "if", "(", "self", ".", "options", ".", "polymorph", ")", "return", "this", ".", "callParent", "(", "options", ")", "return", "Promise", ".", "all", "(", "this", ".", "map", "(", "function", "(", "record", ")", "{", "// validate all records at once.", "return", "record", ".", "validate", "(", ")", "}", ")", ")", ".", "then", "(", "function", "(", ")", "{", "// if validation succeeded, start the transaction", "return", "self", ".", "store", ".", "startTransaction", "(", "options", ",", "function", "(", ")", "{", "return", "self", ".", "_runLazyOperation", "(", "options", ")", ".", "then", "(", "function", "(", ")", "{", "// inside the transaction create all new records and afterwards save all the others", "return", "self", ".", "_create", "(", "options", ")", "}", ")", ".", "then", "(", "function", "(", ")", "{", "// will save all existing records with changes...", "return", "self", ".", "callParent", "(", "options", ",", "save", ")", "}", ")", "}", ")", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "self", "}", ")", "}" ]
create multiple records at once
[ "create", "multiple", "records", "at", "once" ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/stores/sql/save.js#L217-L247
9,584
PhilWaldmann/openrecord
lib/definition.js
function(store, modelName) { this.store = store this.modelName = modelName this.model = null this.middleware = [] this.instanceMethods = {} this.staticMethods = {} events.EventEmitter.call(this) }
javascript
function(store, modelName) { this.store = store this.modelName = modelName this.model = null this.middleware = [] this.instanceMethods = {} this.staticMethods = {} events.EventEmitter.call(this) }
[ "function", "(", "store", ",", "modelName", ")", "{", "this", ".", "store", "=", "store", "this", ".", "modelName", "=", "modelName", "this", ".", "model", "=", "null", "this", ".", "middleware", "=", "[", "]", "this", ".", "instanceMethods", "=", "{", "}", "this", ".", "staticMethods", "=", "{", "}", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", "}" ]
There are two ways to define a model. ```js var store = new OpenRecord({ //my store config }) store.model('MyModel', function(){ //model definition scope }); ``` or via the `models` config option: ```js var store = new OpenRecord({ //my store config models: __dirname + '/models/*' }); ``` ```js // ./models/mymodel.js module.exports = function(){ //model definition scope }; ``` ## Model Definition Scope The definition scope is like the Model class in ActiveRecord. Here you'll define all your validations, relations, scopes, record helpers, hooks and more. ### Async You could also define your model asynchronous ```js store.model('MyModel', function(next){ //model definition scope next(); }); ``` or via the `models` config option: ```js // ./models/mymodel.js module.exports = function(next){ //model definition scope next(); }; ``` @public @class Definition @public @class Model
[ "There", "are", "two", "ways", "to", "define", "a", "model", "." ]
779fdfcd8c7d2e7dba5429938d6847eeaefd20a5
https://github.com/PhilWaldmann/openrecord/blob/779fdfcd8c7d2e7dba5429938d6847eeaefd20a5/lib/definition.js#L66-L77
9,585
pixijs/pixi-filters
tools/screenshots/renderer.js
nextAnim
function nextAnim() { const anim = config.animations[++index]; if (anim) { const encoder = new GIFEncoder(app.view.width, app.view.height); // Stream output encoder.createReadStream().pipe(fs.createWriteStream( path.join(outputPath, anim.filename + '.gif') )); encoder.start(); encoder.setRepeat(0); // 0 for repeat, -1 for no-repeat encoder.setDelay(anim.delay || 500); // frame delay in ms encoder.setQuality(10); // image quality. 10 is default. // Add the frames anim.frames.forEach((frame) => { encoder.addFrame(frames[frame]); delete frames[frame]; }); encoder.finish(); // Wait for next stack to render next animation setTimeout(nextAnim, 0); } else { complete(); } }
javascript
function nextAnim() { const anim = config.animations[++index]; if (anim) { const encoder = new GIFEncoder(app.view.width, app.view.height); // Stream output encoder.createReadStream().pipe(fs.createWriteStream( path.join(outputPath, anim.filename + '.gif') )); encoder.start(); encoder.setRepeat(0); // 0 for repeat, -1 for no-repeat encoder.setDelay(anim.delay || 500); // frame delay in ms encoder.setQuality(10); // image quality. 10 is default. // Add the frames anim.frames.forEach((frame) => { encoder.addFrame(frames[frame]); delete frames[frame]; }); encoder.finish(); // Wait for next stack to render next animation setTimeout(nextAnim, 0); } else { complete(); } }
[ "function", "nextAnim", "(", ")", "{", "const", "anim", "=", "config", ".", "animations", "[", "++", "index", "]", ";", "if", "(", "anim", ")", "{", "const", "encoder", "=", "new", "GIFEncoder", "(", "app", ".", "view", ".", "width", ",", "app", ".", "view", ".", "height", ")", ";", "// Stream output", "encoder", ".", "createReadStream", "(", ")", ".", "pipe", "(", "fs", ".", "createWriteStream", "(", "path", ".", "join", "(", "outputPath", ",", "anim", ".", "filename", "+", "'.gif'", ")", ")", ")", ";", "encoder", ".", "start", "(", ")", ";", "encoder", ".", "setRepeat", "(", "0", ")", ";", "// 0 for repeat, -1 for no-repeat", "encoder", ".", "setDelay", "(", "anim", ".", "delay", "||", "500", ")", ";", "// frame delay in ms", "encoder", ".", "setQuality", "(", "10", ")", ";", "// image quality. 10 is default.", "// Add the frames", "anim", ".", "frames", ".", "forEach", "(", "(", "frame", ")", "=>", "{", "encoder", ".", "addFrame", "(", "frames", "[", "frame", "]", ")", ";", "delete", "frames", "[", "frame", "]", ";", "}", ")", ";", "encoder", ".", "finish", "(", ")", ";", "// Wait for next stack to render next animation", "setTimeout", "(", "nextAnim", ",", "0", ")", ";", "}", "else", "{", "complete", "(", ")", ";", "}", "}" ]
Combine a bunch of frames
[ "Combine", "a", "bunch", "of", "frames" ]
caeac3f2ff85077befaeb18990e7fede6defc61e
https://github.com/pixijs/pixi-filters/blob/caeac3f2ff85077befaeb18990e7fede6defc61e/tools/screenshots/renderer.js#L131-L161
9,586
pixijs/pixi-filters
rollup.config.js
dedupeDefaultVert
function dedupeDefaultVert() { const defaultVert = path.join(__dirname, 'tools/fragments/default.vert'); const fragment = fs.readFileSync(defaultVert, 'utf8') .replace(/\n/g, '\\\\n') .replace(/([()*=.])/g, '\\$1'); const pattern = new RegExp(`(var ([^=\\s]+)\\s?=\\s?)"${fragment}"`, 'g'); return { name: 'dedupeDefaultVert', renderChunk(code) { const matches = []; let match; while ((match = pattern.exec(code)) !== null) { matches.push(match); } if (matches.length <= 1) { return null; } const str = new MagicString(code); const key = matches[0][2]; for (let i = 1; i < matches.length; i++) { const match = matches[i]; const start = code.indexOf(match[0]); str.overwrite( start, start + match[0].length, match[1] + key ); } return { code: str.toString(), map: str.generateMap({ hires: true }), }; }, }; }
javascript
function dedupeDefaultVert() { const defaultVert = path.join(__dirname, 'tools/fragments/default.vert'); const fragment = fs.readFileSync(defaultVert, 'utf8') .replace(/\n/g, '\\\\n') .replace(/([()*=.])/g, '\\$1'); const pattern = new RegExp(`(var ([^=\\s]+)\\s?=\\s?)"${fragment}"`, 'g'); return { name: 'dedupeDefaultVert', renderChunk(code) { const matches = []; let match; while ((match = pattern.exec(code)) !== null) { matches.push(match); } if (matches.length <= 1) { return null; } const str = new MagicString(code); const key = matches[0][2]; for (let i = 1; i < matches.length; i++) { const match = matches[i]; const start = code.indexOf(match[0]); str.overwrite( start, start + match[0].length, match[1] + key ); } return { code: str.toString(), map: str.generateMap({ hires: true }), }; }, }; }
[ "function", "dedupeDefaultVert", "(", ")", "{", "const", "defaultVert", "=", "path", ".", "join", "(", "__dirname", ",", "'tools/fragments/default.vert'", ")", ";", "const", "fragment", "=", "fs", ".", "readFileSync", "(", "defaultVert", ",", "'utf8'", ")", ".", "replace", "(", "/", "\\n", "/", "g", ",", "'\\\\\\\\n'", ")", ".", "replace", "(", "/", "([()*=.])", "/", "g", ",", "'\\\\$1'", ")", ";", "const", "pattern", "=", "new", "RegExp", "(", "`", "\\\\", "\\\\", "\\\\", "${", "fragment", "}", "`", ",", "'g'", ")", ";", "return", "{", "name", ":", "'dedupeDefaultVert'", ",", "renderChunk", "(", "code", ")", "{", "const", "matches", "=", "[", "]", ";", "let", "match", ";", "while", "(", "(", "match", "=", "pattern", ".", "exec", "(", "code", ")", ")", "!==", "null", ")", "{", "matches", ".", "push", "(", "match", ")", ";", "}", "if", "(", "matches", ".", "length", "<=", "1", ")", "{", "return", "null", ";", "}", "const", "str", "=", "new", "MagicString", "(", "code", ")", ";", "const", "key", "=", "matches", "[", "0", "]", "[", "2", "]", ";", "for", "(", "let", "i", "=", "1", ";", "i", "<", "matches", ".", "length", ";", "i", "++", ")", "{", "const", "match", "=", "matches", "[", "i", "]", ";", "const", "start", "=", "code", ".", "indexOf", "(", "match", "[", "0", "]", ")", ";", "str", ".", "overwrite", "(", "start", ",", "start", "+", "match", "[", "0", "]", ".", "length", ",", "match", "[", "1", "]", "+", "key", ")", ";", "}", "return", "{", "code", ":", "str", ".", "toString", "(", ")", ",", "map", ":", "str", ".", "generateMap", "(", "{", "hires", ":", "true", "}", ")", ",", "}", ";", "}", ",", "}", ";", "}" ]
This plugin is a filesize optimization for the pixi-filters bundle it removes all the successive occurances of the default vertex fragment and reassigns the name of the vertex variable @function dedupeDefaultVert @private
[ "This", "plugin", "is", "a", "filesize", "optimization", "for", "the", "pixi", "-", "filters", "bundle", "it", "removes", "all", "the", "successive", "occurances", "of", "the", "default", "vertex", "fragment", "and", "reassigns", "the", "name", "of", "the", "vertex", "variable" ]
caeac3f2ff85077befaeb18990e7fede6defc61e
https://github.com/pixijs/pixi-filters/blob/caeac3f2ff85077befaeb18990e7fede6defc61e/rollup.config.js#L21-L63
9,587
pixijs/pixi-filters
rollup.config.js
getSortedPackages
async function getSortedPackages() { // Support --scope and --ignore globs const {scope, ignore} = minimist(process.argv.slice(2)); // Standard Lerna plumbing getting packages const packages = await getPackages(__dirname); const filtered = filterPackages( packages, scope, ignore, false ); return batchPackages(filtered) .reduce((arr, batch) => arr.concat(batch), []); }
javascript
async function getSortedPackages() { // Support --scope and --ignore globs const {scope, ignore} = minimist(process.argv.slice(2)); // Standard Lerna plumbing getting packages const packages = await getPackages(__dirname); const filtered = filterPackages( packages, scope, ignore, false ); return batchPackages(filtered) .reduce((arr, batch) => arr.concat(batch), []); }
[ "async", "function", "getSortedPackages", "(", ")", "{", "// Support --scope and --ignore globs", "const", "{", "scope", ",", "ignore", "}", "=", "minimist", "(", "process", ".", "argv", ".", "slice", "(", "2", ")", ")", ";", "// Standard Lerna plumbing getting packages", "const", "packages", "=", "await", "getPackages", "(", "__dirname", ")", ";", "const", "filtered", "=", "filterPackages", "(", "packages", ",", "scope", ",", "ignore", ",", "false", ")", ";", "return", "batchPackages", "(", "filtered", ")", ".", "reduce", "(", "(", "arr", ",", "batch", ")", "=>", "arr", ".", "concat", "(", "batch", ")", ",", "[", "]", ")", ";", "}" ]
Get a list of the non-private sorted packages with Lerna v3 @see https://github.com/lerna/lerna/issues/1848 @return {Promise<Package[]>} List of packages
[ "Get", "a", "list", "of", "the", "non", "-", "private", "sorted", "packages", "with", "Lerna", "v3" ]
caeac3f2ff85077befaeb18990e7fede6defc61e
https://github.com/pixijs/pixi-filters/blob/caeac3f2ff85077befaeb18990e7fede6defc61e/rollup.config.js#L70-L85
9,588
3rd-Eden/useragent
index.js
Agent
function Agent(family, major, minor, patch, source) { this.family = family || 'Other'; this.major = major || '0'; this.minor = minor || '0'; this.patch = patch || '0'; this.source = source || ''; }
javascript
function Agent(family, major, minor, patch, source) { this.family = family || 'Other'; this.major = major || '0'; this.minor = minor || '0'; this.patch = patch || '0'; this.source = source || ''; }
[ "function", "Agent", "(", "family", ",", "major", ",", "minor", ",", "patch", ",", "source", ")", "{", "this", ".", "family", "=", "family", "||", "'Other'", ";", "this", ".", "major", "=", "major", "||", "'0'", ";", "this", ".", "minor", "=", "minor", "||", "'0'", ";", "this", ".", "patch", "=", "patch", "||", "'0'", ";", "this", ".", "source", "=", "source", "||", "''", ";", "}" ]
The representation of a parsed user agent. @constructor @param {String} family The name of the browser @param {String} major Major version of the browser @param {String} minor Minor version of the browser @param {String} patch Patch version of the browser @param {String} source The actual user agent string @api public
[ "The", "representation", "of", "a", "parsed", "user", "agent", "." ]
187c17255028bd30d82e3af108846ce73a8197fb
https://github.com/3rd-Eden/useragent/blob/187c17255028bd30d82e3af108846ce73a8197fb/index.js#L34-L40
9,589
3rd-Eden/useragent
index.js
set
function set(os) { if (!(os instanceof OperatingSystem)) return false; return Object.defineProperty(this, 'os', { value: os }).os; }
javascript
function set(os) { if (!(os instanceof OperatingSystem)) return false; return Object.defineProperty(this, 'os', { value: os }).os; }
[ "function", "set", "(", "os", ")", "{", "if", "(", "!", "(", "os", "instanceof", "OperatingSystem", ")", ")", "return", "false", ";", "return", "Object", ".", "defineProperty", "(", "this", ",", "'os'", ",", "{", "value", ":", "os", "}", ")", ".", "os", ";", "}" ]
Bypass the OnDemand parsing and set an OperatingSystem instance. @param {OperatingSystem} os @api public
[ "Bypass", "the", "OnDemand", "parsing", "and", "set", "an", "OperatingSystem", "instance", "." ]
187c17255028bd30d82e3af108846ce73a8197fb
https://github.com/3rd-Eden/useragent/blob/187c17255028bd30d82e3af108846ce73a8197fb/index.js#L84-L90
9,590
3rd-Eden/useragent
index.js
set
function set(device) { if (!(device instanceof Device)) return false; return Object.defineProperty(this, 'device', { value: device }).device; }
javascript
function set(device) { if (!(device instanceof Device)) return false; return Object.defineProperty(this, 'device', { value: device }).device; }
[ "function", "set", "(", "device", ")", "{", "if", "(", "!", "(", "device", "instanceof", "Device", ")", ")", "return", "false", ";", "return", "Object", ".", "defineProperty", "(", "this", ",", "'device'", ",", "{", "value", ":", "device", "}", ")", ".", "device", ";", "}" ]
Bypass the OnDemand parsing and set an Device instance. @param {Device} device @api public
[ "Bypass", "the", "OnDemand", "parsing", "and", "set", "an", "Device", "instance", "." ]
187c17255028bd30d82e3af108846ce73a8197fb
https://github.com/3rd-Eden/useragent/blob/187c17255028bd30d82e3af108846ce73a8197fb/index.js#L135-L141
9,591
3rd-Eden/useragent
index.js
OperatingSystem
function OperatingSystem(family, major, minor, patch) { this.family = family || 'Other'; this.major = major || '0'; this.minor = minor || '0'; this.patch = patch || '0'; }
javascript
function OperatingSystem(family, major, minor, patch) { this.family = family || 'Other'; this.major = major || '0'; this.minor = minor || '0'; this.patch = patch || '0'; }
[ "function", "OperatingSystem", "(", "family", ",", "major", ",", "minor", ",", "patch", ")", "{", "this", ".", "family", "=", "family", "||", "'Other'", ";", "this", ".", "major", "=", "major", "||", "'0'", ";", "this", ".", "minor", "=", "minor", "||", "'0'", ";", "this", ".", "patch", "=", "patch", "||", "'0'", ";", "}" ]
The representation of a parsed Operating System. @constructor @param {String} family The name of the os @param {String} major Major version of the os @param {String} minor Minor version of the os @param {String} patch Patch version of the os @api public
[ "The", "representation", "of", "a", "parsed", "Operating", "System", "." ]
187c17255028bd30d82e3af108846ce73a8197fb
https://github.com/3rd-Eden/useragent/blob/187c17255028bd30d82e3af108846ce73a8197fb/index.js#L222-L227
9,592
3rd-Eden/useragent
index.js
Device
function Device(family, major, minor, patch) { this.family = family || 'Other'; this.major = major || '0'; this.minor = minor || '0'; this.patch = patch || '0'; }
javascript
function Device(family, major, minor, patch) { this.family = family || 'Other'; this.major = major || '0'; this.minor = minor || '0'; this.patch = patch || '0'; }
[ "function", "Device", "(", "family", ",", "major", ",", "minor", ",", "patch", ")", "{", "this", ".", "family", "=", "family", "||", "'Other'", ";", "this", ".", "major", "=", "major", "||", "'0'", ";", "this", ".", "minor", "=", "minor", "||", "'0'", ";", "this", ".", "patch", "=", "patch", "||", "'0'", ";", "}" ]
The representation of a parsed Device. @constructor @param {String} family The name of the device @param {String} major Major version of the device @param {String} minor Minor version of the device @param {String} patch Patch version of the device @api public
[ "The", "representation", "of", "a", "parsed", "Device", "." ]
187c17255028bd30d82e3af108846ce73a8197fb
https://github.com/3rd-Eden/useragent/blob/187c17255028bd30d82e3af108846ce73a8197fb/index.js#L295-L300
9,593
3rd-Eden/useragent
index.js
isSafe
function isSafe(userAgent) { var consecutive = 0 , code = 0; if (userAgent.length > 1000) return false; for (var i = 0; i < userAgent.length; i++) { code = userAgent.charCodeAt(i); // numbers between 0 and 9, letters between a and z, spaces and control if ((code >= 48 && code <= 57) || (code >= 97 && code <= 122) || code <= 32) { consecutive++; } else { consecutive = 0; } if (consecutive >= 100) { return false; } } return true }
javascript
function isSafe(userAgent) { var consecutive = 0 , code = 0; if (userAgent.length > 1000) return false; for (var i = 0; i < userAgent.length; i++) { code = userAgent.charCodeAt(i); // numbers between 0 and 9, letters between a and z, spaces and control if ((code >= 48 && code <= 57) || (code >= 97 && code <= 122) || code <= 32) { consecutive++; } else { consecutive = 0; } if (consecutive >= 100) { return false; } } return true }
[ "function", "isSafe", "(", "userAgent", ")", "{", "var", "consecutive", "=", "0", ",", "code", "=", "0", ";", "if", "(", "userAgent", ".", "length", ">", "1000", ")", "return", "false", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "userAgent", ".", "length", ";", "i", "++", ")", "{", "code", "=", "userAgent", ".", "charCodeAt", "(", "i", ")", ";", "// numbers between 0 and 9, letters between a and z, spaces and control", "if", "(", "(", "code", ">=", "48", "&&", "code", "<=", "57", ")", "||", "(", "code", ">=", "97", "&&", "code", "<=", "122", ")", "||", "code", "<=", "32", ")", "{", "consecutive", "++", ";", "}", "else", "{", "consecutive", "=", "0", ";", "}", "if", "(", "consecutive", ">=", "100", ")", "{", "return", "false", ";", "}", "}", "return", "true", "}" ]
Check if the userAgent is something we want to parse with regexp's. @param {String} userAgent The userAgent. @returns {Boolean}
[ "Check", "if", "the", "userAgent", "is", "something", "we", "want", "to", "parse", "with", "regexp", "s", "." ]
187c17255028bd30d82e3af108846ce73a8197fb
https://github.com/3rd-Eden/useragent/blob/187c17255028bd30d82e3af108846ce73a8197fb/index.js#L414-L435
9,594
aws/aws-xray-sdk-node
packages/core/lib/segments/attributes/aws.js
setAWSWhitelist
function setAWSWhitelist(source) { if (!source || source instanceof String || !(typeof source === 'string' || (source instanceof Object))) throw new Error('Please specify a path to the local whitelist file, or supply a whitelist source object.'); capturer = new CallCapturer(source); }
javascript
function setAWSWhitelist(source) { if (!source || source instanceof String || !(typeof source === 'string' || (source instanceof Object))) throw new Error('Please specify a path to the local whitelist file, or supply a whitelist source object.'); capturer = new CallCapturer(source); }
[ "function", "setAWSWhitelist", "(", "source", ")", "{", "if", "(", "!", "source", "||", "source", "instanceof", "String", "||", "!", "(", "typeof", "source", "===", "'string'", "||", "(", "source", "instanceof", "Object", ")", ")", ")", "throw", "new", "Error", "(", "'Please specify a path to the local whitelist file, or supply a whitelist source object.'", ")", ";", "capturer", "=", "new", "CallCapturer", "(", "source", ")", ";", "}" ]
Overrides the default whitelisting file to specify what params to capture on each AWS Service call. @param {string|Object} source - The path to the custom whitelist file, or a whitelist source JSON object. @exports setAWSWhitelist
[ "Overrides", "the", "default", "whitelisting", "file", "to", "specify", "what", "params", "to", "capture", "on", "each", "AWS", "Service", "call", "." ]
ad817e5ccfbb803ec4140cd8a457be579ea3cc1c
https://github.com/aws/aws-xray-sdk-node/blob/ad817e5ccfbb803ec4140cd8a457be579ea3cc1c/packages/core/lib/segments/attributes/aws.js#L42-L47
9,595
aws/aws-xray-sdk-node
packages/core/lib/segments/attributes/aws.js
appendAWSWhitelist
function appendAWSWhitelist(source) { if (!source || source instanceof String || !(typeof source === 'string' || (source instanceof Object))) throw new Error('Please specify a path to the local whitelist file, or supply a whitelist source object.'); capturer.append(source); }
javascript
function appendAWSWhitelist(source) { if (!source || source instanceof String || !(typeof source === 'string' || (source instanceof Object))) throw new Error('Please specify a path to the local whitelist file, or supply a whitelist source object.'); capturer.append(source); }
[ "function", "appendAWSWhitelist", "(", "source", ")", "{", "if", "(", "!", "source", "||", "source", "instanceof", "String", "||", "!", "(", "typeof", "source", "===", "'string'", "||", "(", "source", "instanceof", "Object", ")", ")", ")", "throw", "new", "Error", "(", "'Please specify a path to the local whitelist file, or supply a whitelist source object.'", ")", ";", "capturer", ".", "append", "(", "source", ")", ";", "}" ]
Appends to the default whitelisting file to specify what params to capture on each AWS Service call. @param {string|Object} source - The path to the custom whitelist file, or a whitelist source JSON object. @exports appendAWSWhitelist
[ "Appends", "to", "the", "default", "whitelisting", "file", "to", "specify", "what", "params", "to", "capture", "on", "each", "AWS", "Service", "call", "." ]
ad817e5ccfbb803ec4140cd8a457be579ea3cc1c
https://github.com/aws/aws-xray-sdk-node/blob/ad817e5ccfbb803ec4140cd8a457be579ea3cc1c/packages/core/lib/segments/attributes/aws.js#L55-L60
9,596
aws/aws-xray-sdk-node
packages/core/lib/segment_emitter.js
batchSendData
function batchSendData (ops, callback) { var client = dgram.createSocket('udp4'); executeSendData(client, ops, 0, function () { try { client.close(); } finally { callback(); } }); }
javascript
function batchSendData (ops, callback) { var client = dgram.createSocket('udp4'); executeSendData(client, ops, 0, function () { try { client.close(); } finally { callback(); } }); }
[ "function", "batchSendData", "(", "ops", ",", "callback", ")", "{", "var", "client", "=", "dgram", ".", "createSocket", "(", "'udp4'", ")", ";", "executeSendData", "(", "client", ",", "ops", ",", "0", ",", "function", "(", ")", "{", "try", "{", "client", ".", "close", "(", ")", ";", "}", "finally", "{", "callback", "(", ")", ";", "}", "}", ")", ";", "}" ]
Sends a collection of data over a UDP socket. This method is designed to be used by `atomic-batcher` as a way to share a single UDP socket for sending multiple data blocks. @param {object} ops - Details of the data to send @param {Function} callback - The function to call when done
[ "Sends", "a", "collection", "of", "data", "over", "a", "UDP", "socket", ".", "This", "method", "is", "designed", "to", "be", "used", "by", "atomic", "-", "batcher", "as", "a", "way", "to", "share", "a", "single", "UDP", "socket", "for", "sending", "multiple", "data", "blocks", "." ]
ad817e5ccfbb803ec4140cd8a457be579ea3cc1c
https://github.com/aws/aws-xray-sdk-node/blob/ad817e5ccfbb803ec4140cd8a457be579ea3cc1c/packages/core/lib/segment_emitter.js#L17-L27
9,597
aws/aws-xray-sdk-node
packages/core/lib/segment_emitter.js
executeSendData
function executeSendData (client, ops, index, callback) { if (index >= ops.length) { callback(); return; } sendMessage(client, ops[index], function () { executeSendData(client, ops, index+1, callback); }); }
javascript
function executeSendData (client, ops, index, callback) { if (index >= ops.length) { callback(); return; } sendMessage(client, ops[index], function () { executeSendData(client, ops, index+1, callback); }); }
[ "function", "executeSendData", "(", "client", ",", "ops", ",", "index", ",", "callback", ")", "{", "if", "(", "index", ">=", "ops", ".", "length", ")", "{", "callback", "(", ")", ";", "return", ";", "}", "sendMessage", "(", "client", ",", "ops", "[", "index", "]", ",", "function", "(", ")", "{", "executeSendData", "(", "client", ",", "ops", ",", "index", "+", "1", ",", "callback", ")", ";", "}", ")", ";", "}" ]
Execute sending data starting at the specified index and using the provided client. @param {Socket} client - Socket to send data with @param {object} ops - Details of data to send @param {number} index - Starting index for sending @param {Function} callback - Function to call when done
[ "Execute", "sending", "data", "starting", "at", "the", "specified", "index", "and", "using", "the", "provided", "client", "." ]
ad817e5ccfbb803ec4140cd8a457be579ea3cc1c
https://github.com/aws/aws-xray-sdk-node/blob/ad817e5ccfbb803ec4140cd8a457be579ea3cc1c/packages/core/lib/segment_emitter.js#L38-L47
9,598
aws/aws-xray-sdk-node
packages/core/lib/segment_emitter.js
sendMessage
function sendMessage (client, data, batchCallback) { var msg = data.msg; var offset = data.offset; var length = data.length; var port = data.port; var address = data.address; var callback = data.callback; client.send(msg, offset, length, port, address, function(err) { try { callback(err); } finally { batchCallback(); } }); }
javascript
function sendMessage (client, data, batchCallback) { var msg = data.msg; var offset = data.offset; var length = data.length; var port = data.port; var address = data.address; var callback = data.callback; client.send(msg, offset, length, port, address, function(err) { try { callback(err); } finally { batchCallback(); } }); }
[ "function", "sendMessage", "(", "client", ",", "data", ",", "batchCallback", ")", "{", "var", "msg", "=", "data", ".", "msg", ";", "var", "offset", "=", "data", ".", "offset", ";", "var", "length", "=", "data", ".", "length", ";", "var", "port", "=", "data", ".", "port", ";", "var", "address", "=", "data", ".", "address", ";", "var", "callback", "=", "data", ".", "callback", ";", "client", ".", "send", "(", "msg", ",", "offset", ",", "length", ",", "port", ",", "address", ",", "function", "(", "err", ")", "{", "try", "{", "callback", "(", "err", ")", ";", "}", "finally", "{", "batchCallback", "(", ")", ";", "}", "}", ")", ";", "}" ]
Send a single message over a UDP socket. @param {Socket} client - Socket to send data with @param {object} data - Details of the data to send @param {Function} batchCallback - Function to call when done
[ "Send", "a", "single", "message", "over", "a", "UDP", "socket", "." ]
ad817e5ccfbb803ec4140cd8a457be579ea3cc1c
https://github.com/aws/aws-xray-sdk-node/blob/ad817e5ccfbb803ec4140cd8a457be579ea3cc1c/packages/core/lib/segment_emitter.js#L56-L71
9,599
aws/aws-xray-sdk-node
packages/core/lib/segment_emitter.js
send
function send(segment) { var client = this.socket; var formatted = segment.format(); var data = PROTOCOL_HEADER + PROTOCOL_DELIMITER + formatted; var message = new Buffer(data); var short = '{"trace_id:"' + segment.trace_id + '","id":"' + segment.id + '"}'; var type = segment.type === 'subsegment' ? 'Subsegment' : 'Segment'; client.send(message, 0, message.length, this.daemonConfig.udp_port, this.daemonConfig.udp_ip, function(err) { if (err) { if (err.code === 'EMSGSIZE') logger.getLogger().error(type + ' too large to send: ' + short + ' (' + message.length + ' bytes).'); else logger.getLogger().error('Error occured sending segment: ', err); } else { logger.getLogger().debug(type + ' sent: {"trace_id:"' + segment.trace_id + '","id":"' + segment.id + '"}'); logger.getLogger().debug('UDP message sent: ' + segment); } }); }
javascript
function send(segment) { var client = this.socket; var formatted = segment.format(); var data = PROTOCOL_HEADER + PROTOCOL_DELIMITER + formatted; var message = new Buffer(data); var short = '{"trace_id:"' + segment.trace_id + '","id":"' + segment.id + '"}'; var type = segment.type === 'subsegment' ? 'Subsegment' : 'Segment'; client.send(message, 0, message.length, this.daemonConfig.udp_port, this.daemonConfig.udp_ip, function(err) { if (err) { if (err.code === 'EMSGSIZE') logger.getLogger().error(type + ' too large to send: ' + short + ' (' + message.length + ' bytes).'); else logger.getLogger().error('Error occured sending segment: ', err); } else { logger.getLogger().debug(type + ' sent: {"trace_id:"' + segment.trace_id + '","id":"' + segment.id + '"}'); logger.getLogger().debug('UDP message sent: ' + segment); } }); }
[ "function", "send", "(", "segment", ")", "{", "var", "client", "=", "this", ".", "socket", ";", "var", "formatted", "=", "segment", ".", "format", "(", ")", ";", "var", "data", "=", "PROTOCOL_HEADER", "+", "PROTOCOL_DELIMITER", "+", "formatted", ";", "var", "message", "=", "new", "Buffer", "(", "data", ")", ";", "var", "short", "=", "'{\"trace_id:\"'", "+", "segment", ".", "trace_id", "+", "'\",\"id\":\"'", "+", "segment", ".", "id", "+", "'\"}'", ";", "var", "type", "=", "segment", ".", "type", "===", "'subsegment'", "?", "'Subsegment'", ":", "'Segment'", ";", "client", ".", "send", "(", "message", ",", "0", ",", "message", ".", "length", ",", "this", ".", "daemonConfig", ".", "udp_port", ",", "this", ".", "daemonConfig", ".", "udp_ip", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", ".", "code", "===", "'EMSGSIZE'", ")", "logger", ".", "getLogger", "(", ")", ".", "error", "(", "type", "+", "' too large to send: '", "+", "short", "+", "' ('", "+", "message", ".", "length", "+", "' bytes).'", ")", ";", "else", "logger", ".", "getLogger", "(", ")", ".", "error", "(", "'Error occured sending segment: '", ",", "err", ")", ";", "}", "else", "{", "logger", ".", "getLogger", "(", ")", ".", "debug", "(", "type", "+", "' sent: {\"trace_id:\"'", "+", "segment", ".", "trace_id", "+", "'\",\"id\":\"'", "+", "segment", ".", "id", "+", "'\"}'", ")", ";", "logger", ".", "getLogger", "(", ")", ".", "debug", "(", "'UDP message sent: '", "+", "segment", ")", ";", "}", "}", ")", ";", "}" ]
Creates a UDP socket connection and send the formatted segment. @param {Segment} segment - The segment to send to the daemon.
[ "Creates", "a", "UDP", "socket", "connection", "and", "send", "the", "formatted", "segment", "." ]
ad817e5ccfbb803ec4140cd8a457be579ea3cc1c
https://github.com/aws/aws-xray-sdk-node/blob/ad817e5ccfbb803ec4140cd8a457be579ea3cc1c/packages/core/lib/segment_emitter.js#L121-L141