language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
addMenuItemBtn({type, interactive, url, mode, custom, title, text, style}) { let c, i, input, btn, icon, disabled=null; let anchor,atr={ title: title } if(url) atr.href='#'; if(custom.style) { atr.style=''+custom.style; delete custom.style; } if(type == 'injectbtn') { anchor=this._make('a',type,atr); anchor.appendChild(document.createTextNode(text)); this._inject(anchor, interactive, url, title, mode, custom); } else if (type == 'textbtn') { anchor=this._make('a',type,atr); anchor.appendChild(document.createTextNode(text)); } else if((btn = /^(fa-[\w\-]+)/.exec(type)) !== null) { //Create a button using Font-awesome matching the class if(mode) atr.id=mode; anchor=this._make('a',null,atr); icon=btn[1]; btn=this._make('span',['fa-stack','fa-lg'],{ style:'font-size:12px' }); if(custom.content && custom.content.disabled) { disabled={ disabled: "disabled" }; } i=this._make('i',['fa',icon,'fa-stack-2x'],disabled); btn.appendChild(i); anchor.appendChild(btn); if(text) anchor.appendChild(document.createTextNode(' '+text)) /* *if(!Array.isArray) { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; }*/ if(custom.content) { if(Array.isArray(custom.content)) { custom.content.forEach(element => { if(typeof element == 'string') { anchor.appendChild(document.createTextNode(element)); } else if(element.input) { input=this._make('input',null,element.input); if(element.input.type == 'file') { if(element.input.hasOwnProperty('onChange')) { input.addEventListener('change',element.input.onChange[0],element.input.onChange[1]); } } if(element.input.type == 'button') { if(element.input.hasOwnProperty('onClick')) { input.addEventListener('click',element.input.onClick[0],element.input.onClick[1]); } } anchor.appendChild(input); } }) } else { if(custom.content.input) { input=this._make('input',null,custom.content.input); if(custom.content.input.type == 'file') { if(custom.content.input.hasOwnProperty('onChange')) { input.addEventListener('change',custom.content.input.onChange[0],custom.content.input.onChange[1]); } } anchor.appendChild(input); } } } }else { //logo if(style) atr.style=style; anchor=this._make('a',null,atr); i=this._make('img',null,{ src:mode, alt:custom, title:title, style:"padding-top:8px" }); (function(url,text){ anchor.addEventListener("click", function() { //alert(text); notifier.show({ message: text, type: 'confirm', okText: 'Go to github', cancelText: 'Extra', okHandler: function() { window.location.href=url; } , cancelHandler: function() { window.location.href='http://sosie.sos-productions.com/gift/index.html'; }, layout: 'middle', style: 'sosie-panel-with-btn' }) return false; }, false);})(url,text); const s=document.createElement('sup',null,{}); s.appendChild(document.createTextNode(custom.content.version.slice(5))); anchor.appendChild(i); anchor.appendChild(s); } return this.addMenuItemAnchor(anchor); }
addMenuItemBtn({type, interactive, url, mode, custom, title, text, style}) { let c, i, input, btn, icon, disabled=null; let anchor,atr={ title: title } if(url) atr.href='#'; if(custom.style) { atr.style=''+custom.style; delete custom.style; } if(type == 'injectbtn') { anchor=this._make('a',type,atr); anchor.appendChild(document.createTextNode(text)); this._inject(anchor, interactive, url, title, mode, custom); } else if (type == 'textbtn') { anchor=this._make('a',type,atr); anchor.appendChild(document.createTextNode(text)); } else if((btn = /^(fa-[\w\-]+)/.exec(type)) !== null) { //Create a button using Font-awesome matching the class if(mode) atr.id=mode; anchor=this._make('a',null,atr); icon=btn[1]; btn=this._make('span',['fa-stack','fa-lg'],{ style:'font-size:12px' }); if(custom.content && custom.content.disabled) { disabled={ disabled: "disabled" }; } i=this._make('i',['fa',icon,'fa-stack-2x'],disabled); btn.appendChild(i); anchor.appendChild(btn); if(text) anchor.appendChild(document.createTextNode(' '+text)) /* *if(!Array.isArray) { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; }*/ if(custom.content) { if(Array.isArray(custom.content)) { custom.content.forEach(element => { if(typeof element == 'string') { anchor.appendChild(document.createTextNode(element)); } else if(element.input) { input=this._make('input',null,element.input); if(element.input.type == 'file') { if(element.input.hasOwnProperty('onChange')) { input.addEventListener('change',element.input.onChange[0],element.input.onChange[1]); } } if(element.input.type == 'button') { if(element.input.hasOwnProperty('onClick')) { input.addEventListener('click',element.input.onClick[0],element.input.onClick[1]); } } anchor.appendChild(input); } }) } else { if(custom.content.input) { input=this._make('input',null,custom.content.input); if(custom.content.input.type == 'file') { if(custom.content.input.hasOwnProperty('onChange')) { input.addEventListener('change',custom.content.input.onChange[0],custom.content.input.onChange[1]); } } anchor.appendChild(input); } } } }else { //logo if(style) atr.style=style; anchor=this._make('a',null,atr); i=this._make('img',null,{ src:mode, alt:custom, title:title, style:"padding-top:8px" }); (function(url,text){ anchor.addEventListener("click", function() { //alert(text); notifier.show({ message: text, type: 'confirm', okText: 'Go to github', cancelText: 'Extra', okHandler: function() { window.location.href=url; } , cancelHandler: function() { window.location.href='http://sosie.sos-productions.com/gift/index.html'; }, layout: 'middle', style: 'sosie-panel-with-btn' }) return false; }, false);})(url,text); const s=document.createElement('sup',null,{}); s.appendChild(document.createTextNode(custom.content.version.slice(5))); anchor.appendChild(i); anchor.appendChild(s); } return this.addMenuItemAnchor(anchor); }
JavaScript
addMenuItemAnchor(anchor) { const item=this._make('li',null,{}); item.appendChild(anchor); this.menu.appendChild(item); return item; }
addMenuItemAnchor(anchor) { const item=this._make('li',null,{}); item.appendChild(anchor); this.menu.appendChild(item); return item; }
JavaScript
loadAllPluginsSamples() { let _this=this; window.SoSIE__plugins.forEach(function(plugin){ _this.loadSample(plugin); }); }
loadAllPluginsSamples() { let _this=this; window.SoSIE__plugins.forEach(function(plugin){ _this.loadSample(plugin); }); }
JavaScript
addMenuIconBtn({icon, id, title, text, onClick, custom}) { custom=Object.assign({ //disabled:false, //Init state of the button style: (custom ? custom.style || '' : ''), //Anchor style content: null //Definitions of element appended after span },{content:custom}); const btn=super.addMenuItemBtn({ type:(icon ? 'fa-'+icon : 'textbtn'), interactive: false, url:false, mode:id, custom: custom, title: title, text:text }).addEventListener('click', onClick[0], onClick[1]); //Register button by its id to make its dom accessible with editor.sosie.get(id) this.set(id); return btn; }
addMenuIconBtn({icon, id, title, text, onClick, custom}) { custom=Object.assign({ //disabled:false, //Init state of the button style: (custom ? custom.style || '' : ''), //Anchor style content: null //Definitions of element appended after span },{content:custom}); const btn=super.addMenuItemBtn({ type:(icon ? 'fa-'+icon : 'textbtn'), interactive: false, url:false, mode:id, custom: custom, title: title, text:text }).addEventListener('click', onClick[0], onClick[1]); //Register button by its id to make its dom accessible with editor.sosie.get(id) this.set(id); return btn; }
JavaScript
init(editor) { //We have to wrap it to avoid 'unhandled rejection!' for Async/Await async function waitForReady() { await editor.isReady; return editor; } //as suggested https://thecodebarbarian.com/unhandled-promise-rejections-in-node.js.html //editor is a Promise now, because an async function returns a promise waitForReady().catch((reason)=>{ console.error(`SoSIE editor initialization failed ${reason}`,reason); }); waitForReady().then(editor => { //Now it is time to init SoSie's plugins, which are init helper for tools window.SoSIE__plugins.forEach(function(plugin){ if(window.hasOwnProperty(plugin)&&(typeof window[plugin]['init'] != 'undefined')) { console.info('executeFunctionByName('+plugin+').init'); window[plugin]["init"](editor); } }); function getURLParameter(sParam){ var sPageURL = window.location.search.substring(1); var sURLVariables = sPageURL.split('&'); for(var i = 0; i < sURLVariables.length; i++){ var sParameterName = sURLVariables[i].split('='); if (sParameterName[0] == sParam){ return sParameterName[1]; } } return ''; } var toolbarPos=getURLParameter('toolbar') || 'top'; //Now, shows SoSIE menubar using the div holder id, on top or bottom of the page editor.sosie.showMenuBar('sosie',toolbarPos); refreshBlocksStatusPanel('after showMenuBar'); }) return editor; }
init(editor) { //We have to wrap it to avoid 'unhandled rejection!' for Async/Await async function waitForReady() { await editor.isReady; return editor; } //as suggested https://thecodebarbarian.com/unhandled-promise-rejections-in-node.js.html //editor is a Promise now, because an async function returns a promise waitForReady().catch((reason)=>{ console.error(`SoSIE editor initialization failed ${reason}`,reason); }); waitForReady().then(editor => { //Now it is time to init SoSie's plugins, which are init helper for tools window.SoSIE__plugins.forEach(function(plugin){ if(window.hasOwnProperty(plugin)&&(typeof window[plugin]['init'] != 'undefined')) { console.info('executeFunctionByName('+plugin+').init'); window[plugin]["init"](editor); } }); function getURLParameter(sParam){ var sPageURL = window.location.search.substring(1); var sURLVariables = sPageURL.split('&'); for(var i = 0; i < sURLVariables.length; i++){ var sParameterName = sURLVariables[i].split('='); if (sParameterName[0] == sParam){ return sParameterName[1]; } } return ''; } var toolbarPos=getURLParameter('toolbar') || 'top'; //Now, shows SoSIE menubar using the div holder id, on top or bottom of the page editor.sosie.showMenuBar('sosie',toolbarPos); refreshBlocksStatusPanel('after showMenuBar'); }) return editor; }
JavaScript
function startQuiz(){ displayQ1(quizContent); var quizTime = setInterval(function(){ changeToSec--; timer.textContent = changeToSec; if (changeToSec === 0) { clearInterval(quizTime); } }, 1000) beginHere.style.visibility = 'hidden'; beginQuestions.style.visibility = 'initial'; viewHighscores.style.visibility = 'hidden'; }
function startQuiz(){ displayQ1(quizContent); var quizTime = setInterval(function(){ changeToSec--; timer.textContent = changeToSec; if (changeToSec === 0) { clearInterval(quizTime); } }, 1000) beginHere.style.visibility = 'hidden'; beginQuestions.style.visibility = 'initial'; viewHighscores.style.visibility = 'hidden'; }
JavaScript
function displayQ1(quizContent){ askQuestion.textContent = quizContent[0].question; for (var i = 0; i < quizContent[0].answers.length - 1; i++) { answerBtn1.textContent = quizContent[0].answers[0]; answerBtn2.textContent = quizContent[0].answers[1]; answerBtn3.textContent = quizContent[0].answers[2]; answerBtn4.textContent = quizContent[0].answers[3]; } // if user clicks the right answer, moves to next question--no penalties; otherwise it moves to next question and deducts 5 second "points" document.querySelector('.list').addEventListener('click', function(event, incorrectPenalty){ if (event.target.matches(".answer-choice2")) { correctAnswer(); displayQ2(quizContent); } else { incorrectAnswer(incorrectPenalty); displayQ2(quizContent); } }) }
function displayQ1(quizContent){ askQuestion.textContent = quizContent[0].question; for (var i = 0; i < quizContent[0].answers.length - 1; i++) { answerBtn1.textContent = quizContent[0].answers[0]; answerBtn2.textContent = quizContent[0].answers[1]; answerBtn3.textContent = quizContent[0].answers[2]; answerBtn4.textContent = quizContent[0].answers[3]; } // if user clicks the right answer, moves to next question--no penalties; otherwise it moves to next question and deducts 5 second "points" document.querySelector('.list').addEventListener('click', function(event, incorrectPenalty){ if (event.target.matches(".answer-choice2")) { correctAnswer(); displayQ2(quizContent); } else { incorrectAnswer(incorrectPenalty); displayQ2(quizContent); } }) }
JavaScript
function displayQ2(quizContent){ askQuestion.textContent = quizContent[1].question; for (var i = 0; i < quizContent[0].answers.length - 1; i++) { answerBtn1.textContent = quizContent[1].answers[0]; answerBtn2.textContent = quizContent[1].answers[1]; answerBtn3.textContent = quizContent[1].answers[2]; answerBtn4.textContent = quizContent[1].answers[3]; } // if user clicks the right answer, moves to next question--no penalties; otherwise it moves to next question and deducts 5 second "points" document.querySelector('.list').addEventListener('click', function(event, incorrectPenalty){ if (event.target.matches(".answer-choice1")) { correctAnswer(); displayQ4(quizContent); } else { incorrectAnswer(incorrectPenalty); displayQ3(quizContent); } }) }
function displayQ2(quizContent){ askQuestion.textContent = quizContent[1].question; for (var i = 0; i < quizContent[0].answers.length - 1; i++) { answerBtn1.textContent = quizContent[1].answers[0]; answerBtn2.textContent = quizContent[1].answers[1]; answerBtn3.textContent = quizContent[1].answers[2]; answerBtn4.textContent = quizContent[1].answers[3]; } // if user clicks the right answer, moves to next question--no penalties; otherwise it moves to next question and deducts 5 second "points" document.querySelector('.list').addEventListener('click', function(event, incorrectPenalty){ if (event.target.matches(".answer-choice1")) { correctAnswer(); displayQ4(quizContent); } else { incorrectAnswer(incorrectPenalty); displayQ3(quizContent); } }) }
JavaScript
function displayQ3(quizContent){ askQuestion.textContent = quizContent[2].question; for (var i = 0; i < quizContent[2].answers.length - 1; i++) { answerBtn1.textContent = quizContent[2].answers[0]; answerBtn2.textContent = quizContent[2].answers[1]; answerBtn3.textContent = quizContent[2].answers[2]; answerBtn4.textContent = quizContent[2].answers[3]; } // if user clicks the right answer, moves to next question--no penalties; otherwise it moves to next question and deducts 5 second "points" document.querySelector('.list').addEventListener('click', function(event, incorrectPenalty){ if (event.target.matches(".answer-choice3")) { correctAnswer(); displayQ4(quizContent); } else { incorrectAnswer(incorrectPenalty); displayQ4(quizContent); } }) popUp.style.visibility = 'hidden'; }
function displayQ3(quizContent){ askQuestion.textContent = quizContent[2].question; for (var i = 0; i < quizContent[2].answers.length - 1; i++) { answerBtn1.textContent = quizContent[2].answers[0]; answerBtn2.textContent = quizContent[2].answers[1]; answerBtn3.textContent = quizContent[2].answers[2]; answerBtn4.textContent = quizContent[2].answers[3]; } // if user clicks the right answer, moves to next question--no penalties; otherwise it moves to next question and deducts 5 second "points" document.querySelector('.list').addEventListener('click', function(event, incorrectPenalty){ if (event.target.matches(".answer-choice3")) { correctAnswer(); displayQ4(quizContent); } else { incorrectAnswer(incorrectPenalty); displayQ4(quizContent); } }) popUp.style.visibility = 'hidden'; }
JavaScript
function displayQ4(quizContent){ askQuestion.textContent = quizContent[3].question; for (var i = 0; i < quizContent[3].answers.length - 1; i++) { answerBtn1.textContent = quizContent[3].answers[0]; answerBtn2.textContent = quizContent[3].answers[1]; answerBtn3.textContent = quizContent[3].answers[2]; answerBtn4.textContent = quizContent[3].answers[3]; } // if user clicks the right answer, moves to next question--no penalties; otherwise it moves to next question and deducts 5 second "points" document.querySelector('.list').addEventListener('click', function(event, incorrectPenalty){ if (event.target.matches(".answer-choice2")) { correctAnswer(); displayQ5(quizContent); } else { incorrectAnswer(incorrectPenalty); displayQ5(quizContent); } }) }
function displayQ4(quizContent){ askQuestion.textContent = quizContent[3].question; for (var i = 0; i < quizContent[3].answers.length - 1; i++) { answerBtn1.textContent = quizContent[3].answers[0]; answerBtn2.textContent = quizContent[3].answers[1]; answerBtn3.textContent = quizContent[3].answers[2]; answerBtn4.textContent = quizContent[3].answers[3]; } // if user clicks the right answer, moves to next question--no penalties; otherwise it moves to next question and deducts 5 second "points" document.querySelector('.list').addEventListener('click', function(event, incorrectPenalty){ if (event.target.matches(".answer-choice2")) { correctAnswer(); displayQ5(quizContent); } else { incorrectAnswer(incorrectPenalty); displayQ5(quizContent); } }) }
JavaScript
function displayQ5(quizContent, changeToSec){ askQuestion.textContent = quizContent[4].question; for (var i = 0; i < quizContent[4].answers.length - 1; i++) { answerBtn1.textContent = quizContent[4].answers[0]; answerBtn2.textContent = quizContent[4].answers[1]; answerBtn3.textContent = quizContent[4].answers[2]; answerBtn4.textContent = quizContent[4].answers[3]; } // if user clicks the right answer, moves to next question--no penalties; otherwise it moves to next question and deducts 5 second "points" document.querySelector('.list').addEventListener('click', function(event, incorrectPenalty, quizTime){ if (event.target.matches(".answer-choice3")){ correctAnswer(); storeHighscore(event); timer.style.display = 'hidden'; localStorage.setItem('stopClock', changeToSec); } else { incorrectAnswer(incorrectPenalty); storeHighscore(event); timer.style.display = 'hidden'; localStorage.setItem('stopClock', changeToSec); if (changeToSec === 0) { clearInterval(quizTime); } } }) if (parseInt(timer.innerHTML) === 0) { clearInterval(quizTime); changeToSec = 0; } }
function displayQ5(quizContent, changeToSec){ askQuestion.textContent = quizContent[4].question; for (var i = 0; i < quizContent[4].answers.length - 1; i++) { answerBtn1.textContent = quizContent[4].answers[0]; answerBtn2.textContent = quizContent[4].answers[1]; answerBtn3.textContent = quizContent[4].answers[2]; answerBtn4.textContent = quizContent[4].answers[3]; } // if user clicks the right answer, moves to next question--no penalties; otherwise it moves to next question and deducts 5 second "points" document.querySelector('.list').addEventListener('click', function(event, incorrectPenalty, quizTime){ if (event.target.matches(".answer-choice3")){ correctAnswer(); storeHighscore(event); timer.style.display = 'hidden'; localStorage.setItem('stopClock', changeToSec); } else { incorrectAnswer(incorrectPenalty); storeHighscore(event); timer.style.display = 'hidden'; localStorage.setItem('stopClock', changeToSec); if (changeToSec === 0) { clearInterval(quizTime); } } }) if (parseInt(timer.innerHTML) === 0) { clearInterval(quizTime); changeToSec = 0; } }
JavaScript
function goBack() { beginHere.style.visibility = 'visible'; highscoreSect.style.visibility = 'hidden'; viewHighscores.style.visibility = 'visible'; }
function goBack() { beginHere.style.visibility = 'visible'; highscoreSect.style.visibility = 'hidden'; viewHighscores.style.visibility = 'visible'; }
JavaScript
function jsonParser(jsonString) { try { return JSON.parse(jsonString); } catch (e) { return safeEval(`${jsonString}`); } }
function jsonParser(jsonString) { try { return JSON.parse(jsonString); } catch (e) { return safeEval(`${jsonString}`); } }
JavaScript
function create(req, res) { //add userId req.body.userId = req.user._id; // change checkboxes' 'on' to Boolean req.body.waterSources = !!req.body.waterSources; req.body.riverCrossings = !!req.body.riverCrossings; req.body.scrambling = !!req.body.scrambling; req.body.carCamping = !!req.body.carCamping; // array features are checkboxes, push to features array req.body.features = []; if(req.body.waterFeature) req.body.features.push(req.body.waterFeature); if(req.body.epicView) req.body.features.push(req.body.epicView); // adjust req.body to match imbeded region schema req.body.region = { primary: req.body.primary, secondary: req.body.secondary, subRegion: req.body.subRegion } // create a new database entry with the request body const hike = new Hike(req.body); //add detailsLink hike.detailsLink = '/adventures/hiking/'; //add userId hike.userId = req.user._id; hike.save(function(err){ //errors if(err) return res.redirect('/adventures'); res.redirect('/adventures'); }) }
function create(req, res) { //add userId req.body.userId = req.user._id; // change checkboxes' 'on' to Boolean req.body.waterSources = !!req.body.waterSources; req.body.riverCrossings = !!req.body.riverCrossings; req.body.scrambling = !!req.body.scrambling; req.body.carCamping = !!req.body.carCamping; // array features are checkboxes, push to features array req.body.features = []; if(req.body.waterFeature) req.body.features.push(req.body.waterFeature); if(req.body.epicView) req.body.features.push(req.body.epicView); // adjust req.body to match imbeded region schema req.body.region = { primary: req.body.primary, secondary: req.body.secondary, subRegion: req.body.subRegion } // create a new database entry with the request body const hike = new Hike(req.body); //add detailsLink hike.detailsLink = '/adventures/hiking/'; //add userId hike.userId = req.user._id; hike.save(function(err){ //errors if(err) return res.redirect('/adventures'); res.redirect('/adventures'); }) }
JavaScript
function calcUsedLength(stylesheet, ruleUsage) { const cssRules = ruleUsage.filter(function(y) { return y.styleSheetId === stylesheet.styleSheetId; }); return cssRules.reduce(function(sum, x) { return sum + x.endOffset - x.startOffset; }, 0); }
function calcUsedLength(stylesheet, ruleUsage) { const cssRules = ruleUsage.filter(function(y) { return y.styleSheetId === stylesheet.styleSheetId; }); return cssRules.reduce(function(sum, x) { return sum + x.endOffset - x.startOffset; }, 0); }
JavaScript
function calcUnusedCss(stylesheets, ruleUsage) { let used = 0; let total = 0; for (let css of stylesheets) { used += calcUsedLength(css, ruleUsage); total += css.length; } return 100 - Math.round(used/total * 100); }
function calcUnusedCss(stylesheets, ruleUsage) { let used = 0; let total = 0; for (let css of stylesheets) { used += calcUsedLength(css, ruleUsage); total += css.length; } return 100 - Math.round(used/total * 100); }
JavaScript
async function multipleRequest(urls) { let responsesAndErrors = []; try { let promises = urls.map(function(url) { let options = { uri: url, resolveWithFullResponse: true }; return rp(options).catch(function(err) { return err; }); }); const resList = await Promise.all(promises); resList.forEach(function(res) { // error case if (typeof res.name === 'string') responsesAndErrors.push(-1); else responsesAndErrors.push(res.statusCode); }); } catch(e) { console.error(e); } return responsesAndErrors; }
async function multipleRequest(urls) { let responsesAndErrors = []; try { let promises = urls.map(function(url) { let options = { uri: url, resolveWithFullResponse: true }; return rp(options).catch(function(err) { return err; }); }); const resList = await Promise.all(promises); resList.forEach(function(res) { // error case if (typeof res.name === 'string') responsesAndErrors.push(-1); else responsesAndErrors.push(res.statusCode); }); } catch(e) { console.error(e); } return responsesAndErrors; }
JavaScript
function bagOfWords(words) { let json = {}; for (let w of words) { if (typeof json[w] !== 'undefined') { json[w] = json[w] + 1; } else { json[w] = 1; } } return json; }
function bagOfWords(words) { let json = {}; for (let w of words) { if (typeof json[w] !== 'undefined') { json[w] = json[w] + 1; } else { json[w] = 1; } } return json; }
JavaScript
function checkComboTitleH1Body(title, h1List, $) { if (title == '') return 0; if (h1List.length == 0) return 0; let bodyText = text.bodyToText($); bodyText = utilities.supertrim(bodyText); bodyText = utilities.replaceMap(bodyText, { '\n': '', '\t': '', '\r': '' }); let h1words = []; for (let h1 of h1List) { h1words = h1words.concat(h1.split(' ')); } let bagOfWordsTitle = text.bagOfWords(title.split(' ')); let bagOfWordsH1 = text.bagOfWords(h1words); let bagOfWordsBody = text.bagOfWords(bodyText.split(' ')); let points = 0; let bagOfWordsTitleLength = 0; for (let word in bagOfWordsTitle) { if (typeof bagOfWordsH1[word] !== 'undefined' && typeof bagOfWordsBody[word] !== 'undefined') points++; bagOfWordsTitleLength++; } return points/bagOfWordsTitleLength; }
function checkComboTitleH1Body(title, h1List, $) { if (title == '') return 0; if (h1List.length == 0) return 0; let bodyText = text.bodyToText($); bodyText = utilities.supertrim(bodyText); bodyText = utilities.replaceMap(bodyText, { '\n': '', '\t': '', '\r': '' }); let h1words = []; for (let h1 of h1List) { h1words = h1words.concat(h1.split(' ')); } let bagOfWordsTitle = text.bagOfWords(title.split(' ')); let bagOfWordsH1 = text.bagOfWords(h1words); let bagOfWordsBody = text.bagOfWords(bodyText.split(' ')); let points = 0; let bagOfWordsTitleLength = 0; for (let word in bagOfWordsTitle) { if (typeof bagOfWordsH1[word] !== 'undefined' && typeof bagOfWordsBody[word] !== 'undefined') points++; bagOfWordsTitleLength++; } return points/bagOfWordsTitleLength; }
JavaScript
async function handleRequest(request) { const { url } = request; const url_obj = new URL(url); const src = url_obj.searchParams.get('src') || 'https://raw.githubusercontent.com/ontouchstart/ontouchstart-rustwasm-markdown-parser/master/README.md'; const input = await (await fetch(src)).text() || `# Hello World`; const { parse } = wasm_bindgen; await wasm_bindgen(wasm); const output = ` <html> <meta charSet="utf-8"/> <a href="https://ontouchstart-rustwasm-markdown-parser.ontouchstart.workers.dev">🏡</a> <h1>HTML</h1> ${parse(input)} <h1>Markdown</h1> <pre><code>${input}</code></pre> </html> ` const headers = new Headers({ 'Content-Type': 'text/html', 'Access-Control-Allow-Origin': '*' }); const res = new Response(output, { status: 200, headers }); return res; }
async function handleRequest(request) { const { url } = request; const url_obj = new URL(url); const src = url_obj.searchParams.get('src') || 'https://raw.githubusercontent.com/ontouchstart/ontouchstart-rustwasm-markdown-parser/master/README.md'; const input = await (await fetch(src)).text() || `# Hello World`; const { parse } = wasm_bindgen; await wasm_bindgen(wasm); const output = ` <html> <meta charSet="utf-8"/> <a href="https://ontouchstart-rustwasm-markdown-parser.ontouchstart.workers.dev">🏡</a> <h1>HTML</h1> ${parse(input)} <h1>Markdown</h1> <pre><code>${input}</code></pre> </html> ` const headers = new Headers({ 'Content-Type': 'text/html', 'Access-Control-Allow-Origin': '*' }); const res = new Response(output, { status: 200, headers }); return res; }
JavaScript
function initialize() { dateField = d3.select("#datetime"); cityField = d3.select("#cityList"); stateField = d3.select("#stateList"); countryField = d3.select("#countryList"); shapeField = d3.select("#shapeList"); searchButton = d3.select("#filter-btn"); clearButton = d3.select("#clear-btn"); searchForm = d3.select("#search-form"); // Filter Button handler searchButton.on("click", function () { searchData(); }); // Clear Search handler clearButton.on("click", function () { dateField.property("value", ""); cityField.property("value" , ""); stateField.property("value" , ""); countryField.property("value" , ""); shapeField.property("value", ""); }); // Stop enter key from reloading the form. searchForm.on("submit", function () { //d3.event.stopPropagation(); d3.event.preventDefault(); cityField.nodefocus(); }); // Populate the pulldowns initializePulldowns(); // Display the table with data searchData(); }
function initialize() { dateField = d3.select("#datetime"); cityField = d3.select("#cityList"); stateField = d3.select("#stateList"); countryField = d3.select("#countryList"); shapeField = d3.select("#shapeList"); searchButton = d3.select("#filter-btn"); clearButton = d3.select("#clear-btn"); searchForm = d3.select("#search-form"); // Filter Button handler searchButton.on("click", function () { searchData(); }); // Clear Search handler clearButton.on("click", function () { dateField.property("value", ""); cityField.property("value" , ""); stateField.property("value" , ""); countryField.property("value" , ""); shapeField.property("value", ""); }); // Stop enter key from reloading the form. searchForm.on("submit", function () { //d3.event.stopPropagation(); d3.event.preventDefault(); cityField.nodefocus(); }); // Populate the pulldowns initializePulldowns(); // Display the table with data searchData(); }
JavaScript
function searchData() { // Get the value property of the input elements let dateVal = dateField.property("value"); let cityVal = cityField.property("value"); let stateVal = stateField.property("value").toLowerCase(); let countryVal = countryField.property("value").toLowerCase(); let shapeVal = shapeField.property("value").toLowerCase(); let searchResults = ufoData; if (dateVal != "") { searchResults = searchResults.filter(ufo => ufo.datetime.toLowerCase() == dateVal); } if (stateVal != "") { searchResults = searchResults.filter(ufo => ufo.state.toLowerCase() == stateVal); }; if (shapeVal != "") { searchResults = searchResults.filter(ufo => ufo.shape.toLowerCase() == shapeVal); }; if (cityVal != "") { searchResults = searchResults.filter(ufo => ufo.city.toLowerCase() == cityVal); }; if (countryVal != "") { searchResults = searchResults.filter(ufo => ufo.country.toLowerCase() == countryVal); }; // Display the data or the no results message. if (searchResults.length != 0){ buildTable(searchResults); } else{ buildNoResults(); } }
function searchData() { // Get the value property of the input elements let dateVal = dateField.property("value"); let cityVal = cityField.property("value"); let stateVal = stateField.property("value").toLowerCase(); let countryVal = countryField.property("value").toLowerCase(); let shapeVal = shapeField.property("value").toLowerCase(); let searchResults = ufoData; if (dateVal != "") { searchResults = searchResults.filter(ufo => ufo.datetime.toLowerCase() == dateVal); } if (stateVal != "") { searchResults = searchResults.filter(ufo => ufo.state.toLowerCase() == stateVal); }; if (shapeVal != "") { searchResults = searchResults.filter(ufo => ufo.shape.toLowerCase() == shapeVal); }; if (cityVal != "") { searchResults = searchResults.filter(ufo => ufo.city.toLowerCase() == cityVal); }; if (countryVal != "") { searchResults = searchResults.filter(ufo => ufo.country.toLowerCase() == countryVal); }; // Display the data or the no results message. if (searchResults.length != 0){ buildTable(searchResults); } else{ buildNoResults(); } }
JavaScript
function buildNoResults() { let ullist = d3.select("tbody"); ullist.selectAll("tr").remove(); let row = ullist.append("tr"); let cell = row.append("td"); cell.text("The search returned no results. Try different search parameters."); }
function buildNoResults() { let ullist = d3.select("tbody"); ullist.selectAll("tr").remove(); let row = ullist.append("tr"); let cell = row.append("td"); cell.text("The search returned no results. Try different search parameters."); }
JavaScript
function initializePulldowns() { let uniqueCities = getCities(); let option = cityField.append("option"); option.property("text", ""); option.property("value", ""); for (each of uniqueCities) { option = cityField.append("option"); option.property("text", each.toUpperCase()); option.property("value", each); } let uniqueStates = getStates(); option = stateField.append("option"); option.property("text", ""); option.property("value", ""); for (each of uniqueStates) { option = stateField.append("option"); option.property("text", each.toUpperCase()); option.property("value", each); } let uniqueCountries = getCountries(); option = countryField.append("option"); option.property("text", ""); option.property("value", ""); for (each of uniqueCountries) { option = countryField.append("option"); option.property("text", each.toUpperCase()); option.property("value", each); } let uniqueShapes = getShapes(); option = shapeField.append("option"); option.property("text", ""); option.property("value", ""); for (each of uniqueShapes) { option = shapeField.append("option"); option.property("text", each.toUpperCase()); option.property("value", each); } }
function initializePulldowns() { let uniqueCities = getCities(); let option = cityField.append("option"); option.property("text", ""); option.property("value", ""); for (each of uniqueCities) { option = cityField.append("option"); option.property("text", each.toUpperCase()); option.property("value", each); } let uniqueStates = getStates(); option = stateField.append("option"); option.property("text", ""); option.property("value", ""); for (each of uniqueStates) { option = stateField.append("option"); option.property("text", each.toUpperCase()); option.property("value", each); } let uniqueCountries = getCountries(); option = countryField.append("option"); option.property("text", ""); option.property("value", ""); for (each of uniqueCountries) { option = countryField.append("option"); option.property("text", each.toUpperCase()); option.property("value", each); } let uniqueShapes = getShapes(); option = shapeField.append("option"); option.property("text", ""); option.property("value", ""); for (each of uniqueShapes) { option = shapeField.append("option"); option.property("text", each.toUpperCase()); option.property("value", each); } }
JavaScript
static toCamelCase(str, split = '-_') { var re = new RegExp('[' + Str.escapeRegExp(split) + '](.?)'); return str.replace(re, function (match, group) { return group.toUpperCase(); }); }
static toCamelCase(str, split = '-_') { var re = new RegExp('[' + Str.escapeRegExp(split) + '](.?)'); return str.replace(re, function (match, group) { return group.toUpperCase(); }); }
JavaScript
testing() { this.forEach((frame, index) => { if (!frame) FFLogger.log(`empty frame: ${index}`); }); }
testing() { this.forEach((frame, index) => { if (!frame) FFLogger.log(`empty frame: ${index}`); }); }
JavaScript
addInput() { const {conf} = this; const dir = conf.getVal('detailedCacheDir'); const files = FS.getCacheFilePath(dir); this.command.addInput(files); }
addInput() { const {conf} = this; const dir = conf.getVal('detailedCacheDir'); const files = FS.getCacheFilePath(dir); this.command.addInput(files); }
JavaScript
start() { const {audios} = this; this.addInput(); this.addInputOptions(); this.addAudio(audios); this.addOutputOptions(); this.addCommandEvents(); this.addOutput(); this.command.run(); }
start() { const {audios} = this; this.addInput(); this.addInputOptions(); this.addAudio(audios); this.addOutputOptions(); this.addCommandEvents(); this.addOutput(); this.command.run(); }
JavaScript
addCommandEvents() { const {conf, command} = this; const totalFrames = conf.getVal('totalFrames'); // start command.on('start', commandLine => { this.eventHelper.emit({type: 'start', command: commandLine}); FFLogger.info({pos: 'Synthesis', msg: `synthesis start: ${commandLine}`}); }); // progress command.on('progress', progress => { const percent = Utils.floor(100 * (progress.frames / totalFrames), 2); this.eventHelper.emitProgress({type: 'progress', percent}); FFLogger.info({pos: 'Synthesis', msg: `synthesis progress: ${percent}% done`}); }); // complete command.on('end', () => { const output = conf.getVal('output'); this.eventHelper.emit({type: 'complete', output}); FFLogger.info({pos: 'Synthesis', msg: 'synthesis complete'}); }); // error command.on('error', (error, stdout, stderr) => { this.eventHelper.emitError({type: 'error', error, pos: 'Synthesis'}); FFLogger.error({ error, pos: 'Synthesis', msg: `stdout:${stdout} \n stderr:${stderr}`, }); }); }
addCommandEvents() { const {conf, command} = this; const totalFrames = conf.getVal('totalFrames'); // start command.on('start', commandLine => { this.eventHelper.emit({type: 'start', command: commandLine}); FFLogger.info({pos: 'Synthesis', msg: `synthesis start: ${commandLine}`}); }); // progress command.on('progress', progress => { const percent = Utils.floor(100 * (progress.frames / totalFrames), 2); this.eventHelper.emitProgress({type: 'progress', percent}); FFLogger.info({pos: 'Synthesis', msg: `synthesis progress: ${percent}% done`}); }); // complete command.on('end', () => { const output = conf.getVal('output'); this.eventHelper.emit({type: 'complete', output}); FFLogger.info({pos: 'Synthesis', msg: 'synthesis complete'}); }); // error command.on('error', (error, stdout, stderr) => { this.eventHelper.emitError({type: 'error', error, pos: 'Synthesis'}); FFLogger.error({ error, pos: 'Synthesis', msg: `stdout:${stdout} \n stderr:${stderr}`, }); }); }
JavaScript
function nm_handleNdefMessage(ndefmessage) { var options = null; var record = ndefmessage[0]; this._debug('RECORD: ' + JSON.stringify(record)); switch (+record.tnf) { case NDEF.TNF_EMPTY: options = this.createActivityOptionsWithType('empty'); break; case NDEF.TNF_WELL_KNOWN: options = this.formatWellKnownRecord(record); break; case NDEF.TNF_MIME_MEDIA: options = this.formatMimeMedia(record); break; case NDEF.TNF_ABSOLUTE_URI: case NDEF.TNF_EXTERNAL_TYPE: // Absolute URI and External payload handling is application specific, // in terms of creating activity they should be handled alike var type = NfcUtils.toUTF8(record.type); options = this.createActivityOptionsWithType(type); break; case NDEF.TNF_UNKNOWN: case NDEF.TNF_RESERVED: options = this.createDefaultActivityOptions(); break; case NDEF.TNF_UNCHANGED: break; } if (options === null) { this._debug('XX Found no ndefmessage actions. XX'); // we're handling here also tnf unchanged, not adding record payload // as ndef record is malformed/unxpected, this is a workaround // until Bug 1007724 will land options = this.createDefaultActivityOptions(); } else { options.data.records = ndefmessage; } return options; }
function nm_handleNdefMessage(ndefmessage) { var options = null; var record = ndefmessage[0]; this._debug('RECORD: ' + JSON.stringify(record)); switch (+record.tnf) { case NDEF.TNF_EMPTY: options = this.createActivityOptionsWithType('empty'); break; case NDEF.TNF_WELL_KNOWN: options = this.formatWellKnownRecord(record); break; case NDEF.TNF_MIME_MEDIA: options = this.formatMimeMedia(record); break; case NDEF.TNF_ABSOLUTE_URI: case NDEF.TNF_EXTERNAL_TYPE: // Absolute URI and External payload handling is application specific, // in terms of creating activity they should be handled alike var type = NfcUtils.toUTF8(record.type); options = this.createActivityOptionsWithType(type); break; case NDEF.TNF_UNKNOWN: case NDEF.TNF_RESERVED: options = this.createDefaultActivityOptions(); break; case NDEF.TNF_UNCHANGED: break; } if (options === null) { this._debug('XX Found no ndefmessage actions. XX'); // we're handling here also tnf unchanged, not adding record payload // as ndef record is malformed/unxpected, this is a workaround // until Bug 1007724 will land options = this.createDefaultActivityOptions(); } else { options.data.records = ndefmessage; } return options; }
JavaScript
function mapInputType(type) { switch (type) { // basic types case 'url': case 'tel': case 'email': case 'text': return type; break; // default fallback and textual types case 'password': case 'search': default: return 'text'; break; case 'number': case 'range': // XXX: should be different from number return 'number'; break; } }
function mapInputType(type) { switch (type) { // basic types case 'url': case 'tel': case 'email': case 'text': return type; break; // default fallback and textual types case 'password': case 'search': default: return 'text'; break; case 'number': case 'range': // XXX: should be different from number return 'number'; break; } }
JavaScript
function hasAlternatives(layout, value) { if (!layout.alt) return false; return (value in layout.alt); }
function hasAlternatives(layout, value) { if (!layout.alt) return false; return (value in layout.alt); }
JavaScript
function sendDelete(isRepeat) { // Pass the isRepeat argument to the input method. It may not want // to compute suggestions, for example, if this is just one in a series // of repeating events. inputMethod.click(KeyboardEvent.DOM_VK_BACK_SPACE, isRepeat); }
function sendDelete(isRepeat) { // Pass the isRepeat argument to the input method. It may not want // to compute suggestions, for example, if this is just one in a series // of repeating events. inputMethod.click(KeyboardEvent.DOM_VK_BACK_SPACE, isRepeat); }
JavaScript
function showAlternatives(key) { // Get the key object from layout var alternatives, altMap, value, keyObj, uppercaseValue, needsCapitalization; var r = key ? key.dataset.row : -1, c = key ? key.dataset.column : -1; if (r < 0 || c < 0 || r === undefined || c === undefined) return; keyObj = currentLayout.keys[r][c]; // Handle languages alternatives if (keyObj.keyCode === SWITCH_KEYBOARD) { showIMEList(); return; } // Hide the keyboard if (keyObj.keyCode === KeyEvent.DOM_VK_SPACE) { dismissKeyboard(); return; } // Handle key alternatives altMap = currentLayout.alt || {}; value = keyObj.value; alternatives = altMap[value] || ''; // If in uppercase, look for uppercase alternatives. If we don't find any // then set a flag so we can manually capitalize the alternatives below. if (isUpperCase || isUpperCaseLocked) { uppercaseValue = getUpperCaseValue(keyObj); if (altMap[uppercaseValue]) { alternatives = altMap[uppercaseValue]; } else { needsCapitalization = true; } } // Split alternatives // If the alternatives are delimited by spaces, it means that one or more // of them is more than a single character long. if (alternatives.indexOf(' ') != -1) { alternatives = alternatives.split(' '); // If there is just a single multi-character alternative, it will have // trailing whitespace which we have to discard here. if (alternatives.length === 2 && alternatives[1] === '') alternatives.pop(); if (needsCapitalization) { for (var i = 0; i < alternatives.length; i++) { if (isUpperCaseLocked) { // Caps lock is on, so capitalize all the characters alternatives[i] = alternatives[i].toLocaleUpperCase(); } else { // We're in uppercase, but not locked, so just capitalize 1st char. alternatives[i] = alternatives[i][0].toLocaleUpperCase() + alternatives[i].substring(1); } } } } else { // No spaces, so all of the alternatives are single characters if (needsCapitalization) // Capitalize them all at once before splitting alternatives = alternatives.toLocaleUpperCase(); alternatives = alternatives.split(''); } if (!alternatives.length) return; // Locked limits // TODO: look for [LOCKED_AREA] var top = getWindowTop(key); var bottom = getWindowTop(key) + key.scrollHeight; var keybounds = key.getBoundingClientRect(); IMERender.showAlternativesCharMenu(key, alternatives); isShowingAlternativesMenu = true; // Locked limits // TODO: look for [LOCKED_AREA] menuLockedArea = { top: top, bottom: bottom, left: getWindowLeft(IMERender.menu), right: getWindowLeft(IMERender.menu) + IMERender.menu.scrollWidth }; menuLockedArea.width = menuLockedArea.right - menuLockedArea.left; // Add some more properties to this locked area object that will help us // redirect touch events to the appropriate alternative key. menuLockedArea.keybounds = keybounds; menuLockedArea.firstAlternative = IMERender.menu.classList.contains('kbr-menu-left') ? IMERender.menu.lastElementChild : IMERender.menu.firstElementChild; menuLockedArea.boxes = []; var children = IMERender.menu.children; for (var i = 0; i < children.length; i++) { menuLockedArea.boxes[i] = children[i].getBoundingClientRect(); } }
function showAlternatives(key) { // Get the key object from layout var alternatives, altMap, value, keyObj, uppercaseValue, needsCapitalization; var r = key ? key.dataset.row : -1, c = key ? key.dataset.column : -1; if (r < 0 || c < 0 || r === undefined || c === undefined) return; keyObj = currentLayout.keys[r][c]; // Handle languages alternatives if (keyObj.keyCode === SWITCH_KEYBOARD) { showIMEList(); return; } // Hide the keyboard if (keyObj.keyCode === KeyEvent.DOM_VK_SPACE) { dismissKeyboard(); return; } // Handle key alternatives altMap = currentLayout.alt || {}; value = keyObj.value; alternatives = altMap[value] || ''; // If in uppercase, look for uppercase alternatives. If we don't find any // then set a flag so we can manually capitalize the alternatives below. if (isUpperCase || isUpperCaseLocked) { uppercaseValue = getUpperCaseValue(keyObj); if (altMap[uppercaseValue]) { alternatives = altMap[uppercaseValue]; } else { needsCapitalization = true; } } // Split alternatives // If the alternatives are delimited by spaces, it means that one or more // of them is more than a single character long. if (alternatives.indexOf(' ') != -1) { alternatives = alternatives.split(' '); // If there is just a single multi-character alternative, it will have // trailing whitespace which we have to discard here. if (alternatives.length === 2 && alternatives[1] === '') alternatives.pop(); if (needsCapitalization) { for (var i = 0; i < alternatives.length; i++) { if (isUpperCaseLocked) { // Caps lock is on, so capitalize all the characters alternatives[i] = alternatives[i].toLocaleUpperCase(); } else { // We're in uppercase, but not locked, so just capitalize 1st char. alternatives[i] = alternatives[i][0].toLocaleUpperCase() + alternatives[i].substring(1); } } } } else { // No spaces, so all of the alternatives are single characters if (needsCapitalization) // Capitalize them all at once before splitting alternatives = alternatives.toLocaleUpperCase(); alternatives = alternatives.split(''); } if (!alternatives.length) return; // Locked limits // TODO: look for [LOCKED_AREA] var top = getWindowTop(key); var bottom = getWindowTop(key) + key.scrollHeight; var keybounds = key.getBoundingClientRect(); IMERender.showAlternativesCharMenu(key, alternatives); isShowingAlternativesMenu = true; // Locked limits // TODO: look for [LOCKED_AREA] menuLockedArea = { top: top, bottom: bottom, left: getWindowLeft(IMERender.menu), right: getWindowLeft(IMERender.menu) + IMERender.menu.scrollWidth }; menuLockedArea.width = menuLockedArea.right - menuLockedArea.left; // Add some more properties to this locked area object that will help us // redirect touch events to the appropriate alternative key. menuLockedArea.keybounds = keybounds; menuLockedArea.firstAlternative = IMERender.menu.classList.contains('kbr-menu-left') ? IMERender.menu.lastElementChild : IMERender.menu.firstElementChild; menuLockedArea.boxes = []; var children = IMERender.menu.children; for (var i = 0; i < children.length; i++) { menuLockedArea.boxes[i] = children[i].getBoundingClientRect(); } }
JavaScript
function handleTouches(evt, callback) { for (var i = 0; i < evt.changedTouches.length; i++) { var touch = evt.changedTouches[i]; var touchId = touch.identifier; callback(touch, touchId); } }
function handleTouches(evt, callback) { for (var i = 0; i < evt.changedTouches.length; i++) { var touch = evt.changedTouches[i]; var touchId = touch.identifier; callback(touch, touchId); } }
JavaScript
function onMouseDown(evt) { // Prevent loosing focus to the currently focused app // Otherwise, right after mousedown event, the app will receive a focus event. evt.preventDefault(); // Bail if we're using touch events. if (touchEventsPresent) return; IMERender.ime.setCapture(false); currentKey = evt.target; startPress(currentKey, evt, null); }
function onMouseDown(evt) { // Prevent loosing focus to the currently focused app // Otherwise, right after mousedown event, the app will receive a focus event. evt.preventDefault(); // Bail if we're using touch events. if (touchEventsPresent) return; IMERender.ime.setCapture(false); currentKey = evt.target; startPress(currentKey, evt, null); }
JavaScript
function startPress(target, coords, touchId) { if (!isNormalKey(target)) return; var keyCode = getKeyCodeFromTarget(target); // Feedback var isSpecialKey = specialCodes.indexOf(keyCode) >= 0 || keyCode < 0; triggerFeedback(isSpecialKey); IMERender.highlightKey(target, { isUpperCase: isUpperCase, isUpperCaseLocked: isUpperCaseLocked }); setMenuTimeout(target, coords, touchId); // Special keys (such as delete) response when pressing (not releasing) // Furthermore, delete key has a repetition behavior if (keyCode === KeyEvent.DOM_VK_BACK_SPACE) { // First repetition, after a delay (with feedback) deleteTimeout = window.setTimeout(function() { sendDelete(true); // Second, after shorter delay (with feedback too) deleteInterval = setInterval(function() { sendDelete(true); }, REPEAT_RATE); }, REPEAT_TIMEOUT); } }
function startPress(target, coords, touchId) { if (!isNormalKey(target)) return; var keyCode = getKeyCodeFromTarget(target); // Feedback var isSpecialKey = specialCodes.indexOf(keyCode) >= 0 || keyCode < 0; triggerFeedback(isSpecialKey); IMERender.highlightKey(target, { isUpperCase: isUpperCase, isUpperCaseLocked: isUpperCaseLocked }); setMenuTimeout(target, coords, touchId); // Special keys (such as delete) response when pressing (not releasing) // Furthermore, delete key has a repetition behavior if (keyCode === KeyEvent.DOM_VK_BACK_SPACE) { // First repetition, after a delay (with feedback) deleteTimeout = window.setTimeout(function() { sendDelete(true); // Second, after shorter delay (with feedback too) deleteInterval = setInterval(function() { sendDelete(true); }, REPEAT_RATE); }, REPEAT_TIMEOUT); } }
JavaScript
function endPress(target, coords, touchId, hasCandidateScrolled) { clearTimeout(deleteTimeout); clearInterval(deleteInterval); clearTimeout(menuTimeout); var wasShowingKeyboardLayoutMenu = isShowingKeyboardLayoutMenu; hideAlternatives(); if (target.classList.contains('dismiss-suggestions-button')) { if (inputMethod.dismissSuggestions) inputMethod.dismissSuggestions(); return; } if (!target || !isNormalKey(target)) return; // IME candidate selected var dataset = target.dataset; if (dataset.selection) { if (!hasCandidateScrolled) { IMERender.toggleCandidatePanel(false, true); if (inputMethod.select) { // We use dataset.data instead of target.textContent because the // text actually displayed to the user might have an ellipsis in it // to make it fit. inputMethod.select(target.textContent, dataset.data); } } IMERender.unHighlightKey(target); return; } IMERender.unHighlightKey(target); // The alternate keys of telLayout and numberLayout do not // trigger keypress on key release. if (target.dataset.ignoreEndPress) { delete target.dataset.ignoreEndPress; return; } var keyCode = getKeyCodeFromTarget(target); // Delete is a special key, it reacts when pressed not released if (keyCode == KeyEvent.DOM_VK_BACK_SPACE) { // The backspace key pressing is regarded as non-repetitive behavior. sendDelete(false); return; } // Reset the flag when a non-space key is pressed, // used in space key double tap handling if (keyCode != KeyEvent.DOM_VK_SPACE) isContinousSpacePressed = false; var keyStyle = getComputedStyle(target); if (keyStyle.display == 'none' || keyStyle.visibility == 'hidden') return; // Handle normal key switch (keyCode) { case BASIC_LAYOUT: // Return to default page setLayoutPage(LAYOUT_PAGE_DEFAULT); break; case ALTERNATE_LAYOUT: // Switch to numbers+symbols page setLayoutPage(LAYOUT_PAGE_SYMBOLS_I); break; case KeyEvent.DOM_VK_ALT: // alternate between pages 1 and 2 of SYMBOLS if (layoutPage === LAYOUT_PAGE_SYMBOLS_I) { setLayoutPage(LAYOUT_PAGE_SYMBOLS_II); } else { setLayoutPage(LAYOUT_PAGE_SYMBOLS_I); } break; // Switch language (keyboard) case SWITCH_KEYBOARD: // If the user selected a new keyboard layout or quickly tapped the // switch layouts button then switch to a new keyboard layout if (target.dataset.keyboard || !wasShowingKeyboardLayoutMenu) switchToNextIME(); break; // Expand / shrink the candidate panel case TOGGLE_CANDIDATE_PANEL: var candidatePanel = IMERender.candidatePanel; if (IMERender.ime.classList.contains('candidate-panel')) { var doToggleCandidatePanel = function doToggleCandidatePanel() { if (candidatePanel.dataset.truncated) { if (candidatePanelScrollTimer) { clearTimeout(candidatePanelScrollTimer); candidatePanelScrollTimer = null; } candidatePanel.addEventListener('scroll', candidatePanelOnScroll); } IMERender.toggleCandidatePanel(true, true); }; if (candidatePanel.dataset.rowCount == 1) { var firstPageRows = 11; var numberOfCandidatesPerRow = IMERender.getNumberOfCandidatesPerRow(); var candidateIndicator = parseInt(candidatePanel.dataset.candidateIndicator); if (inputMethod.getMoreCandidates) { inputMethod.getMoreCandidates( candidateIndicator, firstPageRows * numberOfCandidatesPerRow + 1, function getMoreCandidatesCallbackOnToggle(list) { if (candidatePanel.dataset.rowCount == 1) { IMERender.showMoreCandidates(firstPageRows, list); doToggleCandidatePanel(); } } ); } else { var list = currentCandidates.slice(candidateIndicator, candidateIndicator + firstPageRows * numberOfCandidatesPerRow + 1); IMERender.showMoreCandidates(firstPageRows, list); doToggleCandidatePanel(); } } else { doToggleCandidatePanel(); } } else { if (inputMethod.getMoreCandidates) { candidatePanel.removeEventListener('scroll', candidatePanelOnScroll); if (candidatePanelScrollTimer) { clearTimeout(candidatePanelScrollTimer); candidatePanelScrollTimer = null; } } IMERender.toggleCandidatePanel(false, true); } break; // Shift or caps lock case KeyEvent.DOM_VK_CAPS_LOCK: // Already waiting for caps lock if (isWaitingForSecondTap) { isWaitingForSecondTap = false; setUpperCase(true, true); // Normal behavior: set timeout for second tap and toggle caps } else { isWaitingForSecondTap = true; window.setTimeout( function() { isWaitingForSecondTap = false; }, CAPS_LOCK_TIMEOUT ); // Toggle caps setUpperCase(!isUpperCase, false); } break; // Normal key default: if (target.dataset.compositekey) { // Keys with this attribute set send more than a single character // Like ".com" or "2nd" or (in Catalan) "l·l". var compositeKey = target.dataset.compositekey; for (var i = 0; i < compositeKey.length; i++) { inputMethod.click(compositeKey.charCodeAt(i)); } } else { inputMethod.click(keyCode); } break; } }
function endPress(target, coords, touchId, hasCandidateScrolled) { clearTimeout(deleteTimeout); clearInterval(deleteInterval); clearTimeout(menuTimeout); var wasShowingKeyboardLayoutMenu = isShowingKeyboardLayoutMenu; hideAlternatives(); if (target.classList.contains('dismiss-suggestions-button')) { if (inputMethod.dismissSuggestions) inputMethod.dismissSuggestions(); return; } if (!target || !isNormalKey(target)) return; // IME candidate selected var dataset = target.dataset; if (dataset.selection) { if (!hasCandidateScrolled) { IMERender.toggleCandidatePanel(false, true); if (inputMethod.select) { // We use dataset.data instead of target.textContent because the // text actually displayed to the user might have an ellipsis in it // to make it fit. inputMethod.select(target.textContent, dataset.data); } } IMERender.unHighlightKey(target); return; } IMERender.unHighlightKey(target); // The alternate keys of telLayout and numberLayout do not // trigger keypress on key release. if (target.dataset.ignoreEndPress) { delete target.dataset.ignoreEndPress; return; } var keyCode = getKeyCodeFromTarget(target); // Delete is a special key, it reacts when pressed not released if (keyCode == KeyEvent.DOM_VK_BACK_SPACE) { // The backspace key pressing is regarded as non-repetitive behavior. sendDelete(false); return; } // Reset the flag when a non-space key is pressed, // used in space key double tap handling if (keyCode != KeyEvent.DOM_VK_SPACE) isContinousSpacePressed = false; var keyStyle = getComputedStyle(target); if (keyStyle.display == 'none' || keyStyle.visibility == 'hidden') return; // Handle normal key switch (keyCode) { case BASIC_LAYOUT: // Return to default page setLayoutPage(LAYOUT_PAGE_DEFAULT); break; case ALTERNATE_LAYOUT: // Switch to numbers+symbols page setLayoutPage(LAYOUT_PAGE_SYMBOLS_I); break; case KeyEvent.DOM_VK_ALT: // alternate between pages 1 and 2 of SYMBOLS if (layoutPage === LAYOUT_PAGE_SYMBOLS_I) { setLayoutPage(LAYOUT_PAGE_SYMBOLS_II); } else { setLayoutPage(LAYOUT_PAGE_SYMBOLS_I); } break; // Switch language (keyboard) case SWITCH_KEYBOARD: // If the user selected a new keyboard layout or quickly tapped the // switch layouts button then switch to a new keyboard layout if (target.dataset.keyboard || !wasShowingKeyboardLayoutMenu) switchToNextIME(); break; // Expand / shrink the candidate panel case TOGGLE_CANDIDATE_PANEL: var candidatePanel = IMERender.candidatePanel; if (IMERender.ime.classList.contains('candidate-panel')) { var doToggleCandidatePanel = function doToggleCandidatePanel() { if (candidatePanel.dataset.truncated) { if (candidatePanelScrollTimer) { clearTimeout(candidatePanelScrollTimer); candidatePanelScrollTimer = null; } candidatePanel.addEventListener('scroll', candidatePanelOnScroll); } IMERender.toggleCandidatePanel(true, true); }; if (candidatePanel.dataset.rowCount == 1) { var firstPageRows = 11; var numberOfCandidatesPerRow = IMERender.getNumberOfCandidatesPerRow(); var candidateIndicator = parseInt(candidatePanel.dataset.candidateIndicator); if (inputMethod.getMoreCandidates) { inputMethod.getMoreCandidates( candidateIndicator, firstPageRows * numberOfCandidatesPerRow + 1, function getMoreCandidatesCallbackOnToggle(list) { if (candidatePanel.dataset.rowCount == 1) { IMERender.showMoreCandidates(firstPageRows, list); doToggleCandidatePanel(); } } ); } else { var list = currentCandidates.slice(candidateIndicator, candidateIndicator + firstPageRows * numberOfCandidatesPerRow + 1); IMERender.showMoreCandidates(firstPageRows, list); doToggleCandidatePanel(); } } else { doToggleCandidatePanel(); } } else { if (inputMethod.getMoreCandidates) { candidatePanel.removeEventListener('scroll', candidatePanelOnScroll); if (candidatePanelScrollTimer) { clearTimeout(candidatePanelScrollTimer); candidatePanelScrollTimer = null; } } IMERender.toggleCandidatePanel(false, true); } break; // Shift or caps lock case KeyEvent.DOM_VK_CAPS_LOCK: // Already waiting for caps lock if (isWaitingForSecondTap) { isWaitingForSecondTap = false; setUpperCase(true, true); // Normal behavior: set timeout for second tap and toggle caps } else { isWaitingForSecondTap = true; window.setTimeout( function() { isWaitingForSecondTap = false; }, CAPS_LOCK_TIMEOUT ); // Toggle caps setUpperCase(!isUpperCase, false); } break; // Normal key default: if (target.dataset.compositekey) { // Keys with this attribute set send more than a single character // Like ".com" or "2nd" or (in Catalan) "l·l". var compositeKey = target.dataset.compositekey; for (var i = 0; i < compositeKey.length; i++) { inputMethod.click(compositeKey.charCodeAt(i)); } } else { inputMethod.click(keyCode); } break; } }
JavaScript
function sendKey(keyCode, isRepeat) { switch (keyCode) { case KeyEvent.DOM_VK_BACK_SPACE: if (inputContext) { return inputContext.sendKey(keyCode, 0, 0, isRepeat); } break; case KeyEvent.DOM_VK_RETURN: if (inputContext) { return inputContext.sendKey(keyCode, 0, 0); } break; default: if (inputContext) { return inputContext.sendKey(0, keyCode, 0); } break; } }
function sendKey(keyCode, isRepeat) { switch (keyCode) { case KeyEvent.DOM_VK_BACK_SPACE: if (inputContext) { return inputContext.sendKey(keyCode, 0, 0, isRepeat); } break; case KeyEvent.DOM_VK_RETURN: if (inputContext) { return inputContext.sendKey(keyCode, 0, 0); } break; default: if (inputContext) { return inputContext.sendKey(0, keyCode, 0); } break; } }
JavaScript
function showKeyboard() { perfTimer.printTime('showKeyboard'); clearTimeout(hideKeyboardTimeout); inputContext = navigator.mozInputMethod.inputcontext; resetKeyboard(); if (inputContext) { currentInputMode = inputContext.inputMode; currentInputType = mapInputType(inputContext.inputType); } else { currentInputMode = ''; currentInputType = mapInputType('text'); return; } var state = { type: inputContext.inputType, inputmode: inputContext.inputMode, selectionStart: inputContext.selectionStart, selectionEnd: inputContext.selectionEnd, value: '' }; // everything.me uses this setting to improve searches, // but they really shouldn't. settingsPromiseManager.set({ 'keyboard.current': keyboardName }); function doShowKeyboard() { perfTimer.printTime('doShowKeyboard'); // Force to disable the auto correction for Greek SMS layout. // This is because the suggestion result is still unicode and // we would not convert the suggestion result to GSM 7-bit. if (inputMethod.activate) { inputMethod.activate(Keyboards[keyboardName].autoCorrectLanguage, state, { suggest: imEngineSettings.suggestionsEnabled && !isGreekSMS(), correct: imEngineSettings.correctionsEnabled && !isGreekSMS() }); } // render the keyboard after activation, which will determine the state // of uppercase/suggestion, etc. renderKeyboard(keyboardName, function() { IMERender.showIME(); }); } Promise.all([inputContextGetTextPromise, imEngineSettingsInitPromise]) .then(function gotText(values) { state.value = values[0]; doShowKeyboard(); }, function failedToGetText(ex) { // something is wrong with the inputcontext. We should not proceed. }); }
function showKeyboard() { perfTimer.printTime('showKeyboard'); clearTimeout(hideKeyboardTimeout); inputContext = navigator.mozInputMethod.inputcontext; resetKeyboard(); if (inputContext) { currentInputMode = inputContext.inputMode; currentInputType = mapInputType(inputContext.inputType); } else { currentInputMode = ''; currentInputType = mapInputType('text'); return; } var state = { type: inputContext.inputType, inputmode: inputContext.inputMode, selectionStart: inputContext.selectionStart, selectionEnd: inputContext.selectionEnd, value: '' }; // everything.me uses this setting to improve searches, // but they really shouldn't. settingsPromiseManager.set({ 'keyboard.current': keyboardName }); function doShowKeyboard() { perfTimer.printTime('doShowKeyboard'); // Force to disable the auto correction for Greek SMS layout. // This is because the suggestion result is still unicode and // we would not convert the suggestion result to GSM 7-bit. if (inputMethod.activate) { inputMethod.activate(Keyboards[keyboardName].autoCorrectLanguage, state, { suggest: imEngineSettings.suggestionsEnabled && !isGreekSMS(), correct: imEngineSettings.correctionsEnabled && !isGreekSMS() }); } // render the keyboard after activation, which will determine the state // of uppercase/suggestion, etc. renderKeyboard(keyboardName, function() { IMERender.showIME(); }); } Promise.all([inputContextGetTextPromise, imEngineSettingsInitPromise]) .then(function gotText(values) { state.value = values[0]; doShowKeyboard(); }, function failedToGetText(ex) { // something is wrong with the inputcontext. We should not proceed. }); }
JavaScript
function needsCandidatePanel() { // Disable the word suggestion for Greek SMS layout. // This is because the suggestion result is still unicode and // we would not convert the suggestion result to GSM 7-bit. if (isGreekSMS()) { return false; } return !!((Keyboards[keyboardName].autoCorrectLanguage || Keyboards[keyboardName].needsCandidatePanel) && (!inputMethod.displaysCandidates || inputMethod.displaysCandidates())); }
function needsCandidatePanel() { // Disable the word suggestion for Greek SMS layout. // This is because the suggestion result is still unicode and // we would not convert the suggestion result to GSM 7-bit. if (isGreekSMS()) { return false; } return !!((Keyboards[keyboardName].autoCorrectLanguage || Keyboards[keyboardName].needsCandidatePanel) && (!inputMethod.displaysCandidates || inputMethod.displaysCandidates())); }
JavaScript
function dismissKeyboard() { clearTimeout(deleteTimeout); clearInterval(deleteInterval); clearTimeout(menuTimeout); navigator.mozInputMethod.mgmt.hide(); }
function dismissKeyboard() { clearTimeout(deleteTimeout); clearInterval(deleteInterval); clearTimeout(menuTimeout); navigator.mozInputMethod.mgmt.hide(); }
JavaScript
function ah_displayUnsentConfirmtion(activity) { var msgDiv = document.createElement('div'); msgDiv.innerHTML = '<h1 data-l10n-id="unsent-message-title"></h1>' + '<p data-l10n-id="unsent-message-description"></p>'; var options = new OptionMenu({ type: 'confirm', section: msgDiv, items: [{ l10nId: 'unsent-message-option-edit', method: function editOptionMethod() { // it already in message app, we don't need to do anything but // clearing activity variables in MessageManager. MessageManager.activity = null; } }, { l10nId: 'unsent-message-option-discard', method: this.launchComposer.bind(this), params: [activity] }] }); options.show(); }
function ah_displayUnsentConfirmtion(activity) { var msgDiv = document.createElement('div'); msgDiv.innerHTML = '<h1 data-l10n-id="unsent-message-title"></h1>' + '<p data-l10n-id="unsent-message-description"></p>'; var options = new OptionMenu({ type: 'confirm', section: msgDiv, items: [{ l10nId: 'unsent-message-option-edit', method: function editOptionMethod() { // it already in message app, we don't need to do anything but // clearing activity variables in MessageManager. MessageManager.activity = null; } }, { l10nId: 'unsent-message-option-discard', method: this.launchComposer.bind(this), params: [activity] }] }); options.show(); }
JavaScript
function ah_launchComposer(activity) { if (location.hash === '#new') { MessageManager.handleActivity(activity); } else { MessageManager.activity = activity; // Move to new message window.location.hash = '#new'; } }
function ah_launchComposer(activity) { if (location.hash === '#new') { MessageManager.handleActivity(activity); } else { MessageManager.activity = activity; // Move to new message window.location.hash = '#new'; } }
JavaScript
function GridView(config) { this.config = config; this.clickIcon = this.clickIcon.bind(this); if (config.features.zoom) { this.zoom = new GridZoom(this); } if (config.features.dragdrop) { this.dragdrop = new GridDragDrop(this); } this.layout = new GridLayout(this); // Enable event listeners when instantiated. this.start(); }
function GridView(config) { this.config = config; this.clickIcon = this.clickIcon.bind(this); if (config.features.zoom) { this.zoom = new GridZoom(this); } if (config.features.dragdrop) { this.dragdrop = new GridDragDrop(this); } this.layout = new GridLayout(this); // Enable event listeners when instantiated. this.start(); }
JavaScript
function App() { return ( <div className="main-container"> <div className="header"> <SearchComponent /> </div> <div style={{ display: 'flex', justifyContent: 'center', }} > <StoreList /> <MapWrapper /> </div> </div> ); }
function App() { return ( <div className="main-container"> <div className="header"> <SearchComponent /> </div> <div style={{ display: 'flex', justifyContent: 'center', }} > <StoreList /> <MapWrapper /> </div> </div> ); }
JavaScript
function connectToWifi(name, password) { execSync(`bash ${script} ${name}`, { input: password }); const wifiStatus = execSync(`bash ${statusScript}`).toString(); if(wifiStatus.includes("disconnected")) return false; return true; }
function connectToWifi(name, password) { execSync(`bash ${script} ${name}`, { input: password }); const wifiStatus = execSync(`bash ${statusScript}`).toString(); if(wifiStatus.includes("disconnected")) return false; return true; }
JavaScript
function onFeatureAdd(evt) { if(evt.feature) { drawMarkerFeat(evt.feature); } }
function onFeatureAdd(evt) { if(evt.feature) { drawMarkerFeat(evt.feature); } }
JavaScript
function drawMarkerFeat(markerFeat) { markerSource.clear(); markerSource.un('addfeature', onFeatureAdd); markerSource.addFeature(markerFeat); markerSource.on('addfeature', onFeatureAdd); // get the marker coordinates and transform to WGS84 var projMarkerCoords = ol.proj.transform( markerFeat.getGeometry().getCoordinates(), 'EPSG:3857', 'EPSG:4326'), x = projMarkerCoords[1], y = projMarkerCoords[0]; $('#marker-x').text('LAT: ' + x); $('#marker-y').text('LON: ' + y); // create a possible marker, if the // textarea is filled createMarkerPopup(); // update the links when changing the marker updatePermalinks(); }
function drawMarkerFeat(markerFeat) { markerSource.clear(); markerSource.un('addfeature', onFeatureAdd); markerSource.addFeature(markerFeat); markerSource.on('addfeature', onFeatureAdd); // get the marker coordinates and transform to WGS84 var projMarkerCoords = ol.proj.transform( markerFeat.getGeometry().getCoordinates(), 'EPSG:3857', 'EPSG:4326'), x = projMarkerCoords[1], y = projMarkerCoords[0]; $('#marker-x').text('LAT: ' + x); $('#marker-y').text('LON: ' + y); // create a possible marker, if the // textarea is filled createMarkerPopup(); // update the links when changing the marker updatePermalinks(); }
JavaScript
function updatePermalinks() { window.location.hash = Shareloc.Permalink.createHash(map); var pl = Shareloc.Permalink.createPermalinkUrl(map); $('#code #embed-pl.list-group-item a.pl-link').attr('href', pl); $('#code #embed-pl.list-group-item a.pl-mail').attr('href', 'mailto:?body=' + encodeURIComponent(pl) + '%0D%0A%0D%0Acreated by Shareloc'); $('#code #embed-iframe.list-group-item').text(Shareloc.Permalink.createIframeCode(map)); }
function updatePermalinks() { window.location.hash = Shareloc.Permalink.createHash(map); var pl = Shareloc.Permalink.createPermalinkUrl(map); $('#code #embed-pl.list-group-item a.pl-link').attr('href', pl); $('#code #embed-pl.list-group-item a.pl-mail').attr('href', 'mailto:?body=' + encodeURIComponent(pl) + '%0D%0A%0D%0Acreated by Shareloc'); $('#code #embed-iframe.list-group-item').text(Shareloc.Permalink.createIframeCode(map)); }
JavaScript
function tester(fn) { return function mochaFutureTester(done) { try { const future = fn(); future.fork( (err) => done(err), () => done() ); } catch (err) { console.warn('Caught a synchronous error while testing a future'); // eslint-disable-line no-console done(err); } }; }
function tester(fn) { return function mochaFutureTester(done) { try { const future = fn(); future.fork( (err) => done(err), () => done() ); } catch (err) { console.warn('Caught a synchronous error while testing a future'); // eslint-disable-line no-console done(err); } }; }
JavaScript
function generateMarkdown(data) { var apache = "[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)"; var mit = "[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)"; var isc = "[![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg)](https://opensource.org/licenses/ISC)"; var gnu3 = "[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)"; var badge = ""; if (data.license === "Apache 2.0") { badge = apache; } else if (data.license === "MIT") { badge = mit; } else if (data.license === "ISC") { badge = isc; } else if (data.license === "GNU GPLv3") { badge = gnu3; } else { badge = ""; }; return `# ${data.title} ## Table of Contents * [Badge](#badge) * [Description](#description) * [Installation](#installation) * [Usage](#usage) * [Licensing](#licensing) * [Contribution](#contribution) * [Testing](#testing) * [Questions](#questions) ## Badge ${badge} ## Description ${data.description} ## Installation ${data.installation} ## Usage ${data.usage} ## Licensing ${data.license} ## Contribution ${data.contribution} ## Testing ${data.testing} ## Questions Contact me at ${data.email} or visit my profile at https://github.com/${data.username}`; }
function generateMarkdown(data) { var apache = "[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)"; var mit = "[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)"; var isc = "[![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg)](https://opensource.org/licenses/ISC)"; var gnu3 = "[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)"; var badge = ""; if (data.license === "Apache 2.0") { badge = apache; } else if (data.license === "MIT") { badge = mit; } else if (data.license === "ISC") { badge = isc; } else if (data.license === "GNU GPLv3") { badge = gnu3; } else { badge = ""; }; return `# ${data.title} ## Table of Contents * [Badge](#badge) * [Description](#description) * [Installation](#installation) * [Usage](#usage) * [Licensing](#licensing) * [Contribution](#contribution) * [Testing](#testing) * [Questions](#questions) ## Badge ${badge} ## Description ${data.description} ## Installation ${data.installation} ## Usage ${data.usage} ## Licensing ${data.license} ## Contribution ${data.contribution} ## Testing ${data.testing} ## Questions Contact me at ${data.email} or visit my profile at https://github.com/${data.username}`; }
JavaScript
function drawLazer(lazers, blocks) { var endX = 0; var endY = 0; var lazer, block; for (var i = 0; i < lazers.length; i++) { lazer = lazers[i] ctx.beginPath(); ctx.lineWidth = 3; ctx.strokeStyle = lazer.color if (!lazer.active) { continue } switch (lazer.dir) { case "up": // red ctx.moveTo(lazer.x + (BLOCK_SIZE / 2), lazer.y + BLOCK_SIZE) endX = lazer.x + (BLOCK_SIZE / 2) endY = 0 for (var b = 0; b < blocks.length; b++) { block = blocks[b] if (lazer.x >= block.x && lazer.x <= block.x + BLOCK_SIZE && lazer.y > block.y) { endX = lazer.x + (BLOCK_SIZE/2) if (endY < block.y) { endY = block.y + BLOCK_SIZE } } } lazer.len = lazer.y - endY ctx.lineTo(endX, endY) ctx.stroke(); break; case "down": // white ctx.moveTo(lazer.x + (BLOCK_SIZE / 2), lazer.y) endX = lazer.x + (BLOCK_SIZE / 2) endY = h for (var b = 0; b < blocks.length; b++) { block = blocks[b] if (lazer.x >= block.x && lazer.x <= block.x + BLOCK_SIZE && lazer.y < block.y) { endX = lazer.x + (BLOCK_SIZE / 2) if (endY > block.y) { endY = block.y } } } lazer.len = endY - lazer.y ctx.lineTo(endX, endY) ctx.stroke(); break case "right": // yellow ctx.moveTo(lazer.x, lazer.y + (BLOCK_SIZE / 2)) endX = w endY = lazer.y + (BLOCK_SIZE / 2) for (var b = 0; b < blocks.length; b++) { block = blocks[b] if (lazer.y >= block.y && lazer.y <= block.y + BLOCK_SIZE && lazer.x < block.x) { if (endX > block.x) { endX = block.x } endY = lazer.y + (BLOCK_SIZE / 2) } } lazer.len = endX - lazer.x ctx.lineTo(endX, endY) ctx.stroke(); break case "left": // blue ctx.moveTo(lazer.x + BLOCK_SIZE, lazer.y + (BLOCK_SIZE / 2)) endX = 0 endY = lazer.y + (BLOCK_SIZE / 2) for (var b = 0; b < blocks.length; b++) { block = blocks[b] if (lazer.y >= block.y && lazer.y <= block.y + BLOCK_SIZE && lazer.x > block.x) { if (endX < block.x) { endX = block.x + BLOCK_SIZE } endY = lazer.y + (BLOCK_SIZE / 2) } } lazer.len = lazer.x - endX ctx.lineTo(endX, endY) ctx.stroke(); break default: console.log(`Bad direction : ${lazer.dir}`) break; } ctx.closePath(); } }
function drawLazer(lazers, blocks) { var endX = 0; var endY = 0; var lazer, block; for (var i = 0; i < lazers.length; i++) { lazer = lazers[i] ctx.beginPath(); ctx.lineWidth = 3; ctx.strokeStyle = lazer.color if (!lazer.active) { continue } switch (lazer.dir) { case "up": // red ctx.moveTo(lazer.x + (BLOCK_SIZE / 2), lazer.y + BLOCK_SIZE) endX = lazer.x + (BLOCK_SIZE / 2) endY = 0 for (var b = 0; b < blocks.length; b++) { block = blocks[b] if (lazer.x >= block.x && lazer.x <= block.x + BLOCK_SIZE && lazer.y > block.y) { endX = lazer.x + (BLOCK_SIZE/2) if (endY < block.y) { endY = block.y + BLOCK_SIZE } } } lazer.len = lazer.y - endY ctx.lineTo(endX, endY) ctx.stroke(); break; case "down": // white ctx.moveTo(lazer.x + (BLOCK_SIZE / 2), lazer.y) endX = lazer.x + (BLOCK_SIZE / 2) endY = h for (var b = 0; b < blocks.length; b++) { block = blocks[b] if (lazer.x >= block.x && lazer.x <= block.x + BLOCK_SIZE && lazer.y < block.y) { endX = lazer.x + (BLOCK_SIZE / 2) if (endY > block.y) { endY = block.y } } } lazer.len = endY - lazer.y ctx.lineTo(endX, endY) ctx.stroke(); break case "right": // yellow ctx.moveTo(lazer.x, lazer.y + (BLOCK_SIZE / 2)) endX = w endY = lazer.y + (BLOCK_SIZE / 2) for (var b = 0; b < blocks.length; b++) { block = blocks[b] if (lazer.y >= block.y && lazer.y <= block.y + BLOCK_SIZE && lazer.x < block.x) { if (endX > block.x) { endX = block.x } endY = lazer.y + (BLOCK_SIZE / 2) } } lazer.len = endX - lazer.x ctx.lineTo(endX, endY) ctx.stroke(); break case "left": // blue ctx.moveTo(lazer.x + BLOCK_SIZE, lazer.y + (BLOCK_SIZE / 2)) endX = 0 endY = lazer.y + (BLOCK_SIZE / 2) for (var b = 0; b < blocks.length; b++) { block = blocks[b] if (lazer.y >= block.y && lazer.y <= block.y + BLOCK_SIZE && lazer.x > block.x) { if (endX < block.x) { endX = block.x + BLOCK_SIZE } endY = lazer.y + (BLOCK_SIZE / 2) } } lazer.len = lazer.x - endX ctx.lineTo(endX, endY) ctx.stroke(); break default: console.log(`Bad direction : ${lazer.dir}`) break; } ctx.closePath(); } }
JavaScript
function drawTerminal() { if (cmds.length > 11) { cmds.shift() } ctxTerm.fillStyle = "#0E0E0E"; ctxTerm.fillRect(0, hTerm / 2, wTerm, hTerm / 2) var padding = 5; ctxTerm.font = "15px Arial"; ctxTerm.fillStyle = "#00FF00"; for (var i = 0; i < cmds.length; i++) { ctxTerm.fillText(cmds[i], 10, hTerm / 2 + ((i + 1) * TERM_SCROLL_OFFSET) + padding + cmdScroll); } }
function drawTerminal() { if (cmds.length > 11) { cmds.shift() } ctxTerm.fillStyle = "#0E0E0E"; ctxTerm.fillRect(0, hTerm / 2, wTerm, hTerm / 2) var padding = 5; ctxTerm.font = "15px Arial"; ctxTerm.fillStyle = "#00FF00"; for (var i = 0; i < cmds.length; i++) { ctxTerm.fillText(cmds[i], 10, hTerm / 2 + ((i + 1) * TERM_SCROLL_OFFSET) + padding + cmdScroll); } }
JavaScript
async newClient(id) { const clients = this.clients; // if id already is use if (clients[id]) { // id = "random" + Math.floor(Math.random() * 1000); this.removeClient(id); } const maxSockets = this.opt.max_tcp_sockets; const agent = new TunnelAgent({ clientId: id, maxSockets: 10, }); const client = new Client({ id, agent, }); // add to clients map immediately // avoiding races with other clients requesting same id clients[id] = client; client.once('close', () => { this.removeClient(id); }); // try/catch used here to remove client id try { const info = await agent.listen(); return { id: id, port: info.port, max_conn_count: maxSockets, }; } catch (err) { this.removeClient(id); // rethrow error for upstream to handle throw err; } }
async newClient(id) { const clients = this.clients; // if id already is use if (clients[id]) { // id = "random" + Math.floor(Math.random() * 1000); this.removeClient(id); } const maxSockets = this.opt.max_tcp_sockets; const agent = new TunnelAgent({ clientId: id, maxSockets: 10, }); const client = new Client({ id, agent, }); // add to clients map immediately // avoiding races with other clients requesting same id clients[id] = client; client.once('close', () => { this.removeClient(id); }); // try/catch used here to remove client id try { const info = await agent.listen(); return { id: id, port: info.port, max_conn_count: maxSockets, }; } catch (err) { this.removeClient(id); // rethrow error for upstream to handle throw err; } }
JavaScript
function throttle (callback, limit) { var wait = false; return function () { if (!wait) { callback.apply(null, arguments); wait = true; setTimeout(function () { wait = false; }, limit); } } }
function throttle (callback, limit) { var wait = false; return function () { if (!wait) { callback.apply(null, arguments); wait = true; setTimeout(function () { wait = false; }, limit); } } }
JavaScript
function autoCorrelate(buf, sampleRate) { var SIZE = buf.length; var MAX_SAMPLES = Math.floor(SIZE/2); var best_offset = -1; var best_correlation = 0; var rms = 0; var foundGoodCorrelation = false; var correlations = new Array(MAX_SAMPLES); for (var i=0;i<SIZE;i++) { var val = buf[i]; rms += val*val; } rms = Math.sqrt(rms/SIZE); if (rms<0.01) // not enough signal return -1; var lastCorrelation=1; for (var offset = MIN_SAMPLES; offset < MAX_SAMPLES; offset++) { var correlation = 0; for (var i=0; i<MAX_SAMPLES; i++) { correlation += Math.abs((buf[i])-(buf[i+offset])); } correlation = 1 - (correlation/MAX_SAMPLES); correlations[offset] = correlation; // store it, for the tweaking we need to do below. if ((correlation>GOOD_ENOUGH_CORRELATION) && (correlation > lastCorrelation)) { foundGoodCorrelation = true; if (correlation > best_correlation) { best_correlation = correlation; best_offset = offset; } } else if (foundGoodCorrelation) { // short-circuit - we found a good correlation, then a bad one, so we'd just be seeing copies from here. // Now we need to tweak the offset - by interpolating between the values to the left and right of the // best offset, and shifting it a bit. This is complex, and HACKY in this code (happy to take PRs!) - // we need to do a curve fit on correlations[] around best_offset in order to better determine precise // (anti-aliased) offset. // we know best_offset >=1, // since foundGoodCorrelation cannot go to true until the second pass (offset=1), and // we can't drop into this clause until the following pass (else if). var shift = (correlations[best_offset+1] - correlations[best_offset-1])/correlations[best_offset]; return sampleRate/(best_offset+(8*shift)); } lastCorrelation = correlation; } if (best_correlation > 0.01) { // console.log("f = " + sampleRate/best_offset + "Hz (rms: " + rms + " confidence: " + best_correlation + ")") return sampleRate/best_offset; } return -1; // var best_frequency = sampleRate/best_offset; }
function autoCorrelate(buf, sampleRate) { var SIZE = buf.length; var MAX_SAMPLES = Math.floor(SIZE/2); var best_offset = -1; var best_correlation = 0; var rms = 0; var foundGoodCorrelation = false; var correlations = new Array(MAX_SAMPLES); for (var i=0;i<SIZE;i++) { var val = buf[i]; rms += val*val; } rms = Math.sqrt(rms/SIZE); if (rms<0.01) // not enough signal return -1; var lastCorrelation=1; for (var offset = MIN_SAMPLES; offset < MAX_SAMPLES; offset++) { var correlation = 0; for (var i=0; i<MAX_SAMPLES; i++) { correlation += Math.abs((buf[i])-(buf[i+offset])); } correlation = 1 - (correlation/MAX_SAMPLES); correlations[offset] = correlation; // store it, for the tweaking we need to do below. if ((correlation>GOOD_ENOUGH_CORRELATION) && (correlation > lastCorrelation)) { foundGoodCorrelation = true; if (correlation > best_correlation) { best_correlation = correlation; best_offset = offset; } } else if (foundGoodCorrelation) { // short-circuit - we found a good correlation, then a bad one, so we'd just be seeing copies from here. // Now we need to tweak the offset - by interpolating between the values to the left and right of the // best offset, and shifting it a bit. This is complex, and HACKY in this code (happy to take PRs!) - // we need to do a curve fit on correlations[] around best_offset in order to better determine precise // (anti-aliased) offset. // we know best_offset >=1, // since foundGoodCorrelation cannot go to true until the second pass (offset=1), and // we can't drop into this clause until the following pass (else if). var shift = (correlations[best_offset+1] - correlations[best_offset-1])/correlations[best_offset]; return sampleRate/(best_offset+(8*shift)); } lastCorrelation = correlation; } if (best_correlation > 0.01) { // console.log("f = " + sampleRate/best_offset + "Hz (rms: " + rms + " confidence: " + best_correlation + ")") return sampleRate/best_offset; } return -1; // var best_frequency = sampleRate/best_offset; }
JavaScript
function addDataInFields() { $(document).on("dialog-ready", function () { var $multifields = $("[" + DATA_EAEM_NESTED + "]"); if (_.isEmpty($multifields)) { return; } var mNames = getMultiFieldNames($multifields), $form = $(".cq-dialog"), actionUrl = $form.attr("action") + ".infinity.json"; $.ajax(actionUrl).done(postProcess); function postProcess(data) { _.each(mNames, function ($multifield, mName) { $multifield.on("click", ".js-coral-Multifield-add", function () { buildImageField($multifield, mName); }); buildMultiField(data[mName], $multifield, mName); }); } }); }
function addDataInFields() { $(document).on("dialog-ready", function () { var $multifields = $("[" + DATA_EAEM_NESTED + "]"); if (_.isEmpty($multifields)) { return; } var mNames = getMultiFieldNames($multifields), $form = $(".cq-dialog"), actionUrl = $form.attr("action") + ".infinity.json"; $.ajax(actionUrl).done(postProcess); function postProcess(data) { _.each(mNames, function ($multifield, mName) { $multifield.on("click", ".js-coral-Multifield-add", function () { buildImageField($multifield, mName); }); buildMultiField(data[mName], $multifield, mName); }); } }); }
JavaScript
function collectDataFromFields() { $(document).on("click", ".cq-dialog-submit", function () { var $multifields = $("[" + DATA_EAEM_NESTED + "]"); if (_.isEmpty($multifields)) { return; } var $form = $(this).closest("form.foundation-form"), $fieldSets; $multifields.each(function (i, multifield) { $fieldSets = $(multifield).find("[class='coral-Form-fieldset']"); $fieldSets.each(function (counter, fieldSet) { collectNonImageFields($form, $(fieldSet), counter); collectImageFields($form, $(fieldSet), counter); }); }); }); }
function collectDataFromFields() { $(document).on("click", ".cq-dialog-submit", function () { var $multifields = $("[" + DATA_EAEM_NESTED + "]"); if (_.isEmpty($multifields)) { return; } var $form = $(this).closest("form.foundation-form"), $fieldSets; $multifields.each(function (i, multifield) { $fieldSets = $(multifield).find("[class='coral-Form-fieldset']"); $fieldSets.each(function (counter, fieldSet) { collectNonImageFields($form, $(fieldSet), counter); collectImageFields($form, $(fieldSet), counter); }); }); }); }
JavaScript
function typeInfo(target) { const t = target === null ? 'null' : typeof target; switch (t) { case "object" /* Object */: case "function" /* Function */: return new TypeInfo(target); } let info = typeInfoRegistry[t]; if (!info) typeInfoRegistry[t] = info = new TypeInfo(target); return info; }
function typeInfo(target) { const t = target === null ? 'null' : typeof target; switch (t) { case "object" /* Object */: case "function" /* Function */: return new TypeInfo(target); } let info = typeInfoRegistry[t]; if (!info) typeInfoRegistry[t] = info = new TypeInfo(target); return info; }
JavaScript
function SystemJSLoader() { Loader.call(this); this.paths = {}; this._loader.paths = {}; systemJSConstructor.call(this); }
function SystemJSLoader() { Loader.call(this); this.paths = {}; this._loader.paths = {}; systemJSConstructor.call(this); }
JavaScript
function createPkgConfigPathObj(path) { var lastWildcard = path.lastIndexOf('*'); var length = Math.max(lastWildcard + 1, path.lastIndexOf('/')); return { length: length, regEx: new RegExp('^(' + path.substr(0, length).replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^\\/]+') + ')(\\/|$)'), wildcard: lastWildcard != -1 }; }
function createPkgConfigPathObj(path) { var lastWildcard = path.lastIndexOf('*'); var length = Math.max(lastWildcard + 1, path.lastIndexOf('/')); return { length: length, regEx: new RegExp('^(' + path.substr(0, length).replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^\\/]+') + ')(\\/|$)'), wildcard: lastWildcard != -1 }; }
JavaScript
function ensureEvaluated(moduleName, entry, seen, loader) { // if already seen, that means it's an already-evaluated non circular dependency if (!entry || entry.evaluated || !entry.declarative) return; // this only applies to declarative modules which late-execute seen.push(moduleName); for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) { var depName = entry.normalizedDeps[i]; if (indexOf.call(seen, depName) == -1) { if (!loader.defined[depName]) loader.get(depName); else ensureEvaluated(depName, loader.defined[depName], seen, loader); } } if (entry.evaluated) return; entry.evaluated = true; entry.module.execute.call(__global); }
function ensureEvaluated(moduleName, entry, seen, loader) { // if already seen, that means it's an already-evaluated non circular dependency if (!entry || entry.evaluated || !entry.declarative) return; // this only applies to declarative modules which late-execute seen.push(moduleName); for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) { var depName = entry.normalizedDeps[i]; if (indexOf.call(seen, depName) == -1) { if (!loader.defined[depName]) loader.get(depName); else ensureEvaluated(depName, loader.defined[depName], seen, loader); } } if (entry.evaluated) return; entry.evaluated = true; entry.module.execute.call(__global); }
JavaScript
function combinePluginParts(loader, argumentName, pluginName, defaultExtension) { if (defaultExtension && argumentName.substr(argumentName.length - 3, 3) == '.js') argumentName = argumentName.substr(0, argumentName.length - 3); if (loader.pluginFirst) { return pluginName + '!' + argumentName; } else { return argumentName + '!' + pluginName; } }
function combinePluginParts(loader, argumentName, pluginName, defaultExtension) { if (defaultExtension && argumentName.substr(argumentName.length - 3, 3) == '.js') argumentName = argumentName.substr(0, argumentName.length - 3); if (loader.pluginFirst) { return pluginName + '!' + argumentName; } else { return argumentName + '!' + pluginName; } }
JavaScript
function scrollTitle(text) { let currentText = text + ' - ' document.title = currentText window.__scrollingTitle.intervalKey = setInterval(() => { currentText = currentText.substr(1) + currentText.substr(0, 1) document.title = currentText }, 250) }
function scrollTitle(text) { let currentText = text + ' - ' document.title = currentText window.__scrollingTitle.intervalKey = setInterval(() => { currentText = currentText.substr(1) + currentText.substr(0, 1) document.title = currentText }, 250) }
JavaScript
function lgm_addKnownSites() { gmAddSite("video", "(|.+?\.)dailymotion\..+?", ".*"); gmAddSite("photos", "(|.+?\.)flickr\..+?", ".*"); gmAddSite("/p/", "(|.+?\.)instagram\..+?", ".*"); gmAddSite("watch", "(|.+?\.)metacafe\..+?", ".*"); gmAddSite("video", "(|.+?\.)ok\.ru.+?", ".*"); gmAddSite("pin", "(|.+?\.)pinterest\..+?", ".*"); gmAddSite("video", "(|.+?\.)tiktok\..+?", ".*"); gmAddSite("post|image", "(|.+?\.)tumblr\..+?", ".*"); gmAddSite("post|image", "(|.+?\.)tumbral\..+?", ".*"); gmAddSite("watch?", "(|.+?\.)youtube\..+?", ".*"); gmAddSite("10", "devzone\\..+?\\.(net|eu)", "/test/gmonkey/.*"); }
function lgm_addKnownSites() { gmAddSite("video", "(|.+?\.)dailymotion\..+?", ".*"); gmAddSite("photos", "(|.+?\.)flickr\..+?", ".*"); gmAddSite("/p/", "(|.+?\.)instagram\..+?", ".*"); gmAddSite("watch", "(|.+?\.)metacafe\..+?", ".*"); gmAddSite("video", "(|.+?\.)ok\.ru.+?", ".*"); gmAddSite("pin", "(|.+?\.)pinterest\..+?", ".*"); gmAddSite("video", "(|.+?\.)tiktok\..+?", ".*"); gmAddSite("post|image", "(|.+?\.)tumblr\..+?", ".*"); gmAddSite("post|image", "(|.+?\.)tumbral\..+?", ".*"); gmAddSite("watch?", "(|.+?\.)youtube\..+?", ".*"); gmAddSite("10", "devzone\\..+?\\.(net|eu)", "/test/gmonkey/.*"); }
JavaScript
function gmGetElList(mode, identifier) { if (gmIsObject(identifier)) { return identifier; } if (identifier == null) { return null; } if (DOM) { if (mode.toLowerCase() === "name") { return document.getElementsByName(identifier); } if (mode.toLowerCase() === "tagname") { return document.getElementsByTagName(identifier); } return null; } if (MSIE4) { if (mode.toLowerCase() === "id" || mode.toLowerCase() === "name") { return document.all(identifier); } if (mode.toLowerCase() === "tagname") { return document.all.tags(identifier); } return null; } if (NS4) { return gmGetEl(mode, identifier); } return null; }
function gmGetElList(mode, identifier) { if (gmIsObject(identifier)) { return identifier; } if (identifier == null) { return null; } if (DOM) { if (mode.toLowerCase() === "name") { return document.getElementsByName(identifier); } if (mode.toLowerCase() === "tagname") { return document.getElementsByTagName(identifier); } return null; } if (MSIE4) { if (mode.toLowerCase() === "id" || mode.toLowerCase() === "name") { return document.all(identifier); } if (mode.toLowerCase() === "tagname") { return document.all.tags(identifier); } return null; } if (NS4) { return gmGetEl(mode, identifier); } return null; }
JavaScript
function gmGetAt(mode, identifier, elementNumber, attributeName) { let attribute = null; const element = gmGetEl(mode, identifier, elementNumber); if (element) { if (DOM || MSIE4) { try { attribute = element[attributeName]; } catch (e) { try { attribute = element.getAttribute(attributeName); } catch (e2) { // ignored } } } if (NS4) { attribute = element[attributeName]; if (!attribute) { attribute = null; } } } return attribute; }
function gmGetAt(mode, identifier, elementNumber, attributeName) { let attribute = null; const element = gmGetEl(mode, identifier, elementNumber); if (element) { if (DOM || MSIE4) { try { attribute = element[attributeName]; } catch (e) { try { attribute = element.getAttribute(attributeName); } catch (e2) { // ignored } } } if (NS4) { attribute = element[attributeName]; if (!attribute) { attribute = null; } } } return attribute; }
JavaScript
function gmSetCo(mode, identifier, elementNumber, text) { const element = gmGetEl(mode, identifier, elementNumber); if (element) { if (DOM) { if (!element.firstChild) { element.appendChild(document.createTextNode("")); } element.firstChild.nodeValue = text; return true; } if (MSIE4) { element.innerText = text; return true; } if (NS4) { element.document.open(); element.document.write(text); element.document.close(); return true; } } return false; }
function gmSetCo(mode, identifier, elementNumber, text) { const element = gmGetEl(mode, identifier, elementNumber); if (element) { if (DOM) { if (!element.firstChild) { element.appendChild(document.createTextNode("")); } element.firstChild.nodeValue = text; return true; } if (MSIE4) { element.innerText = text; return true; } if (NS4) { element.document.open(); element.document.write(text); element.document.close(); return true; } } return false; }
JavaScript
function gmSetAt(mode, identifier, elementNumber, attributeName, attributeValue) { //var attribute; const element = gmGetEl(mode, identifier, elementNumber); if (element) { if (DOM || MSIE4) { try { element[attributeName] = attributeValue; } catch (e) { try { element.setAttribute(attributeName, attributeValue); } catch (e2) { // ignored } } return true; // return gmGetAt(mode, identifier, elementNumber, attributeName); } if (NS4) { element[attributeName] = attributeValue; return true; // return gmGetAt(mode, identifier, elementNumber, attributeName); } } return false; }
function gmSetAt(mode, identifier, elementNumber, attributeName, attributeValue) { //var attribute; const element = gmGetEl(mode, identifier, elementNumber); if (element) { if (DOM || MSIE4) { try { element[attributeName] = attributeValue; } catch (e) { try { element.setAttribute(attributeName, attributeValue); } catch (e2) { // ignored } } return true; // return gmGetAt(mode, identifier, elementNumber, attributeName); } if (NS4) { element[attributeName] = attributeValue; return true; // return gmGetAt(mode, identifier, elementNumber, attributeName); } } return false; }
JavaScript
function gmAppAt(mode, identifier, attributeName, attributeValue) { const oldValue = gmGetAt(mode, identifier, attributeName); const newValue = oldValue + ATTR_SEP + attributeValue; return gmSetAt(mode, identifier, attributeName, newValue); }
function gmAppAt(mode, identifier, attributeName, attributeValue) { const oldValue = gmGetAt(mode, identifier, attributeName); const newValue = oldValue + ATTR_SEP + attributeValue; return gmSetAt(mode, identifier, attributeName, newValue); }
JavaScript
function gmIsInstanceOf(obj, objType) { let isType = false; if (obj != null) { if (objType == null) { objType = "Object"; } try { let tObjType = eval(objType); isType = (obj.constructor === tObjType); } catch (e) { // ignore } // isType = (typeof obj) == objType; } return isType; }
function gmIsInstanceOf(obj, objType) { let isType = false; if (obj != null) { if (objType == null) { objType = "Object"; } try { let tObjType = eval(objType); isType = (obj.constructor === tObjType); } catch (e) { // ignore } // isType = (typeof obj) == objType; } return isType; }
JavaScript
function gmSortArray(unsortedArray, sortMode) { const sortedArray = unsortedArray; if (sortMode == null) { sortMode = false; } if (sortMode === SORT_NUM) { sortedArray.sort(function (aE, bE) { return aE - bE; }); } else if (sortMode === SORT_REV) { sortedArray.reverse(); } else if (sortMode || sortMode === SORT_DEF) { sortedArray.sort(); } return sortedArray; }
function gmSortArray(unsortedArray, sortMode) { const sortedArray = unsortedArray; if (sortMode == null) { sortMode = false; } if (sortMode === SORT_NUM) { sortedArray.sort(function (aE, bE) { return aE - bE; }); } else if (sortMode === SORT_REV) { sortedArray.reverse(); } else if (sortMode || sortMode === SORT_DEF) { sortedArray.sort(); } return sortedArray; }
JavaScript
function gmAddHandler(e) { let isDone; lgm_addKnownSites(); lgm_addStyles(); lgm_addControls(); lgm_addInitAction(); isDone = true; return isDone; }
function gmAddHandler(e) { let isDone; lgm_addKnownSites(); lgm_addStyles(); lgm_addControls(); lgm_addInitAction(); isDone = true; return isDone; }
JavaScript
function gmInitEventHandler() { if (INIT_ONLOAD) { window.addEventListener("load", function (e) { gmAddHandler(e); }); } }
function gmInitEventHandler() { if (INIT_ONLOAD) { window.addEventListener("load", function (e) { gmAddHandler(e); }); } }
JavaScript
function gmCreateObj(par, objtyp, id) { // var obj = $("<" + objtyp + ">"); let obj = null; if (objtyp != null && objtyp !== "") { obj = document.createElement(objtyp); if (obj) { if (id != null) { // obj.attr("id", id); // obj.attr("name", id); gmSetAtI(obj, "id", id); gmSetAtI(obj, "name", id); } if (gmIsObject(par)) { // $(par).append(obj); par.appendChild(obj); } } } return obj; }
function gmCreateObj(par, objtyp, id) { // var obj = $("<" + objtyp + ">"); let obj = null; if (objtyp != null && objtyp !== "") { obj = document.createElement(objtyp); if (obj) { if (id != null) { // obj.attr("id", id); // obj.attr("name", id); gmSetAtI(obj, "id", id); gmSetAtI(obj, "name", id); } if (gmIsObject(par)) { // $(par).append(obj); par.appendChild(obj); } } } return obj; }
JavaScript
function gmCreateObjCommon(obj, caption, tit, ro, ev_click, ev_focus, ev_mOver, ev_mOut, ev_dblClick) { if (obj) { // obj.attr("title", tit); gmSetAtI(obj, "title", tit); if (ro) { // obj.attr("readonly", "readonly"); gmSetAtI(obj, "readonly", "readonly"); } if (caption) { // obj.append(caption); gmSetCoI(obj, caption); } if (ev_click) { // obj.click(ev_click); obj.onclick = ev_click; } if (ev_dblClick) { // obj.click(ev_dblClick); obj.ondblclick = ev_dblClick; } if (ev_focus) { // obj.focus(ev_focus); obj.onfocus = ev_focus; } if (ev_mOver) { // obj.hover(ev_mOver); obj.onmouseover = ev_mOver; } if (ev_mOut) { // obj.hover(ev_mOut); obj.onmouseout = ev_mOut; } } return obj; }
function gmCreateObjCommon(obj, caption, tit, ro, ev_click, ev_focus, ev_mOver, ev_mOut, ev_dblClick) { if (obj) { // obj.attr("title", tit); gmSetAtI(obj, "title", tit); if (ro) { // obj.attr("readonly", "readonly"); gmSetAtI(obj, "readonly", "readonly"); } if (caption) { // obj.append(caption); gmSetCoI(obj, caption); } if (ev_click) { // obj.click(ev_click); obj.onclick = ev_click; } if (ev_dblClick) { // obj.click(ev_dblClick); obj.ondblclick = ev_dblClick; } if (ev_focus) { // obj.focus(ev_focus); obj.onfocus = ev_focus; } if (ev_mOver) { // obj.hover(ev_mOver); obj.onmouseover = ev_mOver; } if (ev_mOut) { // obj.hover(ev_mOut); obj.onmouseout = ev_mOut; } } return obj; }
JavaScript
function gmAddObj(obj, parent) { let isSet = false; if (gmIsObject(obj)) { if (!parent) { parent = gmGetEl("tagname", "body"); } parent.appendChild(obj); isSet = true; } return isSet; }
function gmAddObj(obj, parent) { let isSet = false; if (gmIsObject(obj)) { if (!parent) { parent = gmGetEl("tagname", "body"); } parent.appendChild(obj); isSet = true; } return isSet; }
JavaScript
function gmSetInput(id, initval) { let isSet = false; // var obj = document.getElementById(id); const obj = gmGetElI(id); if (obj) { if (initval) { // obj.setAttribute("value", initval); gmSetAtI(obj, "value", initval); isSet = true; } else { // obj.setAttribute("value", ""); gmSetAtI(obj, "value", ""); isSet = true; } } return isSet; }
function gmSetInput(id, initval) { let isSet = false; // var obj = document.getElementById(id); const obj = gmGetElI(id); if (obj) { if (initval) { // obj.setAttribute("value", initval); gmSetAtI(obj, "value", initval); isSet = true; } else { // obj.setAttribute("value", ""); gmSetAtI(obj, "value", ""); isSet = true; } } return isSet; }
JavaScript
function gmSelectInput(inputElem) { let isSet = false; if (gmIsObject(inputElem)) { try { inputElem.select(); isSet = true; } catch (e) { } } return isSet; }
function gmSelectInput(inputElem) { let isSet = false; if (gmIsObject(inputElem)) { try { inputElem.select(); isSet = true; } catch (e) { } } return isSet; }
JavaScript
function gmGetSelectedText() { let selectedText = ""; if (SELECT_IE === SELECT_CURR) { selectedText = document.selection.createRange().text; } else if (SELECT_G === SELECT_CURR) { selectedText = window.getSelection(); } if (typeof selectedText == "object") { selectedText = selectedText.toString(); } return selectedText; }
function gmGetSelectedText() { let selectedText = ""; if (SELECT_IE === SELECT_CURR) { selectedText = document.selection.createRange().text; } else if (SELECT_G === SELECT_CURR) { selectedText = window.getSelection(); } if (typeof selectedText == "object") { selectedText = selectedText.toString(); } return selectedText; }
JavaScript
function gmSelectText(elem, bForceSelect) { let selection; let currSel = gmGetSelectedText(); if (bForceSelect == null) { bForceSelect = false; } if (!bForceSelect && (currSel && currSel !== "")) { if (SELECT_IE === SELECT_CURR) { // noinspection BadExpressionStatementJS document.selection.empty; } else if (SELECT_G === SELECT_CURR) { selection = window.getSelection(); selection.removeAllRanges(); } } else { if (gmIsObject(elem)) { const tRange = gmGetNewRange(elem); if (SELECT_IE === SELECT_CURR) { tRange.select(); } else if (SELECT_G === SELECT_CURR) { selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(tRange); } currSel = gmGetSelectedText(); } } return currSel; }
function gmSelectText(elem, bForceSelect) { let selection; let currSel = gmGetSelectedText(); if (bForceSelect == null) { bForceSelect = false; } if (!bForceSelect && (currSel && currSel !== "")) { if (SELECT_IE === SELECT_CURR) { // noinspection BadExpressionStatementJS document.selection.empty; } else if (SELECT_G === SELECT_CURR) { selection = window.getSelection(); selection.removeAllRanges(); } } else { if (gmIsObject(elem)) { const tRange = gmGetNewRange(elem); if (SELECT_IE === SELECT_CURR) { tRange.select(); } else if (SELECT_G === SELECT_CURR) { selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(tRange); } currSel = gmGetSelectedText(); } } return currSel; }
JavaScript
function gmDelObj(obj) { let isDel = false; let oObj = gmGetElI(obj); if (gmIsObject(oObj)) { const parent = oObj.parentNode; if (gmIsObject(parent)) { try { parent.removeChild(oObj); isDel = true; } catch (e) { alert("ERR: " + e); } } } return isDel; }
function gmDelObj(obj) { let isDel = false; let oObj = gmGetElI(obj); if (gmIsObject(oObj)) { const parent = oObj.parentNode; if (gmIsObject(parent)) { try { parent.removeChild(oObj); isDel = true; } catch (e) { alert("ERR: " + e); } } } return isDel; }
JavaScript
function gmAddSite(filter, site, path) { if (gmIsArray(knownSite)) { if (site && (site.length > 0)) { knownSite.push(new KnowSiteFilterClazz( site, (filter != null ? filter : ".+"), (path != null ? path : "")) ); // const len = knownSite.length; // knownSite[len] = {}; // knownSite[len].site = site; // knownSite[len].filter = (filter != null ? filter : ".+"); // knownSite[len].path = (path != null ? path : ""); } } }
function gmAddSite(filter, site, path) { if (gmIsArray(knownSite)) { if (site && (site.length > 0)) { knownSite.push(new KnowSiteFilterClazz( site, (filter != null ? filter : ".+"), (path != null ? path : "")) ); // const len = knownSite.length; // knownSite[len] = {}; // knownSite[len].site = site; // knownSite[len].filter = (filter != null ? filter : ".+"); // knownSite[len].path = (path != null ? path : ""); } } }
JavaScript
function gmFoundFilter(site, path) { let retFilter = ""; if (gmIsArray(knownSite) && site) { if (!path) { path = ""; } //for (let i = 0; i < knownSite.length; i++) { let init = 0; for (let currSite of knownSite) { //let currSite = knownSite[i]; if (site.search(currSite.site) >= 0) { if (init === 0 && currSite.path === "") { retFilter = currSite.filter; init = 1; } let fIdx = path.search(currSite.path); if (path !== "" && (fIdx >= 0)) { retFilter = currSite.filter; break; } else if (path === "" && currSite.path === "") { retFilter = currSite.filter; break; } } } } return retFilter; }
function gmFoundFilter(site, path) { let retFilter = ""; if (gmIsArray(knownSite) && site) { if (!path) { path = ""; } //for (let i = 0; i < knownSite.length; i++) { let init = 0; for (let currSite of knownSite) { //let currSite = knownSite[i]; if (site.search(currSite.site) >= 0) { if (init === 0 && currSite.path === "") { retFilter = currSite.filter; init = 1; } let fIdx = path.search(currSite.path); if (path !== "" && (fIdx >= 0)) { retFilter = currSite.filter; break; } else if (path === "" && currSite.path === "") { retFilter = currSite.filter; break; } } } } return retFilter; }
JavaScript
function gmFoundFilter2(site) { let retFilter = null; if (gmIsArray(knownSite) && site) { for (let currSite of knownSite) { if (site.search(currSite.site) >= 0) { retFilter = currSite; } } //for (let i = 0; i < knownSite.length; i++) { // if (site.search(knownSite[i].site) >= 0) { // retFilter = knownSite[i]; //} } return retFilter; }
function gmFoundFilter2(site) { let retFilter = null; if (gmIsArray(knownSite) && site) { for (let currSite of knownSite) { if (site.search(currSite.site) >= 0) { retFilter = currSite; } } //for (let i = 0; i < knownSite.length; i++) { // if (site.search(knownSite[i].site) >= 0) { // retFilter = knownSite[i]; //} } return retFilter; }
JavaScript
function gmAddScriptGlobal(scc) { let isSet = false; if (gmIsObject(scc) || gmIsFunction(scc) || (scc && scc.length > 0)) { const head = gmGetHead(); if (head) { const script = gmCreateObj(head, "script"); script.type = "text/javascript"; let allscc = ""; if (gmIsArray(scc)) { for (let i = 0; i < scc.length; i++) { allscc += scc[i] + " \n"; } } else { allscc = scc; } gmSetCoI(script, "\n" + allscc + "\n"); isSet = true; } } return isSet; }
function gmAddScriptGlobal(scc) { let isSet = false; if (gmIsObject(scc) || gmIsFunction(scc) || (scc && scc.length > 0)) { const head = gmGetHead(); if (head) { const script = gmCreateObj(head, "script"); script.type = "text/javascript"; let allscc = ""; if (gmIsArray(scc)) { for (let i = 0; i < scc.length; i++) { allscc += scc[i] + " \n"; } } else { allscc = scc; } gmSetCoI(script, "\n" + allscc + "\n"); isSet = true; } } return isSet; }
JavaScript
function gmCumulativeOffset(element) { let valueT = 0; let valueL = 0; if (element) { valueL = element.width || 0; do { valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; element = element.offsetParent; } while (element); } return [valueL, valueT]; }
function gmCumulativeOffset(element) { let valueT = 0; let valueL = 0; if (element) { valueL = element.width || 0; do { valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; element = element.offsetParent; } while (element); } return [valueL, valueT]; }
JavaScript
function gmCalcOffsetH(parentElem, iPoint, iZoom) { if (isNaN(iZoom)) { iZoom = 1; } let offsetH = 0; if (parentElem) { offsetH = gmCumulativeOffset(parentElem)[1]; if (!isNaN(offsetH) && gmIsArray(iPoint)) { if (!isNaN(iPoint[1])) { offsetH = offsetH - (iPoint[1] * iZoom) + (parentElem.height || 0); } } } return offsetH; }
function gmCalcOffsetH(parentElem, iPoint, iZoom) { if (isNaN(iZoom)) { iZoom = 1; } let offsetH = 0; if (parentElem) { offsetH = gmCumulativeOffset(parentElem)[1]; if (!isNaN(offsetH) && gmIsArray(iPoint)) { if (!isNaN(iPoint[1])) { offsetH = offsetH - (iPoint[1] * iZoom) + (parentElem.height || 0); } } } return offsetH; }
JavaScript
function gmGetReplaceUrl(searchForPattern, replaceWithText, oldUrl) { let newUrl = oldUrl; if (oldUrl != null) { if (searchForPattern !== "") { // there is something to replace if (replaceWithText == null) { replaceWithText = ""; } const patternReplace = new RegExp(searchForPattern); newUrl = oldUrl.replace(patternReplace, replaceWithText); } } return newUrl; }
function gmGetReplaceUrl(searchForPattern, replaceWithText, oldUrl) { let newUrl = oldUrl; if (oldUrl != null) { if (searchForPattern !== "") { // there is something to replace if (replaceWithText == null) { replaceWithText = ""; } const patternReplace = new RegExp(searchForPattern); newUrl = oldUrl.replace(patternReplace, replaceWithText); } } return newUrl; }
JavaScript
function gmGetCurrentSite() { let currSite = document.location.host; if (document.location.port) { currSite += ":" + document.location.port; } return currSite; }
function gmGetCurrentSite() { let currSite = document.location.host; if (document.location.port) { currSite += ":" + document.location.port; } return currSite; }
JavaScript
function gmGetStyle(obj) { let res = null; const oObj = gmGetElI(obj); if (oObj) { try { res = oObj.style; } catch (e) { // ignored } } return res; }
function gmGetStyle(obj) { let res = null; const oObj = gmGetElI(obj); if (oObj) { try { res = oObj.style; } catch (e) { // ignored } } return res; }
JavaScript
function gmGetBodyHeight() { let D = gmGetBody(); let Dh = 0; let Eh = 0; if (D) { // noinspection JSCheckFunctionSignatures Dh = Math.max(isNaN(D.style.height) ? 0 : D.style.height, D.scrollHeight, D.offsetHeight, D.clientHeight); } if (D.documentElement) { D = D.documentElement; // noinspection JSCheckFunctionSignatures Eh = Math.max(isNaN(D.style.height) ? 0 : D.style.height, D.scrollHeight, D.offsetHeight, D.clientHeight); } return Math.max(Dh, Eh); }
function gmGetBodyHeight() { let D = gmGetBody(); let Dh = 0; let Eh = 0; if (D) { // noinspection JSCheckFunctionSignatures Dh = Math.max(isNaN(D.style.height) ? 0 : D.style.height, D.scrollHeight, D.offsetHeight, D.clientHeight); } if (D.documentElement) { D = D.documentElement; // noinspection JSCheckFunctionSignatures Eh = Math.max(isNaN(D.style.height) ? 0 : D.style.height, D.scrollHeight, D.offsetHeight, D.clientHeight); } return Math.max(Dh, Eh); }
JavaScript
function gmClipRef() { let refWindow = window; if (!refWindow && unsafeWindow != null) { refWindow = unsafeWindow; } return refWindow; }
function gmClipRef() { let refWindow = window; if (!refWindow && unsafeWindow != null) { refWindow = unsafeWindow; } return refWindow; }
JavaScript
function gmPrivsManager() { let privsMan = null; const wdw = gmClipRef(); if (gmIsObject(wdw)) { try { if (gmIsObject(wdw.netscape.security.PrivilegeManager)) { privsMan = wdw.netscape.security.PrivilegeManager; } } catch (e) { // ignored } } return privsMan; }
function gmPrivsManager() { let privsMan = null; const wdw = gmClipRef(); if (gmIsObject(wdw)) { try { if (gmIsObject(wdw.netscape.security.PrivilegeManager)) { privsMan = wdw.netscape.security.PrivilegeManager; } } catch (e) { // ignored } } return privsMan; }
JavaScript
function gmIsClipboardSupported() { let isOK = false; try { let privsMan = gmPrivsManager(); if (gmIsObject(privsMan)) { privsMan.enablePrivilege("UniversalXPConnect"); isOK = true; } } catch (ex) { alert("ERR: " + ex); } return isOK; }
function gmIsClipboardSupported() { let isOK = false; try { let privsMan = gmPrivsManager(); if (gmIsObject(privsMan)) { privsMan.enablePrivilege("UniversalXPConnect"); isOK = true; } } catch (ex) { alert("ERR: " + ex); } return isOK; }
JavaScript
function reset() { //console.log('reset'); //reset cached things polygons = d3.geoVoronoi().polygons($this.getPoints({})) contours = []; //level2Points = []; }
function reset() { //console.log('reset'); //reset cached things polygons = d3.geoVoronoi().polygons($this.getPoints({})) contours = []; //level2Points = []; }
JavaScript
static allFishesAppearsThisMonth (data, hemisphere) { if (hemisphere != HEMISPHERES.South && hemisphere != HEMISPHERES.North) { throw new Error( `Los valores posibles son "North" y "South" - Valor utilizado ${hemisphere}"` ) } return data.filter((fish) => { const temp_fish = new Fish({ ...fish }) return temp_fish.appearsThisMonth(hemisphere) }) }
static allFishesAppearsThisMonth (data, hemisphere) { if (hemisphere != HEMISPHERES.South && hemisphere != HEMISPHERES.North) { throw new Error( `Los valores posibles son "North" y "South" - Valor utilizado ${hemisphere}"` ) } return data.filter((fish) => { const temp_fish = new Fish({ ...fish }) return temp_fish.appearsThisMonth(hemisphere) }) }
JavaScript
static allFishesAppearsNow (data, hemisphere) { if (hemisphere != HEMISPHERES.South && hemisphere != HEMISPHERES.North) { throw new Error( `Los valores posibles son "North" y "South" - Valor utilizado ${hemisphere}"` ) } return data.filter((fish) => { const temp_fish = new Fish({ ...fish }) return temp_fish.appearsNow(hemisphere) }) }
static allFishesAppearsNow (data, hemisphere) { if (hemisphere != HEMISPHERES.South && hemisphere != HEMISPHERES.North) { throw new Error( `Los valores posibles son "North" y "South" - Valor utilizado ${hemisphere}"` ) } return data.filter((fish) => { const temp_fish = new Fish({ ...fish }) return temp_fish.appearsNow(hemisphere) }) }
JavaScript
static lastChanceToFishing (data, month) { return data.filter((fish) => { return fish.seasons[0][fish.seasons[0].length - 1] === month }) }
static lastChanceToFishing (data, month) { return data.filter((fish) => { return fish.seasons[0][fish.seasons[0].length - 1] === month }) }