language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
function fakeTitle () { var consonants = 'bcdfghjklmnpqrstvwxyz'; var vowels = 'aeiou'; var patterns = 'CVC VC CV CVVCV CVCV VCVVC CVCCVC'; var n = 1 + Math.floor(Math.random() * 3); var words = []; for (var i = 0; i < n; i++) { words.push(sample(patterns.split(' '))); } return words.join(' ').replace(/[CV]/g, function(x) { return x === 'C' ? sample(consonants) : sample(vowels); }); }
function fakeTitle () { var consonants = 'bcdfghjklmnpqrstvwxyz'; var vowels = 'aeiou'; var patterns = 'CVC VC CV CVVCV CVCV VCVVC CVCCVC'; var n = 1 + Math.floor(Math.random() * 3); var words = []; for (var i = 0; i < n; i++) { words.push(sample(patterns.split(' '))); } return words.join(' ').replace(/[CV]/g, function(x) { return x === 'C' ? sample(consonants) : sample(vowels); }); }
JavaScript
function position () { var lightboxWidth = getWidth(lightbox); var windowWidth = getWidth(document.body); var backButtonWidth = getWidth(backButton); var forwardButtonWidth = getWidth(forwardButton); var margin = 20; var lightboxLeft = (windowWidth - lightboxWidth) / 2; lightbox.style.left = lightboxLeft; backButton.style.left = lightboxLeft - backButtonWidth - 3 * margin; forwardButton.style.left = lightboxLeft + lightboxWidth + margin; }
function position () { var lightboxWidth = getWidth(lightbox); var windowWidth = getWidth(document.body); var backButtonWidth = getWidth(backButton); var forwardButtonWidth = getWidth(forwardButton); var margin = 20; var lightboxLeft = (windowWidth - lightboxWidth) / 2; lightbox.style.left = lightboxLeft; backButton.style.left = lightboxLeft - backButtonWidth - 3 * margin; forwardButton.style.left = lightboxLeft + lightboxWidth + margin; }
JavaScript
function navigateOnKeyDown (ev) { var keys = {rightArrow: 39, leftArrow: 37}; if (ev.which === keys.rightArrow) { progress(); } else if (ev.which === keys.leftArrow) { regress(); } }
function navigateOnKeyDown (ev) { var keys = {rightArrow: 39, leftArrow: 37}; if (ev.which === keys.rightArrow) { progress(); } else if (ev.which === keys.leftArrow) { regress(); } }
JavaScript
function progress () { for (var i = 0; i < imageCollection.length; i++) { if (imageNode.id === imageCollection[i].id && i < imageCollection.length - 1) { closeLightbox(); var image = imageCollection[i + 1]; lightboxView( t.image(image.src, image.id), image.title, imageCollection ); return; } } closeLightbox(); }
function progress () { for (var i = 0; i < imageCollection.length; i++) { if (imageNode.id === imageCollection[i].id && i < imageCollection.length - 1) { closeLightbox(); var image = imageCollection[i + 1]; lightboxView( t.image(image.src, image.id), image.title, imageCollection ); return; } } closeLightbox(); }
JavaScript
function regress () { for (var i = 0; i < imageCollection.length; i++) { if (imageNode.id === imageCollection[i].id && i > 0) { closeLightbox(); var image = imageCollection[i - 1]; lightboxView(t.image(image.src, image.id), image.title, imageCollection); return; } } closeLightbox(); }
function regress () { for (var i = 0; i < imageCollection.length; i++) { if (imageNode.id === imageCollection[i].id && i > 0) { closeLightbox(); var image = imageCollection[i - 1]; lightboxView(t.image(image.src, image.id), image.title, imageCollection); return; } } closeLightbox(); }
JavaScript
function fakeTitle () { var consonants = 'bcdfghjklmnpqrstvwxyz'; var vowels = 'aeiou'; var patterns = 'CVC VC CV CVVCV CVCV VCVVC CVCCVC'; var n = 1 + Math.floor(Math.random() * 3); var words = []; for (var i = 0; i < n; i++) { words.push(sample(patterns.split(' '))); } return words.join(' ').replace(/[CV]/g, function(x) { return x === 'C' ? sample(consonants) : sample(vowels); }); }
function fakeTitle () { var consonants = 'bcdfghjklmnpqrstvwxyz'; var vowels = 'aeiou'; var patterns = 'CVC VC CV CVVCV CVCV VCVVC CVCCVC'; var n = 1 + Math.floor(Math.random() * 3); var words = []; for (var i = 0; i < n; i++) { words.push(sample(patterns.split(' '))); } return words.join(' ').replace(/[CV]/g, function(x) { return x === 'C' ? sample(consonants) : sample(vowels); }); }
JavaScript
function position () { var lightboxWidth = getWidth(lightbox); var windowWidth = getWidth(document.body); var backButtonWidth = getWidth(backButton); var forwardButtonWidth = getWidth(forwardButton); var margin = 20; var lightboxLeft = (windowWidth - lightboxWidth) / 2; lightbox.style.left = lightboxLeft; backButton.style.left = lightboxLeft - backButtonWidth - 3 * margin; forwardButton.style.left = lightboxLeft + lightboxWidth + margin; }
function position () { var lightboxWidth = getWidth(lightbox); var windowWidth = getWidth(document.body); var backButtonWidth = getWidth(backButton); var forwardButtonWidth = getWidth(forwardButton); var margin = 20; var lightboxLeft = (windowWidth - lightboxWidth) / 2; lightbox.style.left = lightboxLeft; backButton.style.left = lightboxLeft - backButtonWidth - 3 * margin; forwardButton.style.left = lightboxLeft + lightboxWidth + margin; }
JavaScript
function navigateOnKeyDown (ev) { var keys = {rightArrow: 39, leftArrow: 37}; if (ev.which === keys.rightArrow) { progress(); } else if (ev.which === keys.leftArrow) { regress(); } }
function navigateOnKeyDown (ev) { var keys = {rightArrow: 39, leftArrow: 37}; if (ev.which === keys.rightArrow) { progress(); } else if (ev.which === keys.leftArrow) { regress(); } }
JavaScript
function progress () { for (var i = 0; i < imageCollection.length; i++) { if (imageNode.id === imageCollection[i].id && i < imageCollection.length - 1) { closeLightbox(); var image = imageCollection[i + 1]; lightboxView( t.image(image.src, image.id), image.title, imageCollection ); return; } } closeLightbox(); }
function progress () { for (var i = 0; i < imageCollection.length; i++) { if (imageNode.id === imageCollection[i].id && i < imageCollection.length - 1) { closeLightbox(); var image = imageCollection[i + 1]; lightboxView( t.image(image.src, image.id), image.title, imageCollection ); return; } } closeLightbox(); }
JavaScript
function regress () { for (var i = 0; i < imageCollection.length; i++) { if (imageNode.id === imageCollection[i].id && i > 0) { closeLightbox(); var image = imageCollection[i - 1]; lightboxView(t.image(image.src, image.id), image.title, imageCollection); return; } } closeLightbox(); }
function regress () { for (var i = 0; i < imageCollection.length; i++) { if (imageNode.id === imageCollection[i].id && i > 0) { closeLightbox(); var image = imageCollection[i - 1]; lightboxView(t.image(image.src, image.id), image.title, imageCollection); return; } } closeLightbox(); }
JavaScript
function startGame() { // initialize game variables progress = 0; gamePlaying = true; generatePattern(); livesLeft = 3; // swap the Start and Stop buttons document.getElementById("startBtn").classList.add("hidden"); document.getElementById("stopBtn").classList.remove("hidden"); // begin clue sequence playClueSequence(); }
function startGame() { // initialize game variables progress = 0; gamePlaying = true; generatePattern(); livesLeft = 3; // swap the Start and Stop buttons document.getElementById("startBtn").classList.add("hidden"); document.getElementById("stopBtn").classList.remove("hidden"); // begin clue sequence playClueSequence(); }
JavaScript
function maintain_this_binding(compressor, parent, orig, val) { var wrap = false; if (parent.TYPE == "Call") { wrap = parent.expression === orig && needs_unbinding(compressor, val); } else if (parent instanceof AST_Template) { wrap = parent.tag === orig && needs_unbinding(compressor, val); } else if (parent instanceof AST_UnaryPrefix) { wrap = parent.operator == "delete" || parent.operator == "typeof" && is_undeclared_ref(val); } return wrap ? make_sequence(orig, [ make_node(AST_Number, orig, { value: 0 }), val ]) : val; }
function maintain_this_binding(compressor, parent, orig, val) { var wrap = false; if (parent.TYPE == "Call") { wrap = parent.expression === orig && needs_unbinding(compressor, val); } else if (parent instanceof AST_Template) { wrap = parent.tag === orig && needs_unbinding(compressor, val); } else if (parent instanceof AST_UnaryPrefix) { wrap = parent.operator == "delete" || parent.operator == "typeof" && is_undeclared_ref(val); } return wrap ? make_sequence(orig, [ make_node(AST_Number, orig, { value: 0 }), val ]) : val; }
JavaScript
function World(def) { if (!(this instanceof World)) { return new World(def); } if (def && Vec2.isValid(def)) { def = {gravity : def}; } def = options(def, WorldDef); this.m_solver = new Solver(this); this.m_broadPhase = new BroadPhase(); this.m_contactList = null; this.m_contactCount = 0; this.m_bodyList = null; this.m_bodyCount = 0; this.m_jointList = null; this.m_jointCount = 0; this.m_stepComplete = true; this.m_allowSleep = def.allowSleep; this.m_gravity = Vec2.clone(def.gravity); this.m_clearForces = true; this.m_newFixture = false; this.m_locked = false; // These are for debugging the solver. this.m_warmStarting = def.warmStarting; this.m_continuousPhysics = def.continuousPhysics; this.m_subStepping = def.subStepping; this.m_blockSolve = def.blockSolve; this.m_velocityIterations = def.velocityIterations; this.m_positionIterations = def.positionIterations; this.m_t = 0; this.m_stepCount = 0; }
function World(def) { if (!(this instanceof World)) { return new World(def); } if (def && Vec2.isValid(def)) { def = {gravity : def}; } def = options(def, WorldDef); this.m_solver = new Solver(this); this.m_broadPhase = new BroadPhase(); this.m_contactList = null; this.m_contactCount = 0; this.m_bodyList = null; this.m_bodyCount = 0; this.m_jointList = null; this.m_jointCount = 0; this.m_stepComplete = true; this.m_allowSleep = def.allowSleep; this.m_gravity = Vec2.clone(def.gravity); this.m_clearForces = true; this.m_newFixture = false; this.m_locked = false; // These are for debugging the solver. this.m_warmStarting = def.warmStarting; this.m_continuousPhysics = def.continuousPhysics; this.m_subStepping = def.subStepping; this.m_blockSolve = def.blockSolve; this.m_velocityIterations = def.velocityIterations; this.m_positionIterations = def.positionIterations; this.m_t = 0; this.m_stepCount = 0; }
JavaScript
open() { // register keypress event readline.emitKeypressEvents(this.stream); // handle keypress this.stream.on('keypress', this.onKeyPress); // initially render the response if (this.renderer) { this.renderer.render(this.selectedValue); } // hide pressed keys and start listening on input this.stream.setRawMode(true); this.stream.resume(); }
open() { // register keypress event readline.emitKeypressEvents(this.stream); // handle keypress this.stream.on('keypress', this.onKeyPress); // initially render the response if (this.renderer) { this.renderer.render(this.selectedValue); } // hide pressed keys and start listening on input this.stream.setRawMode(true); this.stream.resume(); }
JavaScript
close(cancelled = false) { // reset stream properties this.stream.setRawMode(false); this.stream.pause(); // cleanup the output if (this.renderer) { this.renderer.cleanup(); } // call the on select listener if (cancelled) { this.onSelectListener(null); } else { this.onSelectListener(this.selectedValue, this.values[this.selectedValue]); } this.stream.removeListener('keypress', this.onKeyPress); }
close(cancelled = false) { // reset stream properties this.stream.setRawMode(false); this.stream.pause(); // cleanup the output if (this.renderer) { this.renderer.cleanup(); } // call the on select listener if (cancelled) { this.onSelectListener(null); } else { this.onSelectListener(this.selectedValue, this.values[this.selectedValue]); } this.stream.removeListener('keypress', this.onKeyPress); }
JavaScript
onKeyPress(string, key) { if (key) { if (key.name === 'up' && this.selectedValue > 0) { this.selectedValue--; this.render(); } else if (key.name === 'down' && this.selectedValue + 1 < this.values.length) { this.selectedValue++; this.render(); } else if (key.name === 'return') { this.close(); } else if (key.name === 'escape' || (key.name === 'c' && key.ctrl)) { this.close(true); } } }
onKeyPress(string, key) { if (key) { if (key.name === 'up' && this.selectedValue > 0) { this.selectedValue--; this.render(); } else if (key.name === 'down' && this.selectedValue + 1 < this.values.length) { this.selectedValue++; this.render(); } else if (key.name === 'return') { this.close(); } else if (key.name === 'escape' || (key.name === 'c' && key.ctrl)) { this.close(true); } } }
JavaScript
function matrix_mapping(x, y) { let matrix_array = [ [0,47,48,95,96,143,144,191,192,239,240,287,288,335,336,383], [1,46,49,94,97,142,145,190,193,238,241,286,289,334,337,382], [2,45,50,93,98,141,146,189,194,237,242,285,290,333,338,381], [3,44,51,92,99,140,147,188,195,236,243,284,291,332,339,380], [4,43,52,91,100,139,148,187,196,235,244,283,292,331,340,379], [5,42,53,90,101,138,149,186,197,234,245,282,293,330,341,378], [6,41,54,89,102,137,150,185,198,233,246,281,294,329,342,377], [7,40,55,88,103,136,151,184,199,232,247,280,295,328,343,376], [8,39,56,87,104,135,152,183,200,231,248,279,296,327,344,375], [9,38,57,86,105,134,153,182,201,230,249,278,297,326,345,374], [10,37,58,85,106,133,154,181,202,229,250,277,298,325,346,373], [11,36,59,84,107,132,155,180,203,228,251,276,299,324,347,372], [12,35,60,83,108,131,156,179,204,227,252,275,300,323,348,371], [13,34,61,82,109,130,157,178,205,226,253,274,301,322,349,370], [14,33,62,81,110,129,158,177,206,225,254,273,302,321,350,369], [15,32,63,80,111,128,159,176,207,224,255,272,303,320,351,368], [16,31,64,79,112,127,160,175,208,223,256,271,304,319,352,367], [17,30,65,78,113,126,161,174,209,222,257,270,305,318,353,366], [18,29,66,77,114,125,162,173,210,221,258,269,306,317,354,365], [19,28,67,76,115,124,163,172,211,220,259,268,307,316,355,364], [20,27,68,75,116,123,164,171,212,219,260,267,308,315,356,363], [21,26,69,74,117,122,165,170,213,218,261,266,309,314,357,362], [22,25,70,73,118,121,166,169,214,217,262,265,310,313,358,361], [23,24,71,72,119,120,167,168,215,216,263,264,311,312,359,360], ]; return matrix_array[x][y]; }
function matrix_mapping(x, y) { let matrix_array = [ [0,47,48,95,96,143,144,191,192,239,240,287,288,335,336,383], [1,46,49,94,97,142,145,190,193,238,241,286,289,334,337,382], [2,45,50,93,98,141,146,189,194,237,242,285,290,333,338,381], [3,44,51,92,99,140,147,188,195,236,243,284,291,332,339,380], [4,43,52,91,100,139,148,187,196,235,244,283,292,331,340,379], [5,42,53,90,101,138,149,186,197,234,245,282,293,330,341,378], [6,41,54,89,102,137,150,185,198,233,246,281,294,329,342,377], [7,40,55,88,103,136,151,184,199,232,247,280,295,328,343,376], [8,39,56,87,104,135,152,183,200,231,248,279,296,327,344,375], [9,38,57,86,105,134,153,182,201,230,249,278,297,326,345,374], [10,37,58,85,106,133,154,181,202,229,250,277,298,325,346,373], [11,36,59,84,107,132,155,180,203,228,251,276,299,324,347,372], [12,35,60,83,108,131,156,179,204,227,252,275,300,323,348,371], [13,34,61,82,109,130,157,178,205,226,253,274,301,322,349,370], [14,33,62,81,110,129,158,177,206,225,254,273,302,321,350,369], [15,32,63,80,111,128,159,176,207,224,255,272,303,320,351,368], [16,31,64,79,112,127,160,175,208,223,256,271,304,319,352,367], [17,30,65,78,113,126,161,174,209,222,257,270,305,318,353,366], [18,29,66,77,114,125,162,173,210,221,258,269,306,317,354,365], [19,28,67,76,115,124,163,172,211,220,259,268,307,316,355,364], [20,27,68,75,116,123,164,171,212,219,260,267,308,315,356,363], [21,26,69,74,117,122,165,170,213,218,261,266,309,314,357,362], [22,25,70,73,118,121,166,169,214,217,262,265,310,313,358,361], [23,24,71,72,119,120,167,168,215,216,263,264,311,312,359,360], ]; return matrix_array[x][y]; }
JavaScript
function matrix_mapping(x, y) { let matrix_array = [ [0,47,48,95,96,143,144,191,192,239,240,287,288,335,336,383], [1,46,49,94,97,142,145,190,193,238,241,286,289,334,337,382], [2,45,50,93,98,141,146,189,194,237,242,285,290,333,338,381], [3,44,51,92,99,140,147,188,195,236,243,284,291,332,339,380], [4,43,52,91,100,139,148,187,196,235,244,283,292,331,340,379], [5,42,53,90,101,138,149,186,197,234,245,282,293,330,341,378], [6,41,54,89,102,137,150,185,198,233,246,281,294,329,342,377], [7,40,55,88,103,136,151,184,199,232,247,280,295,328,343,376], [8,39,56,87,104,135,152,183,200,231,248,279,296,327,344,375], [9,38,57,86,105,134,153,182,201,230,249,278,297,326,345,374], [10,37,58,85,106,133,154,181,202,229,250,277,298,325,346,373], [11,36,59,84,107,132,155,180,203,228,251,276,299,324,347,372], [12,35,60,83,108,131,156,179,204,227,252,275,300,323,348,371], [13,34,61,82,109,130,157,178,205,226,253,274,301,322,349,370], [14,33,62,81,110,129,158,177,206,225,254,273,302,321,350,369], [15,32,63,80,111,128,159,176,207,224,255,272,303,320,351,368], [16,31,64,79,112,127,160,175,208,223,256,271,304,319,352,367], [17,30,65,78,113,126,161,174,209,222,257,270,305,318,353,366], [18,29,66,77,114,125,162,173,210,221,258,269,306,317,354,365], [19,28,67,76,115,124,163,172,211,220,259,268,307,316,355,364], [20,27,68,75,116,123,164,171,212,219,260,267,308,315,356,363], [21,26,69,74,117,122,165,170,213,218,261,266,309,314,357,362], [22,25,70,73,118,121,166,169,214,217,262,265,310,313,358,361], [23,24,71,72,119,120,167,168,215,216,263,264,311,312,359,360], ]; return matrix_array[x][y]; }
function matrix_mapping(x, y) { let matrix_array = [ [0,47,48,95,96,143,144,191,192,239,240,287,288,335,336,383], [1,46,49,94,97,142,145,190,193,238,241,286,289,334,337,382], [2,45,50,93,98,141,146,189,194,237,242,285,290,333,338,381], [3,44,51,92,99,140,147,188,195,236,243,284,291,332,339,380], [4,43,52,91,100,139,148,187,196,235,244,283,292,331,340,379], [5,42,53,90,101,138,149,186,197,234,245,282,293,330,341,378], [6,41,54,89,102,137,150,185,198,233,246,281,294,329,342,377], [7,40,55,88,103,136,151,184,199,232,247,280,295,328,343,376], [8,39,56,87,104,135,152,183,200,231,248,279,296,327,344,375], [9,38,57,86,105,134,153,182,201,230,249,278,297,326,345,374], [10,37,58,85,106,133,154,181,202,229,250,277,298,325,346,373], [11,36,59,84,107,132,155,180,203,228,251,276,299,324,347,372], [12,35,60,83,108,131,156,179,204,227,252,275,300,323,348,371], [13,34,61,82,109,130,157,178,205,226,253,274,301,322,349,370], [14,33,62,81,110,129,158,177,206,225,254,273,302,321,350,369], [15,32,63,80,111,128,159,176,207,224,255,272,303,320,351,368], [16,31,64,79,112,127,160,175,208,223,256,271,304,319,352,367], [17,30,65,78,113,126,161,174,209,222,257,270,305,318,353,366], [18,29,66,77,114,125,162,173,210,221,258,269,306,317,354,365], [19,28,67,76,115,124,163,172,211,220,259,268,307,316,355,364], [20,27,68,75,116,123,164,171,212,219,260,267,308,315,356,363], [21,26,69,74,117,122,165,170,213,218,261,266,309,314,357,362], [22,25,70,73,118,121,166,169,214,217,262,265,310,313,358,361], [23,24,71,72,119,120,167,168,215,216,263,264,311,312,359,360], ]; return matrix_array[x][y]; }
JavaScript
function numberToLetter(number) { var char = numberToAscii(96 + number).toLowerCase(); if (char >= 'a' && char <= 'z') return char; return ''; }
function numberToLetter(number) { var char = numberToAscii(96 + number).toLowerCase(); if (char >= 'a' && char <= 'z') return char; return ''; }
JavaScript
function romanize(num) { if (!+num || num > 10000) return ''; var digits = String(+num).split(''), key = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'], roman = '', i = 3; while (i--) roman = (key[+digits.pop() + (i * 10)] || '') + roman; return new Array(+digits.join('') + 1).join('M') + roman; }
function romanize(num) { if (!+num || num > 10000) return ''; var digits = String(+num).split(''), key = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'], roman = '', i = 3; while (i--) roman = (key[+digits.pop() + (i * 10)] || '') + roman; return new Array(+digits.join('') + 1).join('M') + roman; }
JavaScript
function caesar(value, offset) { var asciiValue = charToAscii(value.toLowerCase()); if (!isLetter(value)) return ''; var newAsciiValue = asciiValue + offset; newAsciiValue = (newAsciiValue > 122) ? newAsciiValue - 26 : newAsciiValue; return String.fromCharCode(newAsciiValue); }
function caesar(value, offset) { var asciiValue = charToAscii(value.toLowerCase()); if (!isLetter(value)) return ''; var newAsciiValue = asciiValue + offset; newAsciiValue = (newAsciiValue > 122) ? newAsciiValue - 26 : newAsciiValue; return String.fromCharCode(newAsciiValue); }
JavaScript
async function clean() { const files = [...staticFiles, 'module']; if (fs.existsSync(`${stylesDirectory}/${name}.${stylesExtension}`)) { files.push('styles'); } console.log(' ', chalk.yellow('Files to clean:')); console.log(' ', chalk.blueBright(files.join('\n '))); for (const filePath of files) { await fs.remove(`${distDirectory}/${filePath}`); } }
async function clean() { const files = [...staticFiles, 'module']; if (fs.existsSync(`${stylesDirectory}/${name}.${stylesExtension}`)) { files.push('styles'); } console.log(' ', chalk.yellow('Files to clean:')); console.log(' ', chalk.blueBright(files.join('\n '))); for (const filePath of files) { await fs.remove(`${distDirectory}/${filePath}`); } }
JavaScript
async function linkUserData() { let destinationDirectory; if (fs.existsSync(path.resolve(sourceDirectory, 'module.json'))) { destinationDirectory = 'modules'; } else { throw new Error(`Could not find ${chalk.blueBright('module.json')}`); } const linkDirectory = path.resolve(getDataPath(), destinationDirectory, name); if (argv.clean || argv.c) { console.log(chalk.yellow(`Removing build in ${chalk.blueBright(linkDirectory)}.`)); await fs.remove(linkDirectory); } else if (!fs.existsSync(linkDirectory)) { console.log(chalk.green(`Linking dist to ${chalk.blueBright(linkDirectory)}.`)); await fs.ensureDir(path.resolve(linkDirectory, '..')); await fs.symlink(path.resolve(distDirectory), linkDirectory); } }
async function linkUserData() { let destinationDirectory; if (fs.existsSync(path.resolve(sourceDirectory, 'module.json'))) { destinationDirectory = 'modules'; } else { throw new Error(`Could not find ${chalk.blueBright('module.json')}`); } const linkDirectory = path.resolve(getDataPath(), destinationDirectory, name); if (argv.clean || argv.c) { console.log(chalk.yellow(`Removing build in ${chalk.blueBright(linkDirectory)}.`)); await fs.remove(linkDirectory); } else if (!fs.existsSync(linkDirectory)) { console.log(chalk.green(`Linking dist to ${chalk.blueBright(linkDirectory)}.`)); await fs.ensureDir(path.resolve(linkDirectory, '..')); await fs.symlink(path.resolve(distDirectory), linkDirectory); } }
JavaScript
function bumpVersion(cb) { const packageJson = fs.readJSONSync('package.json'); const packageLockJson = fs.existsSync('package-lock.json') ? fs.readJSONSync('package-lock.json') : undefined; const manifest = getManifest(); if (!manifest) cb(Error(chalk.red('Manifest JSON not found'))); try { const release = argv.release || argv.r; const currentVersion = packageJson.version; if (!release) { return cb(Error('Missing release type')); } const targetVersion = getTargetVersion(currentVersion, release); if (!targetVersion) { return cb(new Error(chalk.red('Error: Incorrect version arguments'))); } if (targetVersion === currentVersion) { return cb(new Error(chalk.red('Error: Target version is identical to current version'))); } console.log(`Updating version number to '${targetVersion}'`); packageJson.version = targetVersion; fs.writeJSONSync('package.json', packageJson, { spaces: 2 }); if (packageLockJson) { packageLockJson.version = targetVersion; fs.writeJSONSync('package-lock.json', packageLockJson, { spaces: 2 }); } manifest.file.version = targetVersion; manifest.file.download = getDownloadURL(targetVersion); fs.writeJSONSync(`${sourceDirectory}/${manifest.name}`, manifest.file, { spaces: 2 }); return cb(); } catch (err) { cb(err); } }
function bumpVersion(cb) { const packageJson = fs.readJSONSync('package.json'); const packageLockJson = fs.existsSync('package-lock.json') ? fs.readJSONSync('package-lock.json') : undefined; const manifest = getManifest(); if (!manifest) cb(Error(chalk.red('Manifest JSON not found'))); try { const release = argv.release || argv.r; const currentVersion = packageJson.version; if (!release) { return cb(Error('Missing release type')); } const targetVersion = getTargetVersion(currentVersion, release); if (!targetVersion) { return cb(new Error(chalk.red('Error: Incorrect version arguments'))); } if (targetVersion === currentVersion) { return cb(new Error(chalk.red('Error: Target version is identical to current version'))); } console.log(`Updating version number to '${targetVersion}'`); packageJson.version = targetVersion; fs.writeJSONSync('package.json', packageJson, { spaces: 2 }); if (packageLockJson) { packageLockJson.version = targetVersion; fs.writeJSONSync('package-lock.json', packageLockJson, { spaces: 2 }); } manifest.file.version = targetVersion; manifest.file.download = getDownloadURL(targetVersion); fs.writeJSONSync(`${sourceDirectory}/${manifest.name}`, manifest.file, { spaces: 2 }); return cb(); } catch (err) { cb(err); } }
JavaScript
function mainOnObject() { // Instantiate an object from class ServiceNowConnector. const connector = new ServiceNowConnector(options); // Test the object's get and post methods. // You must write the arguments for get and post. connector.get(options); connector.post(options); }
function mainOnObject() { // Instantiate an object from class ServiceNowConnector. const connector = new ServiceNowConnector(options); // Test the object's get and post methods. // You must write the arguments for get and post. connector.get(options); connector.post(options); }
JavaScript
function HttpConfig($httpProvider) { $httpProvider.defaults.withCredentials = true; if ($httpProvider.defaults.headers['get']) { $httpProvider.defaults.headers['get']['If-Modified-Since'] = '0'; } }
function HttpConfig($httpProvider) { $httpProvider.defaults.withCredentials = true; if ($httpProvider.defaults.headers['get']) { $httpProvider.defaults.headers['get']['If-Modified-Since'] = '0'; } }
JavaScript
function initClient() { gapi.client.init({ apiKey: API_KEY, clientId: CLIENT_ID, discoveryDocs: DISCOVERY_DOCS, scope: SCOPES }).then(function () { // Listen for sign-in state changes. gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus); // Handle the initial sign-in state. updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get()); authorizeButton.onclick = handleAuthClick; signoutButton.onclick = handleSignoutClick; }, function(error) { appendPre(JSON.stringify(error, null, 2)); appendPre2(JSON.stringify(error, null, 2)); }); }
function initClient() { gapi.client.init({ apiKey: API_KEY, clientId: CLIENT_ID, discoveryDocs: DISCOVERY_DOCS, scope: SCOPES }).then(function () { // Listen for sign-in state changes. gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus); // Handle the initial sign-in state. updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get()); authorizeButton.onclick = handleAuthClick; signoutButton.onclick = handleSignoutClick; }, function(error) { appendPre(JSON.stringify(error, null, 2)); appendPre2(JSON.stringify(error, null, 2)); }); }
JavaScript
function updateSigninStatus(isSignedIn) { if (isSignedIn) { authorizeButton.style.display = 'none'; signoutButton.style.display = 'block'; listUpcomingEvents(); listUpcomingEvents2(); //run second function for tomorrows data } else { authorizeButton.style.display = 'block'; signoutButton.style.display = 'none'; } }
function updateSigninStatus(isSignedIn) { if (isSignedIn) { authorizeButton.style.display = 'none'; signoutButton.style.display = 'block'; listUpcomingEvents(); listUpcomingEvents2(); //run second function for tomorrows data } else { authorizeButton.style.display = 'block'; signoutButton.style.display = 'none'; } }
JavaScript
function appendPre(message) { //todays events var pre = document.getElementById('content'); var textContent = document.createTextNode(message + '\n'); pre.appendChild(textContent); }
function appendPre(message) { //todays events var pre = document.getElementById('content'); var textContent = document.createTextNode(message + '\n'); pre.appendChild(textContent); }
JavaScript
function listUpcomingEvents() { //todays events gapi.client.calendar.events.list({ 'calendarId': 'primary', 'timeMin': firstDay + 'T01:00:00+01:00', 'timeMax': secondDay + 'T01:00:00+01:00', 'showDeleted': false, 'singleEvents': true, 'maxResults': 5, 'orderBy': 'startTime' }).then(function(response) { var events = response.result.items; appendPre(''); if (events.length > 0) { for (i = 0; i < events.length; i++) { {var event = events[i]; var when = event.start.dateTime; if (!when) { when = event.start.date; } appendPre((i+1) + ' - ' + event.summary) } } } else { appendPre('No upcoming events found.'); } console.log(events); }); }
function listUpcomingEvents() { //todays events gapi.client.calendar.events.list({ 'calendarId': 'primary', 'timeMin': firstDay + 'T01:00:00+01:00', 'timeMax': secondDay + 'T01:00:00+01:00', 'showDeleted': false, 'singleEvents': true, 'maxResults': 5, 'orderBy': 'startTime' }).then(function(response) { var events = response.result.items; appendPre(''); if (events.length > 0) { for (i = 0; i < events.length; i++) { {var event = events[i]; var when = event.start.dateTime; if (!when) { when = event.start.date; } appendPre((i+1) + ' - ' + event.summary) } } } else { appendPre('No upcoming events found.'); } console.log(events); }); }
JavaScript
function Node (data) { this.data = data; this.next = null; this.prev = null; }
function Node (data) { this.data = data; this.next = null; this.prev = null; }
JavaScript
function LinkedList () { this.head = null; this.tail = null; this.length = 0; }
function LinkedList () { this.head = null; this.tail = null; this.length = 0; }
JavaScript
function Node (value) { this.value = value; this.left = null; this.right = null; }
function Node (value) { this.value = value; this.left = null; this.right = null; }
JavaScript
function inorderWalk (node) { if (node) { inorderWalk (node.left); console.log (node.value); inorderWalk (node.right); } }
function inorderWalk (node) { if (node) { inorderWalk (node.left); console.log (node.value); inorderWalk (node.right); } }
JavaScript
function preorderWalk (node) { if (node) { console.log (node.value); preorderWalk (node.left); preorderWalk (node.right); } }
function preorderWalk (node) { if (node) { console.log (node.value); preorderWalk (node.left); preorderWalk (node.right); } }
JavaScript
function postorderWalk (node) { if (node) { postorderWalk (node.left); postorderWalk (node.right); console.log (node.value); } }
function postorderWalk (node) { if (node) { postorderWalk (node.left); postorderWalk (node.right); console.log (node.value); } }
JavaScript
initialLister(){ //jika user sudah login if(this.isAuth){ //inisiasi fungsi broadcaster window.Echo = new Echo({ broadcaster: 'pusher', key: process.env.MIX_PUSHER_APP_KEY, cluster: process.env.MIX_PUSHER_APP_CLUSTER, encrypted: false, auth: { headers: { Authorization: 'Bearer ' + this.token } } }); if(typeof this.authenticated.id != 'undefined'){ //mengakses channel broadcast secara private window.Echo.private(`App.User.${this.authenticated.id}`) //channel yang dapat ditemukan pada file routes/channel.php, fungsinya untuk memastikan bahwa user yang login benar karena kita menggunakan private channel dimana hanya user yang memiliki akses yang dapat mengambil data broadcast .notification(() => { //apabila ditemukan, maka akan menjalankan fungsi berikut this.getNotifications() this.getExpenses() }) } } }
initialLister(){ //jika user sudah login if(this.isAuth){ //inisiasi fungsi broadcaster window.Echo = new Echo({ broadcaster: 'pusher', key: process.env.MIX_PUSHER_APP_KEY, cluster: process.env.MIX_PUSHER_APP_CLUSTER, encrypted: false, auth: { headers: { Authorization: 'Bearer ' + this.token } } }); if(typeof this.authenticated.id != 'undefined'){ //mengakses channel broadcast secara private window.Echo.private(`App.User.${this.authenticated.id}`) //channel yang dapat ditemukan pada file routes/channel.php, fungsinya untuk memastikan bahwa user yang login benar karena kita menggunakan private channel dimana hanya user yang memiliki akses yang dapat mengambil data broadcast .notification(() => { //apabila ditemukan, maka akan menjalankan fungsi berikut this.getNotifications() this.getExpenses() }) } } }
JavaScript
ASSIGN_FORM(state, payload){ state.outlet = { code: payload.code, name: payload.name, status: payload.status, address: payload.address, phone: payload.phone } }
ASSIGN_FORM(state, payload){ state.outlet = { code: payload.code, name: payload.name, status: payload.status, address: payload.address, phone: payload.phone } }
JavaScript
CLEAR_FORM(state, payload){ state.outlet = { code: '', name: '', status: '', address: '', phone: '' } }
CLEAR_FORM(state, payload){ state.outlet = { code: '', name: '', status: '', address: '', phone: '' } }
JavaScript
editOutlet({ commit }, payload){ return new Promise((resolve, reject) => { $axios.get(`/outlets/${payload}/edit`) .then((res) => { //APABIL BERHASIL, DI ASSIGN KE FORM commit('ASSIGN_FORM', res.data.data) resolve(res.data) }) }) }
editOutlet({ commit }, payload){ return new Promise((resolve, reject) => { $axios.get(`/outlets/${payload}/edit`) .then((res) => { //APABIL BERHASIL, DI ASSIGN KE FORM commit('ASSIGN_FORM', res.data.data) resolve(res.data) }) }) }
JavaScript
updateOutlet({ state, commit }, payload){ return new Promise((resolve, reject) => { commit('SET_LOADING', true) //MELAKUKAN REQUEST DENGAN MENGIRIMKAN CODE DIURL //DAN MENGIRIMKAN DATA TERBARU YANG TELAH DIEDIT //MELALUI STATE OUTLET $axios.put(`/outlets/${payload}`, state.outlet) .then((res) => { //FORM DIBERSIHKAN commit('CLEAR_FORM') commit('SET_LOADING', false) commit('SET_SUCCESS', res.data, { root: true }) resolve(res.data) }) .catch((error) => { commit('SET_LOADING', false) //kirim value error ke store.js commit('SET_ERRORS', error.response.data.errors, { root: true }) }) }) }
updateOutlet({ state, commit }, payload){ return new Promise((resolve, reject) => { commit('SET_LOADING', true) //MELAKUKAN REQUEST DENGAN MENGIRIMKAN CODE DIURL //DAN MENGIRIMKAN DATA TERBARU YANG TELAH DIEDIT //MELALUI STATE OUTLET $axios.put(`/outlets/${payload}`, state.outlet) .then((res) => { //FORM DIBERSIHKAN commit('CLEAR_FORM') commit('SET_LOADING', false) commit('SET_SUCCESS', res.data, { root: true }) resolve(res.data) }) .catch((error) => { commit('SET_LOADING', false) //kirim value error ke store.js commit('SET_ERRORS', error.response.data.errors, { root: true }) }) }) }
JavaScript
viewTransaction({ commit }, payload){ return new Promise((resolve, reject) => { $axios.get(`/transaction/${payload}/view`) .then((res) => { commit('DATA_ORDER', res.data.data) resolve(res.data) }) }) }
viewTransaction({ commit }, payload){ return new Promise((resolve, reject) => { $axios.get(`/transaction/${payload}/view`) .then((res) => { commit('DATA_ORDER', res.data.data) resolve(res.data) }) }) }
JavaScript
completeItem({commit}, payload){ return new Promise((resolve, reject) => { $axios.post(`/transaction/complete-item`, payload) .then((res) => { resolve(res.data) commit('SET_SUCCESS', res.data, { root: true }) }) }) }
completeItem({commit}, payload){ return new Promise((resolve, reject) => { $axios.post(`/transaction/complete-item`, payload) .then((res) => { resolve(res.data) commit('SET_SUCCESS', res.data, { root: true }) }) }) }
JavaScript
ASSIGN_FORM(state, payload){ state.operator = { name: payload.name, email: payload.email, password: '', role: payload.role, outlet_id: payload.outlet_id, photo: '' } }
ASSIGN_FORM(state, payload){ state.operator = { name: payload.name, email: payload.email, password: '', role: payload.role, outlet_id: payload.outlet_id, photo: '' } }
JavaScript
CLEAR_FORM(state, payload){ state.operator = { name: '', email: '', password: '', role: '', outlet_id: '', photo: '' } }
CLEAR_FORM(state, payload){ state.operator = { name: '', email: '', password: '', role: '', outlet_id: '', photo: '' } }
JavaScript
editOperator({ commit }, payload){ return new Promise((resolve, reject) => { $axios.get(`/user/${payload}/edit`) .then((res) => { //APABIL BERHASIL, DI ASSIGN KE FORM commit('ASSIGN_FORM', res.data.data) resolve(res.data) }) }) }
editOperator({ commit }, payload){ return new Promise((resolve, reject) => { $axios.get(`/user/${payload}/edit`) .then((res) => { //APABIL BERHASIL, DI ASSIGN KE FORM commit('ASSIGN_FORM', res.data.data) resolve(res.data) }) }) }
JavaScript
updateOperator({ commit, state }, payload){ let form = new FormData() //UNTUK MENGUPLOAD GAMBAR HARUS MENGGUNAKAN FORMDATA form.append('name', state.operator.name) form.append('email', state.operator.email) form.append('password', state.operator.password) form.append('role', state.operator.role) form.append('outlet_id', state.operator.outlet_id) form.append('photo', state.operator.photo) return new Promise((resolve, reject) => { commit('SET_LOADING', true) $axios.post(`/operator/${payload}`, form, { //KARENA TERDAPAT FILE FOTO, MAKA HEADERNYA DITAMBAHKAN multipart/form-data headers: { 'Content-Type' : 'multipart/form-data' } }) .then((res) => { commit('CLEAR_FORM') commit('SET_LOADING', false) commit('SET_SUCCESS', res.data, { root: true }) resolve(res.data) }) .catch((err) => { if(err.response.status == 422){ commit('SET_ERRORS', err.response.data.errors, {root: true}) } else if(err.response.status == 400){ commit('SET_ERRORS', err.response.data, { root: true }) } commit('SET_LOADING', false) }) }) }
updateOperator({ commit, state }, payload){ let form = new FormData() //UNTUK MENGUPLOAD GAMBAR HARUS MENGGUNAKAN FORMDATA form.append('name', state.operator.name) form.append('email', state.operator.email) form.append('password', state.operator.password) form.append('role', state.operator.role) form.append('outlet_id', state.operator.outlet_id) form.append('photo', state.operator.photo) return new Promise((resolve, reject) => { commit('SET_LOADING', true) $axios.post(`/operator/${payload}`, form, { //KARENA TERDAPAT FILE FOTO, MAKA HEADERNYA DITAMBAHKAN multipart/form-data headers: { 'Content-Type' : 'multipart/form-data' } }) .then((res) => { commit('CLEAR_FORM') commit('SET_LOADING', false) commit('SET_SUCCESS', res.data, { root: true }) resolve(res.data) }) .catch((err) => { if(err.response.status == 422){ commit('SET_ERRORS', err.response.data.errors, {root: true}) } else if(err.response.status == 400){ commit('SET_ERRORS', err.response.data, { root: true }) } commit('SET_LOADING', false) }) }) }
JavaScript
ASSIGN_FORM(state, payload){ state.user = { name: payload.name, email: payload.email, password: '', role: payload.role, outlet_id: payload.outlet_id, photo: '' } }
ASSIGN_FORM(state, payload){ state.user = { name: payload.name, email: payload.email, password: '', role: payload.role, outlet_id: payload.outlet_id, photo: '' } }
JavaScript
CLEAR_FORM(state, payload){ state.user = { name: '', email: '', password: '', role: '', outlet_id: '', photo: '' } }
CLEAR_FORM(state, payload){ state.user = { name: '', email: '', password: '', role: '', outlet_id: '', photo: '' } }
JavaScript
editUser({ commit }, payload){ return new Promise((resolve, reject) => { $axios.get(`/user/${payload}/edit`) .then((res) => { //APABIL BERHASIL, DI ASSIGN KE FORM commit('ASSIGN_FORM', res.data.data) resolve(res.data) }) }) }
editUser({ commit }, payload){ return new Promise((resolve, reject) => { $axios.get(`/user/${payload}/edit`) .then((res) => { //APABIL BERHASIL, DI ASSIGN KE FORM commit('ASSIGN_FORM', res.data.data) resolve(res.data) }) }) }
JavaScript
updateUser({ commit, state }, payload){ let form = new FormData() //UNTUK MENGUPLOAD GAMBAR HARUS MENGGUNAKAN FORMDATA form.append('name', state.user.name) form.append('email', state.user.email) form.append('password', state.user.password) form.append('role', state.user.role) form.append('outlet_id', state.user.outlet_id) form.append('photo', state.user.photo) return new Promise((resolve, reject) => { commit('SET_LOADING', true) $axios.post(`/user/${payload}`, form, { //KARENA TERDAPAT FILE FOTO, MAKA HEADERNYA DITAMBAHKAN multipart/form-data headers: { 'Content-Type' : 'multipart/form-data' } }) .then((res) => { commit('CLEAR_FORM') commit('SET_LOADING', false) commit('SET_SUCCESS', res.data, { root: true }) resolve(res.data) }) .catch((err) => { if(err.response.status == 422){ commit('SET_ERRORS', err.response.data.errors, {root: true}) } else if(err.response.status == 400){ commit('SET_ERRORS', err.response.data, { root: true }) } commit('SET_LOADING', false) }) }) }
updateUser({ commit, state }, payload){ let form = new FormData() //UNTUK MENGUPLOAD GAMBAR HARUS MENGGUNAKAN FORMDATA form.append('name', state.user.name) form.append('email', state.user.email) form.append('password', state.user.password) form.append('role', state.user.role) form.append('outlet_id', state.user.outlet_id) form.append('photo', state.user.photo) return new Promise((resolve, reject) => { commit('SET_LOADING', true) $axios.post(`/user/${payload}`, form, { //KARENA TERDAPAT FILE FOTO, MAKA HEADERNYA DITAMBAHKAN multipart/form-data headers: { 'Content-Type' : 'multipart/form-data' } }) .then((res) => { commit('CLEAR_FORM') commit('SET_LOADING', false) commit('SET_SUCCESS', res.data, { root: true }) resolve(res.data) }) .catch((err) => { if(err.response.status == 422){ commit('SET_ERRORS', err.response.data.errors, {root: true}) } else if(err.response.status == 400){ commit('SET_ERRORS', err.response.data, { root: true }) } commit('SET_LOADING', false) }) }) }
JavaScript
ASSIGN_FORM(state, payload){ state.product = { name: payload.name, type_id: payload.type[0].id, size: payload.type[0].pivot.size, description: payload.description, price: payload.price, // user_id: payload.user.id //user_id tidak diupdate, sehingga dihilangkan saja formnya } }
ASSIGN_FORM(state, payload){ state.product = { name: payload.name, type_id: payload.type[0].id, size: payload.type[0].pivot.size, description: payload.description, price: payload.price, // user_id: payload.user.id //user_id tidak diupdate, sehingga dihilangkan saja formnya } }
JavaScript
updateProduct({ state, commit }, payload){ return new Promise((resolve, reject) => { commit('SET_LOADING', true) $axios.put(`/product/${payload}`, state.product) .then((res) => { commit('CLEAR_FORM') commit('SET_LOADING', false) commit('SET_SUCCESS', res.data, { root: true }) resolve(res.data) }) .catch((err) => { if(err.response.status == 422){ commit('SET_ERRORS', err.response.data.errors, {root: true}) } else if(err.response.status == 400){ commit('SET_ERRORS', err.response.data, { root: true }) } commit('SET_LOADING', false) }) }) }
updateProduct({ state, commit }, payload){ return new Promise((resolve, reject) => { commit('SET_LOADING', true) $axios.put(`/product/${payload}`, state.product) .then((res) => { commit('CLEAR_FORM') commit('SET_LOADING', false) commit('SET_SUCCESS', res.data, { root: true }) resolve(res.data) }) .catch((err) => { if(err.response.status == 422){ commit('SET_ERRORS', err.response.data.errors, {root: true}) } else if(err.response.status == 400){ commit('SET_ERRORS', err.response.data, { root: true }) } commit('SET_LOADING', false) }) }) }
JavaScript
function processScriptQueue (queue) { if (!scriptActive[queue] && scriptQueue[queue].length > 0) { childproc = require('child_process').spawn(scriptQueue[queue][0].command, scriptQueue[queue][0].args, scriptQueue[queue][0].options); scriptActive[queue] = true; childproc.on('error', function (err) { clearQueue(queue); console.log('Script error: ', err); }) childproc.on('exit', function () { // Remove the finished task from the queue if (scriptQueue[queue].length > 0) { scriptQueue[queue].shift(); } // Set the queue as inactive scriptActive[queue] = false; // Process the next task in the queue, if any. processScriptQueue(queue); }); } }
function processScriptQueue (queue) { if (!scriptActive[queue] && scriptQueue[queue].length > 0) { childproc = require('child_process').spawn(scriptQueue[queue][0].command, scriptQueue[queue][0].args, scriptQueue[queue][0].options); scriptActive[queue] = true; childproc.on('error', function (err) { clearQueue(queue); console.log('Script error: ', err); }) childproc.on('exit', function () { // Remove the finished task from the queue if (scriptQueue[queue].length > 0) { scriptQueue[queue].shift(); } // Set the queue as inactive scriptActive[queue] = false; // Process the next task in the queue, if any. processScriptQueue(queue); }); } }
JavaScript
function GetWikiName (wikiName, count) { var updatedName; // If the wikiName is usused than return it if (!$tw.settings.wikis[wikiName]) { return wikiName; } else { // Try the next name and recurse if (wikiName.endsWith(count)) { // If the name ends in a number increment it wikiName = wikiName.slice(0, -1*String(count).length); count = Number(count) + 1; updatedName = wikiName + String(count); } else { // If the name doesn't end in a number than add a 1 to start out. count = Number(count) + 1; updatedName = wikiName + String(count); } return GetWikiName(updatedName, count); } }
function GetWikiName (wikiName, count) { var updatedName; // If the wikiName is usused than return it if (!$tw.settings.wikis[wikiName]) { return wikiName; } else { // Try the next name and recurse if (wikiName.endsWith(count)) { // If the name ends in a number increment it wikiName = wikiName.slice(0, -1*String(count).length); count = Number(count) + 1; updatedName = wikiName + String(count); } else { // If the name doesn't end in a number than add a 1 to start out. count = Number(count) + 1; updatedName = wikiName + String(count); } return GetWikiName(updatedName, count); } }
JavaScript
function handleDisconnected() { console.log('Disconnected from server'); var text = "<div style='position:fixed;top:0px;width:100%;background-color:red;height:15vh;text-align:center;vertical-align:center;'><h1>''WARNING: You are no longer connected to the server. No changes you make will be saved.''</h1></div>"; var tiddler = {title: '$:/plugins/OokTech/Bob/Server Warning', text: text, tags: '$:/tags/PageTemplate'}; $tw.wiki.addTiddler(new $tw.Tiddler(tiddler)); $tw.settings.heartbeat.retry = setInterval(function () { var token = localStorage.getItem('ws-token') $tw.connections[0].socket.send(JSON.stringify({type: 'ping', heartbeat: true, token: token, wiki: $tw.wikiName})); }, $tw.settings.heartbeat.interval); }
function handleDisconnected() { console.log('Disconnected from server'); var text = "<div style='position:fixed;top:0px;width:100%;background-color:red;height:15vh;text-align:center;vertical-align:center;'><h1>''WARNING: You are no longer connected to the server. No changes you make will be saved.''</h1></div>"; var tiddler = {title: '$:/plugins/OokTech/Bob/Server Warning', text: text, tags: '$:/tags/PageTemplate'}; $tw.wiki.addTiddler(new $tw.Tiddler(tiddler)); $tw.settings.heartbeat.retry = setInterval(function () { var token = localStorage.getItem('ws-token') $tw.connections[0].socket.send(JSON.stringify({type: 'ping', heartbeat: true, token: token, wiki: $tw.wikiName})); }, $tw.settings.heartbeat.interval); }
JavaScript
function handleConnection(client) { console.log("new connection"); $tw.connections.push({'socket':client, 'active': true, 'wiki': undefined}); client.on('message', function incoming(event) { var self = this; // Determine which connection the message came from var thisIndex = $tw.connections.findIndex(function(connection) {return connection.socket === self;}); try { var eventData = JSON.parse(event); // Add the source to the eventData object so it can be used later. eventData.source_connection = thisIndex; // If the wiki on this connection hasn't been determined yet, take it // from the first message that lists the wiki. // After that the wiki can't be changed. It isn't a good security // measure but this part doesn't have real security anyway. // TODO figure out if this is actually a security problem. // We may have to add a check to the token before sending outgoing // messages. // This is really only a concern for the secure server, in that case // you authenticate the token and it only works if the wiki matches // and the token has access to that wiki. if (eventData.wiki && eventData.wiki !== $tw.connections[thisIndex].wiki && !$tw.connections[thisIndex].wiki) { $tw.connections[thisIndex].wiki = eventData.wiki; // Make sure that the new connection has the correct list of tiddlers being // edited. $tw.Bob.UpdateEditingTiddlers(); } // Make sure we have a handler for the message type if (typeof $tw.nodeMessageHandlers[eventData.type] === 'function') { $tw.nodeMessageHandlers[eventData.type](eventData); } else { console.log('No handler for message of type ', eventData.type); } } catch (e) { console.log("WebSocket error, probably closed connection: ", e); } }); // Respond to the initial connection with a request for the tiddlers the // browser currently has to initialise everything. $tw.connections[Object.keys($tw.connections).length-1].index = Object.keys($tw.connections).length-1; var message = {type: 'listTiddlers'} $tw.Bob.SendToBrowser($tw.connections[Object.keys($tw.connections).length-1], message); }
function handleConnection(client) { console.log("new connection"); $tw.connections.push({'socket':client, 'active': true, 'wiki': undefined}); client.on('message', function incoming(event) { var self = this; // Determine which connection the message came from var thisIndex = $tw.connections.findIndex(function(connection) {return connection.socket === self;}); try { var eventData = JSON.parse(event); // Add the source to the eventData object so it can be used later. eventData.source_connection = thisIndex; // If the wiki on this connection hasn't been determined yet, take it // from the first message that lists the wiki. // After that the wiki can't be changed. It isn't a good security // measure but this part doesn't have real security anyway. // TODO figure out if this is actually a security problem. // We may have to add a check to the token before sending outgoing // messages. // This is really only a concern for the secure server, in that case // you authenticate the token and it only works if the wiki matches // and the token has access to that wiki. if (eventData.wiki && eventData.wiki !== $tw.connections[thisIndex].wiki && !$tw.connections[thisIndex].wiki) { $tw.connections[thisIndex].wiki = eventData.wiki; // Make sure that the new connection has the correct list of tiddlers being // edited. $tw.Bob.UpdateEditingTiddlers(); } // Make sure we have a handler for the message type if (typeof $tw.nodeMessageHandlers[eventData.type] === 'function') { $tw.nodeMessageHandlers[eventData.type](eventData); } else { console.log('No handler for message of type ', eventData.type); } } catch (e) { console.log("WebSocket error, probably closed connection: ", e); } }); // Respond to the initial connection with a request for the tiddlers the // browser currently has to initialise everything. $tw.connections[Object.keys($tw.connections).length-1].index = Object.keys($tw.connections).length-1; var message = {type: 'listTiddlers'} $tw.Bob.SendToBrowser($tw.connections[Object.keys($tw.connections).length-1], message); }
JavaScript
function internalSave (tiddler, internalName, prefix) { // addTiddler needs the prefixed title!! var tempTiddlerFields = {}; Object.keys(tiddler.fields).forEach(function(fieldName) { tempTiddlerFields[fieldName] = tiddler.fields[fieldName]; }); tempTiddlerFields.title = internalName; $tw.wiki.addTiddler(new $tw.Tiddler(tempTiddlerFields)); var message = {type: 'saveTiddler', wiki: prefix, tiddler: {fields: tiddler.fields}}; $tw.Bob.SendToBrowsers(message); // This may help $tw.Bob.Wikis = $tw.Bob.Wikis || {}; $tw.Bob.Wikis[prefix] = $tw.Bob.Wikis[prefix] || {}; $tw.Bob.Wikis[prefix].tiddlers = $tw.Bob.Wikis[prefix].tiddlers || []; if ($tw.Bob.Wikis[prefix].tiddlers.indexOf(internalName) === -1) { $tw.Bob.Wikis[prefix].tiddlers.push(internalName); } }
function internalSave (tiddler, internalName, prefix) { // addTiddler needs the prefixed title!! var tempTiddlerFields = {}; Object.keys(tiddler.fields).forEach(function(fieldName) { tempTiddlerFields[fieldName] = tiddler.fields[fieldName]; }); tempTiddlerFields.title = internalName; $tw.wiki.addTiddler(new $tw.Tiddler(tempTiddlerFields)); var message = {type: 'saveTiddler', wiki: prefix, tiddler: {fields: tiddler.fields}}; $tw.Bob.SendToBrowsers(message); // This may help $tw.Bob.Wikis = $tw.Bob.Wikis || {}; $tw.Bob.Wikis[prefix] = $tw.Bob.Wikis[prefix] || {}; $tw.Bob.Wikis[prefix].tiddlers = $tw.Bob.Wikis[prefix].tiddlers || []; if ($tw.Bob.Wikis[prefix].tiddlers.indexOf(internalName) === -1) { $tw.Bob.Wikis[prefix].tiddlers.push(internalName); } }
JavaScript
function hasCurly(str) { // we need minimum four chars, example {.b} if (!str || !str.length || str.length < 4) { return false; } // should end in } if (str.charAt(str.length - 1) !== '}') { return false; } // should start with { if (str.indexOf('{') === -1) { return false; } return true; }
function hasCurly(str) { // we need minimum four chars, example {.b} if (!str || !str.length || str.length < 4) { return false; } // should end in } if (str.charAt(str.length - 1) !== '}') { return false; } // should start with { if (str.indexOf('{') === -1) { return false; } return true; }
JavaScript
function firstTokenNotHidden(tokens, i) { if (tokens[i] && tokens[i].hidden) { return firstTokenNotHidden(tokens, i - 1); } return tokens[i]; }
function firstTokenNotHidden(tokens, i) { if (tokens[i] && tokens[i].hidden) { return firstTokenNotHidden(tokens, i - 1); } return tokens[i]; }
JavaScript
function bulletListOpen(tokens, i) { if (tokens[i] && tokens[i].type !== 'bullet_list_open') { return bulletListOpen(tokens, i - 1); } return tokens[i]; }
function bulletListOpen(tokens, i) { if (tokens[i] && tokens[i].type !== 'bullet_list_open') { return bulletListOpen(tokens, i - 1); } return tokens[i]; }
JavaScript
clone() { let clone = new Reference(); for (let key in this) { clone[key] = this[key]; } return clone; }
clone() { let clone = new Reference(); for (let key in this) { clone[key] = this[key]; } return clone; }
JavaScript
hasContent() { switch (this.type) { case CONSTS.DATATYPE_ARRAY: case CONSTS.DATATYPE_OBJECT: return utils.isNonEmptyObject(this.content); default: return false; } }
hasContent() { switch (this.type) { case CONSTS.DATATYPE_ARRAY: case CONSTS.DATATYPE_OBJECT: return utils.isNonEmptyObject(this.content); default: return false; } }
JavaScript
isType(type, checkContent = false) { switch (type){ case CONSTS.DATATYPE_INTEGER: case CONSTS.DATATYPE_INTEGER2: return this.type === CONSTS.DATATYPE_INTEGER || this.type === CONSTS.DATATYPE_INTEGER2; case CONSTS.DATATYPE_BOOLEAN: case CONSTS.DATATYPE_BOOLEAN2: return this.type === CONSTS.DATATYPE_BOOLEAN || this.type === CONSTS.DATATYPE_BOOLEAN2; default: return this.type === type; } }
isType(type, checkContent = false) { switch (type){ case CONSTS.DATATYPE_INTEGER: case CONSTS.DATATYPE_INTEGER2: return this.type === CONSTS.DATATYPE_INTEGER || this.type === CONSTS.DATATYPE_INTEGER2; case CONSTS.DATATYPE_BOOLEAN: case CONSTS.DATATYPE_BOOLEAN2: return this.type === CONSTS.DATATYPE_BOOLEAN || this.type === CONSTS.DATATYPE_BOOLEAN2; default: return this.type === type; } }
JavaScript
applyBase(refs) { //fist check if the reference has a base if (!this.hasBase()){ throw new Error(`Attempting to apply base on reference "${this.name}", it has no base type declared.`); } //check that the ref list passed is not null if (!utils.isObject(refs)){ throw new Error("The passed list of references isn't an array."); } let base = refs[this.base]; if (utils.isNull(base)) { throw new Error(`The reference ${this.base} cannot be applied as a base for reference ${this.name} as it does not exists.`) } base.initialize(refs); this.name = utils.isString(this.name) ? this.name : base.name; this.type = utils.isString(this.type) ? this.type : base.type; this.description = utils.isNull(this.description) ? this.description : base.description; this.required = utils.isBoolean(this.required) ? this.required : base.required; this.base = null; this.ref = null; this.fileType = utils.isString(this.fileType) ? this.fileType : base.fileType; this.content = utils.isObject(this.content) ? this.content : {}; this.enumeration = utils.isArray(this.enumeration) ? this.enumeration : []; this.link = utils.isString(this.link) ? this.link : base.link; //merge trees if(this.isType(CONSTS.DATATYPE_OBJECT)) { if (base.hasContent()) { for (let key in base.content) { this.content[key] = base.content[key]; } } if (!this.hasContent()) { this.content = null; } } else { this.content = false; } //merge enumerations if (base.hasEnumeration()) { for (let key in base.enumeration) { this.enumeration[key] = base.enumeration[key]; } } //returns the merged object return this; }
applyBase(refs) { //fist check if the reference has a base if (!this.hasBase()){ throw new Error(`Attempting to apply base on reference "${this.name}", it has no base type declared.`); } //check that the ref list passed is not null if (!utils.isObject(refs)){ throw new Error("The passed list of references isn't an array."); } let base = refs[this.base]; if (utils.isNull(base)) { throw new Error(`The reference ${this.base} cannot be applied as a base for reference ${this.name} as it does not exists.`) } base.initialize(refs); this.name = utils.isString(this.name) ? this.name : base.name; this.type = utils.isString(this.type) ? this.type : base.type; this.description = utils.isNull(this.description) ? this.description : base.description; this.required = utils.isBoolean(this.required) ? this.required : base.required; this.base = null; this.ref = null; this.fileType = utils.isString(this.fileType) ? this.fileType : base.fileType; this.content = utils.isObject(this.content) ? this.content : {}; this.enumeration = utils.isArray(this.enumeration) ? this.enumeration : []; this.link = utils.isString(this.link) ? this.link : base.link; //merge trees if(this.isType(CONSTS.DATATYPE_OBJECT)) { if (base.hasContent()) { for (let key in base.content) { this.content[key] = base.content[key]; } } if (!this.hasContent()) { this.content = null; } } else { this.content = false; } //merge enumerations if (base.hasEnumeration()) { for (let key in base.enumeration) { this.enumeration[key] = base.enumeration[key]; } } //returns the merged object return this; }
JavaScript
format(){ let sugg = { description : this.description || 'unknown', descriptionMarkdown : this.description || 'unknown', type : 'attribute', leftLabel : this.type, descriptionMoreURL : this.link, displayText: this.name, isProp : false } switch (this.type) { case CONSTS.DATATYPE_OBJECT: sugg.snippet = this.name + "\" : \{ \n\t${1:null}\n\},"; break; case CONSTS.DATATYPE_ARRAY: sugg.snippet = this.name + "\" : \[ \n\t${1:null}\n\],"; break; case CONSTS.DATATYPE_STRING: sugg.snippet = this.name + "\" : \"$1\","; break; case CONSTS.DATATYPE_BOOLEAN: sugg.snippet = this.name + "\" : ${1:false},"; break; case CONSTS.DATATYPE_BOOLEAN2: sugg.snippet = this.name + "\" : ${1:true},"; break; case CONSTS.DATATYPE_INTEGER: sugg.snippet = this.name + "\" : ${1:1},"; break; case CONSTS.DATATYPE_INTEGER2: sugg.snippet = this.name + "\" : ${1:0},"; break; case CONSTS.DATATYPE_FLOAT: sugg.snippet = this.name + "\" : ${1:0.0},"; break; default: sugg.text = this.name; break; } return sugg; }
format(){ let sugg = { description : this.description || 'unknown', descriptionMarkdown : this.description || 'unknown', type : 'attribute', leftLabel : this.type, descriptionMoreURL : this.link, displayText: this.name, isProp : false } switch (this.type) { case CONSTS.DATATYPE_OBJECT: sugg.snippet = this.name + "\" : \{ \n\t${1:null}\n\},"; break; case CONSTS.DATATYPE_ARRAY: sugg.snippet = this.name + "\" : \[ \n\t${1:null}\n\],"; break; case CONSTS.DATATYPE_STRING: sugg.snippet = this.name + "\" : \"$1\","; break; case CONSTS.DATATYPE_BOOLEAN: sugg.snippet = this.name + "\" : ${1:false},"; break; case CONSTS.DATATYPE_BOOLEAN2: sugg.snippet = this.name + "\" : ${1:true},"; break; case CONSTS.DATATYPE_INTEGER: sugg.snippet = this.name + "\" : ${1:1},"; break; case CONSTS.DATATYPE_INTEGER2: sugg.snippet = this.name + "\" : ${1:0},"; break; case CONSTS.DATATYPE_FLOAT: sugg.snippet = this.name + "\" : ${1:0.0},"; break; default: sugg.text = this.name; break; } return sugg; }
JavaScript
isObject (obj) { //an array will also respond true to an object, so we gotta make shure //it's not an array. return (typeof obj) === 'object' && !this.isArray(obj); }
isObject (obj) { //an array will also respond true to an object, so we gotta make shure //it's not an array. return (typeof obj) === 'object' && !this.isArray(obj); }
JavaScript
isNonEmptyObject (obj) { //an array will also respond true to an object, so we gotta make shure //it's not an array. return this.isObject(obj) && Object.keys(obj).length > 0; }
isNonEmptyObject (obj) { //an array will also respond true to an object, so we gotta make shure //it's not an array. return this.isObject(obj) && Object.keys(obj).length > 0; }
JavaScript
isEmptyObject (obj) { //an array will also respond true to an object, so we gotta make shure //it's not an array. return this.isObject(obj) && Object.keys(obj).length === 0; }
isEmptyObject (obj) { //an array will also respond true to an object, so we gotta make shure //it's not an array. return this.isObject(obj) && Object.keys(obj).length === 0; }
JavaScript
format(){ return { text : this.value, description : this.description || 'unknown', descriptionMarkdown : this.description || 'unknown', type : 'value', leftLabel : 'string', descriptionMoreURL : this.link, isProp : true } }
format(){ return { text : this.value, description : this.description || 'unknown', descriptionMarkdown : this.description || 'unknown', type : 'value', leftLabel : 'string', descriptionMoreURL : this.link, isProp : true } }
JavaScript
addRef(node){ let ref = new Reference(node); this.refs[ref.name] = ref; return ref; }
addRef(node){ let ref = new Reference(node); this.refs[ref.name] = ref; return ref; }
JavaScript
function TestClosureClass(widget) { /** This is a member. * @type {object} * @default null */ this.member = null; /** This is another member. * @type {string} * @default "untitled" */ this.member2 = "untitled"; }
function TestClosureClass(widget) { /** This is a member. * @type {object} * @default null */ this.member = null; /** This is another member. * @type {string} * @default "untitled" */ this.member2 = "untitled"; }
JavaScript
function renderLevelCss( containerId, depth, levelOfs, lineOfs, labelOfs, measureUnit ) { var i, prefix = "#" + containerId + " span.fancytree-level-", rules = []; for (i = 0; i < depth; i++) { rules.push( prefix + (i + 1) + " span.fancytree-title { padding-left: " + (i * levelOfs + lineOfs) + measureUnit + "; }" ); } // Some UI animations wrap the UL inside a DIV and set position:relative on both. // This breaks the left:0 and padding-left:nn settings of the title rules.push( "#" + containerId + " div.ui-effects-wrapper ul li span.fancytree-title, " + "#" + containerId + " li.fancytree-animating span.fancytree-title " + // #716 "{ padding-left: " + labelOfs + measureUnit + "; position: static; width: auto; }" ); return rules.join("\n"); }
function renderLevelCss( containerId, depth, levelOfs, lineOfs, labelOfs, measureUnit ) { var i, prefix = "#" + containerId + " span.fancytree-level-", rules = []; for (i = 0; i < depth; i++) { rules.push( prefix + (i + 1) + " span.fancytree-title { padding-left: " + (i * levelOfs + lineOfs) + measureUnit + "; }" ); } // Some UI animations wrap the UL inside a DIV and set position:relative on both. // This breaks the left:0 and padding-left:nn settings of the title rules.push( "#" + containerId + " div.ui-effects-wrapper ul li span.fancytree-title, " + "#" + containerId + " li.fancytree-animating span.fancytree-title " + // #716 "{ padding-left: " + labelOfs + measureUnit + "; position: static; width: auto; }" ); return rules.join("\n"); }
JavaScript
function diff(a, b) { var result = a.slice(); for (var i = 0; i < result.length; i++) { for (var j = 0; j < b.length; j++) { if (result[i] === b[j]) { result.splice(i, 1); i--; break; } } } return result; }
function diff(a, b) { var result = a.slice(); for (var i = 0; i < result.length; i++) { for (var j = 0; j < b.length; j++) { if (result[i] === b[j]) { result.splice(i, 1); i--; break; } } } return result; }
JavaScript
function objectValues(obj) { var vals = is("array", obj) ? [] : {}; for (var key in obj) { if (hasOwn.call(obj, key)) { var val = obj[key]; vals[key] = val === Object(val) ? objectValues(val) : val; } } return vals; }
function objectValues(obj) { var vals = is("array", obj) ? [] : {}; for (var key in obj) { if (hasOwn.call(obj, key)) { var val = obj[key]; vals[key] = val === Object(val) ? objectValues(val) : val; } } return vals; }
JavaScript
function parse(obj, objType, stack) { stack = stack || []; var objIndex = stack.indexOf(obj); if (objIndex !== -1) { return "recursion(".concat(objIndex - stack.length, ")"); } objType = objType || this.typeOf(obj); var parser = this.parsers[objType]; var parserType = _typeof(parser); if (parserType === "function") { stack.push(obj); var res = parser.call(this, obj, stack); stack.pop(); return res; } return parserType === "string" ? parser : this.parsers.error; }
function parse(obj, objType, stack) { stack = stack || []; var objIndex = stack.indexOf(obj); if (objIndex !== -1) { return "recursion(".concat(objIndex - stack.length, ")"); } objType = objType || this.typeOf(obj); var parser = this.parsers[objType]; var parserType = _typeof(parser); if (parserType === "function") { stack.push(obj); var res = parser.call(this, obj, stack); stack.pop(); return res; } return parserType === "string" ? parser : this.parsers.error; }
JavaScript
function indent(extra) { if (!this.multiline) { return ""; } var chr = this.indentChar; if (this.HTML) { chr = chr.replace(/\t/g, " ").replace(/ /g, "&#160;"); } return new Array(this.depth + (extra || 0)).join(chr); }
function indent(extra) { if (!this.multiline) { return ""; } var chr = this.indentChar; if (this.HTML) { chr = chr.replace(/\t/g, " ").replace(/ /g, "&#160;"); } return new Array(this.depth + (extra || 0)).join(chr); }
JavaScript
function functionArgs(fn) { var l = fn.length; if (!l) { return ""; } var args = new Array(l); while (l--) { // 97 is 'a' args[l] = String.fromCharCode(97 + l); } return " " + args.join(", ") + " "; }
function functionArgs(fn) { var l = fn.length; if (!l) { return ""; } var args = new Array(l); while (l--) { // 97 is 'a' args[l] = String.fromCharCode(97 + l); } return " " + args.join(", ") + " "; }
JavaScript
function emit(eventName, data) { if (objectType(eventName) !== "string") { throw new TypeError("eventName must be a string when emitting an event"); } // Clone the callbacks in case one of them registers a new callback var originalCallbacks = LISTENERS[eventName]; var callbacks = originalCallbacks ? _toConsumableArray(originalCallbacks) : []; for (var i = 0; i < callbacks.length; i++) { callbacks[i](data); } }
function emit(eventName, data) { if (objectType(eventName) !== "string") { throw new TypeError("eventName must be a string when emitting an event"); } // Clone the callbacks in case one of them registers a new callback var originalCallbacks = LISTENERS[eventName]; var callbacks = originalCallbacks ? _toConsumableArray(originalCallbacks) : []; for (var i = 0; i < callbacks.length; i++) { callbacks[i](data); } }
JavaScript
function on(eventName, callback) { if (objectType(eventName) !== "string") { throw new TypeError("eventName must be a string when registering a listener"); } else if (!inArray(eventName, SUPPORTED_EVENTS)) { var events = SUPPORTED_EVENTS.join(", "); throw new Error("\"".concat(eventName, "\" is not a valid event; must be one of: ").concat(events, ".")); } else if (objectType(callback) !== "function") { throw new TypeError("callback must be a function when registering a listener"); } if (!LISTENERS[eventName]) { LISTENERS[eventName] = []; } // Don't register the same callback more than once if (!inArray(callback, LISTENERS[eventName])) { LISTENERS[eventName].push(callback); } }
function on(eventName, callback) { if (objectType(eventName) !== "string") { throw new TypeError("eventName must be a string when registering a listener"); } else if (!inArray(eventName, SUPPORTED_EVENTS)) { var events = SUPPORTED_EVENTS.join(", "); throw new Error("\"".concat(eventName, "\" is not a valid event; must be one of: ").concat(events, ".")); } else if (objectType(callback) !== "function") { throw new TypeError("callback must be a function when registering a listener"); } if (!LISTENERS[eventName]) { LISTENERS[eventName] = []; } // Don't register the same callback more than once if (!inArray(callback, LISTENERS[eventName])) { LISTENERS[eventName].push(callback); } }
JavaScript
function doResolve(fn, self) { var done = false; try { fn(function (value) { if (done) return; done = true; resolve(self, value); }, function (reason) { if (done) return; done = true; reject(self, reason); }); } catch (ex) { if (done) return; done = true; reject(self, ex); } }
function doResolve(fn, self) { var done = false; try { fn(function (value) { if (done) return; done = true; resolve(self, value); }, function (reason) { if (done) return; done = true; reject(self, reason); }); } catch (ex) { if (done) return; done = true; reject(self, ex); } }
JavaScript
function advance() { advanceTaskQueue(); if (!taskQueue.length && !config.blocking && !config.current) { advanceTestQueue(); } }
function advance() { advanceTaskQueue(); if (!taskQueue.length && !config.blocking && !config.current) { advanceTestQueue(); } }
JavaScript
function advanceTaskQueue() { var start = now(); config.depth = (config.depth || 0) + 1; processTaskQueue(start); config.depth--; }
function advanceTaskQueue() { var start = now(); config.depth = (config.depth || 0) + 1; processTaskQueue(start); config.depth--; }
JavaScript
function processTaskQueue(start) { if (taskQueue.length && !config.blocking) { var elapsedTime = now() - start; if (!setTimeout$1 || config.updateRate <= 0 || elapsedTime < config.updateRate) { var task = taskQueue.shift(); promisePolyfill.resolve(task()).then(function () { if (!taskQueue.length) { advance(); } else { processTaskQueue(start); } }); } else { setTimeout$1(advance); } } }
function processTaskQueue(start) { if (taskQueue.length && !config.blocking) { var elapsedTime = now() - start; if (!setTimeout$1 || config.updateRate <= 0 || elapsedTime < config.updateRate) { var task = taskQueue.shift(); promisePolyfill.resolve(task()).then(function () { if (!taskQueue.length) { advance(); } else { processTaskQueue(start); } }); } else { setTimeout$1(advance); } } }
JavaScript
function advanceTestQueue() { if (!config.blocking && !config.queue.length && config.depth === 0) { done(); return; } var testTasks = config.queue.shift(); addToTaskQueue(testTasks()); if (priorityCount > 0) { priorityCount--; } advance(); }
function advanceTestQueue() { if (!config.blocking && !config.queue.length && config.depth === 0) { done(); return; } var testTasks = config.queue.shift(); addToTaskQueue(testTasks()); if (priorityCount > 0) { priorityCount--; } advance(); }
JavaScript
function addToTestQueue(testTasksFunc, prioritize, seed) { if (prioritize) { config.queue.splice(priorityCount++, 0, testTasksFunc); } else if (seed) { if (!unitSampler) { unitSampler = unitSamplerGenerator(seed); } // Insert into a random position after all prioritized items var index = Math.floor(unitSampler() * (config.queue.length - priorityCount + 1)); config.queue.splice(priorityCount + index, 0, testTasksFunc); } else { config.queue.push(testTasksFunc); } }
function addToTestQueue(testTasksFunc, prioritize, seed) { if (prioritize) { config.queue.splice(priorityCount++, 0, testTasksFunc); } else if (seed) { if (!unitSampler) { unitSampler = unitSamplerGenerator(seed); } // Insert into a random position after all prioritized items var index = Math.floor(unitSampler() * (config.queue.length - priorityCount + 1)); config.queue.splice(priorityCount + index, 0, testTasksFunc); } else { config.queue.push(testTasksFunc); } }
JavaScript
function unitSamplerGenerator(seed) { // 32-bit xorshift, requires only a nonzero seed // https://excamera.com/sphinx/article-xorshift.html var sample = parseInt(generateHash(seed), 16) || -1; return function () { sample ^= sample << 13; sample ^= sample >>> 17; sample ^= sample << 5; // ECMAScript has no unsigned number type if (sample < 0) { sample += 0x100000000; } return sample / 0x100000000; }; }
function unitSamplerGenerator(seed) { // 32-bit xorshift, requires only a nonzero seed // https://excamera.com/sphinx/article-xorshift.html var sample = parseInt(generateHash(seed), 16) || -1; return function () { sample ^= sample << 13; sample ^= sample >>> 17; sample ^= sample << 5; // ECMAScript has no unsigned number type if (sample < 0) { sample += 0x100000000; } return sample / 0x100000000; }; }
JavaScript
function done() { var storage = config.storage; ProcessingQueue.finished = true; var runtime = now() - config.started; var passed = config.stats.all - config.stats.bad; if (config.stats.testCount === 0) { if (config.filter && config.filter.length) { throw new Error("No tests matched the filter \"".concat(config.filter, "\".")); } if (config.module && config.module.length) { throw new Error("No tests matched the module \"".concat(config.module, "\".")); } if (config.moduleId && config.moduleId.length) { throw new Error("No tests matched the moduleId \"".concat(config.moduleId, "\".")); } if (config.testId && config.testId.length) { throw new Error("No tests matched the testId \"".concat(config.testId, "\".")); } throw new Error("No tests were run."); } emit("runEnd", globalSuite.end(true)); runLoggingCallbacks("done", { passed: passed, failed: config.stats.bad, total: config.stats.all, runtime: runtime }).then(function () { // Clear own storage items if all tests passed if (storage && config.stats.bad === 0) { for (var i = storage.length - 1; i >= 0; i--) { var key = storage.key(i); if (key.indexOf("qunit-test-") === 0) { storage.removeItem(key); } } } }); }
function done() { var storage = config.storage; ProcessingQueue.finished = true; var runtime = now() - config.started; var passed = config.stats.all - config.stats.bad; if (config.stats.testCount === 0) { if (config.filter && config.filter.length) { throw new Error("No tests matched the filter \"".concat(config.filter, "\".")); } if (config.module && config.module.length) { throw new Error("No tests matched the module \"".concat(config.module, "\".")); } if (config.moduleId && config.moduleId.length) { throw new Error("No tests matched the moduleId \"".concat(config.moduleId, "\".")); } if (config.testId && config.testId.length) { throw new Error("No tests matched the testId \"".concat(config.testId, "\".")); } throw new Error("No tests were run."); } emit("runEnd", globalSuite.end(true)); runLoggingCallbacks("done", { passed: passed, failed: config.stats.bad, total: config.stats.all, runtime: runtime }).then(function () { // Clear own storage items if all tests passed if (storage && config.stats.bad === 0) { for (var i = storage.length - 1; i >= 0; i--) { var key = storage.key(i); if (key.indexOf("qunit-test-") === 0) { storage.removeItem(key); } } } }); }
JavaScript
function hooks(handler) { var hooks = []; function processHooks(test, module) { if (module.parentModule) { processHooks(test, module.parentModule); } if (module.hooks[handler].length) { for (var i = 0; i < module.hooks[handler].length; i++) { hooks.push(test.queueHook(module.hooks[handler][i], handler, module)); } } } // Hooks are ignored on skipped tests if (!this.skip) { processHooks(this, this.module); } return hooks; }
function hooks(handler) { var hooks = []; function processHooks(test, module) { if (module.parentModule) { processHooks(test, module.parentModule); } if (module.hooks[handler].length) { for (var i = 0; i < module.hooks[handler].length; i++) { hooks.push(test.queueHook(module.hooks[handler][i], handler, module)); } } } // Hooks are ignored on skipped tests if (!this.skip) { processHooks(this, this.module); } return hooks; }
JavaScript
function test(testName, callback) { if (focused$1 || config.currentModule.ignored) { return; } var newTest = new Test({ testName: testName, callback: callback }); newTest.queue(); }
function test(testName, callback) { if (focused$1 || config.currentModule.ignored) { return; } var newTest = new Test({ testName: testName, callback: callback }); newTest.queue(); }
JavaScript
function lastTestWithinModuleExecuted(module) { return module.testsRun === collectTests(module).filter(function (test) { return !test.skip; }).length - 1; }
function lastTestWithinModuleExecuted(module) { return module.testsRun === collectTests(module).filter(function (test) { return !test.skip; }).length - 1; }
JavaScript
function onError(error) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } if (config.current) { if (config.current.ignoreGlobalErrors) { return true; } pushFailure.apply(void 0, [error.message, error.stacktrace || error.fileName + ":" + error.lineNumber].concat(args)); } else { test("global failure", extend(function () { pushFailure.apply(void 0, [error.message, error.stacktrace || error.fileName + ":" + error.lineNumber].concat(args)); }, { validTest: true })); } return false; }
function onError(error) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } if (config.current) { if (config.current.ignoreGlobalErrors) { return true; } pushFailure.apply(void 0, [error.message, error.stacktrace || error.fileName + ":" + error.lineNumber].concat(args)); } else { test("global failure", extend(function () { pushFailure.apply(void 0, [error.message, error.stacktrace || error.fileName + ":" + error.lineNumber].concat(args)); }, { validTest: true })); } return false; }
JavaScript
function storeFixture() { // Avoid overwriting user-defined values if (hasOwn.call(config, "fixture")) { return; } var fixture = document.getElementById("qunit-fixture"); if (fixture) { config.fixture = fixture.cloneNode(true); } }
function storeFixture() { // Avoid overwriting user-defined values if (hasOwn.call(config, "fixture")) { return; } var fixture = document.getElementById("qunit-fixture"); if (fixture) { config.fixture = fixture.cloneNode(true); } }
JavaScript
function resetFixture() { if (config.fixture == null) { return; } var fixture = document.getElementById("qunit-fixture"); var resetFixtureType = _typeof(config.fixture); if (resetFixtureType === "string") { // support user defined values for `config.fixture` var newFixture = document.createElement("div"); newFixture.setAttribute("id", "qunit-fixture"); newFixture.innerHTML = config.fixture; fixture.parentNode.replaceChild(newFixture, fixture); } else { var clonedFixture = config.fixture.cloneNode(true); fixture.parentNode.replaceChild(clonedFixture, fixture); } }
function resetFixture() { if (config.fixture == null) { return; } var fixture = document.getElementById("qunit-fixture"); var resetFixtureType = _typeof(config.fixture); if (resetFixtureType === "string") { // support user defined values for `config.fixture` var newFixture = document.createElement("div"); newFixture.setAttribute("id", "qunit-fixture"); newFixture.innerHTML = config.fixture; fixture.parentNode.replaceChild(newFixture, fixture); } else { var clonedFixture = config.fixture.cloneNode(true); fixture.parentNode.replaceChild(clonedFixture, fixture); } }
JavaScript
function escapeText(s) { if (!s) { return ""; } s = s + ""; // Both single quotes and double quotes (for attributes) return s.replace(/['"<>&]/g, function (s) { switch (s) { case "'": return "&#039;"; case "\"": return "&quot;"; case "<": return "&lt;"; case ">": return "&gt;"; case "&": return "&amp;"; } }); }
function escapeText(s) { if (!s) { return ""; } s = s + ""; // Both single quotes and double quotes (for attributes) return s.replace(/['"<>&]/g, function (s) { switch (s) { case "'": return "&#039;"; case "\"": return "&quot;"; case "<": return "&lt;"; case ">": return "&gt;"; case "&": return "&amp;"; } }); }
JavaScript
function toolbarChanged() { var updatedUrl, value, tests, field = this, params = {}; // Detect if field is a select menu or a checkbox if ("selectedIndex" in field) { value = field.options[field.selectedIndex].value || undefined; } else { value = field.checked ? field.defaultValue || true : undefined; } params[field.name] = value; updatedUrl = setUrl(params); // Check if we can apply the change without a page refresh if ("hidepassed" === field.name && "replaceState" in window$1.history) { QUnit.urlParams[field.name] = value; config[field.name] = value || false; tests = id("qunit-tests"); if (tests) { var length = tests.children.length; var children = tests.children; if (field.checked) { for (var i = 0; i < length; i++) { var test = children[i]; var className = test ? test.className : ""; var classNameHasPass = className.indexOf("pass") > -1; var classNameHasSkipped = className.indexOf("skipped") > -1; if (classNameHasPass || classNameHasSkipped) { hiddenTests.push(test); } } var _iterator = _createForOfIteratorHelper(hiddenTests), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var hiddenTest = _step.value; tests.removeChild(hiddenTest); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } else { while ((test = hiddenTests.pop()) != null) { tests.appendChild(test); } } } window$1.history.replaceState(null, "", updatedUrl); } else { window$1.location = updatedUrl; } }
function toolbarChanged() { var updatedUrl, value, tests, field = this, params = {}; // Detect if field is a select menu or a checkbox if ("selectedIndex" in field) { value = field.options[field.selectedIndex].value || undefined; } else { value = field.checked ? field.defaultValue || true : undefined; } params[field.name] = value; updatedUrl = setUrl(params); // Check if we can apply the change without a page refresh if ("hidepassed" === field.name && "replaceState" in window$1.history) { QUnit.urlParams[field.name] = value; config[field.name] = value || false; tests = id("qunit-tests"); if (tests) { var length = tests.children.length; var children = tests.children; if (field.checked) { for (var i = 0; i < length; i++) { var test = children[i]; var className = test ? test.className : ""; var classNameHasPass = className.indexOf("pass") > -1; var classNameHasSkipped = className.indexOf("skipped") > -1; if (classNameHasPass || classNameHasSkipped) { hiddenTests.push(test); } } var _iterator = _createForOfIteratorHelper(hiddenTests), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var hiddenTest = _step.value; tests.removeChild(hiddenTest); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } else { while ((test = hiddenTests.pop()) != null) { tests.appendChild(test); } } } window$1.history.replaceState(null, "", updatedUrl); } else { window$1.location = updatedUrl; } }
JavaScript
function searchFocus() { if (dropDown.style.display !== "none") { return; } dropDown.style.display = "block"; addEvent(document, "click", hideHandler); addEvent(document, "keydown", hideHandler); // Hide on Escape keydown or outside-container click function hideHandler(e) { var inContainer = moduleFilter.contains(e.target); if (e.keyCode === 27 || !inContainer) { if (e.keyCode === 27 && inContainer) { moduleSearch.focus(); } dropDown.style.display = "none"; removeEvent(document, "click", hideHandler); removeEvent(document, "keydown", hideHandler); moduleSearch.value = ""; searchInput(); } } }
function searchFocus() { if (dropDown.style.display !== "none") { return; } dropDown.style.display = "block"; addEvent(document, "click", hideHandler); addEvent(document, "keydown", hideHandler); // Hide on Escape keydown or outside-container click function hideHandler(e) { var inContainer = moduleFilter.contains(e.target); if (e.keyCode === 27 || !inContainer) { if (e.keyCode === 27 && inContainer) { moduleSearch.focus(); } dropDown.style.display = "none"; removeEvent(document, "click", hideHandler); removeEvent(document, "keydown", hideHandler); moduleSearch.value = ""; searchInput(); } } }
JavaScript
function hideHandler(e) { var inContainer = moduleFilter.contains(e.target); if (e.keyCode === 27 || !inContainer) { if (e.keyCode === 27 && inContainer) { moduleSearch.focus(); } dropDown.style.display = "none"; removeEvent(document, "click", hideHandler); removeEvent(document, "keydown", hideHandler); moduleSearch.value = ""; searchInput(); } }
function hideHandler(e) { var inContainer = moduleFilter.contains(e.target); if (e.keyCode === 27 || !inContainer) { if (e.keyCode === 27 && inContainer) { moduleSearch.focus(); } dropDown.style.display = "none"; removeEvent(document, "click", hideHandler); removeEvent(document, "keydown", hideHandler); moduleSearch.value = ""; searchInput(); } }
JavaScript
function diffHalfMatchI(longtext, shorttext, i) { var seed, j, bestCommon, prefixLength, suffixLength, bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB; // Start with a 1/4 length substring at position i as a seed. seed = longtext.substring(i, i + Math.floor(longtext.length / 4)); j = -1; bestCommon = ""; while ((j = shorttext.indexOf(seed, j + 1)) !== -1) { prefixLength = dmp.diffCommonPrefix(longtext.substring(i), shorttext.substring(j)); suffixLength = dmp.diffCommonSuffix(longtext.substring(0, i), shorttext.substring(0, j)); if (bestCommon.length < suffixLength + prefixLength) { bestCommon = shorttext.substring(j - suffixLength, j) + shorttext.substring(j, j + prefixLength); bestLongtextA = longtext.substring(0, i - suffixLength); bestLongtextB = longtext.substring(i + prefixLength); bestShorttextA = shorttext.substring(0, j - suffixLength); bestShorttextB = shorttext.substring(j + prefixLength); } } if (bestCommon.length * 2 >= longtext.length) { return [bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB, bestCommon]; } else { return null; } } // First check if the second quarter is the seed for a half-match.
function diffHalfMatchI(longtext, shorttext, i) { var seed, j, bestCommon, prefixLength, suffixLength, bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB; // Start with a 1/4 length substring at position i as a seed. seed = longtext.substring(i, i + Math.floor(longtext.length / 4)); j = -1; bestCommon = ""; while ((j = shorttext.indexOf(seed, j + 1)) !== -1) { prefixLength = dmp.diffCommonPrefix(longtext.substring(i), shorttext.substring(j)); suffixLength = dmp.diffCommonSuffix(longtext.substring(0, i), shorttext.substring(0, j)); if (bestCommon.length < suffixLength + prefixLength) { bestCommon = shorttext.substring(j - suffixLength, j) + shorttext.substring(j, j + prefixLength); bestLongtextA = longtext.substring(0, i - suffixLength); bestLongtextB = longtext.substring(i + prefixLength); bestShorttextA = shorttext.substring(0, j - suffixLength); bestShorttextB = shorttext.substring(j + prefixLength); } } if (bestCommon.length * 2 >= longtext.length) { return [bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB, bestCommon]; } else { return null; } } // First check if the second quarter is the seed for a half-match.
JavaScript
function diffLinesToCharsMunge(text) { var chars, lineStart, lineEnd, lineArrayLength, line; chars = ""; // Walk the text, pulling out a substring for each line. // text.split('\n') would would temporarily double our memory footprint. // Modifying text would create many large strings to garbage collect. lineStart = 0; lineEnd = -1; // Keeping our own length variable is faster than looking it up. lineArrayLength = lineArray.length; while (lineEnd < text.length - 1) { lineEnd = text.indexOf("\n", lineStart); if (lineEnd === -1) { lineEnd = text.length - 1; } line = text.substring(lineStart, lineEnd + 1); lineStart = lineEnd + 1; if (hasOwn.call(lineHash, line)) { chars += String.fromCharCode(lineHash[line]); } else { chars += String.fromCharCode(lineArrayLength); lineHash[line] = lineArrayLength; lineArray[lineArrayLength++] = line; } } return chars; }
function diffLinesToCharsMunge(text) { var chars, lineStart, lineEnd, lineArrayLength, line; chars = ""; // Walk the text, pulling out a substring for each line. // text.split('\n') would would temporarily double our memory footprint. // Modifying text would create many large strings to garbage collect. lineStart = 0; lineEnd = -1; // Keeping our own length variable is faster than looking it up. lineArrayLength = lineArray.length; while (lineEnd < text.length - 1) { lineEnd = text.indexOf("\n", lineStart); if (lineEnd === -1) { lineEnd = text.length - 1; } line = text.substring(lineStart, lineEnd + 1); lineStart = lineEnd + 1; if (hasOwn.call(lineHash, line)) { chars += String.fromCharCode(lineHash[line]); } else { chars += String.fromCharCode(lineArrayLength); lineHash[line] = lineArrayLength; lineArray[lineArrayLength++] = line; } } return chars; }